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
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
( |
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
( |
()
|
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 |
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 |
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 |
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 |
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
|
See |
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). |
data |
Tensor
|
Loaded data, owned by the consumer; a strided view in layout
order unless the iterator was built with |
inner |
Index or None
|
Crop of |
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 |
sample_shape |
tuple of int
|
Shape of |
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 |
required |
result
|
Tensor
|
Shaped like |
required |
into
|
(source, map, samples)
|
|
"source"
|
ArrayLike
Bases: Protocol
Anything with .shape and basic __getitem__.
Tensor, ndarray, memmap, zarr.Array, h5py.Dataset, dask array.
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 |
required |
layout
|
Layout
|
The layout. Mutually exclusive with the role keywords. |
None
|
axes
|
optional
|
Build the layout in place (see |
None
|
spatial
|
optional
|
Build the layout in place (see |
None
|
sample
|
optional
|
Build the layout in place (see |
None
|
group
|
optional
|
Build the layout in place (see |
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 ( |
None
|
layout
|
Layout
|
Axis roles (default: that of a |
None
|
overhead
|
float
|
Number of chunk-sized temporaries the consumer holds (see
|
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: |
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 ( |
False
|
Returns:
| Type | Description |
|---|---|
Chunks
|
Yields |
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
|
See |
None
|
layout
|
int | None
|
See |
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 |
1.0
|
memory
|
float
|
See |
1.0
|
batch
|
float
|
See |
1.0
|
align
|
float
|
See |
1.0
|
dtype
|
float
|
See |
1.0
|
device
|
float
|
See |
1.0
|
prefetch
|
float
|
See |
1.0
|
contiguous
|
float
|
See |
1.0
|
Returns:
| Type | Description |
|---|---|
Chunks
|
Yields |
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
|
halo
|
int or sequence of int
|
Halo width along each blocked dim. |
0
|
layout
|
Layout
|
Axis roles (default: that of a |
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
|
None
|
overhead
|
float
|
See |
1.0
|
memory
|
float
|
See |
1.0
|
batch
|
float
|
See |
1.0
|
align
|
float
|
See |
1.0
|
dtype
|
float
|
See |
1.0
|
device
|
float
|
See |
1.0
|
prefetch
|
float
|
See |
1.0
|
contiguous
|
float
|
See |
1.0
|
Returns:
| Type | Description |
|---|---|
Chunks
|
Yields |
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 |
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 |
None
|
frame_shape
|
sequence of int
|
Shape of one frame (used with |
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 |
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 |
required |
dtype
|
optional
|
Working backend (see |
None
|
device
|
optional
|
Working backend (see |
None
|
copy
|
bool
|
If True, the result never shares memory with |
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 |
required |
shape
|
tuple of int
|
Required shape. |
required |
like
|
object
|
Input data. A new output is allocated on the device of |
None
|
dtype
|
optional
|
Dtype of a new output (default: working dtype). |
None
|
Returns:
| Type | Description |
|---|---|
writable array-like
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
value
|
Tensor
|
Data, broadcastable to |
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).