Readmission by day 30, 60 and 90: longitudinal TMLE#

At a glance#

A hospital offers some patients navigation when they go home: a bedside transition plan and two navigator contacts in the 30 days after discharge, which help with medicines, appointments and warning signs. Does the offer change the chance of an unplanned readmission by day 30, 60 and 90, when some patients leave follow-up early? And in a second, separate program where navigator teams also make a day-30 follow-up call, how sure can we be about the effect of the offer plus the call, when patients of one team share part of their risk? Nobody randomized either decision.

Had every patient stayed in follow-up, offering navigation to every patient rather than to no one would lower readmission by day 90: the change is -17.5 per 100 patients (95% confidence interval -22.1 to -12.8). In the team program, the offer plus the call changes it by -13.2 per 100 (95% CI -18.1 to -8.2). That second interval treats each team, not each patient, as an independent unit; treating the patients as independent gives an interval that is too narrow. Both are causal only if the recorded characteristics capture every common cause of the decisions, of dropout and of readmission, which the data cannot check. The team answer rests mostly on one risk score.

The data are simulated, so we know the true changes (-15.4 and -13.0 per 100), and each interval contains its value.

The question#

The first program makes one decision, the offer, just after the discharge order; that order is time zero, when follow-up starts. The target is the readmission risk of each plan: the share of patients readmitted by day 30, 60 and 90, had every patient been offered navigation, or none, and had every patient stayed in follow-up. Patients who leave can still be readmitted, so this target counts readmissions the data hide.

  lives_alone, prior_admissions ──▶ offer at discharge ──▶ readmission by day 30, 60, 90
         └───────────────────────────────────────────────▶ readmission, leaving follow-up
  assumed absent: an unrecorded cause of both the offer and readmission or leaving

Patients who live alone, or who had more admissions in the past year, were offered navigation more often, and they are also readmitted more often. Both are confounders, variables that drive both the offer and the outcome. The program checks on each patient on days 15, 30, 60 and 90, and a patient can leave follow-up after a check. We then never learn whether they were readmitted later: that is censoring, where the event may happen but the data hide it. Nobody dies in the simulated program; with real data, the study description below counts death before readmission as a readmission.

The second program adds a decision on day 30, a follow-up call, and runs both decisions through 100 navigator teams. Its quantity is the share readmitted by day 90 under “offer and call”, against “neither”.

The data#

Every fit sets its seeds, so a rerun prints the same numbers.

from dataclasses import replace

import pandas as pd
from sklearn.linear_model import LinearRegression, LogisticRegression

import cleverly

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

Another version of cleverly can print slightly different numbers. The figures on this page need matplotlib: pip install "cleverly[plot]".

make_point_survival draws 2,000 simulated patients of the first program and also returns the true answers, which real data never give you.

from cleverly.datasets import make_point_survival

# With your own data, load one row per patient, such as pd.read_csv(...), with the baseline
# characteristics, the offer (0 or 1), the day of the readmission or of the last follow-up
# check, and an event code: 1 for a readmission, 0 for no readmission by that day.
# Real data have no `truth`: delete the lines marked "simulation only" here and below.
# continuous_event_time=True records the day of each readmission; n_times=4 gives four checks.
raw, truth = make_point_survival(n=2_000, seed=11, continuous_event_time=True, n_times=4)
# The rename and the day conversion fit the simulator's output; load your own data with these
# column names and days directly.
frame = raw.rename(
    columns={"W1": "lives_alone", "W2": "prior_admissions", "A": "offer", "event": "readmitted"}
)
# The simulator counts time in 30-day units; the program records days.
frame["day"] = 30.0 * frame.pop("time")
print("rows and columns:", frame.shape)
print(list(frame.columns))
print(frame.head().round(1).to_string())
print()
checks = (15.0, 30.0, 60.0, 90.0)
left = frame[frame["readmitted"].eq(0) & frame["day"].lt(90.0)]
print("left follow-up after the check on day:", left["day"].value_counts().sort_index().to_dict())
print("readmitted by day 90:", int(frame["readmitted"].sum()))
print()
# The days to report, and the position of each among the checks (day 30 is the second check).
# Change both if you change the checks.
horizons = {30.0: 2, 60.0: 3, 90.0: 4}

# simulation only, to the end of the cell: the true readmission risk of each plan. The simulator
# calls the plans arm1 (offered) and arm0 (not offered).
known = pd.DataFrame(
    {
        "day": list(horizons),
        "offered": [truth[f"risk_regimen[arm1 @ t={k}]"] for k in horizons.values()],
        "not_offered": [truth[f"risk_regimen[arm0 @ t={k}]"] for k in horizons.values()],
        "difference": [truth[f"ate_regimen[arm1 vs arm0 @ t={k}]"] for k in horizons.values()],
    }
)
print("true readmission risk of the simulated program:")
print(known.round(4).to_string(index=False))
rows and columns: (2000, 5)
['lives_alone', 'prior_admissions', 'offer', 'readmitted', 'day']
   lives_alone  prior_admissions  offer  readmitted   day
0          0.0               1.0    1.0           0  90.0
1          0.0               1.0    0.0           1   9.3
2          1.0               2.0    1.0           0  30.0
3          0.0               2.0    1.0           0  90.0
4          0.0               0.0    0.0           1  26.9

left follow-up after the check on day: {15.0: 133, 30.0: 83, 60.0: 59}
readmitted by day 90: 942

true readmission risk of the simulated program:
 day  offered  not_offered  difference
30.0   0.1785       0.2646     -0.0861
60.0   0.3236       0.4562     -0.1326
90.0   0.4419       0.5958     -0.1539

Each row is one patient. prior_admissions counts admissions in the past year, from 0 to 3. When readmitted is 1, day is the day of the readmission, such as 9.3 for row 1; otherwise it is the day of the last check that found the patient not readmitted.

Why a simple comparison misleads#

print("baseline means by the offer:")
print(frame.groupby("offer")[["lives_alone", "prior_admissions"]].mean().round(3))
print()

# The simple comparison: the share with a recorded readmission by each day, by offer.
print("share with a recorded readmission, offered minus not offered:")
naive = {}
for day in horizons:
    by_day = frame["readmitted"].eq(1) & frame["day"].le(day)
    shares = by_day.groupby(frame["offer"]).mean()
    naive[day] = shares[1] - shares[0]
    line = f"  day {day:3.0f}: simple {naive[day]:+.4f}"
    line += f", true {known.set_index('day').loc[day, 'difference']:+.4f}"  # simulation only
    print(line)
baseline means by the offer:
       lives_alone  prior_admissions
offer                               
0.0          0.410             1.325
1.0          0.562             1.742

share with a recorded readmission, offered minus not offered:
  day  30: simple -0.0703, true -0.0861
  day  60: simple -0.1073, true -0.1326
  day  90: simple -0.1433, true -0.1539

Offered patients more often lived alone and had more prior admissions, and both raise the risk of readmission. So the offer went to patients at higher risk, which pulls the simple difference toward zero. The simple shares also count a patient who left follow-up as not readmitted. In this sample the simple day-90 difference lands near the truth by luck. Across 400 simulated samples (see “Go deeper”) it averaged -0.1294, about a sixth of the effect short, and more data would not remove that gap.

Set up the analysis#

First, describe the study (StudyProtocol): who is in it, when follow-up starts, what each plan means, and how leaving follow-up and death count. The description does not change the estimate; it records what the estimate means, and each result keeps a copy of it. Passing it is optional. The code adapts the program’s shared study description.

from cleverly.datasets import navigation_protocol

# For your own study, build cleverly.StudyProtocol(...) directly, with the fields printed below.
# The fields this question changes are the outcome, the horizon, and how leaving follow-up and
# death count.
program = navigation_protocol()
protocol = replace(
    program,
    outcome="First unplanned readmission, recorded on the day it happens",
    horizon="30, 60 and 90 days after discharge, with follow-up checks on days 15, 30, 60 and 90",
    intercurrent_event_handling=(
        "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 offer regardless of completed contacts",
        "Count death before readmission as a readmission (composite strategy)",
    ),
)
print("\n".join(protocol.summary_lines()))
Population: Adults with a discharge-home order at a participating hospital during the enrollment period
Eligibility: Age 18 years or older; Discharge home ordered at a participating hospital
Follow-up starts: Discharge-home order, after baseline measurement and before the navigation offer
Strategies: Offer standard transition navigation; Provide usual discharge support
Versions: Bedside transition plan and two scheduled navigator contacts within 30 days; No access to the transition-navigation offer
Outcome: First unplanned readmission, recorded on the day it happens
Horizon: 30, 60 and 90 days after discharge, with follow-up checks on days 15, 30, 60 and 90
Intercurrent events: 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 offer regardless of completed contacts; Count death before readmission as a readmission (composite strategy)
Interference unit: Individual patient
Rationale: The recorded baseline variables cover the measured common causes; Standardized offer and version records support that each offer is one well-defined action, so a patient's recorded outcome is the outcome they would have had under the offer they got; Reserved navigator capacity and access controls support no interference

It changes the outcome, the horizon and the intercurrent events, the rules for events after discharge that change what the outcome means. Leaving follow-up is censoring under a “hypothetical strategy”, the target described above. Death counts as a readmission, so a plan cannot look better because its patients die first.

Name the columns and the question#

Tell cleverly which columns hold the day, the event code and the offer (TimeToEvent), and on which days the program checks on patients (grid=). The grid must hold every day on which a patient can leave follow-up, and cleverly refuses a patient who left follow-up between two checks, because moving that day onto either check biases the risk. cleverly calls a plan a regimen: RegimeMean asks for each plan’s mean risk (ey_regime) at days 30, 60 and 90. identify checks that the columns can answer that question and lists the conditions the answer needs.

from cleverly import CausalStudy, RegimeMean, TimeToEvent

# For your own data, change the column names and the grid of follow-up check days.
design = TimeToEvent(
    time="day",
    event="readmitted",
    treatment="offer",
    baseline=("lives_alone", "prior_admissions"),
    grid=checks,
)
plans = {"offered": 1, "not offered": 0}
study = CausalStudy(frame, design=design, protocol=protocol)
risks = study.identify(RegimeMean(plans, reference="not offered", horizons=tuple(horizons)))
print(risks.summary())
                         Causal question (ey_regime)
==============================================================================
Question:   mean outcome under each     Rows:                            2,000
            declared regime             Answered by:     adjusting for history
Outcome:    readmitted@15,
            readmitted@30,
            readmitted@60,
            readmitted@90 (event by
            each time)
Treatment:  offer
Baseline:   lives_alone,
            prior_admissions
==============================================================================
What each treatment time adjusts for
treatment   adjusted for
------------------------------------------------------------------------------
offer       lives_alone, 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)
collaborative_tmle    collaborative TMLE (C-TMLE)
drtmle                doubly robust TMLE (DR-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. 4 other methods cannot
    estimate this question; the full summary says why.

cleverly turns each row into one readmission indicator per check (readmitted@15 and so on), and the offer is adjusted for both characteristics. The four conditions:

  • well-defined treatment (also called consistency): an offer means the same contacts for every patient;

  • no interference: one patient’s offer does not change another patient’s readmission;

  • no hidden confounding at each time: the two characteristics hold every common cause of the offer, of leaving follow-up, and of readmission;

  • overlap at each time: every kind of patient had a real chance of either option and of staying in follow-up.

The data cannot check the first three. The weight check below partly checks the last. The methods table lists the methods that can answer it; this page uses TMLE, explained next.

Estimate readmission risk by day 30, 60 and 90#

The method, longitudinal targeted maximum likelihood estimation (TMLE), works backward from day 90 one check at a time. At each check it fits an outcome model, then a correction step adjusts its predictions, using the treatment model (who was offered) and the censoring model (who stays in follow-up). When those two models are right, errors in the outcome model do not bias the estimate.

  • outcome_learner predicts a readmission between two checks. pseudo_learner then predicts each patient’s chance of a readmission by the later day from earlier information; a chance is not a 0/1 outcome, so this must be a regression model.

  • treatment_learner and censoring_learner predict who was offered and who stayed in follow-up.

  • 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, 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.
method = TMLEMethod(
    models=ModelSpec(
        outcome_learner=LogisticRegression(max_iter=1000, random_state=41),
        pseudo_learner=LinearRegression(),
        treatment_learner=LogisticRegression(max_iter=1000, random_state=41),
        censoring_learner=LogisticRegression(max_iter=1000, random_state=41),
    ),
    cross_fitting=CrossFitting(enabled=False),
    runtime=Runtime(random_state=41, n_jobs=1),
)
result = risks.estimate(method=method)
print(result.summary())
                        Longitudinal estimate (LTMLE)
==============================================================================
Question:      the event risk under     Rows:                            2,000
               each plan; each row is   Time points:     4 (at 15, 30, 60, 90)
               defined below            Out-of-fold predictions:            no
Outcome:       readmitted by day        Outcome model:    logistic regression;
Treatment:     offer, given at                           linear regression for
               baseline                                    earlier time points
Adjusted for:  lives_alone,             Treatment model:   logistic regression
               prior_admissions         Censoring model:   logistic regression
Censoring:     day>=15, day>=30,        Probability limits:          [0.01, 1]
               day>=60, day>=90; each
               plan keeps every unit
               observed
Method:        longitudinal targeted
               maximum likelihood
               (LTMLE)
==============================================================================
                                 estimate  std. error          95% CI  p-value
------------------------------------------------------------------------------
risk_regimen[offered @ t=2]         0.184       0.013  [0.160, 0.210]  <0.0001
risk_regimen[offered @ t=3]         0.319       0.016  [0.289, 0.351]  <0.0001
risk_regimen[offered @ t=4]         0.437       0.017  [0.403, 0.472]  <0.0001
risk_regimen[not offered @ t=2]     0.278       0.015  [0.250, 0.308]  <0.0001
risk_regimen[not offered @ t=3]     0.455       0.017  [0.423, 0.488]  <0.0001
risk_regimen[not offered @ t=4]     0.612       0.016  [0.580, 0.644]  <0.0001
==============================================================================
What each row estimates
                                  meaning
------------------------------------------------------------------------------
risk_regimen[offered @ t=2]       probability of the event by time 30 if every
                                  unit followed plan offered
risk_regimen[offered @ t=3]       probability of the event by time 60 if every
                                  unit followed plan offered
risk_regimen[offered @ t=4]       probability of the event by time 90 if every
                                  unit followed plan offered
risk_regimen[not offered @ t=2]   probability of the event by time 30 if every
                                  unit followed plan not offered
risk_regimen[not offered @ t=3]   probability of the event by time 60 if every
                                  unit followed plan not offered
risk_regimen[not offered @ t=4]   probability of the event by time 90 if every
                                  unit followed plan not offered
==============================================================================
What each plan assigns and who followed it to the end
plan             followed  max weight  effective size  assigns
------------------------------------------------------------------------------
offered      515 of 2,000         3.8             495  1 from baseline, held
not offered  495 of 2,000         4.3             453  0 from baseline, held
==============================================================================
Simultaneous 95% bands
                                            band
------------------------------------------------------------------------------
risk_regimen[offered @ t=2]       [0.153, 0.219]
risk_regimen[offered @ t=3]       [0.280, 0.362]
risk_regimen[offered @ t=4]       [0.393, 0.483]
risk_regimen[not offered @ t=2]   [0.241, 0.318]
risk_regimen[not offered @ t=3]   [0.412, 0.498]
risk_regimen[not offered @ t=4]   [0.569, 0.654]
==============================================================================
Notes:
[1] The interval of risk_regimen[offered @ t=2], risk_regimen[offered @ t=3],
    risk_regimen[offered @ t=4], risk_regimen[not offered @ t=2],
    risk_regimen[not offered @ t=3], risk_regimen[not offered @ t=4] 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.

In the estimate table, risk_regimen[offered @ t=4] is the risk by day 90 under the offered plan: 0.437, against 0.612 with no offer. The t counts checks, so t=2 is day 30 and t=3 is day 60. The p-values test only whether a risk is zero. In the plan table, 515 offered patients were still in follow-up and not yet readmitted when the last interval, from day 60 to day 90, began. The simultaneous bands cover all six risks at once, so they are wider than the intervals, and cleverly marks them experimental.

Details: what the intervals assume

Each interval comes from how much each patient moves the estimate. With simple parametric models fitted on all rows, it is valid in large samples under overlap, independent patients, and correct treatment and censoring models. This page’s simulation draws the offer and dropout with chances that are not exactly logistic, so its models are close rather than exact. When the outcome models are wrong and those two are right, the standard error can be too large. Probability limits: [0.01, 1] puts a floor of 0.01 under each patient’s predicted chance of following a plan and staying in follow-up.

def risk(plan, day):
    return f"risk_regimen[{plan} @ t={horizons[day]}]"


differences = {}
rows = []
for day in horizons:
    names = [risk("offered", day), risk("not offered", day)]
    # psi holds the named estimates in order; .psi is an estimate's value and .ci its interval.
    differences[day] = result.contrast(
        lambda psi: psi[0] - psi[1], names, name=f"difference by day {day:.0f}"
    )
    low, high = differences[day].ci
    rows.append(
        {
            "day": day,
            "offered": result[names[0]].psi,
            "not_offered": result[names[1]].psi,
            "difference": differences[day].psi,
            "ci_low": low,
            "ci_high": high,
            "true_difference": known.set_index("day").loc[day, "difference"],  # simulation only
        }
    )
curve = pd.DataFrame(rows)
print("readmission risk by plan, and offered minus not offered:")
print(curve.round(4).to_string(index=False))
print()
print("per 100 patients, offered minus not offered:")
for day, row in zip(horizons, rows, strict=True):
    print(
        f"  by day {day:.0f}: {100 * row['difference']:+5.1f}  "
        f"95% CI {100 * row['ci_low']:+5.1f} to {100 * row['ci_high']:+5.1f}"
        f"  true {100 * row['true_difference']:+5.1f}"  # simulation only
    )
day90 = differences[90.0]
risk_fig = result.plot(time_label="Days since discharge", band="none")
readmission risk by plan, and offered minus not offered:
 day  offered  not_offered  difference  ci_low  ci_high  true_difference
30.0   0.1840       0.2780     -0.0941 -0.1323  -0.0556          -0.0861
60.0   0.3194       0.4550     -0.1356 -0.1801  -0.0902          -0.1326
90.0   0.4372       0.6125     -0.1753 -0.2214  -0.1280          -0.1539

per 100 patients, offered minus not offered:
  by day 30:  -9.4  95% CI -13.2 to  -5.6  true  -8.6
  by day 60: -13.6  95% CI -18.0 to  -9.0  true -13.3
  by day 90: -17.5  95% CI -22.1 to -12.8  true -15.4
../_images/551e0aa636d88d8514a4eb389f139bbff351d03e86f0a5df2bb5944f61c0f136.png

result.contrast(...) turns the two risks at each day into a difference, with a standard error that allows for both risks coming from the same patients. The offer lowers readmission at every check: the change runs from -9.4 per 100 by day 30 to -17.5 per 100 by day 90, and no interval comes near zero. In the figure the two plans’ risks pull apart over time; the numbers under it are the patients still followed and not yet readmitted, the 515 of the plan table at day 90. In this sample the fitted day-90 difference lies farther from the truth than the simple one, though inside its interval; over 400 samples only the fitted one averaged the truth (see “Go deeper”).

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. 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. The others
# run later on this page (deferred), or do not apply to this kind of fit.
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 day-90 rows show every interval; time 1 to 4 are the intervals ending on days 15, 30, 60, 90.
weights = support[support["horizon"].eq(horizons[90.0])]
columns = ["regimen", "time", "n_followed", "max_weight", "effective_n", "share_truncated"]
print("weights by plan and follow-up check:")
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%}")
print("correction step converged everywhere:", bool(support["converged"].all()))
          check    status
score_equations    passed
        support completed
nuisance_models completed
needs attention: none

weights by plan and follow-up check:
    regimen  time  n_followed  max_weight  effective_n  share_truncated
    offered     1         978         3.4        912.5              0.0
    offered     2         800         3.5        759.6              0.0
    offered     3         663         3.7        634.3              0.0
    offered     4         515         3.8        494.7              0.0
not offered     1        1022         3.2        965.6              0.0
not offered     2         823         3.7        767.6              0.0
not offered     3         679         3.9        629.2              0.0
not offered     4         495         4.3        453.3              0.0
smallest effective sample, as a share of its group: 91.6%
correction step converged everywhere: True

Nothing needs attention. The correction step reached its target: the average remaining correction is zero (score_equations passed), and a failure would mean outcome-model bias may remain. nuisance_models records the fitted outcome, treatment and censoring models.

The largest weight is 4.3, among the patients not offered in the last interval, from day 60 to day 90, and every group’s weights are worth at least 91.6% of its size. No patient’s predicted chance fell to the 0.01 floor (share_truncated is 0). Warning signs are a few huge weights, patients at the floor, or an effective sample far below the group size. A weight near 100 means a patient at the floor, and cleverly flags the fit when more than 5% of any group sit there at a check. A clean check reads fitted models, so it does not prove overlap or that they are right.

Patients who share a navigator team#

The second program assigns each patient to one of 100 navigator teams of 40 patients. The team offers navigation at discharge and decides on day 30 whether to call the patient. Patients of one team share part of their risk, because a team runs its navigation, and its usual care, well or badly for all of them. In this simulation team quality moves only readmission; if better teams also offered or called more, it would be a confounder too, needing a recorded measure. Shared team risk is not interference, which would mean one patient’s offer changes a teammate’s readmission; it makes teammates’ outcomes move together, so they are not independent.

from cleverly.datasets import make_team_readmission

# With your own data, load one row per patient, with the team, the baseline characteristics,
# and per decision the treatment and a follow-up column: 1 if still followed at the next check
# after that decision (day 30 for the offer, day 90 for the call), 0 once they leave; a patient
# readmitted by day 30 counts as followed to day 90. A readmission by day 30 comes before the
# call. After a patient leaves follow-up, every later column is missing.
teams, team_truth = make_team_readmission(n_teams=100, team_size=40, seed=23)
print("rows and columns:", teams.shape)
print(list(teams.columns))
print(teams.head().round(2).to_string())
print()
print("teams:", teams["team"].nunique(), " patients per team:", teams.groupby("team").size().min())
print("left follow-up by day 30:", int(teams["followed_30"].eq(0).sum()))
print("readmitted by day 30:", int(teams["readmitted_30"].eq(1).sum()))
print("left follow-up between day 30 and day 90:", int(teams["followed_90"].eq(0).sum()))
# simulation only, to the end of the cell
team_target_truth = team_truth["ate_regimen[always vs never]"]
print(f"true difference by day 90, offer and call against neither: {team_target_truth:.4f}")
rows and columns: (4000, 9)
['team', 'lives_alone', 'discharge_risk', 'offer', 'followed_30', 'readmitted_30', 'call', 'followed_90', 'readmitted_90']
   team  lives_alone  discharge_risk  offer  followed_30  readmitted_30  call  followed_90  readmitted_90
0   0.0          1.0            0.51    1.0          1.0            0.0   1.0          1.0            0.0
1   0.0          0.0           -1.97    0.0          1.0            0.0   0.0          1.0            1.0
2   0.0          0.0            1.80    1.0          1.0            1.0   1.0          1.0            1.0
3   0.0          0.0            1.38    0.0          1.0            0.0   0.0          0.0            NaN
4   0.0          1.0            1.95    1.0          1.0            1.0   1.0          1.0            1.0

teams: 100  patients per team: 40
left follow-up by day 30: 299
readmitted by day 30: 561
left follow-up between day 30 and day 90: 226
true difference by day 90, offer and call against neither: -0.1301

Each row is one patient, with the columns in time order, and discharge_risk is a standardized risk score (0 is average). A readmission by day 30 (readmitted_30) happens before the call, and it already counts as a readmission by day 90, as in row 2. The offer lowers early readmission, and an early readmission makes the call more likely and is itself the outcome, so it is a result of the first decision and a confounder of the second. One regression on both decisions fails either way: adjusting for early readmission hides part of the offer’s effect, and leaving it out leaves the call confounded.

from cleverly import LongitudinalTreatment, RegimeContrast
from cleverly.datasets import team_readmission_protocol

# For your own study, build cleverly.StudyProtocol(...) directly, with the fields printed below.
team_protocol = team_readmission_protocol()
print("\n".join(team_protocol.summary_lines()))
# For your own data, change the column names; cluster= names the column that holds the team.
team_design = LongitudinalTreatment(
    treatment=("offer", "call"),
    outcome="readmitted_90",
    censoring=("followed_30", "followed_90"),
    baseline=("lives_alone", "discharge_risk"),
    time_varying=((), ("readmitted_30",)),
    cluster="team",
)
schedules = {"offer and call": 1, "neither": 0}
team_effect = CausalStudy(teams, design=team_design, protocol=team_protocol).identify(
    RegimeContrast(schedules, reference="neither")
)
Population: Adults discharged home from a participating hospital during the enrollment period
Eligibility: Age 18 years or older; Discharged alive; Discharged home from a participating hospital
Follow-up starts: Hospital discharge, after baseline measurement and before first assignment
Strategies: Offer navigation at discharge and make the day-30 follow-up call; Offer no navigation at discharge and make no day-30 call
Versions: The declared discharge navigation contact and the day-30 call by the patient's team; Usual discharge support without navigation contacts or a day-30 call
Outcome: Unplanned readmission between discharge and day 90
Horizon: 90 days after discharge
Intercurrent events: Count a readmission before day 30 as the outcome, and keep it in the history of the day-30 call; Treat loss to follow-up as censoring, so the target is the readmission share had every patient stayed in follow-up (hypothetical strategy); Count death before day 90 as a readmission (composite strategy); Analyze each navigation offer regardless of completed contacts
Interference unit: Individual patient
Rationale: Recorded history covers the measured common causes at each decision; Version records support that the discharge offer and the day-30 call are each one well-defined action, so a patient's recorded outcome is the outcome they would have had under the offer and call they got; Reserved navigator capacity supports no interference between patients

team_readmission_protocol() adapts the shared two-decision description so that an early readmission counts as the outcome and stays in the history of the call. LongitudinalTreatment names the two decisions and the two follow-up columns, and time_varying= places readmitted_30 before the call only. RegimeContrast asks for the difference between the two plans directly, where RegimeMean asked for each plan’s risk. cluster="team" makes the team the independent unit, so cleverly computes the standard error from team totals. The fit works backward as in the first program: it first models day-90 readmission given everything known at the call, early readmission included, then carries that prediction back to discharge. So early readmission adjusts the call without hiding the part of the offer’s effect that runs through it. The four conditions of the first fit apply at each decision.

# Cross-fitting with five folds. With cluster=, cleverly keeps each team inside one fold.
team_method = replace(method, cross_fitting=CrossFitting(n_folds=5))
team_result = team_effect.estimate(method=team_method)
target = "ate_regimen[offer and call vs neither]"
clustered = team_result[target]
print(team_result.summary())
# The weight check, as for the first fit.
team_assessment = team_result.assess()
print("needs attention:", tuple(item.name for item in team_assessment.attention) or "none")
team_support = team_assessment.report("support").to_frame()
team_ratio = (team_support["effective_n"] / team_support["n_followed"]).min()
print(f"smallest effective sample, as a share of its group: {team_ratio:.1%}")
print("largest share at the 0.01 floor:", team_support["share_truncated"].max())
                        Longitudinal estimate (LTMLE)
==============================================================================
Question:      average effect on        Rows:                            4,000
               readmitted_90 of plan    Time points:                         2
               offer and call instead   Out-of-fold predictions:       5 folds
               of neither               Outcome model:    logistic regression;
Outcome:       readmitted_90 (binary),                   linear regression for
               at the end                                  earlier time points
Treatment:     offer, call              Treatment model:   logistic regression
Adjusted for:  lives_alone,             Censoring model:   logistic regression
               discharge_risk; later:   Probability limits:          [0.01, 1]
               readmitted_30
Censoring:     followed_30,
               followed_90; each plan
               keeps every unit
               observed
Method:        longitudinal targeted
               maximum likelihood
               (LTMLE)
Clusters:      100
==============================================================================
                               estimate  std. error            95% CI  p-value
------------------------------------------------------------------------------
ate_regimen[offer and call vs    -0.132       0.025  [-0.181, -0.082]  <0.0001
neither]
==============================================================================
What each plan assigns and who followed it to the end
plan                  followed  max weight  effective size  assigns
------------------------------------------------------------------------------
offer and call  1,143 of 4,000        19.2             874  1 at every time
                                                            point
neither         1,094 of 4,000        58.2             704  0 at every time
                                                            point
==============================================================================
needs attention: none
smallest effective sample, as a share of its group: 64.3%
largest share at the 0.01 floor: 0.0

“Offer and call” changes readmission by day 90 by -0.132 against “neither”, and Clusters: 100 confirms that the fit counts teams. This fit uses cross-fitting: each patient’s predictions come from models trained on other teams, like out-of-fold predictions in cross-validation. Simulation studies back the team interval only for cross-fitted fits, so this fit uses cross-fitting. The largest weight, 58.2 among patients who got neither, is larger than in the first fit because the plan sets two decisions, and the chances of following both multiply. The weight check still finds nothing that needs attention, no patient at the floor, and every group worth at least 64.3% of its size.

What goes wrong when teammates are treated as independent#

The common mistake is to leave out cluster=, so that cleverly treats the 4,000 patients as 4,000 independent units.

independent_design = replace(team_design, cluster=None)
independent = (
    CausalStudy(teams, design=independent_design, protocol=team_protocol)
    .identify(RegimeContrast(schedules, reference="neither"))
    .estimate(method=team_method)[target]
)
print("offer and call against neither, difference in readmission by day 90:")
for label, estimate in (("teams declared", clustered), ("patients as independent", independent)):
    low, high = estimate.ci
    print(
        f"  {label:24s} {estimate.psi:+.4f}  SE {estimate.std_error:.4f}  "
        f"95% CI {low:+.4f} to {high:+.4f}  label {estimate.support.label}"
    )
se_ratio = independent.std_error / clustered.std_error
print(f"standard error ratio, independent over teams: {se_ratio:.2f}")
print()
print("per 100 patients:")
for label, estimate in (("teams declared", clustered), ("patients as independent", independent)):
    low, high = estimate.ci
    print(
        f"  {label:24s} {100 * estimate.psi:+5.1f}  95% CI {100 * low:+5.1f} to {100 * high:+5.1f}"
    )
print(f"  {'true value':24s} {100 * team_target_truth:+5.1f}")  # simulation only
offer and call against neither, difference in readmission by day 90:
  teams declared           -0.1319  SE 0.0253  95% CI -0.1814 to -0.0824  label supported
  patients as independent  -0.1324  SE 0.0183  95% CI -0.1682 to -0.0966  label supported
standard error ratio, independent over teams: 0.72

per 100 patients:
  teams declared           -13.2  95% CI -18.1 to  -8.2
  patients as independent  -13.2  95% CI -16.8 to  -9.7
  true value               -13.0

The two fits give nearly the same estimate, but the independent fit’s standard error is 0.72 times the team fit’s, so its interval is narrower than the honest one. Both print supported, which means simulation studies have checked this kind of fit; the label reads the setup you declare, so it cannot know that teams exist. Across 400 simulated samples, the team interval contained the true value in about 95% of them and the independent one in only 83%. Declare cluster= whenever patients share a team, a clinic or a household that can move their outcomes together; with 20 to 39 teams the interval widens to allow for few teams, and below 20 cleverly reports none.

How much could a missing confounder move the answers?#

For the first fit, the E-value measures how strongly a missing confounder would need to be linked to both the offer and readmission, beyond the two recorded characteristics, to explain the effect away. It reads the risk ratio at one day: the offered risk divided by the not-offered risk.

# For your own data, name the two risks at the day you report.
bound = result.sensitivity.evalue((risk("offered", 90.0), risk("not offered", 90.0)))
print(bound.summary())
                                   E-value
==============================================================================
Question:  how strong a confounder      Estimate:    rr_regimen[offered vs not
           would explain away                                   offered @ t=4]
           rr_regimen[offered vs not    Scale:                      risk ratio
           offered @ t=4]
==============================================================================
                             risk ratio    E-value
------------------------------------------------------------------------------
estimate                          0.714       2.15
95% limit nearest the null        0.784       1.87
==============================================================================
An unmeasured confounder would need a risk ratio of 2.15 with both the
treatment and the outcome, beyond the measured covariates, to explain away the
estimate; 1.87 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.

By day 90 the offered risk is 0.714 times the not-offered risk. A missing confounder would need a risk ratio of 2.15 with both the offer and readmission to explain the estimate away, and 1.87 to pull the end of the interval nearest no effect onto it. So an unrecorded factor, such as frailty or support at home, twice as common among offered patients and doubling the risk of readmission could not explain the effect away, though it could pull the interval to no effect (1.87); whether one that strong is plausible is a judgment about the program. The bound assumes the factor does not change who leaves follow-up. The warning and note [4] say no simulation study checks the interval end or the risk ratio built from two risks, so read both as descriptions.

cleverly has no such bound yet for the team fit, which has censoring and two decisions. For both fits, the code also leaves out each recorded variable in turn and refits. That shows how much the answer leans on each one, but a missing factor can be stronger, or push the other way.

# For your own data, leave out each of your strongest recorded confounders in turn.
moves = []
for dropped in ("lives_alone", "prior_admissions"):
    reduced = replace(design, baseline=tuple(n for n in design.baseline if n != dropped))
    refit = (
        CausalStudy(frame, design=reduced, protocol=protocol)
        .identify(RegimeMean(plans, reference="not offered", horizons=(90.0,)))
        .estimate(method=method)
    )
    names = [risk("offered", 90.0), risk("not offered", 90.0)]
    moved = refit.contrast(lambda psi: psi[0] - psi[1], names, name="difference by day 90")
    moves.append(
        {
            "fit": "first program",
            "left out": dropped,
            "difference": moved.psi,
            "move in SEs": (moved.psi - day90.psi) / day90.std_error,
        }
    )
for dropped in ("lives_alone", "discharge_risk", "readmitted_30"):
    reduced = replace(
        team_design,
        baseline=tuple(n for n in team_design.baseline if n != dropped),
        time_varying=tuple(
            tuple(n for n in node if n != dropped) for node in team_design.time_varying
        ),
    )
    moved = (
        CausalStudy(teams, design=reduced, protocol=team_protocol)
        .identify(RegimeContrast(schedules, reference="neither"))
        .estimate(method=team_method)[target]
    )
    moves.append(
        {
            "fit": "team program",
            "left out": dropped,
            "difference": moved.psi,
            "move in SEs": (moved.psi - clustered.psi) / clustered.std_error,
        }
    )
for label, full in (("first program", day90), ("team program", clustered)):
    print(f"{label}, day 90, all characteristics: {full.psi:+.4f}, SE {full.std_error:.4f}")
print(pd.DataFrame(moves).round(4).to_string(index=False))
first program, day 90, all characteristics: -0.1753, SE 0.0239
team program, day 90, all characteristics: -0.1319, SE 0.0253
          fit         left out  difference  move in SEs
first program      lives_alone     -0.1575       0.7464
first program prior_admissions     -0.1530       0.9355
 team program      lives_alone     -0.1264       0.2177
 team program   discharge_risk     -0.0279       4.1160
 team program    readmitted_30     -0.1075       0.9631

Leaving out discharge_risk moves the team estimate from -0.1319 to -0.0279, or 4.1 standard errors, so most of the adjustment rests on that one score. A missing confounder as strong as it could move the estimate about as far, enough to erase most of the effect. Every other move is under one standard error, including leaving out readmitted_30, which drops early readmission from the call’s adjustment. In the first program the larger move is 0.94 standard errors, for prior_admissions. Each move also includes the change to the censoring model.

A made-up confounder#

Another check plants a made-up confounder of chosen strength and refits. simulated_confounding gives each patient a hidden value. The outcome strength raises or lowers each patient’s chance of a readmission between two checks by that value times the strength, on the log-odds scale. The treatment strength is the share of patients whose recorded offer is flipped, taken from those with the highest hidden values. The follow-up is then replayed check by check, so a patient can gain a readmission, or stay in follow-up past their last check, on models fitted to the data. The call needs the day-90 difference as a named estimate, so the cell refits it with RegimeContrast.

from cleverly.sensitivity import ConfounderStrengthGrid

contrast_fit = study.identify(
    RegimeContrast(plans, reference="not offered", horizons=(90.0,))
).estimate(method=method)
day90_name = "ate_regimen[offered vs not offered @ t=4]"
# For your own data, choose strengths around those the calibration table prints for your
# strongest recorded confounders.
surface = contrast_fit.sensitivity.simulated_confounding(
    day90_name,
    grid=ConfounderStrengthGrid(treatment=(0.0, 0.1, 0.2), outcome=(0.0, 0.2, 0.5, 1.0)),
    benchmark_covariates=("lives_alone", "prior_admissions"),
)
cells = surface.to_frame().rename(
    columns={
        "treatment_strength[offer]": "treatment_strength",
        "induced_treatment_association[offer]": "association_with_offer",
    }
)
shown = ["treatment_strength", "outcome_strength", "estimate", "displacement"]
shown += ["association_with_offer", "new_event_share", "extended_share"]
print("day-90 difference under each pair of strengths:")
print(cells[shown].round(4).to_string(index=False))
print()
calibration = surface.calibration_frame()
print("strength of each recorded characteristic:")
print(calibration[["covariate", "role", "strength"]].round(4).to_string(index=False))
day-90 difference under each pair of strengths:
 treatment_strength  outcome_strength  estimate  displacement  association_with_offer  new_event_share  extended_share
                0.0               0.0   -0.1753        0.0000                  0.0052              NaN             NaN
                0.0               0.2   -0.1742        0.0011                  0.0052           0.0877          0.0103
                0.0               0.5   -0.1602        0.0151                  0.0052           0.1986          0.0272
                0.0               1.0   -0.1392        0.0360                  0.0052           0.3584          0.0520
                0.1               0.0   -0.1446        0.0307                  0.0207           0.0011          0.0010
                0.1               0.2   -0.1284        0.0468                  0.0207           0.0886          0.0113
                0.1               0.5   -0.1268        0.0485                  0.0207           0.2002          0.0279
                0.1               1.0   -0.1102        0.0650                  0.0207           0.3591          0.0526
                0.2               0.0   -0.0848        0.0904                  0.0097           0.0032          0.0018
                0.2               0.2   -0.0836        0.0917                  0.0097           0.0926          0.0117
                0.2               0.5   -0.0899        0.0854                  0.0097           0.2039          0.0284
                0.2               1.0   -0.0892        0.0861                  0.0097           0.3624          0.0530

strength of each recorded characteristic:
       covariate      role  strength
     lives_alone treatment    0.2490
     lives_alone   outcome    0.1897
prior_admissions treatment    0.2435
prior_admissions   outcome    0.2147

With both strengths at 0 the estimate is the original -0.1753. A confounder must be tied to both the offer and readmission, and in every cell the hidden value’s correlation with the offer stays at 0.0207 or below. So no cell plants a real confounder. Flipping the offers of patients at one end of the hidden value moves about as many patients into the offered group as out of it, because about half the patients were offered, which mislabels offers rather than tying them to the hidden value. The outcome axis alone adds unexplained variation in readmission; that changes the replayed readmissions themselves, so the difference they hold changes too, and a move along that axis is not bias from a confounder.

The calibration table measures the two recorded characteristics on the outcome axis’s scale, the change in the log-odds of a readmission per standard deviation of the characteristic: 0.1897 for lives_alone and 0.2147 for prior_admissions. A hidden cause of readmission that strong (0.2) moves the estimate by 0.0011, and one five times stronger (1.0) moves it to -0.1392. Flipping the recorded offer of 20% of patients moves it to -0.0848, and no cell reaches zero. The treatment rows measure something else, the share of predicted offers that change without the characteristic, so they do not match the grid. At outcome strength 1.0, about 36% of the replayed readmissions fall at a check where that patient had no recorded readmission, and about 5% of the replayed patient-checks fall after a patient’s last check; those come from the fitted models, so errors in the models move the estimate too.

The replay refuses the team fit for three reasons. It records readmission once, at day 90, for patients still followed, so the replay has no outcome to give a patient whose dropout it removes. Early readmission, which the fit adjusts for, is measured after the first decision under the recorded offer, so it would not match a flipped offer. Its patients are also grouped in teams, which the replay does not handle yet. The stress-surface reference lists each case. For the team fit, the refits that leave out one characteristic are the only sensitivity reading.

What we can and can’t conclude#

For the hospital: offering navigation at discharge, compared with offering it to no one, lowers readmission at every check through day 90; by day 90 the change is -17.5 per 100 patients (95% interval -22.1 to -12.8), had every patient stayed in follow-up. In the team program, the offer plus a day-30 call changes readmission by day 90 by -13.2 per 100 (95% interval -18.1 to -8.2), with teams as the independent units. Both hold for adults discharged home, under the four conditions and the treatment and censoring models; the team answer leans on discharge_risk.

The team analysis does not say how much of the effect comes from the call rather than the offer, and neither analysis covers other schedules. Nobody dies in this simulation; with real data, decide first whether death counts as a readmission or as a competing event. One simulated sample of each program 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. Point-treatment survival checks the first fit on this page’s simulation, with the readmission time binned onto four checks and 2,000 patients. Its models fit the mean of each group of patients with the same characteristics, rather than this page’s logistic models. That setting is compared with the known truth; the study’s other settings, with visits at fixed times, are also compared with survtmle, another package that fits the same estimates in R. Clustered cross-fitted longitudinal TMLE checks the team fit at 100 clusters of 40 patients, as here, on another simulation whose measurement before the second decision is continuous.

That study gives the method the true treatment and censoring probabilities, while this page fits them, and its fit that ignores the teams shows a too-narrow interval like the mistake above. Few-cluster cross-fitted longitudinal TMLE measures 20 and 30 clusters. The technical entry lists the method’s evidence and limits.

A simulation we ran for this page redraws both programs 400 times at the page’s sizes and refits each with the page’s settings. It checks the page’s readings and does not validate the method. Its script and log are in the cleverly repository at reviews/notebook-review/probes/discharge-to-readmission/. The first fit’s day-90 difference averaged -0.1556 against the true -0.1539, and its interval covered 0.9600 of the samples. In the team program the team standard error matched the spread of the estimates (ratio 0.9915), and the independent one was too small (0.7131).

Try to break the result#

These checks change the data in a known way and refit the day-90 difference of each fit:

  • placebo swaps in random offers that mimic the real ones, 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.

None can detect a missing confounder. For the first program they read the day-90 difference that the made-up confounder cell refitted, contrast_fit.

# Each check refits 20 times, the default.
columns = [
    "test",
    "original",
    "refuted_mean",
    "refuted_sd",
    "statistic_name",
    "statistic",
    "verdict",
]
refutations = {}
for label, fit, name in (
    ("first program", contrast_fit, day90_name),
    ("team program", team_result, target),
):
    refutations[label] = fit.diagnostics.refute(
        estimand=name, tests=("placebo", "subset", "random_common_cause"), random_state=61
    )
    print(label)
    print(refutations[label].to_frame()[columns].round(4).to_string(index=False))
first program
               test  original  refuted_mean  refuted_sd                  statistic_name  statistic     verdict
            placebo   -0.1753       -0.0035      0.0180                               t    -0.8809 descriptive
             subset   -0.1753       -0.1763      0.0156               scatter ratio rho     1.0014 descriptive
random_common_cause   -0.1753       -0.1754      0.0008 paired shift in standard errors    -0.0069 descriptive
team program
               test  original  refuted_mean  refuted_sd                  statistic_name  statistic     verdict
            placebo   -0.1319        0.0019      0.0119                               t     0.7041 descriptive
             subset   -0.1319       -0.1304      0.0215               scatter ratio rho     1.2928 descriptive
random_common_cause   -0.1319       -0.1320      0.0006 paired shift in standard errors    -0.0047 descriptive

All six checks behave as expected over 20 refits each. The random offers give means near zero and the noise column barely moves either estimate. The subset refits spread about as the standard error predicts: their scatter ratio, the spread divided by the predicted spread, is 1.00 and 1.29, where 1 is ideal and 20 refits easily give 0.7 to 1.3. The verdict reads descriptive: cleverly gives a pass or fail only when a simulation study backs the check for this kind of fit. The study behind the placebo and subset checks used out-of-fold predictions, other learners, and no teams, so you judge these numbers.

A stronger test replaces the readmissions with simulated ones whose true difference we know. It refits 20 times and checks how close the estimates come. dummy_outcome draws readmissions that ignore the patients and the offer, so the true difference is zero. simulated_outcome draws readmissions that depend on both, so the true difference is known.

import warnings

from cleverly.exceptions import SparseInfluenceWarning
from cleverly.validation import LogisticHazardOutcome

# The events are drawn check by check from a hazard: the chance of a readmission between two
# checks for a patient still at risk. intercept sets its baseline (log-odds), effect the change
# with the offer (log-odds), and adjustment_scale how strongly the characteristics move it.
generated = {
    "dummy_outcome": LogisticHazardOutcome(intercept=-1.5, effect=0.0, adjustment_scale=0.0),
    "simulated_outcome": LogisticHazardOutcome(intercept=-1.5, effect=-0.4, adjustment_scale=0.5),
}
# In some generated samples few patients without the offer remain at risk by day 90, and the
# refit warns that its standard error rests on few rows. The bias reading below uses only the
# point estimates and their spread, so the warning is silenced.
generated_tests = {}
for name, declaration in generated.items():
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", SparseInfluenceWarning)
        report = contrast_fit.diagnostics.refute(
            estimand=day90_name,
            tests=(name,),
            n_replicates=20,
            random_state=61,
            **{name: declaration},
        )
    test = generated_tests[name] = report.tests[0]
    bias = test.readings[0]
    print(
        f"{name:18s} {test.n_replicates} refits: true difference {test.declared_effect:.4f}, "
        f"mean estimate {test.mean:.4f}; bias in SDs {bias.estimate:.3f}, interval "
        f"{bias.lower:.2f} to {bias.upper:.2f}, pass zone {bias.band[0]} to {bias.band[1]}; "
        f"verdict {test.verdict}"
    )
dummy_outcome      20 refits: true difference 0.0000, mean estimate -0.0012; bias in SDs -0.041, interval -0.48 to 0.40, pass zone -0.2 to 0.2; verdict descriptive
simulated_outcome  20 refits: true difference -0.1167, mean estimate -0.1195; bias in SDs -0.098, interval -0.54 to 0.34, pass zone -0.2 to 0.2; verdict descriptive

Each mean estimate lands near its true value, such as -0.1195 against -0.1167 for simulated_outcome. The bias is measured in standard deviations of the estimates, and a pass needs its whole interval inside -0.2 to 0.2. A verdict needs at least 400 refits, and no simulation study yet backs one for a fit with several checks, so even 400 would read descriptive. You judge the bias interval yourself; at 20 refits it is wide, so it shows only that the bias is not large.

dummy_outcome and simulated_outcome draw only continuous outcomes for a fit with two decisions, so they skip the team fit. plasmode, which redraws patients from models fitted to the data, has no draw yet for one offer held over several checks, or for a yes-or-no outcome at the end of study; the roadmap tracks that work. A negative-control outcome is an outcome the offer cannot affect, so its estimate should be zero; these data hold none.

Where to go next#

Time-to-event outcomes treats death as a competing event and follows navigation offered at two decisions. The longitudinal TMLE reference states the one-row-per-patient input under “Time-to-event input” and the team rule under “Clusters”. The examples index lists every example.