From 652fd45c291b51ebe8a0919aad901bdd27fcd96b Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Tue, 1 Dec 2026 18:24:37 -0600 Subject: [PATCH] CaCu record: the NCI reference comparison section and probability curves at the published horizons --- e2e/ficha-cacu.spec.ts | 347 +++++++++++++++++ src/app/paciente/paciente.html | 13 +- src/app/paciente/paciente.scss | 16 + src/app/paciente/paciente.ts | 84 ++--- src/app/paciente/reference-risk.spec.ts | 90 +++++ src/app/paciente/reference-risk.ts | 479 ++++++++++++++++++++++++ src/app/paciente/risk-curve.spec.ts | 100 +++++ src/app/paciente/risk-curve.ts | 126 +++++++ 8 files changed, 1209 insertions(+), 46 deletions(-) create mode 100644 src/app/paciente/reference-risk.spec.ts create mode 100644 src/app/paciente/reference-risk.ts create mode 100644 src/app/paciente/risk-curve.spec.ts create mode 100644 src/app/paciente/risk-curve.ts diff --git a/e2e/ficha-cacu.spec.ts b/e2e/ficha-cacu.spec.ts index 6f801a1..99be3f3 100644 --- a/e2e/ficha-cacu.spec.ts +++ b/e2e/ficha-cacu.spec.ts @@ -625,3 +625,350 @@ test('ficha: the PDF keeps the stages, antecedents, tests and risks', async ({ p expect(bytes.subarray(0, 4).toString()).toBe('%PDF'); expect(bytes.length).toBeGreaterThan(5_000); }); + +// ---- the NCI reference comparison (experimental) and the institutional curves --------------------- + +const REFERENCE = '**/api/cacu/fhir/Patient/*/$reference-risk*'; +const section = (page: Page) => page.locator('[data-section=referencia-nci]'); +const value = (p: any) => + p.valueCode ?? p.valueString ?? p.valueDate ?? p.valueInteger ?? p.valueDecimal ?? p.valueBoolean; + +/** The first patients' answers of the API, to find one with a given state (the data is synthetic). */ +async function referenceWhere(page: Page, status: string) { + const patients = await (await page.request.get('/api/cacu/fhir/Patient?_count=100')).json(); + for (const { resource } of patients.entry) { + const answer = await page.request.get(`/api/cacu/fhir/Patient/${resource.id}/$reference-risk`); + if (!answer.ok()) throw new Error(`the reference operation answered ${answer.status()}`); + const body = await answer.json(); + if (value(body.parameter.find((p: any) => p.name === 'status')) === status) + return { id: resource.id as string, body }; + } + throw new Error(`no patient with the state ${status}`); +} +const part = (name: string, extra: object) => ({ name, ...extra }); +const answerOf = (...parameter: object[]) => ({ resourceType: 'Parameters', parameter }); +/** A resolved answer for fixtures, with the given horizons and comparisons. */ +function fixture( + horizons: { years: number; reference?: number; comparison?: object[] }[], + more: object[] = [], +) { + return answerOf( + part('status', { valueCode: 'resolved' }), + part('experimental', { valueBoolean: true }), + part('cutoff', { valueDate: '2026-11-30' }), + part('scenario', { + part: [ + part('table', { valueCode: 'screening' }), + part('label', { valueString: 'Tamizaje' }), + part('key', { + part: [ + part('name', { valueCode: 'history' }), + part('value', { valueString: 'Cotest-negative' }), + ], + }), + ], + }), + part('source', { + part: [ + part('id', { valueString: 'fixture-table' }), + part('file', { valueString: 'fixture.xlsx' }), + ], + }), + ...more, + ...horizons.map((h) => + part('horizon', { + part: [ + part('years', { valueInteger: h.years }), + part('published', { valueBoolean: h.reference !== undefined }), + ...(h.reference !== undefined ? [part('reference', { valueDecimal: h.reference })] : []), + ...(h.comparison ?? []), + ], + }), + ), + ); +} +const comparison = (status: string, reasons: string[], extra: object[] = []) => + part('comparison', { + part: [ + part('model', { valueCode: 'fixture.model' }), + part('title', { valueString: 'Modelo de prueba' }), + part('outcome', { valueString: 'CIN3+' }), + ...extra, + part('status', { valueCode: status }), + ...reasons.map((r) => part('reason', { valueCode: r })), + ], + }); +const answerWith = (page: Page, body: object, status = 200) => + page.route(REFERENCE, (route) => + route.fulfill({ status, contentType: 'application/fhir+json', body: JSON.stringify(body) }), + ); + +test('referencia NCI: a resolved cytology shows its reference with scenario, source and no institutional model', async ({ + page, +}) => { + const { id, body } = await referenceWhere(page, 'resolved'); + await open(page, `/indicadores/cacu/pacientes/${id}`); + const box = section(page); + await expect(box).toBeVisible(); + await expect(box.locator('dd[data-status=resolved]')).toHaveText('Referencia disponible'); + await expect(box).toContainText('Tamizaje'); + await expect(box).toContainText('CIN3 o más grave (CIN3+)'); + await expect(box).toContainText('Master_NCI_Risk_Table.xlsx'); + const rows = box.locator('tbody tr'); + await expect(rows).toHaveCount(2); + await expect(rows.first()).toContainText('Inmediato (al índice)'); + await expect(rows.nth(1)).toContainText('5 años'); + // the figures are the API's: percent with two decimals, and no institutional model is made up + const expected = body.parameter + .filter((p: any) => p.name === 'horizon') + .map((h: any) => + (h.part.find((x: any) => x.name === 'reference').valueDecimal * 100).toFixed(2), + ); + for (const [i, pct] of expected.entries()) + await expect(rows.nth(i).locator('td').nth(2)).toContainText(`${pct} %`); + await expect(rows.first().locator('td').nth(1)).toContainText('No disponible'); + await expect(rows.first().locator('td').nth(3)).toContainText('No comparable'); + await expect(rows.first().locator('td').nth(3)).toContainText('Ningún modelo institucional'); + // the antecedents used are collapsed + const used = box.locator('details.used'); + expect(await used.getAttribute('open')).toBeNull(); + await used.locator('summary').click(); + await expect(used).toContainText('Fila de origen'); + await expect(used).toContainText('Citología evaluada'); + // the other risk displays of the record are still there, and the reference is below the scales + await expect(scale(page, FIVE)).toBeVisible(); + const [scales, reference] = await Promise.all([ + scale(page, FIVE).boundingBox(), + box.boundingBox(), + ]); + expect(reference!.y).toBeGreaterThan(scales!.y); + await expect( + page.locator('mat-card-title', { hasText: 'Riesgos y recomendaciones' }), + ).toBeVisible(); +}); + +test('referencia NCI: a cytology the tables cannot resolve says the state and why, with no figure', async ({ + page, +}) => { + const { id } = await referenceWhere(page, 'unverifiable_correspondence'); + await open(page, `/indicadores/cacu/pacientes/${id}`); + const box = section(page); + await expect(box.locator('dd[data-status=unverifiable_correspondence]')).toHaveText( + 'Correspondencia no verificable', + ); + await expect(box.locator('ul.why li').first()).not.toBeEmpty(); + await expect(box.locator('table')).toHaveCount(0); + await expect(box).not.toContainText('%'); +}); + +test('referencia NCI: with the feature off (404) the section is not there and the record is whole', async ({ + page, +}) => { + const { url } = await firstRecord(page); + await answerWith( + page, + { resourceType: 'OperationOutcome', issue: [{ severity: 'error', code: 'not-found' }] }, + 404, + ); + await open(page, url); + await expect(section(page)).toHaveCount(0); + await expect(scale(page, FIVE)).toBeVisible(); +}); + +test('referencia NCI (simulado): a comparison that is valid shows the difference as institutional minus reference', async ({ + page, +}) => { + const { url } = await firstRecord(page); + await answerWith( + page, + fixture([ + { + years: 5, + reference: 0.0027, + comparison: [ + comparison( + 'comparable', + [], + [ + part('institutional', { valueDecimal: 0.0127 }), + part('institutional-low', { valueDecimal: 0.005 }), + part('institutional-high', { valueDecimal: 0.02 }), + part('difference-pp', { valueDecimal: 1 }), + ], + ), + ], + }, + ]), + ); + await open(page, url); + const row = section(page).locator('tbody tr').first(); + await expect(row).toContainText('Modelo de prueba'); + await expect(row).toContainText('1.27 %'); + await expect(row).toContainText('IC 95 %: 0.50–2.00 %'); + await expect(row.locator('td').nth(2)).toContainText('0.27 %'); + await expect(row.locator('td').nth(3)).toContainText('+1.00'); + await expect(row.locator('td').nth(3)).not.toContainText('No comparable'); +}); + +test('referencia NCI (simulado): another outcome or horizon is "No comparable" with its reasons and no difference', async ({ + page, +}) => { + const { url } = await firstRecord(page); + await answerWith( + page, + fixture([ + { + years: 0, + reference: 0.0001, + comparison: [ + comparison( + 'not_comparable', + ['outcome_differs', 'horizon_not_published_by_model', 'population_not_verified'], + [part('institutional', { valueDecimal: 0.05 })], + ), + ], + }, + { years: 5, reference: 0.0027 }, + ]), + ); + await open(page, url); + const first = section(page).locator('tbody tr').first(); + await expect(first.locator('td').nth(3)).toContainText('No comparable'); + await expect(first.locator('td').nth(3)).toContainText( + 'El desenlace del modelo no es el de la tabla (CIN3+)', + ); + await expect(first.locator('td').nth(3)).toContainText( + 'no publica una predicción a este horizonte', + ); + await expect(first.locator('td').nth(3)).not.toContainText(/[+-]\d/); // no signed difference + await expect(first.locator('td').nth(1)).toContainText('5.00 %'); // the model's own risk is shown, never subtracted +}); + +test('referencia NCI (simulado): a year-one reference is a year, never the immediate risk; a blank is not zero', async ({ + page, +}) => { + const { url } = await firstRecord(page); + await answerWith(page, fixture([{ years: 1, reference: 0.0136 }, { years: 5 }])); + await open(page, url); + const rows = section(page).locator('tbody tr'); + await expect(rows.first()).toContainText('1 año'); + await expect(section(page)).not.toContainText('Inmediato'); + await expect(rows.nth(1).locator('td').nth(2)).toContainText('No publicado'); + await expect(rows.nth(1).locator('td').nth(2)).not.toContainText('0.00'); + await expect(rows.first().locator('td').nth(2)).toContainText('1.36 %'); +}); + +for (const width of [1440, 480]) { + test(`referencia NCI (simulado) at ${width} px: the section lays out cleanly beside the scales and curves`, async ({ + page, + }) => { + await page.setViewportSize({ width, height: 1000 }); + const { url } = await firstRecord(page); + await answerWith( + page, + fixture( + [ + { + years: 0, + reference: 0.0001, + comparison: [ + comparison( + 'not_comparable', + ['outcome_differs', 'population_not_verified'], + [part('institutional', { valueDecimal: 0.05 })], + ), + ], + }, + { + years: 5, + reference: 0.0027, + comparison: [ + comparison( + 'comparable', + [], + [ + part('institutional', { valueDecimal: 0.0127 }), + part('difference-pp', { valueDecimal: 1 }), + ], + ), + ], + }, + ], + [part('assumption', { valueString: 'un supuesto sin verificar' })], + ), + ); + await withRisks(page, [ + risk('a', 'Riesgo LIEAG+ v3', 'cacu.survival', '2026-06-01', [ + [1, 0.08, 0.05, 0.12], + [3, 0.21, 0.15, 0.28], + [5, 0.34, 0.26, 0.44], + ]), + risk('b', 'Riesgo cáncer v2', 'cacu.recurrence', '2026-06-01', [ + [1, 0.002, 0.001, 0.005], + [3, 0.008], + [5, 0.015, 0.008, 0.028], + ]), + ]); + await open(page, url); + await section(page).locator('details.used summary').click(); + await page.waitForTimeout(800); + expect(await layoutProblems(page)).toEqual([]); + expect( + await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1), + ).toBe(true); + }); +} + +test('curvas (simulado): one series per model at its published horizons, its band only where it has intervals, and no NCI data', async ({ + page, +}) => { + const { url } = await firstRecord(page); + await answerWith(page, fixture([{ years: 5, reference: 0.0027 }])); + await withRisks(page, [ + risk('a', 'Riesgo LIEAG+ v3', 'cacu.survival', '2026-06-01', [ + [1, 0.08, 0.05, 0.12], + [3, 0.21, 0.15, 0.28], + [5, 0.34, 0.26, 0.44], + ]), + risk('b', 'Riesgo cáncer v2', 'cacu.recurrence', '2026-06-01', [ + [1, 0.002, 0.001, 0.005], + [3, 0.008], + [5, 0.015, 0.008, 0.028], + ]), + risk('c', 'Sin intervalo v1', 'cacu.other', '2026-06-01', [ + [2, 0.1], + [4, 0.2], + ]), + risk('d', 'Un punto v1', 'cacu.partial', '2026-06-01', [[5, 0.5]]), + ]); + await open(page, url); + const card = page.locator('details.curves'); + await expect(card.locator('summary')).toHaveText('Curvas de probabilidad con su intervalo'); + await expect(card).toHaveAttribute('open', ''); + await expect(card.locator('li').first()).toContainText( + 'Riesgo LIEAG+ (fecha índice 2026-06-01): 1 año: 8.0 % (IC 95 %: 5.0–12.0 %); 3 años: 21.0 %', + ); + const plot = await card.locator('.js-plotly-plot').evaluate((e: any) => ({ + names: e.data.filter((t: any) => t.showlegend !== false).map((t: any) => t.name), + series: Object.fromEntries( + e.data.filter((t: any) => t.mode?.includes('markers')).map((t: any) => [t.name, t.x]), + ), + bands: e.data.filter((t: any) => t.fill === 'tonexty').map((t: any) => t.name), + ticks: e.layout.xaxis.tickvals, + title: e.layout.xaxis.title.text, + })); + expect(plot.series).toEqual({ + 'Riesgo LIEAG+': [1, 3, 5], + 'Riesgo cáncer': [1, 3, 5], + 'Sin intervalo': [2, 4], + 'Un punto': [5], + }); + expect(plot.bands).toEqual(['IC 95 % Riesgo LIEAG+', 'IC 95 % Riesgo cáncer']); // none for the models without intervals + expect(plot.ticks).toEqual([1, 2, 3, 4, 5]); + expect(plot.title).toBe('Horizonte (años desde la fecha índice (2026-06-01))'); + // the reference is a separate table: its 0.27 % is nowhere in the figure + expect( + JSON.stringify(await card.locator('.js-plotly-plot').evaluate((e: any) => e.data)), + ).not.toContain('0.27'); + await expect(page.locator('[data-section=referencia-nci]')).toBeVisible(); +}); diff --git a/src/app/paciente/paciente.html b/src/app/paciente/paciente.html index a39f9e1..3355bf0 100644 --- a/src/app/paciente/paciente.html +++ b/src/app/paciente/paciente.html @@ -259,6 +259,9 @@ > + @if (reference.value(); as ref) { + + } @if (models().length) { @@ -291,7 +294,15 @@ }
- +
+ Curvas de probabilidad con su intervalo +
    + @for (t of curveText(); track $index) { +
  • {{ t }}
  • + } +
+ +
} @else {

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

} diff --git a/src/app/paciente/paciente.scss b/src/app/paciente/paciente.scss index c342db8..8af730d 100644 --- a/src/app/paciente/paciente.scss +++ b/src/app/paciente/paciente.scss @@ -122,3 +122,19 @@ h1 .id { padding-left: 18px; } } + +.curves { + border: 1px solid var(--color-border); + border-radius: 6px; + margin-top: 12px; + padding: 8px 12px; + + summary { + cursor: pointer; + font-weight: 500; + } +} +.curve-text { + margin: 8px 0; + padding-left: 18px; +} diff --git a/src/app/paciente/paciente.ts b/src/app/paciente/paciente.ts index 33f9273..f357a1c 100644 --- a/src/app/paciente/paciente.ts +++ b/src/app/paciente/paciente.ts @@ -21,7 +21,13 @@ import { code, EXT, ext, Fhir, label, resources } from '../fhir'; import { scenarioFigure } from '../gobernanza/figures'; import { savePdf } from '../export'; import { recordSheets } from './record-sheets'; +import { HttpClient } from '@angular/common/http'; +import type { Parameters as FhirParameters } from 'fhir/r4'; +import { firstValueFrom } from 'rxjs'; +import { ApiConfiguration } from '../api/api-configuration'; import { ANTECEDENTS, Fact, group, split } from './record-groups'; +import { referenceView, ReferenceRisk, ReferenceView } from './reference-risk'; +import { curveFigure, curveText } from './risk-curve'; import { riskGroups, riskScales, RiskScales } from './risk-scales'; import { route, Stages } from './stages'; import { ageAt, ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up'; @@ -75,6 +81,7 @@ function facts(observations: Observation[]): Fact[] { RouterLink, Plot, RiskScales, + ReferenceRisk, Stages, ], templateUrl: './paciente.html', @@ -83,6 +90,8 @@ function facts(observations: Observation[]): Fact[] { export class Paciente { private readonly fhir = inject(Fhir); private readonly api = inject(Api); + private readonly http = inject(HttpClient); + private readonly root = inject(ApiConfiguration).rootUrl; readonly domain = input.required(); readonly id = input.required(); /** The follow-up list she was opened from: its window (months) and cut-off. */ @@ -154,6 +163,33 @@ export class Paciente { protected readonly groups = computed(() => this.domain() === 'cacu' ? riskGroups(this.models()) : [], ); + /** CaCu, experimental: the NCI reference comparison of the cytology she was opened at. The API + * answers 404 while the feature is off: then nothing is shown. */ + protected readonly reference = resource({ + params: () => + this.domain() === 'cacu' + ? { id: this.id(), cutoff: this.corte(), sample: this.citologia() } + : undefined, + loader: async ({ params }): Promise => { + try { + const answer = await firstValueFrom( + this.http.get( + `${this.root}/cacu/fhir/Patient/${params.id}/$reference-risk`, + { + params: Object.fromEntries( + Object.entries({ cutoff: params.cutoff, sample: params.sample }).filter( + ([, v]) => !!v, + ), + ) as Record, + }, + ), + ); + return referenceView(answer); + } catch { + return undefined; + } + }, + }); protected readonly saving = signal(false); protected readonly saveError = signal(''); /** CaCu: her record as a PDF. */ @@ -430,51 +466,9 @@ export class Paciente { } 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', - }, - }, - }; - }); + /** The institutional models' curves, drawn at the horizons each publishes (risk-curve). */ + protected readonly curve = computed
(() => curveFigure(this.models(), this.top())); + protected readonly curveText = computed(() => curveText(this.models())); private top(): number { return Math.max(0, ...this.models().flatMap((m) => m.predictions.map((p) => p.high ?? p.p))); } diff --git a/src/app/paciente/reference-risk.spec.ts b/src/app/paciente/reference-risk.spec.ts new file mode 100644 index 0000000..eded8ee --- /dev/null +++ b/src/app/paciente/reference-risk.spec.ts @@ -0,0 +1,90 @@ +import type { Parameters } from 'fhir/r4'; +import { horizonLabel, referenceView } from './reference-risk'; + +const part = (name: string, extra: object) => ({ name, ...extra }) as any; +const answer = (...parameter: object[]): Parameters => + ({ resourceType: 'Parameters', parameter }) as Parameters; +const resolved = (comparison: object[] = []) => + answer( + part('status', { valueCode: 'resolved' }), + part('cutoff', { valueDate: '2026-11-30' }), + part('scenario', { + part: [ + part('table', { valueCode: 'screening' }), + part('label', { valueString: 'Tamizaje' }), + part('key', { + part: [ + part('name', { valueCode: 'history' }), + part('value', { valueString: 'Cotest-negative' }), + ], + }), + ], + }), + part('horizon', { + part: [ + part('years', { valueInteger: 0 }), + part('published', { valueBoolean: true }), + part('reference', { valueDecimal: 0 }), + ...comparison, + ], + }), + part('horizon', { + part: [part('years', { valueInteger: 5 }), part('published', { valueBoolean: false })], + }), + ); + +describe('the reference answer as the section shows it', () => { + it('names the horizons and never calls a year the immediate risk', () => { + expect(horizonLabel(0)).toBe('Inmediato (al índice)'); + expect(horizonLabel(1)).toBe('1 año'); + expect(horizonLabel(5)).toBe('5 años'); + }); + it('keeps a published zero as zero and a blank as absent', () => { + const view = referenceView(resolved()); + expect(view.horizons.map((h) => [h.years, h.reference, h.published])).toEqual([ + [0, 0, true], + [5, undefined, false], + ]); + expect(view.scenario).toEqual({ + label: 'Tamizaje', + keys: [{ name: 'Antecedente más reciente', value: 'Cotest-negative' }], + }); + }); + it('reads a comparison with its model, its figures and its reasons, and a difference only when one is given', () => { + const view = referenceView( + resolved([ + part('comparison', { + part: [ + part('model', { valueCode: 'cacu.cin2_pim' }), + part('title', { valueString: 'Riesgo LIEAG+' }), + part('institutional', { valueDecimal: 0.05 }), + part('status', { valueCode: 'not_comparable' }), + part('reason', { valueCode: 'outcome_differs' }), + ], + }), + ]), + ); + const [c] = view.horizons[0].comparisons; + expect(c).toMatchObject({ + model: 'cacu.cin2_pim', + institutional: 0.05, + status: 'not_comparable', + reasons: ['outcome_differs'], + }); + expect(c.differencePp).toBeUndefined(); + }); + it('an unresolved answer has its state and reasons and no horizons', () => { + const view = referenceView( + answer( + part('status', { valueCode: 'history_not_demonstrable' }), + part('reason', { valueCode: 'no_earlier_test_registered' }), + ), + ); + expect(view).toMatchObject({ + status: 'history_not_demonstrable', + reasons: ['no_earlier_test_registered'], + horizons: [], + used: [], + }); + }); +}); diff --git a/src/app/paciente/reference-risk.ts b/src/app/paciente/reference-risk.ts new file mode 100644 index 0000000..630ce49 --- /dev/null +++ b/src/app/paciente/reference-risk.ts @@ -0,0 +1,479 @@ +import { DecimalPipe } from '@angular/common'; +import { Component, input } from '@angular/core'; +import type { Parameters, ParametersParameter } from 'fhir/r4'; + +/** The states a resolution ends in, as the screens say them. */ +export const STATUS_TEXT: Record = { + resolved: 'Referencia disponible', + not_published: 'Riesgo no publicado en las tablas', + missing_data: 'Falta un dato clínico', + history_not_demonstrable: 'Antecedente no demostrable', + not_applicable: 'Escenario no aplicable', + contradictory: 'Resultados contradictorios', + ambiguous: 'Escenario ambiguo', + scenario_not_implemented: 'Escenario aún no resuelto', + unverifiable_correspondence: 'Correspondencia no verificable', + no_published_row: 'Sin fila publicada para esta combinación', +}; + +/** Why a resolution or a comparison has no value. */ +export const REASON_TEXT: Record = { + no_cytology_reported_by_cutoff: 'No hay citología con resultado a la fecha de corte.', + sample_not_reported_by_cutoff: 'La citología pedida no tenía resultado a la fecha de corte.', + no_birth_date: 'Falta la fecha de nacimiento.', + age_outside_25_65: 'La edad está fuera del rango de las tablas (25 a 65 años).', + cytology_not_in_tables: 'El resultado citológico no está en las tablas.', + missing_hpv: 'La citología no tiene resultado de VPH.', + contradictory_hpv: 'El VPH es negativo pero se reporta un genotipo positivo.', + hpv_positive_row: + 'Las tablas muestran «VPH positivo» junto a VPH 16 y VPH 18; no se verificó si esa fila es el total o los otros tipos, y no se asume.', + no_earlier_test_registered: + 'La plataforma no tiene una prueba anterior con VPH; no demuestra que no haya antecedente.', + earlier_test_older_than_5_years: 'La prueba anterior es de hace más de 5 años.', + colposcopy_or_treatment_before: + 'Hay una colposcopía, biopsia o tratamiento previo: es un escenario posterior a colposcopía o tratamiento, aún no resuelto.', + history_is_a_surveillance_scenario: + 'El antecedente anormal corresponde a la tabla de vigilancia, aún no resuelta.', + registered_cin2_plus_before: 'Hay un CIN2+ registrado antes: las tablas lo excluyen.', + hysterectomy_declared: 'El formulario declara una histerectomía: las tablas la excluyen.', + procedure_after_without_named_referral: + 'Hay una colposcopía o biopsia posterior, pero ningún registro la nombra como derivada de esta citología (una asociación por fechas no basta).', + several_biopsies_name_the_cytology: 'Varias biopsias nombran esta citología.', + not_a_referral_result_in_the_tables: + 'La citología no es un resultado de derivación de las tablas.', + hsil_cin2_cin3: 'La histología «LIEAG» no distingue CIN2 de CIN3, que las tablas separan.', + cis_ais: 'El carcinoma in situ no distingue el adenocarcinoma in situ, que las tablas separan.', + biopsy_without_histology: 'La biopsia no tiene histología.', + risk_blank_in_the_tables: 'Las tablas dejan este riesgo en blanco.', + no_row_for_the_combination: 'Las tablas no publican esa combinación.', + several_rows: 'Más de una fila podría corresponder.', + no_institutional_model: 'Ningún modelo institucional ha evaluado a la paciente.', + outcome_differs: 'El desenlace del modelo no es el de la tabla (CIN3+).', + unknown_model: 'El desenlace del modelo no está registrado para comparar.', + horizon_not_published_by_model: 'El modelo no publica una predicción a este horizonte.', + index_date_differs: 'La fecha índice del modelo no es la de la citología evaluada.', + population_not_verified: + 'No se verificó que la población y el escenario del modelo coincidan con los de la tabla.', + no_reference: 'Las tablas no dan un riesgo a este horizonte.', +}; + +const KEY_TEXT: Record = { + history: 'Antecedente más reciente', + hpv: 'VPH actual', + cytology: 'Citología actual', + referral: 'Resultado de tamizaje que originó la colposcopía', + biopsy: 'Resultado de biopsia', +}; + +const USED_TEXT: Record = { + 'sample-date': 'toma', + 'report-date': 'reporte', + 'request-date': 'solicitud', + result: 'resultado', + hpv: 'VPH', + 'hpv-16': 'VPH 16', + 'hpv-18': 'VPH 18', + histology: 'histología', +}; +const usedValue = (v: unknown) => (v === true ? 'positivo' : v === false ? 'negativo' : String(v)); + +export interface ComparisonView { + model?: string; + title?: string; + outcome?: string; + /** probabilities, 0 to 1 */ + institutional?: number; + low?: number; + high?: number; + status: string; + /** percentage points, institutional minus reference */ + differencePp?: number; + reasons: string[]; +} +export interface HorizonView { + years: number; + label: string; + published: boolean; + /** probability, 0 to 1; none when the tables leave it blank */ + reference?: number; + comparisons: ComparisonView[]; +} +export interface ReferenceView { + status: string; + reasons: string[]; + cutoff?: string; + scenario?: { label: string; keys: { name: string; value: string }[] }; + index?: { sampleDate?: string; reportDate?: string; result?: string; age?: number }; + evaluationDate?: string; + source?: { id?: string; file?: string; sha256?: string; outcome?: string; status?: string }; + row?: { sheet?: string; number?: number; officialCheck?: string; matchedVia?: string }; + used: { label: string; details: string }[]; + assumptions: string[]; + horizons: HorizonView[]; +} + +type Part = ParametersParameter; +const value = (p?: Part) => + p?.valueCode ?? + p?.valueString ?? + p?.valueDate ?? + p?.valueInteger ?? + p?.valueDecimal ?? + p?.valueBoolean ?? + undefined; +const named = (parts: Part[] | undefined, name: string) => + (parts ?? []).filter((p) => p.name === name); +const one = (parts: Part[] | undefined, name: string) => value(named(parts, name)[0]); + +/** The horizon's name; the colposcopy table's one year is a year, never "immediate". */ +export function horizonLabel(years: number): string { + return years === 0 ? 'Inmediato (al índice)' : years === 1 ? '1 año' : `${years} años`; +} + +/** The result of `$reference-risk` as the section shows it. A value absent from the answer stays + * absent: no zero is made of a blank, and no difference is made of a comparison that is not one. */ +export function referenceView(answer: Parameters): ReferenceView { + const top = answer.parameter ?? []; + const scenario = named(top, 'scenario')[0]; + const index = named(top, 'index')[0]?.part; + const row = named(top, 'row')[0]?.part; + const source = named(top, 'source')[0]?.part; + const view: ReferenceView = { + status: String(one(top, 'status') ?? 'missing_data'), + reasons: named(top, 'reason').map((r) => String(value(r))), + cutoff: one(top, 'cutoff') as string | undefined, + evaluationDate: one(top, 'evaluation-date') as string | undefined, + used: named(top, 'used').map((u) => ({ + label: String(one(u.part, 'label') ?? ''), + details: (u.part ?? []) + .filter((p) => p.name !== 'label') + .map((p) => `${USED_TEXT[p.name ?? ''] ?? p.name}: ${usedValue(value(p))}`) + .join(' · '), + })), + assumptions: named(top, 'assumption').map((a) => String(value(a))), + horizons: named(top, 'horizon').map((h) => { + const years = Number(one(h.part, 'years')); + return { + years, + label: horizonLabel(years), + published: one(h.part, 'published') === true, + reference: one(h.part, 'reference') as number | undefined, + comparisons: named(h.part, 'comparison').map((c) => ({ + model: one(c.part, 'model') as string | undefined, + title: one(c.part, 'title') as string | undefined, + outcome: one(c.part, 'outcome') as string | undefined, + institutional: one(c.part, 'institutional') as number | undefined, + low: one(c.part, 'institutional-low') as number | undefined, + high: one(c.part, 'institutional-high') as number | undefined, + status: String(one(c.part, 'status')), + differencePp: one(c.part, 'difference-pp') as number | undefined, + reasons: named(c.part, 'reason').map((r) => String(value(r))), + })), + }; + }), + }; + if (scenario?.part) + view.scenario = { + label: String(one(scenario.part, 'label') ?? ''), + keys: named(scenario.part, 'key').map((k) => ({ + name: KEY_TEXT[String(one(k.part, 'name'))] ?? String(one(k.part, 'name')), + value: String(one(k.part, 'value')), + })), + }; + if (index) + view.index = { + sampleDate: one(index, 'sample-date') as string | undefined, + reportDate: one(index, 'report-date') as string | undefined, + result: one(index, 'result') as string | undefined, + age: one(index, 'age') as number | undefined, + }; + if (row) + view.row = { + sheet: one(row, 'sheet') as string | undefined, + number: one(row, 'number') as number | undefined, + officialCheck: one(row, 'official-check') as string | undefined, + matchedVia: one(row, 'matched-via') as string | undefined, + }; + if (source) + view.source = { + id: one(source, 'id') as string | undefined, + file: one(source, 'file') as string | undefined, + sha256: one(source, 'sha256') as string | undefined, + outcome: one(source, 'outcome') as string | undefined, + status: one(source, 'status') as string | undefined, + }; + return view; +} + +const OFFICIAL: Record = { + match: 'coincide con la tabla del NCI', + 'match_within_0.01': 'coincide con la tabla del NCI salvo 0.01 puntos de redondeo', + differs: 'no coincide con la tabla del NCI', + not_found_in_official: 'sin fila equivalente en la tabla del NCI consultada', + blank_in_both: 'en blanco en ambas', + no_official_file: 'sin tabla del NCI para cotejar', +}; + +/** Comparison with the NCI's reference risks (experimental): the reference by horizon beside the + * institutional models', the difference only where the two are the same estimate. */ +@Component({ + selector: 'app-reference-risk', + imports: [DecimalPipe], + template: ` + @let v = view(); +
+

Comparación de riesgos de referencia

+
+
+
Estado
+
{{ statusText(v.status) }}
+
+ @if (v.scenario; as s) { +
+
Escenario clínico
+
{{ s.label }}
+
+ } +
+
Desenlace
+
CIN3 o más grave (CIN3+)
+
+ @if (v.evaluationDate ?? v.index?.sampleDate; as day) { +
+
Fecha de evaluación
+
{{ day }}
+
+ } + @if (v.cutoff) { +
+
Fecha de corte
+
{{ v.cutoff }}
+
+ } + @if (v.source; as src) { +
+
Fuente y versión
+
Tablas NCI (libro {{ src.file }}, {{ src.id }}); no validadas
+
+ } +
+ @if (v.reasons.length) { +
    + @for (r of v.reasons; track r) { +
  • {{ reasonText(r) }}
  • + } +
+ } + @if (v.horizons.length) { + + + + + + + + + + + @for (h of v.horizons; track h.years) { + @for (c of h.comparisons.length ? h.comparisons : [none]; track $index) { + + + + + + + } + } + +
HorizonteModelo institucionalReferencia NCIDiferencia (puntos porcentuales)
{{ h.label }} + @if (c.model) { + {{ c.title }} + {{ c.outcome }} + } + @if (c.institutional !== undefined) { + {{ c.institutional * 100 | number: '1.2-2' }} % + @if (c.low !== undefined && c.high !== undefined) { + (IC 95 %: {{ c.low * 100 | number: '1.2-2' }}–{{ + c.high * 100 | number: '1.2-2' + }} + %) + } + } @else { + No disponible + } + + @if (h.reference !== undefined) { + {{ h.reference * 100 | number: '1.2-2' }} % + } @else { + No publicado + } + + @if (c.status === 'comparable' && c.differencePp !== undefined) { + {{ c.differencePp > 0 ? '+' : '' + }}{{ c.differencePp | number: '1.2-2' }} + } @else { + No comparable + @if (c.reasons.length) { +
    + @for (r of c.reasons; track r) { +
  • {{ reasonText(r) }}
  • + } +
+ } + } +
+

+ La diferencia es el riesgo institucional menos el riesgo NCI y solo se calcula si ambos + estiman lo mismo (desenlace, horizonte, fecha índice y población verificados). +

+ } + @if (v.used.length || v.assumptions.length || v.scenario || v.row) { +
+ Antecedentes utilizados + @if (v.scenario; as s) { +
    + @for (k of s.keys; track k.name) { +
  • {{ k.name }}: {{ k.value }}
  • + } +
+ } + @if (v.index; as i) { +

+ Citología evaluada: toma {{ i.sampleDate }}, reporte {{ i.reportDate }}, resultado + {{ i.result }} + @if (i.age !== undefined) { + , edad {{ i.age }} años + } + . +

+ } +
    + @for (u of v.used; track $index) { +
  • + {{ u.label }}: {{ u.details }} +
  • + } +
+ @if (v.row; as r) { +

+ Fila de origen: «{{ r.sheet }}», fila {{ r.number }} + @if (r.matchedVia === 'table_group') { + (categoría agrupada definida por la propia tabla) + } + — {{ official(r.officialCheck) }}. +

+ } + @for (a of v.assumptions; track a) { +

Sin verificar: {{ a }}

+ } +
+ } +
+ `, + styles: ` + .reference { + border: 1px dashed #9aa3ab; + border-radius: 6px; + margin: 16px 0; + padding: 12px 16px; + } + h3 { + margin: 0 0 8px; + } + .meta { + display: flex; + flex-wrap: wrap; + gap: 8px 24px; + margin: 0 0 8px; + } + .meta dt { + color: var(--color-text-secondary); + font-size: 12px; + } + .meta dd { + font-weight: 500; + margin: 0; + } + table { + border-collapse: collapse; + width: 100%; + } + th, + td { + padding: 6px 8px; + text-align: left; + vertical-align: top; + } + .model strong, + .model .muted { + display: block; + } + .why { + margin: 4px 0; + padding-left: 18px; + } + .note { + font-size: 12px; + } + .used { + margin-top: 8px; + } + .used summary { + cursor: pointer; + } + @media (max-width: 700px) { + .reference { + padding: 8px 10px; + } + table, + thead, + tbody, + tr, + th, + td { + display: block; + } + thead { + display: none; + } + tr { + border-bottom: 1px solid #dce3e7; + padding: 6px 0; + } + td { + padding: 2px 0; + } + td::before { + color: var(--color-text-secondary); + content: attr(data-label); + display: block; + font-size: 12px; + } + } + `, +}) +export class ReferenceRisk { + readonly view = input.required(); + protected readonly none: ComparisonView = { + status: 'not_comparable', + reasons: ['no_institutional_model'], + }; + protected statusText(status: string) { + return STATUS_TEXT[status] ?? status; + } + protected reasonText(reason: string) { + return REASON_TEXT[reason] ?? reason; + } + protected official(check?: string) { + return OFFICIAL[check ?? ''] ?? 'sin cotejo'; + } +} diff --git a/src/app/paciente/risk-curve.spec.ts b/src/app/paciente/risk-curve.spec.ts new file mode 100644 index 0000000..8301d21 --- /dev/null +++ b/src/app/paciente/risk-curve.spec.ts @@ -0,0 +1,100 @@ +import { curveFigure, curveText } from './risk-curve'; + +const model = (text: string, predictions: object[], index = '2026-06-01') => ({ + text, + index, + predictions: predictions as { years: number; p: number; low?: number; high?: number }[], +}); +const traces = (models: ReturnType[]) => curveFigure(models, 0.4).data as any[]; + +describe('the institutional curves', () => { + it('draws one series per model, named as the model, at the horizons it publishes only', () => { + const found = traces([ + model('Riesgo LIEAG+ v3', [ + { years: 1, p: 0.08 }, + { years: 3, p: 0.21 }, + { years: 5, p: 0.34 }, + ]), + model('Riesgo cáncer v2', [{ years: 5, p: 0.015 }]), + ]); + const lines = found.filter((t) => !t.name?.startsWith('IC')); + expect(lines.map((t) => t.name)).toEqual(['Riesgo LIEAG+', 'Riesgo cáncer']); + expect(lines[0].x).toEqual([1, 3, 5]); + expect(lines[0].y.map((y: number) => Math.round(y))).toEqual([8, 21, 34]); + expect(lines[1].x).toEqual([5]); // a single horizon is a point, not a line to nowhere + expect(lines[1].mode).toBe('markers'); + expect(lines[0].color ?? lines[0].line.color).not.toBe(lines[1].line.color); + }); + it('puts the axis ticks on the published horizons and invents none between them', () => { + const f = curveFigure( + [ + model('M v1', [ + { years: 0, p: 0.01 }, + { years: 5, p: 0.05 }, + ]), + ], + 0.05, + ); + expect((f.layout!.xaxis as any).tickvals).toEqual([0, 5]); + expect((f.layout!.xaxis as any).title.text).toBe( + 'Horizonte (años desde la fecha índice (2026-06-01))', + ); + const mixed = curveFigure( + [model('A v1', [{ years: 1, p: 0.1 }]), model('B v1', [{ years: 3, p: 0.2 }], '2026-07-01')], + 0.2, + ); + expect((mixed.layout!.xaxis as any).tickvals).toEqual([1, 3]); + expect((mixed.layout!.xaxis as any).title.text).toBe('Horizonte (años desde la fecha índice)'); // two index dates: none is named + }); + it('draws a band only where intervals are published, with its own legend entry, and no band without them', () => { + const none = traces([ + model('Sin IC v1', [ + { years: 1, p: 0.1 }, + { years: 5, p: 0.3 }, + ]), + ]); + expect(none).toHaveLength(1); + expect(none[0].fill).toBeUndefined(); + const withBand = traces([ + model('Con IC v1', [ + { years: 1, p: 0.1, low: 0.05, high: 0.12 }, + { years: 3, p: 0.2, low: 0.15, high: 0.28 }, + { years: 5, p: 0.3, low: 0.26, high: 0.44 }, + ]), + ]); + expect(withBand.map((t) => t.name)).toEqual([undefined, 'IC 95 % Con IC', 'Con IC']); + expect(withBand[1].fill).toBe('tonexty'); + expect(withBand[1].y.map((y: number) => Math.round(y))).toEqual([5, 15, 26]); + }); + it('a horizon without an interval is a gap in the band, never filled with the probability', () => { + const [high, low] = traces([ + model('Hueco v1', [ + { years: 1, p: 0.1, low: 0.05, high: 0.12 }, + { years: 3, p: 0.2 }, + { years: 5, p: 0.3, low: 0.26, high: 0.44 }, + ]), + ]); + expect(high.y[1]).toBeNull(); + expect(low.y[1]).toBeNull(); + expect(low.connectgaps).toBe(false); + }); + it('one published interval is an error bar, not a band', () => { + const found = traces([model('Uno v1', [{ years: 5, p: 0.34, low: 0.26, high: 0.44 }])]); + expect(found).toHaveLength(1); + expect(found[0].error_y.array[0]).toBeCloseTo(10); + expect(found[0].error_y.arrayminus[0]).toBeCloseTo(8); + }); + it('says each model, its index date and every horizon it publishes, with intervals only where there are', () => { + expect( + curveText([ + model('Riesgo LIEAG+ v3', [ + { years: 5, p: 0.34, low: 0.26, high: 0.44 }, + { years: 1, p: 0.08 }, + ]), + model('Vacío v1', []), + ]), + ).toEqual([ + 'Riesgo LIEAG+ (fecha índice 2026-06-01): 1 año: 8.0 %; 5 años: 34.0 % (IC 95 %: 26.0–44.0 %).', + ]); + }); +}); diff --git a/src/app/paciente/risk-curve.ts b/src/app/paciente/risk-curve.ts new file mode 100644 index 0000000..bb7f2d9 --- /dev/null +++ b/src/app/paciente/risk-curve.ts @@ -0,0 +1,126 @@ +import { Figure, PALETTE } from '../plot'; + +export interface CurvePrediction { + years: number; + p: number; + low?: number; + high?: number; +} +export interface CurveModel { + /** the model's own title, with its version */ + text: string; + /** the model's index date */ + index: string; + predictions: CurvePrediction[]; +} + +const percent = (n: number) => + (Math.round(n * 1000) / 10).toLocaleString('es-MX', { minimumFractionDigits: 1 }); +const title = (m: CurveModel) => m.text.replace(/ v\d+$/, ''); +const interval = (p: CurvePrediction) => p.low !== undefined && p.high !== undefined; + +/** The institutional models' risk by horizon: one series per model, drawn only at the horizons it + * publishes (a model with one horizon is a point), its 95 % interval as a band where it publishes + * one at two or more horizons and as an error bar at a single one. No horizon, interval or + * probability is made up: between published horizons the line joins them and nothing else. The + * NCI reference is not here. */ +export function curveFigure(models: CurveModel[], top: number): Figure { + const shown = models.filter((m) => m.predictions.length); + const years = [...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))]; + return { + 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 bounded = sorted.filter(interval); + const traces: object[] = []; + if (bounded.length > 1) { + // a gap in the published intervals stays a gap: nothing is drawn between them + const at = (pick: (p: CurvePrediction) => number | undefined) => + sorted.map((p) => (interval(p) ? (pick(p) as number) * 100 : null)); + traces.push( + { + x, + y: at((p) => p.high), + mode: 'lines', + line: { width: 0 }, + connectgaps: false, + showlegend: false, + hoverinfo: 'skip', + legendgroup: name, + }, + { + x, + y: at((p) => p.low), + mode: 'lines', + line: { width: 0 }, + fill: 'tonexty', + connectgaps: false, + fillcolor: color + '33', + name: `IC 95 % ${name}`, + legendgroup: name, + hoverinfo: 'skip', + }, + ); + } + traces.push({ + x, + y: sorted.map((p) => p.p * 100), + mode: sorted.length > 1 ? 'lines+markers' : 'markers', + name, + legendgroup: name, + line: { color }, + marker: { color, size: 8 }, + ...(bounded.length === 1 + ? { + error_y: { + type: 'data', + symmetric: false, + color, + array: sorted.map((p) => (interval(p) ? (p.high! - p.p) * 100 : 0)), + arrayminus: sorted.map((p) => (interval(p) ? (p.p - p.low!) * 100 : 0)), + }, + } + : {}), + hovertemplate: `${name}
%{x} años: %{y:.2f} %`, + }); + return traces; + }) as Figure['data'], + layout: { + xaxis: { + title: { + text: `Horizonte (años desde la fecha índice${dates.length === 1 ? ` (${dates[0]})` : ''})`, + }, + tickmode: 'array', + tickvals: years, + ticktext: years.map(String), + }, + // 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, top * 110)], + tickformat: '.0f', + }, + }, + } as Figure; +} + +/** The curves in words: each model, its index date and every horizon it publishes, with its + * interval where it has one. */ +export function curveText(models: CurveModel[]): string[] { + return models + .filter((m) => m.predictions.length) + .map((m) => { + const sorted = [...m.predictions].sort((a, b) => a.years - b.years); + const said = sorted.map( + (p) => + `${p.years === 0 ? 'al índice' : `${p.years} ${p.years === 1 ? 'año' : 'años'}`}: ${percent(p.p)} %` + + (interval(p) ? ` (IC 95 %: ${percent(p.low!)}–${percent(p.high!)} %)` : ''), + ); + return `${title(m)} (fecha índice ${m.index}): ${said.join('; ')}.`; + }); +}