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 (withprobe_deviceand >= 2 devices), kvikio, nvcomp, pyamg, icechunk, zarr_vectors, and the zarr-vectors capabilities zvCFD relies on, prefixedzv_: read_cells, device_decode, gpu_codecs, gpu_io, defer_presence, append_safe_sharding, dense_manifests.
- zvcfd.require(*names, probe_device=True)[source]¶
Raise
RuntimeErrornaming every missing capability.
- zvcfd.device_count()[source]¶
Visible CUDA devices; 0 without cupy or a driver. Initialises CUDA.
- Return type:
- 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
stepsupdates offluid_cellsongpusxgpu.- 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:
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:
objectActive 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)¶
- chunks(chunk_bricks)[source]¶
Occupied chunks and, for each brick, the row of its chunk.
Returns
(chunk_coords (C, 3), brick_chunk (nb,)).
- 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.
- 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.
- classmethod from_flags(flags, *, brick=8, periodic=False)[source]¶
Build from a dense
(z, y, x)flag volume (0 fluid, 1 solid, 2 reservoir).
- classmethod from_mask(fluid, **kw)[source]¶
Build from a boolean fluid mask (True = fluid).
- Parameters:
fluid (ndarray)
- Return type:
- halo(parts, part)[source]¶
Bricks owned by other parts that neighbour
part’s bricks (its ghost set).
- 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:
- n_owned: int | None = None¶
the first
n_ownedbricks are owned, the rest are ghosts, andglobal_idsmaps local bricks to the parent’s.- Type:
For a partition-local domain
- 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).
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:
objectCarreau–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.- __init__(nu_0, nu_inf, lam, a=2.0, n=0.3568)¶
- 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:
_LBMDense periodic box, flags
(z, y, x); reservoir cells takerho_infor 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)
- 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:
_LBMActive 8³ bricks of a
BrickDomainonly.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 parametermagic, default 3/16, which puts half-way bounce-back walls exactly mid-link).rheology (CarreauYasuda | None) – optional
CarreauYasuda(lattice units).boundary (BoundarySet | None) – optional
BoundarySetin 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:
domain (BrickDomain)
collision (str)
magic (float)
rheology (CarreauYasuda | None)
boundary (BoundarySet | None)
- apply_boundary()[source]¶
Write the patch cells of the newest buffer (after a step and its swap).
- Return type:
None
- apply_links()[source]¶
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
- 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:
- patch_velocity()[source]¶
Per patch: summed velocity (z, y, x), summed density, and cell count,
(P, 5).- Return type:
- zvcfd.lbm.solver.dense_from_bricks(domain, values, fill=0.0)[source]¶
Scatter brick rows into a dense volume; see
BrickDomain.to_dense().- Parameters:
domain (BrickDomain)
values (ndarray)
- Return type:
- zvcfd.lbm.solver.equilibrium(rho, ux, uy=None, uz=None)[source]¶
Equilibrium populations
(Q, *rho.shape)(float32, host).
- zvcfd.lbm.solver.kernel(name, half, *, trt=False, nonnewtonian=False, device=None)[source]¶
The compiled kernel
namefor the given storage precision and model options.
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:
every partition collides and streams its owned bricks (kernels on each device, launched without waiting, so devices run concurrently);
ghost bricks are refreshed from their owners (device-to-device copies, peer-to-peer over NVLink where the devices allow it);
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;
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:
objectA
SparseLBMsplit 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:
domain (BrickDomain)
n_parts (int | None)
chunk_bricks (int)
boundary (BoundarySet | 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- __init__(pressure, velocity, iterations, seconds, method)¶
- zvcfd.solvers.lubrication.conductance(fluid, voxel=1.0)[source]¶
k = 3/4 d^2withdthe distance (invoxelunits) to the half-way wall.
- 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 ponfluid.- Parameters:
fluid (ndarray) – Boolean fluid mask (z, y, x).
fixed (ndarray) – Boolean mask of Dirichlet voxels (subset of
fluid).value (ndarray) – Pressure on the
fixedvoxels (same shape; other entries ignored).voxel (float) – Voxel edge (physical length unit);
kand 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:
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:
face_patches()— fluid voxels on a face of the bounding box;zvcfd.geometry.voxelize_mesh()— the named inlet/outlet zones of a surface mesh (e.g. an Ansys Fluent.msh);from_cells()— any explicit voxel set (e.g. a label image).
- class zvcfd.boundary.BoundarySet(patches, cells, nbr, patch, scale, link_cells=<factory>, link_mask=<factory>, link_patch=<factory>)[source]¶
Bases:
objectPatch voxels and patch links of a domain, in the domain’s global cell numbering.
A global cell id is
brick * B³ + localwithlocalthe 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()). Bitqof a cell’s mask is set when the population arriving alongc_qcrosses 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>)¶
- 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:
- 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:
- 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:
objectOne 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 fromzvcfd.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
velocitywhen 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)¶
- 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
twith outflowq_out(m³/s); return the patch pressure (Pa) to hold until the next step.
- zvcfd.boundary.cell_coords(domain, cells)[source]¶
Voxel coordinates (z, y, x) of global cell ids.
- Parameters:
domain (BrickDomain)
cells (ndarray)
- Return type:
- zvcfd.boundary.cell_flags(domain, cells)[source]¶
- Parameters:
domain (BrickDomain)
cells (ndarray)
- Return type:
- zvcfd.boundary.cell_ids(domain, zyx)[source]¶
Global cell ids of voxel coordinates
(N, 3); -1 outside active bricks or the box.- Parameters:
domain (BrickDomain)
zyx (ndarray)
- Return type:
- 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_areais left to the caller viaPatch.area; None means “count voxels”).- Parameters:
domain (BrickDomain)
- Return type:
- 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 groupNoneor(cells, mask): the group’s patch links (zvcfd.geometry.cap_links()), used when the patch is a pressure-flagged one.- Parameters:
- Return type:
- 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:
domain (BrickDomain)
cells (ndarray)
- Return type:
- zvcfd.boundary.profile_scale(domain, cells, patch)[source]¶
- Parameters:
domain (BrickDomain)
cells (ndarray)
patch (Patch)
- Return type:
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:
objectWhere the voxels are: origin (z, y, x) of voxel (0, 0, 0)’s corner, edge, shape.
- __init__(origin, voxel, shape)¶
- zvcfd.geometry.cap_links(domain, grid, tri)[source]¶
The lattice links that cross a cap:
(fluid cell ids, uint32 link masks).triis the cap’s triangles,(T, 3, 3)in (z, y, x) mesh units. A link runs from a fluid voxel centre along-c_qto a non-fluid voxel (or none); it belongs to the cap when that segment crosses the cap’s triangles. Bitqof a cell’s mask is set for each such link: the population arriving alongc_qthen 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.
- zvcfd.geometry.domain_from_voxels(zyx, shape, *, brick=8)[source]¶
A
BrickDomainwhose fluid voxels are exactlyzyx.- Parameters:
- Return type:
- zvcfd.geometry.patch_cells(domain, grid, tri)[source]¶
Fluid voxels just inside a cap (inlet/outlet) and the cap’s geometry (voxel units).
- zvcfd.geometry.voxelize_fluent(path, voxel, *, unit_scale=0.001, pad=2)[source]¶
Voxelise an ASCII Fluent mesh’s boundary; see
voxelize_mesh().
- 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 asvelocitypatches, outlets aspressurepatches (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².
pad (int)
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 * Cfor 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):
coordinator:
create_brick_store()(allocates arrays, defers presence);workers:
write_brick_chunk()for the chunks they own, no locks;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:
domain (BrickDomain)
bricks (ndarray)
voxel_size (float)
- Return type:
- 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
flagsattribute (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.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>"].datais(rows, 512)with CSRoffsetsoverbatch.chunk_coords;device="cuda"decodes on the GPU where the store allows it.
- zvcfd.io.fields.read_domain(path, *, periodic=False)[source]¶
Rebuild the
BrickDomainfrom a domain store (one withflags).- Parameters:
- Return type:
- 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.
- zvcfd.io.fields.store_geometry(domain, voxel_size, chunk_bricks)[source]¶
(bounds, chunk_shape)in physical units for a domain.- Parameters:
domain (BrickDomain)
voxel_size (float)
chunk_bricks (int)
- 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.
bricksare brick indices that all lie in one chunk; each value infieldsis(len(bricks), 512)(numpy, or a device array, which zarr-vectors copies off once). Presence is not stamped; the coordinator’sfinalize_brick_store()does that once.Returns the chunk coordinate written.
- zvcfd.io.fields.write_brick_chunks(level, domain, fields, *, voxel_size, chunk_bricks, bricks=None)[source]¶
Worker: write every chunk touched by
bricksin one write session.fieldsvalues are(len(bricks), 512)rows aligned withbricks(default: every brick of the domain, in domain order), so a worker only ever holds its own share.bricksmust cover whole chunks: a chunk written by two workers keeps whichever landed last. Returns the number of chunks written.
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- __init__(group, datasets, axes, version)¶
- zvcfd.io.omezarr.fluid_mask(volume, *, threshold=None, label=None)[source]¶
Fluid voxels of a segmentation or intensity volume.
- 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:
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- __init__(zone, kind, name='', faces=<factory>)¶
- class zvcfd.io.fluent_msh.FluentBoundary(nodes, zones, n_cells, n_faces, n_interior_faces, source='')[source]¶
Bases:
objectNodes and boundary face zones of a Fluent mesh.
- Parameters:
- __init__(nodes, zones, n_cells, n_faces, n_interior_faces, source='')¶
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, withlabels.sourcepointing atimage), when it is not the image;domain: the brick store holding voxel flags (zvcfd:domain);fields: acollectionof 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_node(doc, n)[source]¶
Add or replace (by id) a top-level node. Ids share one namespace with coordinate systems.
- zvcfd.collection.add_snapshot(doc, run_dir, store_path, *, step, time_s=None, fields=None)[source]¶
Publish one snapshot under the
fieldscollection node.
- zvcfd.collection.atomic_write_json(path, obj)[source]¶
Write-then-rename in the same directory, so readers see old or new, never half.
- zvcfd.collection.check(doc)[source]¶
Structural problems (empty when fine): unique ids, nodes xor path, known version.
- zvcfd.collection.node(kind, name, path, *, path_type='zarr', node_id=None, attributes=None)[source]¶
- zvcfd.collection.rel(target, doc_dir)[source]¶
Relative path from the document’s directory,
./-prefixed inside it.
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- __init__(faces=<factory>, patches=<factory>)¶
- class zvcfd.config.Domain(brick: 'int' = 8, chunk_bricks: 'int' = 32, periodic: 'bool' = False)[source]¶
Bases:
object- __init__(brick=8, chunk_bricks=32, periodic=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:
objectFinite-volume settings (
solver.method: fv).- Parameters:
linear (str)
linear_rtol (float)
precision (str)
advection (Any)
false_dt (float | None)
iterations (int)
tolerance (float)
residual_target (float | None)
backflow_stabilisation (float)
dt (float | None)
steps (int | None)
periods (float | None)
period (float | None)
loops (int)
loop_tolerance (float)
scheme (str)
steady_start (bool)
wss (bool)
tawss_from (float | None)
chunk (float | None)
turbulence (dict | None)
- __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:
linear (str)
linear_rtol (float)
precision (str)
advection (Any)
false_dt (float | None)
iterations (int)
tolerance (float)
residual_target (float | None)
backflow_stabilisation (float)
dt (float | None)
steps (int | None)
periods (float | None)
period (float | None)
loops (int)
loop_tolerance (float)
scheme (str)
steady_start (bool)
wss (bool)
tawss_from (float | None)
chunk (float | None)
turbulence (dict | None)
- Return type:
None
- 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)¶
- class zvcfd.config.Parallel(gpus: 'int' = 1, partitions: 'int | None' = None)[source]¶
Bases:
object
- 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)¶
- 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>)¶
- boundaries: Boundaries¶
- 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)¶
- 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)¶
- zvcfd.config.resolve_method(cfg)[source]¶
The solver
solver.method: autostands 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.
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:
objectSets patch values each check interval and measures patch flows.
- Parameters:
boundary (BoundarySet)
lat (Lattice)
flow_control (bool)
- __init__(sim, boundary, lat, *, flow_control=True)[source]¶
- Parameters:
boundary (BoundarySet)
lat (Lattice)
flow_control (bool)
- zvcfd.run.build_geometry(cfg, log=<built-in function print>, *, out=None)[source]¶
(domain, boundary, voxel_um, image, report)for a configuration.
- zvcfd.run.lattice_for(cfg, voxel_um, log=<built-in function print>)[source]¶
The lattice:
solver.tauif given, else dt fromsolver.machatphysics.u_ref.
- zvcfd.run.make_solver(cfg, domain, boundary, lat)[source]¶
- Parameters:
cfg (RunConfig)
domain (BrickDomain)
lat (Lattice)
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)¶
- 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)¶
- class zvcfd.perfmodel.Method(name: 'str', bytes_per_update: 'float', bytes_per_cell: 'float', efficiency: 'dict')[source]¶
Bases:
object- __init__(name, bytes_per_update, bytes_per_cell, efficiency)¶
- 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.
- 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
stepsupdates offluid_cellsongpusxgpu.- 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:
- 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).
- 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.
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).
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) orany(max-pool).
- zvcfd.phantoms.porous_spheres(n, porosity_target=0.45, radius=6, seed=0)[source]¶
Periodic overlapping-sphere solid; flag 1 = solid.
- zvcfd.phantoms.reservoir_flags(fluid)[source]¶
Flags with fixed-density reservoirs on the fluid voxels of both x faces.
- 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: