920003c5d4
Assign spike candidates and accepted gate midpoints to the inherited 0.5 s state grid, with a 30 s reach, no state before the first labelled window, and transitions between different surrounding labels. Count useful sleep and awake discharges separately. Export awake_rate, awake_minutes and each zone's electrode count as features without adding metrics or baselines. Train zone count baselines from value times minutes over minutes times present electrodes. Keep observed counts and reported zone rates in their existing units while scaling expected counts by the child's electrodes. Carry the optional electrodes argument through curves.score, deviations, Baseline.predict and saved-study scoring as specified by the coordinator. Internal choices: - Use a private NumPy grid helper, preserve labelled-window input order, and look up times by flooring into half-open 0.5 s cells. Keep the existing internal unlabelled sentinel. Apply the 30 s limit before assigning either an inherited label or transition. - Append the three required fields to Spikes. Use integer zone electrode counts, including zero for absent zones. The few-electrode fallback reports available zone members, zero awake minutes and a NaN awake rate. - Divide rates by accumulated minutes before rounding. Round overall sleep and awake rates to three decimals, minutes to four, and retain four decimals for electrode and zone rates. Missing state exposure produces NaN rates. - Preserve rounded event reconstruction and the existing count-law fit. Missing or null training electrode counts default to one; scoring normalizes nonfinite counts to the same default. Nonpositive electrode exposure yields no-exposure when scoring and is excluded when training. Score centiles remain counts divided by minutes. - Use invented intervals, counts and deterministic candidate fixtures; keep the quality gate, candidate extraction and merging rules unchanged. Validation from the worktree root using the shared virtualenv, with local package roots on PYTHONPATH: - ruff check models: passed. - ruff format --check models: passed, 56 files. - ruff format --check: passed, 152 files. - lint-imports: passed, both contracts kept. - pytest test_eeg_spikes, test_curves, test_eeg, test_eeg_reasons, test_eeg_spindles and test_tea_job: 46 passed; run under flock /home/milk/tea-parity/heavy.lock nice -n 10. - git diff --check: passed. Whole-repository ruff check also ran and found the pre-existing E501 at tests/test_dbt_tea_follow_up.py:35, confirmed in HEAD. That file is outside this task's allowed scope and is unchanged.
218 lines
7.8 KiB
Python
218 lines
7.8 KiB
Python
import math
|
|
from dataclasses import dataclass
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
from scipy import stats
|
|
|
|
QUANTILES = {"p5": 0.05, "p25": 0.25, "median": 0.5, "p75": 0.75, "p95": 0.95}
|
|
CURVE_AGES = np.exp(np.linspace(np.log(1.0), np.log(216.0), 120))
|
|
LOG_WIDTH = 0.2
|
|
MIN_EFFECTIVE = 30
|
|
COUNT_AGES = (16.0, 37.0)
|
|
Z_MAX = 8.0
|
|
EXPOSURE = "minutes"
|
|
NOT_MEASURES = ("age_months", EXPOSURE, "rhythm_near_sigma")
|
|
SCORE_FIELDS = ("z", "outside", "p5", "median", "p95")
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Scenario:
|
|
metric: str
|
|
parts: tuple[str, ...]
|
|
counts: bool = False
|
|
|
|
|
|
SCENARIOS = {
|
|
"eeg-posterior-rhythm": Scenario("posterior_rhythm", ("value",)),
|
|
"eeg-spindles": Scenario("spindles", ("value", "zones")),
|
|
"eeg-spindle-topography": Scenario("spindles", ("electrodes",)),
|
|
"eeg-spikes": Scenario("paroxysmal_spikes", ("value", "electrodes", "zones"), counts=True),
|
|
"eeg-gradient": Scenario("anteroposterior_gradient", ("value",)),
|
|
}
|
|
PREFIX = {"electrodes": "electrode_", "zones": "zone_"}
|
|
|
|
|
|
def _weighted_quantile(x: np.ndarray, w: np.ndarray, q: float) -> float:
|
|
order = np.argsort(x)
|
|
x, w = x[order], w[order]
|
|
return float(np.interp(q, (np.cumsum(w) - 0.5 * w) / w.sum(), x))
|
|
|
|
|
|
def _curve(values: np.ndarray, ages: np.ndarray) -> dict:
|
|
ok = np.isfinite(values) & np.isfinite(ages) & (ages > 0)
|
|
v, log_age = values[ok], np.log(ages[ok])
|
|
curve = {"age_months": [], "n_effective": [], **{q: [] for q in QUANTILES}}
|
|
for a in CURVE_AGES:
|
|
w = np.exp(-0.5 * ((log_age - np.log(a)) / LOG_WIDTH) ** 2)
|
|
n_effective = w.sum() ** 2 / (w**2).sum() if w.sum() > 0 else 0.0
|
|
inside = len(log_age) and log_age.min() <= np.log(a) <= log_age.max()
|
|
curve["age_months"].append(round(float(a), 3))
|
|
curve["n_effective"].append(round(float(n_effective), 1))
|
|
for name, q in QUANTILES.items():
|
|
enough = n_effective >= MIN_EFFECTIVE and inside
|
|
curve[name].append(round(_weighted_quantile(v, w, q), 4) if enough else None)
|
|
return {
|
|
"kind": "curves",
|
|
"log_width": LOG_WIDTH,
|
|
"min_effective": MIN_EFFECTIVE,
|
|
"curve": curve,
|
|
}
|
|
|
|
|
|
def _count_rate(
|
|
values: np.ndarray, ages: np.ndarray, exposure: np.ndarray, electrodes: np.ndarray
|
|
) -> dict:
|
|
n = np.round(values * exposure)
|
|
exposure = exposure * electrodes
|
|
keep = np.isfinite(n) & np.isfinite(exposure) & (exposure > 0)
|
|
keep &= (ages >= COUNT_AGES[0]) & (ages < COUNT_AGES[1])
|
|
n, x = n[keep], exposure[keep]
|
|
rate = float(n.sum() / x.sum()) if x.sum() > 0 else float("nan")
|
|
mu = rate * x
|
|
excess = float(((n - mu) ** 2 - n).sum())
|
|
k = float((mu**2).sum() / excess) if excess > 0 else None
|
|
return {
|
|
"kind": "count_rate",
|
|
"ages": list(COUNT_AGES),
|
|
"rate": rate,
|
|
"k": k,
|
|
"reference": int(keep.sum()),
|
|
"events": int(n.sum()),
|
|
}
|
|
|
|
|
|
def train(features: pd.DataFrame, scenario: str) -> dict:
|
|
counts = SCENARIOS[scenario].counts
|
|
ages = features["age_months"].to_numpy(float)
|
|
out = {}
|
|
for name in features.columns.drop(list(NOT_MEASURES), errors="ignore"):
|
|
if name.startswith(("zone_electrodes_", "awake_")):
|
|
continue
|
|
values = pd.to_numeric(features[name]).to_numpy(float)
|
|
if counts:
|
|
column = f"zone_electrodes_{name.removeprefix('zone_')}"
|
|
electrodes = (
|
|
pd.to_numeric(features[column]).fillna(1).to_numpy(float)
|
|
if name.startswith("zone_") and column in features
|
|
else np.ones(len(features))
|
|
)
|
|
out[name] = _count_rate(values, ages, features[EXPOSURE].to_numpy(float), electrodes)
|
|
else:
|
|
out[name] = _curve(values, ages)
|
|
return out
|
|
|
|
|
|
def _unscored(reason: str | None = None) -> dict:
|
|
return {**dict.fromkeys(SCORE_FIELDS), "reason": reason}
|
|
|
|
|
|
def _number(v) -> float | None:
|
|
return float(v) if v is not None and math.isfinite(v) else None
|
|
|
|
|
|
def centiles(baseline_feature: dict, age_months: float) -> dict:
|
|
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 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 _unscored("age-out-of-range")
|
|
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
|
|
return {
|
|
"z": _number(z),
|
|
"outside": outside,
|
|
"p5": q["p5"],
|
|
"median": q["median"],
|
|
"p95": q["p95"],
|
|
"reason": None,
|
|
}
|
|
|
|
|
|
def _score_count(
|
|
baseline: dict, value: float, age: float, exposure: float | None, electrodes: float
|
|
) -> dict:
|
|
rate, k = baseline["rate"], baseline["k"]
|
|
lo, hi = baseline["ages"]
|
|
if not lo <= age < hi:
|
|
return _unscored("age-out-of-range")
|
|
if exposure is None or not math.isfinite(rate) or not exposure > 0 or not electrodes > 0:
|
|
return _unscored("no-exposure")
|
|
n, mu = float(np.round(value * exposure)), rate * exposure * electrodes
|
|
law = stats.poisson(mu) if k is None else stats.nbinom(k, k / (k + mu))
|
|
tail, at = law.sf(n - 1), law.pmf(n)
|
|
z = float(np.clip(stats.norm.ppf(1 - (tail - at / 2)), -Z_MAX, Z_MAX))
|
|
p5, median, p95 = (float(law.ppf(p)) / exposure for p in (0.05, 0.5, 0.95))
|
|
return {
|
|
"z": z,
|
|
"outside": 1 if tail < 0.05 else 0,
|
|
"p5": p5,
|
|
"median": median,
|
|
"p95": p95,
|
|
"reason": None,
|
|
}
|
|
|
|
|
|
def score(
|
|
baseline: dict,
|
|
value: float | None,
|
|
age_months: float | None,
|
|
exposure: float | None = None,
|
|
electrodes: float | None = None,
|
|
) -> dict:
|
|
value, age_months = _number(value), _number(age_months)
|
|
if value is None:
|
|
return _unscored()
|
|
if age_months is None:
|
|
return _unscored("no-age")
|
|
if baseline["kind"] == "count_rate":
|
|
electrodes = _number(electrodes)
|
|
return _score_count(
|
|
baseline,
|
|
value,
|
|
age_months,
|
|
_number(exposure),
|
|
electrodes if electrodes is not None else 1.0,
|
|
)
|
|
return _score_curve(baseline, value, age_months)
|
|
|
|
|
|
def deviations(models: dict[str, dict], analysis) -> dict[str, dict]:
|
|
out = {m.code: {} for m in analysis.metrics}
|
|
metrics = {m.code: m for m in analysis.metrics}
|
|
for name, scenario in SCENARIOS.items():
|
|
model, metric = models.get(name), metrics.get(scenario.metric)
|
|
if model is None or metric is None:
|
|
continue
|
|
exposure = analysis.features[name].get(EXPOSURE) if scenario.counts else None
|
|
for part in scenario.parts:
|
|
if part == "value":
|
|
out[metric.code]["value"] = score(
|
|
model["value"], metric.value, analysis.age_months, exposure
|
|
)
|
|
else:
|
|
out[metric.code][part] = {
|
|
key: score(
|
|
model[PREFIX[part] + key],
|
|
v,
|
|
analysis.age_months,
|
|
exposure,
|
|
analysis.features[name].get(f"zone_electrodes_{key}")
|
|
if scenario.counts and part == "zones"
|
|
else None,
|
|
)
|
|
for key, v in getattr(metric, part).items()
|
|
}
|
|
return out
|