Strain and synthetic data

Strain from displacements, and speckle phantoms with known displacement fields.

zvdvc.post.strain

Strain from displacement, as CCPi’s strain program computes it, with an uncertainty per point.

At each point, the displacements of its strain window are fitted by least squares with a 3D quadratic polynomial per component, and the displacement gradient G = du/dx is taken at the point. The window is the window nearest points (the point itself included), keeping those that are GOOD and whose objective is at most threshold. With refill, further neighbours replace the ones dropped until the window is full (CCPi -r). From G: engineering strain (G + G^T)/2, Lagrangian strain (G + G^T + G^T G)/2, and their principal values (descending). A point cloud in a coordinate plane (every point sharing one coordinate, like CCPi’s central grid) is fitted in that plane, with the out-of-plane component and derivatives zero, as CCPi does.

Unlike CCPi, each point also gets:

  • residual_rms (3,): the fit’s residual per displacement component;

  • strain_sd (6,): the standard deviation of each engineering strain component, from propagating a displacement uncertainty through the least-squares fit. The uncertainty is sigma_u if given (for example the sample-set spread from zvdvc.bench.error_floor.seed_repeatability()), else the fit residual.

The fit is centred on each point and scaled by its window radius, which is mathematically the same model as CCPi’s but better conditioned; points with fewer good neighbours than the polynomial has terms, or whose points cannot determine every term (for example only two levels along an axis), get NaN strain where CCPi would return an ill-determined value. On CCPi’s case A result this reproduces CCPi’s strain to every printed digit at all interior points. Within a grid step of the cloud’s edge the window can end among equidistant points, which CCPi picks with an unstable sort and zvDVC in neighbour-search order, so a few edge windows differ by one point.

zvdvc strain RESULTS reads a results store, a zvDVC .npz or a CCPi .disp and writes CCPi’s CSV layout (<base>-sw<N>.Lstr.csv, .Estr.csv, .dgrd.csv) plus .strain.npz.

class zvdvc.post.strain.StrainResult(pts_in_sw: 'np.ndarray', sw_radius: 'np.ndarray', u_fit: 'np.ndarray', grad: 'np.ndarray', engineering: 'np.ndarray', lagrangian: 'np.ndarray', principal_engineering: 'np.ndarray', principal_lagrangian: 'np.ndarray', residual_rms: 'np.ndarray', strain_sd: 'np.ndarray', planar_axis: 'int | None', window: 'int' = 25)[source]

Bases: object

Parameters:
pts_in_sw: ndarray
sw_radius: ndarray
u_fit: ndarray
grad: ndarray
engineering: ndarray
lagrangian: ndarray
principal_engineering: ndarray
principal_lagrangian: ndarray
residual_rms: ndarray
strain_sd: ndarray
planar_axis: int | None
window: int = 25
zvdvc.post.strain.planar_axis(xyz)[source]

The axis every point shares a coordinate on (CCPi’s -xy/-yz/-zx auto-detection), if any.

Parameters:

xyz (ndarray)

Return type:

int | None

zvdvc.post.strain.fit_strain(xyz, displacement, status, objmin=None, *, window=25, threshold=1.0, refill=False, sigma_u=None, chunk=100000)[source]

Strain at every point from its window’s GOOD displacements (see module doc).

Parameters:
Return type:

StrainResult

zvdvc.post.strain.write_csv(path, point_id, xyz, r, which)[source]

CCPi’s strain CSV (Lstr, Estr or dgrd), plus zvDVC’s uncertainty columns at the end.

Parameters:
Return type:

None

zvdvc.post.strain.compute_strain(results, *, window=25, threshold=1.0, refill=False, sigma_u=None, out_base=None, outputs=('Lstr',))[source]

Strain for a results store, zvDVC .npz or CCPi .disp; writes the CSVs and .strain.npz.

Parameters:
Return type:

dict[str, Any]

zvdvc.synth.phantoms

Speckle phantoms and analytic displacement fields.

Ground truth is what makes the MVP a feasibility test: every accuracy claim in docs/MVP_PLAN.md is measured against these fields, not against another code.

Volumes are generated and warped chunk by chunk (overlap = filter support + max displacement), straight into sharded OME-Zarr, so 4096^3 cases can be built on a workstation with bounded memory.

Fields (all analytic, with gradients for strain checks):

rigid translation + small rotation. Tests seeding, range handling and 6-DOF. affine uniform strain up to ~1 %. Tests 12-DOF and strain post-processing. sinusoid u = A sin(2 pi x / lambda) along one axis. Tests spatial resolution versus subvolume size. inclusion Eshelby-like stiff sphere in a strained matrix. A realistic mix of gradients.

The deformed volume uses backward mapping: g(x) = f(X) where x = X + u(X), with X found by fixed-point iteration. Interpolation is quintic B-spline, so the phantom’s interpolation error sits well below that of the tricubic being tested. Optional Gaussian noise, independent in the two volumes, is added before quantisation (Poisson noise: later, if needed).

The speckle is Gaussian-filtered white noise. The noise is drawn per fixed 64^3 block from a seed derived from the block index, so any region of the volume can be regenerated on its own and chunked writing gives bit-identical volumes whatever the chunking. With the default feature_size = 3 the filter has sigma 1.5 voxels, which keeps the texture band-limited (spectrum at Nyquist ~1e-5) so the B-spline resampling is effectively exact.

class zvdvc.synth.phantoms.DisplacementField(kind, params=<factory>)[source]

Bases: object

Analytic displacement u(X) of reference position X, in voxels.

Parameters (all optional unless noted; vectors are (x, y, z)):

rigid translation; rotation = CCPi angles (phi, the, psi) in

radians; centre. u = t + (R - I)(X - c), so a 6-DOF search recovers u(P) and the angles exactly.

affine translation; strain = (exx, eyy, ezz, exy, eyz, exz)

(tensor shears) or a full 3x3 gradient; centre. u = t + G (X - c).

sinusoid amplitude (required), wavelength (required); axis

the coordinate it varies along and component the displacement component (0/1/2 = x/y/z, both default 0); phase; translation.

inclusion centre, radius (required); far-field strain;

ratio = inclusion strain / far-field strain (default 0.25). u = t + s(r) E (X - c) with s = ratio inside and s = 1 - (1 - ratio) (a / r)^3 outside: continuous, with the r^-3 decay of an Eshelby far field.

Parameters:
kind: Literal['rigid', 'affine', 'sinusoid', 'inclusion']
params: dict[str, Any]
gradient(xyz)[source]

(N, 3) -> (N, 3, 3) displacement gradient du_i / dX_j, for strain checks.

Parameters:

xyz (Any)

Return type:

Any

inverse_map(x, *, iterations=12)[source]

Reference positions X with X + u(X) = x, by fixed-point iteration (needs |grad u| < 1).

Parameters:
Return type:

ndarray

zvdvc.synth.phantoms.default_field(kind, shape_zyx)[source]

The synthetic cases’ fields, scaled so |u| stays within about 3 voxels.

Parameters:
Return type:

DisplacementField

zvdvc.synth.phantoms.speckle_field(box, *, feature_size=3.0, seed=0)[source]

Zero-mean, unit-variance speckle over box of the infinite, seed-defined pattern.

Parameters:
Return type:

ndarray

zvdvc.synth.phantoms.speckle(shape_zyx, *, feature_size=3.0, dtype='uint16', seed=0)[source]

Band-limited random speckle (filtered noise), scaled to the dtype’s range.

Parameters:
Return type:

Any

zvdvc.synth.phantoms.warp_volume(ref, field, *, noise_sigma=0.0, seed=1)[source]

Deform an in-memory volume: g(x) = ref(X) with x = X + u(X), quintic B-spline, float64 out.

noise_sigma is an absolute standard deviation in ref’s units. For large cases use make_case(), which regenerates the speckle chunk by chunk instead of resampling one array.

Parameters:
Return type:

Any

zvdvc.synth.phantoms.case_points(shape_zyx, spacing, margin)[source]

Lattice through the volume centre, keeping points at least margin from every face.

Parameters:
Return type:

ndarray

zvdvc.synth.phantoms.make_case(out_dir, *, shape_zyx, field, spacing=16.0, dtype='uint16', noise_sigma=0.0, chunk=128, shard=1024, subvolume=None, search=None, feature_size=3.0, seed=0, workers=None, points_xyz=None, point_id=None, starting_point=None, overwrite=False)[source]

Write ref.ome.zarr, def.ome.zarr, points.zarrvectors (and the same points as points.roi for CCPi), truth.npz and config.yaml; return the config path.

noise_sigma is the Gaussian noise standard deviation as a fraction of the dtype’s full scale (the speckle’s own standard deviation is 0.12), drawn independently for the two volumes. Points form a spacing lattice kept far enough from the faces that every subvolume stays inside both volumes. The defaults for subvolume and search are case S’s (docs/MVP_PLAN.md): sphere 32 / 2 000 samples, 12-DOF, ZNSSD, tricubic, disp_max 8. points_xyz (and optionally point_id) replaces the lattice with given points, e.g. a CCPi .roi, kept as they are even if some subvolumes leave the volume. starting_point is written to the config’s seeding. An existing case in out_dir is replaced only with overwrite. Blocks are generated by workers processes (default: every core); the output does not depend on it. The point store’s cells are a quarter of the volume per axis, so the one tile (the whole volume) holds 4^3 cells.

Parameters:
Return type:

Path

zvdvc.synth.phantoms.load_field(truth_path)[source]

The analytic field a case was generated with, from its truth.npz.

Parameters:

truth_path (str | Path)

Return type:

DisplacementField