"""Dagster code location: every heavy step of the platform is a job defined here.""" import hashlib import importlib import inspect import io import json import zipfile from collections.abc import Callable from datetime import date import dagster as dg from core.domains import Domain from models import execution, graph from models.jobs import EmptyCohort from models.tea import jobs as tea_jobs from models.tea import preview as tea_preview_analysis from persistance import bundle, cluster, config_log, eeg, previews, silver WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a time (SQLite) class ExecutionConfig(dg.Config): """Where a heavy op's work runs: the fields of `persistance.cluster.Execution`.""" mode: str | None = None # Dagster's config has no Literal: `model()` checks it scheduler: str | None = None def model(self) -> cluster.Execution: return cluster.Execution(**self.model_dump()) class ScopeConfig(dg.Config): """Which EEGs an analysis takes: the fields of `persistance.eeg.Scope`.""" mode: str = "pending" # Dagster's config has no Literal: `model()` checks it n: int | None = None ids: list[str] = [] def model(self) -> eeg.Scope: return eeg.Scope(**self.model_dump()) # validates 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..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 ReferenceConfig(dg.Config): name: str line_hz: int = 50 def model(self) -> cluster.Reference: return cluster.Reference(**self.model_dump()) 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) execution: ExecutionConfig = ExecutionConfig() reference: ReferenceConfig | None = None @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 options = {} if config.reference is not None: if "reference" not in inspect.signature(jobs.train).parameters: raise ValueError(f"{config.domain} models take no reference cohort") options["reference"] = config.reference.model() found = {} with execution.running(context, config.execution.model()): for name in config.models or jobs.JOBS.routine(): try: found[name] = jobs.train(name, as_of, **options) 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 execution: ExecutionConfig = ExecutionConfig() @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).""" with execution.running(context, config.execution.model()): found = _jobs(config.domain).analyze() context.log.info(f"{config.domain}: {found} analysed") return found @dg.job(tags=WRITES) def analyze(): analyze_studies() class TeaAnalysis(dg.Config): scope: ScopeConfig = ScopeConfig() execution: ExecutionConfig = ExecutionConfig() @dg.op def tea_analyze_studies(context: dg.OpExecutionContext, config: TeaAnalysis) -> dict: """The EEGs in scope, analysed in the chosen execution. Bronze is written after the last study, so a cancel during the analysis leaves it as it was.""" with execution.running(context, config.execution.model()): found = tea_jobs.analyze(config.scope.model(), rebuild_gold=False) context.log.info(f"{found} EEGs analysed (scope {config.scope.mode})") return {"analysed": found} @dg.op def tea_score_curves(context: dg.OpExecutionContext, analysed: dict) -> dict: """Each age curve's champion scores every analysed EEG.""" found = tea_jobs.score_curves() for name, version in found.items(): context.log.info(f"{name}: " + (f"version {version}" if version else "no champion")) return {"scored": found} @dg.op def tea_relate_ados2(context: dg.OpExecutionContext, scored: dict) -> dict: """The ADOS-2 association champion scores the EEGs (a seam: nothing until Phase 2).""" version = tea_jobs.relate() context.log.info("ados2_association: " + (f"version {version}" if version else "no champion")) return {"ados2_association": version} @dg.op def tea_build_gold(context: dg.OpExecutionContext, related: dict) -> dict: """Gold's TEA tables rebuilt from bronze. A cancel here stops dbt between models, so gold may be partly rebuilt until the next successful run (dbt replaces each model whole).""" silver.build(tea_jobs.GOLD_SELECT) context.log.info("gold rebuilt") return {"built": tea_jobs.GOLD_SELECT} class Preview(dg.Config): edf: str ados2: str | None = None birth_date: str | None = None pipeline: str = "tea" @dg.op def preview_study(context: dg.OpExecutionContext, config: Preview) -> dict: try: previews.sweep() result = tea_preview_analysis.preview( previews.get(config.edf), previews.get(config.ados2) if config.ados2 else None, date.fromisoformat(config.birth_date) if config.birth_date else None, config.pipeline, ) context.add_output_metadata( {"result": dg.MetadataValue.json(json.loads(result.model_dump_json()))} ) for warning in result.warnings: context.log.warning(warning) return {"valid": result.eeg.valid, "warnings": len(result.warnings)} finally: previews.discard([config.edf, config.ados2]) @dg.job(tags={"domain": "tea"}) def tea_preview(): preview_study() @dg.job(tags={**WRITES, "domain": "tea"}) def tea_eeg(): """Analyse the EEGs in scope, score the age curves, relate ADOS-2, rebuild gold.""" tea_build_gold(tea_relate_ados2(tea_score_curves(tea_analyze_studies()))) def pending_eegs() -> bool: return bool(eeg.pending()) def after_ingest(run_id: str, has_pending: Callable[[], bool]) -> dg.RunRequest | dg.SkipReason: """A `tea_eeg` run for an ingest that left EEGs to analyse; otherwise a skip.""" if not has_pending(): return dg.SkipReason("the ingest brought no EEG to analyse") return dg.RunRequest( run_key=f"after-ingest-{run_id}", run_config={"ops": {"tea_analyze_studies": {"config": {"scope": {"mode": "pending"}}}}}, tags={"domain": "tea", "triggered_by": run_id}, ) @dg.run_status_sensor( name="tea_eeg_after_ingest", run_status=dg.DagsterRunStatus.SUCCESS, monitored_jobs=[ingest], request_job=tea_eeg, minimum_interval_seconds=10, default_status=dg.DefaultSensorStatus.RUNNING, ) def tea_eeg_after_ingest(context: dg.RunStatusSensorContext): return after_ingest(context.dagster_run.run_id, pending_eegs) class BundleImport(dg.Config): domain: str sha256: str @dg.op def import_bundle_files(context: dg.OpExecutionContext, config: BundleImport) -> dict: path = bundle.staged(config.sha256) try: data = path.read_bytes() if hashlib.sha256(data).hexdigest() != config.sha256: raise bundle.BundleError("the staged file's SHA-256 does not match the run config") result = bundle.import_(Domain(config.domain), data) finally: path.unlink(missing_ok=True) with zipfile.ZipFile(io.BytesIO(data)) as archive: manifest = json.loads(archive.read(bundle.MANIFEST)) skipped = set(result.skipped) sources = sorted( (item["name"], item["version"]) for item in manifest["versions"] if (item["name"], item["version"]) not in skipped ) for (_, source), (name, version) in zip(sources, result.imported, strict=True): context.log.info(f"{name}: source v{source} -> version {version}") for name, version in result.skipped: context.log.warning(f"{name} v{version}: already registered, skipped") return { "imported": [list(item) for item in result.imported], "skipped": [list(item) for item in result.skipped], } @dg.job def import_bundle(): import_bundle_files() defs = dg.Definitions( jobs=[ingest, train, score, analyze, tea_eeg, tea_preview, import_bundle], sensors=[tea_eeg_after_ingest], )