Compare commits

...

22 Commits

Author SHA1 Message Date
alberto f6a289e774 F7g: signal preparation as biomarcadores-tea (flat reference, symmetric Hann, mains, stable start, clamps)
Port the five F7f signal-preparation differences from biomarcadores-tea
23cafa4 and the read-only counterfactual source. Reference measurement
retains exactly one flat scalp electrode in the original channel order
and average reference, excluding it from QC. Patients default to dropping
bad flat channels. Periodograms remove the mean and use symmetric Hann
density. Preparation uses the requested mains frequency and raw-channel
IIR notch QC. Stable start masks setup windows and limits fixed-line
detection to the useful suffix. Sleep band sums recover the source FFT
scale before applying clamps.

Files changed (relative to the parent worktree):
- models/models/tea/eeg/preprocess.py
- models/models/tea/eeg/signals.py
- models/models/tea/eeg/sleep.py
- models/models/tea/eeg/analysis.py
- models/models/tea/eeg/reference.py
- models/models/tea/eeg/checks.py (coordinator-approved scope/signature)
- models/tests/test_eeg.py

Internal choices left open by the spec:
- Keep the IIR implementation private as preprocess._iir_notch and the
  annotation word lists private as _START_MARKS and _SETUP_MARKS. Stack
  the Q=30 sections and filter finite runs through signals.by_runs with
  the counterfactual minimum length and harmonic enumeration.
- Preserve the counterfactual flat predicate, not nanstd > 0.5, including
  its treatment of nonfinite standard deviations. Derive QC channels
  from raw scalp data excluding the retained flat electrode; filtering
  finite runs supplies the QC gap mask independently of that electrode.
- Calculate the symmetric Hann once per periodograms call. For odd FFT
  lengths double the final bin, since it has no Nyquist bin; for even
  lengths exclude both DC and Nyquist from doubling.
- Retain the exact stable-start finite-window count, median of channel
  standard deviations, second-half reference, suffix tolerance, sorted
  annotation precedence, accent removal and short-record return. Convert
  the selected annotation onset to a Python float.
- Use int(start_s * fs) for the fixed-line suffix. At thirty seconds or
  less remaining, use the full signal, as the tested counterfactual does.
- Add start_s to the existing rejected-minutes scalar dictionary after
  successful measurement. Recompute stable_start(rec) for reporting to
  keep Prepared's existing public shape. Invalid/error paths retain
  their existing result handling.
- Extend the existing test_eeg.py with deterministic seeded synthetic
  arrays, direct NumPy spectra and SciPy IIR comparisons. Exercise odd
  and even spectra, a 60-second setup prefix with the source's 90-percent
  suffix rule, accented and unordered annotations, the thirty-second
  fixed-line boundary, small-power clamps and analysis/reference calls.
  No real-data fixture or source repository was modified.

Validation from the parent worktree root with the requested shared venv:
- ruff check: passed.
- ruff format --check: passed, 152 files already formatted.
- lint-imports --no-cache: passed, 2 contracts kept, 0 broken.
- pytest -q -rs: 116 passed, 7 warnings, covering test_eeg,
  test_eeg_reasons, test_eeg_spikes, test_eeg_spindles, test_edf_header,
  test_tea_notes, test_tea_training_source, test_tea_preview, test_tea_job
  and test_curves. Run with flock /home/milk/tea-parity/heavy.lock
  nice -n 10 and worktree package roots on PYTHONPATH.
- git diff --check in models and the parent: passed.

All specified checks completed. Helsinki reference remeasurement is a
follow-up after the port, not part of this synthetic-array implementation.
2026-12-04 00:50:28 -06:00
alberto d337542ede Ordinal association: an unbounded profile interval counts as separation 2026-12-03 23:27:28 -06:00
alberto aab20683aa F7b: ADOS-2 association as library 0.4.0 with the accepted spike tests
The 33 zone x item spike pairs could not be estimated with about 46
children. The four spike tests accepted before seeing the ADOS-2 replace
them: any zone with the total CSS (repetitive behaviours and social affect
are one pair until the hospital sends CSS by domain), left with items 1 and
18, right with items 4, 5 and 7, and central with item 21 as exploratory.
The predictor is any useful spike in NREM on the group's electrodes.

Item altered from 2, CSS high from 8, at least 5 children with and without
the event, q within each biomarker without the exploratory pair, one CSS
family adjusted by age and module, no z clipping. The settings are module
constants; each fit saves them with its pairs, and a model without them is
refused. score() leaves each fitted child out. Keys are stored hashed.
2026-12-03 22:27:11 -06:00
alberto 920003c5d4 F7e: spikes inherit the nearest window state; zone rates by electrodes present
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.
2026-12-03 22:08:43 -06:00
alberto 8dbd96bca8 Merge branch 'parity/F7a' into parity/main 2026-12-03 21:13:24 -06:00
alberto 89dac1e979 F7a: ADOS-2 scoring from the manual algorithm sheets
Algorithm scores 0, 1, 2, 3 -> 0, 1, 2, 2 and 7, 8, 9 -> 0, with the Toddler
B-1 exception (1 -> 2). The algorithm column comes from completed months and
item A-1 (new catalog field language_level): Toddler 12-20 months few words,
21-30 by A-1; Module 1 by A-1; Module 2 under five or not. The total adds only
the column's items. Classification from the manual's total cuts; Toddler CSS
from Esler 2015 table 3; Modules 1-2 CSS from the manual's comparison tables
(test transcription, in code for now). Module 3 is not scored (no items in
the ADOS-2 list). Labels non_tea / autism_spectrum / autism and little_or_no /
mild_to_moderate / moderate_to_severe concern. A-1 travels to FHIR, follow-up
(ados2_language_level), association input, synthetic hospital, pipelines and
the Gobernanza preview. Ported from the tea library 0.4.0 (patches 0001/0002).
2026-12-03 21:13:24 -06:00
alberto 473a6535cd Merge branch 'parity/F7c' into parity/main 2026-12-03 20:49:41 -06:00
alberto ee9537b1f2 F7c: one spindle metric over all NREM sleep
Spindles are measured once, over every window the state classifier labels
sleep, and each child's detection thresholds come from all NREM sleep
samples. The 75 uV slow-wave rule labelled 89 % of the epochs after N2
onset in Helsinki toddlers (16-36 months) as N3 and was never validated
against technician-scored stages (biomarcadores-tea E13, usar_n3 = false).

spindles_n2 and spindles_n3 become spindles; the four N2/N3 age scenarios
become eeg-spindles and eeg-spindle-topography. The director's flag for a
posterior rhythm near the sigma band is kept as the rhythm_near_sigma
feature. Reasons: no-sleep under one minute of sleep, else no-spindles.
2026-12-03 20:47:28 -06:00
alberto c3acdf6c12 F7d: technician notes matched by word start and whole word
Port the reference vocabulary and priority order into NOTE_WORDS triples.
Match prefixes at word starts and words at both boundaries, normalize ñ to n
after the existing accent normalization, and reject whole-word closing notes.
Keep note_intervals, window_note, mask, EXCLUDED and MASKED unchanged.

Ported 32 logic cases: 22 recognized texts, nine negative texts and the
closing-note interval case. Did not port test_igual_que_la_libreria_eeg,
as explicitly required: it imports and compares against the external eeg
library rather than testing the local logic. The interval case omits the
am.MODULE.version assertion because this implementation has no annotation
library MODULE or corresponding version API.

Internal choices:
- Keep the existing next-with-default expression for first-match selection.
- Use the reference ordered list and END, _pattern and PATTERNS structure,
  compiling one expression per state at module import.
- Use Ruff's multiline formatting for the vocabulary and invented fixtures.
- Adapt interval fixtures to the existing tuple input/output shapes and
  calculate the asserted interval end as onset plus duration.

Validation from the worktree root with the main checkout's virtualenv:
- ruff check models: passed.
- ruff format --check models: passed, 54 files already formatted.
- lint-imports: passed, two contracts kept and none broken.
- pytest models/tests/test_tea_notes.py: 32 passed.
- pytest test_eeg_reasons.py, test_tea_training_source.py, test_tea_job.py
  and test_tea_preview.py under models/tests: 24 passed, seven warnings.
  This regression run used flock heavy.lock and nice -n 10.
- Reference vocabulary and unchanged interval/masking AST checks: passed.
- git diff --check: passed.

Python checks used PYTHONPATH=Core:Persistance:models:WebApi:synthetic to
resolve this worktree instead of the virtualenv's editable main checkout.
2026-12-03 20:41:04 -06:00
alberto cb1c6bc7ee Merge parity/F2b-reason 2026-12-03 13:57:16 -06:00
alberto 3a409afcaa F2b: No evaluable carries the reason ported from the tea library
Study level: Validation.reasons, built from the three gates that decide
validity (triage-not-analyzable, few-clean-minutes, few-electrodes; the
library's run_study reasons plus its usable-electrode gate) and
invalid-file for an unreadable file. Analysis.reasons sits next to
valid, level and clean_fraction.

Window level: the spike detector's 2 s gate now records every reason a
window is rejected (gap, state, mixed-states, muscle, frozen) and the
minutes rejected by each, kept in Spikes.rejected. A window can count
under more than one reason, as in the library. The platform has no
transient rejection, so there is no transient reason.

Metric level: biomarkers.measure returns a Measured result with the
reason per unmeasured metric: few-wake-windows and no-dominant-peak
(posterior rhythm), no-n2 and no-n3 (under one minute of the stage or no
events), no-sleep and few-electrodes (gradient, spikes). A study that is
not valid now returns its five metrics with no value, each carrying
invalid-eeg. Curve scoring returns a reason next to z: no-age,
age-out-of-range and no-exposure, because only scoring knows the
baseline's age coverage.

The reasons and the rejected minutes travel in the features JSON under
metric-reasons and rejected-minutes, outside the scenario keys so the
reference tables and curve training do not see them.
2026-12-03 13:56:48 -06:00
alberto 806f7687d3 Merge parity/F2b-web 2026-12-03 13:52:27 -06:00
alberto 4c24d4efca F2b: TEA record after the 3 Dec review
Translate EEG quality value text and units into Spanish without changing
check codes, stored triage identifiers, thresholds or analysis behavior.

Choices left open by the spec:
- Use Canal muerto, Señal congelada, Señal saturada and Valores infinitos
  for temporal findings.
- Describe channel gaps as Interrupciones del canal with the excess
  percentage followed by más que el resto; bridges as Puente con followed
  by the electrode; amplitude as veces la mediana del cuero cabelludo.
- Describe failed correlation as Sin correlación con los vecinos with
  the two values separated by frente a; contact loss as Contacto
  intermitente with the percentage de bloques sin señal; bursts as
  Contacto intermitente por ráfagas with the percentage de bloques por
  encima de 4 veces el montaje.
- Render auxiliary amplitude in µV with fuera de rango incluso para and
  the existing auxiliary channel type.
- Use fracción and electrodos as the translated units; keep % and dB.
- Display triage as No analizable, Parcial, Sin referencia auricular or
  Completo, retaining not_analyzable, partial, no_ear_reference and complete
  as the stored identifiers.
- Detect the dead-channel finding by its code rather than matching its
  translated text, preserving the existing early exit for dead channels.

Verification from the superproject root with its Ruff configuration:
ruff check passed; ruff format --check passed for all 144 Python files;
git diff --check passed. Python imports did not change. No heavy checks
were run on the lab server, as specified. No API schema changes.
2026-12-03 13:51:40 -06:00
alberto 4056297608 Scoring a TEA domain also relates the association
The Calcular riesgos button runs the domain score job, which only scored the curves: the association scores that become the RiskAssessments were written by the tea_eeg job alone, so a platform driven from the buttons had champions and no risk analyses. The domain routine now ends with the association, score relates it, and the gold build after a score is the TEA selection that includes the association tables.
2026-12-01 18:09:55 -06:00
alberto 24534606f1 C1a: code only, no comments, no Markdown
Remove 212 Python docstrings and 118 comments, and trim prose from three noqa pragmas. The submodule had zero tracked Markdown files.

Preserve the existing executable statements and lint pragmas. Use pass for class bodies that previously consisted of only a docstring.
2026-12-01 16:55:32 -06:00
alberto e42f6a34b2 Merge parity/F1a 2026-12-01 11:51:43 -06:00
alberto fc8153cef3 F1a: user fixes
Keep the flat Dagster source config and validate it with the same Pydantic union as WebApi. Default to SiteTrainingSource when a run omits the source and reuse the site measurements computed at 60 Hz. Keep the existing folder measurement default and cache keys.
2026-12-01 11:32:48 -06:00
alberto ea585b1f06 Merge parity/main into parity/T17-webapp 2026-12-01 06:48:57 -06:00
alberto c649ad9308 T17: models sweep: unused helpers in execution, association and the EEG analysis and checks removed 2026-12-01 06:07:45 -06:00
alberto 83639e708d Merge parity/main into parity/T3-training-source 2026-12-01 01:09:45 -06:00
alberto 8fd4930ca9 T3: TEA age curves train from one training source: the site or a folder
PLAN-feature-parity §2.3 and user decisions 2 and 6.
- jobs._cohort(source, as_of) replaces _reference: kind "site" (default) takes the valid
  EEGs of the children without the diagnosis by the cut-off (persistance.eeg
  .without_diagnosis, rebuild's ruled-out group in tea/parity's design); kind "folder"
  takes a folder under TEA_REFERENCE_ROOT with its EDFs and edades.csv (path, age in
  months), measured at the folder's mains and cached by content as before.
- The legacy TEA_REFERENCE_DIR / TEA_REFERENCE_AGES path, the hk1k name and the
  years-to-months ages table are gone: Helsinki is one such folder.
- Reports and params name the cohort (site or the folder), its digest, and the cut-off
  (site) or mains (folder).
- definitions: Training.source (TrainingSourceConfig) replaces reference.
- tests: test_tea_reference -> test_tea_training_source (folder listing and errors, the
  site cohort's cut-off rules).
2026-12-01 00:53:27 -06:00
alberto 7751c176f0 T2: removed tests/recurrence_reference.py — reference-parity helper, no test uses it 2026-12-01 00:46:19 -06:00
48 changed files with 2071 additions and 1400 deletions
+2 -20
View File
@@ -1,14 +1,10 @@
"""What the CaCu models read from a patient's timeline (gold `cacu_events`): one row per
event, with the patient's cohort index date. Columns: person_id, index_date, date, type,
value_code, value_num, source_table, source_id."""
import numpy as np
import pandas as pd
from core import cacu
RESULTS = ("bethesda", "glandular", "hpv") # what a cytology sample reports
REFERRED = ("colposcopy", "biopsy") # once either happened, screening is over
RESULTS = ("bethesda", "glandular", "hpv")
REFERRED = ("colposcopy", "biopsy")
MISSING = "(none)"
@@ -23,7 +19,6 @@ def days(events: pd.DataFrame) -> pd.Series:
def _worst(codes: pd.Series, cytology: dict) -> pd.Series:
"""Per patient (the index of `codes`), her most severe result as its cytology category."""
rank = {code: i for i, values in enumerate(cytology.values()) for code in values}
names = list(cytology)
worst = codes.map(rank).groupby(level=0).max()
@@ -31,7 +26,6 @@ def _worst(codes: pd.Series, cytology: dict) -> pd.Series:
def _referral_grade(events: pd.DataFrame, persons: pd.Series, history: dict) -> pd.Series:
"""Why she was referred: the worst result in the year before her first colposcopy."""
first = events[events["type"] == "colposcopy"].groupby("person_id")["date"].min()
before = (events["person_id"].map(first) - events["date"]).dt.days
near = events[before.between(0, history["lookback_days"])]
@@ -46,9 +40,6 @@ def _referral_grade(events: pd.DataFrame, persons: pd.Series, history: dict) ->
def index_results(events: pd.DataFrame, cytology: dict, history: dict | None = None):
"""Per patient: the cytology category and HPV result of her index sample (the first
result of each kind within INDEX_SAMPLE_DAYS of the index), and the referral grade
when `history` asks for it."""
near = events[days(events).between(0, cacu.INDEX_SAMPLE_DAYS) & events["type"].isin(RESULTS)]
wide = near.sort_values("date", kind="stable").pivot_table(
index="person_id", columns="type", values="value_code", aggfunc="first"
@@ -64,8 +55,6 @@ def index_results(events: pd.DataFrame, cytology: dict, history: dict | None = N
def _negatives(events: pd.DataFrame, d: pd.Series, grades: list[str]) -> pd.DataFrame:
"""Days at which she was seen free of the outcome: a biopsy below `grades`, or a
negative co-test (the later day of its two results)."""
timed = events.assign(days=d.astype(float))[d >= 0]
biopsies = timed[(timed["type"] == "biopsy") & ~timed["value_code"].isin(grades)]
visits = None
@@ -86,9 +75,6 @@ def _negatives(events: pd.DataFrame, d: pd.Series, grades: list[str]) -> pd.Data
def interval_coded(events: pd.DataFrame, grades: list[str], cytology: dict,
history: dict | None = None) -> pd.DataFrame: # fmt: skip
"""Index features plus the outcome as (c, l, r): prevalent (an outcome biopsy within
the prevalent window), free at the index (a negative before any outcome), or unknown;
and the years between her last negative and her outcome biopsy."""
d = days(events)
outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades) & (d >= 0)
first = d[outcome].groupby(events.loc[outcome, "person_id"]).min()
@@ -110,7 +96,6 @@ def interval_coded(events: pd.DataFrame, grades: list[str], cytology: dict,
def last_screening_cytology(events: pd.DataFrame) -> pd.Series:
"""Per patient never referred: her latest sample with both a cytology and an HPV result."""
referred = set(events.loc[events["type"].isin(REFERRED), "person_id"])
key = ["person_id", "source_table", "source_id"]
samples = events.loc[(events["type"] == "cytology") & ~events["person_id"].isin(referred),
@@ -126,14 +111,12 @@ def last_screening_cytology(events: pd.DataFrame) -> pd.Series:
def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Temporal: the earliest index dates train, the latest test."""
ordered = members.sort_values(["index_date", "person_id"], kind="stable")
cut = int(len(ordered) * train_fraction)
return ordered.iloc[:cut], ordered.iloc[cut:]
def index_sample(events: pd.DataFrame, predictors: list[str]) -> pd.DataFrame:
"""Per patient: each predictor's result on her index sample, MISSING when none."""
members = events.groupby(["person_id", "index_date"], as_index=False).size()
members = members[["person_id", "index_date"]]
sample = events[(events["type"] == "cytology") & (events["date"] == events["index_date"])]
@@ -153,7 +136,6 @@ def index_sample(events: pd.DataFrame, predictors: list[str]) -> pd.DataFrame:
def windowed_outcome(events: pd.DataFrame, grades: list[str], years: float,
follow_up_end: pd.Timestamp) -> pd.DataFrame: # fmt: skip
"""y: an outcome biopsy within `years` of the index; known: y, or followed that long."""
window = years * cacu.DAYS_PER_YEAR
outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades)
outcome &= days(events).between(0, window)
-2
View File
@@ -1,5 +1,3 @@
"""CaCu's training and scoring jobs (models.jobs) over its models and reports."""
from models.cacu import reports
from models.cacu.specs import MODELS
from models.jobs import Jobs
+3 -30
View File
@@ -1,12 +1,3 @@
"""Prevalence-incidence mixture for interval-censored outcomes (PIMixture, Cheung et al.).
A patient either has the outcome at the index visit (prevalence, a logistic model) or may
develop it later (incidence, a proportional-hazards model with an I-spline baseline). Each
patient is coded `c` = 1 (prevalent), 0 (known free at the index), or UNKNOWN, with the
interval (l, r] in years where an incident outcome happened. No library fits this model, so
the likelihood is written here; everything else is scipy.
"""
from dataclasses import dataclass
import numpy as np
@@ -18,13 +9,12 @@ from scipy.stats import norm
from sklearn.base import BaseEstimator
UNKNOWN = -999
TINY = 1e-12 # floor inside every log
FROZEN = 15.0 # a parameter this far out sits on the boundary: fixed, not estimated
TINY = 1e-12
FROZEN = 15.0
HESSIAN_STEP = 1e-4
def ispline_basis(t, degree: int, knots) -> np.ndarray:
"""Integrated B-splines: monotone from 0 at the first knot to 1 at the last."""
t, knots = np.asarray(t, dtype=float), np.asarray(knots, dtype=float)
full = np.r_[np.repeat(knots[0], degree + 1), knots[1:-1], np.repeat(knots[-1], degree + 1)]
inside = np.clip(np.nan_to_num(t, posinf=knots[-1]), knots[0], knots[-1])
@@ -37,8 +27,6 @@ def ispline_basis(t, degree: int, knots) -> np.ndarray:
@dataclass(frozen=True)
class ISpline:
"""Baseline cumulative hazard: I-splines with non-negative (exp) coefficients."""
knots: tuple[float, ...]
degree: int
@@ -55,12 +43,9 @@ class ISpline:
return ispline_basis(t, self.degree, self.knots) @ np.exp(params)
def start(self, c, l, r) -> np.ndarray:
"""Every coefficient equal, so the hazard is the crude event rate."""
at_risk, finite = c != 1, np.isfinite(r)
exposure = np.where(finite, (l + r) / 2, l)[at_risk].sum()
events = (at_risk & finite & (r > 0)).sum()
# exp(-log(...)), not a plain division: on a flat likelihood BFGS follows the start's
# last bit, and this is the start the current models were fitted from.
rate = np.exp(-np.log(max(exposure, 1e-6) / (events + 0.5)))
return np.full(self.n_params, np.log(max(rate * self.knots[-1], 1e-6) / self.n_params))
@@ -88,7 +73,6 @@ def neg_loglik(params, c, l, r, X, Z, baseline: ISpline, w) -> float:
def hessian(f, x, step: float = HESSIAN_STEP) -> np.ndarray:
"""Central-difference Hessian of f at x."""
p = len(x)
out = np.zeros((p, p))
for i in range(p):
@@ -103,7 +87,6 @@ def hessian(f, x, step: float = HESSIAN_STEP) -> np.ndarray:
def _ridge_logistic(c, X, ridge: float = 1e-3) -> np.ndarray:
"""Prevalence coefficients from the patients whose index status is known."""
known = c != UNKNOWN
if not known.any():
return np.zeros(X.shape[1])
@@ -122,12 +105,11 @@ class Fit:
n_z: int
baseline: ISpline
params: np.ndarray
covariance: np.ndarray # NaN where a parameter is frozen
covariance: np.ndarray
neg_loglik: float
converged: bool
def risk(self, X, Z, years, params=None) -> np.ndarray:
"""Cumulative risk at each horizon: prevalent, or incident by then."""
p = self.params if params is None else params
theta, beta, rest = (
p[: self.n_x],
@@ -141,7 +123,6 @@ class Fit:
]) # fmt: skip
def risk_with_variance(self, X, Z, years) -> tuple[np.ndarray, np.ndarray]:
"""Risk and its delta-method variance (central-difference gradient)."""
gradient = np.empty((len(self.params), len(X), len(years)))
for k, value in enumerate(self.params):
step = 1e-5 * max(1.0, abs(value))
@@ -155,7 +136,6 @@ class Fit:
def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit:
"""Maximum likelihood from two starts (BFGS); covariance from the numerical Hessian."""
n_x, n_z = X.shape[1], Z.shape[1]
start = baseline.start(c, l, r)
starts = [np.r_[_ridge_logistic(c, X), np.zeros(n_z), start], np.r_[np.zeros(n_x + n_z), start]]
@@ -174,10 +154,6 @@ def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit:
class Mixture(BaseEstimator):
"""One mixture per stratum. Categorical features get one dummy per level after the first
level seen in the stratum (`levels` gives their order); rows at a level the stratum never
saw are left out. Every feature enters prevalence; `incidence_features` also incidence."""
def __init__(self, horizons_years, incidence_features, strata, levels, knots=3, degree=4,
interval_level=0.95): # fmt: skip
self.horizons_years = horizons_years
@@ -222,7 +198,6 @@ class Mixture(BaseEstimator):
return [(key if isinstance(key, tuple) else (key,), rows) for key, rows in groups]
def fit(self, X: pd.DataFrame, y: pd.DataFrame):
"""X: the features; y: c, l, r. Identical rows are fitted once, weighted."""
rows = pd.concat([X.reset_index(drop=True), y[["c", "l", "r"]].reset_index(drop=True)],
axis=1).assign(w=1.0) # fmt: skip
self.fits_, self.seen_ = {}, {}
@@ -241,8 +216,6 @@ class Mixture(BaseEstimator):
return self
def predict(self, X: pd.DataFrame) -> np.ndarray:
"""Per row and horizon: (risk, low, high) as three blocks of columns; NaN where the
row's stratum or level was never seen."""
h = len(self.horizons_years)
out = np.full((len(X), 3 * h), np.nan)
z = norm.ppf(0.5 + self.interval_level / 2)
+1 -14
View File
@@ -1,14 +1,3 @@
"""The two reports training writes for each model version (the third, the clinical
validation, is a document the clinical team adds). Both are data the governance page draws.
- technical validation: how the version was trained and tested, and its held-out metrics;
- interpretability: what drives its predictions. For the mixture, observed against
predicted risk per combination of its features: the Turnbull estimate (the
nonparametric cumulative risk under interval censoring) with a bootstrap band, the
model's curve with its delta-method band, and expected over observed at each horizon.
For the logistic regression, its coefficients and calibration by risk decile.
"""
import numpy as np
import pandas as pd
from scipy.stats import norm
@@ -18,7 +7,7 @@ from models import survival
from models.cacu.pim import Mixture
from models.cacu.specs import Logistic, Pim
GRID_STEP = 0.1 # years between points of a curve
GRID_STEP = 0.1
BOOTSTRAP = 200
SEED = 20261122
Z = norm.ppf(0.975)
@@ -40,8 +29,6 @@ def technical_validation(spec: Pim | Logistic | survival.Spec, metrics: dict, da
def turnbull(c, l, r, iters: int = 5000, tol: float = 1e-10):
"""Turnbull's EM: support points and cumulative risk at each. A prevalent case's event
is at 0; a patient free at the index has hers in (l, r]; an unknown one in [0, r]."""
finite = r[np.isfinite(r)]
support = np.unique(np.concatenate([[0.0], finite[finite > 0], [np.inf]]))
low, high = np.where(c == 0, l, -np.inf), np.where(c == 1, 0.0, r)
+1 -17
View File
@@ -1,7 +1,3 @@
"""The CaCu models: each is a spec (what it reads and how it is set) over one of two methods,
the prevalence-incidence mixture or a logistic regression. Training and scoring read the
patient timelines of the spec's cohort (see features)."""
from dataclasses import dataclass, field
from typing import Literal
@@ -23,7 +19,6 @@ OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "
def _rows(members: pd.DataFrame, risks: np.ndarray, horizons) -> pd.DataFrame:
"""One row per patient and horizon; patients the model can't score are left out."""
h = len(horizons)
scored = ~np.isnan(risks[:, :h]).any(axis=1)
members, risks = members[scored], risks[scored]
@@ -43,15 +38,13 @@ def _rows(members: pd.DataFrame, risks: np.ndarray, horizons) -> pd.DataFrame:
@dataclass(frozen=True)
class Pim:
"""Cumulative risk of the outcome at the index and by each horizon (PIMixture)."""
name: str
cohort: str
grades: list[str]
cytology: dict[str, list[str]]
strata: tuple[str, ...]
incidence_features: tuple[str, ...]
history: dict | None = None # a feature from before the index (the referral grade)
history: dict | None = None
predict_at: Literal["index", "last_screening_cytology"] = "index"
horizons: tuple[float, ...] = HORIZONS
method: str = field(default="prevalence-incidence mixture", init=False)
@@ -64,8 +57,6 @@ class Pim:
return self.history and {**self.history, "cytology": self.cytology}
def train(self, events: pd.DataFrame, as_of=None) -> tuple[Mixture, dict, dict]:
"""The fitted mixture, its metrics on the held-out latest patients, and the coded
members it learned from (for the reports)."""
events = f.prepared(events)
coded = f.interval_coded(events, self.grades, self.cytology, self._history())
train, test = f.split(coded, TRAIN_FRACTION)
@@ -80,7 +71,6 @@ class Pim:
found = {
"n_train": len(train),
"n_test": len(test),
# outcomes, prevalent or incident, each split learned from or was judged on
"events_train": float(((train["c"] == 1) | np.isfinite(train["r"])).sum()),
"events_test": float(((test["c"] == 1) | np.isfinite(test["r"])).sum()),
"neg_loglik": mixture.neg_loglik_,
@@ -115,8 +105,6 @@ class Pim:
@dataclass(frozen=True)
class Logistic:
"""Probability of the outcome within one year of the index sample."""
name: str
cohort: str
grades: list[str]
@@ -125,8 +113,6 @@ class Logistic:
method: str = field(default="logistic regression", init=False)
def train(self, events: pd.DataFrame, follow_up_end) -> tuple[Pipeline, dict, dict]:
"""Patients whose outcome is unknown (followed less than a year, no outcome) are left
out. Follow-up ends at `follow_up_end`: the date the data are known to."""
events = f.prepared(events)
found = f.index_sample(events, list(self.predictors))
outcome = f.windowed_outcome(events, self.grades, self.years,
@@ -160,8 +146,6 @@ class Logistic:
def survival_covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
"""Each member's most recent observations up to her index (that day included): her age
group, the KPNC category of her latest cytology result and her latest HPV result."""
found = pd.DataFrame(index=members.index)
found["age_group"] = age_group(events, members, (35, 45, 55))
prior = events[events["date"] <= events["index_date"]]
-2
View File
@@ -1,5 +1,3 @@
"""CaMa's training and scoring jobs (models.jobs) over its models and their reports."""
from models import survival
from models.cama.specs import MODELS
from models.jobs import Jobs
+1 -19
View File
@@ -1,10 +1,3 @@
"""CaMa recurrence: the probability of breast cancer recurring by 12, 36 and 60 months, learned
from the site's own patients (site). Per horizon, a stepwise logistic regression and a Bayesian
network (BDeu parents of the outcome) are fitted and validated (cohorts, modeling); a calculator
gives the recurrence-free probability of clinical scenarios with bootstrap intervals and
survival curves (calculator, curves); risk factors are rated by four criteria (factors); reports
gives the tables and figures."""
from dataclasses import dataclass
import joblib
@@ -13,23 +6,17 @@ import pandas as pd
from models.cama.recurrence import calculator, cohorts, factors, modeling, reports
HORIZONS = modeling.HORIZONS # months
HORIZONS = modeling.HORIZONS
@dataclass
class Recurrence:
"""Per horizon: the LR (intercept and coefficients of its terms) and the HBN (CPT over
its parents, keyed by their categories); the recurrence probability is their mean, and an
unseen parent configuration takes the horizon's recurrence rate."""
cohort: str
horizons: tuple[int, ...]
covariates: list[str]
tables: dict[int, dict]
def predict(self, X: pd.DataFrame) -> pd.DataFrame:
"""The probability of recurrence by each horizon (`recurrence_{H}m`) for each row
of `X`, whose covariates are categories as in `cohort()` (missing: UNKNOWN)."""
found = X[self.covariates].astype(object)
found = found.where(found.notna(), cohorts.UNKNOWN).astype(str)
dummies = pd.get_dummies(found).astype(float)
@@ -50,9 +37,6 @@ class Recurrence:
def train_site(rows: pd.DataFrame, bootstrap: bool = True) -> tuple[Recurrence, dict, dict]:
"""The model of the site's own cohort (models.cama.recurrence.site), its metrics and its
reports. Without `bootstrap`, the AUC bootstrap is skipped (its metrics, and the risk
factors' stability criterion, are then missing)."""
from models.cama.recurrence import site
return fit({"site": site.prepare(rows)}, "site", "site",
@@ -61,8 +45,6 @@ def train_site(rows: pd.DataFrame, bootstrap: bool = True) -> tuple[Recurrence,
def fit(found: dict, saved: str, label: str,
n_bootstrap: dict[str, int]) -> tuple[Recurrence, dict, dict]: # fmt: skip
"""The models of each prepared cohort, their validation, calculator and risk factors;
the `saved` cohort's is the model kept."""
sources = list(found)
try:
fits = modeling.fit(found, n_bootstrap)
+5 -20
View File
@@ -1,12 +1,3 @@
"""The recurrence calculator: for clinical scenarios of each cohort, the mean recurrence-free
probability the LR + HBN average gives its patients at each horizon, with a 95 % interval from
refits on resamples of the whole cohort, next to the scenario's observed survival (Kaplan-Meier)
and its classic and fractional Weibull curves.
The models are refitted on the whole cohort (and on each resample) with the terms and parents
the split chose; the HBN's pseudo-count counts every level of the cohort, seen in the
(re)sample or not."""
from dataclasses import dataclass
import numpy as np
@@ -18,9 +9,9 @@ from models import curves
from models.cama.recurrence.modeling import ESS, HORIZONS, SEED, CohortFit, logit
RESAMPLES = 200
MIN_EVENTS = 15 # a scenario is drawn when it has this many recurrences
CAP_MONTHS = 72 # the Weibull curves' extent
GRID_POINTS = 289 # 0 to CAP_MONTHS by quarter months
MIN_EVENTS = 15
CAP_MONTHS = 72
GRID_POINTS = 289
def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
@@ -32,8 +23,6 @@ def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
@dataclass
class Risk:
"""The cohort coded once: dummies for the LR, integer codes for the HBN."""
fitted: CohortFit
def __post_init__(self):
@@ -51,7 +40,6 @@ class Risk:
return key
def _combined(self, rows, horizon) -> np.ndarray | None:
"""Every patient's (LR + HBN) / 2, fitted on `rows`; None when the LR fails."""
t, e = self.time[rows], self.event[rows]
recurred = (e == 1) & (t <= horizon)
known = recurred | (t > horizon)
@@ -75,8 +63,6 @@ class Risk:
return (p_lr + p_hbn) / 2
def mean_risk(self, rows, scenario_masks) -> dict[str, np.ndarray] | None:
"""Per scenario, the mean risk at each horizon over its patients in `rows` (repeats
counted); None when a refit fails."""
out = {name: np.full(len(HORIZONS), np.nan) for name in scenario_masks}
for j, h in enumerate(HORIZONS):
combined = self._combined(rows, h)
@@ -105,18 +91,17 @@ def _curves(months, event, observed):
def calculator(fitted: CohortFit) -> tuple[list[dict], list[dict]]:
"""The figure record of each scenario with enough recurrences, and its table rows."""
source = fitted.cohort.source
scenarios = fitted.cohort.scenarios
risk = Risk(fitted)
found = masks(fitted.cohort.frame, scenarios)
rng = np.random.default_rng(SEED) # resamples drawn in order, refitted in parallel
rng = np.random.default_rng(SEED)
samples = [np.arange(risk.n)] + [rng.integers(0, risk.n, risk.n) for _ in range(RESAMPLES)]
months = np.floor(risk.time).astype(int)
event = risk.event == 1
drawn = {n: m for n, m in found.items() if m.any() and event[m].sum() >= MIN_EVENTS}
jobs = [delayed(_curves)(months[m], event[m], int(months[m].max())) for m in drawn.values()]
jobs += [delayed(risk.mean_risk)(rows, found) for rows in samples] # the long ones first
jobs += [delayed(risk.mean_risk)(rows, found) for rows in samples]
done = Parallel(n_jobs=-1)(jobs)
fitted_curves, (point, *resampled) = done[: len(drawn)], done[len(drawn) :]
replicas = [r for r in resampled if r is not None]
+5 -20
View File
@@ -1,9 +1,3 @@
"""A cohort as one table of categories: the patients with a known recurrence time and status,
their time to recurrence (`tiempo_meses`), whether it happened (`evento`), and their covariates
as text. A missing or out-of-range value is a category of its own (UNKNOWN); nothing is imputed
or dropped for it. Of each pair of nearly redundant covariates (Cramér's V >= V_MAX), the one
with more unknowns is dropped."""
from dataclasses import dataclass
import pandas as pd
@@ -12,9 +6,8 @@ from scipy.stats.contingency import association
UNKNOWN = "Desconocido"
V_MAX = 0.80
DAYS_PER_MONTH = 30.4375
HORIZONS = (12, 36, 60) # months
HORIZONS = (12, 36, 60)
# Bands, closed on the left: [a, b).
AGE = ([0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"])
SIZE = ([0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"])
NODES = ([0, 1, 4, 1e3], ["0", "1-3", "4+"])
@@ -26,7 +19,6 @@ def _number(s: pd.Series) -> pd.Series:
def _text(s: pd.Series) -> pd.Series:
"""As text; missing values are UNKNOWN."""
return s.astype(object).where(s.notna(), UNKNOWN).astype(str)
@@ -40,9 +32,6 @@ def cramers_v(a: pd.Series, b: pd.Series) -> float:
def collinear(frame: pd.DataFrame, candidates: list[str], v_max: float = V_MAX) -> list[str]:
"""The covariates to drop: pairs by decreasing V (ties: by decreasing names); of each pair
with V >= v_max and neither already dropped, the one with the larger share of unknowns
(on a tie, the first of the pair)."""
pairs = sorted(
(
(cramers_v(frame[a], frame[b]), a, b)
@@ -63,16 +52,14 @@ def collinear(frame: pd.DataFrame, candidates: list[str], v_max: float = V_MAX)
@dataclass(frozen=True)
class Cohort:
"""A source's cohort table and what its covariates are."""
source: str
frame: pd.DataFrame # fixed columns, then the kept covariates
frame: pd.DataFrame
covariates: list[str]
treatment: list[str]
eliminated: list[str]
label: str # as the reports name it
scenarios: dict # the clinical scenarios drawn: name -> covariate -> its categories
sampling: dict # how its patients were chosen (the MUESTREO record)
label: str
scenarios: dict
sampling: dict
@property
def intrinsic(self) -> list[str]:
@@ -80,8 +67,6 @@ class Cohort:
def at_horizon(frame: pd.DataFrame, horizon: int) -> pd.DataFrame:
"""The patients whose status at `horizon` months is known (a recurrence by then, or
followed past it), with `y` = recurred by then."""
t, event = frame["tiempo_meses"], frame["evento"] == 1
found = frame[(event & (t <= horizon)) | (t > horizon)].reset_index(drop=True)
found["y"] = ((found["evento"] == 1) & (found["tiempo_meses"] <= horizon)).astype(int)
+1 -10
View File
@@ -1,7 +1,3 @@
"""The risk factors of recurrence by each horizon, and the ones each calculator scenario has
(the criteria in `models.factors`, all four evaluated: the stepwise LRs' bootstrap gives (2),
the horizon's HBN parents give (3))."""
import warnings
import numpy as np
@@ -81,14 +77,11 @@ def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.Data
def risk_factors(fitted: CohortFit, selection: dict | None = None) -> pd.DataFrame:
"""Every horizon's table: by horizon, factors before treatments, by class, by odds ratio
(decreasing); rounded to 4 places. `selection` (per horizon, the share of bootstrap LRs
each covariate entered) defaults to the fit's own bootstrap."""
if selection is None:
covariates = fitted.cohort.covariates
selection = {h: hz.selection(covariates) for h, hz in fitted.horizons.items()}
with warnings.catch_warnings(), np.errstate(over="ignore"):
warnings.simplefilter("ignore") # rank-deficient designs, unbounded odds ratios
warnings.simplefilter("ignore")
found = [_horizon(fitted, h, selection[h]) for h in fitted.horizons]
tab = pd.concat(found, ignore_index=True)
tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int)
@@ -99,8 +92,6 @@ def risk_factors(fitted: CohortFit, selection: dict | None = None) -> pd.DataFra
def scenario_summary(fitted: CohortFit, factors: pd.DataFrame) -> list[dict]:
"""Per scenario and horizon, the classified factors and treatments nearly all of its
patients have (definitorios) or most have (mayoritarios)."""
frame, source = fitted.cohort.frame, fitted.cohort.source
scenarios = fitted.cohort.scenarios
found = rated.classified(factors[factors["cohorte"] == source])
+2 -47
View File
@@ -1,12 +1,3 @@
"""Per horizon, two models of recurrence by then: a logistic regression (LR) on the dummies a
stepwise selection keeps, and a Bayesian network (HBN) whose outcome's parents a greedy BDeu
search picks, predicting by its conditional probability table. Each is validated on a
stratified 70/30 split of the horizon's cohort (AUC) and on bootstrap resamples of it (each
replicate its own 70/30 split); a penalized Cox model's C-index rates the whole follow-up.
Resamples are drawn in order from one seeded generator and fitted in parallel, so every
replicate is the same however many workers run them."""
import warnings
from dataclasses import dataclass, field
@@ -25,27 +16,21 @@ from models.factors import variable_of
SEED = 42
TEST_SIZE = 0.3
ESS = 10 # BDeu's equivalent sample size, also the CPT's pseudo-count
ESS = 10
MAX_PARENTS = 6
ALPHA_PREFILTER, ALPHA_IN, ALPHA_OUT = 0.10, 0.10, 0.15
MAX_STEPS = 200
COX_PENALIZER = 0.05
COX_MIN_COUNT = 10 # a Cox dummy needs this many patients on each side
COX_MIN_COUNT = 10
N_BOOTSTRAP = {"site": 40}
# ---------------------------------------------------------------- logistic regression
def encode(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame:
"""Dummies (each covariate's alphabetically first level is the reference), the
non-constant ones; a term is `{covariate}_{level}`."""
X = pd.get_dummies(frame[covariates], drop_first=True).astype(float)
return X.loc[:, X.nunique() > 1]
def logit(y, X: pd.DataFrame, has_constant: str = "skip"):
"""Maximum-likelihood logistic regression with an intercept, or None when it fails."""
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
@@ -56,8 +41,6 @@ def logit(y, X: pd.DataFrame, has_constant: str = "skip"):
def stepwise(X: pd.DataFrame, y) -> list[str]:
"""Forward (the smallest Wald p < ALPHA_IN enters) then backward (the largest p >
ALPHA_OUT leaves) until nothing changes; the terms in the order they entered."""
included = []
for _ in range(MAX_STEPS):
changed, best, best_p = False, None, ALPHA_IN
@@ -81,8 +64,6 @@ def stepwise(X: pd.DataFrame, y) -> list[str]:
def lr(train: pd.DataFrame, test: pd.DataFrame, covariates: list[str]):
"""The terms selected on `train` (univariate prefilter, then stepwise) and the test
rows' predicted probabilities (the training rate when no term is selected)."""
X = encode(pd.concat([train, test]), covariates)
X_train = X.loc[train.index]
X_train = X_train.loc[:, X_train.nunique() > 1]
@@ -100,9 +81,6 @@ def lr(train: pd.DataFrame, test: pd.DataFrame, covariates: list[str]):
return terms, m.predict(X_test).to_numpy()
# ---------------------------------------------------------------- Bayesian network
def bn_table(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame:
table = frame[covariates].astype(str)
table["outcome"] = frame["y"].astype(int).astype(str)
@@ -110,8 +88,6 @@ def bn_table(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame:
def parents(table: pd.DataFrame, covariates: list[str]) -> list[str]:
"""Greedy: the covariate whose addition most raises the outcome's BDeu score, while
any does (up to MAX_PARENTS); the parents in the order chosen."""
score = BDeu(table, equivalent_sample_size=ESS)
chosen, current = [], score.local_score("outcome", ())
while len(chosen) < MAX_PARENTS:
@@ -128,8 +104,6 @@ def parents(table: pd.DataFrame, covariates: list[str]) -> list[str]:
def cpt(table: pd.DataFrame, chosen: list[str], q: int | None = None) -> dict[tuple, float]:
"""P(recurrence | parents) for each configuration seen, smoothed by ESS / (2 q) per cell;
`q`, the number of configurations, defaults to the levels seen in `table`."""
q = q or int(np.prod([table[p].nunique() for p in chosen]))
a = ESS / (2 * q)
counts = table.groupby(chosen)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size")
@@ -140,8 +114,6 @@ def cpt(table: pd.DataFrame, chosen: list[str], q: int | None = None) -> dict[tu
def hbn(train: pd.DataFrame, test: pd.DataFrame, chosen: list[str]) -> np.ndarray:
"""The test rows' probabilities by the CPT of `train`; unseen configurations (or no
parents) get the training rate."""
rate = (train["outcome"] == "1").mean()
if not chosen:
return np.full(len(test), rate)
@@ -149,13 +121,8 @@ def hbn(train: pd.DataFrame, test: pd.DataFrame, chosen: list[str]) -> np.ndarra
return np.array([table.get(k, rate) for k in map(tuple, test[chosen].to_numpy())])
# ---------------------------------------------------------------- one split, one cohort
@dataclass(frozen=True)
class Split:
"""The two models' selection and AUC on one 70/30 split."""
terms: list[str]
parents: list[str]
auc_lr: float
@@ -174,8 +141,6 @@ def split_fit(frame: pd.DataFrame, covariates: list[str], seed: int = SEED) -> S
def _replicate(frame, covariates, rows, b) -> Split | None:
"""Bootstrap replicate `b`: the split (seed SEED + b) of the resample `rows`; None when
any fit fails (the replicate is then not counted)."""
try:
return split_fit(frame.iloc[rows].reset_index(drop=True), covariates, SEED + b)
except Exception:
@@ -183,8 +148,6 @@ def _replicate(frame, covariates, rows, b) -> Split | None:
def c_index(cohort: Cohort) -> float:
"""Harrell's C of a ridge-penalized Cox model on the whole follow-up, by a 70/30 split
stratified by event; dummies with fewer than COX_MIN_COUNT patients on a side are left out."""
time_event = ["tiempo_meses", "evento"]
X = pd.get_dummies(
cohort.frame[time_event + cohort.covariates], columns=cohort.covariates, drop_first=True
@@ -205,9 +168,6 @@ def c_index(cohort: Cohort) -> float:
@dataclass
class Horizon:
"""A horizon's cohort size, split fit and bootstrap (AUC pairs, and how often each
covariate entered the LR and the HBN)."""
n: int
events: int
split: Split
@@ -218,7 +178,6 @@ class Horizon:
return np.array([(r.auc_lr, r.auc_hbn) for r in self.replicates]).reshape(-1, 2)
def selection(self, covariates: list[str]) -> dict[str, float] | None:
"""Share of the replicates whose final LR has a term of each covariate."""
if not self.replicates:
return None
counts = {}
@@ -236,8 +195,6 @@ class CohortFit:
def fit(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict[str, CohortFit]:
"""Every cohort's split fits, bootstrap replicates and C-index, in one pool of workers.
Each horizon's resamples come from a fresh generator seeded SEED."""
frames = {(s, h): at_horizon(c.frame, h) for s, c in cohorts.items() for h in HORIZONS}
tasks = []
for (s, h), frame in frames.items():
@@ -268,8 +225,6 @@ def fit(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict[str, Co
def tables(fitted: CohortFit) -> dict[int, dict]:
"""What the saved model keeps per horizon: the split's LR terms refitted on the whole
horizon cohort, and the split's HBN parents with their CPT on it."""
found = {}
for h, hz in fitted.horizons.items():
frame = at_horizon(fitted.cohort.frame, h)
-13
View File
@@ -1,8 +1,3 @@
"""What the governance page draws, as JSON: the development tables (AUC, risk factors,
calculator points, scenario summaries) and the scenarios' figures, as v1 published them in
`analisis/recurrencia_desarrollo.json` and `analisis/recurrencia.json`, and the five routine
records (`rutinas/`)."""
import numpy as np
import pandas as pd
@@ -34,7 +29,6 @@ AUC_COLUMNS = [
def table(rows, columns=None) -> dict:
"""Columns and records; NaN and infinities are null."""
frame = pd.DataFrame(rows, columns=columns).replace([np.inf, -np.inf], np.nan).astype(object)
return {
"columnas": [str(c) for c in frame.columns],
@@ -43,8 +37,6 @@ def table(rows, columns=None) -> dict:
def auc_rows(fitted: CohortFit) -> list[dict]:
"""Per horizon and model, the AUC on the internal split and over the bootstrap
replicates (mean, 2.5 and 97.5 percentiles); then the Cox model's C-index."""
source, rows = fitted.cohort.source, []
for h, hz in fitted.horizons.items():
for j, (name, internal) in enumerate((("LR", hz.split.auc_lr), ("HBN", hz.split.auc_hbn))):
@@ -81,8 +73,6 @@ def auc_rows(fitted: CohortFit) -> list[dict]:
def metrics(auc: list[dict]) -> dict[str, float]:
"""v1's metric names: `{cohort}.auc_{LR|HBN}_{H}m` (internal split), with `_bootstrap`
(the replicates' mean), and `{cohort}.c_index_cox`."""
found = {}
for r in auc:
if r["horizonte_meses"] == "completo":
@@ -96,7 +86,6 @@ def metrics(auc: list[dict]) -> dict[str, float]:
def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
"""The five routine records a promotion reads."""
return {
"MUESTREO": {
"cohortes": {
@@ -144,7 +133,6 @@ def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
def development(auc, factors: pd.DataFrame, points: list[dict], summary: list[dict]) -> dict:
"""`recurrencia_desarrollo`: the tables behind the figures."""
return {
"version": VERSION,
"tablas": {
@@ -157,5 +145,4 @@ def development(auc, factors: pd.DataFrame, points: list[dict], summary: list[di
def figures(records: list[dict]) -> dict:
"""`recurrencia`: each scenario's curves and calculator points."""
return {"version": VERSION, "horizons_months": list(HORIZONS), "escenarios": records}
+2 -27
View File
@@ -1,18 +1,3 @@
"""The site's own recurrence cohort (the `site` source of models.cama.recurrence): the CaMa
timelines of `gold.cama_cohort_recurrence`, indexed at each patient's first invasive biopsy
report, as one table in the shape of SCAN-B's (the clinical cohort the old model learned
from), so the same fits, calculator and risk factors run on it.
- Time and event: months from the index to her first recurrence (any site) after it, else to
her death, else to the cut-off (the site records its recurrences: a patient without one is
taken as free of it up to then); `muerte_sin_recaida` when she died without one.
- Covariates, from the index report's results (a week before to RESULT_DAYS after) and the
first course of treatment (TREATMENT_DAYS), as categories (missing: UNKNOWN):
age, size and positive nodes in SCAN-B's bands, grade, ER, PR, HER2, Ki-67 (< 20 % or
more), histologic type, stage group, and the clinical subtype by the St. Gallen surrogate:
Luminal A (HR+, HER2−, Ki-67 < 20 %), Luminal B HER2− (Ki-67 ≥ 20 %), Luminal B HER2+,
Non-luminal HER2+ and Basal-like (triple negative), as SCAN-B names them."""
import numpy as np
import pandas as pd
@@ -21,7 +6,7 @@ from models.cama.recurrence.cohorts import UNKNOWN, Cohort, _band, _text, collin
RESULT_DAYS = 30
TREATMENT_DAYS = 365
KI67_HIGH = 20.0 # %, St. Gallen's cut between Luminal A and Luminal B
KI67_HIGH = 20.0
STAGE_GROUP = {"0": "0", "I": "I", "IA": "I", "IB": "I", "II": "II", "IIA": "II", "IIB": "II",
"III": "III", "IIIA": "III", "IIIB": "III", "IIIC": "III", "IV": "IV"} # fmt: skip
RECEPTOR = {"positive": "Positive", "negative": "Negative"}
@@ -30,7 +15,6 @@ TREATMENTS = {"Quimioterapia": "chemotherapy", "Radioterapia": "radiotherapy",
"Hormonoterapia": "hormone_therapy", "AntiHER2": "anti_her2"} # fmt: skip
FIXED = ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"]
TREATMENT = ["Cirugia", *TREATMENTS]
# The clinical scenarios drawn: covariate -> the categories it takes (AND across covariates).
SCENARIOS = {
"Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
"Subtipo_clinico": ["Luminal A"], "Ganglios_positivos": ["0"],
@@ -48,7 +32,7 @@ SCENARIOS = {
"Cirugia": ["Lumpectomy"]},
"Grado 3": {"Grado_histologico": ["3"]},
} # fmt: skip
MIN_PER_CLASS = 10 # recurred, and free of it, at each horizon: fewer cannot be split and fitted
MIN_PER_CLASS = 10
SAMPLING = {
"criterio": "pacientes con un primer reporte de biopsia invasiva; sin recaída registrada, "
"libre de ella hasta su defunción o la fecha de corte",
@@ -57,7 +41,6 @@ SAMPLING = {
def subtype(er, pr, her2, ki67) -> str:
"""The St. Gallen surrogate of the intrinsic subtype, as SCAN-B names it."""
hormone = "positive" in (er, pr)
if her2 == "positive":
return "Luminal B HER2+" if hormone else "Non-luminal HER2+"
@@ -71,8 +54,6 @@ def subtype(er, pr, her2, ki67) -> str:
def frame(events: pd.DataFrame, as_of) -> pd.DataFrame:
"""One row per member: her time, event and covariates, as `cohorts.prepare` gives a
reference cohort's."""
events = events.assign(date=pd.to_datetime(events["date"]),
index_date=pd.to_datetime(events["index_date"])) # fmt: skip
members = events.groupby("person_id")["index_date"].first()
@@ -122,8 +103,6 @@ def frame(events: pd.DataFrame, as_of) -> pd.DataFrame:
def scarce(rows: pd.DataFrame) -> str | None:
"""Why the cohort is too small to learn from (a horizon with fewer than MIN_PER_CLASS
patients recurred by it, or known free of it), or None."""
for h in cohorts.HORIZONS:
y = cohorts.at_horizon(rows, h)["y"]
fewest = min(int(y.sum()), int((y == 0).sum()))
@@ -134,10 +113,6 @@ def scarce(rows: pd.DataFrame) -> str | None:
def prepare(rows: pd.DataFrame) -> Cohort:
"""The site's cohort as a reference cohort is prepared: the nearly redundant covariates
dropped (cohorts.collinear) from the model, though kept in the table, since the clinical
scenarios name patients by them (the subtype, built from the receptors and Ki-67, is
redundant by construction)."""
covariates = [c for c in rows.columns if c not in FIXED]
dropped = collinear(rows, [c for c in covariates if c not in TREATMENT])
kept = [c for c in covariates if c not in dropped]
+2 -25
View File
@@ -1,16 +1,3 @@
"""The CaMa models.
- Survival: mortality at 6, 12 and 18 months from the first invasive biopsy report, by
interval survival (models.survival) over the age at the index, that report's results
(stage among them) and the first course of treatment. The first course follows SEER's
convention: what the patient received in the TREATMENT_DAYS after the index, taken as
known at it. A patient who dies before her treatment counts as untreated (immortal-time
bias), which the technical report states.
Training and scoring read the timelines (gold `cama_events`) of `gold.cama_cohort_survival`.
- Recurrence: risk of recurrence at 12, 36 and 60 months, trained on the site's patients
(`gold.cama_cohort_recurrence`, models.cama.recurrence.site) with the old model's math
(proved on METABRIC and SCAN-B by models/tests/test_recurrence.py)."""
from dataclasses import dataclass, field
from datetime import date
@@ -18,16 +5,13 @@ import pandas as pd
from models.survival import DAYS_PER_YEAR, OUTPUT, SCENARIO_SEPARATOR, Spec, age_group, band
# The index report's results (timeline types), read from a week before to RESULT_DAYS after.
RESULTS = ("histologic_type", "grade", "er", "pr", "her2")
RESULT_DAYS = 30
TREATMENT_DAYS = 365
# Stage groups (AJCC): 0, I, II, III, IV, as the clinical scenarios name them.
STAGE_GROUP = {"0": "0", "I": "I", "IA": "I", "IB": "I", "II": "II", "IIA": "II", "IIB": "II",
"III": "III", "IIIA": "III", "IIIB": "III", "IIIC": "III", "IV": "IV"} # fmt: skip
SURGERY = ("breast_conserving_surgery", "mastectomy") # the most extensive one counts
SURGERY = ("breast_conserving_surgery", "mastectomy")
# The clinical scenarios the survival report draws (as the SEER-trained original named them).
STAGE_0_II, STAGE_III_IV = ("stage", "in", ("0", "I", "II")), ("stage", "in", ("III", "IV"))
HER2_POS, HER2_NEG = ("her2", "==", "positive"), ("her2", "==", "negative")
TRIPLE_NEG = (("er", "==", "negative"), ("pr", "==", "negative"), HER2_NEG)
@@ -62,8 +46,6 @@ SCENARIOS = {
def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
"""Each member's age group at the index and her index report's results, in bands where
they are numbers (Ki-67 %, tumour size in mm)."""
found = pd.DataFrame(index=members.index)
found["age_group"] = age_group(events, members, (45, 60, 75))
birth = events[events["type"] == "birth"].groupby("person_id")["date"].min()
@@ -89,13 +71,9 @@ def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
@dataclass(frozen=True)
class SiteRecurrence:
"""The recurrence model on the site's own patients (models.cama.recurrence.site): the
cohort's timelines in, its fits, calculator and risk factors out, with its own reports;
each member scored at 12, 36 and 60 months, with the clinical scenarios she falls in."""
name: str
cohort: str = "cama_cohort_recurrence"
reports: bool = True # it writes its own reports (models.jobs)
reports: bool = True
method: str = field(default="stepwise logistic regression + Bayesian network", init=False)
def train(self, events, as_of=None) -> tuple:
@@ -142,7 +120,6 @@ MODELS = {
"radiotherapy",
),
covariates=covariates,
# As the SEER-trained original: stage, histologic type and the first course, and age.
parents=(
"stage",
"histologic_type",
+5 -34
View File
@@ -1,21 +1,13 @@
"""Survival curves of a group (free of death, or of recurrence), from whole months of
follow-up: Kaplan-Meier with its Greenwood band (log-log scale), and a classic and a
fractional (Kilbas-Saigo) Weibull, both fitted by maximum likelihood on the monthly counts of
events and censorings (an event in month m falls between S(m) and S(m+1); a censoring there
survives to m + 1/2). Fits start from several points and run each to the optimizer's
convergence; one that doesn't converge is an error, not a curve."""
import numpy as np
from scipy.optimize import minimize, minimize_scalar
from scipy.special import beta as beta_function
from scipy.special import betainc, gammaln
Z = 1.96
INVALID = 1e12 # the likelihood outside a model's parameter region
INVALID = 1e12
def life_table(months: np.ndarray, event: np.ndarray, length: int = 0):
"""Per month: recurrences, censorings, and patients at risk at its start."""
months, event = np.asarray(months, int), np.asarray(event, bool)
length = max(length, int(months.max()) + 2)
d = np.bincount(months[event], minlength=length)
@@ -25,7 +17,6 @@ def life_table(months: np.ndarray, event: np.ndarray, length: int = 0):
def kaplan_meier(months, event, until: int):
"""S, low, high at the start of months 0..until."""
d, _, n = life_table(months, event, until + 1)
with np.errstate(divide="ignore", invalid="ignore"):
q = np.where(n > 0, 1 - d / np.maximum(n, 1), 1.0)
@@ -55,7 +46,6 @@ def weibull(t, k, lam):
def fit_weibull(d, c) -> tuple[float, float]:
"""(k, lambda) of the classic Weibull, best of a 3 x 3 grid of Nelder-Mead starts."""
best = None
for k0 in (0.7, 1.0, 1.5):
for l0 in (50.0, 200.0, 1000.0):
@@ -71,9 +61,7 @@ def fit_weibull(d, c) -> tuple[float, float]:
return float(k), float(lam)
# ---------------------------------------------------------------- fractional Weibull
STEPS = 800 # the solver's grid: its error falls as 1/STEPS^2 (~1e-7 here)
STEPS = 800
class NotConverged(RuntimeError):
@@ -87,14 +75,6 @@ def _converged(r, what: str):
def kilbas_saigo_survival(t, c: float, rho: float, s: float) -> np.ndarray:
"""S(t) with S(0) = 1 and Caputo derivative D^rho S(t) = -c t^s S(t) (0 < rho <= 1,
s + rho > 0): the Kilbas-Saigo function E_{rho, 1+s/rho, s/rho}(-c t^(rho+s)).
Solved as its Volterra equation, S(t) = 1 - c/G(rho) int_0^t (t-u)^(rho-1) u^s S(u) du,
by product integration in w = t^(rho+s), where S is a power series in z = c w and so
smooth: S is linear in w on each step, and the kernel's integrals against u^s and
u^(s+rho+s) are exact (incomplete beta functions). The steps are even in log(1 + z):
fine where S starts to fall, wide over its slow tail. No series, no extended precision."""
t = np.atleast_1d(np.asarray(t, float))
e = rho + s
top = float(t.max()) if t.size else 0.0
@@ -112,15 +92,13 @@ def kilbas_saigo_survival(t, c: float, rho: float, s: float) -> np.ndarray:
i0 = grid[n] ** (rho + s) * b0 * np.diff(betainc(s + 1, rho, x))
ie = grid[n] ** (rho + s + e) * be * np.diff(betainc(s + e + 1, rho, x))
slope = (ie - w[:n] * i0) / dw[:n]
own, next_ = i0 - slope, slope # y_j's and y_(j+1)'s weights on step j
own, next_ = i0 - slope, slope
known = own[0] + np.dot(own[1:n] + next_[: n - 1], y[1:n])
y[n] = (1 - kappa * known) / (1 + kappa * next_[n - 1])
return np.interp(t**e, w, y)
def fractional(t, k, alpha, beta, lam) -> np.ndarray:
"""The fractional Weibull's survival (Kilbas-Saigo, with the classic Weibull as its
alpha = beta = 1 case); NaN outside its parameter region."""
t = np.atleast_1d(np.asarray(t, float))
s = k + alpha - 2
if k + alpha <= 1 or s + beta <= 0:
@@ -130,19 +108,12 @@ def fractional(t, k, alpha, beta, lam) -> np.ndarray:
def _shape(k: float, alpha: float, beta: float) -> tuple[float, float, float]:
"""(rho, s, scale): the fractional Weibull is S(t) = g(z), z = scale (t/lambda)^(rho+s),
with g the Kilbas-Saigo survival of order rho and power s at c = 1."""
return beta, k + alpha - 2, float(np.exp(gammaln(k + 1) - gammaln(k + alpha - 1)))
def fit_fractional(d, c, k: float, lam: float) -> tuple[float, ...]:
"""(alpha, beta, lambda) of the fractional Weibull with `k` fixed at the classic fit's, by
maximum likelihood profiled over lambda: for each (alpha, beta), g is solved once over
every z the allowed lambdas (1 to 1e7) reach, and lambda is then fitted exactly on it.
(alpha, beta) is the best of a start at the classic fit (alpha = beta = 1, so it is
never worse) and a grid of others, each to Nelder-Mead's convergence."""
floor = max(0.0, 1.0 - k) + 1e-6
top = len(d) + 0.5 # the latest month the likelihood reads (a censoring's half month)
top = len(d) + 0.5
months = np.concatenate([np.arange(0, len(d) + 1, dtype=float), np.arange(len(d)) + 0.5])
lambdas = (0.0, np.log(1e7))
@@ -155,7 +126,7 @@ def fit_fractional(d, c, k: float, lam: float) -> tuple[float, ...]:
return INVALID, np.nan
rho, s, scale = _shape(k, a, b)
e = rho + s
z_top = scale * top**e # lambda = 1 reaches the farthest
z_top = scale * top**e
z = np.expm1(np.linspace(0.0, np.log1p(z_top), STEPS + 1))
g = np.clip(kilbas_saigo_survival(z ** (1 / e), 1.0, rho, s), 0.0, 1.0)
+13 -26
View File
@@ -1,5 +1,3 @@
"""Dagster code location: every heavy step of the platform is a job defined here."""
import hashlib
import importlib
import inspect
@@ -9,8 +7,10 @@ import os
import zipfile
from collections.abc import Callable
from datetime import date
from typing import Any
import dagster as dg
from pydantic import TypeAdapter
from core.domains import Domain
from models import execution, graph
@@ -20,7 +20,7 @@ from models.tea import preview as tea_preview_analysis
from persistance import backup as backups
from persistance import bundle, cluster, config_log, eeg, previews, silver
WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a time (SQLite)
WRITES = {"writes": "platform"}
class ExecutionConfig(dg.Config):
@@ -42,12 +42,11 @@ class ScopeConfig(dg.Config):
class PipelineRun(dg.Config):
pipeline: str
version: int | None = None # default: the latest saved
version: int | None = None
@dg.op
def run_pipeline(context: dg.OpExecutionContext, config: PipelineRun) -> int:
"""Every node of the pipeline graph, inputs first. Returns the config version run."""
version, pipeline = config_log.get(config.pipeline, config.version)
context.log.info(f"{config.pipeline} v{version}: {len(pipeline.nodes)} nodes")
graph.run(config.pipeline, pipeline, log=context.log.info)
@@ -60,39 +59,29 @@ def ingest():
def _jobs(domain: str):
"""The domain's model jobs (`models.<domain>.jobs`: MODELS, train, score)."""
try:
return importlib.import_module(f"models.{domain}.jobs")
except ModuleNotFoundError as e:
raise ValueError(f"{domain} has no models") from e
class ReferenceConfig(dg.Config):
name: str
line_hz: int = 50
def model(self) -> cluster.Reference:
return cluster.Reference(**self.model_dump())
class Training(dg.Config):
domain: str
models: list[str] = [] # default: every model of the domain
as_of: str | None = None # the date the data are taken up to (default: today)
models: list[str] = []
as_of: str | None = None
execution: ExecutionConfig = ExecutionConfig()
reference: ReferenceConfig | None = None
source: dict[str, Any] | None = None
@dg.op
def train_models(context: dg.OpExecutionContext, config: Training) -> dict:
"""A new registered version of each model (MLflow), with its reports."""
jobs = _jobs(config.domain)
as_of = date.fromisoformat(config.as_of) if config.as_of else None
options = {}
if config.reference is not None:
if "reference" not in inspect.signature(jobs.train).parameters:
raise ValueError(f"{config.domain} models take no reference cohort")
options["reference"] = config.reference.model()
if config.source is not None:
if "source" not in inspect.signature(jobs.train).parameters:
raise ValueError(f"{config.domain} models take no training source")
options["source"] = TypeAdapter(cluster.TrainingSource).validate_python(config.source)
found = {}
with execution.running(context, config.execution.model()):
for name in config.models or jobs.JOBS.routine():
@@ -113,17 +102,16 @@ def train():
class Scoring(dg.Config):
domain: str
models: list[str] = [] # default: every model of the domain
models: list[str] = []
@dg.op
def score_models(context: dg.OpExecutionContext, config: Scoring) -> dict:
"""Each model's champion scores its cohort; then gold's risk tables are rebuilt."""
jobs = _jobs(config.domain)
found = {name: jobs.score(name) for name in config.models or jobs.JOBS.routine()}
for name, version in found.items():
context.log.info(f"{name}: " + (f"version {version}" if version else "no champion"))
silver.build([getattr(jobs, "GOLD", f"{config.domain}_risk") + "+"])
silver.build(getattr(jobs, "GOLD_SELECT", [f"{config.domain}_risk+"]))
return found
@@ -139,7 +127,6 @@ class Analysis(dg.Config):
@dg.op
def analyze_studies(context: dg.OpExecutionContext, config: Analysis) -> int:
"""The domain's studies a model reads whole (TEA: each EEG not analysed yet)."""
with execution.running(context, config.execution.model()):
found = _jobs(config.domain).analyze()
context.log.info(f"{config.domain}: {found} analysed")
-6
View File
@@ -15,13 +15,10 @@ from persistance.cluster import (
ClusterVersionError,
Execution,
ExecutionError,
Health,
Options,
Progress,
Resolved,
Tasks,
Worker,
health,
options,
resolve,
)
@@ -30,11 +27,8 @@ __all__ = [
"ClusterVersionError",
"Execution",
"ExecutionError",
"Health",
"Options",
"Progress",
"Resolved",
"health",
"map",
"options",
"resolve",
-29
View File
@@ -1,16 +1,3 @@
"""Risk factors of an outcome, shared by CaMa recurrence and the interval survival models.
Each category of an intrinsic covariate (not a treatment) is rated against its covariate's
most frequent category by up to four criteria: (1) its adjusted odds ratio's 95 % CI excludes
1 and its Benjamini-Hochberg p < ALPHA; (2) its covariate enters the bootstrap LRs at least
FREQ_MIN of the time; (3) its covariate is in the outcome's Markov blanket in the HBN; (4) its
Kaplan-Meier survival at the horizon differs from the reference's (95 % CI) in the odds ratio's
direction. A criterion the model cannot evaluate is left out. "Robusto" needs (1) and three
criteria (all of them when fewer than three are evaluated), "sugerente" two. Treatments get
their odds ratios, adjusted for the intrinsic covariates, but no class: they are associations,
not effects. Each clinical scenario then lists the classified factors nearly all of its
patients have (definitorios) or most have (mayoritarios)."""
import numpy as np
import pandas as pd
import statsmodels.api as sm
@@ -30,19 +17,16 @@ ORDER = {
"no concluyente": 4,
}
UNKNOWN_CLASS = "no aplica (categoria desconocida)"
# Scenario presence: the share of the scenario's patients in the category.
DEFINING, MAJORITY, PRESENT = 0.95, 0.50, 0.10
DESCRIBING = ("definitoria", "mayoritaria")
def variable_of(term: str, covariates: list[str]) -> str:
"""The covariate a dummy belongs to (the longest name it starts with)."""
found = [c for c in covariates if term.startswith(c + "_")]
return max(found, key=len) if found else term
def km_at(months, event, horizon) -> tuple[float, float]:
"""Kaplan-Meier survival at the end of month `horizon`, and its Greenwood SE."""
d, _, n = life_table(months, event)
q = np.where(n > 0, 1 - d / np.maximum(n, 1), 1.0)
v = np.where((n > 0) & (n > d), d / (np.maximum(n, 1) * np.maximum(n - d, 1)), 0.0)
@@ -52,8 +36,6 @@ def km_at(months, event, horizon) -> tuple[float, float]:
def odds_ratios(data: pd.DataFrame, y, variables, reference, name: str) -> pd.DataFrame:
"""Logistic GLM on every category but each covariate's reference (constant and
duplicated dummies dropped): odds ratios (column `name`) with Wald 95 % CI and p."""
X = pd.get_dummies(data[variables]).astype(float)
X = X.drop(columns=[f"{v}_{reference[v]}" for v in variables])
X = X.loc[:, X.nunique() > 1]
@@ -73,9 +55,6 @@ def odds_ratios(data: pd.DataFrame, y, variables, reference, name: str) -> pd.Da
def complete(table: pd.DataFrame, variables, reference: dict, everyone: pd.DataFrame,
months, event, horizon: int, names: tuple[str, str, str]) -> pd.DataFrame: # fmt: skip
"""Each term's covariate, category, BH p and Kaplan-Meier difference to its reference at
`horizon` over `everyone` (`names`: the category's, the reference's and the difference's
survival columns)."""
table = table.reset_index(drop=True)
table["variable"] = [variable_of(x, variables) for x in table["termino"]]
table["categoria"] = [
@@ -101,8 +80,6 @@ def complete(table: pd.DataFrame, variables, reference: dict, everyone: pd.DataF
def classify(tab: pd.DataFrame, or_name: str, delta_name: str, unknown: str,
evaluated: tuple[str, ...] = CRITERIA) -> pd.DataFrame: # fmt: skip
"""c1 and c4 from the table, then each category's class; c2 and c3 must already be set
for the criteria `evaluated`."""
risk = tab[or_name] > 1
tab["direccion"] = np.where(risk, "riesgo", "protector")
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALPHA)
@@ -136,8 +113,6 @@ def presence(share: float) -> str:
def listing(part: pd.DataFrame) -> str:
"""`variable=category (strength, share)`, `;`-separated; a treatment's strength is
`asociacion`."""
strength = np.where(part["tipo_efecto"] == "tratamiento", "asociacion",
part["clasificacion"].str.split().str[-1]) # fmt: skip
return "; ".join(
@@ -149,8 +124,6 @@ def listing(part: pd.DataFrame) -> str:
def classified(factors: pd.DataFrame) -> pd.DataFrame:
"""The factors a scenario can list (classified ones and treatments), with `tipo_efecto`:
riesgo, protector or tratamiento."""
found = factors[factors["clasificacion"].str.contains("robusto|sugerente|tratamiento")]
kind = np.where(
found["tipo"] == "tratamiento", "tratamiento", found["clasificacion"].str.split().str[0]
@@ -159,8 +132,6 @@ def classified(factors: pd.DataFrame) -> pd.DataFrame:
def scenario_row(frame: pd.DataFrame, mask: np.ndarray, found: pd.DataFrame) -> dict:
"""What one scenario's patients (`mask` over `frame`) have of the `classified` factors:
the listings by kind and presence, and how many risk factors describe it."""
share = [
float((frame.loc[mask, v] == c).mean())
for v, c in zip(found["variable"], found["categoria"], strict=True)
+15 -63
View File
@@ -1,6 +1,3 @@
"""Runs a pipeline graph: each node, after its inputs, writes its output table; then dbt
places what the targets staged into silver."""
import hashlib
import io
import json
@@ -49,9 +46,9 @@ from core.pipeline import (
from models.tea.eeg import read
from persistance import config_log, files, nodes, silver
MIN_WORDS = 5 # fewer than this from a PDF page means it has no text layer
READ_BATCH = 32 # files read at a time (a read is kept as soon as its batch is done)
READ_COLUMNS = { # declared, so a load where every file read cleanly still has `error`
MIN_WORDS = 5
READ_BATCH = 32
READ_COLUMNS = {
"text": {"data_type": "text", "nullable": True},
"ocr": {"data_type": "bool"},
"error": {"data_type": "text", "nullable": True},
@@ -80,25 +77,19 @@ def _reader() -> MarkItDown:
def _lines(text: str) -> str:
"""Non-empty lines, with the spacing inside each collapsed."""
return "\n".join(" ".join(line.split()) for line in text.splitlines() if line.strip())
def _text(content: bytes) -> str:
"""Files other than PDFs, through MarkItDown."""
return _reader().convert_stream(io.BytesIO(content)).text_content
def _pdf_pages(content: bytes) -> list[str]:
"""Each page's text layer, through pdfplumber's layout mode, which keeps a table's rows
on one line each (spacing within a line collapsed)."""
with pdfplumber.open(io.BytesIO(content)) as pdf:
return [_lines(page.extract_text(layout=True) or "") for page in pdf.pages]
def _ocr_pages(content: bytes, numbers: list[int]) -> list[str]:
"""Tesseract's text (OCRmyPDF's sidecar, from the deskewed page) of these pages only,
copied into a PDF of their own: a typed page keeps its own text layer."""
source, scans = pikepdf.open(io.BytesIO(content)), pikepdf.new()
for n in numbers:
scans.pages.append(source.pages[n])
@@ -114,8 +105,6 @@ def _ocr_pages(content: bytes, numbers: list[int]) -> list[str]:
def read_file(content: bytes) -> dict:
"""Text of one file, its format, and whether OCR was needed. An unreadable file keeps
its error; a signal recording (EDF) has no text to read."""
kind = file_format(content)
if kind == "edf":
return {"text": None, "ocr": False, "error": None, "format": kind}
@@ -123,8 +112,6 @@ def read_file(content: bytes) -> dict:
def _read_text(content: bytes) -> dict:
"""The file's text; a PDF page by page, OCR only on the pages without a text layer (a
typed form whose second page is a scan, say)."""
try:
if not content.startswith(b"%PDF"):
return {"text": _text(content), "ocr": False, "error": None}
@@ -134,26 +121,23 @@ def _read_text(content: bytes) -> dict:
for i, page in zip(scanned, _ocr_pages(content, scanned), strict=True):
pages[i] = page
return {"text": "\n".join(p for p in pages if p), "ocr": bool(scanned), "error": None}
except Exception as e: # noqa: BLE001 - an unreadable file is recorded, not fatal
except Exception as e: # noqa: BLE001
return {"text": None, "ocr": False, "error": f"{type(e).__name__}: {e}"}
def run_read(p: str, node: Read):
"""The input's rows with their file's text and format beside the file column (which
keeps the file, for a study that takes the file itself: an EEG's recording); each file
read once."""
rows = list(nodes.rows(p, node.inputs[0]))
for row in rows: # the source kept the file; the row carries its hash
for row in rows:
row["key"] = row.get(node.column) or None
keys = {r["key"] for r in rows} - {None}
found = nodes.cached("read_cache", keys)
legacy = [k for k, r in found.items() if r.get("format") is None] # read before formats
legacy = [k for k, r in found.items() if r.get("format") is None]
for k in legacy:
found[k]["format"] = file_format(files.content(k) or b"")
nodes.remember("read_cache", [{"key": k, **{c: found[k][c] for c in READ_COLUMNS}}
for k in legacy], READ_COLUMNS) # fmt: skip
new = sorted(keys - set(found))
with ProcessPoolExecutor() as pool: # a batch of files in memory at a time, each kept
with ProcessPoolExecutor() as pool:
for start in range(0, len(new), READ_BATCH):
batch = new[start : start + READ_BATCH]
read = dict(zip(batch, pool.map(read_file, (files.content(k) for k in batch)),
@@ -203,7 +187,6 @@ def run_route(p: str, node: Route, others: list[Route] = ()):
def _codes(node: Map | Extract, fields) -> dict[str, dict[str, str]]:
"""The node's ConceptMap as a translation table per field (none without one)."""
if node.concept_map is None:
return {}
found = config_log.concept_map(node.concept_map)
@@ -217,7 +200,6 @@ def run_map(p: str, node: Map):
def run_fhir(p: str, node: Fhir):
"""Each Bundle's rows of the node's entity; a resource sent again is its latest."""
maps = [config_log.concept_map(node.concept_map)] if node.concept_map else []
found: dict[str, dict] = {}
for row in nodes.rows(p, node.inputs[0]):
@@ -234,7 +216,6 @@ def run_join(p: str, node: Join):
@cache
def _llm() -> tuple[OpenAI, str] | None:
"""The configured OpenAI-compatible endpoint, if it answers; None otherwise."""
if not (url := os.environ.get("LLM_URL")):
return None
client = OpenAI(base_url=url, api_key=os.environ.get("LLM_API_KEY", "none"), timeout=600)
@@ -300,37 +281,30 @@ def _comparison(field: str):
def _plain(identifier: str) -> str:
"""An identifier as compared: letters and digits only, upper case."""
return "".join(ch for ch in identifier if ch.isalnum()).upper()
def _name(name: str) -> str:
"""A name as compared: upper case, without accents, single spaces."""
plain = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode()
return " ".join(plain.upper().split())
def _near(identifier: str) -> list[str]:
"""The identifier and every version of it with one character left out: two identifiers
one typo apart (a wrong, missing, extra or swapped character) share one of these."""
return sorted(
{identifier} | {identifier[:i] + identifier[i + 1 :] for i in range(len(identifier))}
)
def _identities(p: str, node: Link) -> tuple[pd.DataFrame, dict[str, str], dict[str, str]]:
"""One row per record: its identity fields (first value found, reviewers' corrections
applied, identifiers plain); records rejected for identity are left out. And the input
each record came through (its record number's system), and its name as written."""
skip, fixed = nodes.rejected("identity"), nodes.corrections()
records: dict[str, dict] = {}
sources: dict[str, str] = {}
written: dict[str, str] = {} # each record's name as it came (compared normalised)
written: dict[str, str] = {}
for i in node.inputs:
for row in nodes.rows(p, i):
if row.get(HELD) or row[RECORD] in skip:
continue
row = {**row, **fixed.get(row[RECORD], {})} # a reviewer's correction wins
row = {**row, **fixed.get(row[RECORD], {})}
mine = records.setdefault(row[RECORD], {"unique_id": row[RECORD]})
sources.setdefault(row[RECORD], i)
for f in node.fields:
@@ -348,10 +322,6 @@ def _identities(p: str, node: Link) -> tuple[pd.DataFrame, dict[str, str], dict[
def _distinct(records: pd.DataFrame, rules: list[str], judged: set[str]) -> pd.Series:
"""Each record's stand-in: one record per identity that the rules join to itself (a
patient's 24 reports carrying one record number are one row to compare, not 24² pairs).
A record a reviewer judged stands for itself, and so does one the rules would not join
to an identical record (nothing compared was read, say)."""
fields = [c for c in records.columns if c != "unique_id"]
key = records[fields].astype(object).where(records[fields].notna(), None)
same = pd.Series(list(key.itertuples(index=False, name=None)), index=records.index)
@@ -377,11 +347,6 @@ def _persons(records: pd.DataFrame, edges: pd.DataFrame, db: DuckDBAPI) -> pd.Da
def run_link(p: str, node: Link):
"""Persons: records the node's rules join (Splink deterministic linking), joined or kept
apart by reviewers' decisions. A person whose records disagree on birth date or sex is
held. Persons that may be one (identifiers one typo apart, or the same birth date) and
don't contradict each other are queued for review, with Splink's probability. A person
with nothing that names her (no name, birth date or record number read) is held too."""
records, sources, written = _identities(p, node)
fields = [c for c in records.columns if c != "unique_id"]
rules = [r for r in node.rules or node.default_rules()
@@ -410,7 +375,6 @@ def run_link(p: str, node: Link):
facts = [f for f in ("birth_date", "sex") if f in fields]
spread = persons.groupby("cluster_id")[facts].nunique() if facts else pd.DataFrame()
torn = set(spread[(spread > 1).any(axis=1)].index) if facts else set()
# Nothing that names her was read (a scan's name line misread, say): nobody to join.
read = persons.groupby("cluster_id")[[f for f in fields if f != "sex"]].count().sum(axis=1)
nameless = set(read[read == 0].index)
why = {c: "records of this person disagree on birth date or sex" for c in torn}
@@ -425,9 +389,8 @@ def run_link(p: str, node: Link):
for r in persons.itertuples()
] # fmt: skip
nodes.write(p, node.id, linked, columns)
nodes.stage("identity", p, node.id, linked, silver.identity_columns()) # silver.person
nodes.stage("identity", p, node.id, linked, silver.identity_columns())
# One row per person, so random pairs are different people and Splink's u is honest.
ids = [f for f in IDENTIFIERS if f in fields]
whole = persons.drop(columns="unique_id").groupby("cluster_id").first()
for f in ids:
@@ -456,23 +419,15 @@ def run_link(p: str, node: Link):
known = [f for f in ("birth_date", "sex") if f in fields]
orphan = set(whole.unique_id[whole[facts].isna().all(axis=1)]) if facts else set()
# no birth date to tell her apart (a pathology scan: a name, misread or not, and a sex)
undated = set(whole.unique_id[whole["birth_date"].isna()]) if "birth_date" in fields else set()
# Answers are kept by record; a person is known by any of hers, whatever joined since.
whose = persons.set_index("unique_id")["cluster_id"].to_dict()
answered = {frozenset(whose.get(r, r) for r in e) for e in decided}
lone = set() # persons whose identifier is carried by one record only
lone = set()
for f in ids:
carried = persons.dropna(subset=[f]).groupby(["cluster_id", f]).size()
lone |= {person for (person, _), n in carried.items() if n == 1}
def settle(r) -> tuple[str, str] | None:
"""(the person to settle, a possible owner), or None when the pair is implausible:
they contradict each other, or one typo apart is all they share (with sequential
record numbers every patient has such neighbours) unless one side has no
demographics and the other's identifier stands on a single record. Names one typo
apart are rare: an undated side (a misread pathology scan) is always queued; so is the
very same identifier on a record that says nothing else (a scan read only in part)."""
a, b = r.unique_id_l, r.unique_id_r
sides = [(getattr(r, f"{f}_l"), getattr(r, f"{f}_r")) for f in known]
if frozenset((a, b)) in answered or any(
@@ -483,10 +438,10 @@ def run_link(p: str, node: Link):
if not reason.endswith("typo apart"):
return a, b
field = reason.removesuffix(" one typo apart")
if getattr(r, f"{field}_l") == getattr(r, f"{field}_r"): # the very same identifier
if getattr(r, f"{field}_l") == getattr(r, f"{field}_r"):
return (a, b) if a in undated or b not in undated else (b, a)
if field == "full_name" and (a in undated) != (b in undated):
return (a, b) if a in undated else (b, a) # names are rarely one typo apart
return (a, b) if a in undated else (b, a)
if a in orphan and b in lone:
return a, b
if b in orphan and a in lone:
@@ -512,14 +467,11 @@ def run_link(p: str, node: Link):
def run_target(p: str, node: Target, kinds: dict[str, str]):
"""Rows of one study into silver's staging, each given its person by the link node:
a clean row becomes one observation per field it has (long), keyed by its study
instance (the study's key values); a row a rule held waits for review, whole."""
link = next(i for i in node.inputs if kinds[i] == "link")
linked = {r[RECORD]: r for r in nodes.rows(p, link)}
person = {k: r["person_id"] for k, r in linked.items()}
model, study = catalog.model(node.entity), catalog.studies()[node.entity]
fixed = nodes.corrections() # a reviewer's reading of a value wins over the extraction
fixed = nodes.corrections()
observations, held_rows = [], []
for i in (i for i in node.inputs if i != link):
for row in nodes.rows(p, i):
@@ -566,5 +518,5 @@ def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print
RUNNERS[node.kind](pipeline_id, node)
log(f"{node.id} ({node.kind}) done")
if entities := sorted({n.entity for n in pipeline.nodes if n.kind == "target"}):
silver.build(["silver+"]) # every entity (empty if never staged) and what derives
silver.build(["silver+"])
log(f"silver and gold, from {', '.join(entities)}")
+2 -16
View File
@@ -1,8 +1,3 @@
"""Training and scoring of a domain's models, what the Dagster jobs run. A domain's module
`models.<domain>.jobs` binds them to its models (`MODELS`) and its reports: `train(name,
as_of)` registers a new version (MLflow) with its two generated reports; `score(name)` writes
the champion's risk batch."""
from collections.abc import Callable
from dataclasses import dataclass
from datetime import date
@@ -15,13 +10,10 @@ from persistance import gold, registry
class EmptyCohort(ValueError):
"""The site has nobody in a model's cohort (no colposcopies, say): nothing to learn from."""
pass
class Predictor(mlflow.pyfunc.PythonModel):
"""A fitted model as MLflow serves it: patient timelines in (gold `<domain>_events` rows
with each patient's index date), one row per patient and horizon out."""
def __init__(self, spec, fitted):
self.spec, self.fitted = spec, fitted
@@ -47,10 +39,8 @@ class Jobs:
return f"{self.domain}.{name}"
def train(self, name: str, as_of: date | None = None) -> int:
"""A new registered version of the model, trained on its cohort's timelines up to
`as_of` (default: today), with its metrics and its two generated reports."""
spec, as_of = self.models[name], as_of or date.today()
if getattr(spec, "reports", False): # trained on its cohort, with its own reports
if getattr(spec, "reports", False):
events = gold.timelines(self.events, spec.cohort, as_of)
if events.empty:
raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}")
@@ -64,16 +54,12 @@ class Jobs:
"technical_validation": self.technical_validation(spec, metrics, data),
"interpretability": self.interpretability(spec, fitted, data),
}
# Bootstraps ran on joblib's worker pool: release it now, or the job's process waits
# for its idle workers to time out (5 minutes) before it can end.
get_reusable_executor().shutdown(wait=True)
params = {"cohort": spec.cohort, "method": spec.method, "as_of": as_of.isoformat()}
model = Predictor(spec, fitted)
return registry.register(self.registered(name), model, params, metrics, found)
def score(self, name: str) -> int | None:
"""The champion's risks for today's members of the model's cohort, saved as its risk
batch; None when the model has no champion yet."""
found = registry.champion(self.registered(name))
if found is None:
return None
+11 -85
View File
@@ -1,14 +1,3 @@
"""Interval survival, shared by CaMa and CaCu: the probability of surviving each interval of
follow-up, given alive at its start, by a logistic regression and by a Bayesian network with a
tabular CPT, mixed per interval; survival to a horizon is the product of the intervals' up to it.
Each interval's models fit the patients alive at its start (`months >= start`); one censored
inside the interval counts as half a risk. The mixture weight of an interval is the one that
best predicts patients out of sample (`folds` folds), shrunk toward 50/50 when there are few
deaths: lambda = shrink / (shrink + deaths). Covariates are categorical; a missing value is a
category of its own (UNKNOWN).
"""
import json
import warnings
from dataclasses import dataclass, field
@@ -28,8 +17,6 @@ DAYS_PER_YEAR = 365.25
def outcomes(index: pd.Series, death: pd.Series, end, cap_months: int) -> pd.DataFrame:
"""Whole months from each index to her death or, alive, to `end`, and whether she died;
follow-up is cut at `cap_months` (a later death counts as alive)."""
index, death, end = pd.to_datetime(index), pd.to_datetime(death), pd.Timestamp(end)
died = (death.notna() & (death <= end)).to_numpy()
last = death.where(died, end)
@@ -42,7 +29,6 @@ def outcomes(index: pd.Series, death: pd.Series, end, cap_months: int) -> pd.Dat
def band(values: pd.Series, cuts: list) -> pd.Series:
"""Values in the bands the cuts make (`<c1`, `c1-(c2-1)`, ..., `≥cn`); empty stays empty."""
edges = [-np.inf, *cuts, np.inf]
labels = [f"<{cuts[0]}", *[f"{a}-{b - 1}" for a, b in pairwise(cuts)], f"≥{cuts[-1]}"]
return pd.cut(values, edges, right=False, labels=labels).astype(object)
@@ -50,8 +36,6 @@ def band(values: pd.Series, cuts: list) -> pd.Series:
@dataclass(frozen=True)
class Constant:
"""An interval where everyone at risk had the same outcome: the same probability for all."""
p: float
def predict_proba(self, X) -> np.ndarray:
@@ -59,7 +43,6 @@ class Constant:
def _bdeu(code, y, w, q, ess) -> float:
"""The outcome's weighted BDeu score given parent configurations `code` (of `q`)."""
n = np.bincount(code * 2 + y, weights=w, minlength=q * 2).reshape(q, 2)
aj, ajk = ess / q, ess / q / 2
return float(np.sum(gammaln(aj) - gammaln(aj + n.sum(1))
@@ -67,7 +50,6 @@ def _bdeu(code, y, w, q, ess) -> float:
def _search(X, levels, y, w, ess, max_parents) -> list[int]:
"""Greedy: the covariate that most improves the outcome's BDeu, until none does."""
parents, code, q = [], np.zeros(len(y), int), 1
best = _bdeu(code, y, w, q, ess)
while len(parents) < max_parents:
@@ -94,12 +76,6 @@ def _code(X, levels, parents) -> np.ndarray:
class IntervalSurvival(BaseEstimator):
"""Survival by intervals (`borders`, months), LR and HBN stacked per interval.
`fit(X, months, event)` takes the categorical covariates `features`; the HBN's parents
are `parents` (feature names) or, when None, learned per interval by the BDeu score.
"""
def __init__(self, features, borders=(0, 6, 12, 18), parents=None, ess=1000, max_parents=5,
folds=5, shrink=20, seed=42): # fmt: skip
self.features = features
@@ -111,8 +87,6 @@ class IntervalSurvival(BaseEstimator):
self.shrink = shrink
self.seed = seed
# -- coding: dummies for the LR (first level alphabetically as reference), integer codes
# (in order of first appearance) for the HBN; an unseen value takes UNKNOWN's code.
def _frame(self, X: pd.DataFrame) -> pd.DataFrame:
found = X[list(self.features)].astype(object)
return found.where(found.notna(), UNKNOWN).astype(str)
@@ -136,8 +110,8 @@ class IntervalSurvival(BaseEstimator):
fitted.append((Constant(1.0), ([], np.array([1.0]))))
continue
m, e = months[at_risk], event[at_risk]
y = np.where(e & (m < b), 0, 1) # 1 = survives the interval
w = np.where(~e & (m < b), 0.5, 1.0) # censored inside it: half a risk
y = np.where(e & (m < b), 0, 1)
w = np.where(~e & (m < b), 0.5, 1.0)
if y.min() == y.max():
lr = Constant(float(y[0]))
else:
@@ -147,7 +121,6 @@ class IntervalSurvival(BaseEstimator):
return fitted
def _hbn(self, X, y, w) -> tuple[list[int], np.ndarray]:
"""The parents and P(survives | parents), smoothed toward the marginal survival."""
if self.parents is None:
parents = _search(X, self.levels_, y, w, self.ess, self.max_parents)
else:
@@ -165,7 +138,6 @@ class IntervalSurvival(BaseEstimator):
return lr, hbn
def _weights(self, X_dum, X_int, months, event) -> np.ndarray:
"""Per interval, the LR's weight in the mixture, from out-of-fold predictions."""
n = len(months)
fold = np.random.default_rng(self.seed + 7).permutation(n) % self.folds
oof_lr, oof_hbn = np.zeros((n, len(self.borders) - 1)), np.zeros((n, len(self.borders) - 1))
@@ -209,35 +181,27 @@ class IntervalSurvival(BaseEstimator):
return self
def components(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
"""Each patient's probability of surviving each interval, by the LR and by the HBN."""
return self._predict(self.fitted_, *self._encode(X))
def survival(self, X: pd.DataFrame) -> np.ndarray:
"""Each patient's survival to the end of each interval."""
lr, hbn = self.components(X)
w = self.weights_[None, :]
return np.cumprod(w * lr + (1 - w) * hbn, axis=1)
# ---------------------------------------------------------------- a model over gold timelines
TRAIN_FRACTION = 0.7
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high",
"scenarios"] # fmt: skip
SCENARIO_SEPARATOR = " | " # between the names of a member's clinical scenarios
SCENARIO_SEPARATOR = " | "
def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Temporal: the earliest index dates train, the latest test; ties in the order of the
hospital's record numbers, so the split (and every fold after it) is the same on every
platform the same data are loaded into."""
ordered = members.sort_values(["index_date", "record_number"], kind="stable")
cut = int(len(ordered) * train_fraction)
return ordered.iloc[:cut].reset_index(drop=True), ordered.iloc[cut:].reset_index(drop=True)
def age_group(events: pd.DataFrame, members: pd.DataFrame, cuts) -> pd.Series:
"""Each member's age at her index (from her birth event), in bands."""
birth = events[events["type"] == "birth"].groupby("person_id")["date"].min()
age = (members["index_date"] - birth.reindex(members.index)).dt.days / DAYS_PER_YEAR
return band(age, list(cuts))
@@ -245,31 +209,20 @@ def age_group(events: pd.DataFrame, members: pd.DataFrame, cuts) -> pd.Series:
@dataclass(frozen=True)
class Spec:
"""Mortality by each horizon from the index (1 minus the interval survival), for the
members of a gold cohort, from their timelines (`person_id`, `index_date`, `date`, `type`,
`value_code`, `value_num`, `source_table`, `source_id`, `record_number`).
`covariates(events, members)` gives each member's `features` at her index. With
`interval_level`, each combination of the covariates seen in training gets an interval:
percentiles of the mortality of `replicas` refits on bootstrap resamples (seed `seed`)."""
name: str
cohort: str
features: tuple[str, ...]
covariates: object # Callable[[pd.DataFrame, pd.DataFrame], pd.DataFrame]
covariates: object
parents: tuple[str, ...] | None = None
borders: tuple[int, ...] = (0, 6, 12, 18) # months
borders: tuple[int, ...] = (0, 6, 12, 18)
cap_months: int = 24
interval_level: float | None = None
replicas: int = 100
seed: int = 0
method: str = "interval survival"
notes: tuple[str, ...] = () # what the technical report states about the method
# Clinical scenarios the report draws: name -> conditions (column, "<" | ">=" | "==" |
# "in", value) on the members' covariates and `scenario_columns` (kept for them only).
notes: tuple[str, ...] = ()
scenarios: dict[str, tuple[tuple[str, str, object], ...]] = field(default_factory=dict)
scenario_columns: tuple[str, ...] = ()
# Features that are treatments: their odds ratios are reported as associations, unclassified.
treatments: tuple[str, ...] = ()
@property
@@ -277,7 +230,6 @@ class Spec:
return tuple(b / 12 for b in self.borders[1:])
def members(self, events: pd.DataFrame) -> pd.DataFrame:
"""One row per member: index date, record number, death date and covariates."""
events = events.assign(date=pd.to_datetime(events["date"]),
index_date=pd.to_datetime(events["index_date"])) # fmt: skip
found = events.groupby("person_id")[["index_date", "record_number"]].first()
@@ -297,7 +249,7 @@ class Spec:
def _intervals(self, train: pd.DataFrame) -> dict[tuple, tuple[list, list]]:
combinations = self._combinations(train).drop_duplicates()
frame = combinations.replace(UNKNOWN, None)
rng = np.random.default_rng(self.seed) # resamples drawn in order, refitted in parallel
rng = np.random.default_rng(self.seed)
samples = [rng.integers(0, len(train), len(train)) for _ in range(self.replicas)]
def mortality(rows: np.ndarray) -> np.ndarray:
@@ -312,8 +264,6 @@ class Spec:
return {tuple(c): (low[i].tolist(), high[i].tolist()) for i, c in enumerate(rows)}
def train(self, events: pd.DataFrame, as_of) -> tuple:
"""Fitted on the earliest members (followed up to `as_of`), with its metrics and what
the reports draw."""
members = self.members(events)
members = members.join(
outcomes(members["index_date"], members["death_date"], as_of, self.cap_months)
@@ -330,8 +280,6 @@ class Spec:
return model, metrics, {"train": train, "test": test}
def predict(self, model: IntervalSurvival, events: pd.DataFrame) -> pd.DataFrame:
"""One row per member and horizon: her mortality by it, its interval when kept, and
the clinical scenarios of the report she falls in (the curves her record draws)."""
members = self.members(events)
mortality = 1.0 - model.survival(members)
n, h = len(members), len(self.horizons)
@@ -352,8 +300,6 @@ class Spec:
})[OUTPUT] # fmt: skip
# ---------------------------------------------------------------- reports (curves)
BOOTSTRAP = 100
BOOTSTRAP_SEED = 42
@@ -382,13 +328,11 @@ def _curve(fitter, name: str) -> dict:
} # fmt: skip
MIN_SCENARIO_EVENTS = 5 # fewer deaths than this: no curves for the scenario
MIN_SCENARIO_EVENTS = 5
GRID_POINTS = 200
def scenario_masks(members: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
"""Which members each scenario takes: all of its conditions hold (an unknown value
holds none)."""
found = {}
for name, conditions in scenarios.items():
mask = np.ones(len(members), bool)
@@ -431,12 +375,6 @@ def _scenario_curves(months: np.ndarray, event: np.ndarray, cap_months: int) ->
def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
"""The training members' observed survival (Kaplan-Meier with its Greenwood band, and a
Weibull fit when anyone died), the model's mean survival at each horizon with a bootstrap
band, the survival of each combination of the covariates, and each clinical scenario's
curves (Kaplan-Meier, Weibull, fractional Weibull) with the model's mean survival over its
members and its band. The model's mixture is its own (the original refitted it per
scenario): the points show the model as it scores."""
from lifelines import KaplanMeierFitter, WeibullFitter
train = data["train"]
@@ -447,8 +385,6 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
rng = np.random.default_rng(BOOTSTRAP_SEED)
samples = [rng.integers(0, len(train), len(train)) for _ in range(BOOTSTRAP)]
# Scenarios: over every member (training first), the observed curves of those with
# enough deaths, and the model's mean survival over each, with the same bootstrap band.
members = pd.concat([train, data.get("test", train.iloc[:0])]).reset_index(drop=True)
masks = scenario_masks(members, spec.scenarios)
@@ -505,14 +441,12 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
for i, row in enumerate(combinations.to_dict("records"))
],
"escenarios": scenarios,
"escenarios_sin_curvas": skipped, # fewer than MIN_SCENARIO_EVENTS deaths
"escenarios_sin_curvas": skipped,
"min_fallecidos_escenario": MIN_SCENARIO_EVENTS,
**risk_factor_report(spec, model, members),
}
# ---------------------------------------------------------------- risk factors
FACTOR_COLUMNS = (
"tipo", "variable", "categoria", "referencia", "n_categoria", "OR_muerte", "IC95_inf",
"IC95_sup", "p", "p_ajustado_BH", "en_manta_markov", "S_categoria", "S_referencia",
@@ -521,15 +455,10 @@ FACTOR_COLUMNS = (
) # fmt: skip
SURVIVAL_COLUMNS = ("S_categoria", "S_referencia", "delta_S")
TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)"
# The model has no variable selection to resample, so stability (2) is not evaluated.
EVALUATED = ("c1_or", "c3_manta_markov", "c4_supervivencia")
def risk_factors(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> pd.DataFrame:
"""The members' risk factors of death by the last horizon (`models.factors`, as the
SEER-trained original rates them): odds ratios of dying before it, among those dead before
it or followed past it; Kaplan-Meier at it over the same members (follow-up cut at
`cap_months`); the Markov blanket is the HBN's parents in any interval."""
from models import factors as rated
horizon = spec.borders[-1]
@@ -552,7 +481,7 @@ def risk_factors(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) ->
SURVIVAL_COLUMNS) # fmt: skip
with warnings.catch_warnings(), np.errstate(over="ignore", divide="ignore"):
warnings.simplefilter("ignore") # rank-deficient designs, unbounded odds ratios
warnings.simplefilter("ignore")
try:
tab = complete(rated.odds_ratios(data, y, intrinsic, reference, "OR_muerte"),
intrinsic) # fmt: skip
@@ -581,8 +510,6 @@ def risk_factors(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) ->
def scenario_factors(spec: Spec, members: pd.DataFrame, table: pd.DataFrame) -> list[dict]:
"""Per clinical scenario, the classified factors and treatments nearly all of its
members have (definitorios) or most have (mayoritarios)."""
from models import factors as rated
found = rated.classified(table) if len(table) else table
@@ -599,9 +526,8 @@ def scenario_factors(spec: Spec, members: pd.DataFrame, table: pd.DataFrame) ->
def risk_factor_report(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> dict:
"""The interpretability report's risk factors: the table and each scenario's summary."""
table = risk_factors(spec, model, members)
rows = json.loads(table.to_json(orient="records")) # NaN as null, numpy types as JSON
rows = json.loads(table.to_json(orient="records"))
return {
"factores_riesgo": {"horizonte_meses": spec.borders[-1], "filas": rows},
"factores_escenarios": scenario_factors(spec, members, table),
+291 -142
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import hashlib
import json
import warnings
from dataclasses import dataclass, field
@@ -12,6 +13,8 @@ from scipy import optimize, stats
from scipy.special import expit
from core.tea import ADOS2_ITEMS
from core.tea.ados2 import algorithm_score
from core.tea.reasons import INSUFFICIENT_DATA
from models.tea.eeg.spindles import ZONES
ASSOCIATION_COLUMNS = (
@@ -43,6 +46,11 @@ SCORE_COLUMNS = (
"reference_probability",
)
ADJUST = ("age_months", "ados_module")
ITEM_ALTERED = 2
CSS_HIGH = 8
MIN_EVENTS = 5
Q_FAMILY = "biomarker"
CLIP_Z = 0
ITEMS = {
1: ("Vocalización espontánea dirigida a otros", "SA", {"toddler", "module_1"}),
@@ -77,85 +85,87 @@ ITEMS = {
),
}
ZONE_ITEMS = {
"frontal_left": (1, 2, 3, 9, 10, 11, 12, 14, 15, 16),
"frontal_right": (4, 5, 7, 14, 22),
"frontal_midline": (6, 11, 12, 13, 14),
"central": (21,),
"parietal": (6, 13, 20),
"temporal_left": (1, 16, 18, 19),
"temporal_right": (4, 5, 8),
"occipital": (4, 20),
SPIKE_GROUPS = {
"any": tuple(ZONES),
"left": ("frontal_left", "temporal_left"),
"right": ("frontal_right", "temporal_right"),
"central": ("central",),
}
SPINDLE_ZONES = ("frontal_left", "frontal_right", "frontal_midline", "central", "parietal")
RHYTHM_ITEMS = (20, 22)
CSS = "CSS"
CSS_HIGH = 8
ALTERED = 1
def item_code(n: int) -> str:
return f"ados2_item_{n:02d}"
def outcome_code(pair: dict) -> str:
if pair["kind"] == "domain":
return pair["outcome"]
if pair["kind"] == "composite":
return "ados2_items_" + "_".join(f"{n:02d}" for n in pair["outcome"])
return item_code(pair["outcome"])
def outcome_items(pair: dict) -> list[int]:
if pair["kind"] == "domain":
return []
return list(pair["outcome"]) if pair["kind"] == "composite" else [pair["outcome"]]
def _pair(biomarker: str, zone: str, predictor: str, kind: str, outcome) -> dict:
return {
"biomarker": biomarker,
"zone": zone,
"predictor": predictor,
"kind": kind,
"outcome": outcome,
}
def pairs(level: str) -> list[dict]:
out = []
for zone in ZONES:
outcomes = [("item", n) for n in ZONE_ITEMS[zone]] if level == "item" else [("domain", CSS)]
def spikes(zone, kind, outcome):
return _pair("spikes", zone, f"spikes_any_{zone}", kind, outcome)
out = [spikes("any", "domain", CSS)]
if level == "item":
out += [
{
"biomarker": "spikes",
"zone": zone,
"predictor": f"z_spikes_{zone}",
"kind": k,
"outcome": o,
}
for k, o in outcomes
spikes("left", "composite", [1, 18]),
spikes("right", "composite", [4, 5, 7]),
spikes("central", "exploratory", 21),
]
out += [
{
"biomarker": "spindles",
"zone": zone,
"predictor": f"z_spindles_{zone}",
"kind": "domain",
"outcome": CSS,
}
for zone in SPINDLE_ZONES
]
out += [_pair("spindles", z, f"z_spindles_{z}", "domain", CSS) for z in SPINDLE_ZONES]
rhythm = [("item", n) for n in RHYTHM_ITEMS] if level == "item" else [("domain", CSS)]
out += [
{
"biomarker": "posterior_rhythm",
"zone": "posterior",
"predictor": "z_posterior_rhythm",
"kind": k,
"outcome": o,
}
for k, o in rhythm
_pair("posterior_rhythm", "posterior", "z_posterior_rhythm", kind, outcome)
for kind, outcome in rhythm
]
out.append(
{
"biomarker": "gradient",
"zone": "global",
"predictor": "z_gradient",
"kind": "domain",
"outcome": CSS,
}
)
out.append(_pair("gradient", "global", "z_gradient", "domain", CSS))
return out
def algorithm_score(v) -> pd.Series:
v = pd.to_numeric(pd.Series(v), errors="coerce")
return v.where(~v.isin([7, 8, 9]), 0).clip(upper=2)
def spikes_any(features: dict) -> dict[str, float]:
minutes = features.get("minutes") or 0
out = {}
for group, zones in SPIKE_GROUPS.items():
rates = [features.get(f"electrode_{e}") for zone in zones for e in ZONES[zone]]
counts = [rate * minutes for rate in rates if rate is not None]
known = minutes > 0 and bool(counts)
out[f"spikes_any_{group}"] = float(any(n > 0 for n in counts)) if known else np.nan
return out
def item_scores(cohort: pd.DataFrame, n: int) -> pd.Series:
column = ADOS2_ITEMS[n - 1]
if "ados_module" not in cohort or column not in cohort:
return pd.Series(np.nan, index=cohort.index)
return algorithm_score(cohort[column]).where(cohort["ados_module"].isin(ITEMS[n][2]))
scores = [
algorithm_score(value, module, column) if module in ITEMS[n][2] else np.nan
for value, module in zip(cohort[column], cohort["ados_module"], strict=True)
]
return pd.Series(scores, index=cohort.index, dtype=float)
def has_items(cohort: pd.DataFrame, minimum: int = 10) -> bool:
@@ -320,11 +330,25 @@ def _summary(model, n, coef, lo, hi, p, design, state, **extra) -> dict:
}
def _complete(t: pd.DataFrame, outcome: str, predictor: str, adjust) -> pd.DataFrame:
return t[[outcome, predictor, *[a for a in adjust if a in t]]].dropna()
def _firth_fits(d: pd.DataFrame, y: np.ndarray, predictor: str) -> bool:
return len(d) >= MIN_ROWS and 2 <= y.sum() <= len(y) - 2 and d[predictor].std() != 0
def _firth_scoring(X, y, b) -> dict:
eta = X[:, 1:] @ b[1:]
flic = optimize.brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50)
return {"beta": [float(v) for v in b[1:]], "intercept": float(flic)}
def firth(t: pd.DataFrame, outcome: str, predictor: str, adjust) -> dict:
d = t[[outcome, predictor, *[a for a in adjust if a in t]]].dropna()
d = _complete(t, outcome, predictor, adjust)
y = d[outcome].to_numpy(float)
out = {"model": "firth", "n": len(d), "events": int(y.sum())}
if len(d) < MIN_ROWS or y.sum() < 2 or y.sum() > len(y) - 2 or d[predictor].std() == 0:
if not _firth_fits(d, y, predictor):
return {**out, "reason": "too few data or no variation"}
design = Design.of(d, predictor, adjust)
X = design.matrix(d)
@@ -334,19 +358,19 @@ def firth(t: pd.DataFrame, outcome: str, predictor: str, adjust) -> dict:
profile = lambda v: _profile_firth(v, 1, X, y, b) # noqa: E731
lo, hi = _interval(profile, b[1], pl, max(se, 0.05))
p = float(stats.chi2.sf(max(2 * (pl - profile(0.0)), 0.0), 1))
eta = X[:, 1:] @ b[1:]
flic = optimize.brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50)
return _summary(
"firth",
len(d),
b[1],
lo,
hi,
p,
design,
{"beta": [float(v) for v in b[1:]], "intercept": float(flic)},
events=int(y.sum()),
)
state = _firth_scoring(X, y, b)
return _summary("firth", len(d), b[1], lo, hi, p, design, state, events=int(y.sum()))
def firth_state(t: pd.DataFrame, outcome: str, predictor: str, adjust) -> dict | None:
d = _complete(t, outcome, predictor, adjust)
y = d[outcome].to_numpy(float)
if not _firth_fits(d, y, predictor):
return None
design = Design.of(d, predictor, adjust)
X = design.matrix(d)
b, _ = _fit_firth(X, y)
return {"design": design.to_dict(), **_firth_scoring(X, y, b)}
def firth_probability(state: dict, t: pd.DataFrame) -> np.ndarray:
@@ -383,42 +407,67 @@ def _fit_ordinal(X, yk, K, fixed=None):
return None, float(optimize.minimize(f, start[idx], method="BFGS").fun)
def _ordinal_fits(d: pd.DataFrame, levels: np.ndarray, predictor: str) -> bool:
return len(d) >= MIN_ROWS and len(levels) >= 2 and d[predictor].std() != 0
def _ordinal_data(d: pd.DataFrame, outcome: str, predictor: str, adjust, levels: np.ndarray):
design = Design.of(d, predictor, adjust)
return design, design.matrix(d)[:, 1:], np.searchsorted(levels, d[outcome].to_numpy())
def _separated(beta: np.ndarray) -> bool:
return abs(beta[0]) > 20
def _ordinal_scoring(par, levels: np.ndarray, high: float) -> dict:
K = len(levels)
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
k = int(np.searchsorted(levels, high))
return {
"beta": [float(v) for v in par[K - 1 :]],
"threshold": float(theta[k - 1]) if 0 < k < K else None,
"always": None if 0 < k < K else float(k == 0),
}
def ordinal(t: pd.DataFrame, outcome: str, predictor: str, adjust, high: float) -> dict:
d = t[[outcome, predictor, *[a for a in adjust if a in t]]].dropna()
d = _complete(t, outcome, predictor, adjust)
levels = np.sort(d[outcome].unique())
out = {"model": "ordinal", "n": len(d), "levels": len(levels)}
if len(d) < MIN_ROWS or len(levels) < 2 or d[predictor].std() == 0:
if not _ordinal_fits(d, levels, predictor):
return {**out, "reason": "too few data or no variation"}
design = Design.of(d, predictor, adjust)
X = design.matrix(d)[:, 1:]
design, X, yk = _ordinal_data(d, outcome, predictor, adjust, levels)
K = len(levels)
yk = np.searchsorted(levels, d[outcome].to_numpy())
with warnings.catch_warnings():
warnings.simplefilter("ignore")
par, nll = _fit_ordinal(X, yk, K)
beta = par[K - 1 :]
if abs(beta[0]) > 20:
if _separated(beta):
return {**out, "reason": "does not converge (separation)"}
profile = lambda v: -_fit_ordinal(X, yk, K, fixed=(0, v))[1] # noqa: E731
lo, hi = _interval(profile, beta[0], -nll, 0.1)
if not (np.isfinite(lo) and np.isfinite(hi)):
return {**out, "reason": "does not converge (separation)"}
p = float(stats.chi2.sf(max(2 * (-nll - profile(0.0)), 0.0), 1))
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
k = int(np.searchsorted(levels, high))
return _summary(
"ordinal",
len(d),
beta[0],
lo,
hi,
p,
design,
{
"beta": [float(v) for v in beta],
"threshold": float(theta[k - 1]) if 0 < k < K else None,
"always": None if 0 < k < K else float(k == 0),
},
levels=K,
)
state = _ordinal_scoring(par, levels, high)
return _summary("ordinal", len(d), beta[0], lo, hi, p, design, state, levels=K)
def ordinal_state(
t: pd.DataFrame, outcome: str, predictor: str, adjust, high: float
) -> dict | None:
d = _complete(t, outcome, predictor, adjust)
levels = np.sort(d[outcome].unique())
if not _ordinal_fits(d, levels, predictor):
return None
design, X, yk = _ordinal_data(d, outcome, predictor, adjust, levels)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
par, _ = _fit_ordinal(X, yk, len(levels))
if _separated(par[len(levels) - 1 :]):
return None
return {"design": design.to_dict(), **_ordinal_scoring(par, levels, high)}
def ordinal_probability(state: dict, t: pd.DataFrame) -> np.ndarray:
@@ -445,12 +494,45 @@ def bh(p) -> np.ndarray:
return q
def _outcome(cohort: pd.DataFrame, pair: dict) -> tuple[pd.Series, pd.Series]:
if pair["kind"] == "item":
score = item_scores(cohort, pair["outcome"])
return (score >= ALTERED).astype(float).where(score.notna()), score
css = pd.to_numeric(cohort.get("css", pd.Series(np.nan, index=cohort.index)), errors="coerce")
return (css >= CSS_HIGH).astype(float).where(css.notna()), css
def _digest(key) -> str:
return hashlib.sha256(str(key).encode()).hexdigest()[:16]
def _prepare(cohort: pd.DataFrame, settings: dict) -> pd.DataFrame:
d = cohort.copy()
clip = settings["clip_z"]
for column in d.columns:
if column.startswith(("z_", "spikes_any_")):
v = pd.to_numeric(d[column], errors="coerce").replace([np.inf, -np.inf], np.nan)
d[column] = v.clip(-clip, clip) if clip > 0 and column.startswith("z_") else v
return d
def _css(cohort: pd.DataFrame) -> pd.Series:
return pd.to_numeric(cohort.get("css", pd.Series(np.nan, index=cohort.index)), errors="coerce")
def _outcome(cohort: pd.DataFrame, pair: dict, settings: dict) -> tuple[pd.Series, pd.Series]:
if pair["kind"] == "domain":
css = _css(cohort)
return (css >= settings["css_high"]).astype(float).where(css.notna()), css
scores = pd.concat([item_scores(cohort, n) for n in outcome_items(pair)], axis=1)
complete = scores.notna().all(axis=1)
altered = (scores >= settings["item_altered"]).sum(axis=1).astype(float).where(complete)
level = altered if pair["kind"] == "composite" else scores.iloc[:, 0]
return (altered >= 1).astype(float).where(complete), level
def _high(pair: dict, settings: dict) -> int:
if pair["kind"] == "composite":
return 1
return settings["css_high" if pair["kind"] == "domain" else "item_altered"]
def _event(pair: dict, settings: dict) -> str:
if pair["kind"] == "composite":
return f"alguno >={settings['item_altered']}"
return f">={_high(pair, settings)}"
def _guarded(fit, model: str, *args, **kwargs) -> dict:
@@ -460,50 +542,117 @@ def _guarded(fit, model: str, *args, **kwargs) -> dict:
return {"model": model, "n": 0, "reason": f"singular design ({type(error).__name__})"}
def _models(d: pd.DataFrame, pair: dict) -> tuple[dict, dict]:
p = pair["predictor"]
fit_firth = lambda: _guarded(firth, "firth", d, "_yes", p, ADJUST) # noqa: E731
if pair["kind"] == "item":
return fit_firth(), _guarded(ordinal, "ordinal", d, "_level", p, ADJUST, high=ALTERED)
return _guarded(ordinal, "ordinal", d, "_level", p, ADJUST, high=CSS_HIGH), fit_firth()
def _fit_pair(d: pd.DataFrame, pair: dict, settings: dict) -> dict:
predictor = pair["predictor"]
used = d[["_yes", predictor]].dropna()
events = int(used["_yes"].sum())
without = len(used) - events
short = min(events, without) < settings["min_events"]
counted = short and pair["kind"] == "composite"
binary = _guarded(firth, "firth", d, "_yes", predictor, ADJUST)
graded = _guarded(
ordinal, "ordinal", d, "_level", predictor, ADJUST, high=_high(pair, settings)
)
ordinal_first = pair["kind"] == "domain" or counted
principal, sensitivity = (graded, binary) if ordinal_first else (binary, graded)
if short and principal.get("odds_ratio") is not None:
note = (
f"{INSUFFICIENT_DATA}{events} con evento y {without} sin evento "
f"(minimo {settings['min_events']})"
)
if counted:
note += "; se usa el numero de reactivos alterados"
principal = {**principal, "reason": note}
return {**pair, "principal": principal, "sensitivity": sensitivity}
def _probability(fit: dict, t: pd.DataFrame) -> tuple[np.ndarray, float]:
if fit["model"] == "firth":
return firth_probability(fit["state"], t), firth_reference(fit["state"])
return ordinal_probability(fit["state"], t), ordinal_reference(fit["state"])
def _q_values(rows: list[dict], settings: dict) -> np.ndarray:
tested = np.array([r["kind"] != "exploratory" for r in rows], bool)
families = np.array(
[r["biomarker"] if settings["q_family"] == "biomarker" else "all" for r in rows]
)
p = np.array([r["principal"].get("p", np.nan) for r in rows], float)
q = np.full(len(rows), np.nan)
for family in dict.fromkeys(families[tested]):
chosen = tested & (families == family)
q[chosen] = bh(p[chosen]).round(5)
return q
def _state(model: str, d: pd.DataFrame, pair: dict, settings: dict) -> dict | None:
try:
if model == "firth":
return firth_state(d, "_yes", pair["predictor"], ADJUST)
return ordinal_state(d, "_level", pair["predictor"], ADJUST, _high(pair, settings))
except (np.linalg.LinAlgError, ValueError):
return None
def _probability(model: str, state: dict, t: pd.DataFrame) -> np.ndarray:
return firth_probability(state, t) if model == "firth" else ordinal_probability(state, t)
def _reference(fit: dict) -> float:
reference = firth_reference if fit["model"] == "firth" else ordinal_reference
return reference(fit["state"])
def _scores(t: pd.DataFrame, fitted: set[str], pair: dict, settings: dict) -> np.ndarray:
fit = pair["principal"]
probability = _probability(fit["model"], fit["state"], t)
train = t[t["key"].map(_digest).isin(fitted)]
child = t["child" if "child" in t else "key"]
for name in child[train.index].unique():
own = (child == name).to_numpy()
state = _state(fit["model"], train[child[train.index] != name], pair, settings)
probability[own] = np.nan if state is None else _probability(fit["model"], state, t[own])
return probability
class Ados2Association:
name = "ados2_association"
version = "0.1.0"
version = "0.4.0"
impl = "modern"
def __init__(self, level: str = "auto", fitted: dict | None = None):
if level not in ("auto", "item", "domain"):
raise ValueError(f"level must be auto, item or domain, not {level!r}")
if fitted is not None and not {"settings", "pairs"} <= fitted.keys():
raise ValueError(
f"{self.name}: the saved model has no settings and pairs; retrain the association"
)
self.level = level
self.fitted = fitted
def fit(self, cohort: pd.DataFrame) -> Ados2Association:
level = self.level if self.level != "auto" else ("item" if has_items(cohort) else "domain")
settings = {
"item_altered": ITEM_ALTERED,
"css_high": CSS_HIGH,
"min_events": MIN_EVENTS,
"q_family": Q_FAMILY,
"clip_z": CLIP_Z,
}
prepared = _prepare(cohort, settings)
tested = pairs(level)
rows = []
for pair in pairs(level):
if pair["predictor"] not in cohort:
for pair in tested:
if pair["predictor"] not in prepared:
continue
d = cohort.copy()
d[pair["predictor"]] = d[pair["predictor"]].replace([np.inf, -np.inf], np.nan)
d["_yes"], d["_level"] = _outcome(cohort, pair)
principal, sensitivity = _models(d, pair)
rows.append({**pair, "principal": principal, "sensitivity": sensitivity})
q = np.full(len(rows), np.nan)
biomarkers = np.array([r["biomarker"] for r in rows])
p = np.array([r["principal"].get("p", np.nan) for r in rows], float)
for b in dict.fromkeys(biomarkers):
q[biomarkers == b] = bh(p[biomarkers == b]).round(5)
for r, v in zip(rows, q, strict=True):
d = prepared.copy()
d["_yes"], d["_level"] = _outcome(d, pair, settings)
rows.append(_fit_pair(d, pair, settings))
for r, v in zip(rows, _q_values(rows, settings), strict=True):
r["q"] = None if np.isnan(v) else float(v)
self.fitted = {"level": level, "n": len(cohort), "rows": rows}
self.fitted = {
"level": level,
"n": len(cohort),
"rows": rows,
"settings": settings,
"pairs": tested,
"css_sources": {"computed": int(_css(cohort).notna().sum())},
"keys": sorted(_digest(k) for k in cohort.get("key", [])),
}
return self
def _rows(self) -> list[dict]:
@@ -515,16 +664,15 @@ class Ados2Association:
out = []
for r in self._rows():
f, s = r["principal"], r["sensitivity"]
kind = r["kind"]
ors, sens = f.get("odds_ratio"), s.get("odds_ratio")
out.append(
{
"biomarker": r["biomarker"],
"zone": r["zone"],
"kind": kind,
"kind": r["kind"],
"outcome": r["outcome"],
"outcome_code": item_code(r["outcome"]) if kind == "item" else CSS,
"event": f">={ALTERED if kind == 'item' else CSS_HIGH}",
"outcome_code": outcome_code(r),
"event": _event(r, self.fitted["settings"]),
"model": f["model"],
"n": f["n"],
"odds_ratio": ors,
@@ -544,20 +692,24 @@ class Ados2Association:
)
return pd.DataFrame(out, columns=list(ASSOCIATION_COLUMNS))
def score(self, cohort: pd.DataFrame) -> pd.DataFrame:
def score(self, cohort: pd.DataFrame, leave_one_out: bool = True) -> pd.DataFrame:
rows = self._rows()
settings = self.fitted["settings"]
prepared = _prepare(cohort, settings)
fitted = set(self.fitted["keys"]) if leave_one_out else set()
parts = []
for r in self._rows():
f = r["principal"]
if f.get("odds_ratio") is None or r["predictor"] not in cohort:
for r in rows:
f, predictor = r["principal"], r["predictor"]
if f.get("odds_ratio") is None or predictor not in prepared:
continue
t = cohort
if r["kind"] == "item":
modules = set(ITEMS[r["outcome"]][2])
t = cohort[cohort["ados_module"].isin(modules)]
t = t[t[r["predictor"]].notna()]
t = prepared
for n in outcome_items(r):
t = t[t["ados_module"].isin(ITEMS[n][2])]
t = t[t[predictor].notna()].copy()
if not len(t):
continue
prob, ref = _probability(f, t)
t["_yes"], t["_level"] = _outcome(t, r, settings)
prob = _scores(t, fitted, r, settings)
kept = np.isfinite(prob)
parts.append(
pd.DataFrame(
@@ -565,10 +717,10 @@ class Ados2Association:
"key": t["key"].to_numpy()[kept],
"biomarker": r["biomarker"],
"zone": r["zone"],
"outcome_code": item_code(r["outcome"]) if r["kind"] == "item" else CSS,
"z": t[r["predictor"]].to_numpy(float)[kept],
"outcome_code": outcome_code(r),
"z": pd.to_numeric(cohort.loc[t.index, predictor]).to_numpy(float)[kept],
"probability": prob[kept].round(4),
"reference_probability": round(ref, 4),
"reference_probability": round(_reference(f), 4),
}
)
)
@@ -587,9 +739,6 @@ class Ados2Association:
return cls(d["level"], d["fitted"])
MODULE = Ados2Association()
class Model(mlflow.pyfunc.PythonModel):
def __init__(self, fitted: dict):
self.fitted = json.loads(json.dumps(fitted, default=float))
-2
View File
@@ -1,2 +0,0 @@
"""The TEA EEG analysis: verdict, metrics and age baselines of a child's EEG (`analysis.py`,
`curves.py`)."""
+38 -45
View File
@@ -1,23 +1,10 @@
"""One EEG, from its EDF bytes: whether it can be analysed and, if so, its five metrics.
analysis = analyze(edf_bytes, birth_date)
Validation (`checks.py`) gives the verdict, level and every check. A valid EEG is prepared
(`preprocess.py`), its windows get a state and a stage (`sleep.py`), and the metrics are
measured (`biomarkers.py`) along with the features the age baselines score (`curves.py`).
The age is the EDF header's (recording start minus birth date) when it has both dates, else the
recording start minus `birth_date`. `analyze` never raises: a failure is an `Analysis` with
`error` set, keeping the verdict and checks when validation finished before it. Missing values
are None.
"""
import math
import re
from dataclasses import dataclass, field
from datetime import date
from core.tea.reasons import METRIC_REASONS, REJECTED_MINUTES
from models.tea.eeg import biomarkers, checks, preprocess, read, sleep
from models.tea.eeg.curves import _number
DAYS_PER_MONTH = 30.4375
MAINS_HZ = 60.0
@@ -27,7 +14,7 @@ MAINS_HZ = 60.0
class Metric:
code: str
value: float | None
electrodes: dict[str, float] = field(default_factory=dict) # None where not measured
electrodes: dict[str, float] = field(default_factory=dict)
zones: dict[str, float] = field(default_factory=dict)
@@ -35,6 +22,7 @@ class Metric:
class Analysis:
valid: bool | None
level: str
reasons: list[str]
age_months: float | None
clean_fraction: float | None
bad_channels: int | None
@@ -42,15 +30,26 @@ class Analysis:
duration_min: float | None
line_noise_db: float | None
sleep: bool | None
checks: list[dict] # code, electrode, value, text, unit, low, high, decisive, abnormal
metrics: list[Metric] # posterior_rhythm, spindles_n2, spindles_n3, paroxysmal_spikes,
# anteroposterior_gradient
features: dict[str, dict[str, float]] # by scenario (`curves.SCENARIOS`), None missing
checks: list[dict]
metrics: list[Metric]
features: dict[str, dict]
error: str | None
def _number(v) -> float | None:
return float(v) if v is not None and math.isfinite(v) else None
def _result(out: dict, measured: biomarkers.Measured, **fields) -> Analysis:
metrics = [
Metric(
code,
_number(value),
{k: _number(v) for k, v in electrodes.items()},
{k: _number(v) for k, v in zones.items()},
)
for code, (value, electrodes, zones) in measured.metrics.items()
]
features = {s: {k: _number(v) for k, v in f.items()} for s, f in measured.features.items()}
features[METRIC_REASONS] = measured.reasons
features[REJECTED_MINUTES] = {k: _number(v) for k, v in measured.rejected.items()}
return Analysis(**out | dict(metrics=metrics, features=features) | fields)
def _error(exc: Exception) -> str:
@@ -64,12 +63,12 @@ def analyze(
*,
age_months: float | None = None,
mains_hz: float = MAINS_HZ,
keep_flat=False,
) -> Analysis:
"""`age_months` overrides the age (a reference cohort's table); `mains_hz` is the frequency
of the recording's mains, which only validation's notch follows (`preprocess.NOTCH_HZ`)."""
out = dict(
valid=None,
level=checks.NOT_ANALYZABLE,
reasons=[],
age_months=age_months,
clean_fraction=None,
bad_channels=None,
@@ -87,8 +86,14 @@ def analyze(
rec = read.read(edf)
except read.FileNotValid as exc:
verdict = checks.file_not_valid(str(exc))
return Analysis(
**out | dict(valid=False, clean_fraction=0.0, bad_channels=0, checks=verdict.checks)
return _result(
out,
biomarkers.invalid(),
valid=False,
reasons=verdict.reasons,
clean_fraction=0.0,
bad_channels=0,
checks=verdict.checks,
)
if age_months is None:
header = read.age_months(rec.start, rec.birthday, DAYS_PER_MONTH)
@@ -100,6 +105,7 @@ def analyze(
out.update(
valid=verdict.valid,
level=verdict.level,
reasons=verdict.reasons,
clean_fraction=verdict.clean_pct / 100,
bad_channels=len(verdict.bad),
channels=len(rec.names) or None,
@@ -108,25 +114,12 @@ def analyze(
checks=verdict.checks,
)
if not verdict.valid:
return Analysis(**out)
prep = preprocess.prepare(rec, verdict.bad)
return _result(out, biomarkers.invalid())
prep = preprocess.prepare(rec, verdict.bad, mains_hz, keep_flat=keep_flat)
notes = sleep.note_intervals(prep.annotations, prep.duration_s)
states = sleep.states(prep, notes, age)
staged = sleep.stages(prep, states)
metrics, features = biomarkers.measure(prep, states, staged, notes)
out.update(
sleep=bool((states == "sleep").any()),
metrics=[
Metric(
code,
_number(value),
{k: _number(v) for k, v in electrodes.items()},
{k: _number(v) for k, v in zones.items()},
)
for code, (value, electrodes, zones) in metrics.items()
],
features={s: {k: _number(v) for k, v in f.items()} for s, f in features.items()},
)
return Analysis(**out)
except Exception as exc: # noqa: BLE001 -- one unreadable EDF must not stop a batch
measured = biomarkers.measure(prep, states, notes)
measured.rejected["start_s"] = preprocess.stable_start(rec)
return _result(out, measured, sleep=bool((states == "sleep").any()))
except Exception as exc: # noqa: BLE001
return Analysis(**out | dict(error=_error(exc)))
+82 -50
View File
@@ -1,16 +1,4 @@
"""The five metrics of a valid EEG, their per-electrode and per-zone values, and the features
each age baseline scores (by scenario, `curves.SCENARIOS`).
Posterior rhythm: over at least 15 wake windows, the dominant 3-14 Hz peak of each posterior
electrode's mean periodogram (O1, O2, P3, P4); the median over those with a peak, if 2 or more.
Anteroposterior gradient: over at least 15 sleep windows, the median delta (0.5-4 Hz) power of
each electrode (symmetric Hann, |FFT|²), and the Theil-Sen slope of its log10 against the
electrode's front-back position (6 electrodes at least).
Spindles in N2 and N3 (`spindles.py`): density, per zone, and enhancement per electrode.
Paroxysmal spikes (`spikes.py`): rate in sleep, per electrode and per zone, against the minutes.
"""
from dataclasses import dataclass, replace
import numpy as np
from scipy.fft import rfft, rfftfreq
@@ -22,6 +10,8 @@ from models.tea.eeg.preprocess import WINDOW_S, Prepared
from models.tea.eeg.sleep import POSTERIOR
MIN_WINDOWS = 15
MIN_GRADIENT_ELECTRODES = 6
INVALID = "invalid-eeg"
FRONT_BACK = {
"Fp1": 0.95, "Fp2": 0.95, "F7": 0.59, "F3": 0.53, "Fz": 0.50, "F4": 0.53, "F8": 0.59,
"T3": 0.0, "C3": 0.0, "Cz": 0.0, "C4": 0.0, "T4": 0.0, "T5": -0.59, "P3": -0.53,
@@ -29,42 +19,61 @@ FRONT_BACK = {
} # fmt: skip
CODES = (
"posterior_rhythm",
"spindles_n2",
"spindles_n3",
"spindles",
"paroxysmal_spikes",
"anteroposterior_gradient",
)
def _segments(prep: Prepared, names, states, state) -> list[np.ndarray] | None:
"""The gap-free 4 s windows labelled `state`, (channels, samples) each; None under 15."""
starts = [s for s, label in zip(prep.starts, states, strict=True) if label == state]
if len(starts) < MIN_WINDOWS or not names:
return None
@dataclass(frozen=True)
class Measured:
metrics: dict[str, tuple[float, dict, dict]]
features: dict[str, dict[str, float]]
reasons: dict[str, str]
rejected: dict[str, float]
def _windows(prep: Prepared, states, state) -> list[float]:
return [s for s, label in zip(prep.starts, states, strict=True) if label == state]
def _segments(prep: Prepared, names, starts) -> list[np.ndarray]:
if not names:
return []
x, n = prep.data(names), int(round(WINDOW_S * prep.fs))
found = []
for a in (int(round(float(s) * prep.fs)) for s in starts):
if a + n <= len(x) and np.isfinite(x[a : a + n]).all():
found.append(x[a : a + n].T)
return found or None
return found
def posterior_rhythm(prep: Prepared, states) -> float:
def posterior_rhythm(prep: Prepared, states) -> tuple[float, str | None]:
names = prep.columns(POSTERIOR)
segments = _segments(prep, names, states, "wake")
if segments is None:
return np.nan
starts = _windows(prep, states, "wake")
if len(starts) < MIN_WINDOWS:
return np.nan, "few-wake-windows"
segments = _segments(prep, names, starts)
if not segments:
return np.nan, "no-dominant-peak"
f, power = signals.periodograms(np.stack(segments), prep.fs)
peaks = [signals.dominant_peak(f, power[:, k].mean(axis=0)) for k in range(len(names))]
found = [hz for hz, _, ok in peaks if ok]
return float(np.median(found)) if len(found) >= 2 else np.nan
if len(found) < 2:
return np.nan, "no-dominant-peak"
return float(np.median(found)), None
def delta_gradient(prep: Prepared, states) -> float:
def delta_gradient(prep: Prepared, states) -> tuple[float, str | None]:
names = [c for c in prep.names if c in FRONT_BACK]
segments = _segments(prep, names, states, "sleep")
if segments is None:
return np.nan
starts = _windows(prep, states, "sleep")
if len(starts) < MIN_WINDOWS:
return np.nan, "no-sleep"
if len(names) < MIN_GRADIENT_ELECTRODES:
return np.nan, "few-electrodes"
segments = _segments(prep, names, starts)
if not segments:
return np.nan, "no-sleep"
stack = np.stack(segments)
n = stack.shape[-1]
f = rfftfreq(n, 1 / prep.fs)
@@ -73,41 +82,64 @@ def delta_gradient(prep: Prepared, states) -> float:
log_power = np.log10(np.maximum(delta, 1e-30))
y = np.array([FRONT_BACK[c] for c in names])
finite = np.isfinite(log_power)
return float(theilslopes(log_power[finite], y[finite])[0]) if finite.sum() >= 6 else np.nan
if finite.sum() < MIN_GRADIENT_ELECTRODES:
return np.nan, "few-electrodes"
return float(theilslopes(log_power[finite], y[finite])[0]), None
def measure(prep: Prepared, states, staged, intervals) -> tuple[dict, dict]:
"""(metrics: code -> (value, electrodes, zones), features by scenario)."""
metrics, features = {}, {}
rhythm = posterior_rhythm(prep, states)
def invalid() -> Measured:
nan = {code: (np.nan, {}, {}) for code in CODES}
return Measured(nan, {}, dict.fromkeys(CODES, INVALID), {})
def measure(prep: Prepared, states, intervals) -> Measured:
metrics, features, reasons = {}, {}, {}
rhythm, why = posterior_rhythm(prep, states)
metrics["posterior_rhythm"] = (rhythm, {}, {})
features["eeg-posterior-rhythm"] = {"value": rhythm}
for stage in ("N2", "N3"):
found = spindles.detect(prep, staged, stage)
value, zones = spindles.density(found)
electrodes = spindles.enhancement(prep, found, states)
metrics[f"spindles_{stage.lower()}"] = (value, electrodes, zones)
features[f"eeg-spindles-{stage.lower()}"] = {
"value": value,
**{f"zone_{z}": v for z, v in zones.items()},
}
features[f"eeg-spindle-topography-{stage.lower()}"] = {
f"electrode_{e}": v for e, v in electrodes.items()
}
if why:
reasons["posterior_rhythm"] = why
found = replace(spindles.detect(prep, states), rhythm_near_sigma=spindles.near_sigma(rhythm))
value, zones = spindles.density(found)
electrodes = spindles.enhancement(prep, found, states)
metrics["spindles"] = (value, electrodes, zones)
features["eeg-spindles"] = {
"value": value,
**{f"zone_{z}": v for z, v in zones.items()},
"rhythm_near_sigma": float(found.rhythm_near_sigma),
}
features["eeg-spindle-topography"] = {f"electrode_{e}": v for e, v in electrodes.items()}
if np.isnan(value):
reasons["spindles"] = "no-sleep" if found.minutes < spindles.MIN_MINUTES else "no-spindles"
found = spikes.detect(prep, states, intervals)
if found is None:
nan = dict.fromkeys
found = spikes.Spikes(
np.nan, nan(spikes.ELECTRODES, np.nan), nan(spindles.ZONES, np.nan), 0.0
np.nan,
nan(spikes.ELECTRODES, np.nan),
nan(spindles.ZONES, np.nan),
0.0,
{},
np.nan,
0.0,
{z: sum(e in prep.names for e in members) for z, members in spindles.ZONES.items()},
)
reasons["paroxysmal_spikes"] = "few-electrodes"
elif np.isnan(found.rate):
reasons["paroxysmal_spikes"] = "no-sleep"
metrics["paroxysmal_spikes"] = (found.rate, found.electrodes, found.zones)
features["eeg-spikes"] = {
"value": found.rate,
**{f"electrode_{e}": v for e, v in found.electrodes.items()},
**{f"zone_{z}": v for z, v in found.zones.items()},
"minutes": found.minutes,
"awake_rate": found.awake_rate,
"awake_minutes": found.awake_minutes,
**{f"zone_electrodes_{z}": n for z, n in found.zone_electrodes.items()},
}
gradient = delta_gradient(prep, states)
gradient, why = delta_gradient(prep, states)
metrics["anteroposterior_gradient"] = (gradient, {}, {})
features["eeg-gradient"] = {"value": gradient}
return {code: metrics[code] for code in CODES}, features
if why:
reasons["anteroposterior_gradient"] = why
return Measured({code: metrics[code] for code in CODES}, features, reasons, found.rejected)
+49 -55
View File
@@ -1,19 +1,3 @@
"""Whether an EEG can be analysed: channel rules, 4 s window QC, triage level and gates.
Channel rules flag a channel bad (each reason is one check): dead (< 10 finite samples or SD
< 0.5 µV, which skips the rest), frozen, saturated, infinite values, gaps of its own; after the
mains notch and a 0.5-45 Hz band-pass, an amplitude over 4 x the scalp median, intermittent
contact (10 s blocks far below the montage) or bursts (far above it); on 1-40 Hz, a bridge with
a contiguous electrode or an ear that does not follow its neighbours; EOG/ECG out of range.
Window QC splits the kept scalp channels (notch, 0.5-45 Hz) into back-to-back 4 s windows: a
gap, or a window over 800 µV peak to peak, with muscle (30-45 / 4-13 Hz power, fixed lines out,
over 0.6) or common mode over 0.8, is not clean. Triage sets the level from coverage, bad scalp
electrodes and clean minutes; the gates make the EEG not valid when the level is
`not_analyzable`, fewer than 60 % of windows are clean or fewer than 12 scalp electrodes are
usable.
"""
from dataclasses import dataclass, field
import numpy as np
@@ -43,14 +27,11 @@ NOT_ANALYZABLE = "not_analyzable"
class Validation:
valid: bool
level: str
bad: dict[str, list[str]] # channel -> reasons, every kind of channel
bad: dict[str, list[str]]
clean_pct: float
line_db: float
checks: list[dict] = field(default_factory=list)
@property
def ears_usable(self) -> bool:
return all(ear not in self.bad for ear in ("A1", "A2"))
reasons: list[str] = field(default_factory=list)
def check(
@@ -80,7 +61,7 @@ def check(
def file_not_valid(reason: str) -> Validation:
rows = [check("file", text=reason, decisive=True, abnormal=True)]
return Validation(False, NOT_ANALYZABLE, {}, 0.0, np.nan, rows)
return Validation(False, NOT_ANALYZABLE, {}, 0.0, np.nan, rows, ["invalid-file"])
def _filtered(x, fs, mains_hz, lo, hi):
@@ -88,23 +69,20 @@ def _filtered(x, fs, mains_hz, lo, hi):
def _temporal(v: np.ndarray) -> list[tuple[str, str]]:
"""Rules on a channel's raw samples: (code, reason)."""
finite = v[np.isfinite(v)]
if len(finite) < 10 or np.std(finite) < 0.5:
return [("dead-channel", "dead channel")]
return [("dead-channel", "Canal muerto")]
out = []
if np.mean(np.abs(np.diff(finite)) < 1e-9) > 0.5:
out.append(("frozen", "frozen"))
out.append(("frozen", "Señal congelada"))
if np.mean(np.abs(finite) > 0.98 * np.max(np.abs(finite))) > 0.001:
out.append(("saturated", "saturated"))
out.append(("saturated", "Señal saturada"))
if np.isinf(v).any():
out.append(("inf-values", "Inf values"))
out.append(("inf-values", "Valores infinitos"))
return out
def _contact(y: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
"""Per channel, the fraction of 10 s blocks silent against the montage and bursting above it
(NaN with fewer than 6 blocks)."""
size = int(10 * fs)
blocks = len(y) // size
low, high = np.full(y.shape[1], np.nan), np.full(y.shape[1], np.nan)
@@ -127,7 +105,6 @@ def _contact(y: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
def _bridges(y: np.ndarray, names: list[str], scalp: list[int]) -> dict[str, str]:
"""Scalp channels correlating over 0.99 with a contiguous electrode and with no far one."""
finite = np.isfinite(y).all(axis=1)
if finite.sum() < 200 or len(scalp) < 2:
return {}
@@ -146,7 +123,6 @@ def _bridges(y: np.ndarray, names: list[str], scalp: list[int]) -> dict[str, str
def _ears(y: np.ndarray, fs: float, names: list[str]) -> dict[str, tuple[float, float]]:
"""Per ear: its best |r| with its neighbours, and the neighbours' median |r| between them."""
out = {}
for ear, around in EAR_NEIGHBOURS.items():
present = [n for n in around if n in names]
@@ -163,12 +139,9 @@ def _ears(y: np.ndarray, fs: float, names: list[str]) -> dict[str, tuple[float,
def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, str]]]:
"""Channel -> [(code, reason)] of every channel some rule flags."""
x, fs, names, kinds = rec.x, rec.fs, list(rec.names), rec.kinds()
reasons = {name: _temporal(x[:, i]) for i, name in enumerate(names)}
dead = {
name for name, found in reasons.items() if found[:1] == [("dead-channel", "dead channel")]
}
dead = {name for name, found in reasons.items() if found and found[0][0] == "dead-channel"}
notched = signals.notch(x, fs, mains_hz)
y45 = signals.bandpass(notched, fs, 0.5, min(45.0, fs / 2 * 0.9))
y40 = signals.bandpass(notched, fs, 1.0, 40.0)
@@ -184,34 +157,38 @@ def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, s
found, k = reasons[name], kinds[name]
if missing[i] > missing.min() + 0.02:
excess = 100 * (missing[i] - missing.min())
found.append(("own-gaps", f"own gaps ({excess:.1f}% more than the rest)"))
found.append(
("own-gaps", f"Interrupciones del canal ({excess:.1f} % más que el resto)")
)
if name in dead:
continue
if k == "eeg" and name in bridges:
found.append(("bridge", f"bridge with {bridges[name]}"))
found.append(("bridge", f"Puente con {bridges[name]}"))
if k in ("eeg", "ear") and np.isfinite(ratio[i]) and ratio[i] > 4.0:
found.append(("amplitude", f"amplitude {ratio[i]:.1f} x the scalp median"))
found.append(
("amplitude", f"Amplitud {ratio[i]:.1f} veces la mediana del cuero cabelludo")
)
if name in ears and ears[name][1] > 0.2 and ears[name][0] < 0.5 * ears[name][1]:
c, e = ears[name]
found.append(
(
"does-not-correlate",
f"does not correlate with its neighbours ({c:.2f} vs {e:.2f})",
f"Sin correlación con los vecinos ({c:.2f} frente a {e:.2f})",
)
)
if np.isfinite(low[i]) and low[i] > 0.10:
found.append(
(
"intermittent-contact",
f"intermittent contact ({100 * low[i]:.0f}% of blocks silent)",
f"Contacto intermitente ({100 * low[i]:.0f} % de bloques sin señal)",
)
)
if k in ("eeg", "ear") and np.isfinite(burst[i]) and burst[i] > 0.05:
found.append(
(
"intermittent-bursts",
f"intermittent contact by bursts "
f"({100 * burst[i]:.0f}% of blocks above 4 x the montage)",
f"Contacto intermitente por ráfagas "
f"({100 * burst[i]:.0f} % de bloques por encima de 4 veces el montaje)",
)
)
if k in ("eog", "ecg"):
@@ -220,18 +197,18 @@ def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, s
found.append(
(
"aux-amplitude",
f"amplitude {np.sqrt(np.mean(v**2)):.0f} uV, "
f"out of range even for {k.upper()}",
f"Amplitud {np.sqrt(np.mean(v**2)):.0f} µV, "
f"fuera de rango incluso para {k.upper()}",
)
)
return {name: found for name, found in reasons.items() if found}
def window_qc(y: np.ndarray, fs: float) -> list[tuple[float, float, str]]:
"""Back-to-back 4 s windows of a filtered scalp signal: (start s, end s, verdict), the
verdict `gap`, `suspect` or `clean`."""
def window_qc(y: np.ndarray, fs: float, start_s=0.0) -> list[tuple[float, float, str]]:
n = int(4 * fs)
lines = signals.fixed_lines(y, fs, f_max=44.0)
start = int(start_s * fs)
after_start = y[start:] if len(y) - start > 30 * fs else y
lines = signals.fixed_lines(after_start, fs, f_max=44.0)
starts = list(range(0, len(y) - n + 1, n))
segments = [y[a : a + n] for a in starts]
whole = [bool(np.isfinite(s).all()) for s in segments]
@@ -259,7 +236,6 @@ def window_qc(y: np.ndarray, fs: float) -> list[tuple[float, float, str]]:
def _triage(rec: Recording, mains_hz: float, bad: dict, clean_pct: float, coverage: float):
"""(level, bad scalp electrodes by the triage rule)."""
x, fs, kinds = rec.x, rec.fs, rec.kinds()
columns = [i for i, name in enumerate(rec.names) if kinds[name] in ("eeg", "ear")]
y = _filtered(x[:, columns], fs, mains_hz, 0.5, 45.0)
@@ -315,7 +291,7 @@ def validate(rec: Recording, mains_hz: float) -> Validation:
check(
"internal-coverage",
value=coverage,
unit="fraction",
unit="fracción",
low=MIN_COVERAGE,
abnormal=coverage < MIN_COVERAGE,
decisive=True,
@@ -323,7 +299,7 @@ def validate(rec: Recording, mains_hz: float) -> Validation:
check(
"bad-scalp-triage",
value=float(len(triaged)),
unit="electrodes",
unit="electrodos",
high=float(MAX_BAD_SCALP),
abnormal=len(triaged) > MAX_BAD_SCALP,
decisive=True,
@@ -331,12 +307,22 @@ def validate(rec: Recording, mains_hz: float) -> Validation:
check(
"usable-scalp",
value=float(len(usable)),
unit="electrodes",
unit="electrodos",
low=float(MIN_SCALP),
abnormal=len(usable) < MIN_SCALP,
decisive=True,
),
check("triage-level", text=level, abnormal=level == NOT_ANALYZABLE, decisive=True),
check(
"triage-level",
text={
NOT_ANALYZABLE: "No analizable",
"partial": "Parcial",
"no_ear_reference": "Sin referencia auricular",
"complete": "Completo",
}[level],
abnormal=level == NOT_ANALYZABLE,
decisive=True,
),
]
if np.isfinite(line):
rows.append(
@@ -344,6 +330,14 @@ def validate(rec: Recording, mains_hz: float) -> Validation:
"line-noise", value=line, unit="dB", high=MAX_LINE_DB, abnormal=line > MAX_LINE_DB
)
)
valid = level != NOT_ANALYZABLE and clean_pct >= MIN_CLEAN_PCT and len(usable) >= MIN_SCALP
reasons = [
reason
for reason, failed in (
("triage-not-analyzable", level == NOT_ANALYZABLE),
("few-clean-minutes", clean_pct < MIN_CLEAN_PCT),
("few-electrodes", len(usable) < MIN_SCALP),
)
if failed
]
bad = {name: [reason for _, reason in found] for name, found in flagged.items()}
return Validation(valid, level, bad, clean_pct, line, rows)
return Validation(not reasons, level, bad, clean_pct, line, rows, reasons)
+70 -51
View File
@@ -1,22 +1,3 @@
"""Age baselines: each metric's value (and per electrode and zone) against children of the same
age in a reference cohort.
Seven scenarios (`SCENARIOS`), each trained on its feature table (one row per valid reference
study: the scenario's features from `Analysis.features` plus `age_months`). Every feature gets
its own baseline, plain JSON-able data (`train`), scored by `score`:
* Centile curves: on 120 ages log-spaced from 1 to 216 months, the p5, p25, median, p75 and p95
of the reference weighted by a Gaussian on log age (width 0.2), where the effective number of
studies is at least 30 and the age lies within the reference's. A value scores z = (value -
median) / ((median - p5 or p95 - median) / 1.645), outside -1 / +1 below p5 / above p95; the
centiles are interpolated on log age; ages outside the curve get none.
* Count rate (spikes, which most reference children never have): the reference's rate per
minute (16 to 37 months) and its dispersion between children (negative binomial by moments,
Poisson without excess). A value is a count in the child's own minutes (`exposure`): z from
the mid-p tail of that many or more, clipped to ±8; outside +1 when P(N >= n) < 0.05; p5,
median and p95 are the rates at those quantiles of the count in those minutes.
"""
import math
from dataclasses import dataclass
@@ -31,22 +12,21 @@ 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 # the metric code it scores
parts: tuple[str, ...] # of the metric: "value", "electrodes", "zones"
stage: str | None = None
counts: bool = False # a count against the `minutes` feature, not centile curves
metric: str
parts: tuple[str, ...]
counts: bool = False
SCENARIOS = {
"eeg-posterior-rhythm": Scenario("posterior_rhythm", ("value",)),
"eeg-spindles-n2": Scenario("spindles_n2", ("value", "zones"), "N2"),
"eeg-spindle-topography-n2": Scenario("spindles_n2", ("electrodes",), "N2"),
"eeg-spindles-n3": Scenario("spindles_n3", ("value", "zones"), "N3"),
"eeg-spindle-topography-n3": Scenario("spindles_n3", ("electrodes",), "N3"),
"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",)),
}
@@ -54,7 +34,6 @@ PREFIX = {"electrodes": "electrode_", "zones": "zone_"}
def _weighted_quantile(x: np.ndarray, w: np.ndarray, q: float) -> float:
"""Interpolated between the midpoints of each weight's cumulative share."""
order = np.argsort(x)
x, w = x[order], w[order]
return float(np.interp(q, (np.cumsum(w) - 0.5 * w) / w.sum(), x))
@@ -81,15 +60,18 @@ def _curve(values: np.ndarray, ages: np.ndarray) -> dict:
}
def _count_rate(values: np.ndarray, ages: np.ndarray, exposure: np.ndarray) -> dict:
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 # None: Poisson
k = float((mu**2).sum() / excess) if excess > 0 else None
return {
"kind": "count_rate",
"ages": list(COUNT_AGES),
@@ -101,20 +83,30 @@ def _count_rate(values: np.ndarray, ages: np.ndarray, exposure: np.ndarray) -> d
def train(features: pd.DataFrame, scenario: str) -> dict:
"""Feature -> baseline, for every feature of the scenario's table (`age_months` and the
count's `minutes` excepted)."""
counts = SCENARIOS[scenario].counts
ages = features["age_months"].to_numpy(float)
out = {}
for name in features.columns.drop(["age_months", EXPOSURE], errors="ignore"):
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:
out[name] = _count_rate(values, ages, features[EXPOSURE].to_numpy(float))
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
@@ -134,7 +126,7 @@ def centiles(baseline_feature: dict, age_months: float) -> dict:
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"))
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
@@ -144,40 +136,59 @@ def _score_curve(baseline: dict, value: float, age: float) -> dict:
"p5": q["p5"],
"median": q["median"],
"p95": q["p95"],
"reason": None,
}
def _score_count(baseline: dict, value: float, age: float, exposure: float | None) -> dict:
out = dict.fromkeys(("z", "outside", "p5", "median", "p95"))
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 exposure is None or not math.isfinite(rate) or not (exposure > 0 and lo <= age < hi):
return out
n, mu = float(np.round(value * exposure)), rate * exposure
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}
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
baseline: dict,
value: float | None,
age_months: float | None,
exposure: float | None = None,
electrodes: float | None = None,
) -> dict:
"""z, outside (-1/0/+1), p5, median, p95 of a value at an age; None where the value, the
age or the baseline's coverage is missing."""
value, age_months = _number(value), _number(age_months)
if value is None or age_months is None:
return dict.fromkeys(("z", "outside", "p5", "median", "p95"))
if value is None:
return _unscored()
if age_months is None:
return _unscored("no-age")
if baseline["kind"] == "count_rate":
return _score_count(baseline, value, age_months, _number(exposure))
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]:
"""Metric code -> {"value": score, "electrodes": {e: score}, "zones": {z: score}} from the
trained scenarios in `models` (scenario -> `train`'s output); a scenario without a model
leaves its parts out."""
out = {m.code: {} for m in analysis.metrics}
metrics = {m.code: m for m in analysis.metrics}
for name, scenario in SCENARIOS.items():
@@ -192,7 +203,15 @@ def deviations(models: dict[str, dict], analysis) -> dict[str, dict]:
)
else:
out[metric.code][part] = {
key: score(model[PREFIX[part] + key], v, analysis.age_months, exposure)
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
+70 -27
View File
@@ -1,35 +1,35 @@
"""A valid EEG ready for the processes: bad channels out, mains removed, 0.5-100 Hz, average
reference, and the 4 s / 2 s window grid with the stretches QC judged not clean.
The mains notch runs when the line stands at least 6 dB over its neighbourhood on the kept scalp
channels. Its frequency is always `NOTCH_HZ` (60), whatever the mains the validation was given:
the reference cohort (50 Hz mains) was built that way, so its curves only hold if it stays so.
The QC behind the unclean spans is the validation's window rule on the post-notch kept scalp
channels at 0.5-45 Hz.
"""
import unicodedata
import warnings
from dataclasses import dataclass
import numpy as np
from scipy import signal
from models.tea.eeg import signals
from models.tea.eeg.checks import window_qc
from models.tea.eeg.read import Recording
NOTCH_HZ = 60.0
NOTCH_MIN_DB = 6.0
WINDOW_S = 4.0
STEP_S = 2.0
_START_MARKS = (
"start record",
"inicio",
"comienzo",
"begin record",
"recording on",
"start of record",
)
_SETUP_MARKS = ("impedanc", "montaje", "montage", "electrod", "calibrac", "colocac", "prueba")
@dataclass(frozen=True)
class Prepared:
x: np.ndarray # (samples, scalp channels) µV, average reference
names: tuple[str, ...] # the kept scalp channels
x: np.ndarray
names: tuple[str, ...]
fs: float
starts: np.ndarray # window grid starts, s
unclean: tuple[tuple[float, float], ...] # (onset s, duration s) of QC windows not clean
starts: np.ndarray
unclean: tuple[tuple[float, float], ...]
annotations: tuple[tuple[float, float, str], ...]
@property
@@ -37,30 +37,73 @@ class Prepared:
return len(self.x) / self.fs
def columns(self, wanted) -> list[str]:
"""The kept channels among `wanted`, in `wanted`'s order."""
return [name for name in wanted if name in self.names]
def data(self, names) -> np.ndarray:
return self.x[:, [self.names.index(name) for name in names]]
def prepare(rec: Recording, bad) -> Prepared:
scalp = [name for name in rec.of("eeg") if name not in bad]
def stable_start(rec: Recording) -> float:
x = rec.x[:, [rec.names.index(name) for name in rec.of("eeg")]]
n = int(10 * rec.fs)
rms = np.array(
[
np.median(np.std(x[a : a + n], axis=0)) if np.isfinite(x[a : a + n]).all() else np.nan
for a in range(0, len(x) - n + 1, n)
]
)
finite = np.isfinite(rms)
if finite.sum() < 12:
return 0.0
limit = 2.0 * np.median(rms[finite][finite.sum() // 2 :])
start = 0.0
for i in range(len(rms)):
if not np.isfinite(rms[i]):
continue
rest = rms[i:][np.isfinite(rms[i:])]
if len(rest) >= 6 and np.mean(rest <= limit) >= 0.9:
start = i * n / rec.fs
break
mark = None
for onset, _, text in sorted(rec.annotations, key=lambda a: a[0]):
plain = "".join(
c for c in unicodedata.normalize("NFD", str(text)) if unicodedata.category(c) != "Mn"
).lower()
if any(m in plain for m in _START_MARKS):
mark = onset
break
if any(m in plain for m in _SETUP_MARKS):
mark = onset
return float(mark) if mark is not None and mark >= start else start
def _iir_notch(x: np.ndarray, fs: float, mains_hz: float) -> np.ndarray:
frequencies = [mains_hz] + [k * mains_hz for k in range(2, 100) if k * mains_hz < fs / 2 * 0.98]
sos = np.vstack([np.hstack(signal.iirnotch(f, 30.0, fs)).reshape(1, 6) for f in frequencies])
minimum = max(3 * (len(sos) * 2 + 1), int(fs))
return signals.by_runs(x, lambda run: signal.sosfiltfilt(sos, run, axis=0), minimum)
def prepare(rec: Recording, bad, mains_hz: float, keep_flat=False) -> Prepared:
flat = [name for name in rec.of("eeg") if not np.nanstd(rec.x[:, rec.names.index(name)]) > 0.5]
keep = flat if keep_flat and len(flat) == 1 else []
scalp = [name for name in rec.of("eeg") if name not in bad or name in keep]
x = rec.x[:, [rec.names.index(name) for name in scalp]]
if np.nanmedian(signals.line_db(x, rec.fs, NOTCH_HZ)) >= NOTCH_MIN_DB:
x = signals.notch(x, rec.fs, NOTCH_HZ, width=1.5)
gaps = ~np.isfinite(x).all(axis=1)
if np.nanmedian(signals.line_db(x, rec.fs, mains_hz)) >= NOTCH_MIN_DB:
x = signals.notch(x, rec.fs, mains_hz, width=1.5)
y = signals.bandpass(x, rec.fs, 0.5, 100.0)
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning) # the mean of a gap's row
warnings.simplefilter("ignore", RuntimeWarning)
referenced = y - np.nanmean(y, axis=1, keepdims=True)
# Kept as the reference analysis read it from MNE: through volts and back, column-major in
# memory (the layout decides the order of float sums along time).
referenced = np.asfortranarray(referenced * 1e-6 * 1e6)
qc = signals.bandpass(x, rec.fs, 0.5, 45.0)
qc[gaps] = np.nan
qc_names = [name for name in scalp if name not in keep]
raw_qc = rec.x[:, [rec.names.index(name) for name in qc_names]]
qc = signals.bandpass(_iir_notch(raw_qc, rec.fs, mains_hz), rec.fs, 0.5, 45.0)
start_s = stable_start(rec)
unclean = tuple(
(float(t0), float(t1) - float(t0)) for t0, t1, v in window_qc(qc, rec.fs) if v != "clean"
(float(t0), float(t1) - float(t0))
for t0, t1, v in window_qc(qc, rec.fs, start_s)
if v != "clean" or t0 < start_s
)
starts = np.arange(0.0, rec.duration_s - WINDOW_S + 1e-9, STEP_S)
return Prepared(referenced, tuple(scalp), rec.fs, starts, unclean, rec.annotations)
+5 -23
View File
@@ -1,14 +1,3 @@
"""An EDF's bytes as signals: the recognised channels in µV, their kind, the notes and dates.
`edfio` reads the header first: a file under 256 bytes, an unreadable header, no signals or no
recognised channel is not valid (`FileNotValid`). Channels sampled at another rate than the
majority, and later duplicates of a name, are dropped rather than resampled. MNE then reads the
kept channels' data (`reject_by_annotation="NaN"`: `BAD*` notes are gaps) and the notes.
Labels are normalised to 10-20 names (`EEG Fp1-REF` -> `Fp1`, T7/T8/P7/P8 -> T3/T4/T5/T6) or
to EKG/LOC/ROC; anything else is not a channel the analysis reads.
"""
import io
import re
from dataclasses import dataclass
@@ -25,16 +14,14 @@ RENAMED = {"T7": "T3", "T8": "T4", "P7": "T5", "P8": "T6"}
AUXILIARY = (("EKG", "EKG"), ("ECG", "EKG"), ("LOC", "LOC"), ("ROC", "ROC"), ("EOG", "ROC"))
EARS = {"A1", "A2"}
EOG = {"LOC", "ROC"}
# What a header's start date holds when the writer didn't know it.
UNKNOWN_START = date(1985, 1, 1)
class FileNotValid(ValueError):
"""The bytes are not an EDF the analysis can read."""
pass
def normalize(label: str) -> str | None:
"""The channel's 10-20 name (or EKG/LOC/ROC), None if not a recognised channel."""
text = str(label).strip()
if not text or "ANNOT" in text.upper():
return None
@@ -47,7 +34,6 @@ def normalize(label: str) -> str | None:
def kind(name: str) -> str:
"""`eeg` (scalp), `ear`, `eog` or `ecg`, for a normalised name."""
if name in EARS:
return "ear"
if name in EOG:
@@ -57,10 +43,10 @@ def kind(name: str) -> str:
@dataclass(frozen=True)
class Recording:
x: np.ndarray # (samples, channels) µV, NaN in gaps
x: np.ndarray
fs: float
names: tuple[str, ...]
annotations: tuple[tuple[float, float, str], ...] # (onset s, duration s, text)
annotations: tuple[tuple[float, float, str], ...]
start: date | None
birthday: date | None
@@ -72,7 +58,6 @@ class Recording:
return {name: kind(name) for name in self.names}
def of(self, *kinds: str) -> list[str]:
"""The channels of these kinds, in file order."""
return [name for name in self.names if kind(name) in kinds]
@@ -149,7 +134,7 @@ def _open(edf: bytes) -> edfio.Edf:
_check_length(edf)
try:
opened = edfio.read_edf(edf, lazy_load_data=True)
except Exception as exc: # noqa: BLE001 -- any parse failure means the same
except Exception as exc: # noqa: BLE001
raise FileNotValid(f"not a readable EDF/EDF+ header ({type(exc).__name__})") from None
declared_records = int(edf[236:244])
if declared_records > opened.num_data_records:
@@ -158,7 +143,6 @@ def _open(edf: bytes) -> edfio.Edf:
def _kept(edf: bytes) -> list[tuple[str, str]]:
"""(label, name) of the channels to read: recognised, at the majority rate, first of each."""
signals = _open(edf).signals
if not signals:
@@ -182,7 +166,7 @@ def read(edf: bytes) -> Recording:
options = dict(include=[label for label, _ in kept], preload=True, verbose="error")
try:
raw = mne.io.read_raw_edf(io.BytesIO(edf), **options)
except Exception as exc: # notes in a Windows code page
except Exception as exc:
if "latin1" not in str(exc):
raise
raw = mne.io.read_raw_edf(io.BytesIO(edf), encoding="latin1", **options)
@@ -205,8 +189,6 @@ def read(edf: bytes) -> Recording:
def age_months(start: date | None, birthday: date | None, days_per_month: float) -> float | None:
"""Months from birth to the recording, to one decimal; None when a date is missing or is the
unknown-start placeholder, the birth is after the start or the age is over 18 years."""
if start is None or birthday is None or start == UNKNOWN_START or birthday > start:
return None
months = round((start - birthday).days / days_per_month, 1)
+6 -21
View File
@@ -1,13 +1,3 @@
"""The reference cohort the age baselines are trained on: HK1K, the Helsinki EEGs (public),
children of 16 to 36 months, recorded on 50 Hz mains.
`listing` pairs each EDF under a folder with its age from the cohort's table (first column the
file name, second the age in years; months = years x 12 to one decimal); keys are positions in
path order, never file names. `measure` analyses each study as a hospital EEG (at the cohort's
mains, with the table's age) in worker processes; `tables` gives each scenario's training table
from the valid studies.
"""
from pathlib import Path
import pandas as pd
@@ -16,26 +6,23 @@ from models import execution
from models.tea.eeg.analysis import analyze
from models.tea.eeg.curves import SCENARIOS
NAME = "hk1k"
MAINS_HZ = 50.0
AGES = (16.0, 36.0)
def listing(folder: Path, ages_table: Path, ages=AGES) -> list[tuple[str, Path, float]]:
"""(key, path, age in months) of each EDF with an age within `ages`."""
table = pd.read_csv(ages_table)
years = dict(zip(table.iloc[:, 0].astype(str), table.iloc[:, 1].astype(float), strict=True))
months = dict(zip(table["path"].astype(str), table["age"].astype(float), strict=True))
found = []
for path in sorted(p for p in Path(folder).rglob("*") if p.suffix.lower() == ".edf"):
age = round(float(years[path.name] * 12), 1) if path.name in years else None
age = months.get(path.relative_to(folder).as_posix())
if age is not None and age == age and ages[0] <= age <= ages[1]:
found.append((path, age))
return [(f"{NAME}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)]
found.append((path, round(age, 1)))
return [(f"{Path(folder).name}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)]
def _one(study: tuple[str, Path, float, float]) -> dict:
key, path, age, mains_hz = study
a = analyze(Path(path).read_bytes(), age_months=age, mains_hz=mains_hz)
a = analyze(Path(path).read_bytes(), age_months=age, mains_hz=mains_hz, keep_flat=True)
return {
"key": key,
"age_months": age,
@@ -45,14 +32,12 @@ def _one(study: tuple[str, Path, float, float]) -> dict:
}
def measure(studies, workers: int | None = None, mains_hz: float = MAINS_HZ) -> list[dict]:
"""Each study's verdict and features, in listing order."""
def measure(studies, mains_hz: float, workers: int | None = None) -> list[dict]:
items = [(k, p, a, mains_hz) for k, p, a in studies]
return execution.map(_one, items, phase="measuring_reference", workers=workers)
def tables(measured: list[dict]) -> dict[str, pd.DataFrame]:
"""Scenario -> its training table: the valid studies' features and `age_months`."""
usable = [s for s in measured if s["valid"] and s["error"] is None]
return {
name: pd.DataFrame([{**s["features"][name], "age_months": s["age_months"]} for s in usable])
+5 -31
View File
@@ -1,27 +1,14 @@
"""Signal primitives every step shares.
Signals are `(samples, channels)` float64 arrays in µV with NaN in gaps (EDF+ `BAD*` notes). A
filter runs on each gap-free run of rows separately; a run shorter than the filter's minimum
stays NaN. The Butterworth filters are SciPy's (`butter` + `sosfiltfilt` with its default edge
padding) and the periodograms MNE's (`psd_array_welch`, one Hann window per segment). The mains
notch, the fixed-line search and the dominant peak are small rules of their own: no library
computes the same thing (MNE's notch filters change the signal by microvolts).
"""
import numpy as np
from mne.time_frequency import psd_array_welch
from scipy import signal
from scipy.ndimage import median_filter
def runs(valid: np.ndarray) -> list[tuple[int, int]]:
"""`(start, stop)` of each run of True."""
edges = np.diff(np.concatenate([[False], np.asarray(valid, bool), [False]]).astype(int))
return list(zip(np.flatnonzero(edges == 1), np.flatnonzero(edges == -1), strict=True))
def by_runs(x: np.ndarray, fn, minimum: int) -> np.ndarray:
"""`fn` on each gap-free run of rows at least `minimum` long; NaN elsewhere."""
x = np.asarray(x, float)
out = np.full_like(x, np.nan)
for a, b in runs(np.isfinite(x).all(axis=1)):
@@ -31,16 +18,12 @@ def by_runs(x: np.ndarray, fn, minimum: int) -> np.ndarray:
def bandpass(x: np.ndarray, fs: float, lo: float, hi: float, order: int = 4) -> np.ndarray:
"""Zero-phase Butterworth band-pass of each gap-free run."""
sos = signal.butter(order, [lo / (fs / 2), hi / (fs / 2)], btype="band", output="sos")
minimum = max(3 * (2 * len(sos) + 1), int(fs))
return by_runs(x, lambda run: signal.sosfiltfilt(sos, run, axis=0), minimum)
def notch(x: np.ndarray, fs: float, f0: float, width: float = 1.5) -> np.ndarray:
"""Mains removal by spectrum interpolation: around `f0` and each harmonic below 98 % of
Nyquist, the FFT magnitudes within `width` Hz are replaced by a line from the mean magnitude
of the `2 width` Hz on the left to that on the right, keeping the phase."""
centres = [f0] + [k * f0 for k in range(2, 1000) if k * f0 < fs / 2 * 0.98]
def interpolate(run):
@@ -67,8 +50,6 @@ def notch(x: np.ndarray, fs: float, f0: float, width: float = 1.5) -> np.ndarray
def line_db(x: np.ndarray, fs: float, f0: float) -> np.ndarray:
"""Per channel, dB of the mains peak (`f0` ± 0.6 Hz) over its neighbourhood (2-6 Hz away),
from one Hann-tapered FFT of the rows finite in every channel."""
finite = np.isfinite(x).all(axis=1)
if not finite.any():
return np.full(x.shape[1], np.nan)
@@ -83,18 +64,15 @@ def line_db(x: np.ndarray, fs: float, f0: float) -> np.ndarray:
def periodograms(segments: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
"""One Hann periodogram (density, mean removed) of each segment along the last axis:
`(..., n)` -> `(frequencies, (..., n // 2 + 1))`."""
n = segments.shape[-1]
power, f = psd_array_welch(segments, fs, n_fft=n, n_per_seg=n, window="hann", verbose="error")
return f, power
window = np.hanning(n)
y = (segments - segments.mean(axis=-1, keepdims=True)) * window
power = np.abs(np.fft.rfft(y, axis=-1)) ** 2 / (fs * (window**2).sum())
power[..., 1 : -1 if n % 2 == 0 else None] *= 2
return np.fft.rfftfreq(n, 1 / fs), power
def fixed_lines(x: np.ndarray, fs: float, f_max: float) -> list[float]:
"""Frequencies of narrow fixed lines of a recording (artefacts, not EEG): the power of 8 s
Hann segments, averaged and its median taken over channels, in dB above a 4 Hz running
median; local maxima in [1, f_max] Hz at least 6 dB up and at most 0.5 Hz wide at -3 dB,
the most prominent kept where two lie within 0.5 Hz."""
n = int(round(8 * fs))
f = np.fft.rfftfreq(n, 1 / fs)
taper = np.hanning(n)[:, None]
@@ -132,8 +110,6 @@ def fixed_lines(x: np.ndarray, fs: float, f_max: float) -> list[float]:
def band_power(f, power, lo, hi, lines=(), include_hi=False):
"""Power summed over [lo, hi) Hz (`include_hi`: [lo, hi]) along the first axis of `power`,
without the bins within 1 Hz of a fixed line, rescaled to the band's full width."""
band = (f >= lo) & ((f <= hi) if include_hi else (f < hi))
clean = band.copy()
for line in lines:
@@ -144,8 +120,6 @@ def band_power(f, power, lo, hi, lines=(), include_hi=False):
def dominant_peak(f: np.ndarray, power: np.ndarray) -> tuple[float, float, bool]:
"""The largest 3-14 Hz peak over a 1/f line fitted on 1.5-45 Hz without 4-16 Hz:
(Hz, prominence in dB, found). Found when at least 1.5 dB up and not at the band's edge."""
usable = (f >= 1.5) & (f <= 45) & (power > 0)
background = usable & ~((f >= 4) & (f <= 16))
if background.sum() < 5:
+61 -93
View File
@@ -1,23 +1,5 @@
"""The state of each grid window (wake, drowsy, sleep) and, in sleep, its stage (N2, N3).
Notes: a note's state is the first whose words its text contains (lower case, accents removed,
ñ kept); it lasts its duration or, without one, until the next note with a state or 60 s;
pieces under 1 s are dropped and the stretches between notes are `unmarked`. Crying, movement,
disconnection, photic stimulation and hyperventilation are masked.
State: every 4 s window (2 s step) not touching a gap, the mask or a QC span gets five
features from one Hann periodogram per channel: delta/beta, relative alpha, central sigma,
muscle (20-40 / theta+alpha) and the prominence of the posterior peak. Each is standardised by
the HK1K reference (`data/hk1k_state.json`, the posterior rhythm's median a line on log age),
and their weighted mean, clipped to ±6, is cut into wake / drowsy / sleep. A window with no
posterior electrode leaves that feature out of the mean.
Stage: slow waves (0.5-4 Hz; a negative half-wave of 0.125-1 s followed by a positive one, 0.5-2
s in all, 75-300 µV peak to peak) on F3, F4, Fz; a sleep window is N3 when they cover at least
20 % of the 30 s centred on it, else N2.
"""
import json
import re
import unicodedata
from pathlib import Path
@@ -27,18 +9,61 @@ from models.tea.eeg import signals
from models.tea.eeg.preprocess import WINDOW_S, Prepared
REFERENCE = json.loads((Path(__file__).parent / "data" / "hk1k_state.json").read_text())
NOTE_WORDS = {
"photic": ("fotic", "photic", "flash", "estimulacion luminosa"),
"hyperventilation": ("hv", "hipervent", "hypervent"),
"eyes_open": ("ojos abiertos", "eyes open", "oa"),
"eyes_closed": ("ojos cerrados", "eyes closed", "oc"),
"sleep": ("sueno", "dormido", "sleep", "somnol", "husos", "spindle", "fase i", "fase ii",
"n1", "n2", "n3"),
"awake": ("despierta", "despierto", "arousal", "vigilia"),
"crying": ("llanto", "llora", "cry"),
"movement": ("movimiento", "movement", "artefacto de movimiento"),
"feeding": ("come", "alimenta", "biberon", "lactancia"),
} # fmt: skip
NOTE_WORDS = [
("photic", ("fotic", "photic", "flash", "estimulacion luminosa"), ()),
("hyperventilation", ("hipervent", "hypervent"), ("hv",)),
(
"eyes_open",
(
"ojos abiertos",
"eyes open",
"open eyes",
"opens eyes",
"abre ojos",
"abre los ojos",
"abrio ojos",
"abrio los ojos",
"apertura de ojos",
"apertura ocular",
),
("oa", "eo"),
),
(
"eyes_closed",
(
"ojos cerrados",
"eyes closed",
"close eyes",
"closes eyes",
"eyes shut",
"cierra ojos",
"cierra los ojos",
"cerro ojos",
"cerro los ojos",
"cierre de ojos",
"cierre ocular",
),
("oc", "ec"),
),
(
"sleep",
("sueno", "dormido", "dormida", "sleep", "asleep", "somnol", "husos", "spindle"),
("fase i", "fase ii", "fase iii", "n1", "n2", "n3"),
),
("awake", ("despierta", "despierto", "arousal", "vigilia"), ()),
("crying", ("llanto", "llora", "cry"), ()),
("movement", ("movimiento", "movement", "artefacto de movimiento"), ()),
("feeding", ("alimenta", "biberon", "lactancia"), ("come", "comer", "comio", "comiendo")),
]
END = re.compile(r"\b(off|fin|end|stop)\b")
def _pattern(prefixes, words) -> re.Pattern:
parts = [rf"\b{re.escape(k)}" for k in prefixes] + [rf"\b{re.escape(k)}\b" for k in words]
return re.compile("|".join(parts))
PATTERNS = [(state, _pattern(prefixes, words)) for state, prefixes, words in NOTE_WORDS]
EXCLUDED = ("crying", "movement", "disconnection")
MASKED = (*EXCLUDED, "photic", "hyperventilation")
STATES = np.array(["wake", "drowsy", "sleep"], dtype=object)
@@ -46,7 +71,6 @@ BANDS = {"delta": (0.5, 4), "theta": (4, 8), "alpha": (8, 13), "sigma": (11, 16)
"beta": (16, 30), "high": (20, 40)} # fmt: skip
POSTERIOR = ("O1", "O2", "P3", "P4")
CENTRAL = ("C3", "C4", "Cz")
FRONTAL = ("F3", "F4", "Fz")
def note_state(text: str) -> str | None:
@@ -55,13 +79,13 @@ def note_state(text: str) -> str | None:
c for c in unicodedata.normalize("NFD", kept) if unicodedata.category(c) != "Mn"
)
plain = plain.replace("\0", "ñ").replace("\1", "Ñ").lower().strip()
return next(
(state for state, words in NOTE_WORDS.items() if any(w in plain for w in words)), None
)
plain = plain.replace("ñ", "n")
if END.search(plain):
return None
return next((state for state, pattern in PATTERNS if pattern.search(plain)), None)
def note_intervals(annotations, duration_s: float) -> list[tuple[float, float, str]]:
"""(onset s, duration s, state) covering the record: the notes' states and `unmarked`."""
notes = sorted(annotations, key=lambda note: note[0])
found = []
for i, (t0, length, text) in enumerate(notes):
@@ -89,7 +113,6 @@ def note_intervals(annotations, duration_s: float) -> list[tuple[float, float, s
def window_note(t0: float, t1: float, intervals) -> tuple[str, bool]:
"""The state covering most of [t0, t1) and whether it covers less than 80 % of it."""
overlap = {}
for onset, length, state in intervals:
lo, hi = max(t0, onset), min(t1, onset + length)
@@ -102,7 +125,6 @@ def window_note(t0: float, t1: float, intervals) -> tuple[str, bool]:
def mask(prep: Prepared, intervals) -> np.ndarray:
"""Samples of the QC spans and of the masked notes."""
out = np.zeros(len(prep.x), bool)
spans = [*prep.unclean, *((o, d) for o, d, state in intervals if state in MASKED)]
for onset, length in spans:
@@ -111,7 +133,6 @@ def mask(prep: Prepared, intervals) -> np.ndarray:
def _features(prep: Prepared, masked: np.ndarray) -> tuple[list[int], dict[str, np.ndarray]]:
"""Start samples of the usable windows and their features."""
fs, x, names = prep.fs, prep.x, list(prep.names)
n, step = int(WINDOW_S * fs), int(2 * fs)
starts = [
@@ -122,6 +143,7 @@ def _features(prep: Prepared, masked: np.ndarray) -> tuple[list[int], dict[str,
if not starts:
return [], {}
f, power = signals.periodograms(np.stack([x[a : a + n].T for a in starts]), fs)
power *= fs * (np.hanning(n) ** 2).sum() / 2
band = {b: power[..., (f >= lo) & (f < hi)].sum(axis=-1) for b, (lo, hi) in BANDS.items()}
total = np.maximum(band["delta"] + band["theta"] + band["alpha"] + band["beta"], 1e-12)
central = [names.index(c) for c in CENTRAL if c in names] or list(range(min(3, len(names))))
@@ -144,7 +166,6 @@ def _features(prep: Prepared, masked: np.ndarray) -> tuple[list[int], dict[str,
def depth(features: dict[str, np.ndarray], age_months: float | None) -> np.ndarray:
"""The weighted mean of the standardised features, clipped to ±6."""
z, weights = [], []
for name, ref in REFERENCE["features"].items():
if name not in features:
@@ -160,7 +181,6 @@ def depth(features: dict[str, np.ndarray], age_months: float | None) -> np.ndarr
def states(prep: Prepared, intervals, age_months: float | None) -> np.ndarray:
"""`wake`, `drowsy`, `sleep` or `` (not scored) per grid window."""
starts, features = _features(prep, mask(prep, intervals))
out = np.full(len(prep.starts), "", dtype=object)
if not starts:
@@ -169,55 +189,3 @@ def states(prep: Prepared, intervals, age_months: float | None) -> np.ndarray:
by_start = dict(zip(np.round(np.array(starts) / prep.fs, 2), labels, strict=True))
out[:] = [by_start.get(round(float(s), 2), "") for s in prep.starts]
return out
def slow_waves(y: np.ndarray, fs: float) -> list[tuple[float, float]]:
"""(onset s, duration s) of the slow waves of one channel."""
y = signals.bandpass(np.asarray(y, float).reshape(-1, 1), fs, 0.5, 4.0)[:, 0]
sign = np.sign(y)
sign[sign == 0] = 1
crossings = np.flatnonzero(np.diff(sign) != 0) + 1
waves = []
for j, c0 in enumerate(crossings):
if not y[c0] < 0:
continue
if j + 2 >= len(crossings):
break
c1, c2 = crossings[j + 1], crossings[j + 2]
negative, total = (c1 - c0) / fs, (c2 - c0) / fs
if not (0.125 <= negative <= 1.0 and 0.5 <= total <= 2.0):
continue
p2p = float(np.max(y[c1:c2]) - float(np.min(y[c0:c1])))
if 75.0 <= p2p <= 300.0:
waves.append((round(c0 / fs, 3), round(total, 3)))
return waves
def _merged(waves: list[tuple[float, float]]) -> np.ndarray:
if not waves:
return np.empty((0, 2))
a = np.array([onset for onset, _ in waves])
b = a + np.array([length for _, length in waves])
order = np.argsort(a)
out = [[a[order[0]], b[order[0]]]]
for i in order[1:]:
if a[i] <= out[-1][1]:
out[-1][1] = max(out[-1][1], b[i])
else:
out.append([a[i], b[i]])
return np.array(out)
def stages(prep: Prepared, labels: np.ndarray) -> np.ndarray:
"""`N3` or `N2` per sleep window (`` elsewhere)."""
waves = [w for c in prep.columns(FRONTAL) for w in slow_waves(prep.data([c])[:, 0], prep.fs)]
covered = _merged(waves)
out = np.full(len(prep.starts), "", dtype=object)
for k, (start, label) in enumerate(zip(prep.starts, labels, strict=True)):
if label != "sleep":
continue
t0, t1 = start + WINDOW_S / 2 - 15.0, start + WINDOW_S / 2 + 15.0
overlap = np.clip(np.minimum(covered[:, 1], t1) - np.maximum(covered[:, 0], t0), 0, None)
coverage = min(overlap.sum() / max(t1 - t0, 1e-9), 1.0) if len(covered) else 0.0
out[k] = "N3" if round(coverage, 4) >= 0.20 else "N2"
return out
+83 -53
View File
@@ -1,25 +1,3 @@
"""Paroxysmal spikes in sleep: candidates per channel, merged into discharges, counted against
the clean minutes of sleep.
Gate: back-to-back 2 s windows of the 10-20 channels; a window is left out with a gap, in an
excluded note (crying, movement, disconnection) or across two notes, with muscle (20-45 / 4-13 Hz
power, fixed lines out, over 1.5) or frozen signal. Large transients are kept: a discharge is
one. Each kept window adds its 2 s to the state of its midpoint.
Candidate (per channel, 1-70 Hz): a strict local maximum of |y| over 3 x the channel's MAD,
20-200 ms wide at half height above the ±500 ms median (search bounded to ±150 ms), with both
flanks at least 6 x the MAD of the channel's slope; inside a kept window. Its field is the
number of 10-20 neighbours with a same-sign candidate within 25 ms.
Discharge: candidates closer than 180 ms are one; the largest (in MADs) gives its channel, state
and width. A useful discharge has field and is not a vertex wave (asleep, max on Cz/Fz/Pz, a
slow after-wave over 3 MADs), a POSTS (asleep, O1/O2, positive, over 80 ms) or ocular (max on
Fp1/Fp2/F7/F8 with no posterior channel in it, or opposite signs in a left/right pair).
Rate: useful discharges in sleep per sleep minute (rounded to 2) to 3 decimals; per electrode
(its own maxima) and per zone (its electrodes' sum), per unrounded minute to 4 decimals.
"""
from dataclasses import dataclass
import numpy as np
@@ -33,20 +11,47 @@ from models.tea.eeg.spindles import ZONES
ELECTRODES = tuple(NEIGHBOURS)
GATE_S = 2.0
INHERIT_S = 30.0
VERTEX = ("Cz", "Fz", "Pz")
POSTS = ("O1", "O2")
OCULAR = ("Fp1", "Fp2", "F7", "F8")
POSTERIOR = {"P3", "P4", "Pz", "O1", "O2", "T5", "T6"}
LEFT_RIGHT = (("Fp1", "Fp2"), ("F7", "F8"), ("F3", "F4"))
ASLEEP = ("N2", "N3", "sleep")
ASLEEP = ("sleep",)
@dataclass(frozen=True)
class Spikes:
rate: float # useful discharges per minute of clean sleep
rate: float
electrodes: dict[str, float]
zones: dict[str, float]
minutes: float # clean sleep minutes, the rate's exposure
minutes: float
rejected: dict[str, float]
awake_rate: float
awake_minutes: float
zone_electrodes: dict[str, int]
def _states(labelled, duration_s: float) -> np.ndarray:
t = np.arange(0.0, duration_s, 0.5)
out = np.full(len(t), "unlabelled", dtype=object)
for t0, t1, label in labelled:
hit = (out == "unlabelled") & (t0 <= t) & (t < t1)
out[hit] = label
direct = np.flatnonzero(out != "unlabelled")
if not len(direct):
return out
missing = np.flatnonzero((out == "unlabelled") & (t >= t[direct[0]]))
j = np.searchsorted(direct, missing)
before, after = direct[np.maximum(j - 1, 0)], direct[np.minimum(j, len(direct) - 1)]
da = np.where(j > 0, t[missing] - t[before], np.inf)
dd = np.where(j < len(direct), t[after] - t[missing], np.inf)
close = np.minimum(da, dd) <= INHERIT_S
labels = np.where(da <= dd, out[before], out[after])
transition = (j > 0) & (j < len(direct)) & (out[before] != out[after])
labels[transition] = "transition"
out[missing[close]] = labels[close]
return out
def _mad(v: np.ndarray) -> float:
@@ -56,33 +61,47 @@ def _mad(v: np.ndarray) -> float:
return float(np.median(np.abs(v - np.median(v))) * 1.4826) or np.nan
def _gate(x: np.ndarray, fs: float, intervals) -> list[tuple[float, float]]:
"""(start, end) s of the 2 s windows the detector reads."""
def _gate(
x: np.ndarray, fs: float, intervals
) -> tuple[list[tuple[float, float]], dict[str, float]]:
n = int(GATE_S * fs)
top = min(45, fs / 2 * 0.9)
lines = signals.fixed_lines(x, fs, f_max=top)
f = np.fft.rfftfreq(n, 1 / fs)
taper = np.hanning(n)[:, None]
kept = []
kept, rejected = [], {}
for a in range(0, len(x) - n + 1, n):
t0, t1 = a / fs, a / fs + GATE_S
state, mixed = window_note(t0, t1, intervals)
segment = x[a : a + n]
if not np.isfinite(segment).all() or state in EXCLUDED or mixed:
continue
power = np.abs(np.fft.rfft((segment - segment.mean(axis=0)) * taper, axis=0)) ** 2
power = power.mean(axis=1)
high = signals.band_power(f, power, 20, top, lines, include_hi=True)
low = signals.band_power(f, power, 4, 13, lines, include_hi=True)
muscle = float(high / max(low, 1e-12))
frozen = float(np.mean(np.abs(np.diff(segment, axis=0)) < 1e-9))
if not (muscle > 1.5 or frozen > 0.5):
reasons = []
if not np.isfinite(segment).all():
reasons.append("gap")
else:
power = np.abs(np.fft.rfft((segment - segment.mean(axis=0)) * taper, axis=0)) ** 2
power = power.mean(axis=1)
high = signals.band_power(f, power, 20, top, lines, include_hi=True)
low = signals.band_power(f, power, 4, 13, lines, include_hi=True)
muscle = float(high / max(low, 1e-12))
frozen = float(np.mean(np.abs(np.diff(segment, axis=0)) < 1e-9))
reasons = [
reason
for reason, failed in (
("state", state in EXCLUDED),
("mixed-states", mixed),
("muscle", muscle > 1.5),
("frozen", frozen > 0.5),
)
if failed
]
if not reasons:
kept.append((round(t0, 2), round(t1, 2)))
return kept
for reason in reasons:
rejected[reason] = rejected.get(reason, 0.0) + GATE_S / 60.0
return kept, {reason: round(minutes, 4) for reason, minutes in rejected.items()}
def _flanks(y: np.ndarray, i: int, fs: float) -> tuple[float, float]:
"""(slower flank's slope µV/s, width ms) of the transient peaking at `i`, at half height."""
n = len(y)
if i <= 0 or i >= n - 1:
return np.nan, np.nan
@@ -137,7 +156,6 @@ def _candidates(x: np.ndarray, fs: float, channel: str) -> list[dict]:
def _field(c: pd.DataFrame) -> np.ndarray:
"""Per candidate, its 10-20 neighbours with a same-sign candidate within 25 ms."""
times = {(ch, s): np.sort(g.t.to_numpy()) for (ch, s), g in c.groupby(["channel", "sign"])}
out = np.zeros(len(c), int)
for k, (ch, t, s) in enumerate(zip(c.channel, c.t, c.sign, strict=True)):
@@ -152,7 +170,6 @@ def _field(c: pd.DataFrame) -> np.ndarray:
def _merge(c: pd.DataFrame) -> pd.DataFrame:
"""One row per discharge: candidates closer than 180 ms."""
c = c.iloc[np.argsort(c.t.to_numpy(), kind="quicksort")].reset_index(drop=True)
groups = np.split(np.arange(len(c)), np.flatnonzero(np.diff(c.t.to_numpy()) > 0.18) + 1)
rows = []
@@ -177,7 +194,6 @@ def _merge(c: pd.DataFrame) -> pd.DataFrame:
def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None:
"""None with fewer than 4 10-20 channels."""
channels = [c for c in prep.names if c in ELECTRODES]
if len(channels) < 4:
return None
@@ -188,21 +204,23 @@ def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None:
for s, label in zip(prep.starts, states, strict=True)
if label in ("wake", "drowsy", "sleep")
]
grid = _states(labelled, prep.duration_s)
def state_at(t: np.ndarray) -> np.ndarray:
"""The state of the first labelled window holding each time."""
out, open_ = np.full(len(t), "unlabelled", dtype=object), np.ones(len(t), bool)
for t0, t1, label in labelled:
hit = open_ & (t0 <= t) & (t < t1)
out[hit], open_ = label, open_ & ~hit
out = np.full(len(t), "unlabelled", dtype=object)
index = np.floor(t / 0.5).astype(int)
inside = (t >= 0) & (t < prep.duration_s) & (index < len(grid))
out[inside] = grid[index[inside]]
return out
gate = _gate(x, fs, intervals)
gate, rejected = _gate(x, fs, intervals)
minutes = {}
middles = state_at(np.array([(t0 + t1) / 2.0 for t0, t1 in gate]))
for (t0, t1), state in zip(gate, middles, strict=True):
minutes[state] = minutes.get(state, 0.0) + (t1 - t0) / 60.0
sleep_minutes = float(sum(minutes.get(s, 0.0) for s in ("sleep",)))
awake_minutes = float(sum(minutes.get(s, 0.0) for s in ("wake", "drowsy")))
awake_count = 0
counts = dict.fromkeys(channels, 0)
candidates = [row for j, c in enumerate(channels) for row in _candidates(x[:, j], fs, c)]
if candidates and gate:
@@ -215,18 +233,30 @@ def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None:
if len(c):
c = c.assign(field=_field(c), state=state_at(c.t.to_numpy()))
found = _merge(c)
found = found[found.useful & (found.field > 0) & (found.state == "sleep")]
found = found[found.useful & (found.field > 0)]
awake_count = int(found.state.isin(("wake", "drowsy")).sum())
found = found[found.state == "sleep"]
for channel, n in found.channel.value_counts().items():
counts[channel] = int(n)
rounded = round(sleep_minutes, 2)
rate = round(sum(counts.values()) / rounded, 3) if rounded > 0 else np.nan
rate = round(sum(counts.values()) / sleep_minutes, 3) if sleep_minutes > 0 else np.nan
awake_rate = round(awake_count / awake_minutes, 3) if awake_minutes > 0 else np.nan
electrodes = {
e: round(counts[e] / sleep_minutes, 4) if sleep_minutes > 0 and e in counts else np.nan
for e in ELECTRODES
}
zones = {}
zones, zone_electrodes = {}, {}
for zone, members in ZONES.items():
present = [e for e in members if e in counts]
zone_electrodes[zone] = len(present)
total = sum(counts[e] for e in present)
zones[zone] = round(total / sleep_minutes, 4) if present and sleep_minutes > 0 else np.nan
return Spikes(rate, electrodes, zones, round(sleep_minutes, 4))
return Spikes(
rate,
electrodes,
zones,
round(sleep_minutes, 4),
rejected,
awake_rate,
round(awake_minutes, 4),
zone_electrodes,
)
+17 -32
View File
@@ -1,20 +1,3 @@
"""Sleep spindles of one stage (N2 or N3): their density, per zone, and the enhancement of the
sigma envelope per electrode.
Detection runs on the frontal, central and parietal electrodes over the windows of the stage
(only when they add up to a minute). The 11-16 Hz envelope (|Hilbert|, 0.2 s moving mean) sets
per channel a core threshold, max(p95, 3 x median), and an extent one, max(p70, 1.6 x median),
from the stage's own samples; a spindle is an extent stretch with a core sample, 0.5-3 s (longer
ones cut in 3 s pieces), whose sigma power stands 1.5 x over the 5-30 Hz flanks, whose
instantaneous frequency stays in 10-17 Hz half the time with an 11-16 Hz median, and whose
envelope peaks 3 x over the median.
Density: spindles per minute and searched channel (NaN when none were found); per zone, the
zone's spindles per minute and searched electrode. Enhancement: spindles overlapping in time are
one episode; per electrode, the median over episodes of the unsmoothed envelope's maximum within
the episode ± 0.25 s, over the median envelope in sleep.
"""
from dataclasses import dataclass
import numpy as np
@@ -25,6 +8,8 @@ from models.tea.eeg.preprocess import WINDOW_S, Prepared
CHANNELS = ("Fp1", "Fp2", "F3", "F4", "Fz", "F7", "F8", "C3", "C4", "Cz", "P3", "P4", "Pz")
SIGMA = (11.0, 16.0)
RHYTHM_MARGIN_HZ = 1.5
MIN_MINUTES = 1
ZONES = {
"frontal_left": ("Fp1", "F3", "F7"),
"frontal_right": ("Fp2", "F4", "F8"),
@@ -39,9 +24,14 @@ ZONES = {
@dataclass(frozen=True)
class Spindles:
events: list[tuple[float, float, str]] # (onset s, duration s, channel)
events: list[tuple[float, float, str]]
minutes: float
channels: list[str] # the channels searched (none when under a minute of the stage)
channels: list[str]
rhythm_near_sigma: bool = False
def near_sigma(posterior_rhythm: float) -> bool:
return bool(posterior_rhythm > SIGMA[0] - RHYTHM_MARGIN_HZ)
def _envelope(x: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
@@ -73,7 +63,6 @@ def _segments(core: np.ndarray, extent: np.ndarray, fs: float) -> list[tuple[int
def _is_spindle(x: np.ndarray, y: np.ndarray, fs: float) -> bool:
"""Sigma over its flanks, and an instantaneous frequency in band."""
if not np.isfinite(x).all():
return False
nperseg = min(len(x), int(fs))
@@ -92,38 +81,36 @@ def _is_spindle(x: np.ndarray, y: np.ndarray, fs: float) -> bool:
return SIGMA[0] <= float(np.median(in_band)) <= SIGMA[1]
def detect(prep: Prepared, staged: np.ndarray, stage: str) -> Spindles:
"""The spindles in the grid windows staged `stage`."""
def detect(prep: Prepared, states: np.ndarray) -> Spindles:
fs, n = prep.fs, int(WINDOW_S * prep.fs)
asleep = np.zeros(len(prep.x), bool)
for start, s in zip(prep.starts, staged, strict=True):
if s == stage:
for start, label in zip(prep.starts, states, strict=True):
if label == "sleep":
a = int(round(float(start) * fs))
asleep[a : a + n] = True
minutes = float(asleep.sum() / fs / 60)
names = prep.columns([c for c in prep.names if c in CHANNELS])
if minutes < 1 or not names:
if minutes < MIN_MINUTES or not names:
return Spindles([], minutes, [])
x = prep.data(names)
y, envelope = _envelope(x, fs)
events = []
for i, name in enumerate(names):
in_stage = np.where(asleep, envelope[:, i], np.nan)
values = in_stage[np.isfinite(in_stage)]
in_sleep = np.where(asleep, envelope[:, i], np.nan)
values = in_sleep[np.isfinite(in_sleep)]
if len(values) < fs * 30:
continue
median = float(np.median(values)) or 1e-9
core = max(float(np.percentile(values, 95)), 3 * median)
extent = max(float(np.percentile(values, 70)), 1.6 * median)
finite = np.isfinite(in_stage)
for a, b in _segments(finite & (in_stage > core), finite & (in_stage > extent), fs):
finite = np.isfinite(in_sleep)
for a, b in _segments(finite & (in_sleep > core), finite & (in_sleep > extent), fs):
if _is_spindle(x[a:b, i], y[a:b, i], fs) and np.nanmax(envelope[a:b, i]) / median >= 3:
events.append((round(a / fs, 3), round((b - a) / fs, 3), name))
return Spindles(events, minutes, names)
def density(found: Spindles) -> tuple[float, dict[str, float]]:
"""Spindles per minute and channel (rounded to 3), and per zone; NaN when none."""
zones = dict.fromkeys(ZONES, np.nan)
if not found.events or found.minutes <= 0:
return np.nan, zones
@@ -155,8 +142,6 @@ def _episodes(events) -> list[list[float]]:
def enhancement(prep: Prepared, found: Spindles, states: np.ndarray) -> dict[str, float]:
"""Per spindle electrode, the envelope's median peak over episodes against its sleep median
(NaN for an absent electrode, or without spindles)."""
out = dict.fromkeys(CHANNELS, np.nan)
use = prep.columns(CHANNELS)
episodes = _episodes(found.events)
+52 -53
View File
@@ -1,11 +1,3 @@
"""TEA's jobs: the analysis of the hospital's EEGs, and its models, the seven age curves
(models.tea.eeg.curves), trained on the reference cohort of TEA_REFERENCE_DIR (its EDFs and
its ages table, TEA_REFERENCE_AGES) and scoring every analysed EEG against the child's age.
Measuring the reference cohort takes long (each study is analysed as a hospital EEG), so its
features are kept in TEA_REFERENCE_CACHE, a JSON file named by the cohort's hash: a file set
or ages table that changes is measured again."""
import hashlib
import json
import os
@@ -28,7 +20,6 @@ from persistance import cluster, eeg, registry, silver
ASSOCIATION = "ados2_association"
MODELS = curves.SCENARIOS
GOLD = "tea_eeg_metrics" # what scoring rebuilds (the other domains: <domain>_risk)
GOLD_SELECT = [
"tea_eeg_analyses+",
"tea_eeg_metrics+",
@@ -38,9 +29,6 @@ GOLD_SELECT = [
class Baseline(mlflow.pyfunc.PythonModel):
"""An age curve as MLflow serves it: (value, age_months, exposure) rows in, their z,
outside, p5, median and p95 out, for one of its features."""
def __init__(self, scenario: str, baseline: dict):
self.scenario, self.baseline = scenario, baseline
@@ -54,7 +42,8 @@ class Baseline(mlflow.pyfunc.PythonModel):
feature = (params or {}).get("feature", "value")
rows = model_input.to_dict("records")
return pd.DataFrame([curves.score(self.baseline[feature], r.get("value"),
r.get("age_months"), r.get("exposure"))
r.get("age_months"), r.get("exposure"),
r.get("electrodes"))
for r in rows]) # fmt: skip
@@ -73,43 +62,38 @@ def analyze(scope: eeg.Scope | None = None, *, rebuild_gold: bool = True) -> int
return len(found)
def _reference(reference: cluster.Reference | None) -> tuple[str, list[dict], str, int]:
if reference is None:
folder = Path(os.environ["TEA_REFERENCE_DIR"])
ages = Path(os.environ.get("TEA_REFERENCE_AGES", folder / "anon_codex_age_sex.csv"))
name, line_hz = cohort_reference.NAME, 50
else:
folder = cluster.reference_dir(reference.name)
ages = folder / "edades.csv"
if not ages.is_file():
raise ValueError(f"reference cohort {reference.name!r} has no edades.csv")
name, line_hz = reference.name, reference.line_hz
def _cohort(source: cluster.TrainingSource, as_of: date) -> tuple[str, list[dict], str, int | None]:
if source.kind == "site":
measured = eeg.without_diagnosis(as_of)
if not measured:
raise EmptyCohort(f"no valid EEG of a child without the diagnosis by {as_of}")
digest = hashlib.sha256("\n".join(m["key"] for m in measured).encode()).hexdigest()
return digest, measured, "site", None
folder = cluster.reference_dir(source.folder)
ages = folder / "edades.csv"
if not ages.is_file():
raise ValueError(f"folder {source.folder!r} has no edades.csv")
studies = cohort_reference.listing(folder, ages)
if reference is not None and not studies:
raise ValueError(f"reference cohort {name!r} has no EDF with an age from 16 to 36 months")
content = "\n".join(f"{p.name}|{a}" for _, p, a in studies)
if line_hz != 50:
content += f"|line_hz={line_hz}"
digest = hashlib.sha256(content.encode()).hexdigest()
if not studies:
raise ValueError(f"folder {source.folder!r} has no EDF with an age from 16 to 36 months")
content = "\n".join(f"{p.relative_to(folder).as_posix()}|{a}" for _, p, a in studies)
digest = hashlib.sha256(f"{content}|line_hz={source.line_hz}".encode()).hexdigest()
cache = os.environ.get("TEA_REFERENCE_CACHE")
path = Path(cache) / f"{name}-{digest[:16]}.json" if cache else None
path = Path(cache) / f"{source.folder}-{digest[:16]}.json" if cache else None
if path and path.exists():
return digest, json.loads(path.read_text()), name, line_hz
measured = cohort_reference.measure(studies, mains_hz=float(line_hz))
return digest, json.loads(path.read_text()), source.folder, source.line_hz
measured = cohort_reference.measure(studies, mains_hz=float(source.line_hz))
measured = [{**m, "key": str(m["key"])} for m in measured]
if path:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(measured))
return digest, measured, name, line_hz
return digest, measured, source.folder, source.line_hz
@dataclass(frozen=True)
class Jobs:
"""The domain's model jobs (models.definitions): every curve is routine."""
def routine(self) -> list[str]:
return list(MODELS)
return [*MODELS, ASSOCIATION]
JOBS = Jobs()
@@ -120,26 +104,26 @@ def registered(name: str) -> str:
def train(
name: str, as_of: date | None = None, reference: cluster.Reference | None = None
name: str, as_of: date | None = None, source: cluster.TrainingSource | None = None
) -> int | None:
"""A new version of one age curve, trained on the reference cohort's valid studies,
with its two reports: the cohort it learned from, and its centile curves."""
if name == ASSOCIATION:
return train_association(as_of)
digest, measured, cohort, hz = _reference(reference)
day = as_of or date.today()
digest, measured, cohort, hz = _cohort(source or cluster.SiteTrainingSource(kind="site"), day)
table = cohort_reference.tables(measured)[name]
baseline = curves.train(table, name)
valid = [m for m in measured if m["valid"] and m["error"] is None]
found = {"cohort": cohort, "cohort_sha256": digest}
found |= {"as_of": day.isoformat()} if hz is None else {"line_hz": hz}
technical = {
"model": name, "method": "age curves (weighted centiles on log age)",
"cohort": cohort, "cohort_sha256": digest, "line_hz": hz, "studies": len(measured),
"valid_studies": len(valid),
"model": name, "method": "age curves (weighted centiles on log age)", **found,
"studies": len(measured), "valid_studies": len(valid),
"ages_months": [min(m["age_months"] for m in valid), max(m["age_months"] for m in valid)],
"features": sorted(baseline),
} # fmt: skip
interpretability = {"model": name, "kind": "age_curves", "curves": baseline}
metrics = {"n_reference": float(len(valid)), "features": float(len(baseline))}
params = {"cohort": cohort, "cohort_sha256": digest, "line_hz": str(hz)}
params = {key: str(value) for key, value in found.items()}
reports = {"technical_validation": technical, "interpretability": interpretability}
return registry.register(registered(name), Baseline(name, baseline), params, metrics, reports)
@@ -151,13 +135,16 @@ def score_curves() -> dict[str, int | None]:
def cohort() -> tuple[pd.DataFrame, pd.DataFrame]:
columns = [
"key",
"child",
"person_id",
"study_date",
"edf",
"age_months",
"ados_module",
"css",
"language_level",
*ADOS2_ITEMS,
*(f"spikes_any_{group}" for group in association.SPIKE_GROUPS),
]
biomarker = {metric: name for name, metric in ASSOCIATION_BIOMARKERS.items()}
studies, scores = eeg.association_cohort_rows()
@@ -165,12 +152,16 @@ def cohort() -> tuple[pd.DataFrame, pd.DataFrame]:
for row in studies:
row["evaluation_date"] = as_day(row["evaluation_date"]) if row["evaluation_date"] else None
birth = as_day(row["birth_date"]) if row["evaluation_date"] and row["birth_date"] else None
scored = ados2.score(row, birth)
features = json.loads(row["features"] or "{}")
records.append(
{
**row,
**association.spikes_any(features.get("eeg-spikes", {})),
"key": eeg_study_id(row["person_id"], row["study_date"]),
"child": row["person_id"],
"ados_module": row["module"],
"css": ados2.score(row, birth)[0],
"css": scored.css if scored else None,
}
)
values = {}
@@ -179,7 +170,9 @@ def cohort() -> tuple[pd.DataFrame, pd.DataFrame]:
if row["edf"] not in edfs:
continue
name = biomarker[row["metric"]]
if name in ("spikes", "spindles"):
if name == "spikes":
continue
if name == "spindles":
if row["part"] != "zones":
continue
predictor = f"z_{name}_{row['site']}"
@@ -194,7 +187,7 @@ def cohort() -> tuple[pd.DataFrame, pd.DataFrame]:
scored = scored.sort_values(["person_id", "study_date", "key"], na_position="last").reset_index(
drop=True
)
predictors = [c for c in scored.columns if c.startswith("z_")]
predictors = [c for c in scored.columns if c.startswith(("z_", "spikes_any_"))]
fit = (
scored[scored[predictors].notna().any(axis=1)]
.drop_duplicates("person_id")
@@ -232,7 +225,8 @@ def train_association(as_of: date | None = None) -> int | None:
estimator.fit(fit)
pairs = estimator.associations()
level = estimator.fitted["level"]
forest = ["biomarker", "zone", "outcome_code", "odds_ratio", "ci_low", "ci_high", "q"]
forest = ["biomarker", "zone", "kind", "outcome_code", "event", "n"]
forest += ["odds_ratio", "ci_low", "ci_high", "q", "reason"]
reports = {
"technical_validation": {
"model": ASSOCIATION,
@@ -281,8 +275,8 @@ def relate() -> int | None:
def score(name: str) -> int | None:
"""The champion curve's scores of every analysed EEG: the metric's value, and each
electrode and zone it measures; None without a champion."""
if name == ASSOCIATION:
return relate()
found = registry.champion(registered(name))
if found is None:
return None
@@ -304,7 +298,12 @@ def score(name: str) -> int | None:
feature = "value" if part == "value" else prefix + site
if feature not in baseline:
continue
s = curves.score(baseline[feature], value, one["age_months"], exposure)
electrodes = (
(one["features"].get(name) or {}).get(f"zone_electrodes_{site}")
if scenario.counts and part == "zones"
else None
)
s = curves.score(baseline[feature], value, one["age_months"], exposure, electrodes)
rows.append({"key": f"{one['edf']}|{name}|{part}|{site}", "edf": one["edf"],
"scenario": name, "model": label, "metric": scenario.metric,
"part": part, "site": site or None, **s}) # fmt: skip
+10 -5
View File
@@ -151,20 +151,25 @@ def _report(
evaluation_date = recorded_on
module = row.get("module")
titles = {i.field: f"{i.code} {i.title}" for i in ados2_items.ITEMS.get(module, ())}
order = [*titles, *(item for item in tea.ADOS2_ITEMS if item not in titles)]
titles["language_level"] = "A-1 Nivel general de lenguaje oral no ecolálico"
order = [
"language_level",
*(field for field in titles if field != "language_level"),
*(item for item in tea.ADOS2_ITEMS if item not in titles),
]
items = {item: _parse(item, row.get(item), "number", warnings) for item in order}
css, classification = None, None
if evaluation_date is None:
warnings.append("ADOS-2 not scored: no evaluation date")
else:
try:
css, classification = scoring.score(
row | items | {"evaluation_date": evaluation_date}, birth
)
scored = scoring.score(row | items | {"evaluation_date": evaluation_date}, birth)
except (ValueError, TypeError) as exc:
warnings.append(f"ADOS-2 not scored: {exc}")
else:
if css is None and classification is None:
if scored:
css, classification = scored.css, scored.classification
else:
warnings.append(
"the ADOS-2 score could not be calculated: "
"the report lacks the module or the item scores"
-135
View File
@@ -1,135 +0,0 @@
"""The two public cohorts the recurrence model is proved on, METABRIC and SCAN-B, each as a
`Cohort` from its dataset as the `cama_reference` pipeline loads it (every value as written,
column names as dlt names them, `line` the order the file is published in)."""
import pandas as pd
from models.cama import recurrence
from models.cama.recurrence import site
from models.cama.recurrence.cohorts import (
AGE,
DAYS_PER_MONTH,
GRADES,
NODES,
SIZE,
Cohort,
_band,
_number,
_text,
collinear,
)
SOURCES = ("metabric", "scanb")
SAVED = "metabric"
N_BOOTSTRAP = {"metabric": 100, "scanb": 40, "site": 40}
LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B"}
SAMPLING = {
"criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres",
"origen": "METABRIC y SCAN-B (externas)",
}
SCENARIOS = {
"metabric": {
"RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["0"],
"Tamano_tumor": ["<=20 mm"]},
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
"< 45 años": {"Edad": ["<45"]},
"≥ 75 años": {"Edad": ["75+"]},
"Basal (PAM50)": {"Subtipo_PAM50": ["Basal"]},
"HER2 (PAM50)": {"Subtipo_PAM50": ["Her2"]},
"Luminal B (PAM50)": {"Subtipo_PAM50": ["LumB"]},
"RE+ · 1-3 ganglios · cirugía conservadora": {
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["1-3"],
"Cirugia": ["BREAST CONSERVING"]},
"RE− · grado 3": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]},
},
"scanb": site.SCENARIOS,
} # fmt: skip
FIXED = {
"metabric": ["paciente", "tiempo_meses", "evento"],
"scanb": ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"],
}
TREATMENT = {
"metabric": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"],
"scanb": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"],
}
# Covariates taken as they come (our name: the dataset's column).
PASSTHROUGH = {
"metabric": {
"Receptor_estrogeno": "er_status", "Receptor_progesterona": "pr_status",
"HER2": "her2_status", "Subtipo_PAM50": "pam50_x_claudin_low_subtype",
"Tipo_histologico": "cancer_type_detailed", "Celularidad": "cellularity",
"Estado_menopausico": "inferred_menopausal_state",
"Cluster_integrativo": "integrative_cluster", "Lateralidad": "primary_tumor_laterality",
"Cirugia": "type_of_breast_surgery", "Quimioterapia": "chemotherapy",
"Radioterapia": "radio_therapy", "Hormonoterapia": "hormone_therapy",
},
"scanb": {
"Receptor_estrogeno": "er", "Receptor_progesterona": "pr", "HER2": "her2",
"Ki67": "ki67", "Subtipo_clinico": "clinical_subtype", "Tipo_histologico": "histology",
"Estado_menopausico": "menopause_status_bin", "Lateralidad": "laterality",
"Estadio_clinico": "tnm_clinical_stage", "Cirugia": "surgery_type",
"Quimioterapia": "chemotherapy", "Radioterapia": "radiation",
"Hormonoterapia": "endocrine", "AntiHER2": "anti_her2",
},
} # fmt: skip
SCANB_NODES = {"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"}
SCANB_GRADES = {"Grade1": "1", "Grade2": "2", "Grade3": "3"}
def _in_order(rows: pd.DataFrame) -> pd.DataFrame:
return rows.sort_values("line", kind="stable").reset_index(drop=True)
def _metabric(rows: pd.DataFrame) -> pd.DataFrame:
d = _in_order(rows).dropna(subset=["relapse_free_status", "relapse_free_status_monthsx"])
d = d.reset_index(drop=True)
out = pd.DataFrame({"paciente": d["patient_id"]})
out["tiempo_meses"] = _number(d["relapse_free_status_monthsx"])
out["evento"] = d["relapse_free_status"].str.startswith("1").astype(int)
out["Edad"] = _band(_number(d["age_at_diagnosis"]), *AGE)
out["Tamano_tumor"] = _band(_number(d["tumor_size"]), *SIZE)
out["Ganglios_positivos"] = _band(_number(d["lymph_nodes_examined_positive"]), *NODES)
out["Grado_histologico"] = _text(d["neoplasm_histologic_grade"].map(GRADES))
# Mutational load in tertiles of this cohort; a value on a cut falls in the lower band.
load = _number(d["mutation_count"])
q1, q2 = load.quantile([1 / 3, 2 / 3]).to_numpy()
edges = [-1, q1 + 1e-9, q2 + 1e-9, 1e6]
out["Carga_mutacional"] = _band(load, edges, ["baja", "media", "alta"])
for name, column in PASSTHROUGH["metabric"].items():
out[name] = _text(d[column])
return out
def _scanb(rows: pd.DataFrame) -> pd.DataFrame:
d = _in_order(rows)
d = d[d["gender"] == "F"].dropna(subset=["rfi_event", "rfi_days"]).reset_index(drop=True)
rfi, died = _number(d["rfi_event"]), _number(d["os_event"])
out = pd.DataFrame({"paciente": d["patient_name"]})
out["tiempo_meses"] = _number(d["rfi_days"]) / DAYS_PER_MONTH
out["evento"] = rfi.astype(int)
out["muerte_sin_recaida"] = ((died == 1) & (rfi == 0)).astype(int)
out["Edad"] = _band(_number(d["age_5year_bin"]) - 2, *AGE) # the 5-year bin's middle
out["Tamano_tumor"] = _band(_number(d["tumor_size_mm"]), *SIZE)
out["Ganglios_positivos"] = _text(d["node_met_spec"].map(SCANB_NODES))
out["Grado_histologico"] = _text(d["nhg"].map(SCANB_GRADES))
for name, column in PASSTHROUGH["scanb"].items():
out[name] = _text(d[column])
return out
def prepare(source: str, raw: pd.DataFrame) -> Cohort:
full = {"metabric": _metabric, "scanb": _scanb}[source](raw)
fixed, treatment = FIXED[source], TREATMENT[source]
covariates = [c for c in full.columns if c not in fixed]
dropped = collinear(full, [c for c in covariates if c not in treatment])
kept = [c for c in covariates if c not in dropped]
return Cohort(source, full[fixed + kept], kept, [c for c in treatment if c in kept], dropped,
LABELS[source], SCENARIOS[source], SAMPLING) # fmt: skip
def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple:
"""Both cohorts' models, validation, calculator and risk factors; METABRIC's is kept."""
found = {s: prepare(s, raws[s]) for s in SOURCES}
return recurrence.fit(found, SAVED, "metabric+scanb", N_BOOTSTRAP if bootstrap else {})
+59 -1
View File
@@ -1,6 +1,12 @@
from types import SimpleNamespace
import numpy as np
import pandas as pd
import pytest
from scipy import stats
from models.tea.eeg import curves
from models.tea.eeg.analysis import Metric
def test_centile_interpolation_preserves_scoring():
@@ -19,6 +25,58 @@ def test_centile_interpolation_preserves_scoring():
{"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(
scored = curves.score(baseline, value, 24)
assert scored.pop("reason") is None
assert scored == pytest.approx(
{"z": z, "outside": outside, "p5": 2, "median": 4, "p95": 8}, rel=1e-9
)
def test_zone_training_uses_counts_over_minutes_times_present_electrodes():
features = pd.DataFrame(
{
"value": [6.0, 9.0],
"electrode_C3": [3.0, 3.0],
"zone_central": [6.0, 9.0],
"minutes": [2.0, 4.0],
"zone_electrodes_central": [2.0, 3.0],
"awake_rate": [1.0, 2.0],
"awake_minutes": [5.0, 6.0],
"age_months": [20.0, 30.0],
}
)
baseline = curves.train(features, "eeg-spikes")
assert set(baseline) == {"value", "electrode_C3", "zone_central"}
assert baseline["zone_central"]["events"] == 48
assert baseline["zone_central"]["rate"] == 3.0
assert baseline["zone_central"]["k"] is None
assert baseline["value"]["rate"] == 8.0
assert baseline["electrode_C3"]["rate"] == 3.0
@pytest.mark.parametrize("electrodes", [None, np.nan, 1.0, 2.0, 3.0])
def test_count_score_scales_expected_counts_by_electrodes(electrodes):
baseline = {"kind": "count_rate", "ages": [16.0, 37.0], "rate": 3.0, "k": None}
scored = curves.score(baseline, 6.0, 24.0, exposure=5.0, electrodes=electrodes)
present = 1.0 if electrodes is None or np.isnan(electrodes) else electrodes
law = stats.poisson(3 * 5 * present)
tail = law.sf(29)
assert scored["reason"] is None
assert scored["z"] == pytest.approx(np.clip(stats.norm.ppf(1 - tail + law.pmf(30) / 2), -8, 8))
assert scored["outside"] == int(tail < 0.05)
for name, q in (("p5", 0.05), ("median", 0.5), ("p95", 0.95)):
assert scored[name] == law.ppf(q) / 5
def test_deviations_use_the_childs_zone_electrodes():
baseline = {"kind": "count_rate", "ages": [16.0, 37.0], "rate": 3.0, "k": None}
model = dict.fromkeys(("value", "electrode_C3", "zone_central"), baseline)
analysis = SimpleNamespace(
age_months=24.0,
metrics=[Metric("paroxysmal_spikes", 6.0, {"C3": 6.0}, {"central": 6.0})],
features={"eeg-spikes": {"minutes": 5.0, "zone_electrodes_central": 2.0}},
)
scored = curves.deviations({"eeg-spikes": model}, analysis)["paroxysmal_spikes"]
assert scored["zones"]["central"] == curves.score(baseline, 6.0, 24.0, 5.0, 2.0)
assert scored["value"] == curves.score(baseline, 6.0, 24.0, 5.0)
assert scored["electrodes"]["C3"] == scored["value"]
+199 -3
View File
@@ -1,16 +1,31 @@
from dataclasses import replace
from types import SimpleNamespace
import numpy as np
import pandas as pd
import pytest
from scipy import signal
from models.tea.eeg import curves, signals
from core.tea.reasons import REJECTED_MINUTES
from models.tea.eeg import (
analysis,
biomarkers,
checks,
curves,
preprocess,
reference,
signals,
sleep,
)
from models.tea.eeg.read import Recording
def test_score_without_value_or_coverage():
table = pd.DataFrame({"value": [1.0, 2.0, 3.0], "age_months": [20.0, 25.0, 30.0]})
baseline = curves.train(table, "eeg-gradient")["value"]
empty = dict.fromkeys(("z", "outside", "p5", "median", "p95"))
assert curves.score(baseline, None, 25.0) == empty
assert curves.score(baseline, 2.0, 25.0) == empty
assert curves.score(baseline, None, 25.0) == {**empty, "reason": None}
assert curves.score(baseline, 2.0, 25.0) == {**empty, "reason": "age-out-of-range"}
def test_dominant_peak_recovers_a_posterior_rhythm_above_background():
@@ -26,3 +41,184 @@ def test_band_power_excludes_line_noise_and_rescales_clean_bins():
frequencies = np.arange(7.0, 14.0)
power = np.array([100.0, 2.0, 30.0, 40.0, 30.0, 4.0, 100.0])
assert signals.band_power(frequencies, power, 8, 13, lines=(10,)) == 15
def _recording(seconds=180, fs=256):
names = ("C3", "Cz", "C4", "O1")
x = np.random.default_rng(7).normal(0, 10, (seconds * fs, len(names)))
return Recording(x, fs, names, (), None, None)
@pytest.mark.parametrize(("flat_count", "keep_flat"), [(1, False), (1, True), (2, True)])
def test_prepare_keeps_only_one_flat_channel_when_requested(monkeypatch, flat_count, keep_flat):
rec = _recording(seconds=20)
rec.x[:, 1 : flat_count + 1] = 0
bad = dict.fromkeys(rec.names[1 : flat_count + 1])
seen = []
def qc(y, fs, start_s):
seen.append(y)
return []
monkeypatch.setattr(preprocess, "window_qc", qc)
prep = preprocess.prepare(rec, bad, 60, keep_flat=keep_flat)
kept = keep_flat and flat_count == 1
names = rec.names if kept else tuple(name for name in rec.names if name not in bad)
assert prep.names == names
assert seen[0].shape[1] == len(rec.names) - flat_count
raw = rec.x[:, [rec.names.index(name) for name in names]]
filtered = signals.bandpass(raw, rec.fs, 0.5, 100)
np.testing.assert_allclose(prep.x, filtered - filtered.mean(axis=1, keepdims=True))
if kept:
assert np.std(prep.data(["Cz"])) > 0.5
@pytest.mark.parametrize("n", [255, 256])
def test_periodograms_match_symmetric_hann_density(n):
fs = 256
segments = np.random.default_rng(1).normal(3, 2, (2, 3, n))
window = np.hanning(n)
transformed = np.fft.rfft((segments - segments.mean(axis=-1, keepdims=True)) * window)
expected = np.abs(transformed) ** 2 / (fs * np.sum(window**2))
for k in range(1, expected.shape[-1]):
if 2 * k != n:
expected[..., k] *= 2
frequencies, power = signals.periodograms(segments, fs)
np.testing.assert_array_equal(frequencies, np.fft.rfftfreq(n, 1 / fs))
np.testing.assert_allclose(power, expected, rtol=1e-14)
def test_prepare_uses_50_hz_mains_and_raw_iir_qc(monkeypatch):
rec = _recording(seconds=40)
t = np.arange(len(rec.x)) / rec.fs
rec.x[:] += np.sin(2 * np.pi * 50 * t)[:, None] * np.array([100, 40, 20, 10])
rec.x[:, 0] += 100 * np.sin(2 * np.pi * 60 * t)
rec.x[:, 0] += 100 * np.sin(2 * np.pi * 100 * t)
seen = []
def qc(y, fs, start_s):
seen.append(y)
return []
monkeypatch.setattr(preprocess, "window_qc", qc)
prep = preprocess.prepare(rec, {}, 50)
f = np.fft.rfftfreq(len(t), 1 / rec.fs)
before = np.abs(np.fft.rfft(rec.x[:, 0]))
after = np.abs(np.fft.rfft(prep.x[:, 0]))
assert after[f == 50] < before[f == 50] * 0.01
assert after[f == 60] > before[f == 60] * 0.5
sos = np.vstack([np.r_[signal.iirnotch(hz, 30, rec.fs)] for hz in (50, 100)])
expected = signal.sosfiltfilt(sos, rec.x, axis=0)
expected = signals.bandpass(expected, rec.fs, 0.5, 45)
np.testing.assert_allclose(seen[0], expected)
def test_stable_start_finds_a_noisy_setup_prefix():
rec = _recording()
rec.x[: 60 * rec.fs] *= 20
assert preprocess.stable_start(rec) == 50.0
def test_stable_start_returns_zero_for_a_clean_record():
assert preprocess.stable_start(_recording()) == 0.0
@pytest.mark.parametrize(
("annotations", "expected"),
[
(((75.0, 0.0, "INÍCIO"),), 75.0),
(((30.0, 0.0, "electrodos"), (65.0, 0.0, "impedancias")), 65.0),
(((90.0, 0.0, "montaje"), (55.0, 0.0, "start recording")), 55.0),
(((20.0, 0.0, "inicio"),), 50.0),
],
)
def test_stable_start_honours_annotations_and_keeps_the_later_start(annotations, expected):
rec = _recording()
rec.x[: 60 * rec.fs] *= 20
assert preprocess.stable_start(replace(rec, annotations=annotations)) == expected
def test_stable_start_returns_zero_with_fewer_than_twelve_finite_windows():
rec = _recording(seconds=120)
rec.x[: 10 * rec.fs] = np.nan
rec = replace(rec, annotations=((80.0, 0.0, "inicio"),))
assert preprocess.stable_start(rec) == 0.0
def test_prepare_marks_every_qc_window_before_start_unclean_and_masks_states():
rec = replace(_recording(), annotations=((45.0, 0.0, "inicio"),))
rec = replace(rec, x=signals.bandpass(rec.x, rec.fs, 0.5, 20))
prep = preprocess.prepare(rec, {}, 60)
assert {(float(t), 4.0) for t in range(0, 45, 4)} <= set(prep.unclean)
labels = sleep.states(prep, [], 24)
assert (labels[prep.starts < 45] == "").all()
assert (labels[prep.starts >= 48] != "").any()
@pytest.mark.parametrize(("seconds", "start_s", "offset_s"), [(80, 20, 20), (50, 20, 0)])
def test_window_qc_finds_fixed_lines_after_start_when_over_thirty_seconds_remain(
monkeypatch, seconds, start_s, offset_s
):
rec = _recording(seconds=seconds)
seen = []
def fixed_lines(y, fs, f_max):
seen.append(y)
return []
monkeypatch.setattr(signals, "fixed_lines", fixed_lines)
checks.window_qc(rec.x, rec.fs, start_s)
np.testing.assert_array_equal(seen[0], rec.x[offset_s * rec.fs :])
def test_sleep_features_apply_clamps_to_unscaled_fft_power():
rec = _recording(seconds=4)
rec.x[:] *= 1e-9
prep = preprocess.Prepared(rec.x, rec.names, rec.fs, np.array([0.0]), (), ())
starts, features = sleep._features(prep, np.zeros(len(rec.x), bool))
x = rec.x.T
f = np.fft.rfftfreq(len(x.T), 1 / rec.fs)
power = np.abs(np.fft.rfft((x - x.mean(axis=-1, keepdims=True)) * np.hanning(len(x.T)))) ** 2
band = {b: power[..., (f >= lo) & (f < hi)].sum(axis=-1) for b, (lo, hi) in sleep.BANDS.items()}
ratio = np.median(band["delta"] / np.maximum(band["beta"], 1e-12))
assert starts == [0]
np.testing.assert_allclose(features["delta_beta"], [np.log10(max(ratio, 1e-6))])
@pytest.mark.parametrize("keep_flat", [False, True])
def test_analysis_passes_mains_and_flat_option_and_reports_start(monkeypatch, keep_flat):
rec = replace(_recording(), annotations=((42.0, 0.0, "inicio"),))
monkeypatch.setattr(analysis.read, "read", lambda _: rec)
verdict = SimpleNamespace(
valid=True, level="complete", reasons=[], clean_pct=100, bad={}, line_db=0, checks=[]
)
monkeypatch.setattr(checks, "validate", lambda rec, mains_hz: verdict)
prepare = preprocess.prepare
seen = []
def prepared(rec, bad, mains_hz, keep_flat=False):
seen.append((mains_hz, keep_flat))
return prepare(rec, bad, mains_hz, keep_flat=keep_flat)
monkeypatch.setattr(preprocess, "prepare", prepared)
monkeypatch.setattr(biomarkers, "measure", lambda *args: biomarkers.Measured({}, {}, {}, {}))
options = {"keep_flat": True} if keep_flat else {}
found = analysis.analyze(b"synthetic", age_months=24, mains_hz=50, **options)
assert found.error is None
assert seen == [(50, keep_flat)]
assert found.features[REJECTED_MINUTES]["start_s"] == 42.0
def test_reference_enables_flat_reference_electrode(monkeypatch, tmp_path):
path = tmp_path / "synthetic.edf"
path.write_bytes(b"synthetic")
seen = []
def analyze(edf, **options):
seen.append((edf, options))
return SimpleNamespace(valid=True, error=None, features={})
monkeypatch.setattr(reference, "analyze", analyze)
result = reference._one(("study", path, 24, 50))
assert result["valid"] is True
assert seen == [(b"synthetic", {"age_months": 24, "mains_hz": 50, "keep_flat": True})]
+163
View File
@@ -0,0 +1,163 @@
from dataclasses import replace
import numpy as np
import pandas as pd
import pytest
from edf_files import small_edf
from core.tea.reasons import METRIC_REASONS, REJECTED_MINUTES
from models.tea.eeg import biomarkers, curves, spikes
from models.tea.eeg.analysis import analyze
from models.tea.eeg.preprocess import STEP_S, WINDOW_S, Prepared
from models.tea.eeg.spindles import CHANNELS
FS = 128
SCALP = tuple(biomarkers.FRONT_BACK)
POSTERIOR = ("O1", "O2", "P3", "P4")
def smooth(t: np.ndarray, channels: int, rng) -> np.ndarray:
f = np.arange(0.5, 40.0, 0.25)
phase = rng.uniform(0, 2 * np.pi, (len(f), channels))
wave = np.sin(2 * np.pi * np.outer(t, f)[:, :, None] + phase[None])
return (wave / f[None, :, None]).sum(axis=1) * 100
def prepared(names=SCALP, seconds=70, rhythm=None, seed=0, flat=False) -> Prepared:
rng = np.random.default_rng(seed)
t = np.arange(seconds * FS) / FS
x = smooth(t, len(names), rng) if flat else rng.normal(0, 10, (len(t), len(names)))
for k, name in enumerate(names):
if rhythm and name in POSTERIOR:
x[:, k] += 40 * np.sin(2 * np.pi * rhythm * t)
starts = np.arange(0.0, seconds - WINDOW_S + 1e-9, STEP_S)
return Prepared(np.asfortranarray(x), tuple(names), FS, starts, (), ())
def states(prep: Prepared, state: str, count: int | None = None) -> np.ndarray:
out = np.full(len(prep.starts), "", dtype=object)
out[:count] = state
return out
def test_posterior_rhythm_without_enough_wake_windows():
prep = prepared(rhythm=10.0)
value, reason = biomarkers.posterior_rhythm(prep, states(prep, "wake", 14))
assert np.isnan(value)
assert reason == "few-wake-windows"
def test_posterior_rhythm_without_a_dominant_peak():
prep = prepared(names=("Fp1", "Fp2", "O1", "O2"), flat=True)
value, reason = biomarkers.posterior_rhythm(prep, states(prep, "wake"))
assert np.isnan(value)
assert reason == "no-dominant-peak"
only_frontal = prepared(names=("Fp1", "Fp2", "F3"))
assert biomarkers.posterior_rhythm(only_frontal, states(only_frontal, "wake"))[1] == (
"no-dominant-peak"
)
def test_posterior_rhythm_measured_has_no_reason():
prep = prepared(rhythm=10.0)
value, reason = biomarkers.posterior_rhythm(prep, states(prep, "wake"))
assert value == pytest.approx(10.0, abs=0.5)
assert reason is None
def test_gradient_without_sleep():
prep = prepared()
assert biomarkers.delta_gradient(prep, states(prep, "wake"))[1] == "no-sleep"
assert biomarkers.delta_gradient(prep, states(prep, "sleep", 14))[1] == "no-sleep"
def test_gradient_with_few_electrodes():
prep = prepared(names=("Fp1", "Fp2", "F3", "Fz", "C3"))
value, reason = biomarkers.delta_gradient(prep, states(prep, "sleep"))
assert np.isnan(value)
assert reason == "few-electrodes"
def test_gradient_measured_has_no_reason():
prep = prepared()
value, reason = biomarkers.delta_gradient(prep, states(prep, "sleep"))
assert np.isfinite(value)
assert reason is None
def test_wake_only_recording_has_no_sleep_reasons():
prep = prepared(rhythm=10.0)
measured = biomarkers.measure(prep, states(prep, "wake"), [])
assert measured.reasons == {
"spindles": "no-sleep",
"paroxysmal_spikes": "no-sleep",
"anteroposterior_gradient": "no-sleep",
}
assert set(measured.metrics) == set(biomarkers.CODES)
def test_spikes_with_few_electrodes():
prep = prepared(names=("Fp1", "Fp2", "Cz"))
measured = biomarkers.measure(prep, states(prep, "sleep"), [])
assert measured.reasons["paroxysmal_spikes"] == "few-electrodes"
assert measured.rejected == {}
def test_spindles_without_enough_sleep_minutes():
prep = prepared()
measured = biomarkers.measure(prep, states(prep, "sleep", 10), [])
assert measured.reasons["spindles"] == "no-sleep"
def test_sleep_without_spindles():
prep = prepared()
silent = replace(prep, x=np.zeros_like(prep.x))
measured = biomarkers.measure(silent, states(silent, "sleep"), [])
assert measured.reasons["spindles"] == "no-spindles"
def test_gate_rejects_windows_by_reason_in_minutes():
prep = prepared(names=CHANNELS[:6], seconds=20, flat=True)
x = np.array(prep.x)
x[: 2 * FS] = np.nan
x[2 * FS : 4 * FS] = 1.0
kept, rejected = spikes._gate(x, FS, [(0.0, 20.0, "crying")])
assert kept == []
assert rejected["gap"] == pytest.approx(2 / 60, abs=1e-4)
assert rejected["frozen"] == pytest.approx(2 / 60, abs=1e-4)
assert rejected["state"] == pytest.approx(18 / 60, abs=1e-4)
clean, none = spikes._gate(np.array(prep.x), FS, [(0.0, 20.0, "sleep")])
assert len(clean) == 10
assert none == {}
def test_score_reasons():
table = {"value": [1.0, 2.0, 3.0], "age_months": [20.0, 25.0, 30.0]}
baseline = curves.train(pd.DataFrame(table), "eeg-gradient")["value"]
assert curves.score(baseline, None, 25.0)["reason"] is None
assert curves.score(baseline, 2.0, None)["reason"] == "no-age"
assert curves.score(baseline, 2.0, 25.0)["reason"] == "age-out-of-range"
rate = {"kind": "count_rate", "ages": [16.0, 37.0], "rate": 1.0, "k": None}
assert curves.score(rate, 1.0, 40.0, 5.0)["reason"] == "age-out-of-range"
assert curves.score(rate, 1.0, 20.0, None)["reason"] == "no-exposure"
assert curves.score(rate, 1.0, 20.0, 0.0)["reason"] == "no-exposure"
measured = curves.score(rate, 1.0, 20.0, 5.0)
assert measured["reason"] is None
assert measured["z"] is not None
def test_invalid_study_carries_the_reasons_on_every_metric(tmp_path):
found = analyze(small_edf(tmp_path / "small.edf", seconds=60))
assert found.valid is False
assert "few-electrodes" in found.reasons
assert [m.code for m in found.metrics] == list(biomarkers.CODES)
assert all(m.value is None for m in found.metrics)
assert found.features[METRIC_REASONS] == dict.fromkeys(biomarkers.CODES, "invalid-eeg")
assert found.features[REJECTED_MINUTES] == {}
def test_a_file_that_is_not_an_edf_is_invalid_with_its_reason():
found = analyze(b"not an edf")
assert found.valid is False
assert found.reasons == ["invalid-file"]
assert found.features[METRIC_REASONS] == dict.fromkeys(biomarkers.CODES, "invalid-eeg")
+127
View File
@@ -0,0 +1,127 @@
import numpy as np
import pytest
from models.tea.eeg import biomarkers, spikes
from models.tea.eeg.preprocess import Prepared
def test_inheritance_reaches_thirty_seconds_from_the_last_labelled_grid_point():
grid = spikes._states([(10.0, 14.0, "sleep")], 50.0)
assert (grid[:20] == "unlabelled").all()
assert (grid[20:88] == "sleep").all()
assert (grid[88:] == "unlabelled").all()
assert grid[87] == "sleep"
assert grid[88] == "unlabelled"
def test_transition_between_different_labels_counts_in_neither_state():
grid = spikes._states([(2.0, 6.0, "wake"), (12.0, 16.0, "sleep")], 18.0)
assert (grid[:4] == "unlabelled").all()
assert (grid[4:12] == "wake").all()
assert (grid[12:24] == "transition").all()
assert (grid[24:] == "sleep").all()
def test_matching_labels_inherit_from_either_side_with_no_state_beyond_reach():
grid = spikes._states([(0.0, 4.0, "sleep"), (80.0, 84.0, "sleep")], 85.0)
assert grid[67] == "sleep"
assert (grid[68:100] == "unlabelled").all()
assert grid[100] == "sleep"
def test_direct_windows_keep_the_first_label_and_empty_windows_have_no_state():
grid = spikes._states([(4.0, 8.0, "wake"), (6.0, 10.0, "sleep")], 12.0)
assert (grid[8:16] == "wake").all()
assert (grid[16:] == "sleep").all()
assert (spikes._states([], 12.0) == "unlabelled").all()
assert spikes._states([], 0.0).size == 0
def prepared(starts, seconds=90, names=("C3", "Cz", "P3", "P4")):
return Prepared(np.zeros((seconds * 128, len(names))), names, 128, np.array(starts), (), ())
def test_gate_minutes_and_candidates_use_the_grid_state(monkeypatch):
prep = prepared([10.0, 30.0, 50.0])
gate = [(float(t), float(t + 2)) for t in range(0, 90, 2)]
monkeypatch.setattr(spikes, "_gate", lambda *args: (gate, {}))
def candidates(x, fs, channel):
return [
dict(
channel=channel,
t=t,
sign=1,
width=50.0,
size=5.0 if channel == "C3" else 4.0,
post=0.0,
)
for t in (9.5, 10.1, 20.1, 30.1, 40.1, 50.1, 60.1, 83.75, 84.1)
if channel in ("C3", "Cz")
]
monkeypatch.setattr(spikes, "_candidates", candidates)
found = spikes.detect(prep, np.array(["wake", "drowsy", "sleep"]), [])
assert found.minutes == pytest.approx(34 / 60, abs=1e-4)
assert found.awake_minutes == pytest.approx(8 / 60, abs=1e-4)
assert found.rate == pytest.approx(round(3 / (34 / 60), 3))
assert found.awake_rate == 15.0
assert found.electrodes["C3"] == pytest.approx(round(3 / (34 / 60), 4))
assert found.zones["central"] == found.electrodes["C3"]
assert found.zone_electrodes["central"] == 2
assert found.zone_electrodes["frontal_left"] == 0
def test_gate_minutes_follow_the_midpoint_even_when_a_window_crosses_labels(monkeypatch):
prep = prepared([1.5], seconds=8)
monkeypatch.setattr(spikes, "_gate", lambda *args: ([(0.0, 2.0), (2.0, 4.0)], {}))
monkeypatch.setattr(spikes, "_candidates", lambda *args: [])
found = spikes.detect(prep, np.array(["sleep"]), [])
assert found.minutes == pytest.approx(2 / 60, abs=1e-4)
assert found.rate == 0.0
assert found.awake_minutes == 0.0
assert np.isnan(found.awake_rate)
@pytest.mark.parametrize("state", ["wake", "drowsy"])
def test_awake_rates_include_direct_and_inherited_discharges(monkeypatch, state):
prep = prepared([0.0], seconds=8)
monkeypatch.setattr(
spikes, "_gate", lambda *args: ([(0.0, 2.0), (2.0, 4.0), (4.0, 6.0), (6.0, 8.0)], {})
)
def candidates(x, fs, channel):
return [
dict(channel=channel, t=t, sign=1, width=50.0, size=5.0, post=0.0)
for t in (1.0, 7.0)
if channel in ("C3", "Cz")
]
monkeypatch.setattr(spikes, "_candidates", candidates)
found = spikes.detect(prep, np.array([state]), [])
assert found.awake_minutes == pytest.approx(8 / 60, abs=1e-4)
assert found.awake_rate == 15.0
assert found.minutes == 0.0
assert np.isnan(found.rate)
def test_biomarker_features_include_awake_rates_and_present_zone_electrodes(monkeypatch):
prep = prepared([0.0], seconds=8)
monkeypatch.setattr(spikes, "_gate", lambda *args: ([(0.0, 2.0)], {}))
monkeypatch.setattr(spikes, "_candidates", lambda *args: [])
measured = biomarkers.measure(prep, np.array(["wake"]), [])
features = measured.features["eeg-spikes"]
assert features["awake_rate"] == 0.0
assert features["awake_minutes"] == pytest.approx(2 / 60, abs=1e-4)
assert features["zone_electrodes_central"] == 2
assert features["zone_electrodes_parietal"] == 2
assert set(measured.metrics) == set(biomarkers.CODES)
def test_few_electrodes_still_reports_present_zone_electrodes():
prep = prepared([0.0], seconds=8, names=("C3", "Cz"))
measured = biomarkers.measure(prep, np.array(["sleep"]), [])
assert measured.reasons["paroxysmal_spikes"] == "few-electrodes"
assert measured.features["eeg-spikes"]["zone_electrodes_central"] == 2
assert measured.features["eeg-spikes"]["awake_minutes"] == 0.0
assert np.isnan(measured.features["eeg-spikes"]["awake_rate"])
+79
View File
@@ -0,0 +1,79 @@
import numpy as np
import pandas as pd
import pytest
from models.tea.eeg import biomarkers, curves, spindles
from models.tea.eeg.preprocess import STEP_S, WINDOW_S, Prepared
FS = 128
QUIET = (0, 60)
LOUD = (80, 200)
QUIET_BURST = 30
LOUD_BURST = 140
def recording(x: np.ndarray, names) -> Prepared:
starts = np.arange(0.0, len(x) / FS - WINDOW_S + 1e-9, STEP_S)
return Prepared(np.asfortranarray(x), tuple(names), FS, starts, (), ())
def asleep_in(prep: Prepared, *stretches) -> np.ndarray:
inside = [any(a <= s and s + WINDOW_S <= b for a, b in stretches) for s in prep.starts]
return np.where(inside, "sleep", "wake").astype(object)
def two_sigma_levels() -> Prepared:
t = np.arange((LOUD[1] + 20) * FS) / FS
amplitude = np.where((t >= LOUD[0] - 10) & (t < LOUD[1] + 10), 20.0, 2.0)
for onset, extra in ((QUIET_BURST, 20.0), (LOUD_BURST, 130.0)):
amplitude[(t >= onset) & (t < onset + 1)] += extra
noise = np.random.default_rng(0).normal(0, 0.5, len(t))
return recording((amplitude * np.sin(2 * np.pi * 13 * t) + noise)[:, None], ["C3"])
def test_thresholds_come_from_all_sleep_samples(monkeypatch):
prep = two_sigma_levels()
seen = []
segments = spindles._segments
def spy(core, extent, fs):
seen.append((core, extent))
return segments(core, extent, fs)
monkeypatch.setattr(spindles, "_segments", spy)
found = spindles.detect(prep, asleep_in(prep, QUIET, LOUD))
t = np.arange(len(prep.x)) / FS
asleep = (t < QUIET[1]) | ((t >= LOUD[0]) & (t < LOUD[1]))
envelope = spindles._envelope(prep.data(["C3"]), FS)[1][:, 0]
values = envelope[asleep]
median = np.median(values)
core = max(np.percentile(values, 95), 3 * median)
extent = max(np.percentile(values, 70), 1.6 * median)
assert np.array_equal(seen[0][0], asleep & (envelope > core))
assert np.array_equal(seen[0][1], asleep & (envelope > extent))
assert found.minutes == pytest.approx(3.0)
assert [round(onset) for onset, _, _ in found.events] == [LOUD_BURST]
alone = spindles.detect(prep, asleep_in(prep, QUIET))
assert [round(onset) for onset, _, _ in alone.events] == [QUIET_BURST]
@pytest.mark.parametrize(("rhythm", "near"), [(10.0, 1.0), (8.0, 0.0)])
def test_posterior_rhythm_near_sigma_is_flagged(rhythm, near):
names = ("O1", "O2", "P3", "P4", "C3", "C4")
t = np.arange(70 * FS) / FS
x = np.random.default_rng(0).normal(0, 5, (len(t), len(names)))
x[:, :4] += 40 * np.sin(2 * np.pi * rhythm * t)[:, None]
prep = recording(x, names)
awake = biomarkers.measure(prep, asleep_in(prep), [])
assert awake.features["eeg-spindles"]["rhythm_near_sigma"] == near
asleep = biomarkers.measure(prep, asleep_in(prep, (0, 70)), [])
assert asleep.features["eeg-spindles"]["rhythm_near_sigma"] == 0.0
def test_training_ignores_the_rhythm_flag():
table = pd.DataFrame(
{"value": [1.0, 2.0], "rhythm_near_sigma": [0.0, 1.0], "age_months": [20.0, 30.0]}
)
assert list(curves.train(table, "eeg-spindles")) == ["value"]
+245 -11
View File
@@ -1,9 +1,14 @@
import json
import numpy as np
import pandas as pd
import pytest
from core.tea import ADOS2_ITEMS
from models.tea import association as a
KEYS = ["key", "biomarker", "zone", "outcome_code"]
def test_firth_on_separation():
frame = pd.DataFrame({"z": np.arange(12), "event": [0] * 6 + [1] * 6})
@@ -21,21 +26,250 @@ def test_ordinal_on_monotone_trend():
assert a.ordinal(frame, "level", "z", (), high=2)["odds_ratio"] > 1
def test_pairs_and_item_availability():
assert len(a.pairs("item")) == 41
assert len(a.pairs("domain")) == 15
assert ADOS2_ITEMS == [
"vocalization_directed", "pointing", "gestures", "unusual_eye_contact",
"facial_expressions", "gaze_integration", "shared_enjoyment", "response_to_name",
"ignoring", "requesting", "showing", "joint_attention_initiation",
"joint_attention_response", "social_overtures_quality", "social_overtures_caregiver",
"reciprocal_communication", "rapport_quality", "intonation", "stereotyped_language",
"unusual_sensory_interest", "hand_finger_mannerisms", "repetitive_interests",
] # fmt: skip
def test_ordinal_separated_binary_predictor():
frame = pd.DataFrame({"z": [0] * 8 + [1] * 8, "level": [0, 1] * 4 + [3, 4] * 4})
fit = a.ordinal(frame, "level", "z", (), high=3)
assert fit["reason"] == "does not converge (separation)"
def test_pairs_by_level():
item = a.pairs("item")
spikes = [p for p in item if p["biomarker"] == "spikes"]
assert [(p["zone"], p["kind"], a.outcome_code(p)) for p in spikes] == [
("any", "domain", "CSS"),
("left", "composite", "ados2_items_01_18"),
("right", "composite", "ados2_items_04_05_07"),
("central", "exploratory", "ados2_item_21"),
]
assert len(item) == 12
domain = a.pairs("domain")
assert [p["zone"] for p in domain if p["biomarker"] == "spikes"] == ["any"]
assert len(domain) == 8
def test_item_scores_follow_the_algorithm_and_the_module():
assert ADOS2_ITEMS[0] == "vocalization_directed"
assert ADOS2_ITEMS[20] == "hand_finger_mannerisms"
frame = pd.DataFrame(
{
"ados_module": ["toddler", "module_1", "module_2", "module_3"],
"vocalization_directed": [3, 7, 1, 1],
"unusual_eye_contact": [1, 1, 1, 1],
}
)
np.testing.assert_allclose(a.item_scores(frame, 1), [2, 0, np.nan, np.nan])
np.testing.assert_allclose(a.item_scores(frame, 4), [2, 1, 1, np.nan])
def test_spikes_any_from_the_electrode_rates():
rates = {f"electrode_{e}": 0.0 for zone in a.ZONES.values() for e in zone}
found = a.spikes_any({**rates, "minutes": 20.0, "electrode_T3": 0.05})
assert found == {
"spikes_any_any": 1,
"spikes_any_left": 1,
"spikes_any_right": 0,
"spikes_any_central": 0,
}
unmeasured = {**rates, "minutes": 20.0, "electrode_C3": None, "electrode_C4": None}
assert a.spikes_any(unmeasured)["spikes_any_central"] == 0
assert np.isnan(a.spikes_any({**unmeasured, "electrode_Cz": None})["spikes_any_central"])
for features in ({**rates, "minutes": 0.0}, {**rates, "minutes": None}, {}):
assert all(np.isnan(v) for v in a.spikes_any(features).values())
def _domain_cohort(n_toddler=60, n_other=8, seed=3):
rng = np.random.default_rng(seed)
n = n_toddler + n_other
z = rng.normal(0, 1.2, n)
return pd.DataFrame(
{
"key": [f"k{i}" for i in range(n)],
"age_months": rng.uniform(16, 36, n).round(1),
"ados_module": ["toddler"] * n_toddler
+ ["module_1"] * (n_other // 2)
+ ["module_2"] * (n_other - n_other // 2),
"css": np.clip(np.round(6 + 1.3 * z + rng.normal(0, 1.2, n)), 1, 10),
"z_gradient": z,
"z_spindles_central": rng.normal(0, 1, n),
"spikes_any_any": (z > 0).astype(float),
}
)
@pytest.fixture(scope="module")
def fitted():
cohort = _domain_cohort()
return cohort, a.Ados2Association(level="domain").fit(cohort)
def test_one_css_family_for_every_module(fitted):
_, model = fitted
found = model.associations()
gradient = found[found.biomarker == "gradient"]
assert list(gradient.outcome_code) == ["CSS"]
assert gradient.n.iloc[0] == 68
assert gradient.odds_ratio.iloc[0] > 1
assert gradient.model.iloc[0] == "ordinal"
assert set(found.event) == {">=8"}
assert found[found.biomarker == "spikes"].q.notna().all()
assert model.fitted["css_sources"] == {"computed": 68}
assert model.fitted["settings"] == {
"item_altered": 2,
"css_high": 8,
"min_events": 5,
"q_family": "biomarker",
"clip_z": 0,
}
assert model.fitted["pairs"] == a.pairs("domain")
def test_few_events_are_fitted_and_flagged():
cohort = _domain_cohort()
cohort["css"] = np.where(cohort.index < 3, 9.0, 4.0 + cohort.index % 3)
found = a.Ados2Association(level="domain").fit(cohort).associations()
gradient = found[found.biomarker == "gradient"].iloc[0]
assert np.isfinite(gradient.odds_ratio)
assert gradient.reason == "datos insuficientes: 3 con evento y 65 sin evento (minimo 5)"
def test_leave_one_out(fitted):
cohort, model = fitted
both = model.score(cohort).merge(
model.score(cohort, leave_one_out=False), on=KEYS, suffixes=("_out", "_in")
)
assert len(both) and np.isfinite(both.probability_out).all()
assert (both.probability_out != both.probability_in).any()
def test_a_new_child_gets_the_full_model(fitted):
cohort, model = fitted
new = cohort.iloc[[0]].assign(key="new")
left_out, full = model.score(new), model.score(new, leave_one_out=False)
assert len(full)
np.testing.assert_allclose(left_out.probability, full.probability)
def test_every_study_of_a_fitted_child_is_scored_without_the_child():
cohort = _domain_cohort().assign(child=lambda t: t.key)
model = a.Ados2Association(level="domain").fit(cohort)
again = cohort.iloc[[0]].assign(key="later")
scored = model.score(pd.concat([cohort, again], ignore_index=True))
first, later = (
scored[scored.key == key].set_index(["biomarker", "zone"]).probability
for key in ("k0", "later")
)
pd.testing.assert_series_equal(first, later)
alone = model.score(again).set_index(["biomarker", "zone"]).probability
assert (later != alone).any()
def test_the_saved_model_lists_no_keys(fitted, tmp_path):
cohort, model = fitted
model.save(tmp_path)
text = (tmp_path / "association.json").read_text()
assert not any(f'"{key}"' in text for key in cohort.key)
keys = json.loads(text)["fitted"]["keys"]
assert len(keys) == len(cohort)
assert all(len(key) == 16 for key in keys)
loaded = a.Ados2Association.load(tmp_path)
pd.testing.assert_frame_equal(loaded.score(cohort), model.score(cohort))
@pytest.mark.parametrize("missing", ["settings", "pairs"])
def test_an_old_saved_model_is_refused(fitted, tmp_path, missing):
_, model = fitted
old = {k: v for k, v in model.fitted.items() if k != missing}
(tmp_path / "association.json").write_text(json.dumps({"level": "domain", "fitted": old}))
with pytest.raises(ValueError, match="retrain"):
a.Ados2Association.load(tmp_path)
with pytest.raises(ValueError, match="retrain"):
a.Model(old).predict(None, pd.DataFrame())
def test_clipping_leaves_the_scored_z(monkeypatch):
monkeypatch.setattr(a, "CLIP_Z", 3)
cohort = _domain_cohort()
cohort.loc[0, "z_gradient"] = 9.0
model = a.Ados2Association(level="domain").fit(cohort)
scored = model.score(cohort)
assert scored.loc[(scored.key == "k0") & (scored.biomarker == "gradient"), "z"].item() == 9.0
def _item_cohort(n=60, seed=5):
rng = np.random.default_rng(seed)
spikes = (rng.random(n) < 0.5).astype(float)
cohort = pd.DataFrame(
{
"key": [f"k{i}" for i in range(n)],
"age_months": rng.uniform(16, 36, n).round(1),
"ados_module": ["toddler", "module_1", "module_2"] * (n // 3),
"css": rng.integers(4, 11, n).astype(float),
"spikes_any_any": spikes,
"spikes_any_left": spikes,
"spikes_any_right": spikes,
"spikes_any_central": spikes,
}
)
for item in (1, 4, 5, 7, 18, 21):
cohort[ADOS2_ITEMS[item - 1]] = rng.choice([0, 1, 2], n, p=[0.5, 0.25, 0.25])
return cohort
def _spike_rows(model):
found = model.associations()
return found[found.biomarker == "spikes"].set_index("zone")
def test_composites_and_the_exploratory_pair():
cohort = _item_cohort()
model = a.Ados2Association().fit(cohort)
found = _spike_rows(model)
assert list(found.index) == ["any", "left", "right", "central"]
assert found.n.to_dict() == {"any": 60, "left": 40, "right": 60, "central": 60}
assert found.event.to_dict() == {
"any": ">=8",
"left": "alguno >=2",
"right": "alguno >=2",
"central": ">=2",
}
assert list(found.loc[["left", "right", "central"]].model) == ["firth"] * 3
assert list(found.loc[["left", "right", "central"]].sens_model) == ["ordinal"] * 3
assert found.outcome["left"] == [1, 18]
assert found.kind["central"] == "exploratory"
assert np.isfinite(found.odds_ratio["central"])
assert np.isnan(found.q["central"])
tested = found.loc[["any", "left", "right"]]
np.testing.assert_allclose(tested.q.to_numpy(float), a.bh(tested.p).round(5))
scored = model.score(cohort)
left = scored[scored.outcome_code == "ados2_items_01_18"]
assert set(cohort.ados_module[cohort.key.isin(left.key)]) == {"toddler", "module_1"}
assert set(scored.z[scored.biomarker == "spikes"]) == {0.0, 1.0}
def test_a_composite_event_is_any_of_its_items_altered():
cohort = _item_cohort()
scores = pd.concat([a.item_scores(cohort, n) for n in (4, 5, 7)], axis=1)
pair = next(p for p in a.pairs("item") if p["zone"] == "right")
settings = a.Ados2Association().fit(cohort).fitted["settings"]
event, count = a._outcome(cohort, pair, settings)
np.testing.assert_allclose(event, (scores == 2).any(axis=1))
np.testing.assert_allclose(count, (scores == 2).sum(axis=1))
def test_a_composite_with_a_small_group_counts_the_altered_items():
cohort = _item_cohort()
rng = np.random.default_rng(11)
cohort["facial_expressions"] = 2
cohort["unusual_eye_contact"] = rng.choice([0, 2], len(cohort))
cohort["shared_enjoyment"] = rng.choice([0, 2], len(cohort))
model = a.Ados2Association().fit(cohort)
found = _spike_rows(model).loc["right"]
assert (found.model, found.sens_model, found.event) == ("ordinal", "firth", "alguno >=2")
assert found.reason == (
"datos insuficientes: 60 con evento y 0 sin evento (minimo 5); "
"se usa el numero de reactivos alterados"
)
scored = model.score(cohort)
right = scored[scored.zone == "right"]
assert (right.probability == 1).all()
assert (right.reference_probability == 1).all()
+92
View File
@@ -1,10 +1,17 @@
import json
from datetime import date
from types import SimpleNamespace
import dagster as dg
import pandas as pd
import pytest
from pydantic import ValidationError
from core.tea import ADOS2_ITEMS
from models.definitions import ScopeConfig, after_ingest
from models.tea import jobs
from models.tea.eeg import curves
from models.tea.jobs import ASSOCIATION, JOBS, MODELS
from persistance import eeg
@@ -36,6 +43,42 @@ def test_scope_validation():
ScopeConfig(mode="first_n").model()
def test_the_domain_routine_scores_the_curves_then_relates_the_association():
assert JOBS.routine() == [*MODELS, ASSOCIATION]
def test_the_association_cohort_takes_spikes_as_yes_or_no(monkeypatch):
def study(child, day, features):
return {
**dict.fromkeys(ADOS2_ITEMS),
"person_id": child,
"study_date": day,
"edf": f"{child}-{day}",
"age_months": 24.0,
"module": "toddler",
"evaluation_date": None,
"birth_date": None,
"language_level": None,
"features": json.dumps(features),
}
spikes = {"eeg-spikes": {"minutes": 10.0, "electrode_F8": 0.2, "electrode_C3": 0.0}}
studies = [study("one", "2025-01-01", spikes), study("two", "2025-01-01", {})]
scores = [
{"edf": "one-2025-01-01", "metric": metric, "part": "zones", "site": "central", "z": 1.5}
for metric in ("paroxysmal_spikes", "spindles")
]
monkeypatch.setattr(eeg, "association_cohort_rows", lambda: (studies, scores))
fit, scored = jobs.cohort()
assert list(fit.child) == ["one"]
assert list(scored.child) == ["one", "two"]
assert [c for c in scored.columns if c.startswith("z_")] == ["z_spindles_central"]
found = fit.iloc[0]
assert (found.spikes_any_any, found.spikes_any_right, found.spikes_any_central) == (1, 1, 0)
assert pd.isna(found.spikes_any_left)
assert scored.iloc[1].filter(like="spikes_any_").isna().all()
def test_after_ingest_requests_a_run_only_with_pending_eegs():
skip = after_ingest("r1", lambda: False)
assert isinstance(skip, dg.SkipReason)
@@ -75,3 +118,52 @@ def test_tea_eeg_first_n_selects_exactly_n_pending_studies(fresh_platform):
]
with pytest.raises(LookupError, match="has no signal"):
eeg.select(eeg.Scope(mode="ids", ids=["p1|2025-05-01"]))
@pytest.mark.parametrize("electrodes", [None, 2.0])
def test_baseline_predict_accepts_optional_electrode_counts(electrodes):
baseline = {"kind": "count_rate", "ages": [16.0, 37.0], "rate": 3.0, "k": None}
model = jobs.Baseline("eeg-spikes", {"zone_central": baseline})
row = {"value": 6.0, "age_months": 24.0, "exposure": 5.0}
rows = [row, {**row, "electrodes": electrodes}]
scored = model.predict(None, pd.DataFrame(rows), {"feature": "zone_central"})
assert scored.to_dict("records") == [
curves.score(baseline, 6.0, 24.0, 5.0),
curves.score(baseline, 6.0, 24.0, 5.0, electrodes),
]
def test_saved_study_scoring_uses_the_childs_present_zone_electrodes(monkeypatch):
baseline = {"kind": "count_rate", "ages": [16.0, 37.0], "rate": 3.0, "k": None}
model = jobs.Baseline(
"eeg-spikes", dict.fromkeys(("value", "electrode_C3", "zone_central"), baseline)
)
champion = SimpleNamespace(unwrap_python_model=lambda: model)
monkeypatch.setattr(jobs.registry, "champion", lambda name: (1, champion))
monkeypatch.setattr(
eeg,
"analysed",
lambda: [
{
"edf": "child",
"age_months": 24.0,
"features": {"eeg-spikes": {"minutes": 5.0, "zone_electrodes_central": 2.0}},
"metrics": [
{
"code": "paroxysmal_spikes",
"value": 6.0,
"electrodes": {"C3": 6.0},
"zones": {"central": 6.0},
}
],
}
],
)
saved = []
monkeypatch.setattr(eeg, "save_scores", lambda name, rows: saved.extend(rows))
assert jobs.score("eeg-spikes") == 1
assert len(saved) == 3
for row in saved:
electrodes = 2.0 if row["part"] == "zones" else None
expected = curves.score(baseline, 6.0, 24.0, 5.0, electrodes)
assert {field: row[field] for field in expected} == expected
+60
View File
@@ -0,0 +1,60 @@
import pytest
from models.tea.eeg.sleep import note_intervals, note_state
VERDADEROS = [
("Ojos cerrados", "eyes_closed"),
("OC", "eyes_closed"),
("oc 10 s", "eyes_closed"),
("Cierra los ojos", "eyes_closed"),
("Eyes closed", "eyes_closed"),
("Ojos abiertos", "eyes_open"),
("OA", "eyes_open"),
("Sueño", "sleep"),
("SUEÑO", "sleep"),
("dormida", "sleep"),
("Fase II", "sleep"),
("N2", "sleep"),
("Asleep", "sleep"),
("Fótica 6 Hz", "photic"),
("Photic 12 Hz", "photic"),
("HV", "hyperventilation"),
("Hiperventilación", "hyperventilation"),
("Despierto", "awake"),
("Llora", "crying"),
("Movimiento", "movement"),
("Biberón", "feeding"),
("come", "feeding"),
]
FALSOS = [
"foco",
"Boca abierta",
"Mov. local",
"Doctor",
"Toalla",
"comentario del técnico",
"Recolocar electrodo",
"Photic: Off",
"Fin de fótica",
]
@pytest.mark.parametrize("texto, estado", VERDADEROS)
def test_estado_reconocido(texto, estado):
assert note_state(texto) == estado
@pytest.mark.parametrize("texto", FALSOS)
def test_sin_falso_positivo(texto):
assert note_state(texto) is None
def test_intervalos_no_abren_estado_con_nota_de_cierre():
notas = [
(0.0, 0.0, "Photic 6 Hz"),
(20.0, 0.0, "Photic: Off"),
(100.0, 0.0, "foco"),
]
iv = note_intervals(notas, 300.0)
assert [state for _, _, state in iv] == ["photic", "unmarked"]
assert iv[0][0] + iv[0][1] == 60.0
+36
View File
@@ -1,9 +1,12 @@
import hashlib
import os
from datetime import date
from types import SimpleNamespace
import pytest
from dagster import build_op_context
from core.pipeline import Extract
from models.definitions import Preview, preview_study
from models.tea import preview as study
from persistance import config, previews
@@ -59,3 +62,36 @@ def test_the_job_deletes_its_files_when_the_study_fails(preview_area):
with build_op_context() as context, pytest.raises(LookupError, match="no preview file"):
preview_study(context, Preview(edf="0" * 64, ados2=report))
assert list(preview_area.iterdir()) == []
@pytest.mark.parametrize("language, css", [(3, 1), (1, 2)])
def test_ados2_preview_reads_language_level_and_scores_its_column(monkeypatch, language, css):
node = Extract(
id="ados2",
column="text",
entity="ados2",
patterns={
"module": r"Módulo (module_1)",
"language_level": r"A-1 (\d)",
"vocalization_directed": r"A-2 (\d)",
"intonation": r"A-3 (\d)",
"stereotyped_language": r"A-5 (\d)",
},
)
monkeypatch.setattr(
study.graph,
"read_file",
lambda _: {
"text": f"Módulo module_1\nA-1 {language}\nA-2 2\nA-3 3\nA-5 3",
"error": None,
},
)
monkeypatch.setattr(study.config_log, "get", lambda _: (1, SimpleNamespace(nodes=[node])))
warnings = []
result = study._report(b"%PDF", "tea", date(2026, 1, 1), date(2023, 7, 1), warnings)
assert result.items["language_level"] == language
assert next(iter(result.items)) == "language_level"
assert result.titles["language_level"] == "A-1 Nivel general de lenguaje oral no ecolálico"
assert result.css == css
assert result.classification == "non_tea"
assert warnings == []
-42
View File
@@ -1,42 +0,0 @@
import pytest
from edf_files import small_edf
from pydantic import ValidationError
from models.tea import jobs
from persistance.cluster import Reference
@pytest.fixture
def cohort(tmp_path, monkeypatch):
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(tmp_path))
monkeypatch.delenv("TEA_REFERENCE_CACHE", raising=False)
folder = tmp_path / "hel"
folder.mkdir()
for i in range(3):
small_edf(folder / f"{i}.edf")
ages = folder / "edades.csv"
ages.write_text("name,age\n0.edf,1.5\n1.edf,2.0\n2.edf,2.5\n")
return folder, ages
def test_bad_references_fail_with_a_reason(cohort):
folder, ages = cohort
for name in ("..", ".", "nope"):
with pytest.raises(ValueError) as exc:
jobs._reference(Reference(name=name))
assert str(exc.value) == f"no reference cohort {name!r}"
ages.write_text("name,age\n0.edf,1\n1.edf,4\n2.edf,5\n")
with pytest.raises(
ValueError, match="reference cohort 'hel' has no EDF with an age from 16 to 36 months"
):
jobs._reference(Reference(name="hel"))
ages.unlink()
with pytest.raises(ValueError, match=r"reference cohort 'hel' has no edades\.csv"):
jobs._reference(Reference(name="hel"))
with pytest.raises(ValidationError, match="name"):
Reference(name="../x")
with pytest.raises(ValidationError, match="line_hz"):
Reference(name="hel", line_hz=55)
+101
View File
@@ -0,0 +1,101 @@
import json
from datetime import date
import pytest
from edf_files import small_edf
from pydantic import ValidationError
from models.jobs import EmptyCohort
from models.tea import jobs
from models.tea.eeg import reference
from persistance import eeg
from persistance.cluster import FolderTrainingSource, SiteTrainingSource
@pytest.fixture
def folder(tmp_path, monkeypatch):
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(tmp_path))
monkeypatch.delenv("TEA_REFERENCE_CACHE", raising=False)
cohort = tmp_path / "hel"
(cohort / "night").mkdir(parents=True)
for name in ("0.edf", "1.edf", "night/2.edf"):
small_edf(cohort / name)
ages = cohort / "edades.csv"
ages.write_text("path,age\n0.edf,18\n1.edf,24.04\nnight/2.edf,30\n")
return cohort, ages
def test_a_folder_lists_each_edf_with_its_age_in_months(folder):
cohort, ages = folder
assert reference.listing(cohort, ages) == [
("hel-0001", cohort / "0.edf", 18.0),
("hel-0002", cohort / "1.edf", 24.0),
("hel-0003", cohort / "night" / "2.edf", 30.0),
]
ages.write_text("path,age\n0.edf,12\n1.edf,24\nnight/2.edf,40\n")
assert [age for _, _, age in reference.listing(cohort, ages)] == [24.0]
def test_bad_folders_fail_with_a_reason(folder):
cohort, ages = folder
for name in ("..", ".", "nope"):
with pytest.raises(ValueError) as exc:
jobs._cohort(FolderTrainingSource(kind="folder", folder=name), date(2026, 1, 1))
assert str(exc.value) == f"no reference cohort {name!r}"
ages.write_text("path,age\n0.edf,12\n1.edf,48\nnight/2.edf,60\n")
with pytest.raises(
ValueError, match="folder 'hel' has no EDF with an age from 16 to 36 months"
):
jobs._cohort(FolderTrainingSource(kind="folder", folder="hel"), date(2026, 1, 1))
ages.unlink()
with pytest.raises(ValueError, match=r"folder 'hel' has no edades\.csv"):
jobs._cohort(FolderTrainingSource(kind="folder", folder="hel"), date(2026, 1, 1))
with pytest.raises(ValidationError, match="folder"):
FolderTrainingSource(kind="folder")
with pytest.raises(ValidationError, match="line_hz"):
FolderTrainingSource(kind="folder", folder="hel", line_hz=55)
def test_the_site_trains_on_children_without_the_diagnosis_by_the_cut_off(fresh_platform):
with fresh_platform.begin() as con:
con.exec_driver_sql("create table silver.eeg (person_id text, study_date text, edf text)")
con.exec_driver_sql(
"insert into silver.eeg values (?, ?, ?)",
[("ruled_out", "2025-03-01", "a"), ("confirmed", "2025-03-01", "b"),
("later", "2025-03-01", "c"), ("ruled_out", "2025-04-01", "d"),
("ruled_out", "2025-09-01", "e")],
) # fmt: skip
con.exec_driver_sql(
"create table bronze.eeg_analysis "
"(edf text, age_months real, features text, valid boolean, error text)"
)
features = json.dumps({"eeg-gradient": {"value": 1.0}})
con.exec_driver_sql(
"insert into bronze.eeg_analysis values (?, ?, ?, ?, ?)",
[("a", 20.0, features, True, None), ("b", 22.0, features, True, None),
("c", 24.0, features, True, None), ("d", 21.0, features, False, None),
("e", 26.0, features, True, None)],
) # fmt: skip
con.exec_driver_sql(
"create table gold.tea_screening "
"(person_id text, not_confirmed_date text, confirmed_date text)"
)
con.exec_driver_sql(
"insert into gold.tea_screening values (?, ?, ?)",
[("ruled_out", "2025-05-01", None), ("confirmed", "2025-02-01", "2025-05-01"),
("later", "2025-07-01", None)],
) # fmt: skip
cut = date(2025, 6, 1)
assert eeg.without_diagnosis(cut) == [
{"key": "a", "age_months": 20.0, "valid": True, "error": None,
"features": {"eeg-gradient": {"value": 1.0}}},
] # fmt: skip
digest, measured, cohort, hz = jobs._cohort(SiteTrainingSource(kind="site"), cut)
assert (cohort, hz, [m["key"] for m in measured]) == ("site", None, ["a"])
assert len(digest) == 64
with pytest.raises(EmptyCohort, match="without the diagnosis by 2025-01-01"):
jobs._cohort(SiteTrainingSource(kind="site"), date(2025, 1, 1))