diff --git a/src/app/gobernanza/figures.ts b/src/app/gobernanza/figures.ts index 61b7a26..f63f18a 100644 --- a/src/app/gobernanza/figures.ts +++ b/src/app/gobernanza/figures.ts @@ -2,37 +2,44 @@ 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. */ +/** A curve with its band, as the reports give them; a value may be absent (null). */ interface Band { x: number[]; - y: number[]; + y: (number | null)[]; low?: (number | null)[]; high?: (number | null)[]; } -function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial[] { - const lines: Partial[] = []; - if (b.low && b.high) { - lines.push({ - x: [...b.x, ...[...b.x].reverse()], - y: [...b.high, ...[...b.low].reverse()] as number[], - fill: 'toself', - fillcolor: `${colour}33`, - line: { width: 0 }, - hoverinfo: 'skip', - showlegend: false, - type: 'scatter', - }); - } - lines.push({ - x: b.x, - y: b.y, - name, - type: 'scatter', - mode: 'lines', - line: { color: colour, dash }, +const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); +/** The value or a gap: an absent value is not drawn (zero is a value). */ +const orGap = (ys: (number | null)[]) => ys.map((v) => (finite(v) ? v : null)) as number[]; + +/** The runs of consecutive indices where both limits are known: the band is drawn there only + * (an absent limit is no zero). */ +function runs(b: Band): number[][] { + const found: number[][] = [[]]; + b.x.forEach((x, i) => { + if (finite(x) && finite(b.low?.[i]) && finite(b.high?.[i])) found.at(-1)!.push(i); + else if (found.at(-1)!.length) found.push([]); }); - return lines; + return found.filter((r) => r.length > 1); +} + +function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial[] { + const bands = runs(b).map((run) => ({ + x: [...run, ...[...run].reverse()].map((i) => b.x[i]), + y: [...run.map((i) => b.high![i]), ...[...run].reverse().map((i) => b.low![i])] as number[], + fill: 'toself' as const, + fillcolor: `${colour}33`, + line: { width: 0 }, + hoverinfo: 'skip' as const, + showlegend: false, + type: 'scatter' as const, + })); + return [ + ...bands, + { x: b.x, y: orGap(b.y), name, type: 'scatter', mode: 'lines', line: { color: colour, dash } }, + ]; } /** What a model's interpretability report draws, by its kind: survival curves, the mixture's @@ -295,20 +302,29 @@ export function scenarioFigure( }; } +/** The model's points; a point without both limits has no bar, and none has: no bars. */ function points( name: string, x: number[], - p: { S: number[]; low: number[]; high: number[] }, + p: { S: (number | null)[]; low?: (number | null)[]; high?: (number | null)[] }, ): Partial { + const bars = p.S.map((v, i) => { + const [low, high] = [p.low?.[i], p.high?.[i]]; + return finite(v) && finite(low) && finite(high) ? [high - v, v - low] : null; + }); return { x, - y: p.S, - error_y: { - type: 'data', - symmetric: false, - array: p.high.map((h, i) => h - p.S[i]), - arrayminus: p.S.map((v, i) => v - p.low[i]), - }, + y: orGap(p.S), + ...(bars.some((e) => e) + ? { + error_y: { + type: 'data' as const, + symmetric: false, + array: bars.map((e) => e?.[0] ?? null) as number[], + arrayminus: bars.map((e) => e?.[1] ?? null) as number[], + }, + } + : {}), name, type: 'scatter', mode: 'markers', diff --git a/src/app/paciente/analysis.ts b/src/app/paciente/analysis.ts new file mode 100644 index 0000000..f1a6378 --- /dev/null +++ b/src/app/paciente/analysis.ts @@ -0,0 +1,85 @@ +import { Api } from '../api/api'; +import { readReport$Json } from '../api/fn/models/read-report-json'; +import type { Domain } from '../api/models/domain'; +import { scenarioFigure } from '../gobernanza/figures'; +import type { ScenarioFactors } from './factores'; +import type { Model } from './record'; +import { combinationOf, noCurveText, sortUndrawn, survivalFigure } from './survival'; +import { figureChoices } from './curve-chooser'; + +type Report = Record | null | undefined; +const count = (n: number) => n.toLocaleString('es-MX'); + +/** A model version's report, by name. */ +function report(api: Api, domain: string, model: Model, which: string): Promise { + return api.invoke(readReport$Json, { + domain: domain as Domain, + name: model.model.split('.')[1], + version: model.version, + report: which, + }) as Promise; +} + +/** The names of the methods the figures draw, each once. */ +const methods = (figures: { figure: { data: { name?: string }[] } }[]) => + [ + ...new Set(figures.flatMap((f) => f.figure.data.map((t) => t.name)).filter((n) => !!n)), + ] as string[]; + +/** "Análisis de supervivencia" or "de recurrencia": the curves of her clinical scenarios from the + * report of the model version that scored her, and the risk factors of those scenarios. CaCu says + * apart a scenario the report lists as short of deaths from one it does not mention. */ +export async function analysis(api: Api, domain: string, m: Model) { + const mine = (all: any[] = []) => all.filter((e) => m.scenarios.includes(e.escenario)); + if (m.model.endsWith('.recurrence')) { + const r = (await report(api, domain, m, 'interpretability'))?.['recurrencia'] ?? {}; + const technical = await report(api, domain, m, 'technical_validation'); + const summary = technical?.['recurrencia_desarrollo']?.['tablas']?.['escenarios_resumen']; + const figures = mine(r['escenarios']).map((e) => + scenarioFigure( + `${e.escenario} (n = ${count(e.n)}, recaídas = ${count(e.recaidas)})`, + e, + r['horizons_months'], + 'Supervivencia libre de recaída', + ), + ); + const none = { unavailable: [], insufficient: [], missing: [], methods: [] }; + return { + ...none, + factors: mine(summary?.['filas']) as ScenarioFactors[], + scenarios: m.scenarios, + figures, + }; + } + const found = await report(api, domain, m, 'interpretability'); + const drawn = mine(found?.['escenarios']); + const figures = drawn.map((e) => + scenarioFigure( + `${e.escenario} (n = ${count(e.n)}, fallecidos = ${count(e.fallecidos)})`, + e, + e.horizons_months, + 'Supervivencia S(t)', + ), + ); + const undrawn = m.scenarios.filter((s) => !drawn.some((e) => e.escenario === s)); + const cacu = domain === 'cacu'; + return { + factors: mine(found?.['factores_escenarios']) as ScenarioFactors[], + scenarios: m.scenarios, + figures, + unavailable: cacu ? [] : undrawn, + ...(cacu ? sortUndrawn(found, undrawn) : { insufficient: [], missing: [] }), + methods: methods(figures), + }; +} +export type Analysis = Awaited>; + +/** CaCu: the Kaplan-Meier of the patients who share all her values, from the survival report of + * the version that scored her; or why there is none. */ +export async function combination(api: Api, m: Model & { inputs: Record }) { + const found = await report(api, 'cacu', m, 'interpretability'); + const mine = combinationOf(found, m.inputs); + return mine?.km + ? { n: mine.n, deaths: mine.fallecidos, curves: figureChoices(survivalFigure(mine)) } + : { missing: noCurveText(found, mine) }; +} diff --git a/src/app/paciente/antecedents.ts b/src/app/paciente/antecedents.ts new file mode 100644 index 0000000..1495be8 --- /dev/null +++ b/src/app/paciente/antecedents.ts @@ -0,0 +1,62 @@ +import { Component, input } from '@angular/core'; +import { MatCardModule } from '@angular/material/card'; +import { ANTECEDENTS } from './record-groups'; + +/** CaCu: what each cytology's form declares of her (the one she was opened at first), by day. + * Statements of the form, not confirmed diagnoses. */ +@Component({ + selector: 'app-antecedents', + imports: [MatCardModule], + template: ` + + + Antecedentes y evaluación ginecológica + + +

+ Datos declarados en el formulario de la citología: no son diagnósticos confirmados. Cada + dato pertenece al formulario de la toma que se indica. +

+

Citología cervical · toma {{ forms()[0].date }}

+
+ @for (a of antecedents; track a.field) { +
+
{{ a.title }}
+
{{ forms()[0].values[a.field] ?? 'No documentado' }}
+
+ } +
+ @if (forms().length > 1) { +
+ Formularios anteriores ({{ forms().length - 1 }}) + + + + + @for (a of antecedents; track a.field) { + + } + + + + @for (o of forms().slice(1); track o.date) { + + + @for (a of antecedents; track a.field) { + + } + + } + +
Toma{{ a.title }}
{{ o.date }}{{ o.values[a.field] ?? 'No documentado' }}
+
+ } +
+
+ `, + styleUrl: './paciente.scss', +}) +export class Antecedents { + readonly forms = input.required<{ date: string; values: Record }[]>(); + protected readonly antecedents = ANTECEDENTS; +} diff --git a/src/app/paciente/cama-record.ts b/src/app/paciente/cama-record.ts new file mode 100644 index 0000000..32c284b --- /dev/null +++ b/src/app/paciente/cama-record.ts @@ -0,0 +1,99 @@ +import type { DiagnosticReport, Patient } from 'fhir/r4'; +import { code, ext, Fhir } from '../fhir'; +import { ageGroup, CAMA_AGE_GROUPS, CamaRow, camaRows } from '../indicadores/follow-up'; +import { name, PRIORITY } from '../indicadores/labels'; +import { PatientRecord, results, shown } from './record'; + +interface Listed { + window: number; + /** the cut-off the list applied */ + cutoff: string; + row?: CamaRow; +} + +/** Her row on CaMa's follow-up list, at the window and cut-off she was opened from. */ +export async function listedRow( + fhir: Fhir, + { id, window, cutoff }: { id: string; window: number; cutoff?: string }, +): Promise { + const page = await fhir.search('cama', 'Patient', { + _id: id, + 'follow-up-window': window, + 'follow-up-cutoff': cutoff, + _revinclude: ['DiagnosticReport:subject'], + '_include:iterate': 'DiagnosticReport:result', + }); + const self = page.link?.find((l) => l.relation === 'self')?.url; + const applied = self ? (new URL(self).searchParams.get('follow-up-cutoff') ?? '') : ''; + return { window, cutoff: applied, row: camaRows(page, applied)[0] }; +} + +/** What the old record's card said of her: her row on the list (on it or not), her own latest + * mammogram and biopsy. */ +export function camaSummary(d: PatientRecord, found: Listed) { + const latest = (study: string) => + d.reports + .filter((r) => code(r.code) === study) + .sort((a, b) => (a.effectiveDateTime ?? '').localeCompare(b.effectiveDateTime ?? '')) + .at(-1); + const value = (r: DiagnosticReport | undefined, field: string) => { + const o = r && results(d, r).find((x) => code(x.code) === field); + return o ? shown(o) : undefined; + }; + const mammogram = latest('mammography'); + const biopsy = latest('breast_biopsy'); + const treated = d.procedures.some((p) => (p.performedDateTime ?? '') <= found.cutoff); + const r = found.row; + return { + ...found, + ageGroup: r?.ageGroup ?? ageGroup(d.patient.birthDate, found.cutoff, CAMA_AGE_GROUPS), + scenario: treated ? 'Post-tratamiento' : 'En observación', + status: r ? name(r.status) : undefined, + priority: r ? (PRIORITY[r.priority] ?? r.priority) : undefined, + birads: value(mammogram, 'mammography.birads'), + mammogram: mammogram?.effectiveDateTime?.slice(0, 10), + days: mammogram ? ext(mammogram, 'days-to-diagnosis')?.valueInteger : undefined, + histology: value(biopsy, 'breast_biopsy.histology'), + biopsy: biopsy + ? (ext(biopsy, 'report-date')?.valueDate ?? biopsy.effectiveDateTime) + : undefined, + }; +} +type Summary = ReturnType | undefined; +type Facts = [string, string | undefined][]; + +const sex = (p?: Patient) => + p?.gender === 'female' ? 'Femenino' : p?.gender === 'male' ? 'Masculino' : undefined; + +/** Her data as the PDF lists them. */ +export function camaFacts( + who: { name?: string; curp?: string; numbers: string[] }, + p: Patient | undefined, + c: Summary, +): Facts { + return [ + ['Nombre', who.name], + ['CURP', who.curp], + ['Expedientes', who.numbers.join(', ')], + ['Fecha de nacimiento', p?.birthDate], + ['Sexo', sex(p)], + ['Grupo de edad', c?.ageGroup], + ['Escenario clínico', c?.scenario], + ['Fecha de corte', c?.cutoff], + [ + 'Estatus de seguimiento', + c && (c.status ?? `Fuera de la lista (${c.window} meses al ${c.cutoff})`), + ], + ['Prioridad', c?.priority], + ['Días de mastografía a diagnóstico', c?.days?.toString()], + ...(p?.deceasedDateTime ? ([['Defunción', p.deceasedDateTime]] as Facts) : []), + ]; +} + +/** Her latest mammogram and biopsy as the PDF lists them. */ +export const camaStudies = (c: Summary): Facts => [ + ['Categoría BI-RADS de la última mastografía', c?.birads], + ['Fecha de la última mastografía', c?.mammogram], + ['Resultado histopatológico', c?.histology], + ['Fecha de reporte de la biopsia', c?.biopsy], +]; diff --git a/src/app/paciente/curve-chooser.ts b/src/app/paciente/curve-chooser.ts new file mode 100644 index 0000000..ce7bde8 --- /dev/null +++ b/src/app/paciente/curve-chooser.ts @@ -0,0 +1,84 @@ +import { Component, computed, input, signal } from '@angular/core'; +import { MatCheckboxModule } from '@angular/material/checkbox'; +import { Figure, Plot } from '../plot'; + +export interface Choice { + id: string; + name: string; + /** drawn until the user says otherwise */ + on: boolean; +} +export type Draw = (ids: Set) => Figure; + +/** A figure's named curves as choices, all on; a trace with no legend of its own (a band) goes + * with the named one after it. */ +export function figureChoices(figure: Figure): { choices: Choice[]; draw: Draw } { + const groups = new Map(); + let pending: Figure['data'] = []; + for (const trace of figure.data) { + pending.push(trace); + const { name, showlegend } = trace as { name?: string; showlegend?: boolean }; + if (name && showlegend !== false) { + groups.set(name, pending); + pending = []; + } + } + return { + choices: [...groups.keys()].map((name) => ({ id: name, name, on: true })), + draw: (ids) => ({ ...figure, data: [...ids].flatMap((id) => groups.get(id) ?? []) }), + }; +} + +/** Curves to compare on one plot, each chosen or not, with what the chosen ones assume. */ +@Component({ + selector: 'app-curve-chooser', + imports: [MatCheckboxModule, Plot], + template: ` +
+ @for (c of choices(); track c.id) { + {{ + c.name + }} + } +
+ @if (chosen().size) { + @for (note of said(); track note) { +

{{ note }}

+ } + + } + `, + styles: ` + :host { + display: block; + } + .choices { + display: flex; + flex-wrap: wrap; + gap: 0 16px; + margin-bottom: 8px; + } + `, +}) +export class CurveChooser { + readonly choices = input.required(); + readonly draw = input.required(); + readonly notes = input<(ids: Set) => string[]>(() => []); + /** the choices the user turned from their default */ + private readonly flipped = signal(new Set()); + protected readonly chosen = computed( + () => + new Set( + this.choices() + .filter((c) => c.on !== this.flipped().has(c.id)) + .map((c) => c.id), + ), + ); + protected readonly figure = computed(() => this.draw()(this.chosen())); + protected readonly said = computed(() => this.notes()(this.chosen())); + protected toggle(id: string) { + const next = new Set(this.flipped()); + if (!next.delete(id)) next.add(id); + this.flipped.set(next); + } +} diff --git a/src/app/paciente/eligibility.spec.ts b/src/app/paciente/eligibility.spec.ts new file mode 100644 index 0000000..d456953 --- /dev/null +++ b/src/app/paciente/eligibility.spec.ts @@ -0,0 +1,73 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import type { Parameters, ParametersParameter } from 'fhir/r4'; +import { currency, eligibilityFailure, eligibilityView, ineligibility } from './eligibility'; + +const visit = (scenario: string, day: string, eligible: boolean, ...criteria: string[]) => ({ + name: 'candidate', + part: [ + { name: 'scenario', valueCoding: { code: scenario } }, + { name: 'index-date', valueDate: day }, + { name: 'eligible', valueBoolean: eligible }, + ...criteria.map((code) => ({ name: 'criterion', valueCoding: { code } })), + ], +}); +const answer = (...candidates: ParametersParameter[]): Parameters => ({ + resourceType: 'Parameters', + parameter: [{ name: 'status', valueCode: 'evaluated' }, ...candidates], +}); + +describe('eligibility', () => { + it('keeps each visit with its own decision, latest first, its reasons as the screens say them', () => { + const state = eligibilityView( + answer( + visit('pre_colposcopy', '2025-01-10', true), + visit('pre_colposcopy', '2026-02-01', false, 'hysterectomy', 'brand_new'), + ), + ); + expect(state).toEqual({ + kind: 'evaluated', + visits: [ + { + scenario: 'pre_colposcopy', + indexDate: '2026-02-01', + eligible: false, + reasons: ['Histerectomía previa al índice', 'brand_new'], + }, + { scenario: 'pre_colposcopy', indexDate: '2025-01-10', eligible: true, reasons: [] }, + ], + }); + }); + it('never reads a malformed answer, or a failure, as a decision', () => { + expect(eligibilityView(answer({ name: 'candidate', part: [] })).kind).toBe('unavailable'); + expect( + eligibilityView({ + resourceType: 'Parameters', + parameter: [{ name: 'status', valueCode: 'no_candidate' }], + }).kind, + ).toBe('none'); + const failed = (status: number) => eligibilityFailure(new HttpErrorResponse({ status })); + expect([409, 404, 500].map((s) => failed(s).kind)).toEqual(['gold', 'unavailable', 'error']); + }); + it('says why she has no estimate from the latest visit of her scenario by the day', () => { + const state = eligibilityView( + answer( + visit('surveillance', '2025-03-01', false, 'under_18'), + visit('pre_colposcopy', '2026-05-01', true), + ), + ); + expect(ineligibility(state, 'pre_colposcopy', '2026-06-01')).toBeUndefined(); + expect(ineligibility(state, 'pre_colposcopy', '2026-01-01')).toBe( + 'No disponible por: Edad menor de 18 años al índice.', + ); + expect(ineligibility(state, 'post_treatment', '2026-06-01')).toBe( + 'No disponible por: paciente ya tratada.', + ); + }); + it('says the cytology the estimate speaks of, and a later one it does not', () => { + const risk = [{ model: 'cacu.cin2_pre_colposcopy', index: '2026-01-10T00:00:00' }]; + expect(currency(risk, ['2026-01-10']).note).toBe('Estimación de la citología del 2026-01-10.'); + expect(currency(risk, ['2026-03-01']).note).toContain('posterior, del 2026-03-01'); + const post = [{ model: 'cacu.cin2_post_colposcopy', index: '2026-01-10' }]; + expect(currency(post, ['2026-03-01']).excluded).toContain('primera visita poscolposcopía'); + }); +}); diff --git a/src/app/paciente/eligibility.ts b/src/app/paciente/eligibility.ts new file mode 100644 index 0000000..b5b8052 --- /dev/null +++ b/src/app/paciente/eligibility.ts @@ -0,0 +1,114 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import type { Parameters, ParametersParameter } from 'fhir/r4'; + +/** The exclusion criteria `$eligibility` names, as the screens say them. */ +const CRITERIA: Record = { + hysterectomy: 'Histerectomía previa al índice', + under_18: 'Edad menor de 18 años al índice', + prior_outcome: 'Resultado CIN2+ previo al índice', + no_index_result: 'Sin resultado de citología o VPH en la visita índice', + unreported_biopsy: 'Biopsia solicitada sin resultado', + outcome_by_index: 'Resultado CIN2+ hasta la visita índice', + cancer_history: 'Antecedente de cáncer cervicouterino', + prior_treatment: 'Tratamiento previo a la visita índice', + no_referral: 'Sin citología de referencia previa a la colposcopia', + referral_not_graded: 'Citología de referencia de bajo grado sin VPH positivo', + no_cotest: 'Sin cotest de citología y VPH en la visita índice', + no_pretreatment_biopsy: 'Sin biopsia previa al tratamiento en el periodo requerido', + outcome_before_index: 'Resultado CIN2+ entre tratamiento e índice', + no_birth_date: 'Fecha de nacimiento desconocida', + died_by_index: 'Defunción en o antes de la visita índice', + not_evaluated: 'Escenario que la plataforma no evalúa por ahora', +}; + +/** One indexed visit of a scenario: the backend's decision and its reasons, as they are. */ +export interface Visit { + scenario: string; + indexDate: string; + eligible: boolean; + reasons: string[]; +} +/** What `$eligibility` answered; "eligible" is never inferred, only read. */ +export type EligibilityState = + | { kind: 'loading' | 'error' | 'unavailable' | 'none' } + | { kind: 'gold'; text?: string } + | { kind: 'evaluated'; visits: Visit[] }; + +type Part = ParametersParameter; +const parts = (of: Part[] | undefined, name: string) => (of ?? []).filter((p) => p.name === name); +const first = (of: Part[] | undefined, name: string) => parts(of, name)[0]; + +/** The answer's visits, latest first. An answer outside the contract is "unavailable". */ +export function eligibilityView(answer: Parameters | null | undefined): EligibilityState { + const top = answer?.resourceType === 'Parameters' ? answer.parameter : undefined; + if (!Array.isArray(top)) return { kind: 'unavailable' }; + const status = first(top, 'status')?.valueCode; + const candidates = parts(top, 'candidate'); + if (status === 'no_candidate' && !candidates.length) return { kind: 'none' }; + if (status !== 'evaluated' || !candidates.length) return { kind: 'unavailable' }; + const visits: Visit[] = []; + for (const { part } of candidates) { + const scenario = first(part, 'scenario')?.valueCoding?.code; + const indexDate = first(part, 'index-date')?.valueDate; + const eligible = first(part, 'eligible')?.valueBoolean; + if (!scenario || !indexDate || eligible === undefined) return { kind: 'unavailable' }; + const reasons = parts(part, 'criterion') + .map((r) => r.valueCoding) + .filter((k) => !!k?.code) + .map((k) => CRITERIA[k!.code!] ?? k!.display ?? k!.code!); + visits.push({ scenario, indexDate, eligible, reasons }); + } + return { + kind: 'evaluated', + visits: visits.sort((a, b) => b.indexDate.localeCompare(a.indexDate)), + }; +} + +/** A failed answer: the gold to rebuild (409), no such operation for her (404, 422), or the call + * itself (anything else). */ +export function eligibilityFailure(error: unknown): EligibilityState { + if (!(error instanceof HttpErrorResponse)) return { kind: 'error' }; + if (error.status === 409) return { kind: 'gold', text: error.error?.issue?.[0]?.diagnostics }; + return error.status === 404 || error.status === 422 ? { kind: 'unavailable' } : { kind: 'error' }; +} + +/** The scenarios that speak for a follow-up status, the first with a visit by the day wins. */ +const SPEAKS_FOR: Record = { + pre_colposcopy: ['pre_colposcopy', 'surveillance'], + post_colposcopy: ['post_colposcopy'], +}; + +/** Why she has no risk estimate in her scenario by `day`; nothing when she is eligible or no visit + * of it is known. A treated patient has none, whatever was indexed. */ +export function ineligibility(state: EligibilityState, status: string, day: string) { + if (status === 'post_treatment') return 'No disponible por: paciente ya tratada.'; + if (state.kind !== 'evaluated') return undefined; + for (const scenario of SPEAKS_FOR[status] ?? []) { + const latest = state.visits.find((v) => v.scenario === scenario && v.indexDate <= day); + if (latest) + return latest.eligible ? undefined : `No disponible por: ${latest.reasons.join('; ')}.`; + } + return undefined; +} + +/** Which cytology her estimates speak of, against her latest by the cut-off: after the first + * post-colposcopy visit nothing is evaluated; otherwise a later cytology is only said. */ +export function currency(estimates: { model: string; index: string }[], cytologies: string[]) { + const sample = estimates + .map((e) => e.index.slice(0, 10)) + .sort() + .at(-1); + if (!sample) return {}; + const latest = cytologies + .map((d) => d.slice(0, 10)) + .sort() + .at(-1); + const said = `Estimación de la citología del ${sample}.`; + if (!latest || latest <= sample) return { sample, note: said }; + if (estimates.some((e) => e.model.includes('post_colposcopy'))) + return { + sample, + excluded: `No disponible por: hay una citología posterior a la primera visita poscolposcopía (${latest}) y solo se evalúa esa primera visita.`, + }; + return { sample, note: `${said} Hay una citología posterior, del ${latest}, que no se evalúa.` }; +} diff --git a/src/app/paciente/paciente.html b/src/app/paciente/paciente.html index c359385..dc13159 100644 --- a/src/app/paciente/paciente.html +++ b/src/app/paciente/paciente.html @@ -5,9 +5,14 @@ @if (error()) { } @else if (patient(); as p) { -

- {{ identity().name ?? 'Paciente' }} {{ p.id!.slice(0, 10) }} -

+
+

+ {{ identity().name ?? 'Paciente' }} {{ p.id!.slice(0, 10) }} +

+ @if (cama()) { + + } +
CURP
@@ -107,23 +112,18 @@ } - @if (stages(); as s) { - - Etapas del tamizaje - - - - @if (saveError()) { - - } - - - } Historial médico + @if (stages(); as s) { + +

+ Los pasos muestran el tamizaje actual, en curso: el de la citología que se consulta. +

+
+ +
+ } @@ -140,7 +140,7 @@ @@ -172,7 +172,19 @@ - + } @empty { @@ -184,249 +196,25 @@ - - Riesgos y recomendaciones - - - @if (models().length) { -
{{ h.text }} @if (h.code && h.code !== h.text) { - ({{ h.code }}) + (CIE-10: {{ h.code }}) }
{{ t.date }} {{ t.kind }} {{ t.reported ?? 'Pendiente' }}{{ t.results.join(' · ') || '—' }} + {{ t.results.join(' · ') || '—' }} + @if (t.findings.length) { +
+ Hallazgos ({{ t.findings.length }}) +
    + @for (f of t.findings; track $index) { +
  • {{ f }}
  • + } +
+
+ } +
- - - - - - - - - - - @for (m of models(); track m.model) { - @for (p of m.predictions; track p.years) { - - - - - - - - } - } - -
ModeloFecha índiceHorizonteProbabilidadIC 95 %
{{ $first ? m.text : '' }}{{ $first ? m.index : '' }}{{ p.years }} {{ p.years === 1 ? 'año' : 'años' }}{{ p.p * 100 | number: '1.1-2' }} % - @if (p.low !== undefined) { - {{ p.low * 100 | number: '1.1-2' }}–{{ p.high! * 100 | number: '1.1-2' }} - % - } @else { - — - } -
- - } @else { -

Sin evaluación de un modelo en producción.

- } -
-
+ @if (forms().length) { + + } + @if (excluded() || groups().length || domain() !== 'cacu' || riskModels().length) { + + } @if (domain() === 'tea') { - - ADOS-2 - - @if (ados2(); as a) { -

Puntajes por reactivo · {{ a.date }}

- -

- @for (t of a.totals; track t.label) { - {{ t.label }}: {{ t.value }} - } -

- } @else { -

Sin evaluación ADOS-2.

- } -
-
- - - EEG - - @if (eeg.isLoading()) { - - } @else if (eeg.value()?.study; as st) { -

Calidad del EEG

-

- Estudio del {{ st.study_date }}: - {{ st.valid ? 'aceptable para el análisis' : 'no aceptable' }} - @if (st.level) { - ({{ levelNames[st.level] ?? st.level }}) - } -

-

Alteraciones del EEG

- @if (!st.valid) { -

EEG no aceptable: no se compara con la norma por edad.

- } @else if (!scored()) { -

Sin curva por edad en producción para este EEG.

- } @else if (alterations().length) { - - - - - - - - - - - - - @for (m of alterations(); track m.code) { - - - - - - - - - } - -
MétricaValorNorma por edad (P5–P95)MedianaDesviación (z)Detalle
- - {{ m.value | number: '1.0-3' }}{{ m.p5 | number: '1.0-3' }} – {{ m.p95 | number: '1.0-3' }}{{ m.median | number: '1.0-3' }}{{ m.z | number: '1.1-2' }}{{ m.outside! > 0 ? 'Aumentado' : 'Disminuido' }}
-

Elija una alteración para ver sus zonas más afectadas.

- @if (zoned(); as z) { -
-

Zonas más afectadas

-

- {{ metricNames[z.code] ?? z.code }} · - {{ - zonesScored() - ? 'desviación de cada zona frente a su norma por edad' - : 'valor de cada zona (sin norma por edad por zona)' - }} -

- @if (z.electrodes.length) { - - } - @if (z.zones.length) { -
    - @for (r of zoneOrder(); track r.site) { -
  1. - {{ zoneNames[r.site] ?? r.site }} - {{ - r.z !== null && r.z !== undefined - ? 'z = ' + (r.z | number: '1.1-2') - : (r.value | number: '1.0-3') - }} -
  2. - } -
- } @else if (!z.electrodes.length) { -

Esta métrica no se mide por zona.

- } -
- } - } @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) { -

Sin modelo de asociación en producción para este EEG.

- } @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 pacienteResultado en 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.

- } -
-
+ } @if (recurrenceModel(); as rm) { @@ -476,37 +264,28 @@ } - @if (models().some((m) => m.model.endsWith('.survival') && m.scenarios.length)) { - - Riesgo de muerte - -

Análisis de supervivencia

- @if (survival.isLoading()) { - - } @else if (survival.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 no tienen fallecimientos suficientes para trazar curvas. -

- } - - } @else if (survival.error()) { - - } -
-
+ @if (survivalModels().length) { + }
} @else if (loading()) { } + +
+ +
+ @if (saveError()) { + + } +
diff --git a/src/app/paciente/paciente.scss b/src/app/paciente/paciente.scss index 23a5a44..17a7ec7 100644 --- a/src/app/paciente/paciente.scss +++ b/src/app/paciente/paciente.scss @@ -54,47 +54,46 @@ mat-card-content { } } -.totals { - display: flex; - flex-wrap: wrap; - gap: 16px; -} - -.zones { - margin-top: 12px; -} -.regions { - list-style: none; - margin: 8px 0 0; - padding: 0; - max-width: 420px; - li { - display: flex; - justify-content: space-between; - padding: 4px 8px; - border-bottom: 1px solid var(--mat-sys-outline-variant); - } - li.marked { - font-weight: 600; - color: var(--mat-sys-error); - } -} -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; - } -} - h1 .id { font-size: 14px; font-weight: 400; margin-left: var(--space-2); vertical-align: middle; } + +/* The name and, in CaMa, the record's export on one line; narrow screens put it under the name. */ +.head { + align-items: center; + display: flex; + flex-wrap: wrap; + gap: 8px 16px; + justify-content: space-between; + h1 { + min-width: 0; + overflow-wrap: anywhere; + } + .actions { + margin-bottom: 0; + } +} +.actions { + display: flex; + justify-content: flex-end; + margin-bottom: var(--space-3); +} +.note { + font-size: 12px; + margin: var(--space-2) 0 var(--space-3); +} +.findings { + margin-top: 4px; + summary { + color: var(--color-text-secondary); + cursor: pointer; + font-size: 13px; + } + ul { + margin: 4px 0 0; + padding-left: 18px; + } +} diff --git a/src/app/paciente/paciente.ts b/src/app/paciente/paciente.ts index ffd1383..5d6c683 100644 --- a/src/app/paciente/paciente.ts +++ b/src/app/paciente/paciente.ts @@ -1,4 +1,4 @@ -import { DecimalPipe } from '@angular/common'; +import { DecimalPipe, NgTemplateOutlet } from '@angular/common'; import { Component, computed, inject, input, resource, signal } from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; @@ -8,64 +8,51 @@ import type { Condition, DiagnosticReport, Observation, + Parameters, Patient, Procedure, RiskAssessment, } from 'fhir/r4'; import { Api } from '../api/api'; -import { studies as eegStudies } from '../api/fn/eeg/studies'; -import { study as eegStudy } from '../api/fn/eeg/study'; -import { readReport$Json } from '../api/fn/models/read-report-json'; -import type { Domain } from '../api/models/domain'; -import { code, EXT, ext, Fhir, label, resources } from '../fhir'; -import { scenarioFigure } from '../gobernanza/figures'; +import { cacuEligibility } from '../api/fn/fhir/cacu-eligibility'; +import { code, ext, Fhir, resources } from '../fhir'; import { savePdf } from '../export'; -import { recordSheets } from './record-sheets'; -import { riskScales, RiskScales } from './risk-scales'; -import { route, Stages } from './stages'; -import { ageAt, ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up'; -import { LABELS, name, PRIORITY } from '../indicadores/labels'; -import { - BIOMARKER_NAMES, - byDeviation, - headMap, - METRIC_NAMES, - OUTCOME_NAMES, - ZONE_NAMES, - LEVEL_NAMES, -} from '../eeg-labels'; -import type { Relation } from '../api/models/relation'; -import { Figure, PALETTE, Plot } from '../plot'; +import { ageAt, CURP } from '../indicadores/follow-up'; +import { name } from '../indicadores/labels'; import { Loading } from '../loading'; -import { Factores, ScenarioFactors } from './factores'; +import { Plot } from '../plot'; +import { analysis } from './analysis'; +import { Antecedents } from './antecedents'; +import { camaSummary, camaFacts, camaStudies, listedRow } from './cama-record'; +import { currency, eligibilityFailure, eligibilityView, ineligibility } from './eligibility'; +import { Factores } from './factores'; +import { forms, history, models, PatientRecord, tests } from './record'; +import { camaRecordSheets, recordSheets } from './record-sheets'; +import { RiskCard } from './risk-card'; +import { riskGroups, riskScales, survivalGroups } from './risk-scales'; +import { route, Stages } from './stages'; +import { SurvivalCard } from './survival-card'; +import { TeaRecord } from './tea-record'; -/** An Observation's value as the screens say it, whatever its type. */ -function shown(o: Observation): string { - if (o.valueBoolean !== undefined) return o.valueBoolean ? 'positivo' : 'negativo'; - if (o.valueCodeableConcept) { - // The screens' own name for the code (BI-RADS 4C), else the server's display. - const c = code(o.valueCodeableConcept) ?? ''; - return (c in LABELS ? name(c) : '') || label(o.valueCodeableConcept); - } - if (o.valueQuantity) return `${o.valueQuantity.value} ${o.valueQuantity.unit ?? ''}`.trim(); - return o.valueString ?? o.valueDateTime ?? ''; -} - -/** One patient: her history (conditions, procedures), her tests and results, and the - * champion models' risks with their curves. Everything read from the FHIR API. */ +/** One patient: her history, her tests and results, the form's antecedents, her risk with its + * curves and her survival, as the FHIR API publishes them. */ @Component({ selector: 'app-paciente', imports: [ + Antecedents, + DecimalPipe, Factores, Loading, - DecimalPipe, MatButtonModule, MatCardModule, MatIconModule, - RouterLink, + NgTemplateOutlet, Plot, - RiskScales, + RiskCard, + RouterLink, Stages, + SurvivalCard, + TeaRecord, ], templateUrl: './paciente.html', styleUrl: './paciente.scss', @@ -83,362 +70,136 @@ export class Paciente { private readonly data = resource({ params: () => ({ domain: this.domain(), id: this.id() }), - loader: async ({ params: { domain, id } }) => { + loader: async ({ params: { domain, id } }): Promise => { const subject = { subject: `Patient/${id}`, _count: 200 }; const [patient, conditions, procedures, reports, observations, risks] = await Promise.all([ this.fhir.read(domain, 'Patient', id), - this.fhir.all(domain, 'Condition', subject), - this.fhir.all(domain, 'Procedure', subject), - this.fhir.all(domain, 'DiagnosticReport', subject), - this.fhir.all(domain, 'Observation', subject), - this.fhir.all(domain, 'RiskAssessment', subject), + ...['Condition', 'Procedure', 'DiagnosticReport', 'Observation', 'RiskAssessment'].map( + (type) => this.fhir.all(domain, type, subject), + ), ]); return { - patient, - conditions: resources(conditions, 'Condition'), - procedures: resources(procedures, 'Procedure'), - reports: resources(reports, 'DiagnosticReport').reverse(), + patient: patient as Patient, + conditions: resources(conditions as never, 'Condition'), + procedures: resources(procedures as never, 'Procedure'), + reports: resources(reports as never, 'DiagnosticReport').reverse(), observations: new Map( - resources(observations, 'Observation').map((o) => [o.id, o]), + resources(observations as never, 'Observation').map((o) => [o.id, o]), ), - risks: resources(risks, 'RiskAssessment'), + risks: resources(risks as never, 'RiskAssessment'), }; }, }); protected readonly patient = computed(() => this.data.value()?.patient); protected readonly error = computed(() => this.data.error()); protected readonly loading = computed(() => this.data.isLoading()); - protected readonly history = computed(() => { - const d = this.data.value(); - if (!d) return []; - return [ - ...d.conditions.map((c) => ({ - date: c.recordedDate ?? '', - kind: 'Diagnóstico', - text: label(c.code), - // the ICD-10 code a note diagnosed by (the platform's own codes stay unsaid) - code: c.code?.coding?.find((x) => x.system?.includes('icd-10'))?.code, - })), - ...d.procedures.map((p) => ({ - date: p.performedDateTime ?? '', - kind: 'Procedimiento', - text: label(p.code), - code: undefined, - })), - ].sort((a, b) => b.date.localeCompare(a.date)); - }); - private readonly cutoff = computed(() => this.corte() ?? new Date().toLocaleDateString('sv')); + protected readonly observations = computed(() => [ + ...(this.data.value()?.observations.values() ?? []), + ]); + protected readonly history = computed(() => + this.data.hasValue() ? history(this.data.value()) : [], + ); + protected readonly tests = computed(() => (this.data.hasValue() ? tests(this.data.value()) : [])); + protected readonly cutoff = computed(() => this.corte() ?? new Date().toLocaleDateString('sv')); protected readonly age = computed(() => ageAt(this.patient()?.birthDate, this.cutoff())); + private readonly cacu = computed(() => this.domain() === 'cacu'); + private readonly cytologies = computed(() => + (this.data.value()?.reports ?? []).filter((r) => code(r.code) === 'cervical_cytology'), + ); /** CaCu: the route of the cytology she was opened at, else of her latest, by the cut-off. */ protected readonly stages = computed(() => { - const cytologies = (this.data.value()?.reports ?? []).filter( - (r) => code(r.code) === 'cervical_cytology', - ); - const shown = cytologies.find((r) => r.effectiveDateTime === this.citologia()) ?? cytologies[0]; - return this.domain() === 'cacu' ? route(shown, this.cutoff()) : undefined; + const opened = this.cytologies().find((r) => r.effectiveDateTime === this.citologia()); + return this.cacu() ? route(opened ?? this.cytologies()[0], this.cutoff()) : undefined; }); - protected readonly scales = computed(() => - this.domain() === 'cacu' ? riskScales(this.models()) : [], + /** CaCu: what each cytology's form declares, the one she was opened at first. */ + protected readonly forms = computed(() => + this.cacu() && this.data.hasValue() ? forms(this.data.value(), this.citologia()) : [], ); - protected readonly saving = signal(false); - protected readonly saveError = signal(''); - /** CaCu: her record as a PDF. */ - protected async save(): Promise { - this.saving.set(true); - this.saveError.set(''); - try { - const { name: who, curp, numbers } = this.identity(); - const facts: [string, string | undefined][] = [ - ['Nombre', who], - ['CURP', curp], - ['Expedientes', numbers.join(', ')], - ['Fecha de nacimiento', this.patient()?.birthDate], - ['Edad', this.age()?.toString()], - ['Estatus de seguimiento', this.status()], - ['Fecha de corte', this.cutoff()], - ]; - const sheets = recordSheets( - facts, - this.stages() ?? [], - this.history(), - this.tests(), - this.scales(), - ); - await savePdf(sheets, 'expediente-cacu'); - } catch { - this.saveError.set('No se generó el archivo.'); - } finally { - this.saving.set(false); - } - } - protected readonly tests = computed(() => { - const d = this.data.value(); - if (!d) return []; - return d.reports.map((r) => { - const results = (r.result ?? []) - .map((x) => d.observations.get(x.reference?.split('/')[1])) - .filter((o) => !!o) as Observation[]; - return { - date: r.effectiveDateTime ?? '', - reported: ext(r, 'report-date')?.valueDate, - kind: label(r.code), - status: r.status, - // "BI-RADS 4C", not "BI-RADS: BI-RADS 4C" - results: results.map((o) => { - const [name, value] = [label(o.code), shown(o)]; - return value.startsWith(name) ? value : `${name}: ${value}`; - }), - }; - }); + + /** CaCu: the decisions `$eligibility` publishes for her indexed visits. */ + private readonly eligibility = resource({ + params: () => (this.cacu() ? { id: this.id(), cutoff: this.corte() } : undefined), + loader: async ({ params }) => { + try { + const answer = await this.api.invoke(cacuEligibility, { + domain: 'cacu', + ...params, + } as never); + return eligibilityView(answer as Parameters); + } catch (error) { + return eligibilityFailure(error); + } + }, }); - /** One model's latest risk assessment per model. */ - protected readonly models = computed(() => { - const latest = new Map(); - for (const r of this.data.value()?.risks ?? []) { - const key = code(r.method) ?? ''; - if ( - !latest.has(key) || - (latest.get(key)!.occurrenceDateTime ?? '') < (r.occurrenceDateTime ?? '') - ) - latest.set(key, r); - } - return [...latest.values()].map((r) => ({ - model: code(r.method) ?? '', - text: r.method?.text ?? '', - version: Number(/v(\d+)$/.exec(r.method?.text ?? '')?.[1] ?? 0), - index: r.occurrenceDateTime ?? '', - // the clinical scenarios of the model's report she falls in - scenarios: (r.extension ?? []) - .filter((e) => e.url === EXT + 'escenario-clinico') - .map((e) => e.valueString ?? ''), - predictions: (r.prediction ?? []).map((p) => ({ - years: p.whenRange?.high?.value ?? 0, - p: p.probabilityDecimal ?? 0, - low: ext(p, 'ic-bajo')?.valueDecimal, - high: ext(p, 'ic-alto')?.valueDecimal, - })), - })); + /** CaCu: why she has no risk estimate: the backend's reason, else a hysterectomy her record + * holds by the index (evidence loaded without the day it became available). */ + protected readonly riskExclusion = computed(() => { + const p = this.patient(); + if (!this.cacu() || !p) return undefined; + const sample = this.citologia()?.slice(0, 10); + const index = sample && sample < this.cutoff() ? sample : this.cutoff(); + const status = ext(p, 'follow-up-status')?.valueCoding?.code ?? ''; + const state = this.eligibility.value() ?? { kind: 'loading' as const }; + const recorded = ext(p, 'first-hysterectomy-recorded')?.valueDate; + return ( + ineligibility(state, status, index) ?? + (recorded && recorded <= index + ? `No disponible por: histerectomía registrada el ${recorded}.` + : undefined) + ); }); - /** "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. */ + /** Each model's latest estimate of her; none when she is excluded. */ + protected readonly models = computed(() => + this.riskExclusion() ? [] : models(this.data.value()?.risks ?? []), + ); + protected readonly riskModels = computed(() => this.models().filter((m) => m.measure === 'risk')); + protected readonly survivalModels = computed(() => + this.models().filter((m) => m.model.endsWith('.survival')), + ); + /** CaCu: the cytology her estimates speak of, against her latest by the cut-off. */ + protected readonly currency = computed(() => + this.cacu() + ? currency( + this.riskModels(), + this.cytologies() + .map((r) => r.effectiveDateTime ?? '') + .filter((d) => d && d.slice(0, 10) <= this.cutoff()), + ) + : {}, + ); + /** The one reason nothing of her risk is shown: the backend withholding it, her exclusion, or a + * later cytology after her first post-colposcopy visit. */ + protected readonly excluded = computed( + () => + (this.patient() && ext(this.patient(), 'risk-withheld')?.valueString) ?? + this.riskExclusion() ?? + this.currency().excluded, + ); + /** CaCu: both horizons of every risk model, or both unavailable (with survival only, nothing). */ + protected readonly groups = computed(() => + this.cacu() && (this.riskModels().length || !survivalGroups(this.survivalModels()).length) + ? riskGroups(this.riskModels()) + : [], + ); + /** "Análisis de supervivencia" and "de recurrencia" of her clinical scenarios. */ 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') { + private analysis(kind: '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; - // The risk factors of her scenarios, by horizon (the development tables). - const technical = (await this.api.invoke(readReport$Json, { - domain: domain as Domain, - name, - version: m.version, - report: 'technical_validation', - })) as any; - const summary = technical?.['recurrencia_desarrollo']?.['tablas']?.['escenarios_resumen']; - return { - factors: mine(summary?.['filas'] ?? []) as ScenarioFactors[], - 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 { - factors: mine((report?.['factores_escenarios'] ?? []) as any[]) as ScenarioFactors[], - 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)', - ), - ), - }; + const domain = this.domain(); + const m = this.models().find((x) => x.model === `${domain}.${kind}` && x.scenarios.length); + return m?.version && !(kind === 'survival' && domain === 'cacu') + ? { domain, m } + : undefined; }, + loader: ({ params: { domain, m } }) => analysis(this.api, domain, m), }); } - /** 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(() => { - const d = this.data.value(); - if (!d) return undefined; - const field = (o: Observation) => (code(o.code) ?? '').replace(/^ados2\./, ''); - const scored = [...d.observations.values()].filter( - (o) => (code(o.code) ?? '').startsWith('ados2.') && o.valueQuantity?.value !== undefined, - ); - const latest = scored - .map((o) => o.effectiveDateTime ?? '') - .sort() - .at(-1); - if (latest === undefined) return undefined; - const results = scored.filter((o) => (o.effectiveDateTime ?? '') === latest); - const totals = ['social_affect_total', 'restricted_repetitive_total', 'overall_total']; - const items = results.filter((o) => !totals.includes(field(o))); - const figure: Figure = { - data: [ - { - type: 'bar', - orientation: 'h', - y: items.map((o) => label(o.code)), - x: items.map((o) => o.valueQuantity!.value!), - marker: { color: PALETTE[0] }, - hovertemplate: '%{y}: %{x}', - }, - ], - layout: { - showlegend: false, - margin: { t: 10, r: 16, b: 40, l: 16 }, - xaxis: { title: { text: 'Puntaje (0 a 3)' }, range: [0, 3], dtick: 1 }, - yaxis: { autorange: 'reversed', automargin: true, type: 'category' }, - }, - }; - return { - date: latest.slice(0, 10), - figure, - height: 60 + items.length * 22, - totals: results - .filter((o) => totals.includes(field(o))) - .map((o) => ({ label: label(o.code), value: o.valueQuantity!.value! })), - }; - }); - /** TEA: her EEG as analysed (the latest), its quality and its metrics against the age - * curves: those outside the band are its alterations. */ - protected readonly eeg = resource({ - params: () => (this.domain() === 'tea' ? this.id() : undefined), - loader: async ({ params: person }) => { - const mine = (await this.api.invoke(eegStudies)) - .filter((s) => s.person_id === person && s.analysed) - .sort((a, b) => b.study_date.localeCompare(a.study_date)); - if (!mine.length) return { study: undefined, analysis: undefined }; - return { - study: mine[0], - analysis: await this.api.invoke(eegStudy, { eeg_id: mine[0].id }), - }; - }, - }); - protected readonly alterations = computed(() => - (this.eeg.value()?.analysis?.metrics ?? []).filter((m) => m.outside), - ); - protected readonly scored = computed(() => - (this.eeg.value()?.analysis?.metrics ?? []).some((m) => m.z !== null && m.z !== undefined), - ); - protected readonly shown = signal(undefined); - protected readonly metricNames = METRIC_NAMES; - protected readonly zoneNames = ZONE_NAMES; - /** "Zonas más afectadas": the alteration chosen, its zones and electrodes. */ - protected readonly zone = signal(undefined); - protected readonly zoned = computed(() => { - const m = this.alterations().find((a) => a.code === this.zone()); - return m ? { code: m.code, zones: m.zones ?? [], electrodes: m.electrodes ?? [] } : undefined; - }); - protected readonly zonesScored = computed(() => - [...(this.zoned()?.zones ?? []), ...(this.zoned()?.electrodes ?? [])].some( - (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 la asociación de la cohorte' - : 'No coincide con la asociación de la cohorte'; - } - protected readonly zoneOrder = computed(() => byDeviation(this.zoned()?.zones ?? [])); - protected readonly head = computed(() => headMap(this.zoned()?.electrodes ?? [])); - protected readonly curve = computed
(() => { - const models = this.models().filter((m) => m.predictions.length > 1); - return { - data: models.flatMap((m, i) => { - const x = m.predictions.map((p) => p.years); - const color = PALETTE[i % PALETTE.length]; - return [ - { - x, - y: m.predictions.map((p) => (p.high ?? p.p) * 100), - mode: 'lines', - line: { width: 0 }, - showlegend: false, - hoverinfo: 'skip', - }, - { - x, - y: m.predictions.map((p) => (p.low ?? p.p) * 100), - mode: 'lines', - line: { width: 0 }, - fill: 'tonexty', - fillcolor: color + '33', - showlegend: false, - hoverinfo: 'skip', - }, - { - x, - y: m.predictions.map((p) => p.p * 100), - mode: 'lines+markers', - name: m.text.replace(/ v\d+$/, ''), - line: { color }, - }, - ]; - }), - layout: { - xaxis: { title: { text: 'Años desde la fecha índice' }, dtick: 1 }, - // At least 0–5 %: a near-zero risk reads as near zero, not as a full axis. - yaxis: { - title: { text: 'Probabilidad (%)' }, - range: [0, Math.max(5, this.top() * 110)], - tickformat: '.1f', - }, - }, - }; - }); - private top(): number { - return Math.max(0, ...this.models().flatMap((m) => m.predictions.map((p) => p.high ?? p.p))); - } - protected readonly name = name; - protected readonly levelNames = LEVEL_NAMES; protected readonly identity = computed(() => { const p = this.patient(); return { @@ -446,74 +207,88 @@ export class Paciente { curp: p?.identifier?.find((i) => i.system === CURP)?.value, // each record number once (several sources may carry the same one) numbers: [ - ...new Set( - (p?.identifier ?? []).filter((i) => i.system !== CURP).map((i) => i.value ?? ''), - ), - ].filter(Boolean), + ...new Set((p?.identifier ?? []).filter((i) => i.system !== CURP).map((i) => i.value)), + ].filter((n): n is string => !!n), }; }); - /** CaMa: her row on the follow-up list (window and cut-off as opened, else the widest - * window up to the last day with data), as the list shows it: the old record's card. */ + /** CaMa: her row on the follow-up list, as opened (else the widest window). */ private readonly listed = resource({ params: () => this.domain() === 'cama' - ? { - domain: this.domain(), - id: this.id(), - window: Number(this.ventana()) || 12, - cutoff: this.corte() || undefined, - } + ? { id: this.id(), window: Number(this.ventana()) || 12, cutoff: this.corte() || undefined } : undefined, - loader: async ({ params: { domain, id, window, cutoff } }) => { - const page = await this.fhir.search(domain, 'Patient', { - _id: id, - 'follow-up-window': window, - 'follow-up-cutoff': cutoff, - _revinclude: ['DiagnosticReport:subject'], - '_include:iterate': 'DiagnosticReport:result', - }); - const self = page.link?.find((l) => l.relation === 'self')?.url; - const applied = self ? (new URL(self).searchParams.get('follow-up-cutoff') ?? '') : ''; - return { window, cutoff: applied, row: camaRows(page, applied)[0] }; - }, + loader: ({ params }) => listedRow(this.fhir, params), }); protected readonly cama = computed(() => { const found = this.listed.value(); - const d = this.data.value(); - if (!found || !d) return undefined; - // Her own latest mammogram and biopsy, on the list or not. - const latest = (study: string) => - d.reports - .filter((r) => code(r.code) === study) - .sort((a, b) => (a.effectiveDateTime ?? '').localeCompare(b.effectiveDateTime ?? '')) - .at(-1); - const value = (r: DiagnosticReport | undefined, field: string) => { - const o = (r?.result ?? []) - .map((x) => d.observations.get(x.reference?.split('/')[1])) - .find((x) => code(x?.code) === field); - return o ? shown(o) : undefined; - }; - const mammogram = latest('mammography'); - const biopsy = latest('breast_biopsy'); - const treated = d.procedures.some((p) => (p.performedDateTime ?? '') <= found.cutoff); - const r = found.row; - return { - ...found, - ageGroup: r?.ageGroup ?? ageGroup(d.patient.birthDate, found.cutoff, CAMA_AGE_GROUPS), - scenario: treated ? 'Post-tratamiento' : 'En observación', - status: r ? name(r.status) : undefined, - priority: r ? (PRIORITY[r.priority] ?? r.priority) : undefined, - birads: value(mammogram, 'mammography.birads'), - mammogram: mammogram?.effectiveDateTime?.slice(0, 10), - days: mammogram ? ext(mammogram, 'days-to-diagnosis')?.valueInteger : undefined, - histology: value(biopsy, 'breast_biopsy.histology'), - biopsy: biopsy - ? (ext(biopsy, 'report-date')?.valueDate ?? biopsy.effectiveDateTime) - : undefined, - }; + return found && this.data.hasValue() ? camaSummary(this.data.value(), found) : undefined; }); protected readonly status = computed(() => { const p = this.patient(); return p ? name(ext(p, 'follow-up-status')?.valueCoding?.code ?? '') : ''; }); + + protected readonly saving = signal(false); + protected readonly saveError = signal(''); + /** Her record as a PDF (CaCu's or CaMa's). */ + protected async save(): Promise { + this.saving.set(true); + this.saveError.set(''); + try { + if (this.domain() === 'cama') await this.saveCama(); + else await this.saveCacu(); + } catch { + this.saveError.set('No se generó el archivo.'); + } finally { + this.saving.set(false); + } + } + private async saveCacu(): Promise { + const { name: who, curp, numbers } = this.identity(); + const facts: [string, string | undefined][] = [ + ['Nombre', who], + ['CURP', curp], + ['Expedientes', numbers.join(', ')], + ['Fecha de nacimiento', this.patient()?.birthDate], + ['Edad', this.age()?.toString()], + ['Estatus de seguimiento', this.status()], + ['Fecha de corte', this.cutoff()], + ]; + if (this.riskExclusion()) facts.push(['Evaluación de probabilidad', this.riskExclusion()]); + const scales = riskScales(this.riskModels()); + const sheets = recordSheets( + facts, + this.stages() ?? [], + this.history(), + this.tests(), + scales, + this.forms(), + ); + await savePdf(sheets, 'expediente-cacu'); + } + private async saveCama(): Promise { + // an analysis that failed to load is none: its absence is said, the file is still made + const read = (title: string, r: typeof this.survival) => { + const v = r.hasValue() ? r.value() : undefined; + return v + ? [ + { + title, + scenarios: v.scenarios, + figures: v.figures.map((f) => f.title), + undrawn: v.unavailable, + }, + ] + : []; + }; + const sheets = camaRecordSheets( + camaFacts(this.identity(), this.patient(), this.cama()), + camaStudies(this.cama()), + this.history(), + this.tests(), + this.models(), + [...read('Supervivencia', this.survival), ...read('Recurrencia', this.recurrence)], + ); + await savePdf(sheets, 'expediente-cama'); + } } diff --git a/src/app/paciente/record-groups.ts b/src/app/paciente/record-groups.ts new file mode 100644 index 0000000..7814b82 --- /dev/null +++ b/src/app/paciente/record-groups.ts @@ -0,0 +1,53 @@ +/** A field of a study's form, as its Observation says it: `cervical_cytology.hpv` is the study + * `cervical_cytology` and the field `hpv`. */ +export interface Fact { + study: string; + field: string; + title: string; + value: string; +} + +/** What the cytology's form declares before and at the sample: statements of the form, not + * diagnoses. */ +export const ANTECEDENTS = [ + { field: 'screening_history', title: 'Detección de cáncer de cérvix' }, + { field: 'gynecologic_condition', title: 'Condición ginecoobstétrica a la detección' }, + { field: 'presenting_symptom', title: 'Actualmente presenta' }, + { field: 'cervix_appearance', title: 'A la exploración se observa' }, +]; +const DECLARED = new Set(ANTECEDENTS.map((a) => a.field)); +const HPV = new Set(['hpv', 'hpv_16', 'hpv_18']); + +/** A catalog code as its study and field. */ +export function split(code: string): { study: string; field: string } { + const [study, ...field] = code.split('.'); + return field.length ? { study, field: field.join('.') } : { study: '', field: code }; +} + +const capital = (s: string) => s.charAt(0).toUpperCase() + s.slice(1); + +/** A report's facts sorted by what they are: the form's antecedents (by field), the study's own + * results, and the extra findings (the cytologist's text first, then each finding stated). */ +export function group(facts: Fact[]) { + const antecedents: Record = {}; + const results: string[] = []; + const findings: string[] = []; + for (const f of facts) { + const form = f.study === 'cervical_cytology'; + if (form && DECLARED.has(f.field)) antecedents[f.field] = f.value; + else if (form && f.field === 'findings') findings.unshift(`Texto del informe: ${f.value}`); + else if (form && f.field.startsWith('finding_')) { + const named = capital(f.title.replace(/^Hallazgo: /, '')); + findings.push(f.value === 'positivo' ? named : `${named}: ${f.value}`); + } + // "BI-RADS 4C", not "BI-RADS: BI-RADS 4C" + else results.push(f.value.startsWith(f.title) ? f.value : `${f.title}: ${f.value}`); + } + return { antecedents, results, findings }; +} + +/** A cytology report's HPV results apart from the cytology's own: they are a study of their own. */ +export function hpvApart(facts: Fact[]) { + const hpv = (f: Fact) => f.study === 'cervical_cytology' && HPV.has(f.field); + return { hpv: facts.filter(hpv), rest: facts.filter((f) => !hpv(f)) }; +} diff --git a/src/app/paciente/record-sheets.ts b/src/app/paciente/record-sheets.ts index 6955dc7..5d15599 100644 --- a/src/app/paciente/record-sheets.ts +++ b/src/app/paciente/record-sheets.ts @@ -1,10 +1,14 @@ import type { Sheet } from '../export'; -import type { RiskScale } from './risk-scales'; -import { Stage, STATES } from './stages'; +import { ANTECEDENTS } from './record-groups'; +import type { Prediction, RiskScale } from './risk-scales'; +import { SOURCES, Stage, STATES } from './stages'; const NONE = 'No disponible'; const percent = (p: number) => `${(100 * p).toFixed(2)} %`; +const between = (p?: Prediction) => + p?.low === undefined || p.high === undefined ? NONE : `${percent(p.low)} a ${percent(p.high)}`; +type Facts = [string, string | undefined][]; interface Event { date: string; kind: string; @@ -15,45 +19,133 @@ interface Test { kind: string; reported?: string; results: string[]; + /** the extra findings (collapsed on the page) */ + findings: string[]; +} +interface Form { + date: string; + values: Record; +} +/** A published estimate (risk, survival or recurrence) by horizon. */ +interface Estimate { + text: string; + index: string; + predictions: Prediction[]; +} +/** The curves of her clinical scenarios as the page lists them. */ +export interface Analysis { + title: string; + scenarios: string[]; + /** the titles of the figures drawn */ + figures: string[]; + /** her scenarios the report draws no curve for */ + undrawn: string[]; } -/** A patient's record as the tables of her PDF, in the page's order. */ +const table = (title: string, facts: Facts): Sheet => ({ + title, + head: ['Dato', 'Valor'], + rows: facts.map(([k, v]) => [k, v || NONE]), +}); +const historySheet = (history: Event[]): Sheet => ({ + title: 'Historial médico', + head: ['Fecha', 'Tipo', 'Detalle'], + rows: history.map((h) => [h.date, h.kind, h.text]), +}); +const testsSheet = (tests: Test[]): Sheet => ({ + title: 'Pruebas y resultados', + head: ['Toma', 'Estudio', 'Reporte', 'Resultados', 'Hallazgos'], + rows: tests.map((t) => [ + t.date, + t.kind, + t.reported ?? 'Pendiente', + t.results.join(' · '), + t.findings.join(' · '), + ]), +}); + +/** A CaCu patient's record as the tables of her PDF, in the page's order. */ export function recordSheets( - facts: [string, string | undefined][], + facts: Facts, stages: Stage[], history: Event[], tests: Test[], scales: RiskScale[], + forms: Form[], ): Sheet[] { return [ - { - title: 'Datos de la paciente', - head: ['Dato', 'Valor'], - rows: facts.map(([k, v]) => [k, v || NONE]), - }, + table('Datos de la paciente', facts), { title: 'Etapas del tamizaje', - head: ['Etapa', 'Estado', 'Fecha'], - rows: stages.map((s) => [s.label, STATES[s.state], s.day ?? '']), - }, - { - title: 'Historial médico', - head: ['Fecha', 'Tipo', 'Detalle'], - rows: history.map((h) => [h.date, h.kind, h.text]), - }, - { - title: 'Pruebas y resultados', - head: ['Toma', 'Estudio', 'Reporte', 'Resultados'], - rows: tests.map((t) => [t.date, t.kind, t.reported ?? 'Pendiente', t.results.join(' · ')]), - }, - { - title: 'Riesgos', - head: ['Riesgo', 'Probabilidad', 'IC 95 %'], - rows: scales.map(({ label, risk }) => [ - label, - risk ? percent(risk.p) : NONE, - risk?.low === undefined ? NONE : `${percent(risk.low)} a ${percent(risk.high!)}`, + head: ['Etapa', 'Estado', 'Fecha', 'Procedencia'], + rows: stages.map((s) => [ + s.label, + STATES[s.state], + s.day ?? (s.requested ? `Solicitada el ${s.requested}` : ''), + (s.sources ?? []).map((c) => SOURCES[c]).join(' · '), ]), }, + historySheet(history), + { + title: + 'Antecedentes y evaluación ginecológica (declarados en el formulario de la citología; no son diagnósticos confirmados)', + head: ['Toma', ...ANTECEDENTS.map((a) => a.title)], + rows: forms.map((f) => [ + f.date, + ...ANTECEDENTS.map((a) => f.values[a.field] ?? 'No documentado'), + ]), + }, + testsSheet(tests), + { + title: 'Probabilidades', + head: ['Estimación', 'Probabilidad', 'IC 95 %'], + rows: scales.map(({ label, risk }) => [label, risk ? percent(risk.p) : NONE, between(risk)]), + }, + ]; +} + +const horizon = (years: number) => + years === 0 ? 'Al índice' : `${years} ${years === 1 ? 'año' : 'años'}`; + +/** A CaMa patient's record as the tables of her PDF: only what CaMa publishes, an absent value + * said as such and no estimate made up. */ +export function camaRecordSheets( + facts: Facts, + studies: Facts, + history: Event[], + tests: Test[], + estimates: Estimate[], + analyses: Analysis[], +): Sheet[] { + const risks = estimates.flatMap((m) => + m.predictions.map((p) => [m.text, m.index || NONE, horizon(p.years), percent(p.p), between(p)]), + ); + const curves = analyses.flatMap((a) => [ + ...a.figures.map((f) => [a.title, f, 'Curva publicada']), + ...a.undrawn.map((s) => [a.title, s, 'No disponible: datos insuficientes']), + ...(a.figures.length || a.undrawn.length + ? [] + : [[a.title, a.scenarios.join('; ') || NONE, NONE]]), + ]); + return [ + table('Datos de la paciente', facts), + table('Última mastografía y resultado histopatológico', studies), + historySheet(history), + testsSheet(tests), + { + title: 'Riesgos y recomendaciones publicados', + head: ['Estimación', 'Fecha índice', 'Horizonte', 'Probabilidad', 'IC 95 %'], + rows: risks.length ? risks : [['Sin estimaciones publicadas', NONE, NONE, NONE, NONE]], + }, + ...(curves.length + ? [ + { + title: + 'Supervivencia y recurrencia por escenario clínico (estimaciones del grupo, no predicciones individuales)', + head: ['Análisis', 'Escenario', 'Estado'], + rows: curves, + }, + ] + : []), ]; } diff --git a/src/app/paciente/record.ts b/src/app/paciente/record.ts new file mode 100644 index 0000000..8297ea5 --- /dev/null +++ b/src/app/paciente/record.ts @@ -0,0 +1,147 @@ +import type { + Condition, + DiagnosticReport, + Observation, + Patient, + Procedure, + RiskAssessment, +} from 'fhir/r4'; +import { code, EXT, ext, label } from '../fhir'; +import { LABELS, name } from '../indicadores/labels'; +import { ANTECEDENTS, Fact, group, hpvApart, split } from './record-groups'; + +/** Her record as the FHIR API gives it. */ +export interface PatientRecord { + patient: Patient; + conditions: Condition[]; + procedures: Procedure[]; + /** latest first */ + reports: DiagnosticReport[]; + observations: Map; + risks: RiskAssessment[]; +} + +/** An Observation's value as the screens say it, whatever its type. */ +export function shown(o: Observation): string { + if (o.valueBoolean !== undefined) return o.valueBoolean ? 'positivo' : 'negativo'; + if (o.valueCodeableConcept) { + // the screens' own name for the code (BI-RADS 4C), else the server's display + const c = code(o.valueCodeableConcept) ?? ''; + return (c in LABELS ? name(c) : '') || label(o.valueCodeableConcept); + } + if (o.valueQuantity) return `${o.valueQuantity.value} ${o.valueQuantity.unit ?? ''}`.trim(); + return o.valueString ?? o.valueDateTime ?? ''; +} + +/** A report's Observations. */ +export const results = (d: PatientRecord, r: DiagnosticReport) => + (r.result ?? []) + .map((x) => d.observations.get(x.reference?.split('/')[1])) + .filter((o): o is Observation => !!o); + +/** Observations as facts of their study's form. */ +const facts = (observations: Observation[]): Fact[] => + observations.map((o) => ({ + ...split(code(o.code) ?? ''), + title: label(o.code), + value: shown(o), + })); + +/** Her diagnoses and procedures, latest first. */ +export function history(d: PatientRecord) { + return [ + ...d.conditions.map((c) => ({ + date: c.recordedDate ?? '', + kind: 'Diagnóstico', + text: label(c.code), + // the ICD-10 code a note diagnosed by (the platform's own codes stay unsaid) + code: c.code?.coding?.find((x) => x.system?.includes('icd-10'))?.code, + })), + ...d.procedures.map((p) => ({ + date: p.performedDateTime ?? '', + kind: 'Procedimiento', + text: label(p.code), + code: undefined, + })), + ].sort((a, b) => b.date.localeCompare(a.date)); +} + +/** Her studies and their own results; the form's antecedents have their section, the extra + * findings are collapsed, and an HPV result is a study of its own row. */ +export function tests(d: PatientRecord) { + return d.reports.flatMap((r) => { + const { hpv, rest } = hpvApart(facts(results(d, r))); + const found = group(rest); + const row = { + date: r.effectiveDateTime ?? '', + reported: ext(r, 'report-date')?.valueDate, + kind: label(r.code), + status: r.status, + results: found.results, + findings: found.findings, + }; + if (!hpv.length) return [row]; + return [row, { ...row, kind: 'Prueba de VPH', results: group(hpv).results, findings: [] }]; + }); +} + +/** What each cytology's form declares (statements, not diagnoses), the one she was opened at + * first; forms that declare nothing are left out. */ +export function forms(d: PatientRecord, opened?: string) { + const cytologies = d.reports.filter((r) => code(r.code) === 'cervical_cytology'); + const first = cytologies.find((r) => r.effectiveDateTime === opened) ?? cytologies[0]; + return [first, ...cytologies.filter((r) => r !== first)] + .filter((r) => !!r) + .map((r) => ({ + date: r.effectiveDateTime ?? '', + values: group(facts(results(d, r))).antecedents, + })) + .filter((f) => ANTECEDENTS.some((a) => f.values[a.field])); +} + +/** The JSON of a model's inputs as an object; anything else is none. */ +function inputs(value?: string): Record | undefined { + try { + const found: unknown = value && JSON.parse(value); + return found && typeof found === 'object' && !Array.isArray(found) + ? (found as never) + : undefined; + } catch { + return undefined; + } +} + +/** The day of an instant at the hospital (America/Monterrey). */ +const localDay = (instant?: string) => + instant && new Date(instant).toLocaleDateString('en-CA', { timeZone: 'America/Monterrey' }); + +/** Each model's latest assessment of her. */ +export function models(risks: RiskAssessment[]) { + const latest = new Map(); + for (const r of risks) { + const key = code(r.method) ?? ''; + const held = latest.get(key)?.occurrenceDateTime; + if (held === undefined || held < (r.occurrenceDateTime ?? '')) latest.set(key, r); + } + return [...latest.values()].map((r) => ({ + model: code(r.method) ?? '', + text: r.method?.text ?? '', + version: Number(/v(\d+)$/.exec(r.method?.text ?? '')?.[1] ?? 0), + index: r.occurrenceDateTime ?? '', + /** risk, mortality (survival) or other (recurrence) */ + measure: ext(r, 'prediction-measure')?.valueCode, + inputs: inputs(ext(r, 'model-inputs')?.valueString), + evaluated: localDay(r.meta?.lastUpdated), + // the clinical scenarios of the model's report she falls in + scenarios: (r.extension ?? []) + .filter((e) => e.url === EXT + 'escenario-clinico') + .map((e) => e.valueString ?? ''), + predictions: (r.prediction ?? []).map((p) => ({ + years: p.whenRange?.high?.value ?? 0, + p: p.probabilityDecimal ?? 0, + low: ext(p, 'ic-bajo')?.valueDecimal, + high: ext(p, 'ic-alto')?.valueDecimal, + })), + })); +} +export type Model = ReturnType[number]; diff --git a/src/app/paciente/risk-card.html b/src/app/paciente/risk-card.html new file mode 100644 index 0000000..c38ed00 --- /dev/null +++ b/src/app/paciente/risk-card.html @@ -0,0 +1,65 @@ + + @if (excluded(); as reason) { + + Sin estimación de riesgo: criterio de exclusión + + +

{{ reason }}

+
+ } @else { + + @if (note(); as said) { +

{{ said }}

+ } + + @if (models().length) { +
+ Modelos y valores + + + + + + + + + + + + @for (m of models(); track m.model) { + @for (p of m.predictions; track p.years) { + + + + + + + + } + } + +
ModeloFecha índiceHorizonteProbabilidadIC 95 %
{{ $first ? m.text : '' }}{{ $first ? m.index : '' }}{{ p.years }} {{ p.years === 1 ? 'año' : 'años' }}{{ p.p * 100 | number: '1.1-2' }} % + @if (p.low !== undefined && p.high !== undefined) { + {{ p.low * 100 | number: '1.1-2' }}–{{ p.high * 100 | number: '1.1-2' }} % + } @else { + — + } +
+
+ } + @if (models().length || drawn()) { +
+ Curvas de probabilidad con su intervalo + @if (drawn(); as series) { + + } @else { + + } +
+ } + @if (!models().length) { +

Sin evaluación de un modelo en producción.

+ } +
+ } +
diff --git a/src/app/paciente/risk-card.ts b/src/app/paciente/risk-card.ts new file mode 100644 index 0000000..709c69a --- /dev/null +++ b/src/app/paciente/risk-card.ts @@ -0,0 +1,79 @@ +import { DecimalPipe } from '@angular/common'; +import { HttpClient } from '@angular/common/http'; +import { Component, computed, inject, input, resource } from '@angular/core'; +import { MatCardModule } from '@angular/material/card'; +import type { Parameters } from 'fhir/r4'; +import { firstValueFrom } from 'rxjs'; +import { ApiConfiguration } from '../api/api-configuration'; +import { Plot } from '../plot'; +import type { Model } from './record'; +import { curveFigure } from './risk-curve'; +import { RiskGroup, RiskScales } from './risk-scales'; +import { parseSeries, RiskSeries } from './risk-series'; + +/** Her risk: why she has none, or the scales of each model, its values and its curves (CaCu: with + * the series `$risk-series` publishes, when the API has them on). */ +@Component({ + selector: 'app-risk-card', + imports: [DecimalPipe, MatCardModule, Plot, RiskScales, RiskSeries], + templateUrl: './risk-card.html', + styles: ` + .note { + font-size: 12px; + margin: 8px 0 12px; + } + .curves { + border: 1px solid var(--color-border); + border-radius: 6px; + margin-top: 12px; + padding: 8px 12px; + summary { + cursor: pointer; + font-weight: 500; + } + } + `, +}) +export class RiskCard { + private readonly http = inject(HttpClient); + private readonly root = inject(ApiConfiguration).rootUrl; + readonly domain = input.required(); + readonly id = input.required(); + readonly cutoff = input(); + /** the day of the cytology her estimates speak of */ + readonly sample = input(); + /** the models whose estimate is a risk (not survival or recurrence) */ + readonly models = input.required(); + readonly groups = input.required(); + /** why she has no estimate, when she has none */ + readonly excluded = input(); + readonly note = input(); + + /** CaCu, experimental: the series her record compares; none while the API has them off. */ + protected readonly series = resource({ + params: () => + this.domain() === 'cacu' + ? { id: this.id(), cutoff: this.cutoff(), sample: this.sample()?.slice(0, 10) } + : undefined, + loader: async ({ params: { id, ...asked } }) => { + const params = Object.fromEntries(Object.entries(asked).filter(([, v]) => !!v)) as never; + const url = `${this.root}/cacu/fhir/Patient/${id}/$risk-series`; + try { + return parseSeries(await firstValueFrom(this.http.get(url, { params }))); + } catch { + return undefined; + } + }, + }); + protected readonly drawn = computed(() => + this.series.hasValue() && this.series.value()?.some((s) => s.points.length) + ? this.series.value() + : undefined, + ); + protected readonly curve = computed(() => + curveFigure( + this.models(), + Math.max(0, ...this.models().flatMap((m) => m.predictions.map((p) => p.high ?? p.p))), + ), + ); +} diff --git a/src/app/paciente/risk-curve.ts b/src/app/paciente/risk-curve.ts new file mode 100644 index 0000000..386b1ce --- /dev/null +++ b/src/app/paciente/risk-curve.ts @@ -0,0 +1,93 @@ +import { Figure, PALETTE } from '../plot'; +import type { Prediction } from './risk-scales'; + +/** A model's (or a source's) probabilities by horizon. */ +export interface CurveModel { + /** its own title, with its version */ + text: string; + /** its index date ('' when it has none) */ + index: string; + predictions: Prediction[]; +} + +const title = (m: CurveModel) => + m.text + .replace(/ v\d+$/, '') + .replace(/riesgo/gi, (w) => (w[0] === 'R' ? 'Probabilidad' : 'probabilidad')); +const bounded = (p: Prediction) => p.low !== undefined && p.high !== undefined; +const percent = (n: number | undefined) => (n === undefined ? null : n * 100); + +/** One series per model drawn only at the horizons it publishes (one horizon is a point); its + * 95 % interval a band where two or more horizons have one, else an error bar. Nothing is made up + * between horizons: a gap in the intervals stays a gap. */ +export function curveFigure(models: CurveModel[], top: number): Figure { + const shown = models.filter((m) => m.predictions.length); + const ticks = [...new Set(shown.flatMap((m) => m.predictions.map((p) => p.years)))].sort( + (a, b) => a - b, + ); + const dates = [...new Set(shown.map((m) => m.index))]; + const data = shown.flatMap((m, i) => { + const color = PALETTE[i % PALETTE.length]; + const sorted = [...m.predictions].sort((a, b) => a.years - b.years); + const x = sorted.map((p) => p.years); + const name = title(m); + const banded = sorted.filter(bounded).length; + const edge = (pick: (p: Prediction) => number | undefined) => ({ + x, + y: sorted.map((p) => (bounded(p) ? percent(pick(p)) : null)), + mode: 'lines', + line: { width: 0 }, + connectgaps: false, + legendgroup: name, + hoverinfo: 'skip', + }); + const band = + banded > 1 + ? [ + { ...edge((p) => p.high), showlegend: false }, + { + ...edge((p) => p.low), + fill: 'tonexty', + fillcolor: color + '33', + name: `IC 95 % ${name}`, + }, + ] + : []; + const bar = sorted.map((p) => (bounded(p) ? (p.high! - p.p) * 100 : 0)); + const barMinus = sorted.map((p) => (bounded(p) ? (p.p - p.low!) * 100 : 0)); + return [ + ...band, + { + x, + y: sorted.map((p) => p.p * 100), + mode: sorted.length > 1 ? 'lines+markers' : 'markers', + name, + legendgroup: name, + line: { color }, + marker: { color, size: 8 }, + ...(banded === 1 + ? { error_y: { type: 'data', symmetric: false, color, array: bar, arrayminus: barMinus } } + : {}), + hovertemplate: `${name}
%{x} años: %{y:.2f} %`, + }, + ]; + }); + const at = dates.length === 1 && dates[0] ? ` (${dates[0]})` : ''; + return { + data, + layout: { + xaxis: { + title: { text: `Horizonte (años desde la fecha índice${at})` }, + tickmode: 'array', + tickvals: ticks, + ticktext: ticks.map(String), + }, + // at least 0–5 %: a near-zero probability reads as near zero, not as a full axis + yaxis: { + title: { text: 'Probabilidad (%)' }, + range: [0, Math.max(5, top * 110)], + tickformat: '.0f', + }, + }, + } as Figure; +} diff --git a/src/app/paciente/risk-scales.html b/src/app/paciente/risk-scales.html new file mode 100644 index 0000000..4b2adae --- /dev/null +++ b/src/app/paciente/risk-scales.html @@ -0,0 +1,94 @@ +@for (g of groups(); track $index) { + @if (g.title) { +

{{ g.title }}

+ } + @for (s of g.scales; track s.label) { +
+

+ {{ s.label }} + @if (s.risk; as r) { + @if (r.low !== undefined && r.high !== undefined) { + · IC 95 %: {{ r.low * 100 | number: '1.1-2' }}–{{ r.high * 100 | number: '1.1-2' }} % + } + } @else { + · No disponible + } +

+
+ + @if (s.risk; as r) { + @if (r.low !== undefined && r.high !== undefined) { + + } + + {{ r.p * 100 | number: '1.1-2' }} % + } +
+ +
+ } + @if (g.index) { +

+ {{ g.scenario ? 'Escenario: ' + g.scenario + ' · ' : '' }}Fecha índice {{ g.index }} +

+ } + @if (g.title && !g.survival) { +
+

Factores de riesgo considerados

+ @if (g.inputs) { +
+ @for (i of entries(g.inputs); track i[0]) { +
+
{{ inputName(i[0]) }}
+
{{ inputValue(i[0], i[1]) }}
+
+ } +
+ } @else { +

Los valores utilizados no están disponibles para esta estimación.

+ } +
+ } + @if (g.model) { +
+ Métodos +
+
+
Modelo y versión
+
{{ g.model }}
+
+
+
Fecha índice
+
{{ g.index }}
+
+
+
Fecha de evaluación
+
{{ g.evaluated ?? 'No disponible' }}
+
+
+
Covariables
+
+ @for (i of entries(g.inputs); track i[0]) { +
{{ inputName(i[0]) }}: {{ inputValue(i[0], i[1]) }}
+ } @empty { + No disponibles para esta estimación. + } +
+
+
+
+ } +} diff --git a/src/app/paciente/risk-scales.scss b/src/app/paciente/risk-scales.scss new file mode 100644 index 0000000..46cc1dd --- /dev/null +++ b/src/app/paciente/risk-scales.scss @@ -0,0 +1,84 @@ +$ink: #17324d; + +.scale { + margin: 8px 0 14px; + max-width: 740px; + p { + margin: 0; + } +} +.plot { + padding-top: 30px; + position: relative; +} +// four equal parts, low to high; survival reads the other way +.line { + background: linear-gradient( + to right, + #42a77e 0 25%, + #a8c243 25% 50%, + #df8640 50% 75%, + #c24269 75% 100% + ); + height: 12px; +} +.survival .line { + background: linear-gradient( + to right, + #c24269 0 25%, + #df8640 25% 50%, + #a8c243 50% 75%, + #42a77e 75% 100% + ); +} +.unavailable .line { + background: repeating-linear-gradient( + to right, + #d9dfe2 0, + #d9dfe2 calc(25% - 1px), + #fff calc(25% - 1px), + #fff 25% + ); +} +.interval { + border-left: 2px solid $ink; + border-right: 2px solid $ink; + height: 8px; + min-width: 2px; + position: absolute; + top: 32px; + &::before { + background: $ink; + content: ''; + height: 2px; + left: 0; + position: absolute; + right: 0; + top: 3px; + } +} +.marker { + background: $ink; + bottom: -2px; + height: 20px; + position: absolute; + transform: translateX(-50%); + width: 3px; +} +.value { + color: $ink; + font-size: 13px; + position: absolute; + top: 1px; + transform: translateX(-50%); + white-space: nowrap; +} +.ticks { + display: flex; + font-size: 12px; + justify-content: space-between; + margin-top: 3px; +} +.foot { + font-size: 12px; +} diff --git a/src/app/paciente/risk-scales.spec.ts b/src/app/paciente/risk-scales.spec.ts new file mode 100644 index 0000000..2ec5a75 --- /dev/null +++ b/src/app/paciente/risk-scales.spec.ts @@ -0,0 +1,125 @@ +import { curveFigure } from './risk-curve'; +import { group, hpvApart } from './record-groups'; +import { horizon, riskGroups, survivalGroups, titleParts } from './risk-scales'; +import { parseSeries, seriesName } from './risk-series'; +import { insufficientText, sortUndrawn } from './survival'; + +describe('risk scales', () => { + it('take a horizon only as published, zero included, and an interval only when whole', () => { + const p = [ + { years: 0, p: 0 }, + { years: 5, p: 0.2, low: 0.3, high: 0.1 }, + { years: 3, p: 1.4 }, + ]; + expect(horizon(p, 0)).toEqual({ years: 0, p: 0 }); + expect(horizon(p, 5)).toEqual({ years: 5, p: 0.2 }); + expect(horizon(p, 3)).toBeUndefined(); + expect(horizon(p, 1)).toBeUndefined(); + }); + it('name a model by its outcome and scenario, and say both horizons even when none is known', () => { + expect(titleParts('Riesgo de CIN3+ en precolposcopía v2')).toEqual({ + title: 'Probabilidad de CIN3+', + scenario: 'precolposcopía', + }); + expect(riskGroups([])[0].scales.map((s) => s.risk)).toEqual([undefined, undefined]); + }); + it('turn survival models (mortality) into S(t), the interval turned too', () => { + const [g] = survivalGroups([ + { + text: 'Supervivencia v1', + index: '2026-01-01', + predictions: [{ years: 5, p: 0.1, low: 0.05, high: 0.2 }], + }, + ]); + const risk = g.scales[0].risk!; + expect([risk.p, risk.low, risk.high].map((v) => +v!.toFixed(2))).toEqual([0.9, 0.8, 0.95]); + }); +}); + +describe('risk curves', () => { + it('band an interval published at two horizons and bar one published at one', () => { + const banded = curveFigure( + [ + { + text: 'Riesgo de CIN3+ v1', + index: '2026-01-01', + predictions: [ + { years: 0, p: 0.1, low: 0.05, high: 0.2 }, + { years: 5, p: 0.2, low: 0.1, high: 0.3 }, + ], + }, + ], + 0.3, + ); + expect(banded.data.map((t) => t.name)).toEqual([ + undefined, + 'IC 95 % Probabilidad de CIN3+', + 'Probabilidad de CIN3+', + ]); + const point = curveFigure( + [{ text: 'x', index: '', predictions: [{ years: 5, p: 0.2, low: 0.1, high: 0.3 }] }], + 0.3, + ); + expect(point.data).toHaveLength(1); + expect((point.data[0] as { error_y?: object }).error_y).toBeTruthy(); + }); +}); + +describe('series and report gaps', () => { + it('read a series as published and name the platform own as the hospital', () => { + const [s] = parseSeries({ + resourceType: 'Parameters', + parameter: [ + { + name: 'series', + part: [ + { name: 'id', valueString: 'institutional-CIN3+' }, + { name: 'source', valueString: 'Institucional' }, + { name: 'outcome', valueString: 'CIN3+' }, + { + name: 'point', + part: [ + { name: 'years', valueInteger: 5 }, + { name: 'probability', valueDecimal: 0.04 }, + ], + }, + ], + }, + ], + }); + expect(seriesName(s)).toBe('ISSSTELEON, CIN3+'); + expect(s.points).toEqual([{ years: 5, p: 0.04, low: undefined, high: undefined }]); + }); + it('tell a scenario short of deaths from one the report does not mention', () => { + const report = { + escenarios_sin_curvas: [{ escenario: 'A', n: 12, fallecidos: 1 }], + min_fallecidos_escenario: 5, + }; + const { insufficient, missing } = sortUndrawn(report, ['A', 'B']); + expect(missing).toEqual(['B']); + expect(insufficientText(insufficient[0])).toBe( + 'Datos insuficientes para trazar la curva (n = 12, fallecidos = 1; mínimo requerido: 5 fallecidos).', + ); + }); + it('keep the form apart from the study: antecedents, results, findings and HPV', () => { + const fact = (field: string, title: string, value: string) => ({ + study: 'cervical_cytology', + field, + title, + value, + }); + const { hpv, rest } = hpvApart([ + fact('hpv', 'VPH', 'positivo'), + fact('screening_history', 'Detección', 'Subsecuente'), + fact('result', 'Resultado', 'LIEBG'), + fact('finding_trichomonas', 'Hallazgo: tricomonas', 'positivo'), + fact('findings', 'Texto', 'inflamación'), + ]); + expect(hpv.map((f) => f.field)).toEqual(['hpv']); + expect(group(rest)).toEqual({ + antecedents: { screening_history: 'Subsecuente' }, + results: ['Resultado: LIEBG'], + findings: ['Texto del informe: inflamación', 'Tricomonas'], + }); + }); +}); diff --git a/src/app/paciente/risk-scales.ts b/src/app/paciente/risk-scales.ts index 2944331..9747c34 100644 --- a/src/app/paciente/risk-scales.ts +++ b/src/app/paciente/risk-scales.ts @@ -1,7 +1,7 @@ import { DecimalPipe } from '@angular/common'; import { Component, input } from '@angular/core'; -interface Prediction { +export interface Prediction { years: number; p: number; low?: number; @@ -11,65 +11,136 @@ export interface RiskScale { label: string; risk?: Prediction; } +/** One model's scales: its title, scenario and index, what it was fed and who scored her. */ +export interface RiskGroup { + title?: string; + scenario?: string; + index?: string; + /** S(t): its scale reads the other way (high is good) */ + survival?: boolean; + inputs?: Record; + model?: string; + evaluated?: string; + scales: RiskScale[]; +} +interface Scored { + text: string; + index: string; + predictions: Prediction[]; + inputs?: Record; + evaluated?: string; + scenarios?: string[]; +} -/** Each model's risk at its index visit and at five years; none where it gives no such horizon. */ -export function riskScales(models: { text: string; predictions: Prediction[] }[]): RiskScale[] { +/** "Riesgo" as "probabilidad", its capital kept. */ +const probability = (text: string) => + text.replace(/riesgo/gi, (w) => (w[0] === 'R' ? 'Probabilidad' : 'probabilidad')); +const unit = (n?: number): n is number => typeof n === 'number' && n >= 0 && n <= 1; +const years = (n: number) => `${n} ${n === 1 ? 'año' : 'años'}`; + +/** A model's prediction at one horizon when it is a probability: zero is a value, a missing + * horizon or a value outside 0–1 is none, and an interval stands only when it is whole. */ +export function horizon(predictions: Prediction[], at: number): Prediction | undefined { + const found = predictions.find((p) => p.years === at); + if (!found || !unit(found.p)) return undefined; + const whole = unit(found.low) && unit(found.high) && found.low <= found.high; + return whole ? found : { years: at, p: found.p }; +} + +/** Each model's probability at its index visit and at five years (the record's PDF). */ +export function riskScales(models: Scored[]): RiskScale[] { return models.flatMap((m) => - [0, 5].map((years) => ({ - label: `${m.text}, riesgo ${years ? 'a 5 años' : 'inmediato'}`, - risk: m.predictions.find((p) => p.years === years), + [0, 5].map((at) => ({ + label: `${probability(m.text)}, probabilidad ${at ? 'a 5 años' : 'inmediata'}`, + risk: horizon(m.predictions, at), })), ); } +/** "Riesgo de X en v1" as its outcome and its scenario. */ +export function titleParts(text: string): { title: string; scenario?: string } { + const [, title, scenario] = /^(.*?)(?: en (.+?))?(?: v\d+)?$/.exec(text)!; + return { title: probability(title), scenario }; +} + +const HORIZONS: [number, string][] = [ + [0, 'Probabilidad inmediata (al índice)'], + [5, 'Probabilidad a 5 años'], +]; + +/** Both horizons of every risk model; with no model, both horizons unavailable. */ +export function riskGroups(models: Scored[]): RiskGroup[] { + const scales = (p: Prediction[]) => + HORIZONS.map(([at, label]) => ({ label, risk: horizon(p, at) })); + if (!models.length) return [{ scales: scales([]) }]; + return models.map((m) => ({ + ...titleParts(m.text), + index: m.index, + inputs: m.inputs, + model: m.text, + evaluated: m.evaluated, + scales: scales(m.predictions), + })); +} + +/** Survival models publish mortality: their scales are its complement, S(t), interval swapped. */ +export function survivalGroups(models: Scored[]): RiskGroup[] { + const complement = (n?: number) => (n === undefined ? undefined : 1 - n); + return models + .map((m) => ({ + title: 'Supervivencia', + index: m.index, + survival: true, + inputs: m.inputs, + model: m.text, + evaluated: m.evaluated, + scenario: m.scenarios?.join(' · '), + scales: m.predictions + .map((p) => horizon(m.predictions, p.years)) + .filter((v) => !!v) + .map((v) => ({ + label: `Supervivencia a ${years(v.years)}`, + risk: { years: v.years, p: 1 - v.p, low: complement(v.high), high: complement(v.low) }, + })), + })) + .filter((g) => g.scales.length); +} + +const INPUTS: Record = { + age_group: 'Edad al diagnóstico', + cytology: 'Citología', + bethesda: 'Citología', + hpv: 'VPH', + hpv_positive: 'VPH', + hpv_16_18: 'VPH 16/18', + hpv_16: 'VPH 16', + hpv_18: 'VPH 18', + referral_grade: 'Citología de referencia', +}; + +/** A model input's value as the screens say it. */ +export function inputValue(name: string, value: unknown): string { + if (value === null || value === undefined) return 'No documentado'; + if (name === 'referral_grade' && (value === 'high' || value === 'low')) + return value === 'high' ? 'Alto grado' : 'Bajo grado'; + if (name.startsWith('hpv')) { + if (value === 1 || value === true || value === 'positive') return 'Positivo'; + if (value === 0 || value === false || value === 'negative') return 'Negativo'; + } + return String(value); +} + +/** Scales of 0 to 100 % in four equal parts (descriptive, not clinical thresholds), the + * probability marked with its interval; one with no prediction is grey and says so. */ @Component({ selector: 'app-risk-scales', imports: [DecimalPipe], - template: ` - @for (s of scales(); track s.label) { -
- {{ s.label }} -
- @if (s.risk; as r) { - - } -
- @if (s.risk; as r) { - {{ r.p * 100 | number: '1.1-2' }} % - @if (r.low !== undefined) { - - IC 95 %: {{ r.low * 100 | number: '1.1-2' }}–{{ r.high! * 100 | number: '1.1-2' }} % - - } - } @else { - No disponible - } -
- } - `, - styles: ` - .scale { - align-items: center; - display: flex; - flex-wrap: wrap; - gap: 12px; - margin-bottom: 8px; - } - .line { - background: linear-gradient(to right, #a8c243, #c24269); - flex: 1 1 200px; - height: 8px; - position: relative; - } - .mark { - background: #333; - height: 16px; - position: absolute; - top: -4px; - width: 3px; - } - `, + templateUrl: './risk-scales.html', + styleUrl: './risk-scales.scss', }) export class RiskScales { - readonly scales = input.required(); + readonly groups = input.required(); + protected readonly entries = (o?: Record) => Object.entries(o ?? {}); + protected readonly inputName = (name: string) => INPUTS[name] ?? name; + protected readonly inputValue = inputValue; } diff --git a/src/app/paciente/risk-series.ts b/src/app/paciente/risk-series.ts new file mode 100644 index 0000000..c063982 --- /dev/null +++ b/src/app/paciente/risk-series.ts @@ -0,0 +1,87 @@ +import { Component, computed, input } from '@angular/core'; +import type { Parameters, ParametersParameter } from 'fhir/r4'; +import { CurveChooser } from './curve-chooser'; +import { curveFigure } from './risk-curve'; +import type { Prediction } from './risk-scales'; + +/** One series of `$risk-series`: a source, an outcome, what it assumes and its points. */ +export interface Series { + id: string; + source: string; + outcome: string; + assumptions: string[]; + points: Prediction[]; +} + +const OUTCOMES: Record = { 'CIN2+': 'LIEAG+', 'CIN3+': 'CIN3+', cancer: 'Cáncer' }; +/** Drawn until the user says otherwise: the platform's own and the NCI master table's CIN2+/3+. */ +const SHOWN = new Set(['nci-master-CIN2+', 'nci-master-CIN3+']); + +/** "ISSSTELEON, CIN3+": the platform's own series are the hospital's. */ +export const seriesName = (s: Series) => + `${s.source === 'Institucional' ? 'ISSSTELEON' : s.source}, ${OUTCOMES[s.outcome] ?? s.outcome}`; + +type Part = ParametersParameter; +const all = (of: Part[] | undefined, name: string) => (of ?? []).filter((p) => p.name === name); +const one = (of: Part[] | undefined, name: string) => all(of, name)[0]; + +/** The answer's series; a value it leaves out stays out. */ +export function parseSeries(answer: Parameters): Series[] { + return all(answer.parameter, 'series').map(({ part }) => ({ + id: one(part, 'id')?.valueString ?? '', + source: one(part, 'source')?.valueString ?? '', + outcome: one(part, 'outcome')?.valueString ?? '', + assumptions: all(part, 'assumption').map((a) => a.valueString ?? ''), + points: all(part, 'point').map(({ part: at }) => ({ + years: one(at, 'years')?.valueInteger ?? 0, + p: one(at, 'probability')?.valueDecimal ?? 0, + low: one(at, 'low')?.valueDecimal, + high: one(at, 'high')?.valueDecimal, + })), + })); +} + +/** Her series side by side, to choose from; no difference between them is computed. */ +@Component({ + selector: 'app-risk-series', + imports: [CurveChooser], + template: ` + @if (drawn().length) { + + } @else { +

No disponible: datos insuficientes.

+ } + `, +}) +export class RiskSeries { + readonly series = input.required(); + protected readonly drawn = computed(() => this.series().filter((s) => s.points.length)); + protected readonly choices = computed(() => + this.drawn().map((s) => ({ + id: s.id, + name: seriesName(s), + on: s.source === 'Institucional' || SHOWN.has(s.id), + })), + ); + private chosen(ids: Set) { + return this.drawn().filter((s) => ids.has(s.id)); + } + /** what the chosen series assume, each said once */ + protected readonly assumptions = (ids: Set) => [ + ...new Set(this.chosen(ids).flatMap((s) => s.assumptions)), + ]; + protected readonly draw = (ids: Set) => { + const shown = this.chosen(ids).map((s) => ({ + text: seriesName(s), + index: '', + predictions: s.points, + })); + const figure = curveFigure( + shown, + Math.max(0, ...shown.flatMap((m) => m.predictions.map((p) => p.high ?? p.p))), + ); + // the sources share no index date: the axis says only the horizon + figure.layout!.xaxis!.title = { text: 'Horizonte (años)' }; + return figure; + }; +} diff --git a/src/app/paciente/stages.scss b/src/app/paciente/stages.scss new file mode 100644 index 0000000..8160189 --- /dev/null +++ b/src/app/paciente/stages.scss @@ -0,0 +1,116 @@ +$line: #667b8a; + +:host { + display: block; +} +ol { + display: flex; + gap: 6px; + list-style: none; + margin: 0; + padding: 0; +} +li { + position: relative; +} +// recorded: solid green; inferred: double blue; pending: pale; ambiguous: double rose; +// no data: an empty dashed circle +.node { + background: #fff; + border: 2px dashed $line; + border-radius: 50%; + box-sizing: border-box; + display: block; + height: 12px; + position: relative; + width: 12px; + z-index: 1; +} +.recorded { + background: #387b66; + border-style: solid; +} +.inferred { + background: #4269a0; + border-style: double; +} +.pending { + background: #fff1c9; + border-style: solid; +} +.ambiguous { + border-color: #a84460; + border-style: double; +} +// the detail: a column per stage across the width, the nodes joined by a line +ol.detail { + background: #fff; + border: 1px solid #dce3e7; + border-radius: 8px; + gap: 0; + padding: 18px 12px; + li { + flex: 1; + min-width: 0; + text-align: center; + } + li:not(:last-child)::after { + border-top: 1px solid $line; + content: ''; + left: calc(50% + 9px); + position: absolute; + right: calc(-50% + 9px); + top: 9px; + } + .node { + height: 18px; + margin: 0 auto; + width: 18px; + } +} +.info { + color: #60717d; + display: flex; + flex-direction: column; + font-size: 12px; + gap: 3px; + overflow-wrap: anywhere; + padding: 8px 4px 0; + strong { + color: #243d4b; + } +} +.interval { + color: #365b69; + font-weight: 600; +} +.origin { + font-style: italic; +} +// narrow screens: the stages one under another +@media (max-width: 700px) { + ol.detail { + display: block; + li { + display: flex; + gap: 12px; + padding-bottom: 10px; + text-align: left; + } + li:not(:last-child)::after { + border-left: 1px solid $line; + border-top: 0; + bottom: 0; + left: 9px; + right: auto; + top: 18px; + } + .node { + flex: none; + margin: 0; + } + } + .info { + padding: 0; + } +} diff --git a/src/app/paciente/stages.spec.ts b/src/app/paciente/stages.spec.ts index bcadb58..a702706 100644 --- a/src/app/paciente/stages.spec.ts +++ b/src/app/paciente/stages.spec.ts @@ -1,5 +1,5 @@ import { EXT } from '../fhir'; -import { route } from './stages'; +import { interval, route } from './stages'; const ext = (name: string, value: object) => ({ url: EXT + name, ...value }); const cytology = (...extension: object[]): any => ({ effectiveDateTime: '2026-01-10', extension }); @@ -23,4 +23,31 @@ describe('the route of a cytology', () => { expect(states('2026-02-15')[3]).toBe('pending'); expect(states('2026-01-15').slice(2)).toEqual(['unknown', 'unknown', 'unknown']); }); + it('takes the states and sources the backend publishes, and the day a pending biopsy was asked', () => { + const report = cytology( + ext('colposcopy-date', { valueDate: '2026-02-01' }), + ext('stage-colposcopy-state', { valueCode: 'ambiguous' }), + ext('stage-colposcopy-source', { valueCode: 'clinical-note' }), + ext('stage-colposcopy-source', { valueCode: 'not-a-source' }), + ext('biopsy-request-date', { valueDate: '2026-02-03' }), + ext('stage-biopsy-state', { valueCode: 'pending' }), + ext('stage-biopsy-source', { valueCode: 'biopsy-order' }), + ); + const [, , colposcopy, biopsy] = route(report, '2026-12-31'); + expect(colposcopy).toMatchObject({ state: 'ambiguous', sources: ['clinical-note'] }); + expect(biopsy).toEqual({ + label: 'Reporte de biopsia', + state: 'pending', + requested: '2026-02-03', + sources: ['biopsy-order'], + }); + }); +}); + +describe('days between stages', () => { + it('say a missing day as a dash, never zero, and mark an inferred one', () => { + expect(interval('2026-01-01', undefined)).toBe('—'); + expect(interval('2026-01-01', '2026-01-02')).toBe('1 día'); + expect(interval('2026-01-01', '2026-01-11', true)).toBe('10 días (inferido)'); + }); }); diff --git a/src/app/paciente/stages.ts b/src/app/paciente/stages.ts index 5c7ce4c..a450658 100644 --- a/src/app/paciente/stages.ts +++ b/src/app/paciente/stages.ts @@ -1,39 +1,66 @@ import { Component, computed, input } from '@angular/core'; import type { DiagnosticReport } from 'fhir/r4'; -import { ext } from '../fhir'; +import { EXT, ext } from '../fhir'; -/** A step of the route that a cytology starts. A day with no state is unknown. */ +/** A step of the route a cytology starts. A stage with no day is unknown; `ambiguous` is a day + * the backend does not stand behind. */ export interface Stage { label: string; day?: string; - state: 'recorded' | 'inferred' | 'pending' | 'unknown'; + state: 'recorded' | 'inferred' | 'pending' | 'ambiguous' | 'unknown'; + /** where its day comes from, as the backend says it (`SOURCES`) */ + sources?: string[]; + /** a stage with no day yet: the day its biopsy was requested */ + requested?: string; } +export const SOURCES: Record = { + 'cytology-form': 'Formulario de citología', + 'clinical-note': 'Nota clínica', + 'biopsy-order': 'Orden de biopsia', + 'biopsy-record': 'Registro de la biopsia (nombra la citología)', + 'date-association': 'Asociación por fechas', +}; export const STATES: Record = { recorded: 'Registrada', inferred: 'Inferida por fechas', pending: 'Pendiente', + ambiguous: 'Ambigua', unknown: 'Sin dato', }; +const SAID: Stage['state'][] = ['recorded', 'inferred', 'ambiguous']; +const FORM = ['cytology-form']; -/** The route of one cytology, as its report says it, by `cutoff`. */ +/** The route of one cytology by `cutoff`. Each later stage's state and sources are the backend's + * (`stage--state`, `stage--source`); a report without them is read from its days and + * its biopsy link. */ export function route(cytology: DiagnosticReport | undefined, cutoff: string): Stage[] { const by = (day?: string) => (day && day.slice(0, 10) <= cutoff ? day.slice(0, 10) : undefined); const at = (name: string) => by(ext(cytology, name)?.valueDate); - const step = (label: string, day: string | undefined, known: Stage['state']): Stage => ({ - label, - day, - state: day ? known : 'unknown', - }); - const linked = ext(cytology, 'biopsy-link')?.valueCode === 'recorded' ? 'recorded' : 'inferred'; - const biopsy = step('Reporte de biopsia', at('biopsy-date'), linked); - if (!biopsy.day && at('biopsy-request-date')) biopsy.state = 'pending'; + const said = (k: string) => ext(cytology, `stage-${k}-state`)?.valueCode as Stage['state']; + const sources = (k: string) => + (cytology?.extension ?? []) + .filter((e) => e.url === `${EXT}stage-${k}-source` && e.valueCode! in SOURCES) + .map((e) => e.valueCode!); + const stage = (label: string, day: string | undefined, state: Stage['state'], from: string[]) => + day ? { label, day, state, sources: from } : { label, state: 'unknown' as const }; + const later = (label: string, k: string, otherwise: Stage['state']): Stage => + stage(label, at(`${k}-date`), SAID.includes(said(k)) ? said(k) : otherwise, sources(k)); + const linked = ext(cytology, 'biopsy-link')?.valueCode === 'recorded'; + const biopsy = later('Reporte de biopsia', 'biopsy', linked ? 'recorded' : 'inferred'); + const requested = at('biopsy-request-date'); + // asked by the cut-off and unreported by it: pending, as the backend says, or reported after + // the cut-off, or with no states published at all + const published = ['colposcopy', 'biopsy', 'diagnosis'].some(said); + const reportedLater = !!ext(cytology, 'biopsy-date')?.valueDate; + if (!biopsy.day && requested && (reportedLater || said('biopsy') === 'pending' || !published)) + Object.assign(biopsy, { state: 'pending', requested, sources: sources('biopsy') }); return [ - step('Toma de muestra', by(cytology?.effectiveDateTime), 'recorded'), - step('Resultado de citología', at('report-date'), 'recorded'), - step('Colposcopía', at('colposcopy-date'), 'inferred'), + stage('Toma de muestra', by(cytology?.effectiveDateTime), 'recorded', FORM), + stage('Resultado de citología', at('report-date'), 'recorded', FORM), + later('Colposcopía', 'colposcopy', 'inferred'), biopsy, - step('Diagnóstico', at('diagnosis-date'), 'inferred'), + later('Diagnóstico', 'diagnosis', 'inferred'), ]; } @@ -43,79 +70,67 @@ export function between(from?: string, to?: string): number | undefined { return Math.round((Date.parse(to) - Date.parse(from)) / 86_400_000); } -/** The stages as a line of dots; `detail` adds each one's state, day and days elapsed. */ +/** Days between two stages as text: "—" for a missing day (never zero), "(inferido)" when it + * rests on a stage inferred from dates. */ +export function interval(from?: string, to?: string, inferred = false): string { + const days = between(from, to); + if (days === undefined) return '—'; + return `${days} ${days === 1 ? 'día' : 'días'}${inferred ? ' (inferido)' : ''}`; +} + +/** The stages as nodes on a line; `detail` adds each one's state, day, source and the days since + * the stage before and since the sample. */ @Component({ selector: 'app-stages', template: ` -
    +
      @for (s of shown(); track s.label) { -
    1. - +
    2. + @if (detail()) { - {{ s.label }} - {{ s.text }} - @if (s.day) { - {{ s.day }} - } - @if (s.previous !== undefined) { - {{ s.previous }} días desde la etapa anterior - } - @if (s.sample !== undefined) { - {{ s.sample }} días desde la toma - } +
      + {{ s.label }} + {{ s.text }} + {{ + s.day ?? (s.requested ? 'Solicitada el ' + s.requested : 'Sin fecha') + }} + @if (s.origin) { + Procedencia: {{ s.origin }} + } + Desde anterior: {{ s.previous }} + Desde toma: {{ s.sample }} +
      }
    3. }
    `, - styles: ` - ol { - display: flex; - gap: 6px; - list-style: none; - margin: 0; - padding: 0; - } - ol.detail { - flex-wrap: wrap; - gap: 16px; - } - .detail li { - display: flex; - flex: 1 1 120px; - flex-direction: column; - font-size: 0.85rem; - } - .dot { - border: 2px solid #9aa3ab; - border-radius: 50%; - display: inline-block; - height: 12px; - width: 12px; - } - .recorded { - background: #6a8000; - border-color: #6a8000; - } - .inferred { - background: #a8c243; - border-color: #6a8000; - } - .pending { - border-color: #c24269; - } - `, + styleUrl: './stages.scss', }) export class Stages { readonly stages = input.required(); readonly detail = input(false); protected readonly shown = computed(() => { const all = this.stages(); + const inferred = (s?: Stage) => s?.state === 'inferred'; + // no interval rests on an ambiguous day + const day = (s?: Stage) => (s?.state === 'ambiguous' ? undefined : s?.day); return all.map((s, i) => ({ ...s, text: STATES[s.state], - previous: i ? between(all[i - 1].day, s.day) : undefined, - sample: i > 1 ? between(all[0].day, s.day) : undefined, + title: `${s.label}: ${STATES[s.state]}`, + // every sample's day comes from its form: only another source is said + origin: (s.sources ?? []) + .filter((c) => c !== 'cytology-form') + .map((c) => SOURCES[c]) + .join(' · '), + previous: i ? interval(day(all[i - 1]), day(s), inferred(s) || inferred(all[i - 1])) : '—', + sample: interval(day(all[0]), day(s), inferred(s)), })); }); + protected readonly summary = computed(() => + this.shown() + .map((s) => s.title) + .join('; '), + ); } diff --git a/src/app/paciente/survival-card.html b/src/app/paciente/survival-card.html new file mode 100644 index 0000000..ae1502e --- /dev/null +++ b/src/app/paciente/survival-card.html @@ -0,0 +1,110 @@ + + + {{ cacu() ? 'Supervivencia' : 'Riesgo de muerte' }} + + + @if (cacu()) { + + @for (g of scales(); track $index) { +
    + Modelos y valores + + + + + + + + + + + + @for (v of g.scales; track v.label) { + @if (v.risk; as r) { + + + + + + + + } + } + +
    ModeloFecha índiceHorizonteSupervivenciaIC 95 %
    {{ $first ? g.model : '' }}{{ $first ? g.index : '' }}{{ r.years }} {{ r.years === 1 ? 'año' : 'años' }}{{ r.p * 100 | number: '1.1-2' }} % + @if (r.low !== undefined && r.high !== undefined) { + {{ r.low * 100 | number: '1.1-2' }}–{{ r.high * 100 | number: '1.1-2' }} % + } @else { + — + } +
    +
    + } +

    Curva de supervivencia

    + @if (combination.isLoading()) { + + } @else if (combination.error()) { + + } @else if (combination.value(); as c) { + @if (c.curves) { +

    + Ajustes sobre las pacientes con sus mismos valores (Kaplan-Meier con IC 95 % Greenwood; + n = {{ c.n }}, fallecidos = {{ c.deaths }}). +

    + + } @else { +

    {{ c.missing }}

    + } + } @else { +

    + No disponible: la estimación no conserva los valores usados para elegir la curva. +

    + } + } @else { +

    Análisis de supervivencia

    + @if (loading()) { + + } @else if (analysis(); as s) { +

    Escenario clínico de la paciente

    +
      + @for (name of s.scenarios; track name) { +
    • {{ name }}
    • + } +
    + @if (s.methods.length) { +
    + Métodos +
      + @for (name of s.methods; track name) { +
    • {{ name }}
    • + } +
    +
    + } + @for (f of s.figures; track f.title) { +

    {{ f.title }}

    + + } + @for (name of s.unavailable; track name) { +

    {{ name }}

    +

    No disponible: datos insuficientes.

    + } + @for (u of s.insufficient; track u.name) { +

    {{ u.name }}

    +

    {{ insufficientText(u) }}

    + } + @for (name of s.missing; track name) { +

    {{ name }}

    +

    + Sin información de este escenario en el informe del modelo. +

    + } + + } @else if (failed()) { + + } @else { +

    No disponible: datos insuficientes.

    + } + } +
    +
    diff --git a/src/app/paciente/survival-card.ts b/src/app/paciente/survival-card.ts new file mode 100644 index 0000000..348bfec --- /dev/null +++ b/src/app/paciente/survival-card.ts @@ -0,0 +1,61 @@ +import { DecimalPipe } from '@angular/common'; +import { Component, computed, inject, input, resource } from '@angular/core'; +import { MatCardModule } from '@angular/material/card'; +import { Api } from '../api/api'; +import { Loading } from '../loading'; +import { Plot } from '../plot'; +import { Analysis, combination } from './analysis'; +import { CurveChooser } from './curve-chooser'; +import { Factores } from './factores'; +import type { Model } from './record'; +import { RiskScales, survivalGroups } from './risk-scales'; +import { insufficientText } from './survival'; + +/** Her survival. CaCu: her S(t) at each horizon, its values and the Kaplan-Meier of the patients + * who share her values; elsewhere, the curves of her clinical scenarios. */ +@Component({ + selector: 'app-survival-card', + imports: [CurveChooser, DecimalPipe, Factores, Loading, MatCardModule, Plot, RiskScales], + templateUrl: './survival-card.html', + styles: ` + mat-card-content { + overflow-x: auto; + } + .scenarios { + display: flex; + flex-wrap: wrap; + gap: 6px 8px; + list-style: none; + margin: 0 0 12px; + padding: 0; + li { + background: var(--color-action-hover, #f1f6f6); + border: 1px solid var(--color-border); + border-radius: 999px; + font-size: 13px; + padding: 2px 10px; + } + } + `, +}) +export class SurvivalCard { + private readonly api = inject(Api); + readonly domain = input.required(); + /** her survival models */ + readonly models = input.required(); + /** her scenarios' curves, as read (not CaCu) */ + readonly analysis = input(); + readonly loading = input(false); + readonly failed = input(false); + + protected readonly cacu = computed(() => this.domain() === 'cacu'); + protected readonly scales = computed(() => (this.cacu() ? survivalGroups(this.models()) : [])); + protected readonly combination = resource({ + params: () => { + const m = this.models().find((x) => x.model === 'cacu.survival' && x.version && x.inputs); + return this.cacu() && m ? { ...m, inputs: m.inputs! } : undefined; + }, + loader: ({ params }) => combination(this.api, params), + }); + protected readonly insufficientText = insufficientText; +} diff --git a/src/app/paciente/survival.ts b/src/app/paciente/survival.ts new file mode 100644 index 0000000..a301321 --- /dev/null +++ b/src/app/paciente/survival.ts @@ -0,0 +1,110 @@ +import { scenarioFigure } from '../gobernanza/figures'; +import { Figure, PALETTE } from '../plot'; + +type Report = Record | null | undefined; +const count = (v: number) => v.toLocaleString('es-MX'); + +/** The survival report's patients who share every one of her values (`km_combinaciones`). */ +export interface Combination { + valores: Record; + n: number; + fallecidos: number; + km?: { months: number[]; S: number[]; low: number[]; high: number[] }; + /** the other fits: a report from before them has the Kaplan-Meier only */ + weibull?: { t: number[]; S: number[] }; + weibull_fractional?: { t: number[]; S: number[] }; + points?: { COMB: { S: number[]; low?: number[]; high?: number[] } }; + horizons_months?: number[]; +} + +/** The entry with exactly her values (a missing one is the report's "NA"), never a partial one. */ +export function combinationOf(report: Report, inputs: Record) { + const all = report?.['km_combinaciones']; + const mine = Object.keys(inputs); + return (Array.isArray(all) ? (all as Combination[]) : []).find((c) => { + const keys = Object.keys(c.valores); + return ( + keys.length === mine.length && + keys.every((k) => k in inputs && c.valores[k] === String(inputs[k] ?? 'NA')) + ); + }); +} + +/** Why she has no curve: a model version that publishes none, or too few deaths. */ +export function noCurveText(report: Report, found: Combination | undefined): string { + if (!Array.isArray(report?.['km_combinaciones'])) + return 'No disponible: la versión del modelo que la evaluó no publica esta curva.'; + const minimum = report['min_fallecidos_escenario']; + const least = typeof minimum === 'number' ? `; mínimo requerido: ${minimum} fallecidos` : ''; + return `No disponible: datos insuficientes para su combinación de valores (n = ${found?.n ?? 0}, fallecidos = ${found?.fallecidos ?? 0}${least}).`; +} + +/** Her combination's fits as a scenario's are drawn; the Kaplan-Meier alone when that is all. */ +export function survivalFigure(c: Combination): Figure { + if (c.weibull && c.weibull_fractional && c.points && c.horizons_months) + return scenarioFigure('', c, c.horizons_months, 'Supervivencia S(t)').figure; + const km = c.km!; + const line = (y: number[], more: object) => ({ + type: 'scatter' as const, + mode: 'lines' as const, + x: km.months, + y, + line: { shape: 'hv' as const, color: PALETTE[0], width: 0 }, + ...more, + }); + return { + data: [ + line(km.low, { showlegend: false, hoverinfo: 'skip' }), + line(km.high, { name: 'IC 95 %', fill: 'tonexty', fillcolor: 'rgba(23, 50, 77, 0.15)' }), + line(km.S, { name: 'Kaplan-Meier', line: { shape: 'hv', color: PALETTE[0], width: 2 } }), + ], + layout: { + xaxis: { title: { text: 'Meses desde el índice' } }, + yaxis: { title: { text: 'Supervivencia S(t)' }, range: [0, 1.02], tickformat: '.0%' }, + }, + }; +} + +/** A scenario the report lists as too short of deaths, with the numbers it gives. */ +export interface Insufficient { + name: string; + n?: number | null; + deaths?: number | null; + minimum?: number; +} + +/** Her scenarios without a curve: those the report lists as short of deaths, and those it does not + * mention at all. */ +export function sortUndrawn(report: Report, undrawn: string[]) { + const listed = report?.['escenarios_sin_curvas']; + const short = (Array.isArray(listed) ? listed : []) as { + escenario?: string; + n?: number | null; + fallecidos?: number | null; + }[]; + const least = report?.['min_fallecidos_escenario']; + const minimum = typeof least === 'number' ? least : undefined; + const insufficient: Insufficient[] = []; + const missing: string[] = []; + for (const name of undrawn) { + const s = short.find((x) => x.escenario === name); + if (s) insufficient.push({ name, n: s.n, deaths: s.fallecidos, minimum }); + else missing.push(name); + } + return { insufficient, missing }; +} + +/** The report's numbers for such a scenario; one it leaves out is left out. */ +export function insufficientText(u: Insufficient): string { + const counts = [ + typeof u.n === 'number' ? `n = ${count(u.n)}` : '', + typeof u.deaths === 'number' ? `fallecidos = ${count(u.deaths)}` : '', + ] + .filter(Boolean) + .join(', '); + const details = [ + counts, + u.minimum === undefined ? '' : `mínimo requerido: ${count(u.minimum)} fallecidos`, + ].filter(Boolean); + return `Datos insuficientes para trazar la curva${details.length ? ` (${details.join('; ')})` : ''}.`; +} diff --git a/src/app/paciente/tea-record.html b/src/app/paciente/tea-record.html new file mode 100644 index 0000000..d509db8 --- /dev/null +++ b/src/app/paciente/tea-record.html @@ -0,0 +1,193 @@ + + ADOS-2 + + @if (ados2(); as a) { +

    Puntajes por reactivo · {{ a.date }}

    + +

    + @for (t of a.totals; track t.label) { + {{ t.label }}: {{ t.value }} + } +

    + } @else { +

    Sin evaluación ADOS-2.

    + } +
    +
    + + + EEG + + @if (eeg.isLoading()) { + + } @else if (eeg.value()?.study; as st) { +

    Calidad del EEG

    +

    + Estudio del {{ st.study_date }}: + {{ st.valid ? 'aceptable para el análisis' : 'no aceptable' }} + @if (st.level) { + ({{ levelNames[st.level] ?? st.level }}) + } +

    +

    Alteraciones del EEG

    + @if (!st.valid) { +

    EEG no aceptable: no se compara con la norma por edad.

    + } @else if (!scored()) { +

    Sin curva por edad en producción para este EEG.

    + } @else if (alterations().length) { + + + + + + + + + + + + + @for (m of alterations(); track m.code) { + + + + + + + + + } + +
    MétricaValorNorma por edad (P5–P95)MedianaDesviación (z)Detalle
    + + {{ m.value | number: '1.0-3' }}{{ m.p5 | number: '1.0-3' }} – {{ m.p95 | number: '1.0-3' }}{{ m.median | number: '1.0-3' }}{{ m.z | number: '1.1-2' }}{{ m.outside! > 0 ? 'Aumentado' : 'Disminuido' }}
    +

    Elija una alteración para ver sus zonas más afectadas.

    + @if (zoned(); as z) { +
    +

    Zonas más afectadas

    +

    + {{ metricNames[z.code] ?? z.code }} · + {{ + zonesScored() + ? 'desviación de cada zona frente a su norma por edad' + : 'valor de cada zona (sin norma por edad por zona)' + }} +

    + @if (z.electrodes.length) { + + } + @if (z.zones.length) { +
      + @for (r of zoneOrder(); track r.site) { +
    1. + {{ zoneNames[r.site] ?? r.site }} + {{ + r.z !== null && r.z !== undefined + ? 'z = ' + (r.z | number: '1.1-2') + : (r.value | number: '1.0-3') + }} +
    2. + } +
    + } @else if (!z.electrodes.length) { +

    Esta métrica no se mide por zona.

    + } +
    + } + } @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) { +

    Sin modelo de asociación en producción para este EEG.

    + } @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 pacienteResultado en 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.

    + } +
    +
    diff --git a/src/app/paciente/tea-record.scss b/src/app/paciente/tea-record.scss new file mode 100644 index 0000000..4e5543c --- /dev/null +++ b/src/app/paciente/tea-record.scss @@ -0,0 +1,46 @@ +:host { + display: grid; + gap: var(--space-4); +} + +mat-card-content { + overflow-x: auto; +} + +.totals { + display: flex; + flex-wrap: wrap; + gap: 16px; +} + +.zones { + margin-top: 12px; +} +.regions { + list-style: none; + margin: 8px 0 0; + padding: 0; + max-width: 420px; + li { + display: flex; + justify-content: space-between; + padding: 4px 8px; + border-bottom: 1px solid var(--mat-sys-outline-variant); + } + li.marked { + font-weight: 600; + color: var(--mat-sys-error); + } +} +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/tea-record.ts b/src/app/paciente/tea-record.ts new file mode 100644 index 0000000..dbdf2a3 --- /dev/null +++ b/src/app/paciente/tea-record.ts @@ -0,0 +1,143 @@ +import { Component, computed, inject, input, resource, signal } from '@angular/core'; +import { DecimalPipe } from '@angular/common'; +import { MatCardModule } from '@angular/material/card'; +import type { Observation } from 'fhir/r4'; +import { Api } from '../api/api'; +import { studies as eegStudies } from '../api/fn/eeg/studies'; +import { study as eegStudy } from '../api/fn/eeg/study'; +import type { Relation } from '../api/models/relation'; +import { + BIOMARKER_NAMES, + byDeviation, + headMap, + LEVEL_NAMES, + METRIC_NAMES, + OUTCOME_NAMES, + ZONE_NAMES, +} from '../eeg-labels'; +import { code, label } from '../fhir'; +import { name } from '../indicadores/labels'; +import { Loading } from '../loading'; +import { Figure, PALETTE, Plot } from '../plot'; + +/** A TEA patient's ADOS-2 and EEG, as her record shows them. */ +@Component({ + selector: 'app-tea-record', + imports: [DecimalPipe, Loading, MatCardModule, Plot], + templateUrl: './tea-record.html', + styleUrl: './tea-record.scss', +}) +export class TeaRecord { + private readonly api = inject(Api); + readonly id = input.required(); + readonly observations = input.required(); + protected readonly name = name; + protected readonly levelNames = LEVEL_NAMES; + + /** 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(() => { + const field = (o: Observation) => (code(o.code) ?? '').replace(/^ados2\./, ''); + const scored = this.observations().filter( + (o) => (code(o.code) ?? '').startsWith('ados2.') && o.valueQuantity?.value !== undefined, + ); + const latest = scored + .map((o) => o.effectiveDateTime ?? '') + .sort() + .at(-1); + if (latest === undefined) return undefined; + const results = scored.filter((o) => (o.effectiveDateTime ?? '') === latest); + const totals = ['social_affect_total', 'restricted_repetitive_total', 'overall_total']; + const items = results.filter((o) => !totals.includes(field(o))); + const figure: Figure = { + data: [ + { + type: 'bar', + orientation: 'h', + y: items.map((o) => label(o.code)), + x: items.map((o) => o.valueQuantity!.value!), + marker: { color: PALETTE[0] }, + hovertemplate: '%{y}: %{x}', + }, + ], + layout: { + showlegend: false, + margin: { t: 10, r: 16, b: 40, l: 16 }, + xaxis: { title: { text: 'Puntaje (0 a 3)' }, range: [0, 3], dtick: 1 }, + yaxis: { autorange: 'reversed', automargin: true, type: 'category' }, + }, + }; + return { + date: latest.slice(0, 10), + figure, + height: 60 + items.length * 22, + totals: results + .filter((o) => totals.includes(field(o))) + .map((o) => ({ label: label(o.code), value: o.valueQuantity!.value! })), + }; + }); + + /** TEA: her EEG as analysed (the latest), its quality and its metrics against the age + * curves: those outside the band are its alterations. */ + protected readonly eeg = resource({ + params: () => this.id(), + loader: async ({ params: person }) => { + const mine = (await this.api.invoke(eegStudies)) + .filter((s) => s.person_id === person && s.analysed) + .sort((a, b) => b.study_date.localeCompare(a.study_date)); + if (!mine.length) return { study: undefined, analysis: undefined }; + return { + study: mine[0], + analysis: await this.api.invoke(eegStudy, { eeg_id: mine[0].id }), + }; + }, + }); + protected readonly alterations = computed(() => + (this.eeg.value()?.analysis?.metrics ?? []).filter((m) => m.outside), + ); + protected readonly scored = computed(() => + (this.eeg.value()?.analysis?.metrics ?? []).some((m) => m.z !== null && m.z !== undefined), + ); + protected readonly shown = signal(undefined); + protected readonly metricNames = METRIC_NAMES; + protected readonly zoneNames = ZONE_NAMES; + /** "Zonas más afectadas": the alteration chosen, its zones and electrodes. */ + protected readonly zone = signal(undefined); + protected readonly zoned = computed(() => { + const m = this.alterations().find((a) => a.code === this.zone()); + return m ? { code: m.code, zones: m.zones ?? [], electrodes: m.electrodes ?? [] } : undefined; + }); + protected readonly zonesScored = computed(() => + [...(this.zoned()?.zones ?? []), ...(this.zoned()?.electrodes ?? [])].some( + (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 la asociación de la cohorte' + : 'No coincide con la asociación de la cohorte'; + } + protected readonly zoneOrder = computed(() => byDeviation(this.zoned()?.zones ?? [])); + protected readonly head = computed(() => headMap(this.zoned()?.electrodes ?? [])); +} diff --git a/src/app/plot.ts b/src/app/plot.ts index d29743b..157c386 100644 --- a/src/app/plot.ts +++ b/src/app/plot.ts @@ -75,12 +75,15 @@ const CONFIG: Partial = { export class Plot implements OnDestroy { readonly figure = input.required
    (); readonly height = input(320); + /** Plotly's buttons over the chart; a record's curves go without them */ + readonly toolbar = input(true); private readonly host = viewChild.required>('host'); constructor() { effect(() => { const { data, layout } = this.figure(); - void Plotly.react(this.host().nativeElement, withRoom(data), layoutOf(layout), CONFIG); + const config = this.toolbar() ? CONFIG : { ...CONFIG, displayModeBar: false }; + void Plotly.react(this.host().nativeElement, withRoom(data), layoutOf(layout), config); }); }