The catalog step seeds each domain's mappings, and a mapping is written only if the function still holds
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.
This commit is contained in:
@@ -13,13 +13,16 @@ A source form (a spelling, an abbreviation, a lab's own code) maps to one `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.
|
||||
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
|
||||
from datetime import date, datetime, timezone
|
||||
from typing import Iterable, NamedTuple
|
||||
|
||||
from extraction.nlp.text import fold
|
||||
@@ -96,3 +99,60 @@ 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())
|
||||
|
||||
Reference in New Issue
Block a user