Source code for pelagos_py.steps.base_step

# This file is part of pelagos_py.
#
# Copyright 2025-2026 National Oceanography Centre and The Contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This module defines the base class for pipeline steps and configurations."""

from pelagos_py.utils.config_mirror import ConfigMirrorMixin
from pelagos_py.utils import parameter_spec
from pelagos_py.utils.log_levels import STOP
from pelagos_py.utils.processing_utils import interpolate_at
from pelagos_py.utils.qc_handling import (
    QC_COMBINATRIX,
    adjusted_name,
    calculation_flags_for,
    prefer_adjusted,
    raw_name,
)
import numpy as np
import logging
import os
import time

[docs] REGISTERED_STEPS = {}
"""Registry of explicitly registered step classes."""
[docs] def register_step(cls): """Decorator to mark a step class for inclusion in the pipeline.""" step_name = getattr(cls, "step_name", None) if step_name is None: raise ValueError( f"Class {cls.__name__} is missing required 'step_name' attribute." ) REGISTERED_STEPS[step_name] = cls return cls
[docs] class BaseStep(ConfigMirrorMixin): """ Base class for pipeline steps with config-mirroring support. Every concrete subclass (registered via @register_step) inherits this. """ #: Declarative parameter schema. See :mod:`pelagos_py.utils.parameter_spec`. #: ``None`` means "not declared yet" and validation is skipped (e.g. the #: deferred oxygen steps). Any dict — including an empty ``{}`` for a step that #: genuinely takes no parameters — opts in to strict validation. parameter_schema = None #: Parameter keys consumed by framework mixins rather than the schema, and so #: permitted in a step's config even when absent from ``parameter_schema`` #: (e.g. ``qc_handling_settings`` handled by :class:`QCHandlingMixin`). framework_parameters = {"qc_handling_settings"} # Shown as "beta" in the dashboard: works, but the method is still being refined. beta = False def __init__(self, name, parameters=None, diagnostics=False, context=None): # === Core behaviour (same as before) === self.name = name self.parameters = parameters or {} self.diagnostics = diagnostics self.context = context or {} # Resolve the declared parameter schema: fill in defaults for any omitted # optional parameters and raise on missing required ones. This is the single # source of parameter defaults — steps read e.g. ``self.velocity_threshold`` # directly, never ``getattr(self, ..., <inline default>)``. # A step with a declared schema opts in to strict validation (defaults + # required + reject-unknown). A step that has not declared one yet # (``parameter_schema is None``, e.g. the deferred oxygen steps) skips # validation, so its parameters pass through untouched until it is migrated. if self.parameter_schema is not None: resolved = parameter_spec.resolve( self.parameter_schema, self.parameters, label=self.name, allowed_extra=self.framework_parameters, ) for key, value in resolved.items(): self.parameters.setdefault(key, value) # Get child logger initialized in pipeline.py self.logger = logging.getLogger(f"pelagos_py.pipeline.step.{self.name}") # === Initialise config mirror system === self._init_config_mirror() # canonical parameters go in private store self._parameters = { "name": self.name, "parameters": self.parameters, "diagnostics": self.diagnostics, } # mirror parameters & diagnostics as attributes self._reset_parameter_bridge(mirror_keys=["parameters", "diagnostics"]) # expose param keys as attributes (for user convenience) for key, value in self.parameters.items(): setattr(self, key, value) # Stop the diagnostics timer as soon as diagnostics generation begins, so # the reported time/RAM cover the processing only (not a blocking plot). self._wrap_diagnostics_timing() # Continue method resolution order super().__init__() @classmethod
[docs] def describe_parameters(cls): """Return a JSON-serialisable description of this step's parameters. Introspection surface for external tools (e.g. a dashboard) that need to render a parameter form without instantiating the step. See :func:`pelagos_py.utils.parameter_spec.describe`. """ return parameter_spec.describe(cls.parameter_schema or {})
@classmethod
[docs] def output_variables(cls, parameters): """Variables this step writes for the given config ``parameters`` (read by the config validator).""" outputs = list(getattr(cls, "provided_variables", [])) outputs += parameters.get("qc_outputs") or [] schema = cls.parameter_schema or {} output_as = parameters.get( "output_as", (schema.get("output_as") or {}).get("default") ) if output_as: outputs += [output_as] if isinstance(output_as, str) else list(output_as) return outputs
[docs] def resolve(self, var): """``var``'s ``_ADJUSTED`` version if it exists in ``self.data``, else the raw one.""" return prefer_adjusted(var, self.data.variables)
[docs] def adjusted_copy(self, var): """Name of ``var``'s ``_ADJUSTED`` version, created (with its ``_QC``) as a copy of the raw variable if missing.""" name = adjusted_name(var) if name not in self.data: raw = raw_name(var) self.data[name] = self.data[raw].copy(deep=True) if f"{raw}_QC" in self.data: self.data[f"{name}_QC"] = self.data[f"{raw}_QC"].copy(deep=True) return name
[docs] def values_at_rows_of(self, var, rows_of): """``var`` time-interpolated onto the rows where ``rows_of`` has data, as ``(values, flags)``. For a step needing another sensor's values at its own rows; the result is for the calculation only and never written to the data. Samples flagged in the calculation flags (default 3/4/9) are not interpolated from, and each row's flag is the merged flag of the samples it came from (9 where no value). """ var = self.resolve(var) values = self.data[var].values.astype(float) if f"{var}_QC" in self.data: flags = np.nan_to_num(self.data[f"{var}_QC"].values, nan=9).astype(np.int8) else: flags = np.zeros(values.shape, dtype=np.int8) excluded = getattr(self, "calculation_flag_filter", None) if excluded is None: excluded = calculation_flags_for(var) usable = np.where(np.isin(flags, excluded), np.nan, values) time = self.data["TIME"].values.astype("datetime64[ns]") seconds = np.where(np.isnat(time), np.nan, time.astype("int64") / 1e9) rows = np.isfinite(self.data[self.resolve(rows_of)].values) query_time = np.where(rows, seconds, np.nan) result, before, after = interpolate_at(seconds, usable, query_time) found = before >= 0 merged = np.full(values.shape, 9, dtype=np.int8) merged[found] = QC_COMBINATRIX[flags[before[found]], flags[after[found]]] return result, merged
[docs] def mark_intermediate(self, *names): """Record pipeline-made working variables that Data Export leaves out unless asked to keep them.""" known = self.context.get("intermediate_variables", []) self.context["intermediate_variables"] = sorted(set(known) | set(names))
def run(self): """ Run the step and return the updated pipeline context. Subclasses override this with their processing logic; the base implementation only enforces that they do so. :meta private: """ raise NotImplementedError(f"Step '{self.name}' must implement a run() method.") return self.context # {name: (title, level)}; level True = default, False = extra ("all"), None = by name only diagnostic_figures = {} def draw_figure(self, name): # return the figure registered under name, or None to skip it raise NotImplementedError(f"Step '{self.name}' has no figure '{name}'.")
[docs] def selected_figures(self): """Figure names this run draws, resolved from the ``diagnostics`` setting.""" selection = self.diagnostics if not selection or not self.diagnostic_figures: return [] if selection is True: return [ n for n, (_, level) in self.diagnostic_figures.items() if level is True ] if selection == "all": return [ n for n, (_, level) in self.diagnostic_figures.items() if level is not None ] names = [selection] if isinstance(selection, str) else list(selection) unknown = [n for n in names if n not in self.diagnostic_figures] if unknown: self.halt( f"Unknown diagnostics figure(s) {unknown}; choose from " f"{list(self.diagnostic_figures)} (or true / all)." ) return names
def generate_diagnostics(self): """ Optional hook for emitting step diagnostics. Draws the figures from :meth:`selected_figures`; steps without a registry override this. :meta private: """ names = self.selected_figures() if not names: return import matplotlib as mpl import matplotlib.pyplot as plt mpl.use( "tkagg" ) # report capture neutralises this; standalone runs pop a window drawn = 0 for name in names: fig = self.draw_figure(name) if fig is None: continue fig._pelagos_figure = name # names the saved file under report capture drawn += 1 if drawn: plt.show(block=True) def plot_failure(self): # optional: plot what the step had when it failed pass def _wrap_diagnostics_timing(self): """ Wrap the step's diagnostics method so the performance timer stops the moment diagnostics generation begins. Steps call ``self.generate_diagnostics()`` (or ``plot_diagnostics()``) as the final action of :meth:`run`, usually a blocking plot. Wrapping it here means the pipeline-reported time/RAM cover the processing only, without every individual step needing to call :meth:`report_performance` itself. :meta private: """ import functools for attr in ("generate_diagnostics", "plot_diagnostics"): method = getattr(self, attr, None) if not callable(method): continue @functools.wraps(method) def wrapped(*args, _method=method, **kwargs): self.report_performance() return _method(*args, **kwargs) setattr(self, attr, wrapped) def report_performance(self): """ Log the step's processing time and memory use (diagnostics mode only). The pipeline records a start time before :meth:`run` and calls this once afterwards. :meth:`_wrap_diagnostics_timing` also triggers it the moment a step's diagnostics method is entered, so the reported time reflects the processing work only and not how long a blocking plot is left open. The call is idempotent: the first call reports, any later call (including the pipeline's fallback) is a no-op. :meta private: """ start = getattr(self, "_diagnostics_start", None) if start is None or getattr(self, "_diagnostics_reported", False): return self._diagnostics_reported = True self.log(f"Execution time: {time.time() - start:.2f} seconds.") try: import psutil mem_info = psutil.Process(os.getpid()).memory_info() self.log(f"Current memory usage: {mem_info.rss / 1024**2:.2f} MB") except ImportError: pass
[docs] def log(self, message, console=True): """Log an info-level message. ``console=False`` keeps it in the log file only.""" self.logger.info(message, extra={"console": console})
[docs] def log_generating_diagnostics(self): """Log that diagnostics are being produced, distinguishing report-capture runs from ``diagnostics: true``.""" if getattr(self, "_report_capture", False): self.log("Generating diagnostics for report") else: self.log("Generating diagnostics")
[docs] def log_progress(self, iterable=None, *, desc, total=None, unit="it", leave=False): """Wrap a countable sub-loop as a standard pipeline progress bar; drop-in for ``tqdm(iterable, ...)``.""" from pelagos_py.utils.console import progress_bar return progress_bar( iterable, desc=desc, total=total, unit=unit, leave=leave, logger=self.logger, step_name=self.name, )
[docs] def log_warn(self, message, warning_type=UserWarning): """Log a warning-level message.""" self.logger.warning(message)
[docs] def check_data(self): """Check for data in context for transformer steps.""" if "data" not in self.context: self.logger.error("No data found in context. Please load data first.") self.logger.log( STOP, "Pipeline stopped at step '%s'. " "Add a data-loading step before it and re-run.", self.name, ) raise SystemExit(1)
[docs] def halt(self, message): """Stop the pipeline cleanly for an unrecoverable misconfiguration. Logs ``message`` (the detail and any fix/install hint) at ERROR level, then a terminal STOP line marking the deliberate halt, and exits. Use this instead of raising for config problems discovered at run time, so the user sees one actionable error rather than a wrapped traceback. """ self.logger.error(message) self.logger.log(STOP, "Pipeline stopped at step '%s'.", self.name) exc = SystemExit(1) exc.halt_message = ( message # lets the dashboard show the reason, not "SystemExit: 1" ) raise exc
# ----------- Config Handling -----------
[docs] def update_parameters(self, **kwargs): """ Update parameter values both in attributes and in private store. Example:: self.update_parameters(file_path='newfile.nc', add_meta=False) """ for k, v in kwargs.items(): self.parameters[k] = v setattr(self, k, v) self._parameters["parameters"] = self.parameters
[docs] def generate_config(self): """Return this step's config dict (suitable for saving to YAML).""" self._sync_attributes_to_parameters() return dict(self._parameters)
[docs] def save_config(self, path: str | None = None): """Save this step's config to YAML (for standalone debugging).""" import yaml import os cfg = self.generate_config() if path is None: safe_name = self.name.replace(" ", "_").lower() path = f"{safe_name}_step.yaml" os.makedirs(os.path.dirname(path) or ".", exist_ok=True) with open(path, "w") as f: yaml.safe_dump(cfg, f, sort_keys=False) self.log(f"Step config saved → {path}") return cfg