AI Code Ruled
AI Code Ruled
# =============================================================================
# =============================================================================
# - dataset_64931192_person_df
# - dataset_64931192_survey_df
# - dataset_64931192_observation_df
# - dataset_64931192_measurement_df
# - dataset_64931192_condition_df
# - dataset_64931192_visit_df
# - dataset_64931192_drug_df
# - dataset_64931192_zip_code_socioeconomic_df
# =============================================================================
import os
import re
import numpy as np
import pandas as pd
try:
except Exception:
def display(x):
print(x)
def Markdown(x):
return x
try:
SCIPY_OK = True
except Exception:
SCIPY_OK = False
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
SMALL_CELL_THRESHOLD = 20
LOOKBACK_DAYS = 365
DISCONTINUATION_GAP_DAYS = 180
SEED = 42
[Link](SEED)
OUTPUT_DIR = "outputs/ms_dmt_loaded_data_only"
[Link](OUTPUT_DIR, exist_ok=True)
if isinstance(x, [Link]):
print([Link]().sum().sort_values(ascending=False).head(top_null_n))
print(f"[{name}] head({head_n}):")
display([Link](head_n))
else:
display(x)
out = [Link]()
for c in cols:
if c in [Link]:
return out
"""
Coerce any mask-like object into a 1D bool numpy array aligned to index.
if isinstance(mask, [Link]):
aligned = [Link](index)
na_count = int([Link]().sum())
return [Link](False).to_numpy(dtype=bool)
arr = [Link](mask)
if [Link] == 0:
if [Link] != 1:
if [Link][0] != len(index):
if [Link] != bool:
return arr
def normalize_column_names(df, df_name="df"):
"""
"""
out = [Link]()
seen = {}
deduped = []
for c in normalized:
if c not in seen:
seen[c] = 1
[Link](c)
else:
seen[c] += 1
[Link](f"{c}__dup{seen[c]}")
[Link] = deduped
if original_cols != deduped:
if o != n:
print(" ...")
return out
def exact_median(x):
s = pd.to_numeric(x, errors="coerce").dropna()
if n_col_candidates is None:
n_col = None
for c in n_col_candidates:
if c in [Link]:
n_col = c
break
if n_col is None:
return out
keep_cols = {n_col}
for c in [Link]:
if [Link]().startswith("denominator"):
keep_cols.add(c)
if c in {"sex_clean", "race_eth_harmonized", "race_3group", "ethnicity_2group", "first_dmt_group", "delay_category", "index_era", "group_type", "group_valu
e", "intersection_group"}:
keep_cols.add(c)
for c in [Link]:
if c in keep_cols:
continue
if numeric_c.notna().any():
[Link][small_mask, c] = f"<{threshold}"
return out
out = df_in.copy().astype(object)
for c in [Link]:
if c in id_cols:
continue
[Link][mask, c] = f"<{threshold}"
return out
if initiated != 1 or [Link](days_to_dmt):
if [Link](y):
return "Unknown"
y = int(y)
if y <= 2009:
return "2000-2009"
if y <= 2016:
return "2010-2016"
return "2017+"
"""
Print compact diagnostics in required format: Issue -> Cause -> Fix.
"""
return {
"gate": check_name,
"detail": str(detail),
if missing:
raise KeyError(f"{df_name} is missing required columns: {missing}")
return True
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
required_frames = {
"person_df": "dataset_64931192_person_df",
"survey_df": "dataset_64931192_survey_df",
"observation_df": "dataset_64931192_observation_df",
"measurement_df": "dataset_64931192_measurement_df",
"condition_df": "dataset_64931192_condition_df",
"visit_df": "dataset_64931192_visit_df",
"drug_df": "dataset_64931192_drug_df",
"zip_ses_df": "dataset_64931192_zip_code_socioeconomic_df",
}
missing_frames = [gname for gname in required_frames.values() if gname not in globals()]
if missing_frames:
raise ValueError(
"Missing required preloaded dataframes. Please run the dataset-builder cells first: "
+ ", ".join(missing_frames)
person_df = globals()[required_frames["person_df"]].copy()
survey_df = globals()[required_frames["survey_df"]].copy()
observation_df = globals()[required_frames["observation_df"]].copy()
measurement_df = globals()[required_frames["measurement_df"]].copy()
condition_df = globals()[required_frames["condition_df"]].copy()
visit_df = globals()[required_frames["visit_df"]].copy()
drug_df = globals()[required_frames["drug_df"]].copy()
zip_ses_df = globals()[required_frames["zip_ses_df"]].copy()
root_cause_items = [
},
"fix": "Detect and remove exact duplicates and key-level duplicates with before/after counts.",
},
"cause": "Applying lookback exclusion while index is earliest observed activity and using mixed baselines across sections.",
"fix": "Retain lookback only as QC; no eligibility exclusion. Use index_date for whole-cohort analyses and first_dmt_date for initiator-only treatment-path
way analyses.",
},
{
"cause": "Window/index mismatches can filter all rows without hard failure.",
"fix": "Add explicit candidate/window counts and fail loudly when emptiness is inconsistent with available data.",
},
"cause": "Residual log-rank columns can be interpreted as inferential results when not intended.",
},
print_issue_cause_fix(root_cause_items)
# Mandatory audits
("person_df", person_df),
("survey_df", survey_df),
("observation_df", observation_df),
("measurement_df", measurement_df),
("condition_df", condition_df),
("visit_df", visit_df),
("drug_df", drug_df),
("zip_ses_df", zip_ses_df),
]:
audit_df(_name, _df)
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
DMT_RULES = [
"dmt_class": "Injectable",
"efficacy_tier": "Moderate",
"route_group": "Injectable",
},
"dmt_class": "Injectable",
"efficacy_tier": "Moderate",
"route_group": "Injectable",
},
"dmt_class": "Injectable",
"efficacy_tier": "Moderate",
"route_group": "Injectable",
},
"ingredient_name": "glatiramer",
"keywords": ["glatiramer"],
"dmt_class": "Injectable",
"efficacy_tier": "Moderate",
"route_group": "Injectable",
},
"ingredient_name": "fingolimod",
"keywords": ["fingolimod"],
"efficacy_tier": "Moderate",
"route_group": "Oral",
},
"ingredient_name": "siponimod",
"keywords": ["siponimod"],
"efficacy_tier": "High",
"route_group": "Oral",
},
{
"ingredient_name": "ozanimod",
"keywords": ["ozanimod"],
"efficacy_tier": "High",
"route_group": "Oral",
},
"ingredient_name": "ponesimod",
"keywords": ["ponesimod"],
"efficacy_tier": "High",
"route_group": "Oral",
},
"efficacy_tier": "Moderate",
"route_group": "Oral",
},
"efficacy_tier": "Moderate",
"route_group": "Oral",
},
"efficacy_tier": "Moderate",
"route_group": "Oral",
},
"ingredient_name": "teriflunomide",
"keywords": ["teriflunomide"],
"route_group": "Oral",
},
"ingredient_name": "cladribine",
"keywords": ["cladribine"],
"efficacy_tier": "High",
"route_group": "Oral",
},
"ingredient_name": "natalizumab",
"keywords": ["natalizumab"],
"efficacy_tier": "High",
"route_group": "Infusion",
},
"ingredient_name": "ocrelizumab",
"keywords": ["ocrelizumab"],
"efficacy_tier": "High",
"route_group": "Infusion",
},
"ingredient_name": "ofatumumab",
"keywords": ["ofatumumab"],
"efficacy_tier": "High",
"route_group": "Injectable",
},
"ingredient_name": "alemtuzumab",
"keywords": ["alemtuzumab"],
"efficacy_tier": "High",
"route_group": "Infusion",
},
{
"ingredient_name": "rituximab",
"keywords": ["rituximab"],
"efficacy_tier": "Off-label",
"route_group": "Infusion",
},
SUSPICIOUS_EXCLUDE = {
if k in txt:
return {
"ingredient_name": [Link],
"dmt_class": [Link],
"efficacy_tier": [Link],
"route_group": [Link],
"include_flag": 0,
"exclusion_reason": reason,
return {
"ingredient_name": rule["ingredient_name"],
"dmt_class": rule["dmt_class"],
"efficacy_tier": rule["efficacy_tier"],
"route_group": rule["route_group"],
"include_flag": 1,
"exclusion_reason": "",
if [Link](route_name):
route_lc = str(route_name).lower()
return {
"ingredient_name": [Link],
"dmt_class": [Link],
"efficacy_tier": [Link],
"route_group": [Link],
"include_flag": 0,
"exclusion_reason": fallback_reason,
}
def mode_or_first_nonnull(series):
s = [Link]()
if [Link]:
return [Link]
m = [Link]()
if not [Link]:
return [Link][0]
return [Link][0]
concept_base = (
drug_df.groupby("drug_concept_id", as_index=False)
.agg(
standard_concept_name=("standard_concept_name", mode_or_first_nonnull),
route_concept_name_mode=("route_concept_name", mode_or_first_nonnull),
.copy()
)
concept_base["route_for_mapping"] = concept_base["route_concept_name_mode"]
mapped_rows = concept_base.apply(
axis=1,
result_type="expand",
cleaned_dmt_mapping = cleaned_dmt_mapping[
"drug_concept_id",
"standard_concept_name",
"ingredient_name",
"dmt_class",
"efficacy_tier",
"route_group",
"include_flag",
"exclusion_reason",
"route_concept_name_mode",
].copy()
et_index(drop=True)
dmt_mapping_unique_ok = bool(cleaned_dmt_mapping["drug_concept_id"].is_unique)
original_unique_concepts_n = int(drug_df["drug_concept_id"].nunique())
audit_df("cleaned_dmt_mapping", cleaned_dmt_mapping)
audit_df("excluded_dmt_concepts", excluded_dmt_concepts)
drug_mapped = drug_df.merge(
cleaned_dmt_mapping[
"drug_concept_id",
"ingredient_name",
"dmt_class",
"efficacy_tier",
"route_group",
"include_flag",
"exclusion_reason",
],
on="drug_concept_id",
how="left",
validate="many_to_one",
assert len(drug_mapped) == len(drug_df), "drug_mapped row count should match drug_df row count"
audit_df("drug_mapped", drug_mapped)
included_exposures = ensure_datetime(
included_exposures,
included_exposures["drug_date"] = pd.to_datetime(
included_exposures["drug_exposure_start_datetime"], errors="coerce"
).[Link]()
included_exposures["drug_end_date"] = pd.to_datetime(
included_exposures["drug_exposure_end_datetime"], errors="coerce"
).[Link]()
included_rows_before_dedup = int(len(included_exposures))
exact_dup_mask = included_exposures.duplicated(keep="first")
exact_dupe_rows_n = int(exact_dup_mask.sum())
if exact_dupe_rows_n > 0:
included_exposures = included_exposures.loc[~exact_dup_mask].copy()
included_exposures = included_exposures.sort_values(
).copy()
key_dupe_rows_n = int(key_dup_mask.sum())
if key_dupe_rows_n > 0:
included_exposures = included_exposures.loc[~key_dup_mask].copy()
included_rows_after_dedup = int(len(included_exposures))
print(
f"key_dupes_removed={key_dupe_rows_n:,} | after={included_rows_after_dedup:,}"
assert included_rows_after_dedup <= included_rows_before_dedup, "Dedup should never increase included exposure rows"
dmt_exposure_dedup_summary = [Link](
audit_df("dmt_exposure_dedup_summary", dmt_exposure_dedup_summary)
# Person-level exposure indicator: any included DMT exposure marks person as exposed.
ever_dmt_exposed = (
included_exposures.groupby("person_id", as_index=False)
.size()
.rename(columns={"size": "n_included_dmt_exposures"})
ever_dmt_exposed["ever_dmt_exposed_flag"] = 1
audit_df("ever_dmt_exposed", ever_dmt_exposed)
dmt_class_freq = (
included_exposures["dmt_class"]
.fillna("Missing")
.value_counts(dropna=False)
.rename_axis("dmt_class")
.reset_index(name="n_exposures")
audit_df("dmt_class_freq", dmt_class_freq)
cleaned_dmt_mapping.to_csv(f"{OUTPUT_DIR}/cleaned_dmt_mapping.csv", index=False)
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# ============================================================
# ============================================================
EXTRACT_IS_MS_ONLY = True
if EXTRACT_IS_MS_ONLY:
activity_parts = []
activity_parts.append(tmp)
activity_parts.append(tmp)
activity_parts.append(tmp)
activity_parts.append(tmp)
activity_parts.append(tmp)
if len(activity_parts) == 0:
raise ValueError("No activity tables available to derive index_date for MS-only extract.")
index_df = (
activity_df_ms_only.groupby("person_id", as_index=False)["activity_datetime"]
.min()
.rename(columns={"activity_datetime": "index_date"})
index_df["last_ms_dx_date"] = index_df["index_date"]
index_df["n_ms_dx_records"] = [Link]
index_df["n_ms_dx_dates"] = [Link]
index_df["ms_two_dx_flag"] = 1
index_df["ms_dx_verifiable_flag"] = 0
index_df["ms_index_method"] = "ms_only_extract_earliest_activity"
if index_df["index_date"].isna().any():
missing_n = int(index_df["index_date"].isna().sum())
ms_dx_df = [Link](columns=[
"condition_start_datetime", "source_concept_name",
])
ms_dx_verification_summary = [Link]({
"ms_dx_verifiable_flag": [0],
"n": [len(index_df)],
})
else:
condition_df["condition_name_lc"] = condition_df["standard_concept_name"].astype(str).[Link]()
r"\bg35\b|\b340\b|"
r"\bms\b"
condition_df["ms_text_blob"] = (
condition_df["condition_name_lc"].fillna("").astype(str)
+ " "
+ condition_df["source_name_lc"].fillna("").astype(str)
+ " "
+ condition_df["source_value_lc"].fillna("").astype(str)
+ " "
+ condition_df["source_code_lc"].fillna("").astype(str)
).[Link]()
ms_condition_concept_audit = (
condition_df.loc[
condition_df["is_ms_dx"],
.drop_duplicates()
.sort_values(["standard_concept_name", "condition_concept_id"])
.reset_index(drop=True)
ms_dx_df = condition_df.loc[
_code"],
].copy()
index_df = (
ms_dx_df.groupby("person_id", as_index=False)
.agg(
index_date=("dx_date", "min"),
last_ms_dx_date=("dx_date", "max"),
n_ms_dx_records=("dx_date", "size"),
n_ms_dx_dates=("dx_date", "nunique"),
index_df["ms_dx_verifiable_flag"] = 1
index_df["ms_index_method"] = "ms_condition_rows"
ms_dx_verification_summary = (
index_df["ms_dx_verifiable_flag"]
.value_counts(dropna=False)
.rename_axis("ms_dx_verifiable_flag")
.reset_index(name="n")
audit_df("ms_condition_concept_audit", ms_condition_concept_audit)
audit_df("ms_dx_df", ms_dx_df)
audit_df("index_df", index_df)
audit_df("ms_dx_verification_summary", ms_dx_verification_summary)
# Start flow from all persons with >=1 MS diagnosis row.
cohort_flow = []
cohort0 = index_df.merge(
person_df[[
"person_id",
"date_of_birth",
"gender",
"sex_at_birth",
"race",
"ethnicity",
"self_reported_category",
]],
on="person_id",
how="left",
cohort0["age_at_index"] = (
cohort0["index_date"].[Link]
- cohort0["date_of_birth"].[Link]
- (
| (
(cohort0["index_date"].[Link] == cohort0["date_of_birth"].[Link])
).astype(float)
audit_df("cohort0", cohort0)
_start_rule = "MS-only extract persons from person_df" if EXTRACT_IS_MS_ONLY else ">=1 MS diagnosis"
# Age >=18
n_before = len(cohort0)
audit_df("cohort1_age_filtered", cohort1)
n_before = len(cohort1)
_two_dx_rule = ">=2 MS diagnosis records" if not EXTRACT_IS_MS_ONLY else "MS-only extract assumption (not re-verified from condition rows)"
cohort_flow.append({"step": "ms_two_dx", "n_before": n_before, "n_after": len(cohort2), "n_excluded": n_before - len(cohort2), "rule": _two_dx_rule})
audit_df("cohort2_two_dx", cohort2)
activity_parts = []
if not visit_df.empty:
activity_parts.append(
visit_df[["person_id", "visit_start_datetime"]]
.rename(columns={"visit_start_datetime": "activity_datetime"})
if not condition_df.empty:
activity_parts.append(
condition_df[["person_id", "condition_start_datetime"]]
.rename(columns={"condition_start_datetime": "activity_datetime"})
if not observation_df.empty:
activity_parts.append(
observation_df[["person_id", "observation_datetime"]]
.rename(columns={"observation_datetime": "activity_datetime"})
if not measurement_df.empty:
activity_parts.append(
measurement_df[["person_id", "measurement_datetime"]]
.rename(columns={"measurement_datetime": "activity_datetime"})
if not drug_mapped.empty:
activity_parts.append(
drug_mapped[["person_id", "drug_exposure_start_datetime"]]
.rename(columns={"drug_exposure_start_datetime": "activity_datetime"})
)
activity_df = [Link](activity_parts, ignore_index=True)
activity_df = activity_df.dropna(subset=["activity_date"]).copy()
audit_df("activity_df", activity_df)
activity_bounds = (
activity_df.groupby("person_id", as_index=False)["activity_date"]
.agg(first_activity_date="min", last_activity_date="max")
audit_df("activity_bounds", activity_bounds)
lookback_check["lookback_hit"] = (
lookback_flag = (
lookback_check.groupby("person_id", as_index=False)["lookback_hit"]
.max()
.rename(columns={"lookback_hit": "lookback_flag"})
lookback_flag["lookback_flag"] = lookback_flag["lookback_flag"].fillna(False).astype(int)
audit_df("lookback_flag", lookback_flag)
cohort3["lookback_flag"] = cohort3["lookback_flag"].fillna(0).astype(int)
n_before = len(cohort3)
cohort4 = [Link]()
cohort_flow.append({
"step": "lookback_removed_for_ms_only",
"n_before": n_before,
"n_after": len(cohort4),
"n_excluded": 0,
})
audit_df("cohort4_no_lookback_exclusion", cohort4)
included_exposures = included_exposures[included_exposures["drug_exposure_start_datetime"].notna()].copy()
audit_df("included_exposures", included_exposures)
# In this MS-only extract, pre-index DMT is not treated as a separate exclusion state.
pre_index_dmt = cohort4[["person_id"]].drop_duplicates().copy()
pre_index_dmt["pre_index_dmt_flag"] = 0
print("[INFO] Reason: pre-index DMT can arise from timestamp/date normalization artifacts and is not used as an exclusion criterion.")
audit_df("pre_index_dmt", pre_index_dmt)
post_index_exposure = drug_idx[drug_idx["drug_date"] >= drug_idx["index_date"]].copy()
first_post_dmt = (
post_index_exposure.drop_duplicates("person_id", keep="first")
.rename(
columns={
"drug_date": "first_dmt_date",
"dmt_class": "first_dmt_group",
"ingredient_name": "first_dmt_ingredient",
"efficacy_tier": "efficacy_tier_first",
audit_df("first_post_dmt", first_post_dmt)
visit_pre = visit_pre[
].copy()
visit_count_pre = (
visit_pre.groupby("person_id", as_index=False)
.agg(visit_count_365d_preindex=("visit_date", "count"))
audit_df("visit_count_pre", visit_count_pre)
cohort_primary = (
cohort4
cohort_primary["ever_dmt_exposed_flag"] = cohort_primary["ever_dmt_exposed_flag"].fillna(0).astype(int)
cohort_primary["pre_index_dmt_flag"] = cohort_primary["pre_index_dmt_flag"].fillna(0).astype(int)
cohort_primary["visit_count_365d_preindex"] = cohort_primary["visit_count_365d_preindex"].fillna(0).astype(int)
cohort_primary["initiated"] = cohort_primary["first_dmt_date"].notna().astype(int)
cohort_primary["cohort_baseline_date"] = pd.to_datetime(
cohort_primary["index_date"], errors="coerce"
).[Link]()
cohort_primary["treatment_start_date"] = pd.to_datetime(
cohort_primary["first_dmt_date"], errors="coerce"
).[Link]()
cohort_primary["analysis_index_source"] = "cohort_baseline_index_date"
cohort_primary["days_to_dmt"] = [Link](
cohort_primary["initiated"] == 1,
(pd.to_datetime(cohort_primary["first_dmt_date"]) - pd.to_datetime(cohort_primary["index_date"])).[Link],
[Link],
cohort_primary["followup_end_date"] = [Link](
cohort_primary["cohort_baseline_date"],
cohort_primary["followup_end_date"],
cohort_primary["time_to_event_days"] = [Link](
cohort_primary["initiated"] == 1,
cohort_primary["days_to_dmt"],
(cohort_primary["followup_end_date"] - cohort_primary["cohort_baseline_date"]).[Link],
)
audit_df("cohort_primary_pre_demo", cohort_primary)
n_before = len(cohort_primary)
cohort_sensitivity = cohort_primary.copy()
cohort_flow.append({
"step": "pre_index_dmt_exclusion_removed",
"n_before": n_before,
"n_after": len(cohort_sensitivity),
"n_excluded": 0,
})
audit_df("cohort_sensitivity_pre_demo", cohort_sensitivity)
cohort_flow_summary = [Link](cohort_flow)
audit_df("cohort_flow_summary", cohort_flow_summary)
cohort_flow_summary.to_csv(f"{OUTPUT_DIR}/cohort_flow_summary.csv", index=False)
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# Sex
sex_map = {
"male": "Male",
"female": "Female",
def clean_sex(row):
sx = str([Link]("sex_at_birth", "")).strip().lower()
gd = str([Link]("gender", "")).strip().lower()
if sx in sex_map:
return sex_map[sx]
if gd in sex_map:
return sex_map[gd]
return "Unknown/Other"
def map_text_to_race3(x):
t = str(x).strip().lower()
if "black" in t or "african" in t:
return "Black"
if "white" in t:
return "White"
return "Other"
def survey_race3_map(ans):
t = str(ans).strip().lower()
if "black" in t or "african" in t:
return "Black"
if "white" in t:
return "White"
return "Other"
def survey_hisp_flag(ans):
t = str(ans).strip().lower()
return 0
if "hispanic" in t or "latino" in t:
return 1
return [Link]
cohort_demo = cohort_primary.copy()
cohort_demo["race_3group"] = cohort_demo["self_reported_category"].apply(map_text_to_race3)
cohort_demo["race_3group_source"] = "self_reported_category"
cohort_demo["ethnicity_2group"] = [Link](
"Hispanic",
"Non-Hispanic",
cohort_demo["ethnicity_2group_source"] = "person_ethnicity"
survey_re["q_txt"] = survey_re["question"].astype(str).[Link]()
survey_re["a_txt"] = survey_re["answer"].astype(str).[Link]()
survey_re = survey_re[
].copy()
audit_df("survey_re_candidates", survey_re)
if not survey_re.empty:
survey_re["abs_delta_days"] = survey_re["delta_days"].abs()
survey_nearest["survey_race3_candidate"] = survey_nearest["answer"].apply(survey_race3_map)
survey_nearest["survey_hispanic_flag"] = survey_nearest["answer"].apply(survey_hisp_flag)
audit_df("survey_nearest", survey_nearest)
# Optional race fallback to upgrade Other -> White/Black when survey gives direct evidence.
survey_race3_series = survey_nearest.set_index("person_id")["survey_race3_candidate"]
survey_hisp_by_person = (
survey_re.assign(survey_hispanic_flag=survey_re["answer"].apply(survey_hisp_flag))
.groupby("person_id")["survey_hispanic_flag"]
cohort_demo.loc[
"ethnicity_2group"
] = "Non-Hispanic"
cohort_demo.loc[
] = "survey_non_hispanic_any"
cohort_demo["race_eth_harmonized"] = cohort_demo["race_3group"]
cohort_demo["race_eth_source"] = cohort_demo["race_3group_source"]
cohort_demo["race_eth_strict"] = cohort_demo["race_3group"]
cohort_demo["unknown_demo_flag"] = (
(cohort_demo["sex_clean"] == "Unknown/Other")
).astype(int)
audit_df("cohort_demo", cohort_demo)
race_codebook_md = """
## Race/Ethnicity Codebook
- `White`
- `Black`
- `Other` (anyone not classified as White or Black)
- `Hispanic`
Assignment notes:
1. Race starts from `self_reported_category` and may use survey fallback for White/Black.
"""
display(Markdown(race_codebook_md))
# Counts
race_counts = cohort_demo["race_3group"].value_counts(dropna=False).rename_axis("race_3group").reset_index(name="n")
ethnicity_counts = cohort_demo["ethnicity_2group"].value_counts(dropna=False).rename_axis("ethnicity_2group").reset_index(name="n")
sex_counts = cohort_demo["sex_clean"].value_counts(dropna=False).rename_axis("sex_clean").reset_index(name="n")
strict_counts = cohort_demo["race_eth_strict"].value_counts(dropna=False).rename_axis("race_eth_strict").reset_index(name="n")
audit_df("race_counts", race_counts)
audit_df("ethnicity_counts", ethnicity_counts)
audit_df("sex_counts", sex_counts)
audit_df("strict_counts", strict_counts)
cohort_primary = cohort_demo.copy()
cohort_sensitivity = cohort_sensitivity.drop(
columns=[c for c in ["sex_clean", "race_eth_harmonized", "race_eth_strict", "unknown_demo_flag", "race_eth_source", "race_3group", "race_3group_source", "ethni
errors="ignore",
).merge(
ethnicity_2group", "ethnicity_2group_source"]],
on="person_id",
how="left",
audit_df("cohort_sensitivity_demo", cohort_sensitivity)
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
analytic_cohort = cohort_primary.copy()
analytic_cohort["index_era"] = analytic_cohort["index_year"].apply(era_from_year)
ses_cols = [
"person_id",
"observation_datetime",
"deprivation_index",
"median_income",
"poverty",
"no_health_insurance",
"assisted_income",
"high_school_education",
ses_df = zip_ses_df[ses_available].copy()
if c in ses_df.columns:
ses_df = ses_df.sort_values(
ses_person = ses_nearest[keep_ses_person_cols].copy()
audit_df("ses_person", ses_person)
def safe_quartile(series):
s = pd.to_numeric(series, errors="coerce")
n_nonnull = int([Link]().sum())
if n_nonnull < 4:
try:
if c in analytic_cohort.columns:
analytic_cohort[f"{c}_quartile"] = safe_quartile(analytic_cohort[c]).astype(object)
required_analytic_cols = [
"person_id",
"index_date",
"cohort_baseline_date",
"treatment_start_date",
"analysis_index_date",
"analysis_index_source",
"age_at_index",
"index_year",
"index_era",
"sex_clean",
"race_3group",
"ethnicity_2group",
"race_eth_harmonized",
"race_eth_strict",
"unknown_demo_flag",
"lookback_flag",
"ever_dmt_exposed_flag",
"pre_index_dmt_flag",
"initiated",
"first_dmt_date",
"first_dmt_group",
"first_dmt_ingredient",
"efficacy_tier_first",
"days_to_dmt",
"delay_category",
"followup_end_date",
"time_to_event_days",
"visit_count_365d_preindex",
"deprivation_index",
"median_income",
"poverty",
"no_health_insurance",
"assisted_income",
"high_school_education",
for c in required_analytic_cols:
if c not in analytic_cohort.columns:
analytic_cohort[c] = [Link]
analytic_cohort["cohort_baseline_date"] = analytic_cohort["cohort_baseline_date"].fillna(analytic_cohort["index_date"])
analytic_cohort["followup_end_date"] = analytic_cohort["followup_end_date"].fillna(analytic_cohort["cohort_baseline_date"])
_bad_followup = (
analytic_cohort["followup_end_date"].notna()
& analytic_cohort["cohort_baseline_date"].notna()
followup_qc = [Link](
"metric": [
"n_rows",
"index_date_missing",
"cohort_baseline_date_missing",
"followup_end_missing",
"followup_equals_cohort_baseline",
"followup_before_index_fixed_rows",
],
"value": [
len(analytic_cohort),
int(analytic_cohort["index_date"].isna().sum()),
int(analytic_cohort["cohort_baseline_date"].isna().sum()),
int(analytic_cohort["followup_end_date"].isna().sum()),
int((analytic_cohort["followup_end_date"] == analytic_cohort["cohort_baseline_date"]).sum()),
int(_bad_followup.sum()),
],
audit_df("followup_qc", followup_qc)
audit_df("analytic_cohort", analytic_cohort)
# Missingness summary
missingness_summary = [Link]({
"variable": analytic_cohort.columns,
"n_total": len(analytic_cohort),
})
audit_df("missingness_summary", missingness_summary)
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
d = df_in.copy()
d[group_col] = d[group_col].fillna("Missing").astype(str)
out = (
[Link](group_col, dropna=False)
.agg(
n=("person_id", "nunique"),
n_initiated=("initiated", "sum"),
n_pre_index_dmt=("pre_index_dmt_flag", "sum"),
mean_pre_index_visits=("visit_count_365d_preindex", "mean"),
.reset_index()
out["denominator_total_n"] = int(d["person_id"].nunique())
dmt_stats = (
d_init.groupby(group_col, dropna=False)["days_to_dmt"]
.agg(mean_days_to_dmt="mean", median_days_to_dmt=exact_median)
.reset_index()
def make_first_dmt_table(df_in):
d = df_in[df_in["initiated"] == 1].copy()
d = d[d["first_dmt_group"].notna()].copy()
d["first_dmt_group"] = d["first_dmt_group"].astype(str)
out = (
[Link]("first_dmt_group", dropna=False)
.agg(
n=("person_id", "nunique"),
mean_days_to_dmt=("days_to_dmt", "mean"),
median_days_to_dmt=("days_to_dmt", exact_median),
)
.reset_index()
out["denominator_initiators_n"] = int(d["person_id"].nunique())
def make_race_dmt_crosstab(df_in):
d["race_3group"] = d["race_3group"].fillna("Other").astype(str)
d["first_dmt_group"] = d["first_dmt_group"].fillna("Missing").astype(str)
ct = ct.reset_index().rename(columns={"race_3group": "race_3group"})
ct["denominator_initiators_n"] = int(d["person_id"].nunique())
return ct
descriptive_table_sex = make_group_table(analytic_cohort, "sex_clean", "by_sex")
descriptive_table_first_dmt = make_first_dmt_table(analytic_cohort)
race_by_dmt_crosstab = make_race_dmt_crosstab(analytic_cohort)
summary_exact = [Link]([
"total_n": int(analytic_cohort["person_id"].nunique()),
"initiated_n": int(analytic_cohort["initiated"].sum()),
"pre_index_dmt_n": int(analytic_cohort["pre_index_dmt_flag"].sum()),
[Link],
])
audit_df("summary_exact", summary_exact)
display(display_descriptive_table_sex)
display(display_descriptive_table_race_eth)
display(display_descriptive_table_ethnicity)
display(display_descriptive_table_first_dmt)
display(display_race_by_dmt_crosstab)
# Validation compare vs existing in-memory prior if available
validation_compare = []
prev = globals()["cohort_raw"].copy()
for r in validation_compare:
if r["metric"] == "total_n":
r["prior_existing_analysis"] = prev_total
r["prior_existing_analysis"] = prev_init
r["prior_existing_analysis"] = prev_pre
else:
for r in validation_compare:
r["prior_existing_analysis"] = [Link]
validation_compare_df = [Link](validation_compare)
validation_compare_df["discrepancy_explanation"] = [Link](
validation_compare_df["prior_existing_analysis"].isna(),
"Differences may reflect strict cleaned DMT mapping, loaded-data-only constraints, and revised demographic/SES logic.",
audit_df("validation_compare_df", validation_compare_df)
# -----------------------------------------------------------------------------
delay_category_summary = (
.agg(n=("person_id", "nunique"))
.reset_index()
delay_tot = (
.sum()
.reset_index()
.rename(columns={"n": "denominator_group_n"})
audit_df("delay_category_summary", delay_category_summary)
delay_category_ethnicity_summary = (
.agg(n=("person_id", "nunique"))
.reset_index()
delay_eth_tot = (
delay_category_ethnicity_summary.groupby(["ethnicity_2group"], dropna=False)["n"]
.sum()
.reset_index()
.rename(columns={"n": "denominator_group_n"})
e(0, [Link])
audit_df("delay_category_ethnicity_summary", delay_category_ethnicity_summary)
if subgroup_col is None:
d["group_type"] = "overall"
d["group_value"] = "All"
else:
d["group_type"] = subgroup_col
d["group_value"] = d[subgroup_col].fillna("Missing").astype(str)
out = (
.agg(
n=("person_id", "nunique"),
initiated_n=("initiated", "sum"),
median_days_to_dmt=("days_to_dmt", exact_median),
.reset_index()
if not d_init.empty:
mode_class = (
.agg(n_class=("person_id", "nunique"))
.reset_index()
.sort_values(["index_era", "group_type", "group_value", "n_class", "first_dmt_group"], ascending=[True, True, True, False, True])
.rename(columns={"first_dmt_group": "most_common_first_dmt_group"})
else:
out["most_common_first_dmt_group"] = [Link]
return out
calendar_era_summary = [Link](
[
era_summary_by(analytic_cohort, None),
era_summary_by(analytic_cohort, "sex_clean"),
era_summary_by(analytic_cohort, "race_3group"),
era_summary_by(analytic_cohort, "ethnicity_2group"),
],
ignore_index=True,
audit_df("calendar_era_summary", calendar_era_summary)
print("[WARNING] `followup_end_date` missing in analytic_cohort; reconstructing from cohort_baseline_date for this step.")
else:
analytic_cohort["followup_end_date"] = analytic_cohort["followup_end_date"].fillna(analytic_cohort["cohort_baseline_date"])
analytic_cohort.loc[
"followup_end_date",
] = analytic_cohort.loc[
"cohort_baseline_date",
high_eff_exp = included_exposures.merge(
on="person_id",
how="inner",
high_eff_exp = high_eff_exp[high_eff_exp["dmt_class"].isin(high_eff_classes)].copy()
high_eff_first = (
high_eff_exp.sort_values(["person_id", "drug_date", "drug_concept_id"])
.drop_duplicates("person_id", keep="first")
[["person_id", "drug_date"]]
.rename(columns={"drug_date": "first_high_efficacy_dmt_date"})
audit_df("high_eff_first", high_eff_first)
high_eff_first,
on="person_id",
how="left",
high_efficacy_df["high_efficacy_initiated"] = high_efficacy_df["first_high_efficacy_dmt_date"].notna().astype(int)
high_efficacy_df["days_to_high_efficacy_dmt"] = [Link](
high_efficacy_df["high_efficacy_initiated"] == 1,
(high_efficacy_df["first_high_efficacy_dmt_date"] - high_efficacy_df["cohort_baseline_date"]).[Link],
[Link],
)
high_efficacy_df["time_to_high_eff_event_or_censor"] = [Link](
high_efficacy_df["high_efficacy_initiated"] == 1,
high_efficacy_df["days_to_high_efficacy_dmt"],
(high_efficacy_df["followup_end_date"] - high_efficacy_df["cohort_baseline_date"]).[Link],
high_efficacy_df["time_to_high_eff_event_or_censor"] = pd.to_numeric(
high_efficacy_df["time_to_high_eff_event_or_censor"], errors="coerce"
).clip(lower=0)
audit_df("high_efficacy_df", high_efficacy_df)
high_efficacy_summary = (
.agg(
n=("person_id", "count"),
high_efficacy_initiated_n=("high_efficacy_initiated", "sum"),
median_days_to_high_efficacy=("days_to_high_efficacy_dmt", "median"),
.reset_index()
)
high_efficacy_summary["high_efficacy_initiation_pct"] = (
cols_to_drop = [
"logrank_p_race_3group",
"logrank_status_race_3group",
"logrank_p_ethnicity_2group",
"logrank_status_ethnicity_2group",
"logrank_p_sex_clean",
"logrank_status_sex_clean",
high_efficacy_summary = high_efficacy_summary.drop(
errors="ignore",
audit_df("high_efficacy_summary", high_efficacy_summary)
# 7D. Intersectional analysis (race x sex), policy-compliant collapse.
intersectional_df["race_3group"] = intersectional_df["race_3group"].fillna("Other")
intersectional_df["sex_clean"] = intersectional_df["sex_clean"].fillna("Missing")
group_n = intersectional_df["intersection_group_raw"].value_counts()
intersectional_df["intersection_group"] = [Link](
intersectional_df["intersection_group_raw"].isin(small_groups),
f"Suppressed (<{SMALL_CELL_THRESHOLD})",
intersectional_df["intersection_group_raw"],
intersectional_summary = (
.reset_index()
)
intersection_tot = (
intersectional_summary.groupby("intersection_group", dropna=False)["n"]
.sum()
.reset_index()
.rename(columns={"n": "denominator_group_n"})
audit_df("intersectional_summary", intersectional_summary)
UTIL_WINDOW_DAYS_POST = 365
visit_util["visit_name_lc"] = visit_util["standard_concept_name"].astype(str).[Link]()
visit_util = visit_util.dropna(subset=["visit_date"]).copy()
util_people_candidates_before_window = int(visit_util["person_id"].nunique())
visit_util = visit_util[
].copy()
util_rows_after_window = int(len(visit_util))
util_people_after_window = int(visit_util["person_id"].nunique())
print(
f"{util_candidates_before_window:,}, persons={util_people_candidates_before_window:,}"
if util_rows_after_window == 0:
if util_candidates_before_window == 0:
else:
raise AssertionError(
"visit_util is empty after post-index window despite non-empty candidate rows. "
visit_util["visit_type_group"] = [Link](
],
default="Other",
audit_df("visit_util", visit_util)
util_counts = (
.size()
.reset_index(name="n")
if c not in util_wide.columns:
util_wide[c] = 0
util_wide = util_wide.rename(
columns={
"Outpatient": "outpatient_count_365d_postindex",
"Inpatient": "inpatient_count_365d_postindex",
"ED": "ED_count_365d_postindex",
"Other": "other_visit_count_365d_postindex",
util_total = (
visit_util.groupby("person_id", dropna=False)
.size()
.reset_index(name="visit_count_365d_postindex")
)
for c in [
"visit_count_365d_postindex",
"outpatient_count_365d_postindex",
"inpatient_count_365d_postindex",
"ED_count_365d_postindex",
"other_visit_count_365d_postindex",
]:
if c not in utilization_df.columns:
utilization_df[c] = 0
utilization_df[c] = utilization_df[c].fillna(0)
audit_df("utilization_df", utilization_df)
utilization_summary = [Link](
[
utilization_df.groupby("race_3group", dropna=False)
.agg(
n=("person_id", "nunique"),
initiated_pct=("initiated", "mean"),
mean_visits=("visit_count_365d_postindex", "mean"),
mean_outpatient=("outpatient_count_365d_postindex", "mean"),
mean_inpatient=("inpatient_count_365d_postindex", "mean"),
mean_ed=("ED_count_365d_postindex", "mean"),
.reset_index()
.rename(columns={"race_3group": "group_value"})
.assign(group_type="race_3group"),
utilization_df.groupby("ethnicity_2group", dropna=False)
.agg(
n=("person_id", "nunique"),
initiated_pct=("initiated", "mean"),
mean_visits=("visit_count_365d_postindex", "mean"),
mean_outpatient=("outpatient_count_365d_postindex", "mean"),
mean_inpatient=("inpatient_count_365d_postindex", "mean"),
mean_ed=("ED_count_365d_postindex", "mean"),
.reset_index()
.rename(columns={"ethnicity_2group": "group_value"})
.assign(group_type="ethnicity_2group"),
utilization_df.groupby("sex_clean", dropna=False)
.agg(
n=("person_id", "nunique"),
initiated_pct=("initiated", "mean"),
mean_visits=("visit_count_365d_postindex", "mean"),
mean_outpatient=("outpatient_count_365d_postindex", "mean"),
mean_inpatient=("inpatient_count_365d_postindex", "mean"),
mean_ed=("ED_count_365d_postindex", "mean"),
.reset_index()
.rename(columns={"sex_clean": "group_value"})
.assign(group_type="sex_clean"),
],
ignore_index=True,
)
audit_df("utilization_summary", utilization_summary)
race_eth_ct = [Link](
analytic_cohort["race_3group"].fillna("Other"),
analytic_cohort["ethnicity_2group"].fillna("Non-Hispanic"),
dropna=False,
race_eth_ct = race_eth_ct.reset_index()
audit_df("race_ethnicity_contingency", race_eth_ct)
if SCIPY_OK:
_ct = [Link](
analytic_cohort["race_3group"].fillna("Other"),
analytic_cohort["ethnicity_2group"].fillna("Non-Hispanic"),
dropna=False,
)
if _ct.shape[0] >= 2 and _ct.shape[1] >= 2 and _ct.[Link]() > 0:
n = _ct.[Link]()
race_ethnicity_association = [Link](
[{
"status": "computed",
"chi2": float(chi2),
"p_value": float(pval),
"dof": int(dof),
"n": int(n),
}]
else:
race_ethnicity_association = [Link](
[{
"status": "not computed: insufficient contingency dimensions",
"chi2": [Link],
"p_value": [Link],
"dof": [Link],
"n": int(_ct.[Link]()),
"cramers_v": [Link],
}]
else:
race_ethnicity_association = [Link](
[{
"chi2": [Link],
"p_value": [Link],
"dof": [Link],
"n": int(len(analytic_cohort)),
"cramers_v": [Link],
audit_df("race_ethnicity_association", race_ethnicity_association)
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
dmt_history = included_exposures.merge(
on="person_id",
how="inner",
dmt_history = dmt_history[dmt_history["treatment_start_date"].notna()].copy()
# Build expected end date using available fields and conservative assumptions.
dmt_history["expected_end_date"] = dmt_history["end_date_from_drug_end"]
mask_need_verbatim = (
dmt_history["expected_end_date"].isna()
& dmt_history["end_date_from_verbatim"].notna()
mask_need_verbatim_np, "end_date_from_verbatim"
]
mask_need_days_supply = (
dmt_history["expected_end_date"].isna()
& dmt_history["days_supply_num"].notna()
dmt_history.loc[mask_need_days_supply_np, "expected_end_date"] = (
dmt_history.loc[mask_need_days_supply_np, "drug_date"]
cond_end_from_drug_end_np = as_bool_mask(
dmt_history["end_date_from_drug_end"].notna(),
dmt_history.index,
"cond_end_from_drug_end",
# If still missing expected_end_date, discontinuation cannot be reliably assessed for that episode.
dmt_history["end_date_source"] = [Link](
cond_end_from_drug_end_np,
mask_need_verbatim_np,
mask_need_days_supply_np,
],
default="missing_unassessable",
)
dmt_history = dmt_history.sort_values(["person_id", "drug_date", "drug_concept_id"]).copy()
dmt_history["exposure_order"] = dmt_history.groupby("person_id").cumcount() + 1
dmt_history["prior_dmt_class"] = dmt_history.groupby("person_id")["dmt_class"].shift(1)
dmt_history["switched_class"] = (
).astype(int)
dmt_history["efficacy_rank"] = dmt_history["efficacy_tier"].map(efficacy_rank)
dmt_history["prior_efficacy_rank"] = dmt_history.groupby("person_id")["efficacy_rank"].shift(1)
dmt_history["escalated"] = (
dmt_history["switched_class"].eq(1)
& dmt_history["efficacy_rank"].notna()
& dmt_history["prior_efficacy_rank"].notna()
).astype(int)
dmt_history["deescalated"] = (
dmt_history["switched_class"].eq(1)
& dmt_history["efficacy_rank"].notna()
& dmt_history["prior_efficacy_rank"].notna()
).astype(int)
dmt_history["is_high_efficacy_class"] = dmt_history["dmt_class"].isin(high_eff_classes).astype(int)
# Discontinuation: final gap > 180 days after expected end with no subsequent DMT.
last_episode = (
.groupby("person_id", as_index=False)
.tail(1)
.copy()
if col in last_episode.columns:
).astype(int)
last_episode["gap_after_last_end_days"] = (
last_episode["followup_end_date"] - last_episode["expected_end_date"]
).[Link]
last_episode["discontinued"] = [Link](
last_episode["discontinuation_assessable"].eq(1)
1,
0,
last_episode["discontinuation_date"] = [Link](
last_episode["discontinued"].eq(1),
[Link],
audit_df("last_episode", last_episode)
switching_person = (
dmt_history.groupby("person_id", as_index=False)
.agg(
first_dmt_class=("dmt_class", "first"),
ever_switched=("switched_class", "max"),
ever_escalated=("escalated", "max"),
ever_deescalated=("deescalated", "max"),
ever_high_efficacy=("is_high_efficacy_class", "max"),
.merge(
nicity_2group", "sex_clean"]],
on="person_id",
how="left",
switching_person["event_or_censor_date"] = switching_person["followup_end_date"]
switching_person.loc[switching_person["discontinued"] == 1, "event_or_censor_date"] = switching_person.loc[
switching_person["discontinued"] == 1, "discontinuation_date"
switching_person["time_to_discontinuation"] = (
pd.to_datetime(switching_person["event_or_censor_date"], errors="coerce").[Link]()
- pd.to_datetime(switching_person["first_dmt_date"], errors="coerce").[Link]()
).[Link]
audit_df("dmt_history", dmt_history)
audit_df("switching_person", switching_person)
switching_summary = [Link](
switching_person.groupby("race_3group", dropna=False)
.agg(
n=("person_id", "nunique"),
ever_switched_n=("ever_switched", "sum"),
ever_escalated_n=("ever_escalated", "sum"),
ever_deescalated_n=("ever_deescalated", "sum"),
ever_high_efficacy_n=("ever_high_efficacy", "sum"),
discontinuation_assessable_n=("discontinuation_assessable", "sum"),
discontinued_n=("discontinued", "sum"),
median_time_to_discontinuation=("time_to_discontinuation", exact_median),
.reset_index()
.rename(columns={"race_3group": "group_value"})
.assign(group_type="race_3group"),
switching_person.groupby("ethnicity_2group", dropna=False)
.agg(
n=("person_id", "nunique"),
ever_switched_n=("ever_switched", "sum"),
ever_escalated_n=("ever_escalated", "sum"),
ever_deescalated_n=("ever_deescalated", "sum"),
ever_high_efficacy_n=("ever_high_efficacy", "sum"),
discontinuation_assessable_n=("discontinuation_assessable", "sum"),
discontinued_n=("discontinued", "sum"),
median_time_to_discontinuation=("time_to_discontinuation", exact_median),
)
.reset_index()
.rename(columns={"ethnicity_2group": "group_value"})
.assign(group_type="ethnicity_2group"),
switching_person.groupby("sex_clean", dropna=False)
.agg(
n=("person_id", "nunique"),
ever_switched_n=("ever_switched", "sum"),
ever_escalated_n=("ever_escalated", "sum"),
ever_deescalated_n=("ever_deescalated", "sum"),
ever_high_efficacy_n=("ever_high_efficacy", "sum"),
discontinuation_assessable_n=("discontinuation_assessable", "sum"),
discontinued_n=("discontinued", "sum"),
median_time_to_discontinuation=("time_to_discontinuation", exact_median),
.reset_index()
.rename(columns={"sex_clean": "group_value"})
.assign(group_type="sex_clean"),
],
ignore_index=True,
("ever_switched_n", "ever_switched_pct"),
("ever_escalated_n", "ever_escalated_pct"),
("ever_deescalated_n", "ever_deescalated_pct"),
("ever_high_efficacy_n", "ever_high_efficacy_pct"),
]:
[Link])
audit_df("switching_summary", switching_summary)
print(
"If expected end date remained missing, discontinuation was marked unassessable."
)
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
MIN_OTHER_CONDITION_PEOPLE = 200
comorb = [Link](
on="person_id",
how="inner",
comorb_candidates_after_merge = int(len(comorb))
comorb_people_candidates_after_merge = int(comorb["person_id"].nunique())
comorb["name_lc"] = comorb["standard_concept_name"].astype(str).[Link]()
comorb = comorb[comorb["cond_date"].notna()].copy()
if COMORB_WINDOW == "post_baseline_365":
comorb = comorb[
].copy()
comorb = comorb[
].copy()
comorb_rows_after_window = int(len(comorb))
comorb_people_after_window = int(comorb["person_id"].nunique())
audit_df("comorb_rows_windowed", comorb)
print(f"[comorb validation] Rows after cohort merge/window: {len(comorb):,}")
print(
f"{comorb_candidates_after_merge:,}, people={comorb_people_candidates_after_merge:,}"
if comorb_rows_after_window == 0:
if comorb_candidates_after_merge == 0:
raise AssertionError(
else:
print(
)
# Known disease groups requested.
comorb["known_group"] = "other"
cohort_n = int(analytic_cohort["person_id"].nunique())
known_group_summary = (
[Link]("known_group", dropna=False)
.agg(
n_people=("person_id", "nunique"),
n_rows=("person_id", "size"),
.reset_index()
)
known_group_summary["pct_people"] = 100 * known_group_summary["n_people"] / max(cohort_n, 1)
audit_df("known_group_summary", known_group_summary)
top_other_conditions = (
comorb[comorb["known_group"] == "other"]
.agg(
n_people=("person_id", "nunique"),
n_rows=("person_id", "size"),
.reset_index()
audit_df("top_other_conditions", top_other_conditions)
audit_df("top_other_conditions_100", top_other_conditions.head(100))
audit_df("selected_other_conditions_n>=200", selected_other_conditions)
# Person-level flags: diabetes, hypertension, cvd + high-prevalence other conditions.
cond_flags = analytic_cohort[["person_id"]].drop_duplicates().copy()
cond_flags[col] = 0
cond_flags.loc[cond_flags["person_id"].isin(ids), col] = 1
selected_flag_rows = []
selected_flag_cols = []
for _, r in selected_other_conditions.iterrows():
cid = r["condition_concept_id"]
cname = str(r["standard_concept_name"])
try:
cid_int = int(cid)
flag_col = f"has_other_{cid_int}"
except Exception:
flag_col = f"has_other_{len(selected_flag_cols)+1}"
if flag_col in cond_flags.columns:
continue
cond_flags[flag_col] = 0
cond_flags.loc[cond_flags["person_id"].isin(ids), flag_col] = 1
selected_flag_cols.append(flag_col)
selected_flag_rows.append(
"condition_concept_id": cid,
"standard_concept_name": cname,
"flag_column": flag_col,
"n_people": int(r["n_people"]),
"n_rows": int(r["n_rows"]),
"pct_people": float(r["pct_people"]),
selected_condition_flags_table = [Link](selected_flag_rows)
audit_df("selected_condition_flags_table", selected_condition_flags_table)
audit_df("comorbidity_flags", cond_flags)
cond_flags,
on="person_id",
how="left",
comorbidity_person[c] = comorbidity_person[c].fillna(0).astype(int)
comorbidity_person["other_selected_condition_count"] = (
comorbidity_person["comorbidity_burden_simple"] = (
+ comorbidity_person["other_selected_condition_count"]
audit_df("comorbidity_person", comorbidity_person)
comorbidity_summary = [Link](
comorbidity_person.groupby("race_3group", dropna=False)
.agg(
n=("person_id", "nunique"),
mean_burden=("comorbidity_burden_simple", "mean"),
median_burden=("comorbidity_burden_simple", "median"),
diabetes_prev=("has_diabetes", "mean"),
hypertension_prev=("has_hypertension", "mean"),
cvd_prev=("has_cvd", "mean"),
mean_other_selected_conditions=("other_selected_condition_count", "mean"),
.reset_index()
.rename(columns={"race_3group": "group_value"})
.assign(group_type="race_3group"),
comorbidity_person.groupby("ethnicity_2group", dropna=False)
.agg(
n=("person_id", "nunique"),
mean_burden=("comorbidity_burden_simple", "mean"),
median_burden=("comorbidity_burden_simple", "median"),
diabetes_prev=("has_diabetes", "mean"),
hypertension_prev=("has_hypertension", "mean"),
cvd_prev=("has_cvd", "mean"),
mean_other_selected_conditions=("other_selected_condition_count", "mean"),
.reset_index()
.rename(columns={"ethnicity_2group": "group_value"})
.assign(group_type="ethnicity_2group"),
comorbidity_person.groupby("sex_clean", dropna=False)
.agg(
n=("person_id", "nunique"),
mean_burden=("comorbidity_burden_simple", "mean"),
median_burden=("comorbidity_burden_simple", "median"),
diabetes_prev=("has_diabetes", "mean"),
hypertension_prev=("has_hypertension", "mean"),
cvd_prev=("has_cvd", "mean"),
mean_other_selected_conditions=("other_selected_condition_count", "mean"),
)
.reset_index()
.rename(columns={"sex_clean": "group_value"})
.assign(group_type="sex_clean"),
.groupby("initiation_group", dropna=False)
.agg(
n=("person_id", "nunique"),
mean_burden=("comorbidity_burden_simple", "mean"),
median_burden=("comorbidity_burden_simple", "median"),
diabetes_prev=("has_diabetes", "mean"),
hypertension_prev=("has_hypertension", "mean"),
cvd_prev=("has_cvd", "mean"),
mean_other_selected_conditions=("other_selected_condition_count", "mean"),
.reset_index()
.rename(columns={"initiation_group": "group_value"})
.assign(group_type="initiation_group"),
],
ignore_index=True,
audit_df("comorbidity_summary", comorbidity_summary)
comorbidity_limitations = [Link]([
{"note": "Comorbidity groups are keyword-based from loaded condition names and may under/over-capture true prevalence."},
{"note": f"Additional 'other condition' flags include only conditions with n_people >= {MIN_OTHER_CONDITION_PEOPLE} in the analytic cohort."},
{"note": "No formal validated Charlson Comorbidity Index is implemented in this loaded-data-only pipeline."},
])
audit_df("comorbidity_limitations", comorbidity_limitations)
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
print("\n=== DATA ASSURANCE AND ROBUSTNESS CHECKS ===")
cohort_n = int(len(analytic_cohort))
v = int(violations)
return {
"check": check,
"n_violations": v,
"denominator_n": int(denominator),
"pct_violations": pct,
}
cohort_timeline_qc_rows = []
cohort_timeline_qc_rows.append(
_qc_row(
"analytic_cohort_one_row_per_person",
int(len(analytic_cohort) - analytic_cohort["person_id"].nunique()),
cohort_n,
cohort_timeline_qc_rows.append(
_qc_row(
"cohort_baseline_date_gte_index_date",
int(
analytic_cohort["cohort_baseline_date"].notna()
& analytic_cohort["index_date"].notna()
).sum()
),
cohort_n,
cohort_timeline_qc_rows.append(
_qc_row(
"followup_end_date_gte_cohort_baseline_date",
int(
analytic_cohort["followup_end_date"].notna()
& analytic_cohort["cohort_baseline_date"].notna()
).sum()
),
cohort_n,
cohort_timeline_qc_rows.append(
_qc_row(
"age_at_index_gte_18",
int((pd.to_numeric(analytic_cohort["age_at_index"], errors="coerce") < 18).fillna(False).sum()),
cohort_n,
cohort_timeline_qc_rows.append(
_qc_row(
"drug_date_not_before_date_of_birth",
int(
drug_with_dob["drug_date"].notna()
& drug_with_dob["date_of_birth"].notna()
).sum()
),
int(drug_with_dob["drug_date"].notna().sum()),
cohort_timeline_qc_rows.append(
_qc_row(
"first_dmt_date_not_before_treatment_start_date_for_initiators",
int(
initiator_df["first_dmt_date"].notna()
& initiator_df["treatment_start_date"].notna()
).sum()
),
int(len(initiator_df)),
cohort_timeline_qc_rows.append(
_qc_row(
"days_to_dmt_nonnegative",
int(pd.to_numeric(analytic_cohort["days_to_dmt"], errors="coerce").notna().sum()),
)
cohort_timeline_qc_rows.append(
_qc_row(
"time_to_event_days_nonnegative",
int(pd.to_numeric(analytic_cohort["time_to_event_days"], errors="coerce").notna().sum()),
cohort_timeline_qc_rows.append(
_qc_row(
"time_to_discontinuation_nonnegative",
int(pd.to_numeric(switching_person["time_to_discontinuation"], errors="coerce").notna().sum()),
cohort_timeline_qc_rows.append(
_qc_row(
"days_to_high_efficacy_dmt_nonnegative",
int(pd.to_numeric(high_efficacy_df["days_to_high_efficacy_dmt"], errors="coerce").notna().sum()),
)
data_assurance_cohort_timeline_qc = [Link](cohort_timeline_qc_rows)
audit_df("data_assurance_cohort_timeline_qc", data_assurance_cohort_timeline_qc)
dmt_end_date_source_summary = (
dmt_history["end_date_source"]
.fillna("missing_unassessable")
.value_counts(dropna=False)
.rename_axis("end_date_source")
.reset_index(name="n")
dmt_end_date_source_summary["pct"] = (
audit_df("dmt_end_date_source_summary", dmt_end_date_source_summary)
dmt_end_date_source_by_class = (
dmt_history.assign(
dmt_class=dmt_history["dmt_class"].fillna("Missing"),
end_date_source=dmt_history["end_date_source"].fillna("missing_unassessable"),
.size()
.reset_index(name="n")
_class_tot = (
dmt_end_date_source_by_class.groupby("dmt_class", dropna=False)["n"]
.sum()
.reset_index(name="class_total_n")
dmt_end_date_source_by_class = dmt_end_date_source_by_class.merge(
dmt_end_date_source_by_class["pct_within_class"] = (
)
audit_df("dmt_end_date_source_by_class", dmt_end_date_source_by_class)
_end_before_start_n = int(
dmt_history["expected_end_date"].notna()
& dmt_history["drug_date"].notna()
).sum()
_ord_sorted["prev_exposure_order"] = _ord_sorted.groupby("person_id")["exposure_order"].shift(1)
_order_not_strict_n = int(
_ord_sorted["prev_exposure_order"].notna()
).sum()
)
_order_span = (
dmt_history.groupby("person_id", dropna=False)["exposure_order"]
.reset_index()
_order_sequence_gap_person_n = int(
(_order_span["min_order"] != 1)
| (_order_span["max_order"] != _order_span["n_rows"])
| (_order_span["nunique_order"] != _order_span["n_rows"])
).sum()
_first_exposure = (
_ord_sorted.groupby("person_id", as_index=False)
.head(1)
.copy()
_first_prior_present_n = int(_first_exposure["prior_dmt_class"].notna().sum())
dmt_construction_qc_rows = [
_qc_row(
"expected_end_date_gte_drug_date_when_both_present",
_end_before_start_n,
),
_qc_row(
"exposure_order_strictly_increasing_within_person",
_order_not_strict_n,
int(len(dmt_history)),
),
_qc_row(
"exposure_order_sequence_has_no_person_level_gaps",
_order_sequence_gap_person_n,
int(dmt_history["person_id"].nunique()),
),
_qc_row(
"first_exposure_has_no_prior_dmt_class",
_first_prior_present_n,
int(len(_first_exposure)),
),
data_assurance_dmt_construction_qc = [Link](dmt_construction_qc_rows)
audit_df("data_assurance_dmt_construction_qc", data_assurance_dmt_construction_qc)
disc_sensitivity_rows = []
_tmp = last_episode.copy()
_tmp["discontinuation_assessable_tmp"] = (
_tmp["gap_after_last_end_days_tmp"] = (
_tmp["followup_end_date"] - _tmp["expected_end_date"]
).[Link]
_tmp["discontinued_tmp"] = [Link](
_tmp["discontinuation_assessable_tmp"]
& (_tmp["gap_after_last_end_days_tmp"] > _gap),
1,
0,
_tmp["discontinuation_date_tmp"] = [Link]
_tmp.loc[_m, "discontinuation_date_tmp"] = (
_tmp["event_or_censor_date_tmp"] = _tmp["followup_end_date"]
_tmp["discontinued_tmp"].eq(1), "discontinuation_date_tmp"
_tmp["time_to_discontinuation_tmp"] = (
pd.to_datetime(_tmp["event_or_censor_date_tmp"], errors="coerce").[Link]()
- pd.to_datetime(_tmp["first_dmt_date"], errors="coerce").[Link]()
).[Link]
_tmp["time_to_discontinuation_tmp"] = pd.to_numeric(
_tmp["time_to_discontinuation_tmp"], errors="coerce"
).clip(lower=0)
_assess_n = int(_tmp["discontinuation_assessable_tmp"].sum())
_disc_n = int(_tmp["discontinued_tmp"].sum())
disc_sensitivity_rows.append(
"threshold_days": int(_gap),
"n_people": int(len(_tmp)),
"discontinuation_assessable_n": _assess_n,
"discontinued_n": _disc_n,
"discontinued_pct_among_assessable": (
),
"median_time_to_discontinuation": exact_median(
_tmp.loc[_tmp["discontinued_tmp"].eq(1), "time_to_discontinuation_tmp"]
),
)
discontinuation_sensitivity_summary = [Link](disc_sensitivity_rows)
audit_df("discontinuation_sensitivity_summary", discontinuation_sensitivity_summary)
_cand = _cand[
_cand["baseline_date"].notna()
& _cand["drug_date"].notna()
].copy()
_first = (
_cand.sort_values(["person_id", "drug_date"])
.drop_duplicates("person_id", keep="first")
[["person_id", "drug_date"]]
.rename(columns={"drug_date": "first_dmt_date_sensitivity"})
_res["initiated"] = _res["first_dmt_date_sensitivity"].notna().astype(int)
_res["days_to_dmt"] = (
_res["first_dmt_date_sensitivity"] - _res["baseline_date"]
).[Link]
return {
"baseline_definition": baseline_name,
"cohort_n": int(len(_res)),
"initiated_n": int(_res["initiated"].sum()),
baseline_definition_sensitivity_summary = [Link](
audit_df("baseline_definition_sensitivity_summary", baseline_definition_sensitivity_summary)
MANUAL_AUDIT_SAMPLE_N = 25
MANUAL_AUDIT_SEED = 42
manual_cols = [
"person_id",
"drug_date",
"ingredient_name",
"dmt_class",
"expected_end_date",
"end_date_source",
"exposure_order",
"prior_dmt_class",
"switched_class",
"escalated",
"deescalated",
_exposed_ids = [Link](sorted(dmt_history["person_id"].dropna().unique()))
if len(_exposed_ids) > 0:
_rng = [Link].default_rng(MANUAL_AUDIT_SEED)
dmt_manual_audit_sample_25 = (
dmt_history[dmt_history["person_id"].isin(_sample_ids)][manual_cols]
.reset_index(drop=True)
else:
dmt_manual_audit_sample_25 = [Link](columns=manual_cols)
print("[INFO] Manual audit sample is empty because no DMT exposures were available.")
baseline_definition_audit["status"] = [Link](
(baseline_definition_audit["population_type"] == "whole_cohort")
& baseline_definition_audit["baseline_used"].[Link]("index_date", regex=False)
| (
(baseline_definition_audit["population_type"] == "initiator_only")
),
"PASS",
"FAIL",
audit_df("baseline_definition_audit", baseline_definition_audit)
print(
"For analyses including both initiators and non-initiators, index_date was used as the common baseline. "
"For initiator-only treatment-pathway analyses, first DMT exposure date was used as the treatment-specific baseline."
# -----------------------------------------------------------------------------
# Basic QC checks
qc_checks = []
qc_checks.append({"check": "utilization_rows_nonempty", "value": int(len(visit_util)), "status": "ok" if len(visit_util) > 0 else "review"})
qc_checks.append({"check": "comorb_rows_nonempty", "value": int(len(comorb)), "status": "ok" if len(comorb) > 0 else "review"})
lse "review"})
qc_checks.append({
"check": "baseline_definition_audit_all_pass",
})
qc_df = [Link](qc_checks)
audit_df("qc_df", qc_df)
cohort_flow_ok = bool(
(cohort_flow_summary["step"] == "lookback_removed_for_ms_only").any()
and int(
cohort_flow_summary.loc[
].sum()
)
== 0
comorb_ok = bool(
qc_gates = [Link](
make_gate(
"mapping_unique_and_no_inflation",
f"dmt_mapping_unique={dmt_mapping_unique_ok}, "
f"drug_rows={len(drug_df):,}, drug_mapped_rows={len(drug_mapped):,}"
),
),
make_gate(
"cohort_flow_consistency",
cohort_flow_ok,
),
make_gate(
"utilization_nonempty_or_proven_none",
utilization_ok,
f"candidates_before_window={util_candidates_before_window:,}, "
f"rows_after_window={len(visit_util):,}"
),
),
make_gate(
"comorbidity_nonempty_and_required_flags",
comorb_ok,
(
f"comorb_candidates={comorb_candidates_after_merge:,}, "
f"rows_after_window={len(comorb):,}, selected_other_conditions={len(selected_other_conditions):,}"
),
),
make_gate(
"high_efficacy_summary_nonempty",
high_eff_ok,
f"rows={len(high_efficacy_summary):,}",
),
make_gate(
"baseline_standardization_consistent",
baseline_standardization_ok,
),
),
)
audit_df("qc_gates", qc_gates)
rowcount_fix_summary = [Link](
{"section": "dmt_mapping", "before": original_unique_concepts_n, "after": len(cleaned_dmt_mapping), "detail": "unique concepts vs canonical mapping rows"},
_n}, key_removed={key_dupe_rows_n}"},
audit_df("rowcount_fix_summary", rowcount_fix_summary)
critical_issues_fixed = [
"Removed dependence on new SQL pulls; pipeline now uses loaded dataframes only.",
"DMT mapping is now canonical one-row-per-concept with many_to_one merge validation and no row inflation.",
"Pre-index DMT is no longer used as an exclusion concept; pre_index_dmt_flag is forced to 0 in this MS-only extract.",
"Baseline standardization is explicit: whole-cohort analyses use index_date, initiator-only treatment-pathway analyses use first_dmt_date.",
"Utilization rebuilt on post-baseline 365-day window with date normalization and explicit non-empty validation.",
"Comorbidity rebuilt with diabetes/hypertension/cvd plus additional high-prevalence other conditions (n_people >= 200).",
"High-efficacy summary is descriptive-only and log-rank columns are removed to avoid ambiguous inference outputs.",
"Race analyses now use fixed 3-group race (White, Black, Other), and ethnicity analyses use Hispanic vs Non-Hispanic.",
"Unsupported inferred person-level covariates (insurance/state/rural/employment) are not required for final outputs.",
remaining_limitations = [
"MS diagnosis identification is based on loaded condition concept names (no live concept hierarchy expansion in this script).",
"Discontinuation depends on end-date availability; rows without end-date evidence remain unassessable.",
"Comorbidity definitions are rule-based from condition names and not a fully validated phenotype library.",
removed_or_deferred = [
"Insurance/payer type as a patient-level payer variable (not robustly derivable from loaded tables only).",
for x in critical_issues_fixed:
print(f"- {x}")
print("\nRemaining limitations:")
for x in remaining_limitations:
print(f"- {x}")
print("\nAnalyses removed/deferred:")
for x in removed_or_deferred:
print(f"- {x}")
cohort_flow_summary.to_csv(f"{OUTPUT_DIR}/cohort_flow_summary.csv", index=False)
analytic_cohort.to_csv(f"{OUTPUT_DIR}/analytic_cohort.csv", index=False)
display_descriptive_table_sex.to_csv(f"{OUTPUT_DIR}/descriptive_table_sex.csv", index=False)
display_descriptive_table_race_eth.to_csv(f"{OUTPUT_DIR}/descriptive_table_race_eth.csv", index=False)
display_descriptive_table_ethnicity.to_csv(f"{OUTPUT_DIR}/descriptive_table_ethnicity.csv", index=False)
display_descriptive_table_first_dmt.to_csv(f"{OUTPUT_DIR}/descriptive_table_first_dmt.csv", index=False)
display_race_by_dmt_crosstab.to_csv(f"{OUTPUT_DIR}/race_by_dmt_crosstab.csv", index=False)
delay_category_summary.to_csv(f"{OUTPUT_DIR}/delay_category_summary.csv", index=False)
delay_category_ethnicity_summary.to_csv(f"{OUTPUT_DIR}/delay_category_ethnicity_summary.csv", index=False)
calendar_era_summary.to_csv(f"{OUTPUT_DIR}/calendar_era_summary.csv", index=False)
high_efficacy_summary.to_csv(f"{OUTPUT_DIR}/high_efficacy_summary.csv", index=False)
race_ethnicity_association.to_csv(f"{OUTPUT_DIR}/race_ethnicity_association.csv", index=False)
race_eth_ct.to_csv(f"{OUTPUT_DIR}/race_ethnicity_contingency.csv", index=False)
intersectional_summary.to_csv(f"{OUTPUT_DIR}/intersectional_summary.csv", index=False)
utilization_summary.to_csv(f"{OUTPUT_DIR}/utilization_summary.csv", index=False)
dmt_history.to_csv(f"{OUTPUT_DIR}/dmt_history_analytic.csv", index=False)
switching_summary.to_csv(f"{OUTPUT_DIR}/switching_summary.csv", index=False)
comorbidity_summary.to_csv(f"{OUTPUT_DIR}/comorbidity_summary.csv", index=False)
known_group_summary.to_csv(f"{OUTPUT_DIR}/comorbidity_known_group_summary.csv", index=False)
top_other_conditions.to_csv(f"{OUTPUT_DIR}/comorbidity_top_other_conditions.csv", index=False)
selected_condition_flags_table.to_csv(f"{OUTPUT_DIR}/comorbidity_selected_other_condition_flags.csv", index=False)
missingness_summary.to_csv(f"{OUTPUT_DIR}/missingness_summary.csv", index=False)
dmt_exposure_dedup_summary.to_csv(f"{OUTPUT_DIR}/dmt_exposure_dedup_summary.csv", index=False)
rowcount_fix_summary.to_csv(f"{OUTPUT_DIR}/rowcount_fix_summary.csv", index=False)
qc_gates.to_csv(f"{OUTPUT_DIR}/qc_gates_pass_fail.csv", index=False)
[Link](root_cause_items).to_csv(f"{OUTPUT_DIR}/root_cause_issue_cause_fix.csv", index=False)
data_assurance_cohort_timeline_qc.to_csv(f"{OUTPUT_DIR}/data_assurance_cohort_timeline_qc.csv", index=False)
data_assurance_dmt_construction_qc.to_csv(f"{OUTPUT_DIR}/data_assurance_dmt_construction_qc.csv", index=False)
dmt_end_date_source_summary.to_csv(f"{OUTPUT_DIR}/dmt_end_date_source_summary.csv", index=False)
dmt_end_date_source_by_class.to_csv(f"{OUTPUT_DIR}/dmt_end_date_source_by_class.csv", index=False)
discontinuation_sensitivity_summary.to_csv(f"{OUTPUT_DIR}/discontinuation_sensitivity_summary.csv", index=False)
baseline_definition_sensitivity_summary.to_csv(f"{OUTPUT_DIR}/baseline_definition_sensitivity_summary.csv", index=False)
baseline_definition_audit.to_csv(f"{OUTPUT_DIR}/baseline_definition_audit.csv", index=False)
dmt_manual_audit_sample_25.to_csv(f"{OUTPUT_DIR}/dmt_manual_audit_sample_25.csv", index=False)
# Save exact (unsuppressed) descriptive tables as additional reproducibility artifacts.
descriptive_table_sex.to_csv(f"{OUTPUT_DIR}/descriptive_table_sex_exact_unsuppressed.csv", index=False)
descriptive_table_race_eth.to_csv(f"{OUTPUT_DIR}/descriptive_table_race_eth_exact_unsuppressed.csv", index=False)
descriptive_table_ethnicity.to_csv(f"{OUTPUT_DIR}/descriptive_table_ethnicity_exact_unsuppressed.csv", index=False)
descriptive_table_first_dmt.to_csv(f"{OUTPUT_DIR}/descriptive_table_first_dmt_exact_unsuppressed.csv", index=False)
race_by_dmt_crosstab.to_csv(f"{OUTPUT_DIR}/race_by_dmt_crosstab_exact_unsuppressed.csv", index=False)
qc_df.to_csv(f"{OUTPUT_DIR}/_qc_checks.csv", index=False)
validation_compare_df.to_csv(f"{OUTPUT_DIR}/_validation_compare_existing_analysis.csv", index=False)
summary_exact.to_csv(f"{OUTPUT_DIR}/_summary_exact_metrics.csv", index=False)
print("- cleaned_dmt_mapping.csv")
print("- cohort_flow_summary.csv")
print("- analytic_cohort.csv")
print("- descriptive_table_sex.csv")
print("- descriptive_table_race_eth.csv")
print("- descriptive_table_ethnicity.csv")
print("- descriptive_table_first_dmt.csv")
print("- race_by_dmt_crosstab.csv")
print("- delay_category_summary.csv")
print("- delay_category_ethnicity_summary.csv")
print("- calendar_era_summary.csv")
print("- high_efficacy_summary.csv")
print("- race_ethnicity_association.csv")
print("- race_ethnicity_contingency.csv")
print("- intersectional_summary.csv")
print("- utilization_summary.csv")
print("- dmt_history_analytic.csv")
print("- switching_summary.csv")
print("- comorbidity_summary.csv")
print("- comorbidity_known_group_summary.csv")
print("- comorbidity_top_other_conditions.csv")
print("- comorbidity_selected_other_condition_flags.csv")
print("- missingness_summary.csv")
print("- dmt_exposure_dedup_summary.csv")
print("- rowcount_fix_summary.csv")
print("- qc_gates_pass_fail.csv")
print("- root_cause_issue_cause_fix.csv")
print("- data_assurance_cohort_timeline_qc.csv")
print("- data_assurance_dmt_construction_qc.csv")
print("- dmt_end_date_source_summary.csv")
print("- dmt_end_date_source_by_class.csv")
print("- discontinuation_sensitivity_summary.csv")
print("- baseline_definition_sensitivity_summary.csv")
print("- baseline_definition_audit.csv")
print("- dmt_manual_audit_sample_25.csv")
print("\nPipeline complete.")