7088e0e946
The preview result names the module's items by the titles in core.tea.ados2_items, module items first, so the Gobernanza dialog and its PDF print what the report asks instead of field names.
218 lines
7.5 KiB
Python
218 lines
7.5 KiB
Python
import math
|
|
from dataclasses import replace
|
|
from datetime import date
|
|
|
|
from sqlalchemy.exc import SQLAlchemyError
|
|
|
|
from core import concept_map, tea
|
|
from core.pipeline import apply_patterns
|
|
from core.tea import ados2 as scoring
|
|
from core.tea import ados2_items
|
|
from models import graph
|
|
from models.tea.eeg import analysis, curves, read
|
|
from models.tea.jobs import MODELS
|
|
from persistance import config_log, registry
|
|
from persistance.previews import PreviewAdos2, PreviewEeg, PreviewMetric, PreviewResult, Site
|
|
|
|
|
|
def _deviations(models: dict, study: analysis.Analysis) -> dict:
|
|
metrics = {metric.code: metric for metric in study.metrics}
|
|
missing_values = set()
|
|
for name, baseline in models.items():
|
|
scenario = curves.SCENARIOS[name]
|
|
if scenario.metric not in metrics:
|
|
continue
|
|
metric = metrics[scenario.metric]
|
|
changes = {
|
|
part: {
|
|
site: value
|
|
for site, value in getattr(metric, part).items()
|
|
if curves.PREFIX[part] + site in baseline
|
|
}
|
|
for part in scenario.parts
|
|
if part != "value"
|
|
}
|
|
if "value" in scenario.parts and "value" not in baseline:
|
|
models[name] = baseline | {"value": {}}
|
|
changes["value"] = None
|
|
missing_values.add(metric.code)
|
|
metrics[metric.code] = replace(metric, **changes)
|
|
|
|
features = {name: study.features.get(name, {}) for name in models}
|
|
found = curves.deviations(
|
|
models, replace(study, metrics=list(metrics.values()), features=features)
|
|
)
|
|
for code in missing_values:
|
|
found.get(code, {}).pop("value", None)
|
|
return found
|
|
|
|
|
|
def _sites(values: dict, scores: dict) -> dict[str, Site]:
|
|
return {key: Site(value=value, score=scores.get(key)) for key, value in values.items()}
|
|
|
|
|
|
def _metrics(study: analysis.Analysis, warnings: list[str]) -> list[PreviewMetric]:
|
|
models, versions = {}, {}
|
|
found = {}
|
|
if study.valid:
|
|
for name in curves.SCENARIOS:
|
|
champion = registry.champion(f"tea.{name}")
|
|
if champion is not None:
|
|
versions[name], model = champion
|
|
models[name] = model.unwrap_python_model().baseline
|
|
if not models:
|
|
warnings.append("there are no champion age curves: no z is shown")
|
|
else:
|
|
codes = {metric.code for metric in study.metrics}
|
|
warnings.extend(
|
|
f"no champion for {name}: its z is not shown"
|
|
for name, scenario in curves.SCENARIOS.items()
|
|
if name not in models and scenario.metric in codes
|
|
)
|
|
found = _deviations(models, study)
|
|
|
|
labels = {
|
|
MODELS[name].metric: f"tea.{name}/{version}"
|
|
for name, version in versions.items()
|
|
if "value" in MODELS[name].parts
|
|
}
|
|
metrics = []
|
|
for metric in study.metrics:
|
|
parts = found.get(metric.code, {})
|
|
metrics.append(
|
|
PreviewMetric(
|
|
code=metric.code,
|
|
value=metric.value,
|
|
score=parts.get("value"),
|
|
model=labels.get(metric.code) if "value" in parts else None,
|
|
electrodes=_sites(metric.electrodes, parts.get("electrodes", {})),
|
|
zones=_sites(metric.zones, parts.get("zones", {})),
|
|
)
|
|
)
|
|
return metrics
|
|
|
|
|
|
def _parse(field, value, kind, warnings):
|
|
if value is None:
|
|
return None
|
|
try:
|
|
if kind == "date":
|
|
return value if isinstance(value, date) else date.fromisoformat(value)
|
|
number = float(value)
|
|
if math.isfinite(number):
|
|
return number
|
|
except (TypeError, ValueError):
|
|
pass
|
|
warnings.append(f"{field}: could not read {value!r} as a {kind}")
|
|
return None
|
|
|
|
|
|
def _report(
|
|
content: bytes,
|
|
pipeline: str,
|
|
recorded_on: date | None,
|
|
birth: date | None,
|
|
warnings: list[str],
|
|
) -> PreviewAdos2 | None:
|
|
if not content.startswith(b"%PDF"):
|
|
warnings.append("the ADOS-2 file is not a PDF")
|
|
return None
|
|
text = graph.read_file(content)
|
|
if error := text["error"]:
|
|
warnings.append(f"the ADOS-2 report could not be read: {error}")
|
|
return None
|
|
|
|
try:
|
|
saved = config_log.get(pipeline)
|
|
except (LookupError, SQLAlchemyError, ValueError):
|
|
saved = None
|
|
if saved is None:
|
|
warnings.append(f"no saved pipeline {pipeline}: the ADOS-2 report is not read")
|
|
return None
|
|
_, definition = saved
|
|
node = next((n for n in definition.nodes if n.kind == "extract" and n.entity == "ados2"), None)
|
|
if node is None:
|
|
warnings.append(f"pipeline {pipeline} has no ados2 extract node")
|
|
return None
|
|
|
|
codes = {}
|
|
if node.concept_map:
|
|
mapping = config_log.concept_map(node.concept_map)
|
|
codes = {field: concept_map.table([mapping], field) for field in node.patterns}
|
|
found = apply_patterns(node, text["text"], codes)
|
|
if not found:
|
|
warnings.append("no ADOS-2 field was found in the report")
|
|
return None
|
|
|
|
row = dict(found[0][0])
|
|
fields = sorted(row)
|
|
evaluation_date = _parse("evaluation_date", row.get("evaluation_date"), "date", warnings)
|
|
if "evaluation_date" not in row:
|
|
evaluation_date = recorded_on
|
|
module = row.get("module")
|
|
titles = {i.field: f"{i.code} {i.title}" for i in ados2_items.ITEMS.get(module, ())}
|
|
order = [*titles, *(item for item in tea.ADOS2_ITEMS if item not in titles)]
|
|
items = {item: _parse(item, row.get(item), "number", warnings) for item in order}
|
|
css, classification = None, None
|
|
if evaluation_date is None:
|
|
warnings.append("ADOS-2 not scored: no evaluation date")
|
|
else:
|
|
try:
|
|
css, classification = scoring.score(
|
|
row | items | {"evaluation_date": evaluation_date}, birth
|
|
)
|
|
except (ValueError, TypeError) as exc:
|
|
warnings.append(f"ADOS-2 not scored: {exc}")
|
|
else:
|
|
if css is None and classification is None:
|
|
warnings.append(
|
|
"the ADOS-2 score could not be calculated: "
|
|
"the report lacks the module or the item scores"
|
|
)
|
|
return PreviewAdos2(
|
|
module=module,
|
|
evaluation_date=evaluation_date,
|
|
items=items,
|
|
titles=titles,
|
|
css=css,
|
|
classification=classification,
|
|
read=fields,
|
|
)
|
|
|
|
|
|
def preview(
|
|
edf: bytes,
|
|
ados2: bytes | None = None,
|
|
birth_date: date | None = None,
|
|
pipeline: str = "tea",
|
|
) -> PreviewResult:
|
|
study = analysis.analyze(edf, birth_date)
|
|
try:
|
|
header = read.header(edf)
|
|
except read.FileNotValid:
|
|
header = None
|
|
recorded_on = header.start_date if header else None
|
|
warnings = []
|
|
if study.error:
|
|
warnings.append(f"the EEG analysis ended with an error: {study.error}")
|
|
eeg = PreviewEeg(
|
|
valid=study.valid,
|
|
level=study.level,
|
|
recorded_on=recorded_on,
|
|
age_months=study.age_months,
|
|
clean_fraction=study.clean_fraction,
|
|
bad_channels=study.bad_channels,
|
|
channels=study.channels,
|
|
duration_min=study.duration_min,
|
|
line_noise_db=study.line_noise_db,
|
|
sleep=study.sleep,
|
|
checks=study.checks,
|
|
metrics=_metrics(study, warnings),
|
|
error=study.error,
|
|
)
|
|
report = None
|
|
if ados2 is not None:
|
|
birth = birth_date or (header.birthdate if header else None)
|
|
report = _report(ados2, pipeline, recorded_on, birth, warnings)
|
|
return PreviewResult(eeg=eeg, ados2=report, warnings=warnings)
|