Source code for cops.config

"""
Configuration management models for COPS particle analysis.

This module centralizes configuration parsing, defaults, validation, and provenance tracking
using immutable dataclass models, ensuring type safety and decoupling pipeline functions
from raw ConfigParser instances.

History:
--------
- 2026-07-03: Yongjie Huang, implemented resolve_probe_config_path and updated load_probe_config.
- 2026-06-27: Yongjie Huang, created to centralize ConfigParser logic into structured dataclass models.
"""

from __future__ import annotations

import ast
import logging
import os
from configparser import ConfigParser
from dataclasses import dataclass, replace
from typing import Any

import numpy as np

from .constants import (
    ACCEPTED_CODES,
    AREA_RATIO_MIN,
    DIAMETER_CATEGORIES,
    ML_DIAMETER_FAMILIES,
    ML_MIXED_DIAMETER_CHOICE,
    PROBE_CONFIG_NAME_BY_HEADER,
    SA_METHODS,
)
from .ml.errors import MLConfigurationError
from .ml.schema import (
    DEFAULT_POPULATION_MODE as ML_DEFAULT_POPULATION_MODE,
    FAMILIES as ML_FAMILIES,
    FALLBACK_POLICIES as ML_FALLBACK_POLICIES,
    POPULATION_MODES as ML_POPULATION_MODES,
)

logger = logging.getLogger(__name__)


_SPEC_PROBE_TYPES = frozenset((1, 2, 3, 4)) # SPEC probes: HVPS (1), 2DS (2), HVPS4 (3), Fast2DS (4)
_SPEC_DOF_CONSTANT = 8.12
_GENERAL_DOF_CONSTANT = 3.0


[docs] def resolve_probe_config_name(instrument_name: str, resolution: float) -> str: """Return the COPS configuration name represented by a SPIF header.""" normalized_name = instrument_name.strip() normalized_resolution = int(round(float(np.asarray(resolution).item()))) return PROBE_CONFIG_NAME_BY_HEADER.get( (normalized_name.upper(), normalized_resolution), normalized_name, )
[docs] def resolve_dof_constant(probe_type: int, configured_value: float | None = None) -> float: """Resolve the configured DoF coefficient or the probe-specific default. SPEC probes (HVPS, 2DS, HVPS4, and Fast2DS) use the SPEC/Lawson default; all other probe types use the general DMT/Knollenberg default. References ---------- - SPEC 2DS Post Processing Software Manual Lawson, R. P., D. O’Connor, P. Zmarzly, K. Weaver, B. Baker, Q. Mo, and H. Jonsson, 2006: The 2D-S (Stereo) Probe: Design and Preliminary Tests of a New Airborne, High-Speed, High-Resolution Particle Imaging Probe. J. Atmos. Oceanic Technol., 23, 1462–1477, https://doi.org/10.1175/JTECH1927.1 - DMT Data Analysis User’s Guide – Chapter II: Single Particle Imaging Knollenberg, R. G., 1970: The Optical Array: An Alternative to Scattering or Extinction for Airborne Particle Size Determination. J. Appl. Meteor. Climatol., 9, 86–103, https://doi.org/10.1175/1520-0450(1970)009%3C0086:TOAAAT%3E2.0.CO;2 History ------- - 2026-07-17: Yongjie Huang (huangynj@gmail.com), first created. """ if configured_value is None: resolved_value = ( _SPEC_DOF_CONSTANT if probe_type in _SPEC_PROBE_TYPES else _GENERAL_DOF_CONSTANT ) else: if isinstance(configured_value, (bool, np.bool_)) or not isinstance( configured_value, (int, float, np.integer, np.floating) ): raise ValueError( f"DoFConstant must be a finite positive number or omitted, got {configured_value!r}" ) resolved_value = float(configured_value) if not np.isfinite(resolved_value) or resolved_value <= 0: raise ValueError( f"DoFConstant must be a finite positive number or omitted, got {configured_value!r}" ) return float(resolved_value)
[docs] @dataclass(frozen=True) class ConfigProvenance: """Tracks the origin and operational status of processing configurations.""" path: str | None status: str @property def attrs(self) -> dict[str, str]: """Returns provenance metadata formatted for NetCDF global attributes.""" if self.path is None: return { "processing_config_source": "missing", "processing_provenance_status": self.status, } return { "processing_config_source": self.path, "processing_provenance_status": self.status, }
def _safe_parse_bin_edges(expr_str: str, diode_size: float) -> np.ndarray: """ Safely parse and validate bin_edges configuration string without using raw eval(). Supports list literals, arithmetic operations, and np.arange / np.linspace calls. Performs rigorous validation on shape, dtype, finite values, length, and strictly increasing edges. """ ALLOWED_NAMES = {'diode_size': diode_size} def _eval_node(node): if isinstance(node, ast.Constant): return node.value elif isinstance(node, ast.List): return np.array([_eval_node(elt) for elt in node.elts]) elif isinstance(node, ast.Tuple): return tuple(_eval_node(elt) for elt in node.elts) elif isinstance(node, ast.Name): if node.id in ALLOWED_NAMES: return ALLOWED_NAMES[node.id] elif node.id == 'np': return np raise ValueError(f"Unauthorized name in bin_edges config: {node.id}") elif isinstance(node, ast.UnaryOp): op = node.op operand = _eval_node(node.operand) if isinstance(op, ast.USub): return -operand elif isinstance(op, ast.UAdd): return operand raise ValueError(f"Unsupported unary op: {type(op).__name__}") elif isinstance(node, ast.BinOp): left = _eval_node(node.left) right = _eval_node(node.right) op = node.op if isinstance(op, ast.Add): return left + right elif isinstance(op, ast.Sub): return left - right elif isinstance(op, ast.Mult): return left * right elif isinstance(op, ast.Div): return left / right elif isinstance(op, ast.Pow): return left ** right raise ValueError(f"Unsupported binary op: {type(op).__name__}") elif isinstance(node, ast.Call): func = node.func if isinstance(func, ast.Attribute) and isinstance(func.value, ast.Name) and func.value.id == 'np': func_name = func.attr if func_name in ('arange', 'linspace'): args = [_eval_node(arg) for arg in node.args] kwargs = {kw.arg: _eval_node(kw.value) for kw in node.keywords} return getattr(np, func_name)(*args, **kwargs) raise ValueError(f"Unauthorized function call in bin_edges config: {ast.dump(node)}") else: raise ValueError(f"Unsupported syntax in bin_edges config: {type(node).__name__}") try: tree = ast.parse(expr_str, mode='eval') result = _eval_node(tree.body) arr = np.array(result) except Exception as e: raise ValueError(f"Failed to parse bin_edges configuration '{expr_str}': {e}") from e if not np.issubdtype(arr.dtype, np.number): raise ValueError(f"bin_edges must be a numeric array, got dtype {arr.dtype}") if arr.ndim != 1: raise ValueError(f"bin_edges must be a 1D array, got {arr.ndim}D") if len(arr) < 2: raise ValueError(f"bin_edges must have at least 2 edges to form a bin, got length {len(arr)}") if not np.all(np.isfinite(arr)): raise ValueError("bin_edges contains non-finite values (inf or nan)") if not np.all(np.diff(arr) > 0): raise ValueError("bin_edges must be strictly increasing with no duplicates") return arr
[docs] @dataclass(frozen=True) class ImageProcessingConfig: """Configuration parameters for Level-1 particle image processing.""" particle_mask: int = 0 iRectEllipse: int = 0 iCalcAllDiodeStats: int = 0 tasMax: float = 170.0 phase_method: str = "soda2_roundness" phase_roundness_mode: str = "standard" # Additional classification floor; does not replace SODA2's fixed 0.40 # tiny-particle threshold in mixed-phase or morphology-only regimes. phase_area_ratio_floor: float = 0.40 phase_max_liquid_diameter_mm: float = 6.0 phase_size_rule_diodes: int = 10 applyLevel1BulkAndQC: int = 1 def __post_init__(self): """Validates parameter values and binary flags.""" if not isinstance(self.tasMax, (float, int)) or isinstance(self.tasMax, bool) or self.tasMax <= 0: raise ValueError(f"tasMax must be a positive number, got {self.tasMax!r}") if not isinstance(self.particle_mask, int) or isinstance(self.particle_mask, bool) or self.particle_mask < 0: raise ValueError(f"particle_mask must be a non-negative integer, got {self.particle_mask!r}") if not isinstance(self.iRectEllipse, int) or isinstance(self.iRectEllipse, bool) or self.iRectEllipse not in (0, 1): raise ValueError(f"iRectEllipse must be 0 or 1, got {self.iRectEllipse!r}") if not isinstance(self.iCalcAllDiodeStats, int) or isinstance(self.iCalcAllDiodeStats, bool) or self.iCalcAllDiodeStats not in (0, 1): raise ValueError(f"iCalcAllDiodeStats must be 0 or 1, got {self.iCalcAllDiodeStats!r}") if not isinstance(self.applyLevel1BulkAndQC, int) or isinstance(self.applyLevel1BulkAndQC, bool) or self.applyLevel1BulkAndQC not in (0, 1): raise ValueError(f"applyLevel1BulkAndQC must be 0 or 1, got {self.applyLevel1BulkAndQC!r}") phase_methods = ("none", "soda2_roundness", "ml_knn", "ml_rf", "ml_hgb") if self.phase_method not in phase_methods: raise ValueError( f"phase_method must be one of {phase_methods}, got {self.phase_method!r}" ) if self.phase_roundness_mode not in ("standard", "strict"): raise ValueError(f"phase_roundness_mode must be 'standard' or 'strict', got {self.phase_roundness_mode!r}") if not isinstance(self.phase_area_ratio_floor, (float, int)) or isinstance(self.phase_area_ratio_floor, bool) or not (0.0 <= self.phase_area_ratio_floor <= 1.0): raise ValueError(f"phase_area_ratio_floor must be between 0.0 and 1.0, got {self.phase_area_ratio_floor!r}") if not isinstance(self.phase_max_liquid_diameter_mm, (float, int)) or isinstance(self.phase_max_liquid_diameter_mm, bool) or self.phase_max_liquid_diameter_mm <= 0: raise ValueError(f"phase_max_liquid_diameter_mm must be a positive number, got {self.phase_max_liquid_diameter_mm!r}") if not isinstance(self.phase_size_rule_diodes, int) or isinstance(self.phase_size_rule_diodes, bool) or self.phase_size_rule_diodes <= 0: raise ValueError(f"phase_size_rule_diodes must be a positive integer, got {self.phase_size_rule_diodes!r}")
[docs] @classmethod def from_parser(cls, config: ConfigParser) -> "ImageProcessingConfig": """Instantiates configuration from a ConfigParser object.""" return cls( particle_mask=config.getint('particle_image_processing', 'particle_mask', fallback=0), iRectEllipse=config.getint('particle_image_processing', 'iRectEllipse', fallback=0), iCalcAllDiodeStats=config.getint('particle_image_processing', 'iCalcAllDiodeStats', fallback=0), applyLevel1BulkAndQC=config.getint('particle_image_processing', 'applyLevel1BulkAndQC', fallback=1), tasMax=config.getfloat('particle_image_processing', 'tasMax', fallback=170.0), phase_method=config.get('particle_image_processing', 'phase_method', fallback="soda2_roundness"), phase_roundness_mode=config.get('particle_image_processing', 'phase_roundness_mode', fallback="standard"), phase_area_ratio_floor=config.getfloat('particle_image_processing', 'phase_area_ratio_floor', fallback=0.40), phase_max_liquid_diameter_mm=config.getfloat('particle_image_processing', 'phase_max_liquid_diameter_mm', fallback=6.0), phase_size_rule_diodes=config.getint('particle_image_processing', 'phase_size_rule_diodes', fallback=10), )
[docs] def attrs_for_dataset(self) -> dict[str, Any]: """Returns dictionary of attributes to attach to NetCDF datasets.""" return { 'applyLevel1BulkAndQC': self.applyLevel1BulkAndQC, 'tasMax': self.tasMax, 'phase_method': self.phase_method, 'phase_roundness_mode': self.phase_roundness_mode, 'phase_area_ratio_floor': self.phase_area_ratio_floor, 'phase_max_liquid_diameter_mm': self.phase_max_liquid_diameter_mm, 'phase_size_rule_diodes': self.phase_size_rule_diodes, }
[docs] @dataclass(frozen=True) class SizeDistributionConfig: """Configuration parameters for Level-2 particle size distribution calculations and QC.""" probe_type: int = 0 laser_wavelength: float = 680.0 DoFConstant: float | None = None diameter_choice: int = 6 applyIntArrThresh: int = 1 defaultIntArrThresh: float = 1e-6 reaccptShatrs: int = 1 reaccptD: float = 0.05 reaccptMaxIAT: float = 1e-6 SAmethod: int = 0 iCreateAspectRatio: int = 0 iCreateBad: int = 0 time_interval_sec: int = 1 missing_overload_policy: str = "warn_nominal" intArrThreshMode: str = "fixed" intArrAdaptiveWindowSec: int = 1 intArrBins: int = 35 intArrMinCount: int = 200 intArrMaxSeconds: float = 1.0 intArrFallback: str = "fixed" intArrProbAlphaStart: float = 0.01 intArrProbAlphaExtend: float = 0.05 intArrProbRollingWindowSec: int = 5 intArrProbMinLambda: float = 10.0 # Multifeature Shattering fields intArrMFScoreStart: float = 0.75 intArrMFScoreExtend: float = 0.55 intArrMFIatWeight: float = 0.50 intArrMFDensityWeight: float = 0.15 intArrMFSizeWeight: float = 0.20 intArrMFFragmentWeight: float = 0.10 intArrMFMorphWeight: float = 0.05 intArrMFSmallDiameterMm: float = 0.20 intArrMFParentRatio: float = 2.0 intArrMFDensityEdgeHalfWindow: int = 5 intArrMFDensityMaxSeconds: float = 1e-3 intArrMFAreaRatioGood: float = 0.6 intArrMFWriteComponentDiagnostics: int = 0 bin_edges_str: str | None = None accepted_codes: tuple[str, ...] = tuple(ACCEPTED_CODES) def __post_init__(self): """Validates parameter values and thresholds.""" if isinstance(self.accepted_codes, str): object.__setattr__(self, "accepted_codes", (self.accepted_codes,)) else: object.__setattr__(self, "accepted_codes", tuple(self.accepted_codes)) if not isinstance(self.probe_type, int) or isinstance(self.probe_type, bool) or self.probe_type < 0: raise ValueError(f"probe_type must be a non-negative integer, got {self.probe_type!r}") if not isinstance(self.laser_wavelength, (float, int)) or isinstance(self.laser_wavelength, bool) or self.laser_wavelength <= 0: raise ValueError(f"laser_wavelength must be a positive number, got {self.laser_wavelength!r}") if not (100.0 <= self.laser_wavelength <= 2000.0): raise ValueError(f"laser_wavelength must be in nanometers (100-2000 nm), got {self.laser_wavelength!r} — " f"did you specify it in micrometers or millimeters?") resolve_dof_constant(self.probe_type, self.DoFConstant) if not isinstance(self.time_interval_sec, int) or isinstance(self.time_interval_sec, bool) or self.time_interval_sec <= 0: raise ValueError(f"time_interval_sec must be a positive integer, got {self.time_interval_sec!r}") if self.missing_overload_policy not in ("warn_nominal", "invalidate", "error"): raise ValueError( "missing_overload_policy must be 'warn_nominal', 'invalidate', or 'error', " f"got {self.missing_overload_policy!r}" ) if not isinstance(self.diameter_choice, int) or isinstance(self.diameter_choice, bool) or self.diameter_choice not in DIAMETER_CATEGORIES: raise ValueError(f"Invalid diameter_choice {self.diameter_choice!r}, expected one of {list(DIAMETER_CATEGORIES.keys())}") if not isinstance(self.SAmethod, int) or isinstance(self.SAmethod, bool) or self.SAmethod not in SA_METHODS: raise ValueError(f"Invalid SAmethod {self.SAmethod!r}, expected one of {list(SA_METHODS.keys())}") if not isinstance(self.applyIntArrThresh, int) or isinstance(self.applyIntArrThresh, bool) or self.applyIntArrThresh not in (0, 1): raise ValueError(f"applyIntArrThresh must be 0 or 1, got {self.applyIntArrThresh!r}") if not isinstance(self.reaccptShatrs, int) or isinstance(self.reaccptShatrs, bool) or self.reaccptShatrs not in (0, 1): raise ValueError(f"reaccptShatrs must be 0 or 1, got {self.reaccptShatrs!r}") if not isinstance(self.iCreateAspectRatio, int) or isinstance(self.iCreateAspectRatio, bool) or self.iCreateAspectRatio not in (0, 1): raise ValueError(f"iCreateAspectRatio must be 0 or 1, got {self.iCreateAspectRatio!r}") if not isinstance(self.iCreateBad, int) or isinstance(self.iCreateBad, bool) or self.iCreateBad not in (0, 1): raise ValueError(f"iCreateBad must be 0 or 1, got {self.iCreateBad!r}") if not isinstance(self.defaultIntArrThresh, (float, int)) or isinstance(self.defaultIntArrThresh, bool) or self.defaultIntArrThresh <= 0: raise ValueError(f"defaultIntArrThresh must be positive, got {self.defaultIntArrThresh!r}") if not isinstance(self.reaccptD, (float, int)) or isinstance(self.reaccptD, bool) or self.reaccptD <= 0: raise ValueError(f"reaccptD must be positive, got {self.reaccptD!r}") if not isinstance(self.reaccptMaxIAT, (float, int)) or isinstance(self.reaccptMaxIAT, bool) or self.reaccptMaxIAT <= 0: raise ValueError(f"reaccptMaxIAT must be positive, got {self.reaccptMaxIAT!r}") if not isinstance(self.intArrThreshMode, str) or self.intArrThreshMode not in ("fixed", "adaptive", "probabilistic", "probabilistic_multifeature"): raise ValueError(f"intArrThreshMode must be 'fixed', 'adaptive', 'probabilistic', or 'probabilistic_multifeature', got {self.intArrThreshMode!r}") if not isinstance(self.intArrAdaptiveWindowSec, int) or isinstance(self.intArrAdaptiveWindowSec, bool) or self.intArrAdaptiveWindowSec <= 0: raise ValueError(f"intArrAdaptiveWindowSec must be a positive integer, got {self.intArrAdaptiveWindowSec!r}") if not isinstance(self.intArrBins, int) or isinstance(self.intArrBins, bool) or self.intArrBins <= 0: raise ValueError(f"intArrBins must be a positive integer, got {self.intArrBins!r}") if not isinstance(self.intArrMinCount, int) or isinstance(self.intArrMinCount, bool) or self.intArrMinCount <= 0: raise ValueError(f"intArrMinCount must be a positive integer, got {self.intArrMinCount!r}") if not isinstance(self.intArrMaxSeconds, (float, int)) or isinstance(self.intArrMaxSeconds, bool) or self.intArrMaxSeconds <= 0: raise ValueError(f"intArrMaxSeconds must be positive, got {self.intArrMaxSeconds!r}") if not isinstance(self.intArrFallback, str) or self.intArrFallback not in ("fixed",): raise ValueError(f"intArrFallback must be 'fixed', got {self.intArrFallback!r}") if not (0 < self.intArrProbAlphaStart <= self.intArrProbAlphaExtend < 1): raise ValueError(f"intArrProbAlphaStart and intArrProbAlphaExtend must satisfy 0 < alpha_start <= alpha_extend < 1, got {self.intArrProbAlphaStart!r}, {self.intArrProbAlphaExtend!r}") if not isinstance(self.intArrProbRollingWindowSec, int) or isinstance(self.intArrProbRollingWindowSec, bool) or self.intArrProbRollingWindowSec <= 0: raise ValueError(f"intArrProbRollingWindowSec must be a positive integer, got {self.intArrProbRollingWindowSec!r}") if not isinstance(self.intArrProbMinLambda, (float, int)) or isinstance(self.intArrProbMinLambda, bool) or self.intArrProbMinLambda <= 0: raise ValueError(f"intArrProbMinLambda must be positive, got {self.intArrProbMinLambda!r}") # Multifeature validations # 1. Weights weights = [self.intArrMFIatWeight, self.intArrMFDensityWeight, self.intArrMFSizeWeight, self.intArrMFFragmentWeight, self.intArrMFMorphWeight] for w in weights: if not isinstance(w, (float, int)) or isinstance(w, bool) or not (0.0 <= w <= 1.0): raise ValueError(f"Multifeature weights must be between 0.0 and 1.0, got weight value: {w!r}") if abs(sum(weights) - 1.0) > 1e-5: raise ValueError(f"Multifeature weights must sum to 1.0, sum was {sum(weights)}") # 2. Hysteresis thresholds for val, name in [(self.intArrMFScoreStart, 'intArrMFScoreStart'), (self.intArrMFScoreExtend, 'intArrMFScoreExtend')]: if not isinstance(val, (float, int)) or isinstance(val, bool) or not (0.0 <= val <= 1.0): raise ValueError(f"{name} must be between 0.0 and 1.0, got {val!r}") if self.intArrMFScoreExtend > self.intArrMFScoreStart: raise ValueError( "intArrMFScoreExtend must be less than or equal to " f"intArrMFScoreStart, got {self.intArrMFScoreExtend!r} > {self.intArrMFScoreStart!r}" ) # 3. Strictly positive float/int non-weight parameters pos_floats = [ (self.intArrMFSmallDiameterMm, 'intArrMFSmallDiameterMm'), (self.intArrMFParentRatio, 'intArrMFParentRatio'), (self.intArrMFDensityMaxSeconds, 'intArrMFDensityMaxSeconds'), (self.intArrMFAreaRatioGood, 'intArrMFAreaRatioGood') ] for val, name in pos_floats: if not isinstance(val, (float, int)) or isinstance(val, bool) or val <= 0: raise ValueError(f"{name} must be strictly positive, got {val!r}") if self.intArrMFAreaRatioGood <= AREA_RATIO_MIN: raise ValueError( f"intArrMFAreaRatioGood must be greater than AREA_RATIO_MIN ({AREA_RATIO_MIN}), " f"got {self.intArrMFAreaRatioGood!r}" ) if not isinstance(self.intArrMFDensityEdgeHalfWindow, int) or isinstance(self.intArrMFDensityEdgeHalfWindow, bool) or self.intArrMFDensityEdgeHalfWindow <= 0: raise ValueError(f"intArrMFDensityEdgeHalfWindow must be a positive integer, got {self.intArrMFDensityEdgeHalfWindow!r}") # 4. Binary/0/1 flags if not isinstance(self.intArrMFWriteComponentDiagnostics, int) or isinstance(self.intArrMFWriteComponentDiagnostics, bool) or self.intArrMFWriteComponentDiagnostics not in (0, 1): raise ValueError(f"intArrMFWriteComponentDiagnostics must be 0 or 1, got {self.intArrMFWriteComponentDiagnostics!r}") if not self.accepted_codes or not all(isinstance(c, str) and c.strip() for c in self.accepted_codes): raise ValueError("accepted_codes must be a non-empty tuple of nonblank strings") allowed = set(ACCEPTED_CODES) | {'all', 'a', 't', 'p', 'h', 'u', 's', 'z', 'f', 'D', 'I', 'r', 'S'} if not all(c in allowed for c in self.accepted_codes): raise ValueError(f"accepted_codes contains invalid codes; allowed codes are {allowed}")
[docs] @classmethod def from_parser(cls, config: ConfigParser) -> "SizeDistributionConfig": """Instantiates configuration from a ConfigParser object.""" accepted_codes_str = config.get('particle_size_distribution', 'accepted_codes', fallback=None) if accepted_codes_str is not None and accepted_codes_str.strip(): try: accepted_list = ast.literal_eval(accepted_codes_str) if not isinstance(accepted_list, list): accepted_codes = (str(accepted_list),) else: accepted_codes = tuple(str(c) for c in accepted_list) except Exception: accepted_codes = tuple(c.strip().strip("'\"") for c in accepted_codes_str.strip("[]").split(",") if c.strip()) else: accepted_codes = tuple(ACCEPTED_CODES) return cls( probe_type=config.getint('particle_size_distribution', 'probe_type', fallback=0), laser_wavelength=config.getfloat('wavelength', 'value', fallback=680.0), DoFConstant=config.getfloat('particle_size_distribution', 'DoFConstant', fallback=None), diameter_choice=config.getint('particle_size_distribution', 'diameter_choice', fallback=6), applyIntArrThresh=config.getint('particle_size_distribution', 'applyIntArrThresh', fallback=1), defaultIntArrThresh=config.getfloat('particle_size_distribution', 'defaultIntArrThresh', fallback=1e-6), reaccptShatrs=config.getint('particle_size_distribution', 'reaccptShatrs', fallback=1), reaccptD=config.getfloat('particle_size_distribution', 'reaccptD', fallback=0.05), reaccptMaxIAT=config.getfloat('particle_size_distribution', 'reaccptMaxIAT', fallback=1e-6), SAmethod=config.getint('particle_size_distribution', 'SAmethod', fallback=0), iCreateAspectRatio=config.getint('particle_size_distribution', 'iCreateAspectRatio', fallback=0), iCreateBad=config.getint('particle_size_distribution', 'iCreateBad', fallback=0), time_interval_sec=config.getint('particle_size_distribution', 'time_interval_sec', fallback=1), missing_overload_policy=config.get( 'particle_size_distribution', 'missing_overload_policy', fallback="warn_nominal", ), intArrThreshMode=config.get('particle_size_distribution', 'intArrThreshMode', fallback="fixed"), intArrAdaptiveWindowSec=config.getint('particle_size_distribution', 'intArrAdaptiveWindowSec', fallback=1), intArrBins=config.getint('particle_size_distribution', 'intArrBins', fallback=35), intArrMinCount=config.getint('particle_size_distribution', 'intArrMinCount', fallback=200), intArrMaxSeconds=config.getfloat('particle_size_distribution', 'intArrMaxSeconds', fallback=1.0), intArrFallback=config.get('particle_size_distribution', 'intArrFallback', fallback="fixed"), intArrProbAlphaStart=config.getfloat('particle_size_distribution', 'intArrProbAlphaStart', fallback=0.01), intArrProbAlphaExtend=config.getfloat('particle_size_distribution', 'intArrProbAlphaExtend', fallback=0.05), intArrProbRollingWindowSec=config.getint('particle_size_distribution', 'intArrProbRollingWindowSec', fallback=5), intArrProbMinLambda=config.getfloat('particle_size_distribution', 'intArrProbMinLambda', fallback=10.0), # Multifeature parsing intArrMFScoreStart=config.getfloat('particle_size_distribution', 'intArrMFScoreStart', fallback=0.75), intArrMFScoreExtend=config.getfloat('particle_size_distribution', 'intArrMFScoreExtend', fallback=0.55), intArrMFIatWeight=config.getfloat('particle_size_distribution', 'intArrMFIatWeight', fallback=0.50), intArrMFDensityWeight=config.getfloat('particle_size_distribution', 'intArrMFDensityWeight', fallback=0.15), intArrMFSizeWeight=config.getfloat('particle_size_distribution', 'intArrMFSizeWeight', fallback=0.20), intArrMFFragmentWeight=config.getfloat('particle_size_distribution', 'intArrMFFragmentWeight', fallback=0.10), intArrMFMorphWeight=config.getfloat('particle_size_distribution', 'intArrMFMorphWeight', fallback=0.05), intArrMFSmallDiameterMm=config.getfloat('particle_size_distribution', 'intArrMFSmallDiameterMm', fallback=0.20), intArrMFParentRatio=config.getfloat('particle_size_distribution', 'intArrMFParentRatio', fallback=2.0), intArrMFDensityEdgeHalfWindow=config.getint('particle_size_distribution', 'intArrMFDensityEdgeHalfWindow', fallback=5), intArrMFDensityMaxSeconds=config.getfloat('particle_size_distribution', 'intArrMFDensityMaxSeconds', fallback=1e-3), intArrMFAreaRatioGood=config.getfloat('particle_size_distribution', 'intArrMFAreaRatioGood', fallback=0.6), intArrMFWriteComponentDiagnostics=config.getint('particle_size_distribution', 'intArrMFWriteComponentDiagnostics', fallback=0), bin_edges_str=config.get('particle_size_distribution', 'bin_edges', fallback=None), accepted_codes=accepted_codes, )
[docs] def resolve_bin_edges(self, diode_size: float) -> np.ndarray: """Parses and resolves bin_edges array based on configuration string or diode size fallback.""" num_bins = 256 default_bin_edges = f'np.arange({diode_size}/2, {(num_bins + 0.6) * diode_size}, {diode_size})' expr_str = self.bin_edges_str if self.bin_edges_str is not None else default_bin_edges return _safe_parse_bin_edges(expr_str, diode_size)
@property def resolved_dof_constant(self) -> float: """Return the configured DoF coefficient or the probe-specific fallback.""" return resolve_dof_constant(self.probe_type, self.DoFConstant)
[docs] def attrs_for_dataset(self) -> dict[str, Any]: """Return scalar configuration attributes for datasets.""" attrs = { 'probe_type': self.probe_type, 'laser_wavelength': self.laser_wavelength, 'DoFConstant': self.resolved_dof_constant, 'diameter_choice': self.diameter_choice, 'applyIntArrThresh': self.applyIntArrThresh, 'defaultIntArrThresh': self.defaultIntArrThresh, 'reaccptShatrs': self.reaccptShatrs, 'reaccptD': self.reaccptD, 'reaccptMaxIAT': self.reaccptMaxIAT, 'SAmethod': self.SAmethod, 'iCreateAspectRatio': self.iCreateAspectRatio, 'iCreateBad': self.iCreateBad, 'time_interval_sec': self.time_interval_sec, 'missing_overload_policy': self.missing_overload_policy, 'intArrThreshMode': self.intArrThreshMode, 'intArrAdaptiveWindowSec': self.intArrAdaptiveWindowSec, 'intArrBins': self.intArrBins, 'intArrMinCount': self.intArrMinCount, 'intArrMaxSeconds': self.intArrMaxSeconds, 'intArrFallback': self.intArrFallback, 'intArrProbAlphaStart': self.intArrProbAlphaStart, 'intArrProbAlphaExtend': self.intArrProbAlphaExtend, 'intArrProbRollingWindowSec': self.intArrProbRollingWindowSec, 'intArrProbMinLambda': self.intArrProbMinLambda, # Multifeature attributes 'intArrMFScoreStart': self.intArrMFScoreStart, 'intArrMFScoreExtend': self.intArrMFScoreExtend, 'intArrMFIatWeight': self.intArrMFIatWeight, 'intArrMFDensityWeight': self.intArrMFDensityWeight, 'intArrMFSizeWeight': self.intArrMFSizeWeight, 'intArrMFFragmentWeight': self.intArrMFFragmentWeight, 'intArrMFMorphWeight': self.intArrMFMorphWeight, 'intArrMFSmallDiameterMm': self.intArrMFSmallDiameterMm, 'intArrMFParentRatio': self.intArrMFParentRatio, 'intArrMFDensityEdgeHalfWindow': self.intArrMFDensityEdgeHalfWindow, 'intArrMFDensityMaxSeconds': self.intArrMFDensityMaxSeconds, 'intArrMFAreaRatioGood': self.intArrMFAreaRatioGood, 'intArrMFWriteComponentDiagnostics': self.intArrMFWriteComponentDiagnostics, 'accepted_codes': list(self.accepted_codes), } return attrs
[docs] @dataclass(frozen=True) class MLSizingConfig: """Optional ML size correction (``[ml_sizing]`` section); disabled when ``families`` is empty. Enabling families stores diagnostic ``D_s_<family>`` predictions in Level-1 without changing the selected diameter. Selecting one of them for sizing additionally needs ``diameter_choice`` 8/9/10 in ``[particle_size_distribution]`` and an explicit ``ml_model_probe`` (validated in :class:`ProbeProcessingConfig`). ``population_mode`` (``ml_population_mode``) is ``"split"`` by default: entire-in and center-in edge particles are sized by separate models of the same family, which needs a version-2 bundle. ``"entire_only"`` is the explicit legacy mode (entire-in models only; version-1 bundles). ``entire_family``/``edge_family`` (``ml_entire_family``, ``ml_edge_family``) define the mixed ``D_s_ml`` selection of ``diameter_choice`` 11; both or neither, split mode only, each enabled in ``families``. ``bundle_path`` falls back to the ``COPS_ML_SIZING_BUNDLE`` environment variable. ``fallback`` is the per-particle policy for active sizing (only ``"D_s"``). ``min_n_s`` is an optional explicit support cutoff in pixels for *active* sizing: particles with stored ``N_s`` below it use the fallback (0 disables; raw predictions are always kept). ``n_threads`` bounds BLAS/OpenMP/forest threads and ``batch_size`` the particles per prediction batch; neither changes results. """ families: tuple[str, ...] = () bundle_path: str | None = None model_probe: str | None = None fallback: str = "D_s" min_n_s: float = 0.0 n_threads: int = 1 batch_size: int = 20000 population_mode: str = ML_DEFAULT_POPULATION_MODE entire_family: str | None = None edge_family: str | None = None def __post_init__(self): object.__setattr__(self, "families", tuple(self.families)) if self.population_mode not in ML_POPULATION_MODES: raise MLConfigurationError( f"ml_population_mode must be one of {ML_POPULATION_MODES}, got {self.population_mode!r}") if (self.entire_family is None) != (self.edge_family is None): raise MLConfigurationError("ml_entire_family and ml_edge_family must be set together") if self.entire_family is not None: if self.population_mode != "split": raise MLConfigurationError( "ml_entire_family/ml_edge_family define the mixed split-population selection " "and require ml_population_mode = split") for key, fam in (("ml_entire_family", self.entire_family), ("ml_edge_family", self.edge_family)): if fam not in self.families: raise MLConfigurationError( f"{key} = {fam!r} must be one of the enabled ml_families {self.families}") bad = [f for f in self.families if f not in ML_FAMILIES] if bad or len(set(self.families)) != len(self.families): raise MLConfigurationError(f"ml_families must be distinct values of {ML_FAMILIES}, got {self.families!r}") if self.fallback not in ML_FALLBACK_POLICIES: raise MLConfigurationError(f"ml_fallback must be one of {ML_FALLBACK_POLICIES}, got {self.fallback!r}") if isinstance(self.min_n_s, bool) or not isinstance(self.min_n_s, (int, float)) \ or not np.isfinite(self.min_n_s) or self.min_n_s < 0: raise MLConfigurationError(f"ml_min_n_s must be a finite number >= 0 pixels, got {self.min_n_s!r}") for name in ("n_threads", "batch_size"): value = getattr(self, name) if not isinstance(value, int) or isinstance(value, bool) or value < 1: raise MLConfigurationError(f"ml_{name} must be a positive integer, got {value!r}") if self.families and not self.bundle_path: raise MLConfigurationError( "ml_families is set but no model bundle is configured: set ml_bundle_path in " "[ml_sizing] or the COPS_ML_SIZING_BUNDLE environment variable") @property def enabled(self) -> bool: return bool(self.families) @property def mixed_families(self) -> dict[str, str] | None: """``{"entire_in": f, "edge": g}`` of the mixed selection, or ``None``.""" if self.entire_family is None: return None return {"entire_in": self.entire_family, "edge": self.edge_family}
[docs] @classmethod def from_parser(cls, config: ConfigParser) -> "MLSizingConfig": """Instantiates configuration from the optional ``[ml_sizing]`` section.""" section = 'ml_sizing' families_str = config.get(section, 'ml_families', fallback='') or '' families = tuple(f.strip().lower() for f in families_str.replace(';', ',').split(',') if f.strip()) bundle_path = config.get(section, 'ml_bundle_path', fallback=None) or None if bundle_path is None and families: # The pre-rename variable would otherwise be ignored and fail as "no bundle". if os.environ.get('COPS_ML_BUNDLE') and not os.environ.get('COPS_ML_SIZING_BUNDLE'): raise MLConfigurationError( "the sizing bundle variable matches COPS_ML_CLASSIFICATION_BUNDLE; rename " "COPS_ML_BUNDLE -> COPS_ML_SIZING_BUNDLE") bundle_path = os.environ.get('COPS_ML_SIZING_BUNDLE') or None model_probe = config.get(section, 'ml_model_probe', fallback=None) or None def _family(key): value = (config.get(section, key, fallback='') or '').strip().lower() return value or None return cls( families=families, bundle_path=os.path.expanduser(bundle_path) if bundle_path else None, model_probe=model_probe.strip() if model_probe else None, fallback=config.get(section, 'ml_fallback', fallback='D_s').strip(), min_n_s=config.getfloat(section, 'ml_min_n_s', fallback=0.0), n_threads=config.getint(section, 'ml_n_threads', fallback=1), batch_size=config.getint(section, 'ml_batch_size', fallback=20000), population_mode=(config.get(section, 'ml_population_mode', fallback='') or ML_DEFAULT_POPULATION_MODE).strip().lower(), entire_family=_family('ml_entire_family'), edge_family=_family('ml_edge_family'), )
[docs] def attrs_for_dataset(self) -> dict[str, Any]: """Attributes describing the ML configuration; empty when disabled (default outputs unchanged).""" if not self.enabled: return {} return { 'ml_sizing_families': ','.join(self.families), 'ml_sizing_bundle_path': self.bundle_path, 'ml_sizing_model_probe': self.model_probe or '', 'ml_sizing_fallback': self.fallback, 'ml_sizing_min_n_s': float(self.min_n_s), 'ml_sizing_population_mode': self.population_mode, **({'ml_sizing_entire_family': self.entire_family, 'ml_sizing_edge_family': self.edge_family} if self.entire_family is not None else {}), }
[docs] @dataclass(frozen=True) class MLClassificationConfig: """Optional ML source-class classification (``[ml_classification]`` section). INI keys carry the same ``ml_`` prefix as ``[ml_sizing]``: ``ml_families``, ``ml_bundle_path``, ``ml_model_probe``, ``ml_n_threads`` and ``ml_batch_size``. The classifier is disabled when ``families`` is empty. Enabling one or more families requires a model bundle, supplied by ``bundle_path`` or the ``COPS_ML_CLASSIFICATION_BUNDLE`` environment variable. ``n_threads`` and ``batch_size`` are runtime controls and therefore are not part of the scientific dataset identity returned by :meth:`attrs_for_dataset`. """ families: tuple[str, ...] = () bundle_path: str | None = None model_probe: str | None = None n_threads: int = 1 batch_size: int = 20000 def __post_init__(self): object.__setattr__(self, "families", tuple(self.families)) bad = [family for family in self.families if family not in ML_FAMILIES] if bad or len(set(self.families)) != len(self.families): raise MLConfigurationError( f"classification families must be distinct values of {ML_FAMILIES}, " f"got {self.families!r}" ) for name in ("n_threads", "batch_size"): value = getattr(self, name) if not isinstance(value, int) or isinstance(value, bool) or value < 1: raise MLConfigurationError( f"classification {name} must be a positive integer, got {value!r}" ) if self.families and not self.bundle_path: raise MLConfigurationError( "classification families are set but no model bundle is configured: set " "ml_bundle_path in [ml_classification] or the " "COPS_ML_CLASSIFICATION_BUNDLE environment variable" ) @property def enabled(self) -> bool: return bool(self.families)
[docs] @classmethod def from_parser(cls, config: ConfigParser) -> "MLClassificationConfig": """Instantiate configuration from the optional ``[ml_classification]`` section.""" section = "ml_classification" # Unprefixed keys from before the ml_ alignment would otherwise be ignored and # silently leave classification disabled. legacy = [key for key in ("families", "bundle_path", "model_probe", "n_threads", "batch_size") if config.has_option(section, key)] if legacy: raise MLConfigurationError( "[ml_classification] keys use the ml_ prefix of [ml_sizing]; rename " + ", ".join(f"{key} -> ml_{key}" for key in legacy)) families_str = config.get(section, "ml_families", fallback="") or "" families = tuple( family.strip().lower() for family in families_str.replace(";", ",").split(",") if family.strip() ) bundle_path = config.get(section, "ml_bundle_path", fallback=None) or None if bundle_path is None and families: bundle_path = os.environ.get("COPS_ML_CLASSIFICATION_BUNDLE") or None model_probe = config.get(section, "ml_model_probe", fallback=None) or None return cls( families=families, bundle_path=os.path.expanduser(bundle_path) if bundle_path else None, model_probe=model_probe.strip() if model_probe else None, n_threads=config.getint(section, "ml_n_threads", fallback=1), batch_size=config.getint(section, "ml_batch_size", fallback=20000), )
[docs] def attrs_for_dataset(self) -> dict[str, Any]: """Return scientific identity attributes, or no attributes when disabled.""" if not self.enabled: return {} return { "ml_classification_families": ",".join(self.families), "ml_classification_bundle_path": self.bundle_path, "ml_classification_model_probe": self.model_probe or "", }
[docs] @dataclass(frozen=True) class ProbeProcessingConfig: """Aggregate configuration container combining image processing, size distributions, and provenance.""" image: ImageProcessingConfig size: SizeDistributionConfig provenance: ConfigProvenance ml: MLSizingConfig = MLSizingConfig() classification: MLClassificationConfig = MLClassificationConfig() def __post_init__(self): """Validate active ML classification before the existing ML sizing checks.""" if self.image.phase_method.startswith("ml_"): family = self.image.phase_method.removeprefix("ml_") if family not in self.classification.families: raise MLConfigurationError( f"phase_method={self.image.phase_method!r} requires classification " f"ml_families to include {family!r} in [ml_classification]" ) if not self.classification.model_probe: raise MLConfigurationError( "active ML phase classification requires an explicit ml_model_probe in " "[ml_classification] (e.g. 2DS, HVPS, CIP or PIP); it must match " "the SPIF probe header" ) if self.size.diameter_choice == ML_MIXED_DIAMETER_CHOICE: if self.ml.population_mode != "split" or self.ml.mixed_families is None: raise MLConfigurationError( f"diameter_choice={ML_MIXED_DIAMETER_CHOICE} selects D_s_ml, which requires " "ml_population_mode = split and both ml_entire_family and ml_edge_family " "(each enabled in ml_families) in [ml_sizing]") if not self.ml.model_probe: raise MLConfigurationError( "active ML sizing requires an explicit ml_model_probe in [ml_sizing] " "(e.g. 2DS, HVPS, CIP or PIP); it must match the SPIF probe header") return family = ML_DIAMETER_FAMILIES.get(self.size.diameter_choice) if family is None: return if family not in self.ml.families: raise MLConfigurationError( f"diameter_choice={self.size.diameter_choice} selects {DIAMETER_CATEGORIES[self.size.diameter_choice][0]}, " f"which requires ml_families to include {family!r} in [ml_sizing]") if not self.ml.model_probe: raise MLConfigurationError( "active ML sizing requires an explicit ml_model_probe in [ml_sizing] " "(e.g. 2DS, HVPS, CIP or PIP); it must match the SPIF probe header")
[docs] @classmethod def from_parser(cls, config: ConfigParser, provenance: ConfigProvenance | None = None) -> "ProbeProcessingConfig": """Instantiates aggregate configuration from a ConfigParser object.""" if provenance is None: provenance = ConfigProvenance(path=None, status="NOMINAL: Loaded from raw ConfigParser instance") return cls( image=ImageProcessingConfig.from_parser(config), size=SizeDistributionConfig.from_parser(config), provenance=provenance, ml=MLSizingConfig.from_parser(config), classification=MLClassificationConfig.from_parser(config), )
[docs] def ensure_probe_config(config: ProbeProcessingConfig | ConfigParser) -> ProbeProcessingConfig: """Transparently converts raw ConfigParser instances to ProbeProcessingConfig for backwards compatibility.""" if isinstance(config, ConfigParser): return ProbeProcessingConfig.from_parser(config) if isinstance(config, ProbeProcessingConfig): return config raise TypeError(f"Expected ProbeProcessingConfig or ConfigParser, got {type(config).__name__}")
[docs] def resolve_probe_config_path( input_path: str, project_name: str | None, probe_name: str, config_path: str | None = None, allow_cwd_fallback: bool = False ) -> str | None: """ Resolves the configuration file path with priority checks and ambiguity/symlink guarding. History: -------- - 2026-07-03: Created by Yongjie Huang to resolve configuration file paths. """ from pathlib import Path if config_path is not None: if os.path.exists(config_path): return config_path raise FileNotFoundError(f"Explicit configuration file '{config_path}' not found.") filename = f"{project_name}.{probe_name}.ini" if project_name else f"{probe_name}.ini" adj_path = os.path.join(os.path.dirname(input_path), filename) cwd_path = os.path.join(os.getcwd(), filename) adj_exists = os.path.exists(adj_path) cwd_exists = os.path.exists(cwd_path) if adj_exists and cwd_exists: if os.path.samefile(adj_path, cwd_path): return adj_path raise ValueError( f"Ambiguous configurations found at different paths:\n" f"Adjacent: '{adj_path}'\n" f"CWD: '{cwd_path}'\n" f"Please specify the configuration path explicitly." ) if adj_exists: return adj_path if cwd_exists: if allow_cwd_fallback: logger.warning( "Configuration file %r not found adjacent to the SPIF file; falling back to CWD: %s", filename, cwd_path, ) return cwd_path return None return None
[docs] def load_probe_config( input_spif_path: str, project_name: str | None, probe_name: str, allow_missing: bool = False, config_path: str | None = None, allow_cwd_fallback: bool = False ) -> ProbeProcessingConfig: """ Locates, loads, and parses probe configuration from an external .ini file. Searches current working directory and input file directory, establishing strict data provenance. History: -------- - 2026-07-03: Refactored by Yongjie Huang to use resolve_probe_config_path. """ probe_config_file = resolve_probe_config_path( input_spif_path, project_name, probe_name, config_path, allow_cwd_fallback=allow_cwd_fallback ) config_missing = (probe_config_file is None) if config_missing: if not allow_missing: filename = f"{project_name}.{probe_name}.ini" if project_name else f"{probe_name}.ini" raise FileNotFoundError( f"Configuration file '{filename}' not found. This is required for production processing.\n" f"Please place the configuration file beside the SPIF file or pass `allow_missing_config=True` " f"to allow fallback to default parameters (for exploratory/testing purposes)." ) logger.warning( "Configuration file for project %r and probe %r was not found; using fallback parameters", project_name, probe_name, ) logger.warning( "Fallback parameters cover particle masks, binning, QC, and sample-area choices" ) else: logger.info("Loaded configuration from %s", probe_config_file) parser = ConfigParser() if not config_missing: parser.read(probe_config_file) if config_missing: provenance = ConfigProvenance( path=None, status='DEGRADED: Using unconfigured fallback default parameters (masks, QC, probe_type=0, sample-area, etc.)' ) else: provenance = ConfigProvenance( path=probe_config_file, status='NOMINAL: Configured via external .ini file' ) config_obj = ProbeProcessingConfig.from_parser(parser, provenance=provenance) # Automatically resolve probe_type if it is 0 (unconfigured) if config_obj.size.probe_type == 0 and probe_name: from cops.constants import PROBE_CATEGORIES resolved_type = 0 for key, (code, desc) in PROBE_CATEGORIES.items(): if code.upper() == probe_name.upper(): resolved_type = key break if resolved_type != 0: new_size_config = replace(config_obj.size, probe_type=resolved_type) config_obj = replace(config_obj, size=new_size_config) else: logger.warning( "Probe name %r does not match any known category (%s); probe_type remains 0 and the generic " "non-SPEC depth-of-field coefficient will be used", probe_name, ", ".join(code for code, _ in PROBE_CATEGORIES.values()), ) return config_obj