83 lines
3.0 KiB
Python
83 lines
3.0 KiB
Python
"""La definición de una cohorte, de su TOML: FHIR `Group` definicional más sus `EvidenceVariable`.
|
|
|
|
Igual que un Measure: la definición es un archivo (`<proyecto>/<nombre>.toml`),
|
|
las reglas clínicas son datos (`[group.reglas]`) y la función que arma el marco se
|
|
nombra con `expression` (`modulo:funcion`, relativo a `models.cohorts`).
|
|
"""
|
|
|
|
import hashlib
|
|
import json
|
|
import tomllib
|
|
from dataclasses import dataclass
|
|
from importlib import import_module
|
|
from pathlib import Path
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parent # `<proyecto>/<nombre>.toml`, next to its rule module
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Variable:
|
|
nombre: str
|
|
rol: str # outcome o covariate
|
|
tipo: str # numero o codigo
|
|
titulo: str
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Definition:
|
|
url: str
|
|
version: str
|
|
titulo: str
|
|
expression: str
|
|
desenlace: str
|
|
reglas: dict
|
|
variables: tuple[Variable, ...]
|
|
definicion_sha: str # sha256 del TOML
|
|
|
|
@property
|
|
def reglas_sha(self) -> str:
|
|
return json_sha(self.reglas)
|
|
|
|
def function(self):
|
|
"""La función que arma el marco: `funcion(filas_de_linea, reglas, inicio, fin, corte)`."""
|
|
return function_of(self.expression)
|
|
|
|
|
|
def json_sha(objeto) -> str:
|
|
"""sha256 del JSON canónico: claves ordenadas, sin espacios."""
|
|
texto = json.dumps(objeto, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str)
|
|
return hashlib.sha256(texto.encode("utf-8")).hexdigest()
|
|
|
|
|
|
def cohort_path(proyecto: str, nombre: str, *, propuesta: bool = False) -> Path:
|
|
"""A cohort's TOML. `propuesta`: from `<proyecto>/proposals/`, which the cycle doesn't build."""
|
|
return ROOT / proyecto / ("proposals" if propuesta else "") / f"{nombre}.toml"
|
|
|
|
|
|
def read_definition(ruta: Path) -> Definition:
|
|
texto = ruta.read_text(encoding="utf-8")
|
|
doc = tomllib.loads(texto)
|
|
g = doc["group"]
|
|
reglas = dict(g["reglas"])
|
|
if "no_prevalente" in reglas: # regla de CaCu: su `description` es texto, no regla
|
|
reglas["no_prevalente"] = {k: v for k, v in reglas["no_prevalente"].items() if k != "description"}
|
|
variables = tuple(Variable(v["name"], v["role"], v["tipo"], v["title"]) for v in doc["evidenceVariable"])
|
|
nombres = [v.nombre for v in variables]
|
|
if len(set(nombres)) != len(nombres):
|
|
raise ValueError(f"{g['url']}: variables repetidas.")
|
|
return Definition(
|
|
url=g["url"], version=g["version"], titulo=g["title"], expression=g["expression"],
|
|
desenlace=g["desenlace"], reglas=reglas, variables=variables,
|
|
definicion_sha=hashlib.sha256(texto.encode("utf-8")).hexdigest(),
|
|
)
|
|
|
|
|
|
def function_of(expresion: str):
|
|
"""The function of `module:function`, relative to `models.cohorts`. Fails if the module doesn't define it."""
|
|
modulo, nombre = expresion.split(":")
|
|
function = getattr(import_module(f"models.cohorts.{modulo}"), nombre, None)
|
|
if not callable(function):
|
|
raise ValueError(f"{modulo} debe definir la función {nombre}.")
|
|
return function
|