195 lines
6.0 KiB
Python
195 lines
6.0 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 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()
|
|
|
|
|
|
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.scored()}
|
|
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 CacuDevelopmentEvaluation(dg.Config):
|
|
as_of: str
|
|
max_fits: int = 100000
|
|
|
|
|
|
@dg.op
|
|
def evaluate_cacu_development(
|
|
context: dg.OpExecutionContext, config: CacuDevelopmentEvaluation
|
|
) -> str:
|
|
"""Opt-in research evaluation only: no registered model, promotion or patient scores."""
|
|
import mlflow
|
|
import pandas as pd
|
|
|
|
from core import cacu
|
|
from models.cacu import encoders, features
|
|
from models.cacu.development_selection import evaluate
|
|
from persistance import gold, registry
|
|
|
|
as_of = date.fromisoformat(config.as_of)
|
|
cohort = "cacu_cohort_surveillance"
|
|
events = gold.evidence_timelines("cacu_events", cohort, as_of)
|
|
if events.empty:
|
|
raise EmptyCohort(f"no eligible patients in {cohort}")
|
|
encoded = encoders.encode(events, gold.cervical_forms(cohort))
|
|
outcome = features.windowed_outcome(
|
|
features.prepared(events), cacu.CIN2_PLUS, 1.0, pd.Timestamp(as_of)
|
|
)
|
|
rows = encoded.merge(outcome, on="person_id", validate="one_to_one")
|
|
rows = rows[rows["known"]].reset_index(drop=True)
|
|
X = rows.drop(columns=["person_id", "index_date", "known", "y"])
|
|
report = evaluate(X, rows["y"].to_numpy(), max_fits=config.max_fits)
|
|
report.update(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("Development evaluation logged as %s", run.info.run_id)
|
|
return run.info.run_id
|
|
|
|
|
|
@dg.job
|
|
def cacu_development_evaluation():
|
|
evaluate_cacu_development()
|
|
|
|
|
|
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()
|
|
|
|
|
|
@dg.op
|
|
def build_gold(context: dg.OpExecutionContext) -> None:
|
|
"""Silver and everything derived from it, with the deployed code: what an ingest ends
|
|
with, without ingesting (after deploying a version that changes the tables)."""
|
|
silver.build(["silver+", "+nci_risk_lookup", "nci_risk_estimate"])
|
|
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 []
|
|
)
|
|
|
|
defs = dg.Definitions(
|
|
jobs=[ingest, train, score, analyze, rebuild, backup, cacu_development_evaluation],
|
|
schedules=nightly,
|
|
)
|