"""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