Skip to content

Note

Click here to download the full example code

VTK files

write_vtk writes a PointSet, Polylines, Mesh or BlockModel as a VTK XML file, which 3D viewers and VTK-based tools open with their columns. read_vtk reads it back to the same container, whether the file is ASCII, binary or appended, compressed or not. You write a vein of the grade-control dataset with a column per vertex and per triangle, points around it with their distance to the vein, and the blocks near it.

import sys
from pathlib import Path

HERE = Path(__file__).parent if "__file__" in globals() else Path.cwd()
sys.path.insert(0, str(HERE.parents[1]))
import tempfile

import boitata as bt
import matplotlib.pyplot as plt
import numpy as np
from common import INK, map_axes, save

vein = bt.datasets.vein_gold_grade_control()["vein_V1"]
elevation = vein.z.copy()
elevation[::50] = np.nan
a, b, c = vein.coords[vein.triangles].transpose(1, 0, 2)
normal = np.cross(b - a, c - a)
dip = np.degrees(np.arccos(np.abs(normal[:, 2]) / np.linalg.norm(normal, axis=1)))
vein = vein.with_vertex_column("elevation", elevation).with_face_column("dip", dip)
print(vein)

rng = np.random.default_rng(7)
(x0, y0, z0), (x1, y1, z1) = vein.bounds
coords = rng.uniform([x0, y0, z0], [x1, y1, z1], size=(300, 3))
points = bt.PointSet(coords, attributes={"distance": vein.distance(coords)})

Out:

Mesh  19,602 vertices, 39,200 triangles, closed
  area    815881.2
  volume  661982.2
  bounds  x 7949.8 to 8185.3, y 14598.7 to 15440.1, z 394.4 to 858
  vertex columns
  column     type     unit  nulls    min   mean  max
  elevation  float64          393  394.4  625.8  858
  face columns
  column  type     unit  nulls  min   mean  max
  dip     float64            0   20  69.81   90

Point and cell data become columns. VTK has no nulls, so a column with nulls is written with NaN in their place and a <name>_valid array of ones and zeros, which read_vtk turns back into nulls. Binary files append the arrays raw after the XML; ascii=True writes them as text.

folder = Path(tempfile.mkdtemp())
for file, data, options in [
    ("vein.vtp", vein, {}),
    ("vein.vtu", vein, {"ascii": True}),
    ("points.vtp", points, {}),
]:
    path = folder / file
    bt.write_vtk(path, data, **options)
    back = bt.read_vtk(path)
    same = all(np.array_equal(back[c], data[c], equal_nan=True) for c in data.column_names)
    print(f"{file:>11}: {path.stat().st_size / 1e3:6.0f} kB, {type(back).__name__}, same columns: {same}")
back = bt.read_vtk(folder / "vein.vtp")
print("nulls in elevation:", np.isnan(back["elevation"]).sum())

Out:

   vein.vtp:   2216 kB, Mesh, same columns: True
   vein.vtu:   3116 kB, Mesh, same columns: True
 points.vtp:     15 kB, PointSet, same columns: True
nulls in elevation: 393
fig, ax = plt.subplots(figsize=(7, 5), layout="constrained")
image = ax.tripcolor(back.x, back.y, back.triangles, facecolors=back["dip"], cmap="cividis")
near = points["distance"] < 10
ax.scatter(points.x[near], points.y[near], s=8, color=INK, label="Points within 10 m")
fig.colorbar(image, ax=ax, shrink=0.8, label="Triangle dip, degrees (cell data)")
ax.legend(loc="upper right")
map_axes(ax, "Vein V1 read back from vein.vtp")
save(fig, "vtk")

Vein V1 read back from vein.vtp

Grids

A BlockModel goes to .vti (image data): the origin, cell sizes and counts, and the rotation as the grid's Direction. A masked model writes every cell and hides the absent ones with vtkGhostType, which viewers skip and read_vtk drops again. .vtu holds one hexahedron per block and takes sub-blocks too; read_vtk rebuilds the grid when the hexahedra are equal boxes on one lattice. read_vtk also reads .vtr and .vts grids, to a BlockModel when their spacing is regular and to the cell centers otherwise.

Grid values stored on the nodes (point data) are not cell values: a file with point data only comes back as the nodes, and point_data=True returns them from any file.

grid = bt.BlockModel.from_extents(vein, size=(10, 10, 10), buffer=20, rotation=(-15, 0, 0))
grid = grid.with_column("distance", vein.distance(grid.coords))
shell = grid.filter(grid["distance"] < 15)
print(shell)
for file in ("shell.vti", "shell.vtu"):
    bt.write_vtk(folder / file, shell)
    back = bt.read_vtk(folder / file)
    print(
        f"{file:>9}: {(folder / file).stat().st_size / 1e3:6.0f} kB, {len(back)} blocks, same: "
        f"{np.allclose(back.coords, shell.coords) and np.array_equal(back['distance'], shell['distance'])}"
    )
nodes = bt.read_vtk(folder / "shell.vti", point_data=True)
print(f"nodes of the grid: {len(nodes)}")

Out:

BlockModel  masked, 13,827 of 158,865 blocks
  count     35 × 89 × 51
  size      10 × 10 × 10
  origin    8013.6, 14546.4, 374.4
  rotation  azimuth -15°, dip 0°, rake 0°
  bounds    x 7930.7 to 8204.2, y 14578 to 15457.3, z 384.4 to 874.4
  column    type     unit  nulls       min   mean  max
  distance  float64            0  0.001431  7.331   15
shell.vti:   1589 kB, 13827 blocks, same: True
shell.vtu:   3776 kB, 13827 blocks, same: True
nodes of the grid: 168480
back = bt.read_vtk(folder / "shell.vti")
level = np.isclose(back.z, np.median(back.z))
fig, ax = plt.subplots(figsize=(7, 5), layout="constrained")
image = ax.scatter(back.x[level], back.y[level], c=back["distance"][level], s=12, marker="s", cmap="cividis")
fig.colorbar(image, ax=ax, shrink=0.8, label="Distance to the vein (m)")
map_axes(ax, "Blocks within 15 m of the vein, read back from shell.vti")
save(fig, "grid")

Blocks within 15 m of the vein, read back from shell.vti

Total running time of the script: ( 0 minutes 2.870 seconds)

Download Python source code: example_03_15.py

Download Jupyter notebook: example_03_15.ipynb

Gallery generated by mkdocs-gallery