3

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?

Mantabit
  • 269
  • 1
  • 4
  • 14

2 Answers2

8

A more lightweight solution would be to use meshio (which I authored). It has no required dependencies except numpy. Install with

pip install meshio

and read the file with

import meshio

mesh = meshio.read("foo.vtu")
# mesh.points, mesh.cells, mesh.point_data, ...
Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249
6

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")
Jnsll
  • 3
  • 3
Mathieu Westphal
  • 2,544
  • 1
  • 19
  • 33