73cbf0cfb8
How: `catalog_rows` turns the TOML's study codes, captions and each value's code, label and aliases into the `catalogo` system's rows; the `catalogs` step adds the system and the forms with no row yet (`mapeos_nuevos`). `register` normalizes the form and adds the row through `SourceMappingRepository.add` with `check_stored`, which runs `check_function` on the stored rows of the same form; captions aren't checked, since one caption may introduce several results. `ctx.repos.silver.mappings` is the domain's repository. Implications: the database keeps every mapping across deploys; a person's change is never overwritten, and a second code for a form in force is refused before it's written. Loads still read the TOML's aliases.
159 lines
7.7 KiB
Python
159 lines
7.7 KiB
Python
"""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.
|
|
|
|
The mappings are stored in `cat_sistema_fuente` and `cat_mapeo`: the `catalogs` step seeds the catalog's own
|
|
(`catalog_rows`, system `catalogo`, always in force) and never changes a stored row, and `register` adds one after
|
|
checking it against the rows of the same form.
|
|
"""
|
|
|
|
import tomllib
|
|
from collections import defaultdict
|
|
from datetime import date, datetime, timezone
|
|
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
|
|
|
|
|
|
# --- the mappings stored in `cat_sistema_fuente` and `cat_mapeo` ---
|
|
|
|
CATALOG_SINCE = date(1900, 1, 1) # the catalog's own mappings hold for every document
|
|
|
|
|
|
def as_source_form(row) -> SourceForm:
|
|
"""A `cat_mapeo` row as the function sees it: a study code maps to its `estudio_id`, a spelling to its value."""
|
|
return SourceForm(row.sistema_fuente_id, row.resultado_id or "", row.forma, row.valor_id or row.estudio_id,
|
|
row.vigente_desde, row.vigente_hasta)
|
|
|
|
|
|
def check_stored(same_form: list, new) -> None:
|
|
"""`SourceMappingRepository.add`'s check: a study code or a spelling stays a function with the new row. A
|
|
caption may introduce several results (a receptor and its percentage), so it isn't checked."""
|
|
if new.clase == "etiqueta":
|
|
return
|
|
check_function([as_source_form(r) for r in same_form if r.clase == new.clase] + [as_source_form(new)])
|
|
|
|
|
|
def register(repository, *, sistema_fuente_id: str, clase: str, forma: str, registrado_por: str,
|
|
vigente_desde: date, estudio_id: str | None = None, resultado_id: str | None = None,
|
|
valor_id: str | None = None, motivo: str | None = None):
|
|
"""Adds one mapping, rejected with `ValueError` if it makes a form give two codes while both are in force."""
|
|
row = repository.model(
|
|
sistema_fuente_id=sistema_fuente_id, clase=clase, forma=forma.strip(), forma_normalizada=normalize(forma),
|
|
estudio_id=estudio_id, resultado_id=resultado_id, valor_id=valor_id, vigente_desde=vigente_desde,
|
|
registrado_por=registrado_por, registrado_en=datetime.now(timezone.utc), motivo=motivo)
|
|
return repository.add(row, check=check_stored)
|
|
|
|
|
|
def catalog_rows(project: str, repository) -> tuple[object, list]:
|
|
"""The catalog's source system and its mappings, from the TOML: study codes, captions, and each value's code,
|
|
label and aliases. What `SourceMappingRepository.seed` adds when they're missing."""
|
|
from webapi.orchestration.reference.catalogs import ruta_de_catalogo
|
|
|
|
system = repository.sistema(sistema_fuente_id=CATALOG, etiqueta="Catálogo del proyecto", fuente_tabla=None,
|
|
vigente_desde=CATALOG_SINCE)
|
|
now = datetime.now(timezone.utc)
|
|
rows = {}
|
|
|
|
def add(clase, forma, **target):
|
|
row = repository.model(sistema_fuente_id=CATALOG, clase=clase, forma=forma, forma_normalizada=normalize(forma),
|
|
vigente_desde=CATALOG_SINCE, registrado_por=CATALOG, registrado_en=now, **target)
|
|
rows.setdefault((clase, target.get("resultado_id"), target.get("estudio_id"), row.forma_normalizada), row)
|
|
|
|
for study_id, study in tomllib.loads(ruta_de_catalogo(project).read_text(encoding="utf-8")).items():
|
|
for code in study.get("codigos_hospital", ()):
|
|
add("estudio", code, estudio_id=study_id)
|
|
for name, result in study.get("resultados", {}).items():
|
|
result_id = f"{study_id}.{name}"
|
|
for caption in result.get("etiquetas_fuente", ()):
|
|
add("etiqueta", caption, resultado_id=result_id)
|
|
for form in from_result(result_id, result):
|
|
add("valor", form.form, resultado_id=result_id, valor_id=form.value_id)
|
|
return system, list(rows.values())
|