Files
models/models/tea/eeg/baselines.py
T

139 lines
5.4 KiB
Python

"""The promoted age baselines: a metric's raw value against its curve at the child's age.
Each baseline is a trained `tea` biomarker module registered as `tea-<scenario>` with the `produccion` alias. Without
one in production a metric keeps its raw value and no deviation, the same as a model never configured.
"""
import math
import sys
from dataclasses import dataclass
import numpy as np
from models.io.lineage import registered_name
from models.io.registry import registry as default_registry
@dataclass(frozen=True)
class Deviation:
z: float | None
outside: int | None
p5: float | None
median: float | None
p95: float | None
def _number(value) -> float | None:
try:
number = float(value)
except (TypeError, ValueError):
return None
return number if math.isfinite(number) else None
def _load(model_uri: str):
"""The library's biomarker module of a registered baseline, leaving `sys.path` as it was.
The model bundles a partial copy of `tea` and MLflow puts it first on `sys.path` while loading. Left there, a Dask
worker spawned afterwards inherits it and can't import `tea.pipeline`. The installed `tea` is imported first so
the copy is never the package.
"""
import tea # noqa: F401
from tea.serving import load_biomarker
path = list(sys.path)
try:
return load_biomarker(model_uri)
finally:
sys.path[:] = path
def _takes_exposure(baseline) -> bool:
import inspect
return "exposure" in inspect.signature(baseline.deviation).parameters
def _feature_baseline(module, feature: str):
baselines = getattr(module, "baselines", None)
return baselines.get(feature) if baselines is not None else module.baseline
def centiles(baseline, age_months: float) -> tuple[float | None, float | None, float | None]:
"""p5, median and p95 of a centile curve at an age, interpolated on log age as the library's z is; none for a
baseline without a curve or an age outside it."""
curve = getattr(baseline, "curva", None)
if curve is None or age_months is None or age_months <= 0:
return None, None, None
rows = curve.dropna(subset=["p5", "mediana", "p95"])
if not len(rows):
return None, None, None
log_ages = np.log(rows["edad_meses"].to_numpy(float))
at = math.log(age_months)
if not log_ages.min() <= at <= log_ages.max():
return None, None, None
return tuple(_number(np.interp(at, log_ages, rows[c].to_numpy(float))) for c in ("p5", "mediana", "p95"))
class Baselines:
"""Resolves each scenario's production version once per instance, and loads it the first time it is used."""
def __init__(self, domain: str = "tea", registry=default_registry, loader=None):
self.domain = domain
self.registry = registry
self._loader = loader
self._resolved: dict[str, object | None] = {}
self._loaded: dict[str, object] = {}
def _resolve(self, scenario: str):
if scenario not in self._resolved:
try:
self._resolved[scenario] = self.registry.resolve(self.domain, scenario)
except LookupError:
self._resolved[scenario] = None
return self._resolved[scenario]
def label(self, scenario: str) -> str | None:
"""`tea-<scenario>/<version>` of the version in production, or none."""
resolved = self._resolve(scenario)
return f"{registered_name(self.domain, scenario)}/{resolved.version}" if resolved else None
def module(self, scenario: str):
"""The trained biomarker module in production, or none."""
resolved = self._resolve(scenario)
if resolved is None:
return None
if scenario not in self._loaded:
if self._loader is not None:
self._loaded[scenario] = self._loader(resolved.model_uri)
else:
self._loaded[scenario] = _load(resolved.model_uri)
return self._loaded[scenario]
def deviation(self, scenario: str, feature: str, value: float | None, age_months: float | None,
exposure: float | None = None) -> Deviation | None:
"""None without a baseline in production; with one, a deviation whose fields are null where the value or
the age is missing or the curve doesn't cover the age. `exposure` reaches a baseline that takes one (a count
against its minutes), whose p5, median and p95 are then the rates expected in those minutes; the others
ignore it."""
module = self.module(scenario)
if module is None:
return None
baseline = _feature_baseline(module, feature)
if baseline is None:
return None
if value is None or age_months is None:
return Deviation(None, None, None, None, None)
args = (np.array([value], float), np.array([age_months], float))
minutes = np.array([np.nan if exposure is None else exposure], float)
if _takes_exposure(baseline):
outside, z = baseline.deviation(*args, exposure=minutes)
else:
outside, z = baseline.deviation(*args)
z_value = _number(z[0])
if hasattr(baseline, "percentiles"):
p5, median, p95 = (_number(v) for v in baseline.percentiles(args[1], minutes)[0])
else:
p5, median, p95 = centiles(baseline, age_months)
outside_value = _number(outside[0])
return Deviation(z_value, int(outside_value) if outside_value is not None else None, p5, median, p95)