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 |
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.
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
- 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
|
0
|
state_dtype
|
dtype
|
Dtype of the running state. Default: float64 (float32 on MPS). |
None
|
update
update(x, *, weight=None)
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 ( |
Create an empty reducer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dim
|
int or tuple of int or None
|
Reduced dims of each chunk (see
|
0
|
update
update(x, *, weight=None)
Add a chunk of data; weight is an optional boolean mask.
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
|
|
Create an empty histogram.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lo
|
Tensor or float
|
Range, as scalars or per-pixel maps (typically from a
|
required |
hi
|
Tensor or float
|
Range, as scalars or per-pixel maps (typically from a
|
required |
bins
|
int
|
Number of regular bins between |
64
|
dim
|
int or tuple of int or None
|
Reduced dims of each chunk (see
|
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)
cdf
cdf()
Cumulative fraction of values up to each bin.
Returns:
| Type | Description |
|---|---|
(bins + 2, *item) Tensor
|
|
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 |
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.
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 |
skewness, kurtosis |
(*group, *spatial) Tensor or None
|
Biased sample skewness and (non-excess) kurtosis ( |
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 |
()
|
ndim
|
int
|
Without a layout: number of trailing spatial dims (default 2). |
None
|
layout
|
Layout
|
Axis roles (see |
None
|
**chunk_options
|
object
|
Forwarded to |
{}
|
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 |
required |
ndim
|
ArrayLike
|
See |
required |
layout
|
ArrayLike
|
See |
required |
**chunk_options
|
ArrayLike
|
See |
required |
*reducers
|
Reducer
|
Templates: each group gets its own
|
()
|
Returns:
| Type | Description |
|---|---|
dict of tuple of int to tuple of Reducer
|
Keyed by group position ( |
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 |
required |
ndim
|
optional
|
See |
None
|
layout
|
optional
|
See |
None
|
**kw
|
object
|
Forwarded to |
{}
|
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
|
See |
None
|
layout
|
optional
|
See |
None
|
**kw
|
object
|
Forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
median, mad : (*group, *spatial) Tensor
|
Lower median (rank |
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 |
required |
ndim
|
int
|
Without a layout: number of trailing spatial dims (default 2). |
None
|
layout
|
Layout
|
Axis roles (see |
None
|
overhead
|
float
|
Chunk-sized temporaries held by |
2.0
|
**chunk_options
|
object
|
Forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
Tensor or tuple of Tensor
|
Full |
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
- 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 |
required |
bins
|
int or None
|
Number of equal bins, or None for one bin per integer value
( |
256
|
ndim
|
int
|
Number of trailing (spatial) dims forming a frame. |
2
|
Returns:
| Type | Description |
|---|---|
Tensor
|
|
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
|
|
required |
order
|
int
|
Highest central moment (2 or 4), for |
2
|
statistic
|
(mean, median)
|
|
"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
|
|