Solver

Batched Gauss–Newton, the engines behind it, coarse search, seeding and per-point uncertainty. See Correlation method.

zvdvc.solver.gauss_newton

Batched Gauss-Newton: CCPi’s per-point search, run for B points at once.

For each batch (following Search::process_point):

  1. Sample the reference brick at centre + template to get f (B, M) and its stats. This happens once per point; IC-GN also keeps grad f.

  2. Optional threshold test (subvol_thresh) -> THRESH_FAIL; then a reference with no texture -> SINGULAR.

  3. params <- [seed, 0, ...]. As in CCPi, only the translation is seeded; rotations and strains start at zero.

  4. Optional translation grid search (basin_radius > 0), from zvdvc.solver.coarse.

  5. Up to max_iterations Gauss-Newton steps on the active set: the engine reduces each point’s samples to the one-pass sums (zvdvc.kernels.objective.sum_layout()), then solves and tests convergence (zvdvc.solver.engines.gn_update(), or the gn_solve kernel on the fused engine).

  6. Exact final objective, and status.

The loop is written once; zvdvc.solver.engines supplies the numerics (numpy reference, cupy, fused CUDA, the CUDA source emulated on the host, and numba on CPU cores).

Methods

fagn: forward-additive, the CCPi-parity default. CCPi forms the Jacobian by forward differences (h = 1e-10, ndof + 1 objective evaluations per step) and solves J^T J dp = -J^T r by QR with no damping. zvDVC uses the analytic Jacobian grad(g)(x')^T dx'/dp (one value+gradient pass) and a batched Cholesky solve. It keeps the same undamped step and the same stopping rules.

icgn: inverse-compositional (M5). The Hessian comes from the reference gradient and is built once per point. Each iteration needs target values only, with no target gradient, which makes it roughly 2-3x cheaper per iteration.

Differences from CCPi (also listed in docs/ARCHITECTURE.md)
  • Range test: zvDVC tests |u - seed|_inf > disp_max directly, plus brick validity. CCPi’s test is implicit: samples leaving a box of margin disp_max + 2 around the seeded subvolume.

  • Convergence: CCPi’s LM path returns after maxit without flagging. zvDVC reports CONVG_FAIL unless search.report_convg_fail is False.

  • Arithmetic: float32 on device (CCPi uses float64). Positions are formed relative to the point centre, so float32 keeps about 1e-4 voxel resolution across 4096^3 volumes. The numpy reference is float64.

  • Linear solve: Cholesky of the Jacobi-scaled J^T J. A point whose scaled system has a pivot below the precision’s threshold (zvdvc.solver.engines.singular_pivot()), or whose target has no texture (FEATURELESS), is SINGULAR.

  • Texture: a point whose reference samples are constant (air, zero padding; zvdvc.solver.engines.textureless()) is SINGULAR before any iteration, for every objective; so is one whose final target samples are constant. A point whose parameters or final objective are not finite is SINGULAR, never GOOD.

  • Stencils: any reference or target sample whose interpolation stencil leaves the brick’s valid region makes the point RANGE_FAIL (CCPi’s implicit range test, made explicit).

Stopping (CCPi): after each step, a point stops if |obj_k - obj_{k-1}| < obj_tol or |dt| < disp_tol (Euclidean norm of the translation step). The reported objective is re-evaluated at the final parameters.

class zvdvc.solver.gauss_newton.BatchResult(params: 'Any', status: 'Any', objmin: 'Any', n_iter: 'Any', seed: 'Any')[source]

Bases: object

Parameters:
params: Any
status: Any
objmin: Any
n_iter: Any
seed: Any
property displacement: Any
zvdvc.solver.gauss_newton.solve_batch(ref_brick, def_brick, centres, seeds, template, search, *, backend='fused', engine=None)[source]

Correlate B points on one engine (zvdvc.solver.engines).

numpy is the float64 reference (M1). cupy is the unfused GPU path, fused the production CUDA kernels and cpu the same fused step on CPU cores (M2). Results come back on the engine’s device. Pass engine to reuse one (and its compiled kernels) across calls.

Callers that solve the same bricks repeatedly (wavefront shells, batches of a tile) should pass bricks already put through engine.prepare: preparing a host brick for a GPU engine copies the whole brick to the device.

Parameters:
Return type:

BatchResult

zvdvc.solver.engines

Compute engines behind zvdvc.solver.gauss_newton.solve_batch().

The Gauss-Newton driver is written once. An engine supplies four operations:

prepare(brick)

Put a brick where the engine computes (device memory for GPU engines).

sample(brick, centres, params, offsets, search)

Interpolated values (B, M) at the warped template, and whether every stencil stayed in the valid region (B,).

sums(brick, centres, params, idx, q, shift, offsets, search)

For the points idx: the one-pass normal-equation sums (A, n_sums) (zvdvc.kernels.objective.sum_layout()) and whether any sample left the valid region (A,).

update(state, idx, sums, outside, shift, search)

Solve, step, and apply the stopping, range and singularity tests; returns which of idx are finished. gn_update() is the reference; the fused engine does the same per point in one kernel.

Engines

backend

engine

precision

numpy

XpEngine on numpy: the M1 reference

float64

numpy32

XpEngine on numpy in float32: the cupy path’s arithmetic on the host, for tests without a GPU

float32

cupy

XpEngine on cupy: the unfused GPU path

float32

fused

zvdvc.kernels.fused.FusedEngine on CUDA

float32

emulated

the same fused kernels, run on the host by zvdvc.kernels.cuda.emulate (tests only; slow)

float32

cpu

zvdvc.kernels.cpu_fused.NumbaEngine: the fused step on all CPU cores (restructured-CPU baseline, Q5)

float32

zvdvc.solver.engines.singular_pivot(dtype)[source]

Smallest acceptable Cholesky pivot of the unit-diagonal (Jacobi-scaled) system.

Parameters:

dtype (Any)

Return type:

float

zvdvc.solver.engines.flat_reference(dtype)[source]

Largest (max f - min f) / max |f| of a point’s reference samples that counts as no texture (SINGULAR).

Well above the interpolation rounding of a constant volume (about 1e-6 in float32, 1e-15 in float64), and below any texture the precision can resolve.

Parameters:

dtype (Any)

Return type:

float

zvdvc.solver.engines.textureless(xp, f, dtype)[source]

(B,) whether the reference samples f (B, M) are constant to within flat_reference().

Non-finite samples count as no texture too.

Parameters:
Return type:

Any

class zvdvc.solver.engines.BatchState(params: 'Any', seeds: 'Any', status: 'Any', objmin: 'Any', prev_obj: 'Any', n_iter: 'Any')[source]

Bases: object

Parameters:
params: Any
seeds: Any
status: Any
objmin: Any
prev_obj: Any
n_iter: Any
classmethod start(xp, dtype, seeds, ndof)[source]
Parameters:
Return type:

BatchState

zvdvc.solver.engines.cholesky_step(H, b, pivot_tol)[source]

Solve H dp = -b per point: Jacobi scaling, then an unrolled batched Cholesky.

Returns (dp, singular). Written with array operations over the batch and loops over the (at most 12) unknowns, so numpy and cupy run the same arithmetic as the per-point solve in the CUDA kernel.

Parameters:
Return type:

tuple[Any, Any]

zvdvc.solver.engines.gn_update(st, idx, sums, outside, shift, search)[source]

One Gauss-Newton update of the points idx from their sums; returns which are finished.

Parameters:
Return type:

Any

class zvdvc.solver.engines.XpBrick(data: 'Any', origin_xyz: 'tuple[float, float, float]', valid_lo_hi: 'tuple[tuple[int, int, int], tuple[int, int, int]]')[source]

Bases: object

Parameters:
data: Any
origin_xyz: tuple[float, float, float]
valid_lo_hi: tuple[tuple[int, int, int], tuple[int, int, int]]
class zvdvc.solver.engines.XpEngine(xp, dtype)[source]

Bases: object

Unfused array path: numpy (reference) or cupy (M2’s first GPU path).

Parameters:
  • xp (Any)

  • dtype (Any)

SAMPLES_PER_CALL = 1048576
points_per_call(n_samples, ndof)[source]
Parameters:
Return type:

int

prepare(brick)[source]

The engine’s form of a brick (a device copy on cupy); a brick already in that form is returned as is.

Parameters:

brick (Brick | XpBrick)

Return type:

XpBrick

sample(brick, centres, params, offsets, search)[source]
Parameters:
Return type:

tuple[Any, Any]

sums(brick, centres, params, idx, q, shift, offsets, search)[source]
Parameters:
Return type:

tuple[Any, Any]

update(st, idx, sums, outside, shift, search)[source]
Parameters:
Return type:

Any

zvdvc.solver.engines.make_engine(backend)[source]
Parameters:

backend (str)

Return type:

Any

zvdvc.solver.engines.gpu_available()[source]
Return type:

bool

zvdvc.solver.engines.default_backend()[source]

fused with a GPU, else cpu (numba) if installed, else the numpy reference.

Return type:

str

zvdvc.solver.engines.on_device(backend)[source]
Parameters:

backend (str)

Return type:

bool

zvdvc.solver.coarse

Global (coarse) searches that produce a starting translation.

translation_grid_search

CCPi’s basin_radius coarse search, batched. With n = floor(disp_max / basin_radius) and step disp_max / n, it evaluates the objective at (2n + 1)^3 translations around the seed and keeps the best. The batch is B points x G translations with value-only interpolation, chunked over G to fit memory. It is expensive: disp_max = 38, basin_radius = 4 gives 6 859 evaluations per point. That is cheap per point on the GPU, but it dominates the solve, so prefer good seeds.

fft_seed (M5)

Path-independent start, the FFT cross-correlation + Gauss-Newton scheme common in the DIC/DVC literature. It runs a batched zero-normalised cross correlation by cuFFT over a (S + 2 * disp_max)^3 window per point and takes the integer peak with a parabolic sub-voxel fit. Every point is independent, so no serial seeding order is needed at all. The cost is about three FFTs of the window per point, so it suits sparse coarse grids, or pyramid levels where disp_max shrinks.

zvdvc.solver.coarse.grid_offsets(search, xp, dtype)[source]

The (2n + 1)^3 translations, n = floor(disp_max / basin_radius), step disp_max / n.

Parameters:
Return type:

Any

Keep, per point, the grid translation (around its seed) with the best objective.

sample(centres, translations) returns values (n, M) and inside (n,) for 3-DOF parameters; every engine provides it, so this runs unchanged on numpy, cupy, the fused kernels and numba. Translations whose samples leave the brick are never chosen.

Parameters:
Return type:

None

zvdvc.solver.coarse.fft_seed(ref_brick, def_brick, centres, seeds, template, search)[source]

(B, 3) integer-plus-subvoxel translations and (B,) peak NCC as a confidence.

Parameters:
Return type:

Any

zvdvc.solver.seeding

Starting displacements, without CCPi’s serial point order.

CCPi (DataCloud, Search::starting_param) sorts points by distance from the start point, then processes them one at a time. Each point starts from the mean translation of the already-solved point_good points among its 75 nearest neighbours, or from rigid_trans if there are none. Neighbours come from an O(N^2) full sort.

zvDVC strategies (SeedingSpec.strategy):

rigid

Every point starts at rigid_trans. Fully parallel; enough for small, smooth deformations.

wavefront (CCPi parity; single GPU, whole problem resident)

Points are bucketed into shells of width shell_width by distance from the start point. Shells are solved in order, each shell as one batch seeded from GOOD neighbours in earlier shells. It differs from CCPi only in that points within the same shell cannot seed each other. With the shell width equal to the lattice spacing, a k^3-point lattice has about 1.7 k shells from a corner (half that from the centre). Shell sizes grow as r^2, so all but the first few shells fill a GPU.

coarse (production, multi-GPU)

Solve every coarse_stride-th lattice point first, on OME-Zarr pyramid level coarse_level. Subvolume size, disp_max and coordinates are scaled by 2**-level, so the pass reads 1/8 of the bytes per level and fits one GPU. It uses wavefront or fft. That field is then interpolated to seed every full-resolution point. Tiles become independent, which is what lets 8+ GPUs run without coordination.

fft

zvdvc.solver.coarse.fft_seed() for every point (M5).

After the main solve, repair_candidates() finds failed points with enough GOOD neighbours and re-seeds them from the neighbour median for another pass (zvdvc repair).

Neighbours come from a KD-tree (scipy, host) in O(N log N), or a uniform-grid hash on the GPU for clouds of more than about 10^7 points (M5).

zvdvc.solver.seeding.knn(xyz, k, *, device='cpu')[source]

(N, 3) -> (N, k) neighbour indices (self excluded), nearest first. k is capped at N - 1.

Parameters:
Return type:

Any

zvdvc.solver.seeding.processing_order(xyz, start_xyz)[source]

CCPi’s order: indices sorted by distance from the start point.

Parameters:
Return type:

ndarray

zvdvc.solver.seeding.median_spacing(xyz)[source]

Median nearest-neighbour distance: the default wavefront shell width.

Parameters:

xyz (ndarray)

Return type:

float

zvdvc.solver.seeding.wavefront_shells(xyz, start_xyz, width)[source]

Index arrays, one per shell, in solve order.

The point nearest the start is a shell of its own, like CCPi’s first point: it is seeded from rigid_trans and everything after it from neighbours. The rest fall in shells floor(distance / width).

Parameters:
Return type:

list[ndarray]

zvdvc.solver.seeding.seed_from_neighbours(idx, neighbours, displacement, status, rigid_trans)[source]

CCPi starting_param: mean of GOOD neighbours’ (u, v, w), else rigid_trans.

Parameters:
Return type:

Any

zvdvc.solver.seeding.coarse_subset(xyz, stride, *, spacing=None)[source]

Indices of every stride-th lattice point along each axis.

Space is cut into cubes of stride x spacing (spacing defaults to the median point spacing) and the point nearest each cube’s lower corner is kept. On a regular lattice that is exactly the points whose lattice index is a multiple of stride on every axis; on irregular clouds it is an even thinning. Indices come back sorted.

Parameters:
Return type:

ndarray

zvdvc.solver.seeding.interpolate_seed_field(coarse_xyz, coarse_disp, coarse_status, xyz, *, k=8, fallback=(0.0, 0.0, 0.0))[source]

Seeds for xyz from the GOOD coarse points (kNN inverse-distance weighting).

A point that coincides with a GOOD coarse point takes its displacement exactly. With no GOOD coarse point at all, every seed is fallback.

Parameters:
Return type:

Any

zvdvc.solver.seeding.repair_candidates(status, displacement, neighbours, *, min_good=3)[source]

Failed points with at least min_good GOOD neighbours, and their median-of-neighbours seeds.

Parameters:
Return type:

tuple[ndarray, ndarray]

zvdvc.solver.uncertainty

Per-point displacement uncertainty from repeat solves with other template seeds.

On real data the largest random error is which sample points each subvolume uses (docs/benchmarks/2026-09-26-error-floor-case-A.md: ~0.03 voxel per axis at 8 000 samples, falling as 1/sqrt(n)). With uncertainty_seeds = k in the run config, every GOOD point is solved k more times, each with a template drawn with another seed, and the per-axis standard deviation over the k + 1 estimates is stored as displacement_sd. Each repeat starts from the same seed displacement as the main solve, not from its answer: a solve that starts at an answer stops within the convergence tolerance (0.01 voxel) of it and would understate the spread. With k = 2 the cost is about twice the main solve’s; the estimate of each sd has about 2 degrees of freedom, so it is rough per point and good in aggregate.

zvdvc.solver.uncertainty.seed_spread(ref, deformed, centres, seeds, displacement, status, subvolume, search, engine, k)[source]

(N, 3) per-axis sd of the displacement over the main solve and k repeats; NaN where < 2 GOOD estimates.

Parameters:
Return type:

ndarray