Source code for runtraj.transforms

"""
Particle transforms: how much each particle row counts, written to its ``weight`` column.

A column measurement counts each particle by its averaging kernel and its
share of the column's air, and a species lost on the way counts each row
by the fraction that survives to the release. A transform multiplies the
particles' ``weight`` column by that factor; a table without the column
starts from 1. A stage multiplies what it makes from a row by the row's
weight (PYSTILT's footprint stage multiplies ``foot``).

The built-ins are pydantic models whose fields are their keys, listed in
a stage's settings in ``config.yaml`` (here PYSTILT's footprint stage)::

    transforms:
      - kind: averaging_kernel
        levels: [0, 500, 1000]
        values: [1.0, 0.9, 0.7]
      - kind: pressure_weighting

An averaging kernel that differs per release (every satellite sounding has
its own) comes from a table in the project instead::

      - kind: averaging_kernel
        table: kernels

Transforms run in list order. Each returns a new table and leaves its
input unchanged, so you can also apply them to particles you have read::

    particles = apply_transforms(particles, [FirstOrderLifetime(lifetime_hours=24)])

Each built-in transform is a module: :mod:`~runtraj.transforms.averaging_kernel`,
:mod:`~runtraj.transforms.pressure_weighting`,
:mod:`~runtraj.transforms.lifetime`, :mod:`~runtraj.transforms.deposition`, and
:mod:`~runtraj.transforms.oxidation`. The functions they are built on are
public so your own transforms can use them: :func:`particle_pwf` and
:func:`ak_weights`, the column weighting of Wu et al. (2018, *Geosci.
Model Dev.* 11, 4843); :func:`survival`, the fraction of a tracer that
reaches the release for any loss rate; :func:`dry_deposition_survival`,
that fraction for a depositing tracer; and :func:`weigh`, which multiplies
the weight. This module also loads transforms from a config and applies
them.

A transform of your own is any object with
``apply(particles, release=None, directory=None) -> DataFrame``: the
particle table, the release the particles were released from, and the
directory a relative file name in its settings starts from (the
project's). It changes how much a row counts through ``weight``
(:func:`weigh`), and may add columns. A ``kind`` containing a dot is its
import path, and the class must be a pydantic model so its settings can
be written back.

Two optional parts let a stage check a project before it runs: a
``check(releases, directory)`` method that returns what is wrong with the
transform's inputs for those release ids, as ``(check, release id or
None, message)`` tuples, and ``reads_zsfc = True`` for a transform that
reads ``zsfc`` for a release above sea level.
"""

from __future__ import annotations

import importlib
from collections.abc import Sequence
from pathlib import Path
from typing import TYPE_CHECKING, Annotated, Any

import pandas as pd
from pydantic import Field, TypeAdapter

from runtraj.transforms._common import WEIGHT, release_coordinate, weigh
from runtraj.transforms.averaging_kernel import (
    AveragingKernel,
    ak_weights,
    averaging_kernel_table,
)
from runtraj.transforms.deposition import DryDeposition, dry_deposition_survival
from runtraj.transforms.lifetime import FirstOrderLifetime, survival
from runtraj.transforms.oxidation import Oxidation
from runtraj.transforms.pressure_weighting import PressureWeighting, particle_pwf

if TYPE_CHECKING:
    from runtraj.releases import Release

BuiltinTransform = Annotated[
    AveragingKernel
    | PressureWeighting
    | FirstOrderLifetime
    | DryDeposition
    | Oxidation,
    Field(discriminator="kind"),
]
_BUILTIN_ADAPTER: TypeAdapter[Any] = TypeAdapter(BuiltinTransform)


# -- loading and dumping ------------------------------------------------------------


[docs] def transform_kind(transform: Any) -> str: """Return the ``kind`` that declares a transform in a config.""" kind = getattr(transform, "kind", None) if isinstance(kind, str): return kind cls = type(transform) return f"{cls.__module__}.{cls.__qualname__}"
def _import_kind(kind: str) -> type: """Import and return the class named by a ``module.Class`` string.""" module_name, _, attr = kind.rpartition(".") module = importlib.import_module(module_name) try: return getattr(module, attr) except AttributeError as exc: raise ImportError(f"{module_name} has no attribute {attr!r}") from exc
[docs] def load_transform(spec: Any) -> Any: """ Return the transform for one config entry. ``spec`` is either a transform already (any object with ``apply``) or a mapping with a ``kind``. The ``kind`` is a built-in name or the import path of a pydantic model class, which is validated from the remaining keys. Only a pydantic model can be written back to ``config.yaml``. Raises ------ ImportError If ``kind`` names a class that cannot be imported on this machine. """ if hasattr(spec, "apply"): return spec if not isinstance(spec, dict): raise TypeError( f"Transform entries must be mappings with a 'kind' or objects with " f"apply(); got {type(spec).__name__}." ) kind = spec.get("kind") if not isinstance(kind, str): raise ValueError("Transform entries require a string 'kind'.") if "." not in kind: return _BUILTIN_ADAPTER.validate_python(spec) fields = {k: v for k, v in spec.items() if k != "kind"} try: cls = _import_kind(kind) except ImportError as exc: raise ImportError( f"Transform {kind!r} could not be imported ({exc}). Install the " "package that defines it on this machine." ) from exc if not callable(getattr(cls, "apply", None)): raise TypeError(f"{kind} does not define an apply() method.") if not hasattr(cls, "model_validate"): raise TypeError( f"{kind} is not a pydantic model. A transform named in a config " "must be one so its settings can be written back." ) return cls.model_validate(fields)
[docs] def dump_transform(transform: Any) -> dict[str, Any]: """ Return the config mapping for one transform, the inverse of :func:`load_transform`. A mapping is returned as it is: a result read from a file keeps a transform it cannot import that way. """ if isinstance(transform, dict): return dict(transform) if hasattr(transform, "model_dump"): data = dict(transform.model_dump(mode="json", exclude_none=True)) else: raise TypeError( f"{type(transform).__qualname__} cannot be written to config: transforms " "declared in config.yaml must be pydantic models." ) data.pop("kind", None) return {"kind": transform_kind(transform), **data}
[docs] def apply_transforms( particles: pd.DataFrame, transforms: Sequence[Any], release: Release | None = None, directory: str | Path | None = None, ) -> pd.DataFrame: """ Apply *transforms* in order, each with the release and the directory. Returns ``particles`` itself when there are none. """ for transform in transforms: particles = transform.apply(particles, release, directory) return particles
__all__ = [ "WEIGHT", "AveragingKernel", "DryDeposition", "FirstOrderLifetime", "Oxidation", "PressureWeighting", "ak_weights", "apply_transforms", "averaging_kernel_table", "dry_deposition_survival", "dump_transform", "load_transform", "particle_pwf", "release_coordinate", "survival", "transform_kind", "weigh", ]