Usar un solo selector de curvas para riesgo y supervivencia

This commit is contained in:
2026-12-03 07:31:12 -06:00
parent 5a82dc780e
commit 4ec071332d
7 changed files with 138 additions and 143 deletions
+10
View File
@@ -0,0 +1,10 @@
import { figureChoices } from './curve-chooser';
describe('figureChoices', () => {
it('keeps each band with its line, one choice per curve', () => {
const data = [{ showlegend: false }, { name: 'Kaplan-Meier' }, { name: 'Weibull' }];
const { choices, draw } = figureChoices({ data: data as never });
expect(choices.map((c) => c.name)).toEqual(['Kaplan-Meier', 'Weibull']);
expect(draw(new Set(['Kaplan-Meier'])).data.length).toBe(2);
});
});
+86
View File
@@ -0,0 +1,86 @@
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 before the user touches it */
on: boolean;
}
/** A figure's curves as choices, all on: a band has no name of its own and goes with the line
* after it. */
export function figureChoices(figure: Figure): { choices: Choice[]; draw: Draw } {
const groups = new Map<string, Figure['data']>();
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) ?? []) }),
};
}
export type Draw = (ids: Set<string>) => Figure;
/** Curves chosen or not, to compare them on one plot: the record's risk and survival curves. */
@Component({
selector: 'app-curve-chooser',
imports: [MatCheckboxModule, Plot],
template: `
<div class="choices">
@for (c of choices(); track c.id) {
<mat-checkbox [checked]="chosen().has(c.id)" (change)="toggle(c.id)">
{{ c.name }}
</mat-checkbox>
}
</div>
@if (chosen().size) {
@for (note of notes()(chosen()); track note) {
<p class="muted">{{ note }}</p>
}
<app-plot [figure]="figure()" [height]="340" [toolbar]="false" />
}
`,
styles: `
:host {
display: block;
}
.choices {
display: flex;
flex-wrap: wrap;
gap: 0 16px;
margin-bottom: 8px;
}
`,
})
export class CurveChooser {
readonly choices = input.required<Choice[]>();
readonly draw = input.required<Draw>();
/** what the chosen curves assume, said under the choices */
readonly notes = input<(ids: Set<string>) => string[]>(() => []);
/** what the user toggled away from its default */
private readonly toggled = signal(new Set<string>());
protected readonly chosen = computed(
() =>
new Set(
this.choices()
.filter((c) => c.on !== this.toggled().has(c.id))
.map((c) => c.id),
),
);
protected readonly figure = computed(() => this.draw()(this.chosen()));
protected toggle(id: string) {
const next = new Set(this.toggled());
if (!next.delete(id)) next.add(id);
this.toggled.set(next);
}
}
+2 -2
View File
@@ -610,13 +610,13 @@
} @else if (combination.error()) { } @else if (combination.error()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p> <p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
} @else if (combination.value(); as c) { } @else if (combination.value(); as c) {
@if (c.figure) { @if (c.curves) {
<p class="muted"> <p class="muted">
Ajustes sobre las pacientes con sus mismos valores (Kaplan-Meier con IC 95 % Ajustes sobre las pacientes con sus mismos valores (Kaplan-Meier con IC 95 %
Greenwood; n = Greenwood; n =
{{ c.n }}, fallecidos = {{ c.fallecidos }}). {{ c.n }}, fallecidos = {{ c.fallecidos }}).
</p> </p>
<app-survival-curves [figure]="c.figure" /> <app-curve-chooser [choices]="c.curves.choices" [draw]="c.curves.draw" />
} @else { } @else {
<p class="muted">{{ c.missing }}</p> <p class="muted">{{ c.missing }}</p>
} }
+3 -3
View File
@@ -50,7 +50,7 @@ import type { Relation } from '../api/models/relation';
import { Figure, PALETTE, Plot } from '../plot'; import { Figure, PALETTE, Plot } from '../plot';
import { Loading } from '../loading'; import { Loading } from '../loading';
import { Factores, ScenarioFactors } from './factores'; import { Factores, ScenarioFactors } from './factores';
import { SurvivalCurves } from './survival-curves'; import { CurveChooser, figureChoices } from './curve-chooser';
/** An Observation's value as the screens say it, whatever its type. */ /** An Observation's value as the screens say it, whatever its type. */
function shown(o: Observation): string { function shown(o: Observation): string {
@@ -104,7 +104,7 @@ function modelInputs(value: string | undefined): Record<string, unknown> | undef
selector: 'app-paciente', selector: 'app-paciente',
imports: [ imports: [
Factores, Factores,
SurvivalCurves, CurveChooser,
Loading, Loading,
DecimalPipe, DecimalPipe,
MatButtonModule, MatButtonModule,
@@ -237,7 +237,7 @@ export class Paciente {
}); });
const found = combinationOf(report as Record<string, unknown>, inputs); const found = combinationOf(report as Record<string, unknown>, inputs);
return found?.km return found?.km
? { n: found.n, fallecidos: found.fallecidos, figure: survivalFigure(found) } ? { n: found.n, fallecidos: found.fallecidos, curves: figureChoices(survivalFigure(found)) }
: { missing: noCurveText(report as Record<string, unknown>, found) }; : { missing: noCurveText(report as Record<string, unknown>, found) };
}, },
}); });
+37 -59
View File
@@ -1,7 +1,6 @@
import { Component, computed, input, signal } from '@angular/core'; import { Component, computed, input } from '@angular/core';
import { MatCheckboxModule } from '@angular/material/checkbox';
import type { Parameters, ParametersParameter } from 'fhir/r4'; import type { Parameters, ParametersParameter } from 'fhir/r4';
import { Plot } from '../plot'; import { CurveChooser } from './curve-chooser';
import { curveFigure } from './risk-curve'; import { curveFigure } from './risk-curve';
export interface SeriesPoint { export interface SeriesPoint {
@@ -64,23 +63,12 @@ export function parseSeries(answer: Parameters): Series[] {
/** The chosen series as curves. Series are shown side by side; no difference is computed. */ /** The chosen series as curves. Series are shown side by side; no difference is computed. */
@Component({ @Component({
selector: 'app-risk-series', selector: 'app-risk-series',
imports: [MatCheckboxModule, Plot], imports: [CurveChooser],
template: ` template: `
<p class="muted">Cada serie tiene su propio desenlace y población: no se restan entre sí.</p> <p class="muted">Cada serie tiene su propio desenlace y población: no se restan entre sí.</p>
<div class="choices"> @if (available().length) {
@for (s of available(); track s.id) { <app-curve-chooser [choices]="choices()" [draw]="draw()" [notes]="assumptions()" />
<mat-checkbox [checked]="chosen().has(s.id)" (change)="toggle(s.id)"> } @else {
{{ name(s) }}
</mat-checkbox>
}
</div>
@if (selected().length) {
@for (assumption of assumptions(); track assumption) {
<p class="muted">{{ assumption }}</p>
}
<app-plot [figure]="figure()" [height]="340" [toolbar]="false" />
}
@if (!available().length) {
<p class="muted">No disponible: datos insuficientes.</p> <p class="muted">No disponible: datos insuficientes.</p>
} }
`, `,
@@ -88,52 +76,42 @@ export function parseSeries(answer: Parameters): Series[] {
:host { :host {
display: block; display: block;
} }
.choices {
display: flex;
flex-wrap: wrap;
gap: 0 16px;
margin-bottom: 8px;
}
`, `,
}) })
export class RiskSeries { export class RiskSeries {
readonly series = input.required<Series[]>(); readonly series = input.required<Series[]>();
protected readonly name = seriesName;
protected readonly available = computed(() => this.series().filter((s) => s.points.length)); protected readonly available = computed(() => this.series().filter((s) => s.points.length));
/** what the user toggled away from the default (the institutional series) */ /** the platform's own series are drawn until the user says otherwise */
private readonly toggled = signal(new Set<string>()); protected readonly choices = computed(() =>
protected readonly chosen = computed( this.available().map((s) => ({
() => id: s.id,
new Set( name: seriesName(s),
this.available() on: s.source === 'Institucional',
.filter((s) => (s.source === 'Institucional') !== this.toggled().has(s.id)) })),
.map((s) => s.id),
),
); );
protected readonly selected = computed(() => private readonly among = computed(() => {
this.available().filter((s) => this.chosen().has(s.id)), const all = this.available();
); return (ids: Set<string>) => all.filter((s) => ids.has(s.id));
/** what the chosen series assume, each said once */ });
protected readonly assumptions = computed(() => [ /** what the chosen series assume, each said once */
...new Set(this.selected().flatMap((s) => s.assumptions)), protected readonly assumptions = computed(() => {
]); const chosen = this.among();
protected readonly figure = computed(() => { return (ids: Set<string>) => [...new Set(chosen(ids).flatMap((s) => s.assumptions))];
const shown = this.selected().map((s) => ({ });
model: s.id, protected readonly draw = computed(() => {
text: seriesName(s), const chosen = this.among();
index: '', return (ids: Set<string>) => {
predictions: s.points, const shown = chosen(ids).map((s) => ({
})); model: s.id,
const top = Math.max(...shown.flatMap((m) => m.predictions.map((p) => p.high ?? p.p))); text: seriesName(s),
const figure = curveFigure(shown, top); index: '',
// sources do not share an index date: the axis says only the horizon predictions: s.points,
figure.layout!.xaxis!.title = { text: 'Horizonte (años)' }; }));
return figure; const top = Math.max(...shown.flatMap((m) => m.predictions.map((p) => p.high ?? p.p)));
const figure = curveFigure(shown, top);
// sources do not share an index date: the axis says only the horizon
figure.layout!.xaxis!.title = { text: 'Horizonte (años)' };
return figure;
};
}); });
protected toggle(id: string) {
const next = new Set(this.toggled());
if (!next.delete(id)) next.add(id);
this.toggled.set(next);
}
} }
-12
View File
@@ -1,12 +0,0 @@
import { curveGroups } from './survival-curves';
describe('curveGroups', () => {
it('keeps each band with its line, one choice per curve', () => {
const data = [{ showlegend: false }, { name: 'Kaplan-Meier' }, { name: 'Weibull' }];
const groups = curveGroups({ data: data as never });
expect(groups.map((g) => [g.name, g.traces.length])).toEqual([
['Kaplan-Meier', 2],
['Weibull', 1],
]);
});
});
-67
View File
@@ -1,67 +0,0 @@
import { Component, computed, input, signal } from '@angular/core';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { Figure, Plot } from '../plot';
type Trace = Figure['data'][number];
/** The figure's curves by name; a band has no name of its own and goes with the line after it. */
export function curveGroups(figure: Figure): { name: string; traces: Trace[] }[] {
const groups: { name: string; traces: Trace[] }[] = [];
let pending: Trace[] = [];
for (const trace of figure.data) {
pending.push(trace);
const { name, showlegend } = trace as { name?: string; showlegend?: boolean };
if (name && showlegend !== false) {
groups.push({ name, traces: pending });
pending = [];
}
}
return groups;
}
/** The survival fits, each one chosen or not, to compare them on one plot. */
@Component({
selector: 'app-survival-curves',
imports: [MatCheckboxModule, Plot],
template: `
<div class="choices">
@for (g of groups(); track g.name) {
<mat-checkbox [checked]="!hidden().has(g.name)" (change)="toggle(g.name)">
{{ g.name }}
</mat-checkbox>
}
</div>
@if (shown().data.length) {
<app-plot [figure]="shown()" [height]="340" [toolbar]="false" />
}
`,
styles: `
:host {
display: block;
}
.choices {
display: flex;
flex-wrap: wrap;
gap: 0 16px;
margin-bottom: 8px;
}
`,
})
export class SurvivalCurves {
readonly figure = input.required<Figure>();
protected readonly groups = computed(() => curveGroups(this.figure()));
private readonly hidden_ = signal(new Set<string>());
protected readonly hidden = this.hidden_.asReadonly();
protected readonly shown = computed<Figure>(() => ({
...this.figure(),
data: this.groups()
.filter((g) => !this.hidden().has(g.name))
.flatMap((g) => g.traces),
}));
protected toggle(name: string) {
const next = new Set(this.hidden());
if (!next.delete(name)) next.add(name);
this.hidden_.set(next);
}
}