71 lines
3.3 KiB
Python
71 lines
3.3 KiB
Python
"""Builds a cohort: all patients -> index date -> A1 -> ... -> An -> study population.
|
|
|
|
Lists the steps of `models.steps.cohort`, gives each rule its own `em_<rule>` and `a_<rule>` node, and runs them.
|
|
"""
|
|
|
|
import types
|
|
|
|
from hamilton import ad_hoc_utils, driver
|
|
from hamilton.function_modifiers import group, inject, parameterize, source, value
|
|
|
|
from persistance.aristas.dbt import DbtQueryRepository
|
|
|
|
from models.io.contracts import BuiltCohort, CohortQueries
|
|
from models.steps.cohort import all_patients, attrition, excluded, indexed, remaining, study_population
|
|
|
|
INPUTS = ("cohort_queries", "dbt_queries")
|
|
|
|
|
|
def _fresh(function):
|
|
"""A copy to decorate: Hamilton keeps a decorator on the function itself, so decorating the step would carry it into
|
|
the next build."""
|
|
copy = types.FunctionType(function.__code__, function.__globals__, function.__name__, function.__defaults__,
|
|
function.__closure__)
|
|
copy.__annotations__, copy.__doc__ = dict(function.__annotations__), function.__doc__
|
|
copy.__module__, copy.__qualname__ = function.__module__, function.__qualname__
|
|
return copy
|
|
|
|
|
|
def build_driver(queries: CohortQueries) -> driver.Driver:
|
|
"""The chain for the cohort's rules, in their order."""
|
|
rules = list(queries.rules)
|
|
previous = ["indexed", *[f"a_{rule.name}" for rule in rules[:-1]]]
|
|
nodes = [
|
|
all_patients,
|
|
indexed,
|
|
parameterize(**{f"em_{rule.name}": {"rule": value(rule)} for rule in rules})(_fresh(excluded)),
|
|
parameterize(**{f"a_{rule.name}": {"population": source(before), "flagged": source(f"em_{rule.name}")}
|
|
for rule, before in zip(rules, previous)})(_fresh(remaining)),
|
|
inject(last=source(f"a_{rules[-1].name}"))(_fresh(study_population)),
|
|
inject(populations=group(*[source(f"a_{rule.name}") for rule in rules]), rules=value(rules))(_fresh(attrition)),
|
|
]
|
|
return driver.Builder().with_modules(ad_hoc_utils.create_temporary_module(*nodes)).build()
|
|
|
|
|
|
def build_cohort(queries: CohortQueries, dbt_queries: DbtQueryRepository) -> BuiltCohort:
|
|
"""Runs the chain; `dbt_queries` is the domain's `dbt_query_repository`."""
|
|
results = build_driver(queries).execute(["study_population", "attrition"],
|
|
inputs={"cohort_queries": queries, "dbt_queries": dbt_queries})
|
|
return BuiltCohort(results["study_population"], results["attrition"])
|
|
|
|
|
|
def mermaid(graph) -> str:
|
|
"""The chain as a Mermaid diagram, read from the graph without running it."""
|
|
def label(name: str) -> str:
|
|
if name.startswith("em_"):
|
|
return f'{name}["EM: {name[3:]}"]'
|
|
if name.startswith("a_"):
|
|
return f'{name}["A: {name[2:]}"]'
|
|
return f"{name}[({name})]" if name in ("all_patients", "study_population") else f"{name}[{name}]"
|
|
|
|
lines = ["graph LR"]
|
|
for node in graph.nodes.values():
|
|
if node.name in INPUTS or node.name == "attrition":
|
|
continue
|
|
if node.name.startswith("em_"):
|
|
lines.append(f' r_{node.name[3:]}[/"R: {node.name[3:]}"/] --> {label(node.name)}')
|
|
lines += [f" {dependency.name} --> {label(node.name)}" for dependency in node.dependencies
|
|
if dependency.name not in INPUTS]
|
|
lines += [f" {dependency.name} -.-> attrition" for dependency in graph.nodes["attrition"].dependencies]
|
|
return "\n".join(lines)
|