F1: training form driven by the API schema; Sankey stopped nodes at the left

The training form flattens the discriminated source union generically: the discriminator becomes a select labelled by each variant's title, a variant's fields hide unless it is chosen, and the payload keeps only the chosen variant's fields. No variant names, option labels or Hz labels live in the WebApp. The Sankey places the three 'Se quedó en' nodes in the leftmost column, every node at its own position.
This commit is contained in:
2026-12-01 13:32:26 -06:00
parent f57a42b22a
commit 5bf022b36f
4 changed files with 103 additions and 47 deletions
+24 -7
View File
@@ -1,8 +1,8 @@
import { trainingForm } from './training';
import { sourcePayload, trainingForm } from './training';
describe('training form', () => {
it('builds the source selector from the folder fields and keeps the site payload minimal', () => {
const { schema, model } = trainingForm({
it('flattens the source union into one selector whose variants own their fields', () => {
const { schema, model, variants } = trainingForm({
name: 'all',
domain: 'tea',
defaults: {
@@ -26,13 +26,15 @@ describe('training form', () => {
},
SiteTrainingSource: {
type: 'object',
properties: { kind: { type: 'string', const: 'site' } },
title: 'Sitio',
properties: { kind: { type: 'string', const: 'site', title: 'Origen' } },
},
FolderTrainingSource: {
type: 'object',
title: 'Carpeta',
required: ['kind', 'folder'],
properties: {
kind: { type: 'string', const: 'folder' },
kind: { type: 'string', const: 'folder', title: 'Origen' },
folder: { type: 'string' },
line_hz: { type: 'integer', enum: [50, 60], default: 50 },
},
@@ -47,14 +49,29 @@ describe('training form', () => {
format: 'date',
});
expect(schema.properties?.['source']).toMatchObject({
type: 'object',
type: ['object', 'null'],
required: ['kind', 'folder'],
properties: {
kind: { enum: ['site', 'folder'] },
kind: {
title: 'Origen',
oneOf: [
{ const: 'site', title: 'Sitio' },
{ const: 'folder', title: 'Carpeta' },
],
},
folder: { type: 'string' },
line_hz: { enum: [50, 60] },
},
});
expect(model).toEqual({ source: { kind: 'site' } });
expect(variants.owners).toEqual({ folder: ['folder'], line_hz: ['folder'] });
expect(sourcePayload({ kind: 'site', folder: 'x', line_hz: 50 }, variants)).toEqual({
kind: 'site',
});
expect(sourcePayload({ kind: 'folder', folder: 'x', line_hz: 60 }, variants)).toEqual({
kind: 'folder',
folder: 'x',
line_hz: 60,
});
});
});
+60 -39
View File
@@ -32,7 +32,15 @@ import type { TrainingSource } from '../api/models/training-source';
import { FORMLY_TYPES } from '../conectar/schema-form';
import { errorText } from './run-monitor';
type Schema = Omit<JSONSchema7, '$defs'> & { $defs?: Record<string, Schema> };
type Schema = Omit<JSONSchema7, '$defs'> & {
$defs?: Record<string, Schema>;
discriminator?: { propertyName: string };
};
export interface Variants {
discriminator: string;
owners: Record<string, string[]>;
}
export function trainingForm(config: TrainingConfig) {
const raw = structuredClone(config.json_schema) as Schema;
@@ -40,20 +48,9 @@ export function trainingForm(config: TrainingConfig) {
delete model['execution'];
delete raw.properties?.['execution'];
raw.required = raw.required?.filter((key) => key !== 'execution');
if (raw.properties?.['source']) {
const folder = raw.$defs!['FolderTrainingSource']!;
raw.properties['source'] = {
...folder,
title: 'Datos de entrenamiento',
properties: {
kind: { type: 'string', title: 'Origen', enum: ['site', 'folder'] },
folder: folder.properties!['folder'],
line_hz: folder.properties!['line_hz'],
},
};
}
const variants: Variants = { discriminator: '', owners: {} };
const normalize = (schema: Schema): Schema => {
if (schema.$ref) return normalize(raw.$defs![schema.$ref.split('/').pop()!]);
if (schema.$ref) return normalize(raw.$defs![schema.$ref.split('/').pop()!]!);
if (schema.anyOf) {
const { anyOf, ...rest } = schema;
const selected = normalize(
@@ -61,6 +58,7 @@ export function trainingForm(config: TrainingConfig) {
);
return { ...selected, ...rest, type: [selected.type as JSONSchema7TypeName, 'null'] };
}
if (schema.oneOf && schema.discriminator) return union(schema as Required<Schema>);
if (schema.properties) {
return {
...schema,
@@ -74,7 +72,44 @@ export function trainingForm(config: TrainingConfig) {
}
return schema;
};
return { schema: normalize(raw), model };
const union = (schema: Required<Pick<Schema, 'oneOf' | 'discriminator'>> & Schema): Schema => {
const key = schema.discriminator.propertyName;
const members = schema.oneOf.map((entry) => normalize(entry as Schema));
const kinds = members.map((member) => member.properties![key] as Schema);
variants.discriminator = key;
const properties: Record<string, Schema> = {
[key]: {
type: 'string',
title: kinds[0]!.title,
oneOf: members.map((member, index) => ({
const: kinds[index]!.const,
title: member.title,
})),
},
};
members.forEach((member, index) => {
for (const [name, property] of Object.entries(member.properties!)) {
if (name === key) continue;
properties[name] ??= property as Schema;
(variants.owners[name] ??= []).push(kinds[index]!.const as string);
}
});
return {
type: 'object',
required: [...new Set(members.flatMap((member) => member.required ?? []))],
properties,
};
};
return { schema: normalize(raw), model, variants };
}
export function sourcePayload<T extends object>(source: T, variants: Variants): T {
const kind = (source as Record<string, unknown>)[variants.discriminator];
return Object.fromEntries(
Object.entries(source).filter(
([name]) => !variants.owners[name] || variants.owners[name].includes(kind as string),
),
) as T;
}
function allowedFile(file: File, allowed: string[]): boolean {
@@ -178,7 +213,9 @@ export class Training {
protected readonly config = resource({
params: () => ({ domain: this.domain(), name: this.name() }),
loader: async ({ params }) => {
const { schema, model } = trainingForm(await this.api.invoke(trainingConfig, params));
const { schema, model, variants } = trainingForm(
await this.api.invoke(trainingConfig, params),
);
const fields = [
this.jsonschema.toFieldConfig(schema, {
map: (field, source) => {
@@ -186,35 +223,18 @@ export class Training {
if (source.format === 'date') {
field.props = { ...field.props, type: 'date' };
}
if (field.key === 'kind') {
field.type = 'select';
field.props = {
...field.props,
options: [
{ value: 'site', label: 'Niños del sitio sin el diagnóstico' },
{ value: 'folder', label: 'Carpeta de EDF con edades' },
],
const owners = variants.owners[field.key as string];
if (owners) {
field.expressions = {
hide: (field) => !owners.includes(field.model?.[variants.discriminator]),
};
}
if (field.key === 'folder' || field.key === 'line_hz') {
field.expressions = { hide: (field) => field.model?.kind !== 'folder' };
field.resetOnHide = false;
}
if (field.key === 'line_hz') {
field.type = 'select';
field.props = {
...field.props,
options: [
{ value: 50, label: '50 Hz' },
{ value: 60, label: '60 Hz' },
],
};
}
return field;
},
}),
];
return { fields, model, form: new UntypedFormGroup({}) };
return { fields, model, variants, form: new UntypedFormGroup({}) };
},
});
protected readonly inputs = resource({
@@ -249,6 +269,7 @@ export class Training {
this.message.set('');
const domain = this.domain();
const name = this.name();
const variants = this.config.value()!.variants;
const source = model['source'] as TrainingSource | undefined;
const autoPromote = domain === 'tea' && this.autoPromote();
try {
@@ -256,7 +277,7 @@ export class Training {
domain,
body: {
as_of: model['as_of'] || undefined,
source: source?.kind === 'site' ? { kind: 'site' } : source,
source: source && sourcePayload(source, variants),
execution: this.execution(),
...(name === 'all' ? {} : { models: [name] }),
},
+4 -1
View File
@@ -490,6 +490,9 @@ export function sexCountBars(r: Reading, catalog: Catalog, axis: string, period:
};
}
export const SANKEY_X = [0.22, 0.5, 0.78, 0.999, 0.001, 0.001, 0.001];
export const SANKEY_Y = [0.2, 0.2, 0.2, 0.2, 0.5, 0.75, 0.999];
export function teaSankey(r: Reading): Figure {
const [mchat, psychology, neuro, eeg] = [
'mchat_only',
@@ -521,7 +524,7 @@ export function teaSankey(r: Reading): Figure {
{
type: 'sankey',
arrangement: 'fixed',
node: { label: labels, color: colors, align: 'left', pad: 24, hovertemplate },
node: { label: labels, color: colors, x: SANKEY_X, y: SANKEY_Y, pad: 24, hovertemplate },
link: {
source: links.map(({ source }) => source),
target: links.map(({ target }) => target),
@@ -339,6 +339,21 @@ describe('TEA clinical figures', () => {
});
});
it('places the stopped nodes at the left and gives every node its own position', () => {
const node = teaSankey({ populations: {}, strata: {} }).data[0] as unknown as {
node: { label: string[]; x: number[]; y: number[] };
};
const stopped = node.node.label.flatMap((label, index) =>
label.startsWith('Se quedó en') ? [index] : [],
);
expect(stopped).toHaveLength(3);
expect(Math.max(...stopped.map((index) => node.node.x[index]))).toBeLessThan(
Math.min(...node.node.x.filter((_, index) => !stopped.includes(index))),
);
const places = node.node.x.map((x, index) => `${x}|${node.node.y[index]}`);
expect(new Set(places).size).toBe(places.length);
});
it('splits prevalence by sex and diagnosis and includes children without a recorded sex', () => {
const r = {
populations: { 'initial-population': 7 },