Files
models/models/definitions.py
T

210 lines
6.7 KiB
Python

"""Dagster code location: every heavy step of the platform is a job defined here."""
import importlib
import os
from datetime import date
import dagster as dg
from models import draft, graph
from models.jobs import EmptyCohort
from persistance import backup as backups
from persistance import config_log, silver
WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a time (SQLite)
class PipelineRun(dg.Config):
pipeline: str
version: int | None = None # default: the latest saved
@dg.op
def run_pipeline(context: dg.OpExecutionContext, config: PipelineRun) -> int:
"""Every node of the pipeline graph, inputs first. Returns the config version run."""
version, pipeline = config_log.get(config.pipeline, config.version)
context.log.info(f"{config.pipeline} v{version}: {len(pipeline.nodes)} nodes")
graph.run(config.pipeline, pipeline, log=context.log.info)
return version
@dg.job(tags=WRITES)
def ingest():
run_pipeline()
class DraftRun(dg.Config):
pipeline: str
run: bool = True # False: drawn and saved only (a large site, read later)
@dg.op
def draft_pipeline(context: dg.OpExecutionContext, config: DraftRun) -> int:
"""Automático: the whole pipeline drafted from its sources, saved as a new version and
run (unless `run` is off). Returns that version."""
drafted = draft.draft(config.pipeline, log=context.log.info)
version = config_log.save(config.pipeline, drafted)
context.log.info(f"{config.pipeline} v{version}: {len(drafted.nodes)} nodes drafted")
if config.run:
graph.run(config.pipeline, drafted, log=context.log.info)
return version
@dg.job(name="draft", tags=WRITES)
def draft_job():
draft_pipeline()
def _jobs(domain: str):
"""The domain's model jobs (`models.<domain>.jobs`: MODELS, train, score)."""
try:
return importlib.import_module(f"models.{domain}.jobs")
except ModuleNotFoundError as e:
raise ValueError(f"{domain} has no models") from e
class Training(dg.Config):
domain: str
models: list[str] = [] # default: every model of the domain
as_of: str | None = None # the date the data are taken up to (default: today)
@dg.op
def train_models(context: dg.OpExecutionContext, config: Training) -> dict:
"""A new registered version of each model (MLflow), with its reports."""
jobs = _jobs(config.domain)
as_of = date.fromisoformat(config.as_of) if config.as_of else None
found = {}
for name in config.models or jobs.JOBS.routine():
try:
found[name] = jobs.train(name, as_of)
except EmptyCohort as e: # the site has no such patients; the others still train
found[name] = None
context.log.warning(f"{e}: not trained")
continue
context.log.info(f"{config.domain}.{name}: version {found[name]}")
return found
@dg.job
def train():
train_models()
class Scoring(dg.Config):
domain: str
models: list[str] = [] # default: every model of the domain
@dg.op
def score_models(context: dg.OpExecutionContext, config: Scoring) -> dict:
"""Each model's champion scores its cohort; then gold's risk tables are rebuilt."""
jobs = _jobs(config.domain)
found = {name: jobs.score(name) for name in config.models or jobs.JOBS.routine()}
for name, version in found.items():
context.log.info(f"{name}: " + (f"version {version}" if version else "no champion"))
silver.build([getattr(jobs, "GOLD", f"{config.domain}_risk") + "+"])
return found
@dg.job(tags=WRITES)
def score():
score_models()
class Analysis(dg.Config):
domain: str
@dg.op
def analyze_studies(context: dg.OpExecutionContext, config: Analysis) -> int:
"""The domain's studies a model reads whole (TEA: each EEG not analysed yet)."""
found = _jobs(config.domain).analyze()
context.log.info(f"{config.domain}: {found} analysed")
return found
@dg.job(tags=WRITES)
def analyze():
analyze_studies()
class Development(dg.Config):
as_of: str
max_fits: int = 100_000
@dg.op
def evaluate_cacu_development(context: dg.OpExecutionContext, config: Development) -> str:
"""Opt-in research (models.cacu.development): which encoders predict CIN2+ at one year
in the surveillance cohort; logged to MLflow, nothing registered, promoted or scored."""
import mlflow
import pandas as pd
from core import cacu
from models.cacu import development, encoders, features
from persistance import gold, registry
as_of, cohort = date.fromisoformat(config.as_of), "cacu_cohort_surveillance"
events = gold.evidence_timelines("cacu_events", cohort, as_of)
if events.empty:
raise EmptyCohort(f"nobody in {cohort}")
outcome = features.windowed_outcome(features.prepared(events), cacu.CIN2_PLUS, 1.0,
pd.Timestamp(as_of)) # fmt: skip
rows = encoders.encode(events, gold.cervical_forms(cohort)).merge(outcome, on="person_id")
rows = rows[rows["known"]].reset_index(drop=True)
X = rows.drop(columns=["person_id", "index_date", "known", "y"])
report = development.evaluate(X, rows["y"].to_numpy(), max_fits=config.max_fits)
report |= {"cohort": cohort, "as_of": as_of.isoformat(), "outcome": "CIN2+ at one year"}
mlflow.set_experiment(registry.EXPERIMENT)
with mlflow.start_run(run_name="cacu.cin2_firth_development") as run:
mlflow.log_dict(report, "reports/development_evaluation.json")
context.log.info(f"development evaluation logged as {run.info.run_id}")
return run.info.run_id
@dg.job
def cacu_development_evaluation():
evaluate_cacu_development()
@dg.op
def build_gold(context: dg.OpExecutionContext) -> None:
"""Silver and all that derives from it, with the deployed code: an ingest's end without
ingesting (after deploying a version that changes the tables)."""
silver.build(["silver+"])
context.log.info("silver and gold rebuilt")
@dg.job(tags=WRITES)
def rebuild():
build_gold()
@dg.op
def make_backup(context: dg.OpExecutionContext) -> str:
"""The data folder into BACKUP_DIR (persistance.backup); the newest BACKUP_KEEP stay."""
folder = backups.create()
context.log.info(f"backup {folder}")
return str(folder)
@dg.job(tags=WRITES) # holds the writing slot: nothing writes while it copies
def backup():
make_backup()
# Nightly by default; BACKUP_SCHEDULE is a cron expression (empty: no schedule).
nightly = (
[
dg.ScheduleDefinition(
job=backup, cron_schedule=cron, default_status=dg.DefaultScheduleStatus.RUNNING
)
] # fmt: skip
if (cron := os.environ.get("BACKUP_SCHEDULE", "30 2 * * *"))
else []
)
JOBS = [ingest, draft_job, train, score, analyze, rebuild, backup, cacu_development_evaluation]
defs = dg.Definitions(jobs=JOBS, schedules=nightly)