API Reference¶
MLArray Module¶
mlarray.mlarray.MLArray ¶
MLArray(array: Optional[Union[ndarray, str, Path]] = None, *, axes: Optional[Sequence[Union[Axis, str, Mapping]]] = None, spaces: Optional[Sequence[Union[Space, Mapping]]] = None, values: Optional[Union[Values, Mapping]] = None, profiles: Optional[Mapping] = None, user: Optional[Mapping] = None, source: Optional[Sequence[Union[SourceEntry, Mapping]]] = None, spacing: Optional[Sequence[float]] = None, origin: Optional[Sequence[float]] = None, direction: Optional[Any] = None, space: Optional[Union[str, Mapping, Space]] = None, meta: Optional[Union[Meta, Mapping]] = None, copy: Optional[MLArray] = None, copy_source: bool = False, patch_size: Optional[Union[int, List, Tuple]] = 'default', chunk_size: Optional[Union[int, List, Tuple]] = None, block_size: Optional[Union[int, List, Tuple]] = None, cparams: Optional[Union[Dict, CParams]] = None, dparams: Optional[Union[Dict, DParams]] = None, compressed: bool = True)
Bases: MLArrayConstructors
Create an MLArray from an array, or load a ".mla" file.
The MLArray file format (".mla") is a Blosc2-compressed array with
explicit, domain-neutral metadata (spec docs/design/spec.md).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
array
|
Optional[Union[ndarray, str, Path]]
|
A NumPy array, or the path of a ".mla" file to load. None creates an instance without array data. |
None
|
axes
|
Optional[Sequence[Union[Axis, str, Mapping]]]
|
One entry per array axis, in array order: names ( |
None
|
spaces
|
Optional[Sequence[Union[Space, Mapping]]]
|
Coordinate systems with their from-array transform
(:class: |
None
|
values
|
Optional[Union[Values, Mapping]]
|
What the numbers mean (:class: |
None
|
profiles
|
Optional[Mapping]
|
Domain metadata by profile name, e.g. |
None
|
user
|
Optional[Mapping]
|
Arbitrary user metadata; never interpreted. |
None
|
source
|
Optional[Sequence[Union[SourceEntry, Mapping]]]
|
Original metadata of converted files (read-only afterwards). |
None
|
spacing, origin, direction
|
Convenience geometry, composed into the
from-array matrix of |
required | |
space
|
Optional[Union[str, Mapping, Space]]
|
The space the convenience geometry lives in: a preset
( |
None
|
meta
|
Optional[Union[Meta, Mapping]]
|
Complete metadata (:class: |
None
|
copy
|
Optional[MLArray]
|
Another MLArray to take metadata from: axes, spaces, values,
profiles and user, but not its history, its |
None
|
copy_source
|
bool
|
Also copy the |
False
|
patch_size
|
Optional[Union[int, List, Tuple]]
|
Patch size hint for
chunk/block optimization. Use |
'default'
|
chunk_size
|
Optional[Union[int, List, Tuple]]
|
Explicit chunk size.
Cannot be combined with an explicit |
None
|
block_size
|
Optional[Union[int, List, Tuple]]
|
Explicit block size.
Cannot be combined with an explicit |
None
|
cparams
|
Optional[Union[Dict, CParams]]
|
Blosc2 compression parameters used when creating in-memory compressed array data. |
None
|
dparams
|
Optional[Union[Dict, DParams]]
|
Blosc2 decompression parameters used for chunk access. |
None
|
compressed
|
bool
|
Keep the data Blosc2-compressed in memory (default) or as a NumPy array. |
True
|
axes
property
writable
¶
axes: Tuple[Axis, ...]
The array axes, in array order. Assign a new list to replace them (validated).
direction
property
¶
direction: Optional[ndarray]
Unit vector of each mapped array axis in the default space (rows: space axes), or None.
dtype
property
¶
dtype
Returns the dtype of the array.
Returns:
| Type | Description |
|---|---|
|
np.dtype: Dtype of the underlying array, or None if no array is loaded. |
history
property
¶
history: Tuple[Mapping, ...]
Conversions and operations applied to this image (append with meta.add_history).
origin
property
¶
origin: Optional[Tuple[float, ...]]
Default-space coordinates of the centre of index (0, ..., 0), or None.
profiles
property
writable
¶
profiles: Dict[str, Dict[str, Any]]
Domain metadata by profile name (plain dicts, validated when written).
shape
property
¶
shape
Returns the shape of the array.
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
Shape of the underlying array, or None if no array is loaded. |
source
property
¶
source: Tuple[SourceEntry, ...]
Original metadata of the converted file(s); read-only, loaded on first access.
spaces
property
writable
¶
spaces: Tuple[Space, ...]
Coordinate systems the array is placed in; the first is the default.
spacing
property
¶
spacing: Optional[Tuple[float, ...]]
Voxel spacing along each mapped array axis of the default space (array order), or None.
user
property
writable
¶
user: Dict[str, Any]
Arbitrary user metadata; loaded from the file on first access.
arange
classmethod
¶
arange(start: Union[int, float], stop: Optional[Union[int, float]] = None, step: Optional[Union[int, float]] = 1, dtype: dtype = None, shape: Optional[Union[int, List, Tuple, ndarray]] = None, c_order: bool = True, meta: Optional[Union[Meta, Mapping]] = None, patch_size: Optional[Union[int, List, Tuple]] = None, chunk_size: Optional[Union[int, List, Tuple]] = None, block_size: Optional[Union[int, List, Tuple]] = None, cparams: Optional[Union[Dict, CParams]] = None, dparams: Optional[Union[Dict, DParams]] = None, compressed: bool = True)
Create an in-memory MLArray with evenly spaced values.
Behavior mirrors :func:blosc2.arange while also applying MLArray
metadata and chunk/block optimization settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
Union[int, float]
|
Start of interval. If |
required |
stop
|
Optional[Union[int, float]]
|
End of interval (exclusive). |
None
|
step
|
Optional[Union[int, float]]
|
Spacing between values. |
1
|
dtype
|
dtype
|
Output dtype. If None, inferred similarly to
|
None
|
shape
|
Optional[Union[int, List, Tuple, ndarray]]
|
Target output shape. If None, shape is inferred from start/stop/step. |
None
|
c_order
|
bool
|
Store in C order (row-major) if True. |
True
|
meta
|
Optional[Union[Meta, Mapping]]
|
Metadata of the created
|
None
|
patch_size
|
Optional[Union[int, List, Tuple]]
|
Patch size hint for chunk/block optimization. Defaults to None for this method. |
None
|
chunk_size
|
Optional[Union[int, List, Tuple]]
|
Explicit chunk size. |
None
|
block_size
|
Optional[Union[int, List, Tuple]]
|
Explicit block size. |
None
|
cparams
|
Optional[Union[Dict, CParams]]
|
Blosc2 compression parameters. |
None
|
dparams
|
Optional[Union[Dict, DParams]]
|
Blosc2 decompression parameters. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
MLArray |
A newly created in-memory MLArray instance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
asarray
classmethod
¶
asarray(array: Union[ndarray], meta: Optional[Union[Meta, Mapping]] = None, patch_size: Optional[Union[int, List, Tuple]] = 'default', chunk_size: Optional[Union[int, List, Tuple]] = None, block_size: Optional[Union[int, List, Tuple]] = None, cparams: Optional[Union[Dict, CParams]] = None, dparams: Optional[Union[Dict, DParams]] = None, compressed: bool = True)
Convert a NumPy array into an in-memory Blosc2-backed MLArray.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
array
|
Union[ndarray]
|
Input array to convert to MLArray. |
required |
meta
|
Optional[Union[Meta, Mapping]]
|
Metadata of the created
|
None
|
patch_size
|
Optional[Union[int, List, Tuple]]
|
Patch size hint for chunk/block optimization. Provide an int for isotropic sizes or a list/tuple with length equal to the number of dimensions. Use "default" to use the default patch size of 192. |
'default'
|
chunk_size
|
Optional[Union[int, List, Tuple]]
|
Explicit chunk size.
Provide an int or a tuple/list with length equal to the number
of dimensions, or None to let Blosc2 decide. Cannot be combined with an
explicit |
None
|
block_size
|
Optional[Union[int, List, Tuple]]
|
Explicit block size.
Provide an int or a tuple/list with length equal to the number
of dimensions, or None to let Blosc2 decide. Cannot be combined with an
explicit |
None
|
cparams
|
Optional[Union[Dict, CParams]]
|
Blosc2
compression parameters used when creating the in-memory Blosc2
container (for example codec, compression level, and filters).
Controls how data is compressed when stored. If None, defaults
to |
None
|
dparams
|
Optional[Union[Dict, DParams]]
|
Blosc2
decompression parameters used when
accessing compressed chunks (for example number of
decompression threads). Controls runtime decompression behavior.
If None, defaults to |
None
|
compressed
|
bool
|
If True (default), the data is compressed into
an in-memory Blosc2 array, which is a copy. If False, the
MLArray wraps |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
MLArray |
A newly created MLArray instance. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
RuntimeError
|
If patch/chunk/block arguments are inconsistent. |
NotImplementedError
|
If automatic patch optimization is not implemented for the provided dimensionality. |
close ¶
close()
Flush metadata and close the underlying store.
After closing, the MLArray instance no longer has an attached array.
comp_blosc2_params
classmethod
¶
comp_blosc2_params(image_size: Tuple[int, ...], patch_size: Tuple[int, ...], spatial_axis_mask: Optional[list[bool]] = None, bytes_per_pixel: int = 4, max_block_nbytes: int = _layout.DEFAULT_MAX_BLOCK_NBYTES, max_chunk_nbytes: int = _layout.DEFAULT_MAX_CHUNK_NBYTES)
Compute recommended Blosc2 chunk and block sizes from a patch-size hint.
Uses nnU-Net's layout heuristic, generalized to any number of spatial
and non-spatial axes (:func:mlarray.blosc2_layout_strategies.comp_blosc2_params):
1. Non-spatial axes (channels, time, ...) get chunk and block
size 1, so reading one channel touches only its own data.
2. Blocks start at the next power of two of the patch size per
spatial axis and are halved until they fit ``max_block_nbytes``
(128 KiB).
3. Chunks grow by whole blocks on the least covered spatial axis
until they reach ``max_chunk_nbytes`` (6 MiB), the image extent,
or 1.5x the patch size per axis.
For 2 and 3 spatial axes the layout is identical to nnU-Net's.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_size
|
Tuple[int, ...]
|
Full array shape. |
required |
patch_size
|
Tuple[int, ...]
|
Patch size over spatial axes only.
A 1 keeps that axis at chunk size 1 (e.g. |
required |
spatial_axis_mask
|
Optional[list[bool]]
|
Mask indicating for every array axis whether it is spatial. If omitted, all axes are treated as spatial. |
None
|
bytes_per_pixel
|
int
|
Number of bytes per element. Defaults to 4 for float32. |
4
|
max_block_nbytes
|
int
|
Largest block in bytes. |
DEFAULT_MAX_BLOCK_NBYTES
|
max_chunk_nbytes
|
int
|
Largest chunk in bytes. |
DEFAULT_MAX_CHUNK_NBYTES
|
Returns:
| Type | Description |
|---|---|
|
Tuple[List[int], List[int]]: Recommended chunk size and block size. |
compress ¶
compress(patch_size: Optional[Union[int, List, Tuple]] = 'default', chunk_size: Optional[Union[int, List, Tuple]] = None, block_size: Optional[Union[int, List, Tuple]] = None, cparams: Optional[Union[Dict, CParams]] = None, dparams: Optional[Union[Dict, DParams]] = None) -> None
Compress this MLArray in-place using the Blosc2 backend.
The instance is detached from any previously opened file state and
becomes an in-memory object. Persist changes by calling save().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
patch_size
|
Optional[Union[int, List, Tuple]]
|
Patch size hint for
chunk/block optimization. Use |
'default'
|
chunk_size
|
Optional[Union[int, List, Tuple]]
|
Explicit chunk size.
Cannot be combined with an explicit |
None
|
block_size
|
Optional[Union[int, List, Tuple]]
|
Explicit block size.
Cannot be combined with an explicit |
None
|
cparams
|
Optional[Union[Dict, CParams]]
|
Blosc2 compression parameters. |
None
|
dparams
|
Optional[Union[Dict, DParams]]
|
Blosc2 decompression parameters. |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If no array data is loaded. |
create
classmethod
¶
create(filepath: Union[str, Path], shape: Union[List, Tuple, ndarray], dtype: dtype, meta: Optional[Union[Meta, Mapping]] = None, mode: str = 'w', mmap_mode: str = 'w+', patch_size: Optional[Union[int, List, Tuple]] = 'default', chunk_size: Optional[Union[int, List, Tuple]] = None, block_size: Optional[Union[int, List, Tuple]] = None, cparams: Optional[Union[Dict, CParams]] = None, dparams: Optional[Union[Dict, DParams]] = None)
Create a new MLArray file with memory mapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
Union[str, Path]
|
Target file path. Must end with ".mla". |
required |
shape
|
Union[List, Tuple, ndarray]
|
Shape of the array to create. If provided, a new file is created. Length must match the full array dimensionality (including non-spatial axes if present). |
required |
dtype
|
dtype
|
Numpy dtype for a newly created array. |
required |
meta
|
Optional[Union[Meta, Mapping]]
|
Metadata of the created
|
None
|
mode
|
str
|
Controls storage open/creation permissions when using standard Blosc2 I/O (read-only, read/write, overwrite). Does not affect lazy loading or decompression; data is accessed and decompressed on demand by Blosc2. Must be 'w' (default). Leave at default if unsure. |
'w'
|
mmap_mode
|
str
|
Controls access via OS-level memory mapping of the compressed data, including read/write permissions.
Changes how bytes are fetched from disk (paging rather than explicit reads), while chunks are still decompressed on demand by Blosc2.
Overrides |
'w+'
|
patch_size
|
Optional[Union[int, List, Tuple]]
|
Patch size hint for chunk/block optimization. Provide an int for isotropic sizes or a list/tuple with length equal to the number of spatial dimensions. Use "default" to use the default patch size of 192. |
'default'
|
chunk_size
|
Optional[Union[int, List, Tuple]]
|
Explicit chunk size.
Provide an int or tuple/list with length equal to the array
dimensions. Cannot be combined with an explicit |
None
|
block_size
|
Optional[Union[int, List, Tuple]]
|
Explicit block size.
Provide an int or tuple/list with length equal to the array
dimensions. Cannot be combined with an explicit |
None
|
cparams
|
Optional[Union[Dict, CParams]]
|
Blosc2
compression parameters used when
creating/writing array data (for example codec, compression
level, and filters). Controls how data is compressed when
stored. If None, defaults to |
None
|
dparams
|
Optional[Union[Dict, DParams]]
|
Blosc2
decompression parameters used when
reading/accessing compressed chunks (for example number of
decompression threads). Controls runtime decompression behavior.
If None, defaults to |
None
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the file extension is invalid or if mode/mmap_mode is invalid for creation. |
decompress ¶
decompress() -> None
Decompress this MLArray in-place to a NumPy-backed array.
The instance is detached from any previously opened file state and
becomes an in-memory object. Persist changes by calling save().
meta.storage keeps the layout record (patch, chunk and block
size, compression), as load(compressed=False) does, so a later
save() or compress() reuses it.
Raises:
| Type | Description |
|---|---|
TypeError
|
If no array data is loaded. |
empty
classmethod
¶
empty(shape: Union[int, List, Tuple, ndarray], dtype: dtype = None, meta: Optional[Union[Meta, Mapping]] = None, patch_size: Optional[Union[int, List, Tuple]] = 'default', chunk_size: Optional[Union[int, List, Tuple]] = None, block_size: Optional[Union[int, List, Tuple]] = None, cparams: Optional[Union[Dict, CParams]] = None, dparams: Optional[Union[Dict, DParams]] = None, compressed: bool = True)
Create an in-memory MLArray with uninitialized values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
Union[int, List, Tuple, ndarray]
|
Shape of the output array. |
required |
dtype
|
dtype
|
Numpy dtype for the output array. If None, uses
|
None
|
meta
|
Optional[Union[Meta, Mapping]]
|
Metadata of the created
|
None
|
patch_size
|
Optional[Union[int, List, Tuple]]
|
Patch size hint for
chunk/block optimization. Use |
'default'
|
chunk_size
|
Optional[Union[int, List, Tuple]]
|
Explicit chunk size.
Cannot be combined with an explicit |
None
|
block_size
|
Optional[Union[int, List, Tuple]]
|
Explicit block size.
Cannot be combined with an explicit |
None
|
cparams
|
Optional[Union[Dict, CParams]]
|
Blosc2 compression parameters used when writing chunks. |
None
|
dparams
|
Optional[Union[Dict, DParams]]
|
Blosc2 decompression parameters used when reading chunks. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
MLArray |
A newly created in-memory MLArray instance. |
empty_like
classmethod
¶
empty_like(x, dtype: dtype = None, meta: Optional[Union[Meta, Mapping]] = None, patch_size: Optional[Union[int, List, Tuple]] = 'default', chunk_size: Optional[Union[int, List, Tuple]] = None, block_size: Optional[Union[int, List, Tuple]] = None, cparams: Optional[Union[Dict, CParams]] = None, dparams: Optional[Union[Dict, DParams]] = None, compressed: bool = True)
Create an in-memory MLArray with the same shape as x.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Source object. Can be an |
required | |
dtype
|
dtype
|
Output dtype. If None, inferred from |
None
|
meta
|
Optional[Union[Meta, Mapping]]
|
Metadata of the created
|
None
|
patch_size
|
Optional[Union[int, List, Tuple]]
|
Patch size hint for chunk/block optimization. |
'default'
|
chunk_size
|
Optional[Union[int, List, Tuple]]
|
Explicit chunk size. |
None
|
block_size
|
Optional[Union[int, List, Tuple]]
|
Explicit block size. |
None
|
cparams
|
Optional[Union[Dict, CParams]]
|
Blosc2 compression parameters. |
None
|
dparams
|
Optional[Union[Dict, DParams]]
|
Blosc2 decompression parameters. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
MLArray |
A newly created in-memory MLArray instance. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
fingerprint ¶
fingerprint() -> Dict[str, Any]
Fingerprint of the array and its geometry (spec 6.3), as written into source entries.
flush ¶
flush()
Write pending metadata changes to the opened file.
Array data written through a writable memory map is persisted by
Blosc2 directly; metadata changes are only written on flush() or
close(). Does nothing for read-only or in-memory arrays.
full
classmethod
¶
full(shape: Union[int, List, Tuple, ndarray], fill_value: Union[bytes, int, float, bool], dtype: dtype = None, meta: Optional[Union[Meta, Mapping]] = None, patch_size: Optional[Union[int, List, Tuple]] = 'default', chunk_size: Optional[Union[int, List, Tuple]] = None, block_size: Optional[Union[int, List, Tuple]] = None, cparams: Optional[Union[Dict, CParams]] = None, dparams: Optional[Union[Dict, DParams]] = None, compressed: bool = True)
Create an in-memory MLArray filled with fill_value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
Union[int, List, Tuple, ndarray]
|
Shape of the output array. |
required |
fill_value
|
Union[bytes, int, float, bool]
|
Fill value used for all elements in the output. |
required |
dtype
|
dtype
|
Numpy dtype for the output array. If None, inferred
from |
None
|
meta
|
Optional[Union[Meta, Mapping]]
|
Metadata of the created
|
None
|
patch_size
|
Optional[Union[int, List, Tuple]]
|
Patch size hint for chunk/block optimization. |
'default'
|
chunk_size
|
Optional[Union[int, List, Tuple]]
|
Explicit chunk size.
Cannot be combined with an explicit |
None
|
block_size
|
Optional[Union[int, List, Tuple]]
|
Explicit block size.
Cannot be combined with an explicit |
None
|
cparams
|
Optional[Union[Dict, CParams]]
|
Blosc2 compression parameters. |
None
|
dparams
|
Optional[Union[Dict, DParams]]
|
Blosc2 decompression parameters. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
MLArray |
A newly created in-memory MLArray instance. |
full_like
classmethod
¶
full_like(x, fill_value: Union[bool, int, float, complex], dtype: dtype = None, meta: Optional[Union[Meta, Mapping]] = None, patch_size: Optional[Union[int, List, Tuple]] = 'default', chunk_size: Optional[Union[int, List, Tuple]] = None, block_size: Optional[Union[int, List, Tuple]] = None, cparams: Optional[Union[Dict, CParams]] = None, dparams: Optional[Union[Dict, DParams]] = None, compressed: bool = True)
Create an in-memory MLArray filled with fill_value and shape of x.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Source object. Can be an |
required | |
fill_value
|
Union[bool, int, float, complex]
|
Fill value used for all elements in the output. |
required |
dtype
|
dtype
|
Output dtype. If None, inferred from |
None
|
meta
|
Optional[Union[Meta, Mapping]]
|
Metadata of the created
|
None
|
patch_size
|
Optional[Union[int, List, Tuple]]
|
Patch size hint for chunk/block optimization. |
'default'
|
chunk_size
|
Optional[Union[int, List, Tuple]]
|
Explicit chunk size. |
None
|
block_size
|
Optional[Union[int, List, Tuple]]
|
Explicit block size. |
None
|
cparams
|
Optional[Union[Dict, CParams]]
|
Blosc2 compression parameters. |
None
|
dparams
|
Optional[Union[Dict, DParams]]
|
Blosc2 decompression parameters. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
MLArray |
A newly created in-memory MLArray instance. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
letter_codes ¶
letter_codes(space: Optional[str] = None) -> Tuple[str, ...]
Display letters: the direction each mapped array axis increases toward, e.g. ("S", "P", "L").
linspace
classmethod
¶
linspace(start: Union[int, float, complex], stop: Union[int, float, complex], num: Optional[int] = None, dtype: dtype = None, endpoint: bool = True, shape: Optional[Union[int, List, Tuple, ndarray]] = None, c_order: bool = True, meta: Optional[Union[Meta, Mapping]] = None, patch_size: Optional[Union[int, List, Tuple]] = None, chunk_size: Optional[Union[int, List, Tuple]] = None, block_size: Optional[Union[int, List, Tuple]] = None, cparams: Optional[Union[Dict, CParams]] = None, dparams: Optional[Union[Dict, DParams]] = None, compressed: bool = True)
Create an in-memory MLArray with evenly spaced samples.
Behavior mirrors :func:blosc2.linspace while also applying MLArray
metadata and chunk/block optimization settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
Union[int, float, complex]
|
Start value of the sequence. |
required |
stop
|
Union[int, float, complex]
|
End value of the sequence. |
required |
num
|
Optional[int]
|
Number of samples. Required when |
None
|
dtype
|
dtype
|
Output dtype. If None, inferred similarly to
|
None
|
endpoint
|
bool
|
Whether |
True
|
shape
|
Optional[Union[int, List, Tuple, ndarray]]
|
Target output
shape. If None, inferred from |
None
|
c_order
|
bool
|
Store in C order (row-major) if True. |
True
|
meta
|
Optional[Union[Meta, Mapping]]
|
Metadata of the created
|
None
|
patch_size
|
Optional[Union[int, List, Tuple]]
|
Patch size hint for chunk/block optimization. Defaults to None for this method. |
None
|
chunk_size
|
Optional[Union[int, List, Tuple]]
|
Explicit chunk size. |
None
|
block_size
|
Optional[Union[int, List, Tuple]]
|
Explicit block size. |
None
|
cparams
|
Optional[Union[Dict, CParams]]
|
Blosc2 compression parameters. |
None
|
dparams
|
Optional[Union[Dict, DParams]]
|
Blosc2 decompression parameters. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
MLArray |
A newly created in-memory MLArray instance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If neither |
load
classmethod
¶
load(filepath: Union[str, Path], dparams: Optional[Union[Dict, DParams]] = None, compressed: bool = True)
Load a MLArray file as a whole without memory mapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
Union[str, Path]
|
Path to the MLArray file to be loaded. The filepath needs to have the extension ".mla". |
required |
dparams
|
Optional[Union[Dict, DParams]]
|
Blosc2
decompression parameters used when loading/accessing compressed
chunks. If None, defaults to |
None
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the file extension is not ".mla". |
matrix ¶
matrix(space: Optional[str] = None) -> np.ndarray
Homogeneous from-array matrix of a space (default: the first one).
Rows are the space axes (+1), columns the space's from_array.array_axes
(+ translation). An integer index is the centre of its voxel.
ones
classmethod
¶
ones(shape: Union[int, List, Tuple, ndarray], dtype: dtype = None, meta: Optional[Union[Meta, Mapping]] = None, patch_size: Optional[Union[int, List, Tuple]] = 'default', chunk_size: Optional[Union[int, List, Tuple]] = None, block_size: Optional[Union[int, List, Tuple]] = None, cparams: Optional[Union[Dict, CParams]] = None, dparams: Optional[Union[Dict, DParams]] = None, compressed: bool = True)
Create an in-memory MLArray filled with ones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
Union[int, List, Tuple, ndarray]
|
Shape of the output array. |
required |
dtype
|
dtype
|
Numpy dtype for the output array. If None, uses
|
None
|
meta
|
Optional[Union[Meta, Mapping]]
|
Metadata of the created
|
None
|
patch_size
|
Optional[Union[int, List, Tuple]]
|
Patch size hint for chunk/block optimization. |
'default'
|
chunk_size
|
Optional[Union[int, List, Tuple]]
|
Explicit chunk size.
Cannot be combined with an explicit |
None
|
block_size
|
Optional[Union[int, List, Tuple]]
|
Explicit block size.
Cannot be combined with an explicit |
None
|
cparams
|
Optional[Union[Dict, CParams]]
|
Blosc2 compression parameters. |
None
|
dparams
|
Optional[Union[Dict, DParams]]
|
Blosc2 decompression parameters. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
MLArray |
A newly created in-memory MLArray instance. |
ones_like
classmethod
¶
ones_like(x, dtype: dtype = None, meta: Optional[Union[Meta, Mapping]] = None, patch_size: Optional[Union[int, List, Tuple]] = 'default', chunk_size: Optional[Union[int, List, Tuple]] = None, block_size: Optional[Union[int, List, Tuple]] = None, cparams: Optional[Union[Dict, CParams]] = None, dparams: Optional[Union[Dict, DParams]] = None, compressed: bool = True)
Create an in-memory MLArray of ones with the same shape as x.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Source object. Can be an |
required | |
dtype
|
dtype
|
Output dtype. If None, inferred from |
None
|
meta
|
Optional[Union[Meta, Mapping]]
|
Metadata of the created
|
None
|
patch_size
|
Optional[Union[int, List, Tuple]]
|
Patch size hint for chunk/block optimization. |
'default'
|
chunk_size
|
Optional[Union[int, List, Tuple]]
|
Explicit chunk size. |
None
|
block_size
|
Optional[Union[int, List, Tuple]]
|
Explicit block size. |
None
|
cparams
|
Optional[Union[Dict, CParams]]
|
Blosc2 compression parameters. |
None
|
dparams
|
Optional[Union[Dict, DParams]]
|
Blosc2 decompression parameters. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
MLArray |
A newly created in-memory MLArray instance. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
open
classmethod
¶
open(filepath: Union[str, Path], mode: str = 'r', mmap_mode: str = 'r', dparams: Optional[Union[Dict, DParams]] = None)
Open an existing MLArray file with memory mapping.
The first open in a process turns on blosc2's read-ahead with 4
threads, which makes reads of data not in the page cache several
times faster; see :func:mlarray.set_read_ahead to change or turn it
off.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
Union[str, Path]
|
Target file path. Must end with ".mla". |
required |
mode
|
str
|
Controls storage open/creation permissions when using standard Blosc2 I/O (read-only, read/write, overwrite). Does not affect lazy loading or decompression; data is accessed and decompressed on demand by Blosc2. Must be either 'r' (default) or 'a'. Leave at default if unsure. |
'r'
|
mmap_mode
|
str
|
Controls access via OS-level memory mapping of the compressed data, including read/write permissions.
Changes how bytes are fetched from disk (paging rather than explicit reads), while chunks are still decompressed on demand by Blosc2.
Overrides |
'r'
|
dparams
|
Optional[Union[Dict, DParams]]
|
Blosc2
decompression parameters used when
reading/accessing compressed chunks (for example number of
decompression threads). Controls runtime decompression behavior.
If None, defaults to |
None
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the file extension is invalid or if mode/mmap_mode is invalid for opening. |
save ¶
save(filepath: Union[str, Path])
Save the array to a MLArray file.
The file is written to a temporary file next to the target and then atomically moved into place, so an existing target is only replaced once the new file is complete. The source file of an opened MLArray is never modified. If an opened MLArray is saved to its own file, it is reopened afterwards with the same mode and mmap_mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
Union[str, Path]
|
Path to save the file. Must end with ".mla". |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the file extension is not ".mla". |
set_geometry ¶
set_geometry(spacing: Optional[Sequence[float]] = None, origin: Optional[Sequence[float]] = None, direction: Optional[Any] = None, space: Optional[Union[str, Mapping, Space]] = None) -> None
Set a space from spacing, origin and direction (see the constructor).
space defaults to the current default space. If the space exists,
values not given are kept, e.g. set_geometry(spacing=[1, 1, 2])
changes only the spacing. The space becomes the first (default) one.
space ¶
space(name: Optional[str] = None) -> Optional[Space]
A space by name; without a name the default (first) space, or None if there is none.
to_numpy ¶
to_numpy()
Return the underlying data as a NumPy array.
Returns:
| Type | Description |
|---|---|
|
np.ndarray: A NumPy view or copy of the stored array data. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If no array data is loaded. |
zeros
classmethod
¶
zeros(shape: Union[int, List, Tuple, ndarray], dtype: dtype = None, meta: Optional[Union[Meta, Mapping]] = None, patch_size: Optional[Union[int, List, Tuple]] = 'default', chunk_size: Optional[Union[int, List, Tuple]] = None, block_size: Optional[Union[int, List, Tuple]] = None, cparams: Optional[Union[Dict, CParams]] = None, dparams: Optional[Union[Dict, DParams]] = None, compressed: bool = True)
Create an in-memory MLArray filled with zeros.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
Union[int, List, Tuple, ndarray]
|
Shape of the output array. |
required |
dtype
|
dtype
|
Numpy dtype for the output array. If None, uses
|
None
|
meta
|
Optional[Union[Meta, Mapping]]
|
Metadata of the created
|
None
|
patch_size
|
Optional[Union[int, List, Tuple]]
|
Patch size hint for chunk/block optimization. |
'default'
|
chunk_size
|
Optional[Union[int, List, Tuple]]
|
Explicit chunk size.
Cannot be combined with an explicit |
None
|
block_size
|
Optional[Union[int, List, Tuple]]
|
Explicit block size.
Cannot be combined with an explicit |
None
|
cparams
|
Optional[Union[Dict, CParams]]
|
Blosc2 compression parameters. |
None
|
dparams
|
Optional[Union[Dict, DParams]]
|
Blosc2 decompression parameters. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
MLArray |
A newly created in-memory MLArray instance. |
zeros_like
classmethod
¶
zeros_like(x, dtype: dtype = None, meta: Optional[Union[Meta, Mapping]] = None, patch_size: Optional[Union[int, List, Tuple]] = 'default', chunk_size: Optional[Union[int, List, Tuple]] = None, block_size: Optional[Union[int, List, Tuple]] = None, cparams: Optional[Union[Dict, CParams]] = None, dparams: Optional[Union[Dict, DParams]] = None, compressed: bool = True)
Create an in-memory MLArray of zeros with the same shape as x.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Source object. Can be an |
required | |
dtype
|
dtype
|
Output dtype. If None, inferred from |
None
|
meta
|
Optional[Union[Meta, Mapping]]
|
Metadata of the created
|
None
|
patch_size
|
Optional[Union[int, List, Tuple]]
|
Patch size hint for chunk/block optimization. |
'default'
|
chunk_size
|
Optional[Union[int, List, Tuple]]
|
Explicit chunk size. |
None
|
block_size
|
Optional[Union[int, List, Tuple]]
|
Explicit block size. |
None
|
cparams
|
Optional[Union[Dict, CParams]]
|
Blosc2 compression parameters. |
None
|
dparams
|
Optional[Union[Dict, DParams]]
|
Blosc2 decompression parameters. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
MLArray |
A newly created in-memory MLArray instance. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
mlarray.mlarray.set_read_ahead ¶
set_read_ahead(nthreads: int = MLARRAY_DEFAULT_READ_AHEAD) -> int
Set blosc2's read-ahead for this process (blosc2.set_prefetch).
With read-ahead, reading a slice of an on-disk array fetches the chunks it
needs with nthreads background threads in parallel, instead of one
small request after another. For data that is not in the page cache this
makes patch reads several times faster, most on network storage (in our
benchmark with 12 nnU-Net-style loader processes on network storage, 3D
patches took 64-82% less time). For data already in the page cache it can
cost a little (up to about 17% per read with a single reader).
MLArray turns it on with MLARRAY_DEFAULT_READ_AHEAD (4) threads the
first time a file is opened, unless this function was called before or
the BLOSC_PREFETCH environment variable is set. The setting applies to
the whole process, including other blosc2 arrays it reads; each reader
thread gets its own read-ahead threads. Call set_read_ahead(0) to turn
it off. Without read-ahead support in the installed blosc2 this does
nothing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nthreads
|
int
|
Read-ahead threads per slice being read; 0 turns read-ahead off. |
MLARRAY_DEFAULT_READ_AHEAD
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The previous number of read-ahead threads (0 if unsupported). |
Layout Module¶
mlarray.blosc2_layout_strategies.comp_blosc2_params ¶
comp_blosc2_params(image_size: Sequence[int], patch_size: Sequence[int], spatial_axis_mask: Optional[Sequence[bool]] = None, bytes_per_pixel: int = 4, max_block_nbytes: int = DEFAULT_MAX_BLOCK_NBYTES, max_chunk_nbytes: int = DEFAULT_MAX_CHUNK_NBYTES, max_chunk_to_patch_ratio_per_axis: Optional[float] = DEFAULT_MAX_CHUNK_TO_PATCH_RATIO, grow_singleton_patch_axes: bool = False) -> tuple[list[int], list[int]]
Chunk and block sizes for patch-wise reading (nnU-Net's heuristic).
- Non-spatial axes (channels, time, ...) get chunk and block size 1, so reading one channel touches only its own data.
- Blocks start at the next power of two of the patch per spatial axis and
are halved on the axis most over-represented relative to its target
extent until they fit
max_block_nbytes. - Chunks grow by whole blocks on the least covered spatial axis until
max_chunk_nbytes, the image extent, ormax_chunk_to_patch_ratio_per_axistimes the patch per axis. - A patch entry of 1 (e.g.
(1, 256, 256)for 2D slices of a 3D image) keeps that axis at 1 unlessgrow_singleton_patch_axesis set.
For 2 and 3 spatial axes the result equals nnU-Net's comp_blosc2_params
(2D images as (1, y, x)); any other number of spatial axes follows the
same rules.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_size
|
Sequence[int]
|
Full array shape. |
required |
patch_size
|
Sequence[int]
|
Patch size over the spatial axes (one entry per spatial axis). |
required |
spatial_axis_mask
|
Optional[Sequence[bool]]
|
For every array axis whether it is spatial. All axes are spatial if omitted. |
None
|
bytes_per_pixel
|
int
|
Bytes per array element. |
4
|
max_block_nbytes
|
int
|
Largest block in bytes. |
DEFAULT_MAX_BLOCK_NBYTES
|
max_chunk_nbytes
|
int
|
Largest chunk in bytes. |
DEFAULT_MAX_CHUNK_NBYTES
|
max_chunk_to_patch_ratio_per_axis
|
Optional[float]
|
Largest chunk extent per axis relative to the patch, or None for no limit. |
DEFAULT_MAX_CHUNK_TO_PATCH_RATIO
|
grow_singleton_patch_axes
|
bool
|
Let axes with patch size 1 grow in chunks. |
False
|
Returns:
| Type | Description |
|---|---|
tuple[list[int], list[int]]
|
Chunk size and block size per array axis. |
mlarray.blosc2_layout_strategies.select_blosc2_filter ¶
select_blosc2_filter(arr: ndarray, chunk_size: Sequence[int], block_size: Sequence[int], codec: Codec = DEFAULT_CODEC, clevel: int = DEFAULT_CLEVEL) -> blosc2.Filter
nnU-Net's per-array filter choice: NOFILTER or SHUFFLE, whichever compresses a centered, chunk-sized slab better. Ties and failures give NOFILTER.
The better filter depends on the data: interpolated (resampled) intensities favour SHUFFLE, quantized (not resampled) ones NOFILTER.
Metadata Module¶
mlarray.metadata.Meta ¶
Meta(axes: Optional[Sequence[Union[Axis, str, Mapping]]] = None, spaces: Optional[Sequence[Union[Space, Mapping]]] = None, values: Optional[Union[Values, Mapping]] = None, profiles: Optional[Mapping] = None, history: Optional[Sequence[Mapping]] = None, storage: Optional[Union[Storage, Mapping]] = None, source: Optional[Sequence[Union[SourceEntry, Mapping]]] = None, user: Optional[Mapping] = None, version: str = SPEC_VERSION, writer: Optional[str] = None, unknown: Optional[Mapping] = None, shape: Optional[Sequence[int]] = None)
All metadata of an MLArray: core, profiles, history, storage, source and user.
Core parts are replaced as a whole (meta.axes = [...]); each change is
validated against the array shape and leaves the metadata unchanged when it
fails. profiles and user are plain dicts that can be edited in place;
profiles are validated whenever the metadata is validated or written.
source is read-only.
history
property
¶
history: Tuple[Mapping, ...]
Append-only history of conversions and operations (read-only view).
shape
property
¶
shape: Optional[Tuple[int, ...]]
Shape of the array the metadata describes (None without an array).
source
property
¶
source: Tuple[SourceEntry, ...]
Original metadata of the converted file(s); read-only, decoded on first access.
user
property
writable
¶
user: Dict[str, Any]
Arbitrary user metadata, never interpreted; decoded on first access.
add_history ¶
add_history(action: str, **fields: Any) -> None
Append a history entry; time defaults to now (UTC).
copy ¶
copy(source: bool = True) -> 'Meta'
Deep copy that shares no mutable state with this metadata.
from_dict
classmethod
¶
from_dict(data: Mapping, shape: Optional[Sequence[int]] = None, source: Optional[_Lazy] = None, user: Optional[_Lazy] = None) -> 'Meta'
Build metadata from the plain content of the mlarray key.
source and user entries in data (the format of
to_dict(include_lazy=True)) are accepted too.
to_dict ¶
to_dict(include_lazy: bool = False) -> Dict[str, Any]
Plain content of the mlarray key (plus source/user with include_lazy).
update ¶
update(**parts: Any) -> None
Replace several core parts at once, validated together (all or nothing).
Accepts axes, spaces, values, profiles and storage.
mlarray.metadata.Axis
dataclass
¶
Axis(name: str, type: str = 'space', labels: Optional[Tuple[str, ...]] = None, start: Optional[float] = None, step: Optional[float] = None, coordinates: Optional[Tuple[float, ...]] = None, unit: Optional[str] = None, unit_code: Optional[str] = None, unknown: Mapping = FrozenMap())
One array axis (spec 4.2). name is a name only, never a direction.
mlarray.metadata.Space
dataclass
¶
Space(name: str, axes: Tuple[SpaceAxis, ...], from_array: FromArray, reference: Optional[Mapping] = None, unknown: Mapping = FrozenMap())
A named coordinate system and how the array sits in it (spec 4.3).
direction
property
¶
direction: ndarray
Unit vector of each mapped array axis in the space (rows: space axes, columns: array axes).
For sheared grids the columns are not orthogonal; they are still unit vectors.
spacing
property
¶
spacing: Tuple[float, ...]
Distance between neighbouring voxel centres along each mapped array axis.
letter_codes ¶
letter_codes() -> Tuple[str, ...]
Display letters: the direction each mapped array axis increases toward.
For each array axis, the space axis its column points along most, with
the sign applied: e.g. ("S", "P", "L") for a (z, y, x) array in the
DICOM patient frame. "?" when the space axis has no known
increases_toward. Letters are derived for display and never stored.
matrix ¶
matrix() -> np.ndarray
Homogeneous from-array matrix (float64 copy). Columns follow from_array.array_axes.
same_frame ¶
same_frame(other: 'Space') -> bool
True when both spaces name the same physical frame (equal reference scheme and id).
mlarray.metadata.SpaceAxis
dataclass
¶
SpaceAxis(name: str, unit: Optional[str] = None, unit_code: Optional[str] = None, increases_toward: Optional[str] = None, unknown: Mapping = FrozenMap())
One axis of a space: its name, unit and the direction its coordinate grows.
mlarray.metadata.FromArray
dataclass
¶
FromArray(array_axes: Tuple[str, ...], matrix: Optional[Tuple[Tuple[float, ...], ...]] = None, scale: Optional[Tuple[float, ...]] = None, translation: Optional[Tuple[float, ...]] = None, profile_mapping: Optional[Mapping] = None, unknown: Mapping = FrozenMap())
How array indices map into a space (spec 4.3).
Either matrix (homogeneous, rows: space axes + 1, columns: array_axes
+ translation) or the axis-aligned shorthand scale + translation.
An integer index is the centre of its voxel.
mlarray.metadata.Values
dataclass
¶
Values(kind: str = 'measurement', unit: Optional[str] = None, unit_code: Optional[str] = None, scale: Optional[float] = None, offset: Optional[float] = None, fill: Optional[Union[int, float]] = None, labels: Optional[Mapping] = None, label_layout: Optional[str] = None, unknown: Mapping = FrozenMap())
What the stored numbers mean (spec 4.4). Replaces v0's is_seg.
without_label_semantics ¶
without_label_semantics() -> 'Values'
These values with labels, label layout and label kinds removed.
mlarray.metadata.Storage
dataclass
¶
Storage(chunk_size: Optional[Tuple[int, ...]] = None, block_size: Optional[Tuple[int, ...]] = None, patch_size: Optional[Tuple[int, ...]] = None, compression: Optional[Mapping] = None, unknown: Mapping = FrozenMap())
Portable blosc2 layout of the file (spec 8). Never thread counts or other runtime settings.
to_cparams ¶
to_cparams(nthreads: Optional[int] = None)
The recorded compression as blosc2.CParams.
nthreads is a runtime choice and never stored; it defaults to
MLArray's 4 compression threads.
mlarray.metadata.SourceEntry
dataclass
¶
SourceEntry(format: str, header: Mapping = FrozenMap(), format_version: Optional[str] = None, files: Tuple[str, ...] = (), reader: Optional[Mapping] = None, index_map: Optional[Mapping] = None, fingerprint: Optional[Mapping] = None, unknown: Mapping = FrozenMap())
Original metadata of one converted source (spec 6). Read-only.
mlarray.metadata.space_from_geometry ¶
space_from_geometry(space: Union[str, Mapping, 'Space'], array_axes: Sequence[str], spacing: Optional[Sequence[float]] = None, origin: Optional[Sequence[float]] = None, direction: Optional[Any] = None) -> Space
Build a space from spacing, origin and direction.
All three follow the array axes array_axes (array order):
spacing[c]: distance between neighbouring voxel centres along array axisc;direction[:, c]: unit vector of array axiscin the space (rows: space axes);origin: space coordinates of the centre of index(0, ..., 0).
The matrix is [[direction * spacing, origin], [0, ..., 0, 1]].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
space
|
Union[str, Mapping, 'Space']
|
A preset name ( |
required |
mlarray.metadata.MetadataError ¶
Bases: ValueError
Metadata violates the MLArray specification.
Fingerprint Module¶
mlarray.fingerprint.compute ¶
compute(array, meta) -> Dict[str, Any]
Fingerprint of array (anything with shape, dtype and slicing) and its meta.
mlarray.fingerprint.matches ¶
matches(fingerprint: Optional[Mapping], array, meta) -> bool
True when fingerprint still describes array and its geometry.
Shape, dtype and geometry are compared first, so the data is only hashed when they agree.
Units Module¶
mlarray.units.unit_code ¶
unit_code(unit: Optional[str]) -> Optional[str]
UCUM code of a curated unit name, or None for free-text or missing units.