models

Lo que rodea a los modelos de riesgo de CaCu, CaMa y TEA: registro de versiones en MLflow con requisitos de promoción, registro de predicciones y los trabajos de OCR de reportes. Las cohortes se definen solo en dbt (Transformation/models/<dominio>/cohorts/); el ciclo de la WebApi guarda un armado de ellas (cohorte_armado, en la base de cada dominio, por models/cohorts/build.py), y con ese armado se entrena y se estima. Las reglas que no caben en SQL son del modelo, sobre cacu/cohorte_total. Lee y escribe por los mismos repositorios de Persistance que usa WebApi.

Módulo Qué hace
__main__.py La línea de comandos: python -m models <comando>. Cada área agrega ahí sus subcomandos.
io/contracts.py The shapes of the data: a cohort build's file (COHORT_SCHEMA), a cohort's rules (ExclusionRule, CohortQueries, BuiltCohort), an estimate's output (ESTIMATE_COLUMNS) and the risk contract (Risk, Provenance, RiskEstimator, which still takes the wide frame).
io/storage.py Where data lives and how it's read and written: cohort and estimate Parquet files (read_cohort, write_once, read_metadata) and their hashes (file_sha256, table_sha256, cohort_reference), dbt's manifest (read_queries), Persistance repositories, the risk batches, and the cohort sources a model trains and estimates on: KitBuild, a kit build read now from the domain's database (nothing written), or CohortFile, an exported file, behind one contract (frame, lineage, reference).
io/lineage.py What each output came from, in one vocabulary: registered names, tag keys, the code's version (the installed models package, code_version), a model's hash (model_sha), and matches, the one rule for "already done".
io/tracking.py TrainingRun: an MLflow run, with its cohort link (ML-03), artifacts (ML-01), environment (ML-02), the models version, and log_model with its modelo_sha (a scikit-learn estimator, served through predict_proba, or a pyfunc). In PROD, only models whose class lives in a module. inspect_onnx_metadata checks an ONNX checkpoint before it's logged. log_routine records what each routine around training did, as it runs (ML-01a): one JSON per kind in ROUTINE_KINDS (MUESTREO, DATOS_FALTANTES, METODO_ANALITICO, BALANCE_CLASES, CONFIANZA_SALIDA) under rutinas/, counts and settings only. run_files/run_file list and download a run's files (a folder as a zip).
io/registry.py registry: versiones en MLflow (<dominio>-<escenario>), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03, y ML-01a/ML-01b: las cinco rutinas y el modelo, escritos por la propia corrida) y el alias produccion. artifacts/artifact listan y descargan los archivos de una versión (ML-01b). Registers a finished run as a version (register_run) and sets its description. PredictionService stores each single prediction with the version in production (MLD-4/5, EL-04b).
steps/ Funciones puras que comparten todos los modelos: sin E/S, se prueban solas.
pipelines/reading.py Los nodos de Hamilton con que lee todo DAG de un modelo: cohort_build, members, known_until y timeline (la línea de tiempo de los miembros, cortada en datos_as_of del armado y en known_until: su conocida_hasta o, si no tiene, el momento de la lectura). Los repositorios entran como insumos.
steps/cohort.py, steps/cohort_file.py The plain functions the cohort pipelines list: the chain's steps, and from a population and the timeline to the file's table, its hash and its lineage.
pipelines/cohort_build.py Builds a cohort: all patients → index date → A1 → … → An → study population. Lists the steps, gives each rule its own nodes and runs them. python -m models cohorts build cacu cohorte_vigilancia --manifest target/manifest.json [--graph] shows the attrition or the Mermaid diagram; it stores nothing.
pipelines/export_cohort.py Exports a build to its Parquet file. python -m models cohorts export cacu cohorte_vigilancia [--build N] writes the kit's build once; --source dbt --manifest target/manifest.json builds it from dbt's rules into dbt/<n>.parquet and writes only when its rows change. The timeline comes from dbt's view <domain>_linea_de_tiempo.
cohorts list, cohorts show python -m models cohorts list cacu cohorte_vigilancia [--source kit|dbt] lists the builds of both sources, newest first, and whether each has its file (dbt's from their files alone); cohorts show … --source kit|dbt --build N prints one build's file, hash, parameters, rules and attrition as JSON (io/storage.py: list_builds, describe_build).
steps/risks.py, pipelines/store_risks.py Stores an estimate file as a batch of risks in the domain's database (evaluacion_riesgo_lote, evaluacion_riesgo), through cohorte_repository: one preliminary risk per member and horizon, with the version's MLflow keys. Storing the same estimate again adds nothing. A batch points to a kit build (armado_id), so estimates of dbt builds are refused. python -m models store cacu cin2_logistic --input file.parquet, or run … --estimate --store --output file.parquet.
reports/ (rendering.py, eda.py) A model's exploratory notebook as an MLflow report: python -m models report eda cacu cin2_logistic [--source kit|dbt] [--build N] [--notebook path] [--kernel name] runs <scenario>/notebooks/01_eda.ipynb on the build's file (COHORT_FILE), renders it with Quarto to one HTML page, and logs the page and the notebook without outputs as a run of the experiment <domain>-<scenario>/<notebook>, tagged with the notebook's content hash and the build's file. The same notebook and file are reported once. Needs Quarto (QUARTO_BIN) and a Python with Jupyter (QUARTO_PYTHON). Rendering: Runs a notebook and renders its page. Renderers are classes (RENDERERS, register_renderer): quarto and jupyter (nbclient + nbconvert, the notebooks extra). NOTEBOOK_RENDERER picks one; otherwise Quarto if installed, else Jupyter. NOTEBOOK_CELL_TIMEOUT limits each cell (1800 s).
reports/experiment.py A notebook uploaded to the platform, run on one exported cohort build as a run of <domain>-<scenario>/experimentos: the notebook, its page, what was imported from it (importado.json), error.txt if it failed, and tags for the notebook's hash, the build's file, the version, the code and where it ran (sandbox). start and execute are separate so the WebApi runs it in the background.
reports/notebook_jobs.py Where the notebook runs: a job folder with the notebook, a copy of the build's file and of the chosen model, and an MLflow store of its own; every database URL is an empty in-memory one. Executors: contenedor leaves the job in NOTEBOOK_JOBS_DIR for the runner (python -m models notebooks serve, the notebooks container: no network, read-only, unprivileged, only that folder); local runs it in this process, unisolated, for development.
reports/notebook_import.py Copies what the notebook trained in its own store into the platform's MLflow, as DEV runs and versions with the build's real cohort tags and a recomputed modelo_sha, never with an alias; refuses symbolic links and anything outside the job folder.
io/extraction_ranker.py Each domain's document extraction ranker (extraction.nlp.ranking.LearnedRanker) as the model <domain>-extraccion: every batch it learns from (an answer key, or the corrections made while reviewing an import) is a new DEV version continuing the latest, with its five routine records, its weights (ranker/ranker.json) and its saved model. current gives the version in production, otherwise the latest; EXTRACTION_RANKER=produccion only takes production, ninguno turns it off. Weights over how candidates were found and counts only, never document text.
notebook.py What a notebook uses inside: experiment() gives the build's rows (cohort()), its metadata, the chosen version loaded (model()), a DEV TrainingRun linked to the build (training_run()) and register(run).
io/adapters.py Hamilton's boundary with storage and MLflow, attached by the driver with with_materializers: the loaders cohort_source and cohort_source_lineage (any source) and the saver registered_model, which logs a scenario's fitted_model in the open TrainingRun, records its metrics (numbers only) and config, registers and describes the version. The packages of the model's own classes are pickled by value, so a version loads without this repository.
annotations.py Validators a dataflow puts on its nodes, with no I/O: @checked_frame(schema), a pandera check whose failure names columns and counts, never values.
dags/training.py, dags/estimation.py Training and estimating any scenario: Scenario reads model.toml (its modules, the graph's nodes, and [config]); the driver is with_modules(*modules) with the config, a source's loaders and the saver; find_trained (same source reference, models version, config and environment) before anything runs; a failing node's inputs are kept out of the log. Estimation runs the registered model's predict_proba on the source's frame and writes one row per member and horizon. python -m models train|estimate|run … [--read db|file]: a kit build is read from the database by default.
steps/model_fitting.py The classifier steps scenarios share: the temporal split, the classifier chosen by config, the fit and its metrics.
cacu/cin2_logistic/ CaCu's CIN2+ prototype: the probability of a CIN2+ biopsy within one year (horizons_years, provisional) of the index cytology, from the index sample's Bethesda, HPV and HPV 16/18 results; no clinical validation. model.toml (names, modules: its model.py and steps/model_fitting.py, and [config]) and model.py (the dataflow to labelled_members, and fitted_model: a scikit-learn Pipeline that takes the long frame). Its routines' records (ML-01a: sampling, missing_data, analytic_method, class_balance, output_confidence) are nodes too, and the saver writes them; train.py only delegates to dags/training.py. Train with `python -m models train cacu cin2_logistic [--source kit
cacu/cin2_pim/ CaCu's CIN2+ prevalence–incidence prototype: the cumulative risk at the index visit and at 1, 3 and 5 years. PrevalenceIncidenceMixture, a scikit-learn estimator (logistic prevalence, Weibull or I-spline incidence, likelihood.py), one mixture per HPV stratum, fitted to each member's code and interval; the clinical settings (windows, known-negative results, KPNC's cytology categories, the incidence family) in model.toml. No correction of verification bias, no clinical validation. Same commands as cin2_logistic.
cacu/cin2_pim_post_colposcopy/, cacu/cin2_pim_post_treatment/ cin2_pim's dataflow on the post-colposcopy and post-treatment cohorts (KPNC's scenarios 4 and 5): only a model.toml, with KPNC's three post-colposcopy cytology groups and, after colposcopy, the referral grade (history).
cacu/, cama/, tea/ Un paquete por dominio, con sus escenarios. Cada escenario lleva sus cuadernos en <escenario>/notebooks/, fuera del paquete instalado.
tea/eeg/ TEA's EEG analysis on one EDF, with the tea library (libs/tea, a submodule installed editable): model.toml maps each MetricaEeg code to a library feature, provisional until the domain expert confirms it (spindles once per sleep stage, with their value per electrode); analyze.measure runs validation, preprocessing, the processes and the biomarkers on the EDF's bytes, without the database, so a Dask worker can run it; baselines.Baselines compares a value with its age baseline in production (tea-eeg-<biomarker>[-<stage>]): z, -1/0/+1 and the curve's p5/median/p95 at the age.
tea/eeg/train.py, tea/eeg/model.py TEA's age baselines: python -m models run tea eeg --train [--promote] [--environment prod] lists the reference cohort ([reference] of model.toml: HK1K, 16 to 36 months, 50 Hz mains) in a Dask worker from the cluster's S3 (the eeg-reference extra), measures each study with the analysis's own unit of work (analyze.reference), and trains each scenario (biomarker and sleep stage) with the library, registered as tea-eeg-<biomarker>[-<stage>] through tea.serving.log_biomarker and tagged with what promotion checks: environment, the reference cohort (cohort.source = referencia, the listing's hash: ML-03), the trained state's hash (ML-01b), the five routine records (ML-01a) and metrics. A scenario already trained on the same listing, plan, module version and baseline isn't trained again. Promotion waits for the technical, clinical and interpretability reports, like any model. It must register in the MLflow the platform reads (MLFLOW_TRACKING_URI); with a remote scheduler (DASK_SCHEDULER_ADDRESS), the workers need models and tea installed.
tea/eeg/reference.py, tea/eeg/bundle.py Training the baselines where the EEGs live and shipping only the result. models run tea eeg --train --reference-dir DIR [--reference-ages edades.csv] [--reference-name NAME] [--line-hz 60] trains on a folder of EDFs on this machine (ages from the table's archivo and edad_meses or edad_anos, or from each EDF header); file names stay in the listing, keyed by position. models tea export-baselines --out baselines.zip [--environment prod] [--production] writes every scenario's trained module, plan, routine records, metrics and promotion tags, with a SHA-256 manifest, after the library's privacy guard; models tea import-baselines baselines.zip checks the manifest, accepts only the module class the platform runs for each scenario, requires the trained module's hash, and registers new versions with the same tags (an already-registered module is kept). Promotion still waits for the three reports.
eeg_analysis.py The EEG analysis against TEA's database: the pending EEGs (an EDF never analysed, or analysed with another plan, other module versions or other baselines), the batch (cluster: this process, a LocalCluster or DASK_SCHEDULER_ADDRESS), each result written to eeg, eeg_criterio, eeg_metrica and eeg_metrica_electrodo with ids that survive a re-analysis, and one governance ExtractionRun per EEG. python -m models tea analyze [--all] [--limit N] [--cluster auto|local|remote|sync].
cama/seer_survival/ CaMa's SEER survival pipeline, ported from six scripts into Hamilton DAGs, one per stage (extra seer-survival). Settings in model.toml (settings.py); paths are inputs, never settings. Each stage is a module of nodes plus, where the routine is heavy, a module of plain functions apart (as tea/eeg/analyze.py): depuration.py + depuration_stats.py (01: Theil's U and GVIF redundancy screen and its threshold calibration), balancing.py + balancing_stats.py and categorization.py + categorization_stats.py (02: 18-month outcome, MCA undersampling, Bayesian change-point grouping of age and tumor size, categorization proposals), bootstrap.py (03: resample indices), modeling.py + lr_selection.py, hbn.py, natural.py, resampling.py + replica.py (04: stepwise LR, hybrid Bayesian network, natural-population LR, bootstrap and proposal replicas), survival_curves.py + survival_models.py, fractional_weibull.py (05: Kaplan-Meier, classic and Kilbas-Saigo Weibull, stacked LR + HBN survival, subgroups) and risk_factors.py + risk_factor_stats.py (06: four-criteria risk factors). run.py writes each stage's files; pipeline.py runs them in order, skipping the current ones: python -m models.cama.seer_survival --data DIR [--solo 05] [--desde 02] [--forzar 02 04] [--todo].
ocr.py Los trabajos de OCR (OCR_JOBS): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09).
testing.py Ayudas para las pruebas de otro código: CacuStandIn, un estimador determinista sin MLflow para correr la cadena de riesgos sin un modelo entrenado. No es un modelo clínico.

MLflow se configura con sus propias variables (MLFLOW_TRACKING_URI). MLFLOW_ARTIFACT_ROOT, si existe, es la carpeta donde los experimentos nuevos guardan sus artefactos.

uv run pytest -q
S
Description
No description provided
Readme 3.3 MiB
Languages
Python 100%