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).
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
"""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)]
|
||||
@@ -42,6 +44,13 @@ RESTRICTED_REPETITIVE_ITEMS = ["intonation", "stereotyped_language", "unusual_se
|
||||
"hand_finger_mannerisms", "repetitive_interests"] # fmt: skip
|
||||
|
||||
|
||||
# The scored items, in catalog order.
|
||||
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
|
||||
|
||||
|
||||
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"}
|
||||
|
||||
@@ -35,3 +35,45 @@ models:
|
||||
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]
|
||||
|
||||
@@ -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 %}
|
||||
@@ -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 %}
|
||||
@@ -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
|
||||
@@ -6,6 +6,7 @@ sources:
|
||||
- name: model_scores
|
||||
- name: eeg_analysis
|
||||
- name: eeg_metrics
|
||||
- name: eeg_sites
|
||||
- name: eeg_scores
|
||||
- name: eeg_checks
|
||||
- name: review_log
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"""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)."""
|
||||
and its metrics (`bronze.eeg_metrics` and `bronze.eeg_sites`), 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
|
||||
@@ -55,6 +56,14 @@ METRICS = {
|
||||
"electrodes": _text(),
|
||||
"zones": _text(),
|
||||
}
|
||||
SITES = {
|
||||
"key": {"data_type": "text"},
|
||||
"edf": {"data_type": "text"},
|
||||
"code": _text(),
|
||||
"part": _text(),
|
||||
"site": _text(),
|
||||
"value": _number(),
|
||||
}
|
||||
SCORES = {
|
||||
"key": {"data_type": "text"},
|
||||
"edf": {"data_type": "text"},
|
||||
@@ -169,7 +178,7 @@ 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,
|
||||
@@ -179,12 +188,21 @@ 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]:
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
from core import catalog
|
||||
from core.tea import ADOS2_ITEMS, RESTRICTED_REPETITIVE_ITEMS, SOCIAL_AFFECT_ITEMS, dbt_vars
|
||||
|
||||
|
||||
def test_ados2_items_match_catalog_order():
|
||||
fields = catalog.studies()["ados2"].fields
|
||||
assert ADOS2_ITEMS == [
|
||||
name for name, field in fields.items()
|
||||
if field.type == "number" and not name.endswith("_total")
|
||||
] # fmt: skip
|
||||
assert len(ADOS2_ITEMS) == 22
|
||||
assert set(SOCIAL_AFFECT_ITEMS + RESTRICTED_REPETITIVE_ITEMS) <= set(ADOS2_ITEMS)
|
||||
assert dbt_vars()["ados2_items"] == ADOS2_ITEMS
|
||||
@@ -0,0 +1,124 @@
|
||||
import json
|
||||
import sys
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from core import catalog
|
||||
from core.tea import ADOS2_ITEMS
|
||||
|
||||
MODELS = ["tea_follow_up", "tea_eeg_checks", "tea_eeg_regions"]
|
||||
METRIC = "posterior_rhythm"
|
||||
EDF = "signal"
|
||||
MODEL = "tea_posterior_rhythm/1"
|
||||
CHILDREN = ("mchat", "neuro", "eeg")
|
||||
|
||||
|
||||
def _load_and_build():
|
||||
from persistance import eeg, nodes, silver
|
||||
|
||||
def day(month):
|
||||
return date(2024, month, 1)
|
||||
|
||||
nodes.stage("identity", "tea", "identity", [
|
||||
{"person_id": child, "_record": child, "_index": 0, "birth_date": date(2022, 1, 1),
|
||||
"sex": "female"}
|
||||
for child in CHILDREN
|
||||
], silver.identity_columns()) # fmt: skip
|
||||
|
||||
observations = []
|
||||
|
||||
def record(person_id, study, **values):
|
||||
spec = catalog.studies()[study]
|
||||
instance = json.dumps([str(values[key]) for key in spec.key])
|
||||
for name, value in values.items():
|
||||
observations.append({
|
||||
"person_id": person_id, "study": study, "instance": instance, "field": name,
|
||||
"_record": f"{person_id}|{study}|{instance}", "_index": 0,
|
||||
catalog.value_column(spec.fields[name]): value,
|
||||
}) # fmt: skip
|
||||
|
||||
for child, score in zip(CHILDREN, (3, 5, 7), strict=True):
|
||||
record(child, "mchat", screening_date=day(1), score=score)
|
||||
record("neuro", "mchat", screening_date=day(2), score=11)
|
||||
record("neuro", "ados2", evaluation_date=day(2), module="module_1", pointing=3, gestures=3)
|
||||
record("neuro", "ados2", evaluation_date=day(3), module="module_2",
|
||||
**{item: i % 3 for i, item in enumerate(ADOS2_ITEMS)}) # fmt: skip
|
||||
record("eeg", "ados2", evaluation_date=day(2), module="module_1", pointing=2)
|
||||
for child in ("neuro", "eeg"):
|
||||
record(child, "clinical_note", note_date=day(4), specialty="pediatric_neurology",
|
||||
icd10="F84.0") # fmt: skip
|
||||
record("eeg", "eeg", study_date=day(5), edf=EDF)
|
||||
nodes.stage("observation", "tea", "observation", observations, silver.OBSERVATION)
|
||||
|
||||
metric = SimpleNamespace(
|
||||
code=METRIC, value=8.0, electrodes={"O1": 7.5, "O2": 8.5}, zones={"occipital": 8.0}
|
||||
)
|
||||
check = {"code": "posterior_check", "electrode": "O1", "value": 7.5, "text": "Check",
|
||||
"unit": "Hz", "low": 4.0, "high": 7.0, "decisive": False,
|
||||
"abnormal": True} # fmt: skip
|
||||
eeg.save_analyses({EDF: SimpleNamespace(
|
||||
valid=True, level="complete", age_months=28, clean_fraction=1, bad_channels=0,
|
||||
channels=19, duration_min=20, line_noise_db=0, sleep=False, features={},
|
||||
error=None, checks=[check], metrics=[metric],
|
||||
)}) # fmt: skip
|
||||
eeg.save_scores(METRIC, [
|
||||
{"key": f"{EDF}|{METRIC}|{part}|{site or ''}", "edf": EDF, "scenario": METRIC,
|
||||
"model": MODEL, "metric": METRIC, "part": part, "site": site, "z": z,
|
||||
"outside": 1, "p5": 4.0, "median": 5.5, "p95": 7.0}
|
||||
for part, site, z in (("value", None, 2.5), ("electrodes", "O1", 2.0),
|
||||
("zones", "occipital", 2.5))
|
||||
]) # fmt: skip
|
||||
|
||||
silver.build([f"+{model}" for model in MODELS])
|
||||
silver.build(MODELS)
|
||||
|
||||
|
||||
def test_tea_follow_up(platform):
|
||||
platform.run(sys.executable, str(Path(__file__).resolve()))
|
||||
q = platform.query
|
||||
items = ", ".join(f"ados2_{item}" for item in ADOS2_ITEMS)
|
||||
rows = {
|
||||
row[0]: row[1:]
|
||||
for row in q(
|
||||
"select person_id, step, status, step_date, mchat_score, ados2_date, ados2_module, "
|
||||
f"eeg_result, eeg_scored, {items} from gold.tea_follow_up"
|
||||
)
|
||||
}
|
||||
assert set(rows) == set(CHILDREN)
|
||||
expected = {
|
||||
"mchat": ("mchat_only", "active", "2024-01-01", 3, None, None, "no_valid_eeg", None),
|
||||
"neuro": ("neurology", "active", "2024-04-01", 5, "2024-03-01", "module_2",
|
||||
"no_valid_eeg", None),
|
||||
"eeg": ("eeg", "finished", "2024-05-01", 7, "2024-02-01", "module_1", "abnormal", True),
|
||||
} # fmt: skip
|
||||
expected_items = {
|
||||
"mchat": (None,) * len(ADOS2_ITEMS),
|
||||
"neuro": tuple(i % 3 for i in range(len(ADOS2_ITEMS))),
|
||||
"eeg": tuple(2 if item == "pointing" else None for item in ADOS2_ITEMS),
|
||||
}
|
||||
for child, row in rows.items():
|
||||
step, status, step_date, score, ados2_date, module, result, scored, *values = row
|
||||
assert (step, status, str(step_date), score, str(ados2_date) if ados2_date else None,
|
||||
module, result, scored) == expected[child] # fmt: skip
|
||||
assert tuple(values) == expected_items[child]
|
||||
|
||||
eeg_id = "eeg|2024-05-01"
|
||||
assert q(
|
||||
"select eeg_id, eeg_duration_min, eeg_channels, altered, alt_posterior_rhythm "
|
||||
"from gold.tea_follow_up where person_id = 'eeg'"
|
||||
) == [(eeg_id, 20, 19, True, True)]
|
||||
assert q("select eeg_id, code, electrode, value from gold.tea_eeg_checks") == [
|
||||
(eeg_id, "posterior_check", "O1", 7.5)
|
||||
]
|
||||
assert q(
|
||||
"select eeg_id, code, kind, site, value, z, model from gold.tea_eeg_regions order by site"
|
||||
) == [
|
||||
(eeg_id, METRIC, "electrode", "O1", 7.5, 2.0, MODEL),
|
||||
(eeg_id, METRIC, "electrode", "O2", 8.5, None, None),
|
||||
(eeg_id, METRIC, "zone", "occipital", 8.0, 2.5, MODEL),
|
||||
]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
_load_and_build()
|
||||
@@ -0,0 +1,33 @@
|
||||
import sys
|
||||
|
||||
|
||||
def test_save_analyses_writes_eeg_sites(fresh_platform):
|
||||
fresh_platform.run(
|
||||
sys.executable,
|
||||
"-c",
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
from persistance.eeg import save_analyses
|
||||
|
||||
metric = SimpleNamespace(
|
||||
code="posterior_rhythm", value=8.0, electrodes={"O1": 7.5, "O2": 8.5},
|
||||
zones={"occipital": 8.0},
|
||||
)
|
||||
analysis = SimpleNamespace(
|
||||
valid=True, level="complete", age_months=25, clean_fraction=1,
|
||||
bad_channels=0, channels=19, duration_min=20, line_noise_db=0, sleep=False,
|
||||
features={}, error=None, checks=[], metrics=[metric],
|
||||
)
|
||||
save_analyses({"signal": analysis})
|
||||
""",
|
||||
)
|
||||
assert fresh_platform.query(
|
||||
"select key, edf, code, part, site, value from bronze.eeg_sites order by key"
|
||||
) == [
|
||||
("signal|posterior_rhythm|electrodes|O1", "signal", "posterior_rhythm", "electrodes",
|
||||
"O1", 7.5),
|
||||
("signal|posterior_rhythm|electrodes|O2", "signal", "posterior_rhythm", "electrodes",
|
||||
"O2", 8.5),
|
||||
("signal|posterior_rhythm|zones|occipital", "signal", "posterior_rhythm", "zones",
|
||||
"occipital", 8.0),
|
||||
] # fmt: skip
|
||||
Reference in New Issue
Block a user