diff --git a/openapi.json b/openapi.json index 1c9d22c..8687e95 100644 --- a/openapi.json +++ b/openapi.json @@ -36,6 +36,14 @@ "title": "Metrics", "type": "array" }, + "relation": { + "default": [], + "items": { + "$ref": "#/components/schemas/Relation" + }, + "title": "Relation", + "type": "array" + }, "valid": { "anyOf": [ { @@ -1413,6 +1421,122 @@ "title": "Rejection", "type": "object" }, + "Relation": { + "description": "One pair of the champion EEG\u2013ADOS-2 association, for this EEG (models.tea.association).", + "properties": { + "biomarker": { + "title": "Biomarker", + "type": "string" + }, + "ci_high": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "title": "Ci High" + }, + "ci_low": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "title": "Ci Low" + }, + "event": { + "title": "Event", + "type": "string" + }, + "kind": { + "title": "Kind", + "type": "string" + }, + "metric": { + "title": "Metric", + "type": "string" + }, + "model": { + "title": "Model", + "type": "string" + }, + "n": { + "title": "N", + "type": "number" + }, + "observed": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "title": "Observed" + }, + "odds_ratio": { + "title": "Odds Ratio", + "type": "number" + }, + "outcome_code": { + "title": "Outcome Code", + "type": "string" + }, + "probability": { + "title": "Probability", + "type": "number" + }, + "q": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "title": "Q" + }, + "reference_probability": { + "title": "Reference Probability", + "type": "number" + }, + "z": { + "title": "Z", + "type": "number" + }, + "zone": { + "title": "Zone", + "type": "string" + } + }, + "required": [ + "biomarker", + "metric", + "zone", + "outcome_code", + "kind", + "event", + "z", + "probability", + "reference_probability", + "odds_ratio", + "ci_low", + "ci_high", + "q", + "n", + "model" + ], + "title": "Relation", + "type": "object" + }, "Route": { "additionalProperties": false, "description": "Only the rows where every condition holds (e.g. reports titled \"Citolog\u00eda\"). An\n`otherwise` route takes the rows of its input that none of the other routes on that\ninput take (documents nobody recognises, for a reviewer), then its own conditions.", diff --git a/src/app/api/models.ts b/src/app/api/models.ts index 0e434a7..92dcda7 100644 --- a/src/app/api/models.ts +++ b/src/app/api/models.ts @@ -31,6 +31,7 @@ export type { Position } from './models/position'; export type { Provider } from './models/provider'; export type { Read } from './models/read'; export type { Rejection } from './models/rejection'; +export type { Relation } from './models/relation'; export type { Route } from './models/route'; export type { RunRequest } from './models/run-request'; export type { SavedPipeline } from './models/saved-pipeline'; diff --git a/src/app/api/models/analysis.ts b/src/app/api/models/analysis.ts index 6f4a06d..4ae857d 100644 --- a/src/app/api/models/analysis.ts +++ b/src/app/api/models/analysis.ts @@ -2,10 +2,12 @@ /* Code generated by ng-openapi-gen DO NOT EDIT. */ import { Metric } from '../models/metric'; +import { Relation } from '../models/relation'; export interface Analysis { age_months: (number | null); id: string; level: (string | null); metrics: Array; + relation?: Array; valid: (boolean | null); } diff --git a/src/app/api/models/relation.ts b/src/app/api/models/relation.ts new file mode 100644 index 0000000..a1b7505 --- /dev/null +++ b/src/app/api/models/relation.ts @@ -0,0 +1,25 @@ +/* eslint-disable */ +/* Code generated by ng-openapi-gen DO NOT EDIT. */ + + +/** + * One pair of the champion EEG–ADOS-2 association, for this EEG (models.tea.association). + */ +export interface Relation { + biomarker: string; + ci_high: (number | null); + ci_low: (number | null); + event: string; + kind: string; + metric: string; + model: string; + n: number; + observed?: (number | null); + odds_ratio: number; + outcome_code: string; + probability: number; + q: (number | null); + reference_probability: number; + z: number; + zone: string; +} diff --git a/src/app/eeg-labels.ts b/src/app/eeg-labels.ts index 5431bbd..f7b96b4 100644 --- a/src/app/eeg-labels.ts +++ b/src/app/eeg-labels.ts @@ -19,6 +19,43 @@ export const ZONE_NAMES: Record = { temporal_left: 'Temporal izquierda', temporal_right: 'Temporal derecha', occipital: 'Occipital', + posterior: 'Posterior', + global: 'Global', +}; + +/** The association's biomarkers (core.tea.association.BIOMARKERS). */ +export const BIOMARKER_NAMES: Record = { + spikes: 'Picos paroxísticos', + spindles: 'Husos de sueño N2', + posterior_rhythm: 'Ritmo posterior', + gradient: 'Gradiente anteroposterior', +}; + +/** ADOS-2 items by their number (core.tea.association.ITEMS), and the CSS. */ +export const OUTCOME_NAMES: Record = { + ados2_item_01: 'Vocalización espontánea dirigida a otros', + ados2_item_02: 'Señalar', + ados2_item_03: 'Gestos', + ados2_item_04: 'Contacto visual inusual', + ados2_item_05: 'Expresiones faciales dirigidas a otros', + ados2_item_06: 'Integración de la mirada con otras conductas', + ados2_item_07: 'Disfrute compartido en la interacción', + ados2_item_08: 'Respuesta al nombre', + ados2_item_09: 'Búsqueda de atención cuando se le ignora', + ados2_item_10: 'Pedir', + ados2_item_11: 'Mostrar', + ados2_item_12: 'Iniciación espontánea de la atención conjunta', + ados2_item_13: 'Respuesta a la atención conjunta', + ados2_item_14: 'Calidad de los acercamientos sociales', + ados2_item_15: 'Cantidad de acercamientos sociales al cuidador', + ados2_item_16: 'Cantidad de comunicación social recíproca', + ados2_item_17: 'Calidad general de la relación', + ados2_item_18: 'Entonación de vocalizaciones o verbalizaciones', + ados2_item_19: 'Uso estereotipado o idiosincrático de palabras', + ados2_item_20: 'Interés sensorial inusual', + ados2_item_21: 'Manierismos de manos y dedos', + ados2_item_22: 'Intereses repetitivos o conductas estereotipadas', + CSS: 'Puntuación de severidad (CSS)', }; /** Where each electrode of the 10-20 system sits on a head seen from above (nose up). */ diff --git a/src/app/gobernanza/figures.ts b/src/app/gobernanza/figures.ts index 105cbc1..0d90d36 100644 --- a/src/app/gobernanza/figures.ts +++ b/src/app/gobernanza/figures.ts @@ -1,5 +1,6 @@ import type { Figure } from '../plot'; import { PALETTE } from '../plot'; +import { BIOMARKER_NAMES, OUTCOME_NAMES, ZONE_NAMES } from '../eeg-labels'; /** A curve with its band, as the reports give them. */ interface Band { @@ -197,6 +198,62 @@ export function interpretabilityFigures( }, ]; } + case 'associations': { + // Each estimated pair's odds ratio with its 95 % interval, clearest first. + const rows = (report['rows'] as any[]) + .filter((r) => r.odds_ratio !== null) + .sort((a, b) => (a.q ?? 1) - (b.q ?? 1)); + const label = (r: any) => + `${BIOMARKER_NAMES[r.biomarker] ?? r.biomarker} · ${ZONE_NAMES[r.zone] ?? r.zone} → ${ + OUTCOME_NAMES[r.outcome_code] ?? r.outcome_code + }`; + return [ + { + title: `Asociaciones con el ADOS-2 (${report['children']} niños, nivel ${ + report['level'] === 'item' ? 'reactivo' : 'dominio' + })`, + figure: { + data: [ + { + type: 'scatter', + mode: 'markers', + x: rows.map((r) => r.odds_ratio), + y: rows.map(label), + error_x: { + type: 'data', + symmetric: false, + array: rows.map((r) => (r.ci_high ?? r.odds_ratio) - r.odds_ratio), + arrayminus: rows.map((r) => r.odds_ratio - (r.ci_low ?? r.odds_ratio)), + }, + marker: { + color: rows.map((r) => ((r.q ?? 1) < 0.05 ? PALETTE[2] : '#9aa0a6')), + size: 9, + }, + customdata: rows.map((r) => r.q), + hovertemplate: 'OR %{x:.2f} · q %{customdata:.3f}%{y}', + showlegend: false, + }, + ], + layout: { + xaxis: { title: { text: 'Razón de momios (escala log)' }, type: 'log' }, + yaxis: { automargin: true, autorange: 'reversed' }, + shapes: [ + { + type: 'line', + x0: 1, + x1: 1, + yref: 'paper', + y0: 0, + y1: 1, + line: { color: '#9aa0a6', dash: 'dot' }, + }, + ], + height: Math.max(320, 22 * rows.length + 80), + }, + }, + }, + ]; + } default: return []; } diff --git a/src/app/paciente/paciente.html b/src/app/paciente/paciente.html index c3e81bb..691751e 100644 --- a/src/app/paciente/paciente.html +++ b/src/app/paciente/paciente.html @@ -259,6 +259,92 @@ } @else {

Sin alteraciones: todas sus métricas están dentro de la norma por edad.

} + @if (st.valid && scored()) { +
+

Relación con el ADOS-2

+ @if (!eeg.value()?.analysis?.relation?.length) { +

+ Ningún modelo de asociación vigente ha evaluado este EEG (se promueven en + Gobernanza). +

+ } @else if (!related().length) { +

+ Ninguna zona alterada de este paciente (|z| ≥ 2) tiene una asociación clara + con el ADOS-2 en la cohorte. +

+ } @else { +

+ Modelo de asociación ajustado en la cohorte ({{ related()[0].n }} niños, por + edad y módulo del ADOS-2): qué tanto se asocia cada alteración del EEG por + zona con un aspecto del ADOS-2. No es un diagnóstico ni indica qué causa qué. +

+ + + + + + + + + + + + @for (f of related(); track f.biomarker + f.zone + f.outcome_code) { + + + + + + + + } + +
Zona del EEGAspecto del ADOS-2Asociación en la cohorteProbabilidad para este pacienteLo que muestra su ADOS-2
+ {{ biomarkerNames[f.biomarker] ?? f.biomarker }} + {{ zoneNames[f.zone] ?? f.zone }} · z = + {{ f.z | number: '1.1-2' }} + + {{ outcomeNames[f.outcome_code] ?? f.outcome_code }} + {{ f.kind === 'item' ? 'Reactivo' : 'Dominio' }} + + OR {{ f.odds_ratio | number: '1.2-2' }} + IC 95 % {{ f.ci_low | number: '1.2-2' }}–{{ + f.ci_high | number: '1.2-2' + }} + · q {{ qText(f.q) }} + {{ + f.odds_ratio >= 1 + ? 'A mayor z, mayor probabilidad' + : 'A menor z, mayor probabilidad' + }} + + {{ f.probability * 100 | number: '1.0-0' }} % + {{ f.event }} · con z = 0: + {{ f.reference_probability * 100 | number: '1.0-0' }} % + + {{ observed(f) }} + @if (matches(f); as m) { + {{ m }} + } +
+

+ OR mayor que 1: a mayor z en esa zona, más probable que el aspecto salga + alterado; menor que 1, al revés. Solo se muestran las zonas alteradas del + paciente (|z| ≥ 2) con una asociación clara en la cohorte (q < 0.05). + Versión del modelo: {{ related()[0].model }}. +

+ } +
+ } } @else {

Sin EEG analizado.

} @@ -266,7 +352,7 @@ } - @if (models().some((m) => m.scenarios.length)) { + @if (models().some((m) => m.model.endsWith('.survival') && m.scenarios.length)) { Análisis de supervivencia } + @if (recurrenceModel(); as rm) { + + Análisis de recurrencia + + + + + + + + + + @for (p of rm.predictions; track p.years) { + + + + + } + +
HorizonteProbabilidad de recurrencia
{{ p.years | number: '1.0-1' }} {{ p.years === 1 ? 'año' : 'años' }}{{ p.p * 100 | number: '1.1-1' }} %
+ @if (recurrence.isLoading()) { + + } @else if (recurrence.value(); as s) { +

Escenario clínico de la paciente

+
    + @for (name of s.scenarios; track name) { +
  • {{ name }}
  • + } +
+ @for (f of s.figures; track f.title) { +

{{ f.title }}

+ + } @empty { +

+ Sus escenarios tienen menos recaídas de las necesarias para trazar curvas. +

+ } + } @else if (recurrence.error()) { + + } +
+
+ } } @else if (loading()) { diff --git a/src/app/paciente/paciente.scss b/src/app/paciente/paciente.scss index 6d406c9..a75cfe8 100644 --- a/src/app/paciente/paciente.scss +++ b/src/app/paciente/paciente.scss @@ -79,3 +79,12 @@ mat-card-content { tr.chosen td { background: var(--mat-sys-surface-container); } + +.relation { + margin-top: 16px; + td small { + display: block; + color: var(--mat-sys-on-surface-variant); + font-size: 0.8em; + } +} diff --git a/src/app/paciente/paciente.ts b/src/app/paciente/paciente.ts index 1459266..83156db 100644 --- a/src/app/paciente/paciente.ts +++ b/src/app/paciente/paciente.ts @@ -21,7 +21,15 @@ import { code, EXT, ext, Fhir, label, resources } from '../fhir'; import { scenarioFigure } from '../gobernanza/figures'; import { CURP } from '../indicadores/follow-up'; import { name } from '../indicadores/measures'; -import { byDeviation, headMap, METRIC_NAMES, ZONE_NAMES } from '../eeg-labels'; +import { + BIOMARKER_NAMES, + byDeviation, + headMap, + METRIC_NAMES, + OUTCOME_NAMES, + ZONE_NAMES, +} from '../eeg-labels'; +import type { Relation } from '../api/models/relation'; import { Figure, PALETTE, Plot } from '../plot'; import { Loading } from '../loading'; @@ -137,36 +145,58 @@ export class Paciente { })), })); }); - /** "Análisis de supervivencia": the curves of her clinical scenarios, from the report of - * the model version that scored her. */ - protected readonly survival = resource({ - params: () => { - const m = this.models().find((x) => x.scenarios.length && x.version); - return m ? { m, domain: this.domain() } : undefined; - }, - loader: async ({ params: { m, domain } }) => { - const report = await this.api.invoke(readReport$Json, { - domain: domain as Domain, - name: m.model.replace(`${domain}.`, ''), - version: m.version, - report: 'interpretability', - }); - const drawn = ((report?.['escenarios'] ?? []) as any[]).filter((e) => - m.scenarios.includes(e.escenario), - ); - return { - scenarios: m.scenarios, - figures: drawn.map((e) => - scenarioFigure( - `${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`, - e, - e.horizons_months, - 'Supervivencia S(t)', + /** "Análisis de supervivencia" and "Análisis de recurrencia": the curves of her clinical + * scenarios, from the report of the model version that scored her. */ + protected readonly survival = this.analysis('survival'); + protected readonly recurrence = this.analysis('recurrence'); + protected readonly recurrenceModel = computed(() => + this.models().find((m) => m.model.endsWith('.recurrence') && m.version), + ); + + private analysis(name: 'survival' | 'recurrence') { + return resource({ + params: () => { + const m = this.models().find( + (x) => x.model === `${this.domain()}.${name}` && x.scenarios.length && x.version, + ); + return m ? { m, domain: this.domain() } : undefined; + }, + loader: async ({ params: { m, domain } }) => { + const report = await this.api.invoke(readReport$Json, { + domain: domain as Domain, + name, + version: m.version, + report: 'interpretability', + }); + const mine = (all: any[]) => all.filter((e) => m.scenarios.includes(e.escenario)); + if (name === 'recurrence') { + const r = (report?.['recurrencia'] ?? {}) as any; + return { + scenarios: m.scenarios, + figures: mine(r['escenarios'] ?? []).map((e) => + scenarioFigure( + `${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, recaídas = ${e.recaidas.toLocaleString('es-MX')})`, + e, + r['horizons_months'], + 'Supervivencia libre de recaída', + ), + ), + }; + } + return { + scenarios: m.scenarios, + figures: mine((report?.['escenarios'] ?? []) as any[]).map((e) => + scenarioFigure( + `${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`, + e, + e.horizons_months, + 'Supervivencia S(t)', + ), ), - ), - }; - }, - }); + }; + }, + }); + } /** TEA: her latest ADOS-2 (an encounter whose observations are the catalog's * `ados2.*` fields), item by item, and its totals. */ protected readonly ados2 = computed(() => { @@ -247,6 +277,32 @@ export class Paciente { (s) => s.z !== null && s.z !== undefined, ), ); + protected readonly biomarkerNames = BIOMARKER_NAMES; + protected readonly outcomeNames = OUTCOME_NAMES; + /** "Relación con el ADOS-2": her altered zones (|z| ≥ 2) with a clear association in the + * cohort (q < 0.05), clearest first, as the old summary showed them. */ + protected readonly related = computed(() => + (this.eeg.value()?.analysis?.relation ?? []) + .filter((f) => Math.abs(f.z) >= 2 && f.q !== null && f.q !== undefined && f.q < 0.05) + .sort((a, b) => (a.q ?? 1) - (b.q ?? 1)), + ); + protected qText(q?: number | null): string { + return q === null || q === undefined ? '—' : q < 0.001 ? '< 0.001' : `= ${q.toFixed(3)}`; + } + protected observed(f: Relation): string { + if (f.observed === null || f.observed === undefined) return 'Sin dato'; + if (f.kind === 'item') + return f.observed >= 1 ? `Alterado (${f.observed})` : 'Sin anormalidad (0)'; + return `CSS ${f.observed}`; + } + /** Whether what she shows is what the model leans to (above or below one half). */ + protected matches(f: Relation): string | undefined { + if (f.observed === null || f.observed === undefined) return undefined; + const present = f.kind === 'item' ? f.observed >= 1 : f.observed >= 8; + return present === f.probability >= 0.5 + ? 'Coincide con lo que el modelo esperaba' + : 'No coincide con lo que el modelo esperaba'; + } protected readonly zoneOrder = computed(() => byDeviation(this.zoned()?.zones ?? [])); protected readonly head = computed(() => headMap(this.zoned()?.electrodes ?? [])); protected readonly curve = computed
(() => {