Skip to content

Array access (optix.io)

Lazy, chunked access to anything that has a shape and can be sliced. See Axes and layouts for the ideas behind it.

Lazy, chunked access to array-likes (Tensor, numpy, memmap, zarr, ...).

Axis roles (spatial, sample, group) are declared with a Layout, either attached to the data with labeled or passed as layout=. Without one, data are (*samples, *spatial) with ndim trailing spatial dims.

Index module-attribute

Index = tuple[int | slice, ...]

Basic index: a full-length tuple of ints and step-1 slices.

Layout dataclass

Layout(axes=None, spatial=(), sample=None, group=(), _allow_empty=False)

Role of each axis of an array: spatial, sample or group.

  • spatial axes span one picture (a frame). Chunks and fitted parameter maps hold them in the order given here, which need not be the storage order.
  • sample axes index pictures that share the same parameters (frames, time points, z planes, ...). Iterators flatten them, in storage order, into one leading axis of length n.
  • group axes index independent fits (e.g. one flat field per channel). Parameter maps are shaped (*group, *spatial), with the group axes in the order given here.

Every axis has exactly one role; axes that are not named default to sample.

Note

A per-axis spacing (voxel size) may be added later.

Parameters:

Name Type Description Default
axes str or sequence of str

Axis labels, in storage order: a string of single-character names ("tczyx") or a sequence of names. Without labels, roles are given by (possibly negative) positions.

None
spatial str, int or sequence of str / int

Spatial axes, in the order wanted for chunks and maps. A string is split into characters when every label is a single character ("yx"), else it names one axis.

()
sample str, int or sequence of str / int

Sample axes (default: every axis without a role).

None
group str, int or sequence of str / int

Group axes (default: none).

()

Raises:

Type Description
ValueError

For an empty spatial, unknown or repeated names, positions out of range, or an axis given two roles.

Examples:

Light-sheet stack stored as (z, y, x), where each x is one picture of the (y, z) plane: chunks are (n, Y, Z).

>>> layout = Layout("zyx", spatial="yz", sample="x")
>>> layout.shape_of((40, 30, 500))
((), (500,), (30, 40))

OME-NGFF (t, c, z, y, x) with one flat field per channel, shared over t and z: parameter maps are (C, Y, X).

>>> Layout("tczyx", spatial="yx", group="c").shape_of((5, 3, 7, 64, 64))
((3,), (5, 7), (64, 64))

The default, (*samples, *spatial) with two trailing spatial axes:

>>> Layout.default(4, 2)
Layout(axes=None, spatial=(-2, -1), sample=None, group=())

default classmethod

default(ndim_total, ndim_spatial)

The (*samples, *spatial) convention.

Parameters:

Name Type Description Default
ndim_total int

Number of dims of the data.

required
ndim_spatial int

Number of trailing spatial dims; the others are samples.

required

Returns:

Type Description
Layout

Trailing spatial axes given by negative positions, so that it applies to data of any number of dims.

positions

positions(ndim)

Storage positions of the group, sample and spatial axes.

Parameters:

Name Type Description Default
ndim int

Number of dims of the data.

required

Returns:

Type Description
group, sample, spatial : tuple of int

Group and spatial axes in layout order, sample axes in storage order.

Raises:

Type Description
ValueError

If the labels do not match ndim, a position is out of range or an axis has two roles.

shape_of

shape_of(array)

Group, sample and spatial shapes of an array (or a shape).

Parameters:

Name Type Description Default
array array-like or sequence of int
required

Returns:

Type Description
group_shape, sample_shape, spatial_shape : tuple of int

In the orders of positions.

permutation

permutation(ndim)

Storage axes in (*group, *sample, *spatial) order.

x.permute(layout.permutation(x.ndim)) is the canonical view.

inverse_permutation

inverse_permutation(ndim)

Inverse of permutation.

Maps the canonical order back to storage.

map_shape

map_shape(array)

Shape (*group, *spatial) of a fitted parameter map.

to_dict

to_dict()

Plain dict (for state_dict); Layout(**d) rebuilds it.

Labeled

Labeled(array, layout)

An array-like bundled with its Layout.

The wrapped array is never loaded. Built by labeled. Indexing, shape and every other attribute (dtype, chunks, ...) pass through to the wrapped array.

Attributes:

Name Type Description
array array - like

The wrapped array.

layout Layout

Wrap array and check that layout fits its dims.

Parameters:

Name Type Description Default
array array - like

The array to label.

required
layout Layout

Axis roles of array.

required

Chunks

Chunks(source, plans, *, view, dtype, device, prefetch=0, pad=None, with_inner=False, contiguous=False)

Re-iterable, sized sequence of lazily loaded chunks.

Built by frame_batches, row_tiles and blocks. Sizes and the backend are resolved at construction, so iterating twice gives identical chunks and len() is exact. Items are Chunk.

Every yielded data tensor is owned by the consumer: it may be modified in place and never aliases the source. It is a permuted (strided) view of the loaded block, not a dense copy, unless contiguous=True.

Attributes:

Name Type Description
shape tuple of int

Shape of the source.

layout Layout

Layout of the source (the default one when none was given).

group_shape, sample_shape, spatial_shape tuple of int

select

select(indices)

The chunks at indices only (in that order), still lazy.

Parameters:

Name Type Description Default
indices sequence of int

Positions in this sequence of chunks.

required

Returns:

Type Description
Chunks

Only those chunks are read when it is iterated.

Chunk

Bases: tuple

One loaded chunk.

Unpacks as (index, data), or (index, data, inner) for blocks.

Attributes:

Name Type Description
index Index

Region of the core in the source, in storage order (full-length: ints and slices). out[index] = ... is only valid for the default layout and a chunk spanning one sample axis: use store.

data Tensor

Loaded data, owned by the consumer; a strided view in layout order unless the iterator was built with contiguous=True. frame_batches: (n, *spatial); row_tiles: (*sample, *spatial); blocks: (*spatial) core + halo. Spatial axes are in layout order, sample axes in storage order.

inner Index or None

Crop of data that gives the core (blocks only).

group tuple of int

Position along the group axes (layout order).

samples tuple of slice

Region along the sample axes (storage order); index a per-sample state of shape (*group, *sample, ...) with state[chunk.group + chunk.samples].

sample_shape tuple of int

Shape of samples; n is its product.

spatial tuple of slice

Region of the core along the spatial axes (layout order).

store

store(out, result, *, into='source')

Write a result computed from this chunk into out.

Parameters:

Name Type Description Default
out writable array-like

Destination (a Labeled is unwrapped).

required
result Tensor

Shaped like data along the sample and spatial axes (see into). For blocks, a result of the loaded shape is cropped to the core.

required
into (source, map, samples)

"source": out has the shape of the source, in storage order, and result is (n, *spatial) (or data's shape); it is un-flattened and permuted back. "map": out is a (*group, *spatial) map in layout order and result is (*spatial), reduced over the samples (e.g. over a row tile, which holds all samples of a group). "samples": out is a per-sample state (*group, *sample, *rest) and result is (n, *rest).

"source"

ArrayLike

Bases: Protocol

Anything with .shape and basic __getitem__.

Tensor, ndarray, memmap, zarr.Array, h5py.Dataset, dask array.

WritableArrayLike

Bases: ArrayLike, Protocol

An ArrayLike that supports __setitem__.

labeled

labeled(data, layout=None, *, axes=None, spatial=None, sample=None, group=None)

Attach a Layout to an array-like.

The array is not loaded.

Parameters:

Name Type Description Default
data array - like

Tensor, ndarray, memmap, zarr, ... (or a Labeled, which is re-labelled).

required
layout Layout

The layout. Mutually exclusive with the role keywords.

None
axes optional

Build the layout in place (see Layout).

None
spatial optional

Build the layout in place (see Layout).

None
sample optional

Build the layout in place (see Layout).

None
group optional

Build the layout in place (see Layout).

None

Returns:

Type Description
Labeled

Examples:

>>> import numpy as np
>>> data = labeled(np.zeros((40, 30, 500)), axes="zyx", spatial="yz")
>>> data.shape, data.layout.shape_of(data)[2]
((40, 30, 500), (30, 40))

frame_batches

frame_batches(data, *, ndim=None, layout=None, overhead=1.0, memory=None, batch=None, align=None, dtype=None, device=None, prefetch=None, contiguous=False)

Batches of samples (frames), one group at a time.

Note

Groups are visited one at a time. Within a group, the innermost (in storage) sample axes are taken whole while the budget allows; the next one is split into blocks (rounded down to a multiple of its storage chunk when at least that large) and the outer ones are iterated one index at a time. A warning is emitted when the read amplification over the group and sample axes is large.

Parameters:

Name Type Description Default
data array - like or Labeled

Source data.

required
ndim int

Without a layout: number of trailing spatial dims (default 2); the leading dims are samples ((*batch, frames, *spatial)).

None
layout Layout

Axis roles (default: that of a Labeled data, else Layout.default(data.ndim, ndim)).

None
overhead float

Number of chunk-sized temporaries the consumer holds (see chunk_length).

1.0
memory optional

Chunk budget in bytes, explicit frame count, and read-ahead depth (default: configuration).

None
batch optional

Chunk budget in bytes, explicit frame count, and read-ahead depth (default: configuration).

None
prefetch optional

Chunk budget in bytes, explicit frame count, and read-ahead depth (default: configuration).

None
align sequence of int

Storage chunks to align to (default: chunks_of(data)). Pass chunks_of(out) when writing to a chunked output.

None
dtype optional

Working backend.

None
device optional

Working backend.

None
contiguous bool

If True, every chunk is made dense (C-contiguous in layout order), e.g. for FFTs or convolutions, and that copy is counted in the budget (overhead + 1) whenever the layout permutes the axes. By default chunks are strided views of the loaded block: the only copy is the unavoidable one when sample axes that are not adjacent in storage are flattened (also counted in the budget).

False

Returns:

Type Description
Chunks

Yields Chunk items, unpacking as (index, data): data is (n, *spatial), the sample axes being flattened in storage order and the spatial axes in layout order. Write a result back with chunk.store(out, result).

row_tiles

row_tiles(data, *, ndim=None, layout=None, axis=-2, overhead=1.0, memory=None, batch=None, align=None, dtype=None, device=None, prefetch=None, contiguous=False)

Strips along one spatial axis holding all samples of one group.

Note

On a store chunked along samples, every tile touches every chunk; the read amplification is computed and a warning is emitted when it is large.

Parameters:

Name Type Description Default
data array - like or Labeled

Source data.

required
ndim int | None None
layout int | None None
axis int or str

Spatial axis along which strips are cut: a position among the spatial axes in layout order (negative allowed), or a name.

-2
overhead float

See frame_batches. With batch, a tile holds about as many elements as batch frames.

1.0
memory float

See frame_batches. With batch, a tile holds about as many elements as batch frames.

1.0
batch float

See frame_batches. With batch, a tile holds about as many elements as batch frames.

1.0
align float

See frame_batches. With batch, a tile holds about as many elements as batch frames.

1.0
dtype float

See frame_batches. With batch, a tile holds about as many elements as batch frames.

1.0
device float

See frame_batches. With batch, a tile holds about as many elements as batch frames.

1.0
prefetch float

See frame_batches. With batch, a tile holds about as many elements as batch frames.

1.0
contiguous float

See frame_batches. With batch, a tile holds about as many elements as batch frames.

1.0

Returns:

Type Description
Chunks

Yields Chunk items, unpacking as (index, data): data is (*sample, *spatial) (sample axes in storage order, not flattened; spatial axes in layout order, cut along axis). Store a per-pixel reduction with chunk.store(map, r, into="map").

blocks

blocks(data, block=None, halo=0, *, layout=None, pad=None, overhead=1.0, memory=None, batch=None, align=None, dtype=None, device=None, prefetch=None, contiguous=False)

nD blocks over the spatial axes, with a halo.

Note

Writing results back into data itself is wrong when halo > 0 (a block's halo would read already-processed neighbours).

Parameters:

Name Type Description Default
data array - like or Labeled

Source data.

required
block sequence of int or None

Core block size along each spatial axis (layout order); None entries mean the whole extent. Without a layout, the blocked dims are the trailing len(block) dims. If block is None, the blocked dims are the spatial axes of the layout, or without one the trailing len(halo) dims (all dims if halo is a scalar), and the size is chosen automatically: starting from the full extents, the largest dim is halved until prod(block + 2 * halo) * overhead fits the budget, then sizes are aligned to storage chunks. Group and sample axes are iterated one index at a time.

None
halo int or sequence of int

Halo width along each blocked dim.

0
layout Layout

Axis roles (default: that of a Labeled data, else as described above).

None
pad (None, reflect, replicate, zeros)

None: halos are clipped at the array boundary, so edge blocks are smaller and the algorithm applies its own boundary condition, as it would on the whole array. Otherwise every block has shape exactly block + 2 * halo, boundary halos and short trailing cores being filled by padding. Where reflection would need a pad at least as large as the loaded extent, replicate padding is used along that dim instead (with a warning at construction).

None
overhead float

See frame_batches. With batch, the budget is batch frames of the last two spatial axes.

1.0
memory float

See frame_batches. With batch, the budget is batch frames of the last two spatial axes.

1.0
batch float

See frame_batches. With batch, the budget is batch frames of the last two spatial axes.

1.0
align float

See frame_batches. With batch, the budget is batch frames of the last two spatial axes.

1.0
dtype float

See frame_batches. With batch, the budget is batch frames of the last two spatial axes.

1.0
device float

See frame_batches. With batch, the budget is batch frames of the last two spatial axes.

1.0
prefetch float

See frame_batches. With batch, the budget is batch frames of the last two spatial axes.

1.0
contiguous float

See frame_batches. With batch, the budget is batch frames of the last two spatial axes.

1.0

Returns:

Type Description
Chunks

Yields Chunk items, unpacking as (index, data, inner): data is core + halo with the spatial axes in layout order, data[inner] is the core, and index is where the core lives in data. chunk.store(out, result) crops and writes back.

group_frames

group_frames(data, layout=None, frame=0, *, dtype=None, device=None)

Load one frame of each group.

Parameters:

Name Type Description Default
data array - like or Labeled
required
layout Layout

Default: that of a labelled data, else (*samples, H, W).

None
frame int

Index of the frame in the flattened sample axes (storage order).

0

Yields:

Name Type Description
group tuple of int

Position along the group axes (layout order).

image Tensor

The frame, with its spatial axes in layout order. Only this frame is read.

chunk_length

chunk_length(item_shape, *, dtype, memory=None, batch=None, frame_shape=None, overhead=1.0, multiple=None, maximum=None)

How many items (frames, rows, ...) of item_shape fit the budget.

The budget is the size of one chunk on the working device, not the total memory used by the process.

Parameters:

Name Type Description Default
item_shape sequence of int

Shape of one item.

required
dtype dtype

Working dtype (sets the bytes per element).

required
memory int

Budget in bytes (default: configuration).

None
batch int

If set, the budget is batch * prod(frame_shape) elements instead (batch wins over memory).

None
frame_shape sequence of int

Shape of one frame (used with batch; default item_shape).

None
overhead float

Number of chunk-sized temporaries, in the working dtype, that the consumer holds, counting the chunk itself.

1.0
multiple int

Storage chunk length along the iterated axis: the result is rounded down to a multiple of it when it is at least that large.

None
maximum int

Upper bound (e.g. the length of the iterated axis).

None

Returns:

Type Description
int

Number of items, ≥ 1.

chunks_of

chunks_of(x)

Storage chunk shape of an array-like.

Parameters:

Name Type Description Default
x array - like
required

Returns:

Type Description
tuple of int or None

zarr .shards (if sharded) or .chunks, h5py .chunks, dask .chunksize; None for in-memory or contiguous arrays.

as_tensor

as_tensor(x, *, dtype=None, device=None, copy=False)

Materialise an (already sliced) array-like as a working tensor.

Note

Non-native byte order and non-contiguous / negatively strided arrays are normalised first. Data are moved to the device before the cast, so e.g. uint16 data cross the host-device link at half the size of float32. A tensor aliasing a read-only buffer (read-only memmap) is never returned: such data are copied.

Parameters:

Name Type Description Default
x array - like

Tensor, ndarray, memmap, or anything numpy.asarray accepts (calling it is what triggers zarr / h5py / dask I/O).

required
dtype optional

Working backend (see resolve_backend; the device follows a Tensor input when unset). Boolean, integer and floating data are cast to the working floating dtype, complex data to the complex dtype of matching precision.

None
device optional

Working backend (see resolve_backend; the device follows a Tensor input when unset). Boolean, integer and floating data are cast to the working floating dtype, complex data to the complex dtype of matching precision.

None
copy bool

If True, the result never shares memory with x.

False

Returns:

Type Description
Tensor

Raises:

Type Description
TypeError

For structured, object, string or datetime dtypes.

prepare_out

prepare_out(out, shape, *, like=None, dtype=None)

Validate a user out= or allocate an in-memory output.

Parameters:

Name Type Description Default
out writable array-like

User-provided output; must have exactly shape.

required
shape tuple of int

Required shape.

required
like object

Input data. A new output is allocated on the device of like if it is a Tensor, else on the CPU (a result the size of a memmap input must not land on the GPU).

None
dtype optional

Dtype of a new output (default: working dtype).

None

Returns:

Type Description
writable array-like

Raises:

Type Description
ValueError

If out does not have the required shape.

store

store(out, index, value)

Write a tensor into a region of a tensor / numpy / zarr output.

Note

Floating values written to an integer output are rounded and clamped to the output's range on the value's device, before the transfer (a raw cast wraps around); NaN becomes 0. Floating values of less than single precision (float16, bfloat16) are promoted to float32 first. Integer values written to a narrower integer output are clamped to its range in the same way, instead of wrapping around. Floating values written to a boolean output become value != 0. An output without a dtype receives the values as they are.

Parameters:

Name Type Description Default
out writable array-like

Destination.

required
index Index

Region of out to write.

required
value Tensor

Data, broadcastable to out[index].

required

flush

flush(out)

Call out.flush() if it exists (memmaps).

Parameters:

Name Type Description Default
out object
required

integer_range

integer_range(dtype)

(min, max) of an integer dtype (torch or numpy-like).