Compare commits

..

63 Commits

Author SHA1 Message Date
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
55 changed files with 2996 additions and 1458 deletions
+1 -3
View File
@@ -1,4 +1,2 @@
__pycache__/ __pycache__/
node_modules/ .pytest_cache/
dist/
.angular/
-1
View File
@@ -1 +0,0 @@
-1
View File
@@ -1 +0,0 @@
+18 -29
View File
@@ -1,5 +1,6 @@
import numpy as np import numpy as np
import pandas as pd import pandas as pd
from core import cacu from core import cacu
RESULTS = ("bethesda", "glandular", "hpv") RESULTS = ("bethesda", "glandular", "hpv")
@@ -32,16 +33,9 @@ def _referral_grade(events: pd.DataFrame, persons: pd.Series, history: dict) ->
worst = _worst(codes, history["cytology"]).reindex(persons).to_numpy() worst = _worst(codes, history["cytology"]).reindex(persons).to_numpy()
hpv = near[(near["type"] == "hpv") & (near["value_code"] == "positive")] hpv = near[(near["type"] == "hpv") & (near["value_code"] == "positive")]
positive = persons.isin(hpv["person_id"]) positive = persons.isin(hpv["person_id"])
grade = np.where( grade = np.where(np.isin(worst, history["high"]), "high", np.where(
np.isin(worst, history["high"]), np.isin(worst, history["low"]) | (np.isin(worst, history["low_if_hpv_positive"])
"high", & positive.to_numpy()), "low", None)) # fmt: skip
np.where(
np.isin(worst, history["low"])
| np.isin(worst, history["low_if_hpv_positive"]) & positive.to_numpy(),
"low",
None,
),
)
return pd.Series(grade, index=persons.index, dtype=object) return pd.Series(grade, index=persons.index, dtype=object)
@@ -71,45 +65,41 @@ def _negatives(events: pd.DataFrame, d: pd.Series, grades: list[str]) -> pd.Data
visits = found visits = found
continue continue
paired = pd.merge_asof( paired = pd.merge_asof(
visits.sort_values("days"), visits.sort_values("days"), found.rename(columns={"days": kind}).sort_values(kind),
found.rename(columns={"days": kind}).sort_values(kind), left_on="days", right_on=kind, by="person_id", direction="nearest",
left_on="days",
right_on=kind,
by="person_id",
direction="nearest",
tolerance=float(cacu.INDEX_SAMPLE_DAYS), tolerance=float(cacu.INDEX_SAMPLE_DAYS),
).dropna(subset=[kind]) ).dropna(subset=[kind]) # fmt: skip
visits = paired.assign(days=paired[["days", kind]].max(axis=1))[["person_id", "days"]] visits = paired.assign(days=paired[["days", kind]].max(axis=1))[["person_id", "days"]]
return pd.concat([biopsies[["person_id", "days"]], visits], ignore_index=True) return pd.concat([biopsies[["person_id", "days"]], visits], ignore_index=True)
def interval_coded( def interval_coded(events: pd.DataFrame, grades: list[str], cytology: dict,
events: pd.DataFrame, grades: list[str], cytology: dict, history: dict | None = None history: dict | None = None) -> pd.DataFrame: # fmt: skip
) -> pd.DataFrame:
d = days(events) d = days(events)
outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades) & (d >= 0) outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades) & (d >= 0)
first = d[outcome].groupby(events.loc[outcome, "person_id"]).min() first = d[outcome].groupby(events.loc[outcome, "person_id"]).min()
negatives = _negatives(events, d, grades) negatives = _negatives(events, d, grades)
before = ~(negatives["days"] >= negatives["person_id"].map(first)) before = ~(negatives["days"] >= negatives["person_id"].map(first))
last_negative = negatives[before].groupby("person_id")["days"].max() last_negative = negatives[before].groupby("person_id")["days"].max()
coded = index_results(events, cytology, history) coded = index_results(events, cytology, history)
window = cacu.PREVALENT_WINDOW_DAYS window = cacu.PREVALENT_WINDOW_DAYS
event_days, free_until = (coded["person_id"].map(first), coded["person_id"].map(last_negative)) event_days, free_until = coded["person_id"].map(first), coded["person_id"].map(last_negative)
prevalent = event_days <= window prevalent = event_days <= window
free = free_until.notna() & ~prevalent free = free_until.notna() & ~prevalent
later = event_days.notna() & ~prevalent later = event_days.notna() & ~prevalent
coded["c"] = np.where(prevalent, 1, np.where(free, 0, -999)) 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["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)) coded["r"] = np.where(prevalent, 0.0,
np.where(later, event_days / cacu.DAYS_PER_YEAR, np.inf)) # fmt: skip
return coded return coded
def last_screening_cytology(events: pd.DataFrame) -> pd.Series: def last_screening_cytology(events: pd.DataFrame) -> pd.Series:
referred = set(events.loc[events["type"].isin(REFERRED), "person_id"]) referred = set(events.loc[events["type"].isin(REFERRED), "person_id"])
key = ["person_id", "source_table", "source_id"] key = ["person_id", "source_table", "source_id"]
samples = events.loc[ samples = events.loc[(events["type"] == "cytology") & ~events["person_id"].isin(referred),
(events["type"] == "cytology") & ~events["person_id"].isin(referred), [*key, "date"] [*key, "date"]] # fmt: skip
]
results = events[events["type"].isin(RESULTS) & events["value_code"].notna()] results = events[events["type"].isin(RESULTS) & events["value_code"].notna()]
has = results.pivot_table(index=key, columns="type", values="value_code", aggfunc="first") has = results.pivot_table(index=key, columns="type", values="value_code", aggfunc="first")
has = has.reindex(columns=list(RESULTS)) has = has.reindex(columns=list(RESULTS))
@@ -123,7 +113,7 @@ def last_screening_cytology(events: pd.DataFrame) -> pd.Series:
def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]: def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]:
ordered = members.sort_values(["index_date", "person_id"], kind="stable") ordered = members.sort_values(["index_date", "person_id"], kind="stable")
cut = int(len(ordered) * train_fraction) cut = int(len(ordered) * train_fraction)
return (ordered.iloc[:cut], ordered.iloc[cut:]) return ordered.iloc[:cut], ordered.iloc[cut:]
def index_sample(events: pd.DataFrame, predictors: list[str]) -> pd.DataFrame: def index_sample(events: pd.DataFrame, predictors: list[str]) -> pd.DataFrame:
@@ -144,9 +134,8 @@ def index_sample(events: pd.DataFrame, predictors: list[str]) -> pd.DataFrame:
return found.fillna(dict.fromkeys(predictors, MISSING)) return found.fillna(dict.fromkeys(predictors, MISSING))
def windowed_outcome( def windowed_outcome(events: pd.DataFrame, grades: list[str], years: float,
events: pd.DataFrame, grades: list[str], years: float, follow_up_end: pd.Timestamp follow_up_end: pd.Timestamp) -> pd.DataFrame: # fmt: skip
) -> pd.DataFrame:
window = years * cacu.DAYS_PER_YEAR window = years * cacu.DAYS_PER_YEAR
outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades) outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades)
outcome &= days(events).between(0, window) outcome &= days(events).between(0, window)
+1 -1
View File
@@ -3,4 +3,4 @@ from models.cacu.specs import MODELS
from models.jobs import Jobs from models.jobs import Jobs
JOBS = Jobs("cacu", MODELS, reports.technical_validation, reports.interpretability) JOBS = Jobs("cacu", MODELS, reports.technical_validation, reports.interpretability)
train, score = (JOBS.train, JOBS.score) train, score = JOBS.train, JOBS.score
+33 -51
View File
@@ -1,4 +1,5 @@
from dataclasses import dataclass from dataclasses import dataclass
import numpy as np import numpy as np
import pandas as pd import pandas as pd
from scipy.interpolate import BSpline from scipy.interpolate import BSpline
@@ -10,11 +11,11 @@ from sklearn.base import BaseEstimator
UNKNOWN = -999 UNKNOWN = -999
TINY = 1e-12 TINY = 1e-12
FROZEN = 15.0 FROZEN = 15.0
HESSIAN_STEP = 0.0001 HESSIAN_STEP = 1e-4
def ispline_basis(t, degree: int, knots) -> np.ndarray: def ispline_basis(t, degree: int, knots) -> np.ndarray:
t, knots = (np.asarray(t, dtype=float), np.asarray(knots, dtype=float)) 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)] 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]) 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() bsplines = BSpline.design_matrix(inside, full, degree, extrapolate=False).toarray()
@@ -32,9 +33,7 @@ class ISpline:
@classmethod @classmethod
def at_quantiles(cls, l, r, n_knots: int, degree: int) -> "ISpline": def at_quantiles(cls, l, r, n_knots: int, degree: int) -> "ISpline":
times = np.unique(np.r_[l, r[np.isfinite(r)]]) times = np.unique(np.r_[l, r[np.isfinite(r)]])
return cls( return cls(tuple(float(k) for k in np.quantile(times, np.linspace(0, 1, n_knots))), degree)
tuple((float(k) for k in np.quantile(times, np.linspace(0, 1, n_knots)))), degree
)
@property @property
def n_params(self) -> int: def n_params(self) -> int:
@@ -44,11 +43,11 @@ class ISpline:
return ispline_basis(t, self.degree, self.knots) @ np.exp(params) return ispline_basis(t, self.degree, self.knots) @ np.exp(params)
def start(self, c, l, r) -> np.ndarray: def start(self, c, l, r) -> np.ndarray:
at_risk, finite = (c != 1, np.isfinite(r)) at_risk, finite = c != 1, np.isfinite(r)
exposure = np.where(finite, (l + r) / 2, l)[at_risk].sum() exposure = np.where(finite, (l + r) / 2, l)[at_risk].sum()
events = (at_risk & finite & (r > 0)).sum() events = (at_risk & finite & (r > 0)).sum()
rate = np.exp(-np.log(max(exposure, 1e-06) / (events + 0.5))) 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-06) / self.n_params)) 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: def survival(t, baseline: ISpline, baseline_params, beta, Z) -> np.ndarray:
@@ -60,13 +59,13 @@ def survival(t, baseline: ISpline, baseline_params, beta, Z) -> np.ndarray:
def neg_loglik(params, c, l, r, X, Z, baseline: ISpline, w) -> float: def neg_loglik(params, c, l, r, X, Z, baseline: ISpline, w) -> float:
n_x, n_z = (X.shape[1], Z.shape[1]) 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 :]) theta, beta, rest = params[:n_x], params[n_x : n_x + n_z], params[n_x + n_z :]
pi = expit(X @ theta) pi = expit(X @ theta)
interval = survival(l, baseline, rest, beta, Z) - survival(r, baseline, rest, beta, Z) interval = survival(l, baseline, rest, beta, Z) - survival(r, baseline, rest, beta, Z)
interval = np.maximum(interval, TINY) interval = np.maximum(interval, TINY)
row = np.zeros(len(c)) row = np.zeros(len(c))
prevalent, free, unknown = (c == 1, c == 0, c == UNKNOWN) prevalent, free, unknown = c == 1, c == 0, c == UNKNOWN
row[prevalent] = np.log(pi[prevalent] + TINY) row[prevalent] = np.log(pi[prevalent] + TINY)
row[free] = np.log(1 - pi[free] + TINY) + np.log(interval[free]) row[free] = np.log(1 - pi[free] + TINY) + np.log(interval[free])
row[unknown] = np.log(pi[unknown] + (1 - pi[unknown]) * interval[unknown] + TINY) row[unknown] = np.log(pi[unknown] + (1 - pi[unknown]) * interval[unknown] + TINY)
@@ -78,8 +77,8 @@ def hessian(f, x, step: float = HESSIAN_STEP) -> np.ndarray:
out = np.zeros((p, p)) out = np.zeros((p, p))
for i in range(p): for i in range(p):
for j in range(i, p): for j in range(i, p):
ei, ej = (np.zeros(p), np.zeros(p)) ei, ej = np.zeros(p), np.zeros(p)
ei[i], ej[j] = (step, step) ei[i], ej[j] = step, step
value = (f(x + ei + ej) - f(x + ei - ej) - f(x - ei + ej) + f(x - ei - ej)) / ( value = (f(x + ei + ej) - f(x + ei - ej) - f(x - ei + ej) + f(x - ei - ej)) / (
4 * step * step 4 * step * step
) )
@@ -87,11 +86,11 @@ def hessian(f, x, step: float = HESSIAN_STEP) -> np.ndarray:
return out return out
def _ridge_logistic(c, X, ridge: float = 0.001) -> np.ndarray: def _ridge_logistic(c, X, ridge: float = 1e-3) -> np.ndarray:
known = c != UNKNOWN known = c != UNKNOWN
if not known.any(): if not known.any():
return np.zeros(X.shape[1]) return np.zeros(X.shape[1])
y, Xk = ((c[known] == 1).astype(float), X[known]) y, Xk = (c[known] == 1).astype(float), X[known]
def loss(theta): def loss(theta):
eta = Xk @ theta eta = Xk @ theta
@@ -118,29 +117,26 @@ class Fit:
p[self.n_x + self.n_z :], p[self.n_x + self.n_z :],
) )
pi = expit(X @ theta) pi = expit(X @ theta)
return np.column_stack( return np.column_stack([
[ pi + (1 - pi) * (1 - survival(np.full(len(X), float(t)), self.baseline, rest, beta, Z))
pi for t in years
+ (1 - pi) * (1 - survival(np.full(len(X), float(t)), self.baseline, rest, beta, Z)) ]) # fmt: skip
for t in years
]
)
def risk_with_variance(self, X, Z, years) -> tuple[np.ndarray, np.ndarray]: def risk_with_variance(self, X, Z, years) -> tuple[np.ndarray, np.ndarray]:
gradient = np.empty((len(self.params), len(X), len(years))) gradient = np.empty((len(self.params), len(X), len(years)))
for k, value in enumerate(self.params): for k, value in enumerate(self.params):
step = 1e-05 * max(1.0, abs(value)) step = 1e-5 * max(1.0, abs(value))
up, down = (self.params.copy(), self.params.copy()) up, down = self.params.copy(), self.params.copy()
up[k] += step up[k] += step
down[k] -= step down[k] -= step
gradient[k] = (self.risk(X, Z, years, up) - self.risk(X, Z, years, down)) / (2 * 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) covariance = np.nan_to_num(self.covariance, nan=0.0)
variance = np.einsum("kij,kl,lij->ij", gradient, covariance, gradient) variance = np.einsum("kij,kl,lij->ij", gradient, covariance, gradient)
return (self.risk(X, Z, years), np.maximum(variance, 0.0)) return self.risk(X, Z, years), np.maximum(variance, 0.0)
def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit: def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit:
n_x, n_z = (X.shape[1], Z.shape[1]) n_x, n_z = X.shape[1], Z.shape[1]
start = baseline.start(c, l, r) 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]] 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) args = (c, l, r, X, Z, baseline, w)
@@ -153,21 +149,13 @@ def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit:
covariance[np.ix_(free, free)] = np.linalg.inv(h[np.ix_(free, free)]) covariance[np.ix_(free, free)] = np.linalg.inv(h[np.ix_(free, free)])
except np.linalg.LinAlgError: except np.linalg.LinAlgError:
pass pass
converged = bool(np.max(np.abs(best.jac[free]), initial=0.0) < 0.001) 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) return Fit(n_x, n_z, baseline, best.x, covariance, float(best.fun), converged)
class Mixture(BaseEstimator): class Mixture(BaseEstimator):
def __init__( def __init__(self, horizons_years, incidence_features, strata, levels, knots=3, degree=4,
self, interval_level=0.95): # fmt: skip
horizons_years,
incidence_features,
strata,
levels,
knots=3,
degree=4,
interval_level=0.95,
):
self.horizons_years = horizons_years self.horizons_years = horizons_years
self.incidence_features = incidence_features self.incidence_features = incidence_features
self.strata = strata self.strata = strata
@@ -201,7 +189,7 @@ class Mixture(BaseEstimator):
def _design(self, X: pd.DataFrame, seen: dict) -> tuple[np.ndarray, np.ndarray]: 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)]) prevalence = np.column_stack([np.ones(len(X)), self._columns(X, X.columns, seen)])
return (prevalence, self._columns(X, self.incidence_features, seen)) return prevalence, self._columns(X, self.incidence_features, seen)
def _groups(self, X: pd.DataFrame): def _groups(self, X: pd.DataFrame):
if not self.strata: if not self.strata:
@@ -210,10 +198,9 @@ class Mixture(BaseEstimator):
return [(key if isinstance(key, tuple) else (key,), rows) for key, rows in groups] return [(key if isinstance(key, tuple) else (key,), rows) for key, rows in groups]
def fit(self, X: pd.DataFrame, y: pd.DataFrame): def fit(self, X: pd.DataFrame, y: pd.DataFrame):
rows = pd.concat( rows = pd.concat([X.reset_index(drop=True), y[["c", "l", "r"]].reset_index(drop=True)],
[X.reset_index(drop=True), y[["c", "l", "r"]].reset_index(drop=True)], axis=1 axis=1).assign(w=1.0) # fmt: skip
).assign(w=1.0) self.fits_, self.seen_ = {}, {}
self.fits_, self.seen_ = ({}, {})
for key, index in self._groups(X): for key, index in self._groups(X):
group = rows.iloc[index] group = rows.iloc[index]
seen = self._seen(group) seen = self._seen(group)
@@ -224,8 +211,8 @@ class Mixture(BaseEstimator):
baseline = ISpline.at_quantiles(l, r, self.knots, self.degree) baseline = ISpline.at_quantiles(l, r, self.knots, self.degree)
self.seen_[key] = seen self.seen_[key] = seen
self.fits_[key] = fit(c, l, r, prevalence, incidence, baseline, group["w"].to_numpy()) 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.neg_loglik_ = float(sum(f.neg_loglik for f in self.fits_.values()))
self.converged_ = all((f.converged for f in self.fits_.values())) self.converged_ = all(f.converged for f in self.fits_.values())
return self return self
def predict(self, X: pd.DataFrame) -> np.ndarray: def predict(self, X: pd.DataFrame) -> np.ndarray:
@@ -245,12 +232,7 @@ class Mixture(BaseEstimator):
unique[:, :n_x], unique[:, n_x:], self.horizons_years unique[:, :n_x], unique[:, n_x:], self.horizons_years
) )
relative = np.where(point > 0, np.sqrt(variance) / np.maximum(point, 1e-300), 0.0) relative = np.where(point > 0, np.sqrt(variance) / np.maximum(point, 1e-300), 0.0)
band = np.column_stack( 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
point,
np.clip(point * np.exp(-z * relative), 0, 1),
np.clip(point * np.exp(z * relative), 0, 1),
]
)
out[index[placed]] = band[inverse.ravel()] out[index[placed]] = band[inverse.ravel()]
return out return out
+27 -54
View File
@@ -2,6 +2,7 @@ import numpy as np
import pandas as pd import pandas as pd
from scipy.stats import norm from scipy.stats import norm
from sklearn.metrics import brier_score_loss from sklearn.metrics import brier_score_loss
from models import survival from models import survival
from models.cacu.pim import Mixture from models.cacu.pim import Mixture
from models.cacu.specs import Logistic, Pim from models.cacu.specs import Logistic, Pim
@@ -30,7 +31,7 @@ def technical_validation(spec: Pim | Logistic | survival.Spec, metrics: dict, da
def turnbull(c, l, r, iters: int = 5000, tol: float = 1e-10): def turnbull(c, l, r, iters: int = 5000, tol: float = 1e-10):
finite = r[np.isfinite(r)] finite = r[np.isfinite(r)]
support = np.unique(np.concatenate([[0.0], finite[finite > 0], [np.inf]])) 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)) 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]) inside = (support[None, :] > low[:, None]) & (support[None, :] <= high[:, None])
patterns, counts = np.unique(inside, axis=0, return_counts=True) patterns, counts = np.unique(inside, axis=0, return_counts=True)
p = np.full(len(support), 1 / len(support)) p = np.full(len(support), 1 / len(support))
@@ -41,7 +42,7 @@ def turnbull(c, l, r, iters: int = 5000, tol: float = 1e-10):
p = new p = new
if done: if done:
break break
return (support, np.cumsum(p)) return support, np.cumsum(p)
def _at(support, cumulative, t) -> np.ndarray: def _at(support, cumulative, t) -> np.ndarray:
@@ -59,10 +60,8 @@ def _label(feature: str, value) -> str:
def _band(curve, variance) -> tuple[list, list]: def _band(curve, variance) -> tuple[list, list]:
relative = np.where(curve > 0, np.sqrt(variance) / np.maximum(curve, 1e-300), 0.0) relative = np.where(curve > 0, np.sqrt(variance) / np.maximum(curve, 1e-300), 0.0)
return ( return (np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(),
np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(), np.clip(curve * np.exp(Z * relative), 0, 1).tolist()) # fmt: skip
np.clip(curve * np.exp(Z * relative), 0, 1).tolist(),
)
def _mixture_curve(mixture: Mixture, row: pd.DataFrame, years) -> tuple | None: def _mixture_curve(mixture: Mixture, row: pd.DataFrame, years) -> tuple | None:
@@ -71,7 +70,7 @@ def _mixture_curve(mixture: Mixture, row: pd.DataFrame, years) -> tuple | None:
return None return None
prevalence, incidence = mixture._design(row, mixture.seen_[key]) prevalence, incidence = mixture._design(row, mixture.seen_[key])
point, variance = mixture.fits_[key].risk_with_variance(prevalence, incidence, years) point, variance = mixture.fits_[key].risk_with_variance(prevalence, incidence, years)
return (point[0], variance[0]) return point[0], variance[0]
def interpretability(spec: Pim | Logistic | survival.Spec, model, data: dict) -> dict: def interpretability(spec: Pim | Logistic | survival.Spec, model, data: dict) -> dict:
@@ -80,9 +79,8 @@ def interpretability(spec: Pim | Logistic | survival.Spec, model, data: dict) ->
if isinstance(spec, Logistic): if isinstance(spec, Logistic):
return _logistic(model, data["test"]) return _logistic(model, data["test"])
coded = data["coded"] coded = data["coded"]
full = Mixture(spec.horizons, spec.incidence_features, spec.strata, model.levels).fit( full = Mixture(spec.horizons, spec.incidence_features, spec.strata,
coded[spec.features], coded[["c", "l", "r"]] model.levels).fit(coded[spec.features], coded[["c", "l", "r"]]) # fmt: skip
)
members = coded.reset_index(drop=True) 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}) 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) horizons = np.asarray(spec.horizons, dtype=float)
@@ -94,78 +92,53 @@ def interpretability(spec: Pim | Logistic | survival.Spec, model, data: dict) ->
group = members[mask] group = members[mask]
c, l, r = (group[k].to_numpy(dtype=float) for k in ("c", "l", "r")) c, l, r = (group[k].to_numpy(dtype=float) for k in ("c", "l", "r"))
support, cumulative = turnbull(c, l, r) support, cumulative = turnbull(c, l, r)
boot_grid, boot_h = ([], []) boot_grid, boot_h = [], []
for _ in range(BOOTSTRAP): for _ in range(BOOTSTRAP):
pick = rng.integers(0, len(group), len(group)) pick = rng.integers(0, len(group), len(group))
s, cum = turnbull(c[pick], l[pick], r[pick]) s, cum = turnbull(c[pick], l[pick], r[pick])
boot_grid.append(_at(s, cum, grid)) boot_grid.append(_at(s, cum, grid))
boot_h.append(_at(s, cum, horizons)) boot_h.append(_at(s, cum, horizons))
observed, var_observed = ( observed, var_observed = _at(support, cumulative, horizons), np.var(boot_h, axis=0, ddof=1)
_at(support, cumulative, horizons),
np.var(boot_h, axis=0, ddof=1),
)
entry = { entry = {
"combination": combination.to_dict(), "combination": combination.to_dict(),
"n": int(mask.sum()), "n": int(mask.sum()),
"prevalent": int((c == 1).sum()), "prevalent": int((c == 1).sum()),
"incident": int(((c != 1) & np.isfinite(r)).sum()), "incident": int(((c != 1) & np.isfinite(r)).sum()),
"observed": { "observed": {"years": grid.tolist(), "risk": _at(support, cumulative, grid).tolist(),
"years": grid.tolist(), "low": np.percentile(boot_grid, 2.5, axis=0).tolist(),
"risk": _at(support, cumulative, grid).tolist(), "high": np.percentile(boot_grid, 97.5, axis=0).tolist()},
"low": np.percentile(boot_grid, 2.5, axis=0).tolist(),
"high": np.percentile(boot_grid, 97.5, axis=0).tolist(),
},
"predicted": None, "predicted": None,
"expected_over_observed": [], "expected_over_observed": [],
} } # fmt: skip
probe = group.iloc[[0]][spec.features] probe = group.iloc[[0]][spec.features]
at_grid, at_h = (_mixture_curve(full, probe, grid), _mixture_curve(full, probe, horizons)) at_grid, at_h = _mixture_curve(full, probe, grid), _mixture_curve(full, probe, horizons)
if at_grid is not None: if at_grid is not None:
low, high = _band(*at_grid) low, high = _band(*at_grid)
entry["predicted"] = { entry["predicted"] = {"years": grid.tolist(), "risk": at_grid[0].tolist(),
"years": grid.tolist(), "low": low, "high": high} # fmt: skip
"risk": at_grid[0].tolist(),
"low": low,
"high": high,
}
for k, h in enumerate(horizons): for k, h in enumerate(horizons):
e = None if at_h is None else float(at_h[0][k]) e = None if at_h is None else float(at_h[0][k])
ratio = { ratio = {"years": float(h), "expected": e, "observed": float(observed[k]),
"years": float(h), "ratio": None, "low": None, "high": None} # fmt: skip
"expected": e,
"observed": float(observed[k]),
"ratio": None,
"low": None,
"high": None,
}
if e and observed[k] > 0 and np.isfinite(var_observed[k]): 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) se = np.sqrt(at_h[1][k] / e**2 + var_observed[k] / observed[k] ** 2)
value = e / observed[k] value = e / observed[k]
ratio |= { ratio |= {"ratio": value, "low": value * np.exp(-Z * se),
"ratio": value, "high": value * np.exp(Z * se)} # fmt: skip
"low": value * np.exp(-Z * se),
"high": value * np.exp(Z * se),
}
entry["expected_over_observed"].append(ratio) entry["expected_over_observed"].append(ratio)
groups.append(entry) groups.append(entry)
groups.sort(key=lambda g: (-g["n"], list(g["combination"].values()))) groups.sort(key=lambda g: (-g["n"], list(g["combination"].values())))
return { return {"model": spec.name, "kind": "subgroups", "bootstrap": BOOTSTRAP, "seed": SEED,
"model": spec.name, "groups": groups} # fmt: skip
"kind": "subgroups",
"bootstrap": BOOTSTRAP,
"seed": SEED,
"groups": groups,
}
def _logistic(model, test: pd.DataFrame, bins: int = 10) -> dict: def _logistic(model, test: pd.DataFrame, bins: int = 10) -> dict:
classifier, encoder = (model.named_steps["classify"], model.named_steps["encode"]) classifier, encoder = model.named_steps["classify"], model.named_steps["encode"]
names = encoder.get_feature_names_out() names = encoder.get_feature_names_out()
p = test["p"] p = test["p"]
deciles = pd.qcut(p, q=min(bins, p.nunique()), duplicates="drop") deciles = pd.qcut(p, q=min(bins, p.nunique()), duplicates="drop")
table = test.groupby(deciles, observed=True).agg( table = test.groupby(deciles, observed=True).agg(n=("y", "size"), predicted=("p", "mean"),
n=("y", "size"), predicted=("p", "mean"), observed=("y", "mean") observed=("y", "mean")) # fmt: skip
)
return { return {
"model": "logistic regression", "model": "logistic regression",
"kind": "coefficients", "kind": "coefficients",
@@ -182,5 +155,5 @@ def _logistic(model, test: pd.DataFrame, bins: int = 10) -> dict:
} }
for k, v in table.iterrows() for k, v in table.iterrows()
], ],
}, }, # fmt: skip
} }
+37 -72
View File
@@ -1,11 +1,13 @@
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Literal from typing import Literal
import numpy as np import numpy as np
import pandas as pd import pandas as pd
from sklearn.linear_model import LogisticRegression from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, roc_auc_score from sklearn.metrics import brier_score_loss, roc_auc_score
from sklearn.pipeline import Pipeline from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder from sklearn.preprocessing import OneHotEncoder
from core import cacu from core import cacu
from models.cacu import features as f from models.cacu import features as f
from models.cacu.pim import Mixture from models.cacu.pim import Mixture
@@ -19,18 +21,16 @@ OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "
def _rows(members: pd.DataFrame, risks: np.ndarray, horizons) -> pd.DataFrame: def _rows(members: pd.DataFrame, risks: np.ndarray, horizons) -> pd.DataFrame:
h = len(horizons) h = len(horizons)
scored = ~np.isnan(risks[:, :h]).any(axis=1) scored = ~np.isnan(risks[:, :h]).any(axis=1)
members, risks = (members[scored], risks[scored]) members, risks = members[scored], risks[scored]
n = len(members) n = len(members)
frame = pd.DataFrame( frame = pd.DataFrame({
{ "person_id": np.repeat(members["person_id"].to_numpy(), h),
"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),
"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),
"horizon_years": np.tile(np.asarray(horizons, dtype=float), n), "probability": risks[:, :h].ravel(),
"probability": risks[:, :h].ravel(), }) # fmt: skip
}
)
if risks.shape[1] == 3 * h: if risks.shape[1] == 3 * h:
frame["ci_low"], frame["ci_high"] = (risks[:, h : 2 * h].ravel(), risks[:, 2 * h :].ravel()) frame["ci_low"], frame["ci_high"] = risks[:, h : 2 * h].ravel(), risks[:, 2 * h :].ravel()
else: else:
frame["ci_low"] = frame["ci_high"] = np.nan frame["ci_low"] = frame["ci_high"] = np.nan
return frame[OUTPUT] return frame[OUTPUT]
@@ -65,7 +65,7 @@ class Pim:
levels[self.history["feature"]] = list(self.history["levels"]) levels[self.history["feature"]] = list(self.history["levels"])
mixture = Mixture(self.horizons, self.incidence_features, self.strata, levels) mixture = Mixture(self.horizons, self.incidence_features, self.strata, levels)
mixture.fit(train[self.features], train[["c", "l", "r"]]) mixture.fit(train[self.features], train[["c", "l", "r"]])
return (mixture, self.metrics(mixture, train, test), {"coded": coded}) return mixture, self.metrics(mixture, train, test), {"coded": coded}
def metrics(self, mixture: Mixture, train, test) -> dict: def metrics(self, mixture: Mixture, train, test) -> dict:
found = { found = {
@@ -78,11 +78,11 @@ class Pim:
} }
risks = mixture.predict(test[self.features]) risks = mixture.predict(test[self.features])
for column, horizon in enumerate(self.horizons): for column, horizon in enumerate(self.horizons):
case = (test["c"] == 1) | (test["c"] != 1) & (test["r"] <= horizon) case = (test["c"] == 1) | ((test["c"] != 1) & (test["r"] <= horizon))
free = (test["c"] == 0) & (test["l"] >= horizon) & ~case free = (test["c"] == 0) & (test["l"] >= horizon) & ~case
status = np.where(case, 1.0, np.where(free, 0.0, np.nan)) status = np.where(case, 1.0, np.where(free, 0.0, np.nan))
known = ~np.isnan(status) & ~np.isnan(risks[:, column]) known = ~np.isnan(status) & ~np.isnan(risks[:, column])
y, p, tag = (status[known], risks[known, column], f"{horizon:g}y") y, p, tag = status[known], risks[known, column], f"{horizon:g}y"
found[f"n_known_{tag}"] = int(known.sum()) found[f"n_known_{tag}"] = int(known.sum())
if known.any(): if known.any():
found[f"observed_{tag}"] = float(y.mean()) found[f"observed_{tag}"] = float(y.mean())
@@ -115,17 +115,14 @@ class Logistic:
def train(self, events: pd.DataFrame, follow_up_end) -> tuple[Pipeline, dict, dict]: def train(self, events: pd.DataFrame, follow_up_end) -> tuple[Pipeline, dict, dict]:
events = f.prepared(events) events = f.prepared(events)
found = f.index_sample(events, list(self.predictors)) found = f.index_sample(events, list(self.predictors))
outcome = f.windowed_outcome(events, self.grades, self.years, pd.Timestamp(follow_up_end)) outcome = f.windowed_outcome(events, self.grades, self.years,
pd.Timestamp(follow_up_end)) # fmt: skip
labelled = found.merge(outcome, on="person_id") labelled = found.merge(outcome, on="person_id")
labelled = labelled[labelled["known"]].reset_index(drop=True) labelled = labelled[labelled["known"]].reset_index(drop=True)
train, test = f.split(labelled, TRAIN_FRACTION) train, test = f.split(labelled, TRAIN_FRACTION)
X = list(self.predictors) X = list(self.predictors)
model = Pipeline( model = Pipeline([("encode", OneHotEncoder(handle_unknown="ignore")),
[ ("classify", LogisticRegression(max_iter=1000))]) # fmt: skip
("encode", OneHotEncoder(handle_unknown="ignore")),
("classify", LogisticRegression(max_iter=1000)),
]
)
model.fit(train[X], train["y"]) model.fit(train[X], train["y"])
p = model.predict_proba(test[X])[:, 1] p = model.predict_proba(test[X])[:, 1]
metrics = { metrics = {
@@ -139,7 +136,7 @@ class Logistic:
"positive_rate_test": float(test["y"].mean()), "positive_rate_test": float(test["y"].mean()),
"mean_probability_test": float(p.mean()), "mean_probability_test": float(p.mean()),
} }
return (model, metrics, {"labelled": labelled, "test": test.assign(p=p)}) return model, metrics, {"labelled": labelled, "test": test.assign(p=p)}
def predict(self, model: Pipeline, events: pd.DataFrame) -> pd.DataFrame: def predict(self, model: Pipeline, events: pd.DataFrame) -> pd.DataFrame:
members = f.index_sample(f.prepared(events), list(self.predictors)) members = f.index_sample(f.prepared(events), list(self.predictors))
@@ -165,60 +162,28 @@ def survival_covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataF
_REFERRAL = { _REFERRAL = {
"feature": "referral_grade", "feature": "referral_grade", "lookback_days": cacu.REFERRAL_LOOKBACK_DAYS,
"lookback_days": cacu.REFERRAL_LOOKBACK_DAYS, "levels": ["low", "high"], "low": ["ASC-US/LSIL"], "low_if_hpv_positive": ["NILM"],
"levels": ["low", "high"],
"low": ["ASC-US/LSIL"],
"low_if_hpv_positive": ["NILM"],
"high": ["High Grade"], "high": ["High Grade"],
} } # fmt: skip
MODELS = { MODELS = {
m.name: m m.name: m
for m in [ for m in [
Pim( Pim("cin2_pim", "cacu_cohort_surveillance", cacu.CIN2_PLUS, cacu.KPNC,
"cin2_pim", strata=("hpv_positive",), incidence_features=("cytology",),
"cacu_cohort_surveillance", predict_at="last_screening_cytology"),
cacu.CIN2_PLUS, Pim("cancer_pim", "cacu_cohort_surveillance", cacu.CANCER, cacu.KPNC,
cacu.KPNC, strata=("hpv_positive",), incidence_features=("cytology",),
strata=("hpv_positive",), predict_at="last_screening_cytology"),
incidence_features=("cytology",), Pim("cin2_pim_post_colposcopy", "cacu_cohort_post_colposcopy", cacu.CIN2_PLUS,
predict_at="last_screening_cytology", cacu.KPNC_3, strata=("referral_grade",),
), incidence_features=("cytology", "hpv_positive"), history=_REFERRAL),
Pim( Pim("cin2_pim_post_treatment", "cacu_cohort_post_treatment", cacu.CIN2_PLUS,
"cancer_pim", cacu.KPNC_3, strata=(), incidence_features=("cytology", "hpv_positive")),
"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), Logistic("cin2_logistic", "cacu_cohort_surveillance", cacu.CIN2_PLUS),
Spec( Spec("survival", "cacu_cohort_survival", ("age_group", "cytology", "hpv"),
"survival", survival_covariates, borders=(0, 12, 36, 60), cap_months=60,
"cacu_cohort_survival", interval_level=0.95),
("age_group", "cytology", "hpv"),
survival_covariates,
borders=(0, 12, 36, 60),
cap_months=60,
interval_level=0.95,
),
] ]
} } # fmt: skip
-1
View File
@@ -1 +0,0 @@
+1 -1
View File
@@ -3,4 +3,4 @@ from models.cama.specs import MODELS
from models.jobs import Jobs from models.jobs import Jobs
JOBS = Jobs("cama", MODELS, survival.technical_validation, survival.interpretability) JOBS = Jobs("cama", MODELS, survival.technical_validation, survival.interpretability)
train, score = (JOBS.train, JOBS.score) train, score = JOBS.train, JOBS.score
+7 -7
View File
@@ -1,7 +1,9 @@
from dataclasses import dataclass from dataclasses import dataclass
import joblib import joblib
import numpy as np import numpy as np
import pandas as pd import pandas as pd
from models.cama.recurrence import calculator, cohorts, factors, modeling, reports from models.cama.recurrence import calculator, cohorts, factors, modeling, reports
HORIZONS = modeling.HORIZONS HORIZONS = modeling.HORIZONS
@@ -37,14 +39,12 @@ class Recurrence:
def train_site(rows: pd.DataFrame, bootstrap: bool = True) -> tuple[Recurrence, dict, dict]: def train_site(rows: pd.DataFrame, bootstrap: bool = True) -> tuple[Recurrence, dict, dict]:
from models.cama.recurrence import site from models.cama.recurrence import site
return fit( return fit({"site": site.prepare(rows)}, "site", "site",
{"site": site.prepare(rows)}, "site", "site", modeling.N_BOOTSTRAP if bootstrap else {} modeling.N_BOOTSTRAP if bootstrap else {}) # fmt: skip
)
def fit( def fit(found: dict, saved: str, label: str,
found: dict, saved: str, label: str, n_bootstrap: dict[str, int] n_bootstrap: dict[str, int]) -> tuple[Recurrence, dict, dict]: # fmt: skip
) -> tuple[Recurrence, dict, dict]:
sources = list(found) sources = list(found)
try: try:
fits = modeling.fit(found, n_bootstrap) fits = modeling.fit(found, n_bootstrap)
@@ -70,4 +70,4 @@ def fit(
"recurrencia": reports.figures([r for s in sources for r in drawn[s][0]]), "recurrencia": reports.figures([r for s in sources for r in drawn[s][0]]),
} }
reports_ = {"technical_validation": technical, "interpretability": interpretability} reports_ = {"technical_validation": technical, "interpretability": interpretability}
return (model, reports.metrics(auc), reports_) return model, reports.metrics(auc), reports_
+11 -9
View File
@@ -1,8 +1,10 @@
from dataclasses import dataclass from dataclasses import dataclass
import numpy as np import numpy as np
import pandas as pd import pandas as pd
import statsmodels.api as sm import statsmodels.api as sm
from joblib import Parallel, delayed from joblib import Parallel, delayed
from models import curves from models import curves
from models.cama.recurrence.modeling import ESS, HORIZONS, SEED, CohortFit, logit from models.cama.recurrence.modeling import ESS, HORIZONS, SEED, CohortFit, logit
@@ -24,12 +26,12 @@ class Risk:
fitted: CohortFit fitted: CohortFit
def __post_init__(self): def __post_init__(self):
frame, covariates = (self.fitted.cohort.frame, self.fitted.cohort.covariates) frame, covariates = self.fitted.cohort.frame, self.fitted.cohort.covariates
self.n = len(frame) self.n = len(frame)
self.X = pd.get_dummies(frame[covariates], drop_first=True).astype(float) 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.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.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()) self.time, self.event = frame["tiempo_meses"].to_numpy(), frame["evento"].to_numpy()
def _key(self, chosen, rows) -> np.ndarray: def _key(self, chosen, rows) -> np.ndarray:
key = np.zeros(len(rows), dtype=np.int64) key = np.zeros(len(rows), dtype=np.int64)
@@ -38,10 +40,10 @@ class Risk:
return key return key
def _combined(self, rows, horizon) -> np.ndarray | None: def _combined(self, rows, horizon) -> np.ndarray | None:
t, e = (self.time[rows], self.event[rows]) t, e = self.time[rows], self.event[rows]
recurred = (e == 1) & (t <= horizon) recurred = (e == 1) & (t <= horizon)
known = recurred | (t > horizon) known = recurred | (t > horizon)
train, y = (rows[known], recurred[known].astype(int)) train, y = rows[known], recurred[known].astype(int)
split = self.fitted.horizons[horizon].split split = self.fitted.horizons[horizon].split
p_lr = p_hbn = np.full(self.n, y.mean()) p_lr = p_hbn = np.full(self.n, y.mean())
if split.terms: if split.terms:
@@ -101,15 +103,15 @@ def calculator(fitted: CohortFit) -> tuple[list[dict], list[dict]]:
jobs = [delayed(_curves)(months[m], event[m], int(months[m].max())) for m in drawn.values()] 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] jobs += [delayed(risk.mean_risk)(rows, found) for rows in samples]
done = Parallel(n_jobs=-1)(jobs) done = Parallel(n_jobs=-1)(jobs)
fitted_curves, (point, *resampled) = (done[: len(drawn)], done[len(drawn) :]) fitted_curves, (point, *resampled) = done[: len(drawn)], done[len(drawn) :]
replicas = [r for r in resampled if r is not None] replicas = [r for r in resampled if r is not None]
records, rows = ([], []) records, rows = [], []
for (name, mask), drawn_curves in zip(drawn.items(), fitted_curves, strict=True): for (name, mask), drawn_curves in zip(drawn.items(), fitted_curves, strict=True):
free = 1 - point[name] free = 1 - point[name]
risks = np.array([r[name] for r in replicas]) risks = np.array([r[name] for r in replicas])
low, high = 1 - np.nanpercentile(risks, [97.5, 2.5], axis=0) 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())) observed, n, events = int(months[mask].max()), int(mask.sum()), int(event[mask].sum())
km, grid = (drawn_curves["km"], drawn_curves["grid"].tolist()) km, grid = drawn_curves["km"], drawn_curves["grid"].tolist()
records.append( records.append(
{ {
"cohorte": source, "cohorte": source,
@@ -153,4 +155,4 @@ def calculator(fitted: CohortFit) -> tuple[list[dict], list[dict]]:
"replicas_bootstrap": len(replicas), "replicas_bootstrap": len(replicas),
} }
) )
return (records, rows) return records, rows
+7 -5
View File
@@ -1,14 +1,16 @@
from dataclasses import dataclass from dataclasses import dataclass
import pandas as pd import pandas as pd
from scipy.stats.contingency import association from scipy.stats.contingency import association
UNKNOWN = "Desconocido" UNKNOWN = "Desconocido"
V_MAX = 0.8 V_MAX = 0.80
DAYS_PER_MONTH = 30.4375 DAYS_PER_MONTH = 30.4375
HORIZONS = (12, 36, 60) HORIZONS = (12, 36, 60)
AGE = ([0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"]) AGE = ([0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"])
SIZE = ([0, 20.01, 50.01, 10000.0], ["<=20 mm", "21-50 mm", ">50 mm"]) SIZE = ([0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"])
NODES = ([0, 1, 4, 1000.0], ["0", "1-3", "4+"]) NODES = ([0, 1, 4, 1e3], ["0", "1-3", "4+"])
GRADES = {"1": "1", "2": "2", "3": "3"} GRADES = {"1": "1", "2": "2", "3": "3"}
@@ -65,8 +67,8 @@ class Cohort:
def at_horizon(frame: pd.DataFrame, horizon: int) -> pd.DataFrame: def at_horizon(frame: pd.DataFrame, horizon: int) -> pd.DataFrame:
t, event = (frame["tiempo_meses"], frame["evento"] == 1) t, event = frame["tiempo_meses"], frame["evento"] == 1
found = frame[event & (t <= horizon) | (t > horizon)].reset_index(drop=True) found = frame[(event & (t <= horizon)) | (t > horizon)].reset_index(drop=True)
found["y"] = ((found["evento"] == 1) & (found["tiempo_meses"] <= horizon)).astype(int) found["y"] = ((found["evento"] == 1) & (found["tiempo_meses"] <= horizon)).astype(int)
return found return found
+16 -20
View File
@@ -1,6 +1,8 @@
import warnings import warnings
import numpy as np import numpy as np
import pandas as pd import pandas as pd
from models import factors as rated from models import factors as rated
from models.cama.recurrence.calculator import masks from models.cama.recurrence.calculator import masks
from models.cama.recurrence.cohorts import UNKNOWN, at_horizon from models.cama.recurrence.cohorts import UNKNOWN, at_horizon
@@ -41,18 +43,17 @@ DESCRIBING = rated.DESCRIBING
def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.DataFrame: def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.DataFrame:
cohort = fitted.cohort cohort = fitted.cohort
frame = at_horizon(cohort.frame, horizon) frame = at_horizon(cohort.frame, horizon)
data, y = (frame[cohort.covariates].astype(str), frame["y"].to_numpy()) data, y = frame[cohort.covariates].astype(str), frame["y"].to_numpy()
reference = {v: data[v].value_counts().idxmax() for v in cohort.covariates} reference = {v: data[v].value_counts().idxmax() for v in cohort.covariates}
t, everyone = (cohort.frame["tiempo_meses"].to_numpy(), cohort.frame[cohort.covariates]) t, everyone = cohort.frame["tiempo_meses"].to_numpy(), cohort.frame[cohort.covariates]
months = np.floor(np.minimum(t, horizon + 1)).astype(int) months = np.floor(np.minimum(t, horizon + 1)).astype(int)
event = ((cohort.frame["evento"] == 1) & (t <= horizon)).to_numpy() event = ((cohort.frame["evento"] == 1) & (t <= horizon)).to_numpy()
def complete(table, variables): def complete(table, variables):
return rated.complete( return rated.complete(table, variables, reference, everyone, months, event, horizon,
table, variables, reference, everyone, months, event, horizon, SURVIVAL SURVIVAL) # fmt: skip
)
intrinsic, treatment = (cohort.intrinsic, cohort.treatment) intrinsic, treatment = cohort.intrinsic, cohort.treatment
tab = complete(rated.odds_ratios(data, y, intrinsic, reference, OR), intrinsic) tab = complete(rated.odds_ratios(data, y, intrinsic, reference, OR), intrinsic)
hz = fitted.horizons[horizon] hz = fitted.horizons[horizon]
tab["freq_seleccion_bootstrap"] = tab["variable"].map( tab["freq_seleccion_bootstrap"] = tab["variable"].map(
@@ -69,9 +70,9 @@ def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.Data
tr = complete( tr = complete(
tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)], treatment tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)], treatment
) )
tr["tipo"], tr["clasificacion"] = ("tratamiento", TREATMENT_CLASS) tr["tipo"], tr["clasificacion"] = "tratamiento", TREATMENT_CLASS
tab = pd.concat([tab, tr], ignore_index=True) tab = pd.concat([tab, tr], ignore_index=True)
tab["cohorte"], tab["horizonte_meses"] = (cohort.source, horizon) tab["cohorte"], tab["horizonte_meses"] = cohort.source, horizon
return tab return tab
@@ -91,23 +92,18 @@ def risk_factors(fitted: CohortFit, selection: dict | None = None) -> pd.DataFra
def scenario_summary(fitted: CohortFit, factors: pd.DataFrame) -> list[dict]: def scenario_summary(fitted: CohortFit, factors: pd.DataFrame) -> list[dict]:
frame, source = (fitted.cohort.frame, fitted.cohort.source) frame, source = fitted.cohort.frame, fitted.cohort.source
scenarios = fitted.cohort.scenarios scenarios = fitted.cohort.scenarios
found = rated.classified(factors[factors["cohorte"] == source]) found = rated.classified(factors[factors["cohorte"] == source])
rows = [] rows = []
for name, mask in masks(frame, scenarios).items(): for name, mask in masks(frame, scenarios).items():
if not mask.any() or found.empty: if not mask.any() or found.empty:
continue continue
definition = "; ".join((f"{v} = {' / '.join(c)}" for v, c in scenarios[name].items())) definition = "; ".join(f"{v} = {' / '.join(c)}" for v, c in scenarios[name].items())
for h in fitted.horizons: for h in fitted.horizons:
rows.append( rows.append({
{ "cohorte": source, "escenario": name, "definicion": definition,
"cohorte": source, "n_escenario": int(mask.sum()), "horizonte_meses": h,
"escenario": name, **rated.scenario_row(frame, mask, found[found["horizonte_meses"] == h]),
"definicion": definition, }) # fmt: skip
"n_escenario": int(mask.sum()),
"horizonte_meses": h,
**rated.scenario_row(frame, mask, found[found["horizonte_meses"] == h]),
}
)
return rows return rows
+18 -16
View File
@@ -1,5 +1,6 @@
import warnings import warnings
from dataclasses import dataclass, field from dataclasses import dataclass, field
import numpy as np import numpy as np
import pandas as pd import pandas as pd
import statsmodels.api as sm import statsmodels.api as sm
@@ -9,6 +10,7 @@ from lifelines.utils import concordance_index
from pgmpy.structure_score import BDeu from pgmpy.structure_score import BDeu
from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split from sklearn.model_selection import train_test_split
from models.cama.recurrence.cohorts import HORIZONS, Cohort, at_horizon from models.cama.recurrence.cohorts import HORIZONS, Cohort, at_horizon
from models.factors import variable_of from models.factors import variable_of
@@ -16,7 +18,7 @@ SEED = 42
TEST_SIZE = 0.3 TEST_SIZE = 0.3
ESS = 10 ESS = 10
MAX_PARENTS = 6 MAX_PARENTS = 6
ALPHA_PREFILTER, ALPHA_IN, ALPHA_OUT = (0.1, 0.1, 0.15) ALPHA_PREFILTER, ALPHA_IN, ALPHA_OUT = 0.10, 0.10, 0.15
MAX_STEPS = 200 MAX_STEPS = 200
COX_PENALIZER = 0.05 COX_PENALIZER = 0.05
COX_MIN_COUNT = 10 COX_MIN_COUNT = 10
@@ -41,13 +43,13 @@ def logit(y, X: pd.DataFrame, has_constant: str = "skip"):
def stepwise(X: pd.DataFrame, y) -> list[str]: def stepwise(X: pd.DataFrame, y) -> list[str]:
included = [] included = []
for _ in range(MAX_STEPS): for _ in range(MAX_STEPS):
changed, best, best_p = (False, None, ALPHA_IN) changed, best, best_p = False, None, ALPHA_IN
for c in X.columns: for c in X.columns:
if c in included: if c in included:
continue continue
m = logit(y, X[included + [c]]) m = logit(y, X[included + [c]])
if m is not None and m.pvalues[c] < best_p: if m is not None and m.pvalues[c] < best_p:
best, best_p = (c, m.pvalues[c]) best, best_p = c, m.pvalues[c]
if best is not None: if best is not None:
included.append(best) included.append(best)
changed = True changed = True
@@ -73,10 +75,10 @@ def lr(train: pd.DataFrame, test: pd.DataFrame, covariates: list[str]):
] ]
terms = stepwise(X_train[candidates], y) if candidates else [] terms = stepwise(X_train[candidates], y) if candidates else []
if not terms: if not terms:
return ([], np.full(len(test), y.mean())) return [], np.full(len(test), y.mean())
m = logit(y, X_train[terms]) m = logit(y, X_train[terms])
X_test = sm.add_constant(X.loc[test.index, terms], has_constant="add") X_test = sm.add_constant(X.loc[test.index, terms], has_constant="add")
return (terms, m.predict(X_test).to_numpy()) return terms, m.predict(X_test).to_numpy()
def bn_table(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame: def bn_table(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame:
@@ -87,13 +89,13 @@ def bn_table(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame:
def parents(table: pd.DataFrame, covariates: list[str]) -> list[str]: def parents(table: pd.DataFrame, covariates: list[str]) -> list[str]:
score = BDeu(table, equivalent_sample_size=ESS) score = BDeu(table, equivalent_sample_size=ESS)
chosen, current = ([], score.local_score("outcome", ())) chosen, current = [], score.local_score("outcome", ())
while len(chosen) < MAX_PARENTS: while len(chosen) < MAX_PARENTS:
best, gain = (None, 0.0) best, gain = None, 0.0
for c in [c for c in covariates if c not in chosen]: for c in [c for c in covariates if c not in chosen]:
g = score.local_score("outcome", (*chosen, c)) - current g = score.local_score("outcome", (*chosen, c)) - current
if g > gain: if g > gain:
best, gain = (c, g) best, gain = c, g
if best is None: if best is None:
break break
chosen.append(best) chosen.append(best)
@@ -106,7 +108,7 @@ def cpt(table: pd.DataFrame, chosen: list[str], q: int | None = None) -> dict[tu
a = ESS / (2 * q) a = ESS / (2 * q)
counts = table.groupby(chosen)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size") counts = table.groupby(chosen)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size")
return { return {
k if isinstance(k, tuple) else (k,): float((r.n1 + a) / (r.n + 2 * a)) (k if isinstance(k, tuple) else (k,)): float((r.n1 + a) / (r.n + 2 * a))
for k, r in counts.iterrows() for k, r in counts.iterrows()
} }
@@ -132,7 +134,7 @@ def split_fit(frame: pd.DataFrame, covariates: list[str], seed: int = SEED) -> S
frame, test_size=TEST_SIZE, random_state=seed, stratify=frame["y"] frame, test_size=TEST_SIZE, random_state=seed, stratify=frame["y"]
) )
terms, p_lr = lr(train, test, covariates) terms, p_lr = lr(train, test, covariates)
bn_train, bn_test = (bn_table(train, covariates), bn_table(test, covariates)) bn_train, bn_test = bn_table(train, covariates), bn_table(test, covariates)
chosen = parents(bn_train, covariates) chosen = parents(bn_train, covariates)
p_hbn = hbn(bn_train, bn_test, chosen) 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)) return Split(terms, chosen, roc_auc_score(test["y"], p_lr), roc_auc_score(test["y"], p_hbn))
@@ -204,21 +206,21 @@ def fit(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict[str, Co
] ]
tasks.append(((s, h, "split"), split_fit, (frame, cohorts[s].covariates))) tasks.append(((s, h, "split"), split_fit, (frame, cohorts[s].covariates)))
tasks += [((s, None, "cox"), c_index, (c,)) for s, c in cohorts.items()] 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))) 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)) results = dict(zip([key for key, _, _ in reversed(tasks)], done, strict=True))
out = {} out = {}
for s, cohort in cohorts.items(): for s, cohort in cohorts.items():
horizons = {} horizons = {}
for h in HORIZONS: for h in HORIZONS:
frame = frames[s, h] frame = frames[(s, h)]
reps = [results[s, h, b] for b in range(n_bootstrap.get(s, 0))] reps = [results[(s, h, b)] for b in range(n_bootstrap.get(s, 0))]
horizons[h] = Horizon( horizons[h] = Horizon(
len(frame), len(frame),
int(frame["y"].sum()), int(frame["y"].sum()),
results[s, h, "split"], results[(s, h, "split")],
[r for r in reps if r is not None], [r for r in reps if r is not None],
) )
out[s] = CohortFit(cohort, results[s, None, "cox"], horizons) out[s] = CohortFit(cohort, results[(s, None, "cox")], horizons)
return out return out
@@ -226,7 +228,7 @@ def tables(fitted: CohortFit) -> dict[int, dict]:
found = {} found = {}
for h, hz in fitted.horizons.items(): for h, hz in fitted.horizons.items():
frame = at_horizon(fitted.cohort.frame, h) frame = at_horizon(fitted.cohort.frame, h)
covariates, terms, chosen = (fitted.cohort.covariates, hz.split.terms, hz.split.parents) covariates, terms, chosen = fitted.cohort.covariates, hz.split.terms, hz.split.parents
prior = float(frame["y"].mean()) prior = float(frame["y"].mean())
entry = { entry = {
"lr_prior": prior, "lr_prior": prior,
+15 -7
View File
@@ -1,5 +1,6 @@
import numpy as np import numpy as np
import pandas as pd import pandas as pd
from models.cama.recurrence.calculator import MIN_EVENTS, RESAMPLES from models.cama.recurrence.calculator import MIN_EVENTS, RESAMPLES
from models.cama.recurrence.cohorts import UNKNOWN, Cohort, unknown_shares from models.cama.recurrence.cohorts import UNKNOWN, Cohort, unknown_shares
from models.cama.recurrence.modeling import ( from models.cama.recurrence.modeling import (
@@ -36,7 +37,7 @@ def table(rows, columns=None) -> dict:
def auc_rows(fitted: CohortFit) -> list[dict]: def auc_rows(fitted: CohortFit) -> list[dict]:
source, rows = (fitted.cohort.source, []) source, rows = fitted.cohort.source, []
for h, hz in fitted.horizons.items(): for h, hz in fitted.horizons.items():
for j, (name, internal) in enumerate((("LR", hz.split.auc_lr), ("HBN", hz.split.auc_hbn))): for j, (name, internal) in enumerate((("LR", hz.split.auc_lr), ("HBN", hz.split.auc_hbn))):
aucs = hz.aucs[:, j] aucs = hz.aucs[:, j]
@@ -68,7 +69,7 @@ def auc_rows(fitted: CohortFit) -> list[dict]:
"AUC_validacion_interna": fitted.c_index, "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] 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]: def metrics(auc: list[dict]) -> dict[str, float]:
@@ -99,11 +100,13 @@ def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
**next(iter(cohorts.values())).sampling, **next(iter(cohorts.values())).sampling,
}, },
"DATOS_FALTANTES": { "DATOS_FALTANTES": {
"criterio": f"el dato faltante es una categoría más («{UNKNOWN}»); no se imputa ni se descarta", "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()}, "desconocidos_por_covariable": {s: unknown_shares(c) for s, c in cohorts.items()},
}, },
"METODO_ANALITICO": { "METODO_ANALITICO": {
"modelos": "regresión logística con selección stepwise y red bayesiana con padres del desenlace por BDeu, uno por horizonte", "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), "horizontes_meses": list(HORIZONS),
"alfa_entrada": ALPHA_IN, "alfa_entrada": ALPHA_IN,
"alfa_salida": ALPHA_OUT, "alfa_salida": ALPHA_OUT,
@@ -114,11 +117,16 @@ def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
}, },
"BALANCE_CLASES": { "BALANCE_CLASES": {
"aplica": False, "aplica": False,
"motivo": "cada horizonte usa las pacientes con recaída hasta el horizonte o libres de ella después; no se rebalancea", "motivo": "cada horizonte usa las pacientes con recaída hasta el horizonte o libres "
"de ella después; no se rebalancea",
}, },
"CONFIANZA_SALIDA": { "CONFIANZA_SALIDA": {
"salida": "probabilidad libre de recaída por escenario y horizonte con IC 95 % por bootstrap", "salida": "probabilidad libre de recaída por escenario y horizonte con IC 95 % por "
"replicas": {**{s: n_bootstrap.get(s, 0) for s in cohorts}, "calculadora": RESAMPLES}, "bootstrap",
"replicas": {
**{s: n_bootstrap.get(s, 0) for s in cohorts},
"calculadora": RESAMPLES,
},
"eventos_minimos_por_escenario": MIN_EVENTS, "eventos_minimos_por_escenario": MIN_EVENTS,
}, },
} }
+26 -48
View File
@@ -1,60 +1,41 @@
import numpy as np import numpy as np
import pandas as pd import pandas as pd
from models.cama.recurrence import cohorts from models.cama.recurrence import cohorts
from models.cama.recurrence.cohorts import UNKNOWN, Cohort, _band, _text, collinear from models.cama.recurrence.cohorts import UNKNOWN, Cohort, _band, _text, collinear
RESULT_DAYS = 30 RESULT_DAYS = 30
TREATMENT_DAYS = 365 TREATMENT_DAYS = 365
KI67_HIGH = 20.0 KI67_HIGH = 20.0
STAGE_GROUP = { STAGE_GROUP = {"0": "0", "I": "I", "IA": "I", "IB": "I", "II": "II", "IIA": "II", "IIB": "II",
"0": "0", "III": "III", "IIIA": "III", "IIIB": "III", "IIIC": "III", "IV": "IV"} # fmt: skip
"I": "I",
"IA": "I",
"IB": "I",
"II": "II",
"IIA": "II",
"IIB": "II",
"III": "III",
"IIIA": "III",
"IIIB": "III",
"IIIC": "III",
"IV": "IV",
}
RECEPTOR = {"positive": "Positive", "negative": "Negative"} RECEPTOR = {"positive": "Positive", "negative": "Negative"}
SURGERY = {"breast_conserving_surgery": "Lumpectomy", "mastectomy": "Mastectomy"} SURGERY = {"breast_conserving_surgery": "Lumpectomy", "mastectomy": "Mastectomy"}
TREATMENTS = { TREATMENTS = {"Quimioterapia": "chemotherapy", "Radioterapia": "radiotherapy",
"Quimioterapia": "chemotherapy", "Hormonoterapia": "hormone_therapy", "AntiHER2": "anti_her2"} # fmt: skip
"Radioterapia": "radiotherapy",
"Hormonoterapia": "hormone_therapy",
"AntiHER2": "anti_her2",
}
FIXED = ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"] FIXED = ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"]
TREATMENT = ["Cirugia", *TREATMENTS] TREATMENT = ["Cirugia", *TREATMENTS]
SCENARIOS = { SCENARIOS = {
"Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": { "Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
"Subtipo_clinico": ["Luminal A"], "Subtipo_clinico": ["Luminal A"], "Ganglios_positivos": ["0"],
"Ganglios_positivos": ["0"], "Tamano_tumor": ["<=20 mm"]},
"Tamano_tumor": ["<=20 mm"],
},
"Ganglios 4+": {"Ganglios_positivos": ["4+"]}, "Ganglios 4+": {"Ganglios_positivos": ["4+"]},
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]}, "Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
"< 45 años": {"Edad": ["<45"]}, "< 45 años": {"Edad": ["<45"]},
"≥ 75 años": {"Edad": ["75+"]}, "≥ 75 años": {"Edad": ["75+"]},
"Basal-like": {"Subtipo_clinico": ["Basal-like"]}, "Basal-like": {"Subtipo_clinico": ["Basal-like"]},
"HER2+ (luminal B HER2+ o no luminal)": { "HER2+ (luminal B HER2+ o no luminal)": {
"Subtipo_clinico": ["Luminal B HER2+", "Non-luminal HER2+"] "Subtipo_clinico": ["Luminal B HER2+", "Non-luminal HER2+"]},
},
"Luminal B HER2−": {"Subtipo_clinico": ["Luminal B HER2-"]}, "Luminal B HER2−": {"Subtipo_clinico": ["Luminal B HER2-"]},
"Luminal · 1-3 ganglios · lumpectomía": { "Luminal · 1-3 ganglios · lumpectomía": {
"Subtipo_clinico": ["Luminal A", "Luminal B HER2-"], "Subtipo_clinico": ["Luminal A", "Luminal B HER2-"], "Ganglios_positivos": ["1-3"],
"Ganglios_positivos": ["1-3"], "Cirugia": ["Lumpectomy"]},
"Cirugia": ["Lumpectomy"],
},
"Grado 3": {"Grado_histologico": ["3"]}, "Grado 3": {"Grado_histologico": ["3"]},
} } # fmt: skip
MIN_PER_CLASS = 10 MIN_PER_CLASS = 10
SAMPLING = { 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", "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)", "origen": "la sede (sus propias pacientes)",
} }
@@ -73,9 +54,8 @@ def subtype(er, pr, her2, ki67) -> str:
def frame(events: pd.DataFrame, as_of) -> pd.DataFrame: def frame(events: pd.DataFrame, as_of) -> pd.DataFrame:
events = events.assign( events = events.assign(date=pd.to_datetime(events["date"]),
date=pd.to_datetime(events["date"]), index_date=pd.to_datetime(events["index_date"]) index_date=pd.to_datetime(events["index_date"])) # fmt: skip
)
members = events.groupby("person_id")["index_date"].first() members = events.groupby("person_id")["index_date"].first()
days = (events["date"] - events["index_date"]).dt.days days = (events["date"] - events["index_date"]).dt.days
cut = pd.Timestamp(as_of) cut = pd.Timestamp(as_of)
@@ -89,16 +69,16 @@ def frame(events: pd.DataFrame, as_of) -> pd.DataFrame:
out["tiempo_meses"] = (end - members).dt.days / cohorts.DAYS_PER_MONTH out["tiempo_meses"] = (end - members).dt.days / cohorts.DAYS_PER_MONTH
out["evento"] = first_recurrence.reindex(members.index).notna().astype(int) out["evento"] = first_recurrence.reindex(members.index).notna().astype(int)
out["muerte_sin_recaida"] = (death.notna() & (out["evento"] == 0)).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"]) 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() 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() 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() birth = events[events["type"] == "birth"].groupby("person_id")["date"].min()
age = (members - birth.reindex(members.index)).dt.days / 365.25 age = (members - birth.reindex(members.index)).dt.days / 365.25
out["Edad"] = _band(age, *cohorts.AGE) out["Edad"] = _band(age, *cohorts.AGE)
out["Tamano_tumor"] = _band(number("size_mm").reindex(members.index), *cohorts.SIZE) out["Tamano_tumor"] = _band(number("size_mm").reindex(members.index), *cohorts.SIZE)
out["Ganglios_positivos"] = _band( out["Ganglios_positivos"] = _band(number("positive_nodes").reindex(members.index),
number("positive_nodes").reindex(members.index), *cohorts.NODES *cohorts.NODES) # fmt: skip
)
out["Grado_histologico"] = _text(code("grade").reindex(members.index).map(cohorts.GRADES)) 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")} receptors = {k: code(k).reindex(members.index) for k in ("er", "pr", "her2")}
ki67 = number("ki67_pct").reindex(members.index) ki67 = number("ki67_pct").reindex(members.index)
@@ -107,10 +87,8 @@ def frame(events: pd.DataFrame, as_of) -> pd.DataFrame:
out["HER2"] = _text(receptors["her2"].map(RECEPTOR)) out["HER2"] = _text(receptors["her2"].map(RECEPTOR))
high = np.where(ki67 < KI67_HIGH, f"<{KI67_HIGH:g}%", f">={KI67_HIGH:g}%") 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["Ki67"] = _text(pd.Series(np.where(ki67.isna(), None, high), index=members.index))
out["Subtipo_clinico"] = [ out["Subtipo_clinico"] = [subtype(*a) for a in zip(
subtype(*a) receptors["er"], receptors["pr"], receptors["her2"], ki67, strict=True)] # fmt: skip
for a in zip(receptors["er"], receptors["pr"], receptors["her2"], ki67, strict=True)
]
out["Tipo_histologico"] = _text(code("histologic_type").reindex(members.index)) out["Tipo_histologico"] = _text(code("histologic_type").reindex(members.index))
out["Estadio_clinico"] = _text(code("stage").reindex(members.index).map(STAGE_GROUP)) out["Estadio_clinico"] = _text(code("stage").reindex(members.index).map(STAGE_GROUP))
course = events[(events["type"] == "treatment") & days.between(0, TREATMENT_DAYS)] course = events[(events["type"] == "treatment") & days.between(0, TREATMENT_DAYS)]
@@ -129,7 +107,8 @@ def scarce(rows: pd.DataFrame) -> str | None:
y = cohorts.at_horizon(rows, h)["y"] y = cohorts.at_horizon(rows, h)["y"]
fewest = min(int(y.sum()), int((y == 0).sum())) fewest = min(int(y.sum()), int((y == 0).sum()))
if fewest < MIN_PER_CLASS: if fewest < MIN_PER_CLASS:
return f"{int(y.sum())} recurred and {int((y == 0).sum())} free of it at {h} months, {MIN_PER_CLASS} of each needed" 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 return None
@@ -138,6 +117,5 @@ def prepare(rows: pd.DataFrame) -> Cohort:
dropped = collinear(rows, [c for c in covariates if c not in TREATMENT]) dropped = collinear(rows, [c for c in covariates if c not in TREATMENT])
kept = [c for c in covariates if c not in dropped] kept = [c for c in covariates if c not in dropped]
treatment = [c for c in TREATMENT if c in kept] treatment = [c for c in TREATMENT if c in kept]
return Cohort( return Cohort("site", rows[FIXED + kept + dropped], kept, treatment, dropped, "Sitio",
"site", rows[FIXED + kept + dropped], kept, treatment, dropped, "Sitio", SCENARIOS, SAMPLING SCENARIOS, SAMPLING) # fmt: skip
)
+22 -47
View File
@@ -1,28 +1,19 @@
from dataclasses import dataclass, field from dataclasses import dataclass, field
from datetime import date from datetime import date
import pandas as pd import pandas as pd
from models.survival import DAYS_PER_YEAR, OUTPUT, SCENARIO_SEPARATOR, Spec, age_group, band from models.survival import DAYS_PER_YEAR, OUTPUT, SCENARIO_SEPARATOR, Spec, age_group, band
RESULTS = ("histologic_type", "grade", "er", "pr", "her2") RESULTS = ("histologic_type", "grade", "er", "pr", "her2")
RESULT_DAYS = 30 RESULT_DAYS = 30
TREATMENT_DAYS = 365 TREATMENT_DAYS = 365
STAGE_GROUP = { STAGE_GROUP = {"0": "0", "I": "I", "IA": "I", "IB": "I", "II": "II", "IIA": "II", "IIB": "II",
"0": "0", "III": "III", "IIIA": "III", "IIIB": "III", "IIIC": "III", "IV": "IV"} # fmt: skip
"I": "I",
"IA": "I",
"IB": "I",
"II": "II",
"IIA": "II",
"IIB": "II",
"III": "III",
"IIIA": "III",
"IIIB": "III",
"IIIC": "III",
"IV": "IV",
}
SURGERY = ("breast_conserving_surgery", "mastectomy") 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")) 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) TRIPLE_NEG = (("er", "==", "negative"), ("pr", "==", "negative"), HER2_NEG)
CONSERVING = ("surgery", "==", "breast_conserving_surgery") CONSERVING = ("surgery", "==", "breast_conserving_surgery")
@@ -43,23 +34,15 @@ SCENARIOS = {
"≥ 75 años": (_older(75),), "≥ 75 años": (_older(75),),
"< 45 años": (_younger(45),), "< 45 años": (_younger(45),),
"Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora": ( "Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora": (
_younger(45), _younger(45), HER2_NEG, STAGE_0_II, CONSERVING),
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_NEG, STAGE_0_II, CONSERVING),
"HER2+ · estadio 0–II · cirugía conservadora": (HER2_POS, 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) · estadio 0–II": (_younger(45), STAGE_0_II),
"Jóvenes (<45) · HER2−": (_younger(45), HER2_NEG), "Jóvenes (<45) · HER2−": (_younger(45), HER2_NEG),
"Triple negativo (HR−/HER2−) · estadio 0–II": (*TRIPLE_NEG, STAGE_0_II), "Triple negativo (HR−/HER2−) · estadio 0–II": (*TRIPLE_NEG, STAGE_0_II),
"≥ 65 años · HER2− · estadio 0–II · cirugía conservadora": ( "≥ 65 años · HER2− · estadio 0–II · cirugía conservadora": (
_older(65), _older(65), HER2_NEG, STAGE_0_II, CONSERVING),
HER2_NEG, } # fmt: skip
STAGE_0_II,
CONSERVING,
),
}
def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame: def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
@@ -71,10 +54,8 @@ def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
near = events[days.between(-7, RESULT_DAYS)].sort_values(["date", "source_id"]) near = events[days.between(-7, RESULT_DAYS)].sort_values(["date", "source_id"])
for kind in RESULTS: for kind in RESULTS:
found[kind] = near[near["type"] == kind].groupby("person_id")["value_code"].first() found[kind] = near[near["type"] == kind].groupby("person_id")["value_code"].first()
for name, kind, cuts in ( for name, kind, cuts in (("ki67_group", "ki67_pct", (14, 20)),
("ki67_group", "ki67_pct", (14, 20)), ("size_group", "size_mm", (20, 50))): # fmt: skip
("size_group", "size_mm", (20, 50)),
):
value = near[near["type"] == kind].groupby("person_id")["value_num"].first() value = near[near["type"] == kind].groupby("person_id")["value_num"].first()
found[name] = band(value.reindex(found.index), list(cuts)) found[name] = band(value.reindex(found.index), list(cuts))
stage = near[near["type"] == "stage"].groupby("person_id")["value_code"].first() stage = near[near["type"] == "stage"].groupby("person_id")["value_code"].first()
@@ -112,24 +93,15 @@ class SiteRecurrence:
found = model.predict(members) found = model.predict(members)
index = events.groupby("person_id")["index_date"].first() index = events.groupby("person_id")["index_date"].first()
masks = calculator.masks(members, site.SCENARIOS) masks = calculator.masks(members, site.SCENARIOS)
named = [ named = [SCENARIO_SEPARATOR.join(n for n, m in masks.items() if m[i]) or None
SCENARIO_SEPARATOR.join((n for n, m in masks.items() if m[i])) or None for i in range(len(members))] # fmt: skip
for i in range(len(members))
]
rows = [] rows = []
for i, person in enumerate(members["paciente"]): for i, person in enumerate(members["paciente"]):
for h in model.horizons: for h in model.horizons:
rows.append( rows.append({"person_id": person,
{ "index_date": pd.Timestamp(index[person]).date(),
"person_id": person, "horizon_years": h / 12, "probability": found[f"recurrence_{h}m"][i],
"index_date": pd.Timestamp(index[person]).date(), "ci_low": None, "ci_high": None, "scenarios": named[i]}) # fmt: skip
"horizon_years": h / 12,
"probability": found[f"recurrence_{h}m"][i],
"ci_low": None,
"ci_high": None,
"scenarios": named[i],
}
)
return pd.DataFrame(rows, columns=OUTPUT) return pd.DataFrame(rows, columns=OUTPUT)
@@ -162,7 +134,10 @@ MODELS = {
scenario_columns=("age",), scenario_columns=("age",),
treatments=("surgery", "chemotherapy", "radiotherapy"), treatments=("surgery", "chemotherapy", "radiotherapy"),
notes=( notes=(
f"Tratamiento: el primer curso (convención de SEER), lo recibido en los {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.", 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"), "recurrence": SiteRecurrence("recurrence"),
-41
View File
@@ -1,41 +0,0 @@
import os
from collections.abc import Callable, Iterable
from importlib.util import find_spec
from typing import Any
from joblib import Parallel, delayed
def jobs() -> int:
return int(os.environ.get("BATCH_JOBS", "-1"))
def run(task: Callable, arguments: Iterable[tuple]) -> list[Any]:
if find_spec("distributed") is None:
return Parallel(n_jobs=jobs())((delayed(task)(*a) for a in arguments))
from distributed import Client, LocalCluster, as_completed
address = os.environ.get("DASK_SCHEDULER_ADDRESS")
where = address or LocalCluster(threads_per_worker=1, dashboard_address=None)
try:
with Client(where) as client:
limit = jobs() if jobs() > 0 else sum(client.nthreads().values())
pending = iter(enumerate(arguments))
results: dict[int, Any] = {}
order: dict[Any, int] = {}
def submit() -> Any | None:
if (item := next(pending, None)) is None:
return None
future = client.submit(task, *item[1], pure=False)
order[future] = item[0]
return future
running = as_completed([f for f in (submit() for _ in range(limit)) if f])
for done in running:
results[order.pop(done)] = done.result()
if (future := submit()) is not None:
running.add(future)
return [results[i] for i in range(len(results))]
finally:
if not address:
where.close()
+19 -23
View File
@@ -4,16 +4,16 @@ from scipy.special import beta as beta_function
from scipy.special import betainc, gammaln from scipy.special import betainc, gammaln
Z = 1.96 Z = 1.96
INVALID = 1000000000000.0 INVALID = 1e12
def life_table(months: np.ndarray, event: np.ndarray, length: int = 0): def life_table(months: np.ndarray, event: np.ndarray, length: int = 0):
months, event = (np.asarray(months, int), np.asarray(event, bool)) months, event = np.asarray(months, int), np.asarray(event, bool)
length = max(length, int(months.max()) + 2) length = max(length, int(months.max()) + 2)
d = np.bincount(months[event], minlength=length) d = np.bincount(months[event], minlength=length)
c = 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]]) at_risk = len(months) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
return (d, c, at_risk) return d, c, at_risk
def kaplan_meier(months, event, until: int): def kaplan_meier(months, event, until: int):
@@ -34,7 +34,7 @@ def kaplan_meier(months, event, until: int):
def _nll(survival, d, c) -> float: def _nll(survival, d, c) -> float:
T = len(d) T = len(d)
both = survival(np.concatenate([np.arange(0, T + 1, dtype=float), np.arange(T) + 0.5])) both = survival(np.concatenate([np.arange(0, T + 1, dtype=float), np.arange(T) + 0.5]))
S, mid = (both[: T + 1], both[T + 1 :]) S, mid = both[: T + 1], both[T + 1 :]
if not (np.all(np.isfinite(S)) and np.all(np.isfinite(mid))): if not (np.all(np.isfinite(S)) and np.all(np.isfinite(mid))):
return INVALID return INVALID
p = np.clip(S[:-1] - S[1:], 1e-300, None) p = np.clip(S[:-1] - S[1:], 1e-300, None)
@@ -53,12 +53,12 @@ def fit_weibull(d, c) -> tuple[float, float]:
lambda p: _nll(lambda t: weibull(t, *np.exp(p)), d, c), lambda p: _nll(lambda t: weibull(t, *np.exp(p)), d, c),
[np.log(k0), np.log(l0)], [np.log(k0), np.log(l0)],
method="Nelder-Mead", method="Nelder-Mead",
options={"xatol": 1e-05, "fatol": 1e-08, "maxiter": 2000}, options={"xatol": 1e-5, "fatol": 1e-8, "maxiter": 2000},
) )
r = _converged(r, "Weibull") r = _converged(r, "Weibull")
best = r if best is None or r.fun < best.fun else best best = r if best is None or r.fun < best.fun else best
k, lam = np.exp(best.x) k, lam = np.exp(best.x)
return (float(k), float(lam)) return float(k), float(lam)
STEPS = 800 STEPS = 800
@@ -85,14 +85,14 @@ def kilbas_saigo_survival(t, c: float, rho: float, s: float) -> np.ndarray:
grid = w ** (1 / e) grid = w ** (1 / e)
y = np.ones(STEPS + 1) y = np.ones(STEPS + 1)
kappa = c / np.exp(gammaln(rho)) kappa = c / np.exp(gammaln(rho))
b0, be = (beta_function(s + 1, rho), beta_function(s + e + 1, rho)) b0, be = beta_function(s + 1, rho), beta_function(s + e + 1, rho)
dw = np.diff(w) dw = np.diff(w)
for n in range(1, STEPS + 1): for n in range(1, STEPS + 1):
x = grid[: n + 1] / grid[n] x = grid[: n + 1] / grid[n]
i0 = grid[n] ** (rho + s) * b0 * np.diff(betainc(s + 1, rho, x)) 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)) ie = grid[n] ** (rho + s + e) * be * np.diff(betainc(s + e + 1, rho, x))
slope = (ie - w[:n] * i0) / dw[:n] slope = (ie - w[:n] * i0) / dw[:n]
own, next_ = (i0 - slope, slope) own, next_ = i0 - slope, slope
known = own[0] + np.dot(own[1:n] + next_[: n - 1], y[1:n]) known = own[0] + np.dot(own[1:n] + next_[: n - 1], y[1:n])
y[n] = (1 - kappa * known) / (1 + kappa * next_[n - 1]) y[n] = (1 - kappa * known) / (1 + kappa * next_[n - 1])
return np.interp(t**e, w, y) return np.interp(t**e, w, y)
@@ -108,22 +108,22 @@ def fractional(t, k, alpha, beta, lam) -> np.ndarray:
def _shape(k: float, alpha: float, beta: float) -> tuple[float, float, float]: 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)))) 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, ...]: def fit_fractional(d, c, k: float, lam: float) -> tuple[float, ...]:
floor = max(0.0, 1.0 - k) + 1e-06 floor = max(0.0, 1.0 - k) + 1e-6
top = len(d) + 0.5 top = len(d) + 0.5
months = np.concatenate([np.arange(0, len(d) + 1, dtype=float), np.arange(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(10000000.0)) lambdas = (0.0, np.log(1e7))
def unpack(p): def unpack(p):
return (floor + np.exp(p[0]), 1 / (1 + np.exp(-p[1]))) return floor + np.exp(p[0]), 1 / (1 + np.exp(-p[1]))
def profile(p) -> tuple[float, float]: def profile(p) -> tuple[float, float]:
a, b = unpack(p) a, b = unpack(p)
if k + a <= 1 or k + a + b <= 2: if k + a <= 1 or k + a + b <= 2:
return (INVALID, np.nan) return INVALID, np.nan
rho, s, scale = _shape(k, a, b) rho, s, scale = _shape(k, a, b)
e = rho + s e = rho + s
z_top = scale * top**e z_top = scale * top**e
@@ -136,21 +136,17 @@ def fit_fractional(d, c, k: float, lam: float) -> tuple[float, ...]:
coarse = np.linspace(*lambdas, 141) coarse = np.linspace(*lambdas, 141)
i = int(np.argmin([nll(x) for x in coarse])) i = int(np.argmin([nll(x) for x in coarse]))
r = minimize_scalar( r = minimize_scalar(nll, bounds=(coarse[max(i - 1, 0)], coarse[min(i + 1, 140)]),
nll, method="bounded", options={"xatol": 1e-9}) # fmt: skip
bounds=(coarse[max(i - 1, 0)], coarse[min(i + 1, 140)]), return float(r.fun), float(r.x)
method="bounded",
options={"xatol": 1e-09},
)
return (float(r.fun), float(r.x))
starts = [[np.log(max(1.0 - floor, 1e-09)), 8.0]] 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)] 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 best = None
for p0 in starts: for p0 in starts:
options = {"xatol": 1e-05, "fatol": 1e-08, "maxiter": 20000, "maxfev": 20000} 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 = minimize(lambda p: profile(p)[0], p0, method="Nelder-Mead", options=options)
r = _converged(r, "fractional Weibull") r = _converged(r, "fractional Weibull")
best = r if best is None or r.fun < best.fun else best best = r if best is None or r.fun < best.fun else best
a, b = unpack(best.x) a, b = unpack(best.x)
return (float(a), float(b), float(np.exp(profile(best.x)[1]))) return float(a), float(b), float(np.exp(profile(best.x)[1]))
+196 -14
View File
@@ -1,15 +1,45 @@
import hashlib
import importlib import importlib
import inspect
import io
import json
import os import os
import zipfile
from collections.abc import Callable
from datetime import date from datetime import date
from typing import Any
import dagster as dg import dagster as dg
from models import graph from pydantic import TypeAdapter
from core.domains import Domain
from models import execution, graph
from models.jobs import EmptyCohort 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 backup as backups
from persistance import config_log, silver from persistance import bundle, cluster, config_log, eeg, previews, silver
WRITES = {"writes": "platform"} 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): class PipelineRun(dg.Config):
pipeline: str pipeline: str
version: int | None = None version: int | None = None
@@ -39,21 +69,29 @@ class Training(dg.Config):
domain: str domain: str
models: list[str] = [] models: list[str] = []
as_of: str | None = None as_of: str | None = None
execution: ExecutionConfig = ExecutionConfig()
source: dict[str, Any] | None = None
@dg.op @dg.op
def train_models(context: dg.OpExecutionContext, config: Training) -> dict: def train_models(context: dg.OpExecutionContext, config: Training) -> dict:
jobs = _jobs(config.domain) jobs = _jobs(config.domain)
as_of = date.fromisoformat(config.as_of) if config.as_of else None 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 = {} found = {}
for name in config.models or jobs.JOBS.routine(): with execution.running(context, config.execution.model()):
try: for name in config.models or jobs.JOBS.routine():
found[name] = jobs.train(name, as_of) try:
except EmptyCohort as e: found[name] = jobs.train(name, as_of, **options)
found[name] = None except EmptyCohort as e:
context.log.warning(f"{e}: not trained") found[name] = None
continue context.log.warning(f"{e}: not trained")
context.log.info(f"{config.domain}.{name}: version {found[name]}") continue
context.log.info(f"{config.domain}.{name}: version {found[name]}")
return found return found
@@ -70,7 +108,7 @@ class Scoring(dg.Config):
@dg.op @dg.op
def score_models(context: dg.OpExecutionContext, config: Scoring) -> dict: def score_models(context: dg.OpExecutionContext, config: Scoring) -> dict:
jobs = _jobs(config.domain) jobs = _jobs(config.domain)
found = {name: jobs.score(name) for name in config.models or jobs.JOBS.scored()} found = {name: jobs.score(name) for name in config.models or jobs.JOBS.routine()}
for name, version in found.items(): for name, version in found.items():
context.log.info(f"{name}: " + (f"version {version}" if version else "no champion")) context.log.info(f"{name}: " + (f"version {version}" if version else "no champion"))
silver.build([getattr(jobs, "GOLD", f"{config.domain}_risk") + "+"]) silver.build([getattr(jobs, "GOLD", f"{config.domain}_risk") + "+"])
@@ -84,11 +122,13 @@ def score():
class Analysis(dg.Config): class Analysis(dg.Config):
domain: str domain: str
execution: ExecutionConfig = ExecutionConfig()
@dg.op @dg.op
def analyze_studies(context: dg.OpExecutionContext, config: Analysis) -> int: def analyze_studies(context: dg.OpExecutionContext, config: Analysis) -> int:
found = _jobs(config.domain).analyze() with execution.running(context, config.execution.model()):
found = _jobs(config.domain).analyze()
context.log.info(f"{config.domain}: {found} analysed") context.log.info(f"{config.domain}: {found} analysed")
return found return found
@@ -98,6 +138,143 @@ def analyze():
analyze_studies() 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 @dg.op
def make_backup(context: dg.OpExecutionContext) -> str: def make_backup(context: dg.OpExecutionContext) -> str:
folder = backups.create() folder = backups.create()
@@ -115,8 +292,13 @@ nightly = (
dg.ScheduleDefinition( dg.ScheduleDefinition(
job=backup, cron_schedule=cron, default_status=dg.DefaultScheduleStatus.RUNNING job=backup, cron_schedule=cron, default_status=dg.DefaultScheduleStatus.RUNNING
) )
] ] # fmt: skip
if (cron := os.environ.get("BACKUP_SCHEDULE", "30 2 * * *")) if (cron := os.environ.get("BACKUP_SCHEDULE", "30 2 * * *"))
else [] else []
) )
defs = dg.Definitions(jobs=[ingest, train, score, analyze, backup], schedules=nightly)
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
+22 -59
View File
@@ -2,10 +2,11 @@ import numpy as np
import pandas as pd import pandas as pd
import statsmodels.api as sm import statsmodels.api as sm
from scipy.stats import false_discovery_control from scipy.stats import false_discovery_control
from models.curves import life_table from models.curves import life_table
ALPHA = 0.05 ALPHA = 0.05
FREQ_MIN = 0.8 FREQ_MIN = 0.80
Z = 1.96 Z = 1.96
CRITERIA = ("c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia") CRITERIA = ("c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia")
ORDER = { ORDER = {
@@ -16,7 +17,7 @@ ORDER = {
"no concluyente": 4, "no concluyente": 4,
} }
UNKNOWN_CLASS = "no aplica (categoria desconocida)" UNKNOWN_CLASS = "no aplica (categoria desconocida)"
DEFINING, MAJORITY, PRESENT = (0.95, 0.5, 0.1) DEFINING, MAJORITY, PRESENT = 0.95, 0.50, 0.10
DESCRIBING = ("definitoria", "mayoritaria") DESCRIBING = ("definitoria", "mayoritaria")
@@ -31,7 +32,7 @@ def km_at(months, event, horizon) -> tuple[float, float]:
v = np.where((n > 0) & (n > d), d / (np.maximum(n, 1) * np.maximum(n - d, 1)), 0.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 last = min(horizon, len(d) - 1) + 1
S = float(np.prod(q[:last])) S = float(np.prod(q[:last]))
return (S, S * float(np.sqrt(np.sum(v[:last])))) return S, S * float(np.sqrt(np.sum(v[:last])))
def odds_ratios(data: pd.DataFrame, y, variables, reference, name: str) -> pd.DataFrame: def odds_ratios(data: pd.DataFrame, y, variables, reference, name: str) -> pd.DataFrame:
@@ -52,16 +53,8 @@ def odds_ratios(data: pd.DataFrame, y, variables, reference, name: str) -> pd.Da
) )
def complete( def complete(table: pd.DataFrame, variables, reference: dict, everyone: pd.DataFrame,
table: pd.DataFrame, months, event, horizon: int, names: tuple[str, str, str]) -> pd.DataFrame: # fmt: skip
variables,
reference: dict,
everyone: pd.DataFrame,
months,
event,
horizon: int,
names: tuple[str, str, str],
) -> pd.DataFrame:
table = table.reset_index(drop=True) table = table.reset_index(drop=True)
table["variable"] = [variable_of(x, variables) for x in table["termino"]] table["variable"] = [variable_of(x, variables) for x in table["termino"]]
table["categoria"] = [ table["categoria"] = [
@@ -72,46 +65,21 @@ def complete(
category, ref, delta_name = names category, ref, delta_name = names
rows = [] rows = []
for v, cat, r in zip(table["variable"], table["categoria"], table["referencia"], strict=True): 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()) a, b = (everyone[v] == cat).to_numpy(), (everyone[v] == r).to_numpy()
sa, ea = km_at(months[a], event[a], horizon) sa, ea = km_at(months[a], event[a], horizon)
sb, eb = km_at(months[b], event[b], horizon) sb, eb = km_at(months[b], event[b], horizon)
delta, se = (sa - sb, np.sqrt(ea**2 + eb**2)) delta, se = sa - sb, np.sqrt(ea**2 + eb**2)
rows.append( rows.append({
{ "n_categoria": int(a.sum()), category: sa, ref: sb, delta_name: delta,
"n_categoria": int(a.sum()), "delta_IC95_inf": delta - Z * se, "delta_IC95_sup": delta + Z * se,
category: sa, }) # fmt: skip
ref: sb, return pd.concat([table, pd.DataFrame(rows, columns=["n_categoria", category, ref, delta_name,
delta_name: delta, "delta_IC95_inf", "delta_IC95_sup"])],
"delta_IC95_inf": delta - Z * se, axis=1) # fmt: skip
"delta_IC95_sup": delta + Z * se,
}
)
return pd.concat(
[
table,
pd.DataFrame(
rows,
columns=[
"n_categoria",
category,
ref,
delta_name,
"delta_IC95_inf",
"delta_IC95_sup",
],
),
],
axis=1,
)
def classify( def classify(tab: pd.DataFrame, or_name: str, delta_name: str, unknown: str,
tab: pd.DataFrame, evaluated: tuple[str, ...] = CRITERIA) -> pd.DataFrame: # fmt: skip
or_name: str,
delta_name: str,
unknown: str,
evaluated: tuple[str, ...] = CRITERIA,
) -> pd.DataFrame:
risk = tab[or_name] > 1 risk = tab[or_name] > 1
tab["direccion"] = np.where(risk, "riesgo", "protector") tab["direccion"] = np.where(risk, "riesgo", "protector")
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALPHA) tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALPHA)
@@ -145,17 +113,12 @@ def presence(share: float) -> str:
def listing(part: pd.DataFrame) -> str: def listing(part: pd.DataFrame) -> str:
strength = np.where( strength = np.where(part["tipo_efecto"] == "tratamiento", "asociacion",
part["tipo_efecto"] == "tratamiento", part["clasificacion"].str.split().str[-1]) # fmt: skip
"asociacion",
part["clasificacion"].str.split().str[-1],
)
return "; ".join( return "; ".join(
( f"{v}={c} ({s}, {p:.0%})"
f"{v}={c} ({s}, {p:.0%})" for v, c, s, p in zip(
for v, c, s, p in zip( part["variable"], part["categoria"], strength, part["share"], strict=True
part["variable"], part["categoria"], strength, part["share"], strict=True
)
) )
) )
+116 -133
View File
@@ -6,6 +6,7 @@ import unicodedata
from collections.abc import Callable from collections.abc import Callable
from concurrent.futures import ProcessPoolExecutor from concurrent.futures import ProcessPoolExecutor
from functools import cache from functools import cache
import duckdb import duckdb
import ocrmypdf import ocrmypdf
import pandas as pd import pandas as pd
@@ -17,12 +18,14 @@ from openai import OpenAI, OpenAIError
from splink import Linker, SettingsCreator, block_on from splink import Linker, SettingsCreator, block_on
from splink.backends.duckdb import DuckDBAPI from splink.backends.duckdb import DuckDBAPI
from splink.clustering import cluster_pairwise_predictions_at_threshold from splink.clustering import cluster_pairwise_predictions_at_threshold
from core import catalog, concept_map, fhir_in from core import catalog, concept_map, fhir_in
from core.pipeline import ( from core.pipeline import (
HELD, HELD,
IDENTIFIERS, IDENTIFIERS,
QUOTES, QUOTES,
RECORD, RECORD,
Edf,
Extract, Extract,
Fhir, Fhir,
Join, Join,
@@ -40,6 +43,7 @@ from core.pipeline import (
matches, matches,
validate, validate,
) )
from models.tea.eeg import read
from persistance import config_log, files, nodes, silver from persistance import config_log, files, nodes, silver
MIN_WORDS = 5 MIN_WORDS = 5
@@ -52,6 +56,12 @@ READ_COLUMNS = {
} }
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: def file_format(content: bytes) -> str:
if content.startswith(b"%PDF"): if content.startswith(b"%PDF"):
return "pdf" return "pdf"
@@ -67,7 +77,7 @@ def _reader() -> MarkItDown:
def _lines(text: str) -> str: def _lines(text: str) -> str:
return "\n".join((" ".join(line.split()) for line in text.splitlines() if line.strip())) return "\n".join(" ".join(line.split()) for line in text.splitlines() if line.strip())
def _text(content: bytes) -> str: def _text(content: bytes) -> str:
@@ -80,25 +90,17 @@ def _pdf_pages(content: bytes) -> list[str]:
def _ocr_pages(content: bytes, numbers: list[int]) -> list[str]: def _ocr_pages(content: bytes, numbers: list[int]) -> list[str]:
source, scans = (pikepdf.open(io.BytesIO(content)), pikepdf.new()) source, scans = pikepdf.open(io.BytesIO(content)), pikepdf.new()
for n in numbers: for n in numbers:
scans.pages.append(source.pages[n]) scans.pages.append(source.pages[n])
pages, sidecar = (io.BytesIO(), io.BytesIO()) pages, sidecar = io.BytesIO(), io.BytesIO()
scans.save(pages) scans.save(pages)
pages.seek(0) pages.seek(0)
ocrmypdf.ocr( ocrmypdf.ocr(
pages, pages, io.BytesIO(), language="spa", force_ocr=True, output_type="pdf", optimize=0,
io.BytesIO(), progress_bar=False, jobs=1, deskew=True, sidecar=sidecar,
language="spa", ) # fmt: skip
force_ocr=True, found = sidecar.getvalue().decode().split("\f")
output_type="pdf",
optimize=0,
progress_bar=False,
jobs=1,
deskew=True,
sidecar=sidecar,
)
found = sidecar.getvalue().decode().split("\x0c")
return [_lines(found[i]) if i < len(found) else "" for i in range(len(numbers))] return [_lines(found[i]) if i < len(found) else "" for i in range(len(numbers))]
@@ -118,8 +120,8 @@ def _read_text(content: bytes) -> dict:
if scanned: if scanned:
for i, page in zip(scanned, _ocr_pages(content, scanned), strict=True): for i, page in zip(scanned, _ocr_pages(content, scanned), strict=True):
pages[i] = page pages[i] = page
return {"text": "\n".join((p for p in pages if p)), "ocr": bool(scanned), "error": None} return {"text": "\n".join(p for p in pages if p), "ocr": bool(scanned), "error": None}
except Exception as e: except Exception as e: # noqa: BLE001
return {"text": None, "ocr": False, "error": f"{type(e).__name__}: {e}"} return {"text": None, "ocr": False, "error": f"{type(e).__name__}: {e}"}
@@ -132,19 +134,16 @@ def run_read(p: str, node: Read):
legacy = [k for k, r in found.items() if r.get("format") is None] legacy = [k for k, r in found.items() if r.get("format") is None]
for k in legacy: for k in legacy:
found[k]["format"] = file_format(files.content(k) or b"") found[k]["format"] = file_format(files.content(k) or b"")
nodes.remember( nodes.remember("read_cache", [{"key": k, **{c: found[k][c] for c in READ_COLUMNS}}
"read_cache", for k in legacy], READ_COLUMNS) # fmt: skip
[{"key": k, **{c: found[k][c] for c in READ_COLUMNS}} for k in legacy],
READ_COLUMNS,
)
new = sorted(keys - set(found)) new = sorted(keys - set(found))
with ProcessPoolExecutor() as pool: with ProcessPoolExecutor() as pool:
for start in range(0, len(new), READ_BATCH): for start in range(0, len(new), READ_BATCH):
batch = new[start : start + READ_BATCH] batch = new[start : start + READ_BATCH]
read = dict( read = dict(zip(batch, pool.map(read_file, (files.content(k) for k in batch)),
zip(batch, pool.map(read_file, (files.content(k) for k in batch)), strict=True) strict=True)) # fmt: skip
) nodes.remember("read_cache", [{"key": k, **r} for k, r in read.items()],
nodes.remember("read_cache", [{"key": k, **r} for k, r in read.items()], READ_COLUMNS) READ_COLUMNS) # fmt: skip
found |= read found |= read
for row in rows: for row in rows:
result = found.get(row.pop("key"), {"text": None, "ocr": False, "error": "empty"}) result = found.get(row.pop("key"), {"text": None, "ocr": False, "error": "empty"})
@@ -152,9 +151,38 @@ def run_read(p: str, node: Read):
return nodes.write(p, node.id, rows, 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] = ()): def run_route(p: str, node: Route, others: list[Route] = ()):
rows = nodes.rows(p, node.inputs[0]) 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)))] 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) return nodes.write(p, node.id, taken)
@@ -195,10 +223,14 @@ def _llm() -> tuple[OpenAI, str] | None:
client.models.list() client.models.list()
except OpenAIError: except OpenAIError:
return None return None
return (client, os.environ["LLM_MODEL"]) 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}" 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: def _ask_llm(node: Extract, text: str) -> dict:
@@ -208,15 +240,11 @@ def _ask_llm(node: Extract, text: str) -> dict:
if found := nodes.cached("llm_cache", {key}): if found := nodes.cached("llm_cache", {key}):
return json.loads(found[key]["answer"]) return json.loads(found[key]["answer"])
reply = client.chat.completions.create( reply = client.chat.completions.create(
model=model, model=model, temperature=0, seed=7,
temperature=0,
seed=7,
messages=[{"role": "system", "content": system}, {"role": "user", "content": text}], messages=[{"role": "system", "content": system}, {"role": "user", "content": text}],
response_format={ response_format={"type": "json_schema", "json_schema": {
"type": "json_schema", "name": "answer", "schema": answer_schema(node.entity), "strict": True}},
"json_schema": {"name": "answer", "schema": answer_schema(node.entity), "strict": True}, ) # fmt: skip
},
)
answer = reply.choices[0].message.content answer = reply.choices[0].message.content
nodes.remember("llm_cache", [{"key": key, "answer": answer, "model": model}], {}) nodes.remember("llm_cache", [{"key": key, "answer": answer, "model": model}], {})
return json.loads(answer) return json.loads(answer)
@@ -236,16 +264,9 @@ def run_extract(p: str, node: Extract):
found = [({}, {}, ["no LLM answering and no patterns set"])] 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} 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"])]): for index, (values, quotes, held) in enumerate(found or [({}, {}, ["nothing found"])]):
out.append( out.append({**values, **taken, RECORD: row[RECORD], "_index": index,
{ QUOTES: json.dumps(quotes, ensure_ascii=False),
**values, HELD: json.dumps(held) if held else None}) # fmt: skip
**taken,
RECORD: row[RECORD],
"_index": index,
QUOTES: json.dumps(quotes, ensure_ascii=False),
HELD: json.dumps(held) if held else None,
}
)
return nodes.write(p, node.id, out) return nodes.write(p, node.id, out)
@@ -260,7 +281,7 @@ def _comparison(field: str):
def _plain(identifier: str) -> str: def _plain(identifier: str) -> str:
return "".join((ch for ch in identifier if ch.isalnum())).upper() return "".join(ch for ch in identifier if ch.isalnum()).upper()
def _name(name: str) -> str: def _name(name: str) -> str:
@@ -275,7 +296,7 @@ def _near(identifier: str) -> list[str]:
def _identities(p: str, node: Link) -> tuple[pd.DataFrame, dict[str, str], dict[str, str]]: def _identities(p: str, node: Link) -> tuple[pd.DataFrame, dict[str, str], dict[str, str]]:
skip, fixed = (nodes.rejected("identity"), nodes.corrections()) skip, fixed = nodes.rejected("identity"), nodes.corrections()
records: dict[str, dict] = {} records: dict[str, dict] = {}
sources: dict[str, str] = {} sources: dict[str, str] = {}
written: dict[str, str] = {} written: dict[str, str] = {}
@@ -292,15 +313,12 @@ def _identities(p: str, node: Link) -> tuple[pd.DataFrame, dict[str, str], dict[
if f == "full_name": if f == "full_name":
written[row[RECORD]] = " ".join(value.split()) written[row[RECORD]] = " ".join(value.split())
mine[f] = ( mine[f] = (
_plain(value) _plain(value) if f in IDENTIFIERS
if f in IDENTIFIERS else _name(value) if f == "full_name" else value
else _name(value) ) # fmt: skip
if f == "full_name"
else value
)
frame = pd.DataFrame(list(records.values())) frame = pd.DataFrame(list(records.values()))
present = [f for f in node.fields if f in frame and frame[f].notna().any()] present = [f for f in node.fields if f in frame and frame[f].notna().any()]
return (frame[["unique_id", *present]], sources, written) return frame[["unique_id", *present]], sources, written
def _distinct(records: pd.DataFrame, rules: list[str], judged: set[str]) -> pd.Series: def _distinct(records: pd.DataFrame, rules: list[str], judged: set[str]) -> pd.Series:
@@ -313,12 +331,11 @@ def _distinct(records: pd.DataFrame, rules: list[str], judged: set[str]) -> pd.S
if rules: if rules:
con = duckdb.connect() con = duckdb.connect()
con.register("candidates", records[records["unique_id"].isin(set(stand_in))]) con.register("candidates", records[records["unique_id"].isin(set(stand_in))])
joins = " or ".join((f"({r})" for r in rules)) joins = " or ".join(f"({r})" for r in rules)
joined = set( joined = set(con.sql(
con.sql( f"select l.unique_id from candidates l join candidates r"
f"select l.unique_id from candidates l join candidates r on l.unique_id = r.unique_id where {joins}" f" on l.unique_id = r.unique_id where {joins}"
).df()["unique_id"] ).df()["unique_id"]) # fmt: skip
)
return stand_in.where(stand_in.isin(joined), records["unique_id"]) return stand_in.where(stand_in.isin(joined), records["unique_id"])
@@ -332,11 +349,8 @@ def _persons(records: pd.DataFrame, edges: pd.DataFrame, db: DuckDBAPI) -> pd.Da
def run_link(p: str, node: Link): def run_link(p: str, node: Link):
records, sources, written = _identities(p, node) records, sources, written = _identities(p, node)
fields = [c for c in records.columns if c != "unique_id"] fields = [c for c in records.columns if c != "unique_id"]
rules = [ rules = [r for r in node.rules or node.default_rules()
r if all(f"l.{f}" not in r or f in fields for f in node.fields)] # fmt: skip
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))
]
comparisons = [_comparison(f) for f in fields] comparisons = [_comparison(f) for f in fields]
decided = nodes.person_decisions() decided = nodes.person_decisions()
stand_in = _distinct(records, rules, set().union(*decided)) stand_in = _distinct(records, rules, set().union(*decided))
@@ -344,13 +358,10 @@ def run_link(p: str, node: Link):
db = DuckDBAPI() db = DuckDBAPI()
linker = Linker( linker = Linker(
db.register(distinct), db.register(distinct),
SettingsCreator( SettingsCreator(link_type="dedupe_only", comparisons=comparisons,
link_type="dedupe_only", blocking_rules_to_generate_predictions=rules),
comparisons=comparisons,
blocking_rules_to_generate_predictions=rules,
),
log_level=None, log_level=None,
) ) # fmt: skip
sure = linker.inference.deterministic_link().as_pandas_dataframe() 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 = {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} pairs = {e for e in pairs if decided.get(e, True)} | {e for e, same in decided.items() if same}
@@ -360,6 +371,7 @@ def run_link(p: str, node: Link):
) )
cluster = _persons(distinct, edges, db).set_index("unique_id")["cluster_id"] cluster = _persons(distinct, edges, db).set_index("unique_id")["cluster_id"]
persons = records.assign(cluster_id=stand_in.map(cluster).to_numpy()) persons = records.assign(cluster_id=stand_in.map(cluster).to_numpy())
facts = [f for f in ("birth_date", "sex") if f in fields] facts = [f for f in ("birth_date", "sex") if f in fields]
spread = persons.groupby("cluster_id")[facts].nunique() if facts else pd.DataFrame() 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() torn = set(spread[(spread > 1).any(axis=1)].index) if facts else set()
@@ -370,18 +382,15 @@ def run_link(p: str, node: Link):
columns = {f: {"data_type": "text", "nullable": True} for f in (HELD, "_source", *fields)} 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()) stable = nodes.stable_persons(persons.groupby("cluster_id")["unique_id"].apply(list).to_dict())
linked = [ linked = [
{ {RECORD: r.unique_id, "person_id": stable[r.cluster_id], "_source": sources[r.unique_id],
RECORD: r.unique_id, HELD: json.dumps([why[r.cluster_id]]) if r.cluster_id in why else None,
"person_id": stable[r.cluster_id], **{f: getattr(r, f) for f in fields},
"_source": sources[r.unique_id], **({"full_name": written[r.unique_id]} if r.unique_id in written else {})}
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() for r in persons.itertuples()
] ] # fmt: skip
nodes.write(p, node.id, linked, columns) nodes.write(p, node.id, linked, columns)
nodes.stage("identity", p, node.id, linked, silver.identity_columns()) nodes.stage("identity", p, node.id, linked, silver.identity_columns())
ids = [f for f in IDENTIFIERS if f in fields] ids = [f for f in IDENTIFIERS if f in fields]
whole = persons.drop(columns="unique_id").groupby("cluster_id").first() whole = persons.drop(columns="unique_id").groupby("cluster_id").first()
for f in ids: for f in ids:
@@ -401,44 +410,42 @@ def run_link(p: str, node: Link):
reasons.append("same birth date") reasons.append("same birth date")
model = Linker( model = Linker(
db.register(whole), db.register(whole),
SettingsCreator( SettingsCreator(link_type="dedupe_only", comparisons=comparisons,
link_type="dedupe_only", blocking_rules_to_generate_predictions=blocks),
comparisons=comparisons,
blocking_rules_to_generate_predictions=blocks,
),
log_level=None, log_level=None,
) ) # fmt: skip
model.training.estimate_u_using_random_sampling(max_pairs=1000000.0) model.training.estimate_u_using_random_sampling(max_pairs=1e6)
found = model.inference.predict(warning_mode="never").as_pandas_dataframe() found = model.inference.predict(warning_mode="never").as_pandas_dataframe()
known = [f for f in ("birth_date", "sex") if f in fields] 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() 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() 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() whose = persons.set_index("unique_id")["cluster_id"].to_dict()
answered = {frozenset((whose.get(r, r) for r in e)) for e in decided} answered = {frozenset(whose.get(r, r) for r in e) for e in decided}
lone = set() lone = set()
for f in ids: for f in ids:
carried = persons.dropna(subset=[f]).groupby(["cluster_id", f]).size() carried = persons.dropna(subset=[f]).groupby(["cluster_id", f]).size()
lone |= {person for (person, _), n in carried.items() if n == 1} lone |= {person for (person, _), n in carried.items() if n == 1}
def settle(r) -> tuple[str, str] | None: def settle(r) -> tuple[str, str] | None:
a, b = (r.unique_id_l, r.unique_id_r) 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] sides = [(getattr(r, f"{f}_l"), getattr(r, f"{f}_r")) for f in known]
if frozenset((a, b)) in answered or any( if frozenset((a, b)) in answered or any(
(pd.notna(x) and pd.notna(y) and (x != y) for x, y in sides) pd.notna(x) and pd.notna(y) and x != y for x, y in sides
): ):
return None return None
reason = reasons[int(r.match_key)] reason = reasons[int(r.match_key)]
if not reason.endswith("typo apart"): if not reason.endswith("typo apart"):
return (a, b) return a, b
field = reason.removesuffix(" one typo apart") field = reason.removesuffix(" one typo apart")
if getattr(r, f"{field}_l") == getattr(r, f"{field}_r"): 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) 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): if field == "full_name" and (a in undated) != (b in undated):
return (a, b) if a in undated else (b, a) return (a, b) if a in undated else (b, a)
if a in orphan and b in lone: if a in orphan and b in lone:
return (a, b) return a, b
if b in orphan and a in lone: if b in orphan and a in lone:
return (b, a) return b, a
return None return None
side = {r.unique_id: r for r in whole.itertuples()} side = {r.unique_id: r for r in whole.itertuples()}
@@ -460,30 +467,24 @@ def run_link(p: str, node: Link):
def run_target(p: str, node: Target, kinds: dict[str, str]): def run_target(p: str, node: Target, kinds: dict[str, str]):
link = next((i for i in node.inputs if kinds[i] == "link")) link = next(i for i in node.inputs if kinds[i] == "link")
linked = {r[RECORD]: r for r in nodes.rows(p, link)} linked = {r[RECORD]: r for r in nodes.rows(p, link)}
person = {k: r["person_id"] for k, r in linked.items()} person = {k: r["person_id"] for k, r in linked.items()}
model, study = (catalog.model(node.entity), catalog.studies()[node.entity]) model, study = catalog.model(node.entity), catalog.studies()[node.entity]
fixed = nodes.corrections() fixed = nodes.corrections()
observations, held_rows = ([], []) observations, held_rows = [], []
for i in (i for i in node.inputs if i != link): for i in (i for i in node.inputs if i != link):
for row in nodes.rows(p, i): 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: row.get(f) for f in model.model_fields if row.get(f) is not None}
values |= { values |= {f: v for f, v in fixed.get(row[RECORD], {}).items()
f: v for f, v in fixed.get(row[RECORD], {}).items() if f in model.model_fields if f in model.model_fields} # fmt: skip
}
held = json.loads(row.get(HELD) or "[]") + validate(node.entity, values) held = json.loads(row.get(HELD) or "[]") + validate(node.entity, values)
if row[RECORD] not in person: if row[RECORD] not in person:
held.append("no identity linked to this record") held.append("no identity linked to this record")
else: else:
held += json.loads(linked[row[RECORD]].get(HELD) or "[]") held += json.loads(linked[row[RECORD]].get(HELD) or "[]")
base = { base = {"study": node.entity, "person_id": person.get(row[RECORD]), RECORD: row[RECORD],
"study": node.entity, "_index": row.get("_index", 0), QUOTES: row.get(QUOTES)} # fmt: skip
"person_id": person.get(row[RECORD]),
RECORD: row[RECORD],
"_index": row.get("_index", 0),
QUOTES: row.get(QUOTES),
}
if held: if held:
raw = json.dumps(values, default=str, ensure_ascii=False) raw = json.dumps(values, default=str, ensure_ascii=False)
held_rows.append({**base, HELD: json.dumps(held), "_raw": raw}) held_rows.append({**base, HELD: json.dumps(held), "_raw": raw})
@@ -492,28 +493,16 @@ def run_target(p: str, node: Target, kinds: dict[str, str]):
instance = json.dumps([str(getattr(clean, k)) for k in model.key]) instance = json.dumps([str(getattr(clean, k)) for k in model.key])
for name, field in study.fields.items(): for name, field in study.fields.items():
if (value := getattr(clean, name)) is not None: if (value := getattr(clean, name)) is not None:
observations.append( observations.append({**base, "instance": instance, "field": name,
{ catalog.value_column(field): value}) # fmt: skip
**base,
"instance": instance,
"field": name,
catalog.value_column(field): value,
}
)
nodes.stage("observation", p, node.id, observations, silver.OBSERVATION) nodes.stage("observation", p, node.id, observations, silver.OBSERVATION)
return nodes.stage("held", p, node.id, held_rows, silver.HELD_ROWS) return nodes.stage("held", p, node.id, held_rows, silver.HELD_ROWS)
RUNNERS: dict[str, Callable] = { RUNNERS: dict[str, Callable] = {
"source": nodes.run_source, "source": nodes.run_source, "read": run_read, "route": run_route, "map": run_map,
"read": run_read, "join": run_join, "extract": run_extract, "link": run_link, "edf": run_edf, "fhir": run_fhir,
"route": run_route, } # fmt: skip
"map": run_map,
"join": run_join,
"extract": run_extract,
"link": run_link,
"fhir": run_fhir,
}
def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print) -> None: def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print) -> None:
@@ -522,14 +511,8 @@ def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print
if node.kind == "target": if node.kind == "target":
run_target(pipeline_id, node, kinds) run_target(pipeline_id, node, kinds)
elif node.kind == "route" and node.otherwise: elif node.kind == "route" and node.otherwise:
others = [ others = [n for n in pipeline.nodes if n.kind == "route" and n.id != node.id
n and n.inputs == node.inputs and not n.otherwise] # fmt: skip
for n in pipeline.nodes
if n.kind == "route"
and n.id != node.id
and (n.inputs == node.inputs)
and (not n.otherwise)
]
run_route(pipeline_id, node, others) run_route(pipeline_id, node, others)
else: else:
RUNNERS[node.kind](pipeline_id, node) RUNNERS[node.kind](pipeline_id, node)
+4 -5
View File
@@ -1,9 +1,11 @@
from collections.abc import Callable from collections.abc import Callable
from dataclasses import dataclass from dataclasses import dataclass
from datetime import date from datetime import date
import mlflow.pyfunc import mlflow.pyfunc
import pandas as pd import pandas as pd
from joblib.externals.loky import get_reusable_executor from joblib.externals.loky import get_reusable_executor
from persistance import gold, registry from persistance import gold, registry
@@ -13,7 +15,7 @@ class EmptyCohort(ValueError):
class Predictor(mlflow.pyfunc.PythonModel): class Predictor(mlflow.pyfunc.PythonModel):
def __init__(self, spec, fitted): def __init__(self, spec, fitted):
self.spec, self.fitted = (spec, fitted) self.spec, self.fitted = spec, fitted
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame: def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
return self.spec.predict(self.fitted, model_input) return self.spec.predict(self.fitted, model_input)
@@ -33,14 +35,11 @@ class Jobs:
def routine(self) -> list[str]: def routine(self) -> list[str]:
return list(self.models) return list(self.models)
def scored(self) -> list[str]:
return list(self.models)
def registered(self, name: str) -> str: def registered(self, name: str) -> str:
return f"{self.domain}.{name}" return f"{self.domain}.{name}"
def train(self, name: str, as_of: date | None = None) -> int: def train(self, name: str, as_of: date | None = None) -> int:
spec, as_of = (self.models[name], as_of or date.today()) spec, as_of = self.models[name], as_of or date.today()
if getattr(spec, "reports", False): if getattr(spec, "reports", False):
events = gold.timelines(self.events, spec.cohort, as_of) events = gold.timelines(self.events, spec.cohort, as_of)
if events.empty: if events.empty:
+102 -182
View File
@@ -2,6 +2,7 @@ import json
import warnings import warnings
from dataclasses import dataclass, field from dataclasses import dataclass, field
from itertools import pairwise from itertools import pairwise
import numpy as np import numpy as np
import pandas as pd import pandas as pd
from joblib import Parallel, delayed from joblib import Parallel, delayed
@@ -16,7 +17,7 @@ DAYS_PER_YEAR = 365.25
def outcomes(index: pd.Series, death: pd.Series, end, cap_months: int) -> pd.DataFrame: 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)) index, death, end = pd.to_datetime(index), pd.to_datetime(death), pd.Timestamp(end)
died = (death.notna() & (death <= end)).to_numpy() died = (death.notna() & (death <= end)).to_numpy()
last = death.where(died, end) last = death.where(died, end)
days = (last - index).dt.days.to_numpy() days = (last - index).dt.days.to_numpy()
@@ -43,25 +44,22 @@ class Constant:
def _bdeu(code, y, w, q, ess) -> float: def _bdeu(code, y, w, q, ess) -> float:
n = np.bincount(code * 2 + y, weights=w, minlength=q * 2).reshape(q, 2) n = np.bincount(code * 2 + y, weights=w, minlength=q * 2).reshape(q, 2)
aj, ajk = (ess / q, ess / q / 2) aj, ajk = ess / q, ess / q / 2
return float( return float(np.sum(gammaln(aj) - gammaln(aj + n.sum(1))
np.sum( + np.sum(gammaln(ajk + n) - gammaln(ajk), axis=1))) # fmt: skip
gammaln(aj) - gammaln(aj + n.sum(1)) + np.sum(gammaln(ajk + n) - gammaln(ajk), axis=1)
)
)
def _search(X, levels, y, w, ess, max_parents) -> list[int]: def _search(X, levels, y, w, ess, max_parents) -> list[int]:
parents, code, q = ([], np.zeros(len(y), int), 1) parents, code, q = [], np.zeros(len(y), int), 1
best = _bdeu(code, y, w, q, ess) best = _bdeu(code, y, w, q, ess)
while len(parents) < max_parents: while len(parents) < max_parents:
found = None found = None
for j in range(X.shape[1]): for j in range(X.shape[1]):
if j in parents or q * levels[j] > 200000: if j in parents or q * levels[j] > 200_000:
continue continue
c2 = code * levels[j] + X[:, j] c2 = code * levels[j] + X[:, j]
score = _bdeu(c2, y, w, q * levels[j], ess) score = _bdeu(c2, y, w, q * levels[j], ess)
if score > best + 1e-09 and (found is None or score > found[0]): if score > best + 1e-9 and (found is None or score > found[0]):
found = (score, j, c2, q * levels[j]) found = (score, j, c2, q * levels[j])
if found is None: if found is None:
break break
@@ -78,17 +76,8 @@ def _code(X, levels, parents) -> np.ndarray:
class IntervalSurvival(BaseEstimator): class IntervalSurvival(BaseEstimator):
def __init__( def __init__(self, features, borders=(0, 6, 12, 18), parents=None, ess=1000, max_parents=5,
self, folds=5, shrink=20, seed=42): # fmt: skip
features,
borders=(0, 6, 12, 18),
parents=None,
ess=1000,
max_parents=5,
folds=5,
shrink=20,
seed=42,
):
self.features = features self.features = features
self.borders = borders self.borders = borders
self.parents = parents self.parents = parents
@@ -111,7 +100,7 @@ class IntervalSurvival(BaseEstimator):
fallback = known.index(UNKNOWN) if UNKNOWN in known else 0 fallback = known.index(UNKNOWN) if UNKNOWN in known else 0
columns.append(np.where(codes < 0, fallback, codes)) columns.append(np.where(codes < 0, fallback, codes))
dummies = pd.get_dummies(frame).reindex(columns=self.dummies_, fill_value=0) 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)) return dummies.to_numpy(dtype=np.float32), np.column_stack(columns).astype(int)
def _fit_intervals(self, X_dum, X_int, months, event) -> list: def _fit_intervals(self, X_dum, X_int, months, event) -> list:
fitted = [] fitted = []
@@ -120,13 +109,13 @@ class IntervalSurvival(BaseEstimator):
if len(at_risk) == 0: if len(at_risk) == 0:
fitted.append((Constant(1.0), ([], np.array([1.0])))) fitted.append((Constant(1.0), ([], np.array([1.0]))))
continue continue
m, e = (months[at_risk], event[at_risk]) m, e = months[at_risk], event[at_risk]
y = np.where(e & (m < b), 0, 1) y = np.where(e & (m < b), 0, 1)
w = np.where(~e & (m < b), 0.5, 1.0) w = np.where(~e & (m < b), 0.5, 1.0)
if y.min() == y.max(): if y.min() == y.max():
lr = Constant(float(y[0])) lr = Constant(float(y[0]))
else: else:
lr = LogisticRegression(C=1000000.0, max_iter=500) lr = LogisticRegression(C=1e6, max_iter=500)
lr.fit(X_dum[at_risk], y, sample_weight=w) lr.fit(X_dum[at_risk], y, sample_weight=w)
fitted.append((lr, self._hbn(X_int[at_risk], y, w))) fitted.append((lr, self._hbn(X_int[at_risk], y, w)))
return fitted return fitted
@@ -137,27 +126,23 @@ class IntervalSurvival(BaseEstimator):
else: else:
parents = [list(self.features).index(p) for p in self.parents] 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 q = int(np.prod([self.levels_[j] for j in parents])) if parents else 1
n = np.bincount( n = np.bincount(_code(X, self.levels_, parents) * 2 + y, weights=w,
_code(X, self.levels_, parents) * 2 + y, weights=w, minlength=q * 2 minlength=q * 2).reshape(q, 2) # fmt: skip
).reshape(q, 2)
aj = self.ess / q aj = self.ess / q
marginal = (n[:, 1].sum() + 0.5) / (n.sum() + 1) marginal = (n[:, 1].sum() + 0.5) / (n.sum() + 1)
return (parents, (n[:, 1] + aj * marginal) / (n.sum(1) + aj)) return parents, (n[:, 1] + aj * marginal) / (n.sum(1) + aj)
def _predict(self, fitted, X_dum, X_int) -> tuple[np.ndarray, np.ndarray]: 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]) 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]) hbn = np.column_stack([cpt[_code(X_int, self.levels_, p)] for _, (p, cpt) in fitted])
return (lr, hbn) return lr, hbn
def _weights(self, X_dum, X_int, months, event) -> np.ndarray: def _weights(self, X_dum, X_int, months, event) -> np.ndarray:
n = len(months) n = len(months)
fold = np.random.default_rng(self.seed + 7).permutation(n) % self.folds fold = np.random.default_rng(self.seed + 7).permutation(n) % self.folds
oof_lr, oof_hbn = ( oof_lr, oof_hbn = np.zeros((n, len(self.borders) - 1)), np.zeros((n, len(self.borders) - 1))
np.zeros((n, len(self.borders) - 1)),
np.zeros((n, len(self.borders) - 1)),
)
for k in range(self.folds): for k in range(self.folds):
test, train = (np.where(fold == k)[0], np.where(fold != k)[0]) 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]) 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]) oof_lr[test], oof_hbn[test] = self._predict(fitted, X_dum[test], X_int[test])
weights = [] weights = []
@@ -166,14 +151,14 @@ class IntervalSurvival(BaseEstimator):
if len(at_risk) == 0: if len(at_risk) == 0:
weights.append(0.5) weights.append(0.5)
continue continue
m, e = (months[at_risk], event[at_risk]) m, e = months[at_risk], event[at_risk]
y = np.where(e & (m < b), 0, 1) y = np.where(e & (m < b), 0, 1)
w = np.where(~e & (m < b), 0.5, 1.0) w = np.where(~e & (m < b), 0.5, 1.0)
p1 = np.clip(oof_lr[at_risk, j], 1e-09, 1 - 1e-09) p1 = np.clip(oof_lr[at_risk, j], 1e-9, 1 - 1e-9)
p2 = np.clip(oof_hbn[at_risk, j], 1e-09, 1 - 1e-09) p2 = np.clip(oof_hbn[at_risk, j], 1e-9, 1 - 1e-9)
def loss(x, p1=p1, p2=p2, y=y, w=w): def loss(x, p1=p1, p2=p2, y=y, w=w):
p = np.clip(x * p1 + (1 - x) * p2, 1e-09, 1 - 1e-09) 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))) return -np.sum(w * (y * np.log(p) + (1 - y) * np.log1p(-p)))
best = float(minimize_scalar(loss, bounds=(0, 1), method="bounded").x) best = float(minimize_scalar(loss, bounds=(0, 1), method="bounded").x)
@@ -187,7 +172,7 @@ class IntervalSurvival(BaseEstimator):
self.categories_ = {name: list(pd.factorize(frame[name])[1]) for name in self.features} self.categories_ = {name: list(pd.factorize(frame[name])[1]) for name in self.features}
X_dum, X_int = self._encode(X) X_dum, X_int = self._encode(X)
self.levels_ = X_int.max(axis=0) + 1 self.levels_ = X_int.max(axis=0) + 1
months, event = (np.asarray(months, int), np.asarray(event, bool)) months, event = np.asarray(months, int), np.asarray(event, bool)
if len(X) >= 2 * self.folds: if len(X) >= 2 * self.folds:
self.weights_ = self._weights(X_dum, X_int, months, event) self.weights_ = self._weights(X_dum, X_int, months, event)
else: else:
@@ -205,22 +190,15 @@ class IntervalSurvival(BaseEstimator):
TRAIN_FRACTION = 0.7 TRAIN_FRACTION = 0.7
OUTPUT = [ OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high",
"person_id", "scenarios"] # fmt: skip
"index_date",
"horizon_years",
"probability",
"ci_low",
"ci_high",
"scenarios",
]
SCENARIO_SEPARATOR = " | " SCENARIO_SEPARATOR = " | "
def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]: def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]:
ordered = members.sort_values(["index_date", "record_number"], kind="stable") ordered = members.sort_values(["index_date", "record_number"], kind="stable")
cut = int(len(ordered) * train_fraction) cut = int(len(ordered) * train_fraction)
return (ordered.iloc[:cut].reset_index(drop=True), ordered.iloc[cut:].reset_index(drop=True)) 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: def age_group(events: pd.DataFrame, members: pd.DataFrame, cuts) -> pd.Series:
@@ -249,12 +227,11 @@ class Spec:
@property @property
def horizons(self) -> tuple[float, ...]: def horizons(self) -> tuple[float, ...]:
return tuple((b / 12 for b in self.borders[1:])) return tuple(b / 12 for b in self.borders[1:])
def members(self, events: pd.DataFrame) -> pd.DataFrame: def members(self, events: pd.DataFrame) -> pd.DataFrame:
events = events.assign( events = events.assign(date=pd.to_datetime(events["date"]),
date=pd.to_datetime(events["date"]), index_date=pd.to_datetime(events["index_date"]) index_date=pd.to_datetime(events["index_date"])) # fmt: skip
)
found = events.groupby("person_id")[["index_date", "record_number"]].first() found = events.groupby("person_id")[["index_date", "record_number"]].first()
death = events[events["type"] == "death"].groupby("person_id")["date"].min() death = events[events["type"] == "death"].groupby("person_id")["date"].min()
found["death_date"] = death.reindex(found.index) found["death_date"] = death.reindex(found.index)
@@ -280,7 +257,7 @@ class Spec:
refit = self._model().fit(sample, sample["months"], sample["event"]) refit = self._model().fit(sample, sample["months"], sample["event"])
return 1.0 - refit.survival(frame) return 1.0 - refit.survival(frame)
replicas = Parallel(n_jobs=-1)((delayed(mortality)(rows) for rows in samples)) replicas = Parallel(n_jobs=-1)(delayed(mortality)(rows) for rows in samples)
tail = 50 * (1 - self.interval_level) tail = 50 * (1 - self.interval_level)
low, high = np.nanpercentile(np.stack(replicas), [tail, 100 - tail], axis=0) low, high = np.nanpercentile(np.stack(replicas), [tail, 100 - tail], axis=0)
rows = combinations.itertuples(index=False) rows = combinations.itertuples(index=False)
@@ -296,39 +273,31 @@ class Spec:
model.intervals_ = self._intervals(train) if self.interval_level else {} model.intervals_ = self._intervals(train) if self.interval_level else {}
weights = zip(self.borders[1:], model.weights_, strict=True) weights = zip(self.borders[1:], model.weights_, strict=True)
metrics = { metrics = {
"n_train": float(len(train)), "n_train": float(len(train)), "n_test": float(len(test)),
"n_test": float(len(test)), "events_train": float(train["event"].sum()), "events_test": float(test["event"].sum()),
"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}, **{f"stack_w_lr_{b}m": float(w) for b, w in weights},
} } # fmt: skip
return (model, metrics, {"train": train, "test": test}) return model, metrics, {"train": train, "test": test}
def predict(self, model: IntervalSurvival, events: pd.DataFrame) -> pd.DataFrame: def predict(self, model: IntervalSurvival, events: pd.DataFrame) -> pd.DataFrame:
members = self.members(events) members = self.members(events)
mortality = 1.0 - model.survival(members) mortality = 1.0 - model.survival(members)
n, h = (len(members), len(self.horizons)) n, h = len(members), len(self.horizons)
empty = ([np.nan] * h, [np.nan] * h) empty = ([np.nan] * h, [np.nan] * h)
ends = [ ends = [model.intervals_.get(tuple(c), empty)
model.intervals_.get(tuple(c), empty) for c in self._combinations(members).itertuples(index=False)] # fmt: skip
for c in self._combinations(members).itertuples(index=False)
]
masks = scenario_masks(members, self.scenarios) masks = scenario_masks(members, self.scenarios)
scenarios = [ scenarios = [SCENARIO_SEPARATOR.join(name for name, m in masks.items() if m[i]) or None
SCENARIO_SEPARATOR.join((name for name, m in masks.items() if m[i])) or None for i in range(n)] # fmt: skip
for i in range(n) return pd.DataFrame({
] "person_id": np.repeat(members["person_id"].to_numpy(), h),
return pd.DataFrame( "index_date": np.repeat(members["index_date"].dt.date.to_numpy(), h),
{ "horizon_years": np.tile(np.asarray(self.horizons, dtype=float), n),
"person_id": np.repeat(members["person_id"].to_numpy(), h), "probability": mortality.ravel(),
"index_date": np.repeat(members["index_date"].dt.date.to_numpy(), h), "ci_low": np.array([e[0] for e in ends], dtype=float).ravel(),
"horizon_years": np.tile(np.asarray(self.horizons, dtype=float), n), "ci_high": np.array([e[1] for e in ends], dtype=float).ravel(),
"probability": mortality.ravel(), "scenarios": np.repeat(np.asarray(scenarios, dtype=object), h),
"ci_low": np.array([e[0] for e in ends], dtype=float).ravel(), })[OUTPUT] # fmt: skip
"ci_high": np.array([e[1] for e in ends], dtype=float).ravel(),
"scenarios": np.repeat(np.asarray(scenarios, dtype=object), h),
}
)[OUTPUT]
BOOTSTRAP = 100 BOOTSTRAP = 100
@@ -338,20 +307,16 @@ BOOTSTRAP_SEED = 42
def technical_validation(spec: Spec, metrics: dict, data: dict) -> dict: def technical_validation(spec: Spec, metrics: dict, data: dict) -> dict:
members = pd.concat([data["train"], data["test"]]) members = pd.concat([data["train"], data["test"]])
return { return {
"model": spec.name, "model": spec.name, "method": spec.method, "cohort": spec.cohort,
"method": spec.method,
"cohort": spec.cohort,
"split": "temporal: the earliest 70% of index dates train, the latest 30% test", "split": "temporal: the earliest 70% of index dates train, the latest 30% test",
"members": len(members), "members": len(members),
"index_dates": [ "index_dates": [str(members["index_date"].min().date()),
str(members["index_date"].min().date()), str(members["index_date"].max().date())],
str(members["index_date"].max().date()),
],
"horizons_months": list(spec.borders[1:]), "horizons_months": list(spec.borders[1:]),
"follow_up_cap_months": spec.cap_months, "follow_up_cap_months": spec.cap_months,
"notes": list(spec.notes), "notes": list(spec.notes),
"metrics": metrics, "metrics": metrics,
} } # fmt: skip
def _curve(fitter, name: str) -> dict: def _curve(fitter, name: str) -> dict:
@@ -359,10 +324,8 @@ def _curve(fitter, name: str) -> dict:
return { return {
"months": fitter.survival_function_.index.tolist(), "months": fitter.survival_function_.index.tolist(),
"survival": fitter.survival_function_.iloc[:, 0].tolist(), "survival": fitter.survival_function_.iloc[:, 0].tolist(),
"low": table.iloc[:, 0].tolist(), "low": table.iloc[:, 0].tolist(), "high": table.iloc[:, 1].tolist(), "name": name,
"high": table.iloc[:, 1].tolist(), } # fmt: skip
"name": name,
}
MIN_SCENARIO_EVENTS = 5 MIN_SCENARIO_EVENTS = 5
@@ -400,36 +363,28 @@ def _scenario_curves(months: np.ndarray, event: np.ndarray, cap_months: int) ->
km = curves.kaplan_meier(months, event, observed) km = curves.kaplan_meier(months, event, observed)
return { return {
"observado_hasta": observed, "observado_hasta": observed,
"km": { "km": {"months": list(range(observed + 1)),
"months": list(range(observed + 1)), **{n: v.tolist() for n, v in zip(("S", "low", "high"), km, strict=True)}},
**{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": { "weibull_fractional": {"t": grid.tolist(),
"t": grid.tolist(), "S": curves.fractional(grid, k, *fractional).tolist(),
"S": curves.weibull(grid, k, lam).tolist(), "alpha": fractional[0], "beta": fractional[1],
"k": k, "lambda": fractional[2]},
"lambda": lam, } # fmt: skip
},
"weibull_fractional": {
"t": grid.tolist(),
"S": curves.fractional(grid, k, *fractional).tolist(),
"alpha": fractional[0],
"beta": fractional[1],
"lambda": fractional[2],
},
}
def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict: def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
from lifelines import KaplanMeierFitter, WeibullFitter from lifelines import KaplanMeierFitter, WeibullFitter
train = data["train"] train = data["train"]
months, event = (train["months"].to_numpy(), train["event"].to_numpy()) months, event = train["months"].to_numpy(), train["event"].to_numpy()
curves = [_curve(KaplanMeierFitter().fit(months, event), "Kaplan-Meier (IC 95 % Greenwood)")] curves = [_curve(KaplanMeierFitter().fit(months, event), "Kaplan-Meier (IC 95 % Greenwood)")]
if event.any() and (months > 0).all(): if event.any() and (months > 0).all():
curves.append(_curve(WeibullFitter().fit(months, event), "Weibull")) curves.append(_curve(WeibullFitter().fit(months, event), "Weibull"))
rng = np.random.default_rng(BOOTSTRAP_SEED) rng = np.random.default_rng(BOOTSTRAP_SEED)
samples = [rng.integers(0, len(train), len(train)) for _ in range(BOOTSTRAP)] 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) members = pd.concat([train, data.get("test", train.iloc[:0])]).reset_index(drop=True)
masks = scenario_masks(members, spec.scenarios) masks = scenario_masks(members, spec.scenarios)
@@ -438,47 +393,34 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
refit = spec._model().fit(sample, sample["months"], sample["event"]) refit = spec._model().fit(sample, sample["months"], sample["event"])
found = refit.survival(members) found = refit.survival(members)
by = {n: found[m].mean(axis=0) for n, m in masks.items() if m.any()} by = {n: found[m].mean(axis=0) for n, m in masks.items() if m.any()}
return (found[: len(train)].mean(axis=0), by) return found[: len(train)].mean(axis=0), by
all_months, all_event = (members["months"].to_numpy(), members["event"].to_numpy(bool)) 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} drawn = {n: m for n, m in masks.items() if all_event[m].sum() >= MIN_SCENARIO_EVENTS}
jobs = [ jobs = [delayed(_scenario_curves)(all_months[m], all_event[m], spec.cap_months)
delayed(_scenario_curves)(all_months[m], all_event[m], spec.cap_months) for m in drawn.values()] # fmt: skip
for m in drawn.values()
]
jobs += [delayed(mean_survival)(rows) for rows in samples] jobs += [delayed(mean_survival)(rows) for rows in samples]
done = Parallel(n_jobs=-1)(jobs) done = Parallel(n_jobs=-1)(jobs)
drawn_curves, replicas = (done[: len(drawn)], done[len(drawn) :]) drawn_curves, replicas = done[: len(drawn)], done[len(drawn) :]
band = np.stack([r[0] for r in replicas]) band = np.stack([r[0] for r in replicas])
point = model.survival(members) point = model.survival(members)
scenarios = [] scenarios = []
for (name, mask), found in zip(drawn.items(), drawn_curves, strict=True): for (name, mask), found in zip(drawn.items(), drawn_curves, strict=True):
spread = np.array([r[1][name] for r in replicas]) spread = np.array([r[1][name] for r in replicas])
low, high = np.nanpercentile(spread, [2.5, 97.5], axis=0) low, high = np.nanpercentile(spread, [2.5, 97.5], axis=0)
scenarios.append( scenarios.append({
{ "escenario": name,
"escenario": name, "condiciones": [list(c) for c in spec.scenarios[name]],
"condiciones": [list(c) for c in spec.scenarios[name]], "n": int(mask.sum()), "fallecidos": int(all_event[mask].sum()),
"n": int(mask.sum()), "horizons_months": list(spec.borders[1:]), "months_max": spec.cap_months,
"fallecidos": int(all_event[mask].sum()), **found,
"horizons_months": list(spec.borders[1:]), "points": {"COMB": {"S": point[mask].mean(axis=0).tolist(),
"months_max": spec.cap_months, "low": np.clip(low, 0, 1).tolist(),
**found, "high": np.clip(high, 0, 1).tolist()}},
"points": { "bootstrap_replicas": len(replicas),
"COMB": { }) # fmt: skip
"S": point[mask].mean(axis=0).tolist(), skipped = [{"escenario": n, "n": int(m.sum()), "fallecidos": int(all_event[m].sum())}
"low": np.clip(low, 0, 1).tolist(), for n, m in masks.items() if n not in drawn] # fmt: skip
"high": np.clip(high, 0, 1).tolist(),
}
},
"bootstrap_replicas": len(replicas),
}
)
skipped = [
{"escenario": n, "n": int(m.sum()), "fallecidos": int(all_event[m].sum())}
for n, m in masks.items()
if n not in drawn
]
combinations = spec._combinations(train).value_counts().reset_index(name="members") combinations = spec._combinations(train).value_counts().reset_index(name="members")
survival = model.survival(combinations.replace(UNKNOWN, None)) survival = model.survival(combinations.replace(UNKNOWN, None))
return { return {
@@ -506,28 +448,11 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
FACTOR_COLUMNS = ( FACTOR_COLUMNS = (
"tipo", "tipo", "variable", "categoria", "referencia", "n_categoria", "OR_muerte", "IC95_inf",
"variable", "IC95_sup", "p", "p_ajustado_BH", "en_manta_markov", "S_categoria", "S_referencia",
"categoria", "delta_S", "delta_IC95_inf", "delta_IC95_sup", "c1_or", "c3_manta_markov",
"referencia", "c4_supervivencia", "criterios_cumplidos", "clasificacion",
"n_categoria", ) # fmt: skip
"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",
)
SURVIVAL_COLUMNS = ("S_categoria", "S_referencia", "delta_S") SURVIVAL_COLUMNS = ("S_categoria", "S_referencia", "delta_S")
TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)" TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)"
EVALUATED = ("c1_or", "c3_manta_markov", "c4_supervivencia") EVALUATED = ("c1_or", "c3_manta_markov", "c4_supervivencia")
@@ -537,11 +462,11 @@ def risk_factors(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) ->
from models import factors as rated from models import factors as rated
horizon = spec.borders[-1] horizon = spec.borders[-1]
months, event = (members["months"].to_numpy(), members["event"].to_numpy(bool)) months, event = members["months"].to_numpy(), members["event"].to_numpy(bool)
died = event & (months < horizon) died = event & (months < horizon)
known = died | (months >= horizon) known = died | (months >= horizon)
data = spec._combinations(members)[known].reset_index(drop=True) data = spec._combinations(members)[known].reset_index(drop=True)
y, months, event = (died[known].astype(int), months[known], event[known]) y, months, event = died[known].astype(int), months[known], event[known]
empty = pd.DataFrame(columns=list(FACTOR_COLUMNS)) empty = pd.DataFrame(columns=list(FACTOR_COLUMNS))
if len(data) == 0 or y.min() == y.max(): if len(data) == 0 or y.min() == y.max():
return empty return empty
@@ -552,14 +477,14 @@ def risk_factors(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) ->
blanket = {features[j] for _, (parents, _) in model.fitted_ for j in parents} blanket = {features[j] for _, (parents, _) in model.fitted_ for j in parents}
def complete(table, variables): def complete(table, variables):
return rated.complete( return rated.complete(table, variables, reference, data, months, event, horizon,
table, variables, reference, data, months, event, horizon, SURVIVAL_COLUMNS SURVIVAL_COLUMNS) # fmt: skip
)
with warnings.catch_warnings(), np.errstate(over="ignore", divide="ignore"): with warnings.catch_warnings(), np.errstate(over="ignore", divide="ignore"):
warnings.simplefilter("ignore") warnings.simplefilter("ignore")
try: try:
tab = complete(rated.odds_ratios(data, y, intrinsic, reference, "OR_muerte"), intrinsic) tab = complete(rated.odds_ratios(data, y, intrinsic, reference, "OR_muerte"),
intrinsic) # fmt: skip
except (np.linalg.LinAlgError, ValueError): except (np.linalg.LinAlgError, ValueError):
return empty return empty
tab["c2_estabilidad"] = np.nan tab["c2_estabilidad"] = np.nan
@@ -574,10 +499,9 @@ def risk_factors(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) ->
tr = None tr = None
if tr is not None: if tr is not None:
of = tr["termino"].map(lambda x: rated.variable_of(x, both)) of = tr["termino"].map(lambda x: rated.variable_of(x, both))
tr = complete( tr = complete(tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)],
tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)], treatment treatment) # fmt: skip
) tr["tipo"], tr["clasificacion"] = "tratamiento", TREATMENT_CLASS
tr["tipo"], tr["clasificacion"] = ("tratamiento", TREATMENT_CLASS)
tab = pd.concat([tab, tr], ignore_index=True) tab = pd.concat([tab, tr], ignore_index=True)
tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int) tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int)
tab["_order"] = tab["clasificacion"].map(rated.ORDER).fillna(5) tab["_order"] = tab["clasificacion"].map(rated.ORDER).fillna(5)
@@ -594,14 +518,10 @@ def scenario_factors(spec: Spec, members: pd.DataFrame, table: pd.DataFrame) ->
for name, mask in scenario_masks(members, spec.scenarios).items(): for name, mask in scenario_masks(members, spec.scenarios).items():
if not mask.any() or found.empty: if not mask.any() or found.empty:
continue continue
rows.append( rows.append({
{ "escenario": name, "condiciones": [list(c) for c in spec.scenarios[name]],
"escenario": name, "n_escenario": int(mask.sum()), **rated.scenario_row(data, mask, found),
"condiciones": [list(c) for c in spec.scenarios[name]], }) # fmt: skip
"n_escenario": int(mask.sum()),
**rated.scenario_row(data, mask, found),
}
)
return rows return rows
-1
View File
@@ -1 +0,0 @@
+456 -220
View File
@@ -1,29 +1,170 @@
from __future__ import annotations
import json
import warnings import warnings
from dataclasses import dataclass, field from dataclasses import dataclass, field
from pathlib import Path
import mlflow.pyfunc
import numpy as np import numpy as np
import pandas as pd import pandas as pd
from scipy import optimize, stats from scipy import optimize, stats
from scipy.special import expit from scipy.special import expit
from statsmodels.stats.multitest import multipletests
from core.tea import association as spec from core.tea import ADOS2_ITEMS
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")
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"},
),
}
ZONE_ITEMS = {
"frontal_left": (1, 2, 3, 9, 10, 11, 12, 14, 15, 16),
"frontal_right": (4, 5, 7, 14, 22),
"frontal_midline": (6, 11, 12, 13, 14),
"central": (21,),
"parietal": (6, 13, 20),
"temporal_left": (1, 16, 18, 19),
"temporal_right": (4, 5, 8),
"occipital": (4, 20),
}
SPINDLE_ZONES = ("frontal_left", "frontal_right", "frontal_midline", "central", "parietal")
RHYTHM_ITEMS = (20, 22)
CSS = "CSS"
CSS_HIGH = 8
ALTERED = 1
def item_code(n: int) -> str:
return f"ados2_item_{n:02d}"
def pairs(level: str) -> list[dict]:
out = []
for zone in ZONES:
outcomes = [("item", n) for n in ZONE_ITEMS[zone]] if level == "item" else [("domain", CSS)]
out += [
{
"biomarker": "spikes",
"zone": zone,
"predictor": f"z_spikes_{zone}",
"kind": k,
"outcome": o,
}
for k, o in outcomes
]
out += [
{
"biomarker": "spindles",
"zone": zone,
"predictor": f"z_spindles_{zone}",
"kind": "domain",
"outcome": CSS,
}
for zone in SPINDLE_ZONES
]
rhythm = [("item", n) for n in RHYTHM_ITEMS] if level == "item" else [("domain", CSS)]
out += [
{
"biomarker": "posterior_rhythm",
"zone": "posterior",
"predictor": "z_posterior_rhythm",
"kind": k,
"outcome": o,
}
for k, o in rhythm
]
out.append(
{
"biomarker": "gradient",
"zone": "global",
"predictor": "z_gradient",
"kind": "domain",
"outcome": CSS,
}
)
return out
def algorithm_score(v) -> pd.Series:
v = pd.to_numeric(pd.Series(v), errors="coerce")
return v.where(~v.isin([7, 8, 9]), 0).clip(upper=2)
def item_scores(cohort: pd.DataFrame, n: int) -> pd.Series:
column = ADOS2_ITEMS[n - 1]
if "ados_module" not in cohort or column not in cohort:
return pd.Series(np.nan, index=cohort.index)
return algorithm_score(cohort[column]).where(cohort["ados_module"].isin(ITEMS[n][2]))
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)) CHI2_95 = float(stats.chi2.ppf(0.95, 1))
MIN_ROWS = 8 MIN_ROWS = 8
TOO_FEW = "too few data or no variation"
def item_scores(frame: pd.DataFrame, number: int) -> pd.Series:
name, modules = spec.ITEMS[number]
if name not in frame or "module" not in frame:
return pd.Series(np.nan, index=frame.index)
v = pd.to_numeric(frame[name], errors="coerce")
v = v.where(~v.isin(spec.NOT_APPLICABLE), 0).clip(upper=2)
return v.where(frame["module"].isin(modules))
def has_items(frame: pd.DataFrame) -> bool:
scores = pd.concat([item_scores(frame, n) for n in spec.ITEMS], axis=1)
return int(scores.notna().any(axis=1).sum()) >= spec.MIN_ITEM_CHILDREN
@dataclass @dataclass
@@ -34,42 +175,51 @@ class Design:
reference: dict[str, str] = field(default_factory=dict) reference: dict[str, str] = field(default_factory=dict)
@classmethod @classmethod
def of(cls, t: pd.DataFrame, predictor: str) -> "Design": def of(cls, t: pd.DataFrame, predictor: str, adjust) -> Design:
d = cls(predictor) d = cls(predictor)
for a in (a for a in spec.ADJUST if a in t): for a in adjust:
if a not in t:
continue
v = t[a] v = t[a]
if pd.api.types.is_numeric_dtype(v): if pd.api.types.is_numeric_dtype(v):
if v.astype(float).std() > 0: v = v.astype(float)
d.numeric[a] = float(v.astype(float).mean()) if v.std() > 0:
continue d.numeric[a] = float(v.mean())
commonest = v.value_counts().index[0] else:
levels = [x for x in sorted(set(v) - {commonest}) if 0 < (v == x).sum() < len(v)] ref = v.value_counts().index[0]
if levels: levels = [lv for lv in sorted(set(v) - {ref}) if 0 < (v == lv).sum() < len(v)]
d.categorical[a], d.reference[a] = ([str(x) for x in levels], str(commonest)) if levels:
d.categorical[a] = [str(lv) for lv in levels]
d.reference[a] = str(ref)
return d return d
@property @property
def names(self) -> list[str]: def names(self) -> list[str]:
return [ return ["intercept", self.predictor, *self.numeric] + [
"intercept", f"{a}={lv}" for a, levels in self.categorical.items() for lv in levels
self.predictor,
*self.numeric,
*(f"{a}={x}" for a, levels in self.categorical.items() for x in levels),
] ]
def matrix(self, t: pd.DataFrame) -> np.ndarray: def matrix(self, t: pd.DataFrame) -> np.ndarray:
cols = [np.ones(len(t)), t[self.predictor].to_numpy(float)] cols = [np.ones(len(t)), t[self.predictor].to_numpy(float)]
cols += [t[a].to_numpy(float) - mean for a, mean in self.numeric.items()] 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) known = np.ones(len(t), bool)
for a, levels in self.categorical.items(): for a, levels in self.categorical.items():
v = t[a].astype(str) seen = {self.reference[a], *levels}
cols += [(v == x).to_numpy(float) for x in levels] known &= (
known &= v.isin({self.reference[a], *levels}).to_numpy() & t[a].notna().to_numpy() t[a].astype(str).isin(seen).to_numpy() & t[a].notna().to_numpy()
X = np.column_stack(cols) if a in t
else False
)
X[~known] = np.nan X[~known] = np.nan
return X return X
def state(self) -> dict: def to_dict(self) -> dict:
return { return {
"predictor": self.predictor, "predictor": self.predictor,
"numeric": self.numeric, "numeric": self.numeric,
@@ -78,282 +228,368 @@ class Design:
} }
@classmethod @classmethod
def from_state(cls, s: dict) -> "Design": def from_dict(cls, d: dict) -> Design:
return cls( return cls(
s["predictor"], d["predictor"],
dict(s["numeric"]), dict(d["numeric"]),
{k: list(v) for k, v in s["categorical"].items()}, {k: list(v) for k, v in d["categorical"].items()},
dict(s["reference"]), dict(d["reference"]),
) )
def _penalised(b, X, y) -> float: def _pl(b, X, y):
eta = X @ b eta = X @ b
w = expit(eta) * (1 - expit(eta)) p = expit(eta)
w = p * (1 - p)
sign, logdet = np.linalg.slogdet(X.T @ (X * w[:, None])) sign, logdet = np.linalg.slogdet(X.T @ (X * w[:, None]))
return -np.inf if sign <= 0 else float(np.sum(y * eta - np.logaddexp(0, eta)) + logdet / 2) if sign <= 0:
return -np.inf
return float(np.sum(y * eta - np.logaddexp(0, eta)) + 0.5 * logdet)
def _gradient(b, X, y): def _score(b, X, y):
p = expit(X @ b) p = expit(X @ b)
w = p * (1 - p) w = p * (1 - p)
info = X.T @ (X * w[:, None]) info = X.T @ (X * w[:, None])
leverage = np.einsum("ij,jk,ik->i", X, np.linalg.inv(info), X) * w h = np.einsum("ij,jk,ik->i", X, np.linalg.inv(info), X) * w
return (X.T @ (y - p + leverage * (0.5 - p)), info) return X.T @ (y - p + h * (0.5 - p)), info
def _firth_fit(X, y, max_iter=200, tol=1e-10): def _fit_firth(X, y, max_iter=200, tol=1e-10):
b = np.zeros(X.shape[1]) b = np.zeros(X.shape[1])
best = _penalised(b, X, y) pl = _pl(b, X, y)
for _ in range(max_iter): for _ in range(max_iter):
score, info = _gradient(b, X, y) U, info = _score(b, X, y)
step, t = (np.linalg.solve(info, score), 1.0) step = np.linalg.solve(info, U)
while t > 1e-08: t = 1.0
trial = _penalised(b + t * step, X, y) while t > 1e-8:
if trial >= best - 1e-12: nb = b + t * step
npl = _pl(nb, X, y)
if npl >= pl - 1e-12:
break break
t /= 2 t /= 2
b, best = (b + t * step, trial) b, pl = nb, npl
if np.max(np.abs(t * step)) < tol: if np.max(np.abs(t * step)) < tol:
break break
return (b, best) return b, pl
def _firth_profile(value, j, X, y, start) -> float: def _profile_firth(value, j, X, y, b0):
free = [k for k in range(X.shape[1]) if k != j] free = [k for k in range(X.shape[1]) if k != j]
def negative(bf): def f(bf):
b = np.empty(X.shape[1]) b = np.empty(X.shape[1])
b[free], b[j] = (bf, value) b[free], b[j] = bf, value
v = _penalised(b, X, y) v = _pl(b, X, y)
if not np.isfinite(v): if not np.isfinite(v):
return (10000000000.0, np.zeros(len(free))) return 1e10, np.zeros(len(free))
return (-v, -_gradient(b, X, y)[0][free]) U, _ = _score(b, X, y)
return -v, -U[free]
return -float(optimize.minimize(negative, start[free], jac=True, method="BFGS").fun) return -float(optimize.minimize(f, b0[free], jac=True, method="BFGS").fun)
def _interval(profile, centre, maximum, scale) -> tuple[float, float]: def _interval(profile, centre, maximum, scale):
drop = lambda v: 2 * (maximum - profile(v)) - CHI2_95 g = lambda v: 2 * (maximum - profile(v)) - CHI2_95 # noqa: E731
limits = [] limits = []
for sign in (-1, 1): for sign in (-1, 1):
previous, limit = (centre, sign * np.inf) previous, limit = centre, sign * np.inf
for k in range(1, 80): for k in range(1, 80):
v = centre + sign * scale * k v = centre + sign * scale * k
if drop(v) > 0: if g(v) > 0:
limit = optimize.brentq(drop, min(previous, v), max(previous, v)) limit = optimize.brentq(g, min(previous, v), max(previous, v))
break break
previous = v previous = v
limits.append(limit) limits.append(limit)
return (limits[0], limits[1]) return limits[0], limits[1]
def _summary(model, n, coef, low, high, p, design, state, **extra) -> dict: def _summary(model, n, coef, lo, hi, p, design, state, **extra) -> dict:
return { return {
"model": model, "model": model,
"n": n, "n": n,
"coef": round(float(coef), 4), "coef": round(float(coef), 4),
"odds_ratio": round(float(np.exp(coef)), 4), "odds_ratio": round(float(np.exp(coef)), 4),
"ci_low": round(float(np.exp(low)), 4), "ci_low": round(float(np.exp(lo)), 4),
"ci_high": round(float(np.exp(high)), 4), "ci_high": round(float(np.exp(hi)), 4),
"p": round(p, 5), "p": round(p, 5),
"adjusted_for": ", ".join(design.names[2:]), "adjusted_for": ", ".join(design.names[2:]),
"reason": "", "reason": "",
**extra, **extra,
"state": {"design": design.state(), **state}, "state": {"design": design.to_dict(), **state},
} }
def firth(t: pd.DataFrame, outcome: str, predictor: str) -> dict: def firth(t: pd.DataFrame, outcome: str, predictor: str, adjust) -> dict:
d = t[[outcome, predictor, *(a for a in spec.ADJUST if a in t)]].dropna() d = t[[outcome, predictor, *[a for a in adjust if a in t]]].dropna()
y = d[outcome].to_numpy(float) y = d[outcome].to_numpy(float)
out = {"model": "firth", "n": len(d), "events": int(y.sum())} out = {"model": "firth", "n": len(d), "events": int(y.sum())}
if len(d) < MIN_ROWS or y.sum() < 2 or y.sum() > len(y) - 2 or (d[predictor].std() == 0): if len(d) < MIN_ROWS or y.sum() < 2 or y.sum() > len(y) - 2 or d[predictor].std() == 0:
return {**out, "reason": TOO_FEW} return {**out, "reason": "too few data or no variation"}
design = Design.of(d, predictor) design = Design.of(d, predictor, adjust)
X = design.matrix(d) X = design.matrix(d)
b, top = _firth_fit(X, y) b, pl = _fit_firth(X, y)
se = float(np.sqrt(np.linalg.inv(_gradient(b, X, y)[1])[1, 1])) _, info = _score(b, X, y)
profile = lambda v: _firth_profile(v, 1, X, y, b) se = float(np.sqrt(np.linalg.inv(info)[1, 1]))
low, high = _interval(profile, b[1], top, max(se, 0.05)) profile = lambda v: _profile_firth(v, 1, X, y, b) # noqa: E731
p = float(stats.chi2.sf(max(2 * (top - profile(0.0)), 0.0), 1)) lo, hi = _interval(profile, b[1], pl, max(se, 0.05))
p = float(stats.chi2.sf(max(2 * (pl - profile(0.0)), 0.0), 1))
eta = X[:, 1:] @ b[1:] eta = X[:, 1:] @ b[1:]
intercept = optimize.brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50) flic = optimize.brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50)
state = {"beta": [float(v) for v in b[1:]], "intercept": float(intercept)} return _summary(
return _summary("firth", len(d), b[1], low, high, p, design, state, events=int(y.sum())) "firth",
len(d),
b[1],
def _ordinal_nll(par, X, y, K) -> float: lo,
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])]) hi,
eta = X @ par[K - 1 :] p,
n = len(y) design,
cdf = np.c_[np.zeros(n), expit(theta[None, :] - eta[:, None]), np.ones(n)] {"beta": [float(v) for v in b[1:]], "intercept": float(flic)},
return -float( events=int(y.sum()),
np.sum(np.log(np.clip(cdf[np.arange(n), y + 1] - cdf[np.arange(n), y], 1e-300, None)))
) )
def _ordinal_fit(X, y, K, fixed=None): 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])] start = np.r_[np.linspace(-1, 1, K - 1)[0], np.zeros(K - 2), np.zeros(X.shape[1])]
if fixed is None: if fixed is None:
r = optimize.minimize(lambda q: _ordinal_nll(q, X, y, K), start, method="BFGS") r = optimize.minimize(lambda q: _nll_ordinal(q, X, yk, K), start, method="BFGS")
return (r.x, float(r.fun)) return r.x, float(r.fun)
j, value = fixed j, value = fixed
free = [k for k in range(len(start)) if k != K - 1 + j] idx = [k for k in range(len(start)) if k != K - 1 + j]
def nll(q): def f(q):
par = np.empty(len(start)) par = np.empty(len(start))
par[free], par[K - 1 + j] = (q, value) par[idx], par[K - 1 + j] = q, value
return _ordinal_nll(par, X, y, K) return _nll_ordinal(par, X, yk, K)
return (None, float(optimize.minimize(nll, start[free], method="BFGS").fun)) return None, float(optimize.minimize(f, start[idx], method="BFGS").fun)
def ordinal(t: pd.DataFrame, outcome: str, predictor: str, high: float) -> dict: def ordinal(t: pd.DataFrame, outcome: str, predictor: str, adjust, high: float) -> dict:
d = t[[outcome, predictor, *(a for a in spec.ADJUST if a in t)]].dropna() d = t[[outcome, predictor, *[a for a in adjust if a in t]]].dropna()
levels = np.sort(d[outcome].unique()) levels = np.sort(d[outcome].unique())
out = {"model": "ordinal", "n": len(d), "levels": len(levels)} out = {"model": "ordinal", "n": len(d), "levels": len(levels)}
if len(d) < MIN_ROWS or len(levels) < 2 or d[predictor].std() == 0: if len(d) < MIN_ROWS or len(levels) < 2 or d[predictor].std() == 0:
return {**out, "reason": TOO_FEW} return {**out, "reason": "too few data or no variation"}
design = Design.of(d, predictor) design = Design.of(d, predictor, adjust)
X = design.matrix(d)[:, 1:] X = design.matrix(d)[:, 1:]
K = len(levels) K = len(levels)
y = np.searchsorted(levels, d[outcome].to_numpy()) yk = np.searchsorted(levels, d[outcome].to_numpy())
with warnings.catch_warnings(): with warnings.catch_warnings():
warnings.simplefilter("ignore") warnings.simplefilter("ignore")
par, nll = _ordinal_fit(X, y, K) par, nll = _fit_ordinal(X, yk, K)
beta = par[K - 1 :] beta = par[K - 1 :]
if abs(beta[0]) > 20: if abs(beta[0]) > 20:
return {**out, "reason": "does not converge (separation)"} return {**out, "reason": "does not converge (separation)"}
profile = lambda v: -_ordinal_fit(X, y, K, fixed=(0, v))[1] profile = lambda v: -_fit_ordinal(X, yk, K, fixed=(0, v))[1] # noqa: E731
low, high_ = _interval(profile, beta[0], -nll, 0.1) lo, hi = _interval(profile, beta[0], -nll, 0.1)
p = float(stats.chi2.sf(max(2 * (-nll - profile(0.0)), 0.0), 1)) p = float(stats.chi2.sf(max(2 * (-nll - profile(0.0)), 0.0), 1))
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])]) theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
k = int(np.searchsorted(levels, high)) k = int(np.searchsorted(levels, high))
inside = 0 < k < K return _summary(
state = { "ordinal",
"beta": [float(v) for v in beta], len(d),
"threshold": float(theta[k - 1]) if inside else None, beta[0],
"always": None if inside else float(k == 0), lo,
} hi,
return _summary("ordinal", len(d), beta[0], low, high_, p, design, state, levels=K) p,
design,
{
def probability(fit: dict, t: pd.DataFrame) -> tuple[np.ndarray, float]: "beta": [float(v) for v in beta],
s = fit["state"] "threshold": float(theta[k - 1]) if 0 < k < K else None,
X = Design.from_state(s["design"]).matrix(t) "always": None if 0 < k < K else float(k == 0),
if fit["model"] == "firth": },
return ( levels=K,
expit(s["intercept"] + X[:, 1:] @ np.asarray(s["beta"])),
float(expit(s["intercept"])),
)
if s["threshold"] is None:
return (np.where(np.isnan(X[:, 1:]).any(axis=1), np.nan, s["always"]), s["always"])
return (
1 - expit(s["threshold"] - X[:, 1:] @ np.asarray(s["beta"])),
float(1 - expit(s["threshold"])),
) )
def _guarded(fit, *args) -> dict: 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 _outcome(cohort: pd.DataFrame, pair: dict) -> tuple[pd.Series, pd.Series]:
if pair["kind"] == "item":
score = item_scores(cohort, pair["outcome"])
return (score >= ALTERED).astype(float).where(score.notna()), score
css = pd.to_numeric(cohort.get("css", pd.Series(np.nan, index=cohort.index)), errors="coerce")
return (css >= CSS_HIGH).astype(float).where(css.notna()), css
def _guarded(fit, model: str, *args, **kwargs) -> dict:
try: try:
return fit(*args) return fit(*args, **kwargs)
except (np.linalg.LinAlgError, ValueError) as error: except (np.linalg.LinAlgError, ValueError) as error:
model = "firth" if fit is firth else "ordinal"
return {"model": model, "n": 0, "reason": f"singular design ({type(error).__name__})"} return {"model": model, "n": 0, "reason": f"singular design ({type(error).__name__})"}
def fit(cohort: pd.DataFrame, level: str = "auto") -> dict: def _models(d: pd.DataFrame, pair: dict) -> tuple[dict, dict]:
if level == "auto": p = pair["predictor"]
level = "item" if has_items(cohort) else "domain" fit_firth = lambda: _guarded(firth, "firth", d, "_yes", p, ADJUST) # noqa: E731
rows = [] if pair["kind"] == "item":
for pair in spec.pairs(level): return fit_firth(), _guarded(ordinal, "ordinal", d, "_level", p, ADJUST, high=ALTERED)
if pair["predictor"] not in cohort: return _guarded(ordinal, "ordinal", d, "_level", p, ADJUST, high=CSS_HIGH), fit_firth()
continue
d = cohort.copy()
d[pair["predictor"]] = d[pair["predictor"]].replace([np.inf, -np.inf], np.nan)
if pair["kind"] == "item":
d["_level"] = item_scores(cohort, pair["outcome"])
d["_yes"] = (d["_level"] >= spec.ALTERED).astype(float).where(d["_level"].notna())
principal = _guarded(firth, d, "_yes", pair["predictor"])
sensitivity = _guarded(ordinal, d, "_level", pair["predictor"], spec.ALTERED)
else:
d["_level"] = pd.to_numeric(cohort.get("css"), errors="coerce")
d["_yes"] = (d["_level"] >= spec.CSS_HIGH).astype(float).where(d["_level"].notna())
principal = _guarded(ordinal, d, "_level", pair["predictor"], spec.CSS_HIGH)
sensitivity = _guarded(firth, d, "_yes", pair["predictor"])
rows.append({**pair, "principal": principal, "sensitivity": sensitivity})
p = np.array([r["principal"].get("p", np.nan) for r in rows], float)
biomarkers = np.array([r["biomarker"] for r in rows])
q = np.full(len(rows), np.nan)
for b in dict.fromkeys(biomarkers):
mine = (biomarkers == b) & np.isfinite(p)
if mine.any():
q[mine] = multipletests(p[mine], method="fdr_bh")[1].round(5)
for r, v in zip(rows, q, strict=True):
r["q"] = None if np.isnan(v) else float(v)
return {"level": level, "n": len(cohort), "rows": rows}
def outcome_code(row: dict) -> str: def _probability(fit: dict, t: pd.DataFrame) -> tuple[np.ndarray, float]:
return spec.item_code(row["outcome"]) if row["kind"] == "item" else spec.CSS if fit["model"] == "firth":
return firth_probability(fit["state"], t), firth_reference(fit["state"])
return ordinal_probability(fit["state"], t), ordinal_reference(fit["state"])
def associations(fitted: dict) -> list[dict]: class Ados2Association:
out = [] name = "ados2_association"
for r in fitted["rows"]: version = "0.1.0"
f, s = (r["principal"], r["sensitivity"]) impl = "modern"
ratio, other = (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": f">={(spec.ALTERED if r['kind'] == 'item' else spec.CSS_HIGH)}",
"model": f["model"],
"n": f["n"],
"odds_ratio": ratio,
"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": other,
"same_direction": None
if ratio is None or other is None
else bool(np.sign(ratio - 1) == np.sign(other - 1)),
"reason": f.get("reason", ""),
}
)
return out
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}")
self.level = level
self.fitted = fitted
def score(fitted: dict, cohort: pd.DataFrame) -> list[dict]: def fit(self, cohort: pd.DataFrame) -> Ados2Association:
out = [] level = self.level if self.level != "auto" else ("item" if has_items(cohort) else "domain")
for r in fitted["rows"]: rows = []
f = r["principal"] for pair in pairs(level):
if f.get("odds_ratio") is None or r["predictor"] not in cohort: if pair["predictor"] not in cohort:
continue continue
t = cohort d = cohort.copy()
if r["kind"] == "item": d[pair["predictor"]] = d[pair["predictor"]].replace([np.inf, -np.inf], np.nan)
t = cohort[cohort["module"].isin(spec.ITEMS[r["outcome"]][1])] d["_yes"], d["_level"] = _outcome(cohort, pair)
t = t[t[r["predictor"]].notna()] principal, sensitivity = _models(d, pair)
if not len(t): rows.append({**pair, "principal": principal, "sensitivity": sensitivity})
continue q = np.full(len(rows), np.nan)
found, reference = probability(f, t) biomarkers = np.array([r["biomarker"] for r in rows])
for key, z, p in zip(t["key"], t[r["predictor"]].to_numpy(float), found, strict=True): p = np.array([r["principal"].get("p", np.nan) for r in rows], float)
if np.isfinite(p): for b in dict.fromkeys(biomarkers):
out.append( q[biomarkers == b] = bh(p[biomarkers == b]).round(5)
for r, v in zip(rows, q, strict=True):
r["q"] = None if np.isnan(v) else float(v)
self.fitted = {"level": level, "n": len(cohort), "rows": rows}
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"]
kind = r["kind"]
ors, sens = f.get("odds_ratio"), s.get("odds_ratio")
out.append(
{
"biomarker": r["biomarker"],
"zone": r["zone"],
"kind": kind,
"outcome": r["outcome"],
"outcome_code": item_code(r["outcome"]) if kind == "item" else CSS,
"event": f">={ALTERED if kind == 'item' else CSS_HIGH}",
"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) -> pd.DataFrame:
parts = []
for r in self._rows():
f = r["principal"]
if f.get("odds_ratio") is None or r["predictor"] not in cohort:
continue
t = cohort
if r["kind"] == "item":
modules = set(ITEMS[r["outcome"]][2])
t = cohort[cohort["ados_module"].isin(modules)]
t = t[t[r["predictor"]].notna()]
if not len(t):
continue
prob, ref = _probability(f, t)
kept = np.isfinite(prob)
parts.append(
pd.DataFrame(
{ {
"key": key, "key": t["key"].to_numpy()[kept],
"biomarker": r["biomarker"], "biomarker": r["biomarker"],
"zone": r["zone"], "zone": r["zone"],
"outcome_code": outcome_code(r), "outcome_code": item_code(r["outcome"]) if r["kind"] == "item" else CSS,
"z": float(z), "z": t[r["predictor"]].to_numpy(float)[kept],
"probability": round(float(p), 4), "probability": prob[kept].round(4),
"reference_probability": round(reference, 4), "reference_probability": round(ref, 4),
} }
) )
return out )
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)
-1
View File
@@ -1 +0,0 @@
pass
+4 -7
View File
@@ -1,8 +1,9 @@
import math
import re import re
from dataclasses import dataclass, field from dataclasses import dataclass, field
from datetime import date from datetime import date
from models.tea.eeg import biomarkers, checks, preprocess, read, sleep from models.tea.eeg import biomarkers, checks, preprocess, read, sleep
from models.tea.eeg.curves import _number
DAYS_PER_MONTH = 30.4375 DAYS_PER_MONTH = 30.4375
MAINS_HZ = 60.0 MAINS_HZ = 60.0
@@ -33,12 +34,8 @@ class Analysis:
error: str | None error: str | None
def _number(v) -> float | None:
return float(v) if v is not None and math.isfinite(v) else None
def _error(exc: Exception) -> str: def _error(exc: Exception) -> str:
message = re.sub("(/|[A-Za-z]:\\\\)[^\\s'\\\"]*", "<path>", str(exc))[:300] message = re.sub(r"(/|[A-Za-z]:\\)[^\s'\"]*", "<path>", str(exc))[:300]
return f"{type(exc).__name__}: {message}" return f"{type(exc).__name__}: {message}"
@@ -110,5 +107,5 @@ def analyze(
features={s: {k: _number(v) for k, v in f.items()} for s, f in features.items()}, features={s: {k: _number(v) for k, v in f.items()} for s, f in features.items()},
) )
return Analysis(**out) return Analysis(**out)
except Exception as exc: except Exception as exc: # noqa: BLE001
return Analysis(**out | dict(error=_error(exc))) return Analysis(**out | dict(error=_error(exc)))
+8 -23
View File
@@ -2,32 +2,17 @@ import numpy as np
from scipy.fft import rfft, rfftfreq from scipy.fft import rfft, rfftfreq
from scipy.signal.windows import hann from scipy.signal.windows import hann
from scipy.stats import theilslopes from scipy.stats import theilslopes
from models.tea.eeg import signals, spikes, spindles from models.tea.eeg import signals, spikes, spindles
from models.tea.eeg.preprocess import WINDOW_S, Prepared from models.tea.eeg.preprocess import WINDOW_S, Prepared
from models.tea.eeg.sleep import POSTERIOR from models.tea.eeg.sleep import POSTERIOR
MIN_WINDOWS = 15 MIN_WINDOWS = 15
FRONT_BACK = { FRONT_BACK = {
"Fp1": 0.95, "Fp1": 0.95, "Fp2": 0.95, "F7": 0.59, "F3": 0.53, "Fz": 0.50, "F4": 0.53, "F8": 0.59,
"Fp2": 0.95, "T3": 0.0, "C3": 0.0, "Cz": 0.0, "C4": 0.0, "T4": 0.0, "T5": -0.59, "P3": -0.53,
"F7": 0.59, "Pz": -0.50, "P4": -0.53, "T6": -0.59, "O1": -0.95, "O2": -0.95,
"F3": 0.53, } # fmt: skip
"Fz": 0.5,
"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.5,
"P4": -0.53,
"T6": -0.59,
"O1": -0.95,
"O2": -0.95,
}
CODES = ( CODES = (
"posterior_rhythm", "posterior_rhythm",
"spindles_n2", "spindles_n2",
@@ -41,7 +26,7 @@ def _segments(prep: Prepared, names, states, state) -> list[np.ndarray] | None:
starts = [s for s, label in zip(prep.starts, states, strict=True) if label == state] starts = [s for s, label in zip(prep.starts, states, strict=True) if label == state]
if len(starts) < MIN_WINDOWS or not names: if len(starts) < MIN_WINDOWS or not names:
return None return None
x, n = (prep.data(names), int(round(WINDOW_S * prep.fs))) x, n = prep.data(names), int(round(WINDOW_S * prep.fs))
found = [] found = []
for a in (int(round(float(s) * prep.fs)) for s in starts): 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(): if a + n <= len(x) and np.isfinite(x[a : a + n]).all():
@@ -77,7 +62,7 @@ def delta_gradient(prep: Prepared, states) -> float:
def measure(prep: Prepared, states, staged, intervals) -> tuple[dict, dict]: def measure(prep: Prepared, states, staged, intervals) -> tuple[dict, dict]:
metrics, features = ({}, {}) metrics, features = {}, {}
rhythm = posterior_rhythm(prep, states) rhythm = posterior_rhythm(prep, states)
metrics["posterior_rhythm"] = (rhythm, {}, {}) metrics["posterior_rhythm"] = (rhythm, {}, {})
features["eeg-posterior-rhythm"] = {"value": rhythm} features["eeg-posterior-rhythm"] = {"value": rhythm}
@@ -109,4 +94,4 @@ def measure(prep: Prepared, states, staged, intervals) -> tuple[dict, dict]:
gradient = delta_gradient(prep, states) gradient = delta_gradient(prep, states)
metrics["anteroposterior_gradient"] = (gradient, {}, {}) metrics["anteroposterior_gradient"] = (gradient, {}, {})
features["eeg-gradient"] = {"value": gradient} features["eeg-gradient"] = {"value": gradient}
return ({code: metrics[code] for code in CODES}, features) return {code: metrics[code] for code in CODES}, features
+34 -45
View File
@@ -1,32 +1,22 @@
from dataclasses import dataclass, field from dataclasses import dataclass, field
import numpy as np import numpy as np
from models.tea.eeg import signals from models.tea.eeg import signals
from models.tea.eeg.read import Recording from models.tea.eeg.read import Recording
NEIGHBOURS = { NEIGHBOURS = {
"Fp1": ("Fp2", "F3", "F7"), "Fp1": ("Fp2", "F3", "F7"), "Fp2": ("Fp1", "F4", "F8"), "F7": ("Fp1", "F3", "T3"),
"Fp2": ("Fp1", "F4", "F8"), "F8": ("Fp2", "F4", "T4"), "F3": ("Fp1", "F7", "Fz", "C3"), "F4": ("Fp2", "F8", "Fz", "C4"),
"F7": ("Fp1", "F3", "T3"), "Fz": ("F3", "F4", "Cz"), "T3": ("F7", "C3", "T5"), "T4": ("F8", "C4", "T6"),
"F8": ("Fp2", "F4", "T4"), "C3": ("F3", "T3", "Cz", "P3"), "C4": ("F4", "T4", "Cz", "P4"), "Cz": ("Fz", "C3", "C4", "Pz"),
"F3": ("Fp1", "F7", "Fz", "C3"), "T5": ("T3", "P3", "O1"), "T6": ("T4", "P4", "O2"), "P3": ("C3", "T5", "Pz", "O1"),
"F4": ("Fp2", "F8", "Fz", "C4"), "P4": ("C4", "T6", "Pz", "O2"), "Pz": ("Cz", "P3", "P4"), "O1": ("T5", "P3", "O2"),
"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"), "O2": ("T6", "P4", "O1"),
} } # fmt: skip
EAR_NEIGHBOURS = {"A1": ("T3", "T5", "F7"), "A2": ("T4", "T6", "F8")} EAR_NEIGHBOURS = {"A1": ("T3", "T5", "F7"), "A2": ("T4", "T6", "F8")}
MIN_CLEAN_PCT = 60.0 MIN_CLEAN_PCT = 60.0
MIN_COVERAGE = 0.9 MIN_COVERAGE = 0.90
MAX_BAD_SCALP = 2 MAX_BAD_SCALP = 2
MIN_SCALP = 12 MIN_SCALP = 12
MAX_LINE_DB = 45.0 MAX_LINE_DB = 45.0
@@ -42,10 +32,6 @@ class Validation:
line_db: float line_db: float
checks: list[dict] = field(default_factory=list) checks: list[dict] = field(default_factory=list)
@property
def ears_usable(self) -> bool:
return all((ear not in self.bad for ear in ("A1", "A2")))
def check( def check(
code, code,
@@ -86,7 +72,7 @@ def _temporal(v: np.ndarray) -> list[tuple[str, str]]:
if len(finite) < 10 or np.std(finite) < 0.5: if len(finite) < 10 or np.std(finite) < 0.5:
return [("dead-channel", "dead channel")] return [("dead-channel", "dead channel")]
out = [] out = []
if np.mean(np.abs(np.diff(finite)) < 1e-09) > 0.5: if np.mean(np.abs(np.diff(finite)) < 1e-9) > 0.5:
out.append(("frozen", "frozen")) out.append(("frozen", "frozen"))
if np.mean(np.abs(finite) > 0.98 * np.max(np.abs(finite))) > 0.001: if np.mean(np.abs(finite) > 0.98 * np.max(np.abs(finite))) > 0.001:
out.append(("saturated", "saturated")) out.append(("saturated", "saturated"))
@@ -98,9 +84,9 @@ def _temporal(v: np.ndarray) -> list[tuple[str, str]]:
def _contact(y: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]: def _contact(y: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
size = int(10 * fs) size = int(10 * fs)
blocks = len(y) // size blocks = len(y) // size
low, high = (np.full(y.shape[1], np.nan), np.full(y.shape[1], np.nan)) low, high = np.full(y.shape[1], np.nan), np.full(y.shape[1], np.nan)
if blocks < 6: if blocks < 6:
return (low, high) return low, high
sd = np.full((blocks, y.shape[1]), np.nan) sd = np.full((blocks, y.shape[1]), np.nan)
for b in range(blocks): for b in range(blocks):
block = y[b * size : (b + 1) * size] block = y[b * size : (b + 1) * size]
@@ -114,7 +100,7 @@ def _contact(y: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
if len(v) >= 6: if len(v) >= 6:
low[i] = np.mean((v < 0.25 * max(float(np.percentile(v, 75)), 1e-12)) & (v < 0.35)) 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) high[i] = np.mean(v > 4.0)
return (low, high) return low, high
def _bridges(y: np.ndarray, names: list[str], scalp: list[int]) -> dict[str, str]: def _bridges(y: np.ndarray, names: list[str], scalp: list[int]) -> dict[str, str]:
@@ -130,8 +116,8 @@ def _bridges(y: np.ndarray, names: list[str], scalp: list[int]) -> dict[str, str
if not near: if not near:
continue continue
best = max(near, key=lambda j: r[k, j]) 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)): 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)) out[name] = next(n for n, j in index.items() if j == best)
return out return out
@@ -152,7 +138,7 @@ def _ears(y: np.ndarray, fs: float, names: list[str]) -> dict[str, tuple[float,
def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, str]]]: 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()) x, fs, names, kinds = rec.x, rec.fs, list(rec.names), rec.kinds()
reasons = {name: _temporal(x[:, i]) for i, name in enumerate(names)} reasons = {name: _temporal(x[:, i]) for i, name in enumerate(names)}
dead = { dead = {
name for name, found in reasons.items() if found[:1] == [("dead-channel", "dead channel")] name for name, found in reasons.items() if found[:1] == [("dead-channel", "dead channel")]
@@ -169,7 +155,7 @@ def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, s
ears = _ears(y40, fs, names) ears = _ears(y40, fs, names)
missing = 1 - np.isfinite(x).mean(axis=0) missing = 1 - np.isfinite(x).mean(axis=0)
for i, name in enumerate(names): for i, name in enumerate(names):
found, k = (reasons[name], kinds[name]) found, k = reasons[name], kinds[name]
if missing[i] > missing.min() + 0.02: if missing[i] > missing.min() + 0.02:
excess = 100 * (missing[i] - missing.min()) excess = 100 * (missing[i] - missing.min())
found.append(("own-gaps", f"own gaps ({excess:.1f}% more than the rest)")) found.append(("own-gaps", f"own gaps ({excess:.1f}% more than the rest)"))
@@ -177,9 +163,9 @@ def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, s
continue continue
if k == "eeg" and name in bridges: if k == "eeg" and name in bridges:
found.append(("bridge", f"bridge with {bridges[name]}")) found.append(("bridge", f"bridge with {bridges[name]}"))
if k in ("eeg", "ear") and np.isfinite(ratio[i]) and (ratio[i] > 4.0): if k in ("eeg", "ear") and np.isfinite(ratio[i]) and ratio[i] > 4.0:
found.append(("amplitude", f"amplitude {ratio[i]:.1f} x the scalp median")) found.append(("amplitude", f"amplitude {ratio[i]:.1f} x the scalp median"))
if name in ears and ears[name][1] > 0.2 and (ears[name][0] < 0.5 * ears[name][1]): if name in ears and ears[name][1] > 0.2 and ears[name][0] < 0.5 * ears[name][1]:
c, e = ears[name] c, e = ears[name]
found.append( found.append(
( (
@@ -187,18 +173,19 @@ def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, s
f"does not correlate with its neighbours ({c:.2f} vs {e:.2f})", f"does not correlate with its neighbours ({c:.2f} vs {e:.2f})",
) )
) )
if np.isfinite(low[i]) and low[i] > 0.1: if np.isfinite(low[i]) and low[i] > 0.10:
found.append( found.append(
( (
"intermittent-contact", "intermittent-contact",
f"intermittent contact ({100 * low[i]:.0f}% of blocks silent)", f"intermittent contact ({100 * low[i]:.0f}% of blocks silent)",
) )
) )
if k in ("eeg", "ear") and np.isfinite(burst[i]) and (burst[i] > 0.05): if k in ("eeg", "ear") and np.isfinite(burst[i]) and burst[i] > 0.05:
found.append( found.append(
( (
"intermittent-bursts", "intermittent-bursts",
f"intermittent contact by bursts ({100 * burst[i]:.0f}% of blocks above 4 x the montage)", f"intermittent contact by bursts "
f"({100 * burst[i]:.0f}% of blocks above 4 x the montage)",
) )
) )
if k in ("eog", "ecg"): if k in ("eog", "ecg"):
@@ -207,7 +194,8 @@ def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, s
found.append( found.append(
( (
"aux-amplitude", "aux-amplitude",
f"amplitude {np.sqrt(np.mean(v**2)):.0f} uV, out of range even for {k.upper()}", f"amplitude {np.sqrt(np.mean(v**2)):.0f} uV, "
f"out of range even for {k.upper()}",
) )
) )
return {name: found for name, found in reasons.items() if found} return {name: found for name, found in reasons.items() if found}
@@ -243,20 +231,20 @@ def window_qc(y: np.ndarray, fs: float) -> list[tuple[float, float, str]]:
def _triage(rec: Recording, mains_hz: float, bad: dict, clean_pct: float, coverage: float): def _triage(rec: Recording, mains_hz: float, bad: dict, clean_pct: float, coverage: float):
x, fs, kinds = (rec.x, rec.fs, rec.kinds()) x, fs, kinds = rec.x, rec.fs, rec.kinds()
columns = [i for i, name in enumerate(rec.names) if kinds[name] in ("eeg", "ear")] 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) y = _filtered(x[:, columns], fs, mains_hz, 0.5, 45.0)
rms, flat = ({}, {}) rms, flat = {}, {}
for k, i in enumerate(columns): for k, i in enumerate(columns):
v = y[:, k][np.isfinite(y[:, k])] v = y[:, k][np.isfinite(y[:, k])]
rms[rec.names[i]] = float(np.nanstd(y[:, k])) if len(v) else np.nan 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-09)) if len(v) > 1 else 1.0 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") scalp = rec.of("eeg")
median = float(np.nanmedian([rms[n] for n in scalp])) if scalp else np.nan 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] 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 minutes = rec.duration_s * clean_pct / 100 / 60
base = coverage >= MIN_COVERAGE and len(triaged) <= MAX_BAD_SCALP base = coverage >= MIN_COVERAGE and len(triaged) <= MAX_BAD_SCALP
if not (base and clean_pct >= 30 and (minutes >= 3)): if not (base and clean_pct >= 30 and minutes >= 3):
level = NOT_ANALYZABLE level = NOT_ANALYZABLE
elif not (clean_pct >= 50 and minutes >= 3): elif not (clean_pct >= 50 and minutes >= 3):
level = "partial" level = "partial"
@@ -264,7 +252,7 @@ def _triage(rec: Recording, mains_hz: float, bad: dict, clean_pct: float, covera
level = "no_ear_reference" level = "no_ear_reference"
else: else:
level = "complete" level = "complete"
return (level, triaged) return level, triaged
def validate(rec: Recording, mains_hz: float) -> Validation: def validate(rec: Recording, mains_hz: float) -> Validation:
@@ -274,12 +262,13 @@ def validate(rec: Recording, mains_hz: float) -> Validation:
qc = usable if len(usable) >= 2 else scalp 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) 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) windows = window_qc(y, rec.fs)
clean_pct = 100.0 * sum((v == "clean" for *_, v in windows)) / max(len(windows), 1) 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()) coverage = float(np.isfinite(rec.x).all(axis=1).mean())
columns = [rec.names.index(n) for n in scalp] if scalp else slice(None) 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) db = signals.line_db(rec.x[:, columns], rec.fs, mains_hz)
line = float(np.nanmedian(db)) if np.isfinite(db).any() else np.nan line = float(np.nanmedian(db)) if np.isfinite(db).any() else np.nan
level, triaged = _triage(rec, mains_hz, flagged, clean_pct, coverage) level, triaged = _triage(rec, mains_hz, flagged, clean_pct, coverage)
rows = [ rows = [
check(code, electrode=name, text=reason, abnormal=True) check(code, electrode=name, text=reason, abnormal=True)
for name, found in flagged.items() for name, found in flagged.items()
@@ -326,6 +315,6 @@ def validate(rec: Recording, mains_hz: float) -> Validation:
"line-noise", value=line, unit="dB", high=MAX_LINE_DB, abnormal=line > MAX_LINE_DB "line-noise", value=line, unit="dB", high=MAX_LINE_DB, abnormal=line > MAX_LINE_DB
) )
) )
valid = level != NOT_ANALYZABLE and clean_pct >= MIN_CLEAN_PCT and (len(usable) >= MIN_SCALP) valid = level != NOT_ANALYZABLE and clean_pct >= MIN_CLEAN_PCT and len(usable) >= MIN_SCALP
bad = {name: [reason for _, reason in found] for name, found in flagged.items()} bad = {name: [reason for _, reason in found] for name, found in flagged.items()}
return Validation(valid, level, bad, clean_pct, line, rows) return Validation(valid, level, bad, clean_pct, line, rows)
+25 -17
View File
@@ -1,5 +1,6 @@
import math import math
from dataclasses import dataclass from dataclasses import dataclass
import numpy as np import numpy as np
import pandas as pd import pandas as pd
from scipy import stats from scipy import stats
@@ -35,13 +36,13 @@ PREFIX = {"electrodes": "electrode_", "zones": "zone_"}
def _weighted_quantile(x: np.ndarray, w: np.ndarray, q: float) -> float: def _weighted_quantile(x: np.ndarray, w: np.ndarray, q: float) -> float:
order = np.argsort(x) order = np.argsort(x)
x, w = (x[order], w[order]) x, w = x[order], w[order]
return float(np.interp(q, (np.cumsum(w) - 0.5 * w) / w.sum(), x)) return float(np.interp(q, (np.cumsum(w) - 0.5 * w) / w.sum(), x))
def _curve(values: np.ndarray, ages: np.ndarray) -> dict: def _curve(values: np.ndarray, ages: np.ndarray) -> dict:
ok = np.isfinite(values) & np.isfinite(ages) & (ages > 0) ok = np.isfinite(values) & np.isfinite(ages) & (ages > 0)
v, log_age = (values[ok], np.log(ages[ok])) v, log_age = values[ok], np.log(ages[ok])
curve = {"age_months": [], "n_effective": [], **{q: [] for q in QUANTILES}} curve = {"age_months": [], "n_effective": [], **{q: [] for q in QUANTILES}}
for a in CURVE_AGES: for a in CURVE_AGES:
w = np.exp(-0.5 * ((log_age - np.log(a)) / LOG_WIDTH) ** 2) w = np.exp(-0.5 * ((log_age - np.log(a)) / LOG_WIDTH) ** 2)
@@ -64,7 +65,7 @@ def _count_rate(values: np.ndarray, ages: np.ndarray, exposure: np.ndarray) -> d
n = np.round(values * exposure) n = np.round(values * exposure)
keep = np.isfinite(n) & np.isfinite(exposure) & (exposure > 0) keep = np.isfinite(n) & np.isfinite(exposure) & (exposure > 0)
keep &= (ages >= COUNT_AGES[0]) & (ages < COUNT_AGES[1]) keep &= (ages >= COUNT_AGES[0]) & (ages < COUNT_AGES[1])
n, x = (n[keep], exposure[keep]) n, x = n[keep], exposure[keep]
rate = float(n.sum() / x.sum()) if x.sum() > 0 else float("nan") rate = float(n.sum() / x.sum()) if x.sum() > 0 else float("nan")
mu = rate * x mu = rate * x
excess = float(((n - mu) ** 2 - n).sum()) excess = float(((n - mu) ** 2 - n).sum())
@@ -96,15 +97,22 @@ def _number(v) -> float | None:
return float(v) if v is not None and math.isfinite(v) else None return float(v) if v is not None and math.isfinite(v) else None
def _score_curve(baseline: dict, value: float, age: float) -> dict: def centiles(baseline_feature: dict, age_months: float) -> dict:
curve = pd.DataFrame(baseline["curve"]).astype(float).dropna() curve = pd.DataFrame(baseline_feature["curve"]).astype(float).dropna()
out = dict.fromkeys(("z", "outside", "p5", "median", "p95")) names = [name for name in QUANTILES if name in curve or name in ("p5", "median", "p95")]
if not len(curve) or not age > 0: if curve.empty or not age_months > 0:
return out return dict.fromkeys(names)
log_ages, at = (np.log(curve["age_months"].to_numpy()), float(np.log(np.array([age]))[0])) 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(): if not log_ages.min() <= at <= log_ages.max():
return out return dict.fromkeys(names)
q = {name: float(np.interp(at, log_ages, curve[name].to_numpy())) for name in QUANTILES} 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 dict.fromkeys(("z", "outside", "p5", "median", "p95"))
side = q["median"] - q["p5"] if value < q["median"] else q["p95"] - q["median"] 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 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 outside = -1 if value < q["p5"] else 1 if value > q["p95"] else 0
@@ -119,13 +127,13 @@ def _score_curve(baseline: dict, value: float, age: float) -> dict:
def _score_count(baseline: dict, value: float, age: float, exposure: float | None) -> dict: def _score_count(baseline: dict, value: float, age: float, exposure: float | None) -> dict:
out = dict.fromkeys(("z", "outside", "p5", "median", "p95")) out = dict.fromkeys(("z", "outside", "p5", "median", "p95"))
rate, k = (baseline["rate"], baseline["k"]) rate, k = baseline["rate"], baseline["k"]
lo, hi = baseline["ages"] lo, hi = baseline["ages"]
if exposure is None or not math.isfinite(rate) or (not (exposure > 0 and lo <= age < hi)): if exposure is None or not math.isfinite(rate) or not (exposure > 0 and lo <= age < hi):
return out return out
n, mu = (float(np.round(value * exposure)), rate * exposure) n, mu = float(np.round(value * exposure)), rate * exposure
law = stats.poisson(mu) if k is None else stats.nbinom(k, k / (k + mu)) law = stats.poisson(mu) if k is None else stats.nbinom(k, k / (k + mu))
tail, at = (law.sf(n - 1), law.pmf(n)) tail, at = law.sf(n - 1), law.pmf(n)
z = float(np.clip(stats.norm.ppf(1 - (tail - at / 2)), -Z_MAX, Z_MAX)) 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)) p5, median, p95 = (float(law.ppf(p)) / exposure for p in (0.05, 0.5, 0.95))
return {"z": z, "outside": 1 if tail < 0.05 else 0, "p5": p5, "median": median, "p95": p95} return {"z": z, "outside": 1 if tail < 0.05 else 0, "p5": p5, "median": median, "p95": p95}
@@ -134,7 +142,7 @@ def _score_count(baseline: dict, value: float, age: float, exposure: float | Non
def score( def score(
baseline: dict, value: float | None, age_months: float | None, exposure: float | None = None baseline: dict, value: float | None, age_months: float | None, exposure: float | None = None
) -> dict: ) -> dict:
value, age_months = (_number(value), _number(age_months)) value, age_months = _number(value), _number(age_months)
if value is None or age_months is None: if value is None or age_months is None:
return dict.fromkeys(("z", "outside", "p5", "median", "p95")) return dict.fromkeys(("z", "outside", "p5", "median", "p95"))
if baseline["kind"] == "count_rate": if baseline["kind"] == "count_rate":
@@ -146,7 +154,7 @@ def deviations(models: dict[str, dict], analysis) -> dict[str, dict]:
out = {m.code: {} for m in analysis.metrics} out = {m.code: {} for m in analysis.metrics}
metrics = {m.code: m for m in analysis.metrics} metrics = {m.code: m for m in analysis.metrics}
for name, scenario in SCENARIOS.items(): for name, scenario in SCENARIOS.items():
model, metric = (models.get(name), metrics.get(scenario.metric)) model, metric = models.get(name), metrics.get(scenario.metric)
if model is None or metric is None: if model is None or metric is None:
continue continue
exposure = analysis.features[name].get(EXPOSURE) if scenario.counts else None exposure = analysis.features[name].get(EXPOSURE) if scenario.counts else None
+5 -3
View File
@@ -1,6 +1,8 @@
import warnings import warnings
from dataclasses import dataclass from dataclasses import dataclass
import numpy as np import numpy as np
from models.tea.eeg import signals from models.tea.eeg import signals
from models.tea.eeg.checks import window_qc from models.tea.eeg.checks import window_qc
from models.tea.eeg.read import Recording from models.tea.eeg.read import Recording
@@ -41,11 +43,11 @@ def prepare(rec: Recording, bad) -> Prepared:
with warnings.catch_warnings(): with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning) warnings.simplefilter("ignore", RuntimeWarning)
referenced = y - np.nanmean(y, axis=1, keepdims=True) referenced = y - np.nanmean(y, axis=1, keepdims=True)
referenced = np.asfortranarray(referenced * 1e-06 * 1000000.0) referenced = np.asfortranarray(referenced * 1e-6 * 1e6)
qc = signals.bandpass(x, rec.fs, 0.5, 45.0) qc = signals.bandpass(x, rec.fs, 0.5, 45.0)
qc[gaps] = np.nan qc[gaps] = np.nan
unclean = tuple( unclean = tuple(
((float(t0), float(t1) - float(t0)) for t0, t1, v in window_qc(qc, rec.fs) if v != "clean") (float(t0), float(t1) - float(t0)) for t0, t1, v in window_qc(qc, rec.fs) if v != "clean"
) )
starts = np.arange(0.0, rec.duration_s - WINDOW_S + 1e-09, STEP_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) return Prepared(referenced, tuple(scalp), rec.fs, starts, unclean, rec.annotations)
+90 -11
View File
@@ -2,6 +2,8 @@ import io
import re import re
from dataclasses import dataclass from dataclasses import dataclass
from datetime import date, datetime from datetime import date, datetime
from struct import Struct
import edfio import edfio
import mne import mne
import numpy as np import numpy as np
@@ -23,8 +25,8 @@ def normalize(label: str) -> str | None:
text = str(label).strip() text = str(label).strip()
if not text or "ANNOT" in text.upper(): if not text or "ANNOT" in text.upper():
return None return None
stem = re.sub("^\\s*(EEG|ECG|EKG|EOG|EMG|POL)\\s+", "", text, flags=re.I).split("-")[0] stem = re.sub(r"^\s*(EEG|ECG|EKG|EOG|EMG|POL)\s+", "", text, flags=re.I).split("-")[0]
key = re.sub("[^A-Z0-9]", "", stem.strip().upper()) key = re.sub(r"[^A-Z0-9]", "", stem.strip().upper())
if key in CANONICAL: if key in CANONICAL:
name = CANONICAL[key] name = CANONICAL[key]
return RENAMED.get(name, name) return RENAMED.get(name, name)
@@ -59,13 +61,90 @@ class Recording:
return [name for name in self.names if kind(name) in kinds] return [name for name in self.names if kind(name) in kinds]
def _kept(edf: bytes) -> list[tuple[str, str]]: @dataclass(frozen=True)
if len(edf) < 256: 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)") raise FileNotValid("file too short to be an EDF (header < 256 bytes)")
def _fixed_header(data: bytes) -> dict:
_check_length(data)
try: try:
signals = edfio.read_edf(edf, lazy_load_data=True).signals (
except Exception as exc: 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 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: if not signals:
raise FileNotValid("the EDF declares zero signals") raise FileNotValid("the EDF declares zero signals")
named = [(s.label, normalize(s.label), float(s.sampling_frequency)) for s in signals] named = [(s.label, normalize(s.label), float(s.sampling_frequency)) for s in signals]
@@ -74,9 +153,9 @@ def _kept(edf: bytes) -> list[tuple[str, str]]:
raise FileNotValid("no recognised channel") raise FileNotValid("no recognised channel")
rates = [rate for _, _, rate in named] rates = [rate for _, _, rate in named]
fs = max(set(rates), key=rates.count) fs = max(set(rates), key=rates.count)
kept, seen = ([], set()) kept, seen = [], set()
for label, name, rate in named: for label, name, rate in named:
if abs(rate - fs) <= 1e-06 and name not in seen: if abs(rate - fs) <= 1e-6 and name not in seen:
seen.add(name) seen.add(name)
kept.append((label, name)) kept.append((label, name))
return kept return kept
@@ -93,11 +172,11 @@ def read(edf: bytes) -> Recording:
raw = mne.io.read_raw_edf(io.BytesIO(edf), encoding="latin1", **options) 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}) 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}] 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 * 1000000.0 x = raw.get_data(picks=names, reject_by_annotation="NaN", verbose="error").T * 1e6
start = raw.info.get("meas_date") start = raw.info.get("meas_date")
born = (raw.info.get("subject_info") or {}).get("birthday") born = (raw.info.get("subject_info") or {}).get("birthday")
notes = tuple( notes = tuple(
((float(a["onset"]), float(a["duration"]), a["description"]) for a in raw.annotations) (float(a["onset"]), float(a["duration"]), a["description"]) for a in raw.annotations
) )
return Recording( return Recording(
x=x, x=x,
@@ -110,7 +189,7 @@ def read(edf: bytes) -> Recording:
def age_months(start: date | None, birthday: date | None, days_per_month: float) -> float | None: 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): if start is None or birthday is None or start == UNKNOWN_START or birthday > start:
return None return None
months = round((start - birthday).days / days_per_month, 1) months = round((start - birthday).days / days_per_month, 1)
return months if months <= 216 else None return months if months <= 216 else None
+15 -13
View File
@@ -1,27 +1,28 @@
from pathlib import Path from pathlib import Path
import pandas as pd import pandas as pd
from models import cluster
from models import execution
from models.tea.eeg.analysis import analyze from models.tea.eeg.analysis import analyze
from models.tea.eeg.curves import SCENARIOS from models.tea.eeg.curves import SCENARIOS
NAME = "hk1k"
MAINS_HZ = 50.0
AGES = (16.0, 36.0) AGES = (16.0, 36.0)
def listing(folder: Path, ages_table: Path, ages=AGES) -> list[tuple[str, Path, float]]: def listing(folder: Path, ages_table: Path, ages=AGES) -> list[tuple[str, Path, float]]:
table = pd.read_csv(ages_table) table = pd.read_csv(ages_table)
years = dict(zip(table.iloc[:, 0].astype(str), table.iloc[:, 1].astype(float), strict=True)) months = dict(zip(table["path"].astype(str), table["age"].astype(float), strict=True))
found = [] found = []
for path in sorted((p for p in Path(folder).rglob("*") if p.suffix.lower() == ".edf")): for path in sorted(p for p in Path(folder).rglob("*") if p.suffix.lower() == ".edf"):
age = round(float(years[path.name] * 12), 1) if path.name in years else None age = months.get(path.relative_to(folder).as_posix())
if age is not None and age == age and (ages[0] <= age <= ages[1]): if age is not None and age == age and ages[0] <= age <= ages[1]:
found.append((path, age)) found.append((path, round(age, 1)))
return [(f"{NAME}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)] return [(f"{Path(folder).name}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)]
def _one(key: str, edf: bytes, age: float) -> dict: def _one(study: tuple[str, Path, float, float]) -> dict:
a = analyze(edf, age_months=age, mains_hz=MAINS_HZ) key, path, age, mains_hz = study
a = analyze(Path(path).read_bytes(), age_months=age, mains_hz=mains_hz)
return { return {
"key": key, "key": key,
"age_months": age, "age_months": age,
@@ -31,8 +32,9 @@ def _one(key: str, edf: bytes, age: float) -> dict:
} }
def measure(studies) -> list[dict]: def measure(studies, mains_hz: float, workers: int | None = None) -> list[dict]:
return cluster.run(_one, ((key, Path(path).read_bytes(), age) for key, path, age in studies)) 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]: def tables(measured: list[dict]) -> dict[str, pd.DataFrame]:
+9 -9
View File
@@ -58,7 +58,7 @@ def line_db(x: np.ndarray, fs: float, f0: float) -> np.ndarray:
f = np.fft.rfftfreq(len(run), 1 / fs) f = np.fft.rfftfreq(len(run), 1 / fs)
power = np.abs(np.fft.rfft(run * np.hanning(len(run))[:, None], axis=0)) ** 2 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) 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) around = ((f >= f0 - 6) & (f <= f0 - 2)) | ((f >= f0 + 2) & (f <= f0 + 6))
near = power[around].mean(axis=0) near = power[around].mean(axis=0)
with np.errstate(divide="ignore", invalid="ignore"): with np.errstate(divide="ignore", invalid="ignore"):
return 10 * np.log10(np.where(near > 0, peak / near, np.nan)) return 10 * np.log10(np.where(near > 0, peak / near, np.nan))
@@ -67,14 +67,14 @@ def line_db(x: np.ndarray, fs: float, f0: float) -> np.ndarray:
def periodograms(segments: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]: def periodograms(segments: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
n = segments.shape[-1] n = segments.shape[-1]
power, f = psd_array_welch(segments, fs, n_fft=n, n_per_seg=n, window="hann", verbose="error") power, f = psd_array_welch(segments, fs, n_fft=n, n_per_seg=n, window="hann", verbose="error")
return (f, power) return f, power
def fixed_lines(x: np.ndarray, fs: float, f_max: float) -> list[float]: def fixed_lines(x: np.ndarray, fs: float, f_max: float) -> list[float]:
n = int(round(8 * fs)) n = int(round(8 * fs))
f = np.fft.rfftfreq(n, 1 / fs) f = np.fft.rfftfreq(n, 1 / fs)
taper = np.hanning(n)[:, None] taper = np.hanning(n)[:, None]
total, count = (None, 0) total, count = None, 0
for a in range(0, len(x) - n + 1, n): for a in range(0, len(x) - n + 1, n):
segment = x[a : a + n] segment = x[a : a + n]
if np.isfinite(segment).all(): if np.isfinite(segment).all():
@@ -91,7 +91,7 @@ def fixed_lines(x: np.ndarray, fs: float, f_max: float) -> list[float]:
found = [] found = []
for i in range(1, len(f) - 1): for i in range(1, len(f) - 1):
p = prominence[i] p = prominence[i]
if not 1 <= f[i] <= f_max or p < 6 or p < prominence[i - 1] or (p < prominence[i + 1]): if not 1 <= f[i] <= f_max or p < 6 or p < prominence[i - 1] or p < prominence[i + 1]:
continue continue
a = b = i a = b = i
while a > 0 and prominence[a - 1] >= p - 3: while a > 0 and prominence[a - 1] >= p - 3:
@@ -102,13 +102,13 @@ def fixed_lines(x: np.ndarray, fs: float, f_max: float) -> list[float]:
found.append((round(float(f[i]), 3), round(float(p), 1))) found.append((round(float(f[i]), 3), round(float(p), 1)))
kept = [] kept = []
for hz, db_up in sorted(found, key=lambda line: -line[1]): for hz, db_up in sorted(found, key=lambda line: -line[1]):
if all((abs(hz - other) > 0.5 for other, _ in kept)): if all(abs(hz - other) > 0.5 for other, _ in kept):
kept.append((hz, db_up)) kept.append((hz, db_up))
return [hz for hz, _ in kept] return [hz for hz, _ in kept]
def band_power(f, power, lo, hi, lines=(), include_hi=False): def band_power(f, power, lo, hi, lines=(), include_hi=False):
band = (f >= lo) & (f <= hi if include_hi else f < hi) band = (f >= lo) & ((f <= hi) if include_hi else (f < hi))
clean = band.copy() clean = band.copy()
for line in lines: for line in lines:
clean &= np.abs(f - line) > 1.0 clean &= np.abs(f - line) > 1.0
@@ -121,14 +121,14 @@ def dominant_peak(f: np.ndarray, power: np.ndarray) -> tuple[float, float, bool]
usable = (f >= 1.5) & (f <= 45) & (power > 0) usable = (f >= 1.5) & (f <= 45) & (power > 0)
background = usable & ~((f >= 4) & (f <= 16)) background = usable & ~((f >= 4) & (f <= 16))
if background.sum() < 5: if background.sum() < 5:
return (np.nan, np.nan, False) return np.nan, np.nan, False
line = np.polyfit(np.log10(f[background]), np.log10(power[background]), 1) 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]))) residual = 10 * (np.log10(power[usable]) - np.polyval(line, np.log10(f[usable])))
fu = f[usable] fu = f[usable]
band = (fu >= 3) & (fu <= 14) band = (fu >= 3) & (fu <= 14)
if not band.any(): if not band.any():
return (np.nan, np.nan, False) return np.nan, np.nan, False
i = int(np.argmax(residual[band])) i = int(np.argmax(residual[band]))
prominence = float(residual[band][i]) prominence = float(residual[band][i])
found = prominence >= 1.5 and 0 < i < int(band.sum()) - 1 found = prominence >= 1.5 and 0 < i < int(band.sum()) - 1
return (float(fu[band][i]) if found else np.nan, prominence, bool(found)) return (float(fu[band][i]) if found else np.nan), prominence, bool(found)
+29 -44
View File
@@ -1,7 +1,9 @@
import json import json
import unicodedata import unicodedata
from pathlib import Path from pathlib import Path
import numpy as np import numpy as np
from models.tea.eeg import signals from models.tea.eeg import signals
from models.tea.eeg.preprocess import WINDOW_S, Prepared from models.tea.eeg.preprocess import WINDOW_S, Prepared
@@ -11,48 +13,31 @@ NOTE_WORDS = {
"hyperventilation": ("hv", "hipervent", "hypervent"), "hyperventilation": ("hv", "hipervent", "hypervent"),
"eyes_open": ("ojos abiertos", "eyes open", "oa"), "eyes_open": ("ojos abiertos", "eyes open", "oa"),
"eyes_closed": ("ojos cerrados", "eyes closed", "oc"), "eyes_closed": ("ojos cerrados", "eyes closed", "oc"),
"sleep": ( "sleep": ("sueno", "dormido", "sleep", "somnol", "husos", "spindle", "fase i", "fase ii",
"sueno", "n1", "n2", "n3"),
"dormido",
"sleep",
"somnol",
"husos",
"spindle",
"fase i",
"fase ii",
"n1",
"n2",
"n3",
),
"awake": ("despierta", "despierto", "arousal", "vigilia"), "awake": ("despierta", "despierto", "arousal", "vigilia"),
"crying": ("llanto", "llora", "cry"), "crying": ("llanto", "llora", "cry"),
"movement": ("movimiento", "movement", "artefacto de movimiento"), "movement": ("movimiento", "movement", "artefacto de movimiento"),
"feeding": ("come", "alimenta", "biberon", "lactancia"), "feeding": ("come", "alimenta", "biberon", "lactancia"),
} } # fmt: skip
EXCLUDED = ("crying", "movement", "disconnection") EXCLUDED = ("crying", "movement", "disconnection")
MASKED = (*EXCLUDED, "photic", "hyperventilation") MASKED = (*EXCLUDED, "photic", "hyperventilation")
STATES = np.array(["wake", "drowsy", "sleep"], dtype=object) STATES = np.array(["wake", "drowsy", "sleep"], dtype=object)
BANDS = { BANDS = {"delta": (0.5, 4), "theta": (4, 8), "alpha": (8, 13), "sigma": (11, 16),
"delta": (0.5, 4), "beta": (16, 30), "high": (20, 40)} # fmt: skip
"theta": (4, 8),
"alpha": (8, 13),
"sigma": (11, 16),
"beta": (16, 30),
"high": (20, 40),
}
POSTERIOR = ("O1", "O2", "P3", "P4") POSTERIOR = ("O1", "O2", "P3", "P4")
CENTRAL = ("C3", "C4", "Cz") CENTRAL = ("C3", "C4", "Cz")
FRONTAL = ("F3", "F4", "Fz") FRONTAL = ("F3", "F4", "Fz")
def note_state(text: str) -> str | None: def note_state(text: str) -> str | None:
kept = str(text or "").replace("ñ", "\x00").replace("Ñ", "\x01") kept = str(text or "").replace("ñ", "\0").replace("Ñ", "\1")
plain = "".join( plain = "".join(
(c for c in unicodedata.normalize("NFD", kept) if unicodedata.category(c) != "Mn") c for c in unicodedata.normalize("NFD", kept) if unicodedata.category(c) != "Mn"
) )
plain = plain.replace("\x00", "ñ").replace("\x01", "Ñ").lower().strip() plain = plain.replace("\0", "ñ").replace("\1", "Ñ").lower().strip()
return next( return next(
(state for state, words in NOTE_WORDS.items() if any((w in plain for w in words))), None (state for state, words in NOTE_WORDS.items() if any(w in plain for w in words)), None
) )
@@ -71,7 +56,7 @@ def note_intervals(annotations, duration_s: float) -> list[tuple[float, float, s
if t1 - t0 >= 1: if t1 - t0 >= 1:
found.append((t0, t1, state)) found.append((t0, t1, state))
found.sort(key=lambda piece: piece[0]) found.sort(key=lambda piece: piece[0])
full, cursor = ([], 0.0) full, cursor = [], 0.0
for t0, t1, state in found: for t0, t1, state in found:
if t0 - cursor >= 1: if t0 - cursor >= 1:
full.append((cursor, t0, "unmarked")) full.append((cursor, t0, "unmarked"))
@@ -86,13 +71,13 @@ def note_intervals(annotations, duration_s: float) -> list[tuple[float, float, s
def window_note(t0: float, t1: float, intervals) -> tuple[str, bool]: def window_note(t0: float, t1: float, intervals) -> tuple[str, bool]:
overlap = {} overlap = {}
for onset, length, state in intervals: for onset, length, state in intervals:
lo, hi = (max(t0, onset), min(t1, onset + length)) lo, hi = max(t0, onset), min(t1, onset + length)
if hi > lo: if hi > lo:
overlap[state] = overlap.get(state, 0) + (hi - lo) overlap[state] = overlap.get(state, 0) + (hi - lo)
if not overlap: if not overlap:
return ("unlabelled", False) return "unlabelled", False
dominant = max(overlap, key=overlap.get) dominant = max(overlap, key=overlap.get)
return (dominant, overlap[dominant] < 0.8 * (t1 - t0)) return dominant, overlap[dominant] < 0.8 * (t1 - t0)
def mask(prep: Prepared, intervals) -> np.ndarray: def mask(prep: Prepared, intervals) -> np.ndarray:
@@ -104,15 +89,15 @@ def mask(prep: Prepared, intervals) -> np.ndarray:
def _features(prep: Prepared, masked: np.ndarray) -> tuple[list[int], dict[str, np.ndarray]]: def _features(prep: Prepared, masked: np.ndarray) -> tuple[list[int], dict[str, np.ndarray]]:
fs, x, names = (prep.fs, prep.x, list(prep.names)) fs, x, names = prep.fs, prep.x, list(prep.names)
n, step = (int(WINDOW_S * fs), int(2 * fs)) n, step = int(WINDOW_S * fs), int(2 * fs)
starts = [ starts = [
a a
for a in range(0, len(x) - n + 1, step) 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 np.isfinite(x[a : a + n]).all() and not masked[a : a + n].any()
] ]
if not starts: if not starts:
return ([], {}) return [], {}
f, power = signals.periodograms(np.stack([x[a : a + n].T for a in starts]), fs) f, power = signals.periodograms(np.stack([x[a : a + n].T for a in starts]), fs)
band = {b: power[..., (f >= lo) & (f < hi)].sum(axis=-1) for b, (lo, hi) in BANDS.items()} 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) total = np.maximum(band["delta"] + band["theta"] + band["alpha"] + band["beta"], 1e-12)
@@ -120,7 +105,7 @@ def _features(prep: Prepared, masked: np.ndarray) -> tuple[list[int], dict[str,
posterior = [names.index(c) for c in POSTERIOR if c in 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) delta_beta = np.median(band["delta"] / np.maximum(band["beta"], 1e-12), axis=1)
features = { features = {
"delta_beta": np.log10(np.clip(delta_beta, 1e-06, None)), "delta_beta": np.log10(np.clip(delta_beta, 1e-6, None)),
"sigma": np.median((band["sigma"] / total)[:, central], axis=1), "sigma": np.median((band["sigma"] / total)[:, central], axis=1),
"muscle": np.median( "muscle": np.median(
band["high"] / np.maximum(band["theta"] + band["alpha"], 1e-12), axis=1 band["high"] / np.maximum(band["theta"] + band["alpha"], 1e-12), axis=1
@@ -132,19 +117,19 @@ def _features(prep: Prepared, masked: np.ndarray) -> tuple[list[int], dict[str,
signals.dominant_peak(f, power[w, posterior].mean(axis=0)) for w in range(len(starts)) 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]) features["posterior_rhythm"] = np.array([db if found else 0.0 for _, db, found in peaks])
return (starts, features) return starts, features
def depth(features: dict[str, np.ndarray], age_months: float | None) -> np.ndarray: def depth(features: dict[str, np.ndarray], age_months: float | None) -> np.ndarray:
z, weights = ([], []) z, weights = [], []
for name, ref in REFERENCE["features"].items(): for name, ref in REFERENCE["features"].items():
if name not in features: if name not in features:
continue continue
if "slope" in ref and age_months and (age_months > 0): if "slope" in ref and age_months and age_months > 0:
median = ref["slope"] * np.log10(float(age_months)) + ref["intercept"] median = ref["slope"] * np.log10(float(age_months)) + ref["intercept"]
else: else:
median = ref["median"] median = ref["median"]
z.append(ref["sign"] * (features[name] - median) / max(ref["dispersion"], 1e-09)) z.append(ref["sign"] * (features[name] - median) / max(ref["dispersion"], 1e-9))
weights.append(ref["weight"]) weights.append(ref["weight"])
w = np.array(weights, float) w = np.array(weights, float)
return np.clip((np.column_stack(z) * w).sum(axis=1) / w.sum(), -6, 6) return np.clip((np.column_stack(z) * w).sum(axis=1) / w.sum(), -6, 6)
@@ -172,8 +157,8 @@ def slow_waves(y: np.ndarray, fs: float) -> list[tuple[float, float]]:
continue continue
if j + 2 >= len(crossings): if j + 2 >= len(crossings):
break break
c1, c2 = (crossings[j + 1], crossings[j + 2]) c1, c2 = crossings[j + 1], crossings[j + 2]
negative, total = ((c1 - c0) / fs, (c2 - c0) / fs) negative, total = (c1 - c0) / fs, (c2 - c0) / fs
if not (0.125 <= negative <= 1.0 and 0.5 <= total <= 2.0): if not (0.125 <= negative <= 1.0 and 0.5 <= total <= 2.0):
continue continue
p2p = float(np.max(y[c1:c2]) - float(np.min(y[c0:c1]))) p2p = float(np.max(y[c1:c2]) - float(np.min(y[c0:c1])))
@@ -204,8 +189,8 @@ def stages(prep: Prepared, labels: np.ndarray) -> np.ndarray:
for k, (start, label) in enumerate(zip(prep.starts, labels, strict=True)): for k, (start, label) in enumerate(zip(prep.starts, labels, strict=True)):
if label != "sleep": if label != "sleep":
continue continue
t0, t1 = (start + WINDOW_S / 2 - 15.0, start + WINDOW_S / 2 + 15.0) t0, t1 = start + WINDOW_S / 2 - 15.0, start + WINDOW_S / 2 + 15.0
overlap = np.clip(np.minimum(covered[:, 1], t1) - np.maximum(covered[:, 0], t0), 0, None) overlap = np.clip(np.minimum(covered[:, 1], t1) - np.maximum(covered[:, 0], t0), 0, None)
coverage = min(overlap.sum() / max(t1 - t0, 1e-09), 1.0) if len(covered) else 0.0 coverage = min(overlap.sum() / max(t1 - t0, 1e-9), 1.0) if len(covered) else 0.0
out[k] = "N3" if round(coverage, 4) >= 0.2 else "N2" out[k] = "N3" if round(coverage, 4) >= 0.20 else "N2"
return out return out
+24 -24
View File
@@ -1,6 +1,8 @@
from dataclasses import dataclass from dataclasses import dataclass
import numpy as np import numpy as np
import pandas as pd import pandas as pd
from models.tea.eeg import signals from models.tea.eeg import signals
from models.tea.eeg.checks import NEIGHBOURS from models.tea.eeg.checks import NEIGHBOURS
from models.tea.eeg.preprocess import WINDOW_S, Prepared from models.tea.eeg.preprocess import WINDOW_S, Prepared
@@ -40,7 +42,7 @@ def _gate(x: np.ndarray, fs: float, intervals) -> list[tuple[float, float]]:
taper = np.hanning(n)[:, None] taper = np.hanning(n)[:, None]
kept = [] kept = []
for a in range(0, len(x) - n + 1, n): for a in range(0, len(x) - n + 1, n):
t0, t1 = (a / fs, a / fs + GATE_S) t0, t1 = a / fs, a / fs + GATE_S
state, mixed = window_note(t0, t1, intervals) state, mixed = window_note(t0, t1, intervals)
segment = x[a : a + n] segment = x[a : a + n]
if not np.isfinite(segment).all() or state in EXCLUDED or mixed: if not np.isfinite(segment).all() or state in EXCLUDED or mixed:
@@ -50,7 +52,7 @@ def _gate(x: np.ndarray, fs: float, intervals) -> list[tuple[float, float]]:
high = signals.band_power(f, power, 20, top, lines, include_hi=True) high = signals.band_power(f, power, 20, top, lines, include_hi=True)
low = signals.band_power(f, power, 4, 13, lines, include_hi=True) low = signals.band_power(f, power, 4, 13, lines, include_hi=True)
muscle = float(high / max(low, 1e-12)) muscle = float(high / max(low, 1e-12))
frozen = float(np.mean(np.abs(np.diff(segment, axis=0)) < 1e-09)) frozen = float(np.mean(np.abs(np.diff(segment, axis=0)) < 1e-9))
if not (muscle > 1.5 or frozen > 0.5): if not (muscle > 1.5 or frozen > 0.5):
kept.append((round(t0, 2), round(t1, 2))) kept.append((round(t0, 2), round(t1, 2)))
return kept return kept
@@ -59,43 +61,43 @@ def _gate(x: np.ndarray, fs: float, intervals) -> list[tuple[float, float]]:
def _flanks(y: np.ndarray, i: int, fs: float) -> tuple[float, float]: def _flanks(y: np.ndarray, i: int, fs: float) -> tuple[float, float]:
n = len(y) n = len(y)
if i <= 0 or i >= n - 1: if i <= 0 or i >= n - 1:
return (np.nan, np.nan) return np.nan, np.nan
w = int(500 * fs / 1000) w = int(500 * fs / 1000)
base = float(np.median(y[max(0, i - w) : min(n, i + w)])) base = float(np.median(y[max(0, i - w) : min(n, i + w)]))
peak = float(y[i]) - base peak = float(y[i]) - base
if peak == 0.0: if peak == 0.0:
return (np.nan, np.nan) return np.nan, np.nan
sign, half, reach = (np.sign(peak), 0.5 * abs(peak), int(150 * fs / 1000)) sign, half, reach = np.sign(peak), 0.5 * abs(peak), int(150 * fs / 1000)
a, low = (i, max(0, i - reach)) a, low = i, max(0, i - reach)
while a > low and sign * (y[a] - base) >= half: while a > low and sign * (y[a] - base) >= half:
a -= 1 a -= 1
b, high = (i, min(n - 1, i + reach)) b, high = i, min(n - 1, i + reach)
while b < high and sign * (y[b] - base) >= half: while b < high and sign * (y[b] - base) >= half:
b += 1 b += 1
if b <= a: if b <= a:
return (np.nan, np.nan) return np.nan, np.nan
rise, fall = (half / (max(i - a, 1) / fs), half / (max(b - i, 1) / fs)) 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)) return float(min(rise, fall)), float((b - a) / fs * 1000.0)
def _candidates(x: np.ndarray, fs: float, channel: str) -> list[dict]: 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() 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: if np.isfinite(y).sum() < fs * 2:
return [] return []
slope_mad, amplitude_mad = (_mad(np.diff(y) * fs), _mad(y)) slope_mad, amplitude_mad = _mad(np.diff(y) * fs), _mad(y)
if not np.isfinite(slope_mad) or not np.isfinite(amplitude_mad): if not np.isfinite(slope_mad) or not np.isfinite(amplitude_mad):
return [] return []
v = np.abs(y) v = np.abs(y)
peaks = np.flatnonzero((v[1:-1] > v[:-2]) & (v[1:-1] >= v[2:])) + 1 if len(v) >= 3 else [] 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)) after = int(100 * fs / 1000), int(500 * fs / 1000)
out = [] out = []
for i in (i for i in peaks if v[i] > 3.0 * amplitude_mad): for i in (i for i in peaks if v[i] > 3.0 * amplitude_mad):
slope, width = _flanks(y, int(i), fs) slope, width = _flanks(y, int(i), fs)
if not (np.isfinite(slope) and np.isfinite(width) and (20.0 <= width <= 200.0)): if not (np.isfinite(slope) and np.isfinite(width) and 20.0 <= width <= 200.0):
continue continue
if slope < 6.0 * slope_mad: if slope < 6.0 * slope_mad:
continue continue
a, b = (int(i) + after[0], min(int(i) + after[1], len(y))) 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 post = float(-np.sign(y[i]) * np.mean(y[a:b]) / amplitude_mad) if b > a else 0.0
out.append( out.append(
dict( dict(
@@ -133,12 +135,10 @@ def _merge(c: pd.DataFrame) -> pd.DataFrame:
top = c.loc[part["size"].idxmax()] top = c.loc[part["size"].idxmax()]
asleep = top.state in ASLEEP asleep = top.state in ASLEEP
signs = dict(zip(part.channel, part.sign, strict=True)) signs = dict(zip(part.channel, part.sign, strict=True))
frontal_only = top.channel in OCULAR and (not set(part.channel) & POSTERIOR) frontal_only = top.channel in OCULAR and not (set(part.channel) & POSTERIOR)
opposite = any( opposite = any(a in signs and b in signs and signs[a] * signs[b] < 0 for a, b in LEFT_RIGHT)
(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
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( rows.append(
dict( dict(
channel=top.channel, channel=top.channel,
@@ -163,10 +163,10 @@ def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None:
] ]
def state_at(t: np.ndarray) -> np.ndarray: def state_at(t: np.ndarray) -> np.ndarray:
out, open_ = (np.full(len(t), "unlabelled", dtype=object), np.ones(len(t), bool)) out, open_ = np.full(len(t), "unlabelled", dtype=object), np.ones(len(t), bool)
for t0, t1, label in labelled: for t0, t1, label in labelled:
hit = open_ & (t0 <= t) & (t < t1) hit = open_ & (t0 <= t) & (t < t1)
out[hit], open_ = (label, open_ & ~hit) out[hit], open_ = label, open_ & ~hit
return out return out
gate = _gate(x, fs, intervals) gate = _gate(x, fs, intervals)
@@ -174,7 +174,7 @@ def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None:
middles = state_at(np.array([(t0 + t1) / 2.0 for t0, t1 in gate])) middles = state_at(np.array([(t0 + t1) / 2.0 for t0, t1 in gate]))
for (t0, t1), state in zip(gate, middles, strict=True): for (t0, t1), state in zip(gate, middles, strict=True):
minutes[state] = minutes.get(state, 0.0) + (t1 - t0) / 60.0 minutes[state] = minutes.get(state, 0.0) + (t1 - t0) / 60.0
sleep_minutes = float(sum((minutes.get(s, 0.0) for s in ("sleep",)))) sleep_minutes = float(sum(minutes.get(s, 0.0) for s in ("sleep",)))
counts = dict.fromkeys(channels, 0) counts = dict.fromkeys(channels, 0)
candidates = [row for j, c in enumerate(channels) for row in _candidates(x[:, j], fs, c)] candidates = [row for j, c in enumerate(channels) for row in _candidates(x[:, j], fs, c)]
if candidates and gate: if candidates and gate:
@@ -199,6 +199,6 @@ def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None:
zones = {} zones = {}
for zone, members in ZONES.items(): for zone, members in ZONES.items():
present = [e for e in members if e in counts] present = [e for e in members if e in counts]
total = sum((counts[e] for e in 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 zones[zone] = round(total / sleep_minutes, 4) if present and sleep_minutes > 0 else np.nan
return Spikes(rate, electrodes, zones, round(sleep_minutes, 4)) return Spikes(rate, electrodes, zones, round(sleep_minutes, 4))
+10 -8
View File
@@ -1,6 +1,8 @@
from dataclasses import dataclass from dataclasses import dataclass
import numpy as np import numpy as np
from scipy.signal import hilbert, welch from scipy.signal import hilbert, welch
from models.tea.eeg import signals from models.tea.eeg import signals
from models.tea.eeg.preprocess import WINDOW_S, Prepared from models.tea.eeg.preprocess import WINDOW_S, Prepared
@@ -33,7 +35,7 @@ def _envelope(x: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
lambda v: np.convolve(v, np.ones(k) / k, mode="same"), 0, envelope lambda v: np.convolve(v, np.ones(k) / k, mode="same"), 0, envelope
) )
envelope[~np.isfinite(y)] = np.nan envelope[~np.isfinite(y)] = np.nan
return (y, envelope) return y, envelope
def _segments(core: np.ndarray, extent: np.ndarray, fs: float) -> list[tuple[int, int]]: def _segments(core: np.ndarray, extent: np.ndarray, fs: float) -> list[tuple[int, int]]:
@@ -59,7 +61,7 @@ def _is_spindle(x: np.ndarray, y: np.ndarray, fs: float) -> bool:
nperseg = min(len(x), int(fs)) nperseg = min(len(x), int(fs))
f, power = welch(x - x.mean(), fs=fs, nperseg=nperseg, nfft=max(1024, nperseg * 4)) f, power = welch(x - x.mean(), fs=fs, nperseg=nperseg, nfft=max(1024, nperseg * 4))
inside = (f >= SIGMA[0]) & (f <= SIGMA[1]) inside = (f >= SIGMA[0]) & (f <= SIGMA[1])
flanks = (f >= 5) & (f < SIGMA[0]) | (f > SIGMA[1]) & (f <= 30) flanks = ((f >= 5) & (f < SIGMA[0])) | ((f > SIGMA[1]) & (f <= 30))
if not inside.any() or not flanks.any(): if not inside.any() or not flanks.any():
return False return False
if power[inside].mean() / max(power[flanks].mean(), 1e-30) < 1.5: if power[inside].mean() / max(power[flanks].mean(), 1e-30) < 1.5:
@@ -73,7 +75,7 @@ def _is_spindle(x: np.ndarray, y: np.ndarray, fs: float) -> bool:
def detect(prep: Prepared, staged: np.ndarray, stage: str) -> Spindles: def detect(prep: Prepared, staged: np.ndarray, stage: str) -> Spindles:
fs, n = (prep.fs, int(WINDOW_S * prep.fs)) fs, n = prep.fs, int(WINDOW_S * prep.fs)
asleep = np.zeros(len(prep.x), bool) asleep = np.zeros(len(prep.x), bool)
for start, s in zip(prep.starts, staged, strict=True): for start, s in zip(prep.starts, staged, strict=True):
if s == stage: if s == stage:
@@ -91,7 +93,7 @@ def detect(prep: Prepared, staged: np.ndarray, stage: str) -> Spindles:
values = in_stage[np.isfinite(in_stage)] values = in_stage[np.isfinite(in_stage)]
if len(values) < fs * 30: if len(values) < fs * 30:
continue continue
median = float(np.median(values)) or 1e-09 median = float(np.median(values)) or 1e-9
core = max(float(np.percentile(values, 95)), 3 * median) core = max(float(np.percentile(values, 95)), 3 * median)
extent = max(float(np.percentile(values, 70)), 1.6 * median) extent = max(float(np.percentile(values, 70)), 1.6 * median)
finite = np.isfinite(in_stage) finite = np.isfinite(in_stage)
@@ -104,17 +106,17 @@ def detect(prep: Prepared, staged: np.ndarray, stage: str) -> Spindles:
def density(found: Spindles) -> tuple[float, dict[str, float]]: def density(found: Spindles) -> tuple[float, dict[str, float]]:
zones = dict.fromkeys(ZONES, np.nan) zones = dict.fromkeys(ZONES, np.nan)
if not found.events or found.minutes <= 0: if not found.events or found.minutes <= 0:
return (np.nan, zones) return np.nan, zones
counts = {} counts = {}
for _, _, channel in found.events: for _, _, channel in found.events:
counts[channel] = counts.get(channel, 0) + 1 counts[channel] = counts.get(channel, 0) + 1
for zone, electrodes in ZONES.items(): for zone, electrodes in ZONES.items():
searched = [e for e in electrodes if e in found.channels] searched = [e for e in electrodes if e in found.channels]
if searched: if searched:
total = sum((counts.get(e, 0) for e in searched)) total = sum(counts.get(e, 0) for e in searched)
zones[zone] = total / (found.minutes * len(searched)) zones[zone] = total / (found.minutes * len(searched))
per_channel = len(found.events) / found.minutes / max(len(found.channels), 1) per_channel = len(found.events) / found.minutes / max(len(found.channels), 1)
return (round(per_channel, 3), zones) return round(per_channel, 3), zones
def _episodes(events) -> list[list[float]]: def _episodes(events) -> list[list[float]]:
@@ -148,7 +150,7 @@ def enhancement(prep: Prepared, found: Spindles, states: np.ndarray) -> dict[str
median = np.nanmedian(envelope[asleep] if asleep.sum() > fs * 30 else envelope, axis=0) median = np.nanmedian(envelope[asleep] if asleep.sum() > fs * 30 else envelope, axis=0)
peaks = np.full((len(episodes), len(use)), np.nan) peaks = np.full((len(episodes), len(use)), np.nan)
for k, (t0, t1) in enumerate(episodes): for k, (t0, t1) in enumerate(episodes):
a, b = (max(0, int((t0 - 0.25) * fs)), min(len(envelope), int((t1 + 0.25) * fs))) a, b = max(0, int((t0 - 0.25) * fs)), min(len(envelope), int((t1 + 0.25) * fs))
if b - a >= 3: if b - a >= 3:
peaks[k] = np.nanmax(envelope[a:b], axis=0) peaks[k] = np.nanmax(envelope[a:b], axis=0)
for j, name in enumerate(use): for j, name in enumerate(use):
+224 -199
View File
@@ -1,56 +1,100 @@
import hashlib import hashlib
import json
import os
from dataclasses import dataclass from dataclasses import dataclass
from datetime import date from datetime import date
from pathlib import Path
import mlflow.pyfunc import mlflow.pyfunc
import pandas as pd import pandas as pd
from core.tea import ados2
from core.tea import association as relation from core.measures import as_day
from models import cluster 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.jobs import EmptyCohort
from models.tea import association from models.tea import association
from models.tea.eeg import analysis, curves, reference from models.tea.eeg import analysis, curves
from persistance import eeg, registry, silver from models.tea.eeg import reference as cohort_reference
from persistance import cluster, eeg, registry, silver
CURVES = curves.SCENARIOS ASSOCIATION = "ados2_association"
ASSOCIATION = "eeg-ados2" MODELS = curves.SCENARIOS
MODELS = [*CURVES, ASSOCIATION]
GOLD = "tea_eeg_metrics" GOLD = "tea_eeg_metrics"
GOLD_SELECT = [
"tea_eeg_analyses+",
"tea_eeg_metrics+",
"tea_associations",
"tea_association_scores",
]
class Baseline(mlflow.pyfunc.PythonModel): class Baseline(mlflow.pyfunc.PythonModel):
def __init__(self, scenario: str, baseline: dict): def __init__(self, scenario: str, baseline: dict):
self.scenario, self.baseline = (scenario, baseline) 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: def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
feature = (params or {}).get("feature", "value") feature = (params or {}).get("feature", "value")
rows = model_input.to_dict("records") rows = model_input.to_dict("records")
return pd.DataFrame( return pd.DataFrame([curves.score(self.baseline[feature], r.get("value"),
[ r.get("age_months"), r.get("exposure"))
curves.score( for r in rows]) # fmt: skip
self.baseline[feature], r.get("value"), r.get("age_months"), r.get("exposure")
)
for r in rows
]
)
def analyze() -> int: def _analyze(item: tuple[str, date | None, bytes]) -> tuple[str, analysis.Analysis]:
pending = eeg.pending() edf, birth, signal = item
done = cluster.run(analysis.analyze, ((eeg.signal(r["edf"]), r["birth_date"]) for r in pending)) return edf, analysis.analyze(signal, birth)
found = dict(zip((r["edf"] for r in pending), done, strict=True))
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) eeg.save_analyses(found)
silver.build(["tea_eeg_analyses+", "tea_eeg_metrics+"]) if rebuild_gold:
silver.build(GOLD_SELECT)
return len(found) 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) @dataclass(frozen=True)
class Jobs: class Jobs:
def routine(self) -> list[str]: def routine(self) -> list[str]:
return list(MODELS) return list(MODELS)
def scored(self) -> list[str]:
return list(MODELS)
JOBS = Jobs() JOBS = Jobs()
@@ -59,52 +103,174 @@ def registered(name: str) -> str:
return f"tea.{name}" return f"tea.{name}"
def train(name: str, as_of: date | None = None) -> int: def train(
name: str, as_of: date | None = None, source: cluster.TrainingSource | None = None
) -> int | None:
if name == ASSOCIATION: if name == ASSOCIATION:
return _train_association(as_of) return train_association(as_of)
return _train_curve(name, as_of)
def _train_curve(name: str, as_of: date | None = None) -> int:
day = as_of or date.today() day = as_of or date.today()
measured = eeg.ruled_out(day) digest, measured, cohort, hz = _cohort(source or cluster.SiteTrainingSource(kind="site"), day)
if not measured: table = cohort_reference.tables(measured)[name]
raise EmptyCohort(f"{name}: no valid EEG of a child with TEA ruled out by {day}")
digest = hashlib.sha256("\n".join((m["key"] for m in measured)).encode()).hexdigest()
table = reference.tables(measured)[name]
baseline = curves.train(table, name) baseline = curves.train(table, name)
ages = [m["age_months"] for m in measured] 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 = { technical = {
"model": name, "model": name, "method": "age curves (weighted centiles on log age)", **found,
"method": "age curves (weighted centiles on log age)", "studies": len(measured), "valid_studies": len(valid),
"cohort": "site: children with TEA ruled out", "ages_months": [min(m["age_months"] for m in valid), max(m["age_months"] for m in valid)],
"cohort_sha256": digest,
"as_of": str(day),
"studies": len(measured),
"valid_studies": len(measured),
"ages_months": [min(ages), max(ages)],
"features": sorted(baseline), "features": sorted(baseline),
} } # fmt: skip
interpretability = {"model": name, "kind": "age_curves", "curves": baseline} interpretability = {"model": name, "kind": "age_curves", "curves": baseline}
metrics = {"n_reference": float(len(measured)), "features": float(len(baseline))} metrics = {"n_reference": float(len(valid)), "features": float(len(baseline))}
params = {"cohort": "ruled_out", "cohort_sha256": digest, "as_of": str(day)} params = {key: str(value) for key, value in found.items()}
reports = {"technical_validation": technical, "interpretability": interpretability} reports = {"technical_validation": technical, "interpretability": interpretability}
return registry.register(registered(name), Baseline(name, baseline), params, metrics, reports) 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",
"person_id",
"study_date",
"edf",
"age_months",
"ados_module",
"css",
*ADOS2_ITEMS,
]
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
records.append(
{
**row,
"key": eeg_study_id(row["person_id"], row["study_date"]),
"ados_module": row["module"],
"css": ados2.score(row, birth)[0],
}
)
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 in ("spikes", "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_")]
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", "outcome_code", "odds_ratio", "ci_low", "ci_high", "q"]
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: def score(name: str) -> int | None:
if name == ASSOCIATION:
return _score_association()
return _score_curve(name)
def _score_curve(name: str) -> int | None:
found = registry.champion(registered(name)) found = registry.champion(registered(name))
if found is None: if found is None:
return None return None
version, model = found version, model = found
baseline = model.unwrap_python_model().baseline baseline = model.unwrap_python_model().baseline
scenario, label = (CURVES[name], f"{registered(name)}/{version}") scenario, label = MODELS[name], f"{registered(name)}/{version}"
rows = [] rows = []
for one in eeg.analysed(): for one in eeg.analysed():
metric = next((m for m in one["metrics"] if m["code"] == scenario.metric), None) metric = next((m for m in one["metrics"] if m["code"] == scenario.metric), None)
@@ -121,149 +287,8 @@ def _score_curve(name: str) -> int | None:
if feature not in baseline: if feature not in baseline:
continue continue
s = curves.score(baseline[feature], value, one["age_months"], exposure) s = curves.score(baseline[feature], value, one["age_months"], exposure)
rows.append( rows.append({"key": f"{one['edf']}|{name}|{part}|{site}", "edf": one["edf"],
{ "scenario": name, "model": label, "metric": scenario.metric,
"key": f"{one['edf']}|{name}|{part}|{site}", "part": part, "site": site or None, **s}) # fmt: skip
"edf": one["edf"],
"scenario": name,
"model": label,
"metric": scenario.metric,
"part": part,
"site": site or None,
**s,
}
)
eeg.save_scores(name, rows) eeg.save_scores(name, rows)
return version return version
class Association(mlflow.pyfunc.PythonModel):
def __init__(self, fitted: dict):
self.fitted = fitted
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
return pd.DataFrame(association.score(self.fitted, model_input))
def association_cohort(as_of: date | None = None) -> tuple[pd.DataFrame, pd.DataFrame]:
day = str(as_of) if as_of else None
rows = []
for r in eeg.association_inputs(relation.BIOMARKERS):
a = r["ados2"]
evaluated = str(a["evaluation_date"])[:10] if a.get("evaluation_date") else None
if day and (r["study_date"] > day or (evaluated and evaluated > day)):
continue
css = None
if evaluated and r["birth_date"]:
row = {**a, "evaluation_date": date.fromisoformat(evaluated)}
css, _ = ados2.score(row, date.fromisoformat(r["birth_date"]))
rows.append(
{
"key": r["edf"],
"person": r["person_id"],
"age_months": r["age_months"],
"module": a.get("module"),
"css": css,
**{n: a.get(n) for n, _ in relation.ITEMS.values()},
**{k: v for k, v in r.items() if k.startswith("z_")},
}
)
scored = pd.DataFrame(rows)
if scored.empty:
return (scored, scored)
predictors = [c for c in scored.columns if c.startswith("z_")]
with_z = scored[predictors].notna().any(axis=1) if predictors else scored["key"].isna()
fit = scored[with_z].drop_duplicates("person").reset_index(drop=True)
return (fit.drop(columns=["person"]), scored.drop(columns=["person"]))
def _train_association(as_of: date | None = None) -> int:
fit, _ = association_cohort(as_of)
if fit.empty:
raise EmptyCohort(f"{ASSOCIATION}: no child with an ADOS-2 and a scored EEG")
fitted = association.fit(fit)
pairs = association.associations(fitted)
estimated = [p for p in pairs if p["odds_ratio"] is not None]
technical = {
"model": ASSOCIATION,
"method": "Firth logistic (items) / cumulative logit (CSS), adjusted for age and module; profile-likelihood 95 % CI; Benjamini–Hochberg q",
"cohort": "site: children with an ADOS-2 and a valid EEG",
"as_of": str(as_of or date.today()),
"children": int(fitted["n"]),
"level": fitted["level"],
"pairs": len(pairs),
"estimated": len(estimated),
"clear": sum((1 for p in estimated if (p["q"] or 1) < 0.05)),
}
interpretability = {
"model": ASSOCIATION,
"kind": "associations",
"level": fitted["level"],
"children": int(fitted["n"]),
"rows": pairs,
}
metrics = {"children": float(fitted["n"]), "estimated": float(len(estimated))}
params = {"level": fitted["level"], "as_of": str(as_of or date.today())}
reports = {"technical_validation": technical, "interpretability": interpretability}
return registry.register(registered(ASSOCIATION), Association(fitted), params, metrics, reports)
def _score_association() -> int | None:
found = registry.champion(registered(ASSOCIATION))
if found is None:
return None
version, model = found
fitted = model.unwrap_python_model().fitted
label = f"{registered(ASSOCIATION)}/{version}"
_, scored = association_cohort()
kept = (
"biomarker",
"zone",
"kind",
"outcome_code",
"event",
"n",
"odds_ratio",
"ci_low",
"ci_high",
"p",
"q",
"sens_odds_ratio",
"same_direction",
"reason",
)
pairs = [
{
**{k: p[k] for k in kept},
"model": label,
"key": f"{label}|{p['biomarker']}|{p['zone']}|{p['outcome_code']}",
"metric": relation.BIOMARKERS[p["biomarker"]],
"principal": p["model"],
"sensitivity": p["sens_model"],
}
for p in association.associations(fitted)
if p["odds_ratio"] is not None
]
observed: dict[str, dict] = {}
if not scored.empty:
keys = scored["key"].tolist()
for n in relation.ITEMS:
items = association.item_scores(scored, n).tolist()
observed[relation.item_code(n)] = dict(zip(keys, items, strict=True))
observed[relation.CSS] = dict(zip(keys, scored["css"].tolist(), strict=True))
scores = []
for one in association.score(fitted, scored) if not scored.empty else []:
seen = observed.get(one["outcome_code"], {}).get(one["key"])
pair = f"{one['biomarker']}|{one['zone']}|{one['outcome_code']}"
shown = None if seen is None or seen != seen else float(seen)
scores.append(
{
**one,
"edf": one["key"],
"model": label,
"key": f"{one['key']}|{pair}",
"observed": shown,
}
)
eeg.save_association(label, pairs, scores)
return version
+217
View File
@@ -0,0 +1,217 @@
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, ())}
order = [*titles, *(item for item in tea.ADOS2_ITEMS if item not in titles)]
items = {item: _parse(item, row.get(item), "number", warnings) for item in order}
css, classification = None, None
if evaluation_date is None:
warnings.append("ADOS-2 not scored: no evaluation date")
else:
try:
css, classification = scoring.score(
row | items | {"evaluation_date": evaluation_date}, birth
)
except (ValueError, TypeError) as exc:
warnings.append(f"ADOS-2 not scored: {exc}")
else:
if css is None and classification is None:
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)
-3
View File
@@ -26,9 +26,6 @@ dependencies = [
"pgmpy>=1.1.2", "pgmpy>=1.1.2",
] ]
[project.optional-dependencies]
dask = ["dask[distributed]>=2026.8.0,<2026.9"] # as the testing cluster runs
[build-system] [build-system]
requires = ["uv_build>=0.12,<0.13"] requires = ["uv_build>=0.12,<0.13"]
build-backend = "uv_build" build-backend = "uv_build"
+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
+24
View File
@@ -0,0 +1,24 @@
import pytest
from models.tea.eeg import curves
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)):
assert curves.score(baseline, value, 24) == pytest.approx(
{"z": z, "outside": outside, "p5": 2, "median": 4, "p95": 8}, rel=1e-9
)
+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")]
+28
View File
@@ -0,0 +1,28 @@
import numpy as np
import pandas as pd
import pytest
from models.tea.eeg import curves, signals
def test_score_without_value_or_coverage():
table = pd.DataFrame({"value": [1.0, 2.0, 3.0], "age_months": [20.0, 25.0, 30.0]})
baseline = curves.train(table, "eeg-gradient")["value"]
empty = dict.fromkeys(("z", "outside", "p5", "median", "p95"))
assert curves.score(baseline, None, 25.0) == empty
assert curves.score(baseline, 2.0, 25.0) == empty
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
+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)
+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),
]
+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
+41
View File
@@ -0,0 +1,41 @@
import numpy as np
import pandas as pd
from core.tea import ADOS2_ITEMS
from models.tea import association as a
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_pairs_and_item_availability():
assert len(a.pairs("item")) == 41
assert len(a.pairs("domain")) == 15
assert ADOS2_ITEMS == [
"vocalization_directed", "pointing", "gestures", "unusual_eye_contact",
"facial_expressions", "gaze_integration", "shared_enjoyment", "response_to_name",
"ignoring", "requesting", "showing", "joint_attention_initiation",
"joint_attention_response", "social_overtures_quality", "social_overtures_caregiver",
"reciprocal_communication", "rapport_quality", "intonation", "stereotyped_language",
"unusual_sensory_interest", "hand_finger_mannerisms", "repetitive_interests",
] # fmt: skip
frame = pd.DataFrame(
{
"ados_module": ["toddler", "module_1", "module_2", "module_3"],
"vocalization_directed": [3, 7, 1, 1],
}
)
np.testing.assert_allclose(a.item_scores(frame, 1), [2, 0, np.nan, np.nan])
+77
View File
@@ -0,0 +1,77 @@
from datetime import date
import dagster as dg
import pytest
from pydantic import ValidationError
from models.definitions import ScopeConfig, after_ingest
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_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"]))
+61
View File
@@ -0,0 +1,61 @@
import hashlib
import os
import pytest
from dagster import build_op_context
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()) == []
+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))