Download code/ae_rates.py from DBbun/oligotox-phase2-dataset: direct link, hf CLI and curl.
- Browser
- Download file 20.2 kB
-
https://huggingface.co/datasets/DBbun/oligotox-phase2-dataset/resolve/main/code/ae_rates.py
- Command line
-
hf download hf://datasets/DBbun/oligotox-phase2-dataset/code/ae_rates.py
-
curl -L -o ae_rates.py https://huggingface.co/datasets/DBbun/oligotox-phase2-dataset/resolve/main/code/ae_rates.py
20.2 kB
| """ | |
| Correct computation of adverse-event rates from ClinicalTrials.gov results. | |
| A bug in the earlier analysis: rates were computed as | |
| sum(num_affected) / sum(num_at_risk) | |
| over MedDRA term rows. Each term row for one trial arm repeats that arm's | |
| at-risk count, so summing inflated the denominator once per term - by about | |
| 2.5x for inclisiran (22,483 reported against 8,920 actual). The numerator was | |
| inflated too, since a participant with both "ALT increased" and "AST increased" | |
| is counted twice. Both errors pushed in the same direction, which is why the | |
| resulting rates looked plausible. Five arm-level rates exceeded 100%, one | |
| reaching 200%. | |
| What aggregate registry data can and cannot support: | |
| CAN: the rate for a single MedDRA term in a single arm, exactly, as | |
| num_affected / num_at_risk for that arm. | |
| CAN: a lower bound on the share of participants with at least one event | |
| from a group of related terms - the largest single-term rate, since | |
| at least that many distinct participants were affected. | |
| CANNOT: the exact share of participants with at least one event from a group | |
| of terms. Overlap between terms is not reported, so this is simply not | |
| recoverable. Any figure claiming it is an artifact of the arithmetic. | |
| This module therefore reports the per-term rate as the exact quantity, and the | |
| maximum single-term rate as an explicit lower bound where a grouped figure is | |
| needed. Every function asserts that no rate exceeds 100%. | |
| """ | |
| from __future__ import annotations | |
| import pandas as pd | |
| # Terms used for the hepatic grouping. Deliberately narrow and explicit: these | |
| # are laboratory and diagnosis terms for hepatocellular injury. Broader terms | |
| # such as "hepatic neoplasm" or "liver disorder" are excluded because they | |
| # conflate underlying disease with drug effect. Earlier figures and tables used | |
| # two different patterns without saying so, giving 22 drugs in one place and 28 | |
| # in another. | |
| # Matched loosely enough to survive registry spelling. An exact-phrase pattern | |
| # silently dropped "Alanine aminotransferase abnormal", a bare "Aspartate | |
| # aminotransferase", "Hepatic enzyme abnormal", and the sponsor misspelling | |
| # "Alanine aminotrasferase increased" - about 20 rows across several drugs. | |
| # | |
| # Gamma-glutamyltransferase is deliberately NOT included, though it accounts for | |
| # a further ~90 rows. GGT is a hepatobiliary and enzyme-induction marker rather | |
| # than a hepatocellular injury one, and standard drug-induced liver injury | |
| # definitions key on ALT, AST and bilirubin. Including it would raise every rate | |
| # reported here; excluding it is a judgement, and is stated so it can be undone. | |
| HEPATOCELLULAR = ( | |
| r"alanine aminotra?n?sferase" # tolerate the registry misspelling | |
| r"|aspartate aminotransferase" | |
| r"|transaminases? (?:increased|abnormal)" | |
| r"|hypertransaminasaemia" | |
| r"|hepatic enzyme (?:increased|abnormal)" | |
| r"|liver function test (?:abnormal|increased)" | |
| r"|hepatotoxicity" | |
| r"|drug-induced liver injury" | |
| ) | |
| # Result groups are not always disjoint treatment populations, and the group | |
| # title is the only thing that says so. Three kinds of row must be removed or | |
| # relabelled before any arm can be counted once. | |
| # | |
| # Aggregate groups restate participants already counted in the component | |
| # groups, and some of them fold the comparator in: NCT05192941 lists | |
| # inclisiran at 900, placebo at 870 and "Total" at 1,770, with the total | |
| # flagged as active, so that trial contributed 2,670 active participants out | |
| # of 1,770 people and 870 placebo recipients were counted as treated. | |
| # | |
| # An arm can study a different drug entirely. NCT05386680's "OAV101 ... All | |
| # Participants" sits under nusinersen because the trial enrolled patients who | |
| # had discontinued it; its events are not nusinersen's. | |
| # | |
| # An active comparator is still a comparator. Fitusiran's factor/bypassing- | |
| # agent prophylaxis arm and inclisiran's usual-care arm were flagged as | |
| # treatment, putting another therapy's outcomes into the named drug's rate. | |
| AGGREGATE_TITLE = ( | |
| r"^\s*(?:total|overall|combined|pooled)\b" | |
| r"|^\s*all\s+\w+" | |
| r"|\ball\s+(?:participants|patients|subjects|treated)\b" | |
| r"|\bpooled\s+\w+" | |
| r"|[(](?:total|overall)[)]") | |
| NOT_THE_STUDY_DRUG = { # (nct_id, arm_group_id) -> why | |
| ("NCT05386680", "EG000"): "arm studies OAV101, not the drug it is filed under", | |
| } | |
| ACTIVE_COMPARATOR = r"usual care|factor/bpa|bypassing agent|standard of care" | |
| def clean_arms(df: pd.DataFrame) -> pd.DataFrame: | |
| """Drop groups that cannot be counted once, and fix comparator labels.""" | |
| title = df.arm_title.fillna("").str.strip() | |
| agg = title.str.contains(AGGREGATE_TITLE, case=False, regex=True) | |
| wrong = pd.Series(list(zip(df.nct_id, df.arm_group_id)), | |
| index=df.index).isin(NOT_THE_STUDY_DRUG) | |
| # A title heuristic must not silently empty a trial. A single-arm study | |
| # legitimately titled "All Participants" would otherwise disappear, and | |
| # the classes most likely to run single-arm studies are the ones with the | |
| # fewest events. A group removed for studying another drug is still | |
| # removed, since its events are not this drug's. | |
| sole = df.groupby("nct_id").arm_group_id.transform("nunique").eq(1) | |
| agg = agg & ~sole | |
| # An arm whose title names other study drugs and not the one it is filed | |
| # under is that other drug's arm. Head-to-head and switch trials produce | |
| # these: NCT03532542 files golodirsen's arm under casimersen and the | |
| # reverse, and NCT04136184 files eplontersen's 144-participant arm under | |
| # inotersen. Naming the cases one at a time would only cover the ones | |
| # already seen, so the test is general. | |
| import re as _re | |
| known = sorted({d for d in df.drug.dropna().unique()}) | |
| patterns = {d: _re.compile(r"(?<![a-z])" + _re.escape(d) + r"(?![a-z])") | |
| for d in known} | |
| def _other_drugs_arm(row): | |
| title = str(row.arm_title).lower() | |
| named = {d for d, pat in patterns.items() if pat.search(title)} | |
| return bool(named) and row.drug not in named | |
| misfiled = df.apply(_other_drugs_arm, axis=1).astype(bool) | |
| out = df[~agg & ~wrong & ~misfiled].copy() | |
| is_active_comp = out.arm_title.fillna("").str.contains( | |
| ACTIVE_COMPARATOR, case=False, regex=True) | |
| out.loc[is_active_comp, "arm_is_comparator"] = 1 | |
| return out | |
| def arm_universe(df: pd.DataFrame, active_only: bool = True) -> pd.DataFrame: | |
| """Every arm that could have reported the event, with its population. | |
| The denominator must not depend on whether the arm reported a hepatic | |
| term. Filtering to matching rows first drops every arm that reported none, | |
| which are disproportionately the low-signal arms, so the surviving rate is | |
| not a lower bound on anything - it is the rate among arms that reported the | |
| event. Of 401 active arms only 213 report a hepatic term; the other 188 | |
| belong in the denominator with a numerator of zero. | |
| """ | |
| d = clean_arms(df) | |
| if active_only: | |
| d = d[d.arm_is_comparator == 0] | |
| return (d.groupby(["drug", "nct_id", "arm_group_id"], as_index=False) | |
| .agg(at_risk=("num_at_risk", "max"), | |
| sugar_backbone_chemistry=("sugar_backbone_chemistry", "first"), | |
| delivery_platform=("delivery_platform", "first"))) | |
| def arm_level(df: pd.DataFrame) -> pd.DataFrame: | |
| """Collapse term rows to one row per (trial, arm, term). | |
| num_at_risk is a property of the arm, so it is taken once rather than | |
| summed. The rate is exact for a term reported under a single seriousness | |
| category, which is nearly all of them. Where a registry reports the same | |
| term as both serious and non-serious in one arm, the two counts cover | |
| participant sets whose overlap is not reported, so taking the maximum is a | |
| lower bound there and not an exact rate. 34 of the 441 active hepatic | |
| arm-term combinations are in that position; the `exact_rate` column marks | |
| which, so a reader is not told something exact that is not. | |
| """ | |
| # A missing count is not a zero count, but it cannot contribute to a lower | |
| # bound either; treating it as zero keeps the bound valid and keeps the | |
| # arm's population in the denominator. | |
| df = df.copy() | |
| df["num_affected"] = df.num_affected.fillna(0) | |
| out = (df.groupby(["drug", "nct_id", "arm_group_id", "ae_term"], as_index=False) | |
| .agg(num_affected=("num_affected", "max"), | |
| num_affected_sum=("num_affected", "sum"), | |
| num_at_risk=("num_at_risk", "max"), | |
| arm_is_comparator=("arm_is_comparator", "max"), | |
| n_seriousness=("event_seriousness", "nunique"), | |
| sugar_backbone_chemistry=("sugar_backbone_chemistry", "first"), | |
| delivery_platform=("delivery_platform", "first"))) | |
| out["pct"] = 100.0 * out.num_affected / out.num_at_risk | |
| out["exact_rate"] = (out.n_seriousness <= 1).astype(int) | |
| bad = out[out.pct > 100] | |
| assert bad.empty, f"per-term rate above 100% in {len(bad)} rows - check the source" | |
| return out | |
| def grouped_lower_bound(terms: pd.DataFrame, by: list[str], | |
| universe: pd.DataFrame | None = None) -> pd.DataFrame: | |
| """Lower bound on participants with at least one of the grouped terms. | |
| Within an arm, take the largest single-term count: at least that many | |
| distinct participants were affected. Sum those over arms, and sum each | |
| arm's at-risk once. This cannot exceed 100% and never double-counts. | |
| """ | |
| per_arm = (terms.groupby(by + ["nct_id", "arm_group_id"], as_index=False) | |
| .agg(affected_lb=("num_affected", "max"))) | |
| # The denominator is every arm that could have reported the event, not | |
| # only those that did. universe must be supplied by the caller, built from | |
| # the unfiltered table, or arms reporting no hepatic term silently vanish | |
| # from the denominator and inflate the rate. | |
| if universe is None: | |
| per_arm_risk = (terms.groupby(by + ["nct_id", "arm_group_id"], | |
| as_index=False) | |
| .agg(at_risk=("num_at_risk", "max"))) | |
| else: | |
| per_arm_risk = universe.groupby(by + ["nct_id", "arm_group_id"], | |
| as_index=False).agg(at_risk=("at_risk", "max")) | |
| per_arm = per_arm_risk.merge(per_arm, how="left", | |
| on=by + ["nct_id", "arm_group_id"]) | |
| per_arm["affected_lb"] = per_arm.affected_lb.fillna(0) | |
| out = (per_arm.groupby(by, as_index=False) | |
| .agg(affected_lb=("affected_lb", "sum"), | |
| at_risk=("at_risk", "sum"), | |
| n_arms=("arm_group_id", "size"))) | |
| out["pct_lower_bound"] = 100.0 * out.affected_lb / out.at_risk | |
| bad = out[out.pct_lower_bound > 100] | |
| assert bad.empty, f"grouped lower bound above 100% for {len(bad)} groups" | |
| return out | |
| def grouped_bounds(terms: pd.DataFrame, by: list[str], | |
| universe: pd.DataFrame | None = None) -> pd.DataFrame: | |
| """Both bounds on participants with at least one of the grouped terms. | |
| The lower bound assumes every term in an arm hit the same people; the | |
| upper assumes no participant appears under two terms, capped at the arm's | |
| population since it cannot exceed it. The upper bound sums the per-term, | |
| per-seriousness counts rather than the maxima arm_level() keeps for the | |
| lower bound: a term reported as five serious and seven non-serious can | |
| involve twelve people, and summing the collapsed maximum would have | |
| claimed seven. The truth lies between, and registry | |
| results never report the overlap that would locate it. Giving only the | |
| lower bound leaves a reader unable to see how wide that gap is - for some | |
| arms it is narrow, for others it is most of the range. | |
| """ | |
| per_arm = (terms.groupby(by + ["nct_id", "arm_group_id"], as_index=False) | |
| .agg(affected_lb=("num_affected", "max"), | |
| affected_sum=("num_affected_sum", "sum"))) | |
| # Same denominator rule as the lower bound: every arm that could have | |
| # reported the event, not only those that did. | |
| if universe is None: | |
| risk = (terms.groupby(by + ["nct_id", "arm_group_id"], as_index=False) | |
| .agg(at_risk=("num_at_risk", "max"))) | |
| else: | |
| risk = universe.groupby(by + ["nct_id", "arm_group_id"], | |
| as_index=False).agg(at_risk=("at_risk", "max")) | |
| per_arm = risk.merge(per_arm, how="left", | |
| on=by + ["nct_id", "arm_group_id"]) | |
| per_arm[["affected_lb", "affected_sum"]] = per_arm[ | |
| ["affected_lb", "affected_sum"]].fillna(0) | |
| per_arm["affected_ub"] = per_arm[["affected_sum", "at_risk"]].min(axis=1) | |
| out = (per_arm.groupby(by, as_index=False) | |
| .agg(affected_lb=("affected_lb", "sum"), | |
| affected_ub=("affected_ub", "sum"), | |
| at_risk=("at_risk", "sum"), | |
| n_arms=("arm_group_id", "size"))) | |
| out["pct_lower_bound"] = 100.0 * out.affected_lb / out.at_risk | |
| out["pct_upper_bound"] = 100.0 * out.affected_ub / out.at_risk | |
| assert (out.pct_upper_bound <= 100.0001).all() | |
| assert (out.pct_lower_bound <= out.pct_upper_bound).all() | |
| return out | |
| def hepatic(ae: pd.DataFrame, active_only: bool = True) -> pd.DataFrame: | |
| sub = ae[ae.ae_term.fillna("").str.contains(HEPATOCELLULAR, case=False, regex=True)] | |
| if active_only: | |
| sub = sub[sub.arm_is_comparator == 0] | |
| return arm_level(sub) | |
| def _report(ae: pd.DataFrame) -> None: | |
| # This path used to call hepatic() on uncleaned rows and | |
| # grouped_lower_bound() with no universe, so running the module printed | |
| # the very numbers the module exists to correct. It now goes through | |
| # hepatic_rates(), the one supported entry point. | |
| terms = hepatic(clean_arms(ae)) | |
| print(f"hepatocellular term rows (active arms): {len(terms):,}") | |
| print(f"drugs: {terms.drug.nunique()} trials: {terms.nct_id.nunique()}") | |
| print("\narm cleaning") | |
| print(cleaning_audit(ae).to_string(index=False)) | |
| print("\nper drug, lower bound on participants with >=1 hepatocellular event") | |
| d = hepatic_rates(ae, ["drug"]).sort_values( | |
| "pct_lower_bound", ascending=False) | |
| print(d.head(12).round(2).to_string(index=False)) | |
| print("\nby chemistry class") | |
| c = hepatic_rates(ae, ["sugar_backbone_chemistry"]).sort_values( | |
| "pct_lower_bound", ascending=False) | |
| print(c.round(2).to_string(index=False)) | |
| print("\nsensitivity: does the class gradient survive unweighting?") | |
| per_drug = hepatic_rates(ae, ["sugar_backbone_chemistry", "drug"]) | |
| unw = (per_drug.groupby("sugar_backbone_chemistry") | |
| .pct_lower_bound.agg(["count", "median", "min", "max"]) | |
| .sort_values("median", ascending=False)) | |
| print(unw.round(2).to_string()) | |
| def hepatic_rates(ae: pd.DataFrame, by: list[str], | |
| active_only: bool = True) -> pd.DataFrame: | |
| """The hepatic lower bound, computed the one correct way. | |
| Callers kept having to remember three separate steps - clean the arms, | |
| build the denominator from all of them, then filter to hepatic terms - and | |
| getting any of them wrong silently inflates the rate. Doing the three here | |
| means a caller cannot assemble them wrongly. Every analysis should use | |
| this rather than composing the pieces itself. | |
| """ | |
| clean = clean_arms(ae) | |
| universe = arm_universe(clean, active_only=active_only) | |
| terms = hepatic(clean, active_only=active_only) | |
| return grouped_lower_bound(terms, by, universe=universe) | |
| # The hepatocellular set is a judgement, and a reviewer should see how much | |
| # rests on it. GGT is excluded because it rises with induction as well as | |
| # injury; bilirubin is excluded because the set is deliberately hepatocellular | |
| # rather than a Hy's-law composite, and a bilirubin term alone does not | |
| # establish hepatocellular injury. Both exclusions move the numbers, so both | |
| # are quantified here rather than asserted. | |
| GGT = r"gamma-?glutamyl" | |
| BILIRUBIN = r"bilirubin" | |
| SEVERE = r"hepatic failure|hepatitis|jaundice|liver injury" | |
| def term_set_sensitivity(ae: pd.DataFrame, by: list[str]) -> dict: | |
| """The same rate under four defensible definitions of the term set.""" | |
| out = {} | |
| for name, pattern in ( | |
| ("hepatocellular (used)", HEPATOCELLULAR), | |
| ("plus GGT", f"{HEPATOCELLULAR}|{GGT}"), | |
| ("plus bilirubin", f"{HEPATOCELLULAR}|{BILIRUBIN}"), | |
| ("plus severe diagnoses", f"{HEPATOCELLULAR}|{SEVERE}")): | |
| clean = clean_arms(ae) | |
| universe = arm_universe(clean) | |
| sub = clean[clean.ae_term.fillna("").str.contains( | |
| pattern, case=False, regex=True)] | |
| sub = arm_level(sub[sub.arm_is_comparator == 0]) | |
| r = grouped_lower_bound(sub, by, universe=universe) | |
| out[name] = {k: round(v, 2) for k, v in | |
| zip(r[by[0]], r.pct_lower_bound)} | |
| return out | |
| def cleaning_audit(ae: pd.DataFrame) -> pd.DataFrame: | |
| """How many arms and participants each cleaning rule removes. | |
| The rules below change every rate in the dataset, so their effect is | |
| reported as a table rather than described. A reader can then see the size | |
| of each correction instead of taking the code's word for it. | |
| """ | |
| arms = (ae.groupby(["nct_id", "arm_group_id"], as_index=False) | |
| .agg(at_risk=("num_at_risk", "max"), | |
| arm_title=("arm_title", "first"), | |
| arm_is_comparator=("arm_is_comparator", "max"))) | |
| title = arms.arm_title.fillna("").str.strip() | |
| agg = title.str.contains(AGGREGATE_TITLE, case=False, regex=True) | |
| wrong = pd.Series(list(zip(arms.nct_id, arms.arm_group_id)), | |
| index=arms.index).isin(NOT_THE_STUDY_DRUG) | |
| relabel = (~agg & ~wrong) & title.str.contains( | |
| ACTIVE_COMPARATOR, case=False, regex=True) & (arms.arm_is_comparator == 0) | |
| mis = (ae.groupby(["nct_id", "arm_group_id", "drug"], as_index=False) | |
| .agg(arm_title=("arm_title", "first"), | |
| at_risk=("num_at_risk", "max"))) | |
| import re as _re | |
| known = sorted({d for d in ae.drug.dropna().unique()}) | |
| pats = {d: _re.compile(r"(?<![a-z])" + _re.escape(d) + r"(?![a-z])") | |
| for d in known} | |
| mis_mask = mis.apply( | |
| lambda r: bool({d for d, p in pats.items() | |
| if p.search(str(r.arm_title).lower())}) | |
| and r.drug not in {d for d, p in pats.items() | |
| if p.search(str(r.arm_title).lower())}, axis=1).astype(bool) | |
| rows = [("all result groups", len(arms), int(arms.at_risk.sum())), | |
| ("aggregate groups removed", int(agg.sum()), | |
| int(arms.loc[agg, "at_risk"].sum())), | |
| ("groups studying another drug removed", int(wrong.sum()), | |
| int(arms.loc[wrong, "at_risk"].sum())), | |
| ("arms filed under the wrong drug removed", int(mis_mask.sum()), | |
| int(mis.loc[mis_mask, "at_risk"].sum())), | |
| ("active comparators relabelled", int(relabel.sum()), | |
| int(arms.loc[relabel, "at_risk"].sum()))] | |
| kept = arms[~agg & ~wrong] | |
| active = kept[(kept.arm_is_comparator == 0) & ~relabel[kept.index]] | |
| rows.append(("active arms used as denominator", len(active), | |
| int(active.at_risk.sum()))) | |
| return pd.DataFrame(rows, columns=["step", "arms", "participants"]) | |
| if __name__ == "__main__": | |
| from pathlib import Path | |
| DATA = Path(__file__).with_name("dataset_root_v2") | |
| _report(pd.read_csv(DATA / "measured" / "clinical_adverse_events.csv", | |
| low_memory=False)) | |