Utils¶
Submodules¶
panoptica.utils.citation_reminder module¶
- panoptica.utils.citation_reminder.citation_reminder(func)¶
Decorator to remind users to cite panoptica.
panoptica.utils.config module¶
- class panoptica.utils.config.SupportsConfig¶
Bases:
object
Base class that provides methods for loading and saving instances as YAML configurations.
This class should be inherited by classes that wish to have load and save functionality for YAML configurations, with class registration to enable custom serialization and deserialization.
- load_from_config(cls, path)¶
Loads a class instance from a YAML file.
- load_from_config_name(cls, name)¶
Loads a class instance from a configuration file identified by name.
- save_to_config(path)¶
Saves the instance to a YAML file.
- save_to_config_by_name(name)¶
Saves the instance to a configuration file identified by name.
- to_yaml(cls, representer, node)¶
YAML serialization method (requires _yaml_repr).
- from_yaml(cls, constructor, node)¶
YAML deserialization method.
- classmethod _register_permanently()¶
Registers the class to globally supported helper classes.
- abstract classmethod _yaml_repr(node) dict ¶
Abstract method for representing the class in YAML.
- Parameters:
node – The object instance to represent in YAML.
- Returns:
A dictionary representation of the class.
- Return type:
dict
- classmethod from_yaml(constructor, node)¶
Deserializes a YAML node to an instance of the class.
- Parameters:
constructor – YAML constructor instance.
node – YAML node to deserialize.
- Returns:
An instance of the class with attributes populated from YAML data.
- classmethod load_from_config(path: str | Path)¶
Loads an instance of the class from a YAML file.
- Parameters:
path (str | Path) – The file path to load the configuration.
- Returns:
An instance of the class.
- classmethod load_from_config_name(name: str)¶
Loads an instance of the class from a configuration file identified by name.
- Parameters:
name (str) – The name used to find the configuration file.
- Returns:
An instance of the class.
- save_to_config(path: str | Path)¶
Saves the instance to a YAML configuration file.
- Parameters:
path (str | Path) – The file path to save the configuration.
- save_to_config_by_name(name: str)¶
Saves the instance to a configuration file identified by name.
- Parameters:
name (str) – The name used to determine the configuration file path.
- classmethod to_yaml(representer, node)¶
Serializes the class to YAML format.
- Parameters:
representer – YAML representer instance.
node – The object instance to serialize.
- Returns:
YAML-compatible node representation of the object.
- Return type:
YAML node
- panoptica.utils.config._load_from_config(cls, path: str | Path)¶
Loads an instance of a class from a YAML configuration file.
- Parameters:
cls – The class type to instantiate.
path (str | Path) – Path to the YAML configuration file.
- Returns:
An instance of the specified class, loaded from configuration.
- panoptica.utils.config._load_from_config_name(cls, name: str)¶
Loads an instance of a class from a configuration file identified by name.
- Parameters:
cls – The class type to instantiate.
name (str) – The name used to find the configuration file.
- Returns:
An instance of the specified class.
- panoptica.utils.config._load_yaml(file: str | Path, registered_class=None)¶
Loads a YAML file into a Python dictionary or object, with optional class registration.
- Parameters:
file (str | Path) – Path to the YAML file.
registered_class (optional) – Optional class to register with the YAML parser.
- Returns:
Parsed content from the YAML file.
- Return type:
dict | object
- panoptica.utils.config._register_class_to_yaml(cls)¶
Registers a class to the global supported helper classes for YAML serialization.
- Parameters:
cls – The class to register.
- panoptica.utils.config._register_helper_classes(yaml: YAML)¶
Registers globally supported helper classes to a YAML instance.
- Parameters:
yaml (YAML) – The YAML instance to register helper classes to.
- panoptica.utils.config._save_to_config(obj, path: str | Path)¶
Saves an instance of a class to a YAML configuration file.
- Parameters:
obj – The object to save.
path (str | Path) – The file path to save the configuration.
- panoptica.utils.config._save_to_config_by_name(obj, name: str)¶
Saves an instance of a class to a configuration file by name.
- Parameters:
obj – The object to save.
name (str) – The name used to determine the configuration file path.
- panoptica.utils.config._save_yaml(data_dict: dict | object, out_file: str | Path, registered_class=None)¶
Saves a Python dictionary or object to a YAML file, with optional class registration.
- Parameters:
data_dict (dict | object) – Data to save.
out_file (str | Path) – Output file path.
registered_class (optional) – Class type to register with YAML if saving an object.
panoptica.utils.constants module¶
- class panoptica.utils.constants.CCABackend(value)¶
Bases:
_Enum_Compare
Enumeration representing different connected component analysis (CCA) backends.
This enumeration defines options for CCA backends, which are used for labeling connected components in segmentation masks.
- Members:
cc3d: Represents the Connected Components in 3D (CC3D) backend for CCA. [CC3D Website](https://github.com/seung-lab/connected-components-3d)
scipy: Represents the SciPy backend for CCA. [SciPy Website](https://www.scipy.org/)
- cc3d = 1¶
- scipy = 2¶
- class panoptica.utils.constants._Enum_Compare(value)¶
Bases:
Enum
An extended Enum class that supports additional comparison and YAML configuration functionality.
This class enhances standard Enum capabilities, allowing comparisons with other enums or strings by name and adding support for YAML serialization and deserialization methods.
- __eq__(__value)¶
Checks equality with another Enum or string.
- __str__()¶
Returns a string representation of the Enum instance.
- __repr__()¶
Returns a string representation for debugging.
- load_from_config(cls, path)¶
Loads an Enum instance from a configuration file.
- load_from_config_name(cls, name)¶
Loads an Enum instance from a configuration file identified by name.
- save_to_config(path)¶
Saves the Enum instance to a configuration file.
- to_yaml(cls, representer, node)¶
Serializes the Enum to YAML.
- from_yaml(cls, constructor, node)¶
Deserializes YAML data into an Enum instance.
- classmethod _register_permanently()¶
- classmethod from_yaml(constructor, node)¶
- classmethod load_from_config(path: str | Path)¶
- classmethod load_from_config_name(name: str)¶
- save_to_config(path: str | Path)¶
- classmethod to_yaml(representer, node)¶
panoptica.utils.edge_case_handling module¶
- class panoptica.utils.edge_case_handling.EdgeCaseHandler(listmetric_zeroTP_handling: dict[~panoptica.metrics.metrics.Metric, ~panoptica.utils.edge_case_handling.MetricZeroTPEdgeCaseHandling] = {Metric.ASSD: <panoptica.utils.edge_case_handling.MetricZeroTPEdgeCaseHandling object>, Metric.DSC: <panoptica.utils.edge_case_handling.MetricZeroTPEdgeCaseHandling object>, Metric.IOU: <panoptica.utils.edge_case_handling.MetricZeroTPEdgeCaseHandling object>, Metric.RVAE: <panoptica.utils.edge_case_handling.MetricZeroTPEdgeCaseHandling object>, Metric.RVD: <panoptica.utils.edge_case_handling.MetricZeroTPEdgeCaseHandling object>, Metric.clDSC: <panoptica.utils.edge_case_handling.MetricZeroTPEdgeCaseHandling object>}, empty_list_std: ~panoptica.utils.edge_case_handling.EdgeCaseResult = EdgeCaseResult.NAN)¶
Bases:
SupportsConfig
Manages edge cases across multiple metrics, including standard deviation handling for empty lists.
- listmetric_zeroTP_handling¶
Dictionary mapping metrics to their zero-TP edge case handling.
- Type:
dict
- empty_list_std¶
Default edge case for handling standard deviation of empty lists.
- Type:
- handle_zero_tp(metric, tp, num_pred_instances, num_ref_instances)¶
Checks if an edge case exists and returns its result.
- listmetric_zeroTP_handling()¶
Returns the edge case handling dictionary.
- get_metric_zero_tp_handle(metric)¶
Returns the zero-TP handler for a specific metric.
- handle_empty_list_std()¶
Handles standard deviation of empty lists.
- _yaml_repr(cls, node)¶
YAML representation of the handler.
- classmethod _yaml_repr(node) dict ¶
Abstract method for representing the class in YAML.
- Parameters:
node – The object instance to represent in YAML.
- Returns:
A dictionary representation of the class.
- Return type:
dict
- handle_empty_list_std() EdgeCaseResult | None ¶
- handle_zero_tp(metric: Metric, tp: int, num_pred_instances: int, num_ref_instances: int) tuple[bool, float | None] ¶
_summary_
- Parameters:
metric (Metric) – _description_
tp (int) – _description_
num_pred_instances (int) – _description_
num_ref_instances (int) – _description_
- Raises:
NotImplementedError – _description_
- Returns:
if edge case, and its edge case value
- Return type:
tuple[bool, float | None]
- property listmetric_zeroTP_handling¶
- class panoptica.utils.edge_case_handling.EdgeCaseResult(value)¶
Bases:
_Enum_Compare
Enumeration of edge case values used for handling specific metric situations.
This enum defines several common edge case values for handling zero-true-positive (zero-TP) situations in various metrics. The values include infinity, NaN, zero, one, and None.
- INF¶
Represents infinity (np.inf).
- NAN¶
Represents not-a-number (np.nan).
- ZERO¶
Represents zero (0.0).
- ONE¶
Represents one (1.0).
- NONE¶
Represents a None value.
- value()¶
Returns the value associated with the edge case.
- __call__()¶
Returns the numeric or None representation of the enum member.
- INF = inf¶
- NAN = nan¶
- NONE = None¶
- ONE = 1.0¶
- ZERO = 0.0¶
- property value¶
- class panoptica.utils.edge_case_handling.EdgeCaseZeroTP(value)¶
Bases:
_Enum_Compare
Enum defining scenarios that could produce zero true positives (zero-TP) in metrics.
- NO_INSTANCES¶
No instances in both the prediction and reference.
- EMPTY_PRED¶
The prediction is empty.
- EMPTY_REF¶
The reference is empty.
- NORMAL¶
A typical scenario with non-zero instances.
- EMPTY_PRED = 2¶
- EMPTY_REF = 3¶
- NORMAL = 4¶
- NO_INSTANCES = 1¶
- class panoptica.utils.edge_case_handling.MetricZeroTPEdgeCaseHandling(default_result: EdgeCaseResult | None = None, no_instances_result: EdgeCaseResult | None = None, empty_prediction_result: EdgeCaseResult | None = None, empty_reference_result: EdgeCaseResult | None = None, normal: EdgeCaseResult | None = None)¶
Bases:
SupportsConfig
Handles zero-TP edge cases for metrics, mapping different zero-TP scenarios to specific results.
- default_result¶
Default result if specific edge cases are not provided.
- Type:
EdgeCaseResult | None
- no_instances_result¶
Result when no instances are present.
- Type:
EdgeCaseResult | None
- empty_prediction_result¶
Result when prediction is empty.
- Type:
EdgeCaseResult | None
- empty_reference_result¶
Result when reference is empty.
- Type:
EdgeCaseResult | None
- normal¶
Result when a normal zero-TP scenario occurs.
- Type:
EdgeCaseResult | None
- __call__(tp, num_pred_instances, num_ref_instances)¶
Determines if an edge case is detected and returns its result.
- __eq__(value)¶
Compares this handling object to another.
- __str__()¶
String representation of edge cases.
- _yaml_repr(cls, node)¶
YAML representation for the edge case.
- classmethod _yaml_repr(node) dict ¶
Abstract method for representing the class in YAML.
- Parameters:
node – The object instance to represent in YAML.
- Returns:
A dictionary representation of the class.
- Return type:
dict
panoptica.utils.filepath module¶
- panoptica.utils.filepath.config_by_name(name: str) Path ¶
- panoptica.utils.filepath.config_dir_by_name(name: str) tuple[Path, str] ¶
- panoptica.utils.filepath.search_path(basepath: str | Path, query: str, verbose: bool = False, suppress: bool = False) list[Path] ¶
Searches from basepath with query :param basepath: ground path to look into :param query: search query, can contain wildcards like .npz or */*.npz :param verbose: :param suppress: if true, will not throwing warnings if nothing is found
- Returns:
All found paths
panoptica.utils.instancelabelmap module¶
- class panoptica.utils.instancelabelmap.InstanceLabelMap¶
Bases:
object
Creates a mapping between prediction labels and reference labels in a many-to-one relationship.
This class allows mapping multiple prediction labels to a single reference label. It includes methods for adding new mappings, checking containment, retrieving predictions mapped to a reference, and exporting the mapping as a dictionary.
- labelmap¶
Dictionary storing the prediction-to-reference label mappings.
- Type:
dict[int, int]
- add_labelmap_entry(pred_labels, ref_label)¶
Adds a new entry mapping prediction labels to a reference label.
- get_pred_labels_matched_to_ref(ref_label)¶
Retrieves prediction labels mapped to a given reference label.
- contains_pred(pred_label)¶
Checks if a prediction label exists in the map.
- contains_ref(ref_label)¶
Checks if a reference label exists in the map.
- contains_and(pred_label, ref_label)¶
Checks if both a prediction and a reference label are in the map.
- contains_or(pred_label, ref_label)¶
Checks if either a prediction or reference label is in the map.
- get_one_to_one_dictionary()¶
Returns the labelmap dictionary for a one-to-one view.
- add_labelmap_entry(pred_labels: list[int] | int, ref_label: int)¶
Adds an entry that maps prediction labels to a single reference label.
- Parameters:
pred_labels (list[int] | int) – List of prediction labels or a single prediction label.
ref_label (int) – Reference label to map to.
- Raises:
AssertionError – If ref_label is not an integer.
AssertionError – If any pred_labels are not integers.
Exception – If a prediction label is already mapped to a different reference label.
- contains_and(pred_label: int | None = None, ref_label: int | None = None) bool ¶
Checks if both a prediction and a reference label are in the map.
- Parameters:
pred_label (int | None) – The prediction label to check.
ref_label (int | None) – The reference label to check.
- Returns:
True if both pred_label and ref_label are in the map; otherwise, False.
- Return type:
bool
- contains_or(pred_label: int | None = None, ref_label: int | None = None) bool ¶
Checks if either a prediction or reference label is in the map.
- Parameters:
pred_label (int | None) – The prediction label to check.
ref_label (int | None) – The reference label to check.
- Returns:
True if either pred_label or ref_label are in the map; otherwise, False.
- Return type:
bool
- contains_pred(pred_label: int)¶
Checks if a prediction label exists in the map.
- Parameters:
pred_label (int) – The prediction label to search.
- Returns:
True if pred_label is in labelmap, otherwise False.
- Return type:
bool
- contains_ref(ref_label: int)¶
Checks if a reference label exists in the map.
- Parameters:
ref_label (int) – The reference label to search.
- Returns:
True if ref_label is in labelmap values, otherwise False.
- Return type:
bool
- get_one_to_one_dictionary()¶
Returns a copy of the labelmap dictionary for a one-to-one view.
- Returns:
The prediction-to-reference label mapping.
- Return type:
dict[int, int]
- get_pred_labels_matched_to_ref(ref_label: int)¶
Retrieves all prediction labels that map to a specified reference label.
- Parameters:
ref_label (int) – The reference label to search.
- Returns:
List of prediction labels mapped to ref_label.
- Return type:
list[int]
- labelmap: dict[int, int]¶
panoptica.utils.label_group module¶
- class panoptica.utils.label_group.LabelGroup(value_labels: list[int] | int, single_instance: bool = False)¶
Bases:
SupportsConfig
Defines a group of labels that semantically belong together for segmentation purposes.
Groups of labels define label sets that can be matched with each other. For example, labels might represent different parts of a segmented object, and only those within the group are eligible for matching.
- value_labels¶
List of integer labels representing segmentation group labels.
- Type:
list[int]
- single_instance¶
If True, the group represents a single instance without matching threshold consideration.
- Type:
bool
- classmethod _yaml_repr(node)¶
Abstract method for representing the class in YAML.
- Parameters:
node – The object instance to represent in YAML.
- Returns:
A dictionary representation of the class.
- Return type:
dict
- extract_label(array: ndarray, set_to_binary: bool = False)¶
Extracts an array of the labels specific to this segmentation group.
- Parameters:
array (np.ndarray) – The array to filter for segmentation group labels.
set_to_binary (bool, optional) – If True, outputs a binary array. Defaults to False.
- Returns:
An array with only the labels of this segmentation group.
- Return type:
np.ndarray
- property single_instance: bool¶
Indicates if this group is treated as a single instance.
- property value_labels: list[int]¶
List of integer labels for this segmentation group.
- class panoptica.utils.label_group.LabelMergeGroup(value_labels: list[int] | int, single_instance: bool = False)¶
Bases:
LabelGroup
Defines a group of labels that will be merged into a single label when extracted.
Inherits from LabelGroup and sets extracted labels to a binary format. This is useful for region-evaluation (e.g. BRATS), where you want to merge multiple labels into one before evaluation.
- __call__(array)¶
Extracts the label group as a binary array.
- class panoptica.utils.label_group._LabelGroupAny¶
Bases:
LabelGroup
Represents a group that includes all labels in the array with no specific segmentation constraints.
Used to represent a group that does not restrict labels.
- __call__(array, set_to_binary)¶
Returns the unfiltered array.
- classmethod _yaml_repr(node)¶
Abstract method for representing the class in YAML.
- Parameters:
node – The object instance to represent in YAML.
- Returns:
A dictionary representation of the class.
- Return type:
dict
- property single_instance: bool¶
Indicates if this group is treated as a single instance.
- property value_labels: list[int]¶
List of integer labels for this segmentation group.
panoptica.utils.numpy_utils module¶
- panoptica.utils.numpy_utils._count_unique_without_zeros(arr: ndarray) int ¶
Count the number of unique elements in the input NumPy array, excluding zeros.
- Parameters:
arr (np.ndarray) – Input array.
- Returns:
Number of unique elements excluding zeros.
- Return type:
int
- panoptica.utils.numpy_utils._get_bbox_nd(img: ndarray, px_dist: int | tuple[int, ...] = 0) tuple[slice, ...] ¶
calculates a bounding box in n dimensions given a image (factor ~2 times faster than compute_crop_slice)
- Parameters:
img – input array
px_dist – int | tuple[int]: dist (int): The amount of padding to be added to the cropped image. If int, will apply the same padding to each dim. Default value is 0.
- Returns:
list of boundary coordinates [x_min, x_max, y_min, y_max, z_min, z_max]
- panoptica.utils.numpy_utils._get_smallest_fitting_uint(max_value: int) type ¶
Determine the smallest unsigned integer type that can accommodate the given maximum value.
- Parameters:
max_value (int) – The maximum value to be accommodated.
- Returns:
The NumPy data type (e.g., np.uint8, np.uint16, np.uint32, np.uint64).
- Return type:
type
Example: >>> _get_smallest_fitting_uint(255) <class ‘numpy.uint8’>
- panoptica.utils.numpy_utils._unique_without_zeros(arr: ndarray) ndarray ¶
Get unique non-zero values from a NumPy array.
- Parameters:
arr (np.ndarray) – Input NumPy array.
- Returns:
Unique non-zero values from the input array.
- Return type:
np.ndarray
Issues a warning if negative values are present.
panoptica.utils.parallel_processing module¶
- class panoptica.utils.parallel_processing.NoDaemonProcess(group: None = None, target: Callable[[...], object] | None = None, name: str | None = None, args=None, kwargs=None, *, daemon: bool | None = None)¶
Bases:
Process
A subclass of multiprocessing.Process that overrides daemon behavior to always be non-daemonic.
Useful for creating a process that allows child processes to spawn their own children, as daemonic processes in Python cannot create further subprocesses.
- group¶
Reserved for future extension when using process groups.
- Type:
None
- target¶
The callable object to be invoked by the process.
- Type:
Callable[…, object] | None
- name¶
The name of the process, for identification.
- Type:
str | None
- args¶
Arguments to pass to the target function.
- Type:
tuple
- kwargs¶
Keyword arguments to pass to the target function.
- Type:
dict
- daemon¶
Indicates if the process is daemonic (overridden to always be False).
- Type:
bool | None
- _get_daemon()¶
- _set_daemon(value)¶
- property daemon¶
Return whether process is a daemon
- class panoptica.utils.parallel_processing.NonDaemonicPool(processes=None, initializer=None, initargs=(), maxtasksperchild=None, context=None)¶
Bases:
Pool
A version of multiprocessing.pool.Pool using non-daemonic processes, allowing child processes to spawn their own children.
This class creates a pool of worker processes using NoDaemonProcess for situations where nested child processes are needed.
- Process¶
alias of
NoDaemonProcess
panoptica.utils.processing_pair module¶
- class panoptica.utils.processing_pair.EvaluateInstancePair(reference_arr: ndarray, prediction_arr: ndarray, num_pred_instances: int, num_ref_instances: int, tp: int, list_metrics: dict[Metric, list[float]])¶
Bases:
object
Represents an evaluation of instance segmentation results, comparing reference and prediction data.
This class is used to store and evaluate metrics for instance segmentation, tracking the number of instances and true positives (tp) alongside calculated metrics.
- reference_arr¶
Array containing reference instance labels.
- Type:
np.ndarray
- prediction_arr¶
Array containing predicted instance labels.
- Type:
np.ndarray
- num_pred_instances¶
The number of unique instances in the prediction array.
- Type:
int
- num_ref_instances¶
The number of unique instances in the reference array.
- Type:
int
- tp¶
The number of true positive matches between predicted and reference instances.
- Type:
int
- list_metrics¶
Dictionary of metric calculations, where each key is a Metric object, and each value is a list of metric scores (floats).
- Type:
dict[Metric, list[float]]
- num_pred_instances: int¶
- num_ref_instances: int¶
- prediction_arr: ndarray¶
- reference_arr: ndarray¶
- tp: int¶
- class panoptica.utils.processing_pair.InputType(value)¶
Bases:
_Enum_Compare
Defines the types of input processing pairs available for evaluation.
This enumeration provides different processing classes for handling various instance segmentation scenarios, allowing flexible instantiation of processing pairs based on the desired comparison type.
- SEMANTIC¶
Processes semantic labels, intended for cases without instances.
- Type:
- UNMATCHED_INSTANCE¶
Processes instance maps without requiring label matches.
- Type:
- MATCHED_INSTANCE¶
Processes instance maps with label matching between prediction and reference.
- Type:
- __call__(self, prediction_arr
np.ndarray, reference_arr: np.ndarray) -> _ProcessingPair: Creates a processing pair based on the specified InputType, using the provided prediction and reference arrays.
Example
>>> input_type = InputType.MATCHED_INSTANCE >>> processing_pair = input_type(prediction_arr, reference_arr)
- MATCHED_INSTANCE = <class 'panoptica.utils.processing_pair.MatchedInstancePair'>¶
- SEMANTIC = <class 'panoptica.utils.processing_pair.SemanticPair'>¶
- UNMATCHED_INSTANCE = <class 'panoptica.utils.processing_pair.UnmatchedInstancePair'>¶
- class panoptica.utils.processing_pair.IntermediateStepsData(original_input: _ProcessingPair | None)¶
Bases:
object
Manages intermediate data steps for a processing pipeline, storing and retrieving processing states.
This class enables step-by-step tracking of data transformations during processing.
- original_input¶
The original input data before processing steps.
- Type:
_ProcessingPair | None
- _intermediatesteps¶
Dictionary of intermediate processing steps.
- Type:
dict[str, _ProcessingPair]
- add_intermediate_arr_data(processing_pair: _ProcessingPair, inputtype: InputType)¶
- add_intermediate_data(key, value)¶
- property original_prediction_arr¶
- property original_reference_arr¶
- class panoptica.utils.processing_pair.MatchedInstancePair(prediction_arr: ndarray, reference_arr: ndarray, missed_reference_labels: list[int] | None = None, missed_prediction_labels: list[int] | None = None, matched_instances: list[int] | None = None, n_prediction_instance: int | None = None, n_reference_instance: int | None = None)¶
Bases:
_ProcessingPairInstanced
Represents a matched processing pair for instance maps, handling matched and unmatched labels.
This class tracks both matched instances and any unmatched labels between prediction and reference arrays.
- missed_reference_labels¶
Reference labels with no matching prediction.
- Type:
list[int]
- missed_prediction_labels¶
Prediction labels with no matching reference.
- Type:
list[int]
- matched_instances¶
Labels matched between prediction and reference arrays.
- Type:
list[int]
- _abc_impl = <_abc._abc_data object>¶
- copy()¶
Creates an exact copy of this object
- matched_instances: list[int]¶
- missed_prediction_labels: list[int]¶
- missed_reference_labels: list[int]¶
- property n_matched_instances¶
- class panoptica.utils.processing_pair.SemanticPair(prediction_arr: ndarray, reference_arr: ndarray)¶
Bases:
_ProcessingPair
Represents a semantic processing pair with integer-type arrays for label analysis.
This class is tailored to scenarios where arrays contain semantic labels rather than instance IDs.
- _abc_impl = <_abc._abc_data object>¶
- class panoptica.utils.processing_pair.UnmatchedInstancePair(prediction_arr: ndarray, reference_arr: ndarray, n_prediction_instance: int | None = None, n_reference_instance: int | None = None)¶
Bases:
_ProcessingPairInstanced
A Processing pair that contain Unmatched Instance Maps Can be of any unsigned (but matching) integer type
- _abc_impl = <_abc._abc_data object>¶
- class panoptica.utils.processing_pair._ProcessingPair(prediction_arr: ndarray, reference_arr: ndarray)¶
Bases:
ABC
Represents a pair of processing arrays, typically prediction and reference arrays.
This base class provides core functionality for processing and comparing prediction and reference data arrays. Each instance contains two arrays and supports cropping and data integrity checks.
- n_dim¶
The number of dimensions in the reference array.
- Type:
int
- crop¶
The crop region applied to both arrays, if any.
- Type:
tuple[slice, …] | None
- is_cropped¶
Indicates whether the arrays have been cropped.
- Type:
bool
- uncropped_shape¶
The original shape of the arrays before cropping.
- Type:
tuple[int, …]
- _abc_impl = <_abc._abc_data object>¶
- copy()¶
Creates an exact copy of this object
- crop_data(verbose: bool = False)¶
Crops prediction and reference arrays to non-zero regions.
- Parameters:
verbose (bool, optional) – If True, prints cropping details. Defaults to False.
- property n_dim¶
- property pred_labels¶
- property prediction_arr¶
- property ref_labels¶
- property reference_arr¶
- set_dtype(type)¶
Sets the data type for both prediction and reference arrays.
- Parameters:
dtype (type) – Expected integer type for the arrays.
- uncrop_data(verbose: bool = False)¶
Restores the arrays to their original, uncropped shape.
- Parameters:
verbose (bool, optional) – If True, prints uncropping details. Defaults to False.
- class panoptica.utils.processing_pair._ProcessingPairInstanced(prediction_arr: ndarray, reference_arr: ndarray, n_prediction_instance: int | None = None, n_reference_instance: int | None = None)¶
Bases:
_ProcessingPair
Represents a processing pair with labeled instances, including unique label counts.
This subclass tracks additional details about the number of unique instances in each array.
- n_prediction_instance¶
Number of unique prediction instances.
- Type:
int
- n_reference_instance¶
Number of unique reference instances.
- Type:
int
- _abc_impl = <_abc._abc_data object>¶
- copy()¶
Creates an exact copy of this object
- n_prediction_instance: int¶
- n_reference_instance: int¶
- panoptica.utils.processing_pair._check_array_integrity(prediction_arr: ndarray, reference_arr: ndarray, dtype: type | None = None)¶
Validates integrity between two arrays, checking shape, dtype, and consistency with dtype.
- Parameters:
prediction_arr (np.ndarray) – The array to be validated.
reference_arr (np.ndarray) – The reference array for comparison.
dtype (type | None) – Expected type of the arrays. If None, dtype validation is skipped.
- Raises:
AssertionError – If validation fails in any of the following cases: - Arrays are not numpy arrays. - Shapes of both arrays are not identical. - Data types of both arrays do not match. - Dtype mismatch when specified.
Example: >>> _check_array_integrity(np.array([1, 2, 3]), np.array([4, 5, 6]), dtype=int)
panoptica.utils.segmentation_class module¶
- class panoptica.utils.segmentation_class.SegmentationClassGroups(groups: list[LabelGroup] | dict[str, LabelGroup | tuple[list[int] | int, bool]])¶
Bases:
SupportsConfig
Represents a collection of segmentation class groups.
This class manages groups of labels used in segmentation tasks. It supports both list and dictionary formats for group initialization. SegmentationClassGroups are a collection of LabelGroups with names. So it maps a group name (str) to a LabelGroup. A LabelGroup defines a collection of labels that belong to the same structure / region of interest.
- __group_dictionary¶
A dictionary mapping group names to their respective LabelGroup instances.
- Type:
dict[str, LabelGroup]
- __labels¶
A flat list of unique labels collected from all LabelGroups.
- Type:
list[int]
- Parameters:
groups (list[LabelGroup] | dict[str, LabelGroup | tuple[list[int] | int, bool]]) – A list of LabelGroup instances or a dictionary where keys are group names (str) and values are either LabelGroup instances or tuples containing a list of label values and a boolean.
- classmethod _yaml_repr(node)¶
Abstract method for representing the class in YAML.
- Parameters:
node – The object instance to represent in YAML.
- Returns:
A dictionary representation of the class.
- Return type:
dict
- has_defined_labels_for(arr: ndarray | list[int], raise_error: bool = False)¶
Checks if the labels in the provided array are defined in the segmentation class groups.
- Parameters:
arr (np.ndarray | list[int]) – The array of labels to check.
raise_error (bool) – If True, raises an error when an undefined label is found. Defaults to False.
- Returns:
True if all labels are defined; False otherwise.
- Return type:
bool
- Raises:
AssertionError – If an undefined label is found and raise_error is True.
- items()¶
- keys() list[str] ¶
- property labels¶
- class panoptica.utils.segmentation_class._NoSegmentationClassGroups¶
Bases:
SegmentationClassGroups
Represents a placeholder for segmentation class groups with no defined labels.
This class indicates that no specific segmentation groups or labels are defined, and any label is valid.
- __group_dictionary¶
A dictionary with a single entry representing all labels as a group.
- Type:
dict[str, LabelGroup]
- classmethod _yaml_repr(node)¶
Abstract method for representing the class in YAML.
- Parameters:
node – The object instance to represent in YAML.
- Returns:
A dictionary representation of the class.
- Return type:
dict
- has_defined_labels_for(arr: ndarray | list[int], raise_error: bool = False)¶
Checks if the labels in the provided array are defined in the segmentation class groups.
- Parameters:
arr (np.ndarray | list[int]) – The array of labels to check.
raise_error (bool) – If True, raises an error when an undefined label is found. Defaults to False.
- Returns:
True if all labels are defined; False otherwise.
- Return type:
bool
- Raises:
AssertionError – If an undefined label is found and raise_error is True.
- keys() list[str] ¶
- property labels¶
- panoptica.utils.segmentation_class.list_duplicates(seq)¶
Identifies duplicates in a sequence.
- Parameters:
seq (list) – The input sequence to check for duplicates.
- Returns:
A list of duplicates found in the input sequence.
- Return type:
list
panoptica.utils.timing module¶
- panoptica.utils.timing.measure_time(func)¶
Decorator to measure the time it takes to execute a function.