Skip to content

Streaming statistics (optix.stats)

Mergeable per-pixel summaries computed in one pass over frame batches, and exact order statistics computed over row tiles.

Streaming, mergeable statistics and per-pixel order statistics.

Reducer

Reducer(*, dim=0)

Streaming, mergeable summary.

State tensors (named in _state) are created on the first update; a never-updated reducer is the identity of merge.

Note

Every reducer satisfies, up to floating-point round-off:

R().update(cat(a, b)) == R().update(a).update(b)
                      == R().update(a).merge(R().update(b))

Create an empty reducer.

Parameters:

Name Type Description Default
dim int or tuple of int or None

Dims of each chunk that are reduced. Default 0: per-pixel over the frame axis of a (n, *spatial) chunk. None: everything (global summary).

0

empty property

empty

True until the first update or merge.

update

update(x, *, weight=None)

Add a chunk of data (optionally weighted). Returns self.

merge

merge(other)

Merge another reducer into this one, in place. Returns self.

copy

copy()

Independent copy (state tensors are cloned).

to

to(device=None, dtype=None)

Move the state (in place); dtype casts floating state only.

state_dict

state_dict()

Constructor arguments and state tensors.

from_state_dict classmethod

from_state_dict(state)

Rebuild a reducer saved with state_dict.

Moments

Moments(order=2, *, dim=0, state_dtype=None)

Bases: Reducer

Per-pixel count, mean and central moments up to order (1..4).

Note

Each update computes the chunk's own (n, mean, M2..Mp) by direct sums about the chunk mean, in the chunk's dtype (no chunk-sized float64 temporaries), then merges it into the running state with the same pairwise formulas as merge. Raw power sums are never accumulated.

Weights are frequency weights (count is their sum), as needed for masks and responsibilities; var(ddof=1) is only meaningful for integer-like weights. Pixels with zero total weight keep zeros in the state, and their accessors return NaN.

References

  1. Pébay P. Formulas for robust, one-pass parallel computation of covariances and arbitrary-order statistical moments. Sandia National Laboratories report SAND2008-6212, 2008. doi:10.2172/1028931
BibTeX
@techreport{pebay2008,
  author = {P{'e}bay, P.},
  title = {Formulas for robust, one-pass parallel
           computation of covariances and arbitrary-order
           statistical moments},
  institution = {Sandia National Laboratories},
  number = {SAND2008-6212},
  year = {2008},
  doi = {10.2172/1028931}
}

Attributes:

Name Type Description
count Tensor

Sum of weights (0-d if every update was unweighted).

mean Tensor

Weighted mean.

Create an empty accumulator.

Parameters:

Name Type Description Default
order int

Highest central moment kept (1 = mean only, 2 = variance, 3 = skewness, 4 = kurtosis).

2
dim int or tuple of int or None

Reduced dims of each chunk (see Reducer).

0
state_dtype dtype

Dtype of the running state. Default: float64 (float32 on MPS).

None

update

update(x, *, weight=None)

Add a chunk of data.

Parameters:

Name Type Description Default
x Tensor

Chunk; the dims in self.dim are reduced.

required
weight Tensor

Frequency weights (or boolean mask) broadcastable to x.

None

Returns:

Type Description
Moments

self

merge

merge(other)

Merge another Moments (same order).

var

var(ddof=1)

Variance M₂ / (count − ddof); NaN where count ≤ ddof.

std

std(ddof=1)

Standard deviation: the square root of var(ddof).

skewness

skewness()

Sample skewness √n M₃ / M₂^(3/2) (biased, g₁).

kurtosis

kurtosis(excess=True)

Sample kurtosis n M₄ / M₂² (minus 3 if excess).

MinMax

MinMax(*, dim=0)

Bases: Reducer

Per-pixel minimum and maximum.

Note

NaNs propagate: mask them out with weight instead. weight is a boolean mask (nonzero = keep).

Attributes:

Name Type Description
min, max Tensor

Running extrema (+inf / -inf where nothing was seen).

Create an empty reducer.

Parameters:

Name Type Description Default
dim int or tuple of int or None

Reduced dims of each chunk (see Reducer).

0

update

update(x, *, weight=None)

Add a chunk of data; weight is an optional boolean mask.

merge

merge(other)

Merge another MinMax into this one.

Histogram

Histogram(lo, hi, bins=64, *, dim=0, count_dtype=int64)

Bases: Reducer

Per-pixel fixed-range histogram with underflow and overflow bins.

Note

Integer counts make the result exactly independent of chunking and order. A zero-width range (hi == lo, dead pixels) puts every value equal to lo into the first regular bin.

The state holds (bins + 2) · ∏(item) counts: 64 bins on a 2048 × 2048 image is about 2.2 GB in int64 (1.1 GB in int32). A warning is emitted when it exceeds the configured chunk memory.

Attributes:

Name Type Description
counts (bins + 2, *item) Tensor

counts[0] counts values below lo, counts[-1] values above hi (and NaNs), counts[1:-1] the regular bins. A value equal to hi goes into the last regular bin.

Create an empty histogram.

Parameters:

Name Type Description Default
lo Tensor or float

Range, as scalars or per-pixel maps (typically from a MinMax pass). Fixed at construction.

required
hi Tensor or float

Range, as scalars or per-pixel maps (typically from a MinMax pass). Fixed at construction.

required
bins int

Number of regular bins between lo and hi.

64
dim int or tuple of int or None

Reduced dims of each chunk (see Reducer).

0
count_dtype dtype

Integer dtype of the counts (default int64, which cannot overflow in practice; int32 halves the memory but overflows past 2³¹ − 1 counts in one bin).

int64

update

update(x, *, weight=None)

Add a chunk of data.

Parameters:

Name Type Description Default
x Tensor

Chunk; the dims in self.dim are reduced.

required
weight Tensor

Boolean mask or integer counts, broadcastable to x.

None

Returns:

Type Description
Histogram

self

merge

merge(other)

Merge another Histogram (same edges).

cdf

cdf()

Cumulative fraction of values up to each bin.

Returns:

Type Description
(bins + 2, *item) Tensor

cdf[j] = fraction of values in bins 0..j (float64; NaN where nothing was counted).

quantile

quantile(q)

Per-pixel quantile(s), interpolated linearly inside bins.

Parameters:

Name Type Description Default
q float or (Q,) Tensor

Quantile level(s) in [0, 1].

required

Returns:

Type Description
(*item) or (Q, *item) Tensor

Quantiles (dtype of lo). The error is bounded by one bin width inside [lo, hi]; ranks falling in the underflow or overflow bins are clamped to lo / hi. NaN where nothing was counted.

Reservoir

Reservoir(size, *, seed=None)

Bases: Reducer

Uniform random sample (without replacement) of the values seen.

Every value gets a random int64 key and the size values with the smallest keys are kept. Merging concatenates and keeps the size smallest keys again, so merging is exact and the sample is exactly uniform.

Note

Once the reservoir is full, with kmax its largest key, a value is only kept if its key is below kmax. A float32 Bernoulli mask with probability q, the smallest power of two ≥ kmax / 2⁶² (and ≥ 2⁻²⁴, so that it is exact in float32), selects candidates, and int64 keys are drawn uniformly in [0, q 2⁶²) for those only; keys ≥ kmax are then discarded. Each value thus gets a key uniform in [0, kmax) with probability exactly kmax / 2⁶², as if a key had been drawn for every value, without a chunk-sized int64 temporary.

Each update synchronises with the host (boolean indexing and reading kmax). The random generator is not part of state_dict: a reservoir restored with from_state_dict starts again from seed, and reservoirs (e.g. parallel workers) built with the same seed draw the same key stream. Give each worker its own seed (or none) for independent samples.

Attributes:

Name Type Description
values (≤ size,) Tensor

Sampled values (flattened, in no particular order).

seen int

Number of values seen (after masking).

Create an empty reservoir.

Parameters:

Name Type Description Default
size int

Maximum number of values kept.

required
seed int

Seed of the random keys. Samples are reproducible for a fixed seed and a fixed chunking only.

None

seen property

seen

Number of values seen.

update

update(x, *, weight=None)

Add a chunk of values; weight is an optional boolean mask.

merge

merge(other)

Merge another Reservoir (exact).

copy

copy()

Independent copy, including the generator state.

PixelStats

PixelStats(count, mean, var, nspatial, skewness=None, kurtosis=None)

Per-pixel temporal statistics of one stack.

Attributes:

Name Type Description
count (*group, 1, ..., 1) Tensor

Number of samples per group.

mean, var (*group, *spatial) Tensor

Per-pixel mean and unbiased variance (or median and squared scaled MAD for statistic="median").

skewness, kurtosis (*group, *spatial) Tensor or None

Biased sample skewness and (non-excess) kurtosis (order=4).

nspatial int

Number of spatial dims.

spatial_mean

spatial_mean(x)

Mean over the spatial dims, kept as size-1 dims.

reduce

reduce(data, *reducers, ndim=None, layout=None, **chunk_options)

One pass over frame batches feeding every reducer.

Parameters:

Name Type Description Default
data array - like or Labeled

Data.

required
*reducers Reducer

Reducers to update with each (n, *spatial) frame batch.

()
ndim int

Without a layout: number of trailing spatial dims (default 2).

None
layout Layout

Axis roles (see frame_batches). It must not have group axes: use reduce_groups.

None
**chunk_options object

Forwarded to frame_batches (overhead, memory, batch, dtype, device, prefetch, contiguous, ...).

{}

Returns:

Type Description
tuple of Reducer

The same reducers, updated with every sample.

reduce_groups

reduce_groups(data, *reducers, ndim=None, layout=None, **chunk_options)

One pass over frame batches, with one copy of the reducers per group.

Parameters:

Name Type Description Default
data ArrayLike

See reduce; the layout may have group axes.

required
ndim ArrayLike

See reduce; the layout may have group axes.

required
layout ArrayLike

See reduce; the layout may have group axes.

required
**chunk_options ArrayLike

See reduce; the layout may have group axes.

required
*reducers Reducer

Templates: each group gets its own copy. The templates themselves are not updated.

()

Returns:

Type Description
dict of tuple of int to tuple of Reducer

Keyed by group position (() without group axes), in iteration order. Groups without samples are absent.

order_statistics

order_statistics(data, k, *, ndim=None, layout=None, **kw)

Per-pixel k-th smallest value(s) over all samples of each group.

Note

Up to four ranks use repeated torch.kthvalue; more ranks use one sort (whose int64 indices make it heavier: overhead defaults to 3 then). torch.quantile is not used: it rejects large inputs. NaNs give undefined results.

Parameters:

Name Type Description Default
data array - like or Labeled

Data.

required
k int or sequence of int

1-based rank(s), as in torch.kthvalue.

required
ndim optional None
layout optional None
**kw object

Forwarded to tile_reduce / row_tiles.

{}

Returns:

Type Description
(*group, *spatial) or (K, *group, *spatial) Tensor

median_mad

median_mad(data, *, ndim=None, layout=None, **kw)

Per-pixel median and median absolute deviation, in one pass.

Parameters:

Name Type Description Default
data array - like or Labeled

Data.

required
ndim optional None
layout optional None
**kw object

Forwarded to tile_reduce / row_tiles.

{}

Returns:

Type Description
median, mad : (*group, *spatial) Tensor

Lower median (rank (N + 1) // 2, as torch.median) and the lower median of |data - median|, unscaled (multiply by 1.4826 for a Gaussian standard deviation).

tile_reduce

tile_reduce(data, fn, *, ndim=None, layout=None, overhead=2.0, **chunk_options)

Apply fn to row tiles holding all samples and stitch the maps.

Parameters:

Name Type Description Default
data array - like or Labeled

Data.

required
fn callable

Takes a (rows, *rest, N) tile (spatial axes in layout order, N = all samples of one group, last) and returns one or several (rows, *rest) maps.

required
ndim int

Without a layout: number of trailing spatial dims (default 2).

None
layout Layout

Axis roles (see row_tiles). Tiles are cut along the first spatial axis.

None
overhead float

Chunk-sized temporaries held by fn (see chunk_length).

2.0
**chunk_options object

Forwarded to row_tiles.

{}

Returns:

Type Description
Tensor or tuple of Tensor

Full (*group, *spatial) maps, on the working device.

otsu_threshold

otsu_threshold(data, *, bins=256, ndim=2)

Otsu's threshold of each frame.

The intensities of a frame are binned into a histogram with counts nₖ at bin centres cₖ; the threshold is the centre cₖ that maximises the between-class variance

w₀(k) · w₁(k) · (μ₀(k) − μ₁(k))²,

with w₀(k) = ∑{j ≤ k} nⱼ, w₁(k) = ∑ nⱼ and μ₀, μ₁ the mean centres of the two classes (Otsu 1979). The first maximiser is taken, and a constant frame returns its value.

The binning follows scikit-image's threshold_otsu: bins equal bins over [min, max] (numpy's histogram edges), or, with bins=None, one bin per integer value from min to max (what scikit-image does for integer images).

References

  1. Otsu N. A threshold selection method from gray-level histograms. IEEE Trans Syst Man Cybern 9(1):62–66, 1979. doi:10.1109/TSMC.1979.4310076
BibTeX
@article{otsu1979threshold,
  author  = {Otsu, Nobuyuki},
  title   = {A Threshold Selection Method from Gray-Level
             Histograms},
  journal = {IEEE Transactions on Systems, Man, and
             Cybernetics},
  volume  = {9}, number = {1}, pages = {62--66},
  year    = {1979}, doi = {10.1109/TSMC.1979.4310076}
}

Parameters:

Name Type Description Default
data Tensor

Frames (..., *spatial).

required
bins int or None

Number of equal bins, or None for one bin per integer value (data must then hold integers).

256
ndim int

Number of trailing (spatial) dims forming a frame.

2

Returns:

Type Description
Tensor

data.shape[:-ndim] thresholds (floating point).

pixel_stats

pixel_stats(data, *, order=2, statistic='mean', dtype=None, device=None, out_dtype=None)

Per-pixel statistics of a stack, in one streaming pass.

Parameters:

Name Type Description Default
data array - like or Labeled

(*samples, H, W) without a layout.

required
order int

Highest central moment (2 or 4), for statistic="mean".

2
statistic (mean, median)

"mean": Welford/Pébay moments over frame batches. "median": exact per-pixel median and MAD over row tiles; the variance is then (1.4826·MAD)².

"mean"
dtype optional

Working backend of the chunks.

None
device optional

Working backend of the chunks.

None
out_dtype dtype

Dtype of the returned maps (default: the working dtype).

None

Returns:

Type Description
PixelStats