Gain over current practice: TMLE for population impact#

At a glance#

A hospital program offers transition navigation (a bedside transition plan and two navigator contacts) to some patients going home. A day-30 survey asks how well the move home went, and a “top box” answer is the best rating on its scale. A quarter of patients never answer. The manager asks what offering every eligible patient would add to current practice, and what current practice already achieves over offering no one.

Offering everyone would raise the share of patients with a top-box answer from 0.5756 under current practice to about 0.67, a gain of 0.0956 (95% confidence interval 0.0739 to 0.1173), or about 10 more top-box patients per 100. Current practice already adds 0.0872 over offering no one. The usual average effect (ATE), 0.1828, compares offering everyone with offering no one, so it also counts the part current practice has already collected. If every patient were guaranteed a primary-care visit within 7 days, offering everyone instead of no one would still raise the share by 0.1153 (interval 0.0592 to 0.1724), against the ATE’s 0.1828 when the visit follows the offer.

The answer assumes that no unrecorded factor drives both who gets the offer and the outcome, and that non-responders would have answered like comparable respondents. The first is the more fragile on this page’s checks. An unrecorded cause of the outcome much stronger than anything recorded could erase the gain, so the question for program staff is whether such a factor exists.

The data are simulated, so we know the true gain (0.0799), and the interval contains it.

The question#

Discharge teams choose who gets the offer, and they favor patients with a high discharge risk. The manager must decide whether to extend the offer to every eligible patient, so the main quantity is the gain: the top-box rate if everyone got the offer minus the rate under current practice, over every eligible patient, whether or not they answer. What current practice achieves is its rate minus the rate if no one got the offer. The code computes both with one quantity, the population attributable risk (PAR): today’s rate minus the rate if every patient got the option named by reference=. The gain is minus the PAR with reference=1, and what current practice achieves is the PAR with reference=0.

A second question asks whether the offer still helps when every patient sees a primary-care doctor within 7 days. The offer makes that visit more likely, so part of its effect may run through it. For that reason the gain does not adjust for the visit: adjusting would remove the part of the gain that runs through it. The controlled direct effect instead compares offer with no offer while every patient’s visit is set to yes.

  W ────────────────────────────────┐
  │                                 ▼
  ├──────▶ A ──────────────────────▶ Y
  │        │                        ▲
  │        ├──────▶ Z ──────────────┘
  │        │        ▲
  ├────────┼────────┘
  │        ▼
  └──────▶ R          Y is seen only when R = 1

  W = discharge_risk, age, prior_utilization (recorded before the offer)
  A = transition_navigation (the offer)
  Z = pcp_visit_7d (a primary-care visit within 7 days of discharge)
  Y = top_box (the day-30 survey rates the transition top box)
  R = responded (the survey came back by day 45)
  not drawn: an unrecorded cause of A and Y, of Z and Y, or of R and Y,
             and any arrow from Z or Y to R

The graph shows what we assume causes what. The characteristics drive the offer, the visit, the outcome, and who answers; the offer drives the visit, the outcome, and who answers; and the visit drives the outcome. The analysis rests on what the graph leaves out. Without an arrow from the outcome to answering, non-responders would have answered like respondents with the same offer and characteristics, an assumption called “missing at random”.

The data#

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

import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures

import cleverly

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

Another version of cleverly can print slightly different numbers.

make_population_impact draws 4,000 simulated discharges and also returns the true values, which real data never give you.

from cleverly.datasets import make_population_impact

# With your own data, load your data frame here, such as frame = pd.read_csv(...), with a
# missing value (NaN) wherever the outcome was not recorded and a 0/1 column that is 1 exactly
# where it was. Real data have no `truth`: drop the lines that print it, and pass float("nan")
# as the true value to the `line` helper defined below.
frame, truth = make_population_impact(n=4_000, seed=2031)
print("rows and columns:", frame.shape)
print(list(frame.columns))
print(frame.head().round(3))
print()
print(f"share offered today:      {frame['transition_navigation'].mean():.3f}")
print(f"share with a 7-day visit: {frame['pcp_visit_7d'].mean():.3f}")
print(f"survey response rate:     {frame['responded'].mean():.3f}")
print()
print("true values, known only because the data are simulated:")
print(f"  top-box rate under current practice: {truth['ey_obs']:.4f}")
print(f"  if every patient got the offer:      {truth['ey1']:.4f}")
print(f"  if no patient got the offer:         {truth['ey0']:.4f}")
rows and columns: (4000, 7)
['top_box', 'transition_navigation', 'discharge_risk', 'age', 'prior_utilization', 'pcp_visit_7d', 'responded']
   top_box  transition_navigation  discharge_risk    age  prior_utilization  pcp_visit_7d  responded
0      1.0                    0.0           0.097  0.445              0.777           1.0        1.0
1      NaN                    0.0           0.308 -0.018             -0.356           1.0        0.0
2      1.0                    1.0           0.691  0.590              0.924           1.0        1.0
3      1.0                    0.0          -1.211  1.138              0.822           1.0        1.0
4      1.0                    0.0          -1.634 -0.696              0.535           1.0        1.0

share offered today:      0.437
share with a 7-day visit: 0.508
survey response rate:     0.758

true values, known only because the data are simulated:
  top-box rate under current practice: 0.5641
  if every patient got the offer:      0.6440
  if no patient got the offer:         0.4791

Each row is one discharge: top_box (1 for top box, NaN when the survey did not come back), the offer, three characteristics measured before it on a standardized scale, the 7-day visit, and responded. The gain the manager asks about is the gap between 0.6440 and 0.5641 in the true values.

Why a simple comparison misleads#

The quick answers use the respondents: the top-box rate of offered patients against the others, and the rate among everyone who answered.

answered = frame[frame["responded"] == 1]
rates = answered.groupby("transition_navigation")["top_box"].mean()
print(f"top-box rate among respondents, offered:     {rates[1.0]:.4f}")
print(f"top-box rate among respondents, not offered: {rates[0.0]:.4f}")
print(f"difference:                                  {rates[1.0] - rates[0.0]:.4f}")
print(f"top-box rate among all respondents:          {answered['top_box'].mean():.4f}")
print()
# The characteristics measured before the offer that every later fit adjusts for. For your own
# data, list yours here.
covariates = ["discharge_risk", "age", "prior_utilization"]
print("mean baseline covariate by offer:")
print(frame.groupby("transition_navigation")[covariates].mean().round(3))
top-box rate among respondents, offered:     0.6566
top-box rate among respondents, not offered: 0.5326
difference:                                  0.1241
top-box rate among all respondents:          0.5869

mean baseline covariate by offer:
                       discharge_risk    age  prior_utilization
transition_navigation                                          
0.0                            -0.233  0.115             -0.113
1.0                             0.302 -0.124              0.116

Offered respondents reach a top box 0.1241 more often than the others. That difference answers neither question. It compares offered with not offered, not everyone with today, and the offered patients had a higher discharge risk (mean 0.302 against -0.233), which lowers the chance of a top box. The rate among respondents, 0.5869, overstates today’s rate (0.5641 in the true values) because high-risk patients answer less often.

Set up the analysis#

First, describe the study (StudyProtocol). The description does not change the estimate; it records what the estimate means, so a reviewer can check it against the manager’s decision. The code starts from this program’s description and changes four fields: the population includes patients who never answer, the outcome is the top-box rating, a death before day 30 counts as not top box (an event after the offer that changes the outcome, which the output calls an intercurrent event), and the reasons add the survey assumption.

from dataclasses import replace

from cleverly.datasets import navigation_protocol

# For your own study, build the description with cleverly.StudyProtocol(target_population=...,
# eligibility=..., time_zero=..., treatment_strategies=..., treatment_versions=..., outcome=...,
# horizon=..., intercurrent_event_handling=..., interference_unit=..., assumption_rationale=...),
# in the order the output prints them; each is text or a tuple of texts. With missing outcomes,
# say in target_population that non-responders belong to it, and give the reason for missing at
# random in assumption_rationale, as below.
program = navigation_protocol()
protocol = replace(
    program,
    target_population=f"{program.target_population}, whether or not they return the survey",
    outcome=(
        "Top-box patient-reported transition score, from the survey sent on day 30 and "
        "closed on day 45"
    ),
    intercurrent_event_handling=(
        *program.intercurrent_event_handling[:2],
        "The protocol scores death before day 30 as not top box (composite strategy)",
    ),
    assumption_rationale=(
        program.assumption_rationale[0],
        "Given the arm and the baseline variables, survey response carries no further "
        "information about the unobserved score (missingness at random)",
        *program.assumption_rationale[1:],
    ),
)
print("\n".join(protocol.summary_lines()))
Population: Adults with a discharge-home order at a participating hospital during the enrollment period, whether or not they return the survey
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: Top-box patient-reported transition score, from the survey sent on day 30 and closed on day 45
Horizon: 30 days after discharge
Intercurrent events: Use the transition score regardless of readmission; Analyze the offer regardless of completed contacts; The protocol scores death before day 30 as not top box (composite strategy)
Interference unit: Individual patient
Rationale: The recorded baseline variables cover the measured common causes; Given the arm and the baseline variables, survey response carries no further information about the unobserved score (missingness at random); 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

The strategies compare the offer with usual discharge support, and current practice is the mix of the two that discharge teams chose. These simulated data have no deaths. In real data a death gives a recorded “not top box” without a survey, so whether an outcome is recorded would depend on the outcome itself, which breaks missing at random. This page does not cover that case: data with deaths need the death rows handled by another design before this analysis.

Next, name the columns and the quantity to estimate. PointTreatment describes a study with one treatment decided at one time, and missingness="responded" marks who answered. PopulationAttributableRisk(reference=1) asks for today’s rate minus the rate if every patient got the offer, so the gain is its negative. study.identify(...) lists what must be true for the answer to be causal.

from cleverly import CausalStudy, PointTreatment, PopulationAttributableRisk

# For your own data, change the column names and the response column; the adjustment list is
# the `covariates` list of the comparison cell. The visit is left out of it, because the offer
# partly causes the visit.
design = PointTreatment(
    outcome="top_box",
    treatment="transition_navigation",
    adjustment=tuple(covariates),
    missingness="responded",
)
study = CausalStudy(frame, design=design, protocol=protocol)
gain_question = study.identify(PopulationAttributableRisk(reference=1))
print(gain_question.summary())
                            Causal question (par)
==============================================================================
Question:      mean top_box as          Rows:                            4,000
               treated, minus the mean  Answered by:  adjusting for covariates
               if every unit had
               transition_navigation =
               1
Outcome:       top_box (binary); 3,033
               of 4,000 observed
Treatment:     transition_navigation
               (levels 0, 1)
Adjusted for:  discharge_risk, age,
               prior_utilization
==============================================================================
Conditions the answer rests on
condition                       checkable   what it says
------------------------------------------------------------------------------
well-defined treatment          no          Each unit's observed outcome is
                                            the outcome it would have had
                                            under the treatment it actually
                                            received. This needs the treatment
                                            to be well defined: every way of
                                            getting the same level has the
                                            same effect.
no interference                 no          One unit's treatment does not
                                            change another unit's outcome.
no hidden confounding           no          Among units with the same
                                            adjusted-for values, which
                                            treatment a unit got is unrelated
                                            to the outcomes it would have had.
                                            This holds when the adjusted-for
                                            columns account for the common
                                            causes of transition_navigation
                                            and top_box and none of them is
                                            affected by transition_navigation.
overlap                         partly      Every group of units that share
                                            the adjusted-for values had some
                                            chance of the reference level of
                                            transition_navigation.
outcome missing at random       no          Among units with the same
                                            treatment and adjusted-for values,
                                            whether top_box was recorded is
                                            unrelated to its value.
chance of a recorded outcome    partly      Every group of units that share
                                            the treatment and adjusted-for
                                            values that the question reads had
                                            some chance of a recorded top_box.
recorded outcome at reference   partly      Every group of units that share
                                            the adjusted-for values had some
                                            chance of both the reference level
                                            of transition_navigation and a
                                            recorded top_box.
==============================================================================
Methods
method          name
------------------------------------------------------------------------------
tmle            targeted maximum likelihood (TMLE)
adaptive_iptw   adaptive-propensity inverse probability weighting
==============================================================================
Notes:
[1] Some top_box values are missing, so the mean of top_box as treated, under
    the treatment each unit actually got, need not equal the average of the
    recorded values. cleverly estimates it from a model of top_box and a model
    of which outcomes were recorded, so it rests on the outcome missing at
    random and chance of a recorded outcome conditions above.
[2] 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.
[3] The methods table lists the methods that fit. 10 other methods cannot
    estimate this question; the full summary says why.

What the answer assumes#

“Well-defined treatment” (an offer always means the same plan) and “no interference” (one patient’s offer does not change another’s outcome) rest on the shared study design: the protocol’s last two reasons, a standard offer and reserved navigator capacity, are the argument to make for your own program. The data cannot check “no hidden confounding” or “outcome missing at random”. “Chance of a recorded outcome” asks for a real chance of answering, with or without the offer, and “recorded outcome at reference” for a chance of the offer and an answer together; “Check the overlap and the models” probes both. Today’s rate alone needs only the survey conditions, because it compares no options.

Estimate current practice and the gain#

The method, targeted maximum likelihood estimation (TMLE), fits an outcome model for the chance of a top box, a treatment model for who gets the offer, and a response model for who answers. A correction step then weights each respondent by one over their predicted chance of their offer and of answering, so the respondents stand in for every patient. NaturalCourseMean() asks for today’s rate. Each model is a learner: any scikit-learn classifier.

  • outcome_learner: a logistic regression on the offer, the characteristics, and each product of two of them, so the offer’s effect can differ between patients.

  • treatment_learner, missingness_learner: logistic regressions, which have the true form in these simulated data. With real data a flexible classifier, such as scikit-learn’s HistGradientBoostingClassifier, is the safer default.

  • CrossFitting(n_folds=10): each patient’s predictions come from models trained without that patient, like out-of-fold predictions in cross-validation.

  • Runtime(random_state=2031, n_jobs=1): a fixed seed.

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


def logistic():
    return LogisticRegression(max_iter=2000)


def with_products():
    return make_pipeline(
        PolynomialFeatures(degree=2, interaction_only=True, include_bias=False), logistic()
    )


# For your own data, swap in your learners.
method = TMLEMethod(
    models=ModelSpec(
        outcome_learner=with_products(),
        treatment_learner=logistic(),
        missingness_learner=logistic(),
    ),
    cross_fitting=CrossFitting(n_folds=10),
    runtime=Runtime(random_state=2031, n_jobs=1),
)
gain_fit = gain_question.estimate(method=method)
current_fit = study.identify(NaturalCourseMean()).estimate(method=method)
print(gain_fit.summary())
                            Effect estimate (TMLE)
==============================================================================
Question:      mean top_box as          Rows:                            4,000
               treated, minus the mean  Treated share:                   0.437
               if every unit had        Out-of-fold predictions:      10 folds
               transition_navigation =  Outcome model:     logistic regression
               1                                        after polynomial terms
Outcome:       top_box (binary); 3,033  Treatment model:   logistic regression
               of 4,000 observed        Probability limits:         [0.009532,
Adjusted for:  discharge_risk, age,                                    0.9905]
               prior_utilization        Missingness model:            logistic
Method:        targeted maximum                                     regression
               likelihood (TMLE)
==============================================================================
      estimate   std. error             95% CI    p-value
------------------------------------------------------------------------------
par     -0.096        0.011   [-0.117, -0.074]    <0.0001
==============================================================================

par in the bottom table is today’s rate minus the rate with everyone offered, so the gain is 0.096 (interval 0.074 to 0.117), and the p-value tests a gain of zero. Rows: 4,000 shows that the fit kept every patient, including the 967 whose outcome is missing. Probability limits are the caps read under “Check the overlap and the models”. The interval is valid in large samples when the models are reasonably accurate.

from cleverly import PopulationAttributableFraction

achieved_fit = study.identify(PopulationAttributableRisk(reference=0)).estimate(method=method)
gain_share_fit = study.identify(PopulationAttributableFraction(reference=1)).estimate(method=method)
achieved_share_fit = study.identify(PopulationAttributableFraction(reference=0)).estimate(
    method=method
)


def line(label, estimate, true, sign=1.0):
    """Print one estimate, its 95% interval, the true value and the support label."""
    low, high = sorted(sign * limit for limit in estimate.ci)
    print(
        f"{label:46s} {sign * estimate.psi:7.4f}  ({low:.4f}, {high:.4f})  "
        f"true {true:.4f}  {estimate.support.label}"
    )


print(f"{'':46s} estimate  95% interval")
line("top-box rate under current practice", current_fit["ey_obs"], truth["ey_obs"])
line("gain if every patient got the offer", gain_fit["par"], -truth["par[reference=1]"], -1.0)
line("  as a share of today's rate", gain_share_fit["paf"], -truth["paf[reference=1]"], -1.0)
line("what current practice achieves over no one", achieved_fit["par"], truth["par[reference=0]"])
line("  as a share of today's rate", achieved_share_fit["paf"], truth["paf[reference=0]"])
                                               estimate  95% interval
top-box rate under current practice             0.5756  (0.5577, 0.5932)  true 0.5641  supported
gain if every patient got the offer             0.0956  (0.0739, 0.1173)  true 0.0799  supported
  as a share of today's rate                    0.1661  (0.1276, 0.2046)  true 0.1416  supported
what current practice achieves over no one      0.0872  (0.0680, 0.1064)  true 0.0850  supported
  as a share of today's rate                    0.1515  (0.1175, 0.1854)  true 0.1507  supported

Each interval contains its true value. The gain is about a sixth of today’s rate (share 0.1661), and removing the offer would lower today’s rate by a 0.1515 share. supported means a simulation study checks this estimator with missing outcomes, though not with these models; cleverly marks a result experimental when no study does.

Why the average effect overstates the gain#

A common mistake reports the average treatment effect (ATE), the rate if everyone got the offer minus the rate if no one did, as the gain from extending the offer.

from cleverly import ATE

ate_fit = study.identify(ATE(reference=0)).estimate(method=method)
line("average effect, everyone against no one (ATE)", ate_fit["ate"], truth["ate"])
line("gain over current practice", gain_fit["par"], -truth["par[reference=1]"], -1.0)
print()
parts = achieved_fit["par"].psi - gain_fit["par"].psi
not_offered = 1 - frame["transition_navigation"].mean()
print(f"achieved by current practice plus the gain:     {parts:.4f}")
print(f"share not offered today:                        {not_offered:.3f}")
print()
# Real data have no truth: drop the lines from here on.
print("true effect of the offer, known only because the data are simulated:")
print(f"  among patients offered today:     {truth['att']:.4f}")
print(f"  among patients not offered today: {truth['atc']:.4f}")
average effect, everyone against no one (ATE)   0.1828  (0.1448, 0.2199)  true 0.1649  supported
gain over current practice                      0.0956  (0.0739, 0.1173)  true 0.0799  supported

achieved by current practice plus the gain:     0.1828
share not offered today:                        0.563

true effect of the offer, known only because the data are simulated:
  among patients offered today:     0.1957
  among patients not offered today: 0.1412

The ATE, 0.1828, splits into what current practice has already collected (0.0872) and what is left to gain (0.0956), which add up to 0.1828. Its interval, 0.1448 to 0.2199, misses the true gain of 0.0799. Only the 0.563 of patients not offered today can still gain, and in these simulated data they gain less than those already offered (true effects 0.1412 against 0.1957): discharge teams already favor high-risk patients, for whom the offer does more. Reporting the ATE as the gain would promise the manager the part current practice already delivers.

Details: the identity behind the split

With \(A\) the offer and \(Y^a\) the outcome under option \(a\), the gain is \(E(Y^1) - E(Y) = P(A = 0)\,E(Y^1 - Y^0 \mid A = 0)\), the share not offered times the effect among them (the ATC). What current practice achieves is \(E(Y) - E(Y^0) = P(A = 1)\,E(Y^1 - Y^0 \mid A = 1)\), the share offered times the effect among them (the ATT), and the two sum to the ATE. The three fits start from the same models, but each corrects for its own quantity, so the identity need not hold exactly; here it holds to the printed digits. Each interval comes from its own fit.

The everyone-against-no-one effect as a ratio#

Some readers expect a relative effect. RiskRatio divides the rate if everyone got the offer by the rate if no one did, and OddsRatio divides the odds.

from cleverly import OddsRatio, RiskRatio

rr_fit = study.identify(RiskRatio(reference=0)).estimate(method=method)
or_fit = study.identify(OddsRatio(reference=0)).estimate(method=method)
line("risk ratio, everyone against no one", rr_fit["rr"], truth["rr"])
line("odds ratio, everyone against no one", or_fit["or"], truth["or"])
risk ratio, everyone against no one             1.3742  (1.2846, 1.4700)  true 1.3442  supported
odds ratio, everyone against no one             2.1379  (1.8207, 2.5104)  true 1.9667  supported

Offering everyone would make a top box 1.3742 times as likely as offering no one (interval 1.2846 to 1.4700). The odds ratio, 2.1379, is further from 1, as it always is when the rate rises, and the gap is large because a top box is common here. Like the ATE, both compare everyone with no one.

Does the offer help beyond the 7-day visit?#

If the program could guarantee every patient a primary-care visit within 7 days, would the offer still help? replace(design, intermediate="pcp_visit_7d") names the visit column, and intermediate_learner predicts it. ControlledDirectEffect(intermediate=1.0, contrast=ATE(reference=0)) sets every visit to yes (1.0) and asks for offer minus no offer. The fit uses every patient for every model (CrossFitting(enabled=False)), because that is the setup its simulation study checks; cleverly does not cross-fit this fit with missing outcomes. Its added conditions include that every kind of patient, offered or not, had a real chance of a visit, that no unrecorded factor drives both the visit and the outcome, and that answering the survey does not depend on the visit, as the graph assumes.

from cleverly import ControlledDirectEffect

visit_study = CausalStudy(
    frame, design=replace(design, intermediate="pcp_visit_7d"), protocol=protocol
)
held_at_yes = ControlledDirectEffect(intermediate=1.0, contrast=ATE(reference=0))
in_sample = TMLEMethod(
    models=ModelSpec(
        outcome_learner=with_products(),
        treatment_learner=logistic(),
        missingness_learner=logistic(),
        intermediate_learner=logistic(),
    ),
    cross_fitting=CrossFitting(enabled=False),
    runtime=Runtime(random_state=2031, n_jobs=1),
)
direct_fit = visit_study.identify(held_at_yes).estimate(method=in_sample)
line("effect with every visit held at yes", direct_fit["ate"], truth["cde_ate[visit=1]"])
line("effect with the visit left to follow the offer", ate_fit["ate"], truth["ate"])
effect with every visit held at yes             0.1153  (0.0592, 0.1724)  true 0.1160  supported
effect with the visit left to follow the offer  0.1828  (0.1448, 0.2199)  true 0.1649  supported

With every patient’s visit set to yes, the offer still raises the top-box rate by 0.1153 (interval 0.0592 to 0.1724), which contains the true 0.1160. So the offer does more than produce the visit. The ATE beside it lets the visit follow the offer; the two come from different fits, so the page gives no interval for their difference. Holding the visit at no could give another answer, so the gap does not measure how much of the effect the visit explains.

Check the overlap and the models#

The gain predicts every patient’s outcome with the offer, so every kind of patient needs a real chance of the offer and of answering under it. The correction step divides by those chances, so a chance near zero gives a few patients huge weights. The fit therefore caps each model’s chances at 0.0095 for the offer and 0.01 for answering. The outcome, offer and response models are what the code calls nuisance models. A model’s calibration slope is 1 when its probabilities are right on average, and below 1 when they are too extreme.

assessment = gain_fit.assess()
support = assessment.report("support")
nuisance = assessment.report("nuisance_models")
scores = assessment.report("score_equations")
models = {model.name: model.metrics for model in nuisance.models}
attention = tuple(item.name for item in assessment.attention)
# Delta is the 0/1 response indicator, R in the graph.
answering = support.mechanisms["P(Delta=1|A,W)"]
joint = support.mechanisms["P(A=a,Delta=1|W)"]
print("gain fit, checks that need attention:", attention or "none")
print(f"  smallest chance of an option:                 {support.truncated['most_extreme']:.3f}")
print(f"  smallest chance of answering under an option: {answering['min']:.3f}")
print(f"  smallest chance of an option and answering:   {joint['min']:.4f}")
print(f"  share of patients at the caps:                {joint['clipped_fraction']:.4f}")
for name, label in (("propensity", "offer"), ("missingness", "response"), ("outcome", "outcome")):
    slope, slope_se = models[name]["calibration_slope"], models[name]["calibration_slope_se"]
    print(f"  {label} model calibration slope: {slope:.2f} (standard error {slope_se:.2f})")
print("  problems the model checks found:", len(nuisance.findings) or "none")
print(f"  correction step solved its equations: {'PASS' if scores.passed else 'FAIL'}")
print()
direct_assessment = direct_fit.assess()
direct_support = direct_assessment.report("support").mechanisms
direct_attention = tuple(item.name for item in direct_assessment.attention)
print("direct-effect fit, checks that need attention:", direct_attention or "none")
print(f"  smallest chance of a visit:                   {direct_support['P(Z=1|A,W)']['min']:.3f}")
triple = direct_support["P(A=a,Delta=1,Z=z|W)"]
print(f"  smallest chance of an option, answering, and a visit: {triple['min']:.4f}")
print(f"  share of patients at the caps:                {triple['clipped_fraction']:.4f}")
gain fit, checks that need attention: none
  smallest chance of an option:                 0.025
  smallest chance of answering under an option: 0.268
  smallest chance of an option and answering:   0.0249
  share of patients at the caps:                0.0000
  offer model calibration slope: 1.00 (standard error 0.05)
  response model calibration slope: 0.98 (standard error 0.07)
  outcome model calibration slope: 0.95 (standard error 0.07)
  problems the model checks found: none
  correction step solved its equations: PASS

direct-effect fit, checks that need attention: none
  smallest chance of a visit:                   0.119
  smallest chance of an option, answering, and a visit: 0.0045
  share of patients at the caps:                0.0000

Nothing needs attention in either fit, and no patient reached a cap. For the gain, the smallest chances are above the caps and the calibration slopes sit near 1. The correction step adjusts the outcome model until its weighted errors average zero, which the interval relies on, and PASS says it got there. A check that needs attention, or a FAIL, would mean fixing the models or the data before reporting the estimate. The direct-effect fit is thinner: one patient’s chance of their offer, an answer, and a visit together is 0.0045. The caps apply to each model, not to this product, so a few respondents carry large weights, which widens its interval.

What if non-responders differ in ways we can’t see?#

The worry is that offered patients with a poor transition skipped the survey more often, and so did patients without the offer whose transition went well; either makes the true gain smaller. This check moves the missing outcomes that way step by step and recomputes the gain without refitting (missingness_tilt). At a given gamma, the odds of a top box among non-responders are exp(gamma) times lower than among comparable respondents with the offer, and that many times higher without it. The code calls each option, offer or no offer, an arm.

from cleverly.sensitivity import missingness_tilt

# For your own data, arm_gamma gives each option (arm) its direction: here a positive gamma
# raises the missing outcomes without the offer (0) and lowers those with it (1).
direction = {0: 1.0, 1: -1.0}
curve = missingness_tilt(gain_fit, (0.0, 0.5, 1.0, 1.5, 2.0), arm_gamma=direction).to_frame()
curve["gain"] = -curve["psi"]
curve["odds factor"] = np.exp(curve["gamma"])
print(curve[["gamma", "odds factor", "gain"]].round(4).to_string(index=False))
print()
both = gain_fit.sensitivity.tipping_gamma("par", arm_gamma=direction)
offered_only = gain_fit.sensitivity.tipping_gamma("par", arm_gamma={0: 0.0, 1: -1.0})
print(f"gamma at which the gain reaches 0: {both:.3f} (odds factor {np.exp(both):.2f})")
found = "none in the range searched" if offered_only is None else f"{offered_only:.3f}"
print("the same, moving only the missing outcomes with the offer:", found)
 gamma  odds factor    gain
   0.0       1.0000  0.0956
   0.5       1.6487  0.0676
   1.0       2.7183  0.0403
   1.5       4.4817  0.0162
   2.0       7.3891 -0.0030
gamma at which the gain reaches 0: 1.912 (odds factor 6.77)
the same, moving only the missing outcomes with the offer: none in the range searched

The gain falls as gamma grows and reaches zero at 1.912, an odds factor of 6.77 in both directions. For scale, the offer itself multiplies the odds of a top box by about 2 (the odds ratio above). Moving only the offered non-responders never erases the gain in the range searched. Whether the survey could miss that strongly is a judgment about this program.

Details: how the outcomes are moved

This is a pattern-mixture analysis. Within each arm and covariate profile, it adds gamma times the arm’s multiplier in arm_gamma to the logit of the fitted respondents’ mean, so with {0: 1.0, 1: -1.0} a positive gamma raises the unobserved mean without the offer and lowers it with the offer. Each row starts from the main fit’s outcome and response models and runs a new correction step for the moved assumption. The PAR moves through both of its parts, the rate under current practice and the rate if every patient got the offer. Each value comes from the fitted outcome model, so it carries that model’s error.

What if a confounder is missing?#

A missing confounder is an unrecorded factor that drives both the offer and the outcome. Today’s rate compares no options, so a missing confounder cannot bias it, but it can bias the rate if everyone got the offer. This check bounds that rate (CounterfactualMean(treatment=1)) and subtracts today’s. The confounder has two strengths, each a share from 0 to 1: on the outcome side (cf_y), how much of the outcome’s remaining variation it explains, and on the weight side (cf_d), how much it changes the correction weights, roughly how strongly it tracks who gets the offer beyond the recorded characteristics. Each recorded characteristic serves as a yardstick (benchmark, omitted_confounding).

from cleverly import CounterfactualMean

everyone_fit = study.identify(CounterfactualMean(treatment=1)).estimate(method=method)
today = current_fit["ey_obs"].psi
sensitivity = everyone_fit.sensitivity
print(f"rate if everyone got the offer: {everyone_fit['ey1'].psi:.4f}, today: {today:.4f}")

# For your own data, benchmark against every recorded confounder.
benchmarks = {}
for covariate in covariates:
    record = sensitivity.benchmark(covariates=(covariate,))
    bound = sensitivity.omitted_confounding(benchmark=record)
    benchmarks[covariate] = (record, bound)
    print()
    print(f"a confounder as strong as {covariate}:")
    print(f"  outcome-side strength, cf_y  {record.cf_y:.3f}")
    print(f"  weight-side strength, cf_d   {record.cf_d:.3f}")
    print(f"  range of the gain            [{bound.lower - today:.4f}, {bound.upper - today:.4f}]")

# The weight-side strength at which the lowest everyone-offered rate reaches today's rate, for a
# confounder that explains all the remaining outcome variation (cf_y = 1), found by bisection.
low, high = 0.0, 0.99
for _ in range(40):
    middle = (low + high) / 2
    if sensitivity.omitted_confounding(cf_y=1.0, cf_d=middle).lower > today:
        low = middle
    else:
        high = middle
tipping_cf_d = (low + high) / 2
print()
print(f"weight-side strength that erases the gain at cf_y = 1: {tipping_cf_d:.3f}")
rate if everyone got the offer: 0.6711, today: 0.5756
a confounder as strong as discharge_risk:
  outcome-side strength, cf_y  0.041
  weight-side strength, cf_d   0.047
  range of the gain            [0.0623, 0.1289]
a confounder as strong as age:
  outcome-side strength, cf_y  0.000
  weight-side strength, cf_d   0.000
  range of the gain            [0.0956, 0.0956]
a confounder as strong as prior_utilization:
  outcome-side strength, cf_y  0.012
  weight-side strength, cf_d   0.008
  range of the gain            [0.0882, 0.1030]

weight-side strength that erases the gain at cf_y = 1: 0.016

A confounder as strong as discharge_risk, the strongest recorded one, would leave the gain between 0.0623 and 0.1289. This range ignores sampling error. The recorded characteristics explain little of the outcome left after the offer (outcome-side strengths of 0.041 or less), so a hidden factor could be far stronger on that side. One that explained all of it would erase the gain with a weight-side strength of only 0.016, below the 0.047 of discharge_risk. So the gain survives confounders like the recorded ones but not a much stronger unrecorded cause of the outcome, such as support at home, that also sways who gets the offer. Only program staff can judge whether one exists.

Details: what the strengths mean

cf_y is the share of the outcome variation, left after the offer and the recorded characteristics, that a missing confounder explains. cf_d is the share of the second moment of the Riesz representer that only the missing confounder adds. For the rate if everyone got the offer, the representer combines the inverse offer probability and the inverse response probability. The bound uses rho = 1, the worst case, and it reads the point estimate only. benchmark() refits without one covariate and reports the gain in fit as proxies for these strengths, clipped at 0; age reads 0 because without it the outcome fits no worse and the weights vary no less. These simulated data have no hidden confounder, so the bounds are stress tests. Omitted-variable bounds defines each quantity.

What we can and can’t conclude#

For the manager: offering navigation to every eligible patient would raise the 30-day top-box rate by about 0.096 (95% interval 0.074 to 0.117) over current practice, counting patients who never answer the survey. Current practice already adds about 0.087 over offering no one, which is why the everyone-against-no-one effect of 0.183 is the wrong number for this decision. A guaranteed 7-day visit would not replace the offer, which still helps with every visit set to yes.

These answers rest on assumptions the data cannot check. Non-responders must have answered like comparable respondents; erasing the gain would take a departure with an odds factor of 6.77 in both arms at once. No unrecorded factor may drive both the offer and the outcome, and one that predicts the outcome well could erase the gain. The direct effect needs the same for the visit. The page shows one simulated sample with a known answer, which does not show how the methods perform in general.

Go deeper#

How we know the method works#

Simulation studies check each fit on other simulated data. They all have outcomes missing at random and one characteristic with three levels, and they fit decision trees or give the method the true model predictions:

section

study

what it uses

today’s rate

stacked missing-outcome natural-course CV-TMLE

ten folds, as here

the gain and what current practice achieves, with their shares

missing-outcome attributable effects

ten folds in one scenario, as here

the ATE, the ratios, and the rate under the offer

stacked arm-indexed missing-outcome CV-TMLE

ten folds, as here

the effect with the visit held at yes

controlled direct-effect TMLE

in sample, as here, against R tmle 2.1.1

CV-TMLE is the cross-fitted TMLE used here. No study uses this page’s logistic models on continuous characteristics, so supported here means the estimator is checked, not this exact setup. The direct-effect study gives both implementations the true model predictions, so it does not check models fitted from data. The confounder bounds and the checks below print numbers without a pass or fail (descriptive), because their studies cover fits without missing outcomes or fits in sample. The technical entry lists the methods’ evidence and limits.

Try to break the result#

These checks change the data in a known way and refit 20 times each. They run on the ATE fit, because cleverly runs them on a comparison of the two options:

  • placebo shuffles the offer, so the estimate should be about zero;

  • random_common_cause adds a column of noise, so the estimate should barely move;

  • subset refits on random 70% samples, so the estimates should spread about as much as the standard error implies for 70% subsamples of these data (0.0126 here).

from cleverly.validation import refute

refutation = refute(ate_fit, tests=("placebo", "subset", "random_common_cause"))
columns = ["test", "original", "refuted_mean", "refuted_sd", "expectation", "verdict"]
print(refutation.to_frame()[columns].round(4).to_string(index=False))
               test  original  refuted_mean  refuted_sd       expectation     verdict
            placebo    0.1828        0.0015      0.0197               ~ 0 descriptive
             subset    0.1828        0.1873      0.0114 scatter ~ 0.01256 descriptive
random_common_cause    0.1828        0.1827      0.0009          ~ 0.1828 descriptive

All three behave as expected: the shuffled offer gives an estimate near zero, the noise column barely moves it, and the 70% refits spread about as much as the standard error predicts. These checks test the method, so they cannot detect a hidden confounder or a survey that is not missing at random. The verdict column reads descriptive: cleverly gives a pass or fail only when a simulation study backs the check for this kind of fit, and none covers a fit with missing outcomes.

The missing survey answers page tests the method on outcomes with a known effect when some outcomes are missing. Its limits hold here too: these data record no outcome before the offer that the offer cannot change, so no negative-control check runs, and cleverly refuses the hidden-confounder simulation (simulated_confounding) because the offer changes who answers (roadmap item F12).

How strong would a confounder be on a risk-ratio scale?#

The E-value asks how strongly a missing confounder would need to be linked to both the offer and the top-box outcome, as a risk ratio, to explain the risk ratio away. Epidemiology papers often report it.

evalue = rr_fit.sensitivity.evalue()
print(evalue.summary())
                                   E-value
==============================================================================
Question:  how strong a confounder      Estimate:                           rr
           would explain away rr        Scale:                      risk ratio
==============================================================================
                             risk ratio    E-value
------------------------------------------------------------------------------
estimate                          1.374       2.09
95% limit nearest the null        1.285       1.89
==============================================================================
An unmeasured confounder would need a risk ratio of 2.09 with both the
treatment and the outcome, beyond the measured covariates, to explain away the
estimate; 1.89 to move the interval to the null.
Notes:
[1] 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.

A weaker link to one of the offer and the outcome can be offset by a stronger link to the other. The E-value is about everyone against no one; it is not a bound on the gain over current practice.

Where to go next#

The survey non-response example treats unreturned surveys in more depth, with a continuous score and the everyone-against-no-one question. The technical entry’s sections on population interventions and missing outcomes and controlled direct effects give the exact estimators. The examples index lists every example.