53 lines
2.5 KiB
Python
53 lines
2.5 KiB
Python
"""The steps of a cohort build: all patients, the index date, each rule's excluded members and what remains.
|
|
|
|
They know no rule by name: a pipeline gives each rule its own `excluded` and `remaining` node. The queries run through
|
|
the domain's `dbt_query_repository`.
|
|
"""
|
|
|
|
import pandas as pd
|
|
|
|
from persistance.aristas.dbt import DbtQueryRepository
|
|
|
|
from models.io.contracts import CohortDefinitionError, CohortQueries, ExclusionRule
|
|
|
|
|
|
def _frame(rows: list[dict], columns: list[str]) -> pd.DataFrame:
|
|
return pd.DataFrame(rows) if rows else pd.DataFrame(columns=columns)
|
|
|
|
|
|
def all_patients(cohort_queries: CohortQueries, dbt_queries: DbtQueryRepository) -> pd.DataFrame:
|
|
return _frame(dbt_queries.read(cohort_queries.all_patients), ["pac_id"])
|
|
|
|
|
|
def indexed(all_patients: pd.DataFrame, cohort_queries: CohortQueries, dbt_queries: DbtQueryRepository) -> pd.DataFrame:
|
|
"""The patients with an index date. A patient outside `all_patients` is an error, not attrition."""
|
|
index = _frame(dbt_queries.read(cohort_queries.index_date), ["pac_id", "fecha_indice"])
|
|
if index["pac_id"].duplicated().any():
|
|
raise CohortDefinitionError("the index query gives a patient more than one index date")
|
|
if unknown := len(set(index["pac_id"]) - set(all_patients["pac_id"])):
|
|
raise CohortDefinitionError(f"the index query gives {unknown} patients outside all patients")
|
|
return index.assign(fecha_indice=pd.to_datetime(index["fecha_indice"]).dt.date)
|
|
|
|
|
|
def excluded(rule: ExclusionRule, dbt_queries: DbtQueryRepository) -> set:
|
|
"""Everyone the rule flags."""
|
|
return {row["pac_id"] for row in dbt_queries.read(rule.sql)}
|
|
|
|
|
|
def remaining(population: pd.DataFrame, flagged: set) -> pd.DataFrame:
|
|
"""The previous population minus a rule's excluded members."""
|
|
return population[~population["pac_id"].isin(flagged)]
|
|
|
|
|
|
def study_population(last: pd.DataFrame) -> pd.DataFrame:
|
|
return last
|
|
|
|
|
|
def attrition(all_patients: pd.DataFrame, indexed: pd.DataFrame, populations: list[pd.DataFrame],
|
|
rules: list[ExclusionRule]) -> pd.DataFrame:
|
|
"""Each rule is charged only for those it removes from the population it receives."""
|
|
sizes = [("all_patients", len(all_patients)), ("indexed", len(indexed)),
|
|
*[(rule.name, len(population)) for rule, population in zip(rules, populations)]]
|
|
rows = [(step, n, None if i == 0 else sizes[i - 1][1] - n) for i, (step, n) in enumerate(sizes)]
|
|
return pd.DataFrame(rows, columns=["step", "n", "excluded"]).astype({"excluded": "Int64"})
|