diff --git a/models/tea/eeg/curves.py b/models/tea/eeg/curves.py index e4c2672..9240d93 100644 --- a/models/tea/eeg/curves.py +++ b/models/tea/eeg/curves.py @@ -119,15 +119,23 @@ def _number(v) -> float | None: return float(v) if v is not None and math.isfinite(v) else None -def _score_curve(baseline: dict, value: float, age: float) -> dict: - curve = pd.DataFrame(baseline["curve"]).astype(float).dropna() - out = dict.fromkeys(("z", "outside", "p5", "median", "p95")) - if not len(curve) or not age > 0: - return out - log_ages, at = np.log(curve["age_months"].to_numpy()), float(np.log(np.array([age]))[0]) +def centiles(baseline_feature: dict, age_months: float) -> dict: + """The stored centiles interpolated at an age, with nulls outside coverage.""" + curve = pd.DataFrame(baseline_feature["curve"]).astype(float).dropna() + names = [name for name in QUANTILES if name in curve or name in ("p5", "median", "p95")] + if curve.empty or not age_months > 0: + return dict.fromkeys(names) + log_ages = np.log(curve["age_months"].to_numpy()) + at = float(np.log(np.array([age_months]))[0]) if not log_ages.min() <= at <= log_ages.max(): - return out - q = {name: float(np.interp(at, log_ages, curve[name].to_numpy())) for name in QUANTILES} + return dict.fromkeys(names) + return {name: float(np.interp(at, log_ages, curve[name].to_numpy())) for name in names} + + +def _score_curve(baseline: dict, value: float, age: float) -> dict: + q = centiles(baseline, age) + if q["median"] is None: + return dict.fromkeys(("z", "outside", "p5", "median", "p95")) side = q["median"] - q["p5"] if value < q["median"] else q["p95"] - q["median"] z = (value - q["median"]) / (side / 1.645) if side > 0 else None outside = -1 if value < q["p5"] else 1 if value > q["p95"] else 0 diff --git a/models/tea/jobs.py b/models/tea/jobs.py index 58408f7..b074552 100644 --- a/models/tea/jobs.py +++ b/models/tea/jobs.py @@ -45,6 +45,13 @@ class Baseline(mlflow.pyfunc.PythonModel): def __init__(self, scenario: str, baseline: dict): self.scenario, self.baseline = scenario, baseline + def curve(self, feature: str, ages) -> list[dict]: + """Centiles by age for a feature, using the same interpolation as scoring.""" + baseline = self.baseline[feature] + if baseline["kind"] == "count_rate": + raise LookupError("no centiles by age for a count-rate feature") + return [{"age_months": age, **curves.centiles(baseline, age)} for age in ages] + def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame: feature = (params or {}).get("feature", "value") rows = model_input.to_dict("records") diff --git a/tests/test_curves.py b/tests/test_curves.py new file mode 100644 index 0000000..5c17a7f --- /dev/null +++ b/tests/test_curves.py @@ -0,0 +1,25 @@ +import pytest + +from models.tea.eeg import curves + + +def test_centile_interpolation_preserves_scoring(): + baseline = { + "kind": "curves", + "curve": { + "age_months": [16, 36], + "p5": [1, 3], + "p25": [2, 4], + "median": [3, 5], + "p75": [5, 7], + "p95": [7, 9], + }, + } + # At the geometric midpoint, the original log-age interpolation gives the means. + assert curves.centiles(baseline, 24) == pytest.approx( + {"p5": 2, "p25": 3, "median": 4, "p75": 6, "p95": 8} + ) + for value, z, outside in ((0, -3.29, -1), (3, -0.8225, 0), (6, 0.8225, 0), (10, 2.4675, 1)): + assert curves.score(baseline, value, 24) == pytest.approx( + {"z": z, "outside": outside, "p5": 2, "median": 4, "p95": 8}, rel=1e-9 + )