A medicine with two effects on readmission and death: separable effects with TMLE#

At a glance#

A heart-failure clinic sends patients home on no water pill, a standard dose or a high dose, as their doctors choose. In this simulated clinic the pill has two parts: one clears fluid, which keeps patients out of hospital, and one lowers blood potassium, which can cause a fatal heart rhythm. So part of any drop in readmissions could be patients who died before they could be readmitted. Would a potassium supplement that blocks the second part keep the benefit without the deaths?

Some patients left the clinic’s follow-up early. Had every patient stayed, the high dose rather than no pill would change readmission by day 90 by -18.6 per 100 patients (95% confidence interval -21.5 to -15.5), and death before any readmission by +23.4 per 100 (20.7 to 26.1). The high dose with the supplement, against no pill, would change readmission by -13.6 per 100 (-16.8 to -10.3) and death by only +1.0 (0.7 to 1.4); the other -5.0 readmissions per 100 are patients who died first. As given, the high dose costs more deaths than the readmissions it saves.

These numbers rest on conditions no data can check: age and prior admissions capture every common cause of the dose, leaving follow-up and the events; the fluid part changes death only through readmission, and the potassium part readmission only through death; the supplement blocks the potassium part and nothing else; and no unrecorded factor, such as frailty, affects both events. The supplement numbers also count a death before a readmission when both fall in the same month; counting the readmission first gives -16.5 (see “Go deeper”). The data are simulated, so we know the true changes (-17.7, +23.1 and -13.1 per 100), and each interval contains its value.

The question#

The clinic decides the dose when the patient goes home; discharge is time zero, when follow-up starts. Follow-up ends at the first readmission or death. They are competing events: a patient who dies can no longer be readmitted. The quantity to estimate is the share readmitted, and the share who die before any readmission, by day 90 under three plans: every patient on the high dose, no patient on the pill, and every patient on the high dose with a supplement that keeps potassium at its level without the pill.

  older, prior_admissions ──▶ dose ──▶ fluid part ──────▶ readmission
           │                       └──▶ potassium part ──▶ death
           └──────────────────────────────────────────▶ readmission, death, leaving follow-up
  assumed absent: fluid part ──▶ death; potassium part ──▶ readmission;
                  an unrecorded cause of the dose and an event, or of both events

Doctors gave higher doses to patients with more admissions in the past year and lower doses to patients aged 75 or older, and both characteristics also change the chance of each event. They are confounders, variables that drive both the dose and the outcome. The clinic checks on patients on days 30, 60 and 90, and a patient can leave follow-up after a check, which is censoring: an event may happen later but the data hide it.

No patient got the supplement. The arrows marked absent let us compute its plan anyway. Because the potassium part has no path to readmission, high-dose patients still alive show the readmission chance under the fluid part. Because the fluid part has no path to death, patients on no pill show the death chance with potassium kept level. A factor that changed both events would make the high-dose survivors unlike the plan’s. Stensrud and colleagues (2022) call this a separable effect.

The data#

from dataclasses import replace

import pandas as pd
from sklearn.linear_model import LogisticRegression

import cleverly

pd.set_option("display.width", 160)
pd.set_option("display.max_columns", 20)
print("cleverly", cleverly.__version__)
cleverly 0.2.4

make_heart_failure draws 8,000 simulated patients and the true answers, which real data never give.

from cleverly.datasets import make_heart_failure

# With your own data, load one row per patient, such as pd.read_csv(...), with the baseline
# characteristics, the dose, the day of the first event or of the last follow-up check, and an
# event code: 1 for a readmission, 2 for a death, 0 for neither by that day.
# Real data have no `truth`: delete the lines marked "simulation only" here and below.
frame, truth = make_heart_failure(n=8_000, seed=11)
print("rows and columns:", frame.shape)
print(list(frame.columns))
print(frame.head().to_string())
print()
print("patients by dose:", frame["dose"].value_counts().sort_index().to_dict())
labels = {0: "neither", 1: "readmission", 2: "death"}
print("first event by day 90:", frame["event"].map(labels).value_counts().to_dict())
left = frame[frame["event"].eq(0) & frame["day"].lt(90)]
print("left follow-up after the check on day:", left["day"].value_counts().sort_index().to_dict())
print()

# simulation only, to the end of the cell: the true risk of each event by day 90. In `truth`,
# readmission_dose is the dose whose fluid part every patient gets, and death_dose the dose
# whose potassium part they get.
by_parts = truth[truth["day"].eq(90)].set_index(["readmission_dose", "death_dose"])
known = pd.DataFrame(
    {
        "high dose": by_parts.loc[(2, 2)],
        "no pill": by_parts.loc[(0, 0)],
        "high dose with supplement": by_parts.loc[(2, 0)],
    }
).T[["readmission", "death"]]
print("true risk by day 90, the share of patients with each event first:")
print(known.round(4).to_string())
rows and columns: (8000, 5)
['older', 'prior_admissions', 'dose', 'day', 'event']
   older  prior_admissions  dose   day  event
0    0.0               3.0   2.0  70.0      2
1    0.0               2.0   1.0  90.0      0
2    1.0               3.0   2.0  11.0      1
3    0.0               3.0   2.0  52.0      1
4    0.0               1.0   0.0  20.0      2

patients by dose: {0.0: 2096, 1.0: 3805, 2.0: 2099}
first event by day 90: {'neither': 4204, 'readmission': 2053, 'death': 1743}
left follow-up after the check on day: {30.0: 518, 60.0: 350}

true risk by day 90, the share of patients with each event first:
                           readmission   death
high dose                       0.1866  0.3610
no pill                         0.3636  0.1300
high dose with supplement       0.2327  0.1409

Each row is one patient. When event is 1 (readmitted) or 2 (died), day is the day it happened, such as day 70 for the death in row 0; when event is 0, day is the last check that found the patient with neither. No plan uses the standard dose, but those patients still help fit the models.

Why a simple comparison misleads#

print("baseline means by dose:")
print(frame.groupby("dose")[["older", "prior_admissions"]].mean().round(3).to_string())
print()

# The simple comparison: the share with each recorded first event by day 90, high dose minus no
# pill.
high_or_none = frame[frame["dose"].isin([0.0, 2.0])]
shares = pd.crosstab(high_or_none["dose"], high_or_none["event"], normalize="index")
print("share with each recorded first event, high dose minus no pill:")
for event_code, cause in ((1, "readmission"), (2, "death")):
    simple = shares.loc[2.0, event_code] - shares.loc[0.0, event_code]
    line = f"  {cause:12s} simple {simple:+.4f}"
    true = known.loc["high dose", cause] - known.loc["no pill", cause]  # simulation only
    line += f", true {true:+.4f}"  # simulation only
    print(line)
baseline means by dose:
      older  prior_admissions
dose                         
0.0   0.492             1.111
1.0   0.394             1.502
2.0   0.292             1.931

share with each recorded first event, high dose minus no pill:
  readmission  simple -0.1358, true -0.1770
  death        simple +0.2099, true +0.2310

High-dose patients had more prior admissions and were less often 75 or older. Prior admissions raise both events, so the high dose went to patients more likely to be readmitted, and the simple readmission difference, -0.1358, is smaller in size than the true -0.1770. The simple shares also count a patient who left follow-up as having neither event. And no simple comparison can estimate the supplement plan, which no patient received.

Set up the analysis#

First, write the study description (StudyProtocol): who is in it, when follow-up starts, what each plan means, and how death and leaving follow-up count. It does not change the estimate; each result keeps a copy, so a reader knows what was estimated.

from cleverly.datasets import heart_failure_protocol

# For your own study, build cleverly.StudyProtocol(...) directly, with the fields printed below.
protocol = heart_failure_protocol()
print("\n".join(protocol.summary_lines()))
Population: Adults sent home from the clinic's hospital after an admission for heart failure
Eligibility: Age 18 years or older; Discharged home alive after a heart-failure admission
Follow-up starts: Discharge, after baseline measurement and the discharge prescription
Strategies: Prescribe the water pill at the high dose; Prescribe no water pill; Prescribe the high dose with a potassium supplement that offsets its potassium loss
Versions: The high dose, taken as prescribed or not; Usual heart-failure care without the water pill; The high dose's fluid-clearing action, with blood potassium kept at its level without the pill
Outcome: First unplanned readmission, and death before any readmission
Horizon: 90 days after discharge, with checks on days 30, 60 and 90
Intercurrent events: Treat death before readmission as a competing event: report the risk of each event first, with neither prevented; Treat leaving follow-up after a check as censoring, so the target is the risk had every patient stayed in follow-up (hypothetical strategy); Analyze the prescribed dose regardless of how the pills were taken
Interference unit: Patient
Rationale: Age and prior admissions recorded at discharge hold every common cause of the dose, of leaving follow-up, and of the two events; The fluid-clearing part changes death only through readmission, and the potassium part changes readmission only through death; No unrecorded cause of both readmission and death exists beyond the recorded characteristics

Each risk is the share of patients with that event first, with neither event prevented.

Next, name the columns for the day, the event code and the dose (TimeToEvent), the event each code stands for (causes=), and the check days (grid=). The fit works month by month, so each event day falls in the month that ends at the next check. cleverly calls a plan a regimen. Separable declares the supplement plan: arms= gives the dose whose part acts on each event, and first= orders a death and a readmission in the same month. RegimeMean asks for each plan’s risks, and study.identify(...) states the question and lists the conditions an answer rests on.

from cleverly import CausalStudy, RegimeMean, TimeToEvent
from cleverly.longitudinal import Separable

# For your own data, change the column names, the check days and the event labels.
design = TimeToEvent(
    time="day",
    event="event",
    treatment="dose",
    baseline=("older", "prior_admissions"),
    grid=(30, 60, 90),
    causes={1: "readmission", 2: "death"},
)
plans = {
    "high dose": 2,
    "no pill": 0,
    # The fluid part at the high dose and the potassium part at no pill. A death counts before a
    # readmission in the same month.
    "high dose with supplement": Separable(arms={"readmission": 2, "death": 0}, first="death"),
}
study = CausalStudy(frame, design=design, protocol=protocol)
risks = study.identify(RegimeMean(plans, horizons=(90,)))
print(risks.summary())
                         Causal question (ey_regime)
==============================================================================
Question:   mean outcome under each     Rows:                            8,000
            declared regime             Answered by:     adjusting for history
Outcome:    event=1@30, event=1@60,
            event=1@90, event=2@30,
            event=2@60, event=2@90
            (event by each time)
Treatment:  dose
Baseline:   older, prior_admissions
==============================================================================
What each treatment time adjusts for
treatment   adjusted for
------------------------------------------------------------------------------
dose        older, prior_admissions
==============================================================================
Conditions the answer rests on
condition                            checkable   what it says
------------------------------------------------------------------------------
well-defined treatment               no          Each unit's observed outcomes
                                                 are the ones it would have
                                                 had under the treatments it
                                                 actually received over time.
                                                 This needs each treatment to
                                                 be well defined: every way of
                                                 getting the same treatment
                                                 has the same effect.
no interference                      no          One unit's treatment does not
                                                 change another unit's
                                                 outcome.
no hidden confounding at each time   no          At each time, among units
                                                 with the same recorded
                                                 history, which treatment a
                                                 unit got and whether it stays
                                                 in follow-up are unrelated to
                                                 the outcomes it would have
                                                 had.
overlap at each time                 partly      At each time, units with
                                                 every history that following
                                                 the compared regimens can
                                                 produce had some chance of
                                                 the treatment a regimen
                                                 assigns and of staying in
                                                 follow-up.
==============================================================================
Methods
method                name
------------------------------------------------------------------------------
tmle                  targeted maximum likelihood (TMLE)
sdr                   sequentially doubly robust regression (SDR)
ipsi                  incremental propensity score intervention (IPSI)
gcomp                 sequential g-computation
ipw                   sequential inverse probability weighting
parametric_gformula   parametric g-formula
==============================================================================
Notes:
[1] The data cannot confirm these conditions. Overlap (marked partly) can be
    probed: after a fit, result.diagnostics.support() shows where the fitted
    treatment model gives units little chance of a compared treatment. That
    check reads a fitted model, so a clean result does not prove overlap.
[2] The methods table lists the methods that fit. 6 other methods cannot
    estimate this question; the full summary says why.

cleverly turns each row into an indicator of each event by each check (event=1@30 is a readmission by day 30). Of the four printed conditions, two carry the most weight here: age and prior admissions hold every common cause of the dose, of leaving follow-up and of either event; and every kind of patient had a real chance of each compared dose and of staying in follow-up (overlap). The supplement plan adds three:

  • the two parts could be given apart;

  • the fluid part changes death only by changing readmission, and the potassium part changes readmission only by changing death;

  • no unrecorded factor, such as frailty, affects both events.

The data cannot check any of these seven except overlap, which the weight check below partly checks; only a trial that gave the two parts apart could test the last three.

Estimate the risk of each event under each plan#

The method, targeted maximum likelihood estimation (TMLE), models the chance of each event in each month among patients still at risk, called a hazard. A correction step then adjusts those models, using the treatment model (who got which dose) and the censoring model (who stays in follow-up), so that right dose and follow-up models can offset an error in one of the two hazard models.

  • outcome_learner predicts the two hazards; survival_model="hazard" asks for hazards, which the supplement plan needs.

  • treatment_learner and censoring_learner predict the dose and staying in follow-up.

  • Targeting(algorithm="one_step") runs the correction step in many small steps, the form a supplement plan requires.

  • CrossFitting(enabled=False) fits every model on all rows, which suits simple models that cannot memorize their training rows.

from cleverly import CrossFitting, ModelSpec, Runtime, Targeting, TMLEMethod


# For your own data, swap in your learners. With flexible learners, leave out
# cross_fitting=... to keep the default, which predicts each row out of fold.
def logistic():
    return LogisticRegression(max_iter=1000, random_state=5)


method = TMLEMethod(
    models=ModelSpec(
        outcome_learner=logistic(),
        treatment_learner=logistic(),
        censoring_learner=logistic(),
        survival_model="hazard",
    ),
    targeting=Targeting(algorithm="one_step"),
    cross_fitting=CrossFitting(enabled=False),
    runtime=Runtime(random_state=5, n_jobs=1),
)
result = risks.estimate(method=method)
print(result.summary())
                        Longitudinal estimate (LTMLE)
==============================================================================
Question:      the event risk under     Rows:                            8,000
               each plan; each row is   Time points:         3 (at 30, 60, 90)
               defined below            Out-of-fold predictions:            no
Outcome:       readmission at           Outcome model:     logistic regression
               event=1@30, event=1@60,                               (hazards)
               event=1@90; death at     Treatment model:   logistic regression
               event=2@30, event=2@60,  Censoring model:   logistic regression
               event=2@90 (competing    Probability limits:          [0.01, 1]
               causes)
Treatment:     dose, given at baseline
Adjusted for:  older, prior_admissions
Censoring:     day>=30, day>=60,
               day>=90; each plan
               keeps every unit
               observed
Method:        longitudinal targeted
               maximum likelihood
               (LTMLE)
==============================================================================
                               estimate  std. error            95% CI  p-value
------------------------------------------------------------------------------
cif_regimen[high dose, death     0.3508      0.0118  [0.3280, 0.3743]  <0.0001
@ t=3]
cif_regimen[high dose,           0.1935      0.0097  [0.1752, 0.2133]  <0.0001
readmission @ t=3]
cif_regimen[no pill, death       0.1165      0.0074  [0.1027, 0.1319]  <0.0001
@ t=3]
cif_regimen[no pill,             0.3792      0.0119  [0.3561, 0.4028]  <0.0001
readmission @ t=3]
cif_regimen[high dose with       0.1262      0.0081  [0.1111, 0.1430]  <0.0001
supplement, death @ t=3]
cif_regimen[high dose with       0.2433      0.0121  [0.2203, 0.2678]  <0.0001
supplement, readmission
@ t=3]
==============================================================================
What each row estimates
                                                           meaning
------------------------------------------------------------------------------
cif_regimen[high dose, death @ t=3]                        probability of
                                                           death by time 90 if
                                                           every unit followed
                                                           plan high dose
cif_regimen[high dose, readmission @ t=3]                  probability of
                                                           readmission by time
                                                           90 if every unit
                                                           followed plan high
                                                           dose
cif_regimen[no pill, death @ t=3]                          probability of
                                                           death by time 90 if
                                                           every unit followed
                                                           plan no pill
cif_regimen[no pill, readmission @ t=3]                    probability of
                                                           readmission by time
                                                           90 if every unit
                                                           followed plan no
                                                           pill
cif_regimen[high dose with supplement, death @ t=3]        probability of
                                                           death by time 90 if
                                                           every unit followed
                                                           plan high dose with
                                                           supplement
cif_regimen[high dose with supplement, readmission @ t=3]  probability of
                                                           readmission by time
                                                           90 if every unit
                                                           followed plan high
                                                           dose with
                                                           supplement
==============================================================================
What each plan assigns and who followed it to the end
plan                        followed  max weight  effective size  assigns
------------------------------------------------------------------------------
high dose               983 of 8,000        12.7             806  2 from
                                                                  baseline,
                                                                  held
no pill               1,167 of 8,000        10.1             974  0 from
                                                                  baseline,
                                                                  held
high dose with        2,150 of 8,000        15.2           1,727  the part
supplement                                                        acting on
                                                                  readmission
                                                                  at 2, the
                                                                  part acting
                                                                  on death at
                                                                  0; death
                                                                  counted
                                                                  first within
                                                                  a time step
==============================================================================
Simultaneous 95% bands
                                                                        band
------------------------------------------------------------------------------
cif_regimen[high dose, death @ t=3]                         [0.3217, 0.3811]
cif_regimen[high dose, readmission @ t=3]                   [0.1702, 0.2192]
cif_regimen[no pill, death @ t=3]                           [0.0991, 0.1365]
cif_regimen[no pill, readmission @ t=3]                     [0.3497, 0.4096]
cif_regimen[high dose with supplement, death @ t=3]         [0.1071, 0.1481]
cif_regimen[high dose with supplement, readmission @ t=3]   [0.2141, 0.2750]
==============================================================================
Notes:
[1] The interval of cif_regimen[high dose, death @ t=3], cif_regimen[high
    dose, readmission @ t=3], cif_regimen[no pill, death @ t=3],
    cif_regimen[no pill, readmission @ t=3], cif_regimen[high dose with
    supplement, death @ t=3], cif_regimen[high dose with supplement,
    readmission @ t=3] is built on the log-odds scale and turned back, so it
    stays inside the possible range of a proportion and need not be centred on
    the estimate.
[2] The bands cover all 6 rows at once with 95% probability; use them when you
    read several rows together. No validation study covers the bands for this
    kind of fit, so cleverly marks them experimental.

cif_regimen[high dose, readmission @ t=3] is the share readmitted by day 90 under the high dose: 0.1935, against 0.3792 with no pill. The t counts checks, so t=3 is day 90, and the p-values test only whether a risk is zero. In the plan table, followed counts patients whose dose matches the plan and who were still event-free and in follow-up in the last month; the supplement plan reads 2,150, the high-dose and no-pill patients together, since it borrows one hazard from each group. The bands cover all six risks at once. Read cleverly’s output explains how every row name is built.

Split the drop in readmission into its two sources#

result.contrast(...) compares two plans’ risks, allowing for both coming from the same patients.

# `t=3` is the third check, day 90; with your own grid, use the number of your last check.
def risk(plan, cause):
    return f"cif_regimen[{plan}, {cause} @ t=3]"


# Each difference: the first plan's risk minus the second plan's.
pairs = {
    "whole medicine": ("high dose", "no pill"),
    "fluid part": ("high dose with supplement", "no pill"),
    "potassium part": ("high dose", "high dose with supplement"),
}
effects = {}
rows = []
for cause in ("readmission", "death"):
    for part, (plan, base) in pairs.items():
        # psi holds the two named risks in order; .psi is an estimate's value and .ci its interval.
        effects[cause, part] = result.contrast(
            lambda psi: psi[0] - psi[1], [risk(plan, cause), risk(base, cause)], name=part
        )
        low, high = effects[cause, part].ci
        rows.append(
            {
                "event": cause,
                "part": part,
                "plans compared": f"{plan} - {base}",
                "change per 100": 100 * effects[cause, part].psi,
                "ci_low": 100 * low,
                "ci_high": 100 * high,
                "true": 100 * (known.loc[plan, cause] - known.loc[base, cause]),  # simulation only
            }
        )
print("change in the risk by day 90, per 100 patients:")
print(pd.DataFrame(rows).round(1).to_string(index=False))
print("label of every estimate:", sorted({result[name].support.label for name in result}))
change in the risk by day 90, per 100 patients:
      event           part                        plans compared  change per 100  ci_low  ci_high  true
readmission whole medicine                   high dose - no pill           -18.6   -21.5    -15.5 -17.7
readmission     fluid part   high dose with supplement - no pill           -13.6   -16.8    -10.3 -13.1
readmission potassium part high dose - high dose with supplement            -5.0    -5.9     -4.2  -4.6
      death whole medicine                   high dose - no pill            23.4    20.7     26.1  23.1
      death     fluid part   high dose with supplement - no pill             1.0     0.7      1.4   1.1
      death potassium part high dose - high dose with supplement            22.5    19.7     25.2  22.0
label of every estimate: ['supported']

With the potassium part blocked, the fluid part alone changes readmission by -13.6 per 100 (95% CI -16.8 to -10.3). The other -5.0 (-5.9 to -4.2) of the whole medicine’s -18.6 is the potassium part’s share: high-dose patients who died before they could be readmitted. Reading -18.6 as the pill’s benefit would count those deaths as a benefit.

For death, the potassium part carries +22.5 of the +23.4 per 100. The fluid part adds +1.0 because patients who avoid readmission stay at risk of dying first.

Check the weights behind the estimate#

The correction step weights each patient who followed a plan by one over their predicted chance of following it and staying in follow-up. For the supplement plan, the weight is also multiplied by the patient’s predicted chance of still being event-free under that plan, divided by the same chance on their own dose. The overlap check reads these weights and the effective sample size, the number of equally weighted patients they are worth.

assessment = result.assess()
ledger = assessment.to_frame()
# Keep the checks that ran: `passed` has a pass mark, `completed` is a report to read.
ran = ledger[ledger["status"].isin(["passed", "completed"])]
print(ran[["check", "status"]].to_string(index=False))
print("needs attention:", tuple(item.name for item in assessment.attention) or "none")
print()
support = assessment.report("support").to_frame()
# The weights are the same for both events, so the readmission rows show them all. Time 1 to 3
# are the months ending on days 30, 60 and 90.
weights = support[support["cause"].eq("readmission")]
columns = ["regimen", "time", "n_followed", "max_weight", "effective_n", "share_truncated"]
print("weights by plan and month:")
print(weights[columns].round(1).to_string(index=False))
ratio = (support["effective_n"] / support["n_followed"]).min()
print(f"smallest effective sample, as a share of its group: {ratio:.1%}")
          check    status
score_equations    passed
        support completed
nuisance_models completed
needs attention: none

weights by plan and month:
                  regimen  time  n_followed  max_weight  effective_n  share_truncated
                high dose     1        2099        10.4       1700.0              0.0
                high dose     2        1418        11.8       1149.2              0.0
                high dose     3         983        12.7        805.6              0.0
                  no pill     1        2096         8.7       1762.5              0.0
                  no pill     2        1558         9.3       1312.6              0.0
                  no pill     3        1167        10.1        974.4              0.0
high dose with supplement     1        4195        10.4       3460.8              0.0
high dose with supplement     2        2976        12.9       2430.1              0.0
high dose with supplement     3        2150        15.2       1727.5              0.0
smallest effective sample, as a share of its group: 80.3%

Nothing needs attention, the correction step reached its target (score_equations passed), and nuisance_models records the fitted hazard, dose and follow-up models. The largest weight is 15.2, in the supplement plan’s last month: above either group’s largest, because of that extra factor, which the 0.01 floor on predicted chances does not cap. Every group is worth at least 80.3% of its size, and no predicted chance hit the floor (share_truncated is 0). Warning signs would be a few huge weights or an effective sample far below the group size.

Try to break the result#

These checks change the data in a known way and refit the fluid part’s effect on readmission:

  • placebo replaces each dose with one drawn at random in the observed proportions, so the difference should be near zero;

  • random_common_cause adds a pure-noise column, so the difference should barely move;

  • subset refits on random 70% samples, so the refits should spread about as much as the standard error predicts for samples of that size.

None can detect a missing confounder or a broken condition of the supplement plan.

import warnings

from cleverly import RegimeContrast
from cleverly.exceptions import ConvergenceWarning, SparseInfluenceWarning

# refute needs the difference as a named estimate, so this fit asks for differences directly.
contrast_fit = study.identify(RegimeContrast(plans, reference="no pill", horizons=(90,))).estimate(
    method=method
)
fluid_name = "ate_regimen[high dose with supplement vs no pill, readmission @ t=3]"
print(f"fluid part, as a named estimate: {contrast_fit[fluid_name].psi:.4f}")
with warnings.catch_warnings():
    # The checks warn that the supplement plan's small change in death rests on few rows, and
    # two placebo refits, on doses drawn at random, stop the correction step slightly short of
    # its target. The readings use only the readmission difference and the refits' estimates.
    warnings.simplefilter("ignore", SparseInfluenceWarning)
    warnings.simplefilter("ignore", ConvergenceWarning)
    # Each check refits 20 times, the default.
    refutation = contrast_fit.diagnostics.refute(
        estimand=fluid_name, tests=("placebo", "subset", "random_common_cause"), random_state=61
    )
columns = [
    "test",
    "original",
    "refuted_mean",
    "refuted_sd",
    "statistic_name",
    "statistic",
    "verdict",
]
print(refutation.to_frame()[columns].round(4).to_string(index=False))
fluid part, as a named estimate: -0.1359
               test  original  refuted_mean  refuted_sd                  statistic_name  statistic     verdict
            placebo   -0.1359       -0.0020      0.0140                               t    -0.6338 descriptive
             subset   -0.1359       -0.1308      0.0099               scatter ratio rho     0.9106 descriptive
random_common_cause   -0.1359       -0.1358      0.0002 paired shift in standard errors     0.0034 descriptive

All three behave as expected. The random doses give a mean of -0.0020, the noise column barely moves the estimate, and the subset refits have a scatter ratio of 0.91, where 1 is ideal and 20 refits easily give 0.7 to 1.3. The verdict reads descriptive because no simulation study backs a pass mark for this fit, so you judge the numbers. Checks that plant a known effect refuse a supplement plan.

What if a confounder is missing?#

The E-value measures how strongly a missing confounder would need to be linked to both the dose and readmission to explain the effect away. It needs two plans that each set the whole dose, so it covers the whole medicine only.

# The E-value reads two plans that each set the whole dose: here the high dose against no pill.
bound = result.sensitivity.evalue(
    (risk("high dose", "readmission"), risk("no pill", "readmission"))
)
print(bound.summary())
                                   E-value
==============================================================================
Question:  how strong a confounder      Estimate:   rr_regimen[high dose vs no
           would explain away                         pill, readmission @ t=3]
           rr_regimen[high dose vs no   Scale:                      risk ratio
           pill, readmission @ t=3]
==============================================================================
                             risk ratio    E-value
------------------------------------------------------------------------------
estimate                          0.510       3.33
95% limit nearest the null        0.573       2.88
==============================================================================
An unmeasured confounder would need a risk ratio of 3.33 with both the
treatment and the outcome, beyond the measured covariates, to explain away the
estimate; 2.88 to move the interval to the null.
Warnings:
[1] No validation study licenses the E-value of the limit for this kind of
    fit, so read it as descriptive.
Notes:
[2] The E-value is the strength at which the confounder's associations with
    the treatment and with the outcome, taken as equal, could explain the
    estimate away. Unequal strengths can trade off: one association may be
    below the E-value if the other is above it.
[3] The risk is the chance of the event by the horizon. The E-value also
    assumes that censoring is random given the treatment and covariates, and
    that the unmeasured confounder does not affect censoring.
[4] The validation study licenses no derived estimate for this estimate.

The high-dose readmission risk is 0.510 times the no-pill risk. A missing confounder would need a risk ratio of 3.33 with both the dose and readmission to explain that away, and 2.88 to move the interval’s end nearest no effect onto it; whether one that strong is plausible is a judgment about the clinic. The bound assumes the factor does not change who leaves follow-up.

cleverly has no such bound for the supplement plan, and its made-up-confounder check refuses this fit: that confounder would shift both events, breaking the condition that no factor affects both.

# For your own data, leave out each of your strongest recorded confounders in turn.
moves = []
for dropped in design.baseline:
    reduced = replace(design, baseline=tuple(n for n in design.baseline if n != dropped))
    refit = (
        CausalStudy(frame, design=reduced, protocol=protocol)
        .identify(RegimeMean(plans, horizons=(90,)))
        .estimate(method=method)
    )
    for part in ("whole medicine", "fluid part"):
        plan, base = pairs[part]
        full = effects["readmission", part]
        moved = refit.contrast(
            lambda psi: psi[0] - psi[1],
            [risk(plan, "readmission"), risk(base, "readmission")],
            name=part,
        )
        moves.append(
            {
                "left out": dropped,
                "readmission difference": part,
                "with both": full.psi,
                "left out one": moved.psi,
                "move in SEs": (moved.psi - full.psi) / full.std_error,
            }
        )
print(pd.DataFrame(moves).round(4).to_string(index=False))
        left out readmission difference  with both  left out one  move in SEs
           older         whole medicine    -0.1856       -0.1832       0.1546
           older             fluid part    -0.1359       -0.1440      -0.4894
prior_admissions         whole medicine    -0.1856       -0.1373       3.1419
prior_admissions             fluid part    -0.1359       -0.0814       3.2763

Leaving out prior_admissions moves the fluid part’s effect from -0.1359 to -0.0814, or 3.3 standard errors, and the whole medicine’s by 3.1, so the adjustment rests mostly on prior admissions; a missing confounder as strong could move the estimates as far. Leaving out older moves each by less than half a standard error.

What we can and can’t conclude#

For the clinic, had every patient stayed in follow-up: the high dose trades -18.6 readmissions per 100 patients for +23.4 deaths before readmission. Counting a death first within a month, a supplement that blocks the potassium part would keep -13.6 of the drop (-16.8 to -10.3) at +1.0 deaths. These hold for adults sent home after a heart-failure admission, under the conditions in “Set up the analysis”, and lean on prior admissions.

The supplement plan describes a treatment no patient got, so its answer needs outside evidence, such as a trial, that the supplement blocks the potassium part and nothing else. One simulated sample does not show how the method performs in general.

Go deeper#

How we know the method works#

Simulation studies check each method over many repeated samples. Separable effects checks this fit: a baseline treatment with three levels, three checks, two events and leaving follow-up, with plans that set the whole treatment and plans that set its two parts apart, at 16,000 patients. It uses another simulation, with one yes-or-no characteristic, and models that fit the mean of each group of patients with the same characteristics. This page’s logistic models, two characteristics and 8,000 patients rest on that study and on theory. No other software that fits this estimate was found to compare against. The technical entry lists the method’s evidence and limits; its section “Separable effects” gives the exact definition and conditions.

Which event counts first within a month#

The fit works month by month on the checks, not on exact days, so a death and a readmission in the same month need an order, and when the two parts sit at different doses, the order changes the question. Death first means that each month the supplement plan’s death chance, the no-pill one, applies first, and readmission is judged among those still alive; readmission first reverses that.

from cleverly.datasets import heart_failure_truth

# The same question with a readmission counted before a death in the same month.
readmission_first = {
    **plans,
    "high dose with supplement": Separable(
        arms={"readmission": 2, "death": 0}, first="readmission"
    ),
}
other_order = study.identify(RegimeMean(readmission_first, horizons=(90,))).estimate(method=method)
fluid = pairs["fluid part"]
names = [risk(plan, "readmission") for plan in fluid]
orders = {"death first": result, "readmission first": other_order}
print("fluid part, change in readmission by day 90 per 100 patients:")
for order, fit in orders.items():
    estimate = fit.contrast(lambda psi: psi[0] - psi[1], names, name=order)
    low, high = estimate.ci
    # simulation only: the true value of each order.
    first = order.split()[0]
    fluid_only, none = (
        heart_failure_truth(*doses, first=first).set_index("day").loc[90, "readmission"]
        for doses in ((2, 0), (0, 0))
    )
    true = fluid_only - none
    print(
        f"  {order:18s} {100 * estimate.psi:+5.1f}  95% CI {100 * low:+5.1f} to {100 * high:+5.1f}"
        f"  true {100 * true:+5.1f}"
    )
fluid part, change in readmission by day 90 per 100 patients:
  death first        -13.6  95% CI -16.8 to -10.3  true -13.1
  readmission first  -16.5  95% CI -19.6 to -13.4  true -15.8

Each order lands near its own true value, and the two differ by about 3 per 100. In this simulated clinic a death does come first within a month, so -13.1 is the supplement’s effect here and -15.8 is only what the readmission-first formula gives. With real data the order is a choice about what the supplement plan means, which the data cannot settle, so cleverly requires first=. The order matters on a coarse grid like these monthly checks, and little when checks are close together, so closer checks are the way to make the choice matter less. Pick it before you look at the results, and report it with the answer.

Where to go next#

Readmission when death can come first follows a treatment offered at two points, with death as a competing event, and also asks the different question of readmission had death been prevented. Readmission by day 30, 60 and 90 follows readmission with leaving follow-up and no competing event. The longitudinal TMLE reference gives the exact definition under “Separable effects”, and scope and refusals lists what a separable fit refuses. The examples index lists every example.