"""
The footprint stage: what a ``stages`` block of ``config.yaml`` names.
A stage is what is made from each simulation's results after the transport
model runs (:class:`runtraj.stages.Stage`). A project lists its stages by name
under ``stages:``, each block giving the stage's import path as ``class``
and then the stage's settings. :class:`FootprintStage` is the one stage
PYSTILT has.
"""
from __future__ import annotations
import datetime as dt
import functools
import logging
import os
import weakref
from collections.abc import Callable, Iterable, Mapping
from pathlib import Path
from typing import TYPE_CHECKING, Any
import pandas as pd
import xarray as xr
from pydantic import TypeAdapter
from runtraj.identity import file_stamp
from runtraj.particles import particles_metadata
from runtraj.releases import Release
from stilt._paths import absolute
from stilt.exceptions import EmptyFootprint
from stilt.footprint.foot import HNF_PLUME_COLUMNS, add_foot
from stilt.footprint.grid import Grid
from .config import (
FileGeometrySpec,
FootprintConfig,
GeometrySpec,
footprint_settings,
)
from .gridding import calc_footprint
from .io import write_empty_footprint, write_footprint
from .targets import Mesh
if TYPE_CHECKING:
from runtraj.config import Variant
from runtraj.output import Output
from runtraj.simulation import Simulation
from upath import UPath
logger = logging.getLogger(__name__)
#: The import path of the footprint stage, the ``class`` of its ``stages:`` block.
FOOTPRINT_STAGE = "stilt.footprint.FootprintStage"
#: One thing :meth:`FootprintStage.check` found: the check, the release it is about (or ``None``), and what is wrong.
_Finding = tuple[str, str | None, str]
_GEOMETRY_SPEC: TypeAdapter[GeometrySpec] = TypeAdapter(GeometrySpec)
[docs]
def footprint_particles(
particles: pd.DataFrame,
config: FootprintConfig,
met_files: Iterable[str | os.PathLike[str]],
*,
z_top: float | None = None,
) -> pd.DataFrame:
"""
Return the particles a footprint under *config* is made from, with the ``foot`` it uses.
The particles are returned as they are when they have ``foot`` and
``pbl_height`` is unset: the transport model's own ``foot``, such as
HYSPLIT's. Otherwise PYSTILT computes ``foot`` with ``footprint_depth``,
``pbl_height`` and ``pbl_height_min`` (:func:`stilt.footprint.add_foot`),
in place of the model's, and returns a copy with it. The particles
passed in are not changed, and the computed ``foot`` is stored
nowhere: each footprint computes it again.
Parameters
----------
particles : pandas.DataFrame
A particle table, such as ``sim.particles``.
config : FootprintConfig
The footprint settings.
met_files : iterable of path-like
The met files the run read, which a particle file records
(:func:`runtraj.particles.particles_metadata`). They are read only
when ``foot`` is computed, and must still be at those paths then.
z_top : float, optional
The top of the run's domain, HYSPLIT's ``z_top``, which
``pbl_height: richardson`` reads.
Returns
-------
pandas.DataFrame
The particles, with ``foot``.
Raises
------
FileNotFoundError
If ``foot`` is computed and the run named no met files, or one of
them is no longer there.
Examples
--------
>>> meta = runtraj.particles.particles_metadata(
... sim.particles_path
... ) # doctest: +SKIP
>>> config = stilt.FootprintConfig(
... grid=grid, pbl_height="richardson"
... ) # doctest: +SKIP
>>> particles = stilt.footprint.footprint_particles(
... sim.particles, config, meta.met_files
... ) # doctest: +SKIP
"""
if not _computes_foot(particles, config):
return particles
files = [Path(f) for f in met_files]
if not files:
raise FileNotFoundError(
"The footprint needs a foot computed by PYSTILT, from the met "
"files the run read, and the run named none."
)
gone = [f for f in files if not f.exists()]
if gone:
raise FileNotFoundError(
f"The footprint needs a foot computed by PYSTILT from the met files "
f"the run read, and {gone[0]} is not there any more"
f"{f' (nor {len(gone) - 1} more)' if len(gone) > 1 else ''}. Put the "
"met files back where the run read them."
)
had_foot = "foot" in particles.columns
out = particles.drop(columns="foot") if had_foot else particles
out = add_foot(
out,
files,
config.footprint_depth,
pbl_height=config.pbl_height,
pbl_height_min=config.pbl_height_min,
z_top=z_top,
)
logger.info(
"foot computed by PYSTILT from %s and the air below it in the met files "
"(stilt.footprint.add_foot)%s",
_mixed_layer(particles, config),
" in place of the model's foot" if had_foot else "",
)
return out
def _mixed_layer(particles: pd.DataFrame, config: FootprintConfig) -> str:
"""Say where the mixed-layer height of a ``foot`` PYSTILT computes comes from."""
pbl_height = config.pbl_height
if pbl_height is None and "mlht" in particles.columns:
return "the model's mlht"
if pbl_height is None or pbl_height == "met":
found = "the met's PBLH"
elif pbl_height == "richardson":
found = "the mixed layer found from the met's profile (HYSPLIT's kmixd 3)"
else:
found = f"a mixed layer of {pbl_height:g} m"
if config.pbl_height_min > 0:
found += f", at least {config.pbl_height_min:g} m,"
return found
def stored_particles(
particles: pd.DataFrame,
config: FootprintConfig,
path: Path | UPath | None,
*,
start: dt.datetime | pd.Timestamp | None = None,
z_top: float | None = None,
) -> pd.DataFrame:
"""
Return particles read from the file at *path* with the ``foot`` a footprint under *config* uses (:func:`footprint_particles`).
The met files are read from the particle file's metadata only when
``foot`` is computed. For that, particles without ``time`` (the run's
own, in memory) get it from *start*, the release time, and lose it
again.
"""
if not _computes_foot(particles, config):
return particles
met_files = [] if path is None else particles_metadata(path).met_files
added_time = "time" not in particles.columns and start is not None
if added_time:
particles = particles.assign(
time=pd.Timestamp(start)
+ pd.to_timedelta(particles["age"].to_numpy(), unit="min")
)
out = footprint_particles(particles, config, met_files, z_top=z_top)
return out.drop(columns="time") if added_time else out
def simulation_particles(sim: Simulation, config: FootprintConfig) -> pd.DataFrame:
"""Return a simulation's particles with the ``foot`` a footprint under *config* uses (:func:`stored_particles`)."""
return stored_particles(
sim.particles,
config,
sim.particles_path,
start=sim.release.time,
z_top=getattr(sim.transport, "z_top", None),
)
def variant_footprint(variant: Variant) -> FootprintConfig:
"""
Return *variant*'s footprint settings, or the defaults when it has no footprint.
The defaults get the depth of the transport model's own ``foot``, as
:meth:`FootprintStage.resolve` gives it (:func:`model_foot_depth`), so a
footprint made from particles of a variant without one corrects the
near field as its run would.
"""
own = variant.stages.get("footprint")
if own is not None:
return own
own = FootprintConfig.model_validate({})
depth = model_foot_depth(own, variant.transport.settings())
return own if depth is None else own.model_copy(update={"footprint_depth": depth})
def _computes_foot(particles: pd.DataFrame, config: FootprintConfig) -> bool:
"""Whether a footprint under *config* is made from a ``foot`` PYSTILT computes: ``pbl_height`` is set, or *particles* have none."""
return config.pbl_height is not None or "foot" not in particles.columns
def model_foot_depth(
config: FootprintConfig, model_settings: Mapping[str, Any]
) -> float | None:
"""
Return the depth the transport model made its ``foot`` with when the footprint uses that ``foot``, else ``None``.
The depth is HYSPLIT's ``veght``. A model that records none, or that is
not asked for ``foot`` (HYSPLIT's ``varsiwant``), or ``pbl_height``
set, gives ``None``: then PYSTILT computes ``foot`` with
``footprint_depth``.
"""
depth = model_settings.get("veght")
columns = model_settings.get("varsiwant")
if config.pbl_height is not None or depth is None:
return None
if columns is not None and "foot" not in columns:
return None
return float(depth)
def store_footprint(
output: Output, variant: Variant, foot: xr.DataArray, realization: int | None = None
) -> Path | UPath:
"""
Write a footprint into *variant*'s footprint folder of an output directory, without calculating it.
For a footprint made elsewhere, as one imported from STILT-R is; a run
calculates its own (:meth:`FootprintStage.run`). The footprint must be
on the variant's grid. The file records the footprint settings, the
folder's hash, and the hash of the particles it was made from, so it
reads alone.
"""
release = foot.stilt.release
name = FootprintStage.name
path = output.make_path(name, variant, str(release.id), realization)
return _write(path, variant.stages[name], variant, release, foot, realization)
def store_empty_footprint(
output: Output, variant: Variant, release: Release, realization: int | None = None
) -> Path | UPath:
"""Record in *variant*'s footprint folder that a release's footprint is empty: no particle reached the grid."""
name = FootprintStage.name
path = output.make_path(name, variant, str(release.id), realization)
return _write(path, variant.stages[name], variant, release, None, realization)
def _write(
path: Path | UPath,
config: FootprintConfig,
variant: Variant,
release: Release,
foot: xr.DataArray | None,
realization: int | None,
stage: str = FootprintStage.name,
) -> Path | UPath:
"""
Write a release's footprint, made with *config*, at *path*; the empty one when *foot* is ``None``.
The file records what every result file does
(:func:`runtraj.identity.file_stamp`, with the hash of *variant*'s folder
of *stage*), and the hash of the particles it was made from.
"""
stamp = file_stamp(variant.stage_hashes[stage], realization)
stamp[b"stilt:particles_hash"] = variant.particles_hash.encode()
if foot is None:
return write_empty_footprint(path, release, config, variant.name, stamp)
return write_footprint(path, foot, config, stamp)
#: The findings of each part of a check for one table of releases, so that
#: variants whose footprints share a grid or a transform share its check.
_CHECKED: dict[int, tuple[weakref.ref, dict[Any, list[_Finding]]]] = {}
def _once(
releases: pd.DataFrame, key: Any, make: Callable[[], list[_Finding]]
) -> list[_Finding]:
"""Return the findings *make* gives for *releases* and *key*, made once while that table is in use."""
known = _CHECKED.get(id(releases))
if known is None or known[0]() is not releases:
_CHECKED.clear() # one table at a time: a project's releases
known = _CHECKED[id(releases)] = (weakref.ref(releases), {})
if key not in known[1]:
known[1][key] = make()
return known[1][key]
def _transform_findings(
check: Callable[..., Any], releases: pd.DataFrame, directory: Path | None
) -> list[_Finding]:
"""Return what a transform's own check finds for the releases, as plain tuples."""
ids = list(dict.fromkeys(str(r) for r in releases["release"]))
return [
(str(name), None if release is None else str(release), str(message))
for name, release, message in check(ids, directory)
]
def _mesh(spec: GeometrySpec, directory: Path | None) -> Mesh:
"""
Return the mesh a geometry spec describes, reading each spec once.
A relative file starts from *directory*. A file is read again when it
has changed. The spec in the settings keeps the path as written, and a
mesh's hash is of its polygons, so moving the project changes no hash.
"""
modified = None
if isinstance(spec, FileGeometrySpec):
if directory is not None:
spec = spec.model_copy(update={"path": str(absolute(spec.path, directory))})
try:
modified = os.stat(spec.path).st_mtime_ns
except OSError:
modified = None # reading it says what is wrong
return _read_mesh(spec.model_dump_json(), modified)
@functools.lru_cache(maxsize=16)
def _read_mesh(spec: str, modified: int | None) -> Mesh:
"""Return the mesh of a geometry spec given as JSON; *modified* is its file's time, so a changed file is read again."""
return Mesh.from_spec(_GEOMETRY_SPEC.validate_json(spec))
def _outside(rows: pd.DataFrame, grid: Grid) -> list[_Finding]:
"""List the releases with a release point outside *grid*, which is bounded in longitude and latitude."""
outside = rows[~grid.contains(rows["longitude"], rows["latitude"])]
box = (
f"{grid.xmin:g} to {grid.xmax:g} longitude, "
f"{grid.ymin:g} to {grid.ymax:g} latitude"
)
return [
(
"grid",
str(row.release),
f"longitude {row.longitude:g} and latitude {row.latitude:g} are "
f"outside the footprint grid ({box})",
)
for row in outside.drop_duplicates("release").itertuples()
]
__all__ = [
"FootprintStage",
"footprint_particles",
"model_foot_depth",
"simulation_particles",
"stored_particles",
"variant_footprint",
"store_empty_footprint",
"store_footprint",
]