Skip to content

czitools.utils.misc #

Miscellaneous utility functions for czitools.

Contains helpers for path normalisation, zoom validation, zarr/dask array utilities, and other small cross-cutting concerns.

Functions:

  • calc_scaling –

    Calculate the scaling for better display

  • get_fname_woext –

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

  • 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.

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

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_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