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-boxBoxobject. -
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:
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 | |
check_scenes_shape #
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
tolerancepixels
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 | |
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
Falsein 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 | |
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
Falsein 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 | |
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
planesdictionary.
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 | |
get_czimd_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 | |
get_fname_woext #
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 | |
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, anddownsample_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_tableis 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 | |
get_pyczi_readertype #
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:
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 | |
is_valid_czi_url #
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 | |
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 | |
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 | |
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 | |
print_section_header #
Print a formatted section header with rich styling.
Parameters:
Source code in czitools/utils/hcs_tools.py
24 25 26 27 28 29 30 31 32 33 34 35 | |
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 | |
save_planetable #
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 | |
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 | |