Datasets Are Python Objects
In VTK and NumPy, a new take, I showed point_data behaving like a dictionary of numpy-friendly arrays, and promised to dig deeper. Since then, this series has been all about arrays. But arrays live in datasets, and a dataset is more than its arrays: it has points, it has cells, and building those used to be where Python code got ugly (InsertNextPoint() in a loop, anyone?). Let’s build some datasets straight from numpy.
A surface
Here is a height field, z = 0.5 sin(x) cos(y), as a triangulated surface. numpy does all the work:
>>> import numpy as np
>>> from vtkmodules import vtkCommonCore as common_core
>>> from vtkmodules import vtkCommonDataModel as data_model
>>> nx, ny = 50, 40
>>> x, y = np.meshgrid(np.linspace(0, 2 * np.pi, nx), np.linspace(0, 2 * np.pi, ny))
>>> z = 0.5 * np.sin(x) * np.cos(y)
>>> xyz = np.column_stack([x.ravel(), y.ravel(), z.ravel()])
>>> i, j = np.meshgrid(np.arange(nx - 1), np.arange(ny - 1))
>>> corner = (j * nx + i).ravel()
>>> tris = np.concatenate([
... np.column_stack([corner, corner + 1, corner + nx + 1]),
... np.column_stack([corner, corner + nx + 1, corner + nx])])
>>> offsets = np.arange(0, 3 * len(tris) + 1, 3)
>>> surface = data_model.vtkPolyData(
... points=common_core.vtkPoints(data=xyz),
... polys=data_model.vtkCellArray(offsets=offsets, connectivity=tris.ravel()))
>>> surface.number_of_points, surface.number_of_cells
(2000, 3822)
A few things to note:
- Each grid square becomes two triangles, and
corneris the index of each square’s lower-left point, so the connectivity is index arithmetic on whole arrays. No loops. vtkCellArraytakes the two arrays VTK stores cells in:connectivity, the point ids of all cells back to back, andoffsets, where each cell starts (plus one entry for the end). Every cell here has 3 points, hence thearangewith a step of 3.points=andpolys=are just constructor keywords, which work for every VTK class (more on those here).
The points are not a copy of xyz:
>>> np.shares_memory(surface.points.data, xyz)
True
Arrays go in the same way as before, and the surface is ready for anything VTK can do. Say, the total area, with the functions module from my last blog:
>>> from vtkmodules.util import functions
>>> surface.point_data['height'] = z.ravel()
>>> functions.area(surface).sum(), (2 * np.pi) ** 2
(np.float64(41.852769592025936), 39.47841760435743)
A bit more than the flat square underneath it, as it should be.
Cells of different kinds
An unstructured grid can mix cell types, so it needs one more array: a type per cell. Here is a house, a hexahedron with a pyramid for a roof:
>>> house_points = common_core.vtkPoints(data=[
... [0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0],
... [0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1],
... [0.5, 0.5, 1.5]])
>>> house_cells = data_model.vtkCellArray(
... offsets=[0, 8, 13], connectivity=[0, 1, 2, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8])
>>> types = common_core.vtkUnsignedCharArray(
... np.array([data_model.VTK_HEXAHEDRON, data_model.VTK_PYRAMID], dtype=np.uint8))
>>> house = data_model.vtkUnstructuredGrid(points=house_points)
>>> house.cells = (types, house_cells)
>>> functions.volume(house).to_numpy()
array([1. , 0.16666667])
A unit cube, and a pyramid with a 1 by 1 base and a height of 0.5, so a sixth. (When all cells have the same type, house.cells = (VTK_TETRA, cells) does it with a single type.) Cell data works like point data, including a scalar that fills the whole array, and assigning a dict replaces all arrays at once:
>>> house.cell_data['material'] = 7
>>> house.cell_data['material'].to_numpy()
array([7, 7])
>>> house.cell_data = {'id': np.arange(2), 'volume': functions.volume(house)}
>>> list(house.cell_data)
['id', 'volume']
Structured grids
The other half of VTK’s datasets are structured: points and cells come in an i-j-k grid, so there is no connectivity to build. There are three kinds: image data (uniform spacing), rectilinear grids (a coordinate array per axis) and structured grids (explicit points on a curvilinear grid). All three number their points with i varying fastest, then j, then k. In numpy terms, that’s Fortran order. Let’s make that visible with a field whose values encode their own indices:
>>> img = data_model.vtkImageData(dimensions=(40, 30, 20), spacing=(0.1, 0.1, 0.1))
>>> i, j, k = np.indices(img.dimensions)
>>> ijk = i + 100 * j + 10000 * k
>>> img.point_data['ijk'] = ijk.ravel(order='F')
>>> img.point_data['ijk'][[0, 1, 40, 1200]]
array([ 0, 1, 100, 10000])
The second point is one step in i, the 40th is one step in j and the 1200th is one step in k. Going back to three dimensions is a reshape() with the same order:
>>> f = img.point_data['ijk'].reshape(img.dimensions, order='F')
>>> np.array_equal(f, ijk)
True
>>> f[:, :, 10].shape
(40, 30)
So the rule is: index your numpy arrays [i, j, k] and use order='F' both ways. If you prefer [k, j, i] (as many imaging libraries do), plain C order works instead, with the dimensions reversed. Mixing the two scrambles your data without an error, which is why this is worth a paragraph.
A rectilinear grid takes one coordinate array per axis, graded ones included:
>>> grid = data_model.vtkRectilinearGrid(dimensions=(8, 4, 2))
>>> grid.x_coordinates = np.geomspace(1, 128, 8)
>>> grid.y_coordinates = np.linspace(0, 3, 4)
>>> grid.z_coordinates = np.array([0.0, 1.0])
>>> grid.points.data[:3]
array([[1., 0., 0.],
[2., 0., 0.],
[4., 0., 0.]])
>>> grid.points.data.GetActualMemorySize()
1
Neither of these stores its points. They are computed from the origin and spacing, or from the coordinates, as in my implicit arrays blog.
A structured grid does store its points, so it can bend. Here is a quarter of a thick cylindrical shell, built in polar coordinates with the same [i, j, k] and order='F' rule:
>>> r, theta, h = np.meshgrid(np.linspace(1, 2, 5), np.linspace(0, np.pi / 2, 20),
... np.linspace(0, 1, 3), indexing='ij')
>>> xyz = np.column_stack([a.ravel(order='F')
... for a in (r * np.cos(theta), r * np.sin(theta), h)])
>>> shell = data_model.vtkStructuredGrid(
... dimensions=r.shape, points=common_core.vtkPoints(data=xyz))
>>> functions.volume(shell).sum(), 3 * np.pi / 4
(np.float64(2.353511345961471), 2.356194490192345)
>>> np.allclose(shell.x_coordinates, r * np.cos(theta))
True
A bit less than the exact volume, because a hexahedron’s sides are flat where the shell’s are curved. indexing='ij' makes meshgrid() return [i, j, k] arrays (its default swaps the first two axes). And x_coordinates on a structured grid hands the x values back as an [i, j, k] array.
Collections of datasets
Real data often comes in pieces: blocks of different types, or partitions of one mesh. VTK’s composite datasets hold them, and they act like Python containers too. Let’s put three of our datasets in a collection:
>>> collection = data_model.vtkPartitionedDataSetCollection()
>>> for ds in (house, shell, img):
... partitioned = data_model.vtkPartitionedDataSet()
... partitioned.append(ds)
... collection.append(partitioned)
>>> [ds.GetClassName() for ds in collection]
['vtkUnstructuredGrid', 'vtkStructuredGrid', 'vtkImageData']
>>> collection.cell_data.keys()
('id', 'volume')
Iterating goes over the datasets themselves, however deep they are nested. The collection’s cell_data is the union of its datasets’ arrays: the two names here come from the house alone. And functions works on the whole thing:
>>> vol = functions.volume(collection)
>>> vol
VTKPartitionedArray(shape=(21643,), dtype=float64, blocks=3)
>>> vol.sum()
np.float64(25.009178012628144)
>>> [a.shape for a in vol.arrays]
[(2,), (152,), (21489,)]
>>> collection.cell_data['volume'] = vol
>>> shell.cell_data['volume'].shape
(152,)
One array that spans three datasets of three types, with numpy reductions across all of them (1.17 for the house, 2.35 for the shell, 21.49 for the image), and assigning it back gives each dataset its piece. Partitioned arrays deserve a blog of their own, along with running the same code on many MPI ranks.
Equality
One more thing that makes datasets feel like Python values: == compares contents, not identity.
>>> copy = data_model.vtkPolyData()
>>> copy.DeepCopy(surface)
>>> copy == surface
True
>>> copy.point_data['height'][0] = 99
>>> copy == surface
False
That’s it folks.