# Using VTK gradient filter to calculate the divergence of a vector field

**URL:** https://discourse.vtk.org/t/using-vtk-gradient-filter-to-calculate-the-divergence-of-a-vector-field/5319
**Category:** Support
**Created:** [March 4, 2021, 5:17pm UTC](https://discourse.vtk.org/t/using-vtk-gradient-filter-to-calculate-the-divergence-of-a-vector-field/5319 "2021-03-04T17:17:12Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![Renard](https://discourse.vtk.org/letter_avatar_proxy/v4/letter/r/e99b99/32.png) [@Renard](https://discourse.vtk.org/u/Renard)
#### Post date: [March 4, 2021, 5:17pm UTC](https://discourse.vtk.org/t/using-vtk-gradient-filter-to-calculate-the-divergence-of-a-vector-field/5319/1 "2021-03-04T17:17:12Z")

</div>

Hi, I have written a simple code in python to calculate the divergence of a vector field stored in a VTU file. I’m getting the following error, what is going wrong here?

TypeError: method requires a string argument

```auto
import numpy
import vtk
def GetField(vtu_filename, fieldname):
    """ This will extract the field with the given name from the specified file """
    reader = vtk.vtkXMLUnstructuredGridReader()
    reader.SetFileName(vtu_filename)
    reader.Update()
    field_array = reader.GetOutput().GetPointData().GetArray(fieldname)
    return field_array

def ComputeDivergence(input_array):
     gradient_9d = vtk.vtkGradientFilter(input_array)
    du_dx, dv_dy, dw_dz = gradient_9d[0], gradient_9d[4], gradient_9d[8]

    return du_dx + dv_dy + dw_dz

Myfile = "hys_Ldiamond080.vtu"
Magnetization = GetField(Myfile, "Magnetization")
divergence = ComputeDivergence(Magnetization)

```

Full Error :

```auto
Traceback (most recent call last):
  File "Stack.py", line 20, in <module>
    divergence = ComputeDivergence(Magnetization)
  File "Stack.py", line 12, in ComputeDivergence
    gradient_9d = vtk.vtkGradientFilter(input_array)
TypeError: method requires a string argument

```

---

<div class="post-metadata">

### Author: ![lassoan](https://discourse.vtk.org/user_avatar/discourse.vtk.org/lassoan/32/50_2.png) [@lassoan](https://discourse.vtk.org/u/lassoan)
#### Post date: [March 4, 2021, 11:09pm UTC](https://discourse.vtk.org/t/using-vtk-gradient-filter-to-calculate-the-divergence-of-a-vector-field/5319/2 "2021-03-04T23:09:38Z")

</div>

We cannot guess where the problem occurs from this trimmed down error message. Please provide complete error message - including call stack and line numbers.

---

<div class="post-metadata">

### Author: ![Renard](https://discourse.vtk.org/letter_avatar_proxy/v4/letter/r/e99b99/32.png) [@Renard](https://discourse.vtk.org/u/Renard)
#### Post date: [March 5, 2021, 9:19am UTC](https://discourse.vtk.org/t/using-vtk-gradient-filter-to-calculate-the-divergence-of-a-vector-field/5319/3 "2021-03-05T09:19:08Z")

</div>

Hi, I have edited the post.
