Volumes#

Volume adapters connect discrete 3D grids (simulation output, CT/MRI, or other VDB-backed data) to OpenVCAD’s continuous sampling model. Instead of baking data into dense meshes, you keep a sparse OpenVDB grid and query it at any world-space point. Sampling uses trilinear interpolation between voxel centers, so fields stay smooth for rendering, slicing, and compilers.

Typical uses include mapping Hounsfield units or bone density to material properties, reusing FEA or fluid fields on printable geometry, and importing artist-authored VDBs from external tools.

Interface you use in Python

  • Typed volumes — FloatVolume, Vec2sVolume, Vec3sVolume, and Vec4sVolume wrap scalar or vector VDB grids. Call sample(x, y, z) for a value, bounding_box() for world-space bounds, and clone() when you need a thread-safe copy for concurrent evaluation.

  • VDB files — Use pyvcad.vdb_loader (load_float_volume, load_vec3s_volume, load_vec4s_volume) to open a named grid from a .vdb file, optionally centered on the origin.

  • PNG images — PNGLoader.FromImage extrudes one image and PNGLoader.FromStack stacks a directory of slices. Depending on the PNGColorMode, as_rgb_volume() returns a Vec3sVolume or as_rgba_volume() a Vec4sVolume with channels in [0, 1].

  • DICOM stacks — DICOMLoader reads a directory of slices, applies real-world spacing and rescale metadata where available, and builds a scalar FloatVolume (commonly HU). Call as_volume() when you are ready to sample. Slices are stacked in Instance Number (0020,0013) order when every file carries a unique one, and otherwise in natural (digit-aware) filename order, so 1/2/10, 001/002/010 and IMG_0000_0001 style exports all stack correctly. Pass slice_order to force a strategy (pv.DICOMSliceOrder.INSTANCE_NUMBER, SLICE_POSITION or FILENAME) and filename_prefix to ignore a leading part of the filename whose digits should not take part in the ordering.

  • Unstructured result fields — UnstructuredFieldDataset copies TET4 point/connectivity arrays, stores named point- or cell-associated scalar and three-component vector results, and exposes them as ordinary FloatAttribute and Vec3Attribute objects. XDMFFieldLoader provides the same dataset from the supported XDMF 3/HDF5 subset.

  • Scattered points — Values at points with no connectivity (measurements, sensors, point exports) become a field with FloatAttribute.from_points or Vec3Attribute.from_points from NumPy arrays; see the scattered-point fields on the Attributes page.

  • Attributes — A FloatVolume is a continuous field; pass it to FloatAttribute(volume) (or set_volume on an existing FloatAttribute) and attach that attribute to geometry with set_attribute, same as expression-driven fields. Evaluation runs where your solid exists, using the volume’s values inside the part.

Examples#

The patterns below mirror the getting-started discussion of sampled scalar fields: load data, wrap in FloatAttribute, attach to a primitive or mesh.

VDB scalar grid

import pyvcad as pv

vol = pv.vdb_loader.load_float_volume("model.vdb", "density")
bbox_min, bbox_max = vol.bounding_box()
solid = pv.RectPrism.FromMinAndMax(bbox_min, bbox_max)
solid.set_attribute(pv.DefaultAttributes.DENSITY, pv.FloatAttribute(vol))

DICOM series → float volume

import pyvcad as pv

loader = pv.DICOMLoader("path/to/dicom_series")
vol = loader.as_volume()
solid = pv.RectPrism.FromMinAndMax(*vol.bounding_box())
solid.set_attribute(pv.DefaultAttributes.HU, pv.FloatAttribute(vol))

DICOM series with an awkward naming convention

When an export writes filenames such as scan2024_001.dcm, the constant 2024 would otherwise dominate a filename sort. Ignore it with filename_prefix, and force the filename strategy when the files carry no usable Instance Number:

import pyvcad as pv

loader = pv.DICOMLoader(
    "path/to/dicom_series",
    slice_order=pv.DICOMSliceOrder.FILENAME,
    filename_prefix="scan2024_",
)

# Inspect the resolved order without loading any pixel data.
files = pv.sort_dicom_slices(
    pv.collect_dicom_files("path/to/dicom_series"),
    pv.DICOMSliceOrder.FILENAME,
    "scan2024_",
)

Unstructured TET4 result fields#

An unstructured field dataset is data, not geometry. Keep or separately import the OpenVCAD node that should consume the result, then attach a returned attribute to that node:

import numpy as np
import pyvcad as pv

results = pv.UnstructuredFieldDataset.from_tetrahedra(points, cells)
results.add_point_vector("displacement", displacement, units="mm")
results.add_point_scalar(
    "strain_energy_density",
    energy,
    units="mJ/mm^3",
    step_identifier="load-1",
)

energy_attribute = results.float_attribute(
    "strain_energy_density",
    outside="boundary_clamp",
    max_distance=0.8,
)
source_geometry.set_attribute("strain_energy_density", energy_attribute)

Point-associated values are interpolated with TET4 barycentric coordinates. Cell-associated values remain piecewise constant. Coordinates and input values may be contiguous or strided NumPy-compatible float32/float64 arrays; connectivity must use an integer dtype. Construction copies every input array, so later mutation or deletion of the NumPy arrays does not affect the dataset.

Outside behavior is always explicit:

  • "error" is the default and raises when an ordinary attribute is sampled outside the domain. A constant or max_distance supplied with this policy is rejected rather than silently changing its meaning.

  • "constant" requires constant_value; no implicit zero fill is used.

  • "boundary_clamp" projects to the closest point on the outer TET4-domain boundary and requires a finite max_distance. Beyond that band it raises, unless an explicit constant_value is also provided.

Numerical containment tolerance is separate from geometric boundary clamping. Use sample_scalar / sample_vector to inspect one query’s SampleStatus, or coverage to preflight a batch without adding counters to ordinary attribute samples:

report = results.coverage(
    query_points,
    outside="boundary_clamp",
    max_distance=0.8,
    maximum_failures=8,
)
print(report.inside_count, report.boundary_clamped_count, report.outside_count)

Coordinates default to the reference dataset coordinates. transformed uses two deliberately separate matrices: a 4x4 affine matrix maps consuming node positions into dataset positions, and a 3x3 matrix maps stored vector components into consuming coordinates. A displacement field never deforms the domain implicitly. Unit conversion is an explicit matrix scale rather than an effect of the units metadata:

aligned = results.transformed(
    consumer_to_dataset_position,
    stored_to_consumer_vector,
)

max_distance is measured after the position transform, in reference dataset-coordinate units. This keeps its meaning explicit when the transform also performs a model-to-solver unit conversion.

XDMFFieldLoader supports XDMF 3 Uniform grids with TopologyType="Tetrahedron", GeometryType="XYZ", direct HDF-backed topology/geometry/attributes, Center="Node" or Center="Cell", and scalar or three-component vector attributes. Select grid_name when a file contains more than one Uniform grid and optionally select field_names. Temporal or spatial collections, mixed topology, HEX8, inline XML arrays, functions, hyperslabs, tensors, malformed dimensions, and unsupported numeric types fail explicitly; this loader is not a general XDMF implementation.

results = pv.XDMFFieldLoader.load(
    "result.xdmf",
    grid_name="OpenVCADMesh",
    field_names=["displacement", "strain_energy_density"],
)

Volume types#

class pyvcad.FloatVolume#

A VDB volume storing scalar float values.

__init__(*args, **kwargs)#

Overloaded function.

  1. __init__(self: pyvcad.pyvcad.FloatVolume) -> None

Constructor. Creates an empty FloatVolume.

  1. __init__(self: pyvcad.pyvcad.FloatVolume, grid: openvdb::v13_2::Grid<openvdb::v13_2::tree::Tree<openvdb::v13_2::tree::RootNode<openvdb::v13_2::tree::InternalNode<openvdb::v13_2::tree::InternalNode<openvdb::v13_2::tree::LeafNode<float, 3u>, 4u>, 5u>>>>, center: bool = False) -> None

Constructor. Creates a FloatVolume from an existing grid.

Parameters:
  • grid (FloatGrid) – The OpenVDB grid to use.

  • center (bool) – If True, centers the volume about the origin. Defaults to False.

bounding_box(self: pyvcad.pyvcad.FloatVolume) → tuple[pyvcad.pyvcad.Vec3, pyvcad.pyvcad.Vec3]#

Get the world space bounding box of the volume.

Returns:

The minimum and maximum coordinates.

Return type:

tuple[Vec3, Vec3]

clone(self: pyvcad.pyvcad.FloatVolume) → pyvcad.pyvcad.FloatVolume#

Create a thread-safe clone of this volume.

Returns:

A cloned volume instance.

Return type:

FloatVolume

static from_array(array: typing.Annotated[numpy.typing.ArrayLike, numpy.float32], voxel_size: object, origin: pyvcad.pyvcad.Vec3 = <pyvcad.pyvcad.Vec3 object at 0x10477a370>, tolerance: typing.SupportsFloat | typing.SupportsIndex = 0.0, center: bool = False) → pyvcad.pyvcad.FloatVolume#

Build a float volume from a 3D numpy array.

The array is indexed as array[i, j, k] with i along X, j along Y and k along Z. Voxel (i, j, k) is centred at origin + (i * dx, j * dy, k * dz), so sampling at a voxel centre returns its value exactly and values in between are trilinearly interpolated. Any numeric dtype is accepted and converted to float32; non-contiguous and Fortran-ordered arrays are copied into C order first.

Voxels with abs(value) <= tolerance are left inactive (value 0) so mostly-empty data stays sparse.

Parameters:
  • array (numpy.ndarray) – Array of shape (nx, ny, nz).

  • voxel_size (float | Vec3) – Spacing between voxel centres in mm. A Vec3 gives per-axis spacing.

  • origin (Vec3) – World position of the centre of voxel (0, 0, 0) in mm. Defaults to (0, 0, 0).

  • tolerance (float) – Values within this distance of zero stay inactive. Defaults to 0.0.

  • center (bool) – If True, centres the whole array about the origin (origin is then ignored). This uses the array extent, not the active voxels, so several fields from one dataset stay aligned. Defaults to False.

Returns:

A new volume holding a sparse copy of the data.

Return type:

FloatVolume

Raises:

ValueError – If the array is not 3D, or voxel_size or tolerance are invalid.

Example

>>> import numpy as np
>>> import pyvcad as pv
>>> density = np.random.rand(64, 64, 32)
>>> volume = pv.FloatVolume.from_array(density, pv.Vec3(0.5, 0.5, 1.0), center=True)
>>> attribute = pv.FloatAttribute(volume)
grid_type(self: pyvcad.pyvcad.FloatVolume) → str#

Get the grid type name.

Returns:

The grid type name.

Return type:

str

sample(self: pyvcad.pyvcad.FloatVolume, x: SupportsFloat | SupportsIndex, y: SupportsFloat | SupportsIndex, z: SupportsFloat | SupportsIndex) → float#

Sample the volume at the given coordinates.

Parameters:
  • x (float) – X coordinate.

  • y (float) – Y coordinate.

  • z (float) – Z coordinate.

Returns:

The sampled value.

Return type:

float

class pyvcad.Vec2sVolume#

A VDB volume storing 2D vector values with single precision.

__init__(self: pyvcad.pyvcad.Vec2sVolume) → None#

Constructor. Creates an empty Vec2sVolume.

bounding_box(self: pyvcad.pyvcad.Vec2sVolume) → tuple[pyvcad.pyvcad.Vec3, pyvcad.pyvcad.Vec3]#

Get the world space bounding box of the volume.

Returns:

The minimum and maximum coordinates.

Return type:

tuple[Vec3, Vec3]

clone(self: pyvcad.pyvcad.Vec2sVolume) → pyvcad.pyvcad.Vec2sVolume#

Create a thread-safe clone of this volume.

Returns:

A cloned volume instance.

Return type:

Vec2sVolume

grid_type(self: pyvcad.pyvcad.Vec2sVolume) → str#

Get the grid type name.

Returns:

The grid type name.

Return type:

str

sample(self: pyvcad.pyvcad.Vec2sVolume, x: SupportsFloat | SupportsIndex, y: SupportsFloat | SupportsIndex, z: SupportsFloat | SupportsIndex) → pyvcad.pyvcad.Vec2#

Sample the volume at the given coordinates.

Parameters:
  • x (float) – X coordinate.

  • y (float) – Y coordinate.

  • z (float) – Z coordinate.

Returns:

The sampled 2D vector value.

Return type:

Vec2

class pyvcad.Vec3sVolume#

A VDB volume storing 3D vector values with single precision.

__init__(*args, **kwargs)#

Overloaded function.

  1. __init__(self: pyvcad.pyvcad.Vec3sVolume) -> None

Constructor. Creates an empty Vec3sVolume.

  1. __init__(self: pyvcad.pyvcad.Vec3sVolume, grid: openvdb::v13_2::Grid<openvdb::v13_2::tree::Tree<openvdb::v13_2::tree::RootNode<openvdb::v13_2::tree::InternalNode<openvdb::v13_2::tree::InternalNode<openvdb::v13_2::tree::LeafNode<openvdb::v13_2::math::Vec3<float>, 3u>, 4u>, 5u>>>>, center: bool = False) -> None

Constructor. Creates a Vec3sVolume from an existing grid.

Parameters:
  • grid (Vec3SGrid) – The OpenVDB grid to use.

  • center (bool) – If True, centers the volume about the origin. Defaults to False.

bounding_box(self: pyvcad.pyvcad.Vec3sVolume) → tuple[pyvcad.pyvcad.Vec3, pyvcad.pyvcad.Vec3]#

Get the world space bounding box of the volume.

Returns:

The minimum and maximum coordinates.

Return type:

tuple[Vec3, Vec3]

clone(self: pyvcad.pyvcad.Vec3sVolume) → pyvcad.pyvcad.Vec3sVolume#

Create a thread-safe clone of this volume.

Returns:

A cloned volume instance.

Return type:

Vec3sVolume

static from_array(array: typing.Annotated[numpy.typing.ArrayLike, numpy.float32], voxel_size: object, origin: pyvcad.pyvcad.Vec3 = <pyvcad.pyvcad.Vec3 object at 0x10472a370>, tolerance: typing.SupportsFloat | typing.SupportsIndex = 0.0, center: bool = False) → pyvcad.pyvcad.Vec3sVolume#

Build a 3D vector volume (e.g. a velocity field or RGB colour) from a 4D numpy array.

The array is indexed as array[i, j, k, c] with i along X, j along Y, k along Z and c the vector component. Placement, dtype handling and memory order follow FloatVolume.from_array. A voxel stays inactive (value (0, 0, 0)) when every component satisfies abs(component) <= tolerance.

Parameters:
  • array (numpy.ndarray) – Array of shape (nx, ny, nz, 3).

  • voxel_size (float | Vec3) – Spacing between voxel centres in mm. A Vec3 gives per-axis spacing.

  • origin (Vec3) – World position of the centre of voxel (0, 0, 0) in mm. Defaults to (0, 0, 0).

  • tolerance (float) – Per-component distance from zero below which a voxel stays inactive. Defaults to 0.0.

  • center (bool) – If True, centres the whole array about the origin (origin is then ignored). Defaults to False.

Returns:

A new volume holding a sparse copy of the data.

Return type:

Vec3sVolume

Raises:

ValueError – If the array shape is not (nx, ny, nz, 3), or voxel_size or tolerance are invalid.

Example

>>> import numpy as np
>>> import pyvcad as pv
>>> velocity = np.zeros((32, 32, 32, 3), dtype=np.float32)
>>> velocity[..., 2] = 1.0
>>> volume = pv.Vec3sVolume.from_array(velocity, 0.25)
>>> attribute = pv.Vec3Attribute(volume)
grid_type(self: pyvcad.pyvcad.Vec3sVolume) → str#

Get the grid type name.

Returns:

The grid type name.

Return type:

str

sample(self: pyvcad.pyvcad.Vec3sVolume, x: SupportsFloat | SupportsIndex, y: SupportsFloat | SupportsIndex, z: SupportsFloat | SupportsIndex) → pyvcad.pyvcad.Vec3#

Sample the volume at the given coordinates.

Parameters:
  • x (float) – X coordinate.

  • y (float) – Y coordinate.

  • z (float) – Z coordinate.

Returns:

The sampled 3D vector value.

Return type:

Vec3

class pyvcad.Vec4sVolume#

A VDB volume storing 4D vector values with single precision.

__init__(self: pyvcad.pyvcad.Vec4sVolume) → None#

Constructor. Creates an empty Vec4sVolume.

bounding_box(self: pyvcad.pyvcad.Vec4sVolume) → tuple[pyvcad.pyvcad.Vec3, pyvcad.pyvcad.Vec3]#

Get the world space bounding box of the volume.

Returns:

The minimum and maximum coordinates.

Return type:

tuple[Vec3, Vec3]

clone(self: pyvcad.pyvcad.Vec4sVolume) → pyvcad.pyvcad.Vec4sVolume#

Create a thread-safe clone of this volume.

Returns:

A cloned volume instance.

Return type:

Vec4sVolume

grid_type(self: pyvcad.pyvcad.Vec4sVolume) → str#

Get the grid type name.

Returns:

The grid type name.

Return type:

str

sample(self: pyvcad.pyvcad.Vec4sVolume, x: SupportsFloat | SupportsIndex, y: SupportsFloat | SupportsIndex, z: SupportsFloat | SupportsIndex) → pyvcad.pyvcad.Vec4#

Sample the volume at the given coordinates.

Parameters:
  • x (float) – X coordinate.

  • y (float) – Y coordinate.

  • z (float) – Z coordinate.

Returns:

The sampled 4D vector value.

Return type:

Vec4

Loaders#

class pyvcad.DICOMLoader#

A loader for DICOM image stacks that converts them to FloatVolume volumes of Hounsfield Units.

Each stored pixel becomes HU = value * rescale_slope + rescale_intercept. The volume is placed by the pixel spacing and slice thickness, then by the patient transform in the first slice, and optionally centred. Only uncompressed pixel data is supported.

__init__(self: pyvcad.pyvcad.DICOMLoader, directory: str, center: bool = False, rescale_slope: SupportsFloat | SupportsIndex = -inf, rescale_intercept: SupportsFloat | SupportsIndex = -inf, slice_thickness: SupportsFloat | SupportsIndex = -inf, x_pixel_spacing: SupportsFloat | SupportsIndex = -inf, y_pixel_spacing: SupportsFloat | SupportsIndex = -inf, slice_order: pyvcad.pyvcad.DICOMSliceOrder = <DICOMSliceOrder.AUTO: 0>, filename_prefix: str = '') → None#

Constructor. Loads a DICOM image stack.

Values left at their default are read from the first slice’s metadata.

Parameters:
  • directory (str) – The directory containing the DICOM stack.

  • center (bool, optional) – Whether to center the volume at the origin. Default is False.

  • rescale_slope (float, optional) – The rescale slope to apply to pixel values.

  • rescale_intercept (float, optional) – The rescale intercept to apply to pixel values.

  • slice_thickness (float, optional) – The slice thickness in mm.

  • x_pixel_spacing (float, optional) – The pixel spacing in x direction in mm.

  • y_pixel_spacing (float, optional) – The pixel spacing in y direction in mm.

  • slice_order (DICOMSliceOrder, optional) – How the slice files are ordered into a stack. Defaults to DICOMSliceOrder.AUTO, which sorts by Instance Number (0020,0013) when every file carries a unique one and otherwise falls back to a natural (digit-aware) filename sort.

  • filename_prefix (str, optional) – A literal filename prefix ignored when the order falls back to filenames. Use it when the fixed part of a filename contains digits that must not take part in the ordering, for example scan2024_ in scan2024_001.dcm.

Raises:

RuntimeError – If a value is neither given nor found in the metadata, or a slice cannot be read.

Example

>>> import pyvcad as pv
>>> loader = pv.DICOMLoader("dicom", slice_order=pv.DICOMSliceOrder.FILENAME, filename_prefix="scan2024_")
as_volume(self: pyvcad.pyvcad.DICOMLoader) → pyvcad.pyvcad.FloatVolume#

Get the loaded DICOM stack as a volume of Hounsfield Units.

Each call returns a new FloatVolume that shares the loader’s grid.

Returns:

The volume, placed in world space.

Return type:

FloatVolume

get_bounding_box(self: pyvcad.pyvcad.DICOMLoader) → tuple[pyvcad.pyvcad.Vec3, pyvcad.pyvcad.Vec3]#

Get the world-space, axis-aligned bounding box of the placed volume in mm.

It equals as_volume().bounding_box(), so it includes the patient transform and centering.

Returns:

The (min, max) corners.

Return type:

tuple[Vec3, Vec3]

get_dimensions(self: pyvcad.pyvcad.DICOMLoader) → pyvcad.pyvcad.Vec3#

Get the physical dimensions of the loaded DICOM volume in mm, before placement.

Returns:

(columns * x spacing, rows * y spacing, (slices - 1) * slice thickness).

Return type:

Vec3

get_min_max_hu(self: pyvcad.pyvcad.DICOMLoader) → tuple[float, float]#

Get the minimum and maximum Hounsfield Unit (HU) values in the loaded DICOM volume.

Returns:

A tuple containing the minimum and maximum HU values (min_hu, max_hu).

Return type:

tuple

get_rescale_intercept(self: pyvcad.pyvcad.DICOMLoader) → float#

Get the rescale intercept used for converting pixel values to Hounsfield Units (HU).

Returns:

The rescale intercept.

Return type:

float

get_rescale_slope(self: pyvcad.pyvcad.DICOMLoader) → float#

Get the rescale slope used for converting pixel values to Hounsfield Units (HU).

Returns:

The rescale slope.

Return type:

float

get_voxel_size(self: pyvcad.pyvcad.DICOMLoader) → pyvcad.pyvcad.Vec3#

Get the voxel size of the loaded DICOM volume in mm.

Returns:

The voxel size as (x pixel spacing, y pixel spacing, slice thickness).

Return type:

Vec3

class pyvcad.DICOMSliceOrder#

How the slice files of a DICOM series are ordered into a stack.

Members:

AUTO : Sort by Instance Number when every file carries a unique one, otherwise sort by filename.

INSTANCE_NUMBER : Always sort by Instance Number (0020,0013). Raises when the tag is missing or duplicated.

SLICE_POSITION : Sort by the geometric slice position taken from Image Position Patient (0020,0032) or Slice Location (0020,1041). Raises when the position cannot be determined.

FILENAME : Sort by filename only, using a natural (digit-aware) comparison. Reads no metadata.

AUTO = <DICOMSliceOrder.AUTO: 0>#
FILENAME = <DICOMSliceOrder.FILENAME: 3>#
INSTANCE_NUMBER = <DICOMSliceOrder.INSTANCE_NUMBER: 1>#
SLICE_POSITION = <DICOMSliceOrder.SLICE_POSITION: 2>#
DICOMSliceOrder.name -> str
property value#
pyvcad.collect_dicom_files(directory: str) → list[str]#

Collect the candidate DICOM slice files stored in a directory, skipping hidden entries and DICOMDIR.

Parameters:

directory (str) – The directory containing the DICOM stack.

Returns:

The unordered paths of every candidate slice file.

Return type:

list[str]

Example

>>> import pyvcad as pv
>>> files = pv.collect_dicom_files("dicom")
pyvcad.sort_dicom_slices(files: collections.abc.Sequence[str], slice_order: pyvcad.pyvcad.DICOMSliceOrder = <DICOMSliceOrder.AUTO: 0>, filename_prefix: str = '') → list[str]#

Order the files of a DICOM series so that index 0 is the first slice of the stack.

Parameters:
  • files (list[str]) – The slice files to order.

  • slice_order (DICOMSliceOrder, optional) – The ordering strategy. Defaults to DICOMSliceOrder.AUTO.

  • filename_prefix (str, optional) – A literal filename prefix stripped before any filename comparison. Use it when the fixed part of a filename contains digits that must not take part in the ordering, for example scan2024_ in scan2024_001.dcm.

Returns:

The ordered file paths.

Return type:

list[str]

Example

>>> import pyvcad as pv
>>> files = pv.sort_dicom_slices(pv.collect_dicom_files("dicom"), pv.DICOMSliceOrder.FILENAME)
class pyvcad.PNGLoader#

A loader for PNG image volumes. Supports both single-image extrusion and ordered image stacks.

Channels are scaled from 0-255 to [0, 1]. Pixel (column c, row r) of slice z becomes voxel (width - 1 - c, r, z), centred at (i, j, k) * voxel_size unless the volume is centred. Every pixel is stored, transparent or black ones included.

static FromImage(file_path: str, voxel_size: pyvcad.pyvcad.Vec3, depth_mm: SupportsFloat | SupportsIndex, color_mode: pyvcad.pyvcad.PNGColorMode, center: bool = False) → pyvcad.pyvcad.PNGLoader#

Create a PNGLoader from a single PNG image.

Parameters:
  • file_path (str) – Path to the PNG image.

  • voxel_size (Vec3) – Voxel size in mm for x, y, and z.

  • depth_mm (float) – Extrusion depth in mm. The image is repeated ceil(depth_mm / voxel_size.z) times, at least once.

  • color_mode (PNGColorMode) – Output color mode.

  • center (bool) – If True, translate the volume so its bounding box is centred at the origin.

Returns:

The loader holding the volume.

Return type:

PNGLoader

Raises:

RuntimeError – If the file is missing or cannot be decoded, or voxel_size or depth_mm is not positive.

static FromStack(directory: str, voxel_size: pyvcad.pyvcad.Vec3, color_mode: pyvcad.pyvcad.PNGColorMode, center: bool = False) → pyvcad.pyvcad.PNGLoader#

Create a PNGLoader from a directory of PNG slices.

Parameters:
  • directory (str) – Directory containing PNG slices. Files are ordered by the number at the end of their name, then by name; files without a trailing number come last.

  • voxel_size (Vec3) – Voxel size in mm for x, y, and z.

  • color_mode (PNGColorMode) – Output color mode.

  • center (bool) – If True, translate the volume so its bounding box is centred at the origin.

Returns:

The loader holding the volume.

Return type:

PNGLoader

Raises:

RuntimeError – If the directory is missing or has no PNGs, an image cannot be decoded, or the slices differ in size.

as_rgb_volume(self: pyvcad.pyvcad.PNGLoader) → pyvcad.pyvcad.Vec3sVolume#

Get the loaded volume as a Vec3sVolume.

Raises:

RuntimeError – If the loader was not created in COLOR_RGB mode.

as_rgba_volume(self: pyvcad.pyvcad.PNGLoader) → pyvcad.pyvcad.Vec4sVolume#

Get the loaded volume as a Vec4sVolume.

Raises:

RuntimeError – If the loader was not created in COLOR_RGBA mode.

color_mode(self: pyvcad.pyvcad.PNGLoader) → pyvcad.pyvcad.PNGColorMode#

Get the configured PNG color mode.

get_bounding_box(self: pyvcad.pyvcad.PNGLoader) → tuple[pyvcad.pyvcad.Vec3, pyvcad.pyvcad.Vec3]#

Get the world-space bounding box of the loaded volume.

It spans the first to the last voxel centre, and is centred at the origin when the loader was created with center=True.

Returns:

The (min, max) corners in mm.

Return type:

tuple[Vec3, Vec3]

get_dimensions(self: pyvcad.pyvcad.PNGLoader) → pyvcad.pyvcad.Vec3#

Get physical dimensions of the volume in mm: (width, height, slices) times the voxel size.

get_slice_count(self: pyvcad.pyvcad.PNGLoader) → int#

Get the number of slices in z.

get_voxel_size(self: pyvcad.pyvcad.PNGLoader) → pyvcad.pyvcad.Vec3#

Get the voxel size in mm.

class pyvcad.PNGColorMode#

Color interpretation mode for PNG volume loading.

Members:

COLOR_RGB

COLOR_RGBA

COLOR_RGB = <PNGColorMode.COLOR_RGB: 0>#
COLOR_RGBA = <PNGColorMode.COLOR_RGBA: 1>#
PNGColorMode.name -> str
property value#
class pyvcad.TetrahedralDomain#

Immutable validated TET4 domain with shared CGAL point-location and outer-boundary queries.

__init__(self: pyvcad.pyvcad.TetrahedralDomain, points: numpy.ndarray, cells: numpy.ndarray) → None#

Construct a TET4 domain by copying NumPy-compatible arrays.

Parameters:
  • points (array-like) – Finite float32/float64 array with shape (N, 3).

  • cells (array-like) – Integer array with shape (M, 4).

Example

>>> domain = pv.TetrahedralDomain(points, cells)
property boundary_face_count#
property bounding_box#
property cell_count#
property cells#

Return a copy of normalized TET4 connectivity.

property point_count#
property points#

Return a copy of validated dataset-space point coordinates.

property reoriented_cell_count#
class pyvcad.UnstructuredFieldDataset#

Solver-neutral named point/cell scalar and Vec3 fields sharing one immutable TET4 domain.

__init__(self: pyvcad.pyvcad.UnstructuredFieldDataset, domain: pyvcad.pyvcad.TetrahedralDomain) → None#

Construct an empty field dataset sharing an immutable domain.

Parameters:

domain (TetrahedralDomain) – Prepared immutable TET4 domain.

Example

>>> results = pv.UnstructuredFieldDataset(domain)
add_cell_scalar(self: pyvcad.pyvcad.UnstructuredFieldDataset, name: str, values: numpy.ndarray, units: str = '', step_identifier: str = '', description: str = '') → None#

Add a copied cell-associated scalar field.

Parameters:
  • name (str) – Unique field name.

  • values (array-like) – Float32/float64 array with one value per cell. Integer arrays raise TypeError; convert them with astype(float).

  • units (str) – Optional units metadata.

  • step_identifier (str) – Optional load/time-step identifier.

  • description (str) – Optional descriptive metadata.

Example

>>> results.add_cell_scalar('material_id', material_ids.astype(float))
add_cell_vector(self: pyvcad.pyvcad.UnstructuredFieldDataset, name: str, values: numpy.ndarray, units: str = '', step_identifier: str = '', description: str = '') → None#

Add a copied cell-associated three-component vector field.

Parameters:
  • name (str) – Unique field name.

  • values (array-like) – Float32/float64 array with shape (cell_count, 3).

  • units (str) – Optional units metadata.

  • step_identifier (str) – Optional load/time-step identifier.

  • description (str) – Optional descriptive metadata.

Example

>>> results.add_cell_vector('flux', flux)
add_point_scalar(self: pyvcad.pyvcad.UnstructuredFieldDataset, name: str, values: numpy.ndarray, units: str = '', step_identifier: str = '', description: str = '') → None#

Add a copied point-associated scalar field.

Parameters:
  • name (str) – Unique field name.

  • values (array-like) – Float32/float64 array with one value per point.

  • units (str) – Optional units metadata.

  • step_identifier (str) – Optional load/time-step identifier.

  • description (str) – Optional descriptive metadata.

Example

>>> results.add_point_scalar('energy', energy, units='mJ/mm^3')
add_point_vector(self: pyvcad.pyvcad.UnstructuredFieldDataset, name: str, values: numpy.ndarray, units: str = '', step_identifier: str = '', description: str = '') → None#

Add a copied point-associated three-component vector field.

Parameters:
  • name (str) – Unique field name.

  • values (array-like) – Float32/float64 array with shape (point_count, 3).

  • units (str) – Optional units metadata.

  • step_identifier (str) – Optional load/time-step identifier.

  • description (str) – Optional descriptive metadata.

Example

>>> results.add_point_vector('displacement', displacement, units='mm')
coverage(self: pyvcad.pyvcad.UnstructuredFieldDataset, positions: numpy.ndarray, outside: object = 'error', max_distance: object = None, maximum_failures: SupportsInt | SupportsIndex = 8) → pyvcad.pyvcad.CoverageReport#

Classify a batch of consuming-coordinate query positions without persistent counters.

Parameters:
  • positions (array-like) – Float array with shape (N, 3).

  • outside (str | OutsidePolicy) – Outside policy to preflight.

  • max_distance (float | None) – Required finite boundary-clamp band.

  • maximum_failures (int) – Bounded number of representative outside points.

Example

>>> report = results.coverage(points, outside='boundary_clamp', max_distance=0.8)
property domain#
field_metadata(self: pyvcad.pyvcad.UnstructuredFieldDataset, name: str) → pyvcad.pyvcad.FieldMetadata#

Return read-only metadata for a named field.

Parameters:

name (str) – Field name.

Example

>>> metadata = results.field_metadata('displacement')
property field_names#
float_attribute(self: pyvcad.pyvcad.UnstructuredFieldDataset, name: str, outside: object = 'error', max_distance: object = None, constant_value: object = None) → pyvcad.pyvcad.FloatAttribute#

Create an ordinary FloatAttribute backed by a named scalar field.

Parameters:
  • name (str) – Scalar field name.

  • outside (str | OutsidePolicy) – error, constant, or boundary_clamp.

  • max_distance (float | None) – Required finite clamp band for boundary_clamp.

  • constant_value (float | None) – Explicit fallback; with boundary_clamp it applies beyond the band.

Example

>>> energy = results.float_attribute('energy', outside='boundary_clamp', max_distance=0.8)
static from_tetrahedra(points: numpy.ndarray, cells: numpy.ndarray) → pyvcad.pyvcad.UnstructuredFieldDataset#

Construct a dataset by copying point and TET4 connectivity arrays.

Parameters:
  • points (array-like) – Float32/float64 array with shape (N, 3).

  • cells (array-like) – Integer array with shape (M, 4).

Example

>>> results = pv.UnstructuredFieldDataset.from_tetrahedra(points, cells)
has_field(self: pyvcad.pyvcad.UnstructuredFieldDataset, name: str) → bool#

Return whether a named field exists.

Parameters:

name (str) – Field name.

Example

>>> assert results.has_field('displacement')
property position_transform#
sample_scalar(self: pyvcad.pyvcad.UnstructuredFieldDataset, name: str, position: numpy.ndarray, outside: object = 'error', max_distance: object = None, constant_value: object = None) → pyvcad.pyvcad.ScalarFieldSample#

Diagnostically sample a scalar field and return its classification.

Parameters:
  • name (str) – Scalar field name.

  • position (array-like) – Three consuming-coordinate values.

  • outside (str | OutsidePolicy) – Outside policy.

  • max_distance (float | None) – Finite clamp band.

  • constant_value (float | None) – Explicit fallback.

Example

>>> sample = results.sample_scalar('energy', [0.1, 0.1, 0.1])
sample_vector(self: pyvcad.pyvcad.UnstructuredFieldDataset, name: str, position: numpy.ndarray, outside: object = 'error', max_distance: object = None, constant_value: object = None) → pyvcad.pyvcad.Vec3FieldSample#

Diagnostically sample a vector field and return its classification.

Parameters:
  • name (str) – Vector field name.

  • position (array-like) – Three consuming-coordinate values.

  • outside (str | OutsidePolicy) – Outside policy.

  • max_distance (float | None) – Finite clamp band.

  • constant_value (array-like | None) – Explicit three-component fallback.

Example

>>> sample = results.sample_vector('displacement', [0.1, 0.1, 0.1])
transformed(self: pyvcad.pyvcad.UnstructuredFieldDataset, position_transform: numpy.ndarray, vector_transform: object = None) → pyvcad.pyvcad.UnstructuredFieldDataset#

Return a field view with explicit position and vector component transforms.

position_transform maps consuming-node positions into reference dataset coordinates. vector_transform separately maps stored vector components into consuming coordinates. Neither transform implicitly deforms the TET4 domain from a displacement field.

Parameters:
  • position_transform (array-like) – Non-singular affine 4x4 consumer-to-dataset matrix.

  • vector_transform (array-like | None) – Non-singular 3x3 stored-to-consumer vector matrix.

Example

>>> aligned = results.transformed(consumer_to_dataset, dataset_to_consumer_vectors)
vec3_attribute(self: pyvcad.pyvcad.UnstructuredFieldDataset, name: str, outside: object = 'error', max_distance: object = None, constant_value: object = None) → pyvcad.pyvcad.Vec3Attribute#

Create an ordinary Vec3Attribute backed by a named vector field.

Parameters:
  • name (str) – Three-component field name.

  • outside (str | OutsidePolicy) – error, constant, or boundary_clamp.

  • max_distance (float | None) – Required finite clamp band for boundary_clamp.

  • constant_value (array-like | None) – Explicit three-component fallback.

Example

>>> displacement = results.vec3_attribute('displacement')
property vector_transform#
class pyvcad.XDMFFieldLoader#

Public loader for the documented XDMF 3/HDF5 Uniform TET4 result-field subset.

static load(xdmf_path: str, grid_name: str = '', field_names: collections.abc.Sequence[str] = []) → pyvcad.pyvcad.UnstructuredFieldDataset#

Load one supported XDMF Uniform TET4 grid and selected HDF-backed fields.

Parameters:
  • xdmf_path (str) – XDMF 3 document path.

  • grid_name (str) – Required selection when multiple Uniform grids are present.

  • field_names (list[str]) – Selected fields, or an empty list for all fields.

Example

>>> results = pv.XDMFFieldLoader.load('results.xdmf', field_names=['displacement'])
class pyvcad.FieldMetadata#

Read-only metadata for one named unstructured result field.

class pyvcad.CoverageReport#

Opt-in classification report for a batch of sample positions.

fraction(self: pyvcad.pyvcad.CoverageReport, status: pyvcad.pyvcad.SampleStatus) → float#

Return the fraction assigned to one SampleStatus.

Parameters:

status (SampleStatus) – Classification to inspect.

Example

>>> outside_fraction = report.fraction(pv.SampleStatus.OUTSIDE)
class pyvcad.ScalarFieldSample#

Diagnostic scalar value and geometric classification.

class pyvcad.Vec3FieldSample#

Diagnostic vector value and geometric classification.

class pyvcad.CoverageFailure#

Representative outside-domain query retained by a coverage report.

class pyvcad.FieldAssociation#

Association of result values with mesh points or cells.

Members:

POINT

CELL

FieldAssociation.name -> str
class pyvcad.OutsidePolicy#

Explicit behavior outside an unstructured field domain.

Members:

ERROR

CONSTANT

BOUNDARY_CLAMP

OutsidePolicy.name -> str
class pyvcad.SampleStatus#

Diagnostic classification for one result-field query.

Members:

INSIDE

TOLERANCE_ADJUSTED

BOUNDARY_CLAMPED

OUTSIDE

SampleStatus.name -> str

pyvcad.vdb_loader#

VDB file loading utilities

pyvcad.vdb_loader.load_float_volume(file_path: str, grid_name: str, center: bool = False) → pyvcad.pyvcad.FloatVolume#

Load a float VDB volume from a specific grid in a VDB file.

Parameters:
  • file_path (str) – Path to the VDB file.

  • grid_name (str) – Name of the grid to load.

  • center (bool) – If True, centers the bounding box of the active voxels at the origin. Defaults to False.

Returns:

The loaded float volume.

Return type:

FloatVolume

Raises:

RuntimeError – If the file cannot be read, the grid is not found, or the grid is not a float grid.

pyvcad.vdb_loader.load_vec3s_volume(file_path: str, grid_name: str, center: bool = False) → pyvcad.pyvcad.Vec3sVolume#

Load a Vec3s VDB volume from a specific grid in a VDB file.

Parameters:
  • file_path (str) – Path to the VDB file.

  • grid_name (str) – Name of the grid to load.

  • center (bool) – If True, centers the bounding box of the active voxels at the origin. Defaults to False.

Returns:

The loaded Vec3s volume.

Return type:

Vec3sVolume

Raises:

RuntimeError – If the file cannot be read, the grid is not found, or the grid is not a Vec3s grid.

pyvcad.vdb_loader.load_vec4s_volume(file_path: str, grid_name: str, center: bool = False) → pyvcad.pyvcad.Vec4sVolume#

Load a Vec4s VDB volume from a specific grid in a VDB file.

Parameters:
  • file_path (str) – Path to the VDB file.

  • grid_name (str) – Name of the grid to load.

  • center (bool) – If True, centers the bounding box of the active voxels at the origin. Defaults to False.

Returns:

The loaded Vec4s volume.

Return type:

Vec4sVolume

Raises:

RuntimeError – If the file cannot be read, the grid is not found, or the grid is not a Vec4s grid.

pyvcad.vdb_loader.save_float_volume(volume: pyvcad.pyvcad.FloatVolume, file_path: str, grid_name: str) → None#

Save a float volume to a VDB file as a single named grid.

Useful for caching volumes built from numpy arrays so they can be reloaded with load_float_volume. The grid keeps its transform, so it reloads at the same world position. Existing files are overwritten.

Parameters:
  • volume (FloatVolume) – The volume to save.

  • file_path (str) – Destination .vdb path.

  • grid_name (str) – Name stored for the grid.

Raises:
  • RuntimeError – If the file cannot be written.

  • ValueError – If grid_name is empty.

Example

>>> volume = pv.FloatVolume.from_array(density, 0.5)
>>> pv.vdb_loader.save_float_volume(volume, 'density.vdb', 'density')
>>> cached = pv.vdb_loader.load_float_volume('density.vdb', 'density')
pyvcad.vdb_loader.save_vec3s_volume(volume: pyvcad.pyvcad.Vec3sVolume, file_path: str, grid_name: str) → None#

Save a Vec3s volume to a VDB file as a single named grid.

Reload it with load_vec3s_volume. Existing files are overwritten.

Parameters:
  • volume (Vec3sVolume) – The volume to save.

  • file_path (str) – Destination .vdb path.

  • grid_name (str) – Name stored for the grid.

Raises:
  • RuntimeError – If the file cannot be written.

  • ValueError – If grid_name is empty.

Example

>>> volume = pv.Vec3sVolume.from_array(velocity, 0.5)
>>> pv.vdb_loader.save_vec3s_volume(volume, 'velocity.vdb', 'velocity')