Skip to content

czitools.utils #

Utility helpers for czitools.

Contains tools for logging configuration, metadata boxing, array scaling, planetable generation, pixel type inspection, HCS metadata display, and napari display helpers.

Modules:

  • box –

    Utilities for loading CZI metadata as a python-box Box object.

  • hcs_tools –

    HCS plate metadata display utilities using rich formatting.

  • logging_tools –

    Logging configuration helpers for czitools.

  • misc –

    Miscellaneous utility functions for czitools.

  • napari_helpers –

    Napari integration helpers for czitools.

  • napari_tools –

    Napari display helpers for czitools.

  • ndv_tools –

    NDV viewer helpers for czitools.

  • pixels –

    Pixel-type utilities for CZI images.

  • planetable –

    Plane-table (stage position) utilities for CZI files.

Functions:

  • calc_scaling –

    Calculate the scaling for better display

  • check_scenes_shape –

    Check if all scenes have the same shape within a pixel tolerance.

  • display_xarray_in_napari –

    Display an xarray DataArray (STCZYX[A]) in Napari.

  • display_xarray_list_in_napari –

    Display a list of xarray stacks in one Napari viewer.

  • filter_planetable –

    Filters the input planetable DataFrame based on specified dimension entries.

  • get_czimd_box –

    get_czimd_box: Get CZI metadata_tools as a python-box. For details: https://pypi.org/project/python-box/

  • get_fname_woext –

    Extracts the filename without its extension from a given file path.

  • get_planetable –

    Extracts the plane table from the individual subblocks of a CZI file.

  • get_pyczi_readertype –

    Determine the appropriate pylibCZIrw reader type for a CZI file path.

  • is_valid_czi_url –

    Validates whether a given URL points to a valid .czi file.

  • md2dataframe –

    Convert a CziMetadata object into a two-column pandas DataFrame.

  • print_hcs_plate_info –

    Print High-Content Screening (HCS) plate information with rich formatting.

  • print_sample_metadata –

    Print sample metadata and first scene details with rich formatting.

  • print_section_header –

    Print a formatted section header with rich styling.

  • print_well_fields –

    Print detailed field information for a specific well with rich formatting.

  • save_planetable –

    Saves a pandas dataframe as a CSV file.

  • set_logging –

    Configures a standard Python logger with customizable level and format.

calc_scaling #

calc_scaling(
    data: ndarray | Array | Array,
    corr_min: float = 1.0,
    offset_min: int = 0,
    corr_max: float = 0.85,
    offset_max: int = 0,
) -> tuple[int, int]

Calculate the scaling for better display

Parameters:

  • data #

    (Union[ndarray, array, array]) –

    Array to calculate scaling.

  • corr_min #

    (float, default: 1.0 ) –

    Correction factor for minimum value. Defaults to 1.0.

  • offset_min #

    (int, default: 0 ) –

    Offset for minimum value. Defaults to 0.

  • corr_max #

    (float, default: 0.85 ) –

    Correction factor for maximum value. Defaults to 0.85.

  • offset_max #

    (int, default: 0 ) –

    Offset for maximum value. Defaults to 0.

Returns:

  • tuple[int, int] –

    Tuple[int, int]: Tuple with minimum value and maximum value.

Raises:

  • ValueError –

    If the data array is not of type numpy.ndarray, dask.array or zarr.array.

Source code in czitools/utils/misc.py
 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
def calc_scaling(
    data: np.ndarray | da.Array | zarr.Array,
    corr_min: float = 1.0,
    offset_min: int = 0,
    corr_max: float = 0.85,
    offset_max: int = 0,
) -> tuple[int, int]:
    """Calculate the scaling for better display

    Args:
        data (Union[numpy.ndarray, dask.array, zarr.array]): Array to calculate scaling.
        corr_min (float, optional): Correction factor for minimum value. Defaults to 1.0.
        offset_min (int, optional): Offset for minimum value. Defaults to 0.
        corr_max (float, optional): Correction factor for maximum value. Defaults to 0.85.
        offset_max (int, optional): Offset for maximum value. Defaults to 0.

    Returns:
        Tuple[int, int]: Tuple with minimum value and maximum value.

    Raises:
        ValueError: If the data array is not of type numpy.ndarray, dask.array or zarr.array.

    """

    start = time.time()

    # get min-max values for initial scaling
    if isinstance(data, zarr.Array):
        # Wrap in dask so reduction is done chunk-by-chunk without loading the
        # full array into memory; also avoids zarr version API differences
        _dask_view = da.from_zarr(data)
        minvalue, maxvalue = da.compute(_dask_view.min(), _dask_view.max())
    elif isinstance(data, da.Array):
        # compute only once since this is faster
        minvalue, maxvalue = da.compute(data.min(), data.max())
    else:
        minvalue, maxvalue = np.min(data), np.max(data)

    end = time.time()

    minvalue = int(np.round((minvalue + offset_min) * corr_min, 0))
    maxvalue = int(np.round((maxvalue + offset_max) * corr_max, 0))

    logger.info(f"Scaling: {minvalue}, {maxvalue}")
    logger.info(f"Calculation of Min-Max [s] : {end - start}")

    return minvalue, maxvalue

check_scenes_shape #

check_scenes_shape(
    czidoc: CziReader,
    size_s: int | None,
    tolerance: int = 1,
) -> bool

Check if all scenes have the same shape within a pixel tolerance.

Parameters:

  • czidoc #

    (CziReader) –

    CziReader to read the properties

  • size_s #

    (Union[int, None]) –

    Size of scene dimension

  • tolerance #

    (int, default: 1 ) –

    Maximum allowed pixel difference in width or height between scenes. Defaults to 1 to absorb sub-pixel rounding in plate coordinate systems.

Returns:

  • bool ( bool ) –

    True if all scenes have XY shapes within tolerance pixels

Source code in czitools/utils/pixels.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def check_scenes_shape(czidoc: pyczi.CziReader, size_s: int | None, tolerance: int = 1) -> bool:
    """Check if all scenes have the same shape within a pixel tolerance.

    Args:
        czidoc (pyczi.CziReader): CziReader to read the properties
        size_s (Union[int, None]): Size of scene dimension
        tolerance (int): Maximum allowed pixel difference in width or height
            between scenes. Defaults to 1 to absorb sub-pixel rounding in
            plate coordinate systems.

    Returns:
        bool: True if all scenes have XY shapes within ``tolerance`` pixels
    """
    if size_s is None:
        return True

    scene_rectangles = czidoc.scenes_bounding_rectangle_no_pyramid or czidoc.scenes_bounding_rectangle
    if not scene_rectangles:
        return True

    scene_width = [rectangle.w for rectangle in scene_rectangles.values()]
    scene_height = [rectangle.h for rectangle in scene_rectangles.values()]

    return (max(scene_width) - min(scene_width)) <= tolerance and (max(scene_height) - min(scene_height)) <= tolerance

display_xarray_in_napari #

display_xarray_in_napari(
    array6d: Any,
    mdata: Any,
    subset_planes: Mapping[str, Any] | None = None,
    *,
    run: bool = True,
) -> Any

Display an xarray DataArray (STCZYX[A]) in Napari.

Parameters:

  • array6d #

    (Any) –

    xarray.DataArray with axes including C and Z.

  • mdata #

    (Any) –

    CziMetadata instance (used for channel names/colors/scaling).

  • subset_planes #

    (Mapping[str, Any] | None, default: None ) –

    dict describing subset planes (as returned in array6d.attrs['subset_planes']). If provided, used to map channel indices and names.

  • run #

    (bool, default: True ) –

    Start Napari's blocking event loop. Set this to False in a Jupyter notebook so the viewer remains available to later cells.

Returns:

  • Any –

    The created Napari viewer. With run=True, the viewer's Qt window

  • Any –

    may already be closed when this function returns.

Notes
  • If Napari is not installed this function raises ImportError.
Source code in czitools/utils/napari_tools.py
 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
def display_xarray_in_napari(
    array6d: Any,
    mdata: Any,
    subset_planes: Mapping[str, Any] | None = None,
    *,
    run: bool = True,
) -> Any:
    """Display an xarray DataArray (STCZYX[A]) in Napari.

    Args:
        array6d: xarray.DataArray with axes including C and Z.
        mdata: CziMetadata instance (used for channel names/colors/scaling).
        subset_planes: dict describing subset planes (as returned in
            `array6d.attrs['subset_planes']`). If provided, used to map
            channel indices and names.
        run: Start Napari's blocking event loop. Set this to ``False`` in a
            Jupyter notebook so the viewer remains available to later cells.

    Returns:
        The created Napari viewer. With ``run=True``, the viewer's Qt window
        may already be closed when this function returns.

    Notes:
        - If Napari is not installed this function raises ImportError.
    """
    # Import napari lazily so czitools does not require it as a dependency.
    try:
        import napari
    except Exception as exc:  # pragma: no cover - optional dependency
        raise ImportError(
            "Napari is required for display_xarray_in_napari but is not installed. "
            "Install napari or skip viewer display. Original error: " + str(exc)
        )

    if subset_planes is None:
        subset_planes_map: Mapping[str, Any] = array6d.attrs.get("subset_planes", {})
    else:
        subset_planes_map = subset_planes

    viewer = napari.Viewer()
    _add_xarray_to_viewer(viewer, array6d, mdata, subset_planes_map)

    if run:
        napari.run()

    return viewer

display_xarray_list_in_napari #

display_xarray_list_in_napari(
    arrays: Sequence[Any],
    mdata: Any,
    subset_planes_list: Sequence[Mapping[str, Any]]
    | None = None,
    *,
    run: bool = True,
) -> Any

Display a list of xarray stacks in one Napari viewer.

This supports stacks with different spatial shapes by adding each stack as its own set of layers.

Parameters:

  • arrays #

    (Sequence[Any]) –

    Sequence of xarray stacks to display.

  • mdata #

    (Any) –

    CZI metadata used for channel names, colors, and scaling.

  • subset_planes_list #

    (Sequence[Mapping[str, Any]] | None, default: None ) –

    Optional subset metadata for each stack.

  • run #

    (bool, default: True ) –

    Start Napari's blocking event loop. Set this to False in a Jupyter notebook so the viewer remains available to later cells.

Returns:

  • Any –

    The created Napari viewer. With run=True, the viewer's Qt window

  • Any –

    may already be closed when this function returns.

Source code in czitools/utils/napari_tools.py
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
def display_xarray_list_in_napari(
    arrays: Sequence[Any],
    mdata: Any,
    subset_planes_list: Sequence[Mapping[str, Any]] | None = None,
    *,
    run: bool = True,
) -> Any:
    """Display a list of xarray stacks in one Napari viewer.

    This supports stacks with different spatial shapes by adding each stack as
    its own set of layers.

    Args:
        arrays: Sequence of xarray stacks to display.
        mdata: CZI metadata used for channel names, colors, and scaling.
        subset_planes_list: Optional subset metadata for each stack.
        run: Start Napari's blocking event loop. Set this to ``False`` in a
            Jupyter notebook so the viewer remains available to later cells.

    Returns:
        The created Napari viewer. With ``run=True``, the viewer's Qt window
        may already be closed when this function returns.
    """
    try:
        import napari
    except Exception as exc:  # pragma: no cover - optional dependency
        raise ImportError(
            "Napari is required for display_xarray_list_in_napari but is not installed. "
            "Install napari or skip viewer display. Original error: " + str(exc)
        )

    viewer = napari.Viewer()
    for idx, arr in enumerate(arrays):
        if subset_planes_list is not None and idx < len(subset_planes_list):
            subset_planes_map = subset_planes_list[idx]
        else:
            subset_planes_map = arr.attrs.get("subset_planes", {})
        _add_xarray_to_viewer(viewer, arr, mdata, subset_planes_map, layer_prefix=f"S{idx}_")

    if run:
        napari.run()

    return viewer

filter_planetable #

filter_planetable(
    planetable: DataFrame,
    planes: dict[str, int] | None = None,
) -> DataFrame

Filters the input planetable DataFrame based on specified dimension entries.

The function uses the planes dictionary to filter the planetable on various dimensions such as scene index, time index, z-plane index, and channel index. If a dimension is not specified in the planes dictionary, it will not be used for filtering. Only valid keys are accepted, which are 'scene', 'time', 'zplane', and 'channel'. An error is raised for invalid keys.

Parameters:

  • planetable #

    (DataFrame) –

    The DataFrame to be filtered. It should contain columns "S", "M", "T", "Z", and "C".

  • planes #

    (Optional[Dict[str, int]], default: None ) –

    A dictionary specifying the indices to filter on. Valid keys include: - 'scene': The scene index. - 'time': The time index. - 'zplane': The z-plane index. - 'channel': The channel index.

Returns:

  • DataFrame –

    pd.DataFrame: The filtered planetable.

Raises:

  • ValueError –

    If an invalid key is passed in the planes dictionary.

Examples:

>>> planetable = pd.DataFrame({'S': [0, 1, 1], 'T': [0, 1, 0], 'Z': [0, 1, 1], 'C': [0, 1, 1]})
>>> filter_planetable(planetable, planes={'scene': 1, 'time': 0})
S  T  Z  C
1  0  1  1
Source code in czitools/utils/planetable.py
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
def filter_planetable(planetable: pd.DataFrame, planes: dict[str, int] | None = None) -> pd.DataFrame:
    """
    Filters the input planetable DataFrame based on specified dimension entries.

    The function uses the `planes` dictionary to filter the planetable on
    various dimensions such as scene index, time index, z-plane index, and channel index.
    If a dimension is not specified in the `planes` dictionary, it will not be used for filtering.
    Only valid keys are accepted, which are 'scene', 'time', 'zplane', and 'channel'.
    An error is raised for invalid keys.

    Args:
        planetable (pd.DataFrame): The DataFrame to be filtered.
            It should contain columns "S", "M", "T", "Z", and "C".
        planes (Optional[Dict[str, int]]): A dictionary specifying the indices to filter on.
            Valid keys include:
                - 'scene': The scene index.
                - 'time': The time index.
                - 'zplane': The z-plane index.
                - 'channel': The channel index.

    Returns:
        pd.DataFrame: The filtered planetable.

    Raises:
        ValueError: If an invalid key is passed in the `planes` dictionary.

    Examples:
        >>> planetable = pd.DataFrame({'S': [0, 1, 1], 'T': [0, 1, 0], 'Z': [0, 1, 1], 'C': [0, 1, 1]})
        >>> filter_planetable(planetable, planes={'scene': 1, 'time': 0})
        S  T  Z  C
        1  0  1  1
    """

    # Define valid keys for filtering
    valid_args = ["scene", "tile", "time", "zplane", "channel"]

    # If no filtering criteria are provided, return the unfiltered planetable
    if planes is None:
        return planetable

    # Check for invalid keys in the `planes` dictionary
    for k in planes:
        if k not in valid_args:
            raise ValueError(f"Invalid keyword argument: {k}")

    # Apply filtering for each valid key if it exists in `planes`
    if "scene" in planes:
        planetable = planetable[planetable["S"] == planes["scene"]]

    if "tile" in planes:
        planetable = planetable[planetable["M"] == planes["tile"]]

    if "time" in planes:
        planetable = planetable[planetable["T"] == planes["time"]]

    if "zplane" in planes:
        planetable = planetable[planetable["Z"] == planes["zplane"]]

    if "channel" in planes:
        planetable = planetable[planetable["C"] == planes["channel"]]

    return planetable

get_czimd_box #

get_czimd_box(filepath: str | PathLike[str]) -> Box

get_czimd_box: Get CZI metadata_tools as a python-box. For details: https://pypi.org/project/python-box/

Parameters:

Returns:

  • Box ( Box ) –

    CZI metadata_tools as a Box object

Source code in czitools/utils/box.py
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 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
def get_czimd_box(filepath: str | os.PathLike[str]) -> Box:
    """
    get_czimd_box: Get CZI metadata_tools as a python-box. For details: https://pypi.org/project/python-box/

    Args:
        filepath (Union[str, os.PathLike[str]]): Filepath of the CZI file

    Returns:
        Box: CZI metadata_tools as a Box object
    """

    readertype = pyczi.ReaderFileInputTypes.Standard

    if validators.url(str(filepath)):
        readertype = pyczi.ReaderFileInputTypes.Curl

    # get metadata_tools dictionary using pylibCZIrw
    with pyczi.open_czi(str(filepath), readertype) as czi_document:
        metadata_dict = czi_document.metadata
        # total_bounding_box_no_pyramid = czi_document.total_bounding_box_no_pyramid
        scenes_bounding_rectangle = czi_document.scenes_bounding_rectangle

    czimd_box = Box(
        metadata_dict,
        conversion_box=True,
        default_box=True,
        default_box_attr=None,
        default_box_create_on_get=True,
        # default_box_no_key_error=True
    )

    # add the filepath
    czimd_box.filepath = filepath
    czimd_box.is_url = validators.url(str(filepath))
    czimd_box.czi_open_arg = readertype

    # set the defaults to False
    czimd_box.has_customattr = False
    czimd_box.has_experiment = False
    czimd_box.has_disp = False
    czimd_box.has_hardware = False
    czimd_box.has_scale = False
    czimd_box.has_instrument = False
    czimd_box.has_microscopes = False
    czimd_box.has_detectors = False
    czimd_box.has_objectives = False
    czimd_box.has_tubelenses = False
    czimd_box.has_disp = False
    czimd_box.has_channels = False
    czimd_box.has_info = False
    czimd_box.has_app = False
    czimd_box.has_doc = False
    czimd_box.has_image = False
    czimd_box.has_scenes = False
    czimd_box.has_T = False
    czimd_box.has_Z = False
    czimd_box.has_dims = False
    czimd_box.has_layers = False

    if "Experiment" in czimd_box.ImageDocument.Metadata:
        czimd_box.has_experiment = True

    if "HardwareSetting" in czimd_box.ImageDocument.Metadata:
        czimd_box.has_hardware = True

    if "CustomAttributes" in czimd_box.ImageDocument.Metadata:
        czimd_box.has_customattr = True

    if "Information" in czimd_box.ImageDocument.Metadata:
        czimd_box.has_info = True

        if "Application" in czimd_box.ImageDocument.Metadata.Information:
            czimd_box.has_app = True

        if "Document" in czimd_box.ImageDocument.Metadata.Information:
            czimd_box.has_doc = True

        if "Image" in czimd_box.ImageDocument.Metadata.Information:
            czimd_box.has_image = True

            if "Dimensions" in czimd_box.ImageDocument.Metadata.Information.Image:
                czimd_box.has_dims = True

                if "Channels" in czimd_box.ImageDocument.Metadata.Information.Image.Dimensions:
                    # if "C" in total_bounding_box_no_pyramid.keys():
                    czimd_box.has_channels = True

                if "T" in czimd_box.ImageDocument.Metadata.Information.Image.Dimensions:
                    # if "T" in total_bounding_box_no_pyramid.keys():
                    czimd_box.has_T = True

                if "Z" in czimd_box.ImageDocument.Metadata.Information.Image.Dimensions:
                    # if "Z" in total_bounding_box_no_pyramid.keys():
                    czimd_box.has_Z = True

                # if "S" in czimd_box.ImageDocument.Metadata.Information.Image.Dimensions:
                if len(scenes_bounding_rectangle) > 0:
                    czimd_box.has_scenes = True

        if "Instrument" in czimd_box.ImageDocument.Metadata.Information:
            czimd_box.has_instrument = True

            if "Detectors" in czimd_box.ImageDocument.Metadata.Information.Instrument:
                czimd_box.has_detectors = True

            if "Microscopes" in czimd_box.ImageDocument.Metadata.Information.Instrument:
                czimd_box.has_microscopes = True

            if "Objectives" in czimd_box.ImageDocument.Metadata.Information.Instrument:
                czimd_box.has_objectives = True

            if "TubeLenses" in czimd_box.ImageDocument.Metadata.Information.Instrument:
                czimd_box.has_tubelenses = True

    if "Scaling" in czimd_box.ImageDocument.Metadata:
        czimd_box.has_scale = True

    if "DisplaySetting" in czimd_box.ImageDocument.Metadata:
        czimd_box.has_disp = True

    if "Layers" in czimd_box.ImageDocument.Metadata:
        czimd_box.has_layers = True

    return czimd_box

get_fname_woext #

get_fname_woext(filepath: str | PathLike[str]) -> str

Extracts the filename without its extension from a given file path. It also works for extensions like myfile.abc.xyz The output will be: myfile

Parameters:

Returns: str: The filename without its extension.

Source code in czitools/utils/misc.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
def get_fname_woext(filepath: str | os.PathLike[str]) -> str:
    """
    Extracts the filename without its extension from a given file path.
    It also works for extensions like myfile.abc.xyz
    The output will be: myfile

    Args:
        filepath (Union[str, os.PathLike[str]]): The path to the file.
    Returns:
        str: The filename without its extension.
    """

    # create empty string
    real_extension = ""

    # get all part of the file extension
    sufs = Path(filepath).suffixes
    for s in sufs:
        real_extension = real_extension + s

    # remove real extension from filepath
    filepath_woext = filepath.replace(real_extension, "")

    return filepath_woext

get_planetable #

get_planetable(
    czipath: str | PathLike[str],
    norm_time: bool | None = True,
    save_table: bool | None = False,
    table_separator: str | None = ";",
    table_index: bool | None = True,
    planes: dict[str, int] | None = None,
    include_pyramid: bool = False,
) -> tuple[DataFrame, str | None]

Extracts the plane table from the individual subblocks of a CZI file.

Iterates all subblocks directly from the CZI file, extracting per-plane position, timing, and bounding-box data. Mosaic tile indices (M) are derived by counting subblocks sharing the same (S, T, C, Z) combination. When pyramid subblocks are included, tile indices are counted separately for each X/Y downsampling-factor pair and pyramid status.

Parameters:

  • czipath #

    (Union[str, PathLike[str]]) –

    The path to the CZI image file.

  • norm_time #

    (Optional[bool], default: True ) –

    Whether to normalize the timestamps. Defaults to True.

  • save_table #

    (Optional[bool], default: False ) –

    Whether to save the plane table to a CSV file. Defaults to False.

  • table_separator #

    (Optional[str], default: ';' ) –

    The separator for the CSV file. Defaults to ";".

  • table_index #

    (Optional[bool], default: True ) –

    Whether to include the index in the CSV file. Defaults to True.

  • planes #

    (Optional[Dict[str, int]], default: None ) –

    Optional dictionary for filtering planes by dimensions. Valid keys: 'scene', 'tile', 'time', 'channel', 'zplane'

  • include_pyramid #

    (bool, default: False ) –

    Include stored pyramid subblocks in addition to full-resolution subblocks. Defaults to False, preserving the existing table columns. When True, adds is_pyramid, stored_width, stored_height, downsample_x, and downsample_y. Downsampling factors are logical size divided by stored size; full resolution is 1.0. Bounding-box columns remain in full-resolution pixel coordinates. Tile indices at different resolutions do not imply matching source tiles.

Returns:

  • tuple[DataFrame, str | None] –

    Tuple[pd.DataFrame, Optional[str]]: A tuple containing: - A Pandas DataFrame representing the plane table. - The file path of the saved CSV file, if save_table is True; otherwise, None.

Raises:

  • ValueError –

    If pyramid inclusion is requested and a subblock has non-positive logical or stored spatial dimensions.

Examples:

>>> table, _ = get_planetable("image.czi", include_pyramid=True)
>>> pyramid_rows = table[table["is_pyramid"]]
Source code in czitools/utils/planetable.py
 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
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
def get_planetable(
    czipath: str | os.PathLike[str],
    norm_time: bool | None = True,
    save_table: bool | None = False,
    table_separator: str | None = ";",
    table_index: bool | None = True,
    planes: dict[str, int] | None = None,
    include_pyramid: bool = False,
) -> tuple[pd.DataFrame, str | None]:
    """
    Extracts the plane table from the individual subblocks of a CZI file.

    Iterates all subblocks directly from the CZI file, extracting per-plane
    position, timing, and bounding-box data.  Mosaic tile indices (M) are
    derived by counting subblocks sharing the same (S, T, C, Z) combination.
    When pyramid subblocks are included, tile indices are counted separately
    for each X/Y downsampling-factor pair and pyramid status.

    Args:
        czipath (Union[str, os.PathLike[str]]): The path to the CZI image file.
        norm_time (Optional[bool]): Whether to normalize the timestamps. Defaults to True.
        save_table (Optional[bool]): Whether to save the plane table to a CSV file. Defaults to False.
        table_separator (Optional[str]): The separator for the CSV file. Defaults to ";".
        table_index (Optional[bool]): Whether to include the index in the CSV file. Defaults to True.
        planes (Optional[Dict[str, int]]): Optional dictionary for filtering planes by dimensions.
            Valid keys: 'scene', 'tile', 'time', 'channel', 'zplane'
        include_pyramid (bool): Include stored pyramid subblocks in addition to
            full-resolution subblocks. Defaults to False, preserving the
            existing table columns. When True, adds ``is_pyramid``,
            ``stored_width``, ``stored_height``, ``downsample_x``, and
            ``downsample_y``. Downsampling factors are logical size divided
            by stored size; full resolution is 1.0. Bounding-box columns
            remain in full-resolution pixel coordinates. Tile indices at
            different resolutions do not imply matching source tiles.

    Returns:
        Tuple[pd.DataFrame, Optional[str]]: A tuple containing:
            - A Pandas DataFrame representing the plane table.
            - The file path of the saved CSV file, if ``save_table`` is True; otherwise, None.

    Raises:
        ValueError: If pyramid inclusion is requested and a subblock has
            non-positive logical or stored spatial dimensions.

    Examples:
        >>> table, _ = get_planetable("image.czi", include_pyramid=True)
        >>> pyramid_rows = table[table["is_pyramid"]]
    """
    if isinstance(czipath, Path):
        czipath = str(czipath)

    if validators.url(czipath):
        logger.warning("Reading PlaneTable from CZI via a link is not supported yet.")
        return pd.DataFrame(), None

    rows = []
    # Mosaic tile counter per dimension group and, optionally, spatial resolution.
    tile_counters: dict[tuple[int | float, ...], int] = {}
    pyramid_dtypes = {
        "is_pyramid": "bool",
        "stored_width": "int32",
        "stored_height": "int32",
        "downsample_x": "float64",
        "downsample_y": "float64",
    }

    with czifile_module.CziFile(czipath) as czi:
        subblocks = list(czi.subblocks())

        if HAS_PROGRESSBAR:
            widgets = [
                progressbar.Percentage(),
                " ",
                progressbar.Bar(),
                " ",
                progressbar.ETA(),
                " ",
                progressbar.SimpleProgress(),
            ]
            iterator = progressbar.progressbar(
                enumerate(subblocks),
                widgets=widgets,
                max_value=len(subblocks),
                term_width=80,
            )
        else:
            iterator = enumerate(subblocks)

        for sbcount, sb in iterator:
            de = sb.directory_entry

            if include_pyramid or not de.is_pyramid:
                s = _get_scene_index(de)
                t = _get_dim_start(de, "T")
                c = _get_dim_start(de, "C")
                z = _get_dim_start(de, "Z")

                xstart, ystart, width, height = _get_bbox(de)
                key = (s, t, c, z)
                pyramid_info = {}
                if include_pyramid:
                    stored_width = de.stored_shape[de.dims.index("X")]
                    stored_height = de.stored_shape[de.dims.index("Y")]
                    if min(width, height, stored_width, stored_height) <= 0:
                        raise ValueError(f"Subblock {sbcount} has non-positive spatial dimensions.")
                    downsample_x = width / stored_width
                    downsample_y = height / stored_height
                    key += (de.is_pyramid, downsample_x, downsample_y)
                    pyramid_info = {
                        "is_pyramid": de.is_pyramid,
                        "stored_width": stored_width,
                        "stored_height": stored_height,
                        "downsample_x": downsample_x,
                        "downsample_y": downsample_y,
                    }
                m = tile_counters.get(key, 0)
                tile_counters[key] = m + 1

                # sb.metadata() returns an XML string in czifile
                md_raw = sb.metadata()
                try:
                    md_xml = ET.fromstring(md_raw) if md_raw else None
                except ET.ParseError:
                    md_xml = None

                timestamp, xpos, ypos, zpos = _getsbinfo(md_xml)

                rows.append(
                    {
                        "Subblock": sbcount,
                        "S": s,
                        "M": m,
                        "T": t,
                        "C": c,
                        "Z": z,
                        "X[micron]": xpos,
                        "Y[micron]": ypos,
                        "Z[micron]": zpos,
                        "Time[s]": timestamp,
                        "xstart": xstart,
                        "ystart": ystart,
                        "width": width,
                        "height": height,
                        **pyramid_info,
                    }
                )

    df_czi = _initialize_planetable_dataframe()
    if include_pyramid:
        for column, dtype in pyramid_dtypes.items():
            df_czi[column] = pd.Series(dtype=dtype)
    if rows:
        df_czi = pd.concat([df_czi, pd.DataFrame(rows)], ignore_index=True)

    # Sort by dimension indices to produce the same ordered output as the old
    # nested-loop implementation, then renumber Subblock sequentially.
    sort_columns = ["S", "M", "T", "C", "Z"]
    if include_pyramid:
        sort_columns += ["downsample_x", "downsample_y", "is_pyramid"]
    df_czi = df_czi.sort_values(sort_columns).reset_index(drop=True)

    # Apply planes filter
    if planes is not None:
        df_czi = filter_planetable(df_czi, planes)
        df_czi = df_czi.reset_index(drop=True)

    # Sequential Subblock numbering (0-based) on the final ordered, filtered set
    df_czi["Subblock"] = np.arange(len(df_czi), dtype="int32")

    # Enforce column dtypes
    df_czi = df_czi.astype(
        {
            "Subblock": "int32",
            "S": "int32",
            "M": "int32",
            "T": "int32",
            "C": "int32",
            "Z": "int32",
            "xstart": "int32",
            "ystart": "int32",
            "width": "int32",
            "height": "int32",
        },
        errors="ignore",
    )

    if include_pyramid:
        df_czi = df_czi.astype(pyramid_dtypes)

    if norm_time:
        df_czi = _norm_columns(df_czi, colname="Time[s]", mode="min")

    if save_table:
        return _save_planetable_if_requested(df_czi, czipath, table_separator, table_index)

    return df_czi, None

get_pyczi_readertype #

get_pyczi_readertype(
    filepath: str | PathLike[str],
) -> tuple[ReaderFileInputTypes, bool]

Determine the appropriate pylibCZIrw reader type for a CZI file path.

This utility function checks whether the filepath is a URL or a local file and returns the appropriate reader type for pylibCZIrw.

Parameters:

  • filepath #

    (str | PathLike[str]) –

    Path to the CZI file. Can be a local path or a URL.

Returns:

  • tuple[ReaderFileInputTypes, bool] –

    Tuple of (reader_type, is_url) where: - reader_type: pyczi.ReaderFileInputTypes.Curl for URLs, pyczi.ReaderFileInputTypes.Standard for local files. - is_url: True if the filepath is a valid URL, False otherwise.

Source code in czitools/utils/misc.py
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
def get_pyczi_readertype(
    filepath: str | os.PathLike[str],
) -> tuple[pyczi.ReaderFileInputTypes, bool]:
    """Determine the appropriate pylibCZIrw reader type for a CZI file path.

    This utility function checks whether the filepath is a URL or a local file
    and returns the appropriate reader type for pylibCZIrw.

    Args:
        filepath: Path to the CZI file. Can be a local path or a URL.

    Returns:
        Tuple of (reader_type, is_url) where:
            - reader_type: pyczi.ReaderFileInputTypes.Curl for URLs,
                          pyczi.ReaderFileInputTypes.Standard for local files.
            - is_url: True if the filepath is a valid URL, False otherwise.
    """
    # Convert Path to string if needed
    if isinstance(filepath, Path):
        filepath = str(filepath)

    if validators.url(str(filepath)):
        return pyczi.ReaderFileInputTypes.Curl, True
    else:
        return pyczi.ReaderFileInputTypes.Standard, False

is_valid_czi_url #

is_valid_czi_url(myurl: str) -> tuple[bool, str]

Validates whether a given URL points to a valid .czi file. Args: myurl (str): The URL to validate. Returns: tuple: - bool: True if the URL is valid and points to a .czi file, False otherwise. - str: A message providing details about the validation result. Validation Steps: 1. Checks if the URL has a valid format using a URL validator. 2. Ensures the URL ends with the '.czi' file extension. 3. Sends an HTTP HEAD request to verify the file's existence and accessibility. - If accessible, optionally checks the Content-Type header for additional validation. Raises: None: Any exceptions during the HTTP request are caught and included in the return message.

Source code in czitools/utils/misc.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
def is_valid_czi_url(myurl: str) -> tuple[bool, str]:
    """
    Validates whether a given URL points to a valid .czi file.
    Args:
        myurl (str): The URL to validate.
    Returns:
        tuple:
            - bool: True if the URL is valid and points to a .czi file, False otherwise.
            - str: A message providing details about the validation result.
    Validation Steps:
        1. Checks if the URL has a valid format using a URL validator.
        2. Ensures the URL ends with the '.czi' file extension.
        3. Sends an HTTP HEAD request to verify the file's existence and accessibility.
           - If accessible, optionally checks the Content-Type header for additional validation.
    Raises:
        None: Any exceptions during the HTTP request are caught and included in the return message.
    """
    # Step 1: Validate the URL format
    if not validators.url(myurl):
        return False, "Invalid URL format"

    # Step 3: Verify the file exists by making a HEAD request
    try:
        response = requests.head(myurl, allow_redirects=True)
        if response.status_code == 200:
            # Optionally, check the Content-Type header for additional validation
            content_type = response.headers.get("Content-Type", "")
            if "application/octet-stream" in content_type or "czi" in content_type:
                return True, "Valid .czi file URL"
            else:
                return True, "File exists but Content-Type is not specific to .czi"
        else:
            return (
                False,
                f"File not accessible, HTTP status code: {response.status_code}",
            )
    except requests.RequestException as e:
        return False, f"Error during HTTP request: {e}"

md2dataframe #

md2dataframe(
    mdata: CziMetadata,
    reduced_params: bool = True,
    paramcol: str = "Parameter",
    keycol: str = "Value",
) -> DataFrame

Convert a CziMetadata object into a two-column pandas DataFrame.

Flattens the metadata object into a key-value dictionary and represents each entry as a row in the returned DataFrame.

Parameters:

  • mdata #

    (CziMetadata) –

    The CziMetadata instance to convert.

  • reduced_params #

    (bool, default: True ) –

    If True, only include a subset of key metadata parameters.

  • paramcol #

    (str, default: 'Parameter' ) –

    Column name for the parameter (key) column. Defaults to "Parameter".

  • keycol #

    (str, default: 'Value' ) –

    Column name for the value column. Defaults to "Value".

Returns:

  • DataFrame –

    DataFrame with one row per metadata entry and columns paramcol / keycol.

Source code in czitools/utils/misc.py
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
def md2dataframe(
    mdata: "CziMetadata", reduced_params: bool = True, paramcol: str = "Parameter", keycol: str = "Value"
) -> pd.DataFrame:
    """Convert a CziMetadata object into a two-column pandas DataFrame.

    Flattens the metadata object into a key-value dictionary and represents
    each entry as a row in the returned DataFrame.

    Args:
        mdata: The CziMetadata instance to convert.
        reduced_params: If True, only include a subset of key metadata parameters.
        paramcol: Column name for the parameter (key) column. Defaults to "Parameter".
        keycol: Column name for the value column. Defaults to "Value".

    Returns:
        DataFrame with one row per metadata entry and columns ``paramcol`` / ``keycol``.
    """
    # Deferred import to avoid circular dependency between utils and metadata_tools
    from czitools.metadata_tools.czi_metadata import _obj2dict  # noqa: PLC0415
    from czitools.metadata_tools.czi_metadata import create_md_dict_red  # noqa: PLC0415

    if reduced_params:
        md_dict = create_md_dict_red(mdata)
    else:
        # Flatten the CziMetadata object into a plain key-value dictionary
        md_dict = _obj2dict(mdata)

    # Initialise an empty DataFrame with the desired column names
    mdframe = pd.DataFrame(columns=[paramcol, keycol])

    for k in md_dict.keys():
        # Build a single-row DataFrame for each metadata entry and append it
        d = {paramcol: k, keycol: md_dict[k]}
        df = pd.DataFrame([d], index=[0])
        mdframe = pd.concat([mdframe, df], ignore_index=True)

    return mdframe

print_hcs_plate_info #

print_hcs_plate_info(
    metadata: CziMetadata, show_well_table: bool = True
) -> None

Print High-Content Screening (HCS) plate information with rich formatting.

Displays plate hierarchy, dimensions, well count, and optionally a summary table of all wells with their positions and field counts.

Parameters:

  • metadata #

    (CziMetadata) –

    CziMetadata object containing file information.

  • show_well_table #

    (bool, default: True ) –

    Whether to display the well summary table. Defaults to True. Set to False to hide the table for large plates.

Source code in czitools/utils/hcs_tools.py
38
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
def print_hcs_plate_info(metadata: CziMetadata, show_well_table: bool = True) -> None:
    """Print High-Content Screening (HCS) plate information with rich formatting.

    Displays plate hierarchy, dimensions, well count, and optionally a summary table of
    all wells with their positions and field counts.

    Args:
        metadata: CziMetadata object containing file information.
        show_well_table: Whether to display the well summary table. Defaults to True.
            Set to False to hide the table for large plates.
    """
    hcs = metadata.hcs
    if hcs is None:
        console.print("\n[yellow]⚠ No HCS plate hierarchy detected in this file.[/yellow]")
        return

    print_section_header("🔬 High-Content Screening (HCS) Plate Information")

    detected_text = Text(str(metadata.hcs_status.detected), style="green bold")
    console.print(f"HCS Detected: {detected_text}")
    console.print(f"Reason: [dim]{metadata.hcs_status.reason}[/dim]")

    plate = hcs
    console.print()
    console.print(f"[bold magenta]Plate ID:[/bold magenta] {plate.id}")
    console.print(f"[bold magenta]Plate Name:[/bold magenta] {plate.name}")
    console.print(f"[bold magenta]Schema Version:[/bold magenta] {plate.schema_version}")
    console.print(
        f"[bold magenta]Dimensions:[/bold magenta] {plate.declared_rows} rows × {plate.declared_columns} columns (declared)"
    )
    console.print(f"[bold magenta]Row Indices:[/bold magenta] {plate.observed_row_indices}")
    console.print(f"[bold magenta]Column Indices:[/bold magenta] {plate.observed_column_indices}")
    console.print()
    console.print(f"[bold yellow]Total Wells:[/bold yellow] {len(plate.wells)}")
    console.print(f"[bold yellow]Total Fields:[/bold yellow] {sum(len(well.fields) for well in plate.wells)}")

    # Display wells in a rich formatted table (optional)
    if show_well_table:
        table = Table(title="Well Summary", style="cyan")
        table.add_column("Well", style="bright_cyan", no_wrap=False)
        table.add_column("Path", style="dim")
        table.add_column("CZI Index", style="magenta")
        table.add_column("Normalized", style="magenta")
        table.add_column("Fields", style="yellow", justify="right")

        for well in plate.wells:
            table.add_row(
                well.canonical_name,
                well.canonical_path,
                f"({well.source_row_index},{well.source_column_index})",
                f"({well.row_index},{well.column_index})",
                str(len(well.fields)),
            )

        console.print(table)

print_sample_metadata #

print_sample_metadata(
    metadata: CziMetadata, well_name: str | None = None
) -> None

Print sample metadata and first scene details with rich formatting.

Displays scene count, unique wells, per-scene collections, and coordinates of the first imaging scene. If a well name is provided, shows the first scene from that well; otherwise shows the overall first scene.

Parameters:

  • metadata #

    (CziMetadata) –

    CziMetadata object containing file information.

  • well_name #

    (str | None, default: None ) –

    Optional well name (e.g., 'B4', 'A1'). If provided, shows the first scene from this well. If None, shows the overall first scene.

Source code in czitools/utils/hcs_tools.py
 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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
def print_sample_metadata(metadata: CziMetadata, well_name: str | None = None) -> None:
    """Print sample metadata and first scene details with rich formatting.

    Displays scene count, unique wells, per-scene collections, and coordinates of the
    first imaging scene. If a well name is provided, shows the first scene from that
    well; otherwise shows the overall first scene.

    Args:
        metadata: CziMetadata object containing file information.
        well_name: Optional well name (e.g., 'B4', 'A1'). If provided, shows the first
            scene from this well. If None, shows the overall first scene.
    """
    sample = metadata.sample
    if sample is None:
        console.print("[yellow]⚠ No sample metadata available.[/yellow]")
        return

    if metadata.filter_hcs_to_stored_scenes:
        scene_indices = tuple(index for index in metadata.stored_scene_indices if 0 <= index < sample.scene_count)
        section_title = "📊 Sample Metadata (Stored Scenes)"
    else:
        scene_indices = tuple(range(sample.scene_count))
        section_title = "📊 Sample Metadata (XML Declared)"

    selected_wells = [
        sample.well_array_names[index]
        for index in scene_indices
        if index < len(sample.well_array_names) and sample.well_array_names[index]
    ]
    well_counts = Counter(selected_wells)

    print_section_header(section_title)

    # Create a table for basic sample info
    info_table = Table(show_header=False, box=None, padding=(0, 2))
    info_table.add_row("[bold]Scene Count:[/bold]", f"[green]{len(scene_indices)}[/green]")
    info_table.add_row("[bold]Unique Wells:[/bold]", f"[green]{len(well_counts)}[/green]")
    info_table.add_row(
        "[bold]Multiple Fields per Well:[/bold]",
        f"[green]{any(count > 1 for count in well_counts.values())}[/green]",
    )
    console.print(info_table)

    # Per-scene collection summary
    per_scene_lengths = {
        "well names": sum(index < len(sample.well_array_names) for index in scene_indices),
        "well indices": sum(index < len(sample.well_indices) for index in scene_indices),
        "position names": sum(index < len(sample.well_position_names) for index in scene_indices),
        "row indices": sum(index < len(sample.well_rowID) for index in scene_indices),
        "column indices": sum(index < len(sample.well_colID) for index in scene_indices),
        "field center X": sum(index < len(sample.field_centerX) for index in scene_indices),
        "field center Y": sum(index < len(sample.field_centerY) for index in scene_indices),
        "region IDs": sum(index < len(sample.well_region_ids) for index in scene_indices),
    }

    console.print(f"\n[bold cyan]Per-Scene Collections[/bold cyan] [dim]({len(per_scene_lengths)} entries)[/dim]")
    coll_table = Table(show_header=False, box=None, padding=(0, 2))
    for label, length in per_scene_lengths.items():
        coll_table.add_row(f"  [dim]{label:<20}[/dim]", f"[yellow]{length}[/yellow]")
    console.print(coll_table)

    # First scene details
    if scene_indices:
        # Determine which scene index to display
        scene_index = scene_indices[0]
        scene_label = "First Scene Details"

        if well_name is not None:
            # Find first scene for the specified well
            try:
                # Normalize well name to match format in well_array_names
                hcs = metadata.hcs
                normalized_well = None
                if hcs is not None:
                    for well in hcs.wells:
                        if well.canonical_name.upper() == well_name.upper():
                            normalized_well = well.canonical_name
                            break

                if normalized_well is None:
                    # If not found in plate, try direct match
                    normalized_well = well_name.upper()

                # Find first scene for this well
                for index in scene_indices:
                    scene_well = sample.well_array_names[index]
                    if scene_well and scene_well.upper() == normalized_well:
                        scene_index = index
                        scene_label = f"First Scene Details (Well {normalized_well})"
                        break
            except (AttributeError, IndexError):
                # Fallback to first scene if well lookup fails
                pass

        print_section_header(f"🎬 {scene_label}")
        scene_table = Table(show_header=False, box=None, padding=(0, 2))
        scene_table.add_row(
            "[bold]Well:[/bold]", f"[green]{sample.well_array_names[scene_index] or '<missing>'}[/green]"
        )
        scene_table.add_row("[bold]Region ID:[/bold]", f"[magenta]{sample.well_region_ids[scene_index]}[/magenta]")
        scene_table.add_row(
            "[bold]Field Center:[/bold]",
            f"[cyan]({sample.field_centerX[scene_index]}, {sample.field_centerY[scene_index]}) µm[/cyan]",
        )
        scene_table.add_row(
            "[bold]Stage Position:[/bold]",
            f"[cyan]({sample.scene_stageX[scene_index]}, {sample.scene_stageY[scene_index]})[/cyan]",
        )
        console.print(scene_table)

print_section_header #

print_section_header(title: str) -> None

Print a formatted section header with rich styling.

Parameters:

  • title #

    (str) –

    The title of the section to display.

Source code in czitools/utils/hcs_tools.py
24
25
26
27
28
29
30
31
32
33
34
35
def print_section_header(title: str) -> None:
    """Print a formatted section header with rich styling.

    Args:
        title: The title of the section to display.
    """
    panel = Panel(
        title,
        border_style="cyan",
        style="bold cyan",
    )
    console.print(panel)

print_well_fields #

print_well_fields(
    metadata: CziMetadata, well_name: str | None
) -> None

Print detailed field information for a specific well with rich formatting.

Displays all imaging fields in the specified well, including their local indices, scene indices, region IDs, and spatial coordinates. Well names are normalized (e.g., 'B04' resolves to 'B4').

Parameters:

  • metadata #

    (CziMetadata) –

    CziMetadata object containing file information.

  • well_name #

    (str | None) –

    Name of the well to inspect (e.g., 'B4', 'A1'). If None, uses the first well in the plate.

Raises:

  • ValueError –

    If the specified well is not found in the plate.

Source code in czitools/utils/hcs_tools.py
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
def print_well_fields(metadata: CziMetadata, well_name: str | None) -> None:
    """Print detailed field information for a specific well with rich formatting.

    Displays all imaging fields in the specified well, including their local indices,
    scene indices, region IDs, and spatial coordinates. Well names are normalized
    (e.g., 'B04' resolves to 'B4').

    Args:
        metadata: CziMetadata object containing file information.
        well_name: Name of the well to inspect (e.g., 'B4', 'A1'). If None, uses the
            first well in the plate.

    Raises:
        ValueError: If the specified well is not found in the plate.
    """
    hcs = metadata.hcs
    if hcs is None:
        console.print("[yellow]⚠ Cannot display well fields: No HCS plate hierarchy detected.[/yellow]")
        return

    plate = hcs

    # Use first well if not specified
    if well_name is None:
        if not plate.wells:
            console.print("[yellow]⚠ No wells found in this file.[/yellow]")
            return
        well = plate.wells[0]
        well_name = well.canonical_name
        print_section_header(f"🔎 Well Fields (default: first well {well_name})")
    else:
        try:
            well = plate.get_well(well_name)
            print_section_header("🔎 Well Fields")
        except KeyError:
            console.print(f"\n[red]❌ Error: Well {well_name!r} not found in plate.[/red]")
            available = [w.canonical_name for w in plate.wells]
            console.print(f"[yellow]Available wells: {', '.join(available)}[/yellow]")
            return

    # Create fields table
    fields_table = Table(title=f"Fields in well {well_name!r}", style="green")
    fields_table.add_column("Local", style="bright_yellow", justify="center")
    fields_table.add_column("Scene", style="bright_cyan", justify="center")
    fields_table.add_column("ID", style="magenta", justify="center")
    fields_table.add_column("Region", style="bright_blue", justify="center")
    fields_table.add_column("Center X", style="green", justify="right")
    fields_table.add_column("Center Y", style="green", justify="right")
    fields_table.add_column("Unit", style="dim")

    if not well.fields:
        console.print("[yellow]⚠ No fields found in this well.[/yellow]")
        return

    for field in well.fields:
        fields_table.add_row(
            str(field.field_index),
            str(field.scene_index),
            str(field.id),
            str(field.region_id),
            f"{field.scene_center_x:.2f}",
            f"{field.scene_center_y:.2f}",
            str(field.position_unit),
        )

    console.print(fields_table)

save_planetable #

save_planetable(
    df: DataFrame,
    filepath: str,
    separator: str = ",",
    index: bool = True,
) -> str

Saves a pandas dataframe as a CSV file.

Parameters:

  • df #

    (DataFrame) –

    The dataframe to be saved as CSV.

  • filepath #

    (str) –

    The filepath of the CSV file to be written.

  • separator #

    (str, default: ',' ) –

    The separator character for the CSV file. Defaults to ','.

  • index #

    (bool, default: True ) –

    Whether to include the index in the CSV file. Defaults to True.

Returns:

  • str ( str ) –

    The filepath of the CSV file that was written.

Source code in czitools/utils/planetable.py
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
def save_planetable(df: pd.DataFrame, filepath: str, separator: str = ",", index: bool = True) -> str:
    """Saves a pandas dataframe as a CSV file.

    Args:
        df (pd.DataFrame): The dataframe to be saved as CSV.
        filepath (str): The filepath of the CSV file to be written.
        separator (str, optional): The separator character for the CSV file. Defaults to ','.
        index (bool, optional): Whether to include the index in the CSV file. Defaults to True.

    Returns:
        str: The filepath of the CSV file that was written.
    """
    # Generate the filepath for the planetable CSV.
    csvfile = os.path.splitext(filepath)[0] + "_planetable.csv"

    # Write the dataframe to the planetable CSV file.
    df.to_csv(csvfile, sep=separator, index=index)

    return csvfile

set_logging #

set_logging(
    level: int = INFO,
    format_string: str | None = None,
    colorize: bool = True,
) -> Logger

Configures a standard Python logger with customizable level and format.

Parameters:

  • level #

    (int, default: INFO ) –

    Logging level (e.g., logging.INFO, logging.DEBUG, logging.WARNING)

  • format_string #

    (str | None, default: None ) –

    Custom format string for log messages. If None, uses default format.

  • colorize #

    (bool, default: True ) –

    Whether to colorize the output (requires colorlog package)

Returns:

  • Logger –

    logging.Logger: Configured standard Python logger instance.

Source code in czitools/utils/logging_tools.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
def set_logging(level: int = logging.INFO, format_string: str | None = None, colorize: bool = True) -> logging.Logger:
    """
    Configures a standard Python logger with customizable level and format.

    Args:
        level: Logging level (e.g., logging.INFO, logging.DEBUG, logging.WARNING)
        format_string: Custom format string for log messages. If None, uses default format.
        colorize: Whether to colorize the output (requires colorlog package)

    Returns:
        logging.Logger: Configured standard Python logger instance.
    """

    # Create a logger
    logger = logging.getLogger("czitools")

    # Clear any existing handlers
    logger.handlers.clear()

    # Set the logging level
    logger.setLevel(level)

    # Create console handler
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(level)

    # Create formatter
    if colorize and HAS_COLORLOG:
        # Use colorlog for colored output
        if format_string is None:
            format_string = "%(log_color)s%(asctime)s - %(name)s - %(levelname)s - %(message)s"

        formatter = colorlog.ColoredFormatter(
            format_string,
            log_colors={
                "DEBUG": "cyan",
                "INFO": "green",
                "WARNING": "yellow",
                "ERROR": "red",
                "CRITICAL": "red,bg_white",
            },
        )
    else:
        # Use standard formatter
        if format_string is None:
            format_string = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"

        formatter = logging.Formatter(format_string)

        # If colorlog is not available but colorize was requested, warn the user
        if colorize and not HAS_COLORLOG:
            print("Warning: colorlog package not found. Install with 'pip install colorlog' for colored output.")

    console_handler.setFormatter(formatter)

    # Add handler to logger
    logger.addHandler(console_handler)

    return logger