Skip to content

API Reference

This page is generated automatically from docstrings using mkdocstrings.

Package Overview

SenoQuant napari plugin package.

Core Components

Main Widget

Bases: QWidget

Main SenoQuant widget with tabbed UI.

closeEvent(event)

Run global shutdown callbacks before widget teardown.

Utilities

Utility package exports.

append_run_metadata(metadata, *, task, runner_type, runner_name, settings=None)

Append a timestamped run entry to layer metadata.

Parameters:

Name Type Description Default
metadata dict or None

Existing layer metadata.

required
task str

Task name (for example "nuclear").

required
runner_type str

Run source type (for example "segmentation_model").

required
runner_name str

Model or detector name used for the run.

required
settings dict or None

Settings used for the run.

None

Returns:

Type Description
dict

Updated metadata dictionary containing task and run_history.

labels_data_as_dask(data)

Wrap label data in a chunked dask array when possible.

Parameters:

Name Type Description Default
data array - like

Label data to present in napari.

required

Returns:

Type Description
array - like

Dask-backed array when conversion succeeds, otherwise the original array-like input.

layer_data_asarray(layer, *, squeeze=True)

Return layer data as a NumPy array, optionally squeezed.

Parameters:

Name Type Description Default
layer object

napari layer instance providing a data attribute.

required
squeeze bool

Whether to remove singleton dimensions.

True

Returns:

Type Description
ndarray

Array representation of the layer data.

Reader

Core BioIO reader implementation for SenoQuant.

get_reader(path)

Return a reader callable for the given path.

Parameters:

Name Type Description Default
path str or list of str

Path(s) selected in the napari reader dialog.

required

Returns:

Type Description
callable or None

Reader callable that returns napari layer data, or None if the path is not supported.

Notes

This uses bioio.BioImage.determine_plugin to ensure the file can be handled by BioIO. If the file is unsupported or BioIO is unavailable, None is returned so napari can try other readers.

Segmentation

Backend

Backend logic for the Segmentation tab.

SegmentationBackend

Manage segmentation models and their storage locations.

Parameters:

Name Type Description Default
models_root Path or None

Optional root folder for model storage. Defaults to the local models directory for this tab.

None

get_model(name)

Return a model wrapper for the given name.

Parameters:

Name Type Description Default
name str

Model name used to locate or create the model folder.

required

Returns:

Type Description
SenoQuantSegmentationModel

Model wrapper instance.

list_model_names(task=None)

List available model folders under the models root.

Parameters:

Name Type Description Default
task str or None

Optional task filter such as "nuclear" or "cytoplasmic".

None

Returns:

Type Description
list[str]

Sorted model folder names.

get_preloaded_model(name)

Return a preloaded model instance by name.

preload_models()

Instantiate all discovered models once.

Models Base Classes

Model wrapper for segmentation resources.

SenoQuantSegmentationModel

Handle per-model storage and metadata paths.

Parameters:

Name Type Description Default
name str

Model identifier used for folder creation.

required
models_root Path or None

Optional root folder for model storage.

None

details_path property

Return the path to the details JSON file.

class_path property

Return the path to the model class file.

__init__(name, models_root=None)

Initialize the model wrapper and ensure its folder exists.

load_details()

Load model metadata from the details file.

Returns:

Type Description
dict

Parsed model metadata dictionary.

run(**kwargs)

Run the model with the provided inputs and settings.

Parameters:

Name Type Description Default
**kwargs

Model inputs and settings passed from the UI.

{}

Returns:

Type Description
dict or None

Result dictionary from the model, or None if not implemented.

list_settings()

Return the settings definitions for this model.

Returns:

Type Description
list[dict]

Settings definitions for building the UI.

display_order()

Return the optional display ordering for this model.

Returns:

Type Description
float or None

Numeric ordering value if specified in details.json.

supports_task(task)

Return whether the model supports a given task.

Parameters:

Name Type Description Default
task str

Task name, such as "nuclear" or "cytoplasmic".

required

Returns:

Type Description
bool

True if the task is supported.

cytoplasmic_input_modes()

Return supported input modes for cytoplasmic segmentation.

Returns:

Type Description
list[str]

Input modes, e.g., "cytoplasmic" or "nuclear+cytoplasmic".

cytoplasmic_nuclear_optional()

Return whether the nuclear channel is optional for cytoplasmic mode.

Returns:

Type Description
bool

True when the nuclear channel is optional.

Spot Detection

Backend

Backend logic for the Spots tab.

SpotsBackend

Manage spot detectors and their storage locations.

Parameters:

Name Type Description Default
models_root Path or None

Optional root folder for detector storage. Defaults to the local models directory for this tab.

None

get_detector(name)

Return a detector wrapper for the given name.

Parameters:

Name Type Description Default
name str

Detector name used to locate or create the detector folder.

required

Returns:

Type Description
SenoQuantSpotDetector

Detector instance.

list_detector_names()

List available detector folders under the models root.

Returns:

Type Description
list[str]

Sorted detector folder names ordered by display_order, then by name.

compute_colocalization(data_a, data_b)

Compute colocalization centroids from two label arrays.

Parameters:

Name Type Description Default
data_a ndarray

First label layer data.

required
data_b ndarray

Second label layer data.

required

Returns:

Type Description
dict

Dictionary containing the points array.

Detector Base Classes

Base class for spot detector implementations.

SenoQuantSpotDetector

Handle per-detector storage and metadata paths.

Parameters:

Name Type Description Default
name str

Detector identifier used for folder creation.

required
models_root Path or None

Optional root folder for detector storage.

None

details_path property

Return the path to the details JSON file.

class_path property

Return the path to the detector class file.

__init__(name, models_root=None)

Initialize the detector wrapper and ensure its folder exists.

load_details()

Load detector metadata from the details file.

Returns:

Type Description
dict

Parsed detector metadata dictionary.

list_settings()

Return the settings definitions for this detector.

Returns:

Type Description
list[dict]

Settings definitions for building the UI.

display_order()

Return the optional display ordering for this detector.

Returns:

Type Description
float or None

Numeric ordering value if specified in details.json.

run(**kwargs)

Run the detector with the provided inputs and settings.

Parameters:

Name Type Description Default
**kwargs

Detector inputs and settings passed from the UI.

{}

Prediction

Backend

Backend logic for the Prediction tab.

PredictionBackend

Manage prediction models and push outputs into a napari viewer.

Parameters:

Name Type Description Default
models_root Path or None

Optional root folder for prediction models. Defaults to the local models directory for this tab.

None

get_model(name)

Return a prediction model wrapper for the given name.

list_model_names()

List available prediction model folders under the models root.

run_model(model_name, *, viewer=None, settings=None, settings_widget=None)

Run a prediction model and normalize its result payload.

push_layers_to_viewer(viewer, model_name, result, source_layer=None)

Add model-produced layers into the napari viewer.

Model Base Classes

Base class for prediction model implementations.

SenoQuantPredictionModel

Handle per-model storage paths and runtime hooks for prediction models.

Parameters:

Name Type Description Default
name str

Model identifier used for folder creation.

required
models_root Path or None

Optional root folder for model storage.

None

class_path property

Return the path to the model class file.

__init__(name, models_root=None)

Initialize the model wrapper and ensure its folder exists.

display_order()

Return optional UI ordering for the model selector.

Returns:

Type Description
float or None

Lower values are shown first. None means no explicit priority.

build_widget(parent=None, viewer=None)

Create and return a model-specific Qt widget.

Parameters:

Name Type Description Default
parent QWidget or None

Optional widget parent.

None
viewer object or None

Optional napari viewer passed by the prediction tab.

None

Returns:

Type Description
QWidget or None

Custom configuration widget for this model.

collect_widget_settings(settings_widget=None)

Collect a serializable settings dictionary from a widget.

Parameters:

Name Type Description Default
settings_widget QWidget or None

Widget previously created by :meth:build_widget.

None

Returns:

Type Description
dict[str, object]

Settings payload passed into :meth:run.

run(**kwargs)

Run the model with provided inputs and return layer payloads.

Parameters:

Name Type Description Default
**kwargs

Model-specific run payload, typically including viewer and settings.

{}

Returns:

Type Description
dict

Mapping with a layers entry compatible with napari-style layer-data tuples.

Quantification

Backend

Backend logic for the Quantification tab.

FeatureExportResult dataclass

Output metadata for a single feature export.

Attributes:

Name Type Description
feature_id str

Stable identifier for the exported feature instance.

feature_type str

Feature type name used for routing (e.g., "Markers").

feature_name str

Display name provided by the user.

temp_dir Path

Temporary directory where the feature wrote its outputs.

outputs list of Path

Explicit file paths returned by the feature processor.

QuantificationResult dataclass

Aggregated output information for a quantification run.

Attributes:

Name Type Description
output_root str

Root output directory for the run.

temp_root Path

Temporary root directory used during processing.

feature_outputs list of FeatureExportResult

Per-feature export metadata for the run.

QuantificationBackend

Backend orchestrator for quantification exports.

Notes

Feature export routines live with their feature implementations. The backend iterates through configured feature contexts, asks each feature handler to export into a temporary directory, and then routes those outputs into a final output structure.

__init__()

Initialize the backend state.

Attributes:

Name Type Description
metrics list

Placeholder container for computed metrics.

process(features, output_path, output_name, export_format, cleanup=True)

Run feature exports and route their outputs.

Parameters:

Name Type Description Default
features iterable of object

Feature UI contexts with state and feature_handler. Each handler should implement export(temp_dir, export_format).

required
output_path str

Base output folder path.

required
output_name str

Folder name used to group exported outputs.

required
export_format str

File format requested by the user ("csv" or "xlsx").

required
cleanup bool

Whether to delete temporary export folders after routing.

True

Returns:

Type Description
QuantificationResult

Output metadata for the completed run.

Notes

If a feature export does not return explicit output paths, the backend will move all files found in the feature's temp directory. This allows feature implementations to either return specific files or simply write into the provided temporary directory.

Features Base Classes

Feature UI base classes for quantification.

FeatureData

Base class for feature-specific configuration data.

Notes

Concrete feature data classes should inherit from this class so they can be stored on :class:FeatureConfig.

FeatureConfig dataclass

Configuration for a single quantification feature.

Attributes:

Name Type Description
feature_id str

Unique identifier for the feature instance.

name str

User-facing name for the feature.

type_name str

Feature type name (e.g., "Markers").

data FeatureData

Feature-specific configuration payload.

SenoQuantFeature

Base class for quantification feature UI.

__init__(tab, context)

Initialize a feature with shared tab context.

Parameters:

Name Type Description Default
tab QuantificationTab

Parent quantification tab instance.

required
context FeatureUIContext

Feature UI context with configuration state.

required

build()

Build the UI for this feature.

export(temp_dir, export_format)

Export feature outputs into a temporary directory.

Parameters:

Name Type Description Default
temp_dir Path

Temporary directory where outputs should be written.

required
export_format str

File format requested by the user ("csv" or "xlsx").

required

Returns:

Type Description
iterable of Path

Paths to files produced by the export routine.

Notes

Implementations may either return explicit file paths or simply write outputs into temp_dir and return an empty iterable.

on_features_changed(configs)

Handle updates when the feature list changes.

Parameters:

Name Type Description Default
configs list of FeatureUIContext

Current feature contexts.

required

update_type_options(tab, configs) classmethod

Update type availability in feature selectors.

Parameters:

Name Type Description Default
tab QuantificationTab

Parent quantification tab instance.

required
configs list of FeatureUIContext

Current feature contexts.

required

RefreshingComboBox

Bases: QComboBox

Combo box that refreshes its items when opened.

__init__(refresh_callback=None, parent=None)

Create a combo box that refreshes before showing its popup.

Parameters:

Name Type Description Default
refresh_callback callable or None

Callback invoked before showing the popup.

None
parent QWidget or None

Optional parent widget.

None

showPopup()

Refresh items before showing the popup.

ROI Configuration

ROI selection UI helpers for quantification features.

ROIConfig dataclass

Configuration for a single ROI entry.

Attributes:

Name Type Description
name str

Display name for the ROI.

layer str

Shapes layer name used for the ROI.

roi_type str

Whether the ROI should be included or excluded.

ROISection

Reusable ROI controls for marker and spots features.

__init__(tab, context, rois)

Initialize the ROI helper for a feature.

Parameters:

Name Type Description Default
tab QuantificationTab

Parent quantification tab instance.

required
context FeatureUIContext

Feature UI context.

required
rois list of ROIConfig

Feature ROI configuration list.

required

build()

Create the ROI controls and attach to the right column.

update_titles()

Refresh ROI section titles based on current feature order.

clear()

Remove all ROI rows and reset layout state.

Batch Processing

Backend

Batch processing backend.

This module coordinates per-image batch processing for segmentation, spot detection, and quantification. It provides a single entry point (BatchBackend.run_job) that consumes a :class:BatchJobConfig and produces a :class:BatchSummary describing outputs and errors.

The batch run flow is:

  1. Normalize input extensions and discover files.
  2. Resolve channel mapping for named channels.
  3. For each file (and each scene, if enabled): a. Optionally run nuclear segmentation. b. Optionally run cytoplasmic segmentation. c. Optionally run spot detection for selected channels. d. Optionally run quantification using a temporary viewer shim.
  4. Persist mask outputs and quantification results.
Notes

This backend is intentionally UI-agnostic. UI widgets build a BatchJobConfig and pass it here for execution.

BatchItemResult dataclass

Result metadata for a single processed image.

Attributes:

Name Type Description
path Path

Input file path.

scene_id str or None

Scene identifier for multi-scene files.

outputs dict of str to Path or str

Mapping of output labels to written files.

errors list of str

Collected error messages for this item.

BatchSummary dataclass

Aggregated results for a batch run.

Attributes:

Name Type Description
input_root Path

Root input directory.

output_root Path or str

Root output directory.

processed int

Number of successfully processed items.

skipped int

Number of skipped items.

failed int

Number of failed items.

results list of BatchItemResult

Per-item metadata for the run.

BatchBackend

Backend for batch segmentation and spot detection workflows.

run_job(job)

Run a batch job using a configuration object.

Parameters:

Name Type Description Default
job BatchJobConfig

Fully-populated batch configuration.

required

Returns:

Type Description
BatchSummary

Summary of the batch run (counts + per-item metadata).

process_folder(input_path, output_path, *, channel_map=None, nuclear_model=None, nuclear_channel=None, nuclear_settings=None, cyto_model=None, cyto_channel=None, cyto_nuclear_channel=None, cyto_settings=None, spot_detector=None, spot_channels=None, spot_settings=None, spot_min_size=0, spot_max_size=0, quantification_features=None, quantification_format='xlsx', quantification_tab=None, extensions=None, include_subfolders=False, overwrite=False, process_all_scenes=False, batch_job_payload=None, progress_callback=None)

Run batch processing on a folder of images.

Parameters:

Name Type Description Default
input_path str

Folder containing input images.

required
output_path str

Folder where outputs should be written.

required
channel_map iterable of BatchChannelConfig or dict

Mapping from channel names to indices.

None
nuclear_model str or None

Segmentation model name for nuclei.

None
nuclear_channel str or int or None

Channel selection for nuclei.

None
nuclear_settings dict or None

Model settings for nuclear segmentation.

None
cyto_model str or None

Segmentation model name for cytoplasm.

None
cyto_channel str or int or None

Channel selection for cytoplasm.

None
cyto_nuclear_channel str or int or None

Optional nuclear input for cytoplasmic models. This may be a channel selection or a generated nuclear label name.

None
cyto_settings dict or None

Model settings for cytoplasmic segmentation.

None
spot_detector str or None

Spot detection model name.

None
spot_channels iterable of str or int or None

Channels used for spot detection.

None
spot_settings dict or None

Detector settings.

None
spot_min_size int

Minimum spot diameter in pixels (0 = no minimum).

0
spot_max_size int

Maximum spot diameter in pixels (0 = no maximum).

0
quantification_features iterable of object or None

Quantification feature contexts (UI-generated).

None
quantification_format str

Output format for quantification ("csv" or "xlsx").

'xlsx'
quantification_tab object or None

Quantification tab instance for viewer wiring.

None
extensions iterable of str or None

File extensions to include.

None
include_subfolders bool

Whether to recurse into subfolders.

False
overwrite bool

Whether to overwrite existing output folders.

False
process_all_scenes bool

Whether to process all scenes in multi-scene files.

False
batch_job_payload dict or None

Optional pre-serialized batch_job payload to persist at the output root as senoquant_settings.json.

None
progress_callback callable or None

Optional callback invoked with (current, total, message) to report progress during batch processing.

None

Returns:

Type Description
BatchSummary

Summary of the batch run.

Configuration

Batch job configuration and serialization helpers.

This module defines dataclasses used to capture batch settings from the UI. BatchJobConfig.to_dict() and from_dict() operate on the inner batch_job payload, while save() and load() persist that payload inside the shared senoquant.settings bundle envelope.

BatchChannelConfig dataclass

Channel mapping configuration.

Attributes:

Name Type Description
name str

User-facing channel name (used in UI and exports).

index int

Zero-based channel index in the input image.

BatchSegmentationConfig dataclass

Segmentation configuration for a single task.

BatchCytoplasmicConfig dataclass

Cytoplasmic segmentation configuration.

BatchSpotsConfig dataclass

Spot detection configuration.

BatchQuantificationConfig dataclass

Quantification configuration.

BatchJobConfig dataclass

Top-level batch configuration.

This dataclass is the in-memory payload exchanged between the batch UI and backend. It also defines the inner batch_job payload embedded in saved settings bundles.

to_dict()

Serialize the inner batch payload to a JSON-friendly dictionary.

Returns:

Type Description
dict

JSON-compatible batch_job payload.

from_dict(payload) classmethod

Hydrate a job config from an inner batch_job payload.

Parameters:

Name Type Description Default
payload dict

JSON-compatible batch_job payload.

required

Returns:

Type Description
BatchJobConfig

Parsed configuration instance.

save(path)

Persist the configuration to disk in bundle format.

Parameters:

Name Type Description Default
path str

Destination file path for the JSON settings file. The file stores the config inside a senoquant.settings bundle envelope.

required

load(path) classmethod

Load a configuration from disk.

Parameters:

Name Type Description Default
path str

Source JSON settings file. Supports both bundle envelopes and legacy plain batch payloads.

required

Returns:

Type Description
BatchJobConfig

Loaded configuration instance.

I/O Utilities

I/O helpers for batch processing.

This module provides filesystem and image-loading utilities used by the batch backend. Functions are intentionally stateless and easy to mock in tests.

normalize_extensions(extensions)

Normalize extension list to lowercase with leading dots.

Parameters:

Name Type Description Default
extensions iterable of str or None

Raw extension strings (with or without dots).

required

Returns:

Type Description
set of str or None

Normalized extensions or None when no filtering is requested.

iter_input_files(root, extensions, include_subfolders)

Yield input files from a root folder.

Parameters:

Name Type Description Default
root Path

Directory to scan.

required
extensions set of str or None

Allowed file extensions. None disables filtering.

required
include_subfolders bool

Whether to scan subfolders recursively.

required

Yields:

Type Description
Path

File paths that match the extension criteria.

basename_for_path(path)

Return a filesystem-friendly base name for a file path.

Parameters:

Name Type Description Default
path Path

Input file path.

required

Returns:

Type Description
str

Base name with common microscopy extensions removed.

safe_scene_dir(scene_id)

Return a sanitized scene identifier for folder naming.

Parameters:

Name Type Description Default
scene_id str

Scene identifier from BioIO.

required

Returns:

Type Description
str

Filesystem-safe scene folder name.

write_array(output_dir, name, data)

Write an array to disk as .npy.

Parameters:

Name Type Description Default
output_dir str or Path

Destination folder.

required
name str

Base name for the output file.

required
data ndarray

Array data to serialize.

required

Returns:

Type Description
Path or str

Path to the written file.

resolve_channel_index(choice, channel_map)

Resolve a channel selection into a numeric index.

Parameters:

Name Type Description Default
choice str or int or None

Channel selection from the UI (name or index).

required
channel_map list of BatchChannelConfig

Mapping from names to indices.

required

Returns:

Type Description
int

Resolved channel index.

Raises:

Type Description
ValueError

If the selection is missing or unknown.

load_channel_data(path, channel_index, scene_id)

Load a single-channel image array for the given path.

Parameters:

Name Type Description Default
path Path

Input file path.

required
channel_index int

Channel index to extract.

required
scene_id str or None

Optional scene identifier.

required

Returns:

Type Description
tuple of (numpy.ndarray or None, dict)

The extracted image data and metadata.

list_scenes(path)

Return scene identifiers for a BioIO image path.

Parameters:

Name Type Description Default
path Path

Input file path.

required

Returns:

Type Description
list of str

Scene identifiers, or an empty list if unavailable.

Viewer Shim

Lightweight layer shims used for batch processing.

These classes emulate the minimal attributes used by feature exporters and quantification routines, without requiring a live napari viewer.

Image

Lightweight image layer placeholder.

Parameters:

Name Type Description Default
data ndarray or None

Image data array.

required
name str

Layer name.

required
metadata dict or None

Metadata dictionary (e.g., pixel sizes).

None
rgb bool

Whether the layer should be treated as RGB.

False

Labels

Lightweight labels layer placeholder.

Parameters:

Name Type Description Default
data ndarray or None

Label image data.

required
name str

Layer name.

required
metadata dict or None

Metadata dictionary (e.g., pixel sizes).

None

BatchViewer

Minimal viewer shim exposing layers for export routines.

Parameters:

Name Type Description Default
layers iterable of object or None

Initial layer collection.

None

__init__(layers=None)

Initialize the viewer shim.

set_layers(layers)

Replace the current layer collection.

Parameters:

Name Type Description Default
layers iterable of object

New layer collection.

required

Settings

Backend helpers for shared settings persistence in the Settings tab.

SettingsBackend

Bases: QObject

Read and write unified settings bundle payloads.

__init__()

Initialize the backend.

default_settings_filename() classmethod

Return the default JSON filename used for settings exports.

build_bundle(*, segmentation=None, spots=None, batch_job=None)

Build a normalized settings bundle payload for UI settings.

Parameters:

Name Type Description Default
segmentation dict or None

Segmentation tab settings state payload.

None
spots dict or None

Spots tab settings state payload.

None
batch_job dict or None

Batch tab settings payload, when available.

None

Returns:

Type Description
dict of str to Any

Canonical senoquant.settings bundle payload.

parse_bundle(payload) staticmethod

Parse raw JSON payload into a normalized settings bundle.

load_bundle(path)

Load and normalize a settings bundle from disk.

save_bundle(path, payload)

Write a settings bundle payload to disk.