Skip to content

brainhops._core.pyramids

Coarser levels of a pyramid, built from its finest level.

A pyramid stores the same image or field at several resolutions, so that a viewer or an algorithm that only needs a coarse view reads less data. This module holds the arithmetic with which the multiscale classes of the data model build their coarser levels, in their method with_scales.

A level is downsampled from a finer level by an integer factor f along each axis, and a factor of 1 leaves the axis as it is. How the voxels of the coarse level are laid over those of the finer level is the alignment, align, and level_map returns the shape, the actual scale s and the shift t of each axis, so that the coarse voxel i lies at the fine voxel s * i + t:

  • "exact", the default, crops an axis of n voxels to the multiple of f below it, and keeps the factor exactly: the coarse level has n // f voxels, and its voxel i covers the fine voxels f * i to f * i + f - 1, so that s = f and t = (f - 1) / 2. This is the rule that OME-NGFF 0.6 states for a level downsampled by a factor f (ngff-spec tag 0.6 at 89da1da, index.md, section "multiscales metadata"). The windows of f voxels do not overlap, so a coarse voxel reads only the fine voxels of its own window.
  • "edges" keeps the outer edges of the field of view: the coarse level has ceil(n / f) voxels, the actual scale is s = n / ceil(n / f), and t = (s - 1) / 2, so that the fine voxel of the coarse voxel i is (i + 1 / 2) * s - 1 / 2.
  • "centers" keeps the centres of the first and the last voxels: the coarse level has ceil((n - 1) / f) + 1 voxels, the actual scale is s = (n - 1) / (ceil((n - 1) / f)), and t = 0. An axis of one voxel is left as it is.

With "edges" and "centers", the finer level is smoothed by the kernel of the mode, sized from the actual scale, and then pulled at the positions of the coarse voxels with the B-splines of brainhops._ext.interpol, through [pull_axes][brainhops._core.bsplines.pull_axes]: of degree 1, which interpolates linearly, after smoothing, and of degree 0, the nearest voxel, in the mode "nearest". The interpolation is separable, one axis after the other, which gives the same values as an interpolation over every axis at once, because a level only scales and shifts each axis. The axis that shrinks the most goes first, so that the next passes work on a smaller array, and no grid of coordinates is built over every axis. These maps compose: a level downsampled by g from a level that was itself downsampled by f lies where a level downsampled by f * g from the finest level lies, and has as many voxels, so a level is computed from the level before it whenever its factors are multiples of those of that level. The mode "nearest" is the exception, because a voxel picked from a picked voxel is not always the voxel nearest to the coarse voxel, so it always picks from the finest level.

How the value of a coarse voxel is computed is the mode, one of MODES:

  • "mean", the default, averages the voxels that the coarse voxel covers: a window of f voxels with "exact", and a window as wide as the actual scale, centred at each voxel, before the pull, otherwise.
  • "binomial" and "gaussian" apply a filter whose width follows one principle: a voxel has an intrinsic Gaussian profile whose full width at half maximum (FWHM) is one voxel, and a level downsampled by a scale s must end with a FWHM of s fine voxels. Gaussian widths add in quadrature, so the filter has a FWHM of sqrt(s ** 2 - 1) fine voxels, which is a standard deviation sigma = sqrt(s ** 2 - 1) / (2 * sqrt(2 * log(2))), about 0.74 for a scale of 2. "gaussian" samples that Gaussian at the voxels, out to 3 standard deviations, and normalizes it to a sum of 1. "binomial" is the row k of Pascal's triangle divided by its sum, whose variance is k / 4, for the order k that brings that variance closest to sigma ** 2 among the orders that centre the filter where it must lie. With "exact" and a factor of 2, it is the filter (1, 3, 3, 1) / 8, centred between two voxels, and before a pull, it is (1, 2, 1) / 4 for a scale of 2.
  • "nearest" takes the fine voxel nearest to the position of the coarse voxel, and computes nothing. With "exact", it is the voxel f * i + (f - 1) // 2, which is half a fine voxel from the centre of the coarse voxel when f is even, the usual error of a nearest neighbour. It suits labels, and a field, which it samples at some of its nodes without changing their values.
  • "mode", "vote_binomial" and "vote_gaussian", the modes of VOTE_MODES, vote among labels, whose values are not averaged. The indicator of a label is 1 at the voxels of that label and 0 elsewhere. A vote smooths the indicator of each label with the box kernel of "mean", the binomial kernel or the Gaussian kernel, pulls it by linear interpolation under "edges" and "centers", and keeps, at each coarse voxel, the label of the highest score. When labels tie, the vote keeps the smallest label value. A level keeps the labels and their type.
  • "max" and "min" keep the largest or the smallest value of the window. These two modes reduce the windows of "exact", and the other alignments refuse them.

A mode is described by a Mode, which pairs a kernel with a reduction, and says whether the mode votes.

vote explains how the loop over the labels works: it only visits the labels of the block that it is given, so a chunk of a Dask array visits its own labels, and it never holds one indicator per label at once. With the box kernel and the alignment "exact", the score of a label is the fraction of the window that the label covers, so "mode" keeps the value that occurs most often in the window. "mode" computes that value by counting the equal voxels of each window instead of looping over the labels, which gives the same labels, ties included, and costs less for the small windows of a level computed from the level before it. The binomial and the Gaussian kernels weight the voxels near the coarse voxel more than those further away, and reach beyond its window, which gives smoother boundaries between the labels.

A vote keeps a label only where that label wins. A structure thinner than half a coarse voxel, such as a line one voxel wide downsampled by 2, therefore disappears when a single other label surrounds it, while "nearest" keeps the voxels of the structure that it happens to pick. Where several labels mix around the structure, the structure holds the highest score, and a vote keeps it along its whole length, while "nearest" keeps pieces of it.

A vote is computed from the level before it, as the other modes except "nearest" are, so a coarse level votes among the labels that the level before it kept, and not among the voxels of the finest level. This changes some voxels along the boundaries between labels. On a test parcellation, "vote_gaussian" changes 5 % of the coarse voxels for a factor of 4 and 10 % for a factor of 8, while the fraction of the fine voxels that keep their label changes by less than one percentage point. A vote from the finest level would cost more, and a chunk of a Dask level would read a region of the finest level that grows as f ** d for d downsampled axes.

A filter may read voxels beyond the edges of the finer level, which are extended as edge says. With "repeat", for an image, an added voxel repeats the voxel at the edge. With "linear", for a field, an added voxel continues the line through the voxels at the edge, by a point reflection through the voxel at the edge, so that a field that is affine, such as the coordinates of an identity, stays exact up to the edges. A vote refuses "linear", which would add labels that the array does not hold.

The values of a field may depend on the grid of the field itself, which rescale_vectors handles after any mode.

The arithmetic is written with the operations of the array package, so an array on a GPU stays on the GPU. A NumPy or a CuPy array is computed as a whole, one pass after the other. A Dask array stays lazy, and each chunk of a level is one task of its graph: the task copies the region of the finer level that the chunk reads, with the voxels around it that the filter and the interpolation read, from the chunks of the finer level that it overlaps, and runs the same passes on that region with the package of the chunks. The passes of a level are therefore not separate layers of the graph, which Dask could not fuse, and a level has as many tasks as chunks, which have the shape of the chunks of the finest level. The interpolation of brainhops._ext.interpol does not smooth, so the filters of the modes are applied before it, and the ndimage packages of SciPy and CuPy, which have no version for Dask, are not used.

When the factors are not given, default_factors chooses them step by step. At each step, each axis that may be downsampled is downsampled by its factor, unless it has min_size voxels or fewer, in which case it stays as it is from then on, or unless its voxels are more than sqrt(f) times larger than the smallest voxels of the axes that can still be downsampled. An axis of 40 voxels therefore becomes an axis of 20 voxels when min_size is 32. The steps stop when no axis can be downsampled. The second rule makes anisotropic voxels roughly isotropic before the coarse axes are downsampled, because downsampling an axis whose voxels are larger than that would move it further, in a ratio of sizes, from the voxel size of the other axes.

Attributes

MIN_SIZE module-attribute

MIN_SIZE = 32

The size at or below which the rules stop downsampling an axis.

MODES module-attribute

MODES = (
    "mean",
    "binomial",
    "gaussian",
    "nearest",
    "mode",
    "vote_binomial",
    "vote_gaussian",
    "max",
    "min",
)

The ways in which a coarse voxel is computed from the finer level.

Mode Value of a coarse voxel Suits
"mean" the mean of the voxels that it covers images, fields
"binomial" a binomial filter around its position images, fields
"gaussian" a Gaussian filter around its position images, fields
"nearest" the fine voxel nearest to its position labels, fields
"mode" the label that covers most of it labels
"vote_binomial" the label with the best binomial score labels
"vote_gaussian" the label with the best Gaussian score labels
"max" the largest value of its window images, masks
"min" the smallest value of its window images, masks

A mode that averages is named after its reduction ("mean") or its kernel ("binomial", "gaussian"). The votes are named after the reduction and then the kernel, except the vote with the box kernel, which keeps the name of the statistic that it computes, "mode".

DEFAULT_MODE module-attribute

DEFAULT_MODE = 'mean'

The mode with which a pyramid is built by default.

FIELD_MODES module-attribute

FIELD_MODES = ('mean', 'binomial', 'gaussian', 'nearest')

The modes that apply to a field of displacements or coordinates.

The other modes compare the vectors of a window component by component, or vote among them, which does not give a vector of the field.

VOTE_MODES module-attribute

VOTE_MODES = ('mode', 'vote_binomial', 'vote_gaussian')

The modes that vote among labels, which work with every alignment.

BLOCK_MODES module-attribute

BLOCK_MODES = ('max', 'min')

The modes that only reduce the windows of the alignment "exact".

ALIGNMENTS module-attribute

ALIGNMENTS = ('exact', 'edges', 'centers')

How the voxels of a coarse level lie over those of the finer one.

DEFAULT_ALIGN module-attribute

DEFAULT_ALIGN = 'exact'

The alignment with which a pyramid is built by default.

Classes

Mode

Bases: NamedTuple

How a mode computes a coarse voxel from the finer level.

A mode filters the voxels with a kernel, or reduces the voxels of a window of the alignment "exact", or takes the fine voxel nearest to the coarse voxel when it has neither. "mean" has both: it reduces the windows of "exact", and filters before a pull. A mode that votes runs its kernel, and the pull of the alignment, on the indicator of each label, and keeps the label of the highest score. "mode" votes and has a reduction too, which counts the values of each window of "exact" and gives the labels of a vote with the box kernel at a lower cost.

Attributes

kernel instance-attribute
kernel: Callable[[float, float], tuple[int, ndarray]] | None

The filter of a scale s, centred at an offset c, or None.

It returns the offset of its first tap from a voxel, and the weights of its taps, which are centred at that voxel plus c.

reduction instance-attribute
reduction: Callable[..., ArrayProtocol] | None

The reduction of each window of "exact", or None.

It is called on an array whose axis k is split into the axes 2 * k and 2 * k + 1, the second of which holds the window, with the axes of the windows given as axis, as dask.array.coarsen calls it.

averages instance-attribute
averages: bool

Whether the mode averages the values, which an integer rounds.

votes class-attribute instance-attribute
votes: bool = False

Whether the mode votes among the labels with its kernel.

The vote goes through vote. A reduction, when the mode has one, replaces the vote for the windows of "exact", and must give the same labels.

Functions:

check_mode

check_mode(
    mode: str,
    field: bool = False,
    align: str = DEFAULT_ALIGN,
) -> str

Return a mode of MODES, or refuse it.

Parameters:

Name Type Description Default
mode str

The mode.

required
field bool

Whether the pyramid is a field of displacements or coordinates, which only takes the modes of FIELD_MODES.

False
align str

The alignment, since the modes of BLOCK_MODES only reduce the windows of "exact".

"exact"

Returns:

Type Description
str

The mode.

Raises:

Type Description
ValueError

If the mode is unknown, if it does not apply to a field, or if it does not apply to the alignment.

check_align

check_align(align: str) -> str

Return an alignment of ALIGNMENTS, or refuse it.

Parameters:

Name Type Description Default
align str

The alignment.

required

Returns:

Type Description
str

The alignment.

Raises:

Type Description
ValueError

If the alignment is unknown.

level_map

level_map(
    align: str, length: int, factor: int
) -> tuple[int, float, float]

Return how a level lies over the finer level along one axis.

Parameters:

Name Type Description Default
align str

The alignment of ALIGNMENTS.

required
length int

The number of voxels of the finer level along the axis.

required
factor int

The factor of the axis.

required

Returns:

Name Type Description
count int

The number of voxels of the level along the axis.

scale float

The actual scale s of the axis.

shift float

The shift t of the axis, so that the voxel i of the level lies at the voxel s * i + t of the finer level.

level_geometry

level_geometry(
    align: str, shape: Sequence[int], factors: Sequence[int]
) -> tuple[tuple[int, ...], ndarray, ndarray]

Return how a level lies over the finer level along each axis.

Parameters:

Name Type Description Default
align str

The alignment of ALIGNMENTS.

required
shape sequence of int

The shape of the finer level.

required
factors sequence of int

The factor of each axis.

required

Returns:

Name Type Description
shape tuple of int

The shape of the level.

scales ndarray

The actual scale of each axis.

shifts ndarray

The shift of each axis, as level_map returns them.

default_factors

default_factors(
    shape: Sequence[int],
    sizes: Sequence[float],
    step: Sequence[int],
    nscales: int | None = None,
    min_size: int = MIN_SIZE,
    strict: bool = False,
    align: str = DEFAULT_ALIGN,
) -> list[tuple[int, ...]]

Return the factors of the coarser levels of a pyramid.

The factors are chosen step by step, by the rules of the module docstring.

Parameters:

Name Type Description Default
shape sequence of int

The number of voxels of the finest level along each axis.

required
sizes sequence of float

The size of a voxel of the finest level along each axis, in the same unit for every axis that may be downsampled. A size that is not positive counts as 1.

required
step sequence of int

The factor of each axis at each step, where 1 means that the axis is never downsampled.

required
nscales int

The number of levels, the finest level included. By default, the levels go on until no axis can be downsampled.

None
min_size int

The number of voxels at or below which an axis is no longer downsampled.

32
strict bool

Whether to refuse to build fewer levels than nscales, when the rules stop before.

False
align str

The alignment of the levels, which decides their numbers of voxels.

"exact"

Returns:

Type Description
list of tuple of int

For each coarser level, the factor of each axis from the finest level.

Raises:

Type Description
ValueError

If the lengths of shape, sizes and step differ, if a factor of step is not a positive integer, if nscales or min_size is smaller than 1, or if strict is true and the rules stop before nscales levels.

downsample

downsample(
    array: ArrayProtocol,
    factors: Sequence[Sequence[int]],
    mode: str = DEFAULT_MODE,
    edge: str = "repeat",
    align: str = DEFAULT_ALIGN,
    previous: tuple[Sequence[int], ArrayProtocol]
    | None = None,
) -> list[ArrayProtocol]

Return the coarser levels of a pyramid, from its finest level.

A level whose factors are multiples of those of the level before it is computed from that level, which costs less, and any other level from the finest level. The mode "nearest" always picks the voxels of the finest level, because a voxel picked from a coarser level is not always the voxel nearest to the coarse voxel.

With "mean", "binomial" or "gaussian", a level of an integer or boolean type is computed in double precision and rounded back to its type, which it never leaves, since these modes average its values. The other modes keep the values and their type. A Dask array gives Dask arrays, which are not computed. Their chunks have the shape of the chunks of array, capped at the shape of each level, and each chunk is one task of the graph.

Parameters:

Name Type Description Default
array ArrayProtocol

The finest level.

required
factors sequence of sequence of int

For each coarser level, the factor of each axis of array from the finest level, which is 1 for an axis that is not downsampled.

required
mode str

How a coarse voxel is computed, one of MODES.

"mean"
edge (repeat, linear)

How the voxels are extended beyond the edges, as the module docstring explains.

"repeat"
align (exact, edges, centers)

How the voxels of a coarse level are laid over those of the finer level, as the module docstring explains.

"exact"
previous tuple of (sequence of int, ArrayProtocol)

The factors and the array of a coarser level that already exists, from which the first level of factors is computed when its factors are multiples of those of that level.

None

Returns:

Type Description
list of ArrayProtocol

The coarser levels, in the order of factors.

Raises:

Type Description
ValueError

If the mode, the edge or the alignment is unknown, if the mode does not apply to the alignment, if a vote is asked with the edge "linear", or if a level does not give a positive integer factor to each axis or leaves no voxel.

rescale_vectors

rescale_vectors(
    values: ArrayProtocol,
    scales: Sequence[float],
    shifts: Sequence[float],
    kind: str | None,
    inverse: bool = False,
) -> ArrayProtocol

Express the vectors of a field in the grid of a coarser level.

A field whose vectors are given in voxels of its own grid holds other values on a coarser grid, since the voxel i of the finer grid is the voxel (i - t) / s of the coarser one, with the actual scale s and the shift t of level_map. Coordinates in that grid are mapped by this affine, and displacements, which are differences of coordinates, by its linear part only, which divides them by s. Vectors given in the world, or in the grid of another image, do not depend on the grid of the field, so they are only averaged by the mode, and returned as they are here.

Parameters:

Name Type Description Default
values ArrayProtocol

The vectors of the level, of shape (*grid, ndim), after the mode averaged them.

required
scales sequence of float

The actual scale of each axis of the grid, from the finest level.

required
shifts sequence of float

The shift of each axis, from the finest level.

required
kind (coordinates, displacements)

What the vectors are when they are given in voxels of the grid of the field, or None when they are not.

"coordinates"
inverse bool

Whether to express the vectors of the level in the grid of the finest level instead.

False

Returns:

Type Description
ArrayProtocol

The vectors in the grid of the level.

Raises:

Type Description
ValueError

If kind is unknown.

vote

Return the label of the highest score at each output voxel.

A label map cannot be averaged, because the mean of two labels is a third label that means nothing. This function computes a label map at other positions, such as the voxels of a coarser level, by a vote: smooth turns the indicator of each label, which is 1 where the label is and 0 elsewhere, into a score at each output voxel, and the label of the highest score wins. A smoothing kernel weights the voxels near the output voxel more than those further away, which gives smoother boundaries between the labels than a vote that counts the voxels of a window.

The labels are those that labels holds, so a chunk of a Dask array that calls this function on its own block only loops over the labels of that block. The vote keeps a running best score and best label, and never builds one indicator per label at once, so it holds two arrays of the output shape whatever the number of labels. Scores that differ by less than 1e-9 tie, so that the rounding of the smoothing does not decide a tie, and a tie goes to the smallest label, which is the first label that the loop visits.

Parameters:

Name Type Description Default
labels ArrayProtocol

The labels, of any integer, boolean or floating type, as one array of the package that computes them.

required
smooth callable

The function that maps the indicator of a label, an array of the shape of labels and of type float64, to its scores at the output voxels. It is called once per label, and it must give scores between about 0 and 1, as a kernel normalized to a sum of 1 and a linear interpolation do.

required

Returns:

Type Description
ArrayProtocol

The label of the highest score at each output voxel, of the type of labels.