"""
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 ------------------------------------------------------------
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
__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",
]