diff --git a/e2e/ficha-cacu.spec.ts b/e2e/ficha-cacu.spec.ts index 9af6efd..e1f8de0 100644 --- a/e2e/ficha-cacu.spec.ts +++ b/e2e/ficha-cacu.spec.ts @@ -321,11 +321,11 @@ test('ficha (simulado): the scales draw 0, 2, 50, 98 and 100 % in place, and tel }) => { const { url } = await firstRecord(page); await withRisks(page, [ - risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [ + risk('a', 'Supervivencia v3', 'cacu.cin2_pim', '2026-02-01', [ [0, 0], [5, 0.5, 0.4, 0.6], ]), - risk('b', 'Recurrencia v2', 'cacu.recurrence', '2026-03-01', [ + risk('b', 'Recurrencia v2', 'cacu.cancer_pim', '2026-03-01', [ [0, 0.02, 0.01, 0.03], [5, 0.98, 0.95, 1], ]), @@ -373,7 +373,7 @@ test('ficha (simulado): the scale is drawn in four equal segments with the numer }) => { const { url } = await firstRecord(page); await withRisks(page, [ - risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [[5, 0.5, 0.4, 0.6]]), + risk('a', 'Supervivencia v3', 'cacu.cin2_pim', '2026-02-01', [[5, 0.5, 0.4, 0.6]]), ]); await open(page, url); const box = scale(page, FIVE); @@ -415,7 +415,7 @@ for (const width of [1440, 480]) { link: 'recorded', }); await withRisks(page, [ - risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [ + risk('a', 'Supervivencia v3', 'cacu.cin2_pim', '2026-02-01', [ [0, 0], [5, 0.98, 0.95, 1], ]), @@ -703,6 +703,7 @@ function fixture( part: [ part('id', { valueString: 'fixture-table' }), part('file', { valueString: 'fixture.xlsx' }), + part('outcome', { valueCode: 'CIN3+' }), ], }), ...more, @@ -745,7 +746,7 @@ test('referencia NCI: a resolved cytology shows its reference with scenario, sou 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'); + const rows = box.locator('table[aria-label="Referencia NCI por horizonte"] tbody tr'); await expect(rows).toHaveCount(2); await expect(rows.first()).toContainText('Inmediato (al índice)'); await expect(rows.nth(1)).toContainText('5 años'); @@ -756,10 +757,13 @@ test('referencia NCI: a resolved cytology shows its reference with scenario, sou (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'); + await expect(rows.nth(i).locator('td').nth(1)).toContainText(`${pct} %`); + // no model evaluated her: said once, not on every horizon + await expect(box.locator('.nomodel')).toContainText('No disponible'); + await expect(box.getByText('Ningún modelo institucional ha evaluado a la paciente.')).toHaveCount( + 1, + ); + await expect(box.locator('[data-model]')).toHaveCount(0); // the antecedents used are collapsed const used = box.locator('details.used'); expect(await used.getAttribute('open')).toBeNull(); @@ -832,13 +836,17 @@ test('referencia NCI (simulado): a comparison that is valid shows the difference ]), ); await open(page, url); - const row = section(page).locator('tbody tr').first(); - await expect(row).toContainText('Modelo de prueba'); + const block = section(page).locator('[data-model]'); + await expect(block.locator('h5')).toContainText('Modelo de prueba'); + await expect(block.locator('h5')).toContainText('CIN3 o más grave (CIN3+)'); + const row = block.locator('tbody tr').first(); 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'); + await expect( + section(page).locator('table').first().locator('tbody tr').first().locator('td').nth(1), + ).toContainText('0.27 %'); + await expect(row.locator('td').nth(2)).toContainText('+1.00'); + await expect(row.locator('td').nth(2)).not.toContainText('No comparable'); }); test('referencia NCI (simulado): another outcome or horizon is "No comparable" with its reasons and no difference', async ({ @@ -863,15 +871,15 @@ test('referencia NCI (simulado): another outcome or horizon is "No comparable" w ]), ); 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( + const first = section(page).locator('[data-model] tbody tr').first(); + await expect(first.locator('td').nth(2)).toContainText('No comparable'); + await expect(first.locator('td').nth(2)).toContainText( 'El desenlace del modelo no es el de la tabla (CIN3+)', ); - await expect(first.locator('td').nth(3)).toContainText( + await expect(first.locator('td').nth(2)).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(2)).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 }); @@ -881,12 +889,12 @@ test('referencia NCI (simulado): a year-one reference is a year, never the immed 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'); + const rows = section(page).locator('table[aria-label="Referencia NCI por horizonte"] 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 %'); + await expect(rows.nth(1).locator('td').nth(1)).toContainText('No publicado'); + await expect(rows.nth(1).locator('td').nth(1)).not.toContainText('0.00'); + await expect(rows.first().locator('td').nth(1)).toContainText('1.36 %'); }); for (const width of [1440, 480]) { @@ -929,12 +937,12 @@ for (const width of [1440, 480]) { ), ); await withRisks(page, [ - risk('a', 'Riesgo LIEAG+ v3', 'cacu.survival', '2026-06-01', [ + risk('a', 'Riesgo LIEAG+ v3', 'cacu.cin2_pim', '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', [ + risk('b', 'Riesgo cáncer v2', 'cacu.cancer_pim', '2026-06-01', [ [1, 0.002, 0.001, 0.005], [3, 0.008], [5, 0.015, 0.008, 0.028], @@ -956,12 +964,12 @@ test('curvas (simulado): one series per model at its published horizons, its ban 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', [ + risk('a', 'Riesgo LIEAG+ v3', 'cacu.cin2_pim', '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', [ + risk('b', 'Riesgo cáncer v2', 'cacu.cancer_pim', '2026-06-01', [ [1, 0.002, 0.001, 0.005], [3, 0.008], [5, 0.015, 0.008, 0.028], @@ -1003,3 +1011,377 @@ test('curvas (simulado): one series per model at its published horizons, its ban ).not.toContain('0.27'); await expect(page.locator('[data-section=referencia-nci]')).toBeVisible(); }); + +// ---- the grouped NCI comparison, the survival texts and the risk-model selection (all "simulado") ------ + +const SHOTS = process.env['SHOTS_DIR']; // when set, the simulated pages are saved for the report +const shot = async (page: Page, name: string) => { + if (SHOTS) await page.screenshot({ path: `${SHOTS}/SIMULADO-${name}.png`, fullPage: true }); +}; +const institutional = (p: number, low?: number, high?: number, diff?: number) => [ + part('institutional', { valueDecimal: p }), + ...(low === undefined ? [] : [part('institutional-low', { valueDecimal: low })]), + ...(high === undefined ? [] : [part('institutional-high', { valueDecimal: high })]), + ...(diff === undefined ? [] : [part('difference-pp', { valueDecimal: diff })]), +]; +const model = ( + code: string, + title: string, + outcome: string, + status: string, + reasons: string[], + extra: object[] = [], +) => + part('comparison', { + part: [ + part('model', { valueCode: code }), + part('title', { valueString: title }), + part('outcome', { valueString: outcome }), + ...extra, + part('status', { valueCode: status }), + ...reasons.map((r) => part('reason', { valueCode: r })), + ], + }); +const SHARED = ['index_date_differs', 'population_not_verified']; + +for (const width of [1440, 480]) { + test(`referencia NCI (simulado) at ${width} px: several models, outcomes and horizons are grouped without losing any`, async ({ + page, + }) => { + await page.setViewportSize({ width, height: 1000 }); + const { url } = await firstRecord(page); + await answerWith( + page, + fixture( + [ + { + years: 0, + reference: 0.0001, + comparison: [ + model( + 'cacu.cin2_pim', + 'Riesgo LIEAG+', + 'CIN2+', + 'not_comparable', + ['outcome_differs', ...SHARED], + institutional(0.05, 0.03, 0.08), + ), + model( + 'cacu.cancer_pim', + 'Riesgo de cáncer', + 'cancer', + 'not_comparable', + ['outcome_differs', ...SHARED], + institutional(0.002), + ), + model( + 'cacu.cin2_logistic', + 'Riesgo LIEAG+ a un año', + 'CIN2+ within one year', + 'not_comparable', + ['horizon_not_published_by_model', 'outcome_differs', ...SHARED], + ), + ], + }, + { + years: 1, + comparison: [ + model( + 'cacu.cin2_logistic', + 'Riesgo LIEAG+ a un año', + 'CIN2+ within one year', + 'not_comparable', + ['no_reference', 'outcome_differs', ...SHARED], + institutional(0.04), + ), + ], + }, + { + years: 5, + reference: 0.0027, + comparison: [ + model( + 'cacu.cin2_pim', + 'Riesgo LIEAG+', + 'CIN2+', + 'not_comparable', + ['outcome_differs', ...SHARED], + institutional(0.12, 0.08, 0.17), + ), + model( + 'cacu.cancer_pim', + 'Riesgo de cáncer', + 'cancer', + 'not_comparable', + ['outcome_differs', ...SHARED], + institutional(0.011, 0.006, 0.02), + ), + model( + 'cacu.cin3_fixture', + 'Modelo CIN3+ de prueba', + 'CIN3+', + 'comparable', + [], + institutional(0.0127, 0.005, 0.02, 1), + ), + ], + }, + ], + [part('assumption', { valueString: 'un supuesto sin verificar' })], + ), + ); + await open(page, url); + const box = section(page); + // the outcome of the reference comes from the answer; the models' are translated for display only + await expect(box).toContainText('Desenlace de la referencia'); + const blocks = box.locator('[data-model]'); + await expect(blocks).toHaveCount(4); + await expect(blocks.locator('h5 [data-outcome="cancer"]')).toHaveText('Cáncer'); + await expect(blocks.locator('h5 [data-outcome="CIN2+ within one year"]')).toHaveText( + 'CIN2+ en un año', + ); + await expect(blocks.locator('h5 [data-outcome="CIN2+"]')).toContainText('CIN2'); + // the reference is one table; each model keeps its own horizons, values and intervals + await expect( + box.locator('table[aria-label="Referencia NCI por horizonte"] tbody tr'), + ).toHaveCount(3); + const pim = box.locator('[data-model="cacu.cin2_pim"] tbody tr'); + await expect(pim).toHaveCount(2); + await expect(pim.first()).toContainText('5.00 %'); + await expect(pim.first()).toContainText('IC 95 %: 3.00–8.00 %'); + await expect(pim.nth(1)).toContainText('12.00 %'); + // an absent interval stays absent; a missing value says so + await expect(box.locator('[data-model="cacu.cancer_pim"] tbody tr').first()).not.toContainText( + 'IC 95 %', + ); + await expect(box.locator('[data-model="cacu.cin2_logistic"] tbody tr').first()).toContainText( + 'No disponible', + ); + // reasons every incompatible comparison gives are said once, not on each row + const common = box.locator('ul[aria-label="Motivos comunes"] li'); + await expect(common).toHaveCount(3); // outcome_differs is in every incompatible row too + await expect( + box.getByText('La fecha índice del modelo no es la de la citología evaluada.'), + ).toHaveCount(1); + // a difference only on the valid comparison + const valid = box.locator('[data-model="cacu.cin3_fixture"] tbody tr'); + await expect(valid.locator('td').nth(2)).toContainText('+1.00'); + await expect( + box.locator('[data-model="cacu.cin2_pim"] tbody td:nth-child(3)').first(), + ).not.toContainText(/[+-]\d/); + // the reasons of one horizon only stay on that row + await expect(box.locator('[data-model="cacu.cin2_logistic"]')).toContainText( + 'no publica una predicción a este horizonte', + ); + await expect(box.locator('[data-model="cacu.cin2_logistic"]')).toContainText( + 'no dan un riesgo a este horizonte', + ); + await box.locator('details.used summary').click(); + await page.waitForTimeout(600); + expect(await layoutProblems(page)).toEqual([]); + expect( + await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1), + ).toBe(true); + await shot(page, `referencia-nci-agrupada-${width}`); + }); +} + +test('referencia NCI (simulado): with no institutional model it says so once; the reference stays', async ({ + page, +}) => { + const { url } = await firstRecord(page); + await answerWith( + page, + fixture([ + { + years: 0, + reference: 0.0001, + comparison: [ + part('comparison', { + part: [ + part('status', { valueCode: 'not_comparable' }), + part('reason', { valueCode: 'no_institutional_model' }), + ], + }), + ], + }, + { + years: 5, + reference: 0.0027, + comparison: [ + part('comparison', { + part: [ + part('status', { valueCode: 'not_comparable' }), + part('reason', { valueCode: 'no_institutional_model' }), + ], + }), + ], + }, + ]), + ); + await open(page, url); + await expect( + section(page).getByText('Ningún modelo institucional ha evaluado a la paciente.'), + ).toHaveCount(1); + await expect( + section(page).locator('table[aria-label="Referencia NCI por horizonte"] tbody tr'), + ).toHaveCount(2); + await shot(page, 'referencia-nci-sin-modelos'); +}); + +const scenarioReport = (name: string, n: number, deaths: number) => ({ + escenario: name, + n, + fallecidos: deaths, + horizons_months: [12, 36, 60], + km: { + months: [0, 12, 36, 60], + S: [1, 0.92, 0.8, 0.7], + low: [1, 0.85, 0.7, 0.55], + high: [1, 0.97, 0.9, 0.82], + }, + weibull: { t: [0, 12, 36, 60], S: [1, 0.93, 0.81, 0.69] }, + weibull_fractional: { t: [0, 12, 36, 60], S: [1, 0.91, 0.79, 0.71] }, + points: { COMB: { S: [0.92, 0.8, 0.7], low: [0.85, 0.7, 0.55], high: [0.97, 0.9, 0.82] } }, +}); +async function withSurvival(page: Page, domain: 'cacu' | 'cama', others: object[] = []) { + const assessed = { + ...risk('s', 'Supervivencia v3', `${domain}.survival`, '2026-02-01', [[5, 0.7, 0.55, 0.82]]), + extension: [ + { url: EXT + 'escenario-clinico', valueString: 'Edad al diagnóstico · 45-54 años' }, + { url: EXT + 'escenario-clinico', valueString: 'VPH positivo' }, + ], + }; + await page.route(`**/api/${domain}/fhir/RiskAssessment**`, (route) => + route.fulfill({ + contentType: 'application/fhir+json', + body: JSON.stringify({ + resourceType: 'Bundle', + type: 'searchset', + entry: [assessed, ...others].map((resource) => ({ resource })), + }), + }), + ); + await page.route( + `**/api/models/${domain}/survival/versions/*/reports/interpretability`, + (route) => + route.fulfill({ + contentType: 'application/json', + body: JSON.stringify({ + escenarios: [ + scenarioReport('Edad al diagnóstico · 45-54 años', 12, 6), + scenarioReport('VPH positivo', 30, 9), + ], + factores_escenarios: [], + }), + }), + ); +} + +for (const width of [1440, 480]) { + test(`supervivencia (simulado) at ${width} px: CaCu says the curves are the scenario group's, not individual predictions`, async ({ + page, + }) => { + await page.setViewportSize({ width, height: 1000 }); + const { url } = await firstRecord(page); + await withSurvival(page, 'cacu'); + await open(page, url); + const card = page.locator('[data-section=supervivencia]'); + await expect(card.locator('mat-card-title')).toHaveText('Supervivencia por escenario clínico'); + await expect(card).not.toContainText('Riesgo de muerte'); + await expect(card.locator('[data-note=grupo]')).toContainText( + 'estimaciones del grupo de pacientes del escenario clínico', + ); + await expect(card.locator('[data-note=grupo]')).toContainText( + 'no son predicciones individuales', + ); + await expect(card.locator('h4')).toHaveText([ + 'Edad al diagnóstico · 45-54 años (n = 12, fallecidos = 6)', + 'VPH positivo (n = 30, fallecidos = 9)', + ]); + // the curves are the report's, untouched + const plot = await card + .locator('.js-plotly-plot') + .first() + .evaluate((e: any) => ({ + names: e.data.filter((t: any) => t.showlegend !== false).map((t: any) => t.name), + y: e.layout.yaxis.title.text, + x: e.layout.xaxis.title.text, + })); + expect(plot.y).toBe('Supervivencia S(t)'); + expect(plot.x).toBe('Meses desde el diagnóstico'); + expect(plot.names).toContain('Kaplan-Meier (IC 95 % Greenwood)'); + expect( + await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1), + ).toBe(true); + await shot(page, `supervivencia-cacu-${width}`); + }); +} + +test('supervivencia (simulado): CaMa keeps its own title and no group note', async ({ page }) => { + const patients = await (await page.request.get('/api/cama/fhir/Patient?_count=1')).json(); + const id = patients.entry[0].resource.id; + await withSurvival(page, 'cama'); + await page.goto(`/indicadores/cama/pacientes/${id}`); + const card = page.locator('[data-section=supervivencia]'); + await expect(card).toBeVisible({ timeout: 120_000 }); + await expect(card.locator('mat-card-title')).toHaveText('Riesgo de muerte'); + await expect(card.locator('[data-note=grupo]')).toHaveCount(0); + await shot(page, 'supervivencia-cama-sin-cambios'); +}); + +const SCALES = [IMMEDIATE, 'Riesgo a 5 años']; +test('escalas (simulado): a survival estimate alone never feeds the risk scales or curves; they say "No disponible"', async ({ + page, +}) => { + await page.setViewportSize({ width: 1440, height: 1000 }); + const { url } = await firstRecord(page); + await withSurvival(page, 'cacu'); // only cacu.survival: S(5 years) = 70 % + await open(page, url); + for (const label of SCALES) { + await expect(scale(page, label)).toContainText('No disponible'); + await expect(scale(page, label).locator('.risk-marker')).toHaveCount(0); + } + await expect(page.locator('.risk-value')).toHaveCount(0); // no 70 % on a risk scale + await expect(page.locator('details.curves')).toHaveCount(0); + await expect(page.locator('table.plain', { hasText: 'Probabilidad' })).toHaveCount(0); + // the survival is still in its own analysis, as the group's estimate + const card = page.locator('[data-section=supervivencia]'); + await expect(card.locator('mat-card-title')).toHaveText('Supervivencia por escenario clínico'); + await expect(card.locator('h4').first()).toContainText('n = 12'); + await shot(page, 'escalas-solo-supervivencia-1440'); +}); + +test('escalas (simulado): with a survival model and compatible risk models, only the risk models feed the scales and curves', async ({ + page, +}) => { + await page.setViewportSize({ width: 1440, height: 1000 }); + const { url } = await firstRecord(page); + await withSurvival(page, 'cacu', [ + risk('r1', 'Riesgo LIEAG+ v3', 'cacu.cin2_pim', '2026-06-01', [ + [0, 0.03, 0.02, 0.05], + [5, 0.12, 0.08, 0.17], + ]), + risk('r2', 'Riesgo de cáncer v2', 'cacu.cancer_pim', '2026-06-01', [[5, 0.011, 0.006, 0.02]]), + ]); + await open(page, url); + const values = await page.locator('.risk-value').allInnerTexts(); + expect(values.map((v) => v.trim())).toEqual(['3.0 %', '12.0 %', '1.1 %']); // none is the 70 % survival + await expect(scale(page, 'Riesgo a 5 años', 0)).toContainText('IC 95 %: 8.0–17.0'); + await expect(scale(page, IMMEDIATE, 1)).toContainText('No disponible'); // the cancer model has no immediate risk + await expect(page.locator('app-risk-scales h3')).toHaveText([ + 'Riesgo LIEAG+ v3 · fecha índice 2026-06-01', + 'Riesgo de cáncer v2 · fecha índice 2026-06-01', + ]); + const curves = page.locator('details.curves'); + await expect(curves).not.toContainText('Supervivencia'); + expect( + JSON.stringify(await curves.locator('.js-plotly-plot').evaluate((e: any) => e.data)), + ).not.toContain('70'); + const table = page.locator('table.plain', { hasText: 'Probabilidad' }); + await expect(table).not.toContainText('Supervivencia'); + // the survival analysis and the NCI reference stay + await expect(page.locator('[data-section=supervivencia]')).toBeVisible(); + await expect(page.locator('[data-section=referencia-nci]')).toBeVisible(); + await shot(page, 'escalas-supervivencia-y-riesgo-1440'); +}); diff --git a/src/app/paciente/paciente.html b/src/app/paciente/paciente.html index 3755998..ab982da 100644 --- a/src/app/paciente/paciente.html +++ b/src/app/paciente/paciente.html @@ -266,7 +266,7 @@ } } - @if (models().length) { + @if (riskModels().length) { @@ -278,7 +278,7 @@ - @for (m of models(); track m.model) { + @for (m of riskModels(); track m.model) { @for (p of m.predictions; track p.years) { @@ -562,9 +562,20 @@ } @if (models().some((m) => m.model.endsWith('.survival') && m.scenarios.length)) { - Riesgo de muerte + + {{ + domain() === 'cacu' ? 'Supervivencia por escenario clínico' : 'Riesgo de muerte' + }} +

Análisis de supervivencia

+ @if (domain() === 'cacu') { +

+ Las curvas son estimaciones del grupo de pacientes del escenario clínico + correspondiente (S(t), probabilidad de supervivencia); no son predicciones + individuales. +

+ } @if (survival.isLoading()) { } @else if (survival.value(); as s) { diff --git a/src/app/paciente/paciente.ts b/src/app/paciente/paciente.ts index 80f4098..fdde577 100644 --- a/src/app/paciente/paciente.ts +++ b/src/app/paciente/paciente.ts @@ -28,7 +28,7 @@ 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 { isRiskModel, riskGroups, 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/measures'; @@ -166,12 +166,14 @@ export class Paciente { const shown = cytologies.find((r) => r.effectiveDateTime === this.citologia()) ?? cytologies[0]; return this.domain() === 'cacu' ? route(shown, this.cutoff()) : undefined; }); + /** The models whose estimate is a risk (scales, curves, PDF): not survival or recurrence. */ + protected readonly riskModels = computed(() => this.models().filter((m) => isRiskModel(m.model))); protected readonly scales = computed(() => - this.domain() === 'cacu' ? riskScales(this.models()) : [], + this.domain() === 'cacu' ? riskScales(this.riskModels()) : [], ); /** CaCu: both horizons of every model, or both unavailable (the PDF keeps `scales`). */ protected readonly groups = computed(() => - this.domain() === 'cacu' ? riskGroups(this.models()) : [], + this.domain() === 'cacu' ? riskGroups(this.riskModels()) : [], ); /** 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. */ @@ -479,10 +481,10 @@ export class Paciente { protected readonly zoneOrder = computed(() => byDeviation(this.zoned()?.zones ?? [])); protected readonly head = computed(() => headMap(this.zoned()?.electrodes ?? [])); /** 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())); + protected readonly curve = computed
(() => curveFigure(this.riskModels(), this.top())); + protected readonly curveText = computed(() => curveText(this.riskModels())); private top(): number { - return Math.max(0, ...this.models().flatMap((m) => m.predictions.map((p) => p.high ?? p.p))); + return Math.max(0, ...this.riskModels().flatMap((m) => m.predictions.map((p) => p.high ?? p.p))); } protected readonly name = name; protected readonly levelNames = LEVEL_NAMES; diff --git a/src/app/paciente/reference-risk.spec.ts b/src/app/paciente/reference-risk.spec.ts index eded8ee..825b778 100644 --- a/src/app/paciente/reference-risk.spec.ts +++ b/src/app/paciente/reference-risk.spec.ts @@ -1,5 +1,5 @@ import type { Parameters } from 'fhir/r4'; -import { horizonLabel, referenceView } from './reference-risk'; +import { groupReference, horizonLabel, outcomeText, referenceView } from './reference-risk'; const part = (name: string, extra: object) => ({ name, ...extra }) as any; const answer = (...parameter: object[]): Parameters => @@ -88,3 +88,173 @@ describe('the reference answer as the section shows it', () => { }); }); }); + +const cmp = ( + model: string, + outcome: string, + status: string, + reasons: string[], + extra: object[] = [], +) => + part('comparison', { + part: [ + part('model', { valueCode: model }), + part('title', { valueString: model }), + part('outcome', { valueString: outcome }), + ...extra, + part('status', { valueCode: status }), + ...reasons.map((r) => part('reason', { valueCode: r })), + ], + }); +const two = (a: object[], b: object[]) => + answer( + part('status', { valueCode: 'resolved' }), + part('horizon', { + part: [ + part('years', { valueInteger: 0 }), + part('published', { valueBoolean: true }), + part('reference', { valueDecimal: 0.001 }), + ...a, + ], + }), + part('horizon', { + part: [ + part('years', { valueInteger: 5 }), + part('published', { valueBoolean: true }), + part('reference', { valueDecimal: 0.0027 }), + ...b, + ], + }), + ); + +describe('outcome names', () => { + it('translates the known outcomes for display and leaves the API identifier untouched', () => { + expect(outcomeText('cancer')).toBe('Cáncer'); + expect(outcomeText('CIN2+ within one year')).toBe('CIN2+ en un año'); + expect(outcomeText('CIN3+')).toBe('CIN3 o más grave (CIN3+)'); + expect(outcomeText('something new')).toBe('something new'); + expect(outcomeText(undefined)).toBe(''); + const view = referenceView( + two([cmp('m', 'cancer', 'not_comparable', ['outcome_differs'])], []), + ); + expect(view.horizons[0].comparisons[0].outcome).toBe('cancer'); + }); +}); + +describe('grouping the comparison', () => { + const reasons = ['outcome_differs', 'population_not_verified']; + it('keeps every model, horizon, value and interval, and says shared reasons once', () => { + const g = groupReference( + referenceView( + two( + [ + cmp( + 'a', + 'CIN2+', + 'not_comparable', + [...reasons, 'index_date_differs'], + [part('institutional', { valueDecimal: 0.05 })], + ), + cmp('b', 'cancer', 'not_comparable', reasons), + ], + [ + cmp('a', 'CIN2+', 'not_comparable', reasons, [ + part('institutional', { valueDecimal: 0.07 }), + part('institutional-low', { valueDecimal: 0.05 }), + part('institutional-high', { valueDecimal: 0.09 }), + ]), + cmp('b', 'cancer', 'not_comparable', [...reasons, 'horizon_not_published_by_model']), + ], + ), + ), + ); + expect(g.reference.map((r) => [r.years, r.reference])).toEqual([ + [0, 0.001], + [5, 0.0027], + ]); + expect(g.common).toEqual(reasons); // every model gives them + expect(g.models.map((m) => [m.model, m.outcome, m.rows.length])).toEqual([ + ['a', 'CIN2+', 2], + ['b', 'cancer', 2], + ]); + expect(g.models[0].reasons).toEqual([]); // nothing else shared by both of a's horizons + expect(g.models[0].rows[0].reasons).toEqual(['index_date_differs']); + expect(g.models[0].rows[1]).toMatchObject({ + institutional: 0.07, + low: 0.05, + high: 0.09, + reasons: [], + }); + expect(g.models[1].rows[1].reasons).toEqual(['horizon_not_published_by_model']); + }); + it('never merges across outcomes: reasons are only shared where every compared row has them', () => { + const g = groupReference( + referenceView( + two( + [ + cmp('a', 'CIN2+', 'not_comparable', ['outcome_differs']), + cmp('b', 'cancer', 'not_comparable', ['no_reference']), + ], + [], + ), + ), + ); + expect(g.common).toEqual([]); + expect(g.models.flatMap((m) => m.rows.flatMap((r) => r.reasons))).toEqual([ + 'outcome_differs', + 'no_reference', + ]); + }); + it('a comparable row keeps its difference and a missing interval stays missing', () => { + const g = groupReference( + referenceView( + two( + [ + cmp( + 'a', + 'CIN3+', + 'comparable', + [], + [ + part('institutional', { valueDecimal: 0.01 }), + part('difference-pp', { valueDecimal: 0.9 }), + ], + ), + ], + [], + ), + ), + ); + expect(g.models[0].rows[0]).toMatchObject({ + status: 'comparable', + differencePp: 0.9, + low: undefined, + }); + }); + it('without a model it says so once, with its reasons', () => { + const g = groupReference( + referenceView( + two( + [ + part('comparison', { + part: [ + part('status', { valueCode: 'not_comparable' }), + part('reason', { valueCode: 'no_institutional_model' }), + ], + }), + ], + [ + part('comparison', { + part: [ + part('status', { valueCode: 'not_comparable' }), + part('reason', { valueCode: 'no_institutional_model' }), + ], + }), + ], + ), + ), + ); + expect(g.models).toEqual([]); + expect(g.withoutModel).toEqual(['no_institutional_model']); + }); +}); diff --git a/src/app/paciente/reference-risk.ts b/src/app/paciente/reference-risk.ts index 630ce49..6fa597d 100644 --- a/src/app/paciente/reference-risk.ts +++ b/src/app/paciente/reference-risk.ts @@ -1,5 +1,5 @@ import { DecimalPipe } from '@angular/common'; -import { Component, input } from '@angular/core'; +import { Component, computed, input } from '@angular/core'; import type { Parameters, ParametersParameter } from 'fhir/r4'; /** The states a resolution ends in, as the screens say them. */ @@ -205,6 +205,86 @@ export function referenceView(answer: Parameters): ReferenceView { return view; } +/** Outcome names as the screens say them; presentation only: the API's identifiers stay as they are + * (an outcome this map does not know is shown as the API gave it). */ +export const OUTCOME_TEXT: Record = { + 'CIN3+': 'CIN3 o más grave (CIN3+)', + 'CIN2+': 'CIN2 o más grave (CIN2+)', + cancer: 'Cáncer', + 'CIN2+ within one year': 'CIN2+ en un año', + 'not stated as a histology outcome': 'No expresado como desenlace histológico', +}; +export const outcomeText = (outcome?: string) => (outcome ? (OUTCOME_TEXT[outcome] ?? outcome) : ''); + +export interface ModelRow extends Omit { + years: number; + label: string; + /** the reasons of this horizon that its model's other horizons do not share */ + reasons: string[]; +} +export interface ModelBlock { + model?: string; + title?: string; + outcome?: string; + /** reasons shared by every non-comparable horizon of this model, said once */ + reasons: string[]; + rows: ModelRow[]; +} +export interface Grouped { + /** the reference by horizon: one table, whatever the models */ + reference: { years: number; label: string; published: boolean; reference?: number }[]; + /** reasons shared by every non-comparable comparison of every model, said once */ + common: string[]; + models: ModelBlock[]; + /** no institutional model evaluated her: said once, with its reasons */ + withoutModel: string[]; +} + +const shared = (lists: string[][]) => + lists.length > 1 ? lists[0].filter((r) => lists.every((l) => l.includes(r))) : []; + +/** Groups only what is equivalent: the reference once per horizon; a reason that every non-comparable + * comparison of a model (or of all models) gives, once; everything else stays where it is. Nothing is + * dropped, and a difference is never made: it is only the API's, on a comparable row. */ +export function groupReference(v: ReferenceView): Grouped { + const reference = v.horizons.map((h) => ({ + years: h.years, + label: h.label, + published: h.published, + reference: h.reference, + })); + const byModel = new Map(); + const withoutModel: string[] = []; + for (const h of v.horizons) + for (const c of h.comparisons) { + if (!c.model) { + for (const r of c.reasons) if (!withoutModel.includes(r)) withoutModel.push(r); + continue; + } + const block = byModel.get(c.model) ?? { + model: c.model, + title: c.title, + outcome: c.outcome, + reasons: [], + rows: [], + }; + byModel.set(c.model, block); + block.rows.push({ ...c, years: h.years, label: h.label }); + } + const models = [...byModel.values()]; + const notComparable = (b: ModelBlock) => b.rows.filter((r) => r.status !== 'comparable'); + const common = shared(models.flatMap(notComparable).map((r) => r.reasons)); + const everyModel = models.length > 1 ? common : []; + for (const b of models) { + const own = shared(notComparable(b).map((r) => r.reasons.filter((x) => !everyModel.includes(x)))); + b.reasons = own; + for (const r of b.rows) + if (r.status !== 'comparable') + r.reasons = r.reasons.filter((x) => !everyModel.includes(x) && !own.includes(x)); + } + return { reference, common: everyModel, models, withoutModel }; +} + 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', @@ -238,10 +318,12 @@ const OFFICIAL: Record = {
{{ s.label }}
} -
-
Desenlace
-
CIN3 o más grave (CIN3+)
-
+ @if (v.source?.outcome; as out) { +
+
Desenlace de la referencia
+
{{ outcomeText(out) }}
+
+ } @if (v.evaluationDate ?? v.index?.sampleDate; as day) {
Fecha de evaluación
@@ -269,68 +351,112 @@ const OFFICIAL: Record = { } @if (v.horizons.length) { -
{{ $first ? m.text : '' }}
+ @let g = grouped(); +
- - - @for (h of v.horizons; track h.years) { - @for (c of h.comparisons.length ? h.comparisons : [none]; track $index) { - - - - - - - } + @for (h of g.reference; track h.years) { + + + + }
HorizonteModelo institucional Referencia 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) }}
  • - } -
- } - } -
{{ h.label }} + @if (h.reference !== undefined) { + {{ h.reference * 100 | number: '1.2-2' }} % + } @else { + No publicado + } +
+

Modelos institucionales

+ @if (g.withoutModel.length || !g.models.length) { +

+ No disponible +

+ + } + @if (g.common.length) { +

Motivos que comparten todas las comparaciones no válidas:

+ + } + @for (m of g.models; track m.model) { +
+
+ {{ m.title }} + {{ outcomeText(m.outcome) }} +
+ @if (m.reasons.length) { +

No comparable en estos horizontes:

+ + } + + + + + + + + + + @for (c of m.rows; track c.years) { + + + + + + } + +
HorizonteModelo institucionalDiferencia (puntos porcentuales)
{{ c.label }} + @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 (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). @@ -406,6 +532,7 @@ const OFFICIAL: Record = { table { border-collapse: collapse; width: 100%; + table-layout: fixed; } th, td { @@ -413,9 +540,18 @@ const OFFICIAL: Record = { text-align: left; vertical-align: top; } - .model strong, - .model .muted { - display: block; + .model { + border-top: 1px solid #dce3e7; + margin-top: 8px; + padding-top: 4px; + } + h4, + h5 { + margin: 12px 0 4px; + } + h5 .muted { + font-weight: 400; + margin-left: 8px; } .why { margin: 4px 0; @@ -463,10 +599,10 @@ const OFFICIAL: Record = { }) export class ReferenceRisk { readonly view = input.required(); - protected readonly none: ComparisonView = { - status: 'not_comparable', - reasons: ['no_institutional_model'], - }; + protected readonly grouped = computed(() => groupReference(this.view())); + protected outcomeText(outcome?: string) { + return outcomeText(outcome); + } protected statusText(status: string) { return STATUS_TEXT[status] ?? status; } diff --git a/src/app/paciente/risk-scales.spec.ts b/src/app/paciente/risk-scales.spec.ts index ee5d789..7c87a7a 100644 --- a/src/app/paciente/risk-scales.spec.ts +++ b/src/app/paciente/risk-scales.spec.ts @@ -1,4 +1,4 @@ -import { horizon, riskGroups, riskScales } from './risk-scales'; +import { horizon, isRiskModel, riskGroups, riskScales } from './risk-scales'; const at = (years: number, p: number, low?: number, high?: number) => ({ years, p, low, high }); @@ -60,3 +60,27 @@ describe('the risk scales', () => { ]); }); }); + +describe('which models feed the risk scales', () => { + it('excludes survival and recurrence estimates, which are not risks of the scales outcome', () => { + expect(['cacu.cin2_pim', 'cacu.cancer_pim', 'cacu.cin2_logistic'].every(isRiskModel)).toBe( + true, + ); + expect(isRiskModel('cacu.survival')).toBe(false); + expect(isRiskModel('cama.recurrence')).toBe(false); + }); + it('with no risk model both horizons are unavailable (nothing is converted from a survival)', () => { + const risk = [ + { + text: 'm', + index: '2026-01-01', + predictions: [{ years: 5, p: 0.7 }], + model: 'cacu.survival', + }, + ].filter((m) => isRiskModel(m.model)); + expect(riskGroups(risk).flatMap((g) => g.scales.map((s) => s.risk))).toEqual([ + undefined, + undefined, + ]); + }); +}); diff --git a/src/app/paciente/risk-scales.ts b/src/app/paciente/risk-scales.ts index 5b725cd..3612f4e 100644 --- a/src/app/paciente/risk-scales.ts +++ b/src/app/paciente/risk-scales.ts @@ -12,6 +12,11 @@ export interface RiskScale { risk?: Prediction; } +/** Whether a model's estimate is a risk of the outcome the scales and curves draw. Survival (S(t)) and + * recurrence-free survival are estimates of another outcome, shown in their own analysis: they are + * never drawn on these scales, and no conversion (1 − S) is made. */ +export const isRiskModel = (model: string) => !/.(survival|recurrence)$/.test(model); + /** 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[] { return models.flatMap((m) => @@ -82,9 +87,7 @@ export function riskGroups( {{ 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' - }} + · IC 95 %: {{ r.low * 100 | number: '1.1-2' }}–{{ r.high * 100 | number: '1.1-2' }} % } } @else {