Source forms as a partial, non-injective function into the catalog's codes, checked on the catalog

How: `reference.source_mapping` keys a mapping by source system, result, normalized form and validity;
`check_function` rejects a form that gives two codes while both mappings are in force, and `resolve` gives
the code in force on a date, or none when nothing or two disagreeing mappings match. The catalog's own
check of spellings (`_claves_de_extraccion`) now runs `check_function` on each result's codes, labels and
aliases.

Implications: the same rule serves the TOML today and any store of mappings with systems and dates; every
catalog passes it.
This commit is contained in:
rockdrigo
2026-11-13 15:29:52 -06:00
parent cea74e1566
commit 64d3d721e3
3 changed files with 170 additions and 11 deletions
+65
View File
@@ -0,0 +1,65 @@
"""What this module covers: source forms as a function into the catalog's codes (`reference.source_mapping`):
many forms to one code, no code for an unknown form, the same form read per source system and per date, and two
codes for one form rejected when they're in force together; and every catalog's TOML passing that check.
Fixtures: none; the rows are built in each test.
"""
import tomllib
from datetime import date
import pytest
from webapi.orchestration.reference.catalogs import ruta_de_catalogo
from webapi.orchestration.reference.source_mapping import (
SourceForm, ambiguities, check_function, from_result, normalize, resolve,
)
HER2 = "biopsia.her2"
LAB_A = [SourceForm("lab_a", HER2, "3+", "H3", None, date(2026, 12, 31)),
SourceForm("lab_a", HER2, "Positivo", "H3", None, date(2026, 12, 31))]
LAB_B = [SourceForm("lab_b", HER2, "Positivo (score 3)", "H3", date(2027, 1, 1)),
SourceForm("lab_b", HER2, "Positivo", "H2", date(2027, 1, 1))]
def test_many_forms_give_one_code_and_an_unknown_form_none():
"""Pins down: the mapping isn't injective and is partial: several spellings, compared without case, accents or
extra spaces, give the same code; a spelling with no mapping gives None. Fails if `normalize` stops folding or
`resolve` invents a code."""
assert {resolve(LAB_A, "lab_a", HER2, f) for f in ("3+", " positivo ", "POSITIVO")} == {"H3"}
assert resolve(LAB_A, "lab_a", HER2, "Equívoco") is None
assert normalize(" Positívo (score 3) ") == "POSITIVO (SCORE 3)"
def test_a_form_is_read_per_source_system_and_per_date():
"""Pins down: "Positivo" is H3 at lab A and H2 at lab B, and a mapping applies only to documents dated within its
validity. Fails if `resolve` ignores the system or the dates, letting one lab's spelling leak into another's."""
rows = LAB_A + LAB_B
assert resolve(rows, "lab_a", HER2, "Positivo", date(2026, 6, 1)) == "H3"
assert resolve(rows, "lab_b", HER2, "Positivo", date(2027, 2, 1)) == "H2"
assert resolve(rows, "lab_b", HER2, "Positivo", date(2026, 6, 1)) is None
assert ambiguities(rows) == []
def test_two_codes_for_one_form_in_force_together_are_rejected():
"""Pins down: a form mapped to two codes with overlapping validity breaks the function: `check_function` names
it and `resolve` gives None rather than either code. Two codes in validities that don't overlap, or the same
code twice, are fine. Fails if the overlap test or the code comparison is dropped."""
clash = SourceForm("lab_b", HER2, "positivo", "H3", date(2027, 6, 1))
with pytest.raises(ValueError, match="se escribe igual para 'H2' y 'H3'"):
check_function(LAB_B + [clash])
assert resolve(LAB_B + [clash], "lab_b", HER2, "Positivo", date(2027, 7, 1)) is None
corrected = [LAB_B[1]._replace(valid_to=date(2027, 5, 31)), clash]
check_function(corrected)
assert resolve(corrected, "lab_b", HER2, "Positivo", date(2027, 7, 1)) == "H3"
check_function(LAB_B + [LAB_B[0]._replace(form="POSITIVO (SCORE 3)")])
@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"])
def test_every_catalog_s_spellings_are_a_function(proyecto):
"""Pins down: in each domain's TOML, every result's codes, labels and aliases map to one value each. Fails when
an edit to a catalog gives one spelling two values."""
estudios = tomllib.loads(ruta_de_catalogo(proyecto).read_text(encoding="utf-8"))
rows = [row for estudio_id, estudio in estudios.items()
for nombre, resultado in estudio.get("resultados", {}).items()
for row in from_result(f"{estudio_id}.{nombre}", resultado)]
check_function(rows)
+7 -11
View File
@@ -15,10 +15,10 @@ from pathlib import Path
from typing import NamedTuple
import core
from extraction.nlp.text import fold
from core.indicadores.catalogos import TIPOS_DE_VALOR
from sqlmodel import SQLModel
from webapi.orchestration.reference.source_mapping import check_function, from_result
from webapi.orchestration.tables import TablasKit
# Los catálogos viven en Core, junto a los modelos de sus tablas.
@@ -165,7 +165,8 @@ def resultados_extraibles(proyecto: str) -> dict[str, ResultadoExtraible]:
def _claves_de_extraccion(resultado: dict, resultado_id: str) -> None:
"""The extraction keys of a result: captions as a non-empty list of texts, and no spelling on two values."""
"""The extraction keys of a result: captions as a non-empty list of texts, and its spellings a function into
its values (`source_mapping.check_function`)."""
etiquetas = resultado.get("etiquetas_fuente")
if etiquetas is not None and (not isinstance(etiquetas, list) or not etiquetas
or not all(isinstance(e, str) and e.strip() for e in etiquetas)):
@@ -176,15 +177,10 @@ def _claves_de_extraccion(resultado: dict, resultado_id: str) -> None:
raise CatalogoInvalido(f"{resultado_id}: un resultado de tipo {resultado.get('tipo_valor')} no se extrae de texto.")
if resultado.get("buscar_en_texto") and resultado.get("tipo_valor") != "codigo":
raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo codigo se busca como mención en el texto.")
de: dict[str, str] = {}
for valor in resultado.get("valores", ()):
for forma in (valor.get("etiqueta", ""), *valor.get("alias", ())):
clave = " ".join(fold(forma).split())
if de.get(clave, valor["valor"]) != valor["valor"]:
raise CatalogoInvalido(
f"{resultado_id}: {forma!r} se escribe igual para {de[clave]!r} y {valor['valor']!r}."
)
de[clave] = valor["valor"]
try:
check_function(from_result(resultado_id, resultado))
except ValueError as e:
raise CatalogoInvalido(str(e)) from None
def _leer(ruta: Path) -> dict:
@@ -0,0 +1,98 @@
"""How a source writes the catalog's values: a partial, non-injective function into a fixed set of codes.
A source form (a spelling, an abbreviation, a lab's own code) maps to one `valor_id` of one result:
f : (source system, resultado_id, normalized form, document date) -> valor_id
- non-injective: many forms give the same code ("3+", "Positivo (score 3)" -> H3);
- partial: a form with no mapping gives nothing, and the observation keeps it as `valor_fuente`, counted as out of
catalog, until a mapping is added;
- per source system and per date: the same form may mean different codes at two labs, and a mapping applies to the
documents dated within its validity;
- into a fixed set: a mapping only names a `valor_id` the catalog defines (`cat_valor`).
For `f` to be a function, two mappings in force on the same date can't give the same key two codes:
`check_function` rejects that, and `resolve` returns nothing for a key it still finds ambiguous, so the observation
goes back to the out-of-catalog queue instead of keeping a code. Today the mappings come from the catalog's TOML
(`from_result`: one system, always in force); any other store of mappings gives `SourceForm` rows and is checked
and read the same way.
"""
from collections import defaultdict
from datetime import date
from typing import Iterable, NamedTuple
from extraction.nlp.text import fold
CATALOG = "catalogo" # the source system of the mappings written in the catalog's TOML
class SourceForm(NamedTuple):
"""One mapping: how `system` writes `value_id` of `result_id`, in force from `valid_from` to `valid_to`."""
system: str
result_id: str
form: str
value_id: str
valid_from: date | None = None # None: since always
valid_to: date | None = None # None: while current
@property
def key(self) -> tuple[str, str, str]:
return self.system, self.result_id, normalize(self.form)
def in_force(self, on: date | None) -> bool:
return on is None or ((self.valid_from is None or self.valid_from <= on)
and (self.valid_to is None or on <= self.valid_to))
class AmbiguousForm(NamedTuple):
"""Two mappings of the same key whose validities overlap and whose codes differ."""
first: SourceForm
second: SourceForm
def normalize(form: str) -> str:
"""What is compared: uppercase, without accents, single spaces."""
return " ".join(fold(form).split())
def ambiguities(rows: Iterable[SourceForm]) -> list[AmbiguousForm]:
"""Every pair of mappings that would give one key two codes on some date."""
by_key: dict[tuple, list[SourceForm]] = defaultdict(list)
for row in rows:
by_key[row.key].append(row)
found = []
for same_key in by_key.values():
for i, a in enumerate(same_key):
found += [AmbiguousForm(a, b) for b in same_key[i + 1:] if a.value_id != b.value_id and _overlap(a, b)]
return found
def check_function(rows: Iterable[SourceForm]) -> None:
"""Raises `ValueError` naming each form that maps to two codes while both mappings are in force."""
found = ambiguities(rows)
if found:
raise ValueError("; ".join(f"{a.first.result_id}: {a.first.form!r} se escribe igual para "
f"{a.first.value_id!r} y {a.second.value_id!r}" for a in found) + ".")
def resolve(rows: Iterable[SourceForm], system: str, result_id: str, form: str, on: date | None = None) -> str | None:
"""The code `form` maps to on `on` for `system`; None when no mapping in force matches it or two disagree."""
key = (system, result_id, normalize(form))
codes = {r.value_id for r in rows if r.key == key and r.in_force(on)}
return codes.pop() if len(codes) == 1 else None
def from_result(result_id: str, result: dict, system: str = CATALOG) -> list[SourceForm]:
"""A catalog result's mappings: each value's code, label and aliases, in force always."""
return [SourceForm(system, result_id, form, value["valor"])
for value in result.get("valores", ())
for form in (value["valor"], value.get("etiqueta", ""), *value.get("alias", ())) if form.strip()]
def _overlap(a: SourceForm, b: SourceForm) -> bool:
starts_before_b_ends = a.valid_from is None or b.valid_to is None or a.valid_from <= b.valid_to
b_starts_before_a_ends = b.valid_from is None or a.valid_to is None or b.valid_from <= a.valid_to
return starts_before_b_ends and b_starts_before_a_ends