Python

Top level

import zvcfd needs only numpy, scipy and zarr. It re-exports BrickDomain, Lattice, RunConfig, load_config, read_fluent_boundary and the functions below.

zvcfd.runtime_capabilities(*, probe_device=False)[source]

{capability: available} for this install.

Keys:

cupy, cuda_device (with probe_device), nccl, peer_access (with probe_device and >= 2 devices), kvikio, nvcomp, pyamg, icechunk, zarr_vectors, and the zarr-vectors capabilities zvCFD relies on, prefixed zv_: read_cells, device_decode, gpu_codecs, gpu_io, defer_presence, append_safe_sharding, dense_manifests.

Parameters:

probe_device (bool)

Return type:

dict[str, bool]

zvcfd.require(*names, probe_device=True)[source]

Raise RuntimeError naming every missing capability.

Parameters:
Return type:

dict[str, bool]

zvcfd.device_count()[source]

Visible CUDA devices; 0 without cupy or a driver. Initialises CUDA.

Return type:

int

zvcfd.estimate(fluid_cells, *, fill=0.6, box_cells=None, gpus=8, gpu='H100-SXM', method='lbm-fp32', layout='sparse', geometry='vessel', steps=None, efficiency='planning', parallel_efficiency=None)[source]

Memory and time for steps updates of fluid_cells on gpus x gpu.

Parameters:
  • fluid_cells (float) – Non-solid voxels.

  • fill (float) – Brick fill (fluid / stored cells), sparse layout only.

  • box_cells (float | None) – Bounding-box voxels; required for layout="dense".

  • geometry (str) – open | porous | vessel (kernel-efficiency class).

  • parallel_efficiency (float | None) – Multi-GPU efficiency; default 1.0 for one GPU, 0.85 for peer-connected GPUs (waLBerla measures >= 82% weak scaling), 0.6 when halos go through the host.

  • gpus (int)

  • gpu (str)

  • method (str)

  • layout (str)

  • steps (int | None)

  • efficiency (str)

Return type:

Estimate

Domains

Sparse brick domains: the solver’s view of a voxel geometry.

A domain is the set of B^3 bricks (default 8^3) that hold at least one non-solid voxel. Only those bricks are stored, on the GPU and on disk, so memory scales with the fluid volume rather than the bounding box.

Bricks group into chunks of chunk_bricks^3 bricks. A chunk is one cell of the Zarr Vectors store, the unit a GPU owns, and the unit of halo exchange. BrickDomain.partition() assigns whole chunks to GPUs, so no two workers ever write the same store cell (or, with shard_shape set on the store, the same shard). This is the zarr-vectors concurrency contract: the shard is the unit of exclusion.

Voxel flags: 0 fluid, 1 solid, 2 fixed-density boundary (reservoir). Axis order is (z, y, x) throughout, as in OME-Zarr.

class zvcfd.domain.BrickDomain(shape, brick, coords, flags, neighbours, periodic=(False, False, False), _lut=None, n_owned=None, global_ids=None)[source]

Bases: object

Active bricks of a voxel geometry, with their neighbour table.

Variables:
  • shape (tuple[int, int, int]) – Voxel shape of the bounding box, (z, y, x).

  • brick (int) – Brick edge in voxels.

  • coords (numpy.ndarray) – (nb, 3) brick coordinates (z, y, x), in Morton order so bricks that are close in space are close in memory.

  • flags (numpy.ndarray) – (nb, brick^3) uint8 voxel flags, x fastest within a brick.

  • neighbours (numpy.ndarray) – (nb, 27) int32 brick index of each neighbour slot, -1 where the neighbour brick is inactive (reads as solid).

  • periodic (tuple[bool, bool, bool]) – Per-axis periodicity used to build neighbours.

Parameters:
__init__(shape, brick, coords, flags, neighbours, periodic=(False, False, False), _lut=None, n_owned=None, global_ids=None)
Parameters:
Return type:

None

property active_fraction: float
brick: int
property brick_grid: tuple[int, int, int]
brick_index(coords)[source]

Brick index for (n, 3) brick coordinates; -1 where inactive.

Parameters:

coords (ndarray)

Return type:

ndarray

property cells_per_brick: int
chunk_of(chunk_bricks)[source]

(nb, 3) chunk coordinate (z, y, x) of every brick.

Parameters:

chunk_bricks (int)

Return type:

ndarray

chunks(chunk_bricks)[source]

Occupied chunks and, for each brick, the row of its chunk.

Returns (chunk_coords (C, 3), brick_chunk (nb,)).

Parameters:

chunk_bricks (int)

Return type:

tuple[ndarray, ndarray]

coords: ndarray
property fill: float

Fraction of stored cells that are not solid (brick fill efficiency).

flags: ndarray
property fluid_cells: int
classmethod from_brick_mask(active, *, brick=8, periodic=False)[source]

Build from a brick-level boolean mask; every voxel of an active brick is fluid.

For synthetic I/O and scaling tests where voxel detail does not matter.

Parameters:
Return type:

BrickDomain

classmethod from_bricks(shape, coords, flags, *, brick=8, periodic=False)[source]

Build from active brick coordinates (nb, 3) and their flags (nb, brick^3).

The form a domain store holds; no dense volume is ever made. Bricks are re-sorted into Morton order.

Parameters:
Return type:

BrickDomain

classmethod from_flags(flags, *, brick=8, periodic=False)[source]

Build from a dense (z, y, x) flag volume (0 fluid, 1 solid, 2 reservoir).

Parameters:
Return type:

BrickDomain

classmethod from_mask(fluid, **kw)[source]

Build from a boolean fluid mask (True = fluid).

Parameters:

fluid (ndarray)

Return type:

BrickDomain

global_ids: ndarray | None = None
halo(parts, part)[source]

Bricks owned by other parts that neighbour part’s bricks (its ghost set).

Parameters:
Return type:

ndarray

local(parts, part)[source]

Partition part’s view: its bricks, then its ghost bricks.

Owned bricks keep their Morton order and come first; ghosts follow. The neighbour table is renumbered to local indices; ghost rows are -1 (ghosts are never updated, only refreshed from their owners).

Parameters:
Return type:

BrickDomain

property n_bricks: int
n_owned: int | None = None

the first n_owned bricks are owned, the rest are ghosts, and global_ids maps local bricks to the parent’s.

Type:

For a partition-local domain

neighbours: ndarray
property owned_fluid_cells: int
partition(n_parts, chunk_bricks)[source]

Assign whole chunks to n_parts workers, balancing fluid cells.

Chunks are ordered along a Morton curve and cut into contiguous runs of roughly equal fluid work, which keeps each worker’s region compact (a small halo surface). Returns (nb,) part ids.

Parameters:
  • n_parts (int)

  • chunk_bricks (int)

Return type:

ndarray

periodic: tuple[bool, bool, bool] = (False, False, False)
shape: tuple[int, int, int]
property stored_cells: int
summary()[source]
Return type:

dict

to_dense(values, fill=0.0)[source]

Scatter (n_bricks, brick^3) rows (domain order) into a dense (z, y, x) volume.

Solid voxels and inactive bricks take fill.

Parameters:

values (ndarray)

Return type:

ndarray

zvcfd.domain.NEIGHBOUR_OFFSETS = array([[-1, -1, -1],        [-1, -1,  0],        [-1, -1,  1],        [-1,  0, -1],        [-1,  0,  0],        [-1,  0,  1],        [-1,  1, -1],        [-1,  1,  0],        [-1,  1,  1],        [ 0, -1, -1],        [ 0, -1,  0],        [ 0, -1,  1],        [ 0,  0, -1],        [ 0,  0,  0],        [ 0,  0,  1],        [ 0,  1, -1],        [ 0,  1,  0],        [ 0,  1,  1],        [ 1, -1, -1],        [ 1, -1,  0],        [ 1, -1,  1],        [ 1,  0, -1],        [ 1,  0,  0],        [ 1,  0,  1],        [ 1,  1, -1],        [ 1,  1,  0],        [ 1,  1,  1]])

Neighbour slot k of a brick is offset (dz, dy, dx) with k = 9(dz+1) + 3(dy+1) + (dx+1).

zvcfd.domain.morton3(coords)[source]

Morton (Z-order) key of non-negative (n, 3) integer coordinates (< 2^21).

Parameters:

coords (ndarray)

Return type:

ndarray

Solvers

D3Q19 lattice-Boltzmann solvers on one GPU: dense boxes and sparse brick domains.

Both keep two population buffers and swap them each step. Units are lattice units throughout; zvcfd.units converts to physical ones.

SparseLBM is the production path: BGK or TRT collision, optional Carreau–Yasuda rheology, inlet/outlet patches (zvcfd.boundary), and partition-local domains with ghost bricks, which zvcfd.lbm.multi.MultiLBM composes across GPUs.

class zvcfd.lbm.solver.CarreauYasuda(nu_0, nu_inf, lam, a=2.0, n=0.3568)[source]

Bases: object

Carreau–Yasuda viscosity, lattice units: nu = nu_inf + (nu_0 - nu_inf) [1 + (lam * gamma_dot)^a]^((n - 1)/a).

Build it from SI parameters with from_si(). Blood (Cho & Kensey 1991): mu_0 = 0.056 Pa s, mu_inf = 0.00345 Pa s, lambda = 3.313 s, n = 0.3568, a = 2.

Parameters:
__init__(nu_0, nu_inf, lam, a=2.0, n=0.3568)
Parameters:
Return type:

None

a: float = 2.0
classmethod from_si(lattice, *, mu_0=0.056, mu_inf=0.00345, lam=3.313, a=2.0, n=0.3568)[source]
lam: float
n: float = 0.3568
nu_0: float
nu_inf: float
class zvcfd.lbm.solver.DenseLBM(flags, *, tau=1.0, force=(0.0, 0.0, 0.0), rho_in=1.0, rho_out=1.0, half=False, init=None)[source]

Bases: _LBM

Dense periodic box, flags (z, y, x); reservoir cells take rho_in for x < nx/2.

BGK only; kept for benchmarks and as the reference the sparse kernel is checked against.

Parameters:

flags (np.ndarray)

__init__(flags, *, tau=1.0, force=(0.0, 0.0, 0.0), rho_in=1.0, rho_out=1.0, half=False, init=None)[source]
Parameters:

flags (ndarray)

fields()[source]

Density and velocity for every stored cell, as flat device arrays.

Return type:

dict[str, cupy.ndarray]

step(k=1)[source]
Parameters:

k (int)

Return type:

None

class zvcfd.lbm.solver.SparseLBM(domain, *, tau=1.0, force=(0.0, 0.0, 0.0), rho_in=1.0, rho_out=1.0, half=False, init=None, collision='bgk', magic=0.1875, rheology=None, boundary=None)[source]

Bases: _LBM

Active 8³ bricks of a BrickDomain only.

One CUDA block per brick and one thread per voxel; a missing neighbour brick reads as solid. fields() returns (n_bricks, 512) arrays, the row layout of a Zarr Vectors brick store (zvcfd.io.fields).

Parameters:
  • domain (BrickDomain) – The domain, or a partition-local domain (owned bricks first, then ghosts); only owned bricks are updated.

  • tau – Relaxation time (zero-shear value with rheology).

  • collision (str) – "bgk" or "trt" (magic parameter magic, default 3/16, which puts half-way bounce-back walls exactly mid-link).

  • rheology (CarreauYasuda | None) – optional CarreauYasuda (lattice units).

  • boundary (BoundarySet | None) – optional BoundarySet in the domain’s cell numbering; its flags must already be applied.

  • magic (float)

__init__(domain, *, tau=1.0, force=(0.0, 0.0, 0.0), rho_in=1.0, rho_out=1.0, half=False, init=None, collision='bgk', magic=0.1875, rheology=None, boundary=None)[source]
Parameters:
apply_boundary()[source]

Write the patch cells of the newest buffer (after a step and its swap).

Return type:

None

Set the anti-bounce-back populations of the patch links in the newest buffer.

Runs just before a step: it rewrites only slots that the step’s bounce-back reads and nothing else does, so the step delivers the pressure condition, and the buffer after the step is clean.

Return type:

None

property device_bytes: int
fields()[source]

Density and velocity for every stored cell, as flat device arrays.

Return type:

dict[str, cupy.ndarray]

property fluid_cells: int
patch_flux()[source]

Lattice mass flux through each patch per step (positive into the domain).

Exact for the lattice: counts the populations crossing between patch cells and the fluid in the newest buffer.

Return type:

ndarray

patch_velocity()[source]

Per patch: summed velocity (z, y, x), summed density, and cell count, (P, 5).

Return type:

ndarray

set_patch(index, *, rho=None, u_zyx=None)[source]

Set a patch’s lattice density and/or velocity vector (z, y, x).

Parameters:
Return type:

None

step(k=1)[source]
Parameters:

k (int)

Return type:

None

step_main()[source]

Collide and stream the owned bricks, then swap buffers (no boundary pass).

Return type:

None

zvcfd.lbm.solver.dense_from_bricks(domain, values, fill=0.0)[source]

Scatter brick rows into a dense volume; see BrickDomain.to_dense().

Parameters:
Return type:

ndarray

zvcfd.lbm.solver.equilibrium(rho, ux, uy=None, uz=None)[source]

Equilibrium populations (Q, *rho.shape) (float32, host).

Parameters:
Return type:

ndarray

zvcfd.lbm.solver.kernel(name, half, *, trt=False, nonnewtonian=False, device=None)[source]

The compiled kernel name for the given storage precision and model options.

Parameters:
Return type:

cupy.RawKernel

Multi-GPU lattice-Boltzmann: one partition per device, ghost-brick exchange.

One process drives every device. Each partition is a SparseLBM over a partition-local domain (its owned bricks, then a one-brick ghost layer). A step is:

  1. every partition collides and streams its owned bricks (kernels on each device, launched without waiting, so devices run concurrently);

  2. ghost bricks are refreshed from their owners (device-to-device copies, peer-to-peer over NVLink where the devices allow it);

  3. every partition writes its patch cells (the boundary kernel reads interior neighbours, which may be ghosts). Patch links are set before step 1, from each link cell’s own populations;

  4. ghosts are refreshed again, so ghost copies of patch cells are current.

The arithmetic per cell is identical to a single-partition run, and the result is bit-identical to it (tests/test_multi.py). With more partitions than devices, partitions share devices round-robin; on a one-GPU machine that exercises the whole exchange path.

What is not optimised yet: exchanges copy whole ghost bricks, not only the populations that cross each face, and communication does not overlap the interior kernel. Both are milestone-1 follow-ups.

class zvcfd.lbm.multi.MultiLBM(domain, *, n_parts=None, chunk_bricks=32, devices=None, boundary=None, **solver_kw)[source]

Bases: object

A SparseLBM split across partitions and devices.

Parameters:
  • domain (BrickDomain) – The whole domain.

  • n_parts (int | None) – Number of partitions (default: number of devices).

  • chunk_bricks (int) – Ownership unit; partitions own whole chunks of chunk_bricks³ bricks, so they can write their store cells without locks.

  • devices (list[int] | None) – Device ids, used round-robin (default: every visible device).

  • boundary (BoundarySet | None) – Patch cells in the whole domain’s numbering.

  • **solver_kw – Passed to every SparseLBM.

__init__(domain, *, n_parts=None, chunk_bricks=32, devices=None, boundary=None, **solver_kw)[source]
Parameters:
exchange()[source]

Refresh every ghost brick from its owner’s newest buffer.

Return type:

None

fields()[source]

Owned-brick fields gathered to the host in the whole domain’s brick order.

Return type:

dict[str, ndarray]

property fluid_cells: int
property ghost_fraction: float
patch_flux()[source]
Return type:

ndarray

patch_velocity()[source]
Return type:

ndarray

set_patch(index, **kw)[source]
Parameters:

index (int)

Return type:

None

step(k=1)[source]
Parameters:

k (int)

Return type:

None

Lubrication (local-Poiseuille) pressure solve on a voxel mask.

div(k grad p) = 0 over the fluid voxels with k = 3/4 d^2, where d is the distance to the half-way wall; for a circular tube this gives the exact Poiseuille conductance (int k dA = pi R^4 / 8). Walls carry no flux; Dirichlet pressures are set on any voxel set (inlets, and any number of outlets, e.g. the 77 outlets of the HiP-CT coronary case).

Uses: a seconds-scale flow and pressure estimate on very large masks (the “tier 0” solver), boundary-pressure estimates for sub-volume LBM runs, and the elliptic kernel that multigrid is exercised on (docs/multiresolution.md).

It is the analogue of Fluent’s hybrid initialisation (a Laplace solve), but with a geometry-aware conductance. As an initial condition for LBM it did not shorten time to steady state in our tests; see the spike results.

class zvcfd.solvers.lubrication.LubricationResult(pressure: 'np.ndarray', velocity: 'np.ndarray', iterations: 'int', seconds: 'float', method: 'str')[source]

Bases: object

Parameters:
__init__(pressure, velocity, iterations, seconds, method)
Parameters:
Return type:

None

flux(axis, index, voxel=1.0)[source]

Volume flux through the plane index normal to axis (0 z, 1 y, 2 x).

Parameters:
Return type:

float

iterations: int
method: str
pressure: ndarray
seconds: float
velocity: ndarray
zvcfd.solvers.lubrication.conductance(fluid, voxel=1.0)[source]

k = 3/4 d^2 with d the distance (in voxel units) to the half-way wall.

Parameters:
Return type:

ndarray

zvcfd.solvers.lubrication.solve(fluid, fixed, value, *, voxel=1.0, mu=1.0, method='auto', tol=1e-08)[source]

Pressure and Darcy velocity u = -(k/mu) grad p on fluid.

Parameters:
  • fluid (ndarray) – Boolean fluid mask (z, y, x).

  • fixed (ndarray) – Boolean mask of Dirichlet voxels (subset of fluid).

  • value (ndarray) – Pressure on the fixed voxels (same shape; other entries ignored).

  • voxel (float) – Voxel edge (physical length unit); k and gradients use it.

  • mu (float) – Dynamic viscosity.

  • method (str) – "amg" (pyamg smoothed aggregation + CG, CPU), "cg" (Jacobi-preconditioned CG; on the GPU when cupy is present), or "auto" (amg if pyamg imports).

  • tol (float)

Return type:

LubricationResult

zvcfd.solvers.lubrication.system(fluid, fixed, value, k)[source]

Assemble the SPD system over free fluid voxels.

Returns (A, b, index) with index the unknown number of each voxel (-1 if not free).

Parameters:

Boundaries and geometry

Inlet and outlet patches: which voxels, what condition, and the lumped outlet models.

A patch is a set of boundary voxels sharing one condition. Its voxels are flagged 3 (pressure, including RCR outlets) or 4 (velocity) in the domain, and each gets an interior neighbour: the fluid voxel one lattice link inward that the boundary scheme extrapolates from (boundary_neem in zvcfd.lbm._cuda).

Patches are specified in physical SI units. The run converts them to lattice units with zvcfd.units.Lattice. Normals point out of the fluid, axis order (z, y, x).

Sources of patches:

class zvcfd.boundary.BoundarySet(patches, cells, nbr, patch, scale, link_cells=<factory>, link_mask=<factory>, link_patch=<factory>)[source]

Bases: object

Patch voxels and patch links of a domain, in the domain’s global cell numbering.

A global cell id is brick * B³ + local with local the voxel’s index in its brick (x fastest).

Two schemes carry a patch’s condition:

  • patch cells (cells): a layer of voxels flagged 3 or 4, written each step by non-equilibrium extrapolation from an interior neighbour. Velocity patches, and pressure patches on box faces.

  • patch links (link_cells, link_mask): lattice links from a fluid cell across a surface cap to a non-fluid node, each carrying an anti-bounce-back pressure condition. Pressure, RCR and coronary patches on surface caps (zvcfd.geometry.cap_links()). Bit q of a cell’s mask is set when the population arriving along c_q crosses the cap. The cells stay fluid.

A pressure-flagged patch that has links uses them, and its patch cells (kept, in case the patch becomes a velocity patch) are not flagged.

Parameters:
__init__(patches, cells, nbr, patch, scale, link_cells=<factory>, link_mask=<factory>, link_patch=<factory>)
Parameters:
Return type:

None

apply_flags(domain)[source]

Set flags 3/4 on the patch cells in use, and fluid on the others (in place).

Parameters:

domain (BrickDomain)

Return type:

None

cell_entries()[source]

Mask of the patch-cell entries in use (those of patches not on links).

Return type:

ndarray

cells: ndarray
counts()[source]

Cells carrying each patch’s condition (patch cells, or link cells).

Return type:

ndarray

Mask of the link entries in use.

Return type:

ndarray

localize(local)[source]

The patch voxels owned by a partition, renumbered to its local cells.

Neighbours may fall in the partition’s ghost bricks; they are kept.

Parameters:

local (BrickDomain)

Return type:

BoundarySet

nbr: ndarray
patch: ndarray
patches: list[Patch]
scale: ndarray

Per patch: True where the condition is carried by links (a pressure-flagged patch that has any).

Return type:

ndarray

class zvcfd.boundary.Patch(name, kind, pressure=0.0, velocity=0.0, flow_rate=None, normal=(0.0, 0.0, 0.0), area=None, profile='plug', rcr=None, waveform=None, centroid=None, coronary=None, pim=None, _model=None)[source]

Bases: object

One inlet or outlet, in SI units.

Variables:
  • name (str) – Patch name (e.g. the Fluent zone name).

  • kind (str) – "pressure", "velocity", "rcr" (a pressure patch whose pressure follows a three-element Windkessel) or "coronary" (an open-loop coronary outlet, Kim et al. 2010). Both lumped kinds come from zvcfd.lumped.

  • pressure (float) – Pa. Fixed pressure, or the venous pressure of a lumped outlet.

  • velocity (float) – m/s. Mean normal velocity into the domain (velocity kind).

  • flow_rate (float | None) – m³/s into the domain; overrides velocity when the area is known.

  • normal (tuple[float, float, float]) – outward unit normal (z, y, x).

  • area (float | None) – m². Physical patch area (from the mesh); estimated from voxels if None.

  • profile (str) – "plug" or "parabolic" (circular patch, peak 2× mean).

  • rcr (tuple[float, float, float] | None) – (Rp, C, Rd) in Pa·s/m³, m³/Pa, Pa·s/m³.

  • coronary (tuple[float, float, float, float, float] | None) – (Ra, Ca, Ram, Cim, Rv) in Pa·s/m³ and m³/Pa.

  • pim (float | list[tuple[float, float]] | None) – intramyocardial pressure for coronary: Pa, or [(t, Pa), ...] (periodic, period = last t).

  • waveform (list[tuple[float, float]] | None) – [(t, factor), ...] periodic multiplier on velocity/flow rate or pressure; linear interpolation, period = last t.

Parameters:
__init__(name, kind, pressure=0.0, velocity=0.0, flow_rate=None, normal=(0.0, 0.0, 0.0), area=None, profile='plug', rcr=None, waveform=None, centroid=None, coronary=None, pim=None, _model=None)
Parameters:
Return type:

None

area: float | None = None
centroid: tuple[float, float, float] | None = None
coronary: tuple[float, float, float, float, float] | None = None
factor(t)[source]
Parameters:

t (float)

Return type:

float

property flag: int
flow_rate: float | None = None
kind: str
property lumped: bool
mean_velocity(t=0.0)[source]

Mean inflow velocity (m/s) at time t.

Parameters:

t (float)

Return type:

float

name: str
normal: tuple[float, float, float] = (0.0, 0.0, 0.0)
outlet_model()[source]

The patch’s 0-D outlet model (zvcfd.lumped), at rest at first use.

Return type:

LumpedOutlet

outlet_pressure(q_out, t, dt)[source]

Commit the outlet model’s step ending at t with outflow q_out (m³/s); return the patch pressure (Pa) to hold until the next step.

Parameters:
Return type:

float

pim: float | list[tuple[float, float]] | None = None
pressure: float = 0.0
profile: str = 'plug'
rcr: tuple[float, float, float] | None = None
rcr_pressure(q_out, dt)[source]

Advance the outlet model by dt with outflow q_out (m³/s); return P (Pa).

Parameters:
Return type:

float

velocity: float = 0.0
waveform: list[tuple[float, float]] | None = None
zvcfd.boundary.cell_coords(domain, cells)[source]

Voxel coordinates (z, y, x) of global cell ids.

Parameters:
Return type:

ndarray

zvcfd.boundary.cell_flags(domain, cells)[source]
Parameters:
Return type:

ndarray

zvcfd.boundary.cell_ids(domain, zyx)[source]

Global cell ids of voxel coordinates (N, 3); -1 outside active bricks or the box.

Parameters:
Return type:

ndarray

zvcfd.boundary.face_patches(domain, faces)[source]

Patches on faces of the bounding box: {"xmin": Patch(...), "xmax": Patch(...)}.

The fluid voxels of the face layer become patch voxels; normals and areas are filled in from the face (area in voxel faces × voxel_area is left to the caller via Patch.area; None means “count voxels”).

Parameters:
Return type:

BoundarySet

zvcfd.boundary.from_cells(domain, groups, links=None)[source]

Build a boundary set from explicit (patch, global cell ids) groups.

links, if given, holds per group None or (cells, mask): the group’s patch links (zvcfd.geometry.cap_links()), used when the patch is a pressure-flagged one.

Parameters:
Return type:

BoundarySet

zvcfd.boundary.inward_neighbours(domain, cells, normal_out)[source]

For each cell, the fluid neighbour along the lattice link closest to the inward normal.

Parameters:
Return type:

ndarray

zvcfd.boundary.profile_scale(domain, cells, patch)[source]
Parameters:
Return type:

ndarray

Closed surface meshes to sparse brick domains, with inlet/outlet patches.

voxelize_mesh turns a watertight triangulated surface (the boundary of an Ansys Fluent mesh from zvcfd.io.fluent_msh, or any triangle soup with zone ids) into a BrickDomain and a BoundarySet whose patches are the mesh’s inlet and outlet zones.

Method: parity ray casting along z. Every voxel column (y, x) casts one ray through the voxel centres; triangles are binned by the columns their footprint covers, each (triangle, column) pair gives at most one crossing, and voxels between the 1st-2nd, 3rd-4th, … crossings are fluid. No dense volume is ever allocated: fluid voxels go straight to bricks. Ray origins are offset by a tiny irrational fraction of a voxel so they never hit an edge or vertex exactly. Columns with an odd number of crossings (a leaky surface) are dropped and counted.

Patches: each non-wall zone’s triangles are sampled densely; the fluid voxel half a voxel inside each sample becomes a patch voxel, with the zone’s area, outward normal and centroid. Each zone also gets its patch links (cap_links()): the lattice links from fluid voxels across the cap. Pressure-type patches use the links (an anti-bounce-back condition at the cap); velocity patches use the patch voxels.

class zvcfd.geometry.VoxelGrid(origin, voxel, shape)[source]

Bases: object

Where the voxels are: origin (z, y, x) of voxel (0, 0, 0)’s corner, edge, shape.

Parameters:
__init__(origin, voxel, shape)
Parameters:
Return type:

None

classmethod around(points_zyx, voxel, *, pad=2, brick=8)[source]
Parameters:
origin: ndarray
shape: tuple[int, int, int]
to_voxel(p_zyx)[source]

Continuous voxel coordinates (voxel centres at integers).

Parameters:

p_zyx (ndarray)

Return type:

ndarray

voxel: float

The lattice links that cross a cap: (fluid cell ids, uint32 link masks).

tri is the cap’s triangles, (T, 3, 3) in (z, y, x) mesh units. A link runs from a fluid voxel centre along -c_q to a non-fluid voxel (or none); it belongs to the cap when that segment crosses the cap’s triangles. Bit q of a cell’s mask is set for each such link: the population arriving along c_q then comes from across the cap, and the solver applies the patch’s anti-bounce-back pressure condition to it. Links from voxels deeper than the first layer (diagonals that cross a staircase patch layer) are found the same way.

Parameters:
Return type:

tuple[ndarray, ndarray]

zvcfd.geometry.domain_from_voxels(zyx, shape, *, brick=8)[source]

A BrickDomain whose fluid voxels are exactly zyx.

Parameters:
Return type:

BrickDomain

zvcfd.geometry.patch_cells(domain, grid, tri)[source]

Fluid voxels just inside a cap (inlet/outlet) and the cap’s geometry (voxel units).

Parameters:
Return type:

tuple[ndarray, dict]

zvcfd.geometry.voxelize_fluent(path, voxel, *, unit_scale=0.001, pad=2)[source]

Voxelise an ASCII Fluent mesh’s boundary; see voxelize_mesh().

Parameters:
zvcfd.geometry.voxelize_mesh(tri_xyz, zone_of_tri, zone_kinds, voxel, *, zone_names=None, unit_scale=1.0, pad=2)[source]

Voxelise a zoned closed surface: returns (domain, boundary, grid, report).

Parameters:
  • tri_xyz (ndarray) – (T, 3, 3) triangles, coordinates (x, y, z) in mesh units.

  • zone_of_tri (ndarray) – zone id per triangle.

  • zone_kinds (dict[int, str]) – zone id -> Fluent kind (wall, velocity-inlet, pressure-outlet, …). Non-wall zones become patches: inlets as velocity patches, outlets as pressure patches (values are set later, per run).

  • voxel (float) – voxel edge in mesh units.

  • unit_scale (float) – metres per mesh unit (1e-3 for millimetres); patch areas are returned in m².

  • zone_names (dict[int, str] | None)

  • pad (int)

zvcfd.geometry.voxelize_surface(tri, grid)[source]

Fluid voxel coordinates (N, 3) (z, y, x) inside a closed surface (T, 3, 3) (zyx).

Parameters:
Return type:

tuple[ndarray, dict]

Brick stores

Brick fields in Zarr Vectors stores.

A brick store is an ordinary Zarr Vectors store (custom geometry type zvcfd:bricks, spec section 12.5) in which one vertex is one 8^3 brick:

  • vertices: the brick centre, in physical units, axes (z, y, x);

  • vertex_attributes/<field>: that brick’s voxel values, ncols = 512 (512 * C for a C-component field), x fastest within the brick;

  • vertex_attributes/flags (domain store only): uint8 voxel flags.

A store cell is a chunk of chunk_bricks^3 bricks, and is the unit a GPU worker owns (zvcfd.domain.BrickDomain.partition()). Writing follows the zarr-vectors three-phase contract (docs/io.md):

  1. coordinator: create_brick_store() (allocates arrays, defers presence);

  2. workers: write_brick_chunk() for the chunks they own, no locks;

  3. coordinator: finalize_brick_store() (one presence rebuild).

Solid-only bricks are never stored, so a store’s size follows the fluid volume. Every call goes through zarr_vectors.building, the supported surface for tools that build stores.

zvcfd.io.fields.brick_centres(domain, bricks, voxel_size)[source]
Parameters:
Return type:

ndarray

zvcfd.io.fields.create_brick_store(path, domain, *, voxel_size, fields=('rho', 'ux', 'uy', 'uz'), chunk_bricks=32, unit='micrometer', shard_shape=None, compressor=None, flags=False, backend=None)[source]

Coordinator: create the store and allocate every array, once.

Parameters:
  • path (Any) – Store path or URL.

  • domain (BrickDomain) – The brick domain (only its shape and brick size are used here).

  • voxel_size (float) – Voxel edge in unit.

  • fields (Mapping[str, str] | Sequence[str]) – Field names, or {name: dtype}; dtype defaults to float32.

  • chunk_bricks (int) – Bricks per chunk edge; a chunk is one store cell.

  • shard_shape (int | Sequence[int] | None) – Cells per shard (declared on the store so every array inherits it). With shards, a worker must own whole shards.

  • flags (bool) – Also allocate the flags attribute (the domain store).

  • unit (str)

  • compressor (Any)

  • backend (str | None)

Returns:

The level-0 group, presence deferred.

zvcfd.io.fields.finalize_brick_store(level)[source]

Coordinator, after every worker: rebuild presence once and record what exists.

Return type:

None

zvcfd.io.fields.open_brick_level(path, mode='r', *, backend=None)[source]
Parameters:
zvcfd.io.fields.read_brick_chunks(level, chunk_coords, fields, *, device=None, decode='auto')[source]

Read chunks’ brick centres and field rows in one batched read.

Returns the zarr-vectors CellBatch: batch["vertex_attributes/<f>"].data is (rows, 512) with CSR offsets over batch.chunk_coords; device="cuda" decodes on the GPU where the store allows it.

Parameters:
zvcfd.io.fields.read_domain(path, *, periodic=False)[source]

Rebuild the BrickDomain from a domain store (one with flags).

Parameters:
Return type:

BrickDomain

zvcfd.io.fields.read_snapshot(path, domain, fields=None, *, device=None, decode='auto')[source]

Every brick of a snapshot store, as {field: (n_bricks, 512)} in domain order.

With device="cuda" the arrays are cupy, decoded on the GPU where the store’s codec allows it.

Parameters:
Return type:

dict[str, Any]

zvcfd.io.fields.store_geometry(domain, voxel_size, chunk_bricks)[source]

(bounds, chunk_shape) in physical units for a domain.

Parameters:
zvcfd.io.fields.store_metadata(path)[source]

The zvcfd user-metadata namespace of a brick store.

Parameters:

path (Any)

Return type:

dict

zvcfd.io.fields.write_brick_chunk(level, domain, bricks, fields, *, voxel_size, chunk_bricks)[source]

Worker: write one chunk’s bricks and their field rows.

bricks are brick indices that all lie in one chunk; each value in fields is (len(bricks), 512) (numpy, or a device array, which zarr-vectors copies off once). Presence is not stamped; the coordinator’s finalize_brick_store() does that once.

Returns the chunk coordinate written.

Parameters:
Return type:

tuple[int, …]

zvcfd.io.fields.write_brick_chunks(level, domain, fields, *, voxel_size, chunk_bricks, bricks=None)[source]

Worker: write every chunk touched by bricks in one write session.

fields values are (len(bricks), 512) rows aligned with bricks (default: every brick of the domain, in domain order), so a worker only ever holds its own share. bricks must cover whole chunks: a chunk written by two workers keeps whichever landed last. Returns the number of chunks written.

Parameters:
Return type:

int

Inputs

Reading OME-Zarr inputs with zarr-python v3 directly (no ome-zarr-py), as BRIDGE does.

Accepts the flat multiscales block of NGFF 0.4 and the nested ome block of 0.5/0.6, and always resolves datasets[level].path rather than assuming the array is called "0". Voxel size comes from the dataset’s scale transform, reordered to (z, y, x).

class zvcfd.io.omezarr.Multiscale(group: 'object', datasets: 'list[dict]', axes: 'list[dict]', version: 'str')[source]

Bases: object

Parameters:
__init__(group, datasets, axes, version)
Parameters:
Return type:

None

axes: list[dict]
datasets: list[dict]
group: object
level_path(level)[source]
Parameters:

level (int)

Return type:

str

nearest_level(voxel_size)[source]

Level whose largest spatial voxel edge is closest to voxel_size.

Parameters:

voxel_size (float)

Return type:

int

unit()[source]
Return type:

str | None

version: str
voxel_size(level)[source]

Spatial scale of level as (z, y, x) in the axes’ units.

Parameters:

level (int)

Return type:

tuple[float, …]

zvcfd.io.omezarr.fluid_mask(volume, *, threshold=None, label=None)[source]

Fluid voxels of a segmentation or intensity volume.

Parameters:
Return type:

ndarray

zvcfd.io.omezarr.open_multiscale(path)[source]
Parameters:

path (str)

Return type:

Multiscale

zvcfd.io.omezarr.read_level(path, level=0, *, region=None)[source]

Read level (optionally a [[z0, z1], [y0, y1], [x0, x1]] crop) as (z, y, x).

Non-spatial axes (t, c) must have extent 1; they are squeezed out.

Parameters:
Return type:

tuple[ndarray, Multiscale]

Streaming reader for ASCII Fluent meshes (.msh), boundary-first.

Ansys users hand over meshes in this format (e.g. Simpleware ScanIP+FE exports of HiP-CT vessel lumens). zvCFD does not solve on unstructured cells; it needs the boundary: the wall surface to voxelise, and the inlet and outlet patches to place boundary conditions. This reader therefore parses node coordinates and every non-interior face zone, and skips the interior faces (the bulk of the file) at C speed via mmap.

Sections understood: (10 ...) nodes, (12 ...) cells (counts only), (13 ...) faces, (45 ...)/(39 ...) zone definitions. Binary sections ((2010 ...), (2013 ...)) are not supported.

class zvcfd.io.fluent_msh.FaceZone(zone: 'int', kind: 'str', name: 'str' = '', faces: 'list[np.ndarray]' = <factory>)[source]

Bases: object

Parameters:
__init__(zone, kind, name='', faces=<factory>)
Parameters:
Return type:

None

faces: list[ndarray]
kind: str
property n_faces: int
name: str = ''
zone: int
class zvcfd.io.fluent_msh.FluentBoundary(nodes, zones, n_cells, n_faces, n_interior_faces, source='')[source]

Bases: object

Nodes and boundary face zones of a Fluent mesh.

Parameters:
__init__(nodes, zones, n_cells, n_faces, n_interior_faces, source='')
Parameters:
Return type:

None

n_cells: int
n_faces: int
n_interior_faces: int
nodes: ndarray
source: str = ''
summary()[source]

Counts, bounding box, enclosed volume, and per-zone patch areas.

Return type:

dict

triangles(zones=None)[source]

Fan-triangulate boundary polygons: (tris (T, 3), zone_of_tri (T,)).

Return type:

tuple[ndarray, ndarray]

zone_faces(zone)[source]
Parameters:

zone (int)

Return type:

list[ndarray]

zones: dict[int, FaceZone]
zvcfd.io.fluent_msh.read_fluent_boundary(path)[source]

Read nodes and non-interior face zones of an ASCII Fluent mesh.

Parameters:

path (str)

Return type:

FluentBoundary

zvcfd.io.fluent_msh.voxel_estimate(summary, voxel_size)[source]

Fluid and bounding-box voxel counts at voxel_size (mesh length units).

Parameters:
Return type:

dict

Run collections

A run as an OME-NGFF RFC-8 collection.

A run directory <name>.zvcfd/ is a Zarr v3 group whose attributes.ome is an RFC-8 collection document. Its nodes point at everything the run reads and writes, by relative path:

  • image: the input OME-Zarr (multiscale), referenced where it lives and never copied;

  • mask: the segmentation the domain was built from (multiscale, with labels.source pointing at image), when it is not the image;

  • domain: the brick store holding voxel flags (zvcfd:domain);

  • fields: a collection of snapshot brick stores, one per saved step (zvcfd:fields);

  • boundary: surfaces, patches and centrelines as Zarr Vectors stores (zvcfd:boundary), e.g. imported from an Ansys .msh;

  • config: the resolved run configuration (json).

Conventions shared with BRIDGE (COLLECTION_LAYOUT_PLAN.md): version "0.6" with type: "collection"; one namespace for node ids and coordinate-system ids; paths relative to the document with ./ inside the container; extensions prefixed zvcfd:; one writer per document (the coordinator), and every write an atomic replace. Publishing a snapshot is adding its node in one such replace, which is what makes a snapshot visible atomically without a transactional store (docs/spec/ snapshots.md). RFC-8 is still a draft (“0.x” in its examples); the version string follows BRIDGE and will move with it.

zvcfd.collection.add_domain(doc, run_dir, store_path, *, summary=None)[source]
Parameters:
Return type:

dict

zvcfd.collection.add_image(doc, run_dir, image_path, *, name='image')[source]
Parameters:
Return type:

dict

zvcfd.collection.add_node(doc, n)[source]

Add or replace (by id) a top-level node. Ids share one namespace with coordinate systems.

Parameters:
Return type:

dict

zvcfd.collection.add_snapshot(doc, run_dir, store_path, *, step, time_s=None, fields=None)[source]

Publish one snapshot under the fields collection node.

Parameters:
Return type:

dict

zvcfd.collection.atomic_write_json(path, obj)[source]

Write-then-rename in the same directory, so readers see old or new, never half.

Parameters:
Return type:

Path

zvcfd.collection.check(doc)[source]

Structural problems (empty when fine): unique ids, nodes xor path, known version.

Parameters:

doc (dict)

Return type:

list[str]

zvcfd.collection.new_id(kind='run')[source]
Parameters:

kind (str)

Return type:

str

zvcfd.collection.node(kind, name, path, *, path_type='zarr', node_id=None, attributes=None)[source]
Parameters:
  • kind (str)

  • name (str)

  • path (str)

  • path_type (str)

  • node_id (str | None)

  • attributes (dict | None)

Return type:

dict

zvcfd.collection.physical_system(unit='micrometer')[source]
Parameters:

unit (str)

Return type:

dict

zvcfd.collection.read(run_dir)[source]
Parameters:

run_dir (str | PathLike)

Return type:

dict

zvcfd.collection.rel(target, doc_dir)[source]

Relative path from the document’s directory, ./-prefixed inside it.

Parameters:
Return type:

str

zvcfd.collection.run_document(run_dir, *, name, unit='micrometer', attributes=None, run_id=None)[source]

A new, empty run collection document.

Parameters:
Return type:

dict

zvcfd.collection.snapshots(doc)[source]
Parameters:

doc (dict)

Return type:

list[dict]

zvcfd.collection.write(run_dir, doc)[source]

Atomically replace the run group’s zarr.json with doc as attributes.ome.

Parameters:
Return type:

Path

Configuration and runs

Run configuration: one YAML or JSON file per run, validated strictly.

Unknown keys are errors (a typo must not silently fall back to a default). The resolved configuration is written into the run collection (config node), and its hash names the run, as in BRIDGE-Simulation.

solver.method defaults to auto: the finite-volume solver (the main one, CFX-style, on the mesh itself) for mesh sources, and the lattice-Boltzmann solver for voxel sources and for meshes given a source.voxel_size (resolve_method()). The resolved method is what is stored and hashed.

Example (the HiP-CT coronary tree on its Ansys Fluent mesh, finite volume; settings in fv):

name: coronary-fv
source: {kind: mesh, path: "mesh 1.msh", unit: mm}
physics: {nu: 3.5e-6, rho: 1060.0}
boundaries:
  patches:
    - {match: inlet, kind: velocity, flow_rate: 1.9e-7, profile: parabolic}
    - {match: outlet, kind: rcr, rcr: [1.0e9, 1.0e-10, 1.0e10]}
fv: {linear: amgx, iterations: 300, tolerance: 1.0e-6}

The same mesh voxelised for the lattice-Boltzmann solver (a voxel size selects it; solver.method: lbm says so explicitly):

name: coronary-50um
source: {kind: mesh, path: "mesh 1.msh", unit: mm, voxel_size: 50.0}
physics: {nu: 3.5e-6, rho: 1060.0, u_ref: 0.2}
boundaries:
  patches:
    - {match: inlet, kind: velocity, flow_rate: 1.9e-7, profile: parabolic}
    - {match: outlet, kind: pressure, pressure: 0.0}
solver: {method: lbm, collision: trt, mach: 0.05, steps: 200000, check_every: 2000,
         tolerance: 1.0e-4}
output: {path: runs, every: 0}
class zvcfd.config.Boundaries(faces: 'dict' = <factory>, patches: 'list' = <factory>)[source]

Bases: object

Parameters:
__init__(faces=<factory>, patches=<factory>)
Parameters:
Return type:

None

faces: dict
patches: list
class zvcfd.config.Domain(brick: 'int' = 8, chunk_bricks: 'int' = 32, periodic: 'bool' = False)[source]

Bases: object

Parameters:
__init__(brick=8, chunk_bricks=32, periodic=False)
Parameters:
Return type:

None

brick: int = 8
chunk_bricks: int = 32
periodic: bool = False
class zvcfd.config.Fv(linear='auto', linear_rtol=0.1, precision='double', advection='high-resolution', false_dt=None, iterations=300, tolerance=1e-06, residual_target=None, backflow_stabilisation=0.2, dt=None, steps=None, periods=None, period=None, loops=5, loop_tolerance=1e-05, scheme='bdf2', steady_start=True, wss=True, tawss_from=None, chunk=None, turbulence=None)[source]

Bases: object

Finite-volume settings (solver.method: fv).

Parameters:
__init__(linear='auto', linear_rtol=0.1, precision='double', advection='high-resolution', false_dt=None, iterations=300, tolerance=1e-06, residual_target=None, backflow_stabilisation=0.2, dt=None, steps=None, periods=None, period=None, loops=5, loop_tolerance=1e-05, scheme='bdf2', steady_start=True, wss=True, tawss_from=None, chunk=None, turbulence=None)
Parameters:
Return type:

None

advection: Any = 'high-resolution'
backflow_stabilisation: float = 0.2
chunk: float | None = None
dt: float | None = None
false_dt: float | None = None
iterations: int = 300
linear: str = 'auto'
linear_rtol: float = 0.1
loop_tolerance: float = 1e-05
loops: int = 5
period: float | None = None
periods: float | None = None
precision: str = 'double'
residual_target: float | None = None
scheme: str = 'bdf2'
steady_start: bool = True
steps: int | None = None
tawss_from: float | None = None
tolerance: float = 1e-06
turbulence: dict | None = None
wss: bool = True
class zvcfd.config.Output(path: 'str' = 'runs', every: 'int' = 0, fields: 'list[str]' = <factory>, dtype: 'str' = 'float32', compressor: 'str | None' = 'zstd', shard_shape: 'int | None' = None)[source]

Bases: object

Parameters:
__init__(path='runs', every=0, fields=<factory>, dtype='float32', compressor='zstd', shard_shape=None)
Parameters:
Return type:

None

compressor: str | None = 'zstd'
dtype: str = 'float32'
every: int = 0
fields: list[str]
path: str = 'runs'
shard_shape: int | None = None
class zvcfd.config.Parallel(gpus: 'int' = 1, partitions: 'int | None' = None)[source]

Bases: object

Parameters:
  • gpus (int)

  • partitions (int | None)

__init__(gpus=1, partitions=None)
Parameters:
  • gpus (int)

  • partitions (int | None)

Return type:

None

gpus: int = 1
partitions: int | None = None
class zvcfd.config.Physics(nu: 'float' = 3.5e-06, rho: 'float' = 1060.0, u_ref: 'float | None' = None, pressure_drop: 'float | None' = None, body_force: 'list[float] | None' = None, rheology: 'dict | None' = None)[source]

Bases: object

Parameters:
__init__(nu=3.5e-06, rho=1060.0, u_ref=None, pressure_drop=None, body_force=None, rheology=None)
Parameters:
Return type:

None

body_force: list[float] | None = None
nu: float = 3.5e-06
pressure_drop: float | None = None
rheology: dict | None = None
rho: float = 1060.0
u_ref: float | None = None
class zvcfd.config.RunConfig(name: 'str' = 'run', source: 'Source' = <factory>, physics: 'Physics' = <factory>, boundaries: 'Boundaries' = <factory>, solver: 'Solver' = <factory>, domain: 'Domain' = <factory>, parallel: 'Parallel' = <factory>, output: 'Output' = <factory>, fv: 'Fv' = <factory>)[source]

Bases: object

Parameters:
__init__(name='run', source=<factory>, physics=<factory>, boundaries=<factory>, solver=<factory>, domain=<factory>, parallel=<factory>, output=<factory>, fv=<factory>)
Parameters:
Return type:

None

as_dict()[source]
Return type:

dict

boundaries: Boundaries
domain: Domain
fv: Fv
property hash: str
name: str = 'run'
output: Output
parallel: Parallel
physics: Physics
solver: Solver
source: Source
class zvcfd.config.Solver(method: 'str' = 'auto', collision: 'str' = 'trt', precision: 'str' = 'fp32', tau: 'float | None' = None, mach: 'float' = 0.05, steps: 'int' = 10000, check_every: 'int' = 500, tolerance: 'float' = 1e-05, mass_tolerance: 'float' = 0.001, flow_control: 'bool' = True)[source]

Bases: object

Parameters:
__init__(method='auto', collision='trt', precision='fp32', tau=None, mach=0.05, steps=10000, check_every=500, tolerance=1e-05, mass_tolerance=0.001, flow_control=True)
Parameters:
Return type:

None

check_every: int = 500
collision: str = 'trt'
flow_control: bool = True
mach: float = 0.05
mass_tolerance: float = 0.001
method: str = 'auto'
precision: str = 'fp32'
steps: int = 10000
tau: float | None = None
tolerance: float = 1e-05
class zvcfd.config.Source(kind: 'str' = 'phantom', name: 'str | None' = None, path: 'str | None' = None, level: 'int' = 0, array: 'str | None' = None, threshold: 'float | None' = None, label: 'int | None' = None, voxel_size: 'float | None' = None, unit: 'str' = 'mm', region: 'list[list[int]] | None' = None)[source]

Bases: object

Parameters:
__init__(kind='phantom', name=None, path=None, level=0, array=None, threshold=None, label=None, voxel_size=None, unit='mm', region=None)
Parameters:
Return type:

None

array: str | None = None
kind: str = 'phantom'
label: int | None = None
level: int = 0
name: str | None = None
path: str | None = None
region: list[list[int]] | None = None
threshold: float | None = None
unit: str = 'mm'
voxel_size: float | None = None
zvcfd.config.from_dict(d)[source]
Parameters:

d (dict[str, Any])

Return type:

RunConfig

zvcfd.config.load(path)[source]
Parameters:

path (str | Path)

Return type:

RunConfig

zvcfd.config.resolve_method(cfg)[source]

The solver solver.method: auto stands for.

The finite-volume solver is the main one: it takes every mesh source. The lattice-Boltzmann solver takes voxel sources (OME-Zarr images, arrays, phantoms), and meshes given a source.voxel_size, which asks for a voxelised run.

Parameters:

cfg (RunConfig)

Return type:

str

Run a configuration end to end: geometry -> domain + patches -> solve -> stores -> collection.

One GPU, or several through zvcfd.lbm.MultiLBM (parallel.gpus, parallel.partitions). Every check interval the patch controller sets patch values (pressures, flow-rate-controlled inlet velocities, Windkessel outlet pressures), measures the exact lattice flux through every patch, and tests convergence; monitors.json records the history and patches.csv the final flows and pressures.

class zvcfd.run.PatchController(sim, boundary, lat, *, flow_control=True)[source]

Bases: object

Sets patch values each check interval and measures patch flows.

Parameters:
__init__(sim, boundary, lat, *, flow_control=True)[source]
Parameters:
flows()[source]

Volume flow into the domain through each patch, m^3/s.

Return type:

ndarray

pressures()[source]

Mean pressure over each patch’s cells, Pa (relative to the reference density).

Return type:

ndarray

update(t, dt_check, q)[source]
Parameters:
Return type:

None

zvcfd.run.build_geometry(cfg, log=<built-in function print>, *, out=None)[source]

(domain, boundary, voxel_um, image, report) for a configuration.

Parameters:
zvcfd.run.lattice_for(cfg, voxel_um, log=<built-in function print>)[source]

The lattice: solver.tau if given, else dt from solver.mach at physics.u_ref.

Parameters:
Return type:

Lattice

zvcfd.run.load_patch_table(path)[source]
Return type:

list[dict]

zvcfd.run.make_solver(cfg, domain, boundary, lat)[source]
Parameters:
zvcfd.run.run(cfg, *, out=None, steps=None, log=<built-in function print>)[source]
Parameters:
Return type:

Path

Performance model and units

Roofline performance and memory model behind zvcfd plan and docs/performance.md.

LBM is memory-bound: one fluid-cell update reads and writes every population once, so

updates/s per GPU = achievable bandwidth x kernel efficiency / bytes per update

Achievable bandwidth is a device-to-device copy (STREAM-like), not the datasheet peak. Kernel efficiency is the fraction of that a kernel reaches per fluid cell. It was measured for the zvCFD kernels on an RTX A2000 (benchmarks/bench_lbm.py) and is assumed to carry over to an H100. This is the main uncertainty. efficiency="target" uses published numbers for tuned kernels instead (FluidX3D, waLBerla); "planning" (the default) takes the lower of the two, so a plan never counts on a kernel that does not exist yet nor on the A2000’s unusually high copy efficiency.

Memory: two population buffers plus flags per stored cell. Stored cells are the fluid cells divided by the brick fill (the fraction of an active brick’s voxels that are fluid).

class zvcfd.perfmodel.Estimate(gpu: 'str', gpus: 'int', method: 'str', layout: 'str', geometry: 'str', fluid_cells: 'float', stored_cells: 'float', memory_per_gpu_gb: 'float', fits: 'bool', updates_per_s: 'float', seconds_per_step: 'float', steps: 'int | None', seconds: 'float | None')[source]

Bases: object

Parameters:
__init__(gpu, gpus, method, layout, geometry, fluid_cells, stored_cells, memory_per_gpu_gb, fits, updates_per_s, seconds_per_step, steps, seconds)
Parameters:
Return type:

None

as_dict()[source]
Return type:

dict

fits: bool
fluid_cells: float
geometry: str
gpu: str
gpus: int
layout: str
memory_per_gpu_gb: float
method: str
seconds: float | None
seconds_per_step: float
steps: int | None
stored_cells: float
updates_per_s: float
class zvcfd.perfmodel.GPU(name: 'str', memory_gb: 'float', peak_tbs: 'float', copy_fraction: 'float', peer_gbs: 'float', host_gbs: 'float')[source]

Bases: object

Parameters:
__init__(name, memory_gb, peak_tbs, copy_fraction, peer_gbs, host_gbs)
Parameters:
Return type:

None

copy_fraction: float
property copy_gbs: float
host_gbs: float
memory_gb: float
name: str
peak_tbs: float
peer_gbs: float
class zvcfd.perfmodel.Method(name: 'str', bytes_per_update: 'float', bytes_per_cell: 'float', efficiency: 'dict')[source]

Bases: object

Parameters:
__init__(name, bytes_per_update, bytes_per_cell, efficiency)
Parameters:
Return type:

None

bytes_per_cell: float
bytes_per_update: float
efficiency: dict
name: str
zvcfd.perfmodel.cpu_fv_estimate(cells, iterations, *, cores=128, cell_iters_per_core_s=120000.0)[source]

Wall seconds for an unstructured FV (SIMPLE-type) solve on CPU cores.

Default throughput ~0.1-0.13 M cell-iterations/s/core, the level both Fluent (CADFEM, DrivAer) and OpenFOAM (OHC-1 benchmark) report.

Parameters:
Return type:

float

zvcfd.perfmodel.estimate(fluid_cells, *, fill=0.6, box_cells=None, gpus=8, gpu='H100-SXM', method='lbm-fp32', layout='sparse', geometry='vessel', steps=None, efficiency='planning', parallel_efficiency=None)[source]

Memory and time for steps updates of fluid_cells on gpus x gpu.

Parameters:
  • fluid_cells (float) – Non-solid voxels.

  • fill (float) – Brick fill (fluid / stored cells), sparse layout only.

  • box_cells (float | None) – Bounding-box voxels; required for layout="dense".

  • geometry (str) – open | porous | vessel (kernel-efficiency class).

  • parallel_efficiency (float | None) – Multi-GPU efficiency; default 1.0 for one GPU, 0.85 for peer-connected GPUs (waLBerla measures >= 82% weak scaling), 0.6 when halos go through the host.

  • gpus (int)

  • gpu (str)

  • method (str)

  • layout (str)

  • steps (int | None)

  • efficiency (str)

Return type:

Estimate

zvcfd.perfmodel.fv_memory_gb(cells, gb_per_million=1.8)[source]

Fluent GPU memory: 1.0-5.6 GB per million cells (SP segregated tet .. DP coupled poly).

Parameters:
Return type:

float

zvcfd.perfmodel.gpu_fv_estimate(cells, iterations, *, gpus=1, cell_iters_per_gpu_s=200000000.0)[source]

Wall seconds for a GPU-native unstructured FV solve (Fluent GPU class).

Default ~200 M cell-iterations/s per H100, between the vendor-reported ~150 (A100) and ~300 (H200) figures; independent OpenFOAM GPU ports are ~15-60 M/s per A100.

Parameters:
Return type:

float

Lattice <-> physical unit conversion, and diffusive scaling between pyramid levels.

A lattice is fixed by the voxel size dx (m), the physical kinematic viscosity nu (m^2/s) and the relaxation time tau; the time step follows from nu = (tau - 1/2)/3 * dx^2/dt.

Coarsening by 2 at fixed tau (diffusive scaling) gives dt -> 4 dt: lattice velocity doubles, lattice pressure (density) differences quadruple, and a lattice body force grows eightfold. These are the factors used to restrict boundary conditions and prolong solutions between OME-Zarr pyramid levels (docs/multiresolution.md).

class zvcfd.units.Lattice(dx: 'float', nu: 'float', tau: 'float' = 1.0, rho: 'float' = 1060.0)[source]

Bases: object

Parameters:
__init__(dx, nu, tau=1.0, rho=1060.0)
Parameters:
Return type:

None

coarsened(factor=2)[source]
Parameters:

factor (int)

Return type:

Lattice

drho_lattice(dp)[source]
Parameters:

dp (float)

Return type:

float

property dt: float
dx: float
mach(u)[source]
Parameters:

u (float)

Return type:

float

nu: float
property nu_lattice: float
pressure(drho_lattice)[source]

Physical pressure difference (Pa) of a lattice density difference.

Parameters:

drho_lattice (float)

Return type:

float

rho: float = 1060.0
steps(seconds)[source]
Parameters:

seconds (float)

Return type:

int

tau: float = 1.0
u_lattice(u)[source]
Parameters:

u (float)

Return type:

float

velocity(u_lattice)[source]
Parameters:

u_lattice (float)

Return type:

float

zvcfd.units.level_factors(k)[source]

Lattice-unit multipliers from level 0 to level k (2^k coarser) at fixed tau.

Parameters:

k (int)

Return type:

dict[str, float]

Phantoms

Synthetic geometries for tests and benchmarks.

Flag volumes use 0 fluid / 1 solid, axis order (z, y, x).

zvcfd.phantoms.PHANTOMS = {'network-128x128x512': <function <lambda>>, 'porous-256': <function <lambda>>, 'vessels-512': <function <lambda>>}

Named phantoms (flag volumes) used by the benchmarks; zvcfd phantom list.

zvcfd.phantoms.coarsen_mask(fluid, rule='majority')[source]

2x downsample of a fluid mask: majority (>= 4 of 8) or any (max-pool).

Parameters:
Return type:

ndarray

zvcfd.phantoms.porous_spheres(n, porosity_target=0.45, radius=6, seed=0)[source]

Periodic overlapping-sphere solid; flag 1 = solid.

Parameters:

n (int)

Return type:

ndarray

zvcfd.phantoms.reservoir_flags(fluid)[source]

Flags with fixed-density reservoirs on the fluid voxels of both x faces.

Parameters:

fluid (ndarray)

Return type:

ndarray

zvcfd.phantoms.vessel_network(shape, n=26, r=(5.0, 9.0), seed=3)[source]

Capsule vessels; half run along x so the network percolates in x.

Return type:

ndarray

zvcfd.phantoms.vessel_tree(shape, n_vessels=40, r_min=3.0, r_max=8.0, seed=0)[source]

Random straight tubes crossing a box (a crude vasculature stand-in).

Returns flag: 1 solid, 0 fluid. Vessels are capsules between random points on opposite faces, so the network percolates in x.

Return type:

ndarray