Commit Graph

22 Commits

Author SHA1 Message Date
AlbertoPMDM 4e224a03cb verify: diagnose failed HK1K studies step by step (file, step, message, traceback) 2026-11-18 23:49:54 -06:00
AlbertoPMDM 5da1921c69 spindle phases (N2/N3), README, registry test for the full module set
- spindle_detection (legacy and modern): phase='N2'|'N3' searches only the
  sleep windows of that stage (husos --fase); requires slow_wave_staging then.
- README: modules, requirements, use, tests and cluster verification.
- test_pipeline: both implementations register the same 5 processes and 9
  biomarkers.
2026-11-18 22:12:02 -06:00
AlbertoPMDM ef2f3dbf39 window_selection and spikes, legacy and modern
- legacy: seleccion.seleccionar and candidatos_punta.de_estudio +
  indicadores vendored unchanged, run on the contract adapter with the
  sleep_state labels as the vigilancia table.
- modern: the director's detector functions copied by name into
  _detector.py with three substitutions (MNE band-pass, channel lists from
  the study, a private port of the seleccion gate); a modern
  window_selection on the same port.
- synthetic builder: optional focal spike-and-wave (the director's own
  _punta shape) with a field on the neighbours.

Modern equals legacy exactly on window verdicts and spike indicators; the
C3 focus is found; contract suites pass.
2026-11-18 22:02:57 -06:00
AlbertoPMDM 5cf9538846 spindle_topography, legacy and modern
- legacy: topografia_huso's helpers (episodios, laplaciano) and
  eeg_io.envolvente vendored unchanged; de_estudio's computation on the
  contract adapter instead of a folder.
- modern: the same episodes, sigma envelope on MNE/SciPy, the director's
  neighbour Laplacian as an option.
- Features: enhancement per spindle channel and amplitude relative to Fp1.

Modern within 2% of legacy, with and without the Laplacian; the channels
carrying synthetic spindles stand out; contract suite passes.
2026-11-18 21:57:34 -06:00
AlbertoPMDM d21ace9aea coupling, legacy and modern
- legacy: acoplamiento.fases_de_estudio + resumen (vendored unchanged);
  spindle and slow-wave events read through the contract columns, so
  either detector can feed it; in_slow_wave = --solo-en-onda.
- modern: slow-oscillation phase (MNE 0.5-2 Hz, scipy Hilbert, per run) at
  the sigma-envelope peak of each spindle; R from 200 subsamples of 30,
  excess over the chance floor, preferred angle, raw R.

Modern within 0.03 of legacy; phase-locked synthetic spindles give R > 0.8
at the trough in both; contract suite passes.
2026-11-18 21:55:30 -06:00
AlbertoPMDM 406944e134 verify: run every biomarker registered in both implementations and compare them per study 2026-11-18 21:52:47 -06:00
AlbertoPMDM 4deba99c92 aperiodic and mse, legacy and modern
- The cluster route's 2 s window table (ventanas.cortar + estado_director
  exclusions and labels) rebuilt from the contract, one private copy per
  module.
- legacy: biomarcadores espectro.py, aperiodico.py (FOOOF with Wilkinson's
  modifications) and complejidad.py copied unchanged; exponent per region
  and state (NaN under 20 windows or R2 < 0.9); MSE fine / coarse / total.
- modern: MNE multitaper + fooof with the same two Wilkinson modifications;
  antropy sample entropy with Costa's fixed tolerance.

Copies byte-identical to the submodule; modern within 2% (exponent) and 1%
(MSE) of legacy on the synthetic study; contract suites pass.
2026-11-18 21:52:22 -06:00
AlbertoPMDM 4987629e8b slow_wave_staging and slow_waves, legacy and modern
- legacy: ondas_lentas.detectar on F3 F4 Fz over the whole recording,
  union_intervalos + estadificar for the 'sueno' windows (the cluster
  route's fases_sueno), ondas_lentas.resumen for the features; vendored
  unchanged.
- modern: the same zero-crossing detector on an MNE band-pass, the same 20%
  of 30 s N3 rule, the same summary definitions.

Legacy waves equal the submodule's exactly; modern equals legacy on the
synthetic study; contract suites pass.
2026-11-18 21:47:39 -06:00
AlbertoPMDM ae92ae8b17 gradient, legacy and modern
- legacy: medidas_director.gradiente on gradiente.analizar (vendored), in
  the 'sueno' and 'somnolencia' windows as analizar_director does.
- modern: Hann periodograms per window (MNE), median band power, Theil-Sen
  slope (scipy.stats.theilslopes) on the director's front-back coordinates.
- 8 features gradient_<band>_<state>, one baseline each.

Legacy equals the submodule's cluster route exactly; modern within 0.01 of
legacy on the synthetic study.
2026-11-18 21:44:52 -06:00
AlbertoPMDM e1ab9fac32 gradient: vendor the director's gradiente.py and baselines (APIs pending) 2026-11-18 20:58:23 -06:00
AlbertoPMDM f870ee9f14 spindle_detection and spindles, legacy and modern
- legacy: husos.detectar / husos.resumen vendored unchanged, run on the
  'sueno' windows as medidas_director does; the wake rhythm that sets the
  'rhythm near sigma' flag is computed inside the process (no biomarker
  dependency).
- modern: the same detector on MNE (sigma band-pass) and SciPy (Hilbert,
  Welch narrowness, phase stability); summary with the director's
  definitions; one baseline per feature.
- privacy.group_size understands per-feature baseline dicts.

Legacy equals the submodule's cluster route exactly (spindle count and the
six summary measures); modern equals legacy on the synthetic study.
2026-11-18 20:57:24 -06:00
AlbertoPMDM 1f8793aacb modern annotation_mask, sleep_state and posterior_rhythm
- processes.annotation_mask: the director's state words and interval rules
  on the EDF+ annotations (MNE), window dominant state and 'mixta'.
- processes.sleep_state: vigilancia's features from batched Hann
  periodograms (mne psd_array_welch), depth index, HK1K cut-offs or cohort
  reference + KMeans (scikit-learn) after train().
- biomarkers.posterior_rhythm: Welch of the wake windows (MNE), 1/f-fitted
  dominant peak, median of O1 O2 P3 P4; private copy of the baselines.
- Registered as the modern modules; Pipeline.default("modern") now runs
  the full slice.

On a synthetic study: annotation states and sleep-state labels identical to
legacy, rhythm equal (6.5 Hz); contract suites and cohort cut-offs tested.
2026-11-18 20:53:52 -06:00
AlbertoPMDM acfd3a70d4 preprocessing: modern Preprocessor on MNE, agreeing with the director's output
Executes a PreprocessPlan with MNE: EDF read and label normalisation, plan
bads dropped, line removal on the raw signal (interpolated notch when the
line is >= min_db on the kept scalp channels, or ZapLine via meegkit),
Raw.filter (IIR Butterworth order 4, zero phase, run by run between
BAD_ACQ_SKIP), set_eeg_reference (average of kept scalp / linked ears),
EOG/ECG filtered only. Window grid and quality spans from a private copy of
the window QC.

Within 0.25 uV of legacy.preprocessing on every channel of both default
plans away from the filter edges (max(5 s, 3/highpass)).
2026-11-18 20:50:33 -06:00
AlbertoPMDM fcd0f76d76 validation: modern validation on MNE/SciPy, agreeing with the director's
The director's rules (validacion.validar, preproceso.canales_malos,
lote.qc_estudio window QC, triaje.triar, cluster gates) rebuilt on MNE
(EDF reading, IIR filtering run by run, Welch PSD), SciPy and antropy (DFA).
All thresholds in rules.ValidationConfig with their sources; edfio header
checks (no silent resampling); R4B FHIR Bundle (private copy of the builder).

Agrees with legacy.validation on dropped channels, triage level and verdict
in every synthetic case; accepted differences (gaps as NaN, one notch, MNE
filter edges, no set-up detection) are documented and tested.
2026-11-18 20:47:07 -06:00
AlbertoPMDM 4956f36d80 serving (MLflow), HK1K verification command and the tea-verify DaskJob
- serving: plans and biomarkers as MLflow "models from code" (standalone
  wrapper files), code_paths = only the module's package + contracts;
  plan.json artifact and plan params; biomarker models pin plan_uri and
  plan_hash. privacy: no study codes / dates / paths, binary artifacts
  refused, baselines from fewer than 5 children refused.
- verify: python -m tea_modulo.verify hk1k lists HK1K in a worker task, runs
  the pipeline remotely (line 50 Hz), checks the remote run equals a plain
  sequential run in one task, summarizes the posterior rhythm by age group
  (groups < 5 suppressed) and writes the summary under processed/usuarios/.
  Any input prefix but raw/eeg-helsinki/ is refused.
- deploy: Dockerfile.verify (dask:1.1 + antropy, fhir.resources, meegkit,
  pytest; tea-modulo from the local checkout), .dockerignore keeping .venv,
  eeg/ and any signal or patient file out, dask-verify.yaml (own 2x4-worker
  cluster, no eeg-data PVC, keys only on workers), verify.sh.

Tests: MLflow round trips on sqlite, model loads with only its own code in
a fresh interpreter, privacy refusals, verify guards.
2026-11-18 20:24:03 -06:00
AlbertoPMDM 038836a701 pipeline: module registry, run_study, Dask runner and legacy serial executor
- Modules are looked up by name through entry points (tea_modulo.modules,
  tea_modulo.legacy_modules) and checked against their protocol.
- run_study: one EDF to one small row (key, verdict, features, plan hash,
  module versions; failures become error rows with paths removed).
- Modern batches are Dask-native: a dask.delayed graph under
  annotate(priority=-10, retries=1), run on cluster='remote'|'local'|'sync'|
  'auto'. Remote: Client(direct_to_workers=False), get_versions(check=True),
  only close(). Local: processes, 1 thread, BLAS threads 1, closed by us.
- Legacy batches: tea_modulo.legacy.executor.run_serial, a plain loop.
- storage.local_copy fetches s3:// objects to a temp file inside the task.

Tests: legacy loop, Dask sync and a 2-worker LocalCluster give the same
table; error rows; positive priority refused; remote never shut down.
2026-11-18 20:18:07 -06:00
AlbertoPMDM 441113c7b7 legacy: annotation_mask, sleep_state and posterior_rhythm on the director's code
- contracts: Preprocessed.quality_spans (QC-unclean stretches at the QC's
  own resolution), so the director's state mask can be rebuilt exactly.
- legacy.preprocessing: annotations straight from the EDF (exact onsets, as
  edf_convert), quality_spans from his 4 s QC.
- legacy processes annotation_mask (intervalos_estado, estado_de_ventana) and
  sleep_state (vigilancia.rasgos with senal._mascara_excluir's mask,
  clasificar with the HK1K cut-offs or cohort cut-offs after train()).
- legacy biomarker posterior_rhythm (medidas_director.ritmo on
  ritmo.psd_de_ventanas + pico_dominante) with a private _baseline.py holding
  curvas.py and perfil_alteraciones' age-block z, copied verbatim.
- Each legacy module owns its adapter, which writes the study in the
  director's preprocessed format and opens it with his eeg_io.Estudio.

Identical to the submodule's cluster route on a synthetic study (window
labels and rhythm); contract suites pass.
2026-11-18 20:12:47 -06:00
AlbertoPMDM 02a885dc10 PreprocessPlan, default plans and legacy.preprocessing
preprocessing.plan: frozen PreprocessPlan (steps, variants, state, gates,
bads, reasons) with checks, to_dict/from_dict (schema 1, unknown keys
refused) and a content hash; defaults DIRECTOR_CLUSTER and DIRECTOR_CLI
turn the route differences into data.

legacy.preprocessing maps the plan dict onto the director's
preproceso.procesar (vendored unchanged), refuses what his code cannot do
(zapline, other notch threshold, manual bads), returns MNE Raw variants and
the window grid flagged from his 4 s QC. Identical to the submodule for
both default plans.
2026-11-18 20:04:18 -06:00
AlbertoPMDM 25dd95a8ad legacy.validation: director's validation behind the Validator protocol
The director's scripts (biomarcadores-tea/preproceso @ 7dfc641) are vendored
unchanged except imports by tools/vendor_legacy.py, one copy per legacy
module; --check re-derives them from the pinned submodule.

LegacyValidation runs steps 1-4 of un_estudio.procesar for an EDF
(edf_convert, lote.excluidos_para_qc + qc_estudio + veredicto, triaje.triar,
60% clean windows) plus preproceso.MIN_CUERO, and returns an R4B FHIR Bundle
and 0/1. Tests: identical to the submodule on a synthetic EDF, contract
suite, not-valid case, vendor check.
2026-11-18 20:00:46 -06:00
AlbertoPMDM 2b4bea0c7f export: optional KTLX -> EDF+ exporter vendored from eeg@92bc2a0
Step 2 of the plan. src/eeg/utils copied into tea_modulo.export with only the
imports changed; outside the EDF pipeline (extra `export`, script ktlx2edf).
Synthetic tests (ktlx_synth, edf export, patient) carried over: 43 pass.
2026-11-18 19:54:48 -06:00
AlbertoPMDM 449acf8b44 contracts: shared data classes, protocols and contract test suites
Step 1 of the tea_modulo plan: Recording (MNE Raw from EDF), ValidationSummary,
Preprocessed, Labels, Study, the Validator/Preprocessor/Process/Biomarker
protocols with check_module(), reusable contract suites in contracts.testing,
and an AST test that enforces the module boundary rule.
2026-11-18 19:54:15 -06:00
AlbertoPMDM fbfad83861 Initialize uv library project 2026-11-18 14:21:36 -06:00