API Reference
Core
Core data models and tile operations. This module contains the fundamental building blocks: Tile (a single image tile with position, size, and loader), TiledImage (a collection of tiles forming one image), and functions for parsing tiles from DataFrames or building them programmatically.
Key exports: Tile, TiledImage, TileSlice, TileFOVGroup, hcs_images_from_dataframe, single_images_from_dataframe, tiled_image_from_tiles, build_dummy_tile.
ome_zarr_converters_tools.core
Core utility module for OME-Zarr converters tools.
Tile
Bases: BaseModel, Generic[CollectionInterfaceType, ImageLoaderInterfaceType]
A tile representing a region of an image to be converted.
This model is a complete definition of a tile, including its position, size, how to load the image data, and additional metadata. This model is the basic entry point for defining what regions of an acquisition to convert.
Attributes:
-
fov_name(str) –Name of the field of view (FOV) this tile belongs to.
-
start_x(float) –Starting position in the X dimension.
-
start_y(float) –Starting position in the Y dimension.
-
start_z(float) –Starting position in the Z dimension.
-
start_c(int) –Starting position in the C (channel) dimension. Channel indices index into
acquisition_details.channelswhen channel metadata is provided, sostart_c + length_cmust not exceed its length. -
start_t(float) –Starting position in the T (time) dimension.
-
length_x(float) –Length of the tile in the X dimension.
-
length_y(float) –Length of the tile in the Y dimension.
-
length_z(float) –Length of the tile in the Z dimension.
-
length_c(int) –Length of the tile in the C (channel) dimension.
-
length_t(float) –Length of the tile in the T (time) dimension.
-
collection(CollectionInterfaceType) –Collection model defining how to build the path to the image(s).
-
image_loader(ImageLoaderInterfaceType) –Image loader model defining how to load the image data.
-
acquisition_details(AcquisitionDetails) –Acquisition specific details that will be used to validate and convert the tile.
-
attributes(dict[str, AttributeType]) –Additional attributes for the these will be passed to the fractal image list as key-value pairs.
Source code in ome_zarr_converters_tools/core/_tile.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 | |
find_data_type(resource: Any | None = None) -> str
Find the data type of the image data.
Source code in ome_zarr_converters_tools/core/_tile.py
to_roi() -> Roi
Convert the Tile to a Roi.
Source code in ome_zarr_converters_tools/core/_tile.py
TileFOVGroup
Bases: BaseModel, Generic[ImageLoaderInterfaceType]
Group of TileSlices belonging to the same acquisition FOV.
Source code in ome_zarr_converters_tools/core/_tile_region.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | |
load_data(resource: Any | None = None) -> np.ndarray
Load the full image data for this FOV group.
Source code in ome_zarr_converters_tools/core/_tile_region.py
load_data_dask(resource: Any | None = None, chunks: tuple[int, ...] | None = None) -> da.Array
Load the full image data for this FOV group using Dask.
Source code in ome_zarr_converters_tools/core/_tile_region.py
ref_slice() -> TileSlice[ImageLoaderInterfaceType]
Get a reference TileSlice for this FOV group.
Source code in ome_zarr_converters_tools/core/_tile_region.py
roi() -> Roi
Get the global ROI covering all TileSlices in the FOV group.
shape() -> tuple[int, ...]
Get the shape of the FOV group by computing the union of all regions.
TileSlice
Bases: BaseModel, Generic[ImageLoaderInterfaceType]
The smallest unit of a tiled image.
Usually corresponds to the minimal unit in which the source data can be loaded (e.g., a single tiff file from the microscope).
Source code in ome_zarr_converters_tools/core/_tile_region.py
from_tile(tile: Tile) -> Self
classmethod
load_data(*, axes: list[CANONICAL_AXES_TYPE], resource: Any | None = None) -> np.ndarray
Load the image data for this TileSlice using the image loader.
Source code in ome_zarr_converters_tools/core/_tile_region.py
TiledImage
Bases: BaseModel, Generic[CollectionInterfaceType, ImageLoaderInterfaceType]
A TiledImage is the unit that will be converted into an OME-Zarr image.
Can contain multiple TileFOVGroups, each containing multiple TileSlices or it can directly contain a single TileFOVGroup.
Source code in ome_zarr_converters_tools/core/_tile_region.py
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 | |
pixel_size: PixelSize
property
Return the PixelSize of the TiledImage.
add_tile(tile: Tile, add_translation: bool = False) -> None
Add a Tile to the TiledImage as a TileSlice.
Source code in ome_zarr_converters_tools/core/_tile_region.py
group_by_fov() -> list[TileFOVGroup[ImageLoaderInterfaceType]]
Group TileSlices by field of view name.
Source code in ome_zarr_converters_tools/core/_tile_region.py
load_data(resource: Any | None = None) -> np.ndarray
Load the full image data for this TiledImage using the image loaders.
Source code in ome_zarr_converters_tools/core/_tile_region.py
load_data_dask(resource: Any | None = None, chunks: tuple[int, ...] | None = None) -> da.Array
Load the full image data for this TiledImage using Dask.
Source code in ome_zarr_converters_tools/core/_tile_region.py
output_shape() -> tuple[int, ...]
Output-array shape anchored at pixel 0 (includes any left-padding).
Equals shape() when the mosaic origin is 0 (the default); larger when a
remove_*_offset="Keep" axis keeps a positive absolute origin.
Source code in ome_zarr_converters_tools/core/_tile_region.py
roi() -> Roi
Get the global ROI covering all TileSlices in the TiledImage.
shape() -> tuple[int, ...]
Get the shape of the TiledImage by computing the union of all regions.
build_dummy_tile(*, fov_name: str, start: StartPosition, shape: TileShape, collection: CollectionInterface, acquisition_details: AcquisitionDetails, font_scale: float = 0.22) -> Tile
Build a dummy tile with default parameters, allowing overrides.
Source code in ome_zarr_converters_tools/core/_dummy_tiles.py
find_url_type(url: str) -> UrlType
Classify a URL as local, S3, or unsupported (see UrlType).
Source code in ome_zarr_converters_tools/models/_url_utils.py
hcs_images_from_dataframe(*, tiles_table: pd.DataFrame, acquisition_details: AcquisitionDetails, plate_name: str | None = None, acquisition_id: int = 0) -> list[Tile]
Build a list of Tiles belonging to an HCS plate acquisition.
Parameters:
-
tiles_table(DataFrame) –DataFrame containing the tiles table.
-
acquisition_details(AcquisitionDetails) –AcquisitionDetails model for the acquisition.
-
plate_name(str | None, default:None) –Optional name of the plate.
-
acquisition_id(int, default:0) –Acquisition index.
Returns:
-
list[Tile]–One Tile per row of the tiles table, with
ImageInPlatecollections.
Source code in ome_zarr_converters_tools/core/_table.py
join_url_paths(base_url: str, *paths: str) -> str
Join path components to a base URL, normalizing ./.. segments.
Used instead of os.path.join or pathlib.Path to support both local
and S3 URLs. Resolves ./.. and collapses redundant slashes while
staying protocol- and Windows-safe: it uses posixpath.normpath (never
os.path.normpath, which on Windows would rewrite forward slashes to
backslashes and corrupt S3 keys).
Raises:
-
ValueError–if
..segments would ascend above the network location of a protocol URL (e.g.join_url_paths("s3://bucket", "..", "x")would otherwise silently drop the bucket).
Source code in ome_zarr_converters_tools/models/_url_utils.py
local_url_to_path(url: str) -> Path
Convert a local URL to an absolute Path, expanding ~.
Does not touch the filesystem.
single_images_from_dataframe(*, tiles_table: pd.DataFrame, acquisition_details: AcquisitionDetails) -> list[Tile]
Build a list of Tiles belonging to stand-alone (non-plate) images.
Parameters:
-
tiles_table(DataFrame) –DataFrame containing the tiles table.
-
acquisition_details(AcquisitionDetails) –AcquisitionDetails model for the acquisition.
Returns:
-
list[Tile]–One Tile per row of the tiles table, with
SingleImagecollections.
Source code in ome_zarr_converters_tools/core/_table.py
tiled_image_from_tiles(*, tiles: list[Tile], split_per_fov: bool = False, resource: Any | None = None) -> list[TiledImage]
Build a list of TiledImages from a list of Tiles.
Parameters:
-
tiles(list[Tile]) –List of Tile models to build the TiledImages from.
-
split_per_fov(bool, default:False) –If True, each field of view becomes its own TiledImage; if False, all fields of view are aggregated into one mosaic image.
-
resource(Any | None, default:None) –Optional resource to assist in processing.
Returns:
-
list[TiledImage]–A list of TiledImage models created from the tiles.
Source code in ome_zarr_converters_tools/core/_tile_to_tiled_images.py
Models
Configuration models, collection types, and image loaders. This module defines the Pydantic models used to configure the conversion pipeline (ConverterOptions, AcquisitionDetails), the collection types that determine output structure (ImageInPlate, SingleImage), and the image loader interface for custom formats.
Key exports: ConverterOptions, AcquisitionDetails, ChannelInfo, ImageInPlate, SingleImage, ImageLoaderInterface, DefaultImageLoader, Grouping, MosaicGrouping, PerFovGrouping, TilingStrategy, AutoTiling, SnapToGridTiling, SnapToCornersTiling, InplaceTiling, WriterMode, OverwriteMode, StagePositionCorrections, OmeZarrOptions.
ome_zarr_converters_tools.models
Models and types definitions for the ome_zarr_converters_tools.
AcquisitionDetails
Bases: BaseModel
Details about the acquisition.
These attributes are known and fixed prior to conversion. (Either parsed from metadata or manually serialized by the user beforehand.)
Source code in ome_zarr_converters_tools/models/_acquisition.py
validate_axes(v: list[CANONICAL_AXES_TYPE]) -> list[CANONICAL_AXES_TYPE]
classmethod
Validate that axes are in canonical order.
Source code in ome_zarr_converters_tools/models/_acquisition.py
AutoTiling
Bases: UserFacingModel
Automatically pick between Snap to Grid and Snap to Corners.
Source code in ome_zarr_converters_tools/models/_converter_options.py
mode: Literal['Auto'] = 'Auto'
class-attribute
instance-attribute
Automatically use Snap to Grid when the field of view positions
align to a regular grid, Snap to Corners otherwise.
tolerance: float = Field(default=1, ge=0, title='Tiling Tolerance (in pixels)')
class-attribute
instance-attribute
Maximum misalignment (in pixels) tolerated when checking whether the field of view positions fit a regular grid.
BackendType
Bases: StrEnum
File format used to store tables (e.g. ROI tables) in the OME-Zarr.
Source code in ome_zarr_converters_tools/models/_converter_options.py
ChannelInfo
Bases: UserFacingModel
Name, wavelength, and display color of a channel.
Source code in ome_zarr_converters_tools/models/_acquisition.py
channel_label: str
instance-attribute
Label of the channel.
color: str | None = Field(default=None, pattern='^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$')
class-attribute
instance-attribute
The color associated with the channel in hex format, e.g. for visualization purposes.
wavelength_id: str | None = None
class-attribute
instance-attribute
The wavelength ID of the channel. This field can be used in some tasks as alternative to channel_label, e.g. for multiplexed acquisitions it can be used for applying illumination correction based on wavelength ID instead of channel name.
validate_channel_info() -> ChannelInfo
Assign a default color if None is provided.
Source code in ome_zarr_converters_tools/models/_acquisition.py
CollectionInterface
Bases: BaseModel, ABC
Base class defining how to build the output path(s) for a collection.
Subclasses implement path and inherit the tiling _suffix slot, which is
set via set_suffix during per-FOV splitting (do not set it manually).
Source code in ome_zarr_converters_tools/models/_collection.py
path() -> str
abstractmethod
set_suffix(suffix: str) -> None
ConverterOptions
Bases: UserFacingModel
Options for the OME-Zarr conversion process.
Source code in ome_zarr_converters_tools/models/_converter_options.py
grouping: Grouping = Field(default_factory=MosaicGrouping, title='Grouping')
class-attribute
instance-attribute
How fields of view are grouped into output images.
Mosaic: Aggregate all fields of view of an acquisition into one OME-Zarr, arranged by the nestedtiling_strategy.Per-FOV: Write each field of view as its own OME-Zarr image (no mosaic, no tiling strategy).
omezarr_options: OmeZarrOptions = Field(default_factory=OmeZarrOptions, title='OME-Zarr Options')
class-attribute
instance-attribute
Options specific to OME-Zarr writing.
runtime_settings: RuntimeSettings = Field(default_factory=RuntimeSettings, title='Runtime Settings')
class-attribute
instance-attribute
Advanced performance settings: parallelism, storage codec, and temporary storage. The defaults are safe for most conversions.
stage_position_corrections: StagePositionCorrections = Field(default_factory=StagePositionCorrections, title='Stage Position Corrections')
class-attribute
instance-attribute
Stage position correction options.
writer_mode: WriterMode = Field(default=(WriterMode.BY_FOV), title='Writer Mode')
class-attribute
instance-attribute
Mode for writing data during conversion.
By Tile: Write data one tile at a time. This consumes less memory, but may be slower.By Tile (Using Dask): Write tiles in parallel using Dask. This is usually faster than writing by tile sequentially, but may consume more memory.By FOV: Write data one field of view at a time. Often the best compromise between speed and memory usage in most cases.By FOV (Using Dask): Write fields of view in parallel using Dask. This is usually faster than writing by FOV sequentially, but may consume more memory.In Memory: Load all data into memory before writing.
DataTypeEnum
Bases: StrEnum
Pixel data type of the output image; autodetect infers it.
Source code in ome_zarr_converters_tools/models/_acquisition.py
DefaultImageLoader
Bases: ImageLoaderInterface
File-based image loader for common formats (TIFF, PNG/JPEG/BMP, NPY).
The file type is inferred from the extension; unrecognized extensions are attempted as TIFF with a warning.
Source code in ome_zarr_converters_tools/models/_loader.py
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 | |
file_path: str
instance-attribute
Path to the image file. If relative, it is resolved against the
resource passed to load_data (usually the acquisition base directory).
load_data(resource: Any | None = None) -> np.ndarray
Load the image data as a NumPy array.
Source code in ome_zarr_converters_tools/models/_loader.py
preflight(resource: Any | None = None) -> None
Warn if the source file does not exist, without reading it.
Source code in ome_zarr_converters_tools/models/_loader.py
DefaultScheduler
Bases: UserFacingModel
Keep the environment's default parallelism settings unchanged.
Source code in ome_zarr_converters_tools/models/_runtime_settings.py
mode: Literal['Default'] = 'Default'
class-attribute
instance-attribute
How the conversion work is parallelized.
FixedSizeChunking
Bases: UserFacingModel
Store the image in chunks of a fixed size.
Source code in ome_zarr_converters_tools/models/_converter_options.py
c_chunk: int = Field(default=1, ge=1, title='Chunk Size for C')
class-attribute
instance-attribute
Chunk size for C dimension.
mode: Literal['Fixed Size'] = 'Fixed Size'
class-attribute
instance-attribute
How the image is split into storage chunks.
t_chunk: int = Field(default=1, ge=1, title='Chunk Size for T')
class-attribute
instance-attribute
Chunk size for T dimension.
xy_chunk: int = Field(default=4096, ge=1, title='Chunk Size for XY')
class-attribute
instance-attribute
Chunk size for XY dimensions.
z_chunk: int = Field(default=10, ge=1, title='Chunk Size for Z')
class-attribute
instance-attribute
Chunk size for Z dimension.
FovBasedChunking
Bases: UserFacingModel
Store the image in chunks sized like the fields of view.
Source code in ome_zarr_converters_tools/models/_converter_options.py
c_chunk: int = Field(default=1, ge=1, title='Chunk Size for C')
class-attribute
instance-attribute
Chunk size for C dimension.
mode: Literal['Same as FOV'] = 'Same as FOV'
class-attribute
instance-attribute
How the image is split into storage chunks.
t_chunk: int = Field(default=1, ge=1, title='Chunk Size for T')
class-attribute
instance-attribute
Chunk size for T dimension.
xy_scaling: Scalings = Field(default=(Scalings.ONE), title='XY Scaling Factor')
class-attribute
instance-attribute
Scaling factor for the XY chunk size, relative to the field of view size.
1: chunks match the field of view size.0.5: chunks are half the field of view (smaller chunks, more files).2: chunks are double the field of view (larger chunks, fewer files).
z_chunk: int = Field(default=10, ge=1, title='Chunk Size for Z')
class-attribute
instance-attribute
Chunk size for Z dimension.
ImageInPlate
Bases: CollectionInterface
Collection for an image inside an HCS plate (plate/row/column layout).
Source code in ome_zarr_converters_tools/models/_collection.py
acquisition: int = Field(default=0, ge=0)
class-attribute
instance-attribute
Acquisition index (used as the image path inside the well).
column: int = Field(ge=1)
class-attribute
instance-attribute
Well column number, 1-based.
plate_name: str
instance-attribute
Name of the plate (.zarr is appended if missing).
row: str
instance-attribute
Well row label, e.g. "A". Integer input is converted (1 → "A").
ImageLoaderInterface
Bases: BaseModel, ABC
Base class for image loaders; subclass it to support a custom format.
Implement load_data to return the tile pixels as a NumPy array. The
optional resource carries per-call context (e.g. a base directory or an
open handle) and is threaded through the conversion pipeline unchanged.
Source code in ome_zarr_converters_tools/models/_loader.py
find_data_type(resource: Any | None = None) -> str
load_data(resource: Any | None = None) -> np.ndarray
abstractmethod
preflight(resource: Any | None = None) -> None
Cheaply verify the source data is reachable, without loading it.
The default implementation is a no-op. Override it to emit a warning on missing or unreadable sources (e.g. a file-existence check) so that pre-flight validators can surface such problems at init time, before compute jobs are dispatched. Implementations should warn, not raise: only loading the data decides whether it is truly unreadable.
Source code in ome_zarr_converters_tools/models/_loader.py
InplaceTiling
Bases: UserFacingModel
Keep every field of view at its original stage position.
Source code in ome_zarr_converters_tools/models/_converter_options.py
mode: Literal['Inplace'] = 'Inplace'
class-attribute
instance-attribute
Keep every field of view at its original stage position. Imprecise stage positions may produce artifacts: where tiles overlap, the last written tile wins.
MosaicGrouping
Bases: UserFacingModel
Aggregate all fields of view of an acquisition into one mosaic OME-Zarr.
Source code in ome_zarr_converters_tools/models/_converter_options.py
mode: Literal['Mosaic'] = 'Mosaic'
class-attribute
instance-attribute
How fields of view are grouped into output images.
split_per_fov: bool
property
Whether each field of view becomes its own OME-Zarr image.
tiling_strategy: TilingStrategy = Field(default_factory=AutoTiling, title='Tiling Strategy')
class-attribute
instance-attribute
How the fields of view are arranged within the mosaic.
Auto: Automatically determine ifSnap to Gridis possible, otherwise useSnap to Corners. Accepts an optional tolerance (in pixels) for grid alignment.Snap to Grid: Tile images to fit a regular grid. This is only possible if image positions align to a grid (potentially with overlap). Accepts an optional tolerance (in pixels).Snap to Corners: Tile images to fit a grid defined by the corner positions.Inplace: Write tiles in their original positions without tiling. This may lead to artifacts if microscope stage positions are not precise.
tiling_for_registration() -> TilingStrategy
NamedLevels
Bases: UserFacingModel
Name each resolution level explicitly, from highest to lowest resolution.
Source code in ome_zarr_converters_tools/models/_converter_options.py
level_names: list[str] = Field(min_length=1, title='Level Names')
class-attribute
instance-attribute
Names of the resolution levels, from highest to lowest resolution,
e.g. ["s0", "s1", "s2"]. Each name becomes a path inside the OME-Zarr.
mode: Literal['Custom Names'] = 'Custom Names'
class-attribute
instance-attribute
How the resolution levels of the pyramid are defined.
to_ngio_levels() -> int | list[str]
NumberOfLevels
Bases: UserFacingModel
Create a number of resolution levels with default names (0, 1, ...).
Source code in ome_zarr_converters_tools/models/_converter_options.py
mode: Literal['Number of Levels'] = 'Number of Levels'
class-attribute
instance-attribute
How the resolution levels of the pyramid are defined.
num_levels: int = Field(default=5, ge=1, title='Number of Resolution Levels')
class-attribute
instance-attribute
Number of resolution levels in the pyramid of the output image.
to_ngio_levels() -> int | list[str]
OmeZarrOptions
Bases: UserFacingModel
Options controlling the layout of the output OME-Zarr.
Source code in ome_zarr_converters_tools/models/_converter_options.py
chunks: ChunkingStrategy = Field(default_factory=FovBasedChunking, title='Chunking Strategy')
class-attribute
instance-attribute
How the image is split into storage chunks: sized like the fields of
view (Same as FOV) or with fixed sizes (Fixed Size).
levels: PyramidLevels = Field(default_factory=NumberOfLevels, title='Resolution Levels')
class-attribute
instance-attribute
How many resolution levels the output pyramid has and how they are named.
Number of Levels: a number of levels with the default names (0,1, ...).Custom Names: an explicit list of level names, e.g.["s0", "s1"].
ngff_version: NgffVersions = Field(default=DefaultNgffVersion, title='NGFF Version')
class-attribute
instance-attribute
Version of the OME-NGFF specification to target.
table_backend: BackendType = Field(default=(BackendType.CSV), title='Table Backend')
class-attribute
instance-attribute
File format used to store tables (e.g. ROI tables) inside the OME-Zarr.
OverwriteMode
Bases: StrEnum
How to handle existing output data: fail, replace, or extend it.
No Overwrite fails instead of touching existing data, Overwrite
removes and replaces it, and Extend adds new wells or acquisitions
while leaving existing ones untouched.
Source code in ome_zarr_converters_tools/models/_converter_options.py
PerFovGrouping
Bases: UserFacingModel
Write each field of view as its own OME-Zarr image (no mosaic).
Source code in ome_zarr_converters_tools/models/_converter_options.py
mode: Literal['Per-FOV'] = 'Per-FOV'
class-attribute
instance-attribute
How fields of view are grouped into output images.
split_per_fov: bool
property
Whether each field of view becomes its own OME-Zarr image.
tiling_for_registration() -> TilingStrategy
Within-image arrangement strategy for the registration pipeline.
Per-FOV images contain a single field of view, so there is nothing to
arrange; InplaceTiling is a no-op here (identical to the removed
NoTiling path in the tiling step).
Source code in ome_zarr_converters_tools/models/_converter_options.py
ProcessScheduler
Bases: UserFacingModel
Parallelize the conversion using multiple processes.
Source code in ome_zarr_converters_tools/models/_runtime_settings.py
mode: Literal['Processes'] = 'Processes'
class-attribute
instance-attribute
How the conversion work is parallelized.
num_workers: int = Field(default=8, ge=1, title='Number of Processes')
class-attribute
instance-attribute
Number of worker processes to use. Must be at least 1.
RuntimeSettings
Bases: UserFacingModel
Advanced performance settings; the defaults suit most conversions.
Covers parallelism, the storage codec, and temporary storage.
Source code in ome_zarr_converters_tools/models/_runtime_settings.py
dask_scheduler: DaskScheduler = Field(default_factory=DefaultScheduler, title='Dask Scheduler')
class-attribute
instance-attribute
How the conversion work is parallelized.
Threads: parallelize using multiple threads.Processes: parallelize using multiple processes.Synchronous: run sequentially, without parallelism.Default: keep the environment's parallelism settings unchanged.
temp_json_options: TempJsonOptions = Field(default_factory=TempJsonOptions, title='Temporary JSON Options')
class-attribute
instance-attribute
Where and when intermediate conversion data is stored on disk.
use_zarrs_codec: bool = Field(default=False, title='Use Zarrs Codec Pipeline')
class-attribute
instance-attribute
Read and write image data with the zarrs Rust backend, which is
usually faster. Requires the optional zarrs dependency to be
installed.
apply() -> Iterator[None]
Apply settings as a scoped context manager.
Mutates zarr.config and/or dask.config only for the duration of
the with block. Default-constructed settings produce a no-op
(no zarr config mutation, and dask.config.set({}) for the default
scheduler).
Source code in ome_zarr_converters_tools/models/_runtime_settings.py
Scalings
Bases: StrEnum
Scaling factor applied to the field of view size to get the chunk size.
Source code in ome_zarr_converters_tools/models/_converter_options.py
SingleImage
Bases: CollectionInterface
Collection for a stand-alone OME-Zarr image (not part of a plate).
Source code in ome_zarr_converters_tools/models/_collection.py
image_path: str
instance-attribute
Output path of the image, relative to the zarr directory
(.zarr is appended if missing).
SnapToCornersTiling
Bases: UserFacingModel
Arrange the fields of view on a grid defined by their corners.
Source code in ome_zarr_converters_tools/models/_converter_options.py
mode: Literal['Snap to Corners'] = 'Snap to Corners'
class-attribute
instance-attribute
Arrange the fields of view on a grid defined by their corner positions.
SnapToGridTiling
Bases: UserFacingModel
Arrange the fields of view on a regular grid.
Source code in ome_zarr_converters_tools/models/_converter_options.py
mode: Literal['Snap to Grid'] = 'Snap to Grid'
class-attribute
instance-attribute
Arrange the fields of view on a regular grid. Only possible when their positions already align to a grid (potentially with overlap).
tolerance: float = Field(default=1, ge=0, title='Tiling Tolerance (in pixels)')
class-attribute
instance-attribute
Maximum misalignment (in pixels) tolerated when checking whether the field of view positions fit a regular grid.
StageOrientation
Bases: UserFacingModel
Corrections for the stage orientation relative to the image axes.
Use these when the fields of view appear mirrored or arranged wrongly in the output image.
Source code in ome_zarr_converters_tools/models/_acquisition.py
flip_x: bool = Field(default=False, title='Flip X')
class-attribute
instance-attribute
Whether to flip the position along the X axis.
flip_y: bool = Field(default=False, title='Flip Y')
class-attribute
instance-attribute
Whether to flip the position along the Y axis.
swap_xy: bool = Field(default=False, title='Swap XY')
class-attribute
instance-attribute
Whether to swap the positions along the X and Y axes.
StagePositionCorrections
Bases: UserFacingModel
Corrections applied to the stage positions before writing the image.
Source code in ome_zarr_converters_tools/models/_converter_options.py
reindex_channels: bool = Field(default=True, title='Reindex Channels')
class-attribute
instance-attribute
If enabled, only the channels actually present are converted; if disabled, missing channels are stored as empty images.
remove_t_offset: Literal['Keep', 'Global'] = Field(default='Global', title='Remove T Offset')
class-attribute
instance-attribute
Whether to shift the image so its time origin is 0.
Global: Shift all positions together so the time origin is 0.Keep: Use the stage positions as-is. Fails if any position is negative; positive positions produce empty padding at the image origin.
remove_xy_jitter: bool = Field(default=True, title='Remove XY Jitter')
class-attribute
instance-attribute
Remove small stage position inconsistencies within a field of view by snapping its sub-tiles to a shared origin.
remove_xy_offset: Literal['Keep', 'Global'] = Field(default='Global', title='Remove XY Offset')
class-attribute
instance-attribute
Whether to shift the image so its XY origin is 0.
Global: Shift all positions together so the image origin is 0.Keep: Use the stage positions as-is. Fails if any position is negative; positive positions produce empty padding at the image origin.
remove_z_offset: Literal['Keep', 'Per-FOV', 'Global'] = Field(default='Global', title='Remove Z Offset')
class-attribute
instance-attribute
Whether to shift the image so its Z origin is 0.
Global: Shift all positions together so the Z origin is 0.Per-FOV: Shift each field of view independently to Z origin 0.Keep: Use the stage positions as-is. Fails if any position is negative; positive positions produce empty padding at the image origin.
SynchronousScheduler
Bases: UserFacingModel
Run the conversion sequentially, without parallelism.
Source code in ome_zarr_converters_tools/models/_runtime_settings.py
mode: Literal['Synchronous'] = 'Synchronous'
class-attribute
instance-attribute
How the conversion work is parallelized.
TempJsonOptions
Bases: UserFacingModel
Where and when intermediate conversion data is stored on disk.
The data is handed over between the init and compute phases of the task.
Source code in ome_zarr_converters_tools/models/_runtime_settings.py
max_in_memory_bytes: int = Field(default=(10 * 1024 * 1024), ge=1, title='Max In-Memory Bytes')
class-attribute
instance-attribute
Maximum total size of serialized tiled image data to keep in-memory
between init and compute phases when serialization is Auto.
If the total size exceeds this threshold, data will be written to temporary
JSON files on disk instead. Default is 10 MiB.
serialization: Literal['Auto', 'Memory', 'JSON'] = 'Auto'
class-attribute
instance-attribute
Serialization mode for tiled image data between init and compute phases.
Memory: always keep data in-memory (skips all filesystem I/O).JSON: always write to a temporary JSON file on disk (required for distributed Fractal runs where init and compute execute on different machines).Auto: use in-memory when the total serialized payload is withinmax_in_memory_bytes(default 10 MiB), otherwise fall back to JSON files on disk.
temp_url: str = Field(default='{zarr_dir}/_tmp_json', title='Temporary Storage URL')
class-attribute
instance-attribute
Where intermediate JSON files are written. The {zarr_dir}
placeholder is replaced by the task's output directory.
use_in_memory(total_bytes: int) -> bool
Resolve whether to skip disk I/O for the given total serialized size.
Source code in ome_zarr_converters_tools/models/_runtime_settings.py
ThreadScheduler
Bases: UserFacingModel
Parallelize the conversion using multiple threads.
Source code in ome_zarr_converters_tools/models/_runtime_settings.py
mode: Literal['Threads'] = 'Threads'
class-attribute
instance-attribute
How the conversion work is parallelized.
num_workers: int = Field(default=8, ge=1, title='Number of Threads')
class-attribute
instance-attribute
Number of worker threads to use. Must be at least 1.
WriterMode
Bases: StrEnum
How image data is written, trading off speed against memory usage.
Source code in ome_zarr_converters_tools/models/_converter_options.py
basename_url(url: str) -> str
Return the last path component of a URL.
A trailing slash is stripped so a directory yields its own name.
default_axes_builder(is_time_series: bool) -> list[CANONICAL_AXES_TYPE]
filesystem_for_url(url: str, error_msg_prefix: str = 'File handling') -> fsspec.AbstractFileSystem
Return the fsspec filesystem for a URL; raise if its type is unsupported.
Source code in ome_zarr_converters_tools/models/_url_utils.py
find_url_type(url: str) -> UrlType
Classify a URL as local, S3, or unsupported (see UrlType).
Source code in ome_zarr_converters_tools/models/_url_utils.py
glob_url_paths(*, base_url: str | None, pattern: str) -> list[str]
Glob a URL pattern, re-prefixing the protocol on each match.
Uses filesystem_for_url so it works for local and S3 URLs, and
re-prefixes the protocol on each result so matches stay usable URLs. If
base_url is None, pattern is treated as absolute — it must then
itself be absolute (/…, ~/…, s3://…, or a Windows path), since a
relative pattern classifies as NOT_SUPPORTED and raises.
A literal, non-existent pattern yields an empty list (fsspec behaviour that downstream code relies on for existence checks).
Source code in ome_zarr_converters_tools/models/_url_utils.py
is_absolute_url(url: str) -> bool
Return True if the URL is absolute (protocol, root, home, or Windows).
Host-independent: shares _is_local_absolute with find_url_type so a
Windows drive/UNC path or a ~-anchored home path is treated as absolute
even when the suite runs on POSIX. Falls back to Path(path).is_absolute()
for anything else. Used to decide whether a path from a manifest/CSV needs
to be resolved against a base directory.
Source code in ome_zarr_converters_tools/models/_url_utils.py
join_url_paths(base_url: str, *paths: str) -> str
Join path components to a base URL, normalizing ./.. segments.
Used instead of os.path.join or pathlib.Path to support both local
and S3 URLs. Resolves ./.. and collapses redundant slashes while
staying protocol- and Windows-safe: it uses posixpath.normpath (never
os.path.normpath, which on Windows would rewrite forward slashes to
backslashes and corrupt S3 keys).
Raises:
-
ValueError–if
..segments would ascend above the network location of a protocol URL (e.g.join_url_paths("s3://bucket", "..", "x")would otherwise silently drop the bucket).
Source code in ome_zarr_converters_tools/models/_url_utils.py
local_url_to_path(url: str) -> Path
Convert a local URL to an absolute Path, expanding ~.
Does not touch the filesystem.
parent_url(url: str) -> str
Return the parent directory of a URL path.
Robust to forward/back slashes and URL protocols, and always returns POSIX
/ separators regardless of host OS (uses posixpath for the local
branch too, never OS-native pathlib, which would emit \ on Windows).
For remote protocols the first component after the protocol is the network
location (e.g. the S3 bucket), which has no parent.
Raises:
-
ValueError–if
urlis a filesystem/network-location root with no parent (e.g./,s3://bucket, or an empty string).
Source code in ome_zarr_converters_tools/models/_url_utils.py
URL & Path Utilities
Protocol-aware path helpers that work transparently for local paths and remote s3:// URLs, and are robust to Windows backslash separators (they always emit POSIX /). Use these instead of os.path / pathlib whenever a location may point at object storage -- they are the URL equivalents of os.path.join / dirname / basename / isabs / glob, plus fsspec filesystem resolution.
url vs path naming
Fields and helpers named *_url (e.g. filesystem_for_url, join_url_paths) take an fsspec-style location that may carry a protocol (s3://…) or be a local path. Fields named *_path (e.g. SingleImage.image_path, DefaultImageLoader.file_path) are collection-relative output locations resolved against the zarr directory or a resource base. s3:// support requires the optional s3 extra: pip install ome-zarr-converters-tools[s3].
Key exports: join_url_paths, parent_url, basename_url, is_absolute_url, glob_url_paths, filesystem_for_url, find_url_type, local_url_to_path, UrlType.
ome_zarr_converters_tools.models
Models and types definitions for the ome_zarr_converters_tools.
UrlType
join_url_paths(base_url: str, *paths: str) -> str
Join path components to a base URL, normalizing ./.. segments.
Used instead of os.path.join or pathlib.Path to support both local
and S3 URLs. Resolves ./.. and collapses redundant slashes while
staying protocol- and Windows-safe: it uses posixpath.normpath (never
os.path.normpath, which on Windows would rewrite forward slashes to
backslashes and corrupt S3 keys).
Raises:
-
ValueError–if
..segments would ascend above the network location of a protocol URL (e.g.join_url_paths("s3://bucket", "..", "x")would otherwise silently drop the bucket).
Source code in ome_zarr_converters_tools/models/_url_utils.py
parent_url(url: str) -> str
Return the parent directory of a URL path.
Robust to forward/back slashes and URL protocols, and always returns POSIX
/ separators regardless of host OS (uses posixpath for the local
branch too, never OS-native pathlib, which would emit \ on Windows).
For remote protocols the first component after the protocol is the network
location (e.g. the S3 bucket), which has no parent.
Raises:
-
ValueError–if
urlis a filesystem/network-location root with no parent (e.g./,s3://bucket, or an empty string).
Source code in ome_zarr_converters_tools/models/_url_utils.py
basename_url(url: str) -> str
Return the last path component of a URL.
A trailing slash is stripped so a directory yields its own name.
is_absolute_url(url: str) -> bool
Return True if the URL is absolute (protocol, root, home, or Windows).
Host-independent: shares _is_local_absolute with find_url_type so a
Windows drive/UNC path or a ~-anchored home path is treated as absolute
even when the suite runs on POSIX. Falls back to Path(path).is_absolute()
for anything else. Used to decide whether a path from a manifest/CSV needs
to be resolved against a base directory.
Source code in ome_zarr_converters_tools/models/_url_utils.py
glob_url_paths(*, base_url: str | None, pattern: str) -> list[str]
Glob a URL pattern, re-prefixing the protocol on each match.
Uses filesystem_for_url so it works for local and S3 URLs, and
re-prefixes the protocol on each result so matches stay usable URLs. If
base_url is None, pattern is treated as absolute — it must then
itself be absolute (/…, ~/…, s3://…, or a Windows path), since a
relative pattern classifies as NOT_SUPPORTED and raises.
A literal, non-existent pattern yields an empty list (fsspec behaviour that downstream code relies on for existence checks).
Source code in ome_zarr_converters_tools/models/_url_utils.py
filesystem_for_url(url: str, error_msg_prefix: str = 'File handling') -> fsspec.AbstractFileSystem
Return the fsspec filesystem for a URL; raise if its type is unsupported.
Source code in ome_zarr_converters_tools/models/_url_utils.py
find_url_type(url: str) -> UrlType
Classify a URL as local, S3, or unsupported (see UrlType).
Source code in ome_zarr_converters_tools/models/_url_utils.py
local_url_to_path(url: str) -> Path
Convert a local URL to an absolute Path, expanding ~.
Does not touch the filesystem.
Pipelines
Pipeline functions for aggregation, registration, filtering, validation, and writing. This module orchestrates the full conversion flow: aggregating tiles into images, running registration steps, applying filters, and writing the final OME-Zarr datasets. It also provides extension points for custom filters, validators, and registration steps.
Key exports: tiles_aggregation_pipeline, tiled_image_creation_pipeline, build_default_registration_pipeline, apply_registration_pipeline, apply_filter_pipeline, add_filter, add_registration_func, add_validator.
ome_zarr_converters_tools.pipelines
Pipeline modules for OME-Zarr converters tools.
add_collection_handler(*, function: SetupCollectionFunction, collection_type: str | None = None, overwrite: bool = False) -> None
Register a new collection setup handler.
The collection setup handler is responsible for setting up the collection structure and metadata in the Zarr group.
Note
Registrations are process-global: under MultiprocessingRunner,
worker processes re-import the consumer's modules, so custom handlers
must be registered at import time of the module that defines them to
be visible in workers.
Parameters:
-
collection_type(str | None, default:None) –Name of the collection setup handler. By convention, the name of the CollectionInterfaceType, e.g., 'SingleImage' or 'ImageInPlate'. Defaults to
function.__name__. -
function(SetupCollectionFunction) –Function that performs the collection setup step.
-
overwrite(bool, default:False) –Whether to overwrite an existing collection setup step with the same name.
Source code in ome_zarr_converters_tools/pipelines/_collection_setup.py
add_filter(*, function: FilterFunctionProtocol, name: str | None = None, overwrite: bool = False) -> None
Register a new filter.
Note
Registrations are process-global: under MultiprocessingRunner,
worker processes re-import the consumer's modules, so custom filters
must be registered at import time of the module that defines them to
be visible in workers.
Parameters:
-
function(FilterFunctionProtocol) –Function that performs the filter step.
-
name(str | None, default:None) –Name of the filter step. Defaults to
function.__name__. -
overwrite(bool, default:False) –Whether to overwrite an existing filter step with the same name.
Source code in ome_zarr_converters_tools/pipelines/_filters.py
add_registration_func(*, function: Callable[..., TiledImage], name: str | None = None, overwrite: bool = False) -> None
Register a new registration step function.
Note
Registrations are process-global: under MultiprocessingRunner,
worker processes re-import the consumer's modules, so custom
registration steps must be registered at import time of the module
that defines them to be visible in workers.
Parameters:
-
function(Callable[..., TiledImage]) –Function that performs the registration step.
-
name(str | None, default:None) –Name of the registration step. Defaults to
function.__name__. -
overwrite(bool, default:False) –Whether to overwrite an existing registration step.
Source code in ome_zarr_converters_tools/pipelines/_registration_pipeline.py
add_validator(*, function: ValidatorFunctionProtocol, name: str | None = None, overwrite: bool = False) -> None
Register a new validator function.
Validators are pre-flight checks that run on each TiledImage after
aggregation and raise on failure; use them to front-load errors that
would otherwise only surface during compute.
Note
Registrations are process-global: under MultiprocessingRunner,
worker processes re-import the consumer's modules, so custom
validators must be registered at import time of the module that
defines them to be visible in workers.
Parameters:
-
function(ValidatorFunctionProtocol) –Function that performs the validation step. It is called as
function(tiled_image, validator_params=step, resource=resource)and must raise on failure. -
name(str | None, default:None) –Name of the validation step. Defaults to
function.__name__. -
overwrite(bool, default:False) –Whether to overwrite an existing validation step with the same name.
Source code in ome_zarr_converters_tools/pipelines/_validators.py
setup_ome_zarr_collection(*, tiled_images: list[TiledImage], collection_type: str, zarr_dir: str, ngff_version: NgffVersions = DefaultNgffVersion, overwrite_mode: OverwriteMode = OverwriteMode.NO_OVERWRITE) -> None
Set up the collection in the Zarr group using the specified handler.
Parameters:
-
tiled_images(list[TiledImage]) –List of TiledImage to set up the collection for.
-
collection_type(str) –Type of collection setup handler to use.
-
zarr_dir(str) –The base directory for the zarr data.
-
ngff_version(NgffVersions, default:DefaultNgffVersion) –NGFF version to use for the collection setup.
-
overwrite_mode(OverwriteMode, default:NO_OVERWRITE) –Overwrite mode to use for the collection setup.
Source code in ome_zarr_converters_tools/pipelines/_collection_setup.py
setup_singleimage(zarr_dir: str, tiled_images: list[TiledImage], ngff_version: NgffVersions = DefaultNgffVersion, overwrite_mode: OverwriteMode = OverwriteMode.NO_OVERWRITE) -> None
Set up a SingleImage collection (overwrite-mode enforcement only).
SingleImage outputs do not need an upfront zarr skeleton — the zarr group is created during the compute task. This handler only enforces the OverwriteMode contract.
Source code in ome_zarr_converters_tools/pipelines/_collection_setup.py
tiled_image_creation_pipeline(*, zarr_url: str, tiled_image: TiledImage, registration_pipeline: list[RegistrationStep], converter_options: ConverterOptions, writer_mode: WriterMode, overwrite_mode: OverwriteMode, resource: Any | None = None) -> OmeZarrContainer
Write a TiledImage from a dictionary.
Source code in ome_zarr_converters_tools/pipelines/_tiled_image_creation_pipeline.py
tiles_aggregation_pipeline(tiles: list[Tile], *, converter_options: ConverterOptions, filters: Sequence[FilterModel] | None = None, validators: Sequence[ValidatorModel] | None = None, resource: Any | None = None) -> list[TiledImage]
Process tiles and aggregates them into TiledImages.
This function applies optional filters to the input tiles and then constructs TiledImage models from the processed tiles.
Parameters:
-
tiles(list[Tile]) –List of Tile models to process.
-
converter_options(ConverterOptions) –ConverterOptions model for the conversion.
-
filters(Sequence[FilterModel] | None, default:None) –Optional sequence of filter steps to apply to the tiles.
-
validators(Sequence[ValidatorModel] | None, default:None) –Optional sequence of validator steps to apply to the tiles.
-
resource(Any | None, default:None) –Optional resource to assist in processing.
Returns:
-
list[TiledImage]–A list of TiledImage models created from the processed tiles.
Source code in ome_zarr_converters_tools/pipelines/_tiles_aggregation_pipeline.py
write_tiled_image_as_zarr(*, zarr_url: str, tiled_image: TiledImage, converter_options: ConverterOptions, writer_mode: WriterMode, overwrite_mode: OverwriteMode, resource: Any | None = None) -> OmeZarrContainer
Write a TiledImage as a Zarr file.
Parameters:
-
zarr_url(str) –URL to write the Zarr file to.
-
tiled_image(TiledImage) –TiledImage model to write.
-
converter_options(ConverterOptions) –Options for the OME-Zarr conversion.
-
writer_mode(WriterMode) –Mode for writing the data.
-
overwrite_mode(OverwriteMode) –Mode to handle existing data.
-
resource(Any | None, default:None) –Optional resource to pass to the image loaders.
Returns:
-
OmeZarrContainer–The written OME-Zarr container.
Source code in ome_zarr_converters_tools/pipelines/_write_ome_zarr.py
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 | |
Fractal Integration
Utilities for building Fractal platform tasks. This module provides setup_images_for_conversion() (init task) and generic_compute_task() (compute task factory) for parallelizing conversions across a Fractal cluster.
Key exports: setup_images_for_conversion, generic_compute_task, ConvertParallelInitArgs, AcquisitionOptions. Lower-level JSON plumbing (tiled_image_from_json, dump_to_json, …) is also exported from this module for task authors who need to serialize TiledImages across the init/compute boundary; it is intentionally namespaced under fractal rather than the package root.
ome_zarr_converters_tools.fractal
API for building OME-Zarr converters tasks for Fractal.
AcquisitionOptions
Bases: UserFacingModel
Per-acquisition settings: channels, pixel sizes, axes, and filters.
In Fractal tasks these settings override/update the acquisition details
parsed from the raw metadata (AcquisitionDetails).
Source code in ome_zarr_converters_tools/fractal/_models.py
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 | |
axes: str | None = None
class-attribute
instance-attribute
Axes of the image data, e.g. czyx. If left empty, the axes parsed
from the raw metadata are used.
channels: list[ChannelInfoUI] | None = None
class-attribute
instance-attribute
Names, wavelengths, and display colors of the channels. If left empty, the channel information parsed from the raw metadata is used.
condition_table_path: str | None = None
class-attribute
instance-attribute
Optional path to a condition table CSV file to store in the plate metadata.
data_type: DataTypeEnum = Field(default=(DataTypeEnum.AUTODETECT), title='Data Type')
class-attribute
instance-attribute
Pixel data type of the output image. autodetect infers it from the
input images.
filters: list[ImplementedFilters] = Field(default_factory=list)
class-attribute
instance-attribute
Filters selecting which tiles of the acquisition are converted.
pixel_info: PixelSizeModel | None = Field(default=None, title='Pixel Size Information')
class-attribute
instance-attribute
Override the pixel size and the Z/time spacing of the images. If left empty, the values parsed from the raw metadata are used.
stage_orientation: StageOrientation = Field(default_factory=StageOrientation, title='Stage Orientation')
class-attribute
instance-attribute
Corrections for the orientation of the microscope stage relative to the image axes.
to_axes_list() -> list[CANONICAL_AXES_TYPE] | None
Convert axes string to list of axes.
Source code in ome_zarr_converters_tools/fractal/_models.py
update_acquisition_details(acquisition_details: AcquisitionDetails) -> AcquisitionDetails
Update AcquisitionDetails model with options from this model.
Parameters:
-
acquisition_details(AcquisitionDetails) –AcquisitionDetails model to update.
Returns:
-
AcquisitionDetails–Updated AcquisitionDetails model.
Source code in ome_zarr_converters_tools/fractal/_models.py
ChannelInfoUI
Bases: UserFacingModel
Set the name, wavelength, and display color of a channel.
Source code in ome_zarr_converters_tools/fractal/_models.py
channel_label: str
instance-attribute
Name of the channel, e.g. DAPI or GFP.
color: ColorMenu = ColorMenu.Auto
class-attribute
instance-attribute
Display color of the channel, e.g. for visualization purposes.
wavelength_id: str | None = Field(default=None, title='Wavelength ID')
class-attribute
instance-attribute
The wavelength ID of the channel. Some tasks can use it instead of the channel name, e.g. to apply illumination correction per wavelength in multiplexed acquisitions.
ConvertParallelInitArgs
Bases: UserFacingModel
Internal data handed from the init phase to compute; filled automatically.
Source code in ome_zarr_converters_tools/fractal/_models.py
converter_options: ConverterOptions
instance-attribute
Converter options forwarded from the init phase.
overwrite_mode: OverwriteMode = OverwriteMode.NO_OVERWRITE
class-attribute
instance-attribute
Overwrite mode forwarded from the init phase.
tiled_image_json_dump_url: str | None = None
class-attribute
instance-attribute
Location of the temporary file describing the image to convert.
tiled_image_json_str: str | None = None
class-attribute
instance-attribute
Inline description of the image to convert (used instead of a temporary file for small conversions).
MultiprocessingRunner
Bases: BaseModel
Runner for executing compound tasks using multiprocessing.
Source code in ome_zarr_converters_tools/fractal/_compound_task_wrapper.py
PixelSizeModel
Bases: UserFacingModel
Override the pixel size and the Z/time spacing of the images.
Source code in ome_zarr_converters_tools/fractal/_models.py
t_spacing: float = Field(title='Time Spacing')
class-attribute
instance-attribute
Time spacing in seconds.
xy_pixel_size: float = Field(title='XY Pixel Size')
class-attribute
instance-attribute
XY pixel size in micrometers.
z_spacing: float = Field(title='Z Spacing')
class-attribute
instance-attribute
Z spacing in micrometers.
SequentialRunner
ThreadedRunner
Bases: BaseModel
Runner for executing compound tasks using threads.
Source code in ome_zarr_converters_tools/fractal/_compound_task_wrapper.py
cleanup_if_exists(temp_json_url: str)
Clean up the temporary JSON directory if it exists.
If cleaning up is not possible, log an error message, but do not raise.
Parameters:
-
temp_json_url(str) –The URL to the temporary JSON directory.
Source code in ome_zarr_converters_tools/fractal/_json_utils.py
converters_tools_models(base: str = 'ome_zarr_converters_tools') -> list[tuple[str, str, str]]
Get all input models for Fractal tasks API.
Returns:
-
list[tuple[str, str, str]]–List of input models.
Source code in ome_zarr_converters_tools/fractal/_models.py
dump_json_str(temp_json_url: str, json_str: str) -> str
Write a pre-serialized JSON string to a unique file in temp_json_url.
Source code in ome_zarr_converters_tools/fractal/_json_utils.py
dump_to_json(temp_json_url: str, tiled_image: TiledImage) -> str
Create a JSON file for the tiled image.
exec_compound_task(init_task_fn: Callable[..., dict], compute_task_fn: Callable[..., ImageListUpdateDict], init_task_kwargs: dict, compute_task_kwargs: dict | None = None, runner: RunnerType | None = None) -> list[ImageListUpdateDict]
Execute a Fractal compound task.
Runs init_task_fn once to obtain a parallelization_list, then calls
compute_task_fn for each item, merging compute_task_kwargs into each
call. Results are returned in the same order as parallelization_list.
Parameters:
-
init_task_fn(Callable[..., dict]) –Returns a dict with a
"parallelization_list"key. -
compute_task_fn(Callable[..., ImageListUpdateDict]) –Invoked once per parallelization item. When using
MultiprocessingRunner, this must be a picklable module-level function. -
init_task_kwargs(dict) –Keyword arguments forwarded to
init_task_fn. -
compute_task_kwargs(dict | None, default:None) –Additional kwargs merged into each compute call.
-
runner(RunnerType | None, default:None) –Execution strategy. Defaults to sequential when
None.
Returns:
-
list[ImageListUpdateDict]–List of
ImageListUpdateDictinparallelization_listorder.
Source code in ome_zarr_converters_tools/fractal/_compound_task_wrapper.py
generic_compute_task(*, zarr_url: str, init_args: ConvertParallelInitArgs | dict, collection_type: type[CollectionInterfaceType], image_loader_type: type[ImageLoaderInterfaceType], resource: Any | None = None) -> ImageListUpdateDict
Initialize the task to convert a LIF plate to OME-Zarr.
Parameters:
-
zarr_url(str) –URL to the OME-Zarr file.
-
init_args(ConvertParallelInitArgs | dict) –Arguments from the initialization task. Accepts either a
ConvertParallelInitArgsinstance or a plain dict (as produced by Fractal's orchestration layer). -
collection_type(type[CollectionInterfaceType]) –The collection type to use when loading the
TiledImage. -
image_loader_type(type[ImageLoaderInterfaceType]) –The image loader type to use when loading the
TiledImage. -
resource(Any | None, default:None) –The resource to associate with the context model.
Returns:
-
ImageListUpdateDict–The Fractal image-list update entry for the converted image.
Source code in ome_zarr_converters_tools/fractal/_compute_task.py
remove_json(tiled_image_json_dump_url: str)
Clean up the JSON file and the directory if it is empty.
Parameters:
-
tiled_image_json_dump_url(str) –The URL to the json file.
Source code in ome_zarr_converters_tools/fractal/_json_utils.py
setup_images_for_conversion(tiled_images: list[TiledImage], *, zarr_dir: str, collection_type: str, converter_options: ConverterOptions, overwrite_mode: OverwriteMode = OverwriteMode.NO_OVERWRITE, ngff_version: NgffVersions = DefaultNgffVersion) -> list[dict]
Setup the OME-Zarr collection from converted tiled images.
This function run all the necessary steps to setup before parallel conversion. - Build the OME-Zarr collection structure. - Build the parallelization list (used by the fractal compute task).
Parameters:
-
tiled_images(list[TiledImage]) –List of tiled images that have been converted.
-
zarr_dir(str) –The base directory for the zarr data.
-
collection_type(str) –The type of collection to set up.
-
converter_options(ConverterOptions) –The converter options to use during conversion.
-
overwrite_mode(OverwriteMode, default:NO_OVERWRITE) –The overwrite mode to use when writing the data.
-
ngff_version(NgffVersions, default:DefaultNgffVersion) –The NGFF version to use when setting up the collection.
Source code in ome_zarr_converters_tools/fractal/_init_task.py
tiled_image_from_json(tiled_image_json_dump_url: str, collection_type: type[CollectionInterfaceType], image_loader_type: type[ImageLoaderInterfaceType]) -> TiledImage
Load the json TiledImage object.
Since TiledImage is a generic model, we need to specify the concrete types when loading it from json otherwise pydantic cannot infer them.
Parameters:
-
tiled_image_json_dump_url(str) –The URL to the json file.
-
collection_type(type[CollectionInterfaceType]) –The concrete collection type of the
TiledImage. -
image_loader_type(type[ImageLoaderInterfaceType]) –The concrete image loader type of the
TiledImage.
Returns:
-
TiledImage–The loaded
TiledImageobject.
Source code in ome_zarr_converters_tools/fractal/_json_utils.py
tiled_image_from_json_str(json_str: str, collection_type: type[CollectionInterfaceType], image_loader_type: type[ImageLoaderInterfaceType]) -> TiledImage
Deserialize a TiledImage from a JSON string (no filesystem I/O).
Parameters:
-
json_str(str) –The JSON string to deserialize.
-
collection_type(type[CollectionInterfaceType]) –The concrete collection type of the TiledImage.
-
image_loader_type(type[ImageLoaderInterfaceType]) –The concrete image loader type of the TiledImage.
Returns:
-
TiledImage–The loaded
TiledImageobject.
Source code in ome_zarr_converters_tools/fractal/_json_utils.py
Testing
Snapshot-testing helpers shipped for downstream converter test suites. Load the pytest plugin from a consumer's tests/conftest.py with pytest_plugins = ["ome_zarr_converters_tools.testing.plugin"]; it provides the --update-snapshots / --extended options, the extended marker, and the update_snapshots fixture.
ome_zarr_converters_tools.testing
Snapshot testing helpers for OME-Zarr converters.
The heavy _snapshot module (numpy/ngio/pydantic) is imported lazily so that
loading the pytest plugin (ome_zarr_converters_tools.testing.plugin, wired via
pytest_plugins in each consumer's conftest, not a pytest11 entry point) does
not pull it in — this keeps plugin load cheap and lets coverage instrument
_snapshot when tests first import it.
FingerprintModel
Bases: BaseModel
Compact pixel-content signature for a single ROI.
Source code in ome_zarr_converters_tools/testing/_snapshot.py
from_array(arr: np.ndarray, decimals: int = _FINGERPRINT_DECIMALS)
classmethod
Build a fingerprint from a pixel array.
Parameters:
-
arr(ndarray) –The pixel data read back from a ROI.
-
decimals(int, default:_FINGERPRINT_DECIMALS) –Decimals to round the stored stats to, and to round the array to before hashing.
Source code in ome_zarr_converters_tools/testing/_snapshot.py
ImageAssertionModel
Bases: BaseModel
Expected metadata and per-table ROI fingerprints for one image.
Source code in ome_zarr_converters_tools/testing/_snapshot.py
MultiPlateAssertionModel
Bases: BaseModel
Snapshot for HCS plate output: one or more plates keyed by zarr name.
Source code in ome_zarr_converters_tools/testing/_snapshot.py
MultiSingleImageAssertionModel
Bases: BaseModel
Snapshot for single-image output: images keyed by zarr name.
Source code in ome_zarr_converters_tools/testing/_snapshot.py
PlateAssertionModel
Bases: BaseModel
Expected wells and images for a single plate.
A top-level images_common mapping may be supplied on input to factor out
assertions shared by every image; it is deep-merged into each image and not
retained on the model.
Source code in ome_zarr_converters_tools/testing/_snapshot.py
validate_images(values)
classmethod
Deep-merge images_common into every image entry.
images_common provides shared defaults; per-image values override them.
Source code in ome_zarr_converters_tools/testing/_snapshot.py
RoiAssertionModel
Bases: BaseModel
Expected fingerprint and geometry for a single ROI.
Source code in ome_zarr_converters_tools/testing/_snapshot.py
TableAssertionModel
__getattr__(name: str)
Lazily resolve public names from _snapshot on first access.
Source code in ome_zarr_converters_tools/testing/__init__.py
build_snapshot(*, zarr_dir: Path, image_list_updates: list[dict], output_type: Literal['plate', 'single_image'] = 'plate') -> MultiPlateAssertionModel | MultiSingleImageAssertionModel
Build a snapshot model from converted OME-Zarr output.
This is the single source of truth for both snapshot generation and
validation: the returned model is either written to disk or compared against
the on-disk expectation. The returned model also carries an informational
versions block (dependency versions at generation time), which is never
compared.
Parameters:
-
zarr_dir(Path) –Directory the converter wrote its output into.
-
image_list_updates(list[dict]) –The list returned by the converter's init task.
-
output_type(Literal['plate', 'single_image'], default:'plate') –"plate"for HCS plate output,"single_image"for individual containers at the top level ofzarr_dir.
Source code in ome_zarr_converters_tools/testing/_snapshot.py
compare_snapshots(expected: MultiPlateAssertionModel | MultiSingleImageAssertionModel, actual: MultiPlateAssertionModel | MultiSingleImageAssertionModel) -> list[str]
Compare an expected snapshot against a freshly built one.
Returns a list of human-readable, fully-pathed difference messages (empty when the snapshots match). Floating-point stats use a tolerance; the sha256 pixel hash and structural fields are compared exactly.
The versions block is deliberately not compared: it is informational only
(a dependency version drift must never fail a snapshot test).
Source code in ome_zarr_converters_tools/testing/_snapshot.py
run_converter_test(*, tmp_path: Path, api_fn: Callable, api_kwargs: dict, snapshot_path: Path, update_snapshots: bool, converter_options: ConverterOptions | None = None, output_type: Literal['plate', 'single_image'] = 'plate') -> None
Run a converter end-to-end and check it against a snapshot.
Runs api_fn into a temporary (or snapshot-adjacent) zarr directory and
builds a snapshot from the output. With update_snapshots the snapshot is
written to snapshot_path as JSON; otherwise it is compared against the
on-disk snapshot and a single AssertionError listing every difference is
raised on mismatch.
Parameters:
-
tmp_path(Path) –Pytest
tmp_pathfor zarr output (validation mode). -
api_fn(Callable) –The high-level converter API function.
-
api_kwargs(dict) –Keyword arguments for
api_fn(e.g.acquisitions). -
snapshot_path(Path) –Path to the snapshot JSON file.
-
update_snapshots(bool) –If True, (re)generate the snapshot instead of checking.
-
converter_options(ConverterOptions | None, default:None) –Options controlling the conversion; passed to
api_fnonly when provided. -
output_type(Literal['plate', 'single_image'], default:'plate') –"plate"for HCS plate output,"single_image"for individual zarr containers at the top level of the output directory.