More contacts and more service time: TMLE for policy effects#

At a glance#

A transition program follows patients home from hospital. Its discharge team puts each patient on a low, medium, or high schedule of follow-up contacts, and sets their hours of navigator time and minutes of pharmacist review. The program’s owner has two ideas. The first nudges the team, for example with a default or a prompt, so that each patient’s odds of the high schedule double while the team still chooses: a patient with a 20% chance of it would have about 33%. The second raises both service times.

Doubling each patient’s odds of the high schedule would raise the average 30-day transition score (0 is worst, 1 is best) by 0.021, with a 95% confidence interval of 0.019 to 0.023: about an eighth of the true 0.17 gap between putting every patient on the high schedule and every patient on the low one. Adding half an hour of navigator time and five minutes of pharmacist review would raise the share of successful transitions (a score of at least 0.7) by 0.075 (7.5 percentage points, interval 0.062 to 0.087). In these data the two services help each other, so that is more than the two raises give apart; the size of that extra is checked only by the page’s own repeated draws (Details), not by a simulation study of the method.

Simple comparisons understate both answers several times over, because the team gives more to higher-risk patients, who do worse. Both answers assume the recorded characteristics capture everything that drove the team’s choices.

The data are simulated, so we know the true effects (0.021 and 0.073), and each interval contains its value.

The question#

The team will keep choosing schedules, so the first question is what happens if each patient’s chances shift toward the intensive schedules. Service time is a dose, a number of hours or minutes, so the second question is what happens if each patient’s own dose goes up a little.

The first answer changes odds. A patient with a 20% chance of the high schedule and a 50% chance of the low one has odds of 0.4 for high against low; doubling makes them 0.8. Every patient keeps a chance of every schedule. The second answer adds a fixed amount to each patient’s recorded dose, up to a limit.

In the graph, an arrow means “affects”. W is the recorded characteristics, A the schedule (or the two doses), Y the outcome, and U any unrecorded factor.

  W ──▶ A ──▶ Y ◀── U
  │           ▲
  └───────────┘

  W  = discharge_risk, age, and baseline_support_need (first question);
       discharge_risk, age, and medication_burden (second question)
  A  = cadence, the contact schedule (first question);
       navigator_hours and pharmacist_minutes (second question)
  Y  = transition_score at day 30 (first question);
       transition_success at day 30 (second question)
  U  = anything unrecorded that affects the outcome

The characteristics affect both what the team gives and how the patient does, so they are confounders, and the analysis adjusts for them. U has no arrow into A: we assume nothing unrecorded drove the team’s choices.

The data#

Every fit sets its seeds, so a rerun prints the same numbers. Another version of cleverly can print slightly different numbers.

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

import cleverly

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

make_contact_schedules draws 3,000 simulated discharges and the true answers. TILTS names each odds change (also called a tilt) and the factor on each schedule’s odds. Current practice multiplies nothing, written as a factor of 1 on the low schedule.

from cleverly.datasets import make_contact_schedules

# Each odds change names the schedules whose odds it multiplies, compared with the low schedule.
# A schedule it leaves out keeps its current odds. For your own data, use your own labels.
# Results are named by kind: ey[low] is the average if every patient got that schedule,
# ey_ipsi[name] the average under an odds change, and ate_ipsi[name vs current practice] its
# change against current practice (ate: average treatment effect; ipsi: incremental propensity-score
# intervention, where a propensity score is a patient's chance of each schedule).
TILTS = {
    "current practice": {"low": 1.0},
    "medium and high doubled": {"medium": 2.0, "high": 2.0},
    "high doubled": {"high": 2.0},
}
SCHEDULES = ["low", "medium", "high"]
# With your own data, load your data frame here, such as frame = pd.read_csv(...).
# Real data have no `truth`: delete the lines that print only it, and remove it from the rest.
frame, truth = make_contact_schedules(n=3_000, seed=24, tilts=TILTS)
print("rows and columns:", frame.shape)
print("column names:", list(frame.columns))
print(frame.head().round(3).to_string())
print()
print("true average score if every patient got one schedule:")
for level in SCHEDULES:
    print(f"  {level:7s} {truth[f'ey[{level}]']:.3f}")
print("true change in the average score under each odds change:")
for name in list(TILTS)[1:]:
    print(f"  {name:24s} {truth[f'ate_ipsi[{name} vs current practice]']:+.4f}")
rows and columns: (3000, 5)
column names: ['transition_score', 'cadence', 'discharge_risk', 'age', 'baseline_support_need']
   transition_score cadence  discharge_risk    age  baseline_support_need
0             0.135  medium           1.351  0.343                 -1.163
1             0.458  medium          -0.187 -0.339                 -0.228
2             0.511    high           0.597 -1.279                  0.967
3             0.332     low          -1.128 -0.188                  0.887
4             0.274     low           0.664 -0.691                  1.769

true average score if every patient got one schedule:
  low     0.478
  medium  0.544
  high    0.652
true change in the average score under each odds change:
  medium and high doubled  +0.0147
  high doubled             +0.0208

Each row is one discharge: the day-30 score, the schedule (cadence), and three characteristics measured before the schedule was set, each scaled to average 0 and spread 1. An odds change alters the schedule of only some patients, so its true effect is far smaller than the gap between all-high and all-low.

Why a simple comparison misleads#

A first guess applies the odds change to the overall share on each schedule and keeps each schedule’s raw average.

observed = frame.groupby("cadence").agg(
    share=("transition_score", "size"),
    average_score=("transition_score", "mean"),
    discharge_risk=("discharge_risk", "mean"),
    age=("age", "mean"),
)
observed = observed.loc[SCHEDULES]
observed["share"] = observed["share"] / len(frame)
observed["true_average"] = [truth[f"ey[{level}]"] for level in SCHEDULES]  # simulated data only
print(observed.round(3).to_string())
print()


def simple_answer(factors):
    """Apply the odds change to the overall shares, and keep each schedule's raw average."""
    weight = observed["share"] * np.array([factors.get(level, 1.0) for level in SCHEDULES])
    return float((weight * observed["average_score"]).sum() / weight.sum())


simple = {
    name: simple_answer(TILTS[name]) - simple_answer(TILTS["current practice"]) for name in TILTS
}
print("change in the average score: the simple answer, and the true change")
for name in list(TILTS)[1:]:
    true_change = truth[f"ate_ipsi[{name} vs current practice]"]
    print(f"  {name:24s} simple {simple[name]:+.4f}   true {true_change:+.4f}")
         share  average_score  discharge_risk    age  true_average
cadence                                                           
low      0.331          0.532          -0.430  0.076         0.478
medium   0.316          0.568          -0.014 -0.245         0.544
high     0.352          0.571           0.432  0.165         0.652

change in the average score: the simple answer, and the true change
  medium and high doubled  simple +0.0050   true +0.0147
  high doubled             simple +0.0036   true +0.0208

The simple answers are about a third and a sixth of the true changes. The high-schedule patients have the highest discharge risk (0.432 on average, against -0.430 on the low schedule), and higher risk lowers the score. So the high schedule’s raw average is barely above the low one’s, because it goes to patients who would do worse anyway: this is confounding by discharge risk.

Set up the analysis#

The study description (StudyProtocol) is optional and does not change the estimate. It writes down who the answer is about, what is compared, and how deaths count, and every result keeps a link to it. replace changes the fields this question changes.

from dataclasses import replace

from cleverly.datasets import navigation_protocol

# For your own study, build cleverly.StudyProtocol(...). It needs all ten fields, each a short
# text or a list of texts:
#   target_population, eligibility: who the answer is about, and the entry rules;
#   time_zero, horizon: when follow-up starts, and when the outcome is measured;
#   treatment_strategies, treatment_versions: the options compared, and their variants;
#   outcome: the measured result;
#   intercurrent_event_handling: how events such as death before the horizon count;
#   interference_unit: the unit whose treatment can affect only its own outcome;
#   assumption_rationale: why the design makes the causal assumptions believable.
# Here the program's own description supplies the fields this question keeps (the program.*
# values, printed below). For your own study, write every field as your own text.
program = navigation_protocol()
protocol = replace(
    program,
    time_zero="Discharge-home order, after baseline measurement and before the schedule is set",
    treatment_strategies=(
        "Keep each patient's current chances of the three contact schedules",
        "Double each patient's odds of the medium and the high schedule against the low one",
        "Double each patient's odds of the high schedule against the other two",
    ),
    treatment_versions=(
        "The schedule as the discharge team assigns it today",
        "A schedule drawn at random with the changed chances, given the recorded characteristics",
        "A schedule drawn at random with the changed chances, given the recorded characteristics",
    ),
    outcome="Patient-reported transition score at day 30, from 0 (worst) to 1 (best)",
    intercurrent_event_handling=(
        program.intercurrent_event_handling[0],
        "Analyze the assigned schedule regardless of completed contacts",
        "A death before day 30 counts as a score of 0 (composite strategy)",
    ),
    assumption_rationale=(
        "The recorded characteristics cover the common causes of the schedule and the score",
        "Every schedule uses the same scripts and access rules, so each schedule is one "
        "well-defined action and a patient's recorded score is the score they would have had "
        "under the schedule they got",
        program.assumption_rationale[2],
    ),
)
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 schedule is set
Strategies: Keep each patient's current chances of the three contact schedules; Double each patient's odds of the medium and the high schedule against the low one; Double each patient's odds of the high schedule against the other two
Versions: The schedule as the discharge team assigns it today; A schedule drawn at random with the changed chances, given the recorded characteristics; A schedule drawn at random with the changed chances, given the recorded characteristics
Outcome: Patient-reported transition score at day 30, from 0 (worst) to 1 (best)
Horizon: 30 days after discharge
Intercurrent events: Use the transition score regardless of readmission; Analyze the assigned schedule regardless of completed contacts; A death before day 30 counts as a score of 0 (composite strategy)
Interference unit: Individual patient
Rationale: The recorded characteristics cover the common causes of the schedule and the score; Every schedule uses the same scripts and access rules, so each schedule is one well-defined action and a patient's recorded score is the score they would have had under the schedule they got; Reserved navigator capacity and access controls support no interference

Under “high doubled” a patient is not promised the high schedule: the schedule is drawn with the changed chances. “Regardless of completed contacts” means the analysis compares assigned schedules, whether or not each patient completed every contact. A death before day 30 counts as a score of 0; the output calls this way of folding an event into the outcome the composite strategy.

What must be true for a causal answer#

Name the outcome, the treatment, and the characteristics to adjust for (PointTreatment, for one treatment decision per patient). IncrementalEffect takes the odds changes, each an Incremental with its factors and name, and the first is the comparison. study.identify(...) writes down what must be true for the answers to be causal.

from cleverly import CausalStudy, IncrementalEffect, PointTreatment
from cleverly.interventions import Incremental

# For your own data, change the outcome and treatment names and the covariates.
covariates = ("discharge_risk", "age", "baseline_support_need")
study = CausalStudy(
    frame,
    design=PointTreatment(outcome="transition_score", treatment="cadence", adjustment=covariates),
    protocol=protocol,
)
tilts = study.identify(
    IncrementalEffect(tuple(Incremental(factors, name=name) for name, factors in TILTS.items()))
)
print("conditions the answer rests on:")
for condition in tilts.identification.assumptions:
    print("  -", condition.split(":")[0].replace("*", ""))
conditions the answer rests on:
  - consistency
  - no interference
  - no unmeasured confounding
  - no positivity assumption
  - the intervention is a functional of the observed-data law

The first three conditions need judgment, and the data cannot check them. “Consistency” means a schedule means the same contacts for every patient. “No interference” means one patient’s schedule does not change another’s score. “No unmeasured confounding” means the three characteristics capture everything that drove both the team’s choice and the score.

The fourth line is good news. Putting everyone on the high schedule would need every kind of patient to have a real chance of it (positivity), but doubling odds never gives a patient a schedule they had no chance of. The last line says the changed chances are built from the current chances, which the treatment model estimates.

Estimate the effect of each odds change#

The method, targeted maximum likelihood estimation (TMLE), fits two models. The outcome model predicts the score from the schedule and the characteristics. The treatment model predicts each patient’s chances of the three schedules, which the odds changes act on. A correction step then weights each patient by how much more likely the odds change makes their own schedule, which removes the bias the outcome model leaves. So this answer leans on the treatment model.

  • outcome_learner: a plain linear regression, deliberately too simple, as any outcome model may be. When the treatment model is right, the correction keeps the estimate on target (the Details cover the interval).

  • treatment_learner: a logistic regression that predicts all three schedules at once. It matches how the simulated data were made. On your own data, refit with a flexible learner, such as gradient boosting with CrossFitting(n_folds=5). If the two estimates differ by more than about a standard error, the simple model missed part of how the team chooses; report the flexible fit.

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

# For your own data, swap in your own learners. CrossFitting(enabled=False) trains and uses each
# model on all rows, which is safe for simple models; a flexible learner needs out-of-fold
# predictions (CrossFitting(n_folds=5)). q_bounds declares the known range of the outcome, here
# 0 to 1, so the correction keeps every prediction inside it. alpha=0.05 asks for 95% intervals.
method = TMLEMethod(
    models=ModelSpec(
        outcome_learner=LinearRegression(),
        treatment_learner=LogisticRegression(max_iter=1000),
    ),
    cross_fitting=CrossFitting(enabled=False),
    targeting=Targeting(q_bounds=(0.0, 1.0)),
    inference=Inference(alpha=0.05),
    runtime=Runtime(random_state=24, n_jobs=1),
)
tilt_result = tilts.estimate(method=method)
print(tilt_result.summary())
print()
for name in list(TILTS)[1:]:
    key = f"ate_ipsi[{name} vs current practice]"
    point = tilt_result[key]
    low, high = point.ci
    print(
        f"{name:24s} estimate {point.psi:+.4f}  95% CI ({low:+.4f}, {high:+.4f})  "
        f"true {truth[key]:+.4f}  {point.support.label}"
    )
                            Effect estimate (TMLE)
==============================================================================
Question:      effect of cadence on     Rows:                            3,000
               transition_score; each   Arm shares:     high=0.352, low=0.331,
               row is defined below                               medium=0.316
Outcome:       transition_score         Out-of-fold predictions:            no
               (continuous)             Outcome model:       linear regression
Adjusted for:  discharge_risk, age,     Treatment model:   logistic regression
               baseline_support_need
Method:        targeted maximum
               likelihood (TMLE)
==============================================================================
                             estimate  std. error              95% CI  p-value
------------------------------------------------------------------------------
ate_ipsi[medium and high      0.01461     0.00084  [0.01295, 0.01628]  <0.0001
doubled vs current
practice]
ate_ipsi[high doubled vs      0.02090     0.00096  [0.01901, 0.02279]  <0.0001
current practice]
==============================================================================
What each row estimates
                                                        meaning
------------------------------------------------------------------------------
ate_ipsi[medium and high doubled vs current practice]   contrast of each tilt
                                                        against the reference
                                                        tilt
ate_ipsi[high doubled vs current practice]              contrast of each tilt
                                                        against the reference
                                                        tilt
==============================================================================
Simultaneous 95% bands
                                                                      band
------------------------------------------------------------------------------
ate_ipsi[medium and high doubled vs current practice]   [0.01276, 0.01646]
ate_ipsi[high doubled vs current practice]              [0.01880, 0.02300]
==============================================================================
Notes:
[1] The interval of ate_ipsi[medium and high doubled vs current practice],
    ate_ipsi[high doubled vs current practice] is widened on the side where a
    skewed outcome makes misses more likely, so it need not be centred on the
    estimate. Its t distribution has 250 or more degrees of freedom, so it is
    close to the normal one. The p-value is the level at which the interval
    would just reach the null value.
[2] The bands cover all 2 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.

medium and high doubled  estimate +0.0146  95% CI (+0.0130, +0.0163)  true +0.0147  supported
high doubled             estimate +0.0209  95% CI (+0.0190, +0.0228)  true +0.0208  supported

Doubling the high odds raises the average score by 0.0209 (interval 0.0190 to 0.0228), and doubling the medium and high odds by 0.0146 (0.0130 to 0.0163). Both intervals contain the true values. In the summary, “arm shares” are the shares on each schedule (an arm is one treatment option), and the simultaneous bands cover both rows at once. The answers read supported: a validation study covers this kind of fit, though it does not check that this fit’s models are right. A fit outside every study reads experimental.

Details: which model must be right, and a repeated-draw check

For an odds change, the error left after the correction step is a product of two errors: the error in the predicted average under the changed chances, which uses both models, and the treatment model’s error. The technical entry gives the exact form. A correct treatment model keeps the estimate centered on the truth whatever the outcome model. A correct outcome model alone does not, because the changed chances are built from the treatment model. A wrong outcome model can still make the interval too narrow: in the validation study, a right treatment model with a constant outcome model covered the truth on 89 to 91% of draws.

A simulation we ran for this page (reviews/notebook-review/probes/schedules-and-intensity/sweep.py in the cleverly repository) repeats this fit on 400 draws of the same simulated data. The interval contained the true change on 377 draws for doubling the medium and high odds and on 378 for doubling the high odds (a 95% interval should contain it on about 380). The mean standard error was 1.03 and 0.99 times the spread of the estimates, and every draw read supported. So coverage held for this page’s models.

Check the weights and the models#

Weights that divide by small chances can let a few patients decide the answer. An odds change never divides by a chance, and the check confirms it.

# "support" reports the weights; "nuisance_models" reports the outcome and treatment models.
tilt_assessment = tilt_result.assess()
attention = tuple(item.name for item in tilt_assessment.attention)
print("checks that need attention:", attention or "none")
print()
for name, row in tilt_assessment.report("support").items():
    if name == "current practice":
        continue
    low, high = row.guaranteed
    print(
        f"{name}: every weight lies between {low:g} and {high:g}; "
        f"effective sample size {row.effective_sample_size:,.0f} of {len(frame):,}"
    )
print()
nuisance = tilt_assessment.report("nuisance_models")
for model in nuisance.models:
    if model.name.startswith("propensity["):  # the treatment model, one schedule at a time
        level = model.name.removeprefix("propensity[").removesuffix("]")
        auc = model.metrics["auc"]
        print(f"treatment model, {level} schedule against the other two: AUC {auc:.2f}")
checks that need attention: none

medium and high doubled: every weight lies between 0.5 and 2; effective sample size 2,788 of 3,000
high doubled: every weight lies between 0.5 and 2; effective sample size 2,712 of 3,000

treatment model, high schedule against the other two: AUC 0.72
treatment model, low schedule against the other two: AUC 0.70
treatment model, medium schedule against the other two: AUC 0.62

Nothing needs attention. Each weight is the factor on the patient’s own schedule over their average factor, so it lies between 0.5 and 2. The effective sample size, how many equally weighted patients the weighted group is worth, is 2,788 and 2,712 of 3,000. The AUC measures how well the treatment model tells one schedule’s patients from the rest (0.5 is chance, 1 is perfect): the characteristics shape the team’s choices only in part. An odds change needs no positivity (overlap), so no AUC is a problem here.

The second question: more navigator and pharmacist time#

The proposal adds 0.5 navigator hours and 5 pharmacist minutes, up to limits of 7 hours and 70 minutes; a patient whose raised dose would pass a limit keeps their current dose. This part uses a second simulated sample, with a yes-or-no outcome (a successful transition) and medication burden, which drives pharmacist time, as its third characteristic. Your own data would use the same patients for both questions.

from cleverly.datasets import make_navigation_doses

# With your own data, load the frame here. Real data have no dose_truth: delete the lines that
# print only it, and remove it from the rest.
dose_frame, dose_truth = make_navigation_doses(n=3_000, seed=23)
# For your own data, name your dose columns and the characteristics to adjust for.
DOSES = ["navigator_hours", "pharmacist_minutes"]
dose_covariates = ("discharge_risk", "age", "medication_burden")
print("rows and columns:", dose_frame.shape)
print(dose_frame.head().round(3).to_string())
print()
print(dose_frame[DOSES].describe().loc[["mean", "std", "min", "max"]].round(1).to_string())
print()
print("true values of the simulated data:")
for name, value in dose_truth.items():
    print(f"  {name:52s} {value:.4f}")
rows and columns: (3000, 6)
   transition_success  navigator_hours  pharmacist_minutes  discharge_risk    age  medication_burden
0                 0.0            4.019              35.319           0.553  0.218             -0.058
1                 1.0            3.726              16.099          -2.319  0.431             -2.126
2                 0.0            4.259              48.825           0.910  0.606              0.830
3                 0.0            3.541              42.822           0.828  0.299             -0.535
4                 0.0            2.062              39.119          -0.307  1.508             -0.582

      navigator_hours  pharmacist_minutes
mean              4.0                40.0
std               1.1                11.1
min               0.1                 4.2
max               8.3                80.9

true values of the simulated data:
  ey_policy[current practice]                          0.4423
  ey_policy[more navigator time]                       0.4705
  ey_policy[more pharmacist time]                      0.4698
  ey_policy[both]                                      0.5155
  ate_policy[more navigator time vs current practice]  0.0282
  ate_policy[more pharmacist time vs current practice] 0.0275
  ate_policy[both vs current practice]                 0.0731

Each row holds success (1 or 0), the two doses, and three characteristics. Patients average 4.0 navigator hours and 40.0 pharmacist minutes. In the true values, ey_policy is the share of successful transitions under each plan, and ate_policy its change against current practice.

Why a simple regression misleads#

# One CPU thread for this plain scikit-learn fit, as cleverly uses for its own fits, so a rerun
# prints the same digits.
with cleverly.learners.thread_limit():
    simple_fit = LinearRegression().fit(dose_frame[DOSES], dose_frame["transition_success"])
    adjusted_fit = LinearRegression().fit(
        dose_frame[[*DOSES, *dose_covariates]], dose_frame["transition_success"]
    )
simple_both = simple_fit.coef_[0] * 0.5 + simple_fit.coef_[1] * 5.0
adjusted_both = adjusted_fit.coef_[0] * 0.5 + adjusted_fit.coef_[1] * 5.0
true_both = dose_truth["ate_policy[both vs current practice]"]  # simulated data only
print("change in success for 0.5 more hours and 5 more minutes:")
print(f"  regression on the two doses only:          {simple_both:+.4f}")
print(f"  regression that adds the characteristics:  {adjusted_both:+.4f}")
print(f"  true change:                               {true_both:+.4f}")
print()
risk_band = pd.qcut(dose_frame["discharge_risk"], 3, labels=["lower", "middle", "higher"])
print(
    dose_frame.groupby(risk_band, observed=True)[[*DOSES, "transition_success"]]
    .mean()
    .round(2)
    .to_string()
)
change in success for 0.5 more hours and 5 more minutes:
  regression on the two doses only:          +0.0049
  regression that adds the characteristics:  +0.0616
  true change:                               +0.0731

                navigator_hours  pharmacist_minutes  transition_success
discharge_risk                                                         
lower                      3.45               35.44                0.54
middle                     3.96               39.86                0.44
higher                     4.47               44.69                0.36

The regression on the doses alone gives one fifteenth of the true change: higher-risk patients get more of both doses (4.47 hours against 3.45 in the lowest third) and succeed less often (0.36 against 0.54), the same confounding as before. Adding the characteristics brings it to +0.0616, still short of +0.0731, because a straight-line model has no room for the two doses helping each other. The method below adds products in its outcome model, then uses weights as a safeguard in case that model is wrong.

Record the dose question#

The study description changes the same fields as before, now for doses.

# For your own study, write these fields for your dose question, as in the protocol cell.
dose_protocol = replace(
    program,
    time_zero="Discharge-home order, after baseline measurement and before the doses are set",
    treatment_strategies=(
        "Keep the navigator hours and pharmacist minutes that current practice gives",
        "Add 0.5 navigator hours unless that passes 7 hours",
        "Add 5 pharmacist minutes unless that passes 70 minutes",
        "Add both, each with its own limit",
    ),
    treatment_versions=(
        "The doses as the discharge team sets them today",
        "Navigator contact time within 30 days, raised for each patient",
        "Pharmacist medication-review time within 30 days, raised for each patient",
        "Both raises for each patient",
    ),
    outcome="Successful transition: a 30-day transition score of at least 0.7 of the maximum",
    intercurrent_event_handling=(
        "Use the success indicator regardless of readmission",
        "Analyze the assigned doses regardless of how much contact was completed",
        "The protocol counts death before day 30 as an unsuccessful transition "
        "(composite strategy)",
    ),
    assumption_rationale=(
        "The recorded characteristics cover the common causes of the doses and success",
        *program.assumption_rationale[1:],
    ),
)
print("\n".join(dose_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 doses are set
Strategies: Keep the navigator hours and pharmacist minutes that current practice gives; Add 0.5 navigator hours unless that passes 7 hours; Add 5 pharmacist minutes unless that passes 70 minutes; Add both, each with its own limit
Versions: The doses as the discharge team sets them today; Navigator contact time within 30 days, raised for each patient; Pharmacist medication-review time within 30 days, raised for each patient; Both raises for each patient
Outcome: Successful transition: a 30-day transition score of at least 0.7 of the maximum
Horizon: 30 days after discharge
Intercurrent events: Use the success indicator regardless of readmission; Analyze the assigned doses regardless of how much contact was completed; The protocol counts death before day 30 as an unsuccessful transition (composite strategy)
Interference unit: Individual patient
Rationale: The recorded characteristics cover the common causes of the doses and success; 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

As before, the plans assign doses and the analysis ignores how much contact was completed. A death before day 30 counts as unsuccessful.

What the dose answer rests on#

Each plan is a JointPolicy, which can raise one dose or both. Shift(0.5, cap=7.0) adds 0.5 unless the result passes 7, and current practice raises nothing (components={}). policy_kind="known" says the raise is a fixed rule written in advance. In PointTreatment, continuous_treatment marks both doses as numbers rather than categories.

from cleverly import ModifiedTreatmentPolicyEffect
from cleverly.interventions import JointPolicy, Shift

# For your own data, change the dose columns, the amounts added, and each dose's limit (cap).
more_hours = Shift(0.5, cap=7.0)
more_minutes = Shift(5.0, cap=70.0)
plans = [
    JointPolicy("current practice", components={}, policy_kind="known"),
    JointPolicy(
        "more navigator time", components={"navigator_hours": more_hours}, policy_kind="known"
    ),
    JointPolicy(
        "more pharmacist time", components={"pharmacist_minutes": more_minutes}, policy_kind="known"
    ),
    JointPolicy(
        "both",
        components={"navigator_hours": more_hours, "pharmacist_minutes": more_minutes},
        policy_kind="known",
    ),
]
dose_study = CausalStudy(
    dose_frame,
    design=PointTreatment(
        outcome="transition_success",
        treatment=DOSES,
        continuous_treatment=DOSES,
        adjustment=dose_covariates,
    ),
    protocol=dose_protocol,
)
raises = dose_study.identify(ModifiedTreatmentPolicyEffect(plans, reference="current practice"))
print("conditions the answer rests on:")
for condition in raises.identification.assumptions:
    name = condition.split(":")[0].replace("*", "")
    if not name.startswith("with "):  # missing outcomes or a mediator: not used here
        print("  -", name)
conditions the answer rests on:
  - consistency
  - no interference
  - no unmeasured confounding
  - positivity for the assigned dose
  - the policy is a known function of (A, W), and of a randomizer of known law when it is randomized
  - on a continuous treatment, d is piecewise smooth invertible (Diaz, Williams, Hoffman & Schenck 2023, Assumption 4)

The first three conditions are those of the first question. “Positivity for the assigned dose” means similar patients sometimes receive the raised dose; the limits help, by keeping raises inside the observed range. The fifth line says the raise is a fixed rule of the recorded doses and characteristics. The last is a condition on the rule, which you check by reading it: on each piece (raised, or kept because the raise would pass the limit) the original dose can be recovered from the new one.

Estimate the effects of the raises#

TMLE again fits two models. The outcome model, a logistic regression on the doses, the characteristics, their squares and their products, lets the effect of one dose depend on the other. The weights now say how much more common the raised doses are than the current ones among patients with the same characteristics (the density ratio). ratio="classifier" estimates them with a classifier, here a logistic regression passed as treatment_learner.

# The outcome model: a logistic regression on the doses, the characteristics, their squares and
# their products, still a simple fixed-form model. The weights (also called the density ratio):
# a logistic classifier, which treatment_learner names on this route (ratio="classifier"). A 0/1
# outcome needs no declared range, so Targeting() drops q_bounds. Swap in your own learners.
dose_method = replace(
    method,
    models=ModelSpec(
        outcome_learner=make_pipeline(
            StandardScaler(), PolynomialFeatures(2), LogisticRegression(max_iter=1000)
        ),
        treatment_learner=LogisticRegression(max_iter=1000),
        ratio="classifier",
    ),
    targeting=Targeting(),
    runtime=Runtime(random_state=23, n_jobs=1),
)
dose_result = raises.estimate(method=dose_method)
HOURS, MINUTES, BOTH = (f"ate_policy[{plan.name} vs current practice]" for plan in plans[1:])
for key in (HOURS, MINUTES, BOTH):
    point = dose_result[key]
    low, high = point.ci
    print(
        f"{key:52s} {point.psi:+.4f}  ({low:+.4f}, {high:+.4f})  "
        f"true {dose_truth[key]:+.4f}  {point.support.label}"
    )
ate_policy[more navigator time vs current practice]  +0.0284  (+0.0194, +0.0374)  true +0.0282  supported
ate_policy[more pharmacist time vs current practice] +0.0289  (+0.0203, +0.0375)  true +0.0275  supported
ate_policy[both vs current practice]                 +0.0747  (+0.0625, +0.0868)  true +0.0731  supported

Both raises together add 0.075 to the share of successful transitions (interval 0.062 to 0.087), and each raise alone adds about 0.03. All three intervals contain the true values, and all three read supported.

Details: how the classifier gives the weights, and a repeated-draw check

The code stacks two copies of the data, one with the current doses and one with the raised doses, and trains the classifier to tell the copies apart. Where it tells them apart easily, the raise moves patients to doses that patients like them rarely get, and the weights grow. The fit never computes a patient’s original dose from the raised one. Here the classifier’s logistic form nearly matches the simulated doses, which are normal around a straight line in the characteristics. A classifier of the wrong form would give wrong weights.

The same simulation repeats this fit on 400 draws. The interval contained the true change on 384 draws for more navigator time, 379 for more pharmacist time, and 372 for both (380 is expected; 372 is within simulation noise). The mean standard errors were 1.04, 1.02, and 0.98 times the spread of the estimates.

Check the weights#

A raise that moves patients to doses rare among similar patients gives those patients large weights, so a few of them carry the answer.

dose_assessment = dose_result.assess()
attention = tuple(item.name for item in dose_assessment.attention)
print("checks that need attention:", attention or "none")
print()
header = ("plan", "moved", "kept own dose", "mean weight", "max weight", "effective n")
print("{:22s} {:>6s} {:>14s} {:>12s} {:>11s} {:>12s}".format(*header))
for name, row in dose_result.diagnostics.support().items():
    if name == "current practice":
        continue
    print(
        f"{name:22s} {row.moved_fraction:6.1%} {row.capped_fraction:14.1%} "
        f"{row.mean_ratio:12.2f} {row.max_ratio:11.1f} {row.effective_sample_size:12,.0f}"
    )
checks that need attention: none

plan                    moved  kept own dose  mean weight  max weight  effective n
more navigator time     98.4%           1.6%         1.00         6.8        2,318
more pharmacist time    98.4%           1.6%         1.00         8.7        2,280
both                   100.0%           3.2%         1.01        14.3        1,780

Nothing needs attention. Under “both”, every patient had at least one dose raised; the patients who kept a dose were those whose raise would pass its limit. The weights average 1 when the classifier is right, and they do, so a mean far from 1 would warn of a poor classifier. cleverly reports the effective sample size without a pass mark. The joint raise is worth about 60% of the rows (1,780 of 3,000), which helps explain its wider interval. If yours falls much lower, a few patients carry the answer: try smaller raises or tighter limits.

Why the two raises can’t be added up#

A tempting shortcut estimates each raise alone and adds the two effects. result.contrast gives the estimate and interval of both raises minus the two single raises.

added_up = dose_result[HOURS].psi + dose_result[MINUTES].psi
true_added_up = dose_truth[HOURS] + dose_truth[MINUTES]  # simulated data only
print(f"two separate raises, added up: {added_up:+.4f}   true {true_added_up:+.4f}")
print(f"both raises together:          {dose_result[BOTH].psi:+.4f}   true {dose_truth[BOTH]:+.4f}")
extra = dose_result.contrast(lambda p: p[0] - p[1] - p[2], [BOTH, HOURS, MINUTES])
low, high = extra.ci
print(f"together minus added up:       {extra.psi:+.4f}   95% CI ({low:+.4f}, {high:+.4f})")
print(f"validation status of that difference: {extra.support.label}")
two separate raises, added up: +0.0573   true +0.0556
both raises together:          +0.0747   true +0.0731
together minus added up:       +0.0175   95% CI (+0.0135, +0.0214)
validation status of that difference: experimental

Together the raises add about 0.0175 more than the two single raises added up (interval 0.0135 to 0.0214). In these simulated data the two services help each other: more navigator time helps more when the patient also gets more pharmacist time. Adding up single raises misses this, and so does any analysis that changes one dose at a time. The difference reads experimental, because no validation study covers a contrast built from several estimates on this kind of fit; the three plan estimates read supported. Measuring the joint raise has a price: its weights are larger, which helps make its interval wider.

Details: how often the shortcut falls short

In the 400 repeated draws, the interval for the difference contained its true value (0.0175) on 379 draws, and its standard error was 0.97 times the spread of the estimates. The added-up estimate fell below the lower end of the interval for both raises on 394 draws, so on these data the shortcut almost always misses.

Try to break both results#

These checks change the data in a known way and refit, for the high-odds change and for both raises. They look for signs of a broken fit, but none of them can detect a missing confounder.

from cleverly.validation import refute

# placebo shuffles the treatment (the estimate should be about zero); random_common_cause adds a
# column of noise (it should barely move); subset refits on random 70% samples (their scatter
# should match what the standard error predicts).
TILT = "ate_ipsi[high doubled vs current practice]"
columns = ["test", "original", "refuted_mean", "refuted_sd", "expectation", "verdict"]
tilt_refutation = refute(tilt_result, estimand=TILT, random_state=24)
dose_refutation = refute(dose_result, estimand=BOTH, random_state=23)
for label, report in (("high doubled", tilt_refutation), ("both raises", dose_refutation)):
    print(label)
    print(report.to_frame()[columns].round(4).to_string(index=False))
    for test in report.tests:
        print(f"  {test.name}: {test.statistic_name} = {test.statistic:.2f}")
    print()
high doubled
               test  original  refuted_mean  refuted_sd         expectation     verdict
            placebo    0.0209       -0.0000      0.0010                 ~ 0 descriptive
random_common_cause    0.0209        0.0209      0.0000            ~ 0.0209 descriptive
             subset    0.0209        0.0206      0.0008 scatter ~ 0.0006292 descriptive
  placebo: t = -0.17
  random_common_cause: paired shift in standard errors = -0.01
  subset: scatter ratio rho = 1.26

both raises
               test  original  refuted_mean  refuted_sd        expectation     verdict
            placebo    0.0747       -0.0001      0.0055                ~ 0 descriptive
random_common_cause    0.0747        0.0747      0.0003          ~ 0.07471 descriptive
             subset    0.0747        0.0739      0.0033 scatter ~ 0.004064 descriptive
  placebo: t = -0.07
  random_common_cause: paired shift in standard errors = 0.00
  subset: scatter ratio rho = 0.80

None of the six checks shows a problem. The shuffled treatment gives estimates near zero (t of -0.17 and -0.07; beyond about 2 would be a warning), and the noise column moves neither estimate by more than 0.01 standard errors on average. The 70% refits spread 1.26 and 0.80 times as much as predicted, where 1 is a perfect match; a ratio from 20 refits is noisy, and only a ratio well above 1 would suggest too narrow an interval. The verdict column reads descriptive: cleverly gives a pass or fail only when a simulation study backs the check.

What if the records are wrong?#

No check on this page tests the no-unmeasured-confounding condition. These checks test recording errors instead: the tool draws a hidden variable and lets it corrupt the recorded treatment, and here it leaves the outcome alone. The code’s comments give the size of each corruption.

from cleverly.sensitivity import ConfounderStrengthGrid

# simulated_confounding draws a hidden variable for each patient. With outcome=(0.0,) it leaves the
# outcome alone and corrupts only the recorded treatment, so here it tests recording errors.
# arm_pair names the two schedules that swap. 0.1 picks the 10% of patients with the largest hidden
# values; among them high becomes low, low becomes high, and medium stays (about 7% of patients
# change). For your own data, choose sizes you find plausible for your records.
tilt_surface = tilt_result.sensitivity.simulated_confounding(
    estimand=TILT,
    arm_pair=("high", "low"),
    grid=ConfounderStrengthGrid(treatment=(0.0, 0.1), outcome=(0.0,)),
)
dose_surface = dose_result.sensitivity.simulated_confounding(
    estimand=BOTH,
    # Dose strengths are in each dose's units per unit of the hidden variable: 0.1 hours and
    # 1 minute, about a tenth of each dose's spread among similar patients.
    grid=ConfounderStrengthGrid(
        treatment={"navigator_hours": (0.0, 0.1), "pharmacist_minutes": (0.0, 1.0)},
        outcome=(0.0,),
    ),
)
for label, surface, fit, name in (
    ("high doubled", tilt_surface, tilt_result, TILT),
    ("both raises", dose_surface, dose_result, BOTH),
):
    strongest = surface.cells[-1]
    moved = strongest.displacement / fit[name].std_error
    print(f"{label}: estimate {strongest.estimate:+.4f}, moved {moved:+.1f} standard errors")
high doubled: estimate +0.0165, moved -4.6 standard errors
both raises: estimate +0.0735, moved -0.2 standard errors

Swapping high and low within a tenth of patients (about 7% of all patients change) moves the high-odds estimate by 4.6 standard errors, because the swapped records blur the difference in scores between the two schedules. The estimate stays positive (+0.0165), so the finding that the nudge helps survives a swap of this size, though its size does not. Small noise in the doses moves the estimate for both raises by 0.2 standard errors. The two corruptions differ in kind and size, so they do not rank the two answers.

cleverly’s bound on a missing confounder, which says how strong one would have to be to change the answer, is not available here: an odds change is defined by the team’s current chances, which a missing confounder would also change, and dose raises have no bound yet. So “no unmeasured confounding” rests on knowing how the team chooses.

What we can and can’t conclude#

For the program’s owner: if a nudge doubles each patient’s odds of the high schedule, the average day-30 transition score would rise by about 0.021 on the 0-to-1 scale (95% interval 0.019 to 0.023); doubling the medium and high odds, by about 0.015. Whether a given nudge doubles the odds is a separate question. Adding half an hour of navigator time and five pharmacist minutes, within the limits, would raise successful transitions by about 7.5 percentage points (6.2 to 8.7). These answers are about adults going home from a participating hospital. Plan the two raises together.

The intervals cover sampling variation only. Both answers rest on the three conditions that need judgment. The schedule answer also needs a treatment model flexible enough for how the team chooses; the dose answer needs raised doses that similar patients get, and the weights or the outcome model close to right. These are not the effects of putting everyone on the high schedule, or of doses beyond the observed range. One simulated sample cannot show how the method does in general.

Go deeper#

How we know the method works#

fit

simulation study

the study’s data

TMLE of odds changes on a three-level treatment, in sample and out of fold

Categorical incremental policies. No package fits this, so it compares with exact truths only

a simulated continuous outcome with four kinds of patient and 8,000 rows, fitted with models that estimate each kind’s chances and means directly

TMLE of raises of two doses, with a classifier for the weights

Vector modified treatment policies. It also agrees with the R package lmtp on the same samples

a simulated binary outcome with a yes-or-no treatment and one dose, at 2,000 rows

Neither study uses this page’s data. The first study’s models were exact for its data, where this page fits simple parametric models. The second study gave its classifier the true log of the weight as its only input, so it says nothing about a classifier that learns the weights, as this page’s does. The repeated-draw checks above cover that only partly, because here the outcome model has the simulated data’s form. The vector treatments section states the conditions of the dose fit.

Where to go next#

The interventions example compares fixed rules, odds changes, and dose raises for a yes-or-no treatment and a single dose. The MSM projections example fits a trend across three schedules. The point-treatment TMLE reference gives the exact conditions of both estimators, and the examples index lists every example.