Compare commits

..

78 Commits

Author SHA1 Message Date
alberto d8f34a77c1 F7i: A-1 read from the ADOS-2 report; no column fallback
ADOS-2 records without A-1 where the manual needs it (Module 1; Toddler from 21 months) and records whose printed totals differ from their items' totals are held for Revision. The preview shows the same errors.
2026-12-04 12:52:27 -06:00
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
alberto fde57b9074 test_link_answers starts a whole platform: removed (P7) 2026-12-01 00:23:32 -06:00
alberto 2ff5c04238 Merge origin/rebuild into parity/T1-merge (models)
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).
2026-11-30 23:56:11 -06:00
alberto 7088e0e946 ADOS-2 preview carries each item's code and title from the Core list
The preview result names the module's items by the titles in
core.tea.ados2_items, module items first, so the Gobernanza dialog and its
PDF print what the report asks instead of field names.
2026-11-30 19:17:46 -06:00
alberto 7c05de6398 Merge tea/P8-ados2-titles into tea/final 2026-11-30 17:00:09 -06:00
alberto c59afacad9 ADOS-2 preview reads every catalog item; totals come from the module's list
core.tea no longer has module-independent SA/RRB lists: the preview parses
all ADOS2_ITEMS and the scoring takes each module's own items from
core.tea.ados2_items.
2026-11-30 16:56:26 -06:00
alberto c1a1e294dc The suite keeps only logic tests
Keep deterministic model, signal, DSL and SQLite storage checks.

Checks: ruff check, ruff format --check, lint-imports (two contracts kept), and pytest (115 passed, 7 warnings in 42.52s).

removed models/tests/test_bundle.py::test_guard_runs_on_export_and_on_import — implementation-detail
removed models/tests/test_cacu_models.py — parity-only
removed models/tests/test_cacu_models.py::test_predictions_match_the_current_models — parity-only
removed models/tests/test_cacu_models.py::test_survival_matches_the_current_model_with_its_index_fixed — parity-only
removed models/tests/test_cacu_models.py::test_a_cohort_the_site_lacks_is_reported_not_trained — implementation-detail
removed models/tests/test_cama_models.py — parity-only
removed models/tests/test_cama_models.py::test_survival_matches_the_current_model — parity-only
removed models/tests/test_edf_node.py — slow integration (logic now covered by test_header_reads_the_facts, test_not_an_edf_is_not_valid and test_collected_files_are_kept_once_by_content)
removed models/tests/test_edf_node.py::test_edf_pipeline_keeps_and_links_the_files — slow integration (logic now covered by test_header_reads_the_facts, test_not_an_edf_is_not_valid and test_collected_files_are_kept_once_by_content)
removed models/tests/test_edf_upload.py — slow integration (logic now covered by test_tea_eeg_first_n_selects_exactly_n_pending_studies for study selection)
removed models/tests/test_edf_upload.py::test_an_uploaded_edf_is_analysed_by_itself — slow integration (logic now covered by test_tea_eeg_first_n_selects_exactly_n_pending_studies for study selection)
removed models/tests/test_eeg.py::test_verdicts_and_checks — parity-only
removed models/tests/test_eeg.py::test_metric_values — parity-only
removed models/tests/test_eeg.py::test_reference_features — parity-only
removed models/tests/test_eeg.py::test_curves — parity-only
removed models/tests/test_execution.py::test_map_empty_items_starts_nothing — implementation-detail
removed models/tests/test_execution.py::test_map_local_equals_sync — slow integration (logic now covered by test_map_sync_keeps_input_order_and_reports_each_item)
removed models/tests/test_execution.py::test_map_lazy_items_are_not_all_loaded_at_once — implementation-detail
removed models/tests/test_execution.py::test_progress_tag_and_log_lines_inside_running — implementation-detail
removed models/tests/test_execution.py::test_no_tag_outside_running — implementation-detail
removed models/tests/test_execution.py::test_version_mismatch_fails_before_any_task — implementation-detail
removed models/tests/test_execution.py::test_local_cancel_leaves_no_worker_processes — slow integration (logic now covered by test_cancel_returns_the_terminal_or_cancelling_state for cancellation states)
removed models/tests/test_execution.py::test_health_sync_and_local — slow integration (logic now covered by test_resolve_defaults_and_allow_list for execution defaults)
removed models/tests/test_execution.py::test_health_unreachable_remote — slow integration (logic now covered by test_resolve_rejects_unlisted_scheduler_and_scheduler_in_local_mode for scheduler validation)
removed models/tests/test_execution.py::test_health_rejects_unlisted_scheduler — implementation-detail
removed models/tests/test_execution.py::test_progress_reaches_the_dagster_run — slow integration (logic now covered by test_shape_progress_tag and test_map_sync_keeps_input_order_and_reports_each_item)
removed models/tests/test_execution.py::test_map_remote_equals_sync — slow integration (logic now covered by test_map_sync_keeps_input_order_and_reports_each_item)
removed models/tests/test_execution.py::test_health_remote — slow integration (logic now covered by test_resolve_defaults_and_allow_list for remote execution choice)
removed models/tests/test_execution.py::test_remote_cancel_cancels_futures — slow integration (logic now covered by test_cancel_returns_the_terminal_or_cancelling_state for cancellation states)
removed models/tests/test_execution.py::test_progress_json_is_stable — implementation-detail
removed models/tests/test_execution.py::test_map_on_error_converts_a_failed_item[local] — slow integration (logic now covered by test_map_on_error_converts_a_failed_item)
removed models/tests/test_execution.py::test_map_raises_without_on_error[local] — slow integration (logic now covered by test_map_raises_without_on_error)
removed models/tests/test_ingest.py — slow integration (logic now covered by test_collected_files_are_kept_once_by_content and test_the_drawn_patterns_read_every_report)
removed models/tests/test_ingest.py::test_a_site_reaches_bronze_once_and_its_documents_are_read — slow integration (logic now covered by test_collected_files_are_kept_once_by_content and test_the_drawn_patterns_read_every_report)
removed models/tests/test_recurrence.py::test_cohorts — parity-only
removed models/tests/test_recurrence.py::test_routines — parity-only
removed models/tests/test_recurrence.py::test_c_index_and_internal_auc — parity-only
removed models/tests/test_recurrence.py::test_saved_model — parity-only
removed models/tests/test_recurrence.py::test_calculator — parity-only
removed models/tests/test_recurrence.py::test_risk_factors — parity-only
removed models/tests/test_recurrence.py::test_train_reproduces_v1 — parity-only
removed models/tests/test_silver.py::test_a_site_becomes_silver_and_review_gets_the_rest — slow integration (logic now covered by test_person_ids_survive_a_review_merge_and_split and test_a_code_nobody_mapped_is_held_with_the_reason)
removed models/tests/test_survival_seer.py — parity-only
removed models/tests/test_survival_seer.py::test_each_scenario_takes_the_originals_patients_and_deaths — parity-only
removed models/tests/test_survival_seer.py::test_each_scenarios_observed_curves_are_the_originals — parity-only
removed models/tests/test_survival_seer.py::test_the_models_points_are_the_survival_of_the_cases_it_learned_from — parity-only
removed models/tests/test_tea_association.py::test_reference_parity — parity-only
removed models/tests/test_tea_job.py::test_tea_eeg_runs_the_four_steps_in_order — implementation-detail
removed models/tests/test_tea_job.py::test_a_failing_analysis_stops_the_graph — implementation-detail
removed models/tests/test_tea_job.py::test_a_bad_scope_fails_before_any_work — implementation-detail
removed models/tests/test_tea_job.py::test_config_mirrors_match_the_shared_models — implementation-detail
removed models/tests/test_tea_job.py::test_definitions_load_with_every_job_and_the_sensor — implementation-detail
removed models/tests/test_tea_job.py::test_relate_returns_none_without_a_champion — implementation-detail
removed models/tests/test_tea_job.py::test_tea_eeg_first_n_analyses_exactly_n — slow integration (logic now covered by test_tea_eeg_first_n_selects_exactly_n_pending_studies)
removed models/tests/test_tea_job.py::test_tea_eeg_remote_mode_gives_the_same_analysis — slow integration (logic now covered by test_dominant_peak_recovers_a_posterior_rhythm_above_background and test_centile_interpolation_preserves_scoring)
removed models/tests/test_tea_preview.py::test_scores_come_from_the_champions — implementation-detail
removed models/tests/test_tea_preview.py::test_no_champions_warns_and_leaves_z_empty — implementation-detail
removed models/tests/test_tea_preview.py::test_ados2_read_with_the_pipeline_patterns — implementation-detail
removed models/tests/test_tea_preview.py::test_ados2_problems_are_warnings_not_errors — implementation-detail
removed models/tests/test_tea_preview.py::test_the_job_deletes_its_files_and_returns_the_result_as_output — slow integration (logic now covered by the direct-op test_the_job_deletes_its_files_and_returns_the_result_as_output)
removed models/tests/test_tea_preview.py::test_the_job_deletes_its_files_when_the_study_fails — implementation-detail
removed models/tests/test_tea_reference.py::test_a_named_reference_resolves_under_the_root — implementation-detail
removed models/tests/test_tea_reference.py::test_60_hz_changes_the_digest_and_is_passed_on — implementation-detail
removed models/tests/test_tea_reference.py::test_the_cache_is_named_by_cohort_and_digest_and_reused — implementation-detail
removed models/tests/test_tea_reference.py::test_legacy_environment_still_works — implementation-detail
removed models/tests/test_tea_reference.py::test_train_records_cohort_and_line_hz — implementation-detail
removed models/tests/test_tea_reference.py::test_the_train_op_passes_the_reference_or_refuses_it — implementation-detail
removed models/tests/test_tea_reference.py::test_reference_config_mirrors_the_shared_model — implementation-detail
2026-11-30 16:48:32 -06:00
alberto d8445fcabf Cleanup of the TEA parity work: no prose in code, no hacks, everything in its place
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.
2026-11-30 13:41:49 -06:00
Roberto Treviño 77350b8fec A reviewer's answer holds when more records join a person 2026-11-30 02:14:13 -06:00
Roberto Treviño a9945bc021 A training run takes every model; the public cohorts' code lives with the tests 2026-11-29 21:12:17 -06:00
alberto a818847b99 Expose TEA baseline centiles by age
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.
2026-11-29 19:45:50 -06:00
alberto e71a7baac5 ADOS-2 association model: Firth/ordinal port, MLflow model, bronze and gold, gate
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.
2026-11-29 13:34:01 -06:00
Roberto Treviño 3a749ba8d1 A nightly Dagster job backs up the data folder 2026-11-29 12:38:56 -06:00
Roberto Treviño f369e8f2eb Survival rates its scenarios' risk factors as Luis's code does; recurrence shares the factor code 2026-11-29 12:38:56 -06:00
Roberto Treviño f3f79831bf Each domain's jobs name the models a score run takes 2026-11-29 07:03:08 -06:00
Roberto Treviño 43207fa3a5 Scoring runs every champion, slow models too 2026-11-29 06:43:08 -06:00
alberto 8c910e7500 Dask scheduler and workers for the test profile and CI; writes-overlap, cancel and remote-mode tests: remote-mode TEA analysis equals sync on synthetic EEGs 2026-11-29 04:47:23 -06:00
Roberto Treviño 7e8e8b44d8 Silver checks the site's recurrences and positive nodes 2026-11-29 01:50:23 -06:00
alberto 0b4f7593e5 TEA hospital test follows the sensor flow; re-analysis by id in local mode; first_n
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.
2026-11-29 01:25:29 -06:00
Roberto Treviño 5c781f2a52 The recurrence report names the site's own cohort 2026-11-29 01:20:40 -06:00
Roberto Treviño 8e9da2c73a The site cohort keeps redundant covariates for its scenarios 2026-11-29 00:41:24 -06:00
Roberto Treviño 53e6f77c9e Every model trains on the site: EEG age curves on the children with TEA ruled out, recurrence on the site's patients (St. Gallen subtype), and the EEG–ADOS-2 association 2026-11-28 21:28:36 -06:00
alberto c6c55e0ffe Merge P3.7 into P3.5 for one combined gate 2026-11-28 16:31:56 -06:00
alberto 3950b3c1f5 tea_preview job: one file previewed, result as run output: preview analyses one staged EDF (and an ADOS-2 PDF) against the champions, writes nothing 2026-11-28 13:37:27 -06:00
alberto b7eaf7055d Training config: reference name and mains frequency: train takes a named reference cohort and its mains frequency; legacy TEA_REFERENCE_DIR stays the default 2026-11-28 13:26:18 -06:00
alberto 9ed686e87a Merge tea/parity into P3.6 2026-11-28 10:31:00 -06:00
alberto dce0e0c690 EDF reader node in the ingestion DSL: run_edf keeps each row and adds the header facts or the file's error; read.header parses the fixed EDF header without edfio 2026-11-28 10:30:48 -06:00
Roberto Treviño 924f662a21 Survival scores name the report's clinical scenarios each patient falls in 2026-11-28 09:29:59 -06:00
alberto d954faa28e Generic model bundles: export and import: the import_bundle job 2026-11-28 09:24:36 -06:00
Roberto Treviño 1a46a5ba73 Link each distinct identity once, not every pair of a patient's records 2026-11-28 01:17:40 -06:00
Roberto Treviño 61eb3a30d0 Read works through files a batch at a time and keeps each batch 2026-11-27 22:29:23 -06:00
Roberto Treviño 0c78f8cf7d OCR only on the pages without text; otherwise routes; batches on Dask through its own API 2026-11-27 19:17:49 -06:00
alberto cc95054a96 The tea_eeg job: analyse, score the age curves, relate ADOS-2, rebuild gold; a sensor starts it after an ingest
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.
2026-11-27 18:02:28 -06:00
alberto 9220b8c52c execution.map runs a heavy op's items in this process, on local workers or on a Dask scheduler, and reports progress on the run 2026-11-27 17:19:55 -06:00
Roberto Treviño 385cc5b80b Read keeps the file and says its format; extract takes fields from columns; EEG batches carry their recording, on Dask where it is installed 2026-11-27 16:25:01 -06:00
Roberto Treviño 3546269eaf Review queues a scan read only in part, and an undated name one typo from a person 2026-11-27 14:02:08 -06:00
Roberto Treviño 7b9ae69de2 CaCu models record the outcomes each split holds 2026-11-27 11:05:28 -06:00
Roberto Treviño 4ff4a3a7d8 A person nothing names is held for review; a scan may misread one valid code as another 2026-11-27 08:46:05 -06:00
Roberto Treviño 999f0fb926 A model whose cohort is empty at a site is skipped, not a failed train run 2026-11-27 05:07:54 -06:00
Roberto Treviño 02aab07a67 Extract reads several columns as one document; reviewers' corrections of study fields applied at the target; the site gates on ISSSTELEON's test source 2026-11-27 01:45:16 -06:00
Roberto Treviño 44cb0dc894 CaMa survival with stage and first-course treatment, clinical scenario report, measured against the SEER-trained original 2026-11-26 19:03:38 -06:00
Roberto Treviño 76eb8cc8af Files read by hash; fractional Weibull solved and fitted to convergence; recurrence reads its reference cohorts from the platform 2026-11-26 14:25:53 -06:00
Roberto Treviño f305cdd044 TEA EEG analysis and age curves, TEA jobs; CaMa recurrence on METABRIC and SCAN-B; reference-data models and routine runs 2026-11-26 07:06:52 -06:00
Roberto Treviño e2f7e95e83 Shared interval survival for CaMa and CaCu, one jobs module for every domain, Dagster train and score by domain 2026-11-25 23:20:52 -06:00
Roberto Treviño d3d9cc3950 Link node keeps names as written; compares them normalised 2026-11-25 17:39:32 -06:00
Roberto Treviño 8c0ec5106c Long silver from targets, stable person ids, ConceptMap translation, the fhir node 2026-11-25 16:17:23 -06:00
Roberto Treviño b6857dab2a CaCu training and scoring jobs on gold, MLflow versions with their reports 2026-11-25 01:16:45 -06:00
Roberto Treviño bea3e4cd2d CaCu models: prevalence-incidence mixture and logistic, equal to the current predictions 2026-11-25 00:28:42 -06:00
Roberto Treviño 77fc039586 Link: reviewer decisions and corrections, orphan candidates by typo-near identifiers; OCR sidecar text 2026-11-24 22:35:13 -06:00
Roberto Treviño 0c4706658b Share the platform fixture from the root conftest 2026-11-24 21:00:52 -06:00
Roberto Treviño 61721a8005 Run every node kind: route, map, join, extract (LLM or patterns), link (Splink), target 2026-11-24 20:05:29 -06:00
Roberto Treviño 8d874736db Run pipeline graphs: one ingest job, Source and Read nodes 2026-11-24 18:20:26 -06:00
Roberto Treviño 79a55a7a62 Collect and unpack jobs; ingestion gate on SQLite and PostgreSQL 2026-11-24 17:48:18 -06:00
rockdrigo f1370d2776 Move DbtProject to its own module so its manifest can be prepared before load
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 11:50:45 -06:00
rockdrigo 639bbcda19 Sample job test: run each Dagster run in its own process, on SQLite and PostgreSQL
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 11:42:07 -06:00
rockdrigo 3558e24a46 Rebuild: Dagster code location with the sample dlt and dbt assets
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 11:18:08 -06:00
67 changed files with 9094 additions and 461 deletions
-6
View File
@@ -1,8 +1,2 @@
__pycache__/
*.pyc
.venv/
.pytest_cache/
.coverage
*.egg-info/
.env
uv.lock
-62
View File
@@ -1,62 +0,0 @@
# models
Python package with the standard `train()`/`predict()` interface for the
three screening models — CaCu, CaMa and TEA. Consumed by `WebApi`, but
independent of it: this package can read its own training/inference data
directly from `Persistance`, without going through `WebApi` at all.
## Structure
- `models/base.py` — `ScreeningModel`, the abstract base every model
implements (`train(data)` / `predict(data)`).
- `models/cacu.py`, `models/cama.py`, `models/tea.py` — one concrete
class per domain.
## How entities are accessed from models
This package depends on `../Persistance` (a local `uv` path dependency —
see `pyproject.toml`), and through it on `../Core`. **As of now this is
wiring, not usage**: `train()`/`predict()` in `cacu.py`/`cama.py`/`tea.py`
just raise `NotImplementedError` — no model imports `persistance` yet.
When real training/inference logic is added, the access pattern is the
same repository instances `WebApi` reads from — no separate data layer
for `models` to maintain:
```python
# models/models/cacu.py
from typing import Any
from persistance.cacu import citologia_cervical_repository
from models.base import ScreeningModel
class CaCuModel(ScreeningModel):
def train(self, data: Any = None) -> None:
if data is None:
data = citologia_cervical_repository.list(limit=10_000)
# ... fit on `data`
def predict(self, data: Any) -> Any:
raise NotImplementedError("CaCu prediction is not implemented yet.")
```
The `data: Any = None` default on `train()`/`predict()` is what lets a
caller (e.g. `WebApi`) optionally hand over already-fetched rows instead
of forcing every call to hit the database — but a model implementation is
just as free to call `persistance.<domain>` itself when `data` is `None`,
exactly like the example above.
Each domain's available repositories (`paciente_repository`,
`citologia_cervical_repository`, etc.) and how to extend one with
table-specific business logic are documented in
`../Persistance/README.md`.
## Riesgos (ADR-MD-008)
`models/riesgo.py` es el contrato con que Orquestacion pide riesgos a un modelo: `EstimadorDeRiesgo`
(recibe el marco ancho de un armado de cohorte y devuelve un `Riesgo` por miembro y horizonte, más su
`Procedencia`, las llaves para conciliar con MLflow). `RiesgoSintetico` es un sustituto determinista, sin
MLflow, para pruebas y para desplegar sin el modelo real; no es un modelo clínico. El modelo real
(Modelo-cacu, con su artefacto de MLflow) entra como otra clase que cumple el contrato (MD-Q6).
-21
View File
@@ -1,21 +0,0 @@
from abc import ABC, abstractmethod
from typing import Any
class ScreeningModel(ABC):
"""Standard train()/predict() interface every screening model implements,
regardless of which of the three data marts (CaCu/CaMa/TEA) it targets.
Implementations are free to pull their own data straight from
`persistance.<domain>` — the same standard repository API WebApi uses —
or accept already-fetched rows from a caller; `data` is intentionally
untyped at this scaffolding stage.
"""
@abstractmethod
def train(self, data: Any = None) -> None:
"""Fit the model, optionally on `data` passed in by the caller."""
@abstractmethod
def predict(self, data: Any) -> Any:
"""Score `data` and return predictions."""
-19
View File
@@ -1,19 +0,0 @@
from typing import Any
from models.base import ScreeningModel
class CaCuModel(ScreeningModel):
"""Scaffold for the CaCu (cervical cancer) screening model.
Can pull its own training data straight from `persistance.cacu`'s
repositories (`paciente_repository`, `citologia_cervical_repository`,
`biopsia_cervical_repository`, ...) or be handed already-fetched rows.
No real model yet — this is interface scaffolding only.
"""
def train(self, data: Any = None) -> None:
raise NotImplementedError("CaCu training is not implemented yet.")
def predict(self, data: Any) -> Any:
raise NotImplementedError("CaCu prediction is not implemented yet.")
View File
+146
View File
@@ -0,0 +1,146 @@
import numpy as np
import pandas as pd
from core import cacu
RESULTS = ("bethesda", "glandular", "hpv")
REFERRED = ("colposcopy", "biopsy")
MISSING = "(none)"
def prepared(events: pd.DataFrame) -> pd.DataFrame:
return events.assign(
date=pd.to_datetime(events["date"]), index_date=pd.to_datetime(events["index_date"])
)
def days(events: pd.DataFrame) -> pd.Series:
return (events["date"] - events["index_date"]).dt.days
def _worst(codes: pd.Series, cytology: dict) -> pd.Series:
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()
return worst.map(lambda r: None if np.isnan(r) else names[int(r)]).astype(object)
def _referral_grade(events: pd.DataFrame, persons: pd.Series, history: dict) -> pd.Series:
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"])]
codes = near[near["type"].isin(["bethesda", "glandular"])].set_index("person_id")["value_code"]
worst = _worst(codes, history["cytology"]).reindex(persons).to_numpy()
hpv = near[(near["type"] == "hpv") & (near["value_code"] == "positive")]
positive = persons.isin(hpv["person_id"])
grade = np.where(np.isin(worst, history["high"]), "high", np.where(
np.isin(worst, history["low"]) | (np.isin(worst, history["low_if_hpv_positive"])
& positive.to_numpy()), "low", None)) # fmt: skip
return pd.Series(grade, index=persons.index, dtype=object)
def index_results(events: pd.DataFrame, cytology: dict, history: dict | None = None):
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"
)
members = events.groupby("person_id", as_index=False)["index_date"].first()
wide = wide.reindex(index=members["person_id"], columns=list(RESULTS))
codes = wide[["bethesda", "glandular"]].stack()
members["cytology"] = _worst(codes, cytology).reindex(members["person_id"]).to_numpy()
members["hpv_positive"] = (wide["hpv"] == "positive").astype(float).to_numpy()
if history:
members[history["feature"]] = _referral_grade(events, members["person_id"], history)
return members
def _negatives(events: pd.DataFrame, d: pd.Series, grades: list[str]) -> pd.DataFrame:
timed = events.assign(days=d.astype(float))[d >= 0]
biopsies = timed[(timed["type"] == "biopsy") & ~timed["value_code"].isin(grades)]
visits = None
for kind, values in cacu.KNOWN_NEGATIVE.items():
found = timed[(timed["type"] == kind) & timed["value_code"].isin(values)]
found = found[["person_id", "days"]]
if visits is None:
visits = found
continue
paired = pd.merge_asof(
visits.sort_values("days"), found.rename(columns={"days": kind}).sort_values(kind),
left_on="days", right_on=kind, by="person_id", direction="nearest",
tolerance=float(cacu.INDEX_SAMPLE_DAYS),
).dropna(subset=[kind]) # fmt: skip
visits = paired.assign(days=paired[["days", kind]].max(axis=1))[["person_id", "days"]]
return pd.concat([biopsies[["person_id", "days"]], visits], ignore_index=True)
def interval_coded(events: pd.DataFrame, grades: list[str], cytology: dict,
history: dict | None = None) -> pd.DataFrame: # fmt: skip
d = days(events)
outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades) & (d >= 0)
first = d[outcome].groupby(events.loc[outcome, "person_id"]).min()
negatives = _negatives(events, d, grades)
before = ~(negatives["days"] >= negatives["person_id"].map(first))
last_negative = negatives[before].groupby("person_id")["days"].max()
coded = index_results(events, cytology, history)
window = cacu.PREVALENT_WINDOW_DAYS
event_days, free_until = coded["person_id"].map(first), coded["person_id"].map(last_negative)
prevalent = event_days <= window
free = free_until.notna() & ~prevalent
later = event_days.notna() & ~prevalent
coded["c"] = np.where(prevalent, 1, np.where(free, 0, -999))
coded["l"] = np.where(free & (free_until > window), free_until / cacu.DAYS_PER_YEAR, 0.0)
coded["r"] = np.where(prevalent, 0.0,
np.where(later, event_days / cacu.DAYS_PER_YEAR, np.inf)) # fmt: skip
return coded
def last_screening_cytology(events: pd.DataFrame) -> pd.Series:
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),
[*key, "date"]] # fmt: skip
results = events[events["type"].isin(RESULTS) & events["value_code"].notna()]
has = results.pivot_table(index=key, columns="type", values="value_code", aggfunc="first")
has = has.reindex(columns=list(RESULTS))
complete = has[(has["bethesda"].notna() | has["glandular"].notna()) & has["hpv"].notna()]
samples = samples.set_index(key)
samples = samples[samples.index.isin(complete.index)].reset_index()
latest = samples.sort_values(["person_id", "date", "source_id"]).groupby("person_id").last()
return latest["date"]
def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]:
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:
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"])]
sample = sample.groupby("person_id", as_index=False)[["source_table", "source_id"]].first()
results = events.merge(sample, on=["person_id", "source_table", "source_id"])
genotype = results["type"] == "hpv_16_18"
results.loc[genotype, "value_code"] = results.loc[genotype, "value_num"].map(
{1.0: "positive", 0.0: "negative"}
)
wide = results[results["type"].isin(predictors)].pivot_table(
index="person_id", columns="type", values="value_code", aggfunc="first"
)
wide = wide.reindex(columns=list(predictors)).astype(object)
found = members.merge(wide, left_on="person_id", right_index=True, how="left")
return found.fillna(dict.fromkeys(predictors, MISSING))
def windowed_outcome(events: pd.DataFrame, grades: list[str], years: float,
follow_up_end: pd.Timestamp) -> pd.DataFrame: # fmt: skip
window = years * cacu.DAYS_PER_YEAR
outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades)
outcome &= days(events).between(0, window)
members = events.groupby(["person_id", "index_date"], as_index=False).size()
members["y"] = members["person_id"].isin(events.loc[outcome, "person_id"]).astype(int)
followed = (follow_up_end - members["index_date"]).dt.days
members["known"] = (members["y"] == 1) | (followed >= window)
return members[["person_id", "y", "known"]]
+6
View File
@@ -0,0 +1,6 @@
from models.cacu import reports
from models.cacu.specs import MODELS
from models.jobs import Jobs
JOBS = Jobs("cacu", MODELS, reports.technical_validation, reports.interpretability)
train, score = JOBS.train, JOBS.score
+238
View File
@@ -0,0 +1,238 @@
from dataclasses import dataclass
import numpy as np
import pandas as pd
from scipy.interpolate import BSpline
from scipy.optimize import minimize
from scipy.special import expit
from scipy.stats import norm
from sklearn.base import BaseEstimator
UNKNOWN = -999
TINY = 1e-12
FROZEN = 15.0
HESSIAN_STEP = 1e-4
def ispline_basis(t, degree: int, knots) -> np.ndarray:
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])
bsplines = BSpline.design_matrix(inside, full, degree, extrapolate=False).toarray()
basis = np.cumsum(bsplines[:, ::-1], axis=1)[:, ::-1][:, 1:]
basis[t >= knots[-1]] = 1.0
basis[t <= knots[0]] = 0.0
return basis
@dataclass(frozen=True)
class ISpline:
knots: tuple[float, ...]
degree: int
@classmethod
def at_quantiles(cls, l, r, n_knots: int, degree: int) -> "ISpline":
times = np.unique(np.r_[l, r[np.isfinite(r)]])
return cls(tuple(float(k) for k in np.quantile(times, np.linspace(0, 1, n_knots))), degree)
@property
def n_params(self) -> int:
return len(self.knots) + self.degree - 2
def cumulative_hazard(self, t, params) -> np.ndarray:
return ispline_basis(t, self.degree, self.knots) @ np.exp(params)
def start(self, c, l, r) -> np.ndarray:
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()
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))
def survival(t, baseline: ISpline, baseline_params, beta, Z) -> np.ndarray:
t = np.asarray(t, dtype=float)
with np.errstate(over="ignore", invalid="ignore"):
found = np.exp(-baseline.cumulative_hazard(t, baseline_params) * np.exp(Z @ beta))
found = np.where(t <= 0, 1.0, found)
return np.where(np.isinf(t), 0.0, found)
def neg_loglik(params, c, l, r, X, Z, baseline: ISpline, w) -> float:
n_x, n_z = X.shape[1], Z.shape[1]
theta, beta, rest = params[:n_x], params[n_x : n_x + n_z], params[n_x + n_z :]
pi = expit(X @ theta)
interval = survival(l, baseline, rest, beta, Z) - survival(r, baseline, rest, beta, Z)
interval = np.maximum(interval, TINY)
row = np.zeros(len(c))
prevalent, free, unknown = c == 1, c == 0, c == UNKNOWN
row[prevalent] = np.log(pi[prevalent] + TINY)
row[free] = np.log(1 - pi[free] + TINY) + np.log(interval[free])
row[unknown] = np.log(pi[unknown] + (1 - pi[unknown]) * interval[unknown] + TINY)
return -np.sum(w * row)
def hessian(f, x, step: float = HESSIAN_STEP) -> np.ndarray:
p = len(x)
out = np.zeros((p, p))
for i in range(p):
for j in range(i, p):
ei, ej = np.zeros(p), np.zeros(p)
ei[i], ej[j] = step, step
value = (f(x + ei + ej) - f(x + ei - ej) - f(x - ei + ej) + f(x - ei - ej)) / (
4 * step * step
)
out[i, j] = out[j, i] = value
return out
def _ridge_logistic(c, X, ridge: float = 1e-3) -> np.ndarray:
known = c != UNKNOWN
if not known.any():
return np.zeros(X.shape[1])
y, Xk = (c[known] == 1).astype(float), X[known]
def loss(theta):
eta = Xk @ theta
return np.sum(np.logaddexp(0, eta) - y * eta) + ridge * theta @ theta
return minimize(loss, np.zeros(X.shape[1]), method="BFGS").x
@dataclass(frozen=True)
class Fit:
n_x: int
n_z: int
baseline: ISpline
params: np.ndarray
covariance: np.ndarray
neg_loglik: float
converged: bool
def risk(self, X, Z, years, params=None) -> np.ndarray:
p = self.params if params is None else params
theta, beta, rest = (
p[: self.n_x],
p[self.n_x : self.n_x + self.n_z],
p[self.n_x + self.n_z :],
)
pi = expit(X @ theta)
return np.column_stack([
pi + (1 - pi) * (1 - survival(np.full(len(X), float(t)), self.baseline, rest, beta, Z))
for t in years
]) # fmt: skip
def risk_with_variance(self, X, Z, years) -> tuple[np.ndarray, np.ndarray]:
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))
up, down = self.params.copy(), self.params.copy()
up[k] += step
down[k] -= step
gradient[k] = (self.risk(X, Z, years, up) - self.risk(X, Z, years, down)) / (2 * step)
covariance = np.nan_to_num(self.covariance, nan=0.0)
variance = np.einsum("kij,kl,lij->ij", gradient, covariance, gradient)
return self.risk(X, Z, years), np.maximum(variance, 0.0)
def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit:
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]]
args = (c, l, r, X, Z, baseline, w)
results = [minimize(neg_loglik, s, args=args, method="BFGS") for s in starts]
best = min(results, key=lambda res: res.fun if np.isfinite(res.fun) else np.inf)
free = np.abs(best.x) < FROZEN
covariance = np.full((len(best.x), len(best.x)), np.nan)
h = hessian(lambda p: neg_loglik(p, *args), best.x)
try:
covariance[np.ix_(free, free)] = np.linalg.inv(h[np.ix_(free, free)])
except np.linalg.LinAlgError:
pass
converged = bool(np.max(np.abs(best.jac[free]), initial=0.0) < 1e-3)
return Fit(n_x, n_z, baseline, best.x, covariance, float(best.fun), converged)
class Mixture(BaseEstimator):
def __init__(self, horizons_years, incidence_features, strata, levels, knots=3, degree=4,
interval_level=0.95): # fmt: skip
self.horizons_years = horizons_years
self.incidence_features = incidence_features
self.strata = strata
self.levels = levels
self.knots = knots
self.degree = degree
self.interval_level = interval_level
def _seen(self, X: pd.DataFrame) -> dict:
return {
f: [v for v in values if (X[f] == v).any()]
for f, values in self.levels.items()
if f in X.columns and f not in self.strata
}
def _placed(self, X: pd.DataFrame, seen: dict) -> np.ndarray:
if not seen:
return np.ones(len(X), dtype=bool)
return np.all([X[f].isin(values).to_numpy() for f, values in seen.items()], axis=0)
def _columns(self, X: pd.DataFrame, features, seen: dict) -> np.ndarray:
columns = []
for f in features:
if f in self.strata:
continue
if f in seen:
columns += [(X[f] == v).to_numpy(dtype=float) for v in seen[f][1:]]
else:
columns.append(X[f].to_numpy(dtype=float))
return np.column_stack(columns) if columns else np.zeros((len(X), 0))
def _design(self, X: pd.DataFrame, seen: dict) -> tuple[np.ndarray, np.ndarray]:
prevalence = np.column_stack([np.ones(len(X)), self._columns(X, X.columns, seen)])
return prevalence, self._columns(X, self.incidence_features, seen)
def _groups(self, X: pd.DataFrame):
if not self.strata:
return [((), np.arange(len(X)))]
groups = X.groupby(list(self.strata), sort=True).indices.items()
return [(key if isinstance(key, tuple) else (key,), rows) for key, rows in groups]
def fit(self, X: pd.DataFrame, y: pd.DataFrame):
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_ = {}, {}
for key, index in self._groups(X):
group = rows.iloc[index]
seen = self._seen(group)
group = group[self._placed(group, seen)]
group = group.groupby([*X.columns, "c", "l", "r"], as_index=False)["w"].sum()
prevalence, incidence = self._design(group[X.columns], seen)
c, l, r = (group[k].to_numpy(dtype=float) for k in ("c", "l", "r"))
baseline = ISpline.at_quantiles(l, r, self.knots, self.degree)
self.seen_[key] = seen
self.fits_[key] = fit(c, l, r, prevalence, incidence, baseline, group["w"].to_numpy())
self.neg_loglik_ = float(sum(f.neg_loglik for f in self.fits_.values()))
self.converged_ = all(f.converged for f in self.fits_.values())
return self
def predict(self, X: pd.DataFrame) -> np.ndarray:
h = len(self.horizons_years)
out = np.full((len(X), 3 * h), np.nan)
z = norm.ppf(0.5 + self.interval_level / 2)
for key, index in self._groups(X):
if key not in self.fits_:
continue
members = X.iloc[index]
placed = self._placed(members, self.seen_[key])
prevalence, incidence = self._design(members[placed], self.seen_[key])
design = np.column_stack([prevalence, incidence])
unique, inverse = np.unique(design, axis=0, return_inverse=True)
n_x = prevalence.shape[1]
point, variance = self.fits_[key].risk_with_variance(
unique[:, :n_x], unique[:, n_x:], self.horizons_years
)
relative = np.where(point > 0, np.sqrt(variance) / np.maximum(point, 1e-300), 0.0)
band = np.column_stack([point, np.clip(point * np.exp(-z * relative), 0, 1),
np.clip(point * np.exp(z * relative), 0, 1)]) # fmt: skip
out[index[placed]] = band[inverse.ravel()]
return out
+159
View File
@@ -0,0 +1,159 @@
import numpy as np
import pandas as pd
from scipy.stats import norm
from sklearn.metrics import brier_score_loss
from models import survival
from models.cacu.pim import Mixture
from models.cacu.specs import Logistic, Pim
GRID_STEP = 0.1
BOOTSTRAP = 200
SEED = 20261122
Z = norm.ppf(0.975)
def technical_validation(spec: Pim | Logistic | survival.Spec, metrics: dict, data: dict) -> dict:
if isinstance(spec, survival.Spec):
return survival.technical_validation(spec, metrics, data)
members = data.get("coded", data.get("labelled"))
return {
"model": spec.name,
"method": spec.method,
"cohort": spec.cohort,
"split": "temporal: the earliest 70% of index dates train, the latest 30% test",
"members": len(members),
"index_dates": [str(members["index_date"].min()), str(members["index_date"].max())],
"metrics": metrics,
}
def turnbull(c, l, r, iters: int = 5000, tol: float = 1e-10):
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)
inside = (support[None, :] > low[:, None]) & (support[None, :] <= high[:, None])
patterns, counts = np.unique(inside, axis=0, return_counts=True)
p = np.full(len(support), 1 / len(support))
for _ in range(iters):
weighted = patterns * p
new = (counts[:, None] * weighted / weighted.sum(1, keepdims=True)).sum(0) / counts.sum()
done = np.max(np.abs(new - p)) < tol
p = new
if done:
break
return support, np.cumsum(p)
def _at(support, cumulative, t) -> np.ndarray:
i = np.searchsorted(support, np.asarray(t, dtype=float), side="right") - 1
return np.where(i < 0, 0.0, cumulative[np.maximum(i, 0)])
def _label(feature: str, value) -> str:
if value is None or (isinstance(value, float) and np.isnan(value)):
return "NA"
if feature == "hpv_positive":
return "positive" if float(value) == 1.0 else "negative"
return str(value)
def _band(curve, variance) -> tuple[list, list]:
relative = np.where(curve > 0, np.sqrt(variance) / np.maximum(curve, 1e-300), 0.0)
return (np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(),
np.clip(curve * np.exp(Z * relative), 0, 1).tolist()) # fmt: skip
def _mixture_curve(mixture: Mixture, row: pd.DataFrame, years) -> tuple | None:
key = tuple(row[list(mixture.strata)].iloc[0]) if mixture.strata else ()
if key not in mixture.fits_ or not mixture._placed(row, mixture.seen_[key]).all():
return None
prevalence, incidence = mixture._design(row, mixture.seen_[key])
point, variance = mixture.fits_[key].risk_with_variance(prevalence, incidence, years)
return point[0], variance[0]
def interpretability(spec: Pim | Logistic | survival.Spec, model, data: dict) -> dict:
if isinstance(spec, survival.Spec):
return survival.interpretability(spec, model, data)
if isinstance(spec, Logistic):
return _logistic(model, data["test"])
coded = data["coded"]
full = Mixture(spec.horizons, spec.incidence_features, spec.strata,
model.levels).fit(coded[spec.features], coded[["c", "l", "r"]]) # fmt: skip
members = coded.reset_index(drop=True)
labels = pd.DataFrame({f: members[f].map(lambda v, f=f: _label(f, v)) for f in spec.features})
horizons = np.asarray(spec.horizons, dtype=float)
grid = np.round(np.arange(0, horizons.max() + GRID_STEP / 2, GRID_STEP), 6)
rng = np.random.default_rng(SEED)
groups = []
for _, combination in labels.drop_duplicates().iterrows():
mask = (labels == combination).all(axis=1).to_numpy()
group = members[mask]
c, l, r = (group[k].to_numpy(dtype=float) for k in ("c", "l", "r"))
support, cumulative = turnbull(c, l, r)
boot_grid, boot_h = [], []
for _ in range(BOOTSTRAP):
pick = rng.integers(0, len(group), len(group))
s, cum = turnbull(c[pick], l[pick], r[pick])
boot_grid.append(_at(s, cum, grid))
boot_h.append(_at(s, cum, horizons))
observed, var_observed = _at(support, cumulative, horizons), np.var(boot_h, axis=0, ddof=1)
entry = {
"combination": combination.to_dict(),
"n": int(mask.sum()),
"prevalent": int((c == 1).sum()),
"incident": int(((c != 1) & np.isfinite(r)).sum()),
"observed": {"years": grid.tolist(), "risk": _at(support, cumulative, grid).tolist(),
"low": np.percentile(boot_grid, 2.5, axis=0).tolist(),
"high": np.percentile(boot_grid, 97.5, axis=0).tolist()},
"predicted": None,
"expected_over_observed": [],
} # fmt: skip
probe = group.iloc[[0]][spec.features]
at_grid, at_h = _mixture_curve(full, probe, grid), _mixture_curve(full, probe, horizons)
if at_grid is not None:
low, high = _band(*at_grid)
entry["predicted"] = {"years": grid.tolist(), "risk": at_grid[0].tolist(),
"low": low, "high": high} # fmt: skip
for k, h in enumerate(horizons):
e = None if at_h is None else float(at_h[0][k])
ratio = {"years": float(h), "expected": e, "observed": float(observed[k]),
"ratio": None, "low": None, "high": None} # fmt: skip
if e and observed[k] > 0 and np.isfinite(var_observed[k]):
se = np.sqrt(at_h[1][k] / e**2 + var_observed[k] / observed[k] ** 2)
value = e / observed[k]
ratio |= {"ratio": value, "low": value * np.exp(-Z * se),
"high": value * np.exp(Z * se)} # fmt: skip
entry["expected_over_observed"].append(ratio)
groups.append(entry)
groups.sort(key=lambda g: (-g["n"], list(g["combination"].values())))
return {"model": spec.name, "kind": "subgroups", "bootstrap": BOOTSTRAP, "seed": SEED,
"groups": groups} # fmt: skip
def _logistic(model, test: pd.DataFrame, bins: int = 10) -> dict:
classifier, encoder = model.named_steps["classify"], model.named_steps["encode"]
names = encoder.get_feature_names_out()
p = test["p"]
deciles = pd.qcut(p, q=min(bins, p.nunique()), duplicates="drop")
table = test.groupby(deciles, observed=True).agg(n=("y", "size"), predicted=("p", "mean"),
observed=("y", "mean")) # fmt: skip
return {
"model": "logistic regression",
"kind": "coefficients",
"intercept": float(classifier.intercept_[0]),
"coefficients": dict(zip(map(str, names), map(float, classifier.coef_[0]), strict=True)),
"calibration": {
"brier": float(brier_score_loss(test["y"], p)),
"bins": [
{
"range": str(k),
"n": int(v.n),
"predicted": float(v.predicted),
"observed": float(v.observed),
}
for k, v in table.iterrows()
],
}, # fmt: skip
}
+189
View File
@@ -0,0 +1,189 @@
from dataclasses import dataclass, field
from typing import Literal
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, roc_auc_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
from core import cacu
from models.cacu import features as f
from models.cacu.pim import Mixture
from models.survival import Spec, age_group
HORIZONS = (0.0, 1.0, 2.0, 3.0, 4.0, 5.0)
TRAIN_FRACTION = 0.7
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high"]
def _rows(members: pd.DataFrame, risks: np.ndarray, horizons) -> pd.DataFrame:
h = len(horizons)
scored = ~np.isnan(risks[:, :h]).any(axis=1)
members, risks = members[scored], risks[scored]
n = len(members)
frame = pd.DataFrame({
"person_id": np.repeat(members["person_id"].to_numpy(), h),
"index_date": np.repeat(pd.to_datetime(members["index_date"]).dt.date.to_numpy(), h),
"horizon_years": np.tile(np.asarray(horizons, dtype=float), n),
"probability": risks[:, :h].ravel(),
}) # fmt: skip
if risks.shape[1] == 3 * h:
frame["ci_low"], frame["ci_high"] = risks[:, h : 2 * h].ravel(), risks[:, 2 * h :].ravel()
else:
frame["ci_low"] = frame["ci_high"] = np.nan
return frame[OUTPUT]
@dataclass(frozen=True)
class Pim:
name: str
cohort: str
grades: list[str]
cytology: dict[str, list[str]]
strata: tuple[str, ...]
incidence_features: tuple[str, ...]
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)
@property
def features(self) -> list[str]:
return ["cytology", "hpv_positive"] + ([self.history["feature"]] if self.history else [])
def _history(self) -> dict | None:
return self.history and {**self.history, "cytology": self.cytology}
def train(self, events: pd.DataFrame, as_of=None) -> tuple[Mixture, dict, dict]:
events = f.prepared(events)
coded = f.interval_coded(events, self.grades, self.cytology, self._history())
train, test = f.split(coded, TRAIN_FRACTION)
levels = {"cytology": list(self.cytology)}
if self.history:
levels[self.history["feature"]] = list(self.history["levels"])
mixture = Mixture(self.horizons, self.incidence_features, self.strata, levels)
mixture.fit(train[self.features], train[["c", "l", "r"]])
return mixture, self.metrics(mixture, train, test), {"coded": coded}
def metrics(self, mixture: Mixture, train, test) -> dict:
found = {
"n_train": len(train),
"n_test": len(test),
"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_,
"converged": float(mixture.converged_),
}
risks = mixture.predict(test[self.features])
for column, horizon in enumerate(self.horizons):
case = (test["c"] == 1) | ((test["c"] != 1) & (test["r"] <= horizon))
free = (test["c"] == 0) & (test["l"] >= horizon) & ~case
status = np.where(case, 1.0, np.where(free, 0.0, np.nan))
known = ~np.isnan(status) & ~np.isnan(risks[:, column])
y, p, tag = status[known], risks[known, column], f"{horizon:g}y"
found[f"n_known_{tag}"] = int(known.sum())
if known.any():
found[f"observed_{tag}"] = float(y.mean())
found[f"expected_{tag}"] = float(p.mean())
found[f"brier_{tag}"] = float(np.mean((p - y) ** 2))
if len(np.unique(y)) == 2:
found[f"auc_{tag}"] = float(roc_auc_score(y, p))
return found
def predict(self, mixture: Mixture, events: pd.DataFrame) -> pd.DataFrame:
events = f.prepared(events)
if self.predict_at == "last_screening_cytology":
chosen = f.last_screening_cytology(events)
events = events[events["person_id"].isin(chosen.index)]
events = events.assign(index_date=events["person_id"].map(chosen))
members = f.index_results(events, self.cytology, self._history())
members = members.sort_values("person_id", kind="stable").reset_index(drop=True)
return _rows(members, mixture.predict(members[self.features]), self.horizons)
@dataclass(frozen=True)
class Logistic:
name: str
cohort: str
grades: list[str]
predictors: tuple[str, ...] = ("bethesda", "hpv", "hpv_16_18")
years: float = 1.0
method: str = field(default="logistic regression", init=False)
def train(self, events: pd.DataFrame, follow_up_end) -> tuple[Pipeline, dict, dict]:
events = f.prepared(events)
found = f.index_sample(events, list(self.predictors))
outcome = f.windowed_outcome(events, self.grades, self.years,
pd.Timestamp(follow_up_end)) # fmt: skip
labelled = found.merge(outcome, on="person_id")
labelled = labelled[labelled["known"]].reset_index(drop=True)
train, test = f.split(labelled, TRAIN_FRACTION)
X = list(self.predictors)
model = Pipeline([("encode", OneHotEncoder(handle_unknown="ignore")),
("classify", LogisticRegression(max_iter=1000))]) # fmt: skip
model.fit(train[X], train["y"])
p = model.predict_proba(test[X])[:, 1]
metrics = {
"n_train": len(train),
"n_test": len(test),
"events_train": float(train["y"].sum()),
"events_test": float(test["y"].sum()),
"auc": float(roc_auc_score(test["y"], p)),
"brier": float(brier_score_loss(test["y"], p)),
"positive_rate_train": float(train["y"].mean()),
"positive_rate_test": float(test["y"].mean()),
"mean_probability_test": float(p.mean()),
}
return model, metrics, {"labelled": labelled, "test": test.assign(p=p)}
def predict(self, model: Pipeline, events: pd.DataFrame) -> pd.DataFrame:
members = f.index_sample(f.prepared(events), list(self.predictors))
members = members.sort_values("person_id", kind="stable").reset_index(drop=True)
p = model.predict_proba(members[list(self.predictors)])[:, 1]
return _rows(members, p[:, None], (self.years,))
def survival_covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
found = pd.DataFrame(index=members.index)
found["age_group"] = age_group(events, members, (35, 45, 55))
prior = events[events["date"] <= events["index_date"]]
names = list(cacu.KPNC)
severity = {code: rank for rank, codes in enumerate(cacu.KPNC.values()) for code in codes}
results = prior[(prior["type"] == "bethesda") & prior["value_code"].notna()]
latest = results[results["date"] == results.groupby("person_id")["date"].transform("max")]
ranks = latest["value_code"].map(severity).groupby(latest["person_id"]).max()
found["cytology"] = ranks.map(lambda r: None if pd.isna(r) else names[int(r)])
hpv = prior[(prior["type"] == "hpv") & prior["value_code"].notna()]
hpv = hpv.sort_values(["date", "source_id"])
found["hpv"] = hpv.groupby("person_id")["value_code"].last()
return found.astype(object)
_REFERRAL = {
"feature": "referral_grade", "lookback_days": cacu.REFERRAL_LOOKBACK_DAYS,
"levels": ["low", "high"], "low": ["ASC-US/LSIL"], "low_if_hpv_positive": ["NILM"],
"high": ["High Grade"],
} # fmt: skip
MODELS = {
m.name: m
for m in [
Pim("cin2_pim", "cacu_cohort_surveillance", cacu.CIN2_PLUS, cacu.KPNC,
strata=("hpv_positive",), incidence_features=("cytology",),
predict_at="last_screening_cytology"),
Pim("cancer_pim", "cacu_cohort_surveillance", cacu.CANCER, cacu.KPNC,
strata=("hpv_positive",), incidence_features=("cytology",),
predict_at="last_screening_cytology"),
Pim("cin2_pim_post_colposcopy", "cacu_cohort_post_colposcopy", cacu.CIN2_PLUS,
cacu.KPNC_3, strata=("referral_grade",),
incidence_features=("cytology", "hpv_positive"), history=_REFERRAL),
Pim("cin2_pim_post_treatment", "cacu_cohort_post_treatment", cacu.CIN2_PLUS,
cacu.KPNC_3, strata=(), incidence_features=("cytology", "hpv_positive")),
Logistic("cin2_logistic", "cacu_cohort_surveillance", cacu.CIN2_PLUS),
Spec("survival", "cacu_cohort_survival", ("age_group", "cytology", "hpv"),
survival_covariates, borders=(0, 12, 36, 60), cap_months=60,
interval_level=0.95),
]
} # fmt: skip
-19
View File
@@ -1,19 +0,0 @@
from typing import Any
from models.base import ScreeningModel
class CaMaModel(ScreeningModel):
"""Scaffold for the CaMa (breast cancer) screening model.
Can pull its own training data straight from `persistance.cama`'s
repositories (`paciente_repository`, `mastografia_repository`,
`biopsia_mama_repository`, ...) or be handed already-fetched rows.
No real model yet — this is interface scaffolding only.
"""
def train(self, data: Any = None) -> None:
raise NotImplementedError("CaMa training is not implemented yet.")
def predict(self, data: Any) -> Any:
raise NotImplementedError("CaMa prediction is not implemented yet.")
View File
+6
View File
@@ -0,0 +1,6 @@
from models import survival
from models.cama.specs import MODELS
from models.jobs import Jobs
JOBS = Jobs("cama", MODELS, survival.technical_validation, survival.interpretability)
train, score = JOBS.train, JOBS.score
+73
View File
@@ -0,0 +1,73 @@
from dataclasses import dataclass
import joblib
import numpy as np
import pandas as pd
from models.cama.recurrence import calculator, cohorts, factors, modeling, reports
HORIZONS = modeling.HORIZONS
@dataclass
class Recurrence:
cohort: str
horizons: tuple[int, ...]
covariates: list[str]
tables: dict[int, dict]
def predict(self, X: pd.DataFrame) -> pd.DataFrame:
found = X[self.covariates].astype(object)
found = found.where(found.notna(), cohorts.UNKNOWN).astype(str)
dummies = pd.get_dummies(found).astype(float)
out = {}
for h in self.horizons:
t = self.tables[h]
p_lr = np.full(len(found), t["lr_prior"])
if t["lr_terms"]:
x = dummies.reindex(columns=t["lr_terms"], fill_value=0.0).to_numpy()
logit = t["lr_constant"] + x @ np.asarray(t["lr_coefficients"])
p_lr = 1 / (1 + np.exp(-logit))
p_hbn = np.full(len(found), t["hbn_prior"])
if t["hbn_parents"]:
keys = map(tuple, found[t["hbn_parents"]].to_numpy())
p_hbn = np.array([t["hbn_cpt"].get(k, t["hbn_prior"]) for k in keys])
out[f"recurrence_{h}m"] = (p_lr + p_hbn) / 2
return pd.DataFrame(out, index=X.index)
def train_site(rows: pd.DataFrame, bootstrap: bool = True) -> tuple[Recurrence, dict, dict]:
from models.cama.recurrence import site
return fit({"site": site.prepare(rows)}, "site", "site",
modeling.N_BOOTSTRAP if bootstrap else {}) # fmt: skip
def fit(found: dict, saved: str, label: str,
n_bootstrap: dict[str, int]) -> tuple[Recurrence, dict, dict]: # fmt: skip
sources = list(found)
try:
fits = modeling.fit(found, n_bootstrap)
drawn = {s: calculator.calculator(fits[s]) for s in sources}
finally:
joblib.externals.loky.get_reusable_executor().shutdown(wait=True)
table = pd.concat([factors.risk_factors(fits[s]) for s in sources], ignore_index=True)
summary = [row for s in sources for row in factors.scenario_summary(fits[s], table)]
auc = [row for s in sources for row in reports.auc_rows(fits[s])]
points = [row for s in sources for row in drawn[s][1]]
kept = fits[saved]
model = Recurrence(saved, HORIZONS, kept.cohort.covariates, modeling.tables(kept))
technical = {
"model": "recurrence",
"cohort": label,
"method": "stepwise logistic regression + Bayesian network (BDeu), averaged",
"rutinas": reports.routines(found, n_bootstrap),
"recurrencia_desarrollo": reports.development(auc, table, points, summary),
}
interpretability = {
"model": "recurrence",
"kind": "scenarios",
"recurrencia": reports.figures([r for s in sources for r in drawn[s][0]]),
}
reports_ = {"technical_validation": technical, "interpretability": interpretability}
return model, reports.metrics(auc), reports_
+158
View File
@@ -0,0 +1,158 @@
from dataclasses import dataclass
import numpy as np
import pandas as pd
import statsmodels.api as sm
from joblib import Parallel, delayed
from models import curves
from models.cama.recurrence.modeling import ESS, HORIZONS, SEED, CohortFit, logit
RESAMPLES = 200
MIN_EVENTS = 15
CAP_MONTHS = 72
GRID_POINTS = 289
def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
return {
name: np.logical_and.reduce([frame[v].isin(c).to_numpy() for v, c in cond.items()])
for name, cond in scenarios.items()
}
@dataclass
class Risk:
fitted: CohortFit
def __post_init__(self):
frame, covariates = self.fitted.cohort.frame, self.fitted.cohort.covariates
self.n = len(frame)
self.X = pd.get_dummies(frame[covariates], drop_first=True).astype(float)
self.codes = {v: pd.factorize(frame[v])[0] for v in covariates}
self.levels = {v: int(c.max()) + 1 for v, c in self.codes.items()}
self.time, self.event = frame["tiempo_meses"].to_numpy(), frame["evento"].to_numpy()
def _key(self, chosen, rows) -> np.ndarray:
key = np.zeros(len(rows), dtype=np.int64)
for p in chosen:
key = key * self.levels[p] + self.codes[p][rows]
return key
def _combined(self, rows, horizon) -> np.ndarray | None:
t, e = self.time[rows], self.event[rows]
recurred = (e == 1) & (t <= horizon)
known = recurred | (t > horizon)
train, y = rows[known], recurred[known].astype(int)
split = self.fitted.horizons[horizon].split
p_lr = p_hbn = np.full(self.n, y.mean())
if split.terms:
m = logit(y, self.X.iloc[train][split.terms].reset_index(drop=True), "add")
if m is None:
return None
p_lr = m.predict(sm.add_constant(self.X[split.terms], has_constant="add")).to_numpy()
if split.parents:
q = int(np.prod([self.levels[p] for p in split.parents]))
a = ESS / (2 * q)
key = self._key(split.parents, train)
table = (pd.Series(y, index=key).groupby(level=0).sum() + a) / (
pd.Series(1, index=key).groupby(level=0).sum() + 2 * a
)
everyone = self._key(split.parents, np.arange(self.n))
p_hbn = table.reindex(everyone).fillna(y.mean()).to_numpy()
return (p_lr + p_hbn) / 2
def mean_risk(self, rows, scenario_masks) -> dict[str, np.ndarray] | None:
out = {name: np.full(len(HORIZONS), np.nan) for name in scenario_masks}
for j, h in enumerate(HORIZONS):
combined = self._combined(rows, h)
if combined is None:
return None
for name, mask in scenario_masks.items():
inside = mask[rows]
if inside.any():
out[name][j] = combined[rows][inside].mean()
return out
def _curves(months, event, observed):
d, c, _ = curves.life_table(months, event)
k, lam = curves.fit_weibull(d, c)
fractional = curves.fit_fractional(d, c, k, lam)
grid = np.linspace(0, CAP_MONTHS, GRID_POINTS)
return {
"km": dict(
zip(("S", "low", "high"), curves.kaplan_meier(months, event, observed), strict=True)
),
"weibull": curves.weibull(grid, k, lam),
"weibull_fractional": curves.fractional(grid, k, *fractional),
"grid": grid,
}
def calculator(fitted: CohortFit) -> tuple[list[dict], list[dict]]:
source = fitted.cohort.source
scenarios = fitted.cohort.scenarios
risk = Risk(fitted)
found = masks(fitted.cohort.frame, scenarios)
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]
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]
records, rows = [], []
for (name, mask), drawn_curves in zip(drawn.items(), fitted_curves, strict=True):
free = 1 - point[name]
risks = np.array([r[name] for r in replicas])
low, high = 1 - np.nanpercentile(risks, [97.5, 2.5], axis=0)
observed, n, events = int(months[mask].max()), int(mask.sum()), int(event[mask].sum())
km, grid = drawn_curves["km"], drawn_curves["grid"].tolist()
records.append(
{
"cohorte": source,
"cohorte_nombre": fitted.cohort.label,
"escenario": name,
"condiciones": scenarios[name],
"n": n,
"recaidas": events,
"horizons_months": list(HORIZONS),
"observado_hasta": observed,
"months_max": CAP_MONTHS,
"km": {
"months": list(range(observed + 1)),
**{k: v.tolist() for k, v in km.items()},
},
"weibull": {"t": grid, "S": drawn_curves["weibull"].tolist()},
"weibull_fractional": {"t": grid, "S": drawn_curves["weibull_fractional"].tolist()},
"points": {
"COMB": {
"S": free.tolist(),
"low": np.clip(low, 0, 1).tolist(),
"high": np.clip(high, 0, 1).tolist(),
}
},
"bootstrap_replicas": len(replicas),
}
)
for j, h in enumerate(HORIZONS):
rows.append(
{
"cohorte": source,
"subgrupo": name,
"n": n,
"recaidas": events,
"horizonte_meses": h,
"S_libre_LR_HBN": free[j],
"IC95_inf": low[j],
"IC95_sup": high[j],
"riesgo_recurrencia": 1 - free[j],
"S_libre_KM": km["S"][min(h, observed)] if h <= observed else np.nan,
"replicas_bootstrap": len(replicas),
}
)
return records, rows
+77
View File
@@ -0,0 +1,77 @@
from dataclasses import dataclass
import pandas as pd
from scipy.stats.contingency import association
UNKNOWN = "Desconocido"
V_MAX = 0.80
DAYS_PER_MONTH = 30.4375
HORIZONS = (12, 36, 60)
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+"])
GRADES = {"1": "1", "2": "2", "3": "3"}
def _number(s: pd.Series) -> pd.Series:
return pd.to_numeric(s, errors="coerce")
def _text(s: pd.Series) -> pd.Series:
return s.astype(object).where(s.notna(), UNKNOWN).astype(str)
def _band(s: pd.Series, edges: list, labels: list) -> pd.Series:
return _text(pd.cut(s, edges, labels=labels, right=False).astype(object))
def cramers_v(a: pd.Series, b: pd.Series) -> float:
table = pd.crosstab(a, b).to_numpy()
return association(table, method="cramer") if min(table.shape) > 1 else 0.0
def collinear(frame: pd.DataFrame, candidates: list[str], v_max: float = V_MAX) -> list[str]:
pairs = sorted(
(
(cramers_v(frame[a], frame[b]), a, b)
for i, a in enumerate(candidates)
for b in candidates[i + 1 :]
),
reverse=True,
)
unknown = {c: (frame[c] == UNKNOWN).mean() for c in candidates}
dropped = []
for v, a, b in pairs:
if v < v_max:
break
if a not in dropped and b not in dropped:
dropped.append(a if unknown[a] >= unknown[b] else b)
return dropped
@dataclass(frozen=True)
class Cohort:
source: str
frame: pd.DataFrame
covariates: list[str]
treatment: list[str]
eliminated: list[str]
label: str
scenarios: dict
sampling: dict
@property
def intrinsic(self) -> list[str]:
return [c for c in self.covariates if c not in self.treatment]
def at_horizon(frame: pd.DataFrame, horizon: int) -> pd.DataFrame:
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)
return found
def unknown_shares(cohort: Cohort) -> dict[str, float]:
return {c: float((cohort.frame[c] == UNKNOWN).mean()) for c in cohort.covariates}
+109
View File
@@ -0,0 +1,109 @@
import warnings
import numpy as np
import pandas as pd
from models import factors as rated
from models.cama.recurrence.calculator import masks
from models.cama.recurrence.cohorts import UNKNOWN, at_horizon
from models.cama.recurrence.modeling import CohortFit
from models.factors import FREQ_MIN, ORDER
OR = "OR_recurrencia"
SURVIVAL = ("S_libre_categoria", "S_libre_referencia", "delta_S")
TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)"
COLUMNS = [
"cohorte",
"horizonte_meses",
"tipo",
"variable",
"categoria",
"referencia",
"n_categoria",
OR,
"IC95_inf",
"IC95_sup",
"p",
"p_ajustado_BH",
"freq_seleccion_bootstrap",
"en_manta_markov",
*SURVIVAL,
"delta_IC95_inf",
"delta_IC95_sup",
"c1_or",
"c2_estabilidad",
"c3_manta_markov",
"c4_supervivencia",
"criterios_cumplidos",
"clasificacion",
]
DESCRIBING = rated.DESCRIBING
def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.DataFrame:
cohort = fitted.cohort
frame = at_horizon(cohort.frame, horizon)
data, y = frame[cohort.covariates].astype(str), frame["y"].to_numpy()
reference = {v: data[v].value_counts().idxmax() for v in cohort.covariates}
t, everyone = cohort.frame["tiempo_meses"].to_numpy(), cohort.frame[cohort.covariates]
months = np.floor(np.minimum(t, horizon + 1)).astype(int)
event = ((cohort.frame["evento"] == 1) & (t <= horizon)).to_numpy()
def complete(table, variables):
return rated.complete(table, variables, reference, everyone, months, event, horizon,
SURVIVAL) # fmt: skip
intrinsic, treatment = cohort.intrinsic, cohort.treatment
tab = complete(rated.odds_ratios(data, y, intrinsic, reference, OR), intrinsic)
hz = fitted.horizons[horizon]
tab["freq_seleccion_bootstrap"] = tab["variable"].map(
lambda v: np.nan if selection is None else selection.get(v, 0.0)
)
tab["c2_estabilidad"] = tab["freq_seleccion_bootstrap"] >= FREQ_MIN
tab["en_manta_markov"] = tab["c3_manta_markov"] = tab["variable"].isin(hz.split.parents)
tab = rated.classify(tab, OR, SURVIVAL[2], UNKNOWN)
tab["tipo"] = "factor de riesgo"
if treatment:
both = intrinsic + treatment
tr = rated.odds_ratios(data, y, both, reference, OR)
of = tr["termino"].map(lambda x: rated.variable_of(x, both))
tr = complete(
tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)], treatment
)
tr["tipo"], tr["clasificacion"] = "tratamiento", TREATMENT_CLASS
tab = pd.concat([tab, tr], ignore_index=True)
tab["cohorte"], tab["horizonte_meses"] = cohort.source, horizon
return tab
def risk_factors(fitted: CohortFit, selection: dict | None = None) -> pd.DataFrame:
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")
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)
tab["_order"] = tab["clasificacion"].map(ORDER).fillna(5)
keys = ["horizonte_meses", "_kind", "_order", OR]
tab = tab.sort_values(keys, ascending=[True, True, True, False])
return tab[COLUMNS].round(4)
def scenario_summary(fitted: CohortFit, factors: pd.DataFrame) -> list[dict]:
frame, source = fitted.cohort.frame, fitted.cohort.source
scenarios = fitted.cohort.scenarios
found = rated.classified(factors[factors["cohorte"] == source])
rows = []
for name, mask in masks(frame, scenarios).items():
if not mask.any() or found.empty:
continue
definition = "; ".join(f"{v} = {' / '.join(c)}" for v, c in scenarios[name].items())
for h in fitted.horizons:
rows.append({
"cohorte": source, "escenario": name, "definicion": definition,
"n_escenario": int(mask.sum()), "horizonte_meses": h,
**rated.scenario_row(frame, mask, found[found["horizonte_meses"] == h]),
}) # fmt: skip
return rows
+248
View File
@@ -0,0 +1,248 @@
import warnings
from dataclasses import dataclass, field
import numpy as np
import pandas as pd
import statsmodels.api as sm
from joblib import Parallel, delayed
from lifelines import CoxPHFitter
from lifelines.utils import concordance_index
from pgmpy.structure_score import BDeu
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from models.cama.recurrence.cohorts import HORIZONS, Cohort, at_horizon
from models.factors import variable_of
SEED = 42
TEST_SIZE = 0.3
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
N_BOOTSTRAP = {"site": 40}
def encode(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame:
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"):
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
X = sm.add_constant(X, has_constant=has_constant)
return sm.Logit(y, X).fit(disp=0, method="bfgs", maxiter=300)
except Exception:
return None
def stepwise(X: pd.DataFrame, y) -> list[str]:
included = []
for _ in range(MAX_STEPS):
changed, best, best_p = False, None, ALPHA_IN
for c in X.columns:
if c in included:
continue
m = logit(y, X[included + [c]])
if m is not None and m.pvalues[c] < best_p:
best, best_p = c, m.pvalues[c]
if best is not None:
included.append(best)
changed = True
if included and (m := logit(y, X[included])) is not None:
p = m.pvalues.drop("const")
if p.max() > ALPHA_OUT:
included.remove(p.idxmax())
changed = True
if not changed:
break
return included
def lr(train: pd.DataFrame, test: pd.DataFrame, covariates: list[str]):
X = encode(pd.concat([train, test]), covariates)
X_train = X.loc[train.index]
X_train = X_train.loc[:, X_train.nunique() > 1]
y = train["y"]
candidates = [
c
for c in X_train.columns
if (m := logit(y, X_train[[c]])) is not None and m.pvalues[c] < ALPHA_PREFILTER
]
terms = stepwise(X_train[candidates], y) if candidates else []
if not terms:
return [], np.full(len(test), y.mean())
m = logit(y, X_train[terms])
X_test = sm.add_constant(X.loc[test.index, terms], has_constant="add")
return terms, m.predict(X_test).to_numpy()
def bn_table(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame:
table = frame[covariates].astype(str)
table["outcome"] = frame["y"].astype(int).astype(str)
return table
def parents(table: pd.DataFrame, covariates: list[str]) -> list[str]:
score = BDeu(table, equivalent_sample_size=ESS)
chosen, current = [], score.local_score("outcome", ())
while len(chosen) < MAX_PARENTS:
best, gain = None, 0.0
for c in [c for c in covariates if c not in chosen]:
g = score.local_score("outcome", (*chosen, c)) - current
if g > gain:
best, gain = c, g
if best is None:
break
chosen.append(best)
current += gain
return chosen
def cpt(table: pd.DataFrame, chosen: list[str], q: int | None = None) -> dict[tuple, float]:
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")
return {
(k if isinstance(k, tuple) else (k,)): float((r.n1 + a) / (r.n + 2 * a))
for k, r in counts.iterrows()
}
def hbn(train: pd.DataFrame, test: pd.DataFrame, chosen: list[str]) -> np.ndarray:
rate = (train["outcome"] == "1").mean()
if not chosen:
return np.full(len(test), rate)
table = cpt(train, chosen)
return np.array([table.get(k, rate) for k in map(tuple, test[chosen].to_numpy())])
@dataclass(frozen=True)
class Split:
terms: list[str]
parents: list[str]
auc_lr: float
auc_hbn: float
def split_fit(frame: pd.DataFrame, covariates: list[str], seed: int = SEED) -> Split:
train, test = train_test_split(
frame, test_size=TEST_SIZE, random_state=seed, stratify=frame["y"]
)
terms, p_lr = lr(train, test, covariates)
bn_train, bn_test = bn_table(train, covariates), bn_table(test, covariates)
chosen = parents(bn_train, covariates)
p_hbn = hbn(bn_train, bn_test, chosen)
return Split(terms, chosen, roc_auc_score(test["y"], p_lr), roc_auc_score(test["y"], p_hbn))
def _replicate(frame, covariates, rows, b) -> Split | None:
try:
return split_fit(frame.iloc[rows].reset_index(drop=True), covariates, SEED + b)
except Exception:
return None
def c_index(cohort: Cohort) -> float:
time_event = ["tiempo_meses", "evento"]
X = pd.get_dummies(
cohort.frame[time_event + cohort.covariates], columns=cohort.covariates, drop_first=True
).astype(float)
X = X.loc[:, X.nunique() > 1]
train, test = train_test_split(X, test_size=TEST_SIZE, random_state=SEED, stratify=X["evento"])
n = len(train)
keep = [
c
for c in X.columns
if c in time_event or COX_MIN_COUNT <= train[c].sum() <= n - COX_MIN_COUNT
]
cox = CoxPHFitter(penalizer=COX_PENALIZER)
cox.fit(train[keep], "tiempo_meses", "evento", fit_options={"step_size": 0.5})
risk = cox.predict_partial_hazard(test[keep])
return float(concordance_index(test["tiempo_meses"], -risk, test["evento"]))
@dataclass
class Horizon:
n: int
events: int
split: Split
replicates: list[Split] = field(default_factory=list)
@property
def aucs(self) -> np.ndarray:
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:
if not self.replicates:
return None
counts = {}
for r in self.replicates:
for v in {variable_of(t, covariates) for t in r.terms}:
counts[v] = counts.get(v, 0) + 1
return {v: k / len(self.replicates) for v, k in counts.items()}
@dataclass
class CohortFit:
cohort: Cohort
c_index: float
horizons: dict[int, Horizon]
def fit(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict[str, CohortFit]:
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():
rng = np.random.default_rng(SEED)
rows = [rng.integers(0, len(frame), len(frame)) for _ in range(n_bootstrap.get(s, 0))]
tasks += [
((s, h, b), _replicate, (frame, cohorts[s].covariates, r, b))
for b, r in enumerate(rows)
]
tasks.append(((s, h, "split"), split_fit, (frame, cohorts[s].covariates)))
tasks += [((s, None, "cox"), c_index, (c,)) for s, c in cohorts.items()]
done = Parallel(n_jobs=-1)(delayed(f)(*args) for _, f, args in reversed(tasks))
results = dict(zip([key for key, _, _ in reversed(tasks)], done, strict=True))
out = {}
for s, cohort in cohorts.items():
horizons = {}
for h in HORIZONS:
frame = frames[(s, h)]
reps = [results[(s, h, b)] for b in range(n_bootstrap.get(s, 0))]
horizons[h] = Horizon(
len(frame),
int(frame["y"].sum()),
results[(s, h, "split")],
[r for r in reps if r is not None],
)
out[s] = CohortFit(cohort, results[(s, None, "cox")], horizons)
return out
def tables(fitted: CohortFit) -> dict[int, dict]:
found = {}
for h, hz in fitted.horizons.items():
frame = at_horizon(fitted.cohort.frame, h)
covariates, terms, chosen = fitted.cohort.covariates, hz.split.terms, hz.split.parents
prior = float(frame["y"].mean())
entry = {
"lr_prior": prior,
"lr_terms": terms,
"lr_constant": 0.0,
"lr_coefficients": [],
"hbn_parents": chosen,
"hbn_prior": prior,
"hbn_cpt": {},
}
if terms and (m := logit(frame["y"], encode(frame, covariates)[terms])) is not None:
entry["lr_constant"] = float(m.params["const"])
entry["lr_coefficients"] = [float(m.params[t]) for t in terms]
if chosen:
entry["hbn_cpt"] = cpt(bn_table(frame, covariates), chosen)
found[h] = entry
return found
+148
View File
@@ -0,0 +1,148 @@
import numpy as np
import pandas as pd
from models.cama.recurrence.calculator import MIN_EVENTS, RESAMPLES
from models.cama.recurrence.cohorts import UNKNOWN, Cohort, unknown_shares
from models.cama.recurrence.modeling import (
ALPHA_IN,
ALPHA_OUT,
COX_PENALIZER,
ESS,
HORIZONS,
MAX_PARENTS,
CohortFit,
)
VERSION = 1
AUC_COLUMNS = [
"cohorte",
"horizonte_meses",
"modelo",
"n_modelo",
"recurrencias",
"AUC_validacion_interna",
"AUC_bootstrap_medio",
"AUC_bootstrap_IC95_inf",
"AUC_bootstrap_IC95_sup",
"replicas_bootstrap",
]
def table(rows, columns=None) -> dict:
frame = pd.DataFrame(rows, columns=columns).replace([np.inf, -np.inf], np.nan).astype(object)
return {
"columnas": [str(c) for c in frame.columns],
"filas": frame.where(frame.notna(), None).to_dict("records"),
}
def auc_rows(fitted: CohortFit) -> list[dict]:
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))):
aucs = hz.aucs[:, j]
boot = (
[np.nanmean(aucs), *np.nanpercentile(aucs, [2.5, 97.5])]
if len(aucs)
else [None] * 3
)
rows.append(
{
"cohorte": source,
"horizonte_meses": h,
"modelo": name,
"n_modelo": hz.n,
"recurrencias": hz.events,
"AUC_validacion_interna": internal,
**dict(zip(AUC_COLUMNS[6:9], boot, strict=True)),
"replicas_bootstrap": len(aucs) if len(aucs) else None,
}
)
frame = fitted.cohort.frame
rows.append(
{
"cohorte": source,
"horizonte_meses": "completo",
"modelo": "Cox penalizado (C-index)",
"n_modelo": len(frame),
"recurrencias": int(frame["evento"].sum()),
"AUC_validacion_interna": fitted.c_index,
}
)
return [{k: (round(v, 4) if isinstance(v, float) else v) for k, v in r.items()} for r in rows]
def metrics(auc: list[dict]) -> dict[str, float]:
found = {}
for r in auc:
if r["horizonte_meses"] == "completo":
found[f"{r['cohorte']}.c_index_cox"] = float(r["AUC_validacion_interna"])
continue
tag = f"{r['cohorte']}.auc_{r['modelo']}_{r['horizonte_meses']}m"
found[tag] = float(r["AUC_validacion_interna"])
if r.get("AUC_bootstrap_medio") is not None:
found[f"{tag}_bootstrap"] = float(r["AUC_bootstrap_medio"])
return found
def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
return {
"MUESTREO": {
"cohortes": {
s: {
"pacientes": len(c.frame),
"recaidas": int(c.frame["evento"].sum()),
"covariables": len(c.covariates),
"eliminadas_por_colinealidad": c.eliminated,
}
for s, c in cohorts.items()
},
**next(iter(cohorts.values())).sampling,
},
"DATOS_FALTANTES": {
"criterio": f"el dato faltante es una categoría más («{UNKNOWN}»); "
"no se imputa ni se descarta",
"desconocidos_por_covariable": {s: unknown_shares(c) for s, c in cohorts.items()},
},
"METODO_ANALITICO": {
"modelos": "regresión logística con selección stepwise y red bayesiana con padres "
"del desenlace por BDeu, uno por horizonte",
"horizontes_meses": list(HORIZONS),
"alfa_entrada": ALPHA_IN,
"alfa_salida": ALPHA_OUT,
"ess_bdeu": ESS,
"maximo_de_padres": MAX_PARENTS,
"cox_penalizado": COX_PENALIZER,
"combinacion": "promedio de la LR y la HBN",
},
"BALANCE_CLASES": {
"aplica": False,
"motivo": "cada horizonte usa las pacientes con recaída hasta el horizonte o libres "
"de ella después; no se rebalancea",
},
"CONFIANZA_SALIDA": {
"salida": "probabilidad libre de recaída por escenario y horizonte con IC 95 % por "
"bootstrap",
"replicas": {
**{s: n_bootstrap.get(s, 0) for s in cohorts},
"calculadora": RESAMPLES,
},
"eventos_minimos_por_escenario": MIN_EVENTS,
},
}
def development(auc, factors: pd.DataFrame, points: list[dict], summary: list[dict]) -> dict:
return {
"version": VERSION,
"tablas": {
"auc": table(auc, AUC_COLUMNS),
"factores_riesgo": table(factors),
"calculadora": table(pd.DataFrame(points).round(4)),
"escenarios_resumen": table(summary),
},
}
def figures(records: list[dict]) -> dict:
return {"version": VERSION, "horizons_months": list(HORIZONS), "escenarios": records}
+121
View File
@@ -0,0 +1,121 @@
import numpy as np
import pandas as pd
from models.cama.recurrence import cohorts
from models.cama.recurrence.cohorts import UNKNOWN, Cohort, _band, _text, collinear
RESULT_DAYS = 30
TREATMENT_DAYS = 365
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"}
SURGERY = {"breast_conserving_surgery": "Lumpectomy", "mastectomy": "Mastectomy"}
TREATMENTS = {"Quimioterapia": "chemotherapy", "Radioterapia": "radiotherapy",
"Hormonoterapia": "hormone_therapy", "AntiHER2": "anti_her2"} # fmt: skip
FIXED = ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"]
TREATMENT = ["Cirugia", *TREATMENTS]
SCENARIOS = {
"Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
"Subtipo_clinico": ["Luminal A"], "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-like": {"Subtipo_clinico": ["Basal-like"]},
"HER2+ (luminal B HER2+ o no luminal)": {
"Subtipo_clinico": ["Luminal B HER2+", "Non-luminal HER2+"]},
"Luminal B HER2−": {"Subtipo_clinico": ["Luminal B HER2-"]},
"Luminal · 1-3 ganglios · lumpectomía": {
"Subtipo_clinico": ["Luminal A", "Luminal B HER2-"], "Ganglios_positivos": ["1-3"],
"Cirugia": ["Lumpectomy"]},
"Grado 3": {"Grado_histologico": ["3"]},
} # fmt: skip
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",
"origen": "la sede (sus propias pacientes)",
}
def subtype(er, pr, her2, ki67) -> str:
hormone = "positive" in (er, pr)
if her2 == "positive":
return "Luminal B HER2+" if hormone else "Non-luminal HER2+"
if her2 != "negative":
return UNKNOWN
if not hormone:
return "Basal-like" if er == "negative" and pr == "negative" else UNKNOWN
if ki67 is None or ki67 != ki67:
return UNKNOWN
return "Luminal A" if ki67 < KI67_HIGH else "Luminal B HER2-"
def frame(events: pd.DataFrame, as_of) -> pd.DataFrame:
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()
days = (events["date"] - events["index_date"]).dt.days
cut = pd.Timestamp(as_of)
after = events[(days > 0) & (events["date"] <= cut)]
first_recurrence = after[after["type"] == "recurrence"].groupby("person_id")["date"].min()
death = events[(events["type"] == "death") & (events["date"] <= cut)]
death = death.groupby("person_id")["date"].min().reindex(members.index)
end = first_recurrence.reindex(members.index).fillna(death).fillna(cut)
out = pd.DataFrame(index=members.index)
out["paciente"] = members.index
out["tiempo_meses"] = (end - members).dt.days / cohorts.DAYS_PER_MONTH
out["evento"] = first_recurrence.reindex(members.index).notna().astype(int)
out["muerte_sin_recaida"] = (death.notna() & (out["evento"] == 0)).astype(int)
near = events[days.between(-7, RESULT_DAYS)].sort_values(["date", "source_id"])
code = lambda kind: near[near["type"] == kind].groupby("person_id")["value_code"].first() # noqa: E731
number = lambda kind: near[near["type"] == kind].groupby("person_id")["value_num"].first() # noqa: E731
birth = events[events["type"] == "birth"].groupby("person_id")["date"].min()
age = (members - birth.reindex(members.index)).dt.days / 365.25
out["Edad"] = _band(age, *cohorts.AGE)
out["Tamano_tumor"] = _band(number("size_mm").reindex(members.index), *cohorts.SIZE)
out["Ganglios_positivos"] = _band(number("positive_nodes").reindex(members.index),
*cohorts.NODES) # fmt: skip
out["Grado_histologico"] = _text(code("grade").reindex(members.index).map(cohorts.GRADES))
receptors = {k: code(k).reindex(members.index) for k in ("er", "pr", "her2")}
ki67 = number("ki67_pct").reindex(members.index)
out["Receptor_estrogeno"] = _text(receptors["er"].map(RECEPTOR))
out["Receptor_progesterona"] = _text(receptors["pr"].map(RECEPTOR))
out["HER2"] = _text(receptors["her2"].map(RECEPTOR))
high = np.where(ki67 < KI67_HIGH, f"<{KI67_HIGH:g}%", f">={KI67_HIGH:g}%")
out["Ki67"] = _text(pd.Series(np.where(ki67.isna(), None, high), index=members.index))
out["Subtipo_clinico"] = [subtype(*a) for a in zip(
receptors["er"], receptors["pr"], receptors["her2"], ki67, strict=True)] # fmt: skip
out["Tipo_histologico"] = _text(code("histologic_type").reindex(members.index))
out["Estadio_clinico"] = _text(code("stage").reindex(members.index).map(STAGE_GROUP))
course = events[(events["type"] == "treatment") & days.between(0, TREATMENT_DAYS)]
given = course.groupby("person_id")["value_code"].agg(set).reindex(members.index)
given = given.apply(lambda g: g if isinstance(g, set) else set())
out["Cirugia"] = given.apply(
lambda g: next((SURGERY[s] for s in reversed(SURGERY) if s in g), "None")
)
for name, kind in TREATMENTS.items():
out[name] = given.apply(lambda g, k=kind: "Yes" if k in g else "No")
return out.reset_index(drop=True)
def scarce(rows: pd.DataFrame) -> str | None:
for h in cohorts.HORIZONS:
y = cohorts.at_horizon(rows, h)["y"]
fewest = min(int(y.sum()), int((y == 0).sum()))
if fewest < MIN_PER_CLASS:
return (f"{int(y.sum())} recurred and {int((y == 0).sum())} free of it at {h} months, "
f"{MIN_PER_CLASS} of each needed") # fmt: skip
return None
def prepare(rows: pd.DataFrame) -> Cohort:
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]
treatment = [c for c in TREATMENT if c in kept]
return Cohort("site", rows[FIXED + kept + dropped], kept, treatment, dropped, "Sitio",
SCENARIOS, SAMPLING) # fmt: skip
+144
View File
@@ -0,0 +1,144 @@
from dataclasses import dataclass, field
from datetime import date
import pandas as pd
from models.survival import DAYS_PER_YEAR, OUTPUT, SCENARIO_SEPARATOR, Spec, age_group, band
RESULTS = ("histologic_type", "grade", "er", "pr", "her2")
RESULT_DAYS = 30
TREATMENT_DAYS = 365
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")
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)
CONSERVING = ("surgery", "==", "breast_conserving_surgery")
def _younger(years):
return ("age", "<", years)
def _older(years):
return ("age", ">=", years)
SCENARIOS = {
"HER2+ · ≥60 años · estadio III–IV (Alto)": (HER2_POS, _older(60), STAGE_III_IV),
"HER2+ · <60 años · estadio 0–II (Bajo)": (HER2_POS, _younger(60), STAGE_0_II),
"Estadio IV": (("stage", "in", ("IV",)),),
"Estadio I": (("stage", "in", ("I",)),),
"≥ 75 años": (_older(75),),
"< 45 años": (_younger(45),),
"Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora": (
_younger(45), HER2_NEG, STAGE_0_II, CONSERVING),
"HER2− · estadio 0–II · cirugía conservadora": (HER2_NEG, STAGE_0_II, CONSERVING),
"HER2+ · estadio 0–II · cirugía conservadora": (HER2_POS, STAGE_0_II, CONSERVING),
"Jóvenes (<45) · estadio 0–II": (_younger(45), STAGE_0_II),
"Jóvenes (<45) · HER2−": (_younger(45), HER2_NEG),
"Triple negativo (HR−/HER2−) · estadio 0–II": (*TRIPLE_NEG, STAGE_0_II),
"≥ 65 años · HER2− · estadio 0–II · cirugía conservadora": (
_older(65), HER2_NEG, STAGE_0_II, CONSERVING),
} # fmt: skip
def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
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()
found["age"] = (members["index_date"] - birth.reindex(members.index)).dt.days / DAYS_PER_YEAR
days = (events["date"] - events["index_date"]).dt.days
near = events[days.between(-7, RESULT_DAYS)].sort_values(["date", "source_id"])
for kind in RESULTS:
found[kind] = near[near["type"] == kind].groupby("person_id")["value_code"].first()
for name, kind, cuts in (("ki67_group", "ki67_pct", (14, 20)),
("size_group", "size_mm", (20, 50))): # fmt: skip
value = near[near["type"] == kind].groupby("person_id")["value_num"].first()
found[name] = band(value.reindex(found.index), list(cuts))
stage = near[near["type"] == "stage"].groupby("person_id")["value_code"].first()
found["stage"] = stage.reindex(found.index).map(STAGE_GROUP)
course = events[(events["type"] == "treatment") & days.between(0, TREATMENT_DAYS)]
given = course.groupby("person_id")["value_code"].agg(set).reindex(found.index)
given = given.apply(lambda g: g if isinstance(g, set) else set())
found["surgery"] = given.apply(lambda g: next((s for s in reversed(SURGERY) if s in g), "none"))
for name in ("chemotherapy", "radiotherapy"):
found[name] = given.apply(lambda g, n=name: "yes" if n in g else "no")
return found
@dataclass(frozen=True)
class SiteRecurrence:
name: str
cohort: str = "cama_cohort_recurrence"
reports: bool = True
method: str = field(default="stepwise logistic regression + Bayesian network", init=False)
def train(self, events, as_of=None) -> tuple:
from models.cama import recurrence
from models.cama.recurrence import site
from models.jobs import EmptyCohort
rows = site.frame(events, as_of or date.today())
if reason := site.scarce(rows):
raise EmptyCohort(f"cama.recurrence: {reason}")
return recurrence.train_site(rows)
def predict(self, model, events) -> pd.DataFrame:
from models.cama.recurrence import calculator, site
members = site.frame(events, date.today())
found = model.predict(members)
index = events.groupby("person_id")["index_date"].first()
masks = calculator.masks(members, site.SCENARIOS)
named = [SCENARIO_SEPARATOR.join(n for n, m in masks.items() if m[i]) or None
for i in range(len(members))] # fmt: skip
rows = []
for i, person in enumerate(members["paciente"]):
for h in model.horizons:
rows.append({"person_id": person,
"index_date": pd.Timestamp(index[person]).date(),
"horizon_years": h / 12, "probability": found[f"recurrence_{h}m"][i],
"ci_low": None, "ci_high": None, "scenarios": named[i]}) # fmt: skip
return pd.DataFrame(rows, columns=OUTPUT)
MODELS = {
"survival": Spec(
name="survival",
cohort="cama_cohort_survival",
features=(
"age_group",
*RESULTS,
"ki67_group",
"size_group",
"stage",
"surgery",
"chemotherapy",
"radiotherapy",
),
covariates=covariates,
parents=(
"stage",
"histologic_type",
"surgery",
"chemotherapy",
"radiotherapy",
"age_group",
),
borders=(0, 6, 12, 18),
cap_months=24,
scenarios=SCENARIOS,
scenario_columns=("age",),
treatments=("surgery", "chemotherapy", "radiotherapy"),
notes=(
f"Tratamiento: el primer curso (convención de SEER), lo recibido en los "
f"{TREATMENT_DAYS} días tras el índice, tomado como conocido en él. Quien muere "
"antes de su tratamiento cuenta como no tratada (sesgo de tiempo inmortal): el "
"efecto protector del tratamiento aparece mayor de lo que es.",
),
),
"recurrence": SiteRecurrence("recurrence"),
}
+152
View File
@@ -0,0 +1,152 @@
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
def life_table(months: np.ndarray, event: np.ndarray, length: int = 0):
months, event = np.asarray(months, int), np.asarray(event, bool)
length = max(length, int(months.max()) + 2)
d = np.bincount(months[event], minlength=length)
c = np.bincount(months[~event], minlength=length)
at_risk = len(months) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
return d, c, at_risk
def kaplan_meier(months, event, until: int):
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)
v = np.where((n > 0) & (n > d), d / (np.maximum(n, 1) * np.maximum(n - d, 1)), 0.0)
S = np.concatenate([[1.0], np.cumprod(q)])[: until + 1]
se = np.sqrt(np.concatenate([[0.0], np.cumsum(v)])[: until + 1]) / np.abs(np.log(S))
inside = (S > 0) & (S < 1)
return (
S,
np.where(inside, S ** np.exp(Z * se), S),
np.where(inside, S ** np.exp(-Z * se), S),
)
def _nll(survival, d, c) -> float:
T = len(d)
both = survival(np.concatenate([np.arange(0, T + 1, dtype=float), np.arange(T) + 0.5]))
S, mid = both[: T + 1], both[T + 1 :]
if not (np.all(np.isfinite(S)) and np.all(np.isfinite(mid))):
return INVALID
p = np.clip(S[:-1] - S[1:], 1e-300, None)
return -(np.sum(d * np.log(p)) + np.sum(c * np.log(np.clip(mid, 1e-300, None))))
def weibull(t, k, lam):
return np.exp(-((np.asarray(t, float) / lam) ** k))
def fit_weibull(d, c) -> tuple[float, float]:
best = None
for k0 in (0.7, 1.0, 1.5):
for l0 in (50.0, 200.0, 1000.0):
r = minimize(
lambda p: _nll(lambda t: weibull(t, *np.exp(p)), d, c),
[np.log(k0), np.log(l0)],
method="Nelder-Mead",
options={"xatol": 1e-5, "fatol": 1e-8, "maxiter": 2000},
)
r = _converged(r, "Weibull")
best = r if best is None or r.fun < best.fun else best
k, lam = np.exp(best.x)
return float(k), float(lam)
STEPS = 800
class NotConverged(RuntimeError):
pass
def _converged(r, what: str):
if not r.success:
raise NotConverged(f"{what}: {r.message}")
return r
def kilbas_saigo_survival(t, c: float, rho: float, s: float) -> np.ndarray:
t = np.atleast_1d(np.asarray(t, float))
e = rho + s
top = float(t.max()) if t.size else 0.0
if top <= 0:
return np.ones_like(t)
w = np.expm1(np.linspace(0.0, np.log1p(c * top**e), STEPS + 1)) / c
w[-1] = top**e
grid = w ** (1 / e)
y = np.ones(STEPS + 1)
kappa = c / np.exp(gammaln(rho))
b0, be = beta_function(s + 1, rho), beta_function(s + e + 1, rho)
dw = np.diff(w)
for n in range(1, STEPS + 1):
x = grid[: n + 1] / grid[n]
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
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:
t = np.atleast_1d(np.asarray(t, float))
s = k + alpha - 2
if k + alpha <= 1 or s + beta <= 0:
return np.full(t.shape, np.nan)
c = np.exp(gammaln(k + 1) - gammaln(k + alpha - 1)) / lam ** (k + alpha + beta - 2)
return np.clip(kilbas_saigo_survival(t, c, beta, s), 0.0, 1.0)
def _shape(k: float, alpha: float, beta: float) -> tuple[float, float, float]:
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, ...]:
floor = max(0.0, 1.0 - k) + 1e-6
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))
def unpack(p):
return floor + np.exp(p[0]), 1 / (1 + np.exp(-p[1]))
def profile(p) -> tuple[float, float]:
a, b = unpack(p)
if k + a <= 1 or k + a + b <= 2:
return INVALID, np.nan
rho, s, scale = _shape(k, a, b)
e = rho + s
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)
def nll(log_lam: float) -> float:
found = np.interp(np.log1p(scale * (months / np.exp(log_lam)) ** e), np.log1p(z), g)
return _nll(lambda t: found, d, c)
coarse = np.linspace(*lambdas, 141)
i = int(np.argmin([nll(x) for x in coarse]))
r = minimize_scalar(nll, bounds=(coarse[max(i - 1, 0)], coarse[min(i + 1, 140)]),
method="bounded", options={"xatol": 1e-9}) # fmt: skip
return float(r.fun), float(r.x)
starts = [[np.log(max(1.0 - floor, 1e-9)), 8.0]]
starts += [[np.log(a0), np.log(b0 / (1 - b0))] for a0 in (0.3, 1.0) for b0 in (0.5, 0.9)]
best = None
for p0 in starts:
options = {"xatol": 1e-5, "fatol": 1e-8, "maxiter": 20_000, "maxfev": 20_000}
r = minimize(lambda p: profile(p)[0], p0, method="Nelder-Mead", options=options)
r = _converged(r, "fractional Weibull")
best = r if best is None or r.fun < best.fun else best
a, b = unpack(best.x)
return float(a), float(b), float(np.exp(profile(best.x)[1]))
+304
View File
@@ -0,0 +1,304 @@
import hashlib
import importlib
import inspect
import io
import json
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
from models.jobs import EmptyCohort
from models.tea import jobs as tea_jobs
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"}
class ExecutionConfig(dg.Config):
mode: str | None = None
scheduler: str | None = None
def model(self) -> cluster.Execution:
return cluster.Execution(**self.model_dump())
class ScopeConfig(dg.Config):
mode: str = "pending"
n: int | None = None
ids: list[str] = []
def model(self) -> eeg.Scope:
return eeg.Scope(**self.model_dump())
class PipelineRun(dg.Config):
pipeline: str
version: int | None = None
@dg.op
def run_pipeline(context: dg.OpExecutionContext, config: PipelineRun) -> int:
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)
return version
@dg.job(tags=WRITES)
def ingest():
run_pipeline()
def _jobs(domain: str):
try:
return importlib.import_module(f"models.{domain}.jobs")
except ModuleNotFoundError as e:
raise ValueError(f"{domain} has no models") from e
class Training(dg.Config):
domain: str
models: list[str] = []
as_of: str | None = None
execution: ExecutionConfig = ExecutionConfig()
source: dict[str, Any] | None = None
@dg.op
def train_models(context: dg.OpExecutionContext, config: Training) -> dict:
jobs = _jobs(config.domain)
as_of = date.fromisoformat(config.as_of) if config.as_of else None
options = {}
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():
try:
found[name] = jobs.train(name, as_of, **options)
except EmptyCohort as e:
found[name] = None
context.log.warning(f"{e}: not trained")
continue
context.log.info(f"{config.domain}.{name}: version {found[name]}")
return found
@dg.job
def train():
train_models()
class Scoring(dg.Config):
domain: str
models: list[str] = []
@dg.op
def score_models(context: dg.OpExecutionContext, config: Scoring) -> dict:
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_SELECT", [f"{config.domain}_risk+"]))
return found
@dg.job(tags=WRITES)
def score():
score_models()
class Analysis(dg.Config):
domain: str
execution: ExecutionConfig = ExecutionConfig()
@dg.op
def analyze_studies(context: dg.OpExecutionContext, config: Analysis) -> int:
with execution.running(context, config.execution.model()):
found = _jobs(config.domain).analyze()
context.log.info(f"{config.domain}: {found} analysed")
return found
@dg.job(tags=WRITES)
def analyze():
analyze_studies()
class TeaAnalysis(dg.Config):
scope: ScopeConfig = ScopeConfig()
execution: ExecutionConfig = ExecutionConfig()
@dg.op
def tea_analyze_studies(context: dg.OpExecutionContext, config: TeaAnalysis) -> dict:
with execution.running(context, config.execution.model()):
found = tea_jobs.analyze(config.scope.model(), rebuild_gold=False)
context.log.info(f"{found} EEGs analysed (scope {config.scope.mode})")
return {"analysed": found}
@dg.op
def tea_score_curves(context: dg.OpExecutionContext, analysed: dict) -> dict:
found = tea_jobs.score_curves()
for name, version in found.items():
context.log.info(f"{name}: " + (f"version {version}" if version else "no champion"))
return {"scored": found}
@dg.op
def tea_relate_ados2(context: dg.OpExecutionContext, scored: dict) -> dict:
version = tea_jobs.relate()
context.log.info("ados2_association: " + (f"version {version}" if version else "no champion"))
return {"ados2_association": version}
@dg.op
def tea_build_gold(context: dg.OpExecutionContext, related: dict) -> dict:
silver.build(tea_jobs.GOLD_SELECT)
context.log.info("gold rebuilt")
return {"built": tea_jobs.GOLD_SELECT}
class Preview(dg.Config):
edf: str
ados2: str | None = None
birth_date: str | None = None
pipeline: str = "tea"
@dg.op
def preview_study(context: dg.OpExecutionContext, config: Preview) -> dict:
try:
previews.sweep()
result = tea_preview_analysis.preview(
previews.get(config.edf),
previews.get(config.ados2) if config.ados2 else None,
date.fromisoformat(config.birth_date) if config.birth_date else None,
config.pipeline,
)
context.add_output_metadata(
{"result": dg.MetadataValue.json(json.loads(result.model_dump_json()))}
)
for warning in result.warnings:
context.log.warning(warning)
return {"valid": result.eeg.valid, "warnings": len(result.warnings)}
finally:
previews.discard([config.edf, config.ados2])
@dg.job(tags={"domain": "tea"})
def tea_preview():
preview_study()
@dg.job(tags={**WRITES, "domain": "tea"})
def tea_eeg():
tea_build_gold(tea_relate_ados2(tea_score_curves(tea_analyze_studies())))
def pending_eegs() -> bool:
return bool(eeg.pending())
def after_ingest(run_id: str, has_pending: Callable[[], bool]) -> dg.RunRequest | dg.SkipReason:
if not has_pending():
return dg.SkipReason("the ingest brought no EEG to analyse")
return dg.RunRequest(
run_key=f"after-ingest-{run_id}",
run_config={"ops": {"tea_analyze_studies": {"config": {"scope": {"mode": "pending"}}}}},
tags={"domain": "tea", "triggered_by": run_id},
)
@dg.run_status_sensor(
name="tea_eeg_after_ingest",
run_status=dg.DagsterRunStatus.SUCCESS,
monitored_jobs=[ingest],
request_job=tea_eeg,
minimum_interval_seconds=10,
default_status=dg.DefaultSensorStatus.RUNNING,
)
def tea_eeg_after_ingest(context: dg.RunStatusSensorContext):
return after_ingest(context.dagster_run.run_id, pending_eegs)
class BundleImport(dg.Config):
domain: str
sha256: str
@dg.op
def import_bundle_files(context: dg.OpExecutionContext, config: BundleImport) -> dict:
path = bundle.staged(config.sha256)
try:
data = path.read_bytes()
if hashlib.sha256(data).hexdigest() != config.sha256:
raise bundle.BundleError("the staged file's SHA-256 does not match the run config")
result = bundle.import_(Domain(config.domain), data)
finally:
path.unlink(missing_ok=True)
with zipfile.ZipFile(io.BytesIO(data)) as archive:
manifest = json.loads(archive.read(bundle.MANIFEST))
skipped = set(result.skipped)
sources = sorted(
(item["name"], item["version"])
for item in manifest["versions"]
if (item["name"], item["version"]) not in skipped
)
for (_, source), (name, version) in zip(sources, result.imported, strict=True):
context.log.info(f"{name}: source v{source} -> version {version}")
for name, version in result.skipped:
context.log.warning(f"{name} v{version}: already registered, skipped")
return {
"imported": [list(item) for item in result.imported],
"skipped": [list(item) for item in result.skipped],
}
@dg.job
def import_bundle():
import_bundle_files()
@dg.op
def make_backup(context: dg.OpExecutionContext) -> str:
folder = backups.create()
context.log.info(f"backup {folder}")
return str(folder)
@dg.job(tags=WRITES)
def backup():
make_backup()
nightly = (
[
dg.ScheduleDefinition(
job=backup, cron_schedule=cron, default_status=dg.DefaultScheduleStatus.RUNNING
)
] # fmt: skip
if (cron := os.environ.get("BACKUP_SCHEDULE", "30 2 * * *"))
else []
)
defs = dg.Definitions(
jobs=[ingest, train, score, analyze, tea_eeg, tea_preview, import_bundle, backup],
sensors=[tea_eeg_after_ingest],
schedules=nightly,
)
+368
View File
@@ -0,0 +1,368 @@
import contextvars
import threading
import time
from collections.abc import Callable, Iterable, Iterator
from contextlib import contextmanager
from datetime import UTC, datetime
from itertools import islice
import dagster as dg
import psutil
from persistance import cluster
from persistance.cluster import (
PROGRESS_TAG,
ClusterVersionError,
Execution,
ExecutionError,
Progress,
Resolved,
Tasks,
Worker,
options,
resolve,
)
__all__ = [
"ClusterVersionError",
"Execution",
"ExecutionError",
"Progress",
"Resolved",
"map",
"options",
"resolve",
"running",
]
SAMPLE_S = 2.0
_SINGLE_THREAD = {
"OMP_NUM_THREADS": "1",
"OPENBLAS_NUM_THREADS": "1",
"MKL_NUM_THREADS": "1",
}
class Eta:
def __init__(self, alpha: float = 0.3, min_done: int = 3):
self.alpha, self.min_done = alpha, min_done
self.rate: float | None = None
self._last: tuple[float, int] | None = None
def update(self, elapsed_s: float, done: int) -> None:
last, self._last = self._last, (elapsed_s, done)
if last is None or elapsed_s <= last[0]:
return
rate = (done - last[1]) / (elapsed_s - last[0])
self.rate = rate if self.rate is None else self.alpha * rate + (1 - self.alpha) * self.rate
def eta_s(self, total: int) -> float | None:
done = self._last[1] if self._last else 0
if done < self.min_done or not self.rate or self.rate <= 0:
return None
return max(0, total - done) / self.rate
class _Ambient:
def __init__(self, context, execution: Execution | None):
self.context, self.execution = context, execution
self.client = None
self.cluster = None
self.phases: list[dict] = []
self.peak_cpu_pct = 0.0
self.peak_memory_bytes = 0
def close(self) -> None:
_close(self.client, self.cluster)
self.client = self.cluster = None
_ambient: contextvars.ContextVar[_Ambient | None] = contextvars.ContextVar(
"execution_ambient", default=None
)
def _close(client, local_cluster) -> None:
for closable in (client, local_cluster):
if closable is not None:
try:
closable.close()
except Exception:
pass
def _counts(dask_scheduler) -> dict:
counts: dict = {}
for task in dask_scheduler.tasks.values():
counts[task.state] = counts.get(task.state, 0) + 1
return counts
def _connect(resolved: Resolved, workers: int | None):
from distributed import Client, LocalCluster
if resolved.mode == "local":
local = LocalCluster(
n_workers=cluster.local_workers(workers),
threads_per_worker=1,
processes=True,
memory_limit=cluster.memory_per_worker(),
dashboard_address=None,
env=_SINGLE_THREAD,
)
try:
return Client(local), local
except BaseException:
_close(None, local)
raise
try:
client = Client(resolved.scheduler, timeout=10)
except Exception as e:
raise ExecutionError(f"cannot reach the Dask scheduler {resolved.scheduler}: {e}") from e
detail = cluster.versions_error(client)
if detail is not None:
_close(client, None)
raise ClusterVersionError(
f"Dask workers differ from this server: {detail}. "
"Rebuild the worker image from the same commit."
)
return client, None
class _Monitor:
def __init__(self, ambient, resolved, phase, total, log, client):
self.ambient, self.resolved, self.phase = ambient, resolved, phase
self.total, self.log, self.client = total, log, client
self.done = 0
self.started = time.monotonic()
self.eta = Eta()
self.tasks: Tasks | None = None
self.last_tenth = 0
self.peak_cpu = 0.0
self.peak_memory = 0
self._lock = threading.Lock()
self._stop = threading.Event()
self._thread = threading.Thread(target=self._loop, daemon=True)
self._process = psutil.Process()
def item_done(self) -> None:
with self._lock:
self.done += 1
def start(self) -> None:
self.report(force_log=True)
self._thread.start()
def stop(self, *, final: bool) -> None:
self._stop.set()
self._thread.join()
if final:
self.report(force_log=True)
def _loop(self) -> None:
while not self._stop.wait(SAMPLE_S):
self.report()
def _cluster_state(self) -> list[Worker]:
if self.client is None:
cpu = self._process.cpu_percent()
self.peak_cpu = max(self.peak_cpu, cpu)
self.peak_memory = max(self.peak_memory, self._process.memory_info().rss)
return []
workers = []
try:
info = self.client.scheduler_info()["workers"]
for w in info.values():
m = w.get("metrics", {})
workers.append(
Worker(
name=str(w.get("name", "")),
cpu_pct=float(m.get("cpu", 0.0)),
memory_bytes=int(m.get("memory", 0)),
memory_limit=w.get("memory_limit"),
executing=int(m.get("executing", 0)),
threads=int(w.get("nthreads", 1)),
)
)
except Exception:
return []
try:
counts = self.client.run_on_scheduler(_counts)
self.tasks = Tasks(**{k: counts.get(k, 0) for k in Tasks.model_fields})
except Exception:
pass
self.peak_cpu = max(self.peak_cpu, sum(w.cpu_pct for w in workers))
self.peak_memory = max(self.peak_memory, sum(w.memory_bytes for w in workers))
return workers
def report(self, *, force_log: bool = False) -> None:
workers = self._cluster_state()
with self._lock:
done = self.done
elapsed = time.monotonic() - self.started
self.eta.update(elapsed, done)
progress = Progress(
phase=self.phase,
done=done,
total=self.total,
elapsed_s=round(elapsed, 1),
eta_s=self.eta.eta_s(self.total),
mode=self.resolved.mode,
scheduler=self.resolved.scheduler,
workers=workers,
tasks=self.tasks,
updated_at=datetime.now(UTC).isoformat(timespec="seconds"),
)
tenth = done * 10 // self.total
if force_log or tenth > self.last_tenth:
self.last_tenth = tenth
self.log(f"{self.phase}: {done}/{self.total}")
context = self.ambient.context if self.ambient else None
if context is not None:
context.instance.add_run_tags(
context.run_id, {PROGRESS_TAG: progress.model_dump_json()}
)
def _default_log(ambient) -> Callable[[str], None]:
return ambient.context.log.info if ambient and ambient.context else print
def _run_sync(fn, iterator, monitor, on_error):
results = []
for item in iterator:
try:
results.append(fn(item))
except Exception as e:
if on_error is None:
raise
results.append(on_error(item, e))
monitor.item_done()
return results
def _run_dask(fn, iterator, client, monitor, on_error):
from distributed import as_completed
threads = sum(w["nthreads"] for w in client.scheduler_info()["workers"].values()) or 1
limit = max(4, 2 * threads)
results: dict[int, object] = {}
pending: dict = {}
completed = as_completed([])
numbered = enumerate(iterator)
try:
while True:
for index, item in islice(numbered, max(0, limit - len(pending))):
future = client.submit(fn, item, pure=False, retries=1)
pending[future] = (index, item)
completed.add(future)
if not pending:
break
future = next(completed)
index, item = pending.pop(future)
try:
results[index] = future.result()
except Exception as e:
if on_error is None:
raise
results[index] = on_error(item, e)
monitor.item_done()
except BaseException:
try:
client.cancel(list(pending), force=True)
except Exception:
pass
raise
return [results[i] for i in range(len(results))]
def map[T, R]( # noqa: A001
fn: Callable[[T], R],
items: Iterable[T],
*,
execution: Execution | None = None,
log: Callable[[str], None] | None = None,
phase: str = "working",
total: int | None = None,
workers: int | None = None,
on_error: Callable[[T, Exception], R] | None = None,
) -> list[R]:
ambient = _ambient.get()
if execution is None and ambient is not None:
execution = ambient.execution
resolved = resolve(execution)
log = log or _default_log(ambient)
if total is None:
try:
total = len(items) # type: ignore[arg-type]
except TypeError:
raise ValueError("total is needed when items has no length") from None
iterator = iter(items)
if total == 0:
return []
monitor = None
client, local = (ambient.client, None) if ambient else (None, None)
opened_here = False
ok = False
try:
if resolved.mode != "sync" and client is None:
client, local = _connect(resolved, workers)
if ambient is not None:
ambient.client, ambient.cluster = client, local
else:
opened_here = True
monitor = _Monitor(ambient, resolved, phase, total, log, client)
monitor.start()
if resolved.mode == "sync":
results = _run_sync(fn, iterator, monitor, on_error)
else:
results = _run_dask(fn, iterator, client, monitor, on_error)
ok = True
return results
finally:
if monitor is not None:
monitor.stop(final=ok)
if ambient is not None:
ambient.phases.append(
{
"phase": phase,
"done": monitor.done,
"total": total,
"elapsed_s": round(time.monotonic() - monitor.started, 1),
}
)
ambient.peak_cpu_pct = max(ambient.peak_cpu_pct, monitor.peak_cpu)
ambient.peak_memory_bytes = max(ambient.peak_memory_bytes, monitor.peak_memory)
if opened_here:
_close(client, local)
@contextmanager
def running(context: dg.OpExecutionContext, execution: Execution | None = None) -> Iterator[None]:
ambient = _Ambient(context, execution)
token = _ambient.set(ambient)
failed = True
try:
yield
failed = False
finally:
_ambient.reset(token)
ambient.close()
try:
resolved = resolve(execution)
context.add_output_metadata(
{
"mode": dg.MetadataValue.text(resolved.mode),
"scheduler": (
dg.MetadataValue.text(resolved.scheduler)
if resolved.scheduler
else dg.MetadataValue.null()
),
"phases": dg.MetadataValue.json(ambient.phases),
"peak_cpu_pct": dg.MetadataValue.float(ambient.peak_cpu_pct),
"peak_memory_bytes": dg.MetadataValue.int(ambient.peak_memory_bytes),
}
)
except Exception:
if not failed:
raise
+149
View File
@@ -0,0 +1,149 @@
import numpy as np
import pandas as pd
import statsmodels.api as sm
from scipy.stats import false_discovery_control
from models.curves import life_table
ALPHA = 0.05
FREQ_MIN = 0.80
Z = 1.96
CRITERIA = ("c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia")
ORDER = {
"riesgo robusto": 0,
"protector robusto": 1,
"riesgo sugerente": 2,
"protector sugerente": 3,
"no concluyente": 4,
}
UNKNOWN_CLASS = "no aplica (categoria desconocida)"
DEFINING, MAJORITY, PRESENT = 0.95, 0.50, 0.10
DESCRIBING = ("definitoria", "mayoritaria")
def variable_of(term: str, covariates: list[str]) -> str:
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]:
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)
last = min(horizon, len(d) - 1) + 1
S = float(np.prod(q[:last]))
return S, S * float(np.sqrt(np.sum(v[:last])))
def odds_ratios(data: pd.DataFrame, y, variables, reference, name: str) -> pd.DataFrame:
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]
X = X.loc[:, ~X.T.duplicated()]
m = sm.GLM(y, sm.add_constant(X), family=sm.families.Binomial()).fit()
ci = np.exp(m.conf_int().loc[X.columns])
return pd.DataFrame(
{
"termino": X.columns,
name: np.exp(m.params[X.columns].to_numpy()),
"IC95_inf": ci[0].to_numpy(),
"IC95_sup": ci[1].to_numpy(),
"p": m.pvalues[X.columns].to_numpy(),
}
)
def complete(table: pd.DataFrame, variables, reference: dict, everyone: pd.DataFrame,
months, event, horizon: int, names: tuple[str, str, str]) -> pd.DataFrame: # fmt: skip
table = table.reset_index(drop=True)
table["variable"] = [variable_of(x, variables) for x in table["termino"]]
table["categoria"] = [
x[len(v) + 1 :] for x, v in zip(table["termino"], table["variable"], strict=True)
]
table["referencia"] = table["variable"].map(reference)
table["p_ajustado_BH"] = false_discovery_control(table["p"]) if len(table) else []
category, ref, delta_name = names
rows = []
for v, cat, r in zip(table["variable"], table["categoria"], table["referencia"], strict=True):
a, b = (everyone[v] == cat).to_numpy(), (everyone[v] == r).to_numpy()
sa, ea = km_at(months[a], event[a], horizon)
sb, eb = km_at(months[b], event[b], horizon)
delta, se = sa - sb, np.sqrt(ea**2 + eb**2)
rows.append({
"n_categoria": int(a.sum()), category: sa, ref: sb, delta_name: delta,
"delta_IC95_inf": delta - Z * se, "delta_IC95_sup": delta + Z * se,
}) # fmt: skip
return pd.concat([table, pd.DataFrame(rows, columns=["n_categoria", category, ref, delta_name,
"delta_IC95_inf", "delta_IC95_sup"])],
axis=1) # fmt: skip
def classify(tab: pd.DataFrame, or_name: str, delta_name: str, unknown: str,
evaluated: tuple[str, ...] = CRITERIA) -> pd.DataFrame: # fmt: skip
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)
excludes_zero = (tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0)
tab["c4_supervivencia"] = excludes_zero & (np.sign(tab[delta_name]) == np.where(risk, -1, 1))
tab["criterios_cumplidos"] = tab[list(evaluated)].astype(bool).sum(axis=1)
robust = min(3, len(evaluated))
tab["clasificacion"] = [
UNKNOWN_CLASS
if cat == unknown
else f"{d} robusto"
if c1 and k >= robust
else f"{d} sugerente"
if k >= 2
else "no concluyente"
for cat, d, c1, k in zip(
tab["categoria"],
tab["direccion"],
tab["c1_or"],
tab["criterios_cumplidos"],
strict=True,
)
]
return tab
def presence(share: float) -> str:
if share >= DEFINING:
return "definitoria"
return "mayoritaria" if share >= MAJORITY else "presente" if share >= PRESENT else "minoritaria"
def listing(part: pd.DataFrame) -> str:
strength = np.where(part["tipo_efecto"] == "tratamiento", "asociacion",
part["clasificacion"].str.split().str[-1]) # fmt: skip
return "; ".join(
f"{v}={c} ({s}, {p:.0%})"
for v, c, s, p in zip(
part["variable"], part["categoria"], strength, part["share"], strict=True
)
)
def classified(factors: pd.DataFrame) -> pd.DataFrame:
found = factors[factors["clasificacion"].str.contains("robusto|sugerente|tratamiento")]
kind = np.where(
found["tipo"] == "tratamiento", "tratamiento", found["clasificacion"].str.split().str[0]
)
return found.assign(tipo_efecto=kind)
def scenario_row(frame: pd.DataFrame, mask: np.ndarray, found: pd.DataFrame) -> dict:
share = [
float((frame.loc[mask, v] == c).mean())
for v, c in zip(found["variable"], found["categoria"], strict=True)
]
detail = found.assign(share=share, presence=[presence(s) for s in share])
row = {}
for k in ("riesgo", "protector", "tratamiento"):
for level, label in (("definitoria", "definitorios"), ("mayoritaria", "mayoritarios")):
row[f"{k}_{label}"] = listing(
detail[(detail["tipo_efecto"] == k) & (detail["presence"] == level)]
)
included = (detail["tipo_efecto"] == "riesgo") & detail["presence"].isin(DESCRIBING)
row["n_factores_riesgo_incluidos"] = int(included.sum())
row["incluye_factor_riesgo"] = row["n_factores_riesgo_incluidos"] > 0
return row
+540
View File
@@ -0,0 +1,540 @@
import hashlib
import io
import json
import os
import unicodedata
from collections.abc import Callable
from concurrent.futures import ProcessPoolExecutor
from datetime import date
from functools import cache
import duckdb
import ocrmypdf
import pandas as pd
import pdfplumber
import pikepdf
import splink.comparison_library as cl
from markitdown import MarkItDown
from openai import OpenAI, OpenAIError
from splink import Linker, SettingsCreator, block_on
from splink.backends.duckdb import DuckDBAPI
from splink.clustering import cluster_pairwise_predictions_at_threshold
from core import catalog, concept_map, fhir_in
from core.measures import as_day
from core.pipeline import (
HELD,
IDENTIFIERS,
QUOTES,
RECORD,
Edf,
Extract,
Fhir,
Join,
Link,
Map,
Pipeline,
Read,
Route,
Target,
answer_schema,
apply_patterns,
ground,
join,
map_row,
matches,
validate,
)
from core.tea import ados2
from models.tea.eeg import read
from persistance import config_log, files, nodes, silver
MIN_WORDS = 5
READ_BATCH = 32
READ_COLUMNS = {
"text": {"data_type": "text", "nullable": True},
"ocr": {"data_type": "bool"},
"error": {"data_type": "text", "nullable": True},
"format": {"data_type": "text", "nullable": True},
}
EDF_COLUMNS = {f"edf_{name}": {"data_type": kind, "nullable": True} for name, kind in (
("patient_code", "text"), ("sex", "text"), ("birth_date", "text"), ("study_date", "text"),
("record_code", "text"), ("duration_s", "double"), ("channels", "bigint"), ("error", "text"),
)} # fmt: skip
def file_format(content: bytes) -> str:
if content.startswith(b"%PDF"):
return "pdf"
head = content[:256]
if len(head) == 256 and head[:8] == b"0 " and head[184:192].strip().isdigit():
return "edf"
return "other"
@cache
def _reader() -> MarkItDown:
return MarkItDown()
def _lines(text: str) -> str:
return "\n".join(" ".join(line.split()) for line in text.splitlines() if line.strip())
def _text(content: bytes) -> str:
return _reader().convert_stream(io.BytesIO(content)).text_content
def _pdf_pages(content: bytes) -> list[str]:
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]:
source, scans = pikepdf.open(io.BytesIO(content)), pikepdf.new()
for n in numbers:
scans.pages.append(source.pages[n])
pages, sidecar = io.BytesIO(), io.BytesIO()
scans.save(pages)
pages.seek(0)
ocrmypdf.ocr(
pages, io.BytesIO(), language="spa", force_ocr=True, output_type="pdf", optimize=0,
progress_bar=False, jobs=1, deskew=True, sidecar=sidecar,
) # fmt: skip
found = sidecar.getvalue().decode().split("\f")
return [_lines(found[i]) if i < len(found) else "" for i in range(len(numbers))]
def read_file(content: bytes) -> dict:
kind = file_format(content)
if kind == "edf":
return {"text": None, "ocr": False, "error": None, "format": kind}
return {**_read_text(content), "format": kind}
def _read_text(content: bytes) -> dict:
try:
if not content.startswith(b"%PDF"):
return {"text": _text(content), "ocr": False, "error": None}
pages = _pdf_pages(content)
scanned = [i for i, page in enumerate(pages) if len(page.split()) < MIN_WORDS]
if scanned:
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
return {"text": None, "ocr": False, "error": f"{type(e).__name__}: {e}"}
def run_read(p: str, node: Read):
rows = list(nodes.rows(p, node.inputs[0]))
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]
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:
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)),
strict=True)) # fmt: skip
nodes.remember("read_cache", [{"key": k, **r} for k, r in read.items()],
READ_COLUMNS) # fmt: skip
found |= read
for row in rows:
result = found.get(row.pop("key"), {"text": None, "ocr": False, "error": "empty"})
row |= {k: result[k] for k in READ_COLUMNS}
return nodes.write(p, node.id, rows, READ_COLUMNS)
def run_edf(p: str, node: Edf):
rows = list(nodes.rows(p, node.inputs[0]))
empty = dict.fromkeys(EDF_COLUMNS)
found = {None: {**empty, "edf_error": "empty"}}
for key in {row.get(node.column) for row in rows} - {None}:
content = files.content(key)
if content is None:
found[key] = {**empty, "edf_error": "no file"}
continue
try:
h = read.header(content)
except read.FileNotValid as exc:
found[key] = {**empty, "edf_error": str(exc)}
continue
found[key] = {
"edf_patient_code": h.patient_code,
"edf_sex": h.sex,
"edf_birth_date": h.birthdate.isoformat() if h.birthdate else None,
"edf_study_date": h.start_date.isoformat() if h.start_date else None,
"edf_record_code": h.record_code,
"edf_duration_s": h.duration_s,
"edf_channels": h.channels,
"edf_error": None,
}
for row in rows:
row.update(found[row.get(node.column)])
return nodes.write(p, node.id, rows, EDF_COLUMNS)
def run_route(p: str, node: Route, others: list[Route] = ()):
rows = nodes.rows(p, node.inputs[0])
taken = [r for r in rows if matches(node, r) and not any(matches(o, r) for o in others)]
return nodes.write(p, node.id, taken)
def _codes(node: Map | Extract, fields) -> dict[str, dict[str, str]]:
if node.concept_map is None:
return {}
found = config_log.concept_map(node.concept_map)
return {f: concept_map.table([found], f) for f in fields}
def run_map(p: str, node: Map):
codes = _codes(node, node.fields)
rows = [map_row(node, r, codes) for r in nodes.rows(p, node.inputs[0])]
return nodes.write(p, node.id, rows)
def run_fhir(p: str, node: Fhir):
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]):
bundle = json.loads(row[node.column])
for r in fhir_in.rows(bundle, node.entity, p, maps):
found[r[RECORD]] = r
return nodes.write(p, node.id, list(found.values()))
def run_join(p: str, node: Join):
left, right = (list(nodes.rows(p, i)) for i in node.inputs)
return nodes.write(p, node.id, join(node, left, right, node.inputs[1]))
@cache
def _llm() -> tuple[OpenAI, str] | None:
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)
try:
client.models.list()
except OpenAIError:
return None
return client, os.environ["LLM_MODEL"]
PROMPT = (
"Extract every {entity} record stated in the document. For each field give its value "
"in the schema's terms and `quote`: the exact text of the document it was read from, "
"copied character by character. Leave out fields the document does not state.{hints}"
)
def _ask_llm(node: Extract, text: str) -> dict:
client, model = _llm()
system = PROMPT.format(entity=node.entity, hints=f"\n{node.hints}" if node.hints else "")
key = hashlib.sha256(json.dumps([model, system, text]).encode()).hexdigest()
if found := nodes.cached("llm_cache", {key}):
return json.loads(found[key]["answer"])
reply = client.chat.completions.create(
model=model, temperature=0, seed=7,
messages=[{"role": "system", "content": system}, {"role": "user", "content": text}],
response_format={"type": "json_schema", "json_schema": {
"name": "answer", "schema": answer_schema(node.entity), "strict": True}},
) # fmt: skip
answer = reply.choices[0].message.content
nodes.remember("llm_cache", [{"key": key, "answer": answer, "model": model}], {})
return json.loads(answer)
def run_extract(p: str, node: Extract):
use_llm = node.method == "llm" or (node.method == "auto" and _llm() is not None)
codes = _codes(node, node.patterns)
out = []
for row in nodes.rows(p, node.inputs[0]):
text = node.text(row)
if use_llm:
found = ground(_ask_llm(node, text), text)
elif node.patterns:
found = apply_patterns(node, text, codes)
else:
found = [({}, {}, ["no LLM answering and no patterns set"])]
taken = {f: row[c] for f, c in node.columns.items() if row.get(c) is not None}
for index, (values, quotes, held) in enumerate(found or [({}, {}, ["nothing found"])]):
out.append({**values, **taken, RECORD: row[RECORD], "_index": index,
QUOTES: json.dumps(quotes, ensure_ascii=False),
HELD: json.dumps(held) if held else None}) # fmt: skip
return nodes.write(p, node.id, out)
def _comparison(field: str):
if field == "birth_date":
return cl.DateOfBirthComparison(field, input_is_string=True)
if field == "full_name":
return cl.NameComparison(field)
if field in ("record_number", "curp", "nss"):
return cl.LevenshteinAtThresholds(field, [1, 2])
return cl.ExactMatch(field)
def _plain(identifier: str) -> str:
return "".join(ch for ch in identifier if ch.isalnum()).upper()
def _name(name: str) -> str:
plain = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode()
return " ".join(plain.upper().split())
def _near(identifier: str) -> list[str]:
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]]:
skip, fixed = nodes.rejected("identity"), nodes.corrections()
records: dict[str, dict] = {}
sources: dict[str, str] = {}
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], {})}
mine = records.setdefault(row[RECORD], {"unique_id": row[RECORD]})
sources.setdefault(row[RECORD], i)
for f in node.fields:
if row.get(f) is not None and mine.get(f) is None:
value = str(row[f])
if f == "full_name":
written[row[RECORD]] = " ".join(value.split())
mine[f] = (
_plain(value) if f in IDENTIFIERS
else _name(value) if f == "full_name" else value
) # fmt: skip
frame = pd.DataFrame(list(records.values()))
present = [f for f in node.fields if f in frame and frame[f].notna().any()]
return frame[["unique_id", *present]], sources, written
def _distinct(records: pd.DataFrame, rules: list[str], judged: set[str]) -> pd.Series:
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)
stand_in = records.groupby(same, sort=False)["unique_id"].transform("first")
stand_in = stand_in.where(~records["unique_id"].isin(judged), records["unique_id"])
joined = set()
if rules:
con = duckdb.connect()
con.register("candidates", records[records["unique_id"].isin(set(stand_in))])
joins = " or ".join(f"({r})" for r in rules)
joined = set(con.sql(
f"select l.unique_id from candidates l join candidates r"
f" on l.unique_id = r.unique_id where {joins}"
).df()["unique_id"]) # fmt: skip
return stand_in.where(stand_in.isin(joined), records["unique_id"])
def _persons(records: pd.DataFrame, edges: pd.DataFrame, db: DuckDBAPI) -> pd.DataFrame:
clusters = cluster_pairwise_predictions_at_threshold(
records[["unique_id"]], edges, db, "unique_id", "unique_id_l", "unique_id_r"
)
return clusters.as_pandas_dataframe()[["unique_id", "cluster_id"]].merge(records)
def run_link(p: str, node: Link):
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()
if all(f"l.{f}" not in r or f in fields for f in node.fields)] # fmt: skip
comparisons = [_comparison(f) for f in fields]
decided = nodes.person_decisions()
stand_in = _distinct(records, rules, set().union(*decided))
distinct = records[records["unique_id"].isin(set(stand_in))]
db = DuckDBAPI()
linker = Linker(
db.register(distinct),
SettingsCreator(link_type="dedupe_only", comparisons=comparisons,
blocking_rules_to_generate_predictions=rules),
log_level=None,
) # fmt: skip
sure = linker.inference.deterministic_link().as_pandas_dataframe()
pairs = {frozenset(e) for e in zip(sure.unique_id_l, sure.unique_id_r, strict=True)}
pairs = {e for e in pairs if decided.get(e, True)} | {e for e, same in decided.items() if same}
known = set(distinct.unique_id)
edges = pd.DataFrame(
[sorted(e) for e in pairs if e <= known], columns=["unique_id_l", "unique_id_r"]
)
cluster = _persons(distinct, edges, db).set_index("unique_id")["cluster_id"]
persons = records.assign(cluster_id=stand_in.map(cluster).to_numpy())
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()
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}
why |= {c: "no name, birth date or record number was read" for c in nameless - torn}
columns = {f: {"data_type": "text", "nullable": True} for f in (HELD, "_source", *fields)}
stable = nodes.stable_persons(persons.groupby("cluster_id")["unique_id"].apply(list).to_dict())
linked = [
{RECORD: r.unique_id, "person_id": stable[r.cluster_id], "_source": sources[r.unique_id],
HELD: json.dumps([why[r.cluster_id]]) if r.cluster_id in why else None,
**{f: getattr(r, f) for f in fields},
**({"full_name": written[r.unique_id]} if r.unique_id in written else {})}
for r in persons.itertuples()
] # fmt: skip
nodes.write(p, node.id, linked, columns)
nodes.stage("identity", p, node.id, linked, silver.identity_columns())
ids = [f for f in IDENTIFIERS if f in fields]
whole = persons.drop(columns="unique_id").groupby("cluster_id").first()
for f in ids:
near = (
persons.dropna(subset=[f])
.groupby("cluster_id")[f]
.agg(lambda values: sorted({n for v in values for n in _near(v)}))
)
whole[f"{f}_near"] = near.reindex(whole.index).apply(
lambda v: v if isinstance(v, list) else []
)
whole = whole.reset_index().rename(columns={"cluster_id": "unique_id"})
blocks = [block_on(f"{f}_near", arrays_to_explode=[f"{f}_near"]) for f in ids]
reasons = [f"{f} one typo apart" for f in ids]
if "birth_date" in fields:
blocks.append(block_on("birth_date"))
reasons.append("same birth date")
model = Linker(
db.register(whole),
SettingsCreator(link_type="dedupe_only", comparisons=comparisons,
blocking_rules_to_generate_predictions=blocks),
log_level=None,
) # fmt: skip
model.training.estimate_u_using_random_sampling(max_pairs=1e6)
found = model.inference.predict(warning_mode="never").as_pandas_dataframe()
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()
undated = set(whole.unique_id[whole["birth_date"].isna()]) if "birth_date" in fields else set()
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()
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:
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(
pd.notna(x) and pd.notna(y) and x != y for x, y in sides
):
return None
reason = reasons[int(r.match_key)]
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"):
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)
if a in orphan and b in lone:
return a, b
if b in orphan and a in lone:
return b, a
return None
side = {r.unique_id: r for r in whole.itertuples()}
queue = []
for r in found.itertuples():
if pair := settle(r):
person, owner = pair
queue.append(
{
"person": person,
"candidate": owner,
"probability": r.match_probability,
"reason": reasons[int(r.match_key)],
**{f"person_{f}": getattr(side[person], f) for f in fields},
**{f"candidate_{f}": getattr(side[owner], f) for f in fields},
}
)
return nodes.write(p, f"{node.id}__review", queue)
def _births(linked) -> dict[str, date]:
found: dict[str, date] = {}
for row in linked:
try:
day = as_day(row.get("birth_date"))
except ValueError:
continue
if day:
found[row["person_id"]] = min(day, found.get(row["person_id"], day))
return found
def run_target(p: str, node: Target, kinds: dict[str, str]):
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()}
births = _births(linked.values())
model, study = catalog.model(node.entity), catalog.studies()[node.entity]
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):
values = {f: row.get(f) for f in model.model_fields if row.get(f) is not None}
values |= {f: v for f, v in fixed.get(row[RECORD], {}).items()
if f in model.model_fields} # fmt: skip
held = json.loads(row.get(HELD) or "[]") + validate(node.entity, values)
if node.entity == "ados2":
held += ados2.errors(values, births.get(person.get(row[RECORD])))
if row[RECORD] not in person:
held.append("no identity linked to this record")
else:
held += json.loads(linked[row[RECORD]].get(HELD) or "[]")
base = {"study": node.entity, "person_id": person.get(row[RECORD]), RECORD: row[RECORD],
"_index": row.get("_index", 0), QUOTES: row.get(QUOTES)} # fmt: skip
if held:
raw = json.dumps(values, default=str, ensure_ascii=False)
held_rows.append({**base, HELD: json.dumps(held), "_raw": raw})
continue
clean = model.model_validate(values)
instance = json.dumps([str(getattr(clean, k)) for k in model.key])
for name, field in study.fields.items():
if (value := getattr(clean, name)) is not None:
observations.append({**base, "instance": instance, "field": name,
catalog.value_column(field): value}) # fmt: skip
nodes.stage("observation", p, node.id, observations, silver.OBSERVATION)
return nodes.stage("held", p, node.id, held_rows, silver.HELD_ROWS)
RUNNERS: dict[str, Callable] = {
"source": nodes.run_source, "read": run_read, "route": run_route, "map": run_map,
"join": run_join, "extract": run_extract, "link": run_link, "edf": run_edf, "fhir": run_fhir,
} # fmt: skip
def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print) -> None:
kinds = {n.id: n.kind for n in pipeline.nodes}
for node in pipeline.order():
if node.kind == "target":
run_target(pipeline_id, node, kinds)
elif node.kind == "route" and node.otherwise:
others = [n for n in pipeline.nodes if n.kind == "route" and n.id != node.id
and n.inputs == node.inputs and not n.otherwise] # fmt: skip
run_route(pipeline_id, node, others)
else:
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+"])
log(f"silver and gold, from {', '.join(entities)}")
+69
View File
@@ -0,0 +1,69 @@
from collections.abc import Callable
from dataclasses import dataclass
from datetime import date
import mlflow.pyfunc
import pandas as pd
from joblib.externals.loky import get_reusable_executor
from persistance import gold, registry
class EmptyCohort(ValueError):
pass
class Predictor(mlflow.pyfunc.PythonModel):
def __init__(self, spec, fitted):
self.spec, self.fitted = spec, fitted
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
return self.spec.predict(self.fitted, model_input)
@dataclass(frozen=True)
class Jobs:
domain: str
models: dict
technical_validation: Callable[..., dict]
interpretability: Callable[..., dict]
@property
def events(self) -> str:
return f"{self.domain}_events"
def routine(self) -> list[str]:
return list(self.models)
def registered(self, name: str) -> str:
return f"{self.domain}.{name}"
def train(self, name: str, as_of: date | None = None) -> int:
spec, as_of = self.models[name], as_of or date.today()
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}")
fitted, metrics, found = spec.train(events, as_of)
else:
events = gold.timelines(self.events, spec.cohort, as_of)
if events.empty:
raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}")
fitted, metrics, data = spec.train(events, as_of)
found = {
"technical_validation": self.technical_validation(spec, metrics, data),
"interpretability": self.interpretability(spec, fitted, data),
}
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:
found = registry.champion(self.registered(name))
if found is None:
return None
version, model = found
risks = model.predict(gold.timelines(self.events, self.models[name].cohort))
gold.save_scores(self.registered(name), version, risks)
return version
-176
View File
@@ -1,176 +0,0 @@
"""El contrato con que se le pide a un modelo el riesgo de los miembros de una cohorte (ADR-MD-008).
Quien llama (la arista `estimar` de Orquestacion) le da al estimador el marco de un armado
de cohorte, ancho: `(columnas, filas)`, con `columnas = ["pac_id", "fecha_indice", <variables>]`
(lo que devuelve `indicadores_kit.cohortes.armado.leer_marco`). El estimador devuelve un
`Riesgo` por miembro y horizonte, y su `Procedencia`: las llaves con que se concilia con
MLflow (opción A del prototipo; MLflow no guarda filas ni pacientes).
Este módulo no importa al kit, a Persistance ni a Orquestacion: recibe listas.
"""
import hashlib
import json
from dataclasses import asdict, dataclass
from typing import NamedTuple, Protocol, runtime_checkable
class Riesgo(NamedTuple):
"""El riesgo de un miembro a un horizonte (FHIR `RiskAssessment.prediction`)."""
pac_id: int
horizonte_anios: float # años desde la fecha índice; 0 = prevalente
probabilidad: float # de 0 a 1
ic_bajo: float | None = None
ic_alto: float | None = None
@dataclass(frozen=True)
class Procedencia:
"""De qué modelo salen los riesgos: las llaves que guarda el lote (`PROCEDENCIA` de Persistance)."""
modelo_nombre: str
modelo_version: str
mlflow_run_id: str
modelo_sha: str
def como_dict(self) -> dict[str, str]:
return asdict(self)
@runtime_checkable
class EstimadorDeRiesgo(Protocol):
"""Lo que cumple todo modelo de riesgo que Orquestacion puede llamar."""
cohorte_url: str # la cohorte cuyo marco consume ("cacu/cohorte_vigilancia")
desenlace: str # lo que predice ("cin2_mas")
def procedencia(self) -> Procedencia: ...
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]: ...
# La regla del sustituto: una probabilidad base y lo que suma cada predictor basal.
REGLA_SINTETICA = {"base": 0.01, "pap_anormal": 0.05, "vph_positivo": 0.10, "tope": 0.95}
PAP_NORMALES = ("NORMAL",)
class RiesgoSintetico:
"""Un estimador sustituto determinista, sin MLflow: para pruebas y para desplegar sin el modelo real.
La probabilidad sale de una tabla fija por los predictores basales: `REGLA_SINTETICA["base"]`,
más `pap_anormal` si `pap_0` no es `NORMAL` ni nulo, más `vph_positivo` si `hpv_0` es
`POSITIVO`, con tope. Sin intervalo. No es un modelo clínico.
"""
def __init__(self, cohorte_url: str = "cacu/cohorte_vigilancia", desenlace: str = "cin2_mas",
horizontes: tuple[float, ...] = (0.0,)):
self.cohorte_url = cohorte_url
self.desenlace = desenlace
self.horizontes = tuple(horizontes)
def procedencia(self) -> Procedencia:
regla = {"regla": REGLA_SINTETICA, "pap_normales": PAP_NORMALES, "horizontes": self.horizontes}
sha = hashlib.sha256(json.dumps(regla, sort_keys=True).encode("utf-8")).hexdigest()
return Procedencia(modelo_nombre="sustituto", modelo_version="1", mlflow_run_id="sin-mlflow", modelo_sha=sha)
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]:
faltan = [c for c in ("pac_id", "pap_0", "hpv_0") if c not in columnas]
if faltan:
raise ValueError(f"El marco no trae las columnas {faltan}: el sustituto las necesita.")
i_pac, i_pap, i_vph = (columnas.index(c) for c in ("pac_id", "pap_0", "hpv_0"))
riesgos = []
for fila in filas:
p = REGLA_SINTETICA["base"]
if fila[i_pap] is not None and fila[i_pap] not in PAP_NORMALES:
p += REGLA_SINTETICA["pap_anormal"]
if fila[i_vph] == "POSITIVO":
p += REGLA_SINTETICA["vph_positivo"]
p = min(p, REGLA_SINTETICA["tope"])
riesgos += [Riesgo(int(fila[i_pac]), float(h), round(p, 6)) for h in self.horizontes]
return riesgos
# La regla del sustituto de TEA: lo que suma la interpretación del M-CHAT índice y lo perinatal.
REGLA_SINTETICA_TEA = {"base": 0.02, "mchat_medio": 0.10, "mchat_alto": 0.30, "ucin": 0.05, "apgar_bajo": 0.05,
"apgar_corte": 7, "tope": 0.95}
class RiesgoSinteticoTea:
"""El sustituto determinista de TEA, sobre el marco de `tea/cohorte_tamizaje` (T-21e). Sin MLflow.
La probabilidad de un diagnóstico de TEA al horizonte (4 años = 48 meses, el de la cohorte) es
`REGLA_SINTETICA_TEA["base"]`, más `mchat_medio` o `mchat_alto` según `mchat_0`, más `ucin` si
`ingreso_ucin` es 1, más `apgar_bajo` si `apgar_5min` es menor que `apgar_corte`, con tope. Sin
intervalo. No es un modelo clínico.
"""
def __init__(self, cohorte_url: str = "tea/cohorte_tamizaje", desenlace: str = "d",
horizontes: tuple[float, ...] = (4.0,)):
self.cohorte_url = cohorte_url
self.desenlace = desenlace
self.horizontes = tuple(horizontes)
def procedencia(self) -> Procedencia:
regla = {"regla": REGLA_SINTETICA_TEA, "horizontes": self.horizontes}
sha = hashlib.sha256(json.dumps(regla, sort_keys=True).encode("utf-8")).hexdigest()
return Procedencia(modelo_nombre="sustituto_tea", modelo_version="1", mlflow_run_id="sin-mlflow",
modelo_sha=sha)
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]:
necesarias = ("pac_id", "mchat_0", "ingreso_ucin", "apgar_5min")
faltan = [c for c in necesarias if c not in columnas]
if faltan:
raise ValueError(f"El marco no trae las columnas {faltan}: el sustituto las necesita.")
i_pac, i_mchat, i_ucin, i_apgar = (columnas.index(c) for c in necesarias)
r = REGLA_SINTETICA_TEA
riesgos = []
for fila in filas:
p = r["base"] + {"RIESGO_MEDIO": r["mchat_medio"], "RIESGO_ALTO": r["mchat_alto"]}.get(fila[i_mchat], 0.0)
if fila[i_ucin] == 1:
p += r["ucin"]
if fila[i_apgar] is not None and fila[i_apgar] < r["apgar_corte"]:
p += r["apgar_bajo"]
p = min(p, r["tope"])
riesgos += [Riesgo(int(fila[i_pac]), float(h), round(p, 6)) for h in self.horizontes]
return riesgos
# La regla del sustituto de CaMa: lo que suma el BI-RADS índice.
REGLA_SINTETICA_CAMA = {"base": 0.005, "birads_0": 0.03, "birads_3": 0.02, "birads_4": 0.30, "birads_5": 0.80,
"tope": 0.95}
BIRADS_SUSPECHA = {"B0": "birads_0", "B3": "birads_3", "B4": "birads_4", "B4A": "birads_4", "B4B": "birads_4",
"B4C": "birads_4", "B5": "birads_5"}
class RiesgoSinteticoCama:
"""El sustituto determinista de CaMa, sobre el marco de `cama/cohorte_tamizaje` (T-21g). Sin MLflow.
La probabilidad de cáncer de mama por biopsia al horizonte (1 año, el de la cohorte) es
`REGLA_SINTETICA_CAMA["base"]` más lo que suma la categoría del BI-RADS índice (`birads_0`), con
tope. Las subcategorías 4A, 4B y 4C suman como 4. Sin intervalo. No es un modelo clínico.
"""
def __init__(self, cohorte_url: str = "cama/cohorte_tamizaje", desenlace: str = "d",
horizontes: tuple[float, ...] = (1.0,)):
self.cohorte_url = cohorte_url
self.desenlace = desenlace
self.horizontes = tuple(horizontes)
def procedencia(self) -> Procedencia:
regla = {"regla": REGLA_SINTETICA_CAMA, "birads": BIRADS_SUSPECHA, "horizontes": self.horizontes}
sha = hashlib.sha256(json.dumps(regla, sort_keys=True).encode("utf-8")).hexdigest()
return Procedencia(modelo_nombre="sustituto_cama", modelo_version="1", mlflow_run_id="sin-mlflow",
modelo_sha=sha)
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]:
faltan = [c for c in ("pac_id", "birads_0") if c not in columnas]
if faltan:
raise ValueError(f"El marco no trae las columnas {faltan}: el sustituto las necesita.")
i_pac, i_birads = columnas.index("pac_id"), columnas.index("birads_0")
r = REGLA_SINTETICA_CAMA
riesgos = []
for fila in filas:
p = min(r["base"] + r.get(BIRADS_SUSPECHA.get(fila[i_birads]), 0.0), r["tope"])
riesgos += [Riesgo(int(fila[i_pac]), float(h), round(p, 6)) for h in self.horizontes]
return riesgos
+534
View File
@@ -0,0 +1,534 @@
import json
import warnings
from dataclasses import dataclass, field
from itertools import pairwise
import numpy as np
import pandas as pd
from joblib import Parallel, delayed
from scipy.optimize import minimize_scalar
from scipy.special import gammaln
from sklearn.base import BaseEstimator
from sklearn.linear_model import LogisticRegression
UNKNOWN = "NA"
DAYS_PER_MONTH = 30.4375
DAYS_PER_YEAR = 365.25
def outcomes(index: pd.Series, death: pd.Series, end, cap_months: int) -> pd.DataFrame:
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)
days = (last - index).dt.days.to_numpy()
months = np.floor(days / DAYS_PER_MONTH).astype(int).clip(min=0)
if cap_months:
died = died & (months < cap_months)
months = np.minimum(months, cap_months)
return pd.DataFrame({"months": months, "event": died}, index=index.index)
def band(values: pd.Series, cuts: list) -> pd.Series:
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)
@dataclass(frozen=True)
class Constant:
p: float
def predict_proba(self, X) -> np.ndarray:
return np.column_stack([np.full(len(X), 1 - self.p), np.full(len(X), self.p)])
def _bdeu(code, y, w, q, ess) -> float:
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))
+ np.sum(gammaln(ajk + n) - gammaln(ajk), axis=1))) # fmt: skip
def _search(X, levels, y, w, ess, max_parents) -> list[int]:
parents, code, q = [], np.zeros(len(y), int), 1
best = _bdeu(code, y, w, q, ess)
while len(parents) < max_parents:
found = None
for j in range(X.shape[1]):
if j in parents or q * levels[j] > 200_000:
continue
c2 = code * levels[j] + X[:, j]
score = _bdeu(c2, y, w, q * levels[j], ess)
if score > best + 1e-9 and (found is None or score > found[0]):
found = (score, j, c2, q * levels[j])
if found is None:
break
best, j, code, q = found
parents.append(j)
return parents
def _code(X, levels, parents) -> np.ndarray:
code = np.zeros(len(X), int)
for j in parents:
code = code * levels[j] + X[:, j]
return code
class IntervalSurvival(BaseEstimator):
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
self.borders = borders
self.parents = parents
self.ess = ess
self.max_parents = max_parents
self.folds = folds
self.shrink = shrink
self.seed = seed
def _frame(self, X: pd.DataFrame) -> pd.DataFrame:
found = X[list(self.features)].astype(object)
return found.where(found.notna(), UNKNOWN).astype(str)
def _encode(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
frame = self._frame(X)
columns = []
for name in self.features:
known = self.categories_[name]
codes = pd.Categorical(frame[name], categories=known).codes
fallback = known.index(UNKNOWN) if UNKNOWN in known else 0
columns.append(np.where(codes < 0, fallback, codes))
dummies = pd.get_dummies(frame).reindex(columns=self.dummies_, fill_value=0)
return dummies.to_numpy(dtype=np.float32), np.column_stack(columns).astype(int)
def _fit_intervals(self, X_dum, X_int, months, event) -> list:
fitted = []
for a, b in pairwise(self.borders):
at_risk = np.where(months >= a)[0]
if len(at_risk) == 0:
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)
w = np.where(~e & (m < b), 0.5, 1.0)
if y.min() == y.max():
lr = Constant(float(y[0]))
else:
lr = LogisticRegression(C=1e6, max_iter=500)
lr.fit(X_dum[at_risk], y, sample_weight=w)
fitted.append((lr, self._hbn(X_int[at_risk], y, w)))
return fitted
def _hbn(self, X, y, w) -> tuple[list[int], np.ndarray]:
if self.parents is None:
parents = _search(X, self.levels_, y, w, self.ess, self.max_parents)
else:
parents = [list(self.features).index(p) for p in self.parents]
q = int(np.prod([self.levels_[j] for j in parents])) if parents else 1
n = np.bincount(_code(X, self.levels_, parents) * 2 + y, weights=w,
minlength=q * 2).reshape(q, 2) # fmt: skip
aj = self.ess / q
marginal = (n[:, 1].sum() + 0.5) / (n.sum() + 1)
return parents, (n[:, 1] + aj * marginal) / (n.sum(1) + aj)
def _predict(self, fitted, X_dum, X_int) -> tuple[np.ndarray, np.ndarray]:
lr = np.column_stack([m.predict_proba(X_dum)[:, 1] for m, _ in fitted])
hbn = np.column_stack([cpt[_code(X_int, self.levels_, p)] for _, (p, cpt) in fitted])
return lr, hbn
def _weights(self, X_dum, X_int, months, event) -> np.ndarray:
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))
for k in range(self.folds):
test, train = np.where(fold == k)[0], np.where(fold != k)[0]
fitted = self._fit_intervals(X_dum[train], X_int[train], months[train], event[train])
oof_lr[test], oof_hbn[test] = self._predict(fitted, X_dum[test], X_int[test])
weights = []
for j, (a, b) in enumerate(pairwise(self.borders)):
at_risk = np.where(months >= a)[0]
if len(at_risk) == 0:
weights.append(0.5)
continue
m, e = months[at_risk], event[at_risk]
y = np.where(e & (m < b), 0, 1)
w = np.where(~e & (m < b), 0.5, 1.0)
p1 = np.clip(oof_lr[at_risk, j], 1e-9, 1 - 1e-9)
p2 = np.clip(oof_hbn[at_risk, j], 1e-9, 1 - 1e-9)
def loss(x, p1=p1, p2=p2, y=y, w=w):
p = np.clip(x * p1 + (1 - x) * p2, 1e-9, 1 - 1e-9)
return -np.sum(w * (y * np.log(p) + (1 - y) * np.log1p(-p)))
best = float(minimize_scalar(loss, bounds=(0, 1), method="bounded").x)
shrunk = self.shrink / (self.shrink + int((y == 0).sum()))
weights.append((1 - shrunk) * best + shrunk * 0.5)
return np.array(weights)
def fit(self, X: pd.DataFrame, months, event):
frame = self._frame(X)
self.dummies_ = list(pd.get_dummies(frame, drop_first=True).columns)
self.categories_ = {name: list(pd.factorize(frame[name])[1]) for name in self.features}
X_dum, X_int = self._encode(X)
self.levels_ = X_int.max(axis=0) + 1
months, event = np.asarray(months, int), np.asarray(event, bool)
if len(X) >= 2 * self.folds:
self.weights_ = self._weights(X_dum, X_int, months, event)
else:
self.weights_ = np.full(len(self.borders) - 1, 0.5)
self.fitted_ = self._fit_intervals(X_dum, X_int, months, event)
return self
def components(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
return self._predict(self.fitted_, *self._encode(X))
def survival(self, X: pd.DataFrame) -> np.ndarray:
lr, hbn = self.components(X)
w = self.weights_[None, :]
return np.cumprod(w * lr + (1 - w) * hbn, axis=1)
TRAIN_FRACTION = 0.7
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high",
"scenarios"] # fmt: skip
SCENARIO_SEPARATOR = " | "
def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]:
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:
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))
@dataclass(frozen=True)
class Spec:
name: str
cohort: str
features: tuple[str, ...]
covariates: object
parents: tuple[str, ...] | None = None
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, ...] = ()
scenarios: dict[str, tuple[tuple[str, str, object], ...]] = field(default_factory=dict)
scenario_columns: tuple[str, ...] = ()
treatments: tuple[str, ...] = ()
@property
def horizons(self) -> tuple[float, ...]:
return tuple(b / 12 for b in self.borders[1:])
def members(self, events: pd.DataFrame) -> pd.DataFrame:
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()
death = events[events["type"] == "death"].groupby("person_id")["date"].min()
found["death_date"] = death.reindex(found.index)
kept = [*self.features, *self.scenario_columns]
found = found.join(self.covariates(events, found)[kept])
return found.reset_index()
def _model(self) -> IntervalSurvival:
return IntervalSurvival(list(self.features), self.borders, self.parents)
def _combinations(self, X: pd.DataFrame) -> pd.DataFrame:
found = X[list(self.features)].astype(object)
return found.where(found.notna(), UNKNOWN).astype(str).reset_index(drop=True)
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)
samples = [rng.integers(0, len(train), len(train)) for _ in range(self.replicas)]
def mortality(rows: np.ndarray) -> np.ndarray:
sample = train.iloc[rows].reset_index(drop=True)
refit = self._model().fit(sample, sample["months"], sample["event"])
return 1.0 - refit.survival(frame)
replicas = Parallel(n_jobs=-1)(delayed(mortality)(rows) for rows in samples)
tail = 50 * (1 - self.interval_level)
low, high = np.nanpercentile(np.stack(replicas), [tail, 100 - tail], axis=0)
rows = combinations.itertuples(index=False)
return {tuple(c): (low[i].tolist(), high[i].tolist()) for i, c in enumerate(rows)}
def train(self, events: pd.DataFrame, as_of) -> tuple:
members = self.members(events)
members = members.join(
outcomes(members["index_date"], members["death_date"], as_of, self.cap_months)
)
train, test = split(members, TRAIN_FRACTION)
model = self._model().fit(train, train["months"], train["event"])
model.intervals_ = self._intervals(train) if self.interval_level else {}
weights = zip(self.borders[1:], model.weights_, strict=True)
metrics = {
"n_train": float(len(train)), "n_test": float(len(test)),
"events_train": float(train["event"].sum()), "events_test": float(test["event"].sum()),
**{f"stack_w_lr_{b}m": float(w) for b, w in weights},
} # fmt: skip
return model, metrics, {"train": train, "test": test}
def predict(self, model: IntervalSurvival, events: pd.DataFrame) -> pd.DataFrame:
members = self.members(events)
mortality = 1.0 - model.survival(members)
n, h = len(members), len(self.horizons)
empty = ([np.nan] * h, [np.nan] * h)
ends = [model.intervals_.get(tuple(c), empty)
for c in self._combinations(members).itertuples(index=False)] # fmt: skip
masks = scenario_masks(members, self.scenarios)
scenarios = [SCENARIO_SEPARATOR.join(name for name, m in masks.items() if m[i]) or None
for i in range(n)] # fmt: skip
return pd.DataFrame({
"person_id": np.repeat(members["person_id"].to_numpy(), h),
"index_date": np.repeat(members["index_date"].dt.date.to_numpy(), h),
"horizon_years": np.tile(np.asarray(self.horizons, dtype=float), n),
"probability": mortality.ravel(),
"ci_low": np.array([e[0] for e in ends], dtype=float).ravel(),
"ci_high": np.array([e[1] for e in ends], dtype=float).ravel(),
"scenarios": np.repeat(np.asarray(scenarios, dtype=object), h),
})[OUTPUT] # fmt: skip
BOOTSTRAP = 100
BOOTSTRAP_SEED = 42
def technical_validation(spec: Spec, metrics: dict, data: dict) -> dict:
members = pd.concat([data["train"], data["test"]])
return {
"model": spec.name, "method": spec.method, "cohort": spec.cohort,
"split": "temporal: the earliest 70% of index dates train, the latest 30% test",
"members": len(members),
"index_dates": [str(members["index_date"].min().date()),
str(members["index_date"].max().date())],
"horizons_months": list(spec.borders[1:]),
"follow_up_cap_months": spec.cap_months,
"notes": list(spec.notes),
"metrics": metrics,
} # fmt: skip
def _curve(fitter, name: str) -> dict:
table = fitter.confidence_interval_survival_function_
return {
"months": fitter.survival_function_.index.tolist(),
"survival": fitter.survival_function_.iloc[:, 0].tolist(),
"low": table.iloc[:, 0].tolist(), "high": table.iloc[:, 1].tolist(), "name": name,
} # fmt: skip
MIN_SCENARIO_EVENTS = 5
GRID_POINTS = 200
def scenario_masks(members: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
found = {}
for name, conditions in scenarios.items():
mask = np.ones(len(members), bool)
for column, op, value in conditions:
v = members[column]
if op in ("<", ">="):
number = pd.to_numeric(v, errors="coerce")
held = number < value if op == "<" else number >= value
elif op == "in":
held = v.isin(list(value))
elif op == "==":
held = v == value
else:
raise ValueError(f"unknown condition {op!r} in scenario {name!r}")
mask &= held.fillna(False).to_numpy(bool)
found[name] = mask
return found
def _scenario_curves(months: np.ndarray, event: np.ndarray, cap_months: int) -> dict:
from models import curves
d, c, _ = curves.life_table(months, event)
k, lam = curves.fit_weibull(d, c)
fractional = curves.fit_fractional(d, c, k, lam)
grid = np.linspace(0, cap_months, GRID_POINTS)
observed = int(months.max())
km = curves.kaplan_meier(months, event, observed)
return {
"observado_hasta": observed,
"km": {"months": list(range(observed + 1)),
**{n: v.tolist() for n, v in zip(("S", "low", "high"), km, strict=True)}},
"weibull": {"t": grid.tolist(), "S": curves.weibull(grid, k, lam).tolist(),
"k": k, "lambda": lam},
"weibull_fractional": {"t": grid.tolist(),
"S": curves.fractional(grid, k, *fractional).tolist(),
"alpha": fractional[0], "beta": fractional[1],
"lambda": fractional[2]},
} # fmt: skip
def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
from lifelines import KaplanMeierFitter, WeibullFitter
train = data["train"]
months, event = train["months"].to_numpy(), train["event"].to_numpy()
curves = [_curve(KaplanMeierFitter().fit(months, event), "Kaplan-Meier (IC 95 % Greenwood)")]
if event.any() and (months > 0).all():
curves.append(_curve(WeibullFitter().fit(months, event), "Weibull"))
rng = np.random.default_rng(BOOTSTRAP_SEED)
samples = [rng.integers(0, len(train), len(train)) for _ in range(BOOTSTRAP)]
members = pd.concat([train, data.get("test", train.iloc[:0])]).reset_index(drop=True)
masks = scenario_masks(members, spec.scenarios)
def mean_survival(rows: np.ndarray) -> tuple[np.ndarray, dict]:
sample = train.iloc[rows].reset_index(drop=True)
refit = spec._model().fit(sample, sample["months"], sample["event"])
found = refit.survival(members)
by = {n: found[m].mean(axis=0) for n, m in masks.items() if m.any()}
return found[: len(train)].mean(axis=0), by
all_months, all_event = members["months"].to_numpy(), members["event"].to_numpy(bool)
drawn = {n: m for n, m in masks.items() if all_event[m].sum() >= MIN_SCENARIO_EVENTS}
jobs = [delayed(_scenario_curves)(all_months[m], all_event[m], spec.cap_months)
for m in drawn.values()] # fmt: skip
jobs += [delayed(mean_survival)(rows) for rows in samples]
done = Parallel(n_jobs=-1)(jobs)
drawn_curves, replicas = done[: len(drawn)], done[len(drawn) :]
band = np.stack([r[0] for r in replicas])
point = model.survival(members)
scenarios = []
for (name, mask), found in zip(drawn.items(), drawn_curves, strict=True):
spread = np.array([r[1][name] for r in replicas])
low, high = np.nanpercentile(spread, [2.5, 97.5], axis=0)
scenarios.append({
"escenario": name,
"condiciones": [list(c) for c in spec.scenarios[name]],
"n": int(mask.sum()), "fallecidos": int(all_event[mask].sum()),
"horizons_months": list(spec.borders[1:]), "months_max": spec.cap_months,
**found,
"points": {"COMB": {"S": point[mask].mean(axis=0).tolist(),
"low": np.clip(low, 0, 1).tolist(),
"high": np.clip(high, 0, 1).tolist()}},
"bootstrap_replicas": len(replicas),
}) # fmt: skip
skipped = [{"escenario": n, "n": int(m.sum()), "fallecidos": int(all_event[m].sum())}
for n, m in masks.items() if n not in drawn] # fmt: skip
combinations = spec._combinations(train).value_counts().reset_index(name="members")
survival = model.survival(combinations.replace(UNKNOWN, None))
return {
"model": spec.name,
"kind": "curves",
"curves": curves,
"predicted": {
"months": list(spec.borders[1:]),
"survival": model.survival(train).mean(axis=0).tolist(),
"low": np.percentile(band, 2.5, axis=0).tolist(),
"high": np.percentile(band, 97.5, axis=0).tolist(),
"name": "LR + HBN combinado (IC 95 % bootstrap)",
},
"weights_lr": model.weights_.tolist(),
"parents": [[spec.features[j] for j in parents] for _, (parents, _) in model.fitted_],
"combinations": [
{**row, "survival": survival[i].tolist()}
for i, row in enumerate(combinations.to_dict("records"))
],
"escenarios": scenarios,
"escenarios_sin_curvas": skipped,
"min_fallecidos_escenario": MIN_SCENARIO_EVENTS,
**risk_factor_report(spec, model, members),
}
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",
"delta_S", "delta_IC95_inf", "delta_IC95_sup", "c1_or", "c3_manta_markov",
"c4_supervivencia", "criterios_cumplidos", "clasificacion",
) # fmt: skip
SURVIVAL_COLUMNS = ("S_categoria", "S_referencia", "delta_S")
TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)"
EVALUATED = ("c1_or", "c3_manta_markov", "c4_supervivencia")
def risk_factors(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> pd.DataFrame:
from models import factors as rated
horizon = spec.borders[-1]
months, event = members["months"].to_numpy(), members["event"].to_numpy(bool)
died = event & (months < horizon)
known = died | (months >= horizon)
data = spec._combinations(members)[known].reset_index(drop=True)
y, months, event = died[known].astype(int), months[known], event[known]
empty = pd.DataFrame(columns=list(FACTOR_COLUMNS))
if len(data) == 0 or y.min() == y.max():
return empty
features = list(spec.features)
treatment = [f for f in features if f in spec.treatments]
intrinsic = [f for f in features if f not in spec.treatments]
reference = {v: data[v].value_counts().idxmax() for v in features}
blanket = {features[j] for _, (parents, _) in model.fitted_ for j in parents}
def complete(table, variables):
return rated.complete(table, variables, reference, data, months, event, horizon,
SURVIVAL_COLUMNS) # fmt: skip
with warnings.catch_warnings(), np.errstate(over="ignore", divide="ignore"):
warnings.simplefilter("ignore")
try:
tab = complete(rated.odds_ratios(data, y, intrinsic, reference, "OR_muerte"),
intrinsic) # fmt: skip
except (np.linalg.LinAlgError, ValueError):
return empty
tab["c2_estabilidad"] = np.nan
tab["en_manta_markov"] = tab["c3_manta_markov"] = tab["variable"].isin(blanket)
tab = rated.classify(tab, "OR_muerte", "delta_S", UNKNOWN, EVALUATED)
tab["tipo"] = "factor de riesgo"
if treatment:
both = intrinsic + treatment
try:
tr = rated.odds_ratios(data, y, both, reference, "OR_muerte")
except (np.linalg.LinAlgError, ValueError):
tr = None
if tr is not None:
of = tr["termino"].map(lambda x: rated.variable_of(x, both))
tr = complete(tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)],
treatment) # fmt: skip
tr["tipo"], tr["clasificacion"] = "tratamiento", TREATMENT_CLASS
tab = pd.concat([tab, tr], ignore_index=True)
tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int)
tab["_order"] = tab["clasificacion"].map(rated.ORDER).fillna(5)
tab = tab.sort_values(["_kind", "_order", "OR_muerte"], ascending=[True, True, False])
return tab[list(FACTOR_COLUMNS)].round(4).reset_index(drop=True)
def scenario_factors(spec: Spec, members: pd.DataFrame, table: pd.DataFrame) -> list[dict]:
from models import factors as rated
found = rated.classified(table) if len(table) else table
data = spec._combinations(members)
rows = []
for name, mask in scenario_masks(members, spec.scenarios).items():
if not mask.any() or found.empty:
continue
rows.append({
"escenario": name, "condiciones": [list(c) for c in spec.scenarios[name]],
"n_escenario": int(mask.sum()), **rated.scenario_row(data, mask, found),
}) # fmt: skip
return rows
def risk_factor_report(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> dict:
table = risk_factors(spec, model, members)
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),
}
-19
View File
@@ -1,19 +0,0 @@
from typing import Any
from models.base import ScreeningModel
class TeaModel(ScreeningModel):
"""Scaffold for the TEA (autism spectrum disorder) screening model.
Can pull its own training data straight from `persistance.tea`'s
repositories (`pacientes_repository`, `evaluacion_psicologica_repository`,
...) or be handed already-fetched rows. No real model yet — this is
interface scaffolding only.
"""
def train(self, data: Any = None) -> None:
raise NotImplementedError("TEA training is not implemented yet.")
def predict(self, data: Any) -> Any:
raise NotImplementedError("TEA prediction is not implemented yet.")
View File
+747
View File
@@ -0,0 +1,747 @@
from __future__ import annotations
import hashlib
import json
import warnings
from dataclasses import dataclass, field
from pathlib import Path
import mlflow.pyfunc
import numpy as np
import pandas as pd
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 = (
"biomarker",
"zone",
"kind",
"outcome",
"outcome_code",
"event",
"model",
"n",
"odds_ratio",
"ci_low",
"ci_high",
"p",
"q",
"sens_model",
"sens_odds_ratio",
"same_direction",
"reason",
)
SCORE_COLUMNS = (
"key",
"biomarker",
"zone",
"outcome_code",
"z",
"probability",
"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"}),
2: ("Señalar", "SA", {"toddler", "module_1", "module_2"}),
3: ("Gestos", "SA", {"toddler", "module_1", "module_2"}),
4: ("Contacto visual inusual", "SA", {"toddler", "module_1", "module_2"}),
5: ("Expresiones faciales dirigidas a otros", "SA", {"toddler", "module_1", "module_2"}),
6: ("Integración de la mirada con otras conductas", "SA", {"toddler", "module_1"}),
7: ("Disfrute compartido en la interacción", "SA", {"toddler", "module_1", "module_2"}),
8: ("Respuesta al nombre", "SA", {"toddler"}),
9: ("Búsqueda de atención cuando se le ignora", "SA", {"toddler"}),
10: ("Pedir", "SA", {"toddler"}),
11: ("Mostrar", "SA", {"toddler", "module_1", "module_2"}),
12: (
"Iniciación espontánea de la atención conjunta",
"SA",
{"toddler", "module_1", "module_2"},
),
13: ("Respuesta a la atención conjunta", "SA", {"toddler", "module_1"}),
14: ("Calidad de los acercamientos sociales", "SA", {"toddler", "module_1", "module_2"}),
15: ("Cantidad de acercamientos sociales al cuidador", "SA", {"toddler"}),
16: ("Cantidad de comunicación social recíproca", "SA", {"module_2"}),
17: ("Calidad general de la relación", "SA", {"toddler", "module_2"}),
18: ("Entonación de vocalizaciones o verbalizaciones", "RRB", {"toddler", "module_1"}),
19: ("Uso estereotipado o idiosincrático de palabras", "RRB", {"module_1", "module_2"}),
20: ("Interés sensorial inusual", "RRB", {"toddler", "module_1", "module_2"}),
21: ("Manierismos de manos y dedos", "RRB", {"toddler", "module_1", "module_2"}),
22: (
"Intereses repetitivos o conductas estereotipadas",
"RRB",
{"toddler", "module_1", "module_2"},
),
}
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"
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]:
def spikes(zone, kind, outcome):
return _pair("spikes", zone, f"spikes_any_{zone}", kind, outcome)
out = [spikes("any", "domain", CSS)]
if level == "item":
out += [
spikes("left", "composite", [1, 18]),
spikes("right", "composite", [4, 5, 7]),
spikes("central", "exploratory", 21),
]
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 += [
_pair("posterior_rhythm", "posterior", "z_posterior_rhythm", kind, outcome)
for kind, outcome in rhythm
]
out.append(_pair("gradient", "global", "z_gradient", "domain", CSS))
return out
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)
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:
scores = pd.concat([item_scores(cohort, n) for n in ITEMS], axis=1)
return int(scores.notna().any(axis=1).sum()) >= minimum
CHI2_95 = float(stats.chi2.ppf(0.95, 1))
MIN_ROWS = 8
@dataclass
class Design:
predictor: str
numeric: dict[str, float] = field(default_factory=dict)
categorical: dict[str, list[str]] = field(default_factory=dict)
reference: dict[str, str] = field(default_factory=dict)
@classmethod
def of(cls, t: pd.DataFrame, predictor: str, adjust) -> Design:
d = cls(predictor)
for a in adjust:
if a not in t:
continue
v = t[a]
if pd.api.types.is_numeric_dtype(v):
v = v.astype(float)
if v.std() > 0:
d.numeric[a] = float(v.mean())
else:
ref = v.value_counts().index[0]
levels = [lv for lv in sorted(set(v) - {ref}) if 0 < (v == lv).sum() < len(v)]
if levels:
d.categorical[a] = [str(lv) for lv in levels]
d.reference[a] = str(ref)
return d
@property
def names(self) -> list[str]:
return ["intercept", self.predictor, *self.numeric] + [
f"{a}={lv}" for a, levels in self.categorical.items() for lv in levels
]
def matrix(self, t: pd.DataFrame) -> np.ndarray:
cols = [np.ones(len(t)), t[self.predictor].to_numpy(float)]
for a, mean in self.numeric.items():
cols.append(t[a].to_numpy(float) - mean if a in t else np.full(len(t), np.nan))
for a, levels in self.categorical.items():
v = t[a].astype(str) if a in t else pd.Series([None] * len(t))
for lv in levels:
cols.append((v == lv).to_numpy(float))
X = np.column_stack(cols)
known = np.ones(len(t), bool)
for a, levels in self.categorical.items():
seen = {self.reference[a], *levels}
known &= (
t[a].astype(str).isin(seen).to_numpy() & t[a].notna().to_numpy()
if a in t
else False
)
X[~known] = np.nan
return X
def to_dict(self) -> dict:
return {
"predictor": self.predictor,
"numeric": self.numeric,
"categorical": self.categorical,
"reference": self.reference,
}
@classmethod
def from_dict(cls, d: dict) -> Design:
return cls(
d["predictor"],
dict(d["numeric"]),
{k: list(v) for k, v in d["categorical"].items()},
dict(d["reference"]),
)
def _pl(b, X, y):
eta = X @ b
p = expit(eta)
w = p * (1 - p)
sign, logdet = np.linalg.slogdet(X.T @ (X * w[:, None]))
if sign <= 0:
return -np.inf
return float(np.sum(y * eta - np.logaddexp(0, eta)) + 0.5 * logdet)
def _score(b, X, y):
p = expit(X @ b)
w = p * (1 - p)
info = X.T @ (X * w[:, None])
h = np.einsum("ij,jk,ik->i", X, np.linalg.inv(info), X) * w
return X.T @ (y - p + h * (0.5 - p)), info
def _fit_firth(X, y, max_iter=200, tol=1e-10):
b = np.zeros(X.shape[1])
pl = _pl(b, X, y)
for _ in range(max_iter):
U, info = _score(b, X, y)
step = np.linalg.solve(info, U)
t = 1.0
while t > 1e-8:
nb = b + t * step
npl = _pl(nb, X, y)
if npl >= pl - 1e-12:
break
t /= 2
b, pl = nb, npl
if np.max(np.abs(t * step)) < tol:
break
return b, pl
def _profile_firth(value, j, X, y, b0):
free = [k for k in range(X.shape[1]) if k != j]
def f(bf):
b = np.empty(X.shape[1])
b[free], b[j] = bf, value
v = _pl(b, X, y)
if not np.isfinite(v):
return 1e10, np.zeros(len(free))
U, _ = _score(b, X, y)
return -v, -U[free]
return -float(optimize.minimize(f, b0[free], jac=True, method="BFGS").fun)
def _interval(profile, centre, maximum, scale):
g = lambda v: 2 * (maximum - profile(v)) - CHI2_95 # noqa: E731
limits = []
for sign in (-1, 1):
previous, limit = centre, sign * np.inf
for k in range(1, 80):
v = centre + sign * scale * k
if g(v) > 0:
limit = optimize.brentq(g, min(previous, v), max(previous, v))
break
previous = v
limits.append(limit)
return limits[0], limits[1]
def _summary(model, n, coef, lo, hi, p, design, state, **extra) -> dict:
return {
"model": model,
"n": n,
"coef": round(float(coef), 4),
"odds_ratio": round(float(np.exp(coef)), 4),
"ci_low": round(float(np.exp(lo)), 4),
"ci_high": round(float(np.exp(hi)), 4),
"p": round(p, 5),
"adjusted_for": ", ".join(design.names[2:]),
"reason": "",
**extra,
"state": {"design": design.to_dict(), **state},
}
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 = _complete(t, outcome, predictor, adjust)
y = d[outcome].to_numpy(float)
out = {"model": "firth", "n": len(d), "events": int(y.sum())}
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)
b, pl = _fit_firth(X, y)
_, info = _score(b, X, y)
se = float(np.sqrt(np.linalg.inv(info)[1, 1]))
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))
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:
X = Design.from_dict(state["design"]).matrix(t)
return expit(state["intercept"] + X[:, 1:] @ np.asarray(state["beta"]))
def firth_reference(state: dict) -> float:
return float(expit(state["intercept"]))
def _nll_ordinal(par, X, yk, K):
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
eta = X @ par[K - 1 :]
n = len(yk)
cdf = np.c_[np.zeros(n), expit(theta[None, :] - eta[:, None]), np.ones(n)]
pr = cdf[np.arange(n), yk + 1] - cdf[np.arange(n), yk]
return -float(np.sum(np.log(np.clip(pr, 1e-300, None))))
def _fit_ordinal(X, yk, K, fixed=None):
start = np.r_[np.linspace(-1, 1, K - 1)[0], np.zeros(K - 2), np.zeros(X.shape[1])]
if fixed is None:
r = optimize.minimize(lambda q: _nll_ordinal(q, X, yk, K), start, method="BFGS")
return r.x, float(r.fun)
j, value = fixed
idx = [k for k in range(len(start)) if k != K - 1 + j]
def f(q):
par = np.empty(len(start))
par[idx], par[K - 1 + j] = q, value
return _nll_ordinal(par, X, yk, K)
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 = _complete(t, outcome, predictor, adjust)
levels = np.sort(d[outcome].unique())
out = {"model": "ordinal", "n": len(d), "levels": len(levels)}
if not _ordinal_fits(d, levels, predictor):
return {**out, "reason": "too few data or no variation"}
design, X, yk = _ordinal_data(d, outcome, predictor, adjust, levels)
K = len(levels)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
par, nll = _fit_ordinal(X, yk, K)
beta = par[K - 1 :]
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))
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:
X = Design.from_dict(state["design"]).matrix(t)[:, 1:]
if state["threshold"] is None:
return np.where(np.isnan(X).any(axis=1), np.nan, state["always"])
return 1 - expit(state["threshold"] - X @ np.asarray(state["beta"]))
def ordinal_reference(state: dict) -> float:
return state["always"] if state["threshold"] is None else float(1 - expit(state["threshold"]))
def bh(p) -> np.ndarray:
p = np.asarray(p, dtype=float)
q = np.full(len(p), np.nan)
ok = np.isfinite(p)
if ok.any():
v = p[ok]
o = np.argsort(v)
r = v[o] * len(v) / np.arange(1, len(v) + 1)
r = np.minimum.accumulate(r[::-1])[::-1]
q[np.flatnonzero(ok)[o]] = np.minimum(r, 1)
return q
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:
try:
return fit(*args, **kwargs)
except (np.linalg.LinAlgError, ValueError) as error:
return {"model": model, "n": 0, "reason": f"singular design ({type(error).__name__})"}
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 _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.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 tested:
if pair["predictor"] not in prepared:
continue
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,
"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]:
if self.fitted is None:
raise ValueError(f"{self.name}: fit() before associations() or score()")
return self.fitted["rows"]
def associations(self) -> pd.DataFrame:
out = []
for r in self._rows():
f, s = r["principal"], r["sensitivity"]
ors, sens = f.get("odds_ratio"), s.get("odds_ratio")
out.append(
{
"biomarker": r["biomarker"],
"zone": r["zone"],
"kind": r["kind"],
"outcome": r["outcome"],
"outcome_code": outcome_code(r),
"event": _event(r, self.fitted["settings"]),
"model": f["model"],
"n": f["n"],
"odds_ratio": ors,
"ci_low": f.get("ci_low"),
"ci_high": f.get("ci_high"),
"p": f.get("p"),
"q": r["q"],
"sens_model": s["model"],
"sens_odds_ratio": sens,
"same_direction": (
None
if ors is None or sens is None
else bool(np.sign(ors - 1) == np.sign(sens - 1))
),
"reason": f.get("reason", ""),
}
)
return pd.DataFrame(out, columns=list(ASSOCIATION_COLUMNS))
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 rows:
f, predictor = r["principal"], r["predictor"]
if f.get("odds_ratio") is None or predictor not in prepared:
continue
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
t["_yes"], t["_level"] = _outcome(t, r, settings)
prob = _scores(t, fitted, r, settings)
kept = np.isfinite(prob)
parts.append(
pd.DataFrame(
{
"key": t["key"].to_numpy()[kept],
"biomarker": r["biomarker"],
"zone": r["zone"],
"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(_reference(f), 4),
}
)
)
if not parts:
return pd.DataFrame(columns=list(SCORE_COLUMNS))
return pd.concat(parts, ignore_index=True)[list(SCORE_COLUMNS)]
def save(self, path) -> None:
Path(path, "association.json").write_text(
json.dumps({"level": self.level, "fitted": self.fitted}, default=float)
)
@classmethod
def load(cls, path) -> Ados2Association:
d = json.loads(Path(path, "association.json").read_text())
return cls(d["level"], d["fitted"])
class Model(mlflow.pyfunc.PythonModel):
def __init__(self, fitted: dict):
self.fitted = json.loads(json.dumps(fitted, default=float))
def predict(self, context, cohort_df):
return Ados2Association(fitted=self.fitted).score(cohort_df)
View File
+125
View File
@@ -0,0 +1,125 @@
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
@dataclass(frozen=True)
class Metric:
code: str
value: float | None
electrodes: dict[str, float] = field(default_factory=dict)
zones: dict[str, float] = field(default_factory=dict)
@dataclass(frozen=True)
class Analysis:
valid: bool | None
level: str
reasons: list[str]
age_months: float | None
clean_fraction: float | None
bad_channels: int | None
channels: int | None
duration_min: float | None
line_noise_db: float | None
sleep: bool | None
checks: list[dict]
metrics: list[Metric]
features: dict[str, dict]
error: str | 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:
message = re.sub(r"(/|[A-Za-z]:\\)[^\s'\"]*", "<path>", str(exc))[:300]
return f"{type(exc).__name__}: {message}"
def analyze(
edf: bytes,
birth_date: date | None = None,
*,
age_months: float | None = None,
mains_hz: float = MAINS_HZ,
keep_flat=False,
) -> Analysis:
out = dict(
valid=None,
level=checks.NOT_ANALYZABLE,
reasons=[],
age_months=age_months,
clean_fraction=None,
bad_channels=None,
channels=None,
duration_min=None,
line_noise_db=None,
sleep=None,
checks=[],
metrics=[],
features={},
error=None,
)
try:
try:
rec = read.read(edf)
except read.FileNotValid as exc:
verdict = checks.file_not_valid(str(exc))
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)
given = read.age_months(rec.start, birth_date, DAYS_PER_MONTH)
out["age_months"] = age = header if header is not None else given
else:
age = age_months
verdict = checks.validate(rec, mains_hz)
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,
duration_min=round(rec.duration_s / 60, 2),
line_noise_db=_number(verdict.line_db),
checks=verdict.checks,
)
if not verdict.valid:
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)
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)))
+145
View File
@@ -0,0 +1,145 @@
from dataclasses import dataclass, replace
import numpy as np
from scipy.fft import rfft, rfftfreq
from scipy.signal.windows import hann
from scipy.stats import theilslopes
from models.tea.eeg import signals, spikes, spindles
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,
"Pz": -0.50, "P4": -0.53, "T6": -0.59, "O1": -0.95, "O2": -0.95,
} # fmt: skip
CODES = (
"posterior_rhythm",
"spindles",
"paroxysmal_spikes",
"anteroposterior_gradient",
)
@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
def posterior_rhythm(prep: Prepared, states) -> tuple[float, str | None]:
names = prep.columns(POSTERIOR)
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]
if len(found) < 2:
return np.nan, "no-dominant-peak"
return float(np.median(found)), None
def delta_gradient(prep: Prepared, states) -> tuple[float, str | None]:
names = [c for c in prep.names if c in FRONT_BACK]
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)
power = np.abs(rfft((stack - stack.mean(axis=-1, keepdims=True)) * hann(n, sym=True))) ** 2
delta = np.median(power[..., (f >= 0.5) & (f < 4)].sum(axis=-1), axis=0)
log_power = np.log10(np.maximum(delta, 1e-30))
y = np.array([FRONT_BACK[c] for c in names])
finite = np.isfinite(log_power)
if finite.sum() < MIN_GRADIENT_ELECTRODES:
return np.nan, "few-electrodes"
return float(theilslopes(log_power[finite], y[finite])[0]), None
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}
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,
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, why = delta_gradient(prep, states)
metrics["anteroposterior_gradient"] = (gradient, {}, {})
features["eeg-gradient"] = {"value": gradient}
if why:
reasons["anteroposterior_gradient"] = why
return Measured({code: metrics[code] for code in CODES}, features, reasons, found.rejected)
+343
View File
@@ -0,0 +1,343 @@
from dataclasses import dataclass, field
import numpy as np
from models.tea.eeg import signals
from models.tea.eeg.read import Recording
NEIGHBOURS = {
"Fp1": ("Fp2", "F3", "F7"), "Fp2": ("Fp1", "F4", "F8"), "F7": ("Fp1", "F3", "T3"),
"F8": ("Fp2", "F4", "T4"), "F3": ("Fp1", "F7", "Fz", "C3"), "F4": ("Fp2", "F8", "Fz", "C4"),
"Fz": ("F3", "F4", "Cz"), "T3": ("F7", "C3", "T5"), "T4": ("F8", "C4", "T6"),
"C3": ("F3", "T3", "Cz", "P3"), "C4": ("F4", "T4", "Cz", "P4"), "Cz": ("Fz", "C3", "C4", "Pz"),
"T5": ("T3", "P3", "O1"), "T6": ("T4", "P4", "O2"), "P3": ("C3", "T5", "Pz", "O1"),
"P4": ("C4", "T6", "Pz", "O2"), "Pz": ("Cz", "P3", "P4"), "O1": ("T5", "P3", "O2"),
"O2": ("T6", "P4", "O1"),
} # fmt: skip
EAR_NEIGHBOURS = {"A1": ("T3", "T5", "F7"), "A2": ("T4", "T6", "F8")}
MIN_CLEAN_PCT = 60.0
MIN_COVERAGE = 0.90
MAX_BAD_SCALP = 2
MIN_SCALP = 12
MAX_LINE_DB = 45.0
NOT_ANALYZABLE = "not_analyzable"
@dataclass(frozen=True)
class Validation:
valid: bool
level: str
bad: dict[str, list[str]]
clean_pct: float
line_db: float
checks: list[dict] = field(default_factory=list)
reasons: list[str] = field(default_factory=list)
def check(
code,
*,
electrode=None,
value=None,
text=None,
unit=None,
low=None,
high=None,
decisive=False,
abnormal=False,
) -> dict:
return dict(
code=code,
electrode=electrode,
value=value,
text=text,
unit=unit,
low=low,
high=high,
decisive=decisive,
abnormal=abnormal,
)
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, ["invalid-file"])
def _filtered(x, fs, mains_hz, lo, hi):
return signals.bandpass(signals.notch(x, fs, mains_hz), fs, lo, hi)
def _temporal(v: np.ndarray) -> list[tuple[str, str]]:
finite = v[np.isfinite(v)]
if len(finite) < 10 or np.std(finite) < 0.5:
return [("dead-channel", "Canal muerto")]
out = []
if np.mean(np.abs(np.diff(finite)) < 1e-9) > 0.5:
out.append(("frozen", "Señal congelada"))
if np.mean(np.abs(finite) > 0.98 * np.max(np.abs(finite))) > 0.001:
out.append(("saturated", "Señal saturada"))
if np.isinf(v).any():
out.append(("inf-values", "Valores infinitos"))
return out
def _contact(y: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
size = int(10 * fs)
blocks = len(y) // size
low, high = np.full(y.shape[1], np.nan), np.full(y.shape[1], np.nan)
if blocks < 6:
return low, high
sd = np.full((blocks, y.shape[1]), np.nan)
for b in range(blocks):
block = y[b * size : (b + 1) * size]
if np.isfinite(block).all():
sd[b] = block.std(axis=0)
with np.errstate(all="ignore"):
relative = sd / np.maximum(np.nanmedian(sd, axis=1, keepdims=True), 1e-12)
for i in range(y.shape[1]):
v = relative[:, i]
v = v[np.isfinite(v) & (v > 0)]
if len(v) >= 6:
low[i] = np.mean((v < 0.25 * max(float(np.percentile(v, 75)), 1e-12)) & (v < 0.35))
high[i] = np.mean(v > 4.0)
return low, high
def _bridges(y: np.ndarray, names: list[str], scalp: list[int]) -> dict[str, str]:
finite = np.isfinite(y).all(axis=1)
if finite.sum() < 200 or len(scalp) < 2:
return {}
r = np.abs(np.corrcoef(y[finite][:, scalp].T))
index = {names[i]: k for k, i in enumerate(scalp)}
out = {}
for name, k in index.items():
near = [index[n] for n in NEIGHBOURS.get(name, ()) if n in index]
far = [j for j in index.values() if j != k and j not in near]
if not near:
continue
best = max(near, key=lambda j: r[k, j])
if r[k, best] > 0.99 and not (far and max(r[k, j] for j in far) > 0.99):
out[name] = next(n for n, j in index.items() if j == best)
return out
def _ears(y: np.ndarray, fs: float, names: list[str]) -> dict[str, tuple[float, float]]:
out = {}
for ear, around in EAR_NEIGHBOURS.items():
present = [n for n in around if n in names]
if ear not in names or len(present) < 2:
continue
cols = [names.index(ear)] + [names.index(n) for n in present]
rows = np.isfinite(y[:, cols]).all(axis=1)
if rows.sum() < fs * 30:
continue
r = np.abs(np.corrcoef(y[rows][:, cols].T))
between = [r[a, b] for a in range(1, len(cols)) for b in range(a + 1, len(cols))]
out[ear] = (float(np.nanmax(r[0, 1:])), float(np.nanmedian(between)))
return out
def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, str]]]:
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 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)
scalp = [i for i, name in enumerate(names) if kinds[name] == "eeg"]
rms = np.nanstd(y45, axis=0)
median = float(np.nanmedian(rms[scalp])) if scalp else np.nan
ratio = rms / median if np.isfinite(median) and median > 0 else np.full(len(names), np.nan)
low, burst = _contact(y45, fs)
bridges = _bridges(y40, names, scalp)
ears = _ears(y40, fs, names)
missing = 1 - np.isfinite(x).mean(axis=0)
for i, name in enumerate(names):
found, k = reasons[name], kinds[name]
if missing[i] > missing.min() + 0.02:
excess = 100 * (missing[i] - missing.min())
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"Puente con {bridges[name]}"))
if k in ("eeg", "ear") and np.isfinite(ratio[i]) and ratio[i] > 4.0:
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"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"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"Contacto intermitente por ráfagas "
f"({100 * burst[i]:.0f} % de bloques por encima de 4 veces el montaje)",
)
)
if k in ("eog", "ecg"):
v = x[:, i][np.isfinite(x[:, i])]
if np.sqrt(np.mean(v**2)) > 20000:
found.append(
(
"aux-amplitude",
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, start_s=0.0) -> list[tuple[float, float, str]]:
n = int(4 * fs)
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]
emg = {}
if any(whole):
stack = np.stack([s.T for s, ok in zip(segments, whole, strict=True) if ok])
f, power = signals.periodograms(stack, fs)
power = np.moveaxis(power, -1, 0)
high = signals.band_power(f, power, 30.0, 45.0, lines)
low = signals.band_power(f, power, 4.0, 13.0, lines)
ratio = np.median(high / np.maximum(low, 1e-12), axis=1)
emg = dict(zip([a for a, ok in zip(starts, whole, strict=True) if ok], ratio, strict=True))
out = []
for a, s, ok in zip(starts, segments, whole, strict=True):
if not ok:
out.append((a / fs, (a + n) / fs, "gap"))
continue
p2p = float(np.max(s.max(axis=0) - s.min(axis=0)))
variance = float(np.mean(s.var(axis=0)))
common = float(s.mean(axis=1).var() / variance) if variance > 0 else np.nan
muscle = float(emg[a])
suspect = p2p > 800 or (np.isfinite(muscle) and muscle > 0.6) or common > 0.8
out.append((a / fs, (a + n) / fs, "suspect" if suspect else "clean"))
return out
def _triage(rec: Recording, mains_hz: float, bad: dict, clean_pct: float, coverage: float):
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)
rms, flat = {}, {}
for k, i in enumerate(columns):
v = y[:, k][np.isfinite(y[:, k])]
rms[rec.names[i]] = float(np.nanstd(y[:, k])) if len(v) else np.nan
flat[rec.names[i]] = float(np.mean(np.abs(np.diff(v)) < 1e-9)) if len(v) > 1 else 1.0
scalp = rec.of("eeg")
median = float(np.nanmedian([rms[n] for n in scalp])) if scalp else np.nan
triaged = [n for n in scalp if rms[n] > max(5 * median, 300.0) or rms[n] < 0.5 or flat[n] > 0.5]
minutes = rec.duration_s * clean_pct / 100 / 60
base = coverage >= MIN_COVERAGE and len(triaged) <= MAX_BAD_SCALP
if not (base and clean_pct >= 30 and minutes >= 3):
level = NOT_ANALYZABLE
elif not (clean_pct >= 50 and minutes >= 3):
level = "partial"
elif {"A1", "A2"} & {n for n in bad if kinds[n] == "ear"}:
level = "no_ear_reference"
else:
level = "complete"
return level, triaged
def validate(rec: Recording, mains_hz: float) -> Validation:
flagged = bad_channels(rec, mains_hz)
scalp = rec.of("eeg")
usable = [n for n in scalp if n not in flagged]
qc = usable if len(usable) >= 2 else scalp
y = _filtered(rec.x[:, [rec.names.index(n) for n in qc]], rec.fs, mains_hz, 0.5, 45.0)
windows = window_qc(y, rec.fs)
clean_pct = 100.0 * sum(v == "clean" for *_, v in windows) / max(len(windows), 1)
coverage = float(np.isfinite(rec.x).all(axis=1).mean())
columns = [rec.names.index(n) for n in scalp] if scalp else slice(None)
db = signals.line_db(rec.x[:, columns], rec.fs, mains_hz)
line = float(np.nanmedian(db)) if np.isfinite(db).any() else np.nan
level, triaged = _triage(rec, mains_hz, flagged, clean_pct, coverage)
rows = [
check(code, electrode=name, text=reason, abnormal=True)
for name, found in flagged.items()
for code, reason in found
]
rows += [
check(
"clean-windows",
value=clean_pct,
unit="%",
low=MIN_CLEAN_PCT,
abnormal=clean_pct < MIN_CLEAN_PCT,
decisive=True,
),
check(
"internal-coverage",
value=coverage,
unit="fracción",
low=MIN_COVERAGE,
abnormal=coverage < MIN_COVERAGE,
decisive=True,
),
check(
"bad-scalp-triage",
value=float(len(triaged)),
unit="electrodos",
high=float(MAX_BAD_SCALP),
abnormal=len(triaged) > MAX_BAD_SCALP,
decisive=True,
),
check(
"usable-scalp",
value=float(len(usable)),
unit="electrodos",
low=float(MIN_SCALP),
abnormal=len(usable) < MIN_SCALP,
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(
check(
"line-noise", value=line, unit="dB", high=MAX_LINE_DB, abnormal=line > MAX_LINE_DB
)
)
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(not reasons, level, bad, clean_pct, line, rows, reasons)
+217
View File
@@ -0,0 +1,217 @@
import math
from dataclasses import dataclass
import numpy as np
import pandas as pd
from scipy import stats
QUANTILES = {"p5": 0.05, "p25": 0.25, "median": 0.5, "p75": 0.75, "p95": 0.95}
CURVE_AGES = np.exp(np.linspace(np.log(1.0), np.log(216.0), 120))
LOG_WIDTH = 0.2
MIN_EFFECTIVE = 30
COUNT_AGES = (16.0, 37.0)
Z_MAX = 8.0
EXPOSURE = "minutes"
NOT_MEASURES = ("age_months", EXPOSURE, "rhythm_near_sigma")
SCORE_FIELDS = ("z", "outside", "p5", "median", "p95")
@dataclass(frozen=True)
class Scenario:
metric: str
parts: tuple[str, ...]
counts: bool = False
SCENARIOS = {
"eeg-posterior-rhythm": Scenario("posterior_rhythm", ("value",)),
"eeg-spindles": Scenario("spindles", ("value", "zones")),
"eeg-spindle-topography": Scenario("spindles", ("electrodes",)),
"eeg-spikes": Scenario("paroxysmal_spikes", ("value", "electrodes", "zones"), counts=True),
"eeg-gradient": Scenario("anteroposterior_gradient", ("value",)),
}
PREFIX = {"electrodes": "electrode_", "zones": "zone_"}
def _weighted_quantile(x: np.ndarray, w: np.ndarray, q: float) -> float:
order = np.argsort(x)
x, w = x[order], w[order]
return float(np.interp(q, (np.cumsum(w) - 0.5 * w) / w.sum(), x))
def _curve(values: np.ndarray, ages: np.ndarray) -> dict:
ok = np.isfinite(values) & np.isfinite(ages) & (ages > 0)
v, log_age = values[ok], np.log(ages[ok])
curve = {"age_months": [], "n_effective": [], **{q: [] for q in QUANTILES}}
for a in CURVE_AGES:
w = np.exp(-0.5 * ((log_age - np.log(a)) / LOG_WIDTH) ** 2)
n_effective = w.sum() ** 2 / (w**2).sum() if w.sum() > 0 else 0.0
inside = len(log_age) and log_age.min() <= np.log(a) <= log_age.max()
curve["age_months"].append(round(float(a), 3))
curve["n_effective"].append(round(float(n_effective), 1))
for name, q in QUANTILES.items():
enough = n_effective >= MIN_EFFECTIVE and inside
curve[name].append(round(_weighted_quantile(v, w, q), 4) if enough else None)
return {
"kind": "curves",
"log_width": LOG_WIDTH,
"min_effective": MIN_EFFECTIVE,
"curve": curve,
}
def _count_rate(
values: np.ndarray, ages: np.ndarray, exposure: np.ndarray, electrodes: np.ndarray
) -> dict:
n = np.round(values * exposure)
exposure = exposure * electrodes
keep = np.isfinite(n) & np.isfinite(exposure) & (exposure > 0)
keep &= (ages >= COUNT_AGES[0]) & (ages < COUNT_AGES[1])
n, x = n[keep], exposure[keep]
rate = float(n.sum() / x.sum()) if x.sum() > 0 else float("nan")
mu = rate * x
excess = float(((n - mu) ** 2 - n).sum())
k = float((mu**2).sum() / excess) if excess > 0 else None
return {
"kind": "count_rate",
"ages": list(COUNT_AGES),
"rate": rate,
"k": k,
"reference": int(keep.sum()),
"events": int(n.sum()),
}
def train(features: pd.DataFrame, scenario: str) -> dict:
counts = SCENARIOS[scenario].counts
ages = features["age_months"].to_numpy(float)
out = {}
for name in features.columns.drop(list(NOT_MEASURES), errors="ignore"):
if name.startswith(("zone_electrodes_", "awake_")):
continue
values = pd.to_numeric(features[name]).to_numpy(float)
if counts:
column = f"zone_electrodes_{name.removeprefix('zone_')}"
electrodes = (
pd.to_numeric(features[column]).fillna(1).to_numpy(float)
if name.startswith("zone_") and column in features
else np.ones(len(features))
)
out[name] = _count_rate(values, ages, features[EXPOSURE].to_numpy(float), electrodes)
else:
out[name] = _curve(values, ages)
return out
def _unscored(reason: str | None = None) -> dict:
return {**dict.fromkeys(SCORE_FIELDS), "reason": reason}
def _number(v) -> float | None:
return float(v) if v is not None and math.isfinite(v) else None
def centiles(baseline_feature: dict, age_months: float) -> dict:
curve = pd.DataFrame(baseline_feature["curve"]).astype(float).dropna()
names = [name for name in QUANTILES if name in curve or name in ("p5", "median", "p95")]
if curve.empty or not age_months > 0:
return dict.fromkeys(names)
log_ages = np.log(curve["age_months"].to_numpy())
at = float(np.log(np.array([age_months]))[0])
if not log_ages.min() <= at <= log_ages.max():
return dict.fromkeys(names)
return {name: float(np.interp(at, log_ages, curve[name].to_numpy())) for name in names}
def _score_curve(baseline: dict, value: float, age: float) -> dict:
q = centiles(baseline, age)
if q["median"] is None:
return _unscored("age-out-of-range")
side = q["median"] - q["p5"] if value < q["median"] else q["p95"] - q["median"]
z = (value - q["median"]) / (side / 1.645) if side > 0 else None
outside = -1 if value < q["p5"] else 1 if value > q["p95"] else 0
return {
"z": _number(z),
"outside": outside,
"p5": q["p5"],
"median": q["median"],
"p95": q["p95"],
"reason": None,
}
def _score_count(
baseline: dict, value: float, age: float, exposure: float | None, electrodes: float
) -> dict:
rate, k = baseline["rate"], baseline["k"]
lo, hi = baseline["ages"]
if not lo <= age < hi:
return _unscored("age-out-of-range")
if exposure is None or not math.isfinite(rate) or not exposure > 0 or not electrodes > 0:
return _unscored("no-exposure")
n, mu = float(np.round(value * exposure)), rate * exposure * electrodes
law = stats.poisson(mu) if k is None else stats.nbinom(k, k / (k + mu))
tail, at = law.sf(n - 1), law.pmf(n)
z = float(np.clip(stats.norm.ppf(1 - (tail - at / 2)), -Z_MAX, Z_MAX))
p5, median, p95 = (float(law.ppf(p)) / exposure for p in (0.05, 0.5, 0.95))
return {
"z": z,
"outside": 1 if tail < 0.05 else 0,
"p5": p5,
"median": median,
"p95": p95,
"reason": None,
}
def score(
baseline: dict,
value: float | None,
age_months: float | None,
exposure: float | None = None,
electrodes: float | None = None,
) -> dict:
value, age_months = _number(value), _number(age_months)
if value is None:
return _unscored()
if age_months is None:
return _unscored("no-age")
if baseline["kind"] == "count_rate":
electrodes = _number(electrodes)
return _score_count(
baseline,
value,
age_months,
_number(exposure),
electrodes if electrodes is not None else 1.0,
)
return _score_curve(baseline, value, age_months)
def deviations(models: dict[str, dict], analysis) -> dict[str, dict]:
out = {m.code: {} for m in analysis.metrics}
metrics = {m.code: m for m in analysis.metrics}
for name, scenario in SCENARIOS.items():
model, metric = models.get(name), metrics.get(scenario.metric)
if model is None or metric is None:
continue
exposure = analysis.features[name].get(EXPOSURE) if scenario.counts else None
for part in scenario.parts:
if part == "value":
out[metric.code]["value"] = score(
model["value"], metric.value, analysis.age_months, exposure
)
else:
out[metric.code][part] = {
key: score(
model[PREFIX[part] + key],
v,
analysis.age_months,
exposure,
analysis.features[name].get(f"zone_electrodes_{key}")
if scenario.counts and part == "zones"
else None,
)
for key, v in getattr(metric, part).items()
}
return out
+11
View File
@@ -0,0 +1,11 @@
{
"source": "HK1K reference of the sleep-depth index (223 studies, 16-36 months): each window feature standardised by its median and dispersion, the posterior rhythm's median a line on log10 age; signs and weights of the weighted mean; cut-offs wake < -1.2327 <= drowsy < -0.3032 <= sleep",
"features": {
"delta_beta": {"median": 1.6117037688126001, "dispersion": 0.3097998485854789, "sign": 1, "weight": 1.0},
"posterior_rhythm": {"slope": 4.934510806157707, "intercept": 0.999676072265559, "median": 7.765061458878031, "dispersion": 1.021788597296859, "sign": -1, "weight": 1.0},
"sigma": {"median": 0.019957376774209706, "dispersion": 0.012167857665235331, "sign": 1, "weight": 0.7},
"muscle": {"median": 0.0742822337558628, "dispersion": 0.056777351044491706, "sign": -1, "weight": 0.7},
"alpha": {"median": 0.03498707283228359, "dispersion": 0.016352123389996105, "sign": -1, "weight": 0.6}
},
"cuts": [-1.2326590642152986, -0.3031551001049524]
}
+109
View File
@@ -0,0 +1,109 @@
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_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
names: tuple[str, ...]
fs: float
starts: np.ndarray
unclean: tuple[tuple[float, float], ...]
annotations: tuple[tuple[float, float, str], ...]
@property
def duration_s(self) -> float:
return len(self.x) / self.fs
def columns(self, wanted) -> list[str]:
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 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, 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)
referenced = y - np.nanmean(y, axis=1, keepdims=True)
referenced = np.asfortranarray(referenced * 1e-6 * 1e6)
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, 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)
+195
View File
@@ -0,0 +1,195 @@
import io
import re
from dataclasses import dataclass
from datetime import date, datetime
from struct import Struct
import edfio
import mne
import numpy as np
STANDARD = "Fp1 Fp2 F7 F3 Fz F4 F8 T3 C3 Cz C4 T4 T5 P3 Pz P4 T6 O1 O2 A1 A2 T7 T8 P7 P8 Oz Fpz"
CANONICAL = {name.upper(): name for name in STANDARD.split()}
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"}
UNKNOWN_START = date(1985, 1, 1)
class FileNotValid(ValueError):
pass
def normalize(label: str) -> str | None:
text = str(label).strip()
if not text or "ANNOT" in text.upper():
return None
stem = re.sub(r"^\s*(EEG|ECG|EKG|EOG|EMG|POL)\s+", "", text, flags=re.I).split("-")[0]
key = re.sub(r"[^A-Z0-9]", "", stem.strip().upper())
if key in CANONICAL:
name = CANONICAL[key]
return RENAMED.get(name, name)
return next((name for part, name in AUXILIARY if part in text.upper()), None)
def kind(name: str) -> str:
if name in EARS:
return "ear"
if name in EOG:
return "eog"
return "ecg" if name == "EKG" else "eeg"
@dataclass(frozen=True)
class Recording:
x: np.ndarray
fs: float
names: tuple[str, ...]
annotations: tuple[tuple[float, float, str], ...]
start: date | None
birthday: date | None
@property
def duration_s(self) -> float:
return len(self.x) / self.fs
def kinds(self) -> dict[str, str]:
return {name: kind(name) for name in self.names}
def of(self, *kinds: str) -> list[str]:
return [name for name in self.names if kind(name) in kinds]
@dataclass(frozen=True)
class Header:
patient_code: str | None
sex: str | None
birthdate: date | None
start_date: date | None
record_code: str | None
duration_s: float | None
channels: int
_FIXED = Struct("8s80s80s8s8s8s44s8s8s4s")
def _check_length(data: bytes) -> None:
if len(data) < _FIXED.size:
raise FileNotValid("file too short to be an EDF (header < 256 bytes)")
def _fixed_header(data: bytes) -> dict:
_check_length(data)
try:
(
version,
patient,
recording,
startdate,
starttime,
size,
reserved,
records,
duration,
signals,
) = (field.decode("ascii").strip() for field in _FIXED.unpack_from(data))
size, records, duration, signals = int(size), int(records), float(duration), int(signals)
if version != "0" or size != 256 * (1 + signals) or signals < 0:
raise ValueError
except ValueError as exc:
raise FileNotValid(f"not a readable EDF/EDF+ header ({type(exc).__name__})") from None
return dict(
version=version, patient=patient, recording=recording, startdate=startdate,
starttime=starttime, size=size, reserved=reserved, records=records,
duration=duration, signals=signals,
) # fmt: skip
def _date(value: str, fmt: str) -> date | None:
try:
return datetime.strptime(value, fmt).date()
except ValueError:
return None
def header(edf: bytes) -> Header:
fixed = _fixed_header(edf)
patient = fixed["patient"].split(maxsplit=3) + [""] * 3
recording = fixed["recording"].split(maxsplit=3) + [""] * 3
start = _date(recording[1], "%d-%b-%Y") if recording[0] == "Startdate" else None
return Header(
patient_code=None if patient[0] in ("", "X") else patient[0],
sex=patient[1] if patient[1] in ("F", "M") else None,
birthdate=_date(patient[2], "%d-%b-%Y"),
start_date=None if start == UNKNOWN_START else start,
record_code=None if recording[2] in ("", "X") else recording[2],
duration_s=None if fixed["records"] == -1 else fixed["records"] * fixed["duration"],
channels=fixed["signals"],
)
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
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:
raise FileNotValid("the EDF signal data is truncated")
return opened
def _kept(edf: bytes) -> list[tuple[str, str]]:
signals = _open(edf).signals
if not signals:
raise FileNotValid("the EDF declares zero signals")
named = [(s.label, normalize(s.label), float(s.sampling_frequency)) for s in signals]
named = [(label, name, rate) for label, name, rate in named if name is not None]
if not named:
raise FileNotValid("no recognised channel")
rates = [rate for _, _, rate in named]
fs = max(set(rates), key=rates.count)
kept, seen = [], set()
for label, name, rate in named:
if abs(rate - fs) <= 1e-6 and name not in seen:
seen.add(name)
kept.append((label, name))
return kept
def read(edf: bytes) -> Recording:
kept = _kept(edf)
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:
if "latin1" not in str(exc):
raise
raw = mne.io.read_raw_edf(io.BytesIO(edf), encoding="latin1", **options)
raw.rename_channels({lab: name for lab, name in kept if lab in raw.ch_names and lab != name})
names = [name for name in raw.ch_names if name in {n for _, n in kept}]
x = raw.get_data(picks=names, reject_by_annotation="NaN", verbose="error").T * 1e6
start = raw.info.get("meas_date")
born = (raw.info.get("subject_info") or {}).get("birthday")
notes = tuple(
(float(a["onset"]), float(a["duration"]), a["description"]) for a in raw.annotations
)
return Recording(
x=x,
fs=float(raw.info["sfreq"]),
names=tuple(names),
annotations=notes,
start=start.date() if isinstance(start, datetime) else start,
birthday=date(*born) if isinstance(born, tuple) else born,
)
def age_months(start: date | None, birthday: date | None, days_per_month: float) -> float | None:
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)
return months if months <= 216 else None
+45
View File
@@ -0,0 +1,45 @@
from pathlib import Path
import pandas as pd
from models import execution
from models.tea.eeg.analysis import analyze
from models.tea.eeg.curves import SCENARIOS
AGES = (16.0, 36.0)
def listing(folder: Path, ages_table: Path, ages=AGES) -> list[tuple[str, Path, float]]:
table = pd.read_csv(ages_table)
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 = 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, 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, keep_flat=True)
return {
"key": key,
"age_months": age,
"valid": a.valid,
"error": a.error,
"features": a.features,
}
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]:
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])
for name in SCENARIOS
}
+136
View File
@@ -0,0 +1,136 @@
import numpy as np
from scipy import signal
from scipy.ndimage import median_filter
def runs(valid: np.ndarray) -> list[tuple[int, int]]:
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:
x = np.asarray(x, float)
out = np.full_like(x, np.nan)
for a, b in runs(np.isfinite(x).all(axis=1)):
if b - a >= minimum:
out[a:b] = fn(x[a:b])
return out
def bandpass(x: np.ndarray, fs: float, lo: float, hi: float, order: int = 4) -> np.ndarray:
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:
centres = [f0] + [k * f0 for k in range(2, 1000) if k * f0 < fs / 2 * 0.98]
def interpolate(run):
f = np.fft.rfftfreq(len(run), 1 / fs)
spectrum = np.fft.rfft(run, axis=0)
for c in centres:
inside = (f >= c - width) & (f <= c + width)
left = (f >= c - 3 * width) & (f < c - width)
right = (f > c + width) & (f <= c + 3 * width)
if not (inside.any() and left.any() and right.any()):
continue
k = np.linspace(0, 1, int(inside.sum()))[:, None]
target = (
np.abs(spectrum[left]).mean(axis=0)[None, :] * (1 - k)
+ np.abs(spectrum[right]).mean(axis=0)[None, :] * k
)
current = spectrum[inside]
magnitude = np.abs(current)
phase = np.where(magnitude > 0, current / np.maximum(magnitude, 1e-30), 1.0)
spectrum[inside] = target * phase
return np.fft.irfft(spectrum, n=len(run), axis=0)
return by_runs(x, interpolate, max(int(2 * fs), 256))
def line_db(x: np.ndarray, fs: float, f0: float) -> np.ndarray:
finite = np.isfinite(x).all(axis=1)
if not finite.any():
return np.full(x.shape[1], np.nan)
run = x[finite] - x[finite].mean(axis=0)
f = np.fft.rfftfreq(len(run), 1 / fs)
power = np.abs(np.fft.rfft(run * np.hanning(len(run))[:, None], axis=0)) ** 2
peak = power[(f >= f0 - 0.6) & (f <= f0 + 0.6)].mean(axis=0)
around = ((f >= f0 - 6) & (f <= f0 - 2)) | ((f >= f0 + 2) & (f <= f0 + 6))
near = power[around].mean(axis=0)
with np.errstate(divide="ignore", invalid="ignore"):
return 10 * np.log10(np.where(near > 0, peak / near, np.nan))
def periodograms(segments: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
n = segments.shape[-1]
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]:
n = int(round(8 * fs))
f = np.fft.rfftfreq(n, 1 / fs)
taper = np.hanning(n)[:, None]
total, count = None, 0
for a in range(0, len(x) - n + 1, n):
segment = x[a : a + n]
if np.isfinite(segment).all():
power = np.abs(np.fft.rfft((segment - segment.mean(axis=0)) * taper, axis=0)) ** 2
total = power if total is None else total + power
count += 1
if not count:
return []
db = 10 * np.log10(np.maximum(np.median(total / count, axis=1), 1e-30))
df = float(f[1] - f[0])
half = max(1, int(round(2 / df)))
prominence = db - median_filter(db, size=2 * half + 1, mode="nearest")
f_max = min(f_max, fs / 2 - 2)
found = []
for i in range(1, len(f) - 1):
p = prominence[i]
if not 1 <= f[i] <= f_max or p < 6 or p < prominence[i - 1] or p < prominence[i + 1]:
continue
a = b = i
while a > 0 and prominence[a - 1] >= p - 3:
a -= 1
while b < len(f) - 1 and prominence[b + 1] >= p - 3:
b += 1
if (b - a + 1) * df <= 0.5:
found.append((round(float(f[i]), 3), round(float(p), 1)))
kept = []
for hz, db_up in sorted(found, key=lambda line: -line[1]):
if all(abs(hz - other) > 0.5 for other, _ in kept):
kept.append((hz, db_up))
return [hz for hz, _ in kept]
def band_power(f, power, lo, hi, lines=(), include_hi=False):
band = (f >= lo) & ((f <= hi) if include_hi else (f < hi))
clean = band.copy()
for line in lines:
clean &= np.abs(f - line) > 1.0
if not clean.any():
return np.full(power.shape[1:], np.nan) if power.ndim > 1 else np.nan
return power[clean].sum(axis=0) * (band.sum() / clean.sum())
def dominant_peak(f: np.ndarray, power: np.ndarray) -> tuple[float, float, bool]:
usable = (f >= 1.5) & (f <= 45) & (power > 0)
background = usable & ~((f >= 4) & (f <= 16))
if background.sum() < 5:
return np.nan, np.nan, False
line = np.polyfit(np.log10(f[background]), np.log10(power[background]), 1)
residual = 10 * (np.log10(power[usable]) - np.polyval(line, np.log10(f[usable])))
fu = f[usable]
band = (fu >= 3) & (fu <= 14)
if not band.any():
return np.nan, np.nan, False
i = int(np.argmax(residual[band]))
prominence = float(residual[band][i])
found = prominence >= 1.5 and 0 < i < int(band.sum()) - 1
return (float(fu[band][i]) if found else np.nan), prominence, bool(found)
+191
View File
@@ -0,0 +1,191 @@
import json
import re
import unicodedata
from pathlib import Path
import numpy as np
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", ("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)
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")
def note_state(text: str) -> str | None:
kept = str(text or "").replace("ñ", "\0").replace("Ñ", "\1")
plain = "".join(
c for c in unicodedata.normalize("NFD", kept) if unicodedata.category(c) != "Mn"
)
plain = plain.replace("\0", "ñ").replace("\1", "Ñ").lower().strip()
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]]:
notes = sorted(annotations, key=lambda note: note[0])
found = []
for i, (t0, length, text) in enumerate(notes):
state = note_state(text)
if state is None:
continue
if length > 0:
t1 = t0 + length
else:
following = next((n[0] for n in notes[i + 1 :] if note_state(n[2])), None)
t1 = min(t0 + 60.0, following if following else t0 + 60.0)
if t1 - t0 >= 1:
found.append((t0, t1, state))
found.sort(key=lambda piece: piece[0])
full, cursor = [], 0.0
for t0, t1, state in found:
if t0 - cursor >= 1:
full.append((cursor, t0, "unmarked"))
full.append((t0, t1, state))
cursor = max(cursor, t1)
if duration_s - cursor >= 1:
full.append((cursor, duration_s, "unmarked"))
pieces = [(round(t0, 2), round(t1, 2), state) for t0, t1, state in full]
return [(t0, t1 - t0, state) for t0, t1, state in pieces]
def window_note(t0: float, t1: float, intervals) -> tuple[str, bool]:
overlap = {}
for onset, length, state in intervals:
lo, hi = max(t0, onset), min(t1, onset + length)
if hi > lo:
overlap[state] = overlap.get(state, 0) + (hi - lo)
if not overlap:
return "unlabelled", False
dominant = max(overlap, key=overlap.get)
return dominant, overlap[dominant] < 0.8 * (t1 - t0)
def mask(prep: Prepared, intervals) -> np.ndarray:
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:
out[int(onset * prep.fs) : int((onset + length) * prep.fs)] = True
return out
def _features(prep: Prepared, masked: np.ndarray) -> tuple[list[int], dict[str, np.ndarray]]:
fs, x, names = prep.fs, prep.x, list(prep.names)
n, step = int(WINDOW_S * fs), int(2 * fs)
starts = [
a
for a in range(0, len(x) - n + 1, step)
if np.isfinite(x[a : a + n]).all() and not masked[a : a + n].any()
]
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))))
posterior = [names.index(c) for c in POSTERIOR if c in names]
delta_beta = np.median(band["delta"] / np.maximum(band["beta"], 1e-12), axis=1)
features = {
"delta_beta": np.log10(np.clip(delta_beta, 1e-6, None)),
"sigma": np.median((band["sigma"] / total)[:, central], axis=1),
"muscle": np.median(
band["high"] / np.maximum(band["theta"] + band["alpha"], 1e-12), axis=1
),
"alpha": np.median(band["alpha"] / total, axis=1),
}
if posterior:
peaks = [
signals.dominant_peak(f, power[w, posterior].mean(axis=0)) for w in range(len(starts))
]
features["posterior_rhythm"] = np.array([db if found else 0.0 for _, db, found in peaks])
return starts, features
def depth(features: dict[str, np.ndarray], age_months: float | None) -> np.ndarray:
z, weights = [], []
for name, ref in REFERENCE["features"].items():
if name not in features:
continue
if "slope" in ref and age_months and age_months > 0:
median = ref["slope"] * np.log10(float(age_months)) + ref["intercept"]
else:
median = ref["median"]
z.append(ref["sign"] * (features[name] - median) / max(ref["dispersion"], 1e-9))
weights.append(ref["weight"])
w = np.array(weights, float)
return np.clip((np.column_stack(z) * w).sum(axis=1) / w.sum(), -6, 6)
def states(prep: Prepared, intervals, age_months: float | None) -> np.ndarray:
starts, features = _features(prep, mask(prep, intervals))
out = np.full(len(prep.starts), "", dtype=object)
if not starts:
return out
labels = STATES[np.digitize(depth(features, age_months), REFERENCE["cuts"])]
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
+262
View File
@@ -0,0 +1,262 @@
from dataclasses import dataclass
import numpy as np
import pandas as pd
from models.tea.eeg import signals
from models.tea.eeg.checks import NEIGHBOURS
from models.tea.eeg.preprocess import WINDOW_S, Prepared
from models.tea.eeg.sleep import EXCLUDED, window_note
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 = ("sleep",)
@dataclass(frozen=True)
class Spikes:
rate: float
electrodes: dict[str, float]
zones: dict[str, float]
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:
v = v[np.isfinite(v)]
if not len(v):
return np.nan
return float(np.median(np.abs(v - np.median(v))) * 1.4826) or np.nan
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, 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]
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)))
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]:
n = len(y)
if i <= 0 or i >= n - 1:
return np.nan, np.nan
w = int(500 * fs / 1000)
base = float(np.median(y[max(0, i - w) : min(n, i + w)]))
peak = float(y[i]) - base
if peak == 0.0:
return np.nan, np.nan
sign, half, reach = np.sign(peak), 0.5 * abs(peak), int(150 * fs / 1000)
a, low = i, max(0, i - reach)
while a > low and sign * (y[a] - base) >= half:
a -= 1
b, high = i, min(n - 1, i + reach)
while b < high and sign * (y[b] - base) >= half:
b += 1
if b <= a:
return np.nan, np.nan
rise, fall = half / (max(i - a, 1) / fs), half / (max(b - i, 1) / fs)
return float(min(rise, fall)), float((b - a) / fs * 1000.0)
def _candidates(x: np.ndarray, fs: float, channel: str) -> list[dict]:
y = signals.bandpass(x.reshape(-1, 1), fs, 1.0, min(70.0, fs / 2 * 0.9)).ravel()
if np.isfinite(y).sum() < fs * 2:
return []
slope_mad, amplitude_mad = _mad(np.diff(y) * fs), _mad(y)
if not np.isfinite(slope_mad) or not np.isfinite(amplitude_mad):
return []
v = np.abs(y)
peaks = np.flatnonzero((v[1:-1] > v[:-2]) & (v[1:-1] >= v[2:])) + 1 if len(v) >= 3 else []
after = int(100 * fs / 1000), int(500 * fs / 1000)
out = []
for i in (i for i in peaks if v[i] > 3.0 * amplitude_mad):
slope, width = _flanks(y, int(i), fs)
if not (np.isfinite(slope) and np.isfinite(width) and 20.0 <= width <= 200.0):
continue
if slope < 6.0 * slope_mad:
continue
a, b = int(i) + after[0], min(int(i) + after[1], len(y))
post = float(-np.sign(y[i]) * np.mean(y[a:b]) / amplitude_mad) if b > a else 0.0
out.append(
dict(
channel=channel,
t=float(i) / fs,
sign=int(np.sign(y[i])),
width=width,
size=float(abs(y[i]) / amplitude_mad),
post=post,
)
)
return out
def _field(c: pd.DataFrame) -> np.ndarray:
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)):
for other in NEIGHBOURS.get(ch, ()):
near = times.get((other, s))
if near is None:
continue
j = np.searchsorted(near, t)
close = near[max(j - 1, 0) : j + 1]
out[k] += bool(np.any(np.abs(close - t) <= 0.025))
return out
def _merge(c: pd.DataFrame) -> pd.DataFrame:
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 = []
for g in groups:
part = c.iloc[g]
top = c.loc[part["size"].idxmax()]
asleep = top.state in ASLEEP
signs = dict(zip(part.channel, part.sign, strict=True))
frontal_only = top.channel in OCULAR and not (set(part.channel) & POSTERIOR)
opposite = any(a in signs and b in signs and signs[a] * signs[b] < 0 for a, b in LEFT_RIGHT)
vertex = asleep and top.channel in VERTEX and float(part.post.max()) > 3.0
posts = asleep and top.channel in POSTS and top.sign > 0 and top.width > 80.0
rows.append(
dict(
channel=top.channel,
state=top.state,
field=int(part.field.max()),
useful=not (vertex or posts or frontal_only or opposite),
)
)
return pd.DataFrame(rows, columns=["channel", "state", "field", "useful"])
def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None:
channels = [c for c in prep.names if c in ELECTRODES]
if len(channels) < 4:
return None
fs = prep.fs
x = np.array(prep.data(channels), dtype=np.float64)
labelled = [
(s, s + WINDOW_S, label)
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:
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, 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:
c = pd.DataFrame(candidates)
t = c.t.to_numpy(float)
inside = np.zeros(len(t), bool)
for t0, t1 in gate:
inside |= (t >= t0) & (t < t1)
c = c[inside]
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)]
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)
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, 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),
rejected,
awake_rate,
round(awake_minutes, 4),
zone_electrodes,
)
+166
View File
@@ -0,0 +1,166 @@
from dataclasses import dataclass
import numpy as np
from scipy.signal import hilbert, welch
from models.tea.eeg import signals
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"),
"frontal_midline": ("Fz",),
"central": ("C3", "Cz", "C4"),
"parietal": ("P3", "Pz", "P4"),
"temporal_left": ("T3", "T5"),
"temporal_right": ("T4", "T6"),
"occipital": ("O1", "O2"),
}
@dataclass(frozen=True)
class Spindles:
events: list[tuple[float, float, str]]
minutes: float
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]:
y = signals.bandpass(x, fs, *SIGMA)
envelope = np.abs(hilbert(np.nan_to_num(y), axis=0))
k = max(1, int(0.2 * fs))
envelope = np.apply_along_axis(
lambda v: np.convolve(v, np.ones(k) / k, mode="same"), 0, envelope
)
envelope[~np.isfinite(y)] = np.nan
return y, envelope
def _segments(core: np.ndarray, extent: np.ndarray, fs: float) -> list[tuple[int, int]]:
edges = np.diff(extent.astype(np.int8), prepend=0, append=0)
out = []
for a, b in zip(np.flatnonzero(edges == 1), np.flatnonzero(edges == -1), strict=True):
if not core[a:b].any():
continue
if 0.5 <= (b - a) / fs <= 3.0:
out.append((int(a), int(b)))
elif (b - a) / fs > 3.0:
step = int(3.0 * fs)
for c in range(a, b, step):
e = min(c + step, b)
if 0.5 <= (e - c) / fs <= 3.0 and core[c:e].any():
out.append((int(c), int(e)))
return out
def _is_spindle(x: np.ndarray, y: np.ndarray, fs: float) -> bool:
if not np.isfinite(x).all():
return False
nperseg = min(len(x), int(fs))
f, power = welch(x - x.mean(), fs=fs, nperseg=nperseg, nfft=max(1024, nperseg * 4))
inside = (f >= SIGMA[0]) & (f <= SIGMA[1])
flanks = ((f >= 5) & (f < SIGMA[0])) | ((f > SIGMA[1]) & (f <= 30))
if not inside.any() or not flanks.any():
return False
if power[inside].mean() / max(power[flanks].mean(), 1e-30) < 1.5:
return False
frequency = np.diff(np.unwrap(np.angle(hilbert(y)))) * fs / (2 * np.pi)
frequency = frequency[np.isfinite(frequency)]
in_band = frequency[(frequency >= SIGMA[0] - 1) & (frequency <= SIGMA[1] + 1)]
if len(in_band) < 0.5 * max(len(frequency), 1):
return False
return SIGMA[0] <= float(np.median(in_band)) <= SIGMA[1]
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, 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 < 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_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_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]]:
zones = dict.fromkeys(ZONES, np.nan)
if not found.events or found.minutes <= 0:
return np.nan, zones
counts = {}
for _, _, channel in found.events:
counts[channel] = counts.get(channel, 0) + 1
for zone, electrodes in ZONES.items():
searched = [e for e in electrodes if e in found.channels]
if searched:
total = sum(counts.get(e, 0) for e in searched)
zones[zone] = total / (found.minutes * len(searched))
per_channel = len(found.events) / found.minutes / max(len(found.channels), 1)
return round(per_channel, 3), zones
def _episodes(events) -> list[list[float]]:
if not events:
return []
a = np.array([onset for onset, _, _ in events], float)
b = a + np.array([length for _, length, _ in events], float)
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 out
def enhancement(prep: Prepared, found: Spindles, states: np.ndarray) -> dict[str, float]:
out = dict.fromkeys(CHANNELS, np.nan)
use = prep.columns(CHANNELS)
episodes = _episodes(found.events)
if not use or not episodes:
return out
fs = prep.fs
y = signals.bandpass(prep.data(use), fs, *SIGMA)
envelope = signals.by_runs(y, lambda run: np.abs(hilbert(run, axis=0)), int(fs))
asleep = np.zeros(len(envelope), bool)
for start, label in zip(prep.starts, states, strict=True):
if label == "sleep":
asleep[int(start * fs) : int((start + WINDOW_S) * fs)] = True
median = np.nanmedian(envelope[asleep] if asleep.sum() > fs * 30 else envelope, axis=0)
peaks = np.full((len(episodes), len(use)), np.nan)
for k, (t0, t1) in enumerate(episodes):
a, b = max(0, int((t0 - 0.25) * fs)), min(len(envelope), int((t1 + 0.25) * fs))
if b - a >= 3:
peaks[k] = np.nanmax(envelope[a:b], axis=0)
for j, name in enumerate(use):
if np.isfinite(median[j]) and median[j] > 0:
out[name] = float(np.nanmedian(peaks[:, j]) / median[j])
return out
+311
View File
@@ -0,0 +1,311 @@
import hashlib
import json
import os
from dataclasses import dataclass
from datetime import date
from pathlib import Path
import mlflow.pyfunc
import pandas as pd
from core.measures import as_day
from core.tea import ADOS2_ITEMS, ASSOCIATION_BIOMARKERS, ados2
from core.tea.fhir import eeg_study_id
from models import execution
from models.jobs import EmptyCohort
from models.tea import association
from models.tea.eeg import analysis, curves
from models.tea.eeg import reference as cohort_reference
from persistance import cluster, eeg, registry, silver
ASSOCIATION = "ados2_association"
MODELS = curves.SCENARIOS
GOLD_SELECT = [
"tea_eeg_analyses+",
"tea_eeg_metrics+",
"tea_associations",
"tea_association_scores",
]
class Baseline(mlflow.pyfunc.PythonModel):
def __init__(self, scenario: str, baseline: dict):
self.scenario, self.baseline = scenario, baseline
def curve(self, feature: str, ages) -> list[dict]:
baseline = self.baseline[feature]
if baseline["kind"] == "count_rate":
raise LookupError("no centiles by age for a count-rate feature")
return [{"age_months": age, **curves.centiles(baseline, age)} for age in ages]
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
feature = (params or {}).get("feature", "value")
rows = model_input.to_dict("records")
return pd.DataFrame([curves.score(self.baseline[feature], r.get("value"),
r.get("age_months"), r.get("exposure"),
r.get("electrodes"))
for r in rows]) # fmt: skip
def _analyze(item: tuple[str, date | None, bytes]) -> tuple[str, analysis.Analysis]:
edf, birth, signal = item
return edf, analysis.analyze(signal, birth)
def analyze(scope: eeg.Scope | None = None, *, rebuild_gold: bool = True) -> int:
rows = eeg.select(scope or eeg.Scope())
items = ((r["edf"], r["birth_date"], eeg.signal(r["edf"])) for r in rows)
found = dict(execution.map(_analyze, items, phase="analyzing", total=len(rows)))
eeg.save_analyses(found)
if rebuild_gold:
silver.build(GOLD_SELECT)
return len(found)
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 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"{source.folder}-{digest[:16]}.json" if cache else None
if path and path.exists():
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, source.folder, source.line_hz
@dataclass(frozen=True)
class Jobs:
def routine(self) -> list[str]:
return [*MODELS, ASSOCIATION]
JOBS = Jobs()
def registered(name: str) -> str:
return f"tea.{name}"
def train(
name: str, as_of: date | None = None, source: cluster.TrainingSource | None = None
) -> int | None:
if name == ASSOCIATION:
return train_association(as_of)
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)", **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 = {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)
def score_curves() -> dict[str, int | None]:
return {name: score(name) for name in MODELS}
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()
records = []
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": scored.css if scored else None,
}
)
values = {}
edfs = {row["edf"] for row in records}
for row in scores:
if row["edf"] not in edfs:
continue
name = biomarker[row["metric"]]
if name == "spikes":
continue
if name == "spindles":
if row["part"] != "zones":
continue
predictor = f"z_{name}_{row['site']}"
else:
if row["part"] != "value":
continue
predictor = f"z_{name}"
values.setdefault(row["edf"], {})[predictor] = row["z"]
scored = pd.DataFrame(records, columns=columns)
if values:
scored = scored.join(pd.DataFrame.from_dict(values, orient="index"), on="edf")
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_", "spikes_any_"))]
fit = (
scored[scored[predictors].notna().any(axis=1)]
.drop_duplicates("person_id")
.reset_index(drop=True)
)
drop = ["person_id", "study_date", "edf"]
return fit.drop(columns=drop), scored.drop(columns=drop)
def fingerprint(fit: pd.DataFrame, scored: pd.DataFrame, module: str) -> str:
t = scored.assign(_fit=scored["key"].isin(fit["key"]))
t = t.reindex(sorted(t.columns), axis=1).sort_values("key").reset_index(drop=True)
text = module + "\n" + t.to_csv(index=False, float_format="%.6g")
return hashlib.sha256(text.encode()).hexdigest()[:8]
def _records(frame: pd.DataFrame) -> list[dict]:
clean = frame.replace([float("inf"), -float("inf")], None).astype(object)
return clean.where(clean.notna(), None).to_dict("records")
def train_association(as_of: date | None = None) -> int | None:
fit, scored = cohort()
if fit.empty:
raise EmptyCohort(ASSOCIATION)
estimator = association.Ados2Association(level="auto")
mark = fingerprint(
fit, scored, f"{estimator.name}/{estimator.version}/{estimator.impl}/{estimator.level}"
)
name = registered(ASSOCIATION)
versions = registry.versions(name)
if versions and versions[-1]["params"].get("fingerprint") == mark:
return versions[-1]["version"]
estimator.fit(fit)
pairs = estimator.associations()
level = estimator.fitted["level"]
forest = ["biomarker", "zone", "kind", "outcome_code", "event", "n"]
forest += ["odds_ratio", "ci_low", "ci_high", "q", "reason"]
reports = {
"technical_validation": {
"model": ASSOCIATION,
"method": "Firth / ordinal logistic, profile CI, BH within biomarker",
"level": level,
"cohort": len(fit),
"scored": len(scored),
"fingerprint": mark,
"pairs": _records(pairs),
},
"interpretability": {"kind": "forest", "rows": _records(pairs[forest])},
}
params = {"fingerprint": mark, "level": level}
metrics = {"n_reference": len(fit), "pairs": int(pairs["odds_ratio"].notna().sum())}
return registry.register(name, association.Model(estimator.fitted), params, metrics, reports)
def relate() -> int | None:
found = registry.champion(registered(ASSOCIATION))
if found is None:
return None
version, model = found
estimator = association.Ados2Association(fitted=model.unwrap_python_model().fitted)
_, scored = cohort()
rows = []
for row in _records(estimator.associations()):
if row["odds_ratio"] is None or row["odds_ratio"] <= 0:
continue
row["key"] = f"{row['biomarker']}|{row['zone']}|{row['outcome_code']}"
row["method"] = row.pop("model")
row.pop("outcome")
row["level"] = estimator.fitted["level"]
row["n_cohort"] = estimator.fitted["n"]
row["reason"] = row["reason"] or None
rows.append(row)
keys = {row["key"] for row in rows}
scores = []
for row in model.predict(scored).to_dict("records"):
pair = "|".join(row.pop(field) for field in ("biomarker", "zone", "outcome_code"))
if pair in keys:
eeg_id = row["key"]
scores.append({**row, "eeg_id": eeg_id, "pair": pair, "key": f"{eeg_id}|{pair}"})
eeg.save_associations(version, rows)
eeg.save_association_scores(version, scores)
return version
def score(name: str) -> int | None:
if name == ASSOCIATION:
return relate()
found = registry.champion(registered(name))
if found is None:
return None
version, model = found
baseline = model.unwrap_python_model().baseline
scenario, label = MODELS[name], f"{registered(name)}/{version}"
rows = []
for one in eeg.analysed():
metric = next((m for m in one["metrics"] if m["code"] == scenario.metric), None)
if metric is None:
continue
exposure = (
(one["features"].get(name) or {}).get(curves.EXPOSURE) if scenario.counts else None
)
for part in scenario.parts:
sites = {"": metric["value"]} if part == "value" else metric[part]
prefix = "" if part == "value" else curves.PREFIX[part]
for site, value in sites.items():
feature = "value" if part == "value" else prefix + site
if feature not in baseline:
continue
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
eeg.save_scores(name, rows)
return version
+224
View File
@@ -0,0 +1,224 @@
import math
from dataclasses import replace
from datetime import date
from sqlalchemy.exc import SQLAlchemyError
from core import concept_map, tea
from core.pipeline import apply_patterns
from core.tea import ados2 as scoring
from core.tea import ados2_items
from models import graph
from models.tea.eeg import analysis, curves, read
from models.tea.jobs import MODELS
from persistance import config_log, registry
from persistance.previews import PreviewAdos2, PreviewEeg, PreviewMetric, PreviewResult, Site
def _deviations(models: dict, study: analysis.Analysis) -> dict:
metrics = {metric.code: metric for metric in study.metrics}
missing_values = set()
for name, baseline in models.items():
scenario = curves.SCENARIOS[name]
if scenario.metric not in metrics:
continue
metric = metrics[scenario.metric]
changes = {
part: {
site: value
for site, value in getattr(metric, part).items()
if curves.PREFIX[part] + site in baseline
}
for part in scenario.parts
if part != "value"
}
if "value" in scenario.parts and "value" not in baseline:
models[name] = baseline | {"value": {}}
changes["value"] = None
missing_values.add(metric.code)
metrics[metric.code] = replace(metric, **changes)
features = {name: study.features.get(name, {}) for name in models}
found = curves.deviations(
models, replace(study, metrics=list(metrics.values()), features=features)
)
for code in missing_values:
found.get(code, {}).pop("value", None)
return found
def _sites(values: dict, scores: dict) -> dict[str, Site]:
return {key: Site(value=value, score=scores.get(key)) for key, value in values.items()}
def _metrics(study: analysis.Analysis, warnings: list[str]) -> list[PreviewMetric]:
models, versions = {}, {}
found = {}
if study.valid:
for name in curves.SCENARIOS:
champion = registry.champion(f"tea.{name}")
if champion is not None:
versions[name], model = champion
models[name] = model.unwrap_python_model().baseline
if not models:
warnings.append("there are no champion age curves: no z is shown")
else:
codes = {metric.code for metric in study.metrics}
warnings.extend(
f"no champion for {name}: its z is not shown"
for name, scenario in curves.SCENARIOS.items()
if name not in models and scenario.metric in codes
)
found = _deviations(models, study)
labels = {
MODELS[name].metric: f"tea.{name}/{version}"
for name, version in versions.items()
if "value" in MODELS[name].parts
}
metrics = []
for metric in study.metrics:
parts = found.get(metric.code, {})
metrics.append(
PreviewMetric(
code=metric.code,
value=metric.value,
score=parts.get("value"),
model=labels.get(metric.code) if "value" in parts else None,
electrodes=_sites(metric.electrodes, parts.get("electrodes", {})),
zones=_sites(metric.zones, parts.get("zones", {})),
)
)
return metrics
def _parse(field, value, kind, warnings):
if value is None:
return None
try:
if kind == "date":
return value if isinstance(value, date) else date.fromisoformat(value)
number = float(value)
if math.isfinite(number):
return number
except (TypeError, ValueError):
pass
warnings.append(f"{field}: could not read {value!r} as a {kind}")
return None
def _report(
content: bytes,
pipeline: str,
recorded_on: date | None,
birth: date | None,
warnings: list[str],
) -> PreviewAdos2 | None:
if not content.startswith(b"%PDF"):
warnings.append("the ADOS-2 file is not a PDF")
return None
text = graph.read_file(content)
if error := text["error"]:
warnings.append(f"the ADOS-2 report could not be read: {error}")
return None
try:
saved = config_log.get(pipeline)
except (LookupError, SQLAlchemyError, ValueError):
saved = None
if saved is None:
warnings.append(f"no saved pipeline {pipeline}: the ADOS-2 report is not read")
return None
_, definition = saved
node = next((n for n in definition.nodes if n.kind == "extract" and n.entity == "ados2"), None)
if node is None:
warnings.append(f"pipeline {pipeline} has no ados2 extract node")
return None
codes = {}
if node.concept_map:
mapping = config_log.concept_map(node.concept_map)
codes = {field: concept_map.table([mapping], field) for field in node.patterns}
found = apply_patterns(node, text["text"], codes)
if not found:
warnings.append("no ADOS-2 field was found in the report")
return None
row = dict(found[0][0])
fields = sorted(row)
evaluation_date = _parse("evaluation_date", row.get("evaluation_date"), "date", warnings)
if "evaluation_date" not in row:
evaluation_date = recorded_on
module = row.get("module")
titles = {i.field: f"{i.code} {i.title}" for i in ados2_items.ITEMS.get(module, ())}
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
errors = scoring.errors(row | items | {"evaluation_date": evaluation_date}, birth)
warnings.extend(errors)
if evaluation_date is None:
warnings.append("ADOS-2 not scored: no evaluation date")
else:
try:
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 scored:
css, classification = scored.css, scored.classification
elif not errors:
warnings.append(
"the ADOS-2 score could not be calculated: "
"the report lacks the module or the item scores"
)
return PreviewAdos2(
module=module,
evaluation_date=evaluation_date,
items=items,
titles=titles,
css=css,
classification=classification,
read=fields,
)
def preview(
edf: bytes,
ados2: bytes | None = None,
birth_date: date | None = None,
pipeline: str = "tea",
) -> PreviewResult:
study = analysis.analyze(edf, birth_date)
try:
header = read.header(edf)
except read.FileNotValid:
header = None
recorded_on = header.start_date if header else None
warnings = []
if study.error:
warnings.append(f"the EEG analysis ended with an error: {study.error}")
eeg = PreviewEeg(
valid=study.valid,
level=study.level,
recorded_on=recorded_on,
age_months=study.age_months,
clean_fraction=study.clean_fraction,
bad_channels=study.bad_channels,
channels=study.channels,
duration_min=study.duration_min,
line_noise_db=study.line_noise_db,
sleep=study.sleep,
checks=study.checks,
metrics=_metrics(study, warnings),
error=study.error,
)
report = None
if ados2 is not None:
birth = birth_date or (header.birthdate if header else None)
report = _report(ados2, pipeline, recorded_on, birth, warnings)
return PreviewResult(eeg=eeg, ados2=report, warnings=warnings)
+30 -15
View File
@@ -1,23 +1,38 @@
[project]
name = "models"
version = "0.1.0"
description = "train()/predict() interfaces for the CaCu, CaMa and TEA screening models."
requires-python = ">=3.11"
version = "0.0.0"
description = "Dagster assets and jobs; one module per model."
requires-python = ">=3.12"
dependencies = [
"core",
"persistance",
"dagster",
"dagster-webserver",
"mlflow-skinny",
"openai>=3.59.0",
"splink>=5.0.0",
"duckdb>=2.0.1",
"markitdown[docx,xlsx]>=0.1.9",
"ocrmypdf>=17.14.2",
"pikepdf>=10.0",
"pdfplumber>=0.11.11",
"scikit-learn>=1.9.1",
"scipy>=1.18.1",
"joblib>=1.6.0",
"lifelines>=0.30.0",
"mne>=1.13.2",
"edfio>=0.4.18",
"statsmodels>=0.15.0",
"pgmpy>=1.1.2",
]
[tool.uv.sources]
persistance = { path = "../Persistance", editable = true }
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
requires = ["uv_build>=0.12,<0.13"]
build-backend = "uv_build"
[tool.hatch.build.targets.wheel]
packages = ["models"]
[dependency-groups]
dev = [
"pytest>=8.0.0",
]
[tool.uv.build-backend]
module-name = "models"
module-root = ""
[tool.uv.sources]
core = { workspace = true }
persistance = { workspace = true }
+32
View File
@@ -0,0 +1,32 @@
from datetime import date
from pathlib import Path
import edfio
import numpy as np
def small_edf(
path: Path,
*,
patient_code="N1001",
sex="F",
birthdate=date(2025, 1, 5),
startdate=date(2026, 3, 2),
record_code="LAB-1",
seconds=20,
channels=("Fp1", "Fp2", "Cz"),
) -> bytes:
edf = edfio.Edf(
[
edfio.EdfSignal(
np.random.default_rng(1).normal(0, 20, 100 * seconds),
sampling_frequency=100,
label=name,
)
for name in channels
],
patient=edfio.Patient(code=patient_code, sex=sex, birthdate=birthdate),
recording=edfio.Recording(startdate=startdate, hospital_administration_code=record_code),
)
edf.write(path)
return path.read_bytes()
+220
View File
@@ -0,0 +1,220 @@
import hashlib
import io
import json
import zipfile
import mlflow
import pandas as pd
import pytest
from core.domains import Domain
from persistance import bundle, config, registry
DOMAIN = Domain.TEA
NAME = "tea.curve_x"
class Model(mlflow.pyfunc.PythonModel):
def __init__(self, value):
self.value = value
def predict(self, context, model_input: pd.DataFrame, params=None):
return model_input.assign(score=self.value)
@pytest.fixture
def stores(tmp_path, monkeypatch):
monkeypatch.setattr(config, "DATA_DIR", tmp_path)
def use(name):
path = tmp_path / name
path.mkdir(exist_ok=True)
monkeypatch.setenv("MLFLOW_TRACKING_URI", f"sqlite:///{path}/a.db")
monkeypatch.chdir(path)
use("a")
return use
def _register(value=1, clinical=True):
version = registry.register(
NAME,
Model(value),
{"scenario": "curve"},
{"n_reference": 10},
{"technical_validation": {"a": 1}, "interpretability": {"b": 2}},
tags={"source": "test", "bundle.source_version": "stale"},
)
if clinical:
registry.add_report(NAME, version, "clinical_validation", "review.txt", b"approved")
return version
def _trust(data):
sha = hashlib.sha256(data).hexdigest()
with bundle.trusted_file().open("a") as file:
file.write(f"\n {sha.upper()} \n")
return sha
def _entries(data):
with zipfile.ZipFile(io.BytesIO(data)) as archive:
return {name: archive.read(name) for name in archive.namelist()}
def _zip(entries):
stream = io.BytesIO()
with zipfile.ZipFile(stream, "w") as archive:
for name, data in entries.items():
archive.writestr(name, data)
return stream.getvalue()
def test_export_is_deterministic(stores):
registry.promote(NAME, _register())
first, second = bundle.export(DOMAIN), bundle.export(DOMAIN)
assert first.data == second.data
assert first.sha256 == second.sha256 == hashlib.sha256(first.data).hexdigest()
with zipfile.ZipFile(io.BytesIO(first.data)) as archive:
assert archive.namelist() == sorted(archive.namelist())
for info in archive.infolist():
assert info.date_time == bundle.EPOCH
assert info.compress_type == zipfile.ZIP_DEFLATED
assert info.external_attr == 0o644 << 16
assert info.create_system == 3
def test_layout_and_manifest_hold_every_file_hash(stores):
_register()
entries = _entries(bundle.export(DOMAIN, versions="latest").data)
manifest = json.loads(entries.pop("manifest.json"))
assert (manifest["format"], manifest["domain"]) == (1, "tea")
(item,) = manifest["versions"]
assert (item["name"], item["version"]) == (NAME, 1)
prefix = "models/tea.curve_x/v1/"
assert prefix + "meta.json" in entries
assert prefix + "model/MLmodel" in entries
assert prefix + "reports/clinical_validation.txt" in entries
assert item["files"] == {key: hashlib.sha256(data).hexdigest() for key, data in entries.items()}
meta = json.loads(entries.pop(prefix + "meta.json"))
content = {key.removeprefix(prefix): data for key, data in entries.items()}
assert meta["content_sha256"] == item["content_sha256"] == bundle.content_sha256(content)
def test_selection_champion_latest_all(stores):
for value in (1, 2, 3):
_register(value)
with pytest.raises(bundle.Empty, match="nothing to export"):
bundle.export(DOMAIN)
registry.promote(NAME, 2)
assert bundle.export(DOMAIN).versions == [(NAME, 2)]
assert bundle.export(DOMAIN, ["curve_x"], "latest").versions == [(NAME, 3)]
assert bundle.export(DOMAIN, versions="all").versions == [(NAME, 1), (NAME, 2), (NAME, 3)]
with pytest.raises(bundle.BundleError, match="no tea model missing"):
bundle.export(DOMAIN, ["missing"])
@pytest.mark.parametrize("clinical", [True, False])
def test_roundtrip_registers_candidates_with_lineage(stores, clinical):
_register()
source_version = _register(2, clinical=clinical)
source = registry.snapshot(NAME, source_version)
inputs = pd.DataFrame({"value": [0]})
prediction = mlflow.pyfunc.load_model(f"models:/{NAME}/{source_version}").predict(inputs)
exported = bundle.export(DOMAIN, versions="latest")
stores("b")
_trust(exported.data)
assert bundle.import_(DOMAIN, exported.data) == bundle.Imported(
exported.sha256, [(NAME, 1)], []
)
target = registry.snapshot(NAME, 1)
pd.testing.assert_frame_equal(
mlflow.pyfunc.load_model(f"models:/{NAME}/1").predict(inputs),
prediction,
)
assert target.params == source.params
assert target.metrics == source.metrics
assert target.reports == source.reports
assert target.tags == {
"source": "test",
"bundle.sha256": exported.sha256,
"bundle.source_name": NAME,
"bundle.source_version": "2",
"bundle.content_sha256": json.loads(_entries(exported.data)["manifest.json"])["versions"][
0
]["content_sha256"],
}
assert registry.champion_version(NAME) is None
if clinical:
registry.promote(NAME, 1)
assert registry.champion_version(NAME) == 1
else:
with pytest.raises(registry.MissingReports, match="clinical_validation"):
registry.promote(NAME, 1)
def test_importing_twice_is_a_conflict_and_partial_imports_skip(stores):
_register()
single = bundle.export(DOMAIN, versions="latest")
_register(2)
both = bundle.export(DOMAIN, versions="all")
stores("b")
_trust(single.data)
_trust(both.data)
assert bundle.import_(DOMAIN, single.data).imported == [(NAME, 1)]
with pytest.raises(bundle.Conflict, match="every version is already registered"):
bundle.import_(DOMAIN, single.data)
result = bundle.import_(DOMAIN, both.data)
assert result.imported == [(NAME, 2)]
assert result.skipped == [(NAME, 1)]
def test_tampered_bundles_are_refused(stores):
_register()
entries = _entries(bundle.export(DOMAIN, versions="latest").data)
path = "models/tea.curve_x/v1/model/MLmodel"
manifest = json.loads(entries["manifest.json"])
def with_manifest(**fields):
return entries | {"manifest.json": json.dumps(manifest | fields).encode()}
cases = [
(_zip(entries | {path: entries[path][:-1] + b"!"}), "content does not match the manifest"),
(_zip(entries | {"extra": b""}), "files in the bundle do not match the manifest"),
(_zip({k: v for k, v in entries.items() if k != path}), "files in the bundle do not match"),
(_zip(entries | {"../x": b""}), r"unsafe bundle path: \.\./x"),
(_zip(with_manifest(format=2)), "bundle format 2, this platform reads 1"),
(_zip(with_manifest(domain="cacu")), "bundle is for cacu, not tea"),
(b"hello", "not a bundle"),
]
for data, message in cases:
_trust(data)
with pytest.raises(bundle.BundleError, match=message):
bundle.import_(DOMAIN, data)
def test_import_refuses_an_untrusted_digest(stores):
_register()
exported = bundle.export(DOMAIN, versions="latest")
with pytest.raises(bundle.BundleError, match=f"bundle {exported.sha256} is not trusted"):
bundle.import_(DOMAIN, exported.data)
def test_version_lifecycle(stores):
first = _register(clinical=False)
second = _register(clinical=True)
assert registry.status(NAME, first) == "candidate"
with pytest.raises(registry.MissingReports, match="clinical_validation"):
registry.promote(NAME, first)
registry.add_report(NAME, first, "clinical_validation", "review.txt", b"approved")
registry.promote(NAME, first)
assert registry.status(NAME, first) == "champion"
with pytest.raises(ValueError, match="the champion cannot be retired"):
registry.retire(NAME, first)
registry.promote(NAME, second)
assert registry.status(NAME, first) == "candidate"
registry.retire(NAME, first)
assert registry.status(NAME, first) == "retired"
with pytest.raises(ValueError, match="is retired"):
registry.promote(NAME, first)
assert registry.champion_version(NAME) == second
+82
View File
@@ -0,0 +1,82 @@
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():
baseline = {
"kind": "curves",
"curve": {
"age_months": [16, 36],
"p5": [1, 3],
"p25": [2, 4],
"median": [3, 5],
"p75": [5, 7],
"p95": [7, 9],
},
}
assert curves.centiles(baseline, 24) == pytest.approx(
{"p5": 2, "p25": 3, "median": 4, "p75": 6, "p95": 8}
)
for value, z, outside in ((0, -3.29, -1), (3, -0.8225, 0), (6, 0.8225, 0), (10, 2.4675, 1)):
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"]
+50
View File
@@ -0,0 +1,50 @@
from datetime import date
import pytest
from edf_files import small_edf
from models.tea.eeg.read import FileNotValid, Header, _kept, header
def test_header_reads_the_facts(tmp_path):
data = small_edf(tmp_path / "a.edf")
assert header(data) == Header(
"N1001", "F", date(2025, 1, 5), date(2026, 3, 2), "LAB-1", 20.0, 3
)
def test_placeholders_are_none(tmp_path):
data = small_edf(
tmp_path / "a.edf", patient_code="X", sex="X", birthdate=None,
startdate=date(1985, 1, 1), record_code="X",
) # fmt: skip
assert header(data) == Header(None, None, None, None, None, 20.0, 3)
def test_header_does_not_read_the_signal(tmp_path):
data = small_edf(tmp_path / "a.edf")
truncated = data[: int(data[184:192])]
assert header(truncated) == header(data)
assert header(truncated).duration_s == 20.0
with pytest.warns(UserWarning, match="Updating header"):
with pytest.raises(FileNotValid, match="truncated"):
_kept(truncated)
def test_zero_signal_header_is_valid(tmp_path):
data = small_edf(tmp_path / "a.edf")
zero = data[:184] + b"256 " + data[192:252] + b"0 "
assert header(zero).channels == 0
with pytest.raises(FileNotValid, match="ZeroDivisionError"):
_kept(zero)
@pytest.mark.parametrize("data", [b"", b"x" * 100, b"x" * 300])
def test_not_an_edf_is_not_valid(data):
with pytest.raises(FileNotValid):
header(data)
def test_kept_channels_are_unchanged(tmp_path):
data = small_edf(tmp_path / "a.edf")
assert _kept(data) == [("Fp1", "Fp1"), ("Fp2", "Fp2"), ("Cz", "Cz")]
+224
View File
@@ -0,0 +1,224 @@
from dataclasses import replace
from types import SimpleNamespace
import numpy as np
import pandas as pd
import pytest
from scipy import signal
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, "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():
frequencies = np.arange(1.0, 46.0, 0.5)
background = 1 / frequencies
power = background.copy()
power[frequencies == 8] *= 10
assert signals.dominant_peak(frequencies, power) == (8.0, pytest.approx(10), True)
assert not signals.dominant_peak(frequencies, background)[2]
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"]
+76
View File
@@ -0,0 +1,76 @@
import pytest
from models import execution
from models.execution import Execution, ExecutionError
from persistance import cluster
def square(x):
return int(x) ** 2
def fail_on_three(x):
if x == 3:
raise RuntimeError("three")
return x
@pytest.fixture(autouse=True)
def env(monkeypatch):
for name in ("EXECUTION_MODE", "DASK_SCHEDULERS"):
monkeypatch.delenv(name, raising=False)
def test_resolve_defaults_and_allow_list(monkeypatch):
assert execution.resolve().mode == "local"
monkeypatch.setenv("EXECUTION_MODE", "sync")
assert execution.resolve().mode == "sync"
with pytest.raises(ExecutionError):
execution.resolve(Execution(mode="remote"))
monkeypatch.setenv("DASK_SCHEDULERS", "a:8786,tcp://b:8786")
assert execution.resolve(Execution(mode="remote")).scheduler == "tcp://a:8786"
assert execution.resolve(Execution(mode="remote", scheduler="b:8786")).scheduler == (
"tcp://b:8786"
)
assert execution.options().schedulers == ["tcp://a:8786", "tcp://b:8786"]
def test_resolve_rejects_unlisted_scheduler_and_scheduler_in_local_mode(monkeypatch):
monkeypatch.setenv("DASK_SCHEDULERS", "a:8786")
with pytest.raises(ExecutionError, match="not in DASK_SCHEDULERS"):
execution.resolve(Execution(mode="remote", scheduler="c:8786"))
with pytest.raises(ExecutionError, match="only goes with remote"):
execution.resolve(Execution(mode="local", scheduler="a:8786"))
with pytest.raises(ExecutionError, match="not host:port"):
cluster.normalize("http://a:1")
def test_map_sync_keeps_input_order_and_reports_each_item(monkeypatch):
monkeypatch.setenv("EXECUTION_MODE", "sync")
lines = []
assert execution.map(square, range(5), log=lines.append) == [0, 1, 4, 9, 16]
assert lines[0] == "working: 0/5" and lines[-1] == "working: 5/5"
def test_map_on_error_converts_a_failed_item(monkeypatch):
monkeypatch.setenv("EXECUTION_MODE", "sync")
out = execution.map(fail_on_three, range(6), on_error=lambda item, e: -item, log=lambda s: None)
assert out == [0, 1, 2, -3, 4, 5]
def test_map_raises_without_on_error(monkeypatch):
monkeypatch.setenv("EXECUTION_MODE", "sync")
with pytest.raises(RuntimeError, match="three"):
execution.map(fail_on_three, range(6), log=lambda s: None)
def test_eta_smoothing_and_threshold():
eta = execution.Eta(alpha=0.3, min_done=3)
eta.update(0.0, 0)
eta.update(1.0, 2)
assert eta.eta_s(10) is None
eta.update(2.0, 4)
assert eta.eta_s(10) == pytest.approx((10 - 4) / 2.0)
eta.update(3.0, 8)
assert eta.rate == pytest.approx(0.3 * 4 + 0.7 * 2.0)
assert eta.eta_s(10) == pytest.approx(2 / eta.rate)
+60
View File
@@ -0,0 +1,60 @@
from datetime import date
import pytest
from sqlalchemy import text
from core.pipeline import HELD, RECORD, Target
from core.tea import ados2
from core.tea.ados2_items import ITEMS
from models.graph import run_target
from persistance import nodes, review
NODE = Target(id="ados2_out", inputs=["reports", "persons"], entity="ados2")
KINDS = {"reports": "extract", "persons": "link"}
A1_NEEDED = "language_level: A-1 (0 to 4) is needed to score"
def _loaded(module, birth):
report = {
RECORD: "report",
"_index": 0,
"evaluation_date": date(2025, 2, 1),
"module": module,
**{item.field: 1 for item in ITEMS[module]},
}
nodes.write("tea", "reports", [report])
persons = [
{RECORD: "report", "person_id": "child", "birth_date": None},
{RECORD: "patient", "person_id": "child", "birth_date": birth},
]
columns = {"birth_date": {"data_type": "text", "nullable": True}}
nodes.write("tea", "persons", persons, columns)
run_target("tea", NODE, KINDS)
def _held():
return [row[HELD] for row in review.held("ados2")]
def test_a_held_record_corrected_with_a1_is_scored(fresh_platform):
birth = "2022-08-01"
_loaded("module_1", birth)
assert _held() == [[A1_NEEDED]]
nodes.correct("report", "language_level", "3", "reviewer", "ados2")
run_target("tea", NODE, KINDS)
assert _held() == []
with fresh_platform.connect() as con:
sql = text("select field, value_num, value_text from bronze.staged__observation")
values = {field: num if num is not None else said for field, num, said in con.execute(sql)}
scored = ados2.score(values | {"evaluation_date": date(2025, 2, 1)}, date.fromisoformat(birth))
assert (scored.column, scored.column_source) == ("few_words", "a1")
@pytest.mark.parametrize(
"birth, held",
[("2023-08-01", []), ("2023-01-01", [[A1_NEEDED]]), (None, [[A1_NEEDED]])],
)
def test_the_persons_birth_date_says_whether_a_toddler_needs_a1(fresh_platform, birth, held):
_loaded("toddler", birth)
assert _held() == held
-19
View File
@@ -1,19 +0,0 @@
import pytest
from models.cacu import CaCuModel
from models.cama import CaMaModel
from models.tea import TeaModel
@pytest.mark.parametrize("cls", [CaCuModel, CaMaModel, TeaModel])
def test_train_not_implemented(cls):
model = cls()
with pytest.raises(NotImplementedError):
model.train()
@pytest.mark.parametrize("cls", [CaCuModel, CaMaModel, TeaModel])
def test_predict_not_implemented(cls):
model = cls()
with pytest.raises(NotImplementedError):
model.predict(data=None)
+50
View File
@@ -0,0 +1,50 @@
import numpy as np
import pandas as pd
from scipy.special import gammaln
from models import curves, survival
SOLVER_TOLERANCE = 1e-6
def test_fractional_weibull_reproduces_the_classic_one():
t = np.linspace(0, 300, 61)
for k, lam in ((0.9, 476.0), (2.4, 233.6), (1.3, 60.0)):
found, want = curves.fractional(t, k, 1.0, 1.0, lam), curves.weibull(t, k, lam)
np.testing.assert_allclose(found, want, rtol=0, atol=SOLVER_TOLERANCE)
def _series(z: np.ndarray, rho: float, m: float, l: float, terms: int = 200) -> np.ndarray: # noqa: E741
j = np.arange(terms - 1)
log_c = np.concatenate([[0.0], np.cumsum(gammaln(rho * (m * j + l) + 1)
- gammaln(rho * (m * j + l + 1) + 1))]) # fmt: skip
return (np.exp(log_c)[None, :] * z[:, None] ** np.arange(terms)[None, :]).sum(axis=1)
def test_fractional_weibull_solver_matches_the_series():
t = np.linspace(0, 72, 289)
for k, a, b, lam in ((1.0, 0.5, 0.7, 80.0), (0.8, 0.9, 0.4, 150.0), (1.3, 0.3, 0.9, 60.0)):
s = k + a - 2
z = -np.exp(gammaln(k + 1) - gammaln(k + a - 1)) * (t / lam) ** (k + a + b - 2)
assert np.abs(z).max() < 2
found, want = curves.fractional(t, k, a, b, lam), _series(z, b, s / b + 1, s / b)
np.testing.assert_allclose(found, want, rtol=0, atol=SOLVER_TOLERANCE)
def test_survival_censors_deaths_after_follow_up_or_horizon():
index = pd.Series(["2020-01-01"] * 4)
death = pd.Series(["2020-03-05", "2020-05-15", "2020-08-01", None])
result = survival.outcomes(index, death, "2020-06-01", cap_months=3)
assert list(result.itertuples(index=False, name=None)) == [
(2, True),
(3, False),
(3, False),
(3, False),
]
uncapped = survival.outcomes(index, death, "2020-06-01", cap_months=0)
assert list(uncapped.itertuples(index=False, name=None)) == [
(2, True),
(4, True),
(4, False),
(4, False),
]
-105
View File
@@ -1,105 +0,0 @@
"""El contrato `EstimadorDeRiesgo` y el estimador sustituto (ADR-MD-008)."""
import pytest
from models import riesgo
from models.riesgo import (
REGLA_SINTETICA_CAMA,
REGLA_SINTETICA_TEA,
EstimadorDeRiesgo,
Riesgo,
RiesgoSintetico,
RiesgoSinteticoCama,
RiesgoSinteticoTea,
)
COLUMNAS = ["pac_id", "fecha_indice", "c", "pap_0", "hpv_0"]
FILAS = [(1, "2024-07-01", 0, "NORMAL", "NEGATIVO"), (2, "2024-08-01", 0, "LIEAG", "POSITIVO"), (3, "2024-09-01", 0, None, None)]
def test_el_sustituto_cumple_el_contrato():
assert isinstance(RiesgoSintetico(), EstimadorDeRiesgo)
def test_un_riesgo_por_miembro_y_horizonte_en_el_orden_del_marco():
riesgos = RiesgoSintetico(horizontes=(0.0, 1.0)).estimar(COLUMNAS, FILAS)
assert [(r.pac_id, r.horizonte_anios) for r in riesgos] == [(1, 0.0), (1, 1.0), (2, 0.0), (2, 1.0), (3, 0.0), (3, 1.0)]
assert all(isinstance(r, Riesgo) and 0 <= r.probabilidad <= 1 and r.ic_bajo is None for r in riesgos)
def test_la_regla_suma_por_predictor_basal():
p = {r.pac_id: r.probabilidad for r in RiesgoSintetico().estimar(COLUMNAS, FILAS)}
assert p == {1: 0.01, 2: 0.16, 3: 0.01}
def test_es_determinista():
a, b = RiesgoSintetico(), RiesgoSintetico()
assert a.estimar(COLUMNAS, FILAS) == b.estimar(COLUMNAS, FILAS)
assert a.procedencia() == b.procedencia()
def test_la_procedencia_trae_las_cuatro_llaves_y_su_sha_cambia_con_la_regla(monkeypatch):
procedencia = RiesgoSintetico().procedencia()
assert set(procedencia.como_dict()) == {"modelo_nombre", "modelo_version", "mlflow_run_id", "modelo_sha"}
assert all(procedencia.como_dict().values())
monkeypatch.setitem(riesgo.REGLA_SINTETICA, "vph_positivo", 0.2)
assert RiesgoSintetico().procedencia().modelo_sha != procedencia.modelo_sha
def test_sin_los_predictores_falla_y_los_nombra():
with pytest.raises(ValueError, match="pap_0"):
RiesgoSintetico().estimar(["pac_id", "hpv_0"], [(1, None)])
# --- El sustituto de TEA (T-21f) ---------------------------------------------------------------
COLUMNAS_TEA = ["pac_id", "fecha_indice", "d", "t", "mchat_0", "apgar_5min", "ingreso_ucin", "n_antecedentes",
"hipoacusia_0"]
def test_el_sustituto_de_tea_cumple_el_contrato_y_lee_su_cohorte():
estimador = RiesgoSinteticoTea()
assert isinstance(estimador, EstimadorDeRiesgo)
assert estimador.cohorte_url == "tea/cohorte_tamizaje" and estimador.horizontes == (4.0,)
def test_la_regla_de_tea_suma_mchat_ucin_y_apgar_bajo():
filas = [(1, None, None, None, "RIESGO_BAJO", 9.0, 0.0, 0, None),
(2, None, None, None, "RIESGO_ALTO", 6.0, 1.0, 2, "LEVE"),
(3, None, None, None, None, None, None, 0, None)]
r = REGLA_SINTETICA_TEA
assert [x.probabilidad for x in RiesgoSinteticoTea().estimar(COLUMNAS_TEA, filas)] == pytest.approx(
[r["base"], r["base"] + r["mchat_alto"] + r["ucin"] + r["apgar_bajo"], r["base"]])
def test_el_sustituto_de_tea_sin_sus_predictores_falla():
with pytest.raises(ValueError, match="mchat_0"):
RiesgoSinteticoTea().estimar(["pac_id", "fecha_indice"], [])
# --- El sustituto de CaMa (T-21g) --------------------------------------------------------------
COLUMNAS_CAMA = ["pac_id", "fecha_indice", "d", "t", "birads_0", "calidad_0", "n_ordenes_previas"]
def test_el_sustituto_de_cama_cumple_el_contrato_y_lee_su_cohorte():
estimador = RiesgoSinteticoCama()
assert isinstance(estimador, EstimadorDeRiesgo)
assert estimador.cohorte_url == "cama/cohorte_tamizaje" and estimador.horizontes == (1.0,)
def test_la_regla_de_cama_suma_por_birads_indice_y_4a_cuenta_como_4():
filas = [(1, None, None, None, "B2", None, 0), (2, None, None, None, "B4A", None, 0),
(3, None, None, None, "B5", None, 0), (4, None, None, None, None, None, 0)]
r = REGLA_SINTETICA_CAMA
assert [x.probabilidad for x in RiesgoSinteticoCama().estimar(COLUMNAS_CAMA, filas)] == pytest.approx(
[r["base"], r["base"] + r["birads_4"], r["base"] + r["birads_5"], r["base"]])
def test_el_sustituto_de_cama_sin_su_predictor_falla():
with pytest.raises(ValueError, match="birads_0"):
RiesgoSinteticoCama().estimar(["pac_id", "fecha_indice"], [])
+19
View File
@@ -0,0 +1,19 @@
from persistance.nodes import stable_persons
def test_person_ids_survive_a_review_merge_and_split(fresh_platform):
older = stable_persons({"one": ["a"]})["one"]
newer = stable_persons({"two": ["b", "c"]})["two"]
assert older != newer
assert stable_persons({"merged": ["a", "b", "c"]}) == {"merged": older}
with fresh_platform.connect() as connection:
assert connection.exec_driver_sql(
"select person_id, replaced_by from bronze.person_link"
).all() == [(newer, older)]
split = {"small": ["a"], "large": ["b", "c"]}
assigned = stable_persons(split)
assert assigned["large"] == older
assert assigned["small"] not in {older, newer}
assert stable_persons(split) == assigned
+275
View File
@@ -0,0 +1,275 @@
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})
fit = a.firth(frame, "event", "z", ())
assert np.isfinite(fit["odds_ratio"])
assert fit["ci_low"] < fit["odds_ratio"] < fit["ci_high"]
def test_bh():
np.testing.assert_allclose(a.bh([0.04, 0.01, np.nan, 0.03]), [0.04, 0.03, np.nan, 0.04])
def test_ordinal_on_monotone_trend():
frame = pd.DataFrame({"z": np.arange(12), "level": [0, 0, 1, 0, 1, 1, 2, 0, 2, 1, 2, 2]})
assert a.ordinal(frame, "level", "z", (), high=2)["odds_ratio"] > 1
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()
+169
View File
@@ -0,0 +1,169 @@
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
def test_scope_validation():
assert eeg.Scope().mode == "pending"
assert eeg.Scope(mode="first_n", n=3).n == 3
good = "p1|2024-05-06"
assert eeg.Scope(mode="ids", ids=[good]).ids == [good]
bad = [
{"mode": "first_n"},
{"mode": "first_n", "n": 0},
{"mode": "first_n", "n": 2, "ids": [good]},
{"mode": "ids"},
{"mode": "ids", "ids": [good], "n": 1},
{"mode": "ids", "ids": ["nobar"]},
{"mode": "ids", "ids": ["p|2024-5-6"]},
{"mode": "ids", "ids": ["|2024-05-06"]},
{"mode": "ids", "ids": [f"p{i}|2024-05-06" for i in range(501)]},
{"mode": "pending", "n": 1},
{"mode": "pending", "ids": [good]},
{"mode": "other"},
{"extra": 1},
]
for kwargs in bad:
with pytest.raises(ValidationError):
eeg.Scope(**kwargs)
assert len(eeg.Scope(mode="ids", ids=[f"p{i}|2024-05-06" for i in range(500)]).ids) == 500
with pytest.raises(ValidationError, match="first_n needs n"):
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)
request = after_ingest("r1", lambda: True)
assert isinstance(request, dg.RunRequest)
assert request.run_key == "after-ingest-r1"
scope = request.run_config["ops"]["tea_analyze_studies"]["config"]["scope"]
assert scope == {"mode": "pending"}
assert request.tags["domain"] == "tea" and request.tags["triggered_by"] == "r1"
def test_tea_eeg_first_n_selects_exactly_n_pending_studies(fresh_platform):
with fresh_platform.begin() as con:
con.exec_driver_sql("create table silver.person (person_id text, birth_date text)")
con.exec_driver_sql("insert into silver.person values ('p1', '2023-01-01')")
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 (?, ?, ?)",
[
("p1", "2025-01-01", "c"),
("p1", "2025-02-01", "b"),
("p1", "2025-03-01", "a"),
("p1", "2025-04-01", "d"),
("p1", "2025-05-01", None),
],
)
con.exec_driver_sql("create table bronze.eeg_analysis (edf text)")
con.exec_driver_sql("insert into bronze.eeg_analysis values ('b')")
birth = date(2023, 1, 1)
assert eeg.select(eeg.Scope(mode="first_n", n=2)) == [
{"edf": "a", "birth_date": birth},
{"edf": "c", "birth_date": birth},
]
assert eeg.select(eeg.Scope(mode="ids", ids=["p1|2025-02-01"])) == [
{"edf": "b", "birth_date": birth}
]
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
+112
View File
@@ -0,0 +1,112 @@
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
@pytest.fixture
def preview_area(monkeypatch, tmp_path):
monkeypatch.setattr(config, "DATA_DIR", tmp_path)
return previews.area()
def test_previews_area(preview_area):
key = previews.put(b"file")
assert key == hashlib.sha256(b"file").hexdigest()
os.utime(preview_area / key, (1, 1))
assert previews.put(b"file") == key
assert (preview_area / key).stat().st_mtime == 1
assert previews.get(key) == b"file"
for invalid in ("../x", "abc"):
with pytest.raises(ValueError):
previews.get(invalid)
with pytest.raises(LookupError, match=f"no preview file {'0' * 64}"):
previews.get("0" * 64)
previews.discard([key, None, "0" * 64])
assert not (preview_area / key).exists()
old = previews.put(b"old")
recent = previews.put(b"recent")
os.utime(preview_area / old, (1, 1))
assert previews.sweep() == 1
assert {path.name for path in preview_area.iterdir()} == {recent}
def test_an_unreadable_file_is_a_result_not_a_crash():
result = study.preview(b"nope")
assert result.eeg.valid is False
assert result.eeg.checks
assert result.ados2 is None
assert result.eeg.recorded_on is None
def test_the_job_deletes_its_files_and_returns_the_result_as_output(preview_area):
edf = previews.put(b"not an EDF")
report = previews.put(b"not a PDF")
with build_op_context() as context:
result = preview_study(context, Preview(edf=edf, ados2=report))
assert result == {"valid": False, "warnings": 1}
assert list(preview_area.iterdir()) == []
def test_the_job_deletes_its_files_when_the_study_fails(preview_area):
report = previews.put(b"%PDF")
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()) == []
def _preview_report(monkeypatch, *lines):
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)",
"social_affect_total": r"AS (\d+)",
"restricted_repetitive_total": r"CRR (\d+)",
},
)
text = "\n".join(("Módulo module_1", "A-2 2", "A-3 3", "A-5 3", *lines))
monkeypatch.setattr(study.graph, "read_file", lambda _: {"text": text, "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)
return result, warnings
@pytest.mark.parametrize(
"lines, css, warned",
[
(("AS 2", "CRR 2"), None, ["language_level: A-1 (0 to 4) is needed to score"]),
(("A-1 3", "AS 2", "CRR 2"), 1, []),
(("A-1 3", "AS 2", "CRR 3"), 1, ["the printed totals differ from the item scores"]),
],
)
def test_ados2_preview_warns_what_would_hold_the_record(monkeypatch, lines, css, warned):
result, warnings = _preview_report(monkeypatch, *lines)
assert result.css == css
assert warnings == warned
@pytest.mark.parametrize("language, css", [(3, 1), (1, 2)])
def test_ados2_preview_reads_language_level_and_scores_its_column(monkeypatch, language, css):
result, warnings = _preview_report(monkeypatch, f"A-1 {language}")
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 == []
+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))