Skip to content

viscy-utils

Shared ML infrastructure for virtual staining microscopy.

pip install viscy-utils
uv add viscy-utils

Depends on viscy-data

viscy-utils is the one package that builds on another (viscy-data); the other three are leaf dependencies. See the dependency layering.

API reference

configure_adamw_scheduler(module, model, lr, schedule, warmup_steps=3, warmup_multiplier=0.001)

Build an AdamW optimizer with a WarmupCosine or Constant LR schedule.

Parameters:

Name Type Description Default
module LightningModule

The LightningModule whose trainer supplies estimated_stepping_batches (WarmupCosine) or max_epochs (Constant).

required
model Module

The network whose parameters are optimized.

required
lr float

Learning rate.

required
schedule (WarmupCosine, Constant)

Learning rate scheduler.

"WarmupCosine"
warmup_steps int

WarmupCosine only: number of steps to linearly ramp the LR from lr * warmup_multiplier up to lr. Ignored for Constant.

3
warmup_multiplier float

WarmupCosine only: initial LR multiplier at step 0 (final LR at warmup_steps is lr). Ignored for Constant.

0.001

Returns:

Type Description
tuple[list, list]

([optimizer], [scheduler_config]) as expected by LightningModule.configure_optimizers.

Raises:

Type Description
ValueError

If schedule is not "WarmupCosine" or "Constant".

detach_sample(imgs, log_samples_per_batch)

Extract middle-Z slices from a batch for image grid logging.

Layout: one row per sample, columns ordered as view0_ch0, view0_ch1, ..., view1_ch0, view1_ch1, .... Each view contributes all of its own channels, so views with different channel counts (e.g. a 1-channel source with a 2-channel target/pred) are all logged in full. Channels expand horizontally within each view, which suits landscape monitors.

Parameters:

Name Type Description Default
imgs Sequence[Tensor]

One (B, C, Z, Y, X) tensor per view. Examples: (anchor, positive, negative) for contrastive learning, or (source, target, pred) for virtual staining. Views may have different channel counts.

required
log_samples_per_batch int

Number of samples from the batch to include (first N).

required

Returns:

Type Description
list[list[ndarray]]

Grid of 2-D (H, W) arrays. Rows are samples, columns are (view, channel) pairs in view-major order.

get_val_stats(sample_values)

Compute statistics of a numpy array.

Parameters:

Name Type Description Default
sample_values array_like

Values to compute statistics for.

required

Returns:

Type Description
dict

Dictionary with intensity statistics (mean, std, median, iqr, percentiles).

hist_clipping(input_image, min_percentile=2, max_percentile=98)

Clip and rescale histogram from min to max intensity percentiles.

Parameters:

Name Type Description Default
input_image ndarray

Input image for intensity normalization.

required
min_percentile int or float

Min intensity percentile.

2
max_percentile int or float

Max intensity percentile.

98

Returns:

Type Description
ndarray

Intensity-clipped and rescaled image.

mp_wrapper(fn, fn_args, workers)

Execute function with multiprocessing.

Parameters:

Name Type Description Default
fn callable

Function to execute.

required
fn_args list of tuple

List of tuples of function arguments.

required
workers int

Max number of workers.

required

Returns:

Type Description
list

List of returned values.

render_images(imgs, cmaps=[])

Render images in a grid.

Parameters:

Name Type Description Default
imgs Sequence[Sequence[ndarray]]

Grid of images to render, output of detach_sample.

required
cmaps list[str]

Colormaps for each column, by default [].

[]

Returns:

Type Description
ndarray

Rendered RGB images grid.

to_numpy(t)

Convert a tensor to a NumPy array, handling mixed-precision dtypes.

Bfloat16 tensors (from AMP/autocast) are cast to float32 because NumPy does not support bfloat16. All other dtypes (float16, float32, float64, integers, booleans) are preserved.

Parameters:

Name Type Description Default
t Tensor

Input tensor (any device, any dtype).

required

Returns:

Type Description
ndarray

NumPy array on CPU.

unzscore(im_norm, zscore_median, zscore_iqr)

Revert z-score normalization applied during preprocessing.

Parameters:

Name Type Description Default
im_norm ndarray

Normalized image.

required
zscore_median float

Image median.

required
zscore_iqr float

Image interquartile range.

required

Returns:

Type Description
ndarray

Image at its original scale.

zscore(input_image, im_mean=None, im_std=None)

Perform z-score normalization.

Parameters:

Name Type Description Default
input_image ndarray

Input image for intensity normalization.

required
im_mean float or None

Image mean.

None
im_std float or None

Image std.

None

Returns:

Type Description
ndarray

Z-score normalized image.