Files
models/models/definitions.py
T
2026-11-29 06:43:08 -06:00

109 lines
3.2 KiB
Python

"""Dagster code location: every heavy step of the platform is a job defined here."""
import importlib
from datetime import date
import dagster as dg
from models import graph
from models.jobs import EmptyCohort
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 but the slow ones
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.models}
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()
defs = dg.Definitions(jobs=[ingest, train, score, analyze])