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

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

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 :

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

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

1 Like

Hi, I have edited the post.