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.
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).
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.
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.
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.
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.
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.
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).
Per PLAN-feature-parity §2.1/2.2/2.4: non-TEA from rebuild, TEA backend from tea/parity.
- tea/association.py, tea/jobs.py, tea/eeg/reference.py: tea/parity's (tea-lib association
checked against the reference; reference-cohort training; execution.map). rebuild's
ruled-out training and its own association go; T3 adds the site cohort as a training
source in tea/parity's design.
- cluster.py deleted: tea/parity's persistance.cluster + models.execution run every batch.
The optional [dask] extra goes with it (Persistance depends on dask directly).
- definitions.py: tea/parity's jobs (tea_eeg, preview, bundles, sensor) plus rebuild's
backup job and nightly schedule. Scoring takes Jobs.routine(); rebuild's scored() was
the same list, so it is not kept as a second name.
- graph.py: tea/parity's edf reader node plus rebuild's file_format and otherwise-routes.
- jobs.py: rebuild's (every model is routine; no reference-trained branch).
- tests: tea/parity's logic tests kept where both changed (test_eeg, test_recurrence,
test_silver); test_survival_seer stays deleted (P7).
1. No prose in code
- Remove parity-added comments and docstrings from TEA jobs, analysis and
scoring helpers, execution, definitions, and tests. Keep base prose and
Ruff and type-checker directives.
2. No hacks, no glued code
- Delegate both association cohort queries to persistance.eeg. Keep the
predictor mapping and DataFrame shaping in the job, sharing biomarker
codes and EEG study IDs with Core. Preserve column names and order, row
selection, score filtering, and earliest fitting study.
- Use the existing MODELS registry for curve scoring in place of CURVES.
Keep GOLD because the generic score job reads it.
- Catch lookup, database, and validation failures when loading a preview
pipeline, preserving the existing warning. Keep execution-boundary
exception handling for submitted tasks, telemetry and shutdown.
- Name the association test for the missing-champion case. Preserve its
assertion and the other test assertions.
3. Everything in its place
- Keep SQL in Persistance, cohort shaping in models, and tests in their
existing testpaths. Keep the association fits together with their
shared design and result machinery.
Share log-age interpolation with scoring and preserve nulls outside coverage. Use a synthetic geometric midpoint and values on both sides of the median to check numeric parity.
Port the association estimator and add its source-parity tests in models.
Wire cohort selection, fingerprint deduplication, MLflow registration, and
champion scoring into the TEA jobs. Add both bronze tables, gold models
and key tests, and extend the existing WebApi hospital gate.
Follow the spec's resolved silver/bronze cohort and full CSV fingerprint.
No adaptations beyond the resolved spec. Preserve the source numerical
code with Ruff formatting and reflowed docstrings.
Internal choices:
- Select the first ADOS-2 with a SQL window and assemble predictor columns
by EDF in pandas. Normalize dates to days across SQLite and PostgreSQL
and use the undated CSS path if evaluation date is absent.
- Treat unstaged analysis or score tables as empty inputs. Retain the
existing as_of argument without a cutoff in the specified cohort.
- Keep missing and non-finite report and bronze values as null, including
open confidence limits. Store counts as bigint and direction as boolean.
Reuse the EEG bronze merge writer after deleting the prior projection.
- Use a NumPy default_rng seeded with 0, uniform ages, normal predictors,
and independent draws of module, item codes, and CSS for source parity.
Load the reference modules in a test-only namespace with stub contracts.
- Record model and WebApi changes in their existing submodule branches
and update the corresponding gitlinks in the parent commit.
Checks: Ruff lint and format check passed. lint-imports kept both
contracts. The association unit suite passed all five tests. Eight
lightweight TEA job tests passed, with two integration tests deselected.
SQLite smoke checks passed for cohort, registration and deduplication, promotion,
prediction, bronze writes, and both dbt models and their four key tests.
Fixture replay matched the 15 published pairs and 470 published scores.
The full hospital API gate runs on the test machines.
Update tests/test_tea_job.py. Use the synthetic TEA builder with the existing pipeline and concept map, ingest via the platform fixture without a daemon, and run first_n synchronously in process.
Use SQLite and its temporary platform environment, count an absent analysis table as zero, and clear the cached engine around the in-process calls.
Analysis and the reference cohort's measuring run on execution.map; relate is the
Phase 2 seam. A LocalCluster starts inside a multiprocess Dagster step (checked on a
real run), so the ops keep the default executor.