Saving data as .csv files

This is how this histogram viewer works in the gui, if it is a vtu file, use read_griddata, if it is a vtp file, use read_partdata. The functions will return a dict of variables names with some other info including the actual array, data. Then just use the vtk_to_numpy function on that data array.

import vtk

def read_griddata(path):
    ugrid_reader = (
        vtk.vtkXMLPUnstructuredGridReader()
        if path.suffix == "pvtu"
        else vtk.vtkXMLUnstructuredGridReader()
    )

    ugrid_reader.SetFileName(path)
    ugrid_reader.Update()
    data = ugrid_reader.GetOutput()

    cell_data = data.GetCellData()
    array_info = {}
    for i in range(cell_data.GetNumberOfArrays()):
        array = cell_data.GetArray(i)
        n_comp = array.GetNumberOfComponents()
        name = cell_data.GetArrayName(i)
        array_info[name] = {
            'magnitude':  array.GetRange(-1),
            'components': n_comp,
            'range':      [array.GetRange(i) for i in range(n_comp)],
            'data':       cell_data.GetAbstractArray(name),
        }
    return array_info

def read_partdata(path):
    particle_reader = (
        vtk.vtkXMLPPolyDataReader()
        if path.suffix == ".pvtp"
        else vtk.vtkXMLPolyDataReader()
    )
    particle_reader.SetFileName(path)
    particle_reader.Update()

    data = particle_reader.GetOutput()
    point_data = data.GetPointData()
    array_info = {}
    n_tuples = None
    for i in range(point_data.GetNumberOfArrays()):
        array = point_data.GetArray(i)
        n_comp = array.GetNumberOfComponents()
        n_tuples = array.GetNumberOfTuples()

        name = point_data.GetArrayName(i)
        array_info[name] = {
            'number_of_tuples': n_tuples,
            'components':       n_comp,
            'range':            [array.GetRange(i) for i in range(n_comp)],
            'magnitude':        array.GetRange(-1),
            'data':             point_data.GetAbstractArray(name),
        }
    return array_info

if __name__ == "__main__":
    vtp_arrays = read_partdata('/path/to/output.vtp')
1 Like