Skip to content

Tile fusion (optix.fusion)

Estimators

Fusion of tiled and multiview acquisitions.

Building blocks (overlap statistics, the intensity solver) are in optix.fusion.utils.

IntensityAdjustment

IntensityAdjustment(*, weights=None, downsample=None, max_pixels=None, seed=None, faithful=True, dtype=None, device=None, layout=None)

Bases: Estimator

Brightness and contrast adjustment of overlapping tiles (BigStitcher).

Tiles of a mosaic, placed on a common pixel grid by known positions, differ in brightness and contrast (bleaching, illumination drift). Each tile i gets a linear intensity transform

x̂ᵢ = aᵢ yᵢ + cᵢ,

chosen so that the transformed intensities of corresponding pixels agree in the overlap Oᵢⱼ of every pair of tiles. The mismatch is the squared difference (Supplementary Note 17, eq. 8, read with both tiles of a pair transformed)

Σᵢ Σ_{j ≠ i} Σ_{r ∈ Oᵢⱼ} ((aⱼ yⱼ(r) + cⱼ) − (aᵢ yᵢ(r) + cᵢ))².

As printed, eq. 8 transforms only one tile of the pair; the two-sided reading is the one of the point-correspondence objective of the paper's global optimisation (Supplementary Note 12, eq. 3), which the paper uses to solve it. As unconstrained, this sum has the trivial solution a = c = 0. Each transform is therefore the weighted average of a linear, an additive and the identity transform (eq. 9),

aᵢ y + cᵢ = λ₁ (a′ᵢ y + c′ᵢ) + λ₂ (y + c″ᵢ) + λ₃ y,
λ₁ + λ₂ + λ₃ = 1,

which pulls the solution towards the identity when λ₂, λ₃ > 0. Without the identity term (λ₃ = 0), a common offset of all tiles is left free (and with λ₂ = 0 a common scale too), so tiles must then be fixed (fixed=). The paper solves eq. 8 with the iterative optimiser of its image registration (Supplementary Note 12): each tile's models are fitted by least squares to its corresponding points, the pixel values pᵣ = yᵢ(r) paired with the current transformed values qᵣ = aⱼ yⱼ(r) + cⱼ of the other tiles, and the fits are repeated until they agree. The result is the fixed point of these regularised per-tile fits: it minimises the sum above only for λ = (1, 0, 0), not for other weights. Those fits only need the count, means, scatters and co-scatter of the pixel pairs of each overlap, which are accumulated in one streaming pass over the overlaps; the agreed transforms are then the solution of one linear system of size 2T for T tiles, whose solution is the limit of the paper's iteration (see solve_intensity).

Paper notation: Iₐ → yᵢ, α^{Iₐ} → aᵢ, β^{Iₐ} → cᵢ, α′ → a′ᵢ, β₁ → c′ᵢ, β₂ → c″ᵢ, Oₐᵦ → Oᵢⱼ.

Faithful mode

Eq. 8 (read with both tiles transformed) and eq. 9. The paper leaves the weights λ to the user and does not give defaults; the default here, (λ₁, λ₂, λ₃) = (0.8, 0.1, 0.1), is not specified in the paper. The paper fits on precomputed downsampled images and offers to cap the number of corresponding pixels per overlap, without stating the factor or the cap: both are off in the faithful preset (downsample=1, max_pixels=None). The recommended preset (faithful=False) bins by downsample=4 (see "Noise"). Tiles held at the identity (fixed=) are those of the paper's global optimisation (Supplementary Note 12, eq. 3).

Positions and correspondences

Tiles are placed by translations on a common pixel grid: positions[i] is the grid position of the first pixel of tile i along each spatial axis (layout order). Non-integer positions are rounded to the nearest pixel: corresponding pixels are those that land on the same grid pixel. Rotated or affinely registered tiles are not supported. Sample axes (e.g. time points) share the tile transforms and pool their pixels; group axes (e.g. channels) are fitted independently.

Downsampling

With downsample=f, both tiles of an overlap are averaged over the same bins of f pixels per axis (anchored at the corner of the overlap), so that binned values still correspond exactly. Partial bins at the far edges of an overlap are weighted by the fraction of a full bin that they hold, i.e. by the inverse of their noise variance relative to a full bin.

Noise

The per-tile fits regress the other tiles' values on the tile's own noisy values, so noise biases them (errors-in-variables attenuation): with signal variance s² and noise variance σ² in the overlaps, each linear fit shrinks the slope by about s² / (s² + σ²), and the fixed point compounds the shrinkage along the chain of overlaps from the fixed tiles. On a 3 × 3 mosaic with signal standard deviation s ≈ 50 and 20 % overlap (λ = (1, 0, 0), centre tile fixed), the mean error of scale is about −6 % at σ = 5 and −48 % at σ = 20 without binning, and −0.4 % and −6 % with downsample=4. Binning by f per axis divides σ² by f^D, which is why the paper fits on downsampled images; use downsample > 1 on noisy data. max_pixels does not reduce the bias.

References

  1. Hörl D, Rojas Rusak F, Preusser F, Tillberg P, Randel N, Chhetri RK, Cardona A, Keller PJ, Harz H, Leonhardt H, Treier M, Preibisch S. BigStitcher: reconstructing high-resolution image datasets of cleared and expanded samples. Nat Methods 16(9):870–874, 2019. doi:10.1038/s41592-019-0501-0
BibTeX
@article{horl2019bigstitcher,
  author  = {H{\"o}rl, David and Rojas Rusak, Fabio and
             Preusser, Friedrich and Tillberg, Paul and
             Randel, Nadine and Chhetri, Raghav K. and
             Cardona, Albert and Keller, Philipp J. and
             Harz, Hartmann and Leonhardt, Heinrich and
             Treier, Mathias and Preibisch, Stephan},
  title   = {{BigStitcher}: reconstructing high-resolution image
             datasets of cleared and expanded samples},
  journal = {Nature Methods},
  volume  = {16}, number = {9}, pages = {870--874},
  year    = {2019}, doi = {10.1038/s41592-019-0501-0}
}

Attributes:

Name Type Description
estimates dict

{"intensity": TileIntensityEstimate} with scale and shift of shape (*group, T); meta["mse_before"] and meta["mse_after"] hold the mean squared difference of corresponding pixels before and after the adjustment, per group (flattened).

Configure the adjustment.

Parameters:

Name Type Description Default
weights (float, float, float)

λ₁, λ₂, λ₃ of the linear, additive and identity transforms (eq. 9); non-negative, summing to 1. λ₃ > 0 makes the solution unique; with λ₃ = 0 (a common offset is then free, and with λ₂ = 0 too a common scale), every connected set of overlapping tiles needs a fixed tile. Default (0.8, 0.1, 0.1), not specified in the paper.

None
downsample int or sequence of int

Bin size along each spatial axis (layout order) before the fit, which reduces the bias that noise puts on the fit (see "Noise" above). Default 1 (no binning) in faithful mode, 4 with faithful=False; the paper fits on downsampled images without stating the factor.

None
max_pixels int

Maximum number of corresponding pixels (after binning) per overlap, drawn uniformly at random without replacement, so that large overlaps do not dominate small ones. Default None: all pixels.

None
seed int

Seed of the random selection of max_pixels. Each overlap and group draws from its own stream, derived from (seed, group, overlap).

None
faithful bool

See Estimator.

True
dtype bool

See Estimator.

True
device bool

See Estimator.

True
layout bool

See Estimator.

True

fit

fit(data, positions, *, fixed=(), layout=None, init=None, callback=None, verbose=False)

Estimate one intensity transform per tile from the overlaps.

Parameters:

Name Type Description Default
data sequence of array-like or Labeled

The T tiles, all in the same layout (spatial shapes may differ). Without a layout, the trailing D dims are spatial, with D the number of columns of positions.

required
positions (T, D) array-like

Grid position of the first pixel of each tile, along each spatial axis in layout order (rounded to whole pixels).

required
fixed sequence of int

Tiles held at the identity (a = 1, c = 0).

()
layout Layout | None

See Estimator.fit; init is not used (the solution is computed directly).

None
init Layout | None

See Estimator.fit; init is not used (the solution is computed directly).

None
callback Layout | None

See Estimator.fit; init is not used (the solution is computed directly).

None
verbose Layout | None

See Estimator.fit; init is not used (the solution is computed directly).

None

Returns:

Type Description
IntensityAdjustment

self

apply

apply(data, out=None)

Harmonise every tile: x̂ᵢ = aᵢ yᵢ + cᵢ.

Parameters:

Name Type Description Default
data sequence of array-like or Labeled

The T tiles, in the order and layout of the fit.

required
out sequence of writable array-like

One output per tile (in place is allowed). Default: new tensors.

None

Returns:

Type Description
list of writable array-like

The outputs.

Utilities

No stability promise

optix.fusion.utils holds building blocks of the estimators above; they may change without notice.

Building blocks of tile intensity harmonisation.

Overlap geometry, streaming overlap statistics and the solver of IntensityAdjustment.

OverlapStats dataclass

OverlapStats(n, mean, scatter)

Bivariate sufficient statistics of corresponding pixel pairs.

One entry per (group, pair) along the leading dims of the state. Pairs may be weighted (e.g. bins by the fraction of a full bin they hold); n is then the sum of the weights. Moments are kept centred (count, means and scatter / co-scatter about the means) and merged with the pairwise formulas of Chan et al. 1983, so that the fit does not suffer from the cancellation of raw sums.

Attributes:

Name Type Description
n Tensor

(..., P) number (or total weight) of pixel pairs.

mean Tensor

(..., P, 2) means of the first and second tile of each pair.

scatter Tensor

(..., P, 3) sums of squared deviations M_aa, M_bb and of cross products M_ab.

zeros classmethod

zeros(shape, *, dtype=float64, device=None)

Empty statistics of shape (*shape,) (e.g. (*group, P)).

of staticmethod

of(a, b, weight=None)

Count, means and scatters of the pairs (a, b) (flattened).

With weight (one per pair), the count is the sum of the weights and the means and scatters are weighted.

add

add(index, a, b, weight=None)

Merge the pixel pairs (a, b), optionally weighted, at index.

merge_at

merge_at(index, n2, m2, s2)

Merge precomputed (n, mean, scatter) into entry index.

overlap_box

overlap_box(pos_a, shape_a, pos_b, shape_b)

Overlap of two axis-aligned tiles placed on a common pixel grid.

Parameters:

Name Type Description Default
pos_a sequence of int

Position of the first pixel of each tile in the common grid.

required
pos_b sequence of int

Position of the first pixel of each tile in the common grid.

required
shape_a sequence of int

Spatial shapes of the tiles.

required
shape_b sequence of int

Spatial shapes of the tiles.

required

Returns:

Type Description
(tuple of slice, tuple of slice) or None

The overlap as local slices of tile A and of tile B (pixel a[sa] lies on b[sb]), or None when the tiles do not overlap.

overlaps

overlaps(positions, shapes)

All overlapping pairs (i, j, slices_i, slices_j), with i < j.

bin_mean

bin_mean(x, factor, *, count=False)

Mean over non-overlapping bins of factor pixels along each dim.

Trailing partial bins average the pixels they hold. With count=True, also return the number of pixels of each bin (a tensor of the shape of the means), e.g. to weight partial bins.

components

components(nodes, edges)

Connected-component label of each node (union-find).

solve_intensity

solve_intensity(pairs, n, mean, scatter, ntiles, weights, fixed=())

Per-tile intensity transforms from overlap statistics (one group).

Each tile i is mapped to aᵢ yᵢ + cᵢ, the weighted average (Hörl et al. 2019, Supplementary Note 17, eq. 9)

aᵢ y + cᵢ = λ₁ (a′ᵢ y + c′ᵢ) + λ₂ (y + c″ᵢ) + λ₃ y

of a linear model (a′ᵢ, c′ᵢ) and an additive model c″ᵢ, each fitted by least squares to the corresponding pixels (p, q) of tile i: p = yᵢ(r) and q = aⱼ yⱼ(r) + cⱼ, the transformed value of every overlapping tile j at the same position r. The transforms are the fixed point of this per-tile fit (the global optimisation of the paper's Supplementary Note 12 applied to one-dimensional points); as the fits are linear in the (aⱼ, cⱼ), the fixed point is found by one linear solve of size 2T. For λ = (1, 0, 0) the fixed point minimises eq. 8 (read with both tiles transformed); for other weights it does not minimise any sum of squares, it is where the regularised per-tile fits agree.

Existence, uniqueness and the paper's iteration

Write the per-tile update as f ↦ J f + b on the transformed intensities fᵢ = aᵢ yᵢ + cᵢ, and measure them in the norm E(f) = Σᵢ ‖fᵢ‖²_{Ωᵢ}, with Ωᵢ the pixel pairs of tile i. Each pixel pair is counted once from each side, so the values qᵢ that tile i is fitted to satisfy Σᵢ ‖qᵢ‖²_{Ωᵢ} = E(f). The update of tile i is, up to a constant term, λ₁ P + λ₂ E₀ applied to qᵢ, with P the least-squares projection onto affine functions of yᵢ and E₀ the projection onto constants (both over Ωᵢ): both are orthogonal projections, so the update has norm at most λ₁ + λ₂ = 1 − λ₃. For λ₃ > 0 the homogeneous map J is therefore a contraction with factor 1 − λ₃ in this norm: I − J is invertible (the system is non-singular and the solution unique), and the paper's iterative optimiser (sweeps of per-tile fits) converges to this same solution. The condition number grows roughly like 1/λ₃. For λ₃ = 0 the null space holds a common offset (and, with λ₂ = 0 too, a common affine map); one fixed tile per connected set of tiles removes it.

Scaling

The system is dense, 2T × 2T, and assembled entry by entry: it takes 32 T² bytes and O(T³) operations per group, which is fast up to a few thousand tiles (T = 5000 needs 800 MB). The matrix has one block per overlap, so a sparse solve would scale further.

Parameters:

Name Type Description Default
pairs sequence of (int, int)

Tile indices (i, j) of each overlap.

required
n (P,) Tensor

Number of pixel pairs in each overlap.

required
mean (P, 2) Tensor

Means of tile i and of tile j over each overlap.

required
scatter (P, 3) Tensor

Scatters M_ii, M_jj and co-scatter M_ij over each overlap.

required
ntiles int

Number of tiles T.

required
weights (float, float, float)

λ₁, λ₂, λ₃ (summing to 1).

required
fixed sequence of int

Tiles held at the identity.

()

Returns:

Type Description
scale, shift : (T,) Tensor

aᵢ and cᵢ, in the dtype of mean.

Raises:

Type Description
ValueError

When λ₃ = 0 and a connected set of tiles has no fixed tile. The linear and additive models are both equivariant to a common offset, so without the identity term any offset common to all tiles of the set is a solution (and with λ₂ = 0 too, any common affine map, zero included).

intensity_mse

intensity_mse(pairs, n, mean, scatter, scale, shift)

Mean squared difference of corresponding transformed pixels.

The objective of Hörl et al. 2019, Supplementary Note 17, eq. 8 (with both tiles of a pair transformed), divided by the number of pairs of pixels: Σ ‖(aᵢ yᵢ + cᵢ) − (aⱼ yⱼ + cⱼ)‖² / Σ nᵢⱼ.