Skip to content

Status: Needs Review

This page has not been reviewed for accuracy and completeness. Content may be outdated or contain errors.


Utilities API

Helper functions and utilities for CUVIS.AI.

Overview

This page documents utility modules that provide helper functions for various tasks.


Deep SVDD Factory

Utility functions for Deep SVDD channel configuration and model setup.

deep_svdd_factory

Deep SVDD Channel Configuration Utilities.

This module provides utilities for inferring channel counts after bandpass filtering for Deep SVDD networks. This is useful for automatically configuring network architectures based on the data pipeline's preprocessing steps.

See Also

cuvis_ai.node.preprocessors : Bandpass filtering nodes cuvis_ai.anomaly.deep_svdd : Deep SVDD anomaly detection

ChannelConfig dataclass

ChannelConfig(num_channels, in_channels)

Configuration for network channel counts.

Stores the number of input and output channels for network layers, typically determined after bandpass filtering.

Attributes:

Name Type Description
num_channels int

Total number of channels in the network.

in_channels int

Number of input channels to the network.

infer_channels_after_bandpass

infer_channels_after_bandpass(datamodule, bandpass_cfg)

Infer post-bandpass channel count from a sample batch.

Parameters:

Name Type Description Default
datamodule object

Datamodule with a train_dataloader() method returning batches with "wavelengths".

required
bandpass_cfg object

Config with min_wavelength_nm and max_wavelength_nm fields.

required

Returns:

Type Description
ChannelConfig

num_channels and in_channels set to the filtered channel count.

Source code in cuvis_ai/utils/deep_svdd_factory.py
def infer_channels_after_bandpass(datamodule, bandpass_cfg) -> ChannelConfig:
    """Infer post-bandpass channel count from a sample batch.

    Parameters
    ----------
    datamodule : object
        Datamodule with a train_dataloader() method returning batches with "wavelengths".
    bandpass_cfg : object
        Config with min_wavelength_nm and max_wavelength_nm fields.

    Returns
    -------
    ChannelConfig
        num_channels and in_channels set to the filtered channel count.
    """
    sample_batch = next(iter(datamodule.train_dataloader()))
    wavelengths = sample_batch["wavelengths"]
    keep_mask = wavelengths >= bandpass_cfg.min_wavelength_nm
    if bandpass_cfg.max_wavelength_nm is not None:
        keep_mask = keep_mask & (wavelengths <= bandpass_cfg.max_wavelength_nm)
    num_channels_after_bandpass = int(keep_mask.sum().item())
    return ChannelConfig(
        num_channels=num_channels_after_bandpass, in_channels=num_channels_after_bandpass
    )

Visualization Helpers

Helper functions for creating visualizations.

vis_helpers

Visualization helper utilities for converting figures and tensors to arrays.

fig_to_array

fig_to_array(fig, dpi=150)

Convert matplotlib figure to numpy array in RGB format.

This utility handles the conversion of a matplotlib figure to a numpy array by saving it to a BytesIO buffer, loading it with PIL, and converting to a numpy array. The figure is automatically closed after conversion.

Parameters:

Name Type Description Default
fig Figure

The matplotlib figure to convert

required
dpi int

Resolution for the saved image (default: 150)

150

Returns:

Type Description
ndarray

RGB image as numpy array with shape (H, W, 3) and dtype uint8

Examples:

>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [1, 4, 9])
>>> img_array = fig_to_array(fig, dpi=150)
>>> img_array.shape
(height, width, 3)
Source code in cuvis_ai/utils/vis_helpers.py
def fig_to_array(fig: matplotlib.figure.Figure, dpi: int = 150) -> np.ndarray:
    """Convert matplotlib figure to numpy array in RGB format.

    This utility handles the conversion of a matplotlib figure to a numpy array
    by saving it to a BytesIO buffer, loading it with PIL, and converting to
    a numpy array. The figure is automatically closed after conversion.

    Parameters
    ----------
    fig : matplotlib.figure.Figure
        The matplotlib figure to convert
    dpi : int, optional
        Resolution for the saved image (default: 150)

    Returns
    -------
    np.ndarray
        RGB image as numpy array with shape (H, W, 3) and dtype uint8

    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> fig, ax = plt.subplots()
    >>> ax.plot([1, 2, 3], [1, 4, 9])
    >>> img_array = fig_to_array(fig, dpi=150)
    >>> img_array.shape
    (height, width, 3)
    """
    buf = BytesIO()
    fig.savefig(buf, format="png", dpi=dpi, bbox_inches="tight")
    buf.seek(0)
    img = Image.open(buf)
    img_array = np.array(img.convert("RGB"))
    buf.close()

    # Close the figure to free memory
    import matplotlib.pyplot as plt

    plt.close(fig)

    return img_array

tensor_to_uint8

tensor_to_uint8(tensor)

Convert float tensor [0, 1] to uint8 [0, 255].

Parameters:

Name Type Description Default
tensor Tensor

Input tensor with values in [0, 1]

required

Returns:

Type Description
Tensor

Tensor converted to uint8 in range [0, 255], stays on original device

Source code in cuvis_ai/utils/vis_helpers.py
def tensor_to_uint8(tensor: torch.Tensor) -> torch.Tensor:
    """Convert float tensor [0, 1] to uint8 [0, 255].

    Parameters
    ----------
    tensor : torch.Tensor
        Input tensor with values in [0, 1]

    Returns
    -------
    torch.Tensor
        Tensor converted to uint8 in range [0, 255], stays on original device
    """
    return (tensor.clamp(0, 1) * 255).to(torch.uint8)

tensor_to_numpy

tensor_to_numpy(tensor)

Convert torch tensor to numpy array on CPU.

Parameters:

Name Type Description Default
tensor Tensor

Input tensor (can be on any device)

required

Returns:

Type Description
ndarray

Numpy array representation

Source code in cuvis_ai/utils/vis_helpers.py
def tensor_to_numpy(tensor: torch.Tensor) -> np.ndarray:
    """Convert torch tensor to numpy array on CPU.

    Parameters
    ----------
    tensor : torch.Tensor
        Input tensor (can be on any device)

    Returns
    -------
    np.ndarray
        Numpy array representation
    """
    return tensor.detach().cpu().numpy()