nima_io.read#

Microscopy Data Reader for nima_io Library.

This module provides a set of functions to read microscopy data files, leveraging the bioformats library and custom processing for metadata and pixel data.

For detailed function documentation and usage, refer to the Sphinx-generated documentation.

Functions:

start_loci([version, java_memory, debug_level])

Initialize the loci package and associated classes.

ensure_jvm()

Start java VM and initialize logger (globally) or Attach running JVM.

read(filepath)

Read metadata and data using bioformats and scyjava.

read_pims(filepath)

Read metadata and initialize Bioformats reader using the pims library.

stitch(core, wr[, c, t, z])

Stitch image tiles returning a tiled single plane.

diff(fp_a, fp_b)

Diff for two image data.

first_nonzero_reverse(llist)

Return the index of the last nonzero element in a list.

get_md_dict(ome_store[, log_fp])

Parse xml_md and return parsed md dictionary and md status dictionary.

convert_field(field)

Convert a JavaField to a Python data type, optionally including its unit symbol.

next_tuple(llist, *, increment_last)

Generate the next tuple in lexicographical order.

retrieve_values(ome_store, key, npar)

Retrieve values for the given key and number of parameters from the OMEStore.

group_metadata(res)

Tidy up by grouping common metadata.

get_allvalues_grouped(ome_store, key, npar)

Retrieve and group metadata values for a given key.

Classes:

JavaFieldUnit(*args, **kwargs)

Protocol for JavaField's unit representation.

JavaField(*args, **kwargs)

Protocol for JavaField.

StagePosition(x, y, z)

Dataclass representing stage position.

VoxelSize(x, y, z)

Dataclass representing voxel size.

CoreMetadata(rdr[, size_x, size_y, size_c, ...])

Dataclass representing core metadata.

Metadata(core, full, log_miss)

Dataclass representing all metadata.

ImageReaderWrapper(rdr)

Wrapper class for Bioformats image reader.

Exceptions:

MultiplePositionsError(message)

Exception raised when a series contains multiple stage positions.

StopExceptionError

Exception raised when need to stop.

nima_io.read.start_loci(version='7.3.0', java_memory='4g', debug_level='INFO')#

Initialize the loci package and associated classes.

This function starts the Java Virtual Machine (JVM), configures endpoints, and initializes global variables for the loci package and related classes.

Return type:

None

Global Variables#

loci: JPackage

Global variable for the loci package.

Pixels: ome.xml.model.Pixels

Global variable for the Pixels class from the ome.xml.model package.

Image: ome.xml.model.Image

Global variable for the Image class from the ome.xml.model package.

Parameters:
  • version (str, optional) – Version of Bioformats to use (default “7.3.0”).

  • java_memory (str, optional) – Maximum memory for JVM (default “4g”).

  • debug_level (str, optional) – Logging level for Java process “ERROR”, “WARN”, “INFO”, “DEBUG”, “TRACE” (default “INFO”).

nima_io.read.ensure_jvm()#

Start java VM and initialize logger (globally) or Attach running JVM.

Return type:

None

class nima_io.read.JavaFieldUnit(*args, **kwargs)#

Protocol for JavaField’s unit representation.

Methods:

getSymbol()

Retrieve the symbol of the unit.

getSymbol()#

Retrieve the symbol of the unit.

Return type:

str

class nima_io.read.JavaField(*args, **kwargs)#

Protocol for JavaField.

Methods:

value()

Get the value of the JavaField.

unit()

Get the unit of the JavaField.

value()#

Get the value of the JavaField.

Return type:

None | str | float | int

unit()#

Get the unit of the JavaField.

Return type:

None | JavaFieldUnit

class nima_io.read.StagePosition(x, y, z)#

Dataclass representing stage position.

x: float | None#

Position in the X dimension.

y: float | None#

Position in the Y dimension.

z: float | None#

Position in the Z dimension.

class nima_io.read.VoxelSize(x, y, z)#

Dataclass representing voxel size.

x: float | None#

Size in the X dimension.

y: float | None#

Size in the Y dimension.

z: float | None#

Size in the Z dimension.

exception nima_io.read.MultiplePositionsError(message)#

Exception raised when a series contains multiple stage positions.

class nima_io.read.CoreMetadata(rdr, size_x=<factory>, size_y=<factory>, size_c=<factory>, size_z=<factory>, size_t=<factory>, bits=<factory>, name=<factory>, date=<factory>, stage_position=<factory>, voxel_size=<factory>)#

Dataclass representing core metadata.

Parameters:

rdr (loci.formats.ChannelSeparator) – ChannelSeparator instance.

rdr: InitVar#
size_s: int#

Number of series.

file_format: str#

File format.

size_x: list[int]#

List of sizes in the X dimension.

size_y: list[int]#

List of sizes in the Y dimension.

size_c: list[int]#

List of sizes in the C dimension.

size_z: list[int]#

List of sizes in the Z dimension.

size_t: list[int]#

List of sizes in the T dimension.

bits: list[int]#

List of bits per pixel.

name: list[str]#

List of names.

date: list[str | None]#

List of acquisition dates.

stage_position: list[StagePosition]#

List of stage positions.

voxel_size: list[VoxelSize]#

List of voxel sizes.

class nima_io.read.Metadata(core, full, log_miss)#

Dataclass representing all metadata.

core: CoreMetadata#

Core metadata.

full: dict[str, list[tuple[tuple[int, ...], str | bool | int | float | None | tuple[str | bool | int | float | None, str]]]]#

All metadata.

log_miss: dict[str, Any]#

Log of missed keys.

class nima_io.read.ImageReaderWrapper(rdr)#

Wrapper class for Bioformats image reader.

Parameters:

rdr (ChannelSeparator) – Bioformats image reader.

Methods:

read([series, z, c, t, rescale])

Read image data from the specified series, z-stack, channel, and time point.

rdr: Any#

Bioformats image reader.

dtype: type[int8] | type[int16]#

Data type based on the bit depth of the image.

read(series=0, z=0, c=0, t=0, *, rescale=False)#

Read image data from the specified series, z-stack, channel, and time point.

Parameters:
  • series (int, optional) – Index of the image series. Default is 0.

  • z (int, optional) – Index of the z-stack. Default is 0.

  • c (int, optional) – Index of the channel. Default is 0.

  • t (int, optional) – Index of the time point. Default is 0.

  • rescale (bool, optional) – Whether to rescale the data. Default is False.

Returns:

NumPy array containing the frame data.

Return type:

NDArray[np.generic]

nima_io.read.read(filepath)#

Read metadata and data using bioformats and scyjava.

Get all OME metadata. bioformats.formatreader.ImageReader

rdr as a lot of information e.g rdr.isOriginalMetadataPopulated() (core, OME, original metadata)

Parameters:

filepath (str) – The path to the image file.

Return type:

tuple[Metadata, ImageReaderWrapper]

Returns:

  • md (Metadata) – Tidied metadata.

  • wrapper (ImageReaderWrapper) – A wrapper to the Image Reader; to be used for accessing data from disk.

Raises:

FileNotFoundError – If the specified file is not found.

Examples

>>> md, wr = read("tests/data/multi-channel-time-series.ome.tif")
>>> md.core.file_format
'OME-TIFF'
>>> md.core.size_c, md.core.size_t, md.core.size_x, md.core.bits
([3], [7], [439], [8])
>>> a = wr.read(c=2, t=6, series=0, z=0, rescale=False)
>>> a[20, 200]
np.int8(-1)
>>> md, wr = read("tests/data/LC26GFP_1.tf8")
>>> wr.rdr.getSizeX(), md.core.size_x
(1600, [1600])
>>> wr.rdr.getMetadataStore()
<java object 'loci.formats.ome.OMEPyramidStore'>
nima_io.read.read_pims(filepath)#

Read metadata and initialize Bioformats reader using the pims library.

Parameters:

filepath (str) – The file path to the Bioformats file.

Return type:

tuple[Metadata, ImageReaderWrapper]

Returns:

  • md (Metadata) – Tidied metadata.

  • wrapper (ImageReaderWrapper) – A wrapper to the Loci image reader; to be used for accessing data from disk.

Notes

The core metadata includes information necessary to understand the basic structure of the pixels:

  • Image resolution

  • Number of focal planes

  • Time points (SizeT)

  • Channels (SizeC) and other dimensional axes

  • Byte order

  • Dimension order

  • Color arrangement (RGB, indexed color, or separate channels)

  • Thumbnail resolution

The series metadata includes information about each series, such as the size in X, Y, C, T, and Z dimensions, physical sizes, pixel type, and position in XYZ coordinates.

NB name and date are not core metadata. (series) (series, plane) where plane combines z, t and c?

nima_io.read.stitch(core, wr, c=0, t=0, z=0)#

Stitch image tiles returning a tiled single plane.

Parameters:
  • core (CoreMetadata) – A dictionary containing information about the series of images, such as their positions.

  • wr (ImageReaderWrapper) – An object that has a method read to read the images.

  • c (int, optional) – The index or identifier for the images to be read (default is 0).

  • t (int, optional) – The index or identifier for the images to be read (default is 0).

  • z (int, optional) – The index or identifier for the images to be read (default is 0).

Returns:

The stitched image tiles.

Return type:

npt.NDArray[np.float64]

Raises:

IndexError – If building tilemap fails in searching xy_position indexes.

nima_io.read.diff(fp_a, fp_b)#

Diff for two image data.

Parameters:
  • fp_a (str) – File path for the first image.

  • fp_b (str) – File path for the second image.

Returns:

True if the two files are equal.

Return type:

bool

nima_io.read.first_nonzero_reverse(llist)#

Return the index of the last nonzero element in a list.

Parameters:

llist (list[int]) – The input list of integers.

Returns:

The index of the last nonzero element. Returns None if all elements are zero.

Return type:

None | int

Examples

>>> first_nonzero_reverse([0, 2, 0, 0])
-3
>>> first_nonzero_reverse([0, 0, 0])
None
nima_io.read.get_md_dict(ome_store, log_fp=None)#

Parse xml_md and return parsed md dictionary and md status dictionary.

Parameters:
  • ome_store (OMEPyramidStore) – The metadata java object.

  • log_fp (None | Path) – The filepath, used for logging JavaExceptions (default=None).

Return type:

tuple[dict[str, list[tuple[tuple[int, ...], str | bool | int | float | None | tuple[str | bool | int | float | None, str]]]], dict[str, str]]

Returns:

  • md (dict[str, FullMDValueType]) – Parsed metadata dictionary excluding None values.

  • mdd (dict[str, str]) – Metadata status dictionary indicating if a value was found (‘Found’), is None (‘None’), or if there was a JavaException (‘Jmiss’).

nima_io.read.convert_field(field)#

Convert a JavaField to a Python data type, optionally including its unit symbol.

This function handles cases where the JavaField could be None, which is possible for composite metadata, which may contain None e.g., [(4, 1), (543.0, ‘nm’)] might be followed by [(4, 2), None].

Parameters:

field (JavaField | float | str | None) – A field from Java, potentially holding a numeric value and a unit.

Returns:

The converted metadata value as a Python primitive type (int, float, str, or bool), or None, or a tuple of the value and the unit symbol (as a string) if a unit is associated with the value.

Return type:

MDValueType

exception nima_io.read.StopExceptionError#

Exception raised when need to stop.

nima_io.read.next_tuple(llist, *, increment_last)#

Generate the next tuple in lexicographical order.

This function generates the next tuple in lexicographical order based on the input list llist. The lexicographical order is defined as follows:

  • If the s flag is True, the last element of the tuple is incremented.

  • If the s flag is False, the function finds the rightmost non-zero element and increments the element to its left, setting the rightmost non-zero element to 0.

Parameters:
  • llist (list[int]) – The input list representing a tuple.

  • increment_last (bool) – A flag indicating whether to increment the last element or not.

Returns:

The next tuple in lexicographical order.

Return type:

list[int]

Raises:

StopExceptionError – If the input tuple is empty or if the generation needs to stop.

Examples

>>> next_tuple([0, 0, 0], increment_last=True)
[0, 0, 1]
>>> next_tuple([0, 0, 1], increment_last=True)
[0, 0, 2]
>>> next_tuple([0, 0, 2], increment_last=False)
[0, 1, 0]
>>> next_tuple([0, 1, 2], increment_last=False)
[0, 2, 0]
>>> next_tuple([2, 0, 0], increment_last=False)
Traceback (most recent call last):
...
nima_io.read.StopExceptionError
nima_io.read.retrieve_values(ome_store, key, npar)#

Retrieve values for the given key and number of parameters from the OMEStore.

Return type:

list[tuple[tuple[int, ...], str | bool | int | float | None | tuple[str | bool | int | float | None, str]]]

nima_io.read.group_metadata(res)#

Tidy up by grouping common metadata.

Return type:

list[tuple[tuple[int, ...], str | bool | int | float | None | tuple[str | bool | int | float | None, str]]]

nima_io.read.get_allvalues_grouped(ome_store, key, npar)#

Retrieve and group metadata values for a given key.

Assume that all the OMEStore methods have a certain number of parameters. Group common values into a list without knowledge of parameters meaning.

Parameters:
  • ome_store (OMEPyramidStore) – The metadata java object.

  • key (str) – The key for which values are retrieved.

  • npar (int) – The number of parameters for the key.

Returns:

A list of tuples containing the tuple configuration and corresponding values.

Return type:

FullMDValueType