python-3.xnumpyvtk

Reading data from a raw VTK (.vtu) file


I want to extract data arrays from a .vtu file using the Python VTK module. The file looks like this (the raw data at the end of the file is ommitted):

<?xml version="1.0"?>
<VTKFile type="UnstructuredGrid" version="0.1" byte_order="LittleEndian">
  <UnstructuredGrid>
    <Piece NumberOfPoints="10471" NumberOfCells="64892">
      <PointData>
        <DataArray type="Float64" Name="potential" NumberOfComponents="1" format="appended" offset="0"/>
        <DataArray type="Float64" Name="electric field" NumberOfComponents="3" format="appended" offset="83772"/>
      </PointData>
      <CellData>
        <DataArray type="Int32" Name="GeometryIds" format="appended" offset="335080"/>
      </CellData>
      <Points>
        <DataArray type="Float64" NumberOfComponents="3" format="appended" offset="594652"/>
      </Points>
      <Cells>
        <DataArray type="Int32" Name="connectivity" format="appended" offset="845960"/>
        <DataArray type="Int32" Name="offsets" format="appended" offset="1865068"/>
        <DataArray type="Int32" Name="types" format="appended" offset="2124640"/>
      </Cells>
    </Piece>
  </UnstructuredGrid>
<AppendedData encoding="raw">

I try to extract the data using the following python code:

import numpy
from vtk import vtkUnstructuredGridReader
from vtk.util import numpy_support as VN

reader = vtkUnstructuredGridReader()
reader.SetFileName("charged_wire.vtu")
reader.ReadAllVectorsOn()
reader.ReadAllScalarsOn()
reader.Update()

data = reader.GetOutput()
potential = data.GetPointData().GetScalars("potential")

print(type(potential))

Unfortunately, this program prints NoneType as output and I'm not really sure what I need to change in order to extract the data stores in the potential array?


Solution

  • You are not using the right reader, this is a .vtu file, you have to use the vtkXMLUnstructuredGridReader.

    import vtk.vtk
    
    # The source file
    file_name = "path/to/your/file.vtu"
    
    # Read the source file.
    reader = vtk.vtkXMLUnstructuredGridReader()
    reader.SetFileName(file_name)
    reader.Update()  # Needed because of GetScalarRange
    output = reader.GetOutput()
    potential = output.GetPointData().GetArray("potential")