Skip to content

webknossos.dataset.mag_view

MagView

MagView(layer: Layer, mag: Mag, mag_path: LazyPath)

Bases: View

A view of a specific magnification level within a WEBKNOSSOS layer.

MagView provides access to volumetric data at a specific resolution/magnification level. It supports reading, writing, and processing operations on the underlying data, with coordinates automatically handled in the correct magnification space.

Key Features
  • Read/write volumetric data at specific magnification levels
  • Automatic coordinate transformation between Mag(1) and current magnification
  • Support for compressed and uncompressed data formats
  • Chunked processing for efficient memory usage
  • Downsampling and upsampling capabilities

Attributes:

  • layer (Layer) –

    The parent Layer object this magnification belongs to.

  • mag (Layer) –

    The magnification level (e.g., Mag(1), Mag(2), Mag(4), etc.).

  • info (Layer) –

    Information about array storage (chunk shape, compression, etc.).

  • path (Path) –

    Path to the data on disk.

  • bounding_box (NDBoundingBox) –

    The spatial extent of this magnification in Mag(1) coordinates.

Examples:

# Create a dataset with a segmentation layer
ds = Dataset("path/to/dataset", voxel_size=(1, 1, 1))
layer = ds.add_layer("segmentation", SEGMENTATION_CATEGORY)

# Add and work with magnification levels
mag1 = layer.add_mag(Mag(1))
mag2 = layer.add_mag(Mag(2))

# Write data at Mag(1)
mag1.write(data, absolute_offset=(100, 200, 300))

# Read data at Mag(2) - coordinates are in Mag(1) space
data = mag2.read(absolute_offset=(100, 200, 300), size=(512, 512, 512))

# Process data in chunks
def process_chunk(view: View) -> None:
    data = view.read()
    # Process data...
    view.write(processed_data)

mag1.for_each_chunk(process_chunk)
Notes
  • All offset/size parameters in read/write methods expect Mag(1) coordinates
  • Use get_view() to obtain restricted views of the data
  • Compressed data operations may have performance implications
  • When writing to segmentation layers, update largest_segment_id as needed
See Also
  • Layer: Parent container for magnification levels
  • View: Base class providing data access methods
  • Dataset: Root container for all layers

Do not use this constructor manually. Instead use webknossos.dataset.layer.Layer.get_mag().

bounding_box property

bounding_box: NDBoundingBox

Get the spatial extent of this magnification level in Mag(1) coordinates.

Returns:

  • NDBoundingBox ( NDBoundingBox ) –

    The bounding box of this magnification level in Mag(1) coordinates.

Notes
  • The bounding box is automatically aligned with the magnification level
  • It represents the overall extent of the data, potentially including empty regions

global_offset property

global_offset: Vec3Int

⚠️ Deprecated, use Vec3Int.zeros() instead.

header property

header: Header

⚠️ Deprecated, use info instead.

info property

info: ArrayInfo

Get information about the array structure and properties.

Returns:

  • ArrayInfo ( ArrayInfo ) –

    Object containing array metadata such as data type, num_channels, and other array-specific information.

Examples:

view = layer.get_mag("1").get_view(size=(100, 100, 10))
array_info = view.info
print(f"Data type: {array_info.data_type}")
print(f"Num channels: {array_info.num_channels}")

is_remote_to_dataset property

is_remote_to_dataset: bool

Check if this magnification's data is stored remotely on a server relative to the dataset.

Returns:

  • bool ( bool ) –

    True if data is stored in a different location than the parent dataset.

layer property

layer: Layer

Get the parent Layer object.

Returns:

  • Layer ( Layer ) –

    The Layer object that contains this magnification level.

Notes
  • The Layer provides context about data type, category, and overall properties
  • Used internally for coordinate transformations and data validation

mag property

mag: Mag

Gets the magnification level of this view.

The magnification level determines the resolution at which the data is accessed. A higher magnification number means lower resolution (e.g., mag 2 means every second voxel, mag 4 means every fourth voxel, etc.).

Returns:

  • Mag ( Mag ) –

    The magnification level of this view.

Examples:

view = layer.get_mag("1").get_view(size=(100, 100, 10))
print(f"Current magnification: {view.mag}")

name property

name: str

Get the name of this magnification level.

Returns:

  • str ( str ) –

    String representation of the magnification level (e.g., "1-1-1" for Mag(1)).

path property

path: Path

Get the path to this magnification level's data.

Returns:

  • Path ( Path ) –

    Path to the data files on disk.

Notes
  • Path may be local or remote depending on dataset configuration

read_only property

read_only: bool

Indicates whether this view is read-only.

When a view is read-only, write operations are not permitted. This property helps prevent accidental modifications to the dataset.

Returns:

  • bool ( bool ) –

    True if the view is read-only, False if write operations are allowed.

Examples:

view = layer.get_mag("1").get_view(size=(100, 100, 10))
if not view.read_only:
    view.write(data)
else:
    print("Cannot modify read-only view")

size property

size: VecInt

⚠️ Deprecated, use mag_view.bounding_box.in_mag(mag_view.mag).bottomright instead.

chunk

chunk(chunk_shape: VecIntLike, chunk_border_alignments: Optional[VecIntLike] = None, read_only: bool = False) -> Generator[View, None, None]

Generate a sequence of sub-views by chunking the current view.

Divides the view into smaller, regularly-sized chunks that can be processed independently. This is useful for parallel processing or when working with large datasets that don't fit in memory.

Parameters:

  • chunk_shape (VecIntLike) –

    Size of each chunk in Mag(1) coordinates.

  • chunk_border_alignments (Optional[VecIntLike], default: None ) –

    Alignment of chunk borders in Mag(1) coordinates. If None, aligns to (0, 0, 0). Defaults to None.

  • read_only (bool, default: False ) –

    Whether the generated chunks should be read-only. Defaults to False.

Yields:

  • View ( View ) –

    Sub-views representing each chunk of the original view.

Examples:

# let 'mag1' be a `MagView`
chunks = mag1.chunk(chunk_shape=(100, 100, 100), chunk_border_alignments=(50, 50, 50))

compress

compress(target_path: Optional[Union[str, Path]] = None, args: Optional[Namespace] = None, executor: Optional[Executor] = None) -> None

Compresses the files on disk.

Compresses the magnification level's data, either in-place or to a new location. Compression can reduce storage space but may impact read/write performance.

Parameters:

  • target_path (Optional[Union[str, Path]], default: None ) –

    Optional path to write compressed data. If None, compresses in-place.

  • args (Optional[Namespace], default: None ) –

    ⚠️ Deprecated. Use executor parameter instead.

  • executor (Optional[Executor], default: None ) –

    Optional executor for parallel compression.

Examples:

# Compress in-place
mag1.compress()
Notes
  • In-place compression requires local filesystem
  • Remote compression requires target_path
  • Compression is parallelized when executor is provided
  • Progress is displayed during compression
  • Compressed data may have slower read/write speeds

content_is_equal

content_is_equal(other: View, args: Optional[Namespace] = None, executor: Optional[Executor] = None) -> bool

Compare the content of this view with another view.

Performs a chunk-by-chunk comparison of the data in both views. This is more memory efficient than reading entire views at once for large datasets.

Parameters:

  • other (View) –

    The view to compare against.

  • args (Optional[Namespace], default: None ) –

    ⚠️ Deprecated. Arguments to pass to executor.

  • executor (Optional[Executor], default: None ) –

    Executor for parallel comparison. If None, compares sequentially. Defaults to None.

  • progress_desc (Optional[str]) –

    Description for progress bar. If None, no progress bar is shown. Defaults to None.

Returns:

  • bool ( bool ) –

    True if the content of both views is identical, False otherwise.

Examples:

# Compare views sequentially
if view1.content_is_equal(view2):
    print("Views are identical")
Note
  • Comparison is done chunk by chunk to manage memory usage
  • Views must have the same shape and data type
  • Returns False immediately if shapes or types don't match
  • Progress tracks total volume compared
  • Parallel execution can speed up comparison of large views

create classmethod

create(layer: Layer, mag: Mag, chunk_shape: Vec3Int, chunks_per_shard: Vec3Int, compression_mode: bool, path: Optional[LazyPath] = None) -> MagView

Do not use this constructor manually. Instead use webknossos.dataset.layer.Layer.add_mag().

for_each_chunk

for_each_chunk(func_per_chunk: Callable[[Tuple[View, int]], None], chunk_shape: Optional[Vec3IntLike] = None, executor: Optional[Executor] = None, progress_desc: Optional[str] = None, *, chunk_size: Optional[Vec3IntLike] = None) -> None

Process each chunk of the view with a given function.

Divides the view into chunks and applies a function to each chunk, optionally in parallel. This is useful for processing large datasets in manageable pieces, with optional progress tracking and parallel execution.

Parameters:

  • func_per_chunk (Callable[[Tuple[View, int]], None]) –

    Function to apply to each chunk. Takes a tuple of (chunk_view, chunk_index) as argument. The chunk_index can be used for progress tracking or logging.

  • chunk_shape (Optional[Vec3IntLike], default: None ) –

    Size of each chunk in Mag(1) coordinates. If None, uses one chunk per file based on the dataset's file dimensions. Defaults to None.

  • executor (Optional[Executor], default: None ) –

    Executor for parallel processing. If None, processes chunks sequentially. Defaults to None.

  • progress_desc (Optional[str], default: None ) –

    Description for progress bar. If None, no progress bar is shown. Defaults to None.

  • chunk_size (Optional[Vec3IntLike], default: None ) –

    ⚠️ Deprecated. Use chunk_shape instead. Defaults to None.

Examples:

from webknossos.utils import named_partial

# Define processing function
def process_chunk(args: Tuple[View, int], threshold: float) -> None:
    chunk_view, chunk_idx = args
    data = chunk_view.read()
    # Process data...
    chunk_view.write(processed_data)
    print(f"Processed chunk {chunk_idx}")

# Sequential processing with progress bar
view.for_each_chunk(
    named_partial(process_chunk, threshold=0.5),
    chunk_shape=(64, 64, 64),
    progress_desc="Processing chunks"
)
Note
  • Each chunk is processed independently, making this suitable for parallel execution
  • For non-read-only views, chunks must align with file boundaries
  • Progress tracking shows total volume processed
  • Memory usage depends on chunk_shape and parallel execution settings
  • When using an executor, ensure thread/process safety in func_per_chunk
  • The view's magnification affects the actual data resolution

for_zipped_chunks

for_zipped_chunks(func_per_chunk: Callable[[Tuple[View, View, int]], None], target_view: View, source_chunk_shape: Optional[Vec3IntLike] = None, target_chunk_shape: Optional[Vec3IntLike] = None, executor: Optional[Executor] = None, progress_desc: Optional[str] = None, *, source_chunk_size: Optional[Vec3IntLike] = None, target_chunk_size: Optional[Vec3IntLike] = None) -> None

Process paired chunks from source and target views simultaneously.

Chunks both the source (self) and target views, then applies a function to each corresponding pair of chunks. This is particularly useful for operations that transform data between views of different magnifications, like downsampling.

Parameters:

  • func_per_chunk (Callable[[Tuple[View, View, int]], None]) –

    Function to apply to each chunk pair. Takes (source_chunk, target_chunk, index) as arguments.

  • target_view (View) –

    The target view to write transformed data to.

  • source_chunk_shape (Optional[Vec3IntLike], default: None ) –

    Size of source chunks in Mag(1). If None, uses maximum of source and target file dimensions. Defaults to None.

  • target_chunk_shape (Optional[Vec3IntLike], default: None ) –

    Size of target chunks in Mag(1). If None, uses maximum of source and target file dimensions. Defaults to None.

  • executor (Optional[Executor], default: None ) –

    Executor for parallel processing. If None, processes chunks sequentially. Defaults to None.

  • progress_desc (Optional[str], default: None ) –

    Description for progress bar. If None, no progress bar is shown. Defaults to None.

  • source_chunk_size (Optional[Vec3IntLike], default: None ) –

    ⚠️ Deprecated. Use source_chunk_shape instead. Defaults to None.

  • target_chunk_size (Optional[Vec3IntLike], default: None ) –

    ⚠️ Deprecated. Use target_chunk_shape instead. Defaults to None.

Examples:

# Downsample data from Mag(1) to Mag(2)
def downsample_chunk(args: Tuple[View, View, int]) -> None:
    source_chunk, target_chunk, idx = args
    data = source_chunk.read()
    downsampled = downsample_data(data)  # Your downsampling function
    target_chunk.write(downsampled)
    print(f"Processed chunk pair {idx}")

# Process with default chunk sizes
mag1_view.for_zipped_chunks(
    downsample_chunk,
    mag2_view,
    progress_desc="Downsampling data"
)
Note
  • Source/target view size ratios must match chunk size ratios
  • Target chunks must align with file boundaries to avoid concurrent writes
  • Both views are chunked with matching strides
  • Progress tracks total volume processed
  • Memory usage depends on chunk sizes and parallel execution

get_bounding_boxes_on_disk

get_bounding_boxes_on_disk() -> Iterator[NDBoundingBox]

Returns a Mag(1) bounding box for each file on disk.

This method iterates through the actual files stored on disk and returns their bounding boxes. This is different from the layer's bounding box property, which represents the overall extent of the data, potentially including regions without actual data files.

Returns:

  • Iterator[NDBoundingBox]

    Iterator[NDBoundingBox]: Iterator yielding bounding boxes in Mag(1) coordinates.

Examples:

# Print all data file bounding boxes
for bbox in mag1.get_bounding_boxes_on_disk():
    print(f"Found data file at {bbox}")

# Calculate total data volume
total_volume = sum(bbox.volume() for bbox in mag1.get_bounding_boxes_on_disk())
Notes
  • Bounding boxes are in Mag(1) coordinates
  • Some storage formats may not support efficient listing
  • For unsupported formats, falls back to chunk-based iteration
  • Useful for understanding actual data distribution on disk

get_buffered_slice_reader

get_buffered_slice_reader(offset: Optional[Vec3IntLike] = None, size: Optional[Vec3IntLike] = None, buffer_size: int = 32, dimension: int = 2, *, relative_bounding_box: Optional[NDBoundingBox] = None, absolute_bounding_box: Optional[NDBoundingBox] = None, use_logging: bool = False) -> BufferedSliceReader

Get a buffered reader for efficiently reading data slices.

Creates a BufferedSliceReader that allows efficient reading of data slices by buffering multiple slices in memory. This is particularly useful when reading large datasets slice by slice.

Parameters:

  • offset (Optional[Vec3IntLike], default: None ) –

    Starting position for reading in the dataset. Defaults to None.

  • size (Optional[Vec3IntLike], default: None ) –

    Size of the region to read in voxels. Defaults to None.

  • buffer_size (int, default: 32 ) –

    Number of slices to buffer in memory at once. Defaults to 32.

  • dimension (int, default: 2 ) –

    Axis along which to read slices (0=x, 1=y, 2=z). Defaults to 2 (z-axis).

  • relative_bounding_box (Optional[NDBoundingBox], default: None ) –

    Bounding box in mag1 coordinates, relative to the current view's offset. Mutually exclusive with absolute_bounding_box. Defaults to None.

  • absolute_bounding_box (Optional[NDBoundingBox], default: None ) –

    Bounding box in mag1 coordinates in absolute dataset coordinates. Mutually exclusive with relative_bounding_box. Defaults to None.

  • use_logging (bool, default: False ) –

    Whether to enable logging of read operations.

Returns:

  • BufferedSliceReader ( BufferedSliceReader ) –

    A reader object that yields data slices.

Examples:

view = layer.get_mag("1").get_view(size=(100, 100, 10))

# Create a reader with default settings (z-slices)
with view.get_buffered_slice_reader() as reader:
    for slice_data in reader:
        process_slice(slice_data)

# Read y-slices with custom buffer size
with view.get_buffered_slice_reader(
    buffer_size=10,
    dimension=1,  # y-axis
    relative_offset=(10, 0, 0)
) as reader:
Note
  • Larger buffer sizes improve performance but use more memory
  • Choose dimension based on your data access pattern
  • Only one positioning parameter should be specified
  • The reader can be used as an iterator

get_buffered_slice_writer

get_buffered_slice_writer(offset: Optional[Vec3IntLike] = None, buffer_size: int = 32, dimension: int = 2, json_update_allowed: bool = True, *, relative_offset: Optional[Vec3IntLike] = None, absolute_offset: Optional[Vec3IntLike] = None, relative_bounding_box: Optional[NDBoundingBox] = None, absolute_bounding_box: Optional[NDBoundingBox] = None, use_logging: bool = False) -> BufferedSliceWriter

Get a buffered writer for efficiently writing data slices.

Creates a BufferedSliceWriter that allows efficient writing of data slices by buffering multiple slices before performing the actual write operation.

Args: offset (Optional[Vec3IntLike]): Starting position for writing in the dataset. Defaults to None. buffer_size (int): Number of slices to buffer before performing a write. Defaults to 32. dimension (int): Axis along which to write slices (0=x, 1=y, 2=z). Defaults to 2 (z-axis). json_update_allowed (bool): Whether to allow updating the bounding box and datasource-properties.json. Should be False for parallel access. Defaults to True. relative_offset (Optional[Vec3IntLike]): Offset in mag1 coordinates, relative to the current view's position. Mutually exclusive with absolute_offset. Defaults to None. absolute_offset (Optional[Vec3IntLike]): Offset in mag1 coordinates in absolute dataset coordinates. Mutually exclusive with relative_offset. Defaults to None. relative_bounding_box (Optional[NDBoundingBox]): Bounding box in mag1 coordinates, relative to the current view's offset. Mutually exclusive with absolute_bounding_box. Defaults to None. absolute_bounding_box (Optional[NDBoundingBox]): Bounding box in mag1 coordinates in absolute dataset coordinates. Mutually exclusive with relative_bounding_box. Defaults to None. use_logging (bool): Whether to enable logging of write operations. Defaults to False.

Returns:

  • BufferedSliceWriter ( BufferedSliceWriter ) –

    A writer object for buffered slice writing.

Examples:

view = layer.get_mag("1").get_view(size=(100, 100, 10))

# Create a buffered writer with default settings
with view.get_buffered_slice_writer() as writer:
    # Write slices efficiently
    for z in range(10):
        slice_data = np.zeros((100, 100))  # Your slice data
        writer.send(slice_data)

# Create a writer with custom buffer size and offset
with view.get_buffered_slice_writer(
    buffer_size=5,
    relative_offset=(10, 10, 0)
)
Note
  • Larger buffer sizes can improve performance but use more memory
  • Remember to use the writer in a context manager
  • Only one positioning parameter should be specified

get_dtype

get_dtype() -> dtype

Returns the dtype per channel of the data. For example uint8.

get_view

get_view(offset: Optional[Vec3IntLike] = None, size: Optional[Vec3IntLike] = None, *, relative_offset: Optional[Vec3IntLike] = None, absolute_offset: Optional[Vec3IntLike] = None, relative_bounding_box: Optional[NDBoundingBox] = None, absolute_bounding_box: Optional[NDBoundingBox] = None, read_only: Optional[bool] = None) -> View

Get a restricted view of this magnification level.

Creates a new View object that represents a subset of this magnification level's data. The view can be used to read/write data within its bounds. All offset and bounding box coordinates are expected to be in Mag(1) space, regardless of the current magnification level.

Parameters:

  • offset (Optional[Vec3IntLike], default: None ) –

    ⚠️ Deprecated. Use relative_offset or absolute_offset instead.

  • size (Optional[Vec3IntLike], default: None ) –

    Size of region to view. In Mag(1) coordinates unless used with deprecated offset.

  • relative_offset (Optional[Vec3IntLike], default: None ) –

    Optional offset relative to the view's position in Mag(1) coordinates.

  • absolute_offset (Optional[Vec3IntLike], default: None ) –

    Optional absolute position in Mag(1) coordinates.

  • relative_bounding_box (Optional[NDBoundingBox], default: None ) –

    Optional bounding box relative to view's position in Mag(1) coordinates.

  • absolute_bounding_box (Optional[NDBoundingBox], default: None ) –

    Optional absolute bounding box in Mag(1) coordinates.

  • read_only (Optional[bool], default: None ) –

    If True, the view will be read-only. If None, determined by context.

Returns:

  • View ( View ) –

    A new View object representing the specified region.

Examples:

# Get view at absolute position
view = mag1.get_view(absolute_offset=(100, 200, 300), size=(512, 512, 512))
data = view.read()  # Read from the view
view.write(data)    # Write to the view

# Get view using bounding box
bbox = BoundingBox((0, 0, 0), (100, 100, 100))
view = mag2.get_view(absolute_bounding_box=bbox)
Notes
  • Views are lightweight objects that don't copy data
  • Read-only views prevent accidental data modification
  • Views can be used for efficient parallel processing
  • Coordinates are automatically scaled based on magnification

get_views_on_disk

get_views_on_disk(read_only: Optional[bool] = None) -> Iterator[View]

Yields a view for each file on disk for efficient parallelization.

Creates View objects that correspond to actual data files on disk. This is particularly useful for parallel processing as each view represents a natural unit of data storage.

Parameters:

  • read_only (Optional[bool], default: None ) –

    If True, returned views will be read-only. If None, determined by context.

Returns:

  • Iterator[View]

    Iterator[View]: Iterator yielding View objects for each data file.

Examples:

# Process each data file in parallel
def process_chunk(view: View) -> None:
    data = view.read()
    # Process data...
    if not view.read_only:
        view.write(processed_data)

with get_executor_for_args(None) as executor:
    executor.map(process_chunk, mag1.get_views_on_disk())
Notes
  • Views correspond to actual files/chunks on disk
  • Ideal for parallel processing of large datasets
  • Each view's bounding box aligns with storage boundaries
  • Memory efficient as only one chunk is loaded at a time

get_zarr_array

get_zarr_array() -> TensorStore

Get direct access to the underlying Zarr array.

Provides direct access to the underlying Zarr array for advanced operations. Only available for Zarr-based datasets.

Returns:

  • NDArrayLike ( TensorStore ) –

    The underlying Zarr array object.

Raises:

  • ValueError

    If called on a non-Zarr dataset.

Notes
  • Only works with Zarr-based datasets
  • Provides low-level access to data storage
  • Use with caution as it bypasses normal access patterns

map_chunk

map_chunk(func_per_chunk: Callable[[View], Any], chunk_shape: Optional[Vec3IntLike] = None, executor: Optional[Executor] = None, progress_desc: Optional[str] = None) -> List[Any]

Process each chunk of the view and collect results.

Similar to for_each_chunk(), but collects and returns the results from each chunk. Useful for parallel data analysis or feature extraction where results need to be aggregated.

Parameters:

  • func_per_chunk (Callable[[View], Any]) –

    Function to apply to each chunk. Takes a chunk view as argument and returns a result of any type.

  • chunk_shape (Optional[Vec3IntLike], default: None ) –

    Size of each chunk in Mag(1) coordinates. If None, uses one chunk per file based on the dataset's file dimensions. Defaults to None.

  • executor (Optional[Executor], default: None ) –

    Executor for parallel processing. If None, processes chunks sequentially. Defaults to None.

  • progress_desc (Optional[str], default: None ) –

    Description for progress bar. If None, no progress bar is shown. Defaults to None.

Returns:

  • List[Any]

    List[Any]: List of results from processing each chunk, in chunk order.

Examples:

from webknossos.utils import named_partial

# Calculate statistics per chunk
def chunk_statistics(view: View, min_value: float) -> Dict[str, float]:
    data = view.read()
    return {
        "mean": data[data > min_value].mean(),
        "std": data[data > min_value].std(),
        "volume": view.bounding_box.volume()
    }

# Sequential processing
stats = view.map_chunk(
    named_partial(chunk_statistics, min_value=0.1),
    chunk_shape=(128, 128, 128)
)

# Aggregate results
total_volume = sum(s["volume"] for s in stats)
mean_values = [s["mean"] for s in stats]
Note
  • Results are collected in memory, consider memory usage for large datasets
  • Each chunk is processed independently, suitable for parallel execution
  • For non-read-only views, chunks must align with file boundaries
  • When using an executor, ensure thread/process safety in func_per_chunk
  • Results maintain chunk order regardless of execution order

merge_chunk

merge_chunk(args: Tuple[MagView, NDBoundingBox, List[NDBoundingBox]]) -> None

Merge a single chunk during parallel merge operations.

Internal method used by merge_with_view() for parallel processing. Merges data from another view into this one for a specific chunk region.

Parameters:

  • args (Tuple[MagView, NDBoundingBox, List[NDBoundingBox]]) –

    Tuple containing: - other (MagView): Source view to merge from - shard (NDBoundingBox): Target shard region - bboxes (List[NDBoundingBox]): List of source bounding boxes

merge_with_view

merge_with_view(other: MagView, executor: Executor) -> None

Merges data from another view into this one.

Combines data from another MagView into this one, using this view's data as the base and overlaying the other view's data where present. This is particularly useful for merging annotations or overlays.

Parameters:

  • other (MagView) –

    The MagView to merge into this one.

  • executor (Executor) –

    Executor for parallel merging operations.

Notes
  • Both views must have same magnification
  • Other view must have file_len = 1
  • Both views must have same voxel type
  • Merging is parallelized using the provided executor
  • Updates layer bounding box if necessary

read

read(offset: Optional[Vec3IntLike] = None, size: Optional[Vec3IntLike] = None, *, relative_offset: Optional[Vec3IntLike] = None, absolute_offset: Optional[Vec3IntLike] = None, relative_bounding_box: Optional[NDBoundingBox] = None, absolute_bounding_box: Optional[NDBoundingBox] = None) -> ndarray

Read volumetric data from the magnification level.

This method reads data from the dataset at the specified location. All offset and bounding box coordinates are expected to be in Mag(1) space, regardless of the current magnification level.

Parameters:

  • offset (Optional[Vec3IntLike], default: None ) –

    ⚠️ Deprecated. Use relative_offset or absolute_offset instead.

  • size (Optional[Vec3IntLike], default: None ) –

    Size of region to read. In Mag(1) coordinates unless used with deprecated offset.

  • relative_offset (Optional[Vec3IntLike], default: None ) –

    Optional offset relative to the view's position in Mag(1) coordinates.

  • absolute_offset (Optional[Vec3IntLike], default: None ) –

    Optional absolute position in Mag(1) coordinates.

  • relative_bounding_box (Optional[NDBoundingBox], default: None ) –

    Optional bounding box relative to view's position in Mag(1) coordinates.

  • absolute_bounding_box (Optional[NDBoundingBox], default: None ) –

    Optional absolute bounding box in Mag(1) coordinates.

Returns:

  • ndarray

    np.ndarray: The volumetric data as a numpy array.

Examples:

# Read data at absolute position
data = mag1.read(absolute_offset=(100, 200, 300), size=(512, 512, 512))

# Read using bounding box
bbox = BoundingBox((0, 0, 0), (100, 100, 100))
data = mag2.read(absolute_bounding_box=bbox)
Notes
  • At least one of offset/bounding_box parameters must be provided
  • Coordinates are automatically scaled based on magnification
  • For compressed data, reading includes decompression time
  • Large reads may temporarily increase memory usage

read_bbox

read_bbox(bounding_box: Optional[BoundingBox] = None) -> ndarray

⚠️ Deprecated. Please use read() with relative_bounding_box or absolute_bounding_box in Mag(1) instead. The user can specify the bounding_box in the current mag of the requested data. See read() for more details.

read_xyz

read_xyz(relative_bounding_box: Optional[NDBoundingBox] = None, absolute_bounding_box: Optional[NDBoundingBox] = None) -> ndarray

Read n-dimensional data and convert it to 3D XYZ format.

This method is designed for handling n-dimensional data (n > 3) and converting it to strictly 3D data ordered as (X, Y, Z). It is primarily used internally by operations that require 3D data like downsampling, upsampling, and compression.

When provided with a BoundingBox where additional dimensions (beyond X, Y, Z) have a shape of 1, it returns an array containing only the 3D spatial data. This ensures compatibility with operations that expect purely 3-dimensional input.

Parameters:

  • relative_bounding_box (Optional[NDBoundingBox], default: None ) –

    Bounding box relative to view's position in Mag(1) coordinates. Defaults to None.

  • absolute_bounding_box (Optional[NDBoundingBox], default: None ) –

    Absolute bounding box in Mag(1) coordinates. Defaults to None.

Returns:

  • ndarray

    np.ndarray: The requested data as a numpy array with dimensions ordered as (channels, X, Y, Z) for multi-channel data or (X, Y, Z) for single-channel data. Areas outside the dataset are zero-padded.

Examples:

# Read entire view's data in XYZ order
view = layer.get_mag("1").get_view(size=(100, 100, 10))
xyz_data = view.read_xyz()  # Returns (X, Y, Z) array

# Read with relative bounding box
bbox = NDBoundingBox((10, 10, 0), (50, 50, 10), axis=("x", "y", "z"), index=(1, 2, 3))
xyz_data = view.read_xyz(relative_bounding_box=bbox)
Note
  • If no bounding box is provided, reads the entire view's region
  • Only one bounding box parameter should be specified
  • The returned array's axes are ordered differently from read()
  • All coordinates are in Mag(1)

write

write(data: ndarray, offset: Optional[Vec3IntLike] = None, json_update_allowed: bool = True, *, relative_offset: Optional[Vec3IntLike] = None, absolute_offset: Optional[Vec3IntLike] = None, relative_bounding_box: Optional[NDBoundingBox] = None, absolute_bounding_box: Optional[NDBoundingBox] = None) -> None

Write volumetric data to the magnification level.

This method writes numpy array data to the dataset at the specified location. All offset and bounding box coordinates are expected to be in Mag(1) space, regardless of the current magnification level.

Parameters:

  • data (ndarray) –

    Numpy array containing the volumetric data to write. Shape must match the target region.

  • offset (Optional[Vec3IntLike], default: None ) –

    ⚠️ Deprecated. Use relative_offset or absolute_offset instead.

  • json_update_allowed (bool, default: True ) –

    If True, allows updating the layer's bounding box if the write extends beyond it.

  • relative_offset (Optional[Vec3IntLike], default: None ) –

    Optional offset relative to the view's position in Mag(1) coordinates.

  • absolute_offset (Optional[Vec3IntLike], default: None ) –

    Optional absolute position in Mag(1) coordinates.

  • relative_bounding_box (Optional[NDBoundingBox], default: None ) –

    Optional bounding box relative to view's position in Mag(1) coordinates.

  • absolute_bounding_box (Optional[NDBoundingBox], default: None ) –

    Optional absolute bounding box in Mag(1) coordinates.

Examples:

# Write data at absolute position
mag1.write(data, absolute_offset=(100, 200, 300))

# Write using bounding box
bbox = BoundingBox((0, 0, 0), (100, 100, 100))
mag2.write(data, absolute_bounding_box=bbox)
Notes
  • At least one of offset/bounding_box parameters must be provided
  • Data shape must match the target region size
  • Coordinates are automatically scaled based on magnification
  • For compressed data, writing may be slower due to compression
  • Large writes may temporarily increase memory usage