Compare commits

...

153 Commits

Author SHA1 Message Date
alberto 6e153e8122 Gobernanza buttons, timeline, probability curve and age-norm bands
Analizar EEG leads to Estudios EEG, which hosts the single-study evaluation; Calcular riesgos stays only where there is no Estudios EEG. The timeline is a dotted line, the probability curve and the age-norm bands are drawn from the model and the centiles.
2026-12-01 18:35:47 -06:00
alberto 465ab2906d Calcular riesgos relates the association
The domain score job now ends with the association, so the buttons produce the risk analyses; the hospital test follows the Gobernanza steps and checks that risk analyses exist.
2026-12-01 18:09:55 -06:00
alberto 85c35ef150 Synthetic hospital: the appended children's ADOS-2 and neuropediatrics intervals vary
Every appended child waited exactly 30 days for the ADOS-2 and 25 for the neuropediatrics note, so the days indicators had no spread and their box plots collapsed to a line. The intervals now vary per child (20 to 30 and 15 to 25 days) inside the same total length.
2026-12-01 17:30:43 -06:00
alberto 025ca49280 WebApp: OpenAPI document regenerated 2026-12-01 17:26:09 -06:00
alberto d530cc18ec WebApp: per-chart axis defaults 2026-12-01 17:23:53 -06:00
alberto 373e83ca08 WebApp: shared short number format in every chart 2026-12-01 17:20:28 -06:00
alberto 12f45b2066 WebApp: shared linear value axis with short tick labels 2026-12-01 17:15:35 -06:00
alberto 781e1ea75a C1a: code only, no comments, no Markdown
The four Markdown files (README.md, tests/fixtures/ados2_items_by_module.md, tools/delivery/README.md, tools/delivery/README.repo.md) live in the outer repo under docs/ISSSTELEON; the delivery scripts no longer produce a README and the ADOS-2 expected values stay in the Python test.
2026-12-01 16:56:14 -06:00
alberto a2f8b9b493 Bundle guard: the training cut-off is not a study date
The date check ignores the model's own as_of value wherever it appears (the param and the technical_validation report), so a baseline trained from the site exports; study codes, paths and every other date are still refused.
2026-12-01 15:56:31 -06:00
alberto bf7054d21a F1e: WebApp pointer (complete-child case) 2026-12-01 15:28:54 -06:00
alberto 1c5e4846e0 F1e: WebApp pointer (period and refusal) 2026-12-01 15:09:10 -06:00
alberto fe1f86247c F1e: WebApp pointer (page case fixes) 2026-12-01 14:53:29 -06:00
alberto 425fce47d1 Merge parity/F1i 2026-12-01 14:36:33 -06:00
alberto 16ad2b2dc9 F1: WebApp pointer (Sankey layout) 2026-12-01 14:36:30 -06:00
alberto eb8d307c39 F1i: synthetic hospital has children without the diagnosis, so the site source trains the curves
Append three ascending passes through ages 16 to 34 for 57 children
with the not_confirmed_eeg profile. Use M-CHAT score 7 to select the
existing low ADOS-2 item score pool. Reuse the alternating sexes,
14-slot screening calendar, existing study intervals, and seeds
derived from the child index. Each EEG uses the existing defaults
with empty channel faults.

Test counts, the screening chain and F809 code, ADOS-2 items, ages,
sexes, and EEG validity. Use seed 11 for the repeat-build test and
compare every stored row and blob. A separate default-seed comparison
matched all 29 original children, including COMPLETE, against the
parent commit.

The full build took 13.48 seconds on one core. Ruff check, Ruff
format --check, lint-imports, and all 7 Docker-free synthetic unit
tests passed. A local curve probe validated all 57 new EEGs and
produced posterior-rhythm and N2 curves. The probe stopped at the
N3 spindle scenario, which had no usable baseline.
2026-12-01 14:21:05 -06:00
alberto a9866c6fe2 F1: WebApp pointer (Sankey order and width) 2026-12-01 14:20:58 -06:00
alberto 3ac4a8b129 F1: WebApp pointer (Sankey right column) 2026-12-01 14:14:00 -06:00
alberto ac230221c4 F1e: WebApi pointer (analysis before training) 2026-12-01 14:10:42 -06:00
alberto 28726390d7 F1e: WebApp and WebApi pointers 2026-12-01 14:05:40 -06:00
alberto fee5be3a74 Merge parity/F1h
# Conflicts:
#	WebApp
2026-12-01 14:04:31 -06:00
alberto 519f6fc705 F1: WebApp pointer (record test) 2026-12-01 14:04:28 -06:00
alberto 8b006758af F1: WebApp pointer (axis typing) 2026-12-01 13:51:14 -06:00
alberto ef008c366b F1h: Gobernanza without Vista previa and Subir archivos, button spacing
Remove the upload-only InputSpec, TEA input registry and persistence module. Keep REFERENCE_NAME and external-folder resolution in cluster, where they validate and resolve TEA_REFERENCE_ROOT. Keep file uploads for model bundles, clinical validation and single-study preview.

Keep the toggle in Modelos, reset it on domain changes, and hide the preview form while preserving its file selections and run state. Use space-3 for shared wrapping action rows and vertical spacing, with existing cell padding for rows inside tables. Keep the preview dialog and PDF logic.

Remove the upload routes, schema and generated client entries. Keep the OpenAPI exporter formatting, which Prettier flags on the baseline as well. Ruff check, Ruff format check, import contracts, Prettier for authored WebApp files and the model-route OpenAPI comparison passed. The full OpenAPI export requires fastapi_users, and the live router comparison showed existing drift in FolderTrainingSource, SiteTrainingSource and Training. Angular and Playwright runs are reserved for the test machines.
2026-12-01 13:49:50 -06:00
alberto d78384f886 Merge parity/F1g
# Conflicts:
#	WebApp
2026-12-01 13:45:29 -06:00
alberto a0abbfb2bf Merge parity/F1f 2026-12-01 13:45:25 -06:00
alberto 01b04953ee F1g: whole-number axes, risk list link, dotted timeline, head map 2026-12-01 13:45:25 -06:00
alberto ac17829147 F1f: TEA indicator chart formats (sex by age group, men blue, women magenta)
Keep the existing age-group stratum and add AGE_SEX to M21 and M22.
M24 already declares AGE_SEX. The existing StatusComposition evaluator
emits the sex-by-category counts needed by M23 and M31. Backend totals
retain unknown sex and the charts omit those bars.

Use the existing sex colors in male-first order, sort age groups by
starting month, use zero for missing counts, and leave gaps for rates
without a denominator. M24 retains count heights and percentage labels
using offset groups. Both charts use the previous prevalence alpha of
0.25 for transparent outcomes. M31 uses the published outcome counts
and keeps sex focus through a bar outline. Use the standard chart card
height and identify changed figures by measure in the page checks.

Ruff check, Ruff format check, lint-imports, Prettier, seven backend
tests, 23 WebApp logic tests, and focused figure type checking passed.
Full application type checking was blocked by missing pdfmake
dependencies. Angular and Playwright runs are reserved for test machines.
2026-12-01 13:37:11 -06:00
alberto bd717354b9 F1: source titles in the API schema, WebApp training form and Sankey pointers
The site and folder variants carry their option labels (title), the source field its heading, and kind its label; the WebApp reads them from the training-config schema.
2026-12-01 13:32:26 -06:00
alberto 857826846d F1: WebApp pointer (page case locator) 2026-12-01 13:06:00 -06:00
alberto 90855f1def F1: WebApp pointer (openapi, client, training types) 2026-12-01 12:19:18 -06:00
alberto 8bf2260eb1 Merge parity/F1a
# Conflicts:
#	WebApp
2026-12-01 11:52:05 -06:00
alberto 7ac53edbd5 WebApp: import cleanup 2026-12-01 11:52:00 -06:00
alberto 90c17d6b02 Merge parity/F1c
# Conflicts:
#	WebApp
2026-12-01 11:51:57 -06:00
alberto 1bfa8e82ff Merge parity/F1b 2026-12-01 11:51:43 -06:00
alberto 334cc95141 Merge parity/F1d 2026-12-01 11:51:41 -06:00
alberto 547e6a62bd F1b: user fixes
Select the earliest qualifying neuropediatrics note per child in gold.
Use an exclusive exit for prevalence in AtEnd and retain inclusive
exits for screening events. Publish linked sex and outcome counts in
the existing crossed FHIR report representation. Add sex strata for M23
and M24, retain the age-by-sex stratum, and publish the exact titles and
definitions through the Measure catalog.

Use a SQLite model and report logic case to cover absent screening data,
diagnosis at period end, and the exit boundary. Ruff check, Ruff format
check, lint-imports and 19 focused Python tests passed. FHIR OpenAPI paths
and schemas match the checked-in schema, so the client did not need
regeneration. Angular, Playwright and integration pytest were deferred
to the test machines.
2026-12-01 11:33:35 -06:00
alberto 90c95cdbd2 F1a: user fixes
Use a named discriminated alias with a required kind on both variants and a required folder on the folder variant. Keep the external folder default at 50 Hz and use the existing site EEG measurements produced at 60 Hz. Pass a flat source dictionary through Dagster and validate it with the shared union.

Reset preview visibility on domain changes. Project the folder schema into Formly, keep hidden folder edits in the form, and send only kind for site training. Keep the controls in a separate upload card and use the inputs GET only for upload metadata. Drop the listing helper and description, and retain the shared ingestion API used by Conectar.

Ruff check, Ruff format check, both import contracts, 12 targeted Python tests, Dagster config validation, and Prettier passed. Docker socket access was denied, so generate the changed OpenAPI components from the models router against the checked-in baseline and run the cached client generator directly. WebApp type-checking and page execution are deferred to the VM.
2026-12-01 11:33:15 -06:00
alberto adbdb01071 F1c: user fixes
Publish the follow-up M-CHAT score as a decimal and CSS ADOS-2 and the
alteration count as integers in Patient extensions. Use the existing
follow-up row values and count true flags across the configured EEG
metrics. Treat absent or false flags as zero and omit missing scores.
Keep the extensions scoped to TEA follow-up Patients.

Update FHIR mapping and follow-up logic coverage. Advance WebApp to
183e100 for the screening stepper, risk columns, Gantt chart, and logic
and page cases. Its commit records the frontend implementation choices.

Ruff check, Ruff format check, both import contracts and 37 targeted
Python logic cases passed. The FHIR OpenAPI routes and schemas match
the checked-in document, so client generation is unnecessary. Full
OpenAPI generation was unavailable locally because fastapi-users is
missing and the Docker socket is inaccessible. Angular, Playwright
and integration checks are reserved for the test machines.
2026-12-01 11:32:51 -06:00
alberto 7674b419dd F1d: synthetic TEA hospital trains the association and has one complete child
Append 14 valid confirmed EEG profiles and one all-flat profile. Keep
the original patient slots and mixed flat/loud EEG. The 17 valid EEGs
cover the three ADOS-2 modules in groups of 6, 6, and 5, with mixed
sexes and all three first-screening age strata. Keep all six hospital
profiles. The WebApi and e2e cases have no fixed count.

Keep the sex alternation and seeded surnames and cycle the given names.
Cycle the original 40-day screening calendar for the appended profiles.
Use a 30-day interval from their first screening to ADOS-2, followed by
the existing diagnosis and EEG intervals. Keep the original dates.

Seed each report as before. Draw from (0, 0, 0, 1) below M-CHAT 8 and
(1, 2, 2, 3) otherwise. Keep the missing item in the psychology-only
report. COMPLETE is patient 11 (N-0011, the 11th profile). It has a
second M-CHAT score of 10 after 30 days, all module_1 items, an F840
note, and a valid EEG at 29.1 months.

Use the existing channel fault map for 4 and 12 Hz posterior rhythms
and synchronous central and temporal Gaussian spikes during sleep.
Use 360 uV peaks, a 12.5 ms width parameter, and three-second spacing.
Keep three-minute EDFs and use a direct weighted source sum and local
EKG pulse windows to limit generation cost. The single-core build
process took 4.34 seconds with about 126 MiB peak RSS.

Ruff check, Ruff format check, both import contracts, and 25 targeted
unit tests passed. With cached Helsinki reference features the
in-memory association fit used 16 children and fitted 22 item-level
pairs. The complete child had 22 association scores and four altered
metrics, including spike activity mapped at the electrodes. The fit
emitted overflow warnings for some upper confidence bounds. Docker
integration and browser checks are left to the test machines.
2026-12-01 11:11:31 -06:00
alberto b85b0f9f08 Merge parity/main into parity/T17-webapp 2026-12-01 06:48:57 -06:00
alberto c6ed9b3b54 T17: submodules merged 2026-12-01 06:48:57 -06:00
alberto 6f8986b430 T17: WebApp sweep pointer 2026-12-01 06:48:57 -06:00
alberto 382a35b63c T17: sweep of the backend after the feature-parity work
Removed code with no reader (CaCu cohort total model, unused Core/Persistance
helpers, the obsolete Docker extras argument, a duplicate edfio declaration,
site generator leftovers); kept Dask execution, TEA_REFERENCE_ROOT and
TEA_REFERENCE_CACHE (active: folder training) and every route (each has a
consumer). README describes the platform, the domains, the tests and the TEA
training source.
2026-12-01 06:07:45 -06:00
alberto eed663c97e T15/T16: WebApp pointer 2026-12-01 05:06:43 -06:00
alberto eeb949bb84 T8/T9: WebApp pointer 2026-12-01 04:17:02 -06:00
alberto 19c818b5bd Merge parity/main into parity/T8-tea-lists 2026-12-01 03:55:35 -06:00
alberto a4f8e7004d T8/T9: submodules merged 2026-12-01 03:55:35 -06:00
alberto 9400416f71 T8/T9: Patient carries tea-eeg-result; the _id search keeps the TEA follow-up row; submodules 2026-12-01 03:55:35 -06:00
alberto 0154ce3907 T13: WebApp pointer 2026-12-01 02:25:00 -06:00
alberto 6e65208d17 Merge parity/main into parity/T13-gobernanza 2026-12-01 02:16:45 -06:00
alberto ee281ab0f5 T13: WebApp pointer 2026-12-01 02:16:45 -06:00
alberto 4fc7fe3a0b Merge parity/main into parity/T10-tea-record
# Conflicts:
#	WebApp
2026-12-01 02:03:03 -06:00
alberto ac8da9590c T10/T11: WebApp pointer 2026-12-01 02:02:56 -06:00
alberto e41221602c T7: WebApp pointer 2026-12-01 01:30:27 -06:00
alberto a2776ca03f Merge parity/T6-tea-case into parity/T5-identity 2026-12-01 01:26:26 -06:00
alberto 16bdefda7d T5: one record-number system per pipeline; the TEA persons link carries the name
Root causes: the TEA persons link node listed only record_number, birth_date
and sex as fields, so no name reached silver.person_name and TEA Patients had
none; and silver.person_identifier built the record-number system from
pipeline and source, so one number seen by the patient, M-CHAT and EEG
sources became several (system, value) pairs. The system is now
urn:isssteleon:<pipeline>, the hospital's numbering that linkage already
treats as one, and the link node gains full_name and a rule that equal
record numbers match unless both birth dates differ. Silver is rebuilt from
bronze on every build, so nothing migrates.

Test: persons from several sources yield one identifier and the name on the
TEA Patient.
2026-12-01 01:26:26 -06:00
alberto d6326cf545 Merge parity/main into parity/T6-tea-case 2026-12-01 01:20:52 -06:00
alberto 3f7985182c Merge parity/main into parity/T4-ados2-site 2026-12-01 01:20:41 -06:00
alberto 475915c3ad T3: WebApp openapi and client regenerated 2026-12-01 01:20:29 -06:00
alberto 2d7a77f1cf T6: TEA follow-up carries the case state beside the route stage
listed() gives each row case = confirmed | not_confirmed | in_process from
the confirmed / not-confirmed dates against the cut-off; a date after the
cut-off does not count. Filter tea-case, Patient extension tea-case and its
code system follow the tea-step / tea-age-group pattern; those two
extensions were not declared and now are. Tests: the three outcomes around
the cut-off, the filter, and the Patient extension.
2026-12-01 01:10:35 -06:00
alberto 332da5f82a T4: the synthetic site prints the ADOS-2 items from the one list
The site report takes each module's items, titles and domains from
core.tea.ados2_items instead of the catalog titles and the flat item sets,
and the erick_site extraction patterns match the exact titles per module,
so one list drives generation, extraction and scoring. Tests: the stored
patterns of both pipelines equal the table; the site report follows the module.
2026-12-01 01:10:29 -06:00
alberto 133e9462a7 Merge parity/main into parity/T3-training-source
# Conflicts:
#	WebApp
#	models
2026-12-01 01:09:51 -06:00
alberto d95b7b9569 T3: persistance.cluster.TrainingSource and eeg.without_diagnosis; TEA training inputs described as folders with edades.csv (path, age in months) 2026-12-01 00:53:32 -06:00
alberto 3994877859 T2: logic tests only over the merged suite; capture tooling removed
PLAN-feature-parity §2.13, P7 rule.
- removed tools/capture_pages.py, tools/capture_pages.mjs, tools/capture_association.py
  — they produced reference fixtures for parity tests that no longer exist.
- removed tests/fixtures/reference/ (cacu, cama, tea ui captures: pages.json,
  responses.json, screenshots) — only the capture tools and two comments read them.
- removed models/tests/recurrence_reference.py — reference-parity helper, unused.
- kept from rebuild, all fast and pure or in-process SQLite: test_cama_recurrence_site,
  test_core_fhir_record, test_core_sources, test_measure_periods, test_patient_search,
  test_promotion_reports, WebApi test_sources and test_users (TestClient on own_platform).
  Already removed in T1: test_tea_association, test_persistance_eeg_study, test_backup,
  test_link_answers, the SQL Server and PostgreSQL source cases (whole platforms or
  external servers).
- tools/load_site.py, synthetic/ and tests/fixtures/synthea stay: they load a demo
  deployment, not tests.
2026-12-01 00:46:19 -06:00
alberto 95069151a8 Logic tests after the merge: in-process own_platform fixture for the sign-in and source tests; files test reads the spool 2026-12-01 00:23:32 -06:00
alberto e80dee1b5a Merge origin/rebuild into parity/T1-merge
T1 of PLAN-feature-parity (§2.1, 2.2, 2.4, 2.12): one design per concern.
- Non-TEA from rebuild: CaCu/CaMa (recurrence scenarios, factors, model titles in
  core.models, escenario-clinico on RiskAssessment, CaMa procedures and recurrence
  conditions), Conectar source types (core.sources), files spooled straight to their
  table (persistance.files, nodes keep/discard), promotion reports set by the site
  (registry.required, retired versions still refused), backups, deploy and delivery.
- TEA backend from tea/parity: core/tea/follow_up.py, Persistance eeg.py and the TEA
  reads in persistance/fhir.py. Deleted: rebuild's core/tea/association.py, its TEA
  Patient extensions and code systems in core/fhir.py (tea-case, tea-eeg-status,
  tea-eeg-alteration, _tea_listed), its TEA follow-up read, the duplicate
  FOLLOW_UP_WINDOWS, and the tests of that code (test_tea_association,
  test_persistance_eeg_study, reference/tea/association.json). T6 adds route stage and
  case state to tea/parity's follow-up module.
- core.models titles name the association by its registered name (ados2_association).
- Execution: tea/parity's persistance.cluster/models.execution; the dask-worker image
  stays and syncs the app as is (no dask extra: Persistance depends on dask).
- Auth: rebuild's users and sign-in; compose carries both env sets.
- Tests: tea/parity's conftest (P7); capture_reference.py and the CaCu/CaMa hospital
  pipelines (only rebuild's page runner read them) stay deleted. CI keeps tea/parity's
  jobs.
- uv.lock re-resolved.
2026-11-30 23:58:00 -06:00
alberto e7d5bbb09d Merge tea/P5.5-e2e into tea/parity
Gobernanza preview "Guardar como PDF", the Playwright TEA page tests over
the synthetic TEA hospital with their runner and CI step, and the fixes
they found (TEA xlsx name, ng serve with Plotly, repeated record numbers,
bundle export error text). Submodules fast-forwarded.
2026-11-30 19:23:21 -06:00
alberto cedf32d3cc P5.5: Gobernanza preview PDF and Playwright TEA page tests
Restores a page-test runner (WebApi/tests/test_webapp.py, marker webapp,
deselected by default through addopts) that loads the synthetic TEA
hospital through the platform and runs the Playwright TEA cases; the CI
web job runs it again after ng test. The ADOS-2 preview carries item
titles from core.tea.ados2_items (Persistance PreviewAdos2.titles).

Checks on the VM: ruff check, ruff format (128 files), lint-imports (2
kept), pytest 132 passed / 1 deselected, ng build, ng test 16 files /
57 tests, Playwright TEA cases 3 passed (runner 1 passed, 5 min) in
mcr.microsoft.com/playwright:v1.64.1-noble.
2026-11-30 19:23:10 -06:00
alberto 39c2a8ddf4 Merge tea/final: logic-tests-only suite (P7) and ADOS-2 item list end to end (P8) 2026-11-30 18:26:43 -06:00
alberto 0f625d7071 Merge tea/P5-combined: TEA indicators, TEA patient record, gobernanza and P6 cleanup 2026-11-30 18:26:35 -06:00
alberto ba4509d9f4 Merge tea/P8-ados2-titles into tea/final 2026-11-30 17:01:26 -06:00
alberto 9e1fe279bb ADOS-2: one item table per module drives reports, extraction, scoring and FHIR
core/tea/ados2_items.py holds, for toddler, module_1 and module_2, the
ordered items of specs/P8-ados2-items-by-module.md (domain, subdomain,
code, exact title, catalog field); it is the only place the list lives.
A copy of the spec is kept as tests/fixtures/ados2_items_by_module.md and
a test checks the table against it.

- Extraction: the stored hospital_tea.json patterns equal
  ados2_items.patterns() (test), so they cover exactly the table's items.
- Scoring: SA/RRB totals are the module's own AS/CRR items (3 counts as
  2); SOCIAL_AFFECT_ITEMS / RESTRICTED_REPETITIVE_ITEMS are removed. A
  module without a table (module_3, or none) has no total. CSS cuts,
  algorithm and classification rules are unchanged; since Module 1 now
  always prints B-11 and A-3, its algorithm resolves to few_to_no_words.
- Synthetic reports are generated from the table, same layout; headings
  use the spec's casing. Module by age at M-CHAT: under 24 months
  toddler, 24-29 module_1, 30+ module_2. The toddler report says
  'se aplicó el Módulo para niños pequeños', which the concept map maps
  to toddler.
- FHIR: ados2-item-<module>, ados2-domain and ados2-subdomain code
  systems and ados2-domain / ados2-subdomain extensions; the aggregate
  Observation lists the module's items first in table order, each with the
  item code/title coding, then the remaining catalog items as before.

Synthetic CSS changes (seed 7): child 4 9->8, child 11 7->6 (module_1,
now few_to_no_words with B-11 and A-3); child 10 (18 months) is now a
toddler: no CSS, severe_concern (was module_1 CSS 10, autism). Others
unchanged.
2026-11-30 16:56:26 -06:00
alberto 614973e658 The suite keeps only logic tests
Reduce the Python suite from 224 to 115 collected cases. The local
Python run took about 43 seconds. Historical runs of the SQLite and
PostgreSQL TEA gates alone total roughly two hours. The full baseline
was not timed again. WebApp unit sources and e2e/ are unchanged.
The Python and WebApp suites run on the test machines.

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

Remove the hospital and reference fixtures, reference capture tool,
HL7 validator, and test-only SQL Server, PostgreSQL and Dask services.
Remove the Playwright Python runner and CI step pending P5.5. Keep the
synthetic TEA drawing and ConceptMap for that seed, and retain the
Synthea modules, site's drawing and ConceptMap, and test image's Java
and Synthea runtime for the documented synthetic.load workflow.
Production Dask settings and deployment services stay in place.

Use one temporary SQLite engine with attached schemas and a per-test
dlt directory for persistence tests. Render the three existing gold
SQL models with minimal Jinja bindings and seeded upstream rows. That
keeps the first valid EEG, score attachment, and latest ADOS-2 checks
independent of a dbt build. Seed EEG selection directly in SQLite.
Drive API rules by direct calls and use a minimal Dagster client
double for cancellation. Let the real preview op run with an in-process
context and use a missing EDF to exercise cleanup after failure.
Use fixed synthetic values for spectral tests, measures, FHIR rows
and survival outcomes. Keep execution map logic in sync mode. Drop
the internal batch-size override and assert content addressing,
temporary file cleanup and deduplication instead.

The retained I/O tests guard behavior that requires actual storage:
- test_person_ids_survive_a_review_merge_and_split checks persistent
  identities and replacement links across successive reviews.
- test_collected_files_are_kept_once_by_content and
  test_save_analyses_writes_eeg_sites verify rows or bytes written
  to SQLite by the real persistence path.
- test_tea_follow_up runs the actual SQL rules and joins in SQLite.
- The bundle export tests (determinism, manifest hashes, version
  selection) need real registry snapshots and archive bytes.
  Round-trip, duplicate import, tamper and untrusted-digest tests
  require the archive or registry to verify the outcomes. Lifecycle
  checks require real alias, report and retirement state in SQLite.
- test_import_rejects_invalid_uploads, test_training_inputs and
  test_previews_area assert real filesystem cleanup or preservation.
  Both preview-op cleanup tests verify that temporary study input is
  deleted on return and on error. The bad-reference test verifies
  filesystem-based cohort diagnostics without measuring a cohort.
- The three synthetic TEA checks exercise the generated SQLite
  hospital's profile coverage and reproducibility, and read the
  emitted PDFs with the actual drawing's extraction patterns.

removed tests/test_dbt_tea_follow_up.py::test_tea_follow_up[sqlite] — slow integration (logic now covered by test_tea_follow_up executing the production model SQL against small SQLite tables)
removed tests/test_dbt_tea_follow_up.py::test_tea_follow_up[postgres] — slow integration (logic now covered by the SQLite-only test_tea_follow_up)
removed tests/test_persistance_eeg_sites.py::test_save_analyses_writes_eeg_sites — slow integration (logic now covered by the in-process SQLite test_save_analyses_writes_eeg_sites)
removed tests/test_persistance_files.py::test_collected_files_wait_on_disk_and_are_kept_in_batches — slow integration (logic now covered by test_collected_files_are_kept_once_by_content)
removed tests/test_synthetic_tea.py::test_every_eeg_reads_as_a_study — slow integration (logic now covered by test_header_reads_the_facts)
removed tests/test_synthetic_tea.py::test_the_clean_eegs_pass_the_analysis — slow integration (logic now covered by test_dominant_peak_recovers_a_posterior_rhythm_above_background and test_band_power_excludes_line_noise_and_rescales_clean_bins for the underlying signal calculations)

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

removed WebApi/tests/test_bundles.py::test_export_and_import_through_the_api — slow integration (logic now covered by test_layout_and_manifest_hold_every_file_hash and test_roundtrip_registers_candidates_with_lineage)
removed WebApi/tests/test_bundles.py::test_import_refuses_a_wrong_sha_and_a_non_zip — slow integration (logic now covered by test_import_rejects_invalid_uploads)
removed WebApi/tests/test_bundles.py::test_importing_the_same_bundle_again_fails_the_run — slow integration (logic now covered by test_importing_twice_is_a_conflict_and_partial_imports_skip)
removed WebApi/tests/test_bundles.py::test_export_guard_failure_is_422 — slow integration (logic now covered by test_reference_group_size and test_selection_champion_latest_all)
removed WebApi/tests/test_bundles.py::test_an_untrusted_bundle_is_refused — slow integration (logic now covered by test_import_rejects_invalid_uploads and test_import_refuses_an_untrusted_digest)
removed WebApi/tests/test_cacu.py — parity-only
removed WebApi/tests/test_cacu.py::test_cacu_from_the_hospital_to_indicators_and_risks — parity-only
removed WebApi/tests/test_cama.py — parity-only
removed WebApi/tests/test_cama.py::test_cama_from_the_hospital_to_indicators — parity-only
removed WebApi/tests/test_conectar.py — slow integration (logic now covered by test_person_ids_survive_a_review_merge_and_split and test_a_concept_map_onto_a_code_no_field_allows_is_refused)
removed WebApi/tests/test_conectar.py::test_an_operator_connects_a_site_and_settles_its_review — slow integration (logic now covered by test_person_ids_survive_a_review_merge_and_split and test_a_concept_map_onto_a_code_no_field_allows_is_refused)
removed WebApi/tests/test_fhir_door.py — slow integration (logic now covered by test_fhir_in_joins_encounter_results_and_subject_by_full_url and tests/test_core_tea_fhir.py for FHIR mappings)
removed WebApi/tests/test_fhir_door.py::test_what_one_platform_serves_another_places_through_the_fhir_door — slow integration (logic now covered by test_fhir_in_joins_encounter_results_and_subject_by_full_url and tests/test_core_tea_fhir.py for FHIR mappings)
removed WebApi/tests/test_fhir_door.py::test_a_new_label_is_a_concept_map_row_not_code — slow integration (logic now covered by test_hospital_codes_and_dates_become_platform_values)
removed WebApi/tests/test_governance.py::test_version_lifecycle — slow integration (logic now covered by models/tests/test_bundle.py::test_version_lifecycle)
removed WebApi/tests/test_governance.py::test_imported_lineage — slow integration (logic now covered by test_roundtrip_registers_candidates_with_lineage)
removed WebApi/tests/test_governance.py::test_preview — slow integration (logic now covered by test_the_job_deletes_its_files_and_returns_the_result_as_output and test_shape_outputs)
removed WebApi/tests/test_governance.py::test_training_inputs — slow integration (logic now covered by the direct-call test_training_inputs)
removed WebApi/tests/test_runs.py::test_unknown_run_is_404 — implementation-detail
removed WebApi/tests/test_runs.py::test_failed_run_reports_its_error — slow integration (logic now covered by test_shape_failure_message_is_the_ops_own_exception)
removed WebApi/tests/test_runs.py::test_history_filters_by_job_and_domain — implementation-detail
removed WebApi/tests/test_runs.py::test_run_requests_validate_the_execution_choice — slow integration (logic now covered by test_resolve_rejects_unlisted_scheduler_and_scheduler_in_local_mode)
removed WebApi/tests/test_runs.py::test_execution_options_and_health — implementation-detail
removed WebApi/tests/test_runs.py::test_tea_eegs_analyze_validates_scope — slow integration (logic now covered by test_scope_validation)
removed WebApi/tests/test_runs.py::test_a_locked_run_storage_is_read_again — implementation-detail
removed WebApi/tests/test_runs.py::test_cancel_waits_for_a_starting_run — implementation-detail
removed WebApi/tests/test_runs.py::test_cancel_a_finished_run_is_409 — slow integration (logic now covered by test_cancel_a_finished_run_is_409 with a client double)
removed WebApi/tests/test_runs_concurrency.py — slow integration (logic now covered by test_cancel_returns_the_terminal_or_cancelling_state for the queued transition)
removed WebApi/tests/test_runs_concurrency.py::test_writing_runs_never_overlap — implementation-detail
removed WebApi/tests/test_runs_concurrency.py::test_cancelling_an_ingest_run_leaves_no_silver_or_gold — slow integration (logic now covered by test_cancel_returns_the_terminal_or_cancelling_state for the API state transition)
removed WebApi/tests/test_runs_concurrency.py::test_cancelling_a_queued_run_never_starts_it — slow integration (logic now covered by test_cancel_returns_the_terminal_or_cancelling_state for the queued transition)
removed WebApi/tests/test_runs_concurrency.py::test_a_dead_run_does_not_stay_running — implementation-detail
removed WebApi/tests/test_synthea.py — slow integration (logic now covered by test_fhir_in_joins_encounter_results_and_subject_by_full_url and test_hospital_codes_and_dates_become_platform_values)
removed WebApi/tests/test_synthea.py::test_a_synthea_population_comes_in_through_the_fhir_door — slow integration (logic now covered by test_fhir_in_joins_encounter_results_and_subject_by_full_url and test_hospital_codes_and_dates_become_platform_values)
removed WebApi/tests/test_synthea_cama.py — slow integration (logic now covered by test_fhir_in_joins_encounter_results_and_subject_by_full_url for FHIR ingestion mapping)
removed WebApi/tests/test_synthea_cama.py::test_a_synthea_cama_population_comes_in_through_the_fhir_door — slow integration (logic now covered by test_fhir_in_joins_encounter_results_and_subject_by_full_url for FHIR ingestion mapping)
removed WebApi/tests/test_tea.py — parity-only
removed WebApi/tests/test_tea.py::test_tea_from_the_hospital_to_indicators — parity-only
removed WebApi/tests/test_training_config.py::test_tea_training_config_schema — slow integration (logic now covered by the direct-call test_tea_training_config_schema)
removed WebApi/tests/test_training_config.py::test_other_domains_have_no_reference — slow integration (logic now covered by the direct-call test_other_domains_have_no_reference)
removed WebApi/tests/test_training_config.py::test_train_validates_the_reference — slow integration (logic now covered by the direct-call test_train_validates_the_reference and test_bad_references_fail_with_a_reason)
removed WebApi/tests/test_webapp.py — slow integration (logic now covered by existing WebApp unit tests for figure, row and export builders; loaded-page browser coverage is deferred to P5.5)
removed WebApi/tests/test_webapp.py::test_every_page_loads_from_the_api — slow integration (logic now covered by existing WebApp unit tests for figure, row and export builders; loaded-page browser coverage is deferred to P5.5)
2026-11-30 16:48:32 -06:00
alberto e886863936 ADOS-2 extraction matches the exact item titles of Módulos T, 1 and 2
The ados2_results patterns in the hospital fixture were assumed titles
(e.g. "Búsqueda de atención" for ignoring, "Cantidad de acercamientos
sociales" for the caregiver item, "Calidad de los acercamientos
sociales", unaccented and abbreviated variants). They now match the
question titles verbatim from specs/P8-ados2-items-by-module.md, each
optionally preceded by its own module code (A-2, B-16b, ...), so a report
that prints "<code> <title> <score>" or, as the synthetic reports do,
"<title> <score>", both read. Codes are tied to their own title, so one
module's code before another item's title does not match. Spaces between
words are \s+ so a title wrapped across lines still reads. Módulo 3
titles are out of scope and not matched. Fields, scoring and the report
layout are unchanged; the synthetic generator already prints these exact
titles, so it is untouched.

Adds a pure test with one snippet per module (with and without codes).
2026-11-30 16:37:16 -06:00
alberto ae0619f60b Merge P6 cleanup into P5-combined 2026-11-30 16:34:17 -06:00
alberto 6484eaa99b Merge P5.3-tea-patient into P5-combined 2026-11-30 14:20:14 -06:00
alberto d1af78e0b9 Merge P5.2-tea-indicators into P5-combined 2026-11-30 14:20:14 -06:00
alberto 4af892e055 Merge P5.4-gobernanza into P5-combined 2026-11-30 14:20:14 -06:00
alberto 22bfc175e2 TEA patient pages: the record and the risk analysis page
Publish the existing follow-up row's step and age group on TEA Patients
as valueCode extensions. Carry the stored champion name/version on
aggregate EEG metric scores as eeg-model. Test populated, missing and
non-TEA fields and the champion gate. The Patient search and curve
operation keep their existing schemas. Regenerating OpenAPI and the
client produced identical files.

Advance WebApp to d995a36. The record uses Patient search reverse
includes and contains the dated events those resources describe. The
risk route uses the RiskAssessment EEG for its plots and links to
Seguimiento with the agreed patient query parameter. The WebApp
commit records the layout, figure, missing-value, and PDF choices.

Ruff check, Ruff format check, all nine TEA FHIR mapper tests, and
OpenAPI/client regeneration checks passed. Static TypeScript and
Angular template checks passed with a temporary PDF type shim. npm ci, ng build, ng test --watch=false, and Playwright run with P5.5.
2026-11-30 14:19:03 -06:00
alberto fcb6e3c806 Indicadores TEA: Resumen, Trazabilidad, Seguimiento, Análisis de riesgo, periodicities 2026-11-30 14:19:03 -06:00
alberto c76bc55369 Gobernanza: execution, models (training, run monitor, checks, lineage, bundles, interpretability), EEG studies 2026-11-30 14:19:03 -06:00
alberto 65f714337a Cleanup of the TEA parity work: no prose in code, no hacks, everything in its place
Parity-added comments and docstrings removed (tool directives kept); association cohort SQL moved into persistance.eeg, the EEG value-score join shared there; curve scoring uses the MODELS registry; narrower exception handling when loading a preview pipeline; stale test name fixed. No behaviour change intended.
2026-11-30 13:41:55 -06:00
alberto 2cf26e77f1 Merge P5.1: WebApp shared pieces (Plotly partial bundle, card actions, print report, export module) 2026-11-30 13:36:35 -06:00
alberto 6481a0f525 WebApp shared: Plotly partial bundle, card actions, print report, export module 2026-11-30 13:36:35 -06:00
alberto 9c8021050d Merge P4.2: TEA per-child FHIR resources (ADOS-2, EEG report, checks, metrics, Condition, RiskAssessment)
Hospital gate on the VM: SQLite and Postgres passed, each child's resources compared with the reference.
2026-11-30 12:22:46 -06:00
alberto 0ce9a76ce6 TEA gate: scores keyed by the served report id 2026-11-30 10:42:56 -06:00
alberto 125764f847 TEA gate: complex extensions in the FHIR helper 2026-11-30 09:10:39 -06:00
alberto 1af7c2c609 TEA per-child FHIR resources: ADOS-2, EEG report, checks, metrics, Condition, RiskAssessment
Aggregate ADOS-2 Observation (CSS, classification, module, 22 items); one EEG DiagnosticReport per signal-backed study (id from person and study date; quality, validity, duration, age, channels) with its check and metric Observations (electrode/zone components; z, outside and curve centiles only from a champion); F84.0 Condition; one RiskAssessment per child with every association pair, the headline first (altered biomarkers by q, else lowest q). Served from silver/bronze, not the screening-gated gold; EEG summary gains fhir_eegs/fhir_metrics. Predictions come from the child's earliest scored EEG.

Checks: ruff, import-linter, 44 pure tests, openapi unchanged, client no drift.
2026-11-30 01:14:21 -06:00
alberto a965346d35 Merge P4.1: TEA follow-up Patient search with TEA filters and $eeg-summary
Hospital gate on the combined P4.1+P4.3 branch: SQLite passed (76 min, server), Postgres passed (48 min, VM, peak 5.7 GB).
2026-11-30 00:54:43 -06:00
alberto 576378fe48 Merge P4.3: governance REST (checks, retire, lineage, training inputs), TEA curve, preview and EEG summary
Hospital gate on the combined P4.1+P4.3 branch: SQLite passed (76 min, server), Postgres passed (48 min, VM, peak 5.7 GB).
2026-11-30 00:54:43 -06:00
alberto 5dfcc49001 TEA gate waits stretch with TEA_GATE_SLOW 2026-11-29 23:10:46 -06:00
alberto a20042f51e EEG governance summary counts every EEG (bronze), not the screening-gated gold
The SQLite gate found eegs 54 / metrics 190 / with_z 139 / low 28 against the reference 62 / 215 / 154 / 32: gold.tea_eegs and tea_eeg_metrics only hold the screening cohort. Checked on that run's database: the new counts equal the reference exactly.
2026-11-29 21:27:41 -06:00
alberto 4b21a444f5 Distinct operation names for the two EEG summaries 2026-11-29 19:47:01 -06:00
alberto 3d1d9c6047 Merge P4.3 into P4.1 for one combined gate 2026-11-29 19:46:08 -06:00
alberto b44a898bcc Governance REST: version checks, retire, lineage, training inputs; TEA curve, preview, EEG summary
Generic: GET .../versions/{v}/checks (reports present/missing, candidate/champion/retired), POST .../retire (not the champion), GET .../lineage (params, metrics, tags, bundle origin), training inputs declared by the domain (TEA reference cohorts: .edf and edades.csv only, path-safe, temp+rename). TEA: GET /models/tea/{name}/versions/{v}/curve (centiles by month 16-36 via curves.centiles; scoring unchanged, regression test), POST/GET /tea/preview, GET /tea/eegs/summary (nine fields from gold/bronze), checks and regions in GET /tea/eegs/{id}.

Checks: ruff, import-linter, openapi diff, client generation, centile regression.
2026-11-29 19:45:51 -06:00
alberto 67524afd4c TEA follow-up: Patient search with TEA filters and $eeg-summary
Implement overlap selection, ADOS-2 scoring and TEA filters for Patient
search and $eeg-summary. Add comparisons for all 29 reference queries
inside the existing hospital test. Record the WebApi and WebApp changes
through their submodule pointers.

Implementation choices
- Store filter kind, row field and allowed tokens together. Combine
  repeated token values with comma-separated tokens. Use _limit and
  finite Decimal bounds for numeric comparisons. Validate every supplied
  value even when a preceding condition misses.
- Keep stored row dates intact and normalize them for date comparisons,
  ordering and scoring. Count alterations in EEG_METRICS order and
  derive the missing EEG count from the total.
- Use TEA_PERSONS for the common SQL projection and _patient_rows for
  API selection. Share the four follow-up Query declarations. Validate
  filters against an empty row to handle empty selections. Serialize
  repeated paging parameters with urlencode and doseq. Skip operation
  routes when deriving metadata read and search interactions.
- Use _follow_up_gate for fixture translation and comparison. Normalize
  record numbers to integers and compare alteration counts by metric.

Ruff check and format check passed from the worktree root.
Import lint passed both contracts and all 20 pure follow-up tests passed.
FHIR handler smoke checks with stubbed reads passed. The OpenAPI diff
showed the new start parameter and summary operation. The repeated
client regeneration matched. Git diff --check passed. The hospital gate runs on the test machines.
2026-11-29 19:42:17 -06:00
alberto 32f219c691 Merge P2: the ADOS-2 association model (tea-lib Firth/ordinal port), MLflow model, bronze and gold
Hospital gate with the association step passed on SQLite (65 min) and Postgres (80 min, peak 5.2 GB): all 15 pairs match relacion_ados2 and all 470 scores relacion_ados2_paciente.
2026-11-29 18:50:53 -06:00
alberto a325a086dd 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:02 -06:00
alberto 2bd174cd49 Merge P3.8: Dask scheduler and workers in the test profile and CI; writes-overlap, cancel and remote-mode tests
SQLite hospital gate passed with the cancel step (50 min); compose: every test passed across runs (30 + the two fixed tests rerun: options on sqlite and postgres, queued cancel); cancel now waits out a starting run.
2026-11-29 07:43:50 -06:00
alberto 05e2c03ab3 P3.8 tests follow the configured Dask scheduler and Dagster's queue order 2026-11-29 07:43:49 -06:00
alberto afad847de2 Runs API: cancel waits out a starting run 2026-11-29 06:06:50 -06:00
alberto 9971583a7f Dask scheduler and workers for the test profile and CI; writes-overlap, cancel and remote-mode tests
The compose test profile and the CI python job run a Dask scheduler and two workers (1500 MiB each; compose caps: worker 3 GB, scheduler 512 MB) so remote mode is tested for real.
2026-11-29 04:47:23 -06:00
alberto 5859555c7b Merge P3.2b: the TEA hospital test follows the sensor flow; re-analysis by id in local mode; first_n
SQLite gate passed (60 min) with the full new flow; the Postgres gate passed every step before the re-analysis check (whose only fix after it was None-aware comparison).
2026-11-29 04:40:53 -06:00
alberto 704ca664a7 TEA gate: re-analysis comparison keeps empty values empty 2026-11-29 03:38:20 -06:00
alberto 81c50481a0 TEA hospital test follows the sensor flow; re-analysis by id in local mode; first_n
The single hospital test waits for the run the tea_eeg_after_ingest sensor starts, applies the curves with POST /tea/eegs/analyze (pending), and at the end re-analyses one study by id in local (Dask) mode and checks it equals the sync analysis, and that an unknown id fails with "no EEG". first_n is checked in process on the synthetic TEA source. Checks: ruff, import-linter, models/tests/test_tea_job.py 9 passed.
2026-11-29 01:25:29 -06:00
alberto 707d6b49c0 Merge P3.5: tea_preview job, one file previewed, result as run output
Gates on the combined P3.5+P3.7 branch: SQLite passed (47 min), Postgres passed (55 min, peak 5.5 GB).
2026-11-29 01:19:36 -06:00
alberto df13c81147 Merge P3.7: training config, reference cohort name and mains frequency
Gates on the combined P3.5+P3.7 branch: SQLite passed (47 min), Postgres passed (55 min, peak 5.5 GB).
2026-11-29 01:19:36 -06:00
alberto 704edf071e Merge tea/parity into P3.5 (mlflow-init) 2026-11-29 00:30:51 -06:00
alberto 969f8006cf Merge mlflow-init: test platforms start with MLflow's schema 2026-11-29 00:30:51 -06:00
alberto 06f2bf45ac Test platforms start with MLflow's schema in place, built once per session
The SQLite TEA gate failed in training: the API and the run opened the new MLflow SQLite file together, both ran its migrations, and one failed with "duplicate column name: step". Deployments use an MLflow server, so only tests had the race.
2026-11-29 00:30:51 -06:00
alberto 8ec1a04891 Merge P3.7 into P3.5 for one combined gate 2026-11-28 16:32:11 -06:00
alberto 8c51d84fde Merge tea/parity into P3.5 (ingest-memory, gate wait) 2026-11-28 16:32:11 -06:00
alberto a34d19c0bd Merge tea/parity into P3.7 (ingest-memory, gate wait) 2026-11-28 16:31:56 -06:00
alberto 9560c676fd Merge ingest-memory: TEA gate analysis wait 3600 s 2026-11-28 16:31:46 -06:00
alberto 24de28ede9 TEA gate: analysis wait 3600 s 2026-11-28 16:31:45 -06:00
alberto 93c1949571 Merge ingest-memory: ingest keeps files on disk and stores them in bounded loads (Postgres gate OOM); gate analysis wait 3600 s 2026-11-28 16:31:34 -06:00
alberto 0a6872b79d Ingest keeps a source's files on disk until stored, and stores them in bounded loads
The Postgres TEA gate was OOM-killed reading the hospital's 62 EDFs (~2 GB): sql_table fetched every row in one chunk, Collector held every blob in memory, and keep() handed all of them to one dlt load. Now Collector spills each blob to a temp folder (removed after the load, also on failure), keep() writes ~64 MB per load reading each file when its batch is written (and asks which are known once), and the hospital pipeline reads its two blob tables 4 rows at a time.
2026-11-28 15:16:40 -06:00
alberto aad9f4bd31 Merge tea/parity into P3.5 (P1.4) 2026-11-28 13:37:28 -06:00
alberto efe116dcb0 tea_preview job: one file previewed, result as run output
Preview files live in an ephemeral area (DATA_DIR/previews, swept after a day, discarded after the run). The result (EEG verdict, checks, metrics with electrode and zone scores; ADOS-2 items, CSS, warnings) is the step output metadata, served by GET /runs/{id}?outputs=true. The preview check runs inside the existing hospital gate test instead of a second 80-minute load.

Checks: ruff, import-linter, openapi diff, 13 unit tests (sandbox).
2026-11-28 13:37:28 -06:00
alberto 77ffe24ee8 Merge tea/parity into P3.7 (P1.4); tea/__init__ keeps ADOS2_ITEMS and TRAINING_OPTIONS 2026-11-28 13:26:44 -06:00
alberto 493de8c1a1 Training config: reference name and mains frequency
A TEA training run can name its reference cohort (a folder under TEA_REFERENCE_ROOT with edades.csv) and mains frequency (50/60 Hz, validation only); the cache key and the reports carry both. GET /models/{domain}/{name}/training-config gives the train form JSON schema and defaults. Checks: ruff, import-linter, openapi diff, 8 model tests (sandbox).
2026-11-28 13:26:19 -06:00
alberto df5368c3e8 Merge P1.4: gold follow-up, EEG checks and regions 2026-11-28 13:24:54 -06:00
alberto 74c9827cef Gold tea_follow_up, tea_eeg_checks, tea_eeg_regions; bronze eeg_sites
tea_follow_up: one row per screening child (step, status, step date, M-CHAT score, latest ADOS-2 items for core.tea.ados2.score, first good EEG with duration, channels, whether a champion scored it and its result, alteration flags). tea_eeg_checks: every check of an EEG. tea_eeg_regions: electrode and zone values (new bronze.eeg_sites, written by save_analyses) with their age-curve scores. ADOS2_ITEMS: the 22 catalog items.

Checks: ruff, import-linter, dbt parse; compose: 9 passed (test_core_tea, test_persistance_eeg_sites, test_dbt_tea_follow_up on sqlite and postgres, test_synthetic_tea).
2026-11-28 13:24:54 -06:00
alberto 58f0e7f38f Merge P3.6: EDF reader node in the ingestion DSL 2026-11-28 13:15:14 -06:00
alberto 0fc18077c4 Merge tea/parity into P3.6 (P3.4 bundles, runs-locked, P1 gate); openapi.json regenerated, identical 2026-11-28 10:32:03 -06:00
alberto 6eb04a1d27 EDF reader node in the ingestion DSL
The edf node turns a column of EDF file hashes into edf_* header columns (patient code, sex, birth date, study date, record code, duration, channels, error) for identity and the eeg target. read.header parses the fixed header with the standard library (declared duration, zero signals accepted); _kept/_open keep edfio and refuse truncated or zero-signal files with FileNotValid.

Checks: ruff, import-linter, openapi diff; compose: 21 passed (test_core_pipeline, test_edf_header, test_edf_node, test_edf_upload); ng build clean.
2026-11-28 10:30:50 -06:00
alberto 7cba0df111 Merge P3.4: generic model bundles, export and import
# Conflicts:
#	WebApi
2026-11-28 09:24:54 -06:00
alberto fdce3a5f49 Generic model bundles: export and import
Export (GET /models/{domain}/export) writes a deterministic zip of chosen versions with a manifest of SHA-256s, after the domain guard (TEA: n_reference >= 5, no study codes, dates or paths). Import (POST /models/{domain}/import, Dagster job import_bundle) stages the upload, checks its SHA-256 and that the operator listed it in $DATA_DIR/bundles/trusted (403 otherwise), verifies every file against the manifest and registers new candidate versions with lineage tags; duplicates are skipped.

Checks: ruff, import-linter, openapi diff; compose: 43 passed (test_bundles, test_runs, test_bundle, test_core_bundle_guard); ng build clean.
2026-11-28 09:24:40 -06:00
alberto 15bdef5ee2 Merge runs-locked: the runs API retries a locked Dagster run storage 2026-11-28 08:43:00 -06:00
alberto 3bca49469b Runs API retries a locked Dagster run storage 2026-11-28 08:43:00 -06:00
alberto 4f83e8fae9 Merge P1 gate: TEA end-to-end parity against the sitio-b hospital (SQLite passes); M24 by age group and sex 2026-11-28 08:14:35 -06:00
alberto be77587f8f Merge P3.3: runs API (progress, info and warnings, cancel, history), execution options and health 2026-11-28 06:54:01 -06:00
alberto 0616df6927 Runs API and run monitoring: Dagster ends a run whose process died, and a cancel that never stops 2026-11-28 06:54:01 -06:00
alberto 993a36599c TEA gate: indicators after scoring 2026-11-28 06:38:32 -06:00
alberto acef3e97fd M24 by age group and sex: tea_screening carries the child's sex, and the age_sex stratifier joins them as one value
The current platform reports M24 by age and sex (edad_sexo); the WebApp's Resumen draws it.
2026-11-28 05:56:42 -06:00
alberto 529bd0ee7e TEA gate: ADOS-2 match by record number 2026-11-28 04:50:08 -06:00
alberto 25af679665 TEA gate follows the sitio-b reference 2026-11-27 23:56:15 -06:00
alberto f0df5799ef Merge P0.3: TEA reference from sitio-b 2026-11-27 23:53:49 -06:00
alberto 125b413ec6 TEA reference recaptured from sitio-b: 62 children with real EDFs, M30/M31, follow-up queries, patient summaries, code systems, association tables, baselines bundle
The hospital manifest records the sitio-b TEA hospital (sha256 2b2abae4...), which replaces the
200-child synthetic one. follow_up and patients are stored gzipped (58 MB and 6 MB as JSON); the
capture tool writes them that way with mtime 0, so a recapture is byte-identical.
2026-11-27 23:53:48 -06:00
alberto 0b4851b681 Merge P3.2: the tea_eeg job (analyse, score age curves, relate ADOS-2, rebuild gold) and the after-ingest sensor 2026-11-27 23:30:06 -06:00
alberto c4c11fa4ef EEG scope: which EEGs an analysis takes (pending, first n, named ids), in a fixed order 2026-11-27 18:02:28 -06:00
alberto 931e4e5107 Merge P3.1: execution backend (sync, local, remote Dask) with live progress 2026-11-27 17:56:17 -06:00
alberto ae924a6399 compose passes DASK_LOCAL_WORKERS, so a shared host can size the local cluster 2026-11-27 17:56:17 -06:00
alberto a82edd879f Execution backend: the cluster choice, allow-list, health and progress shape live in Persistance; Dask and psutil added 2026-11-27 17:19:55 -06:00
alberto 1afc89ab2d Merge P1.3: gold for M30 and M31 2026-11-27 17:11:46 -06:00
alberto b6cd1f7d50 Gold for M30 and M31: each child's first good EEG and its alterations, every person in the prevalence age band
tea_alterations: one row per child whose chain reached the EEG step, dated by her first good EEG,
altered when a metric scored by a champion curve falls outside p5-p95. tea_prevalence: every person
with a birth date, the day she enters and leaves the 16-36 month band, and her confirmation day.
add_days macro on every engine; tea.yml tests every TEA gold model.
2026-11-27 17:11:46 -06:00
alberto abb1183691 Merge P1.1: TEA identity reads sex and name 2026-11-27 17:09:25 -06:00
alberto 58d2a8eeb0 The TEA pipeline reads the child's sex and name into identity
As the CaMa pipeline does: the patients' sex (through the hospital_tea ConceptMap) and full name,
and the link compares sex too. M31 is stratified by sex; the follow-up list searches names.
The TEA gate runs once the sitio-b reference is captured (P0.3).
2026-11-27 17:09:25 -06:00
alberto ea800e48b8 Merge P0.4: synthetic TEA hospital 2026-11-27 17:09:07 -06:00
alberto 0b63c19e53 Synthetic TEA hospital: fourteen children covering every case state, ADOS-2 reports in the hospital's layout, generated EDF studies
Default seed EEG verdicts by spec child index:
- 8: valid, complete.
- 9: valid, complete.
- 10: valid, complete.
- 11: invalid, not_analyzable. T3/T4 are dead and P3/P4/O1/O2
  have abnormal amplitudes and intermittent bursts.

After validation, children 8–10 each return a ValueError during
preprocessing. The model's 100 Hz bandpass cutoff exceeds the 64 Hz
Nyquist frequency of the specified 128 Hz studies (since raised to 256 Hz). The test uses the
validation verdict as specified.

Implementation choices:
- Group the fixed profiles, table definitions and report item labels in
  the generator. Insert child by child in a SQLite transaction. Use
  truth row counts to allocate table-local IDs and flatten truth by table.
- Reuse the synthetic package's fixed PDF creation date and fpdf2's
  default margins. Draw the score for the S/D item in print order, then
  replace it with None before totaling and rendering.
- Evaluate continuous EDF events on the sample grid with start-inclusive,
  end-exclusive bounds. Give awake the extra sample when the count is
  odd. Draw the gap after every slow-wave candidate, clip blinks at the
  awake boundary and evaluate beat Gaussians across the full recording.
  Apply awake rhythm and slow-wave scaling to the positioned channels,
  including ears, and give the auxiliary channels their specified events.
- Require positive whole-second durations and positive integer sample
  rates. Keep zero-variance noise at zero. Apply channel faults after
  adding mains. Write each study in a private temporary directory.
- Compare SQLite rows in primary-key order, and use case-insensitive
  fixture patterns to check PDF text. The slow test prints the validator
  checks and any analysis error when run with capture disabled.
- Updated the synthetic package entries in uv.lock against the existing
  locked versions after the registry lookup failed. uv lock validated
  the resulting lockfile.

The default sampling rate was raised to 256 Hz: at 128 Hz the analysis's 100 Hz band edge is above
Nyquist. At 256 Hz children 8-10 analyse fully (valid, complete, five metrics) and child 11 is not analysable.
2026-11-27 17:09:07 -06:00
alberto 2d185eba7f Merge P0.2: TEA capture from sitio-b 2026-11-27 17:03:03 -06:00
alberto 5edc7eebff Capture TEA from sitio-b: follow-up list with each filter, EEG summary, patient summaries, code systems, association tables and bundle manifest
Follow-up queries in the unit check: 24
2026-11-27 17:03:03 -06:00
alberto 2f39d9cd8d M30 and M31: proportions over overlapping groups and status compositions with strata
M30_RESULTADO_EEG counts each child of the cohort whose first good EEG falls in the period, and
of them those with an alteration, one overlapping group per EEG metric. M31_PREVALENCIA counts
every person while in the prevalence age band by her state at the period's end, by sex.
core.measures gains Proportion.overlaps and StatusComposition.strata, generic for every domain.
core.tea sets PREVALENCE_AGE and EEG_METRICS; dbt reads both.
2026-11-27 16:59:59 -06:00
245 changed files with 4978 additions and 347314 deletions
+5 -65
View File
@@ -7,80 +7,25 @@ on:
branches: [rebuild]
env:
# Submodule URLs are SSH; the runner reaches the same repos over the server's HTTP.
GIT_CONFIG_COUNT: 1
GIT_CONFIG_KEY_0: url.${{ github.server_url }}/ISSSTELEON/.insteadOf
GIT_CONFIG_VALUE_0: ssh://git@10.0.10.41:2222/ISSSTELEON/
jobs:
python: # the whole suite, nothing skipped: SQLite and PostgreSQL, OCR included
python:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:17
env:
POSTGRES_PASSWORD: postgres
POSTGRES_DB: platform
options: >-
--health-cmd pg_isready --health-interval 5s --health-timeout 5s --health-retries 10
sqlserver: # the hospital's test source (synthetic.site): ArchivosUni and ResultadosSubrogados
image: mcr.microsoft.com/mssql/server:2022-CU20-ubuntu-22.04
env:
ACCEPT_EULA: "Y"
MSSQL_PID: Developer
MSSQL_SA_PASSWORD: Test-only-Site-1
options: >-
--health-cmd "/opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P Test-only-Site-1 -Q 'select 1' -b"
--health-interval 5s --health-timeout 10s --health-retries 30
env:
POSTGRES_TEST_URL: postgresql://postgres:postgres@postgres:5432/platform
SITE_SQL_SERVER: mssql+pymssql://sa:Test-only-Site-1@sqlserver:1433
PGHOST: postgres
FHIR_VALIDATOR_JAR: /opt/fhir/validator_cli.jar
SYNTHEA_JAR: /opt/synthea/synthea.jar
steps:
- uses: actions/checkout@v4
- run: git submodule update --init
- run: |
echo 'Acquire::Retries "5";' > /etc/apt/apt.conf.d/80-retries # mirrors drop connections
apt-get update --error-on=any
apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-spa ghostscript \
default-jre-headless postgresql-common
# pg_dump of the server's version (backups), as in the product's image.
/usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y
apt-get install -y --no-install-recommends postgresql-client-17
- name: HL7 validator, pinned
run: |
mkdir -p /opt/fhir
curl -sLo /opt/fhir/validator_cli.jar https://github.com/hapifhir/org.hl7.fhir.core/releases/download/7.0.5/validator_cli.jar
echo "9dfe9f305b0f9389eceade2a4a1c9a2740d7b0e614066fdf07a78b571c76d92f /opt/fhir/validator_cli.jar" | sha256sum -c
- name: Synthea, pinned
run: |
mkdir -p /opt/synthea
curl -sLo /opt/synthea/synthea.jar https://github.com/synthetichealth/synthea/releases/download/v4.0.0/synthea-with-dependencies.jar
echo "ed43c20ad40ba5c3bc724503a5af032715fe3c491620b766148e7c2361e6ecc1 /opt/synthea/synthea.jar" | sha256sum -c
- uses: astral-sh/setup-uv@v5
- run: uv sync --locked
- run: uv run ruff check
- run: uv run ruff format --check
- run: uv run lint-imports
- run: uv run pytest -q -rs -m "not webapp" # the pages run in the web job
- run: uv run pytest -q -rs
web:
runs-on: ubuntu-latest
services:
sqlserver: # the hospital's test source (synthetic.site): ArchivosUni and ResultadosSubrogados
image: mcr.microsoft.com/mssql/server:2022-CU20-ubuntu-22.04
env:
ACCEPT_EULA: "Y"
MSSQL_PID: Developer
MSSQL_SA_PASSWORD: Test-only-Site-1
options: >-
--health-cmd "/opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P Test-only-Site-1 -Q 'select 1' -b"
--health-interval 5s --health-timeout 10s --health-retries 30
env:
SITE_SQL_SERVER: mssql+pymssql://sa:Test-only-Site-1@sqlserver:1433
SYNTHEA_JAR: /opt/synthea/synthea.jar
steps:
- uses: actions/checkout@v4
- run: git submodule update --init
@@ -98,14 +43,9 @@ jobs:
run: npx ng build
- working-directory: WebApp
run: npx ng test --watch=false
- name: Every page loads from the API (Playwright over a loaded platform)
- name: TEA pages over the synthetic hospital (Playwright)
run: |
echo 'Acquire::Retries "5";' > /etc/apt/apt.conf.d/80-retries # mirrors drop connections
apt-get update --error-on=any
apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-spa ghostscript \
default-jre-headless
mkdir -p /opt/synthea
curl -sLo /opt/synthea/synthea.jar https://github.com/synthetichealth/synthea/releases/download/v4.0.0/synthea-with-dependencies.jar
echo "ed43c20ad40ba5c3bc724503a5af032715fe3c491620b766148e7c2361e6ecc1 /opt/synthea/synthea.jar" | sha256sum -c
apt-get update
apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-spa ghostscript
(cd WebApp && npx playwright install --with-deps chromium)
uv run pytest -q -rs -m webapp
+16 -32
View File
@@ -1,16 +1,10 @@
"""CaCu clinical parameters: the one place they are set. dbt reads them as vars, the models
import them. Codes are the platform's (core.schema)."""
# Biopsy grades that count as CIN2+ (the outcome) and as invasive cancer.
CIN2_PLUS = ["HSIL", "CIS", "carcinoma"]
CANCER = ["carcinoma"]
CASE = ["CIS", "carcinoma"] # a biopsy this grade makes her a case: she has cancer
CASE = ["CIS", "carcinoma"]
# The follow-up list: patients with a cytology sampled within the window before the cut-off.
FOLLOW_UP_WINDOWS = [1, 3, 6, 12] # months
FOLLOW_UP_WINDOWS = [1, 3, 6, 12]
FOLLOW_UP_WINDOW = 3
# Index cytology in the six KPNC categories, least to most severe.
KPNC = {
"NILM": ["NILM"],
"ASC-US": ["ASC-US"],
@@ -19,34 +13,28 @@ KPNC = {
"AGC": ["AGC"],
"HSIL+": ["HSIL", "CIS", "adenocarcinoma"],
}
# The three categories used after colposcopy and after treatment.
KPNC_3 = {
"NILM": ["NILM"],
"ASC-US/LSIL": ["ASC-US", "LSIL"],
"High Grade": ["ASC-H", "AGC", "HSIL", "CIS", "adenocarcinoma"],
}
# Results that show a patient free of CIN2+ at a visit: a negative co-test (both within
# INDEX_SAMPLE_DAYS of each other), or a biopsy below the outcome grades.
KNOWN_NEGATIVE = {"bethesda": ["NILM", "ASC-US"], "hpv": ["negative"]}
INDEX_SAMPLE_DAYS = 30 # results this many days after the index sample still describe it
PREVALENT_WINDOW_DAYS = 6 * 365.25 / 12 # an outcome this soon was there at the index
INDEX_SAMPLE_DAYS = 30
PREVALENT_WINDOW_DAYS = 6 * 365.25 / 12
DAYS_PER_YEAR = 365.25
# Recruitment windows (start inclusive, end exclusive).
RECRUITMENT = ("2018-01-01", "2027-01-01")
POST_TREATMENT_RECRUITMENT = ("2024-01-01", "2027-01-01")
POST_TREATMENT_INDEX_AFTER_DAYS = 90 # the index cytology comes this long after treatment
POST_TREATMENT_LOOKBACK_DAYS = 365 # a biopsy result this long before treatment is required
POST_COLPOSCOPY_VISIT = 1 # index: the k-th surveillance cytology after the colposcopy result
REFERRAL_LOOKBACK_DAYS = 365 # results this long before colposcopy are why she was referred
POST_TREATMENT_INDEX_AFTER_DAYS = 90
POST_TREATMENT_LOOKBACK_DAYS = 365
POST_COLPOSCOPY_VISIT = 1
REFERRAL_LOOKBACK_DAYS = 365
HYSTERECTOMY_ICD10 = ["Z907"]
# Inferred procedures, from clinical notes (ICD-10 without the dot).
# Specialties are the platform's codes; each site's pipeline maps its own names to them.
DIAGNOSIS_SPECIALTIES = ["colposcopy", "oncology_surgery"]
COLPOSCOPY_SPECIALTIES = ["colposcopy"]
SAMPLE_TO_DIAGNOSIS_DAYS = 120 # a diagnosis note this soon after a sample assesses it
SAMPLE_TO_DIAGNOSIS_DAYS = 120
DIAGNOSIS_ICD10 = [
"Z014", "Z124", "B977", "R876", "N87", "N870", "N871", "N872", "N879",
"D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539",
@@ -56,25 +44,21 @@ TREATMENT_ICD10 = ["D06", "D060", "D061", "D067", "D069"]
COLPOSCOPY_ICD10 = ["R876", "N87", "N870", "N871", "N872", "N879", "B977"]
COLPOSCOPY_REASONS = ["ACUDE A COLPOSCOPIA", "COLPOSCOPIA"]
COLPOSCOPY_DIAGNOSES = ["VIRUS DEL PAPILOMA HUMANO"]
SURVEILLANCE_SPECIALTIES = ["family_medicine", "colposcopy"]
# Measures (core.measures): the horizons of the screening route, in days; an interval
# that hasn't ended after its horizon counts as not ended.
HORIZONS = {
"sample_to_report": 60, "sample_to_treatment": 180, "diagnosis_to_treatment": 60,
"sample_to_colposcopy": 60, "sample_to_biopsy": 60, "result_to_colposcopy": 60,
"colposcopy_to_biopsy": 60, "biopsy_to_diagnosis": 60,
} # fmt: skip
ABNORMAL = ["ASC-US", "ASC-H", "LSIL", "HSIL", "CIS"] # IND1
HIGH_GRADE = ["ASC-H", "HSIL", "CIS"] # cytology that should be confirmed by biopsy
DETECTION = ["HSIL", "CIS", "carcinoma"] # biopsy grades counted as detected (EU13)
BIOPSY_SEVERITY = ["normal", "LSIL", "HSIL", "CIS", "carcinoma"] # least to most severe
AGE_GROUPS = [(25, 34), (35, 44), (45, 54), (55, 64)] # plus "<25" and "65+"
RISK_BAND_MODEL = "cacu.cin2_pim" # whose risk at the index visit is banded (surveillance)
RISK_BANDS = [("low", 0.04), ("intermediate", 0.25), ("high", None)] # below each cut
ABNORMAL = ["ASC-US", "ASC-H", "LSIL", "HSIL", "CIS"]
HIGH_GRADE = ["ASC-H", "HSIL", "CIS"]
DETECTION = ["HSIL", "CIS", "carcinoma"]
BIOPSY_SEVERITY = ["normal", "LSIL", "HSIL", "CIS", "carcinoma"]
AGE_GROUPS = [(25, 34), (35, 44), (45, 54), (55, 64)]
RISK_BAND_MODEL = "cacu.cin2_pim"
RISK_BANDS = [("low", 0.04), ("intermediate", 0.25), ("high", None)]
def dbt_vars() -> dict:
"""What dbt reads (`var('cacu')`)."""
return {k.lower(): v for k, v in globals().items() if k.isupper()}
+1 -13
View File
@@ -1,37 +1,27 @@
"""CaCu's follow-up list (pure): who is on it at a cut-off day, her status then, and the order
it is read in. The list holds every patient with a cytology sampled within the window
(`cacu.FOLLOW_UP_WINDOWS` months) up to the cut-off."""
from collections.abc import Iterable
from datetime import date
from core import cacu
from core.cacu.measures import follow_up_status
# Risk outcomes the list can be ordered by: a model counts for the outcome its name starts.
OUTCOMES = {"cin2": "cacu.cin2", "cancer": "cacu.cancer"}
SORTS = ("-recent", *(f"-risk-{o}" for o in OUTCOMES))
DEFAULT_HORIZON = 5.0
WINDOWS = cacu.FOLLOW_UP_WINDOWS
STATUS_SYSTEM = "cacu-follow-up-status"
PROCEDURES = ("colposcopy", "treatment")
REPORT_FACTS = {"cervical_cytology": "diagnosis_days"} # days from the sample to its diagnosis
REPORT_FACTS = {"cervical_cytology": "diagnosis_days"}
def status(row: dict, cutoff: date) -> str:
"""Her follow-up status by the end of the cut-off day."""
return follow_up_status(row, cutoff, through=True)
def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
"""The rows (whoever had a cytology sampled in the window, most recent first), each with
her status."""
return [{**r, "status": status(r, cutoff)} for r in rows]
def current_risk(risks: Iterable[dict], outcome: str, horizon: float) -> float | None:
"""Her current risk of an outcome at a horizon (years): from the latest index date any
of the outcome's models scored her at; the highest when several did."""
prefix = OUTCOMES[outcome]
mine = [r for r in risks if r["model"].startswith(prefix) and r["horizon_years"] == horizon]
if not mine:
@@ -42,8 +32,6 @@ def current_risk(risks: Iterable[dict], outcome: str, horizon: float) -> float |
def ordered(rows: list[dict], sort: str, risks: dict[str, list[dict]],
horizon: float) -> list[dict]: # fmt: skip
"""The list in reading order. `rows` come most recent first; by risk, highest first,
unscored patients last, ties kept most recent first."""
if sort == "-recent":
return rows
outcome = sort.removeprefix("-risk-")
+1 -10
View File
@@ -1,5 +1,3 @@
"""CaCu's measures (`core.measures` evaluates them) and the follow-up status they stratify by."""
from datetime import date
from core import cacu
@@ -18,9 +16,6 @@ from core.measures import (
def follow_up_status(row: dict, at: date, through: bool = False) -> str:
"""Where the patient was in her follow-up just before `at` (`through`: by the end of
`at`), from the first day of each step (`gold.cacu_follow_up`). A case already has
cancer; what follows her is survival."""
def by(first: str) -> bool:
day = as_day(row.get(first))
@@ -34,17 +29,14 @@ def follow_up_status(row: dict, at: date, through: bool = False) -> str:
def valid(row: dict) -> bool:
"""A cytology with a result, reported, of satisfactory (or unknown) adequacy."""
return row["result_date"] is not None and row.get("adequacy") != "unsatisfactory"
def latest(row: dict) -> tuple:
"""A patient's latest valid sample ranks highest."""
return valid(row), as_day(row["sample_date"]), row["sample_id"]
def latest_most_severe_biopsy(row: dict) -> tuple:
"""Her latest valid sample, then its most severe reported biopsy, the latest first."""
reported = row.get("biopsy_report_date") is not None
return (*latest(row), reported, row.get("severity") or 0,
desc(as_day(row.get("biopsy_report_date"))), desc(row.get("biopsy_id"))) # fmt: skip
@@ -55,7 +47,6 @@ def result(row: dict) -> str:
def histology(row: dict) -> str:
"""The chosen biopsy's histology (NO_BIOPSY without one reported)."""
if not valid(row):
return NO_DATA
if row.get("biopsy_report_date") is None:
@@ -64,7 +55,7 @@ def histology(row: dict) -> str:
H = cacu.HORIZONS
NO_HISTORY = lambda row: row["history"] == 0 # noqa: E731 -- no cervical cancer note before
NO_HISTORY = lambda row: row["history"] == 0 # noqa: E731
AGE = ("age_group", lambda row, p: age_group(row.get("birth_date"), p.start, cacu.AGE_GROUPS))
STATUS = ("follow_up_status", lambda row, p: follow_up_status(row, p.start))
RESULT = ("result", lambda row, p: row["result"])
+4 -21
View File
@@ -1,26 +1,14 @@
"""CaMa clinical parameters: the one place they are set. dbt reads them as vars, the measures
and models import them. Codes are the platform's (core.catalog)."""
# BI-RADS, least to most severe: an incomplete study (0) asks for more and weighs more than a
# benign one; a 4 without subcategory weighs less than 4A.
BIRADS_SEVERITY = ["1", "2", "3", "0", "4", "4A", "4B", "4C", "5", "6"]
BIRADS_4_TO_6 = ["4", "4A", "4B", "4C", "5", "6"]
SUSPICIOUS = ["4", "4A", "4B", "4C", "5"] # should be confirmed by biopsy (not 6: already is)
SUSPICIOUS = ["4", "4A", "4B", "4C", "5"]
# Biopsy grades, least to most severe.
BIOPSY_SEVERITY = ["benign", "in_situ", "invasive"]
CANCER = ["in_situ", "invasive"] # detected (detection rate)
CANCER = ["in_situ", "invasive"]
INVASIVE = ["invasive"]
# Survival: indexed at the first biopsy reported with one of these, within the recruitment
# window (start inclusive, end exclusive).
SURVIVAL_GRADES = ["invasive"]
RECRUITMENT = ("2018-01-01", "2027-01-01")
# Inferred from clinical notes (ICD-10 without the dot; specialties are the platform's codes):
# - diagnosis: a note that resolves a mammogram, with a diagnosis ICD-10 by a diagnosing
# specialty;
# - history: a breast cancer note, whoever wrote it.
DIAGNOSIS_SPECIALTIES = ["oncology_surgery"]
HISTORY_ICD10 = [
"D05", "D050", "D051", "D057", "D059",
@@ -32,17 +20,12 @@ DIAGNOSIS_ICD10 = [
*HISTORY_ICD10,
] # fmt: skip
# Measures (core.measures): the horizons, in days; an interval that hasn't ended after its
# horizon counts as not ended. A diagnosis this soon after the mammogram resolves it.
HORIZONS = {"sample_to_report": 60, "to_diagnosis": 180}
AGE_GROUPS = [(40, 49), (50, 59), (60, 69)] # plus "<40" and "70+"
AGE_GROUPS = [(40, 49), (50, 59), (60, 69)]
# The follow-up list: patients whose latest mammogram, taken within the window before the
# cut-off, is BI-RADS 4 to 6.
FOLLOW_UP_WINDOWS = [1, 3, 6, 12] # months
FOLLOW_UP_WINDOWS = [1, 3, 6, 12]
FOLLOW_UP_WINDOW = 3
def dbt_vars() -> dict:
"""What dbt reads (`var('cama')`)."""
return {k.lower(): v for k, v in globals().items() if k.isupper()}
+3 -18
View File
@@ -1,15 +1,3 @@
"""CaMa's follow-up list (pure): the patients whose latest mammogram reported by the cut-off
is BI-RADS 4 to 6 and was taken within the window, with where her biopsy stands and how soon
she should be seen.
Status, from the biopsies that mammogram led to, reported by the cut-off:
- cancer: one found cancer (in situ or invasive);
- pending_biopsy: none reported;
- biopsy_no_result: the latest has no grade;
- benign_biopsy: otherwise.
Priority: high for a cancer, or a pending biopsy after a BI-RADS 5 or 6; medium for any other
pending biopsy or one without result; low otherwise."""
from datetime import date
from core import cama
@@ -19,9 +7,9 @@ WINDOWS = cama.FOLLOW_UP_WINDOWS
SORTS = ("-recent",)
DEFAULT_HORIZON = None
STATUS_SYSTEM = "cama-follow-up-status"
PROCEDURES = ("treatment",) # by kind (persistance.fhir: CaMa's procedure read)
REPORT_FACTS = {"mammography": "diagnosis_days"} # days from the mammogram to its diagnosis
URGENT = ["5", "6"] # BI-RADS whose pending biopsy is high priority
PROCEDURES = ("treatment",)
REPORT_FACTS = {"mammography": "diagnosis_days"}
URGENT = ["5", "6"]
def _ranked(row: dict) -> tuple:
@@ -29,8 +17,6 @@ def _ranked(row: dict) -> tuple:
def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
"""From each reported mammogram and the biopsies it led to (`gold.cama_mammogram_biopsies`),
who is on the list, most recent mammogram first."""
latest: dict[str, dict] = {}
biopsies: dict[str, list[dict]] = {}
for row in rows:
@@ -69,7 +55,6 @@ def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
def status(row: dict, cutoff: date) -> None:
"""A patient's status exists only on the list."""
return None
+1 -12
View File
@@ -1,10 +1,3 @@
"""CaMa's measures (`core.measures` evaluates them), over the gold rows of
`persistance.measures`: mammograms, biopsies, and each mammogram with the biopsies it led to.
A mammogram's report, a biopsy's report and a diagnosis note can become known after the
mammogram itself; asked before then, a row has them empty (`facts`), so the mammogram counts
with no data instead of being left out."""
from core import cama
from core.measures import (
NO_BIOPSY,
@@ -25,17 +18,14 @@ BIOPSY = {"biopsy_known_at": ("biopsy_report_date", "histology", "histology_rank
def reported(row: dict) -> bool:
"""A mammogram with a reported BI-RADS."""
return row["birads"] is not None and row["report_date"] is not None
def most_severe(row: dict) -> tuple:
"""Her most severe reported mammogram ranks highest; on a tie, the latest."""
return reported(row), row["birads_rank"] or 0, as_day(row["exam_date"])
def then_its_most_severe_biopsy(row: dict) -> tuple:
"""Her most severe mammogram, then its most severe reported biopsy, the latest first."""
counted = row["biopsy_report_date"] is not None
return (*most_severe(row), counted, desc(row["histology_rank"]),
desc(as_day(row["biopsy_report_date"])), desc(row["biopsy_id"])) # fmt: skip
@@ -46,7 +36,6 @@ def birads(row: dict) -> str:
def biopsy_histology(row: dict) -> str:
"""The chosen biopsy's grade (NO_BIOPSY when her mammogram led to none reported)."""
if row["biopsy_report_date"] is None:
return NO_BIOPSY
return row["histology"] or NO_DATA
@@ -56,7 +45,7 @@ def four_to_six(row: dict) -> bool:
return reported(row) and row["birads"] in cama.BIRADS_4_TO_6
NO_HISTORY = lambda row: row["history"] == 0 # noqa: E731 -- no breast cancer note before
NO_HISTORY = lambda row: row["history"] == 0 # noqa: E731
BIRADS = ("birads", lambda row, p: row["birads"])
MEASURES = {m.id: m for m in [
+6 -25
View File
@@ -1,12 +1,3 @@
"""The platform's clinical catalog: every study, the events it is made of, its fields, and the
code systems their values come from. It is data (the YAML files beside this module) and
changes only by a reviewed commit; nothing ships that it doesn't name.
Everything that validates, stores or serves a clinical value reads it: the pydantic model of
each study (what a pipeline's target checks rows against), the long silver tables and their
wide views (dbt), and the FHIR conformance resources the API serves.
"""
from datetime import date
from functools import cache
from pathlib import Path
@@ -17,8 +8,6 @@ from pydantic import BaseModel, ConfigDict, Field, create_model, model_validator
HERE = Path(__file__).parent
EventClass = Literal["order", "encounter", "sample", "report", "part"]
# `file`: a document or signal kept whole (an EEG); silver holds its content hash, the
# platform keeps the content once (persistance.files).
ValueType = Literal["code", "boolean", "number", "date", "text", "file"]
@@ -26,12 +15,12 @@ class System(BaseModel):
model_config = ConfigDict(extra="forbid")
url: str
title: str
external: bool = False # a standard system we name but don't publish
external: bool = False
class Event(BaseModel):
model_config = ConfigDict(extra="forbid")
date: str # the field that dates it
date: str
parent: EventClass | None = None
@@ -41,7 +30,7 @@ class FieldDef(BaseModel):
event: EventClass
title: str
system: str | None = None
codes: dict[str, str] = {} # allowed code -> display; empty: any code of `system`
codes: dict[str, str] = {}
pattern: str | None = None
unit: str | None = None
required: bool = False
@@ -58,7 +47,7 @@ class FieldDef(BaseModel):
class Study(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str
key: list[str] # fields that, with the person, identify one study instance
key: list[str]
events: dict[EventClass, Event]
fields: dict[str, FieldDef]
@@ -89,7 +78,6 @@ def systems() -> dict[str, System]:
@cache
def files() -> dict[str, list[str]]:
"""Each catalog file (a domain, or `common` to all) and the studies it defines."""
return {
path.stem: list(_load(path.stem))
for path in sorted(HERE.glob("*.yaml"))
@@ -98,13 +86,11 @@ def files() -> dict[str, list[str]]:
def of_domain(domain: str) -> list[str]:
"""The studies a domain serves: its own and the common ones."""
return [*files().get(domain, []), *files().get("common", [])]
@cache
def studies() -> dict[str, Study]:
"""Every study of every catalog file, by name (names are unique across files)."""
found: dict[str, Study] = {}
for path in sorted(HERE.glob("*.yaml")):
if path.stem == "systems":
@@ -121,8 +107,6 @@ def studies() -> dict[str, Study]:
class Record(BaseModel):
"""One row of a study, as a pipeline's target receives it."""
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
key: ClassVar[tuple[str, ...]] = ()
study: ClassVar[str] = ""
@@ -134,7 +118,7 @@ _TYPES: dict[str, Any] = {
"date": date,
"text": str,
"file": str,
} # fmt: skip (a file field holds its content hash)
} # fmt: skip
def _annotation(f: FieldDef) -> Any:
@@ -149,9 +133,8 @@ def _annotation(f: FieldDef) -> Any:
@cache
def model(study: str) -> type[Record]:
"""The pydantic model a row of this study is checked against."""
spec = studies()[study]
fields = { # titled as the catalog names them (forms and review show the titles)
fields = {
name: (_annotation(f), Field(... if f.required else None, title=f.title))
for name, f in spec.fields.items()
}
@@ -162,14 +145,12 @@ def model(study: str) -> type[Record]:
def value_column(f: FieldDef) -> str:
"""The typed column of the long observation table a field's value is stored in."""
return {"boolean": "value_bool", "number": "value_num", "date": "value_date"}.get(
f.type, "value_text"
)
def dbt_vars() -> dict:
"""What dbt reads (`var('catalog')`): each study's key, events and typed fields."""
return {
name: {
"key": s.key,
-1
View File
@@ -1,4 +1,3 @@
# Cervical cancer screening.
cervical_cytology:
title: Citología cervical
key: [sample_date]
-1
View File
@@ -1,4 +1,3 @@
# Breast cancer screening.
mammography:
title: Mastografía
key: [exam_date]
-1
View File
@@ -1,4 +1,3 @@
# Studies every domain shares.
clinical_note:
title: Nota médica
key: [note_date, specialty]
-2
View File
@@ -1,5 +1,3 @@
# The code systems the platform's fields take their codes from. External systems are named by
# their canonical URI; only the codes a field allows are listed with the field.
bethesda:
url: https://isssteleon.org/fhir/CodeSystem/bethesda
title: Sistema Bethesda (citología cervical)
-3
View File
@@ -1,5 +1,3 @@
# Autism (TEA) screening: M-CHAT, ADOS-2, EEG; the neurology note that confirms the diagnosis
# is the common clinical note (specialty pediatric_neurology).
mchat:
title: M-CHAT-R/F
key: [screening_date]
@@ -22,7 +20,6 @@ ados2:
title: Módulo
system: ados2-module
codes: {toddler: Módulo para niños pequeños, module_1: Módulo 1, module_2: Módulo 2, module_3: Módulo 3}
# The 22 items by what they observe (the same meaning in every module), each 0 to 3.
vocalization_directed: {type: number, event: encounter, title: Frecuencia de la vocalización espontánea dirigida a otros}
pointing: {type: number, event: encounter, title: Señalar}
gestures: {type: number, event: encounter, title: Gestos}
-16
View File
@@ -1,12 +1,3 @@
"""A site's codes in platform terms: FHIR ConceptMaps (R4B), as data a site's configuration
holds, never code. A new laboratory that writes "Negativo para lesión" for NILM, or "F" for
female, is one more element in its ConceptMap.
Each group maps the site's codes (`source`, any URI the site uses) onto one system the
platform's fields take their codes from (`target`): a catalog system (core.catalog), FHIR's
administrative gender (identity `sex`), or the platform's yes/no system (boolean fields).
"""
from collections.abc import Iterable
from fhir.resources.R4B.conceptmap import ConceptMap
@@ -20,8 +11,6 @@ _BOOLEAN_CODES = {"true", "false"}
def systems(field: str) -> dict[str, set[str] | None]:
"""The systems a field of this name takes codes from, each with its allowed codes
(None: any code of the system)."""
found: dict[str, set[str] | None] = {}
if field == "sex":
found[GENDER] = _GENDER_CODES
@@ -40,8 +29,6 @@ def systems(field: str) -> dict[str, set[str] | None]:
def problems(cm: ConceptMap) -> list[str]:
"""Why this map can't be used: a group onto a system no field takes, or a target code
its field doesn't allow."""
allowed: dict[str, set[str] | None] = {GENDER: _GENDER_CODES, BOOLEAN: _BOOLEAN_CODES}
for study in catalog.studies().values():
for name in study.fields:
@@ -60,8 +47,6 @@ def problems(cm: ConceptMap) -> list[str]:
def table(maps: Iterable[ConceptMap], field: str) -> dict[str, str]:
"""A field's translations, site code (case ignored) -> platform code, from the groups
of these maps that target a system the field takes."""
targets = systems(field)
found = {}
for cm in maps:
@@ -76,7 +61,6 @@ def table(maps: Iterable[ConceptMap], field: str) -> dict[str, str]:
def translate(maps: Iterable[ConceptMap], source: str, code: str) -> tuple[str, str] | None:
"""A sender's coding (system, code) as (platform system, code), when a map knows it."""
for cm in maps:
for group in cm.group or []:
if group.source != source:
-6
View File
@@ -1,7 +1,3 @@
"""The platform's domains. A domain is a package `core.<domain>` holding its parameters
(`__init__`: what dbt reads through `dbt_vars()`), and when it has them, its measures
(`measures.MEASURES`) and its follow-up list (`follow_up`)."""
import importlib
from enum import StrEnum
from types import ModuleType
@@ -14,7 +10,6 @@ class Domain(StrEnum):
def part(domain: Domain, name: str = "") -> ModuleType | None:
"""The domain's module `name` (its package without one), or None while it has none."""
path = f"core.{domain.value}" + (f".{name}" if name else "")
try:
return importlib.import_module(path)
@@ -25,6 +20,5 @@ def part(domain: Domain, name: str = "") -> ModuleType | None:
def measures(domain: Domain) -> dict:
"""The domain's measures by id (none for a domain without them yet)."""
found = part(domain, "measures")
return found.MEASURES if found else {}
+102 -97
View File
@@ -1,11 +1,3 @@
"""Platform rows as FHIR R4B resources (pure, no IO), and the conformance resources that
declare what ours are: the local code systems, our extensions and our search parameters.
Every mapper builds a `fhir.resources.R4B` model, so a resource that breaks FHIR's structure
fails here, before it is served. Clinical resources other than Patient are found by search
only; their ids are stable (a UUID of their natural key), not addresses.
"""
import uuid
from collections.abc import Iterable
from datetime import UTC, date, datetime
@@ -23,7 +15,8 @@ from fhir.resources.R4B.riskassessment import RiskAssessment
from fhir.resources.R4B.searchparameter import SearchParameter
from fhir.resources.R4B.structuredefinition import StructureDefinition
from core import catalog, models
from core import catalog, models, tea
from core.tea import ados2_items
FHIR_VERSION = "4.3.0"
BASE = "https://isssteleon.org/fhir"
@@ -34,7 +27,6 @@ UCUM = "http://unitsofmeasure.org"
_IDS = uuid.uuid5(uuid.NAMESPACE_URL, BASE)
# Local code systems: code -> display (Spanish, as the screens show them).
CODE_SYSTEMS: dict[str, tuple[str, dict[str, str]]] = {
"cacu-procedure": ("Procedimientos de CaCu", {
"colposcopy": "Colposcopia", "treatment": "Tratamiento",
@@ -47,33 +39,63 @@ CODE_SYSTEMS: dict[str, tuple[str, dict[str, str]]] = {
"cancer": "Diagnóstico confirmado", "pending_biopsy": "Pendiente de biopsia",
"biopsy_no_result": "Biopsia sin resultado", "benign_biopsy": "Biopsia benigna",
}),
"tea-follow-up-status": ("Estatus de seguimiento", {
"mchat_only": "Solo M-CHAT", "psychology": "Hasta evaluación psicológica",
"neuropediatrics": "Hasta evaluación neuropediátrica", "eeg": "Con EEG",
}),
"tea-case": ("Estado del caso", {
"confirmed": "Diagnóstico confirmado", "in_process": "En proceso",
"not_confirmed": "Sin TEA",
}),
"tea-eeg-status": ("Estatus de EEG", {
"normal": "Normal", "abnormal": "Anormal", "no_valid_eeg": "Sin EEG válido",
"tea-eeg-result": ("Resultado del EEG", {
"abnormal": "Anormal", "normal": "Normal",
"no_valid_eeg": "Sin EEG válido", "not_scored": "Sin analizar",
}),
# an EEG metric outside its age band: `<metric>:above` or `<metric>:below`
"tea-eeg-alteration": ("Alteración del EEG", {}),
"follow-up-priority": ("Prioridad de seguimiento", {
"high": "Alta", "medium": "Media", "low": "Baja",
}),
"measure-stratifier": ("Estratos de indicadores", {
"category": "Categoría", "age_group": "Grupo de edad",
"follow_up_status": "Estatus de seguimiento", "result": "Citología de alto grado",
"birads": "BI-RADS de la mastografía",
"birads": "BI-RADS de la mastografía", "alteration": "Alteración del EEG",
"sex": "Sexo", "age_sex": "Grupo de edad y sexo",
}),
"risk-model": ("Modelos de riesgo", {}), # open: a model's name is its code
"risk-model": ("Modelos de riesgo", {}),
} # fmt: skip
for _system, _title, _codes in (
("tea-eeg-metric", "Métricas del EEG", tea.EEG_METRICS),
("tea-eeg-zone", "Zonas del EEG", (
"frontal_left", "frontal_right", "frontal_midline", "central", "parietal",
"temporal_left", "temporal_right", "occipital", "posterior", "global",
)),
("eeg-electrode-10-20", "Electrodos del EEG", (
"Fp1", "Fp2", "F7", "F3", "Fz", "F4", "F8", "T3", "C3", "Cz", "C4", "T4", "T5",
"P3", "Pz", "P4", "T6", "O1", "O2", "A1", "A2", "Oz", "Fpz", "EKG", "LOC", "ROC",
)),
("tea-eeg-check", "Controles de calidad del EEG", (
"file", "dead-channel", "frozen", "saturated", "inf-values", "own-gaps", "bridge",
"amplitude", "does-not-correlate", "intermittent-contact", "intermittent-bursts",
"aux-amplitude", "clean-windows", "internal-coverage", "bad-scalp-triage",
"usable-scalp", "triage-level", "line-noise",
)),
("tea-eeg-quality", "Calidad del EEG", ("good", "bad", "not_analyzed")),
("tea-eeg-validity", "Validez del EEG", ("valid", "not_valid")),
("tea-association", "Asociaciones del EEG con el ADOS-2", ()),
("tea-ados2-classification", "Clasificación del ADOS-2", (
*(code for code, _ in tea.ADOS2_CLASSIFICATION),
"mild_to_moderate_concern", "severe_concern",
)),
): # fmt: skip
CODE_SYSTEMS[_system] = (_title, {code: code for code in _codes})
CODE_SYSTEMS["ados2-domain"] = ("Dominios del ADOS-2", dict(ados2_items.DOMAINS))
CODE_SYSTEMS["ados2-subdomain"] = ("Subdominios del ADOS-2", dict(ados2_items.SUBDOMAINS))
for _module, _items in ados2_items.ITEMS.items():
CODE_SYSTEMS[f"ados2-item-{_module}"] = (
f"Ítems del ADOS-2: {catalog.studies()['ados2'].fields['module'].codes[_module]}",
{item.code: item.title for item in _items},
)
def _catalog_systems() -> dict[str, tuple[str, dict[str, str]]]:
"""The catalog's own code systems, with every code some field allows."""
found: dict[str, tuple[str, dict[str, str]]] = {}
for name, system in catalog.systems().items():
if not system.external:
@@ -85,14 +107,12 @@ def _catalog_systems() -> dict[str, tuple[str, dict[str, str]]]:
CODE_SYSTEMS |= _catalog_systems()
CODE_SYSTEMS["cama-procedure"] = ("Procedimientos de CaMa", CODE_SYSTEMS["breast-treatment"][1])
# What the catalog names: its studies, and every field as `<study>.<field>`.
CODE_SYSTEMS["study"] = ("Estudios", {n: s.title for n, s in catalog.studies().items()})
CODE_SYSTEMS["catalog-field"] = ("Campos de los estudios", {
f"{n}.{f}": d.title for n, s in catalog.studies().items() for f, d in s.fields.items()
}) # fmt: skip
# Our extensions: name -> (value type, the elements they extend).
EXTENSIONS: dict[str, tuple[str, list[str]]] = {
EXTENSIONS: dict[str, tuple[str | None, list[str]]] = {
"ic-bajo": ("decimal", ["MeasureReport.group.measureScore", "RiskAssessment.prediction"]),
"ic-alto": ("decimal", ["MeasureReport.group.measureScore", "RiskAssessment.prediction"]),
"q1": ("decimal", ["MeasureReport.group.measureScore"]),
@@ -101,23 +121,40 @@ EXTENSIONS: dict[str, tuple[str, list[str]]] = {
"period-type": ("code", ["Measure"]),
"follow-up-status": ("Coding", ["Patient"]),
"follow-up-priority": ("Coding", ["Patient"]),
"tea-step": ("code", ["Patient"]),
"tea-age-group": ("code", ["Patient"]),
"tea-case": ("code", ["Patient"]),
"tea-eeg-result": ("code", ["Patient"]),
"tea-mchat": ("decimal", ["Patient"]),
"tea-css": ("integer", ["Patient"]),
"tea-alterations": ("integer", ["Patient"]),
"report-date": ("date", ["DiagnosticReport"]),
"days-to-diagnosis": ("integer", ["DiagnosticReport"]),
# a clinical scenario of the model's report the person falls in (its curves)
"eeg-duration-min": ("decimal", ["DiagnosticReport"]),
"eeg-age-months": ("decimal", ["DiagnosticReport"]),
"eeg-channels": ("integer", ["DiagnosticReport"]),
"eeg-check-decisive": ("boolean", ["Observation"]),
"eeg-z": ("decimal", ["Observation", "Observation.component"]),
"eeg-outside": ("integer", ["Observation", "Observation.component"]),
"curve-centiles": (None, ["Observation"]),
"association-model-version": ("string", ["RiskAssessment"]),
"association-cohort": ("integer", ["RiskAssessment"]),
"association-level": ("string", ["RiskAssessment"]),
"association-reliable": ("boolean", ["RiskAssessment.prediction"]),
"association-headline": ("boolean", ["RiskAssessment.prediction"]),
"association-odds-ratio": ("decimal", ["RiskAssessment.prediction"]),
"association-ci-low": ("decimal", ["RiskAssessment.prediction"]),
"association-ci-high": ("decimal", ["RiskAssessment.prediction"]),
"association-q": ("decimal", ["RiskAssessment.prediction"]),
"association-reference-probability": ("decimal", ["RiskAssessment.prediction"]),
"association-same-direction": ("boolean", ["RiskAssessment.prediction"]),
"ados2-domain": ("Coding", ["Observation.component"]),
"ados2-subdomain": ("Coding", ["Observation.component"]),
"escenario-clinico": ("string", ["RiskAssessment"]),
# a child on TEA's list: her age group, case, EEG and scores
"tea-age-group": ("string", ["Patient"]),
"tea-case": ("Coding", ["Patient"]),
"tea-eeg-status": ("Coding", ["Patient"]),
"tea-eeg-alteration": ("Coding", ["Patient"]),
"tea-last-eeg": ("date", ["Patient"]),
"mchat-score": ("integer", ["Patient"]),
"ados2-css": ("integer", ["Patient"]),
} # fmt: skip
def _name(code: str) -> str:
"""A conformance resource's computable name (CamelCase)."""
return "".join(part.capitalize() for part in code.replace("_", "-").split("-"))
@@ -131,12 +168,11 @@ def _day(value) -> str | None:
return value.isoformat()[:10] if isinstance(value, date) else str(value)[:10]
def _instant(value) -> str | None:
"""A stored moment as an instant; one stored without an offset is UTC."""
def _moment(value) -> datetime | None:
if value is None:
return None
found = value if isinstance(value, datetime) else datetime.fromisoformat(str(value))
return (found if found.tzinfo else found.replace(tzinfo=UTC)).isoformat()
return found if found.tzinfo else found.replace(tzinfo=UTC)
def coding(system: str, code: str) -> dict:
@@ -157,12 +193,7 @@ def subject(person_id: str) -> dict:
return {"reference": f"Patient/{person_id}"}
# --- clinical resources ----------------------------------------------------------------
def patient(row: dict, status_system: str | None = None) -> Patient:
"""A person: what her records agree on, her names and identifiers, the ids she
replaced; on a follow-up list, her status there (`status_system`) and priority."""
found: dict = {"resourceType": "Patient", "id": row["person_id"]}
if row.get("sex"):
found["gender"] = row["sex"]
@@ -176,9 +207,18 @@ def patient(row: dict, status_system: str | None = None) -> Patient:
if row.get("priority"):
priority = coding("follow-up-priority", row["priority"])
found["extension"].append(ext("follow-up-priority", "Coding", priority))
found.setdefault("extension", []).extend(_tea_listed(row))
if not found["extension"]:
del found["extension"]
if status_system == "tea-follow-up-status":
for field, name, kind in (
("step", "tea-step", "code"),
("age_group", "tea-age-group", "code"),
("case", "tea-case", "code"),
("eeg_result", "tea-eeg-result", "code"),
("mchat_score", "tea-mchat", "decimal"),
("css", "tea-css", "integer"),
("alterations", "tea-alterations", "integer"),
):
if row.get(field) is not None:
found.setdefault("extension", []).append(ext(name, kind, row[field]))
if row.get("names"):
found["name"] = [{"text": n} for n in row["names"]]
if row.get("identifiers"):
@@ -189,27 +229,7 @@ def patient(row: dict, status_system: str | None = None) -> Patient:
return Patient.model_validate(found)
def _tea_listed(row: dict) -> list[dict]:
"""What TEA's list shows of a child, when she is on it (core.tea.follow_up)."""
found = []
if row.get("age_group"):
found.append(ext("tea-age-group", "string", row["age_group"]))
for key, system in (("case", "tea-case"), ("eeg_status", "tea-eeg-status")):
if row.get(key):
found.append(ext(system, "Coding", coding(system, row[key])))
for altered in row.get("alterations") or []:
found.append(ext("tea-eeg-alteration", "Coding", coding("tea-eeg-alteration", altered)))
if row.get("last_eeg"):
found.append(ext("tea-last-eeg", "date", _day(row["last_eeg"])))
for key, name in (("mchat_score", "mchat-score"), ("ados2_css", "ados2-css")):
if row.get(key) is not None:
found.append(ext(name, "integer", int(row[key])))
return found
def replaced_patient(person_id: str, replaced_by: str) -> Patient:
"""A person a review merged into another: no longer active, pointing at who replaced
her, so her id keeps resolving."""
return Patient.model_validate({
"resourceType": "Patient", "id": person_id, "active": False,
"link": [{"other": {"reference": f"Patient/{replaced_by}"}, "type": "replaced-by"}],
@@ -217,7 +237,6 @@ def replaced_patient(person_id: str, replaced_by: str) -> Patient:
def _value(f: catalog.FieldDef, value) -> dict:
"""A field's value as the Observation value of its type."""
if f.type == "code":
system = catalog.systems()[f.system]
if system.external:
@@ -234,8 +253,6 @@ def _value(f: catalog.FieldDef, value) -> dict:
def known(study: str, row: dict, cutoff) -> dict:
"""A study instance as the platform knew it by the end of `cutoff`: the fields of an
event that has no date yet, or a later one, are not known."""
spec = catalog.studies()[study]
out = dict(row)
for cls, event in spec.events.items():
@@ -248,16 +265,13 @@ def known(study: str, row: dict, cutoff) -> dict:
def instance(study: str, row: dict, report_extensions: Iterable[dict] = ()) -> list[Resource]:
"""One study instance (a row of `silver.<study>`) as FHIR, from the catalog: an
Observation per field that is not an event's date, and, when the study has a report,
the DiagnosticReport that gathers them."""
spec = catalog.studies()[study]
person = row["person_id"]
key = [_day(row[k]) if spec.fields[k].type == "date" else row[k] for k in spec.key]
dates = {e.date for e in spec.events.values()}
root = next(e for e in spec.events.values() if e.parent is None)
effective = _day(row.get(root.date))
container = _id(study, person, *key) # its report, or the encounter its notes are of
container = _id(study, person, *key)
visit = "report" not in spec.events
observations = []
for name, f in spec.fields.items():
@@ -273,7 +287,7 @@ def instance(study: str, row: dict, report_extensions: Iterable[dict] = ()) -> l
**({"effectiveDateTime": effective} if effective else {}),
**_value(f, row[name]),
})) # fmt: skip
if visit: # a study without a report (a consultation): the encounter its values are of
if visit:
if not observations:
return []
encounter = Encounter.model_validate({
@@ -303,9 +317,6 @@ def instance(study: str, row: dict, report_extensions: Iterable[dict] = ()) -> l
def condition(row: dict) -> Condition:
"""What a clinical note diagnosed (`silver.clinical_note`), by ICD-10 or as written; or
a study of the catalog that is a diagnosis (`study`: a breast recurrence), by its name
and its coded field (`code`: where it recurred)."""
person, day = row["person_id"], _day(row["note_date"])
code: dict = {"text": row.get("diagnosis_text") or row.get("icd10")}
if row.get("icd10"):
@@ -334,8 +345,6 @@ def condition(row: dict) -> Condition:
def procedure(row: dict, domain: str = "cacu") -> Procedure:
"""A procedure the timeline inferred (`gold.<domain>_events`; CaCu: colposcopy,
treatment; CaMa: each treatment by its kind), coded in `<domain>-procedure`."""
person, day = row["person_id"], _day(row["date"])
return Procedure.model_validate({
"resourceType": "Procedure",
@@ -347,13 +356,10 @@ def procedure(row: dict, domain: str = "cacu") -> Procedure:
}) # fmt: skip
SCENARIO_SEPARATOR = " | " # as models.survival joins them
SCENARIO_SEPARATOR = " | "
def risk_assessment(row: dict, horizons: Iterable[dict]) -> RiskAssessment:
"""A model's risk for one person at her index date (`gold.cacu_risk`): one prediction
per horizon, in years, with its 95% interval; and the clinical scenarios of the model's
report she falls in (an extension each), for her record to draw their curves."""
predictions = []
for h in sorted(horizons, key=lambda h: h["horizon_years"]):
bounds = (("ic-bajo", "ci_low"), ("ic-alto", "ci_high"))
@@ -366,10 +372,11 @@ def risk_assessment(row: dict, horizons: Iterable[dict]) -> RiskAssessment:
**({"extension": interval} if interval else {}),
}) # fmt: skip
model = row["model"]
scored_at = _moment(row["scored_at"])
return RiskAssessment.model_validate({
"resourceType": "RiskAssessment",
"id": _id("risk", model, row["version"], row["person_id"], _day(row["index_date"])),
"meta": {"lastUpdated": _instant(row["scored_at"])},
"meta": {"lastUpdated": scored_at.isoformat() if scored_at is not None else None},
"status": "final",
"method": {"coding": [{"system": CODES + "risk-model", "code": model,
"display": models.title(model)}],
@@ -388,7 +395,6 @@ SCORING = {"proportion": "proportion", "continuous-variable": "continuous-variab
def measure_id(code: str) -> str:
"""A measure's FHIR id (ids allow no underscore)."""
return code.lower().replace("_", "-")
@@ -396,7 +402,6 @@ def measure_url(code: str) -> str:
return f"{BASE}/Measure/{code}"
# The populations each kind of measure counts (core.measures emits exactly these).
POPULATIONS = {"proportion": ["initial-population", "denominator", "numerator"],
"continuous-variable": ["initial-population", "measure-observation"],
"composition": ["initial-population", "measure-observation"]} # fmt: skip
@@ -404,7 +409,6 @@ POPULATION = "http://terminology.hl7.org/CodeSystem/measure-population"
def stratifiers(m) -> list[str]:
"""A measure's strata: a composition's categories first, then its declared strata."""
first = ["category"] if m.rule.kind == "composition" else []
return first + [name for name, _ in getattr(m.rule, "strata", ())]
@@ -414,8 +418,6 @@ def stratifier_code(name: str) -> dict:
def measure(m, domain: str) -> Measure:
"""A measure definition (`core.measures.Measure`): how it is computed is Core's code,
which `criteria` points to."""
criteria = {"language": "text/x-python",
"expression": f"core.{domain}.measures.MEASURES['{m.id}']"} # fmt: skip
group: dict = {
@@ -439,6 +441,8 @@ def measure(m, domain: str) -> Measure:
"extension": [ext("period-type", "code", p) for p in m.periods],
"group": [group],
} # fmt: skip
if m.description:
found["description"] = m.description
if m.improvement:
found["improvementNotation"] = {"coding": [{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
@@ -446,9 +450,6 @@ def measure(m, domain: str) -> Measure:
return Measure.model_validate(found)
# --- conformance: what our resources declare ---------------------------------------------
def code_systems() -> list[CodeSystem]:
return [CodeSystem.model_validate({
"resourceType": "CodeSystem", "id": name, "url": CODES + name,
@@ -463,6 +464,14 @@ def extensions() -> list[StructureDefinition]:
found = []
for name, (value_type, contexts) in EXTENSIONS.items():
url = EXTENSION + name
elements = [
{"id": "Extension.extension", "path": "Extension.extension", "max": "0"},
{"id": "Extension.value[x]", "path": "Extension.value[x]", "min": 1,
"type": [{"code": value_type}]},
] if value_type else [
{"id": "Extension.extension", "path": "Extension.extension", "min": 1},
{"id": "Extension.value[x]", "path": "Extension.value[x]", "max": "0"},
] # fmt: skip
found.append(StructureDefinition.model_validate({
"resourceType": "StructureDefinition", "id": name, "url": url,
"name": _name(name), "status": "active", "fhirVersion": FHIR_VERSION,
@@ -473,16 +482,14 @@ def extensions() -> list[StructureDefinition]:
"differential": {"element": [
{"id": "Extension", "path": "Extension", "max": "*" if name == "period-type"
else "1"},
{"id": "Extension.extension", "path": "Extension.extension", "max": "0"},
*elements[:-1],
{"id": "Extension.url", "path": "Extension.url", "fixedUri": url},
{"id": "Extension.value[x]", "path": "Extension.value[x]", "min": 1,
"type": [{"code": value_type}]},
elements[-1],
]},
})) # fmt: skip
return found
# Our search parameters: code -> (resource, type, description).
SEARCH_PARAMETERS: dict[str, tuple[str, str, str]] = {
"follow-up-status": ("Patient", "token", "Follow-up status at the cut-off"),
"follow-up-cutoff": ("Patient", "date", "The day the follow-up list is taken at"),
@@ -509,6 +516,4 @@ def search_parameters() -> list[SearchParameter]:
def conformance() -> list[Resource]:
"""Everything our resources declare: what the validator loads, and what the
CapabilityStatement points to."""
return [*code_systems(), *extensions(), *search_parameters()]
+3 -28
View File
@@ -1,15 +1,3 @@
"""FHIR in: what a standard hospital sends (R4 Bundles), as the rows a pipeline's link and
target nodes take, the same rows a site's map and extract nodes give. One silver,
two doors.
A record is one resource the hospital sent: a Patient, and each DiagnosticReport or
Encounter (one study instance). Every report also gives an identity row, its subject's, so
the link node joins it to its person the way it joins any document: by identifiers, name and
birth date. Codes in the platform's own systems pass as they are; any other code goes through
the sender's ConceptMaps (core.concept_map), and one no map knows is kept as sent, so the
target holds the row saying why.
"""
import hashlib
from collections.abc import Iterable
from typing import Any
@@ -26,18 +14,10 @@ FIELD = CODES + "catalog-field"
def record(sender: str, reference: str) -> str:
"""A sent resource's record id: stable across resends of the same resource."""
return hashlib.sha256(f"{sender}|{reference}".encode()).hexdigest()
def resources(bundle: dict) -> dict[str, dict]:
"""The Bundle's resources by `Type/id`: what its references name, whether they use that
form or the entry's `fullUrl` (`urn:uuid:...`, as transaction Bundles do)."""
return {f"{r['resourceType']}/{r['id']}": r for r in _entries(bundle).values()}
def _entries(bundle: dict) -> dict[str, dict]:
"""Every resource under each name a reference may use: `Type/id` and its fullUrl."""
found = {}
for entry in bundle.get("entry", []):
r = entry.get("resource") or {}
@@ -49,7 +29,6 @@ def _entries(bundle: dict) -> dict[str, dict]:
def _translated(maps: Iterable[ConceptMap], coding: dict, system: str) -> str | None:
"""A coding as a code of `system`: as it is when already there, else through the maps."""
if coding.get("system") == system:
return coding.get("code")
found = concept_map.translate(maps, coding.get("system", ""), coding.get("code", ""))
@@ -61,7 +40,6 @@ def _codings(concept: dict | None) -> list[dict]:
def identity(patient: dict) -> dict[str, Any]:
"""What a Patient says about whom she is: identifiers by system, name, birth date, sex."""
found: dict[str, Any] = {}
by_system = {v: k for k, v in IDENTIFIER_SYSTEMS.items()}
for i in patient.get("identifier", []):
@@ -86,7 +64,7 @@ def _value(observation: dict, f: catalog.FieldDef, maps) -> Any:
for coding in codings:
if url and (code := _translated(maps, coding, url)) is not None:
return code
return codings[0].get("code") if codings else None # kept as sent: held, saying why
return codings[0].get("code") if codings else None
for key in ("valueBoolean", "valueString", "valueInteger"):
if key in observation:
return observation[key]
@@ -98,12 +76,9 @@ def _value(observation: dict, f: catalog.FieldDef, maps) -> Any:
def rows(bundle: dict, entity: str, sender: str, maps: Iterable[ConceptMap] = ()) -> list[dict]:
"""The Bundle's rows of one entity: `identity` (each Patient, and each report's
subject), `death` (Patients who died), or a study of the catalog (each report or
encounter of it, with its results as fields)."""
maps = list(maps)
sent = resources(bundle)
named = _entries(bundle) # what a reference may name
named = _entries(bundle)
sent = {f"{r['resourceType']}/{r['id']}": r for r in named.values()}
def subject(r: dict) -> dict | None:
return named.get((r.get("subject") or {}).get("reference", ""))
-17
View File
@@ -1,25 +1,8 @@
"""What every domain's follow-up list shares (pure). A domain with a list has a module
`core.<domain>.follow_up` with:
- `WINDOWS`: the windows (months) the list can be asked for; `SORTS` and `DEFAULT_HORIZON`
(years, for orders by risk; None without one);
- `STATUS_SYSTEM`: the code system of a patient's status on the list;
- `listed(rows, start, cutoff)`: who is on the list in reading order (most recent first),
each with her `status` (and `priority`, when the domain ranks them), from the rows of its
`follow_up` read (persistance.fhir);
- `status(row, cutoff)`: a person's status at the cut-off from her person row, or None;
- `ordered(rows, sort, risks, horizon)`: the list in another sort;
- `PROCEDURES`: the timeline's inferred procedures served as FHIR Procedures;
- `REPORT_FACTS`: facts gold adds to a study's report, by study.
"""
import calendar
from datetime import date
def window_start(cutoff: date, months: int) -> date:
"""The first day of the window: `months` before the cut-off (the month's last day when
shorter), plus one day."""
total = cutoff.year * 12 + cutoff.month - 1 - months
year, month = divmod(total, 12)
day = min(cutoff.day, calendar.monthrange(year, month + 1)[1])
+44 -90
View File
@@ -1,18 +1,3 @@
"""The measure engine: what a domain's measure counts, evaluated per period over the rows gold
gives (pure, no IO), and the FHIR R4B MeasureReport each evaluation is served as. Each domain
declares its measures in `core.<domain>.measures` (`MEASURES`).
Three kinds, as FHIR scores them:
- proportion: patients in the denominator and, of them, in the numerator; with a Wilson
95% interval;
- composition: patients split by the category of their latest valid fact in the period;
- continuous variable: days per unit, summarized by the median and inclusive quartiles. A
unit still within its horizon without an end isn't measured yet, so it is left out.
Rows are known from `known_at`; an evaluation `as_of` a moment uses only rows known by then
(all of them by default). Durations count to the event cut-off, `as_of`'s day by default.
"""
import functools
import math
import statistics
@@ -24,7 +9,7 @@ from typing import ClassVar
from fhir.resources.R4B.measurereport import MeasureReport
from core.fhir import EXTENSION, measure_url, stratifier_code
from core.fhir import EXTENSION, _moment, measure_url, stratifier_code
POPULATION = "http://terminology.hl7.org/CodeSystem/measure-population"
IMPROVEMENT = "http://terminology.hl7.org/CodeSystem/measure-improvement-notation"
@@ -36,11 +21,10 @@ NO_BIOPSY = "no_biopsy"
@dataclass(frozen=True)
class Period:
start: date
end: date # exclusive
end: date
@classmethod
def parse(cls, text: str) -> "Period":
"""A semester (`2025-S1`) or a month (`2025-03`)."""
year, part = text.split("-")
if part.startswith("S"):
first = 1 if part == "S1" else 7
@@ -57,14 +41,13 @@ class Period:
return self.start.isoformat(), self.end.isoformat()
def __contains__(self, day) -> bool:
if isinstance(day, str): # ISO days sort as the days they name
if isinstance(day, str):
start, end = self._iso
return start <= day[:10] < end
return day is not None and self.start <= as_day(day) < self.end
def as_day(value) -> date | None:
"""A day, from a date, a datetime or ISO text."""
if value is None or isinstance(value, date) and not isinstance(value, datetime):
return value
if isinstance(value, datetime):
@@ -74,20 +57,10 @@ def as_day(value) -> date | None:
@functools.lru_cache(maxsize=65536)
def _iso_day(text: str) -> date:
"""Parsed once per day: every period scans every row."""
return date.fromisoformat(text)
def _moment(value) -> datetime | None:
"""A moment; one stored without an offset is UTC (how the platform stores them)."""
if value is None:
return None
found = value if isinstance(value, datetime) else datetime.fromisoformat(str(value))
return found if found.tzinfo else found.replace(tzinfo=UTC)
def age_group(birth, at: date, groups: list[tuple[int, int]]) -> str:
"""`low-high` of the group her age at `at` falls in, or below/above them all."""
birth = as_day(birth)
if birth is None:
return NO_DATA
@@ -99,8 +72,8 @@ def age_group(birth, at: date, groups: list[tuple[int, int]]) -> str:
return f"<{lowest}" if age < lowest else f"{highest + 1}+"
# A stratum: its name and the value a row takes in a period.
Stratum = tuple[str, Callable[[dict, "Period"], str]]
Overlap = tuple[str, dict[str, Callable[[dict], bool]]]
@dataclass(frozen=True)
@@ -110,8 +83,6 @@ class Result:
score_extensions: dict[str, float] = field(default_factory=dict)
unit: str | None = None
strata: dict[str, dict[str, dict[str, int]]] = field(default_factory=dict)
# A stratum crossed with the category: (its name, "category") -> (value, category) ->
# counts (a composition by clinical scenario and result, say).
crossed: dict[tuple[str, str], dict[tuple[str, str], dict[str, int]]] = field(
default_factory=dict
)
@@ -126,16 +97,13 @@ def wilson(k: int, n: int) -> tuple[float, float]:
@dataclass(frozen=True)
class Proportion:
"""Units with a row dated in the period that meets `denominator` and, of them, those
with such a row that also meets `numerator`; with a Wilson 95% interval."""
numerator: Callable[[dict], bool]
strata: tuple[Stratum, ...] = ()
denominator: Callable[[dict], bool] = lambda row: True
unit: str = "person_id"
date: str = "sample_date"
overlaps: tuple[Overlap, ...] = ()
kind: str = "proportion"
# Reads only the rows dated in the period (evaluate_periods hands it just those).
dated_only: ClassVar[bool] = True
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
@@ -155,6 +123,10 @@ class Proportion:
cell["denominator"] += 1
cell["numerator"] += unit in num
strata[name] = values
for name, groups in self.overlaps:
strata[name] = {value: {"initial-population": len(den), "denominator": len(den),
"numerator": sum(belongs(row) for row in den.values())}
for value, belongs in groups.items()} # fmt: skip
if not den:
return Result(found, strata=strata)
low, high = wilson(len(num), len(den))
@@ -162,16 +134,11 @@ class Proportion:
def desc(value) -> tuple:
"""A sort key on which a value ranks above a missing one."""
return (value is not None, value)
@dataclass(frozen=True)
class Composition:
"""Units by the category of one row each: of a unit's rows dated in the period (that meet
`where`), the one `order` ranks highest. Only units whose chosen row is `admit`ted count.
The chosen row's `category` is the first stratifier; `strata` add others."""
order: Callable[[dict], tuple]
category: Callable[[dict], str]
admit: Callable[[dict], bool] = lambda row: True
@@ -180,7 +147,6 @@ class Composition:
unit: str = "person_id"
date: str = "sample_date"
kind: str = "composition"
# Reads only the rows dated in the period (evaluate_periods hands it just those).
dated_only: ClassVar[bool] = True
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
@@ -199,7 +165,7 @@ class Composition:
values.setdefault(value, {"initial-population": 0})["initial-population"] += 1
strata[name] = values
crossed: dict[tuple[str, str], dict[tuple[str, str], dict[str, int]]] = {}
for name, stratum in self.strata: # each also by category
for name, stratum in self.strata:
pairs: dict[tuple[str, str], dict[str, int]] = {}
for row in chosen.values():
key = (stratum(row, period), self.category(row))
@@ -212,10 +178,6 @@ class Composition:
@dataclass(frozen=True)
class Duration:
"""Days from `start` to `end` per unit (`value`), within `horizon` days. A unit whose
interval `ended` (default: has an `end`) without a value, like a sample reported
unsatisfactory, is in the initial population but not measured."""
value: str
end: str
start: str
@@ -225,7 +187,6 @@ class Duration:
unit: str = "sample_id"
date: str = "sample_date"
kind: str = "continuous-variable"
# Keeps each unit's last row, then reads only those dated in the period.
dated_only: ClassVar[bool] = True
one_per_unit: ClassVar[bool] = True
@@ -254,9 +215,6 @@ class Duration:
@dataclass(frozen=True)
class RiskBand:
"""Patients indexed in the period, by the band their risk falls in (NO_DATA unscored):
`bands` are (name, upper cut), the last one's cut None."""
bands: tuple[tuple[str, float | None], ...]
kind: str = "composition"
@@ -275,14 +233,11 @@ class RiskBand:
@dataclass(frozen=True)
class AtEnd:
"""The units on the books at a period's end: entered (`entry`) before it ended and not
gone (`exit`) before it began. Each is in the latest of `states` (name, date column, in
order) it reached before the end."""
entry: str
exit: str
states: tuple[tuple[str, str], ...]
unit: str = "person_id"
exit_inclusive: bool = True
def units(self, rows: list[dict], period: Period) -> dict[str, tuple[dict, str]]:
found = {}
@@ -290,6 +245,8 @@ class AtEnd:
entry, gone = as_day(row.get(self.entry)), as_day(row.get(self.exit))
if entry is None or entry >= period.end or (gone is not None and gone < period.start):
continue
if gone == period.start and not self.exit_inclusive:
continue
reached = [n for n, c in self.states
if (d := as_day(row.get(c))) is not None and d < period.end] # fmt: skip
if reached:
@@ -298,17 +255,12 @@ class AtEnd:
def reached(row: dict, column: str, period: Period) -> bool:
"""A date reached by the period's end."""
day = as_day(row.get(column))
return day is not None and day < period.end
@dataclass(frozen=True)
class StatusProportion:
"""Of the units on the books at the end (`population`) that meet `denominator`, those
that meet `numerator`; both see the unit's row, its state and the period. Strata count
every unit on the books, so a stratum with none in the denominator still shows."""
population: AtEnd
denominator: Callable[[dict, str, Period], bool]
numerator: Callable[[dict, str, Period], bool]
@@ -338,28 +290,38 @@ class StatusProportion:
@dataclass(frozen=True)
class StatusComposition:
"""The units on the books at the end, by their state; only `admit`ted states count."""
population: AtEnd
admit: Callable[[str], bool] = lambda state: True
strata: tuple[Stratum, ...] = ()
kind: str = "composition"
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
states = [s for _, s in self.population.units(rows, period).values() if self.admit(s)]
categories: dict[str, dict[str, int]] = {}
for state in states:
categories.setdefault(state, {"initial-population": 0})["initial-population"] += 1
n = len(states)
return Result({"initial-population": n, "measure-observation": n},
strata={"category": categories}) # fmt: skip
units = [(r, s) for r, s in self.population.units(rows, period).values() if self.admit(s)]
strata: dict[str, dict[str, dict[str, int]]] = {}
crossed: dict[tuple[str, str], dict[tuple[str, str], dict[str, int]]] = {
(name, "category"): {} for name, _ in self.strata
}
strata["category"] = {}
strata.update((name, {}) for name, _ in self.strata)
for row, state in units:
category = strata["category"].setdefault(state, {"initial-population": 0})
category["initial-population"] += 1
for name, stratum in self.strata:
value = stratum(row, period)
cell = strata[name].setdefault(value, {"initial-population": 0})
cell["initial-population"] += 1
pair = crossed[name, "category"].setdefault(
(value, state), {"initial-population": 0}
)
pair["initial-population"] += 1
n = len(units)
return Result(
{"initial-population": n, "measure-observation": n}, strata=strata, crossed=crossed
)
@dataclass(frozen=True)
class StatusDuration:
"""Days (`value`) per unit on the books at the end, for those whose interval ended
(`end`) before the period's end and by the cut-off; every unit on the books is in the
initial population."""
population: AtEnd
value: str
end: str
@@ -388,17 +350,16 @@ Rule = (Proportion | Composition | Duration | RiskBand | StatusProportion | Stat
class Measure:
id: str
title: str
rows: str # which gold rows it reads (see persistance.measures)
rows: str
rule: Rule
improvement: str | None = None
version: str = "1.0.0"
periods: tuple[str, ...] = ("semester", "month")
group: str = "TOTAL"
params: dict = field(default_factory=dict) # bound into the read of its rows
known: str = "known_at" # when a row's unit became known: before then it isn't counted
# Facts a row carries that became known apart from the row itself: their `known_at`
# column -> the columns they fill. Asked `as_of` before then, the row has them empty.
params: dict = field(default_factory=dict)
known: str = "known_at"
facts: dict[str, tuple[str, ...]] = field(default_factory=dict)
description: str | None = None
def evaluate(
@@ -408,11 +369,9 @@ def evaluate(
as_of: datetime | None = None,
event_cutoff: date | None = None,
) -> Result:
"""The measure over the rows known `as_of` (all by default) for one period; durations
count to `event_cutoff` (default: `as_of`'s day, or today)."""
as_of = _moment(as_of)
cutoff = event_cutoff or (as_of or datetime.now(UTC)).date()
if as_of is None: # every row and fact is known
if as_of is None:
return measure.rule.evaluate(rows if isinstance(rows, list) else list(rows), period, cutoff)
def known(column: str, row: dict) -> bool:
@@ -433,15 +392,11 @@ def evaluate_periods(
as_of: datetime | None = None,
event_cutoff: date | None = None,
) -> list[Result]:
"""`evaluate` for each period. A rule that reads only the rows dated in the period gets
just those, in their order: the rows are indexed by month once (periods are whole
months), not scanned once per period. One that keeps a row per unit first gets them
already kept."""
rule = measure.rule
rows = rows if isinstance(rows, list) else list(rows)
if as_of is not None or not getattr(rule, "dated_only", False):
return [evaluate(measure, rows, p, as_of, event_cutoff) for p in periods]
if getattr(rule, "one_per_unit", False): # the same for every period: done once
if getattr(rule, "one_per_unit", False):
rows = list({row[rule.unit]: row for row in rows}.values())
months: dict[tuple[int, int], list[int]] = defaultdict(list)
for i, row in enumerate(rows):
@@ -461,7 +416,6 @@ def _population(code: str, count: int) -> dict:
def report(
measure: Measure, period: Period, result: Result, as_of: datetime | None
) -> MeasureReport:
"""The evaluation as a FHIR R4B MeasureReport (validated when built)."""
group: dict = {
"id": measure.group,
"population": [_population(c, n) for c, n in result.populations.items()],
@@ -473,7 +427,7 @@ def report(
"extension": [{"url": EXTENSION + k, "valueDecimal": v}
for k, v in result.score_extensions.items()],
} # fmt: skip
elif measure.rule.kind == "composition": # a cohort scores its count
elif measure.rule.kind == "composition":
group["measureScore"] = {"value": result.populations["initial-population"]}
if result.strata:
group["stratifier"] = [
@@ -493,7 +447,7 @@ def report(
found = {
"resourceType": "MeasureReport",
"status": "complete",
"type": "summary", # with no score when nothing in the period could be measured
"type": "summary",
"measure": f"{measure_url(measure.id)}|{measure.version}",
"period": {"start": period.start.isoformat(),
"end": date.fromordinal(period.end.toordinal() - 1).isoformat()},
+1 -5
View File
@@ -1,6 +1,3 @@
"""The models' names as the pages and FHIR resources show them (`<domain>.<model>`). A model
without one is shown by its code."""
TITLES: dict[str, str] = {
"cacu.cin2_logistic": "Riesgo de LIEAG+ (regresión logística)",
"cacu.cin2_pim": "Riesgo de LIEAG+ en vigilancia",
@@ -17,10 +14,9 @@ TITLES: dict[str, str] = {
"tea.eeg-spindles-n3": "Curva por edad: husos de sueño N3",
"tea.eeg-spindle-topography-n2": "Curva por edad: topografía de husos N2",
"tea.eeg-spindle-topography-n3": "Curva por edad: topografía de husos N3",
"tea.eeg-ados2": "Relación del EEG con el ADOS-2",
"tea.ados2_association": "Relación del EEG con el ADOS-2",
}
def title(model: str) -> str:
"""`model` (`<domain>.<name>`) as the pages name it."""
return TITLES.get(model, model.split(".", 1)[-1])
+159 -94
View File
@@ -1,11 +1,3 @@
"""The ingestion DSL: a graph an operator draws, and the pure steps it needs. No IO here.
A pipeline is one versioned JSON document of nodes; each node names its inputs (the edges).
Every node kind wraps one library operation and outputs one table, so any node's output can
be previewed and a run can restart from the node that changed. Each kind's JSON Schema is
the form the canvas shows for it. Nothing in a graph is specific to one hospital in code.
"""
import re
from datetime import datetime
from graphlib import CycleError, TopologicalSorter
@@ -26,21 +18,16 @@ from pydantic import (
from core import catalog, sources
from core.schema import ENTITIES
ID_PATTERN = r"^[a-z][a-z0-9_]*$" # pipeline and node ids: also table-name safe
ID_PATTERN = r"^[a-z][a-z0-9_]*$"
Id = Annotated[str, Field(pattern=ID_PATTERN, max_length=40)]
ImportPath = Annotated[str, Field(pattern=r"^[A-Za-z_][\w.]*:[A-Za-z_]\w*$")]
EntityName = Literal[tuple(ENTITIES)] # type: ignore[valid-type]
# How the forms name each entity: identity, and each study by its catalog title.
ENTITY_TITLES = {"identity": "Identidad de la persona",
**{name: spec.title for name, spec in catalog.studies().items()}} # fmt: skip
def _says(title: str, description: str = "", options: dict[str, str] | None = None,
advanced: bool = False, keys: Literal["field"] | None = None) -> Any: # fmt: skip
"""A field as the canvas form shows it: its title and help in the operator's words,
for a fixed set of values how each one reads, and whether only the "Avanzado" tab
shows it (what a guided dialog fills instead); a map keyed by platform fields says so
(`keys="field"`), so its keys are picked by their titles."""
extra: dict[str, Any] = {}
if options:
listed = [{"value": k, "label": v} for k, v in options.items()]
@@ -59,41 +46,55 @@ class Position(BaseModel):
class Node(BaseModel):
model_config = ConfigDict(extra="forbid")
inputs_allowed: ClassVar[tuple[int, int | None]] = (1, 1) # (min, max); None: no max
inputs_allowed: ClassVar[tuple[int, int | None]] = (1, 1)
id: Id
inputs: list[Id] = []
label: Annotated[str, _says("Nombre", "Cómo se ve en el diagrama.")] = ""
position: Position | None = None # where the canvas drew it
position: Position | None = None
class Guided(BaseModel):
"""How the Conectar dialog drew a source: its type (core.sources) and the answers given.
The node's dlt fields are made from them; drawn by hand ("Avanzado"), a node has none."""
model_config = ConfigDict(extra="forbid")
model_config = ConfigDict(
extra="forbid",
json_schema_extra={
"description": (
"How the Conectar dialog drew a source: its type (core.sources) "
"and the answers given.\n"
"The node's dlt fields are made from them; drawn by hand "
'("Avanzado"), a node has none.'
)
},
)
type: str
answers: dict[str, Any] = {}
class Source(Node):
"""One table, file set or API resource, copied as it is (dlt). Merged on the source's
own primary key or `primary_key`; replaced whole when it has none."""
model_config = ConfigDict(
json_schema_extra={
"description": (
"One table, file set or API resource, copied as it is (dlt). "
"Merged on the source's\n"
"own primary key or `primary_key`; replaced whole when it has "
"none."
)
}
)
inputs_allowed = (0, 0)
kind: Literal["source"] = "source"
# any dlt source or resource, e.g. dlt.sources.sql_database:sql_table
source: Annotated[
ImportPath, _says("Fuente dlt", "Módulo:función de la fuente dlt.", advanced=True)
]
args: Annotated[
dict[str, Any], _says("Argumentos", "Los de la fuente dlt.", advanced=True)
] = {}
resource: Annotated[ # which resource, when the source has several
resource: Annotated[
str | None,
_says("Recurso", "Cuál, si la fuente ofrece varios (una tabla).", advanced=True),
] = None
then: Annotated[ # a dlt transformer piped after (file contents, Excel)
then: Annotated[
ImportPath | None, _says("Lector", "Transformador dlt para los archivos.", advanced=True)
] = None
primary_key: Annotated[
@@ -104,21 +105,25 @@ class Source(Node):
@model_validator(mode="before")
@classmethod
def _made_from_answers(cls, data: Any) -> Any:
"""A guided source's dlt fields always follow its answers. A source drawn by hand
that a catalog type makes exactly is read as that type, so the dialog edits it."""
if isinstance(data, dict) and not data.get("guided") and data.get("source"):
if found := sources.recognise(data):
data = {**data, "guided": {"type": found[0], "answers": found[1]}}
if isinstance(data, dict) and data.get("guided"):
guided = data["guided"]
guided = guided.model_dump() if isinstance(guided, BaseModel) else guided
if MASK not in repr(guided.get("answers", {})): # masked: shown, not run
if MASK not in repr(guided.get("answers", {})):
data = {**data, **sources.render(guided["type"], guided.get("answers", {}))}
return data
class Read(Node):
"""Files in a column (PDF, Word, Excel, scans...) to text (MarkItDown, OCRmyPDF)."""
model_config = ConfigDict(
json_schema_extra={
"description": (
"Files in a column (PDF, Word, Excel, scans...) to text (MarkItDown, OCRmyPDF)."
)
}
)
kind: Literal["read"] = "read"
column: Annotated[
@@ -144,9 +149,18 @@ class Condition(BaseModel):
class Route(Node):
"""Only the rows where every condition holds (e.g. reports titled "Citología"). An
`otherwise` route takes the rows of its input that none of the other routes on that
input take (documents nobody recognises, for a reviewer), then its own conditions."""
model_config = ConfigDict(
json_schema_extra={
"description": (
"Only the rows where every condition holds (e.g. reports titled "
'"Citología"). An\n'
"`otherwise` route takes the rows of its input that none of the "
"other routes on that\n"
"input take (documents nobody recognises, for a reviewer), then "
"its own conditions."
)
}
)
kind: Literal["route"] = "route"
when: Annotated[list[Condition], _says("Pasan las filas donde")] = []
@@ -156,37 +170,50 @@ class Route(Node):
class Map(Node):
"""Columns to platform fields, the site's codes translated by its ConceptMap
(core.concept_map), and its date formats."""
model_config = ConfigDict(
json_schema_extra={
"description": (
"Columns to platform fields, the site's codes translated by its "
"ConceptMap\n"
"(core.concept_map), and its date formats."
)
}
)
kind: Literal["map"] = "map"
fields: Annotated[ # platform field -> column
fields: Annotated[
dict[str, str], _says("Campos", "Dato de la plataforma → columna del sitio.", keys="field")
]
concept_map: Annotated[ # the site's codes in platform terms
concept_map: Annotated[
Id | None, _says("Equivalencias de códigos", "La tabla de códigos del sitio.")
] = None
formats: Annotated[ # platform field -> strptime format
formats: Annotated[
dict[str, str], _says("Formatos de fecha", "Por ejemplo %d/%m/%Y.", keys="field")
] = {}
# platform field -> a value in platform terms that every row has, though no column says
# it (a table of neurology notes: their specialty)
values: Annotated[
dict[str, str], _says("Valores fijos", "Un dato igual para todas las filas.", keys="field")
] = {}
class Extract(Node):
"""Platform fields read from text, each kept with the text it was read from.
`auto` asks the LLM when one is configured and answering, else applies `patterns`;
with neither, the row is held. Patterns are regexes with one group, per field (the
LLM can propose them from sample documents); their values go through the ConceptMap
and `formats` as in `map`."""
model_config = ConfigDict(
json_schema_extra={
"description": (
"Platform fields read from text, each kept with the text it was "
"read from.\n"
"\n"
"`auto` asks the LLM when one is configured and answering, else "
"applies `patterns`;\n"
"with neither, the row is held. Patterns are regexes with one "
"group, per field (the\n"
"LLM can propose them from sample documents); their values go "
"through the ConceptMap\n"
"and `formats` as in `map`."
)
}
)
kind: Literal["extract"] = "extract"
# the text to read; several columns are read as one document, in their order (an
# outsourced result joined to the order it answers)
column: Annotated[str | list[str], _says("Columna con el texto")]
entity: Annotated[
EntityName, _says("Estudio", "Qué estudio se saca del documento.", ENTITY_TITLES)
@@ -203,11 +230,9 @@ class Extract(Node):
), # fmt: skip
] = "auto"
hints: Annotated[str, _says("Indicaciones", "Para el modelo de lenguaje.")] = ""
patterns: Annotated[ # platform field -> regex with one group
patterns: Annotated[
dict[str, str], _says("Patrones", "Dato → expresión con un grupo ( ).", keys="field")
] = {}
# platform field -> a column of the row taken as it is, not read from the text (an EEG
# report joined to its recording: the date from the report, the file from the column)
columns: Annotated[
dict[str, str],
_says("Datos tomados de columnas", "Dato → columna, sin leer el texto.", keys="field"),
@@ -224,15 +249,57 @@ class Extract(Node):
return v
def text(self, row: dict[str, Any]) -> str:
"""The row's text this node reads."""
columns = [self.column] if isinstance(self.column, str) else self.column
return "\n".join(str(row[c]) for c in columns if row.get(c))
class Edf(Node):
model_config = ConfigDict(
json_schema_extra={
"description": (
"EDF files (a column of file hashes) to the facts their header holds: "
"patient code, sex,\n"
"birth date, recording date, record code, duration and channel count, as "
"`edf_*` columns.\n"
"An unreadable file keeps its row with `edf_error` set.\n"
"\n"
"Use a filesystem source (`dlt.sources.filesystem:filesystem`) with the "
"uploads folder as\n"
'`bucket_url`, `file_glob: "*.edf"`, and `then: '
'"persistance.readers:read_bytes"`. Read its\n'
"`content` column with this node. Map `edf_patient_code`, `edf_birth_date`, "
"and `edf_sex` to\n"
"identity's `record_number`, `birth_date`, and `sex`, using the site's "
"formats and ConceptMap.\n"
"\n"
"The patient code must match the hospital's record number including its "
"prefix. Feed the\n"
"identity map into the pipeline's link node alongside the hospital identity "
"source. Map\n"
"`edf_study_date` to `study_date` (format `%Y-%m-%d`), `edf_record_code` to "
"`lab_record_id`,\n"
"and `content` to `edf`, then feed that map and the link into a target with "
"entity `eeg`."
)
},
)
kind: Literal["edf"] = "edf"
column: str
class Fhir(Node):
"""FHIR R4 Bundles a standard hospital sent (a column of their JSON) as rows of one
entity: identity, death or a study (core.fhir_in). The sender's own codes go through
its ConceptMap."""
model_config = ConfigDict(
json_schema_extra={
"description": (
"FHIR R4 Bundles a standard hospital sent (a column of their "
"JSON) as rows of one\n"
"entity: identity, death or a study (core.fhir_in). The sender's "
"own codes go through\n"
"its ConceptMap."
)
}
)
kind: Literal["fhir"] = "fhir"
column: Annotated[str, _says("Columna con el FHIR")] = "doc"
@@ -241,11 +308,13 @@ class Fhir(Node):
class Join(Node):
"""Two inputs side by side where their columns match."""
model_config = ConfigDict(
json_schema_extra={"description": "Two inputs side by side where their columns match."}
)
inputs_allowed = (2, 2)
kind: Literal["join"] = "join"
on: Annotated[ # (left column, right column)
on: Annotated[
list[tuple[str, str]],
_says("Columnas iguales", "Columna de la primera entrada = columna de la segunda."),
]
@@ -262,18 +331,28 @@ IDENTIFIERS = ("record_number", "curp", "nss")
class Link(Node):
"""Identity rows from every input, grouped into persons (Splink).
Two records are the same person when any rule holds (Splink's SQL rule syntax, `l.`
and `r.` for the two records); persons are the connected groups. A person whose
records disagree on birth date or sex is held for review as a whole. Pairs Splink
scores above `review` that ended up apart are queued as possible matches."""
model_config = ConfigDict(
json_schema_extra={
"description": (
"Identity rows from every input, grouped into persons (Splink).\n"
"\n"
"Two records are the same person when any rule holds (Splink's "
"SQL rule syntax, `l.`\n"
"and `r.` for the two records); persons are the connected "
"groups. A person whose\n"
"records disagree on birth date or sex is held for review as a "
"whole. Pairs Splink\n"
"scores above `review` that ended up apart are queued as "
"possible matches."
)
}
)
inputs_allowed = (1, None)
kind: Literal["link"] = "link"
fields: Annotated[list[str], _says("Datos que comparar")] = [
"record_number", "full_name", "curp", "nss", "birth_date", "sex"] # fmt: skip
rules: Annotated[ # empty: the defaults for `fields` (see default_rules)
rules: Annotated[
list[str],
_says(
"Reglas",
@@ -287,8 +366,6 @@ class Link(Node):
] = 0.5
def default_rules(self) -> list[str]:
"""The same identifier, unless the birth dates differ; or the same birth date and
the same name (as compared: upper case, no accents, single spaces)."""
dob = "birth_date" in self.fields
same_dob = (
" and (l.birth_date is null or r.birth_date is null"
@@ -301,8 +378,16 @@ class Link(Node):
class Target(Node):
"""Rows of platform fields into one platform entity, each row given its person by the
one `link` node among the inputs. Rule breaks are held for review."""
model_config = ConfigDict(
json_schema_extra={
"description": (
"Rows of platform fields into one platform entity, each row "
"given its person by the\n"
"one `link` node among the inputs. Rule breaks are held for "
"review."
)
}
)
inputs_allowed = (2, None)
kind: Literal["target"] = "target"
@@ -320,7 +405,8 @@ class Target(Node):
AnyNode = Annotated[
Source | Read | Route | Map | Extract | Fhir | Join | Link | Target, Field(discriminator="kind")
Source | Read | Route | Map | Extract | Edf | Fhir | Join | Link | Target,
Field(discriminator="kind"),
]
@@ -349,15 +435,14 @@ class Pipeline(BaseModel):
return self
def order(self) -> list[AnyNode]:
"""Nodes in an order where every input runs before the nodes that read it."""
by_id = {n.id: n for n in self.nodes}
graph = TopologicalSorter({n.id: n.inputs for n in self.nodes})
return [by_id[i] for i in graph.static_order()]
RECORD = "_record" # the source row every row comes from (hash of that row)
HELD = "_held" # why a row may not reach silver (list of reasons) or None
QUOTES = "_quotes" # what text each LLM value was read from
RECORD = "_record"
HELD = "_held"
QUOTES = "_quotes"
def matches(node: Route, row: dict[str, Any]) -> bool:
@@ -376,7 +461,6 @@ def matches(node: Route, row: dict[str, Any]) -> bool:
def join(node: Join, left: list[dict], right: list[dict], right_id: str) -> list[dict]:
"""Left rows with the matching right rows' columns (a clashing name gets `__<right>`)."""
index: dict[tuple, list[dict]] = {}
for r in right:
index.setdefault(tuple(r.get(b) for _, b in node.on), []).append(r)
@@ -389,15 +473,10 @@ def join(node: Join, left: list[dict], right: list[dict], right_id: str) -> list
return out
Codes = dict[str, dict[str, str]] # field -> site code (casefolded) -> platform code
Codes = dict[str, dict[str, str]]
def convert(node: Map | Extract, field: str, raw: Any, codes: Codes) -> Any:
"""A raw value as the platform field expects it: the site's code translated (its
ConceptMap, case ignored), then its date format: a strptime format (spaces inside the
value ignored when the format has none), or `dateparser:<language>` for dates written
out ("9 de diciembre de 2025"). A value that doesn't parse is kept as written, so the
target holds it with the reason."""
if not isinstance(raw, str):
return raw
raw = raw.strip()
@@ -407,7 +486,7 @@ def convert(node: Map | Extract, field: str, raw: Any, codes: Codes) -> Any:
found = dateparser.parse(raw, languages=[fmt.split(":")[1]])
return found.date() if found else raw
if fmt:
if " " not in fmt: # OCR may split a number ("25/01/1 967")
if " " not in fmt:
raw = "".join(raw.split())
try:
return datetime.strptime(raw, fmt).date()
@@ -424,7 +503,6 @@ def map_row(node: Map, row: dict[str, Any], codes: Codes) -> dict[str, Any]:
def validate(entity: str, values: dict[str, Any]) -> list[str]:
"""Why these values break the platform schema; empty if they don't."""
try:
ENTITIES[entity].model_validate(values)
except ValidationError as e:
@@ -436,7 +514,6 @@ _SPACE = re.compile(r"\s+")
def grounded(quote: str | None, text: str) -> bool:
"""An LLM value counts only if the text it says it read is really in the document."""
if not quote:
return False
norm = lambda s: _SPACE.sub(" ", s).strip().casefold() # noqa: E731
@@ -444,8 +521,6 @@ def grounded(quote: str | None, text: str) -> bool:
def ground(answer: dict, text: str) -> list[tuple[dict, dict, list[str]]]:
"""Each record of an LLM answer as (values, quotes, reasons to hold it). A value whose
quote is not in the text is dropped, and the record is held saying so."""
out = []
for record in answer.get("records", []):
values, quotes, held = {}, {}, []
@@ -461,8 +536,6 @@ def ground(answer: dict, text: str) -> list[tuple[dict, dict, list[str]]]:
def apply_patterns(node: Extract, text: str, codes: Codes) -> list[tuple[dict, dict, list[str]]]:
"""One record from the node's patterns: (values, quotes, reasons to hold it). A value
found this way is grounded by construction: the quote is the matched text."""
values, quotes = {}, {}
for field, pattern in node.patterns.items():
if found := re.search(pattern, text, re.IGNORECASE):
@@ -474,8 +547,6 @@ def apply_patterns(node: Extract, text: str, codes: Codes) -> list[tuple[dict, d
def answer_schema(entity: str) -> dict:
"""JSON Schema for an LLM answer: every record of `entity` found, each field with the
quote it was read from."""
fields = {
f: (create_model(f"{entity}_{f}", value=(info.annotation, None), quote=(str, "")), None)
for f, info in ENTITIES[entity].model_fields.items()
@@ -503,8 +574,6 @@ def _mask(key: str, value: Any) -> Any:
def _secret_answers(guided: "Guided") -> set[str]:
"""Answers masked whole (a password); a sign-in's account keeps who it is and masks
its tokens and client secret, like any argument."""
fields = sources.catalog().types[guided.type].fields
return {k for k, f in fields.items() if f.type == "password"}
@@ -520,8 +589,6 @@ def _masked_source(n: "Source") -> "Source":
def redacted(pipeline: Pipeline) -> Pipeline:
"""The pipeline with every secret in its sources masked (arguments and the dialog's
answers), as the API shows it."""
nodes = [_masked_source(n) if n.kind == "source" else n for n in pipeline.nodes]
return pipeline.model_copy(update={"nodes": nodes})
@@ -538,8 +605,6 @@ def _restore(new: Any, old: Any, where: str) -> Any:
def restored(new: Pipeline, old: Pipeline | None) -> Pipeline:
"""A pipeline sent back by the UI with masks where secrets were: the saved secrets are
kept. A mask with nothing saved behind it is refused."""
saved = {n.id: n for n in old.nodes if n.kind == "source"} if old else {}
nodes = [_restored_source(n, saved.get(n.id)) if n.kind == "source" else n
for n in new.nodes] # fmt: skip
+8 -13
View File
@@ -1,11 +1,3 @@
"""The platform schema: the only fixed shape in ingestion. Every source is mapped onto it.
`identity` is what a record says about whom it belongs to; every other entity is a study of
the clinical catalog (core.catalog), whose natural key and fields the catalog declares. Two
values for one key that disagree are a conflict. `person` is never a field: record linkage
over `identity` values assigns it.
"""
import re
from datetime import date
from enum import StrEnum
@@ -21,8 +13,6 @@ class Sex(StrEnum):
MALE = "male"
# Systems of the identifiers a person carries. A record number's system is where it came
# from (`urn:isssteleon:<pipeline>:<node>`): a hospital has as many as it has sources.
IDENTIFIER_SYSTEMS = {
"curp": "https://isssteleon.org/fhir/sid/curp",
"nss": "https://isssteleon.org/fhir/sid/nss",
@@ -39,7 +29,14 @@ class Entity(BaseModel):
class Identity(Entity):
"""What a record says about whom it belongs to. Input to linkage, never trusted alone."""
model_config = ConfigDict(
json_schema_extra={
"description": (
"What a record says about whom it belongs to. "
"Input to linkage, never trusted alone."
)
}
)
record_number: str | None = Field(None, title="Número de expediente")
full_name: str | None = Field(None, title="Nombre completo")
@@ -51,8 +48,6 @@ class Identity(Entity):
@field_validator("record_number")
@classmethod
def _not_a_date(cls, v: str | None) -> str | None:
"""A date read where a record number should be (a report's date beside "No.
Registro:", say) would join strangers: the record waits for a reviewer instead."""
if v is not None and _DATE.fullmatch(v.strip()):
raise ValueError("a date is not a record number")
return v
+40 -56
View File
@@ -1,18 +1,3 @@
"""The kinds of source an operator can connect, as the Conectar dialog walks them through.
It is data (`types.yaml` beside this module): each type says what to ask (its fields, in
plain words), how the answers become a pipeline's `Source` node (a dlt source and its
arguments), and what "Probar conexión" can list from it. A new kind of source is a new entry,
never code; a site's own source is configuration (the answers saved in its pipeline).
Templates: a string that is exactly "{field}" takes the answer as given (a number stays a
number, a "{field[part]}" one part of a structured answer such as a sign-in's; an empty
optional answer drops the key, and a block whose every answer is empty
goes with it); inside a longer string, `{field:url}` quotes
the answer for a URL's user or password, `{field:path}` for a URL's path, and `{field:last}`
takes the last part of a link (a folder's id in a shared link).
"""
import re
import string
from functools import cache
@@ -25,18 +10,18 @@ from pydantic import BaseModel, ConfigDict, model_validator
HERE = Path(__file__).parent
FieldType = Literal[
"text", # a line of text
"text",
"number",
"password", # never shown back; masked like any secret
"select", # one of `options`
"folder", # a folder on the server, browsed under the roots the operator mounted
"server_file", # a file on the server, browsed the same way
"upload", # files sent from the user's computer; holds the folder they landed in
"url", # a web address, or a path typed in
"oauth", # "Iniciar sesión con …": holds the provider's refresh token
"table", # picked from what "Probar conexión" listed
"format", # how to read the files: one of the catalog's `formats`
"columns", # some of the table's columns (a list), picked from its first rows
"password",
"select",
"folder",
"server_file",
"upload",
"url",
"oauth",
"table",
"format",
"columns",
]
@@ -54,9 +39,9 @@ class FieldSpec(BaseModel):
placeholder: str = ""
required: bool = True
default: Any = None
options: list[Option] = [] # select
provider: str | None = None # oauth: microsoft, google
advanced: bool = False # shown under "Más opciones"
options: list[Option] = []
provider: str | None = None
advanced: bool = False
@model_validator(mode="after")
def _complete(self):
@@ -68,10 +53,17 @@ class FieldSpec(BaseModel):
class Listing(BaseModel):
"""What "Probar conexión" shows: a database's tables (the resources of `source`, built
from `args`), or the first rows the type's own node reads (files, records)."""
model_config = ConfigDict(extra="forbid")
model_config = ConfigDict(
extra="forbid",
json_schema_extra={
"description": (
'What "Probar conexión" shows: a database\'s tables (the '
"resources of `source`, built\n"
"from `args`), or the first rows the type's own node reads "
"(files, records)."
)
},
)
kind: Literal["tables", "rows"]
source: str | None = None
args: dict[str, Any] = {}
@@ -84,7 +76,7 @@ class SourceType(BaseModel):
description: str
icon: str
fields: dict[str, FieldSpec]
source: str # the dlt source or resource the node runs
source: str
args: dict[str, Any] = {}
resource: str | None = None
then: str | None = None
@@ -102,11 +94,14 @@ class SourceType(BaseModel):
class Provider(BaseModel):
"""A sign-in button's OAuth 2.0 provider (authorization code flow)."""
model_config = ConfigDict(extra="forbid")
model_config = ConfigDict(
extra="forbid",
json_schema_extra={
"description": "A sign-in button's OAuth 2.0 provider (authorization code flow)."
},
)
title: str
env: str # prefix of the server's settings for its app registration
env: str
authorize_url: str
token_url: str
scope: str
@@ -123,7 +118,7 @@ class Catalog(BaseModel):
model_config = ConfigDict(extra="forbid")
groups: dict[str, Group]
providers: dict[str, Provider]
formats: list[Option] # how a file is read: the `then` of a filesystem source
formats: list[Option]
types: dict[str, SourceType]
@model_validator(mode="after")
@@ -138,7 +133,7 @@ class Catalog(BaseModel):
class MissingAnswer(ValueError):
"""An answer the type needs was left empty; its message names it in plain words."""
pass
@cache
@@ -180,7 +175,7 @@ _DROP = object()
def _fill(template: Any, values: dict[str, Any]) -> Any:
named = _placeholders(template)
if isinstance(template, dict) and named and all(values.get(n) in (None, "") for n in named):
return _DROP # a block whose every answer is empty (an optional token's auth)
return _DROP
if isinstance(template, dict):
filled = {k: _fill(v, values) for k, v in template.items()}
return {k: v for k, v in filled.items() if v is not _DROP}
@@ -190,7 +185,7 @@ def _fill(template: Any, values: dict[str, Any]) -> Any:
return template
parts = list(_FORMAT.parse(template))
if len(parts) == 1 and parts[0][0] == "" and parts[0][1] and not parts[0][2]:
name = parts[0][1] # "{account}", or a part of it: "{account[drive_id]}"
name = parts[0][1]
if values.get(_base(name)) in (None, ""):
return _DROP
value = _FORMAT.get_field(name, (), values)[0]
@@ -199,7 +194,6 @@ def _fill(template: Any, values: dict[str, Any]) -> Any:
def answers(type_id: str, given: dict[str, Any]) -> dict[str, Any]:
"""The answers with defaults filled in; a required answer missing is refused."""
spec = catalog().types[type_id]
if unknown := set(given) - set(spec.fields):
raise ValueError(f"{type_id}: no fields {sorted(unknown)}")
@@ -215,8 +209,6 @@ def answers(type_id: str, given: dict[str, Any]) -> dict[str, Any]:
def render(type_id: str, given: dict[str, Any]) -> dict[str, Any]:
"""The `Source` node fields (source, args, resource, then, primary_key) the answers
make."""
spec = catalog().types[type_id]
values = answers(type_id, given)
made = {
@@ -230,8 +222,6 @@ def render(type_id: str, given: dict[str, Any]) -> dict[str, Any]:
def listing(type_id: str, given: dict[str, Any]) -> tuple[str, dict[str, Any]] | None:
"""For a type that lists tables: the dlt source and arguments that list them. The
table field may still be empty (it is what the listing helps pick)."""
spec = catalog().types[type_id]
if not spec.listing or spec.listing.kind != "tables" or not spec.listing.source:
return None
@@ -248,14 +238,13 @@ class _NoMatch(Exception):
def _take(template: Any, value: Any, found: dict[str, Any]) -> None:
"""The answers that make `template` give `value`, into `found` (_NoMatch when none)."""
if isinstance(template, dict):
if not isinstance(value, dict) or set(value) - set(template):
raise _NoMatch
for key, part in template.items():
if key in value:
_take(part, value[key], found)
elif not _placeholders(part): # a fixed key the node lacks
elif not _placeholders(part):
raise _NoMatch
return
if isinstance(template, list):
@@ -270,9 +259,9 @@ def _take(template: Any, value: Any, found: dict[str, Any]) -> None:
return
parts = list(_FORMAT.parse(template))
if any(name and ("[" in name or "." in name) for _, name, _, _ in parts):
raise _NoMatch # an answer's part (an account's drive): not read back
raise _NoMatch
if len(parts) == 1 and parts[0][0] == "" and parts[0][1] and not parts[0][2]:
_answer(found, parts[0][1], value) # the whole value, whatever its type
_answer(found, parts[0][1], value)
return
if not isinstance(value, str):
raise _NoMatch
@@ -297,8 +286,6 @@ def _answer(found: dict[str, Any], name: str, value: Any) -> None:
def recognise(node: dict[str, Any]) -> tuple[str, dict[str, Any]] | None:
"""The catalog type and answers that make a source node drawn by hand, when one makes
exactly it (its source, args, resource and reader): what lets the dialog edit it."""
made = {k: node.get(k) for k in ("source", "args", "resource", "then")}
made["args"] = made["args"] or {}
for type_id, spec in catalog().types.items():
@@ -325,9 +312,6 @@ def recognise(node: dict[str, Any]) -> tuple[str, dict[str, Any]] | None:
def _same_args(rendered: dict, drawn: dict, spec: "SourceType") -> bool:
"""The same arguments, but for those the type fills from its fields' defaults (rows per
batch, say) where the drawn node left them to the source: how much it reads at a time,
not what."""
defaults = {f"{{{n}}}": f.default for n, f in spec.fields.items() if f.default is not None}
for key, value in rendered.items():
if key in drawn:
+1 -7
View File
@@ -1,6 +1,3 @@
# The kinds of source the Conectar dialog offers (core.sources). Words are what the operator
# reads: plain Spanish, no jargon. Each type becomes one pipeline `Source` node.
groups:
database:
title: Base de datos
@@ -15,9 +12,6 @@ groups:
title: Web
description: Un sistema que entrega sus datos por internet (una API) o envía FHIR.
# The sign-in buttons. The app registration (client id and secret) is the site's IT's, set
# on the server as <ENV>_CLIENT_ID and <ENV>_CLIENT_SECRET (Microsoft also <ENV>_TENANT_ID,
# default "organizations"); `{tenant}` in an endpoint takes it.
providers:
microsoft:
title: Microsoft
@@ -249,7 +243,7 @@ types:
read_as: {label: Qué contienen, type: format, default: "persistance.readers:read_bytes"}
pattern: {label: Qué archivos tomar, default: "**/*", advanced: true}
source: "persistance.readers:fsspec_files"
args: # the signed-in user's own drive, by its id (msgraphfs single-drive mode)
args:
url: "msgd://{folder:path}"
file_glob: "{pattern}"
storage_options:
+24 -22
View File
@@ -1,18 +1,15 @@
"""TEA clinical parameters: the one place they are set. dbt reads them as vars, the measures
import them. Codes are the platform's (core.catalog)."""
from core import catalog
# The screening cohort: children whose first M-CHAT is at this age (completed months, from
# the age in months rounded to one decimal), in these windows.
AGE_GROUPS = [(16, 23), (24, 29), (30, 36)]
DAYS_PER_MONTH = 30.4375
FOLLOW_UP_WINDOWS = [1, 3, 6, 12] # months: the list's windows, as CaCu's and CaMa's
# A neurology note with one of these confirms the diagnosis (ICD-10, with the dot).
CONFIRMING_ICD10 = ["F84.0"]
NEUROLOGY = "pediatric_neurology" # the specialty of the notes the screening counts
NEUROLOGY = "pediatric_neurology"
PREVALENCE_AGE = (16, 36)
FOLLOW_UP_WINDOWS = (1, 3, 6, 12)
EEG_METRICS = ("posterior_rhythm", "spindles_n2", "spindles_n3", "paroxysmal_spikes",
"anteroposterior_gradient") # fmt: skip
# ADOS-2 calibrated severity (CSS): the lowest total reaching CSS 2..10, by module and
# algorithm (Module 1) and whether the child is under five. Items score 0 to 3; a 3 counts
# as 2. The values are approximate published ones, kept as data.
ADOS2_CSS = {
("module_1", "few_to_no_words", True): [4, 7, 11, 14, 16, 18, 20, 22, 24],
("module_1", "few_to_no_words", False): [6, 9, 12, 15, 17, 19, 21, 23, 25],
@@ -22,21 +19,26 @@ ADOS2_CSS = {
("module_2", None, False): [3, 6, 8, 10, 11, 13, 15, 17, 19],
("module_3", None, None): [2, 4, 7, 8, 9, 11, 13, 15, 17],
}
# Classification by CSS: below 3 no spectrum, 3-4 autism spectrum, 5 or more autism.
ADOS2_CLASSIFICATION = [("non_spectrum", 3), ("autism_spectrum", 5), ("autism", None)]
# The Module 1 items that only the "few to no words" algorithm prints.
FEW_TO_NO_WORDS_ITEMS = ["joint_attention_response", "intonation"]
SOCIAL_AFFECT_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",
ADOS2_ITEMS: list[str] = [
name for name, field in catalog.studies()["ados2"].fields.items()
if field.type == "number" and not name.endswith("_total")
] # fmt: skip
RESTRICTED_REPETITIVE_ITEMS = ["intonation", "stereotyped_language", "unusual_sensory_interest",
"hand_finger_mannerisms", "repetitive_interests"] # fmt: skip
def dbt_vars() -> dict:
"""What dbt reads (`var('tea')`)."""
return {k.lower(): v for k, v in globals().items() if k.isupper() and k != "ADOS2_CSS"}
return {
k.lower(): v
for k, v in globals().items()
if k.isupper() and k not in ("ADOS2_CSS", "ASSOCIATION_BIOMARKERS")
}
ASSOCIATION_BIOMARKERS = {
"spikes": "paroxysmal_spikes",
"spindles": "spindles_n2",
"posterior_rhythm": "posterior_rhythm",
"gradient": "anteroposterior_gradient",
}
+5 -9
View File
@@ -1,16 +1,12 @@
"""ADOS-2 scoring (pure): the calibrated severity score (CSS) and classification of one
evaluation from its items (core.tea). The total is the sum of the items given, a 3 counting
as 2; an evaluation without items in either domain is not scored."""
from datetime import date
from core import tea
from core.tea import ados2_items
TODDLER_BANDS = {True: (10, 16), False: (8, 14)} # 20 months or younger: (mild, severe) totals
TODDLER_BANDS = {True: (10, 16), False: (8, 14)}
def algorithm(row: dict) -> str | None:
"""Module 1's algorithm, from the items its report prints."""
if row.get("module") != "module_1":
return None
printed = any(row.get(i) is not None for i in tea.FEW_TO_NO_WORDS_ITEMS)
@@ -21,13 +17,13 @@ def total(row: dict) -> int | None:
def domain(items: list[str]) -> list[int]:
return [min(int(row[i]), 2) for i in items if row.get(i) is not None]
social = domain(tea.SOCIAL_AFFECT_ITEMS)
restricted = domain(tea.RESTRICTED_REPETITIVE_ITEMS)
module = row.get("module")
social = domain(ados2_items.domain(module, "AS"))
restricted = domain(ados2_items.domain(module, "CRR"))
return sum(social) + sum(restricted) if social and restricted else None
def score(row: dict, birth: date | None) -> tuple[int | None, str | None]:
"""(CSS, classification); (None, None) when it can't be scored."""
found, module = total(row), row.get("module")
if found is None or module is None:
return None, None
+291
View File
@@ -0,0 +1,291 @@
import re
from typing import NamedTuple
class Item(NamedTuple):
domain: str
subdomain: str
code: str
title: str
field: str
DOMAINS = {
"AS": "Afectación social (AS)",
"CRR": "Comportamiento restringido y repetitivo (CRR)",
}
COMMUNICATION = "communication"
RECIPROCAL = "reciprocal_social_interaction"
RESTRICTED = "restricted_repetitive_behaviors"
SUBDOMAINS = {
COMMUNICATION: "Comunicación",
RECIPROCAL: "Interacción social recíproca",
RESTRICTED: "Comportamientos restringidos y repetitivos",
}
ITEMS: dict[str, tuple[Item, ...]] = {
"toddler": (
Item(
"AS",
COMMUNICATION,
"A-2",
"Frecuencia de la vocalización espontánea dirigida a otros",
"vocalization_directed",
),
Item("AS", COMMUNICATION, "A-7", "Señalar", "pointing"),
Item("AS", COMMUNICATION, "A-8", "Gestos", "gestures"),
Item("AS", RECIPROCAL, "B-1", "Contacto visual inusual", "unusual_eye_contact"),
Item(
"AS", RECIPROCAL, "B-4", "Expresiones faciales dirigidas a otros", "facial_expressions"
),
Item(
"AS",
RECIPROCAL,
"B-5",
"Integración de la mirada y otras conductas durante las iniciaciones sociales",
"gaze_integration",
),
Item(
"AS",
RECIPROCAL,
"B-6",
"Disfrute compartido durante la interacción",
"shared_enjoyment",
),
Item("AS", RECIPROCAL, "B-7", "Respuesta al nombre", "response_to_name"),
Item("AS", RECIPROCAL, "B-8", "Ignorar", "ignoring"),
Item("AS", RECIPROCAL, "B-9", "Pedir", "requesting"),
Item("AS", RECIPROCAL, "B-12", "Mostrar", "showing"),
Item(
"AS",
RECIPROCAL,
"B-13",
"Iniciación espontánea de la atención conjunta",
"joint_attention_initiation",
),
Item(
"AS", RECIPROCAL, "B-14", "Respuesta a la atención conjunta", "joint_attention_response"
),
Item(
"AS",
RECIPROCAL,
"B-15",
"Características de las iniciaciones sociales",
"social_overtures_quality",
),
Item(
"AS",
RECIPROCAL,
"B-16b",
"Cantidad de las iniciaciones sociales/familiar o cuidador",
"social_overtures_caregiver",
),
Item("AS", RECIPROCAL, "B-18", "Calidad general de la relación", "rapport_quality"),
Item(
"CRR",
RESTRICTED,
"A-3",
"Entonación de las vocalizaciones o verbalizaciones",
"intonation",
),
Item(
"CRR",
RESTRICTED,
"D-1",
"Interés sensorial inusual en los materiales de juego o en las personas",
"unusual_sensory_interest",
),
Item(
"CRR",
RESTRICTED,
"D-2",
"Movimientos de manos y dedos / postura",
"hand_finger_mannerisms",
),
Item(
"CRR",
RESTRICTED,
"D-5",
"Intereses inusualmente repetitivos o comportamientos estereotipados",
"repetitive_interests",
),
),
"module_1": (
Item(
"AS",
COMMUNICATION,
"A-2",
"Frecuencia de la vocalización espontánea dirigida a otros",
"vocalization_directed",
),
Item("AS", COMMUNICATION, "A-7", "Señalar", "pointing"),
Item("AS", COMMUNICATION, "A-8", "Gestos", "gestures"),
Item("AS", RECIPROCAL, "B-1", "Contacto visual inusual", "unusual_eye_contact"),
Item(
"AS", RECIPROCAL, "B-3", "Expresiones faciales dirigidas a otros", "facial_expressions"
),
Item(
"AS",
RECIPROCAL,
"B-4",
"Integración de la mirada y otras conductas durante las iniciaciones sociales",
"gaze_integration",
),
Item(
"AS",
RECIPROCAL,
"B-5",
"Disfrute compartido durante la interacción",
"shared_enjoyment",
),
Item("AS", RECIPROCAL, "B-9", "Mostrar", "showing"),
Item(
"AS",
RECIPROCAL,
"B-10",
"Iniciación espontánea de la atención conjunta",
"joint_attention_initiation",
),
Item(
"AS", RECIPROCAL, "B-11", "Respuesta a la atención conjunta", "joint_attention_response"
),
Item(
"AS",
RECIPROCAL,
"B-12",
"Características de las iniciaciones sociales",
"social_overtures_quality",
),
Item(
"CRR",
RESTRICTED,
"A-3",
"Entonación de las vocalizaciones o verbalizaciones",
"intonation",
),
Item(
"CRR",
RESTRICTED,
"A-5",
"Uso estereotipado o idiosincrásico de palabras o frases",
"stereotyped_language",
),
Item(
"CRR",
RESTRICTED,
"D-1",
"Interés sensorial inusual en los materiales de juego o en las personas",
"unusual_sensory_interest",
),
Item(
"CRR",
RESTRICTED,
"D-2",
"Manierismos de manos y dedos y otros manierismos complejos",
"hand_finger_mannerisms",
),
Item(
"CRR",
RESTRICTED,
"D-4",
"Intereses inusualmente repetitivos o comportamientos estereotipados",
"repetitive_interests",
),
),
"module_2": (
Item("AS", COMMUNICATION, "A-6", "Señalar", "pointing"),
Item(
"AS",
COMMUNICATION,
"A-7",
"Gestos descriptivos, convencionales, instrumentales o informativos",
"gestures",
),
Item("AS", RECIPROCAL, "B-1", "Contacto visual inusual", "unusual_eye_contact"),
Item(
"AS", RECIPROCAL, "B-2", "Expresiones faciales dirigidas a otros", "facial_expressions"
),
Item(
"AS",
RECIPROCAL,
"B-3",
"Disfrute compartido durante la interacción",
"shared_enjoyment",
),
Item("AS", RECIPROCAL, "B-5", "Mostrar", "showing"),
Item(
"AS",
RECIPROCAL,
"B-6",
"Iniciación espontánea de la atención conjunta",
"joint_attention_initiation",
),
Item(
"AS",
RECIPROCAL,
"B-8",
"Características de las iniciaciones sociales",
"social_overtures_quality",
),
Item(
"AS",
RECIPROCAL,
"B-11",
"Cantidad de comunicación social recíproca",
"reciprocal_communication",
),
Item("AS", RECIPROCAL, "B-12", "Calidad general de la relación", "rapport_quality"),
Item(
"CRR",
RESTRICTED,
"A-4",
"Uso estereotipado o idiosincrásico de palabras o frases",
"stereotyped_language",
),
Item(
"CRR",
RESTRICTED,
"D-1",
"Interés sensorial inusual en los materiales de juego o en las personas",
"unusual_sensory_interest",
),
Item(
"CRR",
RESTRICTED,
"D-2",
"Manierismos de manos y dedos y otros manierismos complejos",
"hand_finger_mannerisms",
),
Item(
"CRR",
RESTRICTED,
"D-4",
"Intereses inusualmente repetitivos o comportamientos estereotipados",
"repetitive_interests",
),
),
}
def domain(module: str, name: str) -> list[str]:
return [item.field for item in ITEMS.get(module, ()) if item.domain == name]
def pattern(field: str) -> str:
codes: dict[str, list[str]] = {}
for items in ITEMS.values():
for item in items:
if item.field == field and item.code not in codes.setdefault(item.title, []):
codes[item.title].append(item.code)
alternatives = []
for title, found in codes.items():
code = found[0] if len(found) == 1 else f"(?:{'|'.join(found)})"
words = r"\s+".join(re.escape(word) for word in title.split())
alternatives.append(f"(?:{code}\\s+)?{words}")
body = alternatives[0] if len(alternatives) == 1 else f"(?:{'|'.join(alternatives)})"
return f"(?m)^{body}\\s+([0-3])\\s*$"
def patterns() -> dict[str, str]:
fields = dict.fromkeys(item.field for items in ITEMS.values() for item in items)
return {field: pattern(field) for field in fields}
-120
View File
@@ -1,120 +0,0 @@
"""What the EEG–ADOS-2 association relates (pure configuration, models.tea.association):
each EEG biomarker's deviation from its age curve (z) in a zone, against the ADOS-2 items
that zone is linked to, or against the calibrated severity (CSS).
An item counts as altered at ALTERED or more (its algorithm score: 0 to 2, a 3 counting as
2, and 7, 8 or 9, "not applicable", as 0); the CSS at CSS_HIGH or more. Items are numbered
as the old platform numbered them, which names each outcome `ados2_item_NN`."""
from core import tea
# The 22 items, in their number's order, and the modules that administer each.
ITEMS = {
1: ("vocalization_directed", ("toddler", "module_1")),
2: ("pointing", ("toddler", "module_1", "module_2")),
3: ("gestures", ("toddler", "module_1", "module_2")),
4: ("unusual_eye_contact", ("toddler", "module_1", "module_2")),
5: ("facial_expressions", ("toddler", "module_1", "module_2")),
6: ("gaze_integration", ("toddler", "module_1")),
7: ("shared_enjoyment", ("toddler", "module_1", "module_2")),
8: ("response_to_name", ("toddler",)),
9: ("ignoring", ("toddler",)),
10: ("requesting", ("toddler",)),
11: ("showing", ("toddler", "module_1", "module_2")),
12: ("joint_attention_initiation", ("toddler", "module_1", "module_2")),
13: ("joint_attention_response", ("toddler", "module_1")),
14: ("social_overtures_quality", ("toddler", "module_1", "module_2")),
15: ("social_overtures_caregiver", ("toddler",)),
16: ("reciprocal_communication", ("module_2",)),
17: ("rapport_quality", ("toddler", "module_2")),
18: ("intonation", ("toddler", "module_1")),
19: ("stereotyped_language", ("module_1", "module_2")),
20: ("unusual_sensory_interest", ("toddler", "module_1", "module_2")),
21: ("hand_finger_mannerisms", ("toddler", "module_1", "module_2")),
22: ("repetitive_interests", ("toddler", "module_1", "module_2")),
}
assert [n for n, _ in ITEMS.values()] == tea.SOCIAL_AFFECT_ITEMS + tea.RESTRICTED_REPETITIVE_ITEMS
# The items each zone's spikes are related to.
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)
# Each biomarker's EEG metric (models.tea.eeg.biomarkers.CODES).
BIOMARKERS = {
"spikes": "paroxysmal_spikes",
"spindles": "spindles_n2",
"posterior_rhythm": "posterior_rhythm",
"gradient": "anteroposterior_gradient",
}
ZONED = ("spikes", "spindles")
CSS = "CSS"
CSS_HIGH = 8
ALTERED = 1
NOT_APPLICABLE = (7, 8, 9)
# Below this many children with item scores the association is fitted on the CSS only.
MIN_ITEM_CHILDREN = 10
ADJUST = ("age_months", "module")
def item_code(n: int) -> str:
return f"ados2_item_{n:02d}"
def pairs(level: str) -> list[dict]:
"""Every (biomarker, zone, predictor, outcome) the association fits at `level`: `item`
(each zone against its items) or `domain` (against the CSS)."""
def outcomes(numbers) -> list[tuple[str, object]]:
return [("item", n) for n in numbers] if level == "item" else [("domain", CSS)]
out = [
{
"biomarker": "spikes",
"zone": zone,
"predictor": f"z_spikes_{zone}",
"kind": k,
"outcome": o,
}
for zone, numbers in ZONE_ITEMS.items()
for k, o in outcomes(numbers)
]
out += [
{
"biomarker": "spindles",
"zone": zone,
"predictor": f"z_spindles_{zone}",
"kind": "domain",
"outcome": CSS,
}
for zone in SPINDLE_ZONES
]
out += [
{
"biomarker": "posterior_rhythm",
"zone": "posterior",
"predictor": "z_posterior_rhythm",
"kind": k,
"outcome": o,
}
for k, o in outcomes(RHYTHM_ITEMS)
]
out.append(
{
"biomarker": "gradient",
"zone": "global",
"predictor": "z_gradient",
"kind": "domain",
"outcome": CSS,
}
)
return out
+19
View File
@@ -0,0 +1,19 @@
import re
MIN_GROUP = 5
FORBIDDEN = re.compile(r"eeg_\d+|\d{4}-\d{2}-\d{2}|[A-Za-z]:\\|/Users/|/home/", re.IGNORECASE)
def guard(version: dict) -> list[str]:
problems = []
n = version["metrics"].get("n_reference")
if n is None:
problems.append("cannot tell the reference group size (no n_reference metric)")
elif n < MIN_GROUP:
problems.append(f"reference group of {n:g} children is under {MIN_GROUP}")
cutoff = version["params"].get("as_of", "")
for field, label in (("params", "param"), ("tags", "tag"), ("reports", "report")):
for key, value in version[field].items():
if match := FORBIDDEN.search(value.replace(cutoff, "")):
problems.append(f"{label} {key} holds a study code, date or path ({match[0]!r})")
return problems
+212
View File
@@ -0,0 +1,212 @@
import hashlib
from fhir.resources.R4B.diagnosticreport import DiagnosticReport
from fhir.resources.R4B.observation import Observation
from fhir.resources.R4B.riskassessment import RiskAssessment
from core import catalog, fhir, tea
from core.measures import as_day
from core.tea import ados2, ados2_items
INTERPRETATION = "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation"
SITE_SYSTEMS = {"electrode": "eeg-electrode-10-20", "zone": "tea-eeg-zone"}
BIOMARKER_METRIC = {
"spikes": "paroxysmal_spikes",
"spindles": "spindles_n2",
"posterior_rhythm": "posterior_rhythm",
"gradient": "anteroposterior_gradient",
}
def _interpretation(code):
return [{"coding": [{"system": INTERPRETATION, "code": code}]}]
def _extensions(row, fields):
return [fhir.ext(name, kind, row[key]) for key, name, kind in fields
if row.get(key) is not None] # fmt: skip
def _ados2_id(person, day):
return f"ados2-{person}-{fhir._day(day)}"
def ados2_observation(row, birth):
day = fhir._day(row["evaluation_date"])
spec = catalog.studies()["ados2"]
module = row.get("module")
items = {item.field: item for item in ados2_items.ITEMS.get(module, ())}
components = []
for name in ("module", *items, *(i for i in tea.ADOS2_ITEMS if i not in items)):
value = row.get(name)
component = {"code": fhir.concept("catalog-field", f"ados2.{name}")}
if item := items.get(name):
component["code"]["coding"].append(fhir.coding(f"ados2-item-{module}", item.code))
component["code"]["text"] = item.title
component["extension"] = [
fhir.ext("ados2-domain", "Coding", fhir.coding("ados2-domain", item.domain)),
fhir.ext("ados2-subdomain", "Coding",
fhir.coding("ados2-subdomain", item.subdomain)),
] # fmt: skip
if value is not None:
component.update(fhir._value(spec.fields[name], value))
components.append(component)
css, classification = ados2.score(row, birth)
return Observation(
id=_ados2_id(row["person_id"], day),
status="final",
code=fhir.concept("study", "ados2"),
subject=fhir.subject(row["person_id"]),
effectiveDateTime=day,
valueInteger=css,
interpretation=[fhir.concept("tea-ados2-classification", classification)]
if classification
else None,
component=components,
)
def eeg_study_id(person_id: str, study_date) -> str:
return f"{person_id}|{as_day(study_date)}"
def _eeg_report_id(person_id, study_date) -> str:
key = eeg_study_id(person_id, study_date)
return f"eeg-{hashlib.sha256(key.encode()).hexdigest()[:16]}"
def eeg_report(row, results):
valid = row["valid"]
quality = "not_analyzed" if valid is None else "good" if valid else "bad"
conclusions = [fhir.concept("tea-eeg-quality", quality)]
if valid is not None:
conclusions.append(fhir.concept("tea-eeg-validity", "valid" if valid else "not_valid"))
extensions = _extensions(row, (
("duration_min", "eeg-duration-min", "decimal"),
("age_months", "eeg-age-months", "decimal"),
("channels", "eeg-channels", "integer"),
)) # fmt: skip
return DiagnosticReport(
id=_eeg_report_id(row["person_id"], row["study_date"]),
status="registered" if valid is None else "final",
code=fhir.concept("study", "eeg"),
subject=fhir.subject(row["person_id"]),
effectiveDateTime=fhir._day(row["study_date"]),
conclusionCode=conclusions,
extension=extensions or None,
result=[{"reference": f"Observation/{r.id}"} for r in results] or None,
)
def _quantity(value, unit=None):
return {"value": value, **({"unit": unit} if unit else {})}
def _eeg_observation(row, system, *key, **fields):
return Observation(
id=fhir._id(system, row["person_id"], row["study_date"], row["edf"], *key),
status="final",
code=fhir.concept(system, row["code"]),
subject=fhir.subject(row["person_id"]),
effectiveDateTime=fhir._day(row["study_date"]),
**fields,
)
def eeg_check(row):
electrode = row.get("electrode")
unit = row.get("unit")
value = row.get("value")
bounds = {key: _quantity(row[key], unit) for key in ("low", "high")
if row.get(key) is not None} # fmt: skip
return _eeg_observation(
row, "tea-eeg-check", row["code"], electrode,
valueQuantity=_quantity(value, unit) if value is not None else None,
valueString=row.get("text") if value is None else None,
referenceRange=[bounds] if bounds else None,
interpretation=_interpretation("A" if row["abnormal"] else "N"),
extension=[fhir.ext("eeg-check-decisive", "boolean", row["decisive"])],
component=[{"code": fhir.concept(SITE_SYSTEMS["electrode"], electrode)}]
if electrode else None,
) # fmt: skip
def _curve_extensions(row, *, centiles=False):
if row.get("model") is None:
return None
extensions = _extensions(
row, (("z", "eeg-z", "decimal"), ("outside", "eeg-outside", "integer"))
)
if centiles:
extensions.append(fhir.ext("eeg-model", "string", row["model"]))
parts = [{"url": key, "valueDecimal": row[key]} for key in ("p5", "median", "p95")
if row.get(key) is not None] # fmt: skip
if parts:
extensions.append({"url": fhir.EXTENSION + "curve-centiles", "extension": parts})
return extensions or None
def eeg_metric(row, regions):
components = [
{
"code": fhir.concept(SITE_SYSTEMS[site["kind"]], site["site"]),
"valueQuantity": _quantity(site["value"]) if site["value"] is not None else None,
"extension": _curve_extensions(site),
}
for site in regions
]
outside = row.get("outside") if row.get("model") is not None else None
return _eeg_observation(
row, "tea-eeg-metric", row["code"],
valueQuantity=_quantity(row["value"]) if row["value"] is not None else None,
component=components or None,
extension=_curve_extensions(row, centiles=True),
interpretation=_interpretation({-1: "L", 0: "N", 1: "H"}[outside])
if outside is not None else None,
) # fmt: skip
def association_risk(rows):
def order(row):
metric = BIOMARKER_METRIC[row["biomarker"]]
q = row["q"]
return not row.get(f"alt_{metric}"), q if q is not None else float("inf"), row["pair"]
head, *other = sorted(rows, key=order)
predictions = []
for index, row in enumerate((head, *other)):
extensions = _extensions(row, (
("odds_ratio", "association-odds-ratio", "decimal"),
("ci_low", "association-ci-low", "decimal"),
("ci_high", "association-ci-high", "decimal"),
("q", "association-q", "decimal"),
("reference_probability", "association-reference-probability", "decimal"),
("same_direction", "association-same-direction", "boolean"),
)) # fmt: skip
extensions.append(fhir.ext("association-reliable", "boolean", row["n"] >= 20))
if index == 0:
extensions.append(fhir.ext("association-headline", "boolean", True))
predictions.append(
{
"outcome": fhir.concept("tea-association", row["pair"]),
"probabilityDecimal": row["probability"],
"extension": extensions,
}
)
person = head["person_id"]
basis = [{"reference": f"DiagnosticReport/{_eeg_report_id(person, head['study_date'])}"}]
if head["evaluation_date"] is not None:
basis.append({"reference": f"Observation/{_ados2_id(person, head['evaluation_date'])}"})
return RiskAssessment(
id=f"tea-association-{person}",
status="final",
subject=fhir.subject(person),
occurrenceDateTime=fhir._day(head["study_date"]),
basis=basis,
prediction=predictions,
extension=_extensions(head, (
("model", "association-model-version", "string"),
("n_cohort", "association-cohort", "integer"),
("level", "association-level", "string"),
)),
) # fmt: skip
+94 -81
View File
@@ -1,15 +1,5 @@
"""TEA's follow-up list (pure): the children of the screening cohort active in the window, where
each stands on the route by the cut-off day, and their EEG.
- status (the route): mchat_only, psychology (ADOS-2), neuropediatrics (a neurology note), eeg
(a good EEG after it);
- case: confirmed (the neurologist confirmed TEA), not_confirmed, or in_process;
- EEG: the study EEG is her first valid one known by the cut-off, else her latest; its status
is no_valid_eeg without a valid one, abnormal when any of its metrics falls outside the age
curve's band (its alterations, each `<metric>:<above|below>`), else normal.
A child is on the list when any step of hers happened within the window."""
from datetime import date
from decimal import Decimal, InvalidOperation
from core import tea
from core.measures import as_day
@@ -19,86 +9,109 @@ WINDOWS = tea.FOLLOW_UP_WINDOWS
SORTS = ("-recent",)
DEFAULT_HORIZON = None
STATUS_SYSTEM = "tea-follow-up-status"
PROCEDURES: tuple[str, ...] = ()
REPORT_FACTS: dict[str, str] = {}
STEPS = (("psychology_date", "psychology"), ("neuro_date", "neuropediatrics"),
("eeg_date", "eeg")) # fmt: skip
DATES = ("mchat_date", "psychology_date", "neuro_date", "confirmed_date", "not_confirmed_date",
"eeg_date") # fmt: skip
PROCEDURES = ()
REPORT_FACTS = {}
def _by(day, cutoff: date) -> date | None:
found = as_day(day)
return found if found is not None and found <= cutoff else None
def stage(row: dict, cutoff: date) -> str:
reached = "mchat_only"
for column, name in STEPS:
if _by(row.get(column), cutoff):
reached = name
return reached
def case(row: dict, cutoff: date) -> str:
if _by(row.get("confirmed_date"), cutoff):
return "confirmed"
if _by(row.get("not_confirmed_date"), cutoff):
return "not_confirmed"
return "in_process"
FILTERS = {
"tea-step": ("token", "step", ("eeg", "neurology", "psychology", "mchat_only")),
"tea-case": ("token", "case", ("confirmed", "in_process", "not_confirmed")),
"tea-eeg-result": ("token", "eeg_result", ("abnormal", "normal", "no_valid_eeg", "not_scored")),
"tea-model": ("token", "eeg_scored", ("yes", "no")),
"tea-age-group": ("token", "age_group", ("16-23", "24-29", "30-36", "no_data")),
"tea-sex": ("token", "sex", ("female", "male")),
"tea-alteration": ("token", None, tea.EEG_METRICS),
"tea-mchat": ("number", "mchat_score", ()),
"tea-css": ("number", "css", ()),
}
def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
"""From each child's screening row joined to her EEGs and their metrics outside the band
(one row per child, EEG and such metric), who is on the list, most recent step first."""
children: dict[str, dict] = {}
eegs: dict[str, dict[str, dict]] = {}
for row in rows:
person = row["person_id"]
if not _by(row.get("mchat_date"), cutoff):
continue
children.setdefault(person, row)
studied = _by(row.get("eeg_study_date"), cutoff)
if row.get("eeg_id") and studied:
eeg = eegs.setdefault(person, {}).setdefault(
row["eeg_id"], {"date": studied, "valid": row.get("valid"), "altered": set()}
)
if row.get("metric") and row.get("outside"):
side = "above" if row["outside"] > 0 else "below"
eeg["altered"].add(f"{row['metric']}:{side}")
out = []
for person, row in children.items():
steps = [d for c in DATES if (d := _by(row.get(c), cutoff))]
recent = max(steps)
if recent < start:
for row in rows:
begins, ends = as_day(row["start_date"]), as_day(row["end_date"])
if begins > cutoff or (ends is not None and ends < start):
continue
mine = sorted(eegs.get(person, {}).values(), key=lambda e: e["date"])
valid = [e for e in mine if e["valid"]]
study = valid[0] if valid else (mine[-1] if mine else None)
if not valid:
eeg_status, altered = "no_valid_eeg", []
confirmed = as_day(row.get("confirmed_date"))
not_confirmed = as_day(row.get("not_confirmed_date"))
if confirmed is not None and confirmed <= cutoff:
case = "confirmed"
elif not_confirmed is not None and not_confirmed <= cutoff:
case = "not_confirmed"
else:
altered = sorted(study["altered"])
eeg_status = "abnormal" if altered else "normal"
css = None
if row.get("module") and as_day(row.get("evaluation_date")):
evaluated = {**row, "evaluation_date": as_day(row["evaluation_date"])}
css, _ = ados2.score(evaluated, as_day(row.get("birth_date")))
out.append({
"person_id": person, "birth_date": row.get("birth_date"),
"status": stage(row, cutoff), "priority": None, "recent": recent,
"age_group": row.get("age_group"), "case": case(row, cutoff),
"eeg_status": eeg_status, "alterations": altered,
"last_eeg": mine[-1]["date"] if mine else None,
"mchat_score": row.get("score"), "ados2_css": css,
}) # fmt: skip
return sorted(out, key=lambda r: (-r["recent"].toordinal(), r["person_id"]))
case = "in_process"
css, classification = None, None
if evaluated := as_day(row.get("ados2_date")):
evaluation = {item: row.get(f"ados2_{item}") for item in tea.ADOS2_ITEMS}
evaluation.update(module=row.get("ados2_module"), evaluation_date=evaluated)
css, classification = ados2.score(evaluation, as_day(row["birth_date"]))
out.append(
{
**row,
"priority": None,
"recent": row["step_date"],
"case": case,
"css": css,
"classification": classification,
"alterations": sum(bool(row.get(f"alt_{m}")) for m in tea.EEG_METRICS),
}
)
return sorted(out, key=lambda row: (-as_day(row["recent"]).toordinal(), row["person_id"]))
def status(row: dict, cutoff: date) -> None:
"""A child's status exists only on the list."""
return None
def status(row: dict, cutoff: date) -> str | None:
return row.get("status")
def ordered(rows: list[dict], sort: str, risks: dict, horizon) -> list[dict]:
return rows
def _limit(name: str, value: str) -> tuple[str, Decimal]:
prefix = value[:2]
try:
limit = Decimal(value[2:])
if prefix in ("ge", "le") and limit.is_finite():
return prefix, limit
except InvalidOperation:
pass
raise ValueError(f"invalid {name} value: {value}")
def matches(row: dict, params: dict[str, list[str]]) -> bool:
matched = True
for name, values in params.items():
kind, field, allowed = FILTERS[name]
actual = row.get(field)
if kind == "number":
for value in values:
prefix, limit = _limit(name, value)
if actual is None or (actual < limit if prefix == "ge" else actual > limit):
matched = False
continue
tokens = [token for value in values for token in value.split(",")]
for token in tokens:
if token not in allowed:
raise ValueError(f"invalid {name} value: {token}")
if name == "tea-alteration":
actual = any(row.get(f"alt_{token}") for token in tokens)
elif name == "tea-model":
actual = ("yes" if actual else "no") in tokens
else:
actual = actual in tokens
matched = matched and actual
return matched
def summary(rows: list[dict]) -> dict:
valid = sum(row["eeg_id"] is not None for row in rows)
return {
"valid": valid,
"not_valid": len(rows) - valid,
"normal": sum(row["eeg_result"] == "normal" for row in rows),
"abnormal": sum(row["eeg_result"] == "abnormal" for row in rows),
"by_alteration": [
{"alteration": metric, "patients": count}
for metric in tea.EEG_METRICS
if (count := sum(bool(row.get(f"alt_{metric}")) for row in rows))
],
}
+139 -33
View File
@@ -1,20 +1,16 @@
"""TEA's measures (`core.measures` evaluates them), over gold's screening chain: one row per
child of the cohort (`gold.tea_screening`) with the day she reached each step, and her EEGs
(`gold.tea_eegs`).
A child is on the books from her first M-CHAT until the period after her chain ended with a
good EEG; in a period she is in the latest step, and diagnosis state, reached by its end."""
from core.measures import (
NO_DATA,
AtEnd,
Composition,
Measure,
Proportion,
StatusComposition,
StatusDuration,
StatusProportion,
as_day,
reached,
)
from core.tea import EEG_METRICS
DIAGNOSIS = AtEnd("mchat_date", "eeg_date", (
("in_process", "mchat_date"), ("not_confirmed", "not_confirmed_date"),
@@ -24,36 +20,146 @@ STEPS = AtEnd("mchat_date", "eeg_date", (
("mchat_only", "mchat_date"), ("psychology", "psychology_date"),
("neuropediatrics", "neuro_date"), ("eeg", "eeg_date"),
)) # fmt: skip
PREVALENCE = AtEnd("entry_date", "exit_date", (
("in_population", "entry_date"), ("confirmed", "confirmed_date"),
), exit_inclusive=False) # fmt: skip
AGE = ("age_group", lambda row, p: row["age_group"])
SEX = ("sex", lambda row, p: row.get("sex") or NO_DATA)
AGE_SEX = ("age_sex", lambda row, p: f"{row['age_group']}|{row.get('sex') or NO_DATA}")
ALTERATIONS = ("alteration", {m: lambda row, m=m: bool(row[f"alt_{m}"]) for m in EEG_METRICS})
CONFIRMED = lambda row, state, p: state == "confirmed" # noqa: E731
MEASURES = {m.id: m for m in [
Measure("M21_DIAGNOSTICADOS_CON_EEG", "Pacientes con diagnóstico de TEA con EEG",
MEASURES = {
m.id: m
for m in [
Measure(
"M21_DIAGNOSTICADOS_CON_EEG",
"Porcentaje de pacientes con diagnóstico de TEA con EEG",
"screening",
StatusProportion(DIAGNOSIS, CONFIRMED,
lambda row, s, p: reached(row, "eeg_date", p), strata=(AGE,)),
"increase"),
Measure("M22_DIAGNOSTICADOS_SIN_EEG", "Pacientes con diagnóstico de TEA sin EEG",
StatusProportion(
DIAGNOSIS,
CONFIRMED,
lambda row, s, p: reached(row, "eeg_date", p),
strata=(AGE, AGE_SEX),
),
"increase",
description=(
"Of the children with a confirmed diagnosis at period end, how many already have a "
"good-quality EEG. By age group at the first M-CHAT."
),
),
Measure(
"M22_DIAGNOSTICADOS_SIN_EEG",
"Porcentaje de pacientes con diagnóstico de TEA sin EEG",
"screening",
StatusProportion(DIAGNOSIS, CONFIRMED,
lambda row, s, p: not reached(row, "eeg_date", p), strata=(AGE,)),
"decrease"),
Measure("M23_PACIENTES_EVALUADOS", "Pacientes evaluados por resultado diagnóstico",
StatusProportion(
DIAGNOSIS,
CONFIRMED,
lambda row, s, p: not reached(row, "eeg_date", p),
strata=(AGE, AGE_SEX),
),
"decrease",
description=("The complement of M21."),
),
Measure(
"M23_PACIENTES_EVALUADOS",
"Pacientes evaluados por resultado diagnóstico",
"screening",
StatusComposition(DIAGNOSIS, admit=lambda s: s in ("confirmed", "in_process"))),
Measure("M24_CONFIRMACION_DIAGNOSTICO", "Confirmación diagnóstica", "screening",
StatusProportion(DIAGNOSIS, lambda row, s, p: s in ("confirmed", "in_process"),
CONFIRMED, strata=(AGE,)),
"increase"),
Measure("M25_DIAS_MCHAT_DIAGNOSTICO", "Días de M-CHAT a diagnóstico positivo", "screening",
StatusDuration(STEPS, "days_mchat_confirmed", "confirmed_date"), "decrease"),
Measure("M26_DIAS_MCHAT_ADOS2", "Días de M-CHAT a ADOS-2", "screening",
StatusDuration(STEPS, "days_mchat_psychology", "psychology_date"), "decrease"),
Measure("M27_DIAS_ADOS2_DIAGNOSTICO", "Días de ADOS-2 a valoración neuropediátrica",
StatusComposition(
DIAGNOSIS, admit=lambda s: s in ("confirmed", "in_process"), strata=(SEX,)
),
description=(
"Children in the screening during the period by result: confirmed (a "
"neuropediatrics note with F84.0) or in process."
),
),
Measure(
"M24_CONFIRMACION_DIAGNOSTICO",
"Porcentaje de confirmación diagnóstica",
"screening",
StatusDuration(STEPS, "days_psychology_neuro", "neuro_date"), "decrease"),
Measure("M28_CASOS_POR_ESTADO", "Casos por estatus", "screening", StatusComposition(STEPS)),
Measure("M29_CALIDAD_EEG", "Calidad del EEG", "eegs",
Composition(lambda r: (as_day(r["study_date"]),), lambda r: r["quality"],
unit="eeg_id", date="study_date")),
]} # fmt: skip
StatusProportion(
DIAGNOSIS,
lambda row, s, p: s in ("confirmed", "in_process"),
CONFIRMED,
strata=(AGE, SEX, AGE_SEX),
),
"increase",
description=(
"Of the children confirmed or in process at period end, how many are confirmed."
),
),
Measure(
"M25_DIAS_MCHAT_DIAGNOSTICO",
"Días de M-CHAT a diagnóstico positivo",
"screening",
StatusDuration(STEPS, "days_mchat_confirmed", "confirmed_date"),
"decrease",
description=(
"Calendar days from the first M-CHAT to the neuropediatrics note with F84.0."
),
),
Measure(
"M26_DIAS_MCHAT_ADOS2",
"Días de M-CHAT a ADOS-2",
"screening",
StatusDuration(STEPS, "days_mchat_psychology", "psychology_date"),
"decrease",
description=(
"Calendar days from the first M-CHAT to the psychology note with the ADOS-2."
),
),
Measure(
"M27_DIAS_ADOS2_DIAGNOSTICO",
"Días de ADOS-2 a diagnóstico",
"screening",
StatusDuration(STEPS, "days_psychology_neuro", "neuro_date"),
"decrease",
description=("Calendar days from the psychology note to the neuropediatrics note."),
),
Measure(
"M28_CASOS_POR_ESTADO",
"Casos por estatus",
"screening",
StatusComposition(STEPS),
description=("Children in the screening during the period, by status."),
),
Measure(
"M29_CALIDAD_EEG",
"Calidad del EEG",
"eegs",
Composition(
lambda r: (as_day(r["study_date"]),),
lambda r: r["quality"],
unit="eeg_id",
date="study_date",
),
description=(
"EEGs done in the period for cohort children: good if the analysis found it valid, "
"bad if not, and those not yet analysed."
),
),
Measure(
"M30_RESULTADO_EEG",
"Porcentaje de EEG normal y anormal",
"alterations",
Proportion(
lambda row: bool(row["altered"]), date="study_date", overlaps=(ALTERATIONS,)
),
"decrease",
description=(
"Of the children whose first good EEG falls in the period, how many have an "
"alteration. One group per alteration. Hidden until the alterations are validated."
),
),
Measure(
"M31_PREVALENCIA",
"Prevalencia registrada de TEA",
"prevalence",
StatusComposition(PREVALENCE, strata=(SEX,)),
description=(
"Every child loaded on the platform, with or without M-CHAT, aged 16 to 36 months "
"during the period, by whether they were confirmed at its end."
),
),
]
}
+3 -22
View File
@@ -1,4 +1,3 @@
# One Python image for the API, the Dagster webserver and the Dagster daemon.
FROM python:3.12-slim AS app
RUN apt-get update \
&& apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-spa ghostscript \
@@ -8,40 +7,22 @@ COPY --from=ghcr.io/astral-sh/uv:0.12.21 /uv /bin/uv
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy UV_PROJECT_ENVIRONMENT=/venv PATH=/venv/bin:$PATH
WORKDIR /app
COPY . .
# Optional extras a machine opts into (`--extra dask` where a Dask cluster runs the batches).
ARG EXTRAS=""
RUN uv sync --frozen --no-dev $EXTRAS
RUN uv sync --frozen --no-dev
ENV ISSSTELEON_DATA=/data DAGSTER_HOME=/data/dagster DLT_DATA_DIR=/data/dlt
# The same image plus the dev tools: what CI and `docker compose run --rm test` run.
# The HL7 validator is pinned by checksum; its FHIR 4.3.0 packages are fetched here, once,
# so tests validate offline.
FROM app AS test
RUN apt-get update \
&& apt-get install -y --no-install-recommends default-jre-headless \
&& rm -rf /var/lib/apt/lists/*
ADD --checksum=sha256:9dfe9f305b0f9389eceade2a4a1c9a2740d7b0e614066fdf07a78b571c76d92f \
https://github.com/hapifhir/org.hl7.fhir.core/releases/download/7.0.5/validator_cli.jar \
/opt/fhir/validator_cli.jar
RUN echo '{"resourceType":"Basic","code":{"text":"warm-up"}}' > /tmp/warm.json \
&& java -jar /opt/fhir/validator_cli.jar /tmp/warm.json -version 4.3.0 -tx n/a > /dev/null \
&& rm /tmp/warm.json
ENV FHIR_VALIDATOR_JAR=/opt/fhir/validator_cli.jar
# Synthea, pinned: seeded synthetic patients sent through the FHIR door in tests.
ADD --checksum=sha256:ed43c20ad40ba5c3bc724503a5af032715fe3c491620b766148e7c2361e6ecc1 \
https://github.com/synthetichealth/synthea/releases/download/v4.0.0/synthea-with-dependencies.jar \
/opt/synthea/synthea.jar
ENV SYNTHEA_JAR=/opt/synthea/synthea.jar
RUN uv sync --frozen
# The pages (-m webapp) run in CI's web job, which has Node and a browser.
CMD ["pytest", "-q", "-rs", "-m", "not webapp"]
CMD ["pytest", "-q", "-rs"]
# A Dask worker for testing on a cluster (not part of the product): the app's Python and code
# with the `dask` extra, run as the cluster runs its workers (user dask, one thread per math
# library). The cluster gives the command (`dask worker <scheduler>`).
FROM app AS dask-worker
RUN uv sync --frozen --no-dev --extra dask \
&& useradd --uid 10001 --create-home dask
RUN useradd --uid 10001 --create-home dask
ENV OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1
WORKDIR /home/dask
USER dask
+12 -2
View File
@@ -1,4 +1,3 @@
{# Whole days from `a` to `b` (dates), on every engine the platform runs on. #}
{% macro days_between(a, b) -%}
{{ return(adapter.dispatch('days_between', 'isssteleon')(a, b)) }}
{%- endmacro %}
@@ -11,7 +10,18 @@
cast(julianday({{ b }}) - julianday({{ a }}) as integer)
{%- endmacro %}
{# The run's as-of date: `var('as_of')` when given, else the day dbt runs. #}
{% macro add_days(d, n) -%}
{{ return(adapter.dispatch('add_days', 'isssteleon')(d, n)) }}
{%- endmacro %}
{% macro default__add_days(d, n) -%}
(cast({{ d }} as date) + {{ n }})
{%- endmacro %}
{% macro sqlite__add_days(d, n) -%}
date({{ d }}, '+' || ({{ n }}) || ' days')
{%- endmacro %}
{% macro as_of() -%}
'{{ var("as_of", run_started_at.strftime("%Y-%m-%d")) }}'
{%- endmacro %}
-3
View File
@@ -1,6 +1,3 @@
{# The first event of `kind` after each unit's `start` (on that day too when not `strict`),
fewer than `days` later: one row per unit that has one. Units are the CTE `units`, keyed
by `key`, with the person's `person_id`. #}
{% macro first_after(name, start, kind, days, strict=true, units='sample', key='sample_id') %}
{{ name }} as (
select s.{{ key }}, min(e.date) as date
@@ -1,9 +1,3 @@
{#
A survival cohort over a domain's timeline (`<domain>_events`): every patient indexed at her
first biopsy reported with one of `grades`, within the recruitment window (start inclusive,
end exclusive), up to the as-of date. Out (`excluded_by`): no birth date (no age at the
index), a death on or before the index.
#}
{% macro first_biopsy_cohort(events, grades, recruitment) %}
with timeline as (
select * from {{ ref(events) }} where date <= {{ as_of() }}
@@ -1,4 +1,3 @@
{# Use the declared schema as is (bronze, silver, gold), on SQLite and PostgreSQL alike. #}
{% macro generate_schema_name(custom_schema_name, node) -%}
{{ custom_schema_name if custom_schema_name else target.schema }}
{%- endmacro %}
-1
View File
@@ -1,4 +1,3 @@
{# The later of two dates; empty when either is (a step counts once the previous one was reached). #}
{% macro later(a, b) -%}
case when {{ a }} is null or {{ b }} is null then null
when {{ b }} > {{ a }} then {{ b }} else {{ a }} end
-7
View File
@@ -1,10 +1,3 @@
{#
One study, wide: one row per study instance (person and the study's key), one column per
field of the catalog (core.catalog), from the long `silver.observation`. `known_at` is when
anything of the instance was first known, `<event>_known_at` when its event was (a report can
arrive loads after its sample). A subquery, for
`from {{ pivot('cervical_cytology') }} as c`, or a whole model.
#}
{% macro pivot(study) -%}
{%- set s = var('catalog')[study] -%}
(
-2
View File
@@ -1,10 +1,8 @@
{#- Whether a bronze table exists yet (nothing staged there before the first run). -#}
{% macro staged_exists(name) -%}
{{ return(execute and adapter.get_relation(this.database, 'bronze', name) is not none) }}
{%- endmacro %}
{# Whether a bronze table has a column (one a later version of its writer added). #}
{% macro staged_has_column(name, column) -%}
{%- if not execute -%}{{ return(false) }}{%- endif -%}
{%- set relation = adapter.get_relation(this.database, 'bronze', name) -%}
-2
View File
@@ -1,9 +1,7 @@
{# A list of values as a SQL list: ('a', 'b'). #}
{% macro sql_list(values) -%}
({% for v in values %}'{{ v | replace("'", "''") }}'{% if not loop.last %}, {% endif %}{% endfor %})
{%- endmacro %}
{# Upper case without Spanish accents, so free text compares with written patterns. #}
{% macro plain_upper(column) -%}
{%- set pairs = [('á','a'),('é','e'),('í','i'),('ó','o'),('ú','u'),('ü','u'),
('Á','A'),('É','E'),('Í','I'),('Ó','O'),('Ú','U'),('Ü','U')] -%}
@@ -1,14 +1,3 @@
{#
After colposcopy (KPNC's post-colposcopy tables): the patient's first colposcopy is an
episode whose result is known at the last report of the biopsies ordered that day (at the
colposcopy itself when none were); indexed at the POST_COLPOSCOPY_VISIT-th cytology sample
after that result and before any later colposcopy, in the recruitment window. Out, in
order: a biopsy ordered that day without a report (unreported_biopsy); an outcome biopsy
up to the index (outcome_by_index); a cervical cancer history (cancer_history); a
hysterectomy (hysterectomy); a treatment (prior_treatment), each up to the index; no
cytology or HPV result in the REFERRAL_LOOKBACK_DAYS before the colposcopy (no_referral);
an index sample without both a cytology and an HPV result (no_cotest).
#}
{% set p = var('cacu') %}
with known as (
select * from {{ ref('cacu_events') }} where date <= {{ as_of() }}
@@ -1,10 +1,3 @@
{#
After treatment: indexed at the first cytology sample more than
POST_TREATMENT_INDEX_AFTER_DAYS after the patient's first treatment, in the recruitment
window. Out, in order: no biopsy result in the POST_TREATMENT_LOOKBACK_DAYS up to the
treatment (no_pretreatment_biopsy); an outcome biopsy between treatment and index
(outcome_before_index); an index sample with no cytology or HPV result (no_index_result).
#}
{% set p = var('cacu') %}
with known as (
select * from {{ ref('cacu_events') }} where date <= {{ as_of() }}
@@ -1,8 +1,3 @@
{#
Screening surveillance: indexed at the patient's first cytology sample, when it falls in
the recruitment window. Out, in order: an outcome biopsy (CIN2+) before the index
(prior_outcome); an index sample with no cytology or HPV result (no_index_result).
#}
{% set p = var('cacu') %}
with known as (
select * from {{ ref('cacu_events') }} where date <= {{ as_of() }}
@@ -1,3 +1,2 @@
{# Survival: indexed at the first biopsy reported as carcinoma or carcinoma in situ (core.cacu CASE). #}
{% set p = var('cacu') %}
{{ first_biopsy_cohort('cacu_events', p.case, p.recruitment) }}
@@ -1,13 +0,0 @@
{# Every patient with a clinical event up to the as-of date, indexed at her first one. No
window and no rules: models that set their own index start from here. #}
with ranked as (
select
person_id, date,
row_number() over (partition by person_id order by date, source_table, source_id) as n
from {{ ref('cacu_events') }}
where date <= {{ as_of() }} and source_table <> 'person'
)
select person_id, date as index_date, cast(null as {{ dbt.type_string() }}) as excluded_by
from ranked
where n = 1
@@ -1,18 +1,3 @@
{#
Every CaCu patient's timeline: one row per event, in one shape, from silver. Results are
dated when they were reported; a cytology's results and a biopsy's order and report share
their source (`source_table`, `source_id`), so a model can tell which sample a result
belongs to.
Procedures silver has no record of are inferred from notes and biopsies (core.cacu):
- diagnosis: a note with a diagnosis ICD-10 by a diagnosing specialty;
- colposcopy: once a patient has been assessed (a diagnosis note within
SAMPLE_TO_DIAGNOSIS_DAYS after a cytology sample), a later colposcopy-clinic note that
says so (reason, ICD-10 or diagnosis text), and the biopsies ordered on such a day (at
their order and at their report);
- treatment: a note with a treatment ICD-10 after the first colposcopy;
- history: a note with a cervical cancer ICD-10.
#}
{% set p = var('cacu') %}
with cytology as (
@@ -1,8 +1,3 @@
{#
One row per CaCu patient: the first day of each follow-up step, from her timeline. Her
status at any day follows from them (core.measures.follow_up_status): a case (a biopsy
reported CASE grade), after treatment, after colposcopy, or before colposcopy.
#}
{% set p = var('cacu') %}
select
p.person_id,
@@ -1,6 +1,3 @@
{# The latest risk batch of each CaCu model: from its champion version, one row per
patient and horizon (years from her index date; 0 is the index visit itself), with the
report's clinical scenarios she is in (survival's). #}
select model, version, person_id, index_date, horizon_years, probability, ci_low, ci_high,
{% if staged_has_column('model_scores', 'scenarios') -%} scenarios
{%- else -%} cast(null as {{ dbt.type_string() }}) as scenarios {%- endif %},
@@ -1,5 +1,3 @@
{# The biopsies each cytology sample led to, with the grade's severity (core.cacu
BIOPSY_SEVERITY, from 1; -1 a report without a grade, 0 a grade outside it). #}
{% set p = var('cacu') %}
select
{{ dbt.concat(['b.person_id', "'|'", 'cast(b.cytology_sample_date as ' ~ dbt.type_string() ~ ')']) }} as sample_id,
@@ -1,12 +1,3 @@
{#
One row per cytology sample: the unit CaCu's cytology and screening-route measures count
over, with the intervals they measure. A sample's result date is its report's when the
report has a result (an unsatisfactory sample's report is not a result). Each interval ends at the first event of a kind
after its start (`first_after`), within that measure's horizon (core.cacu): diagnosis,
treatment and colposcopy from the timeline; the biopsy is the first report of a biopsy
the sample led to. `history`: a cervical cancer note before the sample. The patient's
first treatment and colposcopy give her follow-up status at any date.
#}
{% set p = var('cacu') %}
{% set h = p.horizons %}
with sample as (
@@ -1,8 +1,3 @@
{#
One row per breast biopsy, with the mammogram that led to it (the patient's, taken on
`mammogram_exam_date`) and that mammogram's BI-RADS. `histology_rank` orders grades from
least to most severe (core.cama): -1 for a report without one.
#}
{% set p = var('cama') %}
select
b.person_id,
@@ -1,4 +1,2 @@
{# Recurrence: the patients of the survival cohort (indexed at the first invasive biopsy
report, core.cama SURVIVAL_GRADES), followed for a recurrence (models.cama.recurrence.site). #}
{% set p = var('cama') %}
{{ first_biopsy_cohort('cama_events', p.survival_grades, p.recruitment) }}
@@ -1,3 +1,2 @@
{# Survival: indexed at the first invasive biopsy report (core.cama SURVIVAL_GRADES). #}
{% set p = var('cama') %}
{{ first_biopsy_cohort('cama_events', p.survival_grades, p.recruitment) }}
@@ -1,18 +1,3 @@
{#
Every CaMa patient's timeline (whoever has a mammogram or a breast biopsy): one row per
event, in the shape of the other domains' timelines. Results are dated when they were
reported; a mammogram's report and a biopsy's order and report share their source
(`source_table`, `source_id`), and a biopsy names the mammogram that led to it
(`value_code` of `biopsy_order`).
A biopsy report's results (histologic type, grade, receptors, Ki-67, size, positive nodes,
stage) are one event each, dated with the report; each treatment is an event at its start,
each recurrence at its diagnosis (`value_code`: local, regional or distant).
Procedures silver has no record of are inferred from notes (core.cama):
- diagnosis: a note with a diagnosis ICD-10 by a diagnosing specialty;
- history: a note with a breast cancer ICD-10, whoever wrote it.
#}
{% set p = var('cama') %}
with mammogram as (
@@ -1,7 +1,3 @@
{#
One row per mammogram and each reported biopsy it led to (one row with no biopsy when it led
to none): what the measures that follow a mammogram to its biopsy count over.
#}
select
m.*,
b.biopsy_id, b.report_date as biopsy_report_date, b.histology, b.histology_rank,
@@ -1,10 +1,3 @@
{#
One row per mammogram: the unit CaMa's mammography measures count over, with the intervals
they measure. A diagnosis resolves a mammogram when it is the patient's first diagnosis note
after it (on the report's day too, counted from the report), within the horizon (core.cama).
`history`: a breast cancer note before the mammogram. Each fact keeps when it became known:
the sample, its report, and the diagnosis note.
#}
{% set p = var('cama') %}
with sample as (
select
@@ -1,5 +1,3 @@
{# The latest risk batch of each CaMa model: from its champion version, one row per patient
and horizon (years from her index date), with the report's clinical scenarios she is in. #}
select model, version, person_id, index_date, horizon_years, probability, ci_low, ci_high,
{% if staged_has_column('model_scores', 'scenarios') -%} scenarios
{%- else -%} cast(null as {{ dbt.type_string() }}) as scenarios {%- endif %},
+87
View File
@@ -0,0 +1,87 @@
version: 2
models:
- name: tea_screening
columns:
- name: person_id
data_tests: [unique, not_null]
- name: tea_eegs
columns:
- name: eeg_id
data_tests: [not_null]
- name: tea_eeg_analyses
columns:
- name: person_id
data_tests: [not_null]
- name: tea_eeg_metrics
columns:
- name: eeg_id
data_tests: [not_null]
- name: code
data_tests: [not_null]
- name: tea_events
columns:
- name: person_id
data_tests: [not_null]
- name: tea_alterations
columns:
- name: person_id
data_tests: [unique, not_null]
- name: study_date
data_tests: [not_null]
- name: tea_prevalence
columns:
- name: person_id
data_tests: [unique, not_null]
- name: entry_date
data_tests: [not_null]
- name: tea_follow_up
columns:
- name: person_id
data_tests: [unique, not_null]
- name: step
data_tests:
- not_null
- accepted_values:
arguments:
values: [eeg, neurology, psychology, mchat_only]
- name: status
data_tests:
- not_null
- accepted_values:
arguments:
values: [finished, active]
- name: eeg_result
data_tests:
- not_null
- accepted_values:
arguments:
values: [no_valid_eeg, abnormal, normal, not_scored]
- name: tea_eeg_checks
columns:
- name: eeg_id
data_tests: [not_null]
- name: code
data_tests: [not_null]
- name: tea_eeg_regions
columns:
- name: eeg_id
data_tests: [not_null]
- name: code
data_tests: [not_null]
- name: kind
data_tests:
- not_null
- accepted_values:
arguments:
values: [electrode, zone]
- name: site
data_tests: [not_null]
- name: tea_associations
columns:
- name: key
data_tests: [unique, not_null]
- name: tea_association_scores
columns:
- name: key
data_tests: [unique, not_null]
@@ -0,0 +1,25 @@
{% set p = var('tea') %}
with first_good as (
select person_id, min(study_date) as study_date
from {{ ref('tea_eegs') }} where valid group by person_id
),
eeg as (
select s.person_id, s.age_group, f.study_date, e.eeg_id, e.known_at
from {{ ref('tea_screening') }} as s
join first_good as f on f.person_id = s.person_id
join {{ ref('tea_eegs') }} as e on e.person_id = f.person_id and e.study_date = f.study_date and e.valid
where s.eeg_date is not null
),
scored as (
select eeg_id, code, (outside is not null and outside <> 0 and model is not null) as altered
from {{ ref('tea_eeg_metrics') }}
)
select
eeg.person_id, eeg.age_group, eeg.study_date, eeg.eeg_id, eeg.known_at,
coalesce(max(case when m.altered then 1 else 0 end), 0) = 1 as altered
{%- for metric in p.eeg_metrics %},
coalesce(max(case when m.code = '{{ metric }}' and m.altered then 1 else 0 end), 0) = 1 as alt_{{ metric }}
{%- endfor %}
from eeg
left join scored as m on m.eeg_id = eeg.eeg_id
group by eeg.person_id, eeg.age_group, eeg.study_date, eeg.eeg_id, eeg.known_at
@@ -0,0 +1,21 @@
-- depends_on: {{ ref('eeg') }}
{% if staged_exists('eeg_association_scores') %}
select
a.key, a.model, a.eeg_id, a.pair, a.z, a.probability, a.reference_probability,
e.person_id, e.study_date
from {{ source('bronze', 'eeg_association_scores') }} as a
join {{ ref('eeg') }} as e
on a.eeg_id = {{ dbt.concat(['e.person_id', "'|'", 'cast(e.study_date as ' ~ dbt.type_string() ~ ')']) }}
{% else %}
select
cast(null as {{ dbt.type_string() }}) as key,
cast(null as {{ dbt.type_string() }}) as model,
cast(null as {{ dbt.type_string() }}) as eeg_id,
cast(null as {{ dbt.type_string() }}) as pair,
cast(null as {{ dbt.type_float() }}) as z,
cast(null as {{ dbt.type_float() }}) as probability,
cast(null as {{ dbt.type_float() }}) as reference_probability,
cast(null as {{ dbt.type_string() }}) as person_id,
cast(null as date) as study_date
where 1 = 0
{% endif %}
@@ -0,0 +1,32 @@
{% if staged_exists('eeg_associations') %}
select
a.key, a.model, a.level, a.n_cohort, a.biomarker, a.zone, a.kind, a.outcome_code,
a.event, a.method, a.n, a.odds_ratio, a.ci_low, a.ci_high, a.p, a.q,
a.sens_model, a.sens_odds_ratio, a.same_direction, a.reason,
cast(substr(a.model, 23) as integer) as champion_version
from {{ source('bronze', 'eeg_associations') }} as a
{% else %}
select
cast(null as {{ dbt.type_string() }}) as key,
cast(null as {{ dbt.type_string() }}) as model,
cast(null as {{ dbt.type_string() }}) as level,
cast(null as bigint) as n_cohort,
cast(null as {{ dbt.type_string() }}) as biomarker,
cast(null as {{ dbt.type_string() }}) as zone,
cast(null as {{ dbt.type_string() }}) as kind,
cast(null as {{ dbt.type_string() }}) as outcome_code,
cast(null as {{ dbt.type_string() }}) as event,
cast(null as {{ dbt.type_string() }}) as method,
cast(null as bigint) as n,
cast(null as {{ dbt.type_float() }}) as odds_ratio,
cast(null as {{ dbt.type_float() }}) as ci_low,
cast(null as {{ dbt.type_float() }}) as ci_high,
cast(null as {{ dbt.type_float() }}) as p,
cast(null as {{ dbt.type_float() }}) as q,
cast(null as {{ dbt.type_string() }}) as sens_model,
cast(null as {{ dbt.type_float() }}) as sens_odds_ratio,
cast(null as {{ dbt.type_boolean() }}) as same_direction,
cast(null as {{ dbt.type_string() }}) as reason,
cast(null as integer) as champion_version
where 1 = 0
{% endif %}
@@ -1,4 +1,3 @@
{# Every EEG with its analysis verdict (the EEG job's `bronze.eeg_analysis`, by signal hash). #}
select e.person_id, e.study_date, e.edf,
{%- if staged_exists('eeg_analysis') %}
a.valid
@@ -0,0 +1,24 @@
-- depends_on: {{ ref('tea_eegs') }}
{%- if not staged_exists('eeg_checks') %}
select
cast(null as {{ dbt.type_string() }}) as person_id,
cast(null as {{ dbt.type_string() }}) as eeg_id,
cast(null as date) as study_date,
cast(null as {{ dbt.type_string() }}) as edf,
cast(null as {{ dbt.type_string() }}) as code,
cast(null as {{ dbt.type_string() }}) as electrode,
cast(null as {{ dbt.type_float() }}) as value,
cast(null as {{ dbt.type_string() }}) as text,
cast(null as {{ dbt.type_string() }}) as unit,
cast(null as {{ dbt.type_float() }}) as low,
cast(null as {{ dbt.type_float() }}) as high,
cast(null as {{ dbt.type_boolean() }}) as decisive,
cast(null as {{ dbt.type_boolean() }}) as abnormal
where 1 = 0
{%- else %}
select
e.person_id, e.eeg_id, e.study_date, c.edf,
c.code, c.electrode, c.value, c.text, c.unit, c.low, c.high, c.decisive, c.abnormal
from {{ source('bronze', 'eeg_checks') }} as c
join {{ ref('tea_eegs') }} as e on e.edf = c.edf
{%- endif %}
@@ -1,9 +1,4 @@
{%- do ref('tea_eegs') %}
{#
One row per EEG metric (the EEG job's `bronze.eeg_metrics`), with the age curve's score of
its value (`bronze.eeg_scores`, when a curve in production scored it): what the EEG pages
and FHIR read.
#}
{%- if not staged_exists('eeg_metrics') %}
select
cast(null as {{ dbt.type_string() }}) as person_id, cast(null as {{ dbt.type_string() }}) as eeg_id,
@@ -0,0 +1,40 @@
-- depends_on: {{ ref('tea_eegs') }}
{%- if not staged_exists('eeg_sites') %}
select
cast(null as {{ dbt.type_string() }}) as person_id,
cast(null as {{ dbt.type_string() }}) as eeg_id,
cast(null as date) as study_date,
cast(null as {{ dbt.type_string() }}) as edf,
cast(null as {{ dbt.type_string() }}) as code,
cast(null as {{ dbt.type_string() }}) as kind,
cast(null as {{ dbt.type_string() }}) as site,
cast(null as {{ dbt.type_float() }}) as value,
cast(null as {{ dbt.type_float() }}) as z,
cast(null as {{ dbt.type_float() }}) as outside,
cast(null as {{ dbt.type_float() }}) as p5,
cast(null as {{ dbt.type_float() }}) as median,
cast(null as {{ dbt.type_float() }}) as p95,
cast(null as {{ dbt.type_string() }}) as model
where 1 = 0
{%- else %}
select
e.person_id, e.eeg_id, e.study_date, x.edf, x.code,
case x.part when 'electrodes' then 'electrode' when 'zones' then 'zone' end as kind,
x.site, x.value,
{%- if staged_exists('eeg_scores') %}
s.z, s.outside, s.p5, s.median, s.p95, s.model
{%- else %}
cast(null as {{ dbt.type_float() }}) as z,
cast(null as {{ dbt.type_float() }}) as outside,
cast(null as {{ dbt.type_float() }}) as p5,
cast(null as {{ dbt.type_float() }}) as median,
cast(null as {{ dbt.type_float() }}) as p95,
cast(null as {{ dbt.type_string() }}) as model
{%- endif %}
from {{ source('bronze', 'eeg_sites') }} as x
join {{ ref('tea_eegs') }} as e on e.edf = x.edf
{%- if staged_exists('eeg_scores') %}
left join {{ source('bronze', 'eeg_scores') }} as s
on s.edf = x.edf and s.metric = x.code and s.part = x.part and s.site = x.site
{%- endif %}
{%- endif %}
@@ -1,8 +1,3 @@
{#
One row per EEG of a child of the screening cohort, with its analysis (the EEG job's
`bronze.eeg_analysis`, by the signal's hash): `quality` good (valid), bad (not valid) or
not_analyzed (no analysis yet, or no signal).
#}
select
e.person_id,
{{ dbt.concat(['e.person_id', "'|'", 'cast(e.study_date as ' ~ dbt.type_string() ~ ')']) }} as eeg_id,
@@ -1,4 +1,3 @@
{# Every TEA child's timeline, in the shape of the other domains' (the default cut-off reads it). #}
select person_id, screening_date as date, known_at, 'mchat' as type,
cast(null as {{ dbt.type_string() }}) as value_code,
cast(score as {{ dbt.type_float() }}) as value_num,
@@ -0,0 +1,70 @@
{% set p = var('tea') %}
with screening as (
select *,
case
when eeg_date is not null then 'eeg'
when neuro_date is not null then 'neurology'
when psychology_date is not null then 'psychology'
else 'mchat_only'
end as step
from {{ ref('tea_screening') }}
),
mchat_scores as (
select person_id, screening_date, max(score) as score
from {{ ref('mchat') }}
group by person_id, screening_date
),
ranked_ados2 as (
select *,
row_number() over (partition by person_id order by evaluation_date desc, known_at desc) as rn
from {{ ref('ados2') }}
),
first_good as (
select person_id, min(study_date) as study_date
from {{ ref('tea_eegs') }} where valid group by person_id
),
eeg as (
select e.person_id, e.eeg_id,
{%- if staged_exists('eeg_analysis') %}
a.duration_min, a.channels,
{%- else %}
cast(null as {{ dbt.type_float() }}) as duration_min,
cast(null as {{ dbt.type_float() }}) as channels,
{%- endif %}
exists (
select 1 from {{ ref('tea_eeg_metrics') }} as m
where m.eeg_id = e.eeg_id and m.model is not null
) as scored
from first_good as f
join {{ ref('tea_eegs') }} as e on e.person_id = f.person_id and e.study_date = f.study_date and e.valid
{%- if staged_exists('eeg_analysis') %}
left join {{ source('bronze', 'eeg_analysis') }} as a on a.edf = e.edf
{%- endif %}
)
select
s.person_id, s.sex, s.birth_date, s.age_months, s.age_group, s.known_at,
s.step, coalesce(s.eeg_date, s.neuro_date, s.psychology_date, s.mchat_date) as step_date,
case when s.step = 'eeg' then 'finished' else 'active' end as status,
s.mchat_date as start_date, s.eeg_date as end_date,
s.mchat_date, m.score as mchat_score,
s.psychology_date, s.neuro_date, s.confirmed_date, s.not_confirmed_date, s.eeg_date,
a.evaluation_date as ados2_date, a.module as ados2_module,
{%- for item in p.ados2_items %}
a.{{ item }} as ados2_{{ item }},
{%- endfor %}
e.eeg_id, e.duration_min as eeg_duration_min, e.channels as eeg_channels, e.scored as eeg_scored,
case
when e.eeg_id is null then 'no_valid_eeg'
when t.altered then 'abnormal'
when e.scored then 'normal'
else 'not_scored'
end as eeg_result,
t.altered
{%- for metric in p.eeg_metrics %},
t.alt_{{ metric }}
{%- endfor %}
from screening as s
left join mchat_scores as m on m.person_id = s.person_id and m.screening_date = s.mchat_date
left join ranked_ados2 as a on a.person_id = s.person_id and a.rn = 1
left join eeg as e on e.person_id = s.person_id
left join {{ ref('tea_alterations') }} as t on t.person_id = s.person_id
@@ -0,0 +1,17 @@
{% set p = var('tea') %}
{% set entry = (p.prevalence_age[0] * p.days_per_month) | round | int %}
{% set leave = ((p.prevalence_age[1] + 1) * p.days_per_month) | round | int %}
with confirmed as (
select person_id, min(note_date) as confirmed_date
from {{ ref('clinical_note') }}
where specialty = '{{ p.neurology }}' and icd10 in {{ sql_list(p.confirming_icd10) }}
group by person_id
)
select
pe.person_id, pe.sex, pe.birth_date, pe.known_at,
{{ add_days('pe.birth_date', entry) }} as entry_date,
{{ add_days('pe.birth_date', leave) }} as exit_date,
s.confirmed_date
from {{ ref('person') }} as pe
left join confirmed as s on s.person_id = pe.person_id
where pe.birth_date is not null
@@ -1,10 +1,3 @@
{#
One row per child of the screening cohort (her first M-CHAT at 16 to 36 months, or with no
birth date), with the day she reached each step. A step counts once the previous one was
reached: its day is the later of the two (core.tea):
psychology (first ADOS-2) <- M-CHAT; neurology (first note) and its confirming or
non-confirming verdict <- psychology; EEG (first good one) <- neurology.
#}
{% set p = var('tea') %}
with mchat as (
@@ -14,7 +7,7 @@ with mchat as (
child as (
select
m.person_id, m.mchat_date, m.known_at, b.birth_date,
m.person_id, m.mchat_date, m.known_at, b.birth_date, b.sex,
cast(round({{ days_between('b.birth_date', 'm.mchat_date') }} / {{ p.days_per_month }}, 1) * 10
as integer) / 10 as age_months
from mchat as m
@@ -68,7 +61,7 @@ steps as (
)
select
person_id, birth_date, age_months, known_at,
person_id, birth_date, sex, age_months, known_at,
case
when age_months is null then 'no_data'
{%- for low, high in p.age_groups %}
-1
View File
@@ -1,3 +1,2 @@
{{ config(materialized='table') }}
{#- ados2, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('ados2') }} as p
@@ -1,3 +1,2 @@
{{ config(materialized='table') }}
{#- breast_biopsy, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('breast_biopsy') }} as p
@@ -1,3 +1,2 @@
{{ config(materialized='table') }}
{#- breast_recurrence, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('breast_recurrence') }} as p
@@ -1,3 +1,2 @@
{{ config(materialized='table') }}
{#- breast_treatment, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('breast_treatment') }} as p
@@ -1,3 +1,2 @@
{{ config(materialized='table') }}
{#- cervical_biopsy, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('cervical_biopsy') }} as p
@@ -1,3 +1,2 @@
{{ config(materialized='table') }}
{#- cervical_cytology, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('cervical_cytology') }} as p
@@ -1,3 +1,2 @@
{{ config(materialized='table') }}
{#- clinical_note, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('clinical_note') }} as p
-1
View File
@@ -1,3 +1,2 @@
{{ config(materialized='table') }}
{#- death, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('death') }} as p
-1
View File
@@ -1,3 +1,2 @@
{{ config(materialized='table') }}
{#- eeg, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('eeg') }} as p
@@ -1,3 +1,2 @@
{{ config(materialized='table') }}
{#- mammography, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('mammography') }} as p
-1
View File
@@ -1,3 +1,2 @@
{{ config(materialized='table') }}
{#- mchat, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('mchat') }} as p
@@ -1,12 +1,3 @@
{#
Silver: every clinical value, long. One row per field of one study instance (a person and
the study's key, e.g. her cytology sampled on a day), from what targets staged:
- rows a reviewer rejected (review_log) stay out; rows a rule held never got here;
- rows of one instance are one record: values that complement each other are merged; a
field with two different values is a conflict, and the whole instance stays out until a
reviewer rejects the wrong row;
- an instance is known from when its first row was (`known_at`).
#}
{%- if not staged_exists('staged__observation') %}
select
cast(null as {{ dbt.type_string() }}) as person_id,
-5
View File
@@ -1,8 +1,3 @@
{#
One row per person the link nodes found, with what her records agree on. A person whose
records disagree on birth date or sex is held whole by the link node, so what is left
agrees and min() only picks the one value.
#}
select
person_id,
min(birth_date) as birth_date,
@@ -1,8 +1,3 @@
{#
Every identifier a person carries: CURP and NSS under their own systems, and each record
number under the system of the source it came from (a site has as many as it has
sources). Records held by the link node (a torn person) give none until reviewed.
#}
{%- set ids = var('identifiers') %}
with identity as (
select * from {{ source('bronze', 'staged__identity') }}
@@ -15,6 +10,6 @@ union
{%- endfor %}
select distinct
person_id,
{{ dbt.concat(["'" ~ var('record_number_system') ~ "'", '_pipeline', "':'", '_source']) }} as system,
'{{ var("record_number_system") }}' || _pipeline as system,
record_number as value
from identity where record_number is not null
@@ -1,7 +1,3 @@
{#
Persons a review merged into another: the replaced id and the one that replaced it (the
latest decision). A replaced id keeps resolving, to its survivor.
#}
{%- if not staged_exists('person_link') %}
select cast(null as {{ dbt.type_string() }}) as person_id,
cast(null as {{ dbt.type_string() }}) as replaced_by
@@ -1,4 +1,3 @@
{#- Every name a person's records give (as the link node compared them). -#}
select distinct person_id, full_name as text
from {{ source('bronze', 'staged__identity') }}
where _held is null and person_id is not null and full_name is not null
+3
View File
@@ -6,7 +6,10 @@ sources:
- name: model_scores
- name: eeg_analysis
- name: eeg_metrics
- name: eeg_sites
- name: eeg_scores
- name: eeg_associations
- name: eeg_association_scores
- name: eeg_checks
- name: review_log
- name: staged__identity
@@ -1,5 +1,3 @@
{#- Every value silver holds is a field of its study, and a code is one its field allows
(core.catalog). -#}
select o.study, o.field, o.value_text
from {{ ref('observation') }} as o
where not (
@@ -1,4 +1,3 @@
{#- Silver holds one value per field of a study instance. -#}
select person_id, study, instance, field
from {{ ref('observation') }}
group by person_id, study, instance, field
-29
View File
@@ -1,23 +1,3 @@
"""Backups of a deployment: everything the platform keeps lives in its data folder
(`ISSSTELEON_DATA`), so a backup is that folder at one moment, checked and restorable.
- SQLite databases (the platform's schemas, Dagster's runs, MLflow's registry) are copied with
SQLite's online backup, consistent while the stack runs. Run as the Dagster job `backup`,
it holds the `writes` slot, so no ingestion, training or scoring writes meanwhile.
- Every other file (MLflow's artifacts, uploads, dlt's state, the sign-in secret) is copied.
- A PostgreSQL platform database (PLATFORM_DATABASE_URL) is dumped with pg_dump.
- Left out: what is downloaded again or rebuilt (BACKUP_EXCLUDE, default the local LLM's
weights), SQLite's -wal/-shm files and temporary spools.
Each backup is a folder `<BACKUP_DIR>/<UTC time>` with `manifest.json`: the version, a sha256
per file and the row count of every table. Only finished backups get their final name; the
newest BACKUP_KEEP are kept.
python -m persistance.backup create [--to DIR]
python -m persistance.backup verify DIR
python -m persistance.backup restore DIR [--force] (with the stack stopped)
"""
import argparse
import hashlib
import json
@@ -89,8 +69,6 @@ def _copy_sqlite(source: Path, target: Path) -> None:
dst = sqlite3.connect(target)
try:
src.backup(dst)
# A copy at rest: no WAL (the platform turns it back on when it connects), so reading
# the backup leaves no -wal/-shm files beside it.
dst.execute("PRAGMA journal_mode=DELETE")
finally:
dst.close()
@@ -98,7 +76,6 @@ def _copy_sqlite(source: Path, target: Path) -> None:
def create(to: Path | None = None, data: Path = DATA_DIR) -> Path:
"""A new backup of `data` under `to` (default BACKUP_DIR); returns its folder."""
root = (to or backup_dir()).resolve()
if root == data.resolve() or data.resolve() in root.parents:
raise ValueError(f"the backups ({root}) must be outside the data folder ({data})")
@@ -150,7 +127,6 @@ def _prune(root: Path) -> None:
def verify(folder: Path) -> list[str]:
"""What is wrong with a backup (missing or changed files); empty when it is whole."""
manifest = json.loads((folder / MANIFEST).read_text())
problems = []
for rel, entry in manifest["files"].items():
@@ -163,7 +139,6 @@ def verify(folder: Path) -> list[str]:
def _holds_platform(held: list[Path]) -> bool:
"""Whether a platform is already there: its SQLite files, or its PostgreSQL schemas."""
if platform_url().startswith("sqlite"):
return any(p.name.startswith("platform") for p in held)
from sqlalchemy import inspect
@@ -175,10 +150,6 @@ def _holds_platform(held: list[Path]) -> bool:
def restore(folder: Path, data: Path = DATA_DIR, force: bool = False) -> None:
"""The backup's files into `data` (with the stack stopped). Checked first: a damaged
backup restores nothing. A data folder that already has a platform needs `force`; what
it held is moved aside (`.before-restore-<time>/` inside it), so nothing newer than the
backup mixes with it, and nothing is lost."""
if problems := verify(folder):
raise ValueError("the backup is damaged: " + "; ".join(problems))
manifest = json.loads((folder / MANIFEST).read_text())
+349
View File
@@ -0,0 +1,349 @@
import hashlib
import io
import json
import re
import tempfile
import zipfile
from dataclasses import dataclass
from pathlib import Path
from typing import BinaryIO, Literal
from core.domains import Domain
from core.tea import bundle as tea_bundle
from persistance import config, registry
FORMAT = 1
MANIFEST = "manifest.json"
EPOCH = (1980, 1, 1, 0, 0, 0)
MAX_BYTES = 2 * 1024**3
Selection = Literal["champion", "latest", "all"]
class BundleError(ValueError):
pass
class Empty(BundleError):
pass
class Conflict(BundleError):
pass
@dataclass(frozen=True)
class Exported:
data: bytes
sha256: str
versions: list[tuple[str, int]]
@dataclass(frozen=True)
class Imported:
sha256: str
imported: list[tuple[str, int]]
skipped: list[tuple[str, int]]
def _sha256(content: bytes) -> str:
return hashlib.sha256(content).hexdigest()
def content_sha256(files: dict[str, bytes]) -> str:
return _sha256("".join(f"{path}\0{_sha256(files[path])}\n" for path in sorted(files)).encode())
def guard(domain: Domain, snapshot: registry.Snapshot) -> list[str]:
if domain != Domain.TEA:
return []
reports = {}
for key in ("technical_validation", "interpretability"):
if key in snapshot.reports:
try:
reports[key] = snapshot.reports[key][1].decode("utf-8")
except UnicodeDecodeError:
continue
return tea_bundle.guard(
{
"name": snapshot.name,
"version": snapshot.version,
"params": snapshot.params,
"metrics": snapshot.metrics,
"tags": snapshot.tags,
"reports": reports,
}
)
def _check_guard(domain: Domain, snapshots: list[registry.Snapshot]) -> None:
problems = [
f"{snapshot.name} v{snapshot.version}: {problem}"
for snapshot in snapshots
for problem in guard(domain, snapshot)
]
if problems:
raise BundleError("; ".join(problems))
def _prefix(name: str, version: int) -> str:
return f"models/{name}/v{version}/"
def export(
domain: Domain, names: list[str] | None = None, versions: Selection = "champion"
) -> Exported:
prefix = f"{domain.value}."
available = registry.names(prefix)
selected = available
if names is not None:
selected = []
for short in names:
name = prefix + short
if name not in available:
raise BundleError(f"no {domain.value} model {short}")
selected.append(name)
pairs = []
for name in sorted(set(selected)):
if versions == "all":
pairs.extend((name, item["version"]) for item in registry.versions(name))
else:
lookup = (
registry.champion_version if versions == "champion" else registry.latest_version
)
if (version := lookup(name)) is not None:
pairs.append((name, version))
if not pairs:
raise Empty("nothing to export: no version selected")
snapshots = [registry.snapshot(name, version) for name, version in pairs]
_check_guard(domain, snapshots)
entries = {}
manifest_versions = []
for snapshot in snapshots:
files = {f"model/{path}": data for path, data in snapshot.model.items()}
files.update({f"reports/{filename}": data for filename, data in snapshot.reports.values()})
identity = {
"name": snapshot.name,
"version": snapshot.version,
"content_sha256": content_sha256(files),
}
meta = {
**identity,
"created": snapshot.created,
"params": snapshot.params,
"metrics": snapshot.metrics,
"tags": snapshot.tags,
"reports": {key: filename for key, (filename, _) in snapshot.reports.items()},
}
files["meta.json"] = json.dumps(meta, sort_keys=True, indent=1, ensure_ascii=False).encode()
folder = _prefix(snapshot.name, snapshot.version)
entries.update({folder + path: data for path, data in files.items()})
manifest_versions.append(
{**identity, "files": {folder + path: _sha256(data) for path, data in files.items()}}
)
manifest = {"format": FORMAT, "domain": domain.value, "versions": manifest_versions}
entries[MANIFEST] = json.dumps(manifest, sort_keys=True, indent=1).encode()
output = io.BytesIO()
with zipfile.ZipFile(output, "w") as archive:
for path, data in sorted(entries.items()):
info = zipfile.ZipInfo(path, EPOCH)
info.compress_type = zipfile.ZIP_DEFLATED
info.external_attr = 0o644 << 16
info.create_system = 3
archive.writestr(info, data, compresslevel=6)
data = output.getvalue()
return Exported(data, _sha256(data), pairs)
def _safe_path(path: str) -> bool:
return not any(part in ("", ".", "..") for part in path.split("/")) and not (
"\\" in path or "\0" in path
)
def _read(domain: Domain, archive: zipfile.ZipFile) -> list[tuple[registry.Snapshot, str]]:
paths = set()
for entry in archive.infolist():
path = entry.orig_filename
if not _safe_path(path):
raise BundleError(f"unsafe bundle path: {path}")
if path in paths:
raise BundleError(f"duplicate bundle path: {path}")
paths.add(path)
if sum(entry.file_size for entry in archive.infolist()) > MAX_BYTES:
raise BundleError("bundle exceeds the uncompressed size limit")
if MANIFEST not in paths:
raise BundleError("bundle has no manifest.json")
manifest = json.loads(archive.read(MANIFEST))
if (format_ := manifest.get("format")) != FORMAT:
raise BundleError(f"bundle format {format_}, this platform reads 1")
if (source := manifest.get("domain")) != domain.value:
raise BundleError(f"bundle is for {source}, not {domain.value}")
versions = manifest["versions"]
expected = {path for item in versions for path in item["files"]}
if MANIFEST in expected or paths != expected | {MANIFEST}:
raise BundleError("the files in the bundle do not match the manifest")
files = {path: archive.read(path) for path in expected}
for item in versions:
for path, digest in item["files"].items():
if _sha256(files[path]) != digest:
raise BundleError(f"{path}: content does not match the manifest")
snapshots = [_snapshot(domain, item, files) for item in versions]
if len({(snapshot.name, snapshot.version) for snapshot, _ in snapshots}) != len(snapshots):
raise BundleError("duplicate model version in the manifest")
return snapshots
def _snapshot(domain: Domain, item: dict, files: dict[str, bytes]) -> tuple[registry.Snapshot, str]:
name, version, digest = item["name"], item["version"], item["content_sha256"]
if (
not name.startswith(f"{domain.value}.")
or "/" in name
or type(version) is not int
or version < 1
):
raise BundleError("invalid model name or version in the manifest")
prefix = _prefix(name, version)
if any(not path.startswith(prefix) for path in item["files"]):
raise BundleError(f"{name} v{version}: file outside version folder")
relative = {path.removeprefix(prefix): files[path] for path in item["files"]}
meta = json.loads(relative.pop("meta.json"))
if any(meta[key] != item[key] for key in ("name", "version", "content_sha256")):
raise BundleError(f"{name} v{version}: meta.json does not match the manifest")
if content_sha256(relative) != digest:
raise BundleError(f"{name} v{version}: content SHA-256 does not match")
reports = {}
for key, filename in meta["reports"].items():
if key not in registry.REPORTS or "/" in filename:
raise BundleError(f"{name} v{version}: invalid report {key}")
reports[key] = (filename, relative.pop(f"reports/{filename}"))
if any(not path.startswith("model/") for path in relative):
raise BundleError(f"{name} v{version}: unexpected file in version folder")
model = {path.removeprefix("model/"): data for path, data in relative.items()}
return registry.Snapshot(
name,
version,
meta["created"],
meta["params"],
meta["metrics"],
meta["tags"],
reports,
model,
), digest
def import_(domain: Domain, data: bytes) -> Imported:
sha256 = _sha256(data)
if not trusted(sha256):
raise BundleError(
f"bundle {sha256} is not trusted on this server: "
f"the operator adds its SHA-256 to {trusted_file()}"
)
try:
archive = zipfile.ZipFile(io.BytesIO(data))
except zipfile.BadZipFile:
raise BundleError("not a bundle") from None
try:
with archive:
versions = _read(domain, archive)
versions.sort(key=lambda item: (item[0].name, item[0].version))
_check_guard(domain, [snapshot for snapshot, _ in versions])
except BundleError:
raise
except (
ValueError,
KeyError,
TypeError,
AttributeError,
RuntimeError,
OSError,
zipfile.BadZipFile,
) as e:
raise BundleError(f"invalid bundle: {e}") from None
pending, skipped = [], []
for snapshot, digest in versions:
if digest in registry.content_hashes(snapshot.name):
skipped.append((snapshot.name, snapshot.version))
else:
pending.append((snapshot, digest))
if not pending:
found = ", ".join(f"{name} v{version}" for name, version in skipped)
raise Conflict(f"every version is already registered: {found}")
imported = []
for snapshot, digest in pending:
tags = {key: val for key, val in snapshot.tags.items() if not key.startswith("bundle.")}
tags.update(
{
"bundle.sha256": sha256,
"bundle.source_name": snapshot.name,
"bundle.source_version": str(snapshot.version),
"bundle.content_sha256": digest,
}
)
with tempfile.TemporaryDirectory() as tmp:
model_dir = Path(tmp)
for path, content in snapshot.model.items():
target = model_dir / path
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(content)
try:
version = registry.restore(
snapshot.name,
model_dir,
snapshot.params,
snapshot.metrics,
snapshot.reports,
tags,
)
except ValueError as e:
raise BundleError(str(e)) from None
imported.append((snapshot.name, version))
return Imported(sha256, imported, skipped)
def staging() -> Path:
path = config.DATA_DIR / "bundles"
path.mkdir(parents=True, exist_ok=True)
return path
def staged(sha256: str) -> Path:
if not re.fullmatch(r"[0-9a-f]{64}", sha256):
raise ValueError("invalid bundle SHA-256")
return staging() / f"{sha256}.zip"
def stage(stream: BinaryIO) -> tuple[str, Path]:
digest = hashlib.sha256()
with tempfile.NamedTemporaryFile(dir=staging(), delete=False) as output:
temp = Path(output.name)
try:
while chunk := stream.read(1024**2):
digest.update(chunk)
output.write(chunk)
output.close()
sha256 = digest.hexdigest()
path = staged(sha256)
temp.replace(path)
finally:
temp.unlink(missing_ok=True)
return sha256, path
def trusted_file() -> Path:
return staging() / "trusted"
def trusted(sha256: str) -> bool:
try:
with trusted_file().open(encoding="utf-8") as file:
return any(
line == sha256
for raw in file
if (line := raw.strip().lower()) and not line.startswith("#")
)
except FileNotFoundError:
return False
+310
View File
@@ -0,0 +1,310 @@
import os
import re
import time
import urllib.request
from pathlib import Path
from typing import Annotated, Literal
from urllib.parse import urlsplit
import psutil
from dask.utils import parse_bytes
from pydantic import BaseModel, ConfigDict, Field
Mode = Literal["sync", "local", "remote"]
PROGRESS_TAG = "isssteleon/progress"
CHECKED_PACKAGES = (
"numpy",
"scipy",
"pandas",
"scikit-learn",
"mne",
"edfio",
"statsmodels",
"cloudpickle",
"joblib",
)
REFERENCE_NAME = re.compile(r"^[A-Za-z0-9._-]{1,64}$")
_SCHEDULER = re.compile(r"^(tcp|tls)://[A-Za-z0-9._-]+:\d{1,5}$")
_MODES = ("sync", "local", "remote")
class ExecutionError(ValueError):
pass
class ClusterVersionError(ExecutionError):
pass
class Execution(BaseModel):
model_config = ConfigDict(
extra="forbid",
title="Ejecución",
json_schema_extra={
"description": "What a request or a job config carries: "
"None means the deployment's default."
},
)
mode: Mode | None = Field(None, title="Modo")
scheduler: str | None = Field(None, title="Planificador Dask")
class SiteTrainingSource(BaseModel):
model_config = ConfigDict(extra="forbid", title="Niños del sitio sin el diagnóstico")
kind: Literal["site"] = Field(title="Origen")
class FolderTrainingSource(BaseModel):
model_config = ConfigDict(extra="forbid", title="Carpeta de EDF con edades")
kind: Literal["folder"] = Field(title="Origen")
folder: str = Field(
pattern=r"^[A-Za-z0-9._-]{1,64}$",
title="Carpeta",
description="Carpeta dentro de TEA_REFERENCE_ROOT",
)
line_hz: Literal[50, 60] = Field(50, title="Frecuencia de la red eléctrica (Hz)")
type TrainingSource = Annotated[
SiteTrainingSource | FolderTrainingSource, Field(discriminator="kind")
]
class Resolved(BaseModel):
model_config = ConfigDict(frozen=True)
mode: Mode
scheduler: str | None
class Worker(BaseModel):
name: str
cpu_pct: float
memory_bytes: int
memory_limit: int | None
executing: int
threads: int
class Tasks(BaseModel):
waiting: int = 0
queued: int = 0
processing: int = 0
memory: int = 0
erred: int = 0
class Progress(BaseModel):
model_config = ConfigDict(
json_schema_extra={"description": "The run tag's JSON; the API returns it as it is."}
)
phase: str
done: int
total: int
elapsed_s: float
eta_s: float | None
mode: Mode
scheduler: str | None
workers: list[Worker] = []
tasks: Tasks | None = None
updated_at: str
class Health(BaseModel):
mode: Mode
scheduler: str | None
reachable: bool
workers: int | None = None
expected_workers: int | None = None
threads: int | None = None
versions_ok: bool | None = None
version_error: str | None = None
dashboard_url: str | None = None
dashboard_ok: bool | None = None
latency_ms: float | None = None
reference: dict | None = None
error: str | None = None
class Options(BaseModel):
default_mode: Mode
schedulers: list[str]
def normalize(address: str) -> str:
address = address.strip()
full = address if "://" in address else f"tcp://{address}"
if not _SCHEDULER.match(full):
raise ExecutionError(f"scheduler {address!r} is not host:port")
return full
def schedulers() -> list[str]:
found = [
normalize(part) for part in os.environ.get("DASK_SCHEDULERS", "").split(",") if part.strip()
]
return list(dict.fromkeys(found))
def default_mode() -> Mode:
mode = os.environ.get("EXECUTION_MODE", "").strip() or "local"
if mode not in _MODES:
raise ExecutionError(f"EXECUTION_MODE {mode!r} is not one of {', '.join(_MODES)}")
return mode # type: ignore[return-value]
def options() -> Options:
return Options(default_mode=default_mode(), schedulers=schedulers())
def resolve(execution: Execution | None = None) -> Resolved:
execution = execution or Execution()
mode = execution.mode or default_mode()
if mode != "remote":
if execution.scheduler:
raise ExecutionError("a scheduler only goes with remote mode")
return Resolved(mode=mode, scheduler=None)
allowed = schedulers()
if execution.scheduler:
scheduler = normalize(execution.scheduler)
if scheduler not in allowed:
raise ExecutionError(f"scheduler {scheduler} is not in DASK_SCHEDULERS")
elif allowed:
scheduler = allowed[0]
else:
raise ExecutionError(
"remote execution needs a scheduler: none given and DASK_SCHEDULERS is empty"
)
return Resolved(mode=mode, scheduler=scheduler)
def memory_per_worker() -> str:
return os.environ.get("DASK_MEMORY_PER_WORKER") or "4GiB"
def local_workers(n: int | None = None) -> int:
if n is not None:
return n
given = os.environ.get("DASK_LOCAL_WORKERS")
if given:
value = int(given)
if value < 1:
raise ExecutionError("DASK_LOCAL_WORKERS must be at least 1")
return value
fits = psutil.virtual_memory().available // parse_bytes(memory_per_worker())
return max(1, min(os.cpu_count() or 1, fits))
def versions_error(client) -> str | None:
try:
from distributed.versions import error_message
v = client.get_versions(packages=list(CHECKED_PACKAGES))
m = error_message(v["scheduler"], v["workers"], v["client"])
return m["error"] or m["warning"] or None
except Exception as e:
return str(e) or type(e).__name__
def dashboard_url(scheduler: str | None) -> str | None:
given = os.environ.get("DASK_DASHBOARD_URL")
if given:
return given
if scheduler:
return f"http://{urlsplit(scheduler).hostname}:8787/status"
return None
def reference_dir(name: str) -> Path:
root = os.environ.get("TEA_REFERENCE_ROOT")
if not root:
raise ValueError("TEA_REFERENCE_ROOT is not set")
if not REFERENCE_NAME.match(name) or name in (".", ".."):
raise ValueError(f"no reference cohort {name!r}")
path = Path(root) / name
if path.resolve().parent != Path(root).resolve() or not path.is_dir():
raise ValueError(f"no reference cohort {name!r}")
return path
def reference_edfs(name: str) -> int:
return sum(
1 for p in reference_dir(name).rglob("*") if p.suffix.lower() == ".edf" and p.is_file()
)
def _dashboard_ok(url: str) -> bool:
parts = urlsplit(url)
try:
with urllib.request.urlopen(f"{parts.scheme}://{parts.netloc}/health", timeout=3) as r:
return 200 <= r.status < 300
except (OSError, ValueError):
return False
def _expected_workers() -> int | None:
try:
return int(os.environ["DASK_EXPECTED_WORKERS"])
except (KeyError, ValueError):
return None
def health(execution: Execution | None = None, reference: str | None = None) -> Health:
r = resolve(execution)
if reference is not None and (not REFERENCE_NAME.match(reference) or reference in (".", "..")):
raise ExecutionError(f"reference {reference!r} is not a cohort name")
url = dashboard_url(r.scheduler)
h = Health(
mode=r.mode,
scheduler=r.scheduler,
reachable=False,
expected_workers=_expected_workers(),
dashboard_url=url,
dashboard_ok=_dashboard_ok(url) if url else None,
)
def count_here():
try:
return {"name": reference, "edfs": reference_edfs(reference)}
except (OSError, ValueError):
return {"name": reference, "edfs": None}
if r.mode != "remote":
h.reachable = True
h.workers = 1 if r.mode == "sync" else local_workers()
h.threads = h.workers
if reference is not None:
h.reference = count_here()
return h
from distributed import Client
client = None
try:
started = time.perf_counter()
client = Client(r.scheduler, timeout=5)
h.latency_ms = (time.perf_counter() - started) * 1000
h.reachable = True
info = client.scheduler_info()["workers"]
h.workers = len(info)
h.threads = sum(w["nthreads"] for w in info.values())
h.version_error = versions_error(client)
h.versions_ok = h.version_error is None
if reference is not None and info:
h.reference = {"name": reference, "edfs": None}
try:
h.reference["edfs"] = client.submit(
reference_edfs, reference, pure=False, workers=[next(iter(info))]
).result(timeout=5)
except Exception:
pass
elif reference is not None:
h.reference = {"name": reference, "edfs": None}
except Exception as e:
if client is None:
h.reachable = False
h.error = str(e) or type(e).__name__
finally:
if client is not None:
client.close()
return h
-2
View File
@@ -1,5 +1,3 @@
"""Where the platform data lives. One env var per location; SQLite by default."""
import os
from pathlib import Path
+5 -15
View File
@@ -1,7 +1,3 @@
"""A site's configuration, append-only: every save is a new version; runs name the one they
used. Two kinds: pipelines (the drawn graphs) and concept maps (the site's codes in
platform terms, FHIR ConceptMaps)."""
from datetime import UTC, datetime
import dlt
@@ -26,7 +22,7 @@ def latest_version(item_id: str, kind: str = "pipelines") -> int:
def save(item_id: str, doc: BaseModel, kind: str = "pipelines") -> int:
version = latest_version(item_id, kind) + 1
row = {
"pipeline_id": item_id, # the item's id, whichever kind
"pipeline_id": item_id,
"version": version,
"doc": doc.model_dump_json(exclude_none=True),
"saved_at": datetime.now(UTC),
@@ -37,14 +33,13 @@ def save(item_id: str, doc: BaseModel, kind: str = "pipelines") -> int:
return version
def listing(kind: str = "pipelines") -> list[dict]:
"""Every item's id with its latest version and when it was saved."""
def pipelines() -> list[dict]:
with engine().connect() as con:
if not inspect(con).has_table(kind, schema="config"):
if not inspect(con).has_table("pipelines", schema="config"):
return []
sql = text(
"select pipeline_id, max(version) as version, max(saved_at) as saved_at "
f"from config.{kind} group by pipeline_id order by pipeline_id"
"from config.pipelines group by pipeline_id order by pipeline_id"
)
return [dict(r) for r in con.execute(sql).mappings()]
@@ -57,16 +52,11 @@ def get(item_id: str, version: int | None = None, kind: str = "pipelines"):
return version, KINDS[kind].model_validate_json(doc)
def pipelines() -> list[dict]:
return listing("pipelines")
def concept_map(item_id: str) -> ConceptMap:
"""The latest version of a concept map."""
return get(item_id, kind="concept_maps")[1]
if __name__ == "__main__": # python -m persistance.config_log <kind> <id> <doc.json>
if __name__ == "__main__":
import sys
from pathlib import Path
+2 -10
View File
@@ -1,10 +1,3 @@
"""The platform database (SQLite now, PostgreSQL later): the dlt destination that writes it
and the engine that reads it.
On SQLite each schema is its own file (`platform__<schema>.db`, as dlt lays it out),
attached under its name, so the same SQL (`bronze.raw__...`) runs on both engines.
"""
from functools import cache
import dlt
@@ -31,14 +24,13 @@ def _sqlite(attach: bool) -> Engine:
def platform():
if platform_url().startswith("sqlite"):
return dlt.destinations.sqlalchemy(_sqlite(attach=False)) # dlt attaches its own
return dlt.destinations.sqlalchemy(_sqlite(attach=False))
return dlt.destinations.postgres(platform_url())
@cache
def engine() -> Engine:
"""For reading: every platform schema reachable by name."""
url = platform_url()
if url.startswith("sqlite"):
return _sqlite(attach=True)
return create_engine(make_url(url).set(drivername="postgresql+psycopg2")) # dlt's driver
return create_engine(make_url(url).set(drivername="postgresql+psycopg2"))
+248 -150
View File
@@ -1,19 +1,24 @@
"""The EEG analysis as the platform keeps it, by signal (the EDF's content hash, silver's
`eeg.edf`): its verdict and measures (`bronze.eeg_analysis`), its checks (`bronze.eeg_checks`)
and its metrics (`bronze.eeg_metrics`), written by the analysis job; the age curves' scores of
each metric (`bronze.eeg_scores`), by the scoring job. dbt places them in gold (tea)."""
import json
import re
from datetime import UTC, date, datetime
from typing import Literal
import dlt
from sqlalchemy import inspect, text
from pydantic import BaseModel, ConfigDict, Field, model_validator
from sqlalchemy import bindparam, inspect, text
from core.measures import as_day
from core.tea import ADOS2_ITEMS, ASSOCIATION_BIOMARKERS
from core.tea.fhir import eeg_study_id
from persistance import files
from persistance.destination import engine, platform
_SCORE_JOIN = "left join bronze.eeg_scores as s on s.edf = m.edf and s.metric = m.code"
VALUE_SCORE_JOIN = f"{_SCORE_JOIN} and s.part = 'value'"
REGION_SCORE_JOIN = f"{_SCORE_JOIN} and s.part = m.part and s.site = m.site"
def _text() -> dict: # a new dict per column: dlt writes the column's name into it
def _text() -> dict:
return {"data_type": "text", "nullable": True}
@@ -52,30 +57,13 @@ METRICS = {
"electrodes": _text(),
"zones": _text(),
}
ASSOCIATIONS = {
SITES = {
"key": {"data_type": "text"},
**{
c: _text()
for c in (
"model",
"biomarker",
"metric",
"zone",
"kind",
"outcome_code",
"event",
"principal",
"sensitivity",
"reason",
)
},
**{c: _number() for c in ("n", "odds_ratio", "ci_low", "ci_high", "p", "q", "sens_odds_ratio")},
"same_direction": {"data_type": "bool", "nullable": True},
}
ASSOCIATION_SCORES = {
"key": {"data_type": "text"},
**{c: _text() for c in ("edf", "model", "biomarker", "zone", "outcome_code")},
**{c: _number() for c in ("z", "probability", "reference_probability", "observed")},
"edf": {"data_type": "text"},
"code": _text(),
"part": _text(),
"site": _text(),
"value": _number(),
}
SCORES = {
"key": {"data_type": "text"},
@@ -92,21 +80,95 @@ def _write(name: str, rows: list[dict], columns: dict, key: str = "key") -> None
dlt.pipeline(name, destination=platform(), dataset_name="bronze").run(resource)
_ID = re.compile(r"^[^|]+\|\d{4}-\d{2}-\d{2}$")
MAX_IDS = 500
class Scope(BaseModel):
model_config = ConfigDict(
extra="forbid",
json_schema_extra={
"description": (
"Which EEGs an analysis takes: the pending ones, the first `n` of them, "
"or the named\n"
"ones (re-analysis), each named by the `id` that `/tea/eegs` shows."
)
},
)
mode: Literal["pending", "first_n", "ids"] = "pending"
n: int | None = Field(None, ge=1)
ids: list[str] = []
@model_validator(mode="after")
def _consistent(self):
if self.mode == "first_n":
if self.n is None:
raise ValueError("first_n needs n")
if self.ids:
raise ValueError("first_n takes no ids")
elif self.mode == "ids":
if not self.ids:
raise ValueError("ids needs a non-empty ids")
if self.n is not None:
raise ValueError("ids takes no n")
if len(self.ids) > MAX_IDS:
raise ValueError(f"ids takes at most {MAX_IDS} ids")
bad = [i for i in self.ids if not _ID.match(i)]
if bad:
raise ValueError(f"ids must look like person|YYYY-MM-DD, not {bad[0]!r}")
else:
if self.n is not None:
raise ValueError("pending takes no n")
if self.ids:
raise ValueError("pending takes no ids")
return self
def _with_dates(rows: list[dict]) -> list[dict]:
for r in rows:
if r["birth_date"] is not None and not isinstance(r["birth_date"], date):
r["birth_date"] = as_day(r["birth_date"])
return rows
def pending() -> list[dict]:
"""The hospital's EEG signals not analysed yet, each with the child's birth date."""
with engine().connect() as con:
if not inspect(con).has_table("eeg", schema="silver"):
return []
done = inspect(con).has_table("eeg_analysis", schema="bronze")
where = "and e.edf not in (select edf from bronze.eeg_analysis)" if done else ""
sql = text(f"""
select distinct e.edf, p.birth_date from silver.eeg as e
left join silver.person as p on p.person_id = e.person_id
where e.edf is not null {where}
order by e.edf
""") # fmt: skip
rows = [dict(r) for r in con.execute(sql).mappings()]
for r in rows: # SQLite gives dates as text
if r["birth_date"] is not None and not isinstance(r["birth_date"], date):
r["birth_date"] = date.fromisoformat(str(r["birth_date"])[:10])
return rows
return _with_dates(rows)
def select(scope: Scope) -> list[dict]:
if scope.mode == "pending":
return pending()
if scope.mode == "first_n":
return pending()[: scope.n]
found: dict[str, dict] = {}
sql = text("""
select e.edf, p.birth_date from silver.eeg as e
left join silver.person as p on p.person_id = e.person_id
where e.person_id = :p and cast(e.study_date as varchar(10)) = :d
""") # fmt: skip
with engine().connect() as con:
for one in scope.ids:
person, day = one.split("|")
rows = con.execute(sql, {"p": person, "d": day}).mappings()
row = next(iter(_with_dates([dict(r) for r in rows])), None)
if row is None:
raise LookupError(f"no EEG {one}")
if row["edf"] is None:
raise LookupError(f"EEG {one} has no signal")
found.setdefault(row["edf"], row)
return list(found.values())
def signal(edf: str) -> bytes:
@@ -117,9 +179,8 @@ def signal(edf: str) -> bytes:
def save_analyses(analyses: dict[str, object]) -> None:
"""Analyses by signal hash (models.tea.eeg.analysis.Analysis)."""
now = datetime.now(UTC)
found, checks, metrics = [], [], []
found, checks, metrics, sites = [], [], [], []
for edf, a in analyses.items():
found.append({
"edf": edf, "valid": a.valid, "level": a.level, "age_months": a.age_months,
@@ -129,16 +190,24 @@ def save_analyses(analyses: dict[str, object]) -> None:
"features": json.dumps(a.features), "error": a.error, "analysed_at": now,
}) # fmt: skip
checks += [{**c, "key": f"{edf}|{i}", "edf": edf} for i, c in enumerate(a.checks)]
metrics += [{"key": f"{edf}|{m.code}", "edf": edf, "code": m.code, "value": m.value,
"electrodes": json.dumps(m.electrodes), "zones": json.dumps(m.zones)}
for m in a.metrics] # fmt: skip
for m in a.metrics:
metrics.append({
"key": f"{edf}|{m.code}", "edf": edf, "code": m.code, "value": m.value,
"electrodes": json.dumps(m.electrodes), "zones": json.dumps(m.zones),
}) # fmt: skip
for part in ("electrodes", "zones"):
for site, value in getattr(m, part).items():
sites.append({
"key": f"{edf}|{m.code}|{part}|{site}", "edf": edf,
"code": m.code, "part": part, "site": site, "value": value,
}) # fmt: skip
_write("eeg_analysis", found, ANALYSIS, key="edf")
_write("eeg_checks", checks, CHECKS)
_write("eeg_metrics", metrics, METRICS)
_write("eeg_sites", sites, SITES)
def analysed() -> list[dict]:
"""Every valid analysis with its metrics: what the age curves score."""
with engine().connect() as con:
if not inspect(con).has_table("eeg_metrics", schema="bronze"):
return []
@@ -159,16 +228,12 @@ def analysed() -> list[dict]:
return list(out.values())
def ruled_out(as_of: date) -> list[dict]:
"""The age curves' reference group on the site: each valid EEG, studied by `as_of`, of a
child whose neurology verdict ruled TEA out by then (gold `tea_screening`) and that no
confirming verdict followed by then. Each as the curves train on it: its key (the
signal's hash), age in months and features."""
def without_diagnosis(as_of: date) -> list[dict]:
with engine().connect() as con:
if not (inspect(con).has_table("eeg_analysis", schema="bronze")
and inspect(con).has_table("tea_screening", schema="gold")): # fmt: skip
return []
sql = text("""
rows = con.execute(text("""
select a.edf, a.age_months, a.features
from bronze.eeg_analysis as a
join silver.eeg as e on e.edf = a.edf
@@ -178,96 +243,19 @@ def ruled_out(as_of: date) -> list[dict]:
and cast(s.not_confirmed_date as varchar(10)) <= :as_of
and (s.confirmed_date is null or cast(s.confirmed_date as varchar(10)) > :as_of)
order by a.edf
""") # fmt: skip (ISO days compare as text on both engines)
rows = con.execute(sql, {"as_of": as_of.isoformat()}).mappings()
"""), {"as_of": as_of.isoformat()}).mappings() # fmt: skip
return [{"key": r["edf"], "age_months": r["age_months"], "valid": True, "error": None,
"features": json.loads(r["features"])} for r in rows] # fmt: skip
def association_inputs(metrics: dict[str, str]) -> list[dict]:
"""What the EEG–ADOS-2 association reads: each valid EEG with the child's age at it, her
birth date, her first ADOS-2 (module and items) and the z its champion age curves gave
(`metrics`: biomarker -> EEG metric code), each `z_<biomarker>` or, by zone,
`z_<biomarker>_<zone>`. Oldest first per child."""
with engine().connect() as con:
has = lambda t, s: inspect(con).has_table(t, schema=s) # noqa: E731
if not (has("eeg_analysis", "bronze") and has("ados2", "silver")):
return []
eegs = [dict(r) for r in con.execute(text("""
select e.person_id, cast(e.study_date as varchar(10)) as study_date, a.edf,
a.age_months, cast(p.birth_date as varchar(10)) as birth_date
from bronze.eeg_analysis as a join silver.eeg as e on e.edf = a.edf
left join silver.person as p on p.person_id = e.person_id
where a.valid and a.age_months is not null
order by e.person_id, e.study_date, a.edf
""")).mappings()] # fmt: skip
first: dict[str, dict] = {}
for r in con.execute(text("""
select * from silver.ados2
order by person_id, case when evaluation_date is null then 1 else 0 end,
evaluation_date
""")).mappings(): # fmt: skip
first.setdefault(r["person_id"], dict(r))
z: dict[str, dict[str, float]] = {}
if has("eeg_scores", "bronze"):
codes = {code: b for b, code in metrics.items()}
for r in con.execute(text("""
select edf, metric, part, site, z from bronze.eeg_scores
where part in ('value', 'zones') and z is not null
""")).mappings(): # fmt: skip
b = codes.get(r["metric"])
if b is not None:
name = f"z_{b}" if r["part"] == "value" else f"z_{b}_{r['site']}"
z.setdefault(r["edf"], {})[name] = r["z"]
out = []
for e in eegs:
ados2 = first.get(e["person_id"])
if ados2 is not None:
out.append({**e, "ados2": ados2, **z.get(e["edf"], {})})
return out
def save_association(model: str, associations: list[dict], scores: list[dict]) -> None:
"""The champion association's pairs and each EEG's probabilities, replacing the last."""
with engine().begin() as con:
for table in ("ados2_association", "ados2_association_scores"):
if inspect(con).has_table(table, schema="bronze"):
con.execute(text(f"delete from bronze.{table}"))
_write("ados2_association", associations, ASSOCIATIONS)
_write("ados2_association_scores", scores, ASSOCIATION_SCORES)
def relation(edf: str) -> list[dict]:
"""One EEG's probabilities under the champion association, each with its pair."""
with engine().connect() as con:
if not inspect(con).has_table("ados2_association_scores", schema="bronze"):
return []
return [dict(r) for r in con.execute(text("""
select s.biomarker, a.metric, s.zone, s.outcome_code, a.kind, a.event, s.z,
s.probability, s.reference_probability, s.observed, a.odds_ratio,
a.ci_low, a.ci_high, a.q, a.n, s.model
from bronze.ados2_association_scores as s
join bronze.ados2_association as a
on a.model = s.model and a.biomarker = s.biomarker and a.zone = s.zone
and a.outcome_code = s.outcome_code
where s.edf = :e order by a.q, s.biomarker, s.zone
"""), {"e": edf}).mappings()] # fmt: skip
def save_scores(scenario: str, rows: list[dict]) -> None:
"""One age curve's scores of every EEG, replacing what it scored before."""
with engine().begin() as con:
if inspect(con).has_table("eeg_scores", schema="bronze"):
con.execute(text("delete from bronze.eeg_scores where scenario = :s"), {"s": scenario})
_write("eeg_scores", rows, SCORES)
def _id(person_id: str, study_date) -> str:
return f"{person_id}|{str(study_date)[:10]}"
def studies() -> list[dict]:
"""Every EEG with its analysis verdict (none while not analysed), newest first."""
with engine().connect() as con:
analysed = inspect(con).has_table("eeg_analysis", schema="bronze")
verdict = "a.valid, a.level, a.error, a.edf as analysed" if analysed else (
@@ -279,15 +267,61 @@ def studies() -> list[dict]:
order by e.study_date desc, e.person_id
""") # fmt: skip
rows = [dict(r) for r in con.execute(sql).mappings()]
return [{"id": _id(r["person_id"], r["study_date"]), "person_id": r["person_id"],
return [{"id": eeg_study_id(r["person_id"], r["study_date"]), "person_id": r["person_id"],
"study_date": str(r["study_date"])[:10], "lab_record_id": r["lab_record_id"],
"analysed": r["analysed"] is not None or r["error"] is not None,
"valid": r["valid"], "level": r["level"]} for r in rows] # fmt: skip
def summary() -> dict[str, int]:
with engine().connect() as con:
has_analysis = inspect(con).has_table("eeg_analysis", schema="bronze")
join = "left join bronze.eeg_analysis as b on b.edf = a.edf" if has_analysis else ""
analysed = "b.edf is not null" if has_analysis else "a.valid is not null"
failed = "b.error is not null" if has_analysis else "false"
studies = con.execute(text(f"""
select
count(*) as eegs,
count(case when {analysed} then 1 end) as analysed,
count(case when a.valid then 1 end) as valid,
count(case when {analysed} and a.valid = false then 1 end) as not_valid,
count(case when {analysed} and {failed} then 1 end) as failed
from gold.tea_eeg_analyses as a {join}
""")).mappings().one() # fmt: skip
tables = inspect(con)
if not tables.has_table("eeg_metrics", schema="bronze"):
metrics = {"metrics": 0, "metrics_with_z": 0, "high": 0, "low": 0}
else:
scores = tables.has_table("eeg_scores", schema="bronze")
join = VALUE_SCORE_JOIN if scores else ""
z, outside = ("s.z", "s.outside") if scores else ("null", "null")
metrics = con.execute(text(f"""
select count(*) as metrics, count({z}) as metrics_with_z,
count(case when {outside} > 0 then 1 end) as high,
count(case when {outside} < 0 then 1 end) as low
from bronze.eeg_metrics as m {join}
where m.edf in (select edf from silver.eeg)
""")).mappings().one() # fmt: skip
served = """
from silver.eeg as e
join silver.person as p on p.person_id = e.person_id
where e.edf is not null
"""
fhir_eegs = con.execute(text(f"select count(*) {served}")).scalar_one()
fhir_metrics = 0
if tables.has_table("eeg_metrics", schema="bronze"):
fhir_metrics = con.execute(
text(f"""
select count(*) from bronze.eeg_metrics as m
join (select e.edf {served}) as e on e.edf = m.edf
""")
).scalar_one()
return {**studies, **metrics, "fhir_eegs": fhir_eegs, "fhir_metrics": fhir_metrics}
def study(eeg_id: str) -> dict | None:
"""One EEG's verdict, age and metrics, each with its age curve's score and band (its 5th,
50th and 95th percentiles at her age) when scored."""
if not _ID.fullmatch(eeg_id):
return None
person, day = eeg_id.split("|")
with engine().connect() as con:
if not inspect(con).has_table("eeg_analysis", schema="bronze"):
@@ -300,29 +334,93 @@ def study(eeg_id: str) -> dict | None:
if head is None:
return None
scored = inspect(con).has_table("eeg_scores", schema="bronze")
score = ("s.z, s.outside, s.p5, s.median, s.p95, s.model" if scored else
"null as z, null as outside, null as p5, null as median, null as p95, "
"null as model") # fmt: skip
join = ("left join bronze.eeg_scores as s on s.edf = m.edf and s.metric = m.code "
"and s.part = 'value'") if scored else "" # fmt: skip
score = "s.z, s.outside, s.model" if scored else "null as z, null as outside, null as model"
join = VALUE_SCORE_JOIN if scored else ""
metrics = con.execute(text(f"""
select m.code, m.value, m.electrodes, m.zones, {score}
from bronze.eeg_metrics as m {join}
select m.code, m.value, {score} from bronze.eeg_metrics as m {join}
where m.edf = :e and m.value is not null order by m.code
"""), {"e": head["edf"]}).mappings() # fmt: skip
found = [dict(m) for m in metrics]
sites: dict[tuple[str, str, str], float | None] = {}
if scored:
for r in con.execute(text("""
select metric, part, site, z from bronze.eeg_scores
where edf = :e and part in ('zones', 'electrodes')
"""), {"e": head["edf"]}).mappings(): # fmt: skip
sites[(r["metric"], r["part"], r["site"])] = r["z"]
for m in found:
for part in ("zones", "electrodes"):
values = json.loads(m[part] or "{}")
m[part] = [{"site": k, "value": v, "z": sites.get((m["code"], part, k))}
for k, v in values.items() if v is not None and v == v] # fmt: skip
return {"id": eeg_id, "valid": head["valid"], "level": head["level"],
"age_months": head["age_months"], "metrics": found,
"relation": relation(head["edf"])} # fmt: skip
details = {}
for kind in ("checks", "regions"):
table = f"tea_eeg_{kind}"
details[kind] = []
if inspect(con).has_table(table, schema="gold"):
rows = con.execute(
text(f"select * from gold.{table} where eeg_id = :id"), {"id": eeg_id}
).mappings()
details[kind] = [
{k: v for k, v in row.items() if k not in ("person_id", "eeg_id")}
for row in rows
]
return {"id": eeg_id, "valid": head["valid"], "level": head["level"],
"age_months": head["age_months"], "metrics": found, **details} # fmt: skip
ASSOCIATIONS = {
"key": {"data_type": "text"},
"model": _text(),
"level": _text(),
"n_cohort": {"data_type": "bigint"},
**{c: _text() for c in ("biomarker", "zone", "kind", "outcome_code", "event", "method")},
"n": {"data_type": "bigint"},
**{c: _number() for c in ("odds_ratio", "ci_low", "ci_high", "p", "q")},
"sens_model": _text(),
"sens_odds_ratio": _number(),
"same_direction": {"data_type": "bool", "nullable": True},
"reason": _text(),
}
ASSOCIATION_SCORES = {
"key": {"data_type": "text"},
**{c: _text() for c in ("model", "eeg_id", "pair")},
**{c: _number() for c in ("z", "probability", "reference_probability")},
}
def _save_association(name: str, version: int, rows: list[dict], columns: dict) -> None:
with engine().begin() as con:
if inspect(con).has_table(name, schema="bronze"):
con.execute(text(f"delete from bronze.{name}"))
_write(name, [{**row, "model": f"tea.ados2_association/{version}"} for row in rows], columns)
def save_associations(version: int, rows: list[dict]) -> None:
_save_association("eeg_associations", version, rows, ASSOCIATIONS)
def save_association_scores(version: int, rows: list[dict]) -> None:
_save_association("eeg_association_scores", version, rows, ASSOCIATION_SCORES)
def association_cohort_rows() -> tuple[list[dict], list[dict]]:
studies, scores = [], []
with engine().connect() as con:
tables = inspect(con)
if tables.has_table("eeg_analysis", schema="bronze"):
items = ", ".join(ADOS2_ITEMS)
selected_items = ", ".join(f"t.{i}" for i in ADOS2_ITEMS)
query = text(f"""
with first_ados as (
select person_id, module, evaluation_date, {items},
row_number() over (
partition by person_id order by evaluation_date nulls last, known_at
) as rn
from silver.ados2
)
select e.person_id, e.study_date, e.edf, a.age_months,
t.module, t.evaluation_date, p.birth_date, {selected_items}
from silver.eeg as e
join bronze.eeg_analysis as a on a.edf = e.edf
join first_ados as t on t.person_id = e.person_id and t.rn = 1
left join silver.person as p on p.person_id = e.person_id
where a.valid and a.age_months is not null
""")
studies = [dict(row) for row in con.execute(query).mappings()]
if studies and tables.has_table("eeg_scores", schema="bronze"):
query = text("""
select edf, metric, part, site, z from bronze.eeg_scores
where metric in :metrics and z is not null
""").bindparams(bindparam("metrics", expanding=True))
metrics = list(ASSOCIATION_BIOMARKERS.values())
scores = [dict(row) for row in con.execute(query, {"metrics": metrics}).mappings()]
return studies, scores
+95 -53
View File
@@ -1,12 +1,11 @@
"""The rows the FHIR resources are built from (core.fhir): persons, their identifiers and
names, and every study instance of the catalog (`silver.<study>`), up to a cut-off day."""
from datetime import date
from sqlalchemy import bindparam, inspect, text
from core import catalog
from core import catalog, tea
from core.measures import as_day
from persistance.destination import engine
from persistance.eeg import REGION_SCORE_JOIN, VALUE_SCORE_JOIN
PERSONS = """
select p.person_id, p.birth_date, p.sex, d.death_date{extra}
@@ -19,6 +18,10 @@ CACU_PERSONS = PERSONS.format(
join=" left join gold.cacu_follow_up as f on f.person_id = p.person_id",
)
CAMA_PERSONS = PERSONS.format(extra="", join="")
TEA_PERSONS = PERSONS.format(
extra=", f.status, f.step, f.age_group",
join=" left join gold.tea_follow_up as f on f.person_id = p.person_id",
)
COMMON = {
"names": "select person_id, text from silver.person_name where person_id in :persons",
@@ -37,7 +40,6 @@ COMMON = {
and (icd10 is not null or diagnosis_text is not null)
order by person_id, note_date
""",
# The timeline's inferred procedures of these kinds (the domain's `PROCEDURES`).
"procedure": """
select distinct person_id, date, type from gold.{domain}_events
where person_id in :persons and date <= :cutoff and type in :types
@@ -52,13 +54,62 @@ COMMON = {
""",
}
TEA_PERSONS = PERSONS.format(extra="", join="")
_TEA_EEG_SCOPE = "e.edf is not null and e.person_id in :persons and e.study_date <= :cutoff"
_TEA_EEG_SOURCE = "from silver.eeg as e join silver.person as p on p.person_id = e.person_id"
_TEA_SCORE_FIELDS = "z, outside, p5, median, p95, model"
_TEA_ALTERATIONS = ", ".join(f"f.alt_{metric}" for metric in tea.EEG_METRICS)
READS = {
"tea": {
"births": "select person_id, birth_date from silver.person where person_id in :persons",
"person": TEA_PERSONS + " where p.person_id = :id",
"persons": TEA_PERSONS + " order by p.person_id",
"follow_up": "select * from gold.tea_follow_up where start_date <= :cutoff",
"eegs": f"""
select e.person_id, e.study_date, e.edf, {{analysis_fields}}
{_TEA_EEG_SOURCE} {{analysis_join}}
where {_TEA_EEG_SCOPE} order by e.person_id, e.study_date, e.edf
""",
"checks": f"""
select e.person_id, e.study_date, c.*
{_TEA_EEG_SOURCE} join bronze.eeg_checks as c on c.edf = e.edf
where {_TEA_EEG_SCOPE} order by e.person_id, e.study_date, c.code, c.electrode
""",
"metrics": f"""
select e.person_id, e.study_date, m.edf, m.code, m.value, {{score_fields}}
{_TEA_EEG_SOURCE} join bronze.eeg_metrics as m on m.edf = e.edf
{{score_join}}
where {_TEA_EEG_SCOPE} order by e.person_id, e.study_date, m.code
""",
"regions": f"""
select e.person_id, e.study_date, m.edf, m.code, m.site, m.value,
case m.part when 'electrodes' then 'electrode' when 'zones' then 'zone' end as kind,
{{score_fields}}
{_TEA_EEG_SOURCE} join bronze.eeg_sites as m on m.edf = e.edf
{{score_join}}
where {_TEA_EEG_SCOPE} order by e.person_id, e.study_date, m.code, m.part, m.site
""",
"association_scores": f"""
select s.person_id, s.study_date, s.pair, s.model, s.probability,
s.reference_probability, e.edf,
a.biomarker, a.n, a.n_cohort, a.level, a.q, a.odds_ratio,
a.ci_low, a.ci_high, a.same_direction, {_TEA_ALTERATIONS},
(select min(t.evaluation_date) from silver.ados2 as t
where t.person_id = s.person_id and t.evaluation_date <= :cutoff
) as evaluation_date
from gold.tea_association_scores as s
join gold.tea_associations as a on a.key = s.pair and a.model = s.model
join silver.eeg as e on e.person_id = s.person_id and e.study_date = s.study_date
join silver.person as p on p.person_id = e.person_id
left join gold.tea_follow_up as f on f.person_id = s.person_id
where {_TEA_EEG_SCOPE}
order by s.person_id, s.study_date, e.edf, s.pair
""",
},
"cacu": {
"person": CACU_PERSONS + " where p.person_id = :id",
"persons": CACU_PERSONS + " order by p.person_id",
# The list: whoever had a cytology sampled within [start, cutoff], with the latest one.
"follow_up": f"""
select x.*, w.recent from ({CACU_PERSONS}) as x
join (select person_id, max(sample_date) as recent from silver.cervical_cytology
@@ -66,50 +117,21 @@ READS = {
group by person_id) as w on w.person_id = x.person_id
order by w.recent desc, x.person_id
""",
# Days from a sample to its diagnosis, when known by the cut-off (gold).
"diagnosis_days": """
select person_id, sample_date, days_sample_diagnosis as days
from gold.cacu_samples
where person_id in :persons and history = 0 and diagnosis_date <= :cutoff
""",
},
"tea": {
"person": TEA_PERSONS + " where p.person_id = :id",
"persons": TEA_PERSONS + " order by p.person_id",
# The list's candidates (core.tea.follow_up): each child of the screening cohort, with
# her latest M-CHAT score and ADOS-2 by the cut-off, her EEGs and, of each, the metrics
# outside the age curve's band (one row per child, EEG and such metric).
"follow_up": """
select s.*, mc.score, {ados2}, e.eeg_id, e.study_date as eeg_study_date, e.valid,
m.code as metric, m.outside
from gold.tea_screening as s
left join (select person_id, max(screening_date) as last_mchat from silver.mchat
where screening_date <= :cutoff group by person_id) as lm
on lm.person_id = s.person_id
left join silver.mchat as mc
on mc.person_id = lm.person_id and mc.screening_date = lm.last_mchat
left join (select person_id, max(evaluation_date) as last_ados from silver.ados2
where evaluation_date <= :cutoff group by person_id) as la
on la.person_id = s.person_id
left join silver.ados2 as a
on a.person_id = la.person_id and a.evaluation_date = la.last_ados
left join gold.tea_eegs as e on e.person_id = s.person_id
left join gold.tea_eeg_metrics as m
on m.eeg_id = e.eeg_id and m.outside is not null and m.outside <> 0
where s.mchat_date <= :cutoff
""".replace("{ados2}", ", ".join(f"a.{f}" for f in catalog.studies()["ados2"].fields)),
},
"cama": {
"person": CAMA_PERSONS + " where p.person_id = :id",
"persons": CAMA_PERSONS + " order by p.person_id",
# Her treatments, by kind (the timeline's `treatment` events carry it as their code).
"procedure": """
select distinct person_id, date, value_code as type from gold.cama_events
where person_id in :persons and date <= :cutoff and type in :types
and value_code is not null
order by person_id, date, type
""",
# What clinical notes diagnosed, and each recurrence (a study of the catalog).
"condition": """
select person_id, note_date, specialty, icd10, reason, diagnosis_text,
null as study, null as code
@@ -122,15 +144,11 @@ READS = {
where person_id in :persons and diagnosis_date <= :cutoff
order by person_id, note_date
""",
# Days from a mammogram to its diagnosis, when known by the cut-off (gold; as the
# indicator, only without a breast cancer note before it).
"diagnosis_days": """
select person_id, exam_date as sample_date, days_sample_diagnosis as days
from gold.cama_mammograms
where person_id in :persons and history = 0 and diagnosis_date <= :cutoff
""",
# The list's candidates: each reported mammogram by the cut-off and its biopsies
# (core.cama.follow_up picks the latest per patient and places her in the window).
"follow_up": """
select * from gold.cama_mammogram_biopsies
where birads is not null and report_date <= :cutoff
@@ -139,24 +157,50 @@ READS = {
}
_TEA_OPTIONAL = {"checks": "eeg_checks", "metrics": "eeg_metrics", "regions": "eeg_sites"}
def _tea_sql(query, kind, tables):
if kind == "eegs":
fields = ("valid", "duration_min", "age_months", "channels")
analysed = tables.has_table("eeg_analysis", schema="bronze")
return query.format(
analysis_fields=", ".join(f"a.{f}" if analysed else f"null as {f}" for f in fields),
analysis_join="left join bronze.eeg_analysis as a on a.edf = e.edf" if analysed else "",
)
if kind in _TEA_OPTIONAL and not tables.has_table(_TEA_OPTIONAL[kind], schema="bronze"):
return None
if kind in ("metrics", "regions"):
scored = tables.has_table("eeg_scores", schema="bronze")
score_join = REGION_SCORE_JOIN if kind == "regions" else VALUE_SCORE_JOIN
return query.format(
score_fields=", ".join(
f"s.{f}" if scored else f"null as {f}" for f in _TEA_SCORE_FIELDS.split(", ")
),
score_join=score_join if scored else "",
)
return query
def rows(domain: str, kind: str, **params) -> list[dict]:
"""The rows of one kind for the domain. `persons` (and `types`) limit them to those;
none when the table doesn't exist yet (no risk batch)."""
sql = text((READS.get(domain, {}).get(kind) or COMMON[kind]).replace("{domain}", domain))
for many in ("persons", "types"):
if many in params:
sql = sql.bindparams(bindparam(many, expanding=True))
if not params[many]:
return []
if any(many in params and not params[many] for many in ("persons", "types")):
return []
query = (READS.get(domain, {}).get(kind) or COMMON[kind]).replace("{domain}", domain)
with engine().connect() as con:
if kind == "risk" and not inspect(con).has_table(f"{domain}_risk", schema="gold"):
return []
if domain == "tea":
query = _tea_sql(query, kind, inspect(con))
if query is None:
return []
sql = text(query)
for many in ("persons", "types"):
if many in params:
sql = sql.bindparams(bindparam(many, expanding=True))
return [dict(r) for r in con.execute(sql, params).mappings()]
def instances(study: str, persons: list[str], cutoff: str) -> list[dict]:
"""A study's instances of these persons that began by the cut-off (its first event's
date), as `silver.<study>` holds them; what was known by then is core.fhir.known's."""
spec = catalog.studies()[study]
first = next(e.date for e in spec.events.values() if e.parent is None)
sql = text(
@@ -172,11 +216,9 @@ def instances(study: str, persons: list[str], cutoff: str) -> list[dict]:
def last_data_day(domain: str) -> date | None:
"""The last day anything happened in the domain's timeline (up to today): the default
cut-off."""
sql = text(f"select max(date) from gold.{domain}_events where date <= :today")
with engine().connect() as con:
if not inspect(con).has_table(f"{domain}_events", schema="gold"):
return None
found = con.execute(sql, {"today": date.today().isoformat()}).scalar()
return None if found is None else date.fromisoformat(str(found)[:10])
return as_day(found)
+3 -19
View File
@@ -1,8 +1,3 @@
"""Files kept whole (a PDF report, an EEG's signal), once each, by content hash. A source keeps
every binary value it collects here and passes on its hash, so the nodes after it carry a
reference, never the content; `read` and the analyses fetch the content by hash, and a
catalog `file` field holds the hash in silver."""
import hashlib
import os
import shutil
@@ -15,7 +10,7 @@ from sqlalchemy.types import TypeEngine
from persistance.destination import engine
TABLE = "files"
INSERT_BYTES = 32_000_000 # file contents per insert
INSERT_BYTES = 32_000_000
FILES = Table(TABLE, MetaData(), Column("key", Text, primary_key=True),
Column("content", LargeBinary, nullable=False), schema="bronze") # fmt: skip
@@ -24,15 +19,10 @@ def key(content: bytes) -> str:
return hashlib.sha256(content).hexdigest()
FLUSH_BYTES = 256_000_000 # file contents stored per load
FLUSH_BYTES = 256_000_000
class Collector:
"""A dlt map that replaces each binary value of a row with its hash, spooling each new
content to a folder on disk (ISSSTELEON_DATA) so a source of large files (scans, EEG
recordings) never holds them in memory; `keep` stores them once the rows have loaded
(a dlt load can't run inside another's extract), FLUSH_BYTES at a time."""
def __init__(self):
self.spool = Path(tempfile.mkdtemp(prefix="files-", dir=os.environ.get("ISSSTELEON_DATA")))
self.keys: list[str] = []
@@ -67,13 +57,10 @@ class Collector:
def reference_type(sql_type: TypeEngine) -> TypeEngine:
"""For a source that reflects its columns' types (dlt's `sql_table`): a binary column
is text, since what it carries from the source on is the file's hash."""
return Text() if isinstance(sql_type, LargeBinary) else sql_type
def known(keys: set[str]) -> set[str]:
"""Which of these hashes the platform already keeps."""
with engine().connect() as con:
if not keys or not inspect(con).has_table(TABLE, schema="bronze"):
return set()
@@ -82,8 +69,6 @@ def known(keys: set[str]) -> set[str]:
def keep(contents: dict[str, bytes]) -> None:
"""Contents by hash, each written once, straight into the table (SQLAlchemy, a few at a
time): a load through dlt would write every file as base64 JSON and hold it."""
if not contents:
return
with engine().begin() as con:
@@ -95,7 +80,7 @@ def keep(contents: dict[str, bytes]) -> None:
if k in have:
continue
row = {"key": k, "content": c}
if "_dlt_id" in columns: # a table an earlier platform made through dlt
if "_dlt_id" in columns:
row |= {"_dlt_load_id": "files", "_dlt_id": k[:14]}
batch.append(row)
size += len(c)
@@ -113,7 +98,6 @@ def _with_dlt():
def content(key: str) -> bytes | None:
"""A file's content, or None when the platform has no file with that hash."""
with engine().connect() as con:
if not inspect(con).has_table(TABLE, schema="bronze"):
return None
-15
View File
@@ -1,5 +1,3 @@
"""What the models read from gold, and the risk batches they write back."""
from datetime import UTC, date, datetime
import dlt
@@ -13,9 +11,6 @@ TIMELINE = ["person_id", "index_date", "date", "type", "value_code", "value_num"
def timelines(events: str, cohort: str, as_of: date | None = None) -> pd.DataFrame:
"""The events (`gold.<events>`) up to `as_of` (default: today) of every member of
`gold.<cohort>`, each with her index date and her record number (the lowest of the
hospital's numbers for her: a deterministic order among patients), in date order."""
sql = text(f"""
select e.person_id, c.index_date, e.date, e.type, e.value_code, e.value_num,
e.source_table, e.source_id, n.record_number
@@ -32,20 +27,10 @@ def timelines(events: str, cohort: str, as_of: date | None = None) -> pd.DataFra
return found.astype({"value_num": float})[TIMELINE]
def person_numbers() -> dict[str, str]:
"""Each person's record numbers as the link node compared them (for checks and reviews)."""
sql = text("select distinct person_id, record_number from bronze.staged__identity "
"where person_id is not null and record_number is not null") # fmt: skip
with engine().connect() as con:
return dict(con.execute(sql).fetchall())
SCORES = "model_scores"
def save_scores(model: str, version: int, scores: pd.DataFrame) -> None:
"""A model's risk batch into `bronze.model_scores`, replacing its previous batch; dbt
places it in gold (`cacu_risk`)."""
with engine().begin() as con:
if inspect(con).has_table(SCORES, schema="bronze"):
con.execute(text(f"delete from bronze.{SCORES} where model = :m"), {"m": model})

Some files were not shown because too many files have changed in this diff Show More