The risk score dropped.
Is the patient safer?

Elena reviews an intensive care model that flags patients at high risk of pressure injury. When she asks an explanation tool what small chart change would move her flagged cardiac patient below the alert line, it suggests ordering fewer blood tests.

Follow that single admission (Bed 04) from a misleading chart shortcut to a bedside plan she can defend. Every patient, ward record and causal relationship here is synthetic, with known truth underneath so each method can be tested directly.

  1. 00 The intuition
  2. 01 The shortcut
  3. 02 Causes and effort
  4. 03 Interactive lab
  5. 04 Model agreement
  6. 05 What can she say?

Part 00 · The intuition

One mile on a flat map can hide a cliff.

CAPRE grew directly out of Diverse Counterfactual Explanations (DiCE; Mothilal, Sharma & Tan, 2020) together with microeconomic cost theory. DiCE introduced the core insight of offering decision-makers a diverse menu of counterfactual paths into a safer region, and it already supports feature ranges, actionability locks and per-feature weights.

Bringing that idea to hospital charts calls for two additions: explicit causal constraints (separating upstream causes of injury from recording counts, while letting nursing and nutrition flow through physiological mediators) and effort elasticity (shared team setup costs and rising effort for steeper shifts). To a climber at the base of Llanberis Pass, heading straight up the vertical wall (R2) or traversing into an overhang (R1) looks short on a flat map; redrawing coordinates onto an equal-effort scale highlights walkable gullies such as R3 where DiCE's portfolio diversity can shine.

Part 01 · The shortcut

What would happen to this patient if bedside care changed?

That is Elena's clinical question. A standard prediction model answers a different question: how often pressure injury followed similar hospital charts in the past.

Hospital charts blend patient biology with staff vigilance. Unstable patients receive frequent blood tests; stable patients receive few. When a search tool scans all chart inputs for the easiest way to lower the score, ordering fewer blood tests mimics stability on paper while skin and deep-tissue resilience, called tissue tolerance, stays unchanged.

Elena's stay (Bed 04) Low mobility · 44 blood draws in 48h Bedside care path: scheduled turning and nutrition Improves tissue tolerance · Lower score and lower true risk Recording shortcut: fewer routine blood draws Mimics stability on paper · Lower score, unchanged true risk
Two ways to move Bed 04's predicted risk score below the alert line. Only the upper path alters the physiological process that injures tissue.

Begin with the bedside actions she can order.

Before searching for chart changes, Elena refits her risk model on clinical factors that sit upstream of injury, leaves out recording counts, and prices realistic nursing and nutrition effort across a single 12-hour shift.

  1. Define the windowSet baseline window, injury outcome and shift horizon.
  2. Map the causesKeep upstream causes of injury; exclude recording counts.
  3. Price shift effortAccount for team setup and rising effort for larger shifts.
  4. Trace physiologyLet nursing and nutrition flow through intermediate states.
  5. Offer distinct plansSpread options across walkable bedside routes.
  6. Check data supportRequire model agreement and comparable past stays.
If no modifiable upstream cause clears the alert within realistic shift effort and historical data support, report that constraint without relaxing the causal map.
What makes a recourse suggestion credible?
  • Upstream causal path: every modified variable lies on a directed causal path to injury, excluding surveillance counts, post-onset notes and missing-value flags.
  • Actionability and bounds: chronic traits such as admission body mass index, life-support settings and acute-phase lab markers cannot be rewritten by a single shift order.
  • Mediated physiology: locking intermediate states against direct edits must be paired with structural equations so upstream nursing and nutritional care retain their indirect benefit.
  • Historical overlap and confounding: proposed combinations must appear in comparable past stays, and causes shared with unmeasured illness severity must be flagged for clinical review.

A flexible risk predictor verifies none of these four conditions on its own.

Compare six ward stays See Elena's Bed 04 alongside five neighboring admissions

Elena's cardiac patient (Bed 04) sits alongside five neighboring flagged admissions on morning rounds. Compare what four search rules propose under the same 5.0-unit full-chart shift budget before revealing the simulated causal truth.

Summary of the four counterfactual search rules
Rule What it searches Failure mode
Unpriced search Smallest standardized changes across all model inputs. Rewrites physiological states or chronic traits that no shift order can set directly.
Cost-only Lowest-effort feature changes on the full observational model without a causal diagram. Exploits inexpensive recording shortcuts such as ordering fewer blood draws.
Mediators fixed Modifiable upstream causes while holding intermediate physiology fixed at baseline. Misses indirect benefits that flow through tissue tolerance, starving solvable stays.
CAPRE Modifiable upstream causes propagated through mediator equations on an ancestor-only model. Unmeasured severity confounding or misspecified mediator equations can still bias projections.
Six synthetic ICU stays (alert threshold 31.2%, full-chart shift budget 5.0 effort units). Bold teal values are observed; dotted italic entries are proposed edits.
Stay Baseline profile Proposed change Model score Effort Simulated truth Finding

Part 02 · Causes and effort

Whether a variable causes injury is separate from how hard it is to move.

Adding effort weights without a causal diagram blocks impossible edits such as rewriting admission body mass index, yet steers optimization toward inexpensive recording counts.

In the causal diagram below, variables with a directed path to injury are causal ancestors; intermediate states such as tissue tolerance are mediators that carry upstream nursing and nutrition forward; and chart tallies such as 48-hour blood draws are non-ancestors with no causal effect on tissue. Holding mediators fixed without updating them hides indirect physiological recovery.

Directed causal path Shared unmeasured severity Recording shortcut (non-causal)
Causal lever · Low effort

Mobility & turning

Assisted repositioning and two-hour turning share one team setup cost, reducing mechanical load and supporting tissue tolerance.

Select or focus any box in the diagram to inspect its causal role and shift effort.

Does Elena need to know the entire causal graph?

No, and avoiding that assumption prevents circularity. Nobody knows every pairwise arrow among dozens of intensive care variables, and CAPRE never requires a complete graph. Clinical physics and workflow timing supply coarse exclusions and role tiers (what cannot cause tissue injury), while the cohort data estimates how strongly each care lever moves physiology and risk.

Using capre_dag_from_tiers() in R or DAGSpec.from_tiers() in Python, a team can supply as little as sink-only knowledge (stating solely that blood-draw counts lie downstream of illness, with zero internal clinical arrows assumed) or four coarse buckets (baseline traits, bedside care orders, physiological mediators, and recording counts). By Frisch-Waugh-Lovell projection, updating mediators from upstream care orders yields the exact same linear counterfactual state regardless of unknown wiring inside the mediator bucket.

Equations: tracing physiology and assigning causal credit

CAPRE uses the causal graph in two distinct steps: predicting what happens to Elena's specific patient when bedside care changes, and measuring which upstream levers carry causal influence across the cohort.

u^M = xM − g^M ( xPa(M) ) xM′ = g^M ( xPa(M)′ ) + u^M
Patient-level mediator propagation (abduct, act, predict): Here M denotes an intermediate physiological state (tissue tolerance), xM is its observed baseline value in Elena's chart, and xPa(M) collects its direct upstream parents Pa(M) on the causal graph (mobility, turning, nutrition and baseline BMI). Using a ridge or cubic-spline regression g^M fitted on training stays under an additive-error assumption, CAPRE recovers the patient's baseline residual u^M and holds it fixed while updating the candidate mediator value xM′ in topological order whenever candidate parent values xPa(M)′ change.
vx,G (S) = 𝔼U [ f^Anc ( ℳ^G ( do(XS=xS) ;U ) Anc ) ]
Value function for Causal Shapley attribution (Heskes et al., 2020): For patient chart x and causal graph G, vx,G(S) is the average predicted risk when feature subset S is set by intervention do(XS=xS) (XS names the random variables and xS their observed values in x) and downstream variables respond through the fitted structural causal model ℳ^G(·;U), with 𝔼U averaging over cohort background residuals U. Here Anc denotes the set of causal ancestors of pressure injury on G (all features with a directed causal path to injury, excluding recording counts), f^Anc is the risk model refitted on Anc alone, and the outer subscript Anc extracts the resulting ancestor vector. Each feature's Causal Shapley score averages its marginal contribution to vx,G(S) across all subsets S; non-ancestors such as blood-draw counts never alter Anc, so their attribution is identically zero.

Whenever an actionable cause shares unmeasured illness severity with the outcome, CAPRE records it in confounded_ancestors so clinicians read the projected risk drop as a structured sensitivity estimate.

Part 03 · Interactive lab

Test the four routes on an elastic surface.

In Part 00, three causal care plans separated once feature coordinates stretched by shift effort. The interactive surface below places those same three causal plans (T, D+T and N) alongside the fourth candidate from morning rounds, ordering fewer blood draws (route S), all at 1.00 ruler unit from Bed 04's current chart x.

Drag the patient marker x' to feel supple turn-team care against stiffer solo nutrition, uncheck mediator propagation to watch nutrition lose its indirect path into the lower-risk region Y', and switch between the unwarped feature-space map and the stretched equal-effort isochrone.

Four 1.00-unit ruler paths:
Paper ruler distance 1.00 map units
Bedside shift effort 1.65 / 3.20 budget
True causal risk change −22.3 pp
Bedside verdict Walkable causal route into Y'
On an unwarped feature map, routes T, D+T, N and S all sit 1.00 unit from x (budgeted here at 3.20 effort units on this normalized two-lever slice, compared with 5.00 across all eight ward variables). Drag x' or press arrow keys to compare turn-team care against stiffer solo nutrition, uncheck mediator propagation to watch nutrition lose its indirect path into Y', and stretch into the equal-effort isochrone where DiCE-style diversity spreads options across walkable causal plans while excluding non-causal route S.
Equations: shift disutility and the equal-effort warp

To price bedside work without letting recording shortcuts compete, CAPRE restricts search to modifiable causal ancestors (assigning infinite cost to non-ancestors and shift-fixed traits) and evaluates effort across active care teams:

C ( x→xS′ ) = ∑ d:S∩Id≠∅ κd + ∑ j∈S cj± ( |xj′−xj| σj ) γj
Shift disutility function: Total shift effort C(x→xS′) prices moving actionable ancestor subset S from observed chart x to candidate profile xS′ (any edit outside actionable causal ancestors carries infinite cost). Each bedside workflow domain d with feature index set Id charges a one-time team setup cost κd≥0 when S∩Id≠∅ (for example, assembling a two-nurse turn team once; standalone levers outside a shared domain add their own setup charge κj). Each modified feature j∈S adds directional slope cj+ when xj′>xj or cj− when xj′<xj, scaled by training standard deviation σj and elasticity exponent γj≥1.
zj = sign(xj′−xj) cj± ( |xj′−xj| σj ) γj κd + ‖z‖22 = C(x→xS′) ≤ B
Equal-effort coordinate warp: Within a single active workflow domain d, mapping each shift xj′−xj to rescaled coordinate zj (where sign(·) is +1 for increases, −1 for decreases and 0 for no change) makes squared Euclidean radius ‖z‖22=∑j∈Szj2 equal variable bedside effort. Under shift budget B≥κd, every feasible plan lies inside an equal-effort circle of radius B−κd, so radial distance measures effort and angular separation spreads diverse options across distinct care mixes.

Part 04 · When models disagree

Do different models agree on the proposed plan?

Political scientists Gary King and Langche Zeng showed that statistical models which fit observed records equally well can give conflicting predictions for an unusual combination of features that rarely appeared in past data. The further a counterfactual proposal strays from recorded stays, the more its predicted risk reflects each model's curve shape rather than observed patients.

On our travel-time map, historical admissions mark the surveyed ground. Moving Elena's cardiac patient (Bed 04) along a supported care plan of scheduled turning and nutrition stays inside well-recorded care patterns: logistic regression, cubic splines, boosted trees and random forests (combined in a cross-validated SuperLearner ensemble) predict nearly the same drop in risk. By contrast, when the full-chart model scores a blood-draw shortcut that cuts lab orders while illness physiology stays severe, the proposal leaves surveyed ground: fewer than four comparable stays exist in the cohort, so the four model families fan apart.

CAPRE runs two checks on every candidate plan. It counts comparable historical stays near the proposal (requiring at least 15), and it tests whether the plan still clears the alert after adding a caution margin for inter-model spread. Set the slider to 0 to judge by the blended ensemble curve alone, or raise it to require agreement near the top of the spread.

SuperLearner ensemble Logistic curve (solid) Cubic spline (dashed) Boosted trees (dotted) Random forest (dash-dot)

Four model families evaluated along two candidate paths for Bed 04. The shaded band marks one standard deviation of inter-model spread around the SuperLearner curve, and the dashed upper line adds your chosen caution multiple.
Equations: SuperLearner disagreement bound and effective sample size

Instead of trusting a single parametric or tree learner outside historical support, CAPRE fits a cross-validated SuperLearner ensemble across K = 4 functional families and requires candidate plans to pass both an inter-model agreement check and a local data-overlap check:

p^SL (x′) + λMD σMD (x′) ≤ τ∗ σMD (x′) = ∑k=1K ωk ( pk(x′) − p¯ω(x′) ) 2
Model-dependence risk bound: At candidate profile x′, pk(x′) is the predicted injury probability from learner family k∈{1,…,K} (K=4), combined using non-negative out-of-fold log-loss weights wk≥0 (∑k=1Kwk=1) into ensemble prediction p^SL(x′)=∑k=1Kwkpk(x′) against alert threshold τ∗. Blended weights ωk=12wk+12K around mean p¯ω(x′)=∑k=1Kωkpk(x′) ensure every learner family contributes to disagreement spread σMD(x′), scaled by user-selected caution λMD≥0.
ESS(x′) = ( ∑i=1n ai(x′) ) 2 ∑i=1n ai2(x′)
Local historical support (Kish effective sample size): Across n training stays indexed by i=1,…,n, each stay receives Gaussian kernel similarity weight ai(x′)=exp(−di2/2h2), where di is ridge-stabilized Mahalanobis distance to candidate x′ and h is the Gaussian bandwidth scale in Mahalanobis units. When dozens of past stays resemble x′, ESS(x′) stays well above CAPRE's 15-stay floor; in sparse corners of the chart space, weight concentrates on one or two stays and ESS(x′) drops toward 1.

Download the precomputed cohort trajectories (JSON) ↓

Part 05 · What can she say?

What can she now say?

Elena can bring her bedside team nursing and nutritional plans for Bed 04 that act on upstream causes of injury and fit within a single shift's effort. Each candidate updates tissue tolerance automatically and stays inside historical care patterns where four distinct model families agree.

In the synthetic benchmark, refitting the risk model on the six upstream causes removes blood-draw shortcuts while holding held-out test discrimination steady (area under the ROC curve 0.8974 versus 0.8976 on all eight chart inputs). Even so, an observational risk model paired with a working causal diagram does not substitute for longitudinal treatment evaluation.

When is a counterfactual a sensitivity projection instead of a directive?

In electronic health records, nursing subscales record observed mobility alongside staff orders, 48-hour summaries blur within-window timing, and acute illness severity confounds both care delivery and injury. Flagging confounded ancestors reminds clinicians to interpret returned plans as structured bedside hypotheses alongside clinical judgment and longitudinal modified treatment policy studies.

What strengthens bedside recourse most: a more complex classifier, a clearer causal map of care and effort, or time-stamped longitudinal intervention data?

CAPRE for the classroom.

Teach causal recourse and counterfactual model dependence with self-contained R and Python workshops, a 600-patient synthetic ward cohort, a separate oracle answer key, an educator study guide and draft slides. The study guide and slides include editable LaTeX sources alongside ready-to-use PDFs.

Preview the R, Python and Lean 4 package interfaces
library(capre)

demo <- capre_icu_demo_data(n = 1200, seed = 42)
# Partial knowledge works too: capre_dag_from_tiers("hapri", sinks = c("lab_count_48h", ...), ...)
sl_anc <- capre_superlearner(demo$df, demo$ancestor_columns, demo$outcome, cv_folds = 5)
scm <- capre_fit_scm(demo$dag, demo$df, outcome = demo$outcome, method = "spline")

tau <- sl_anc$oof_youden_threshold
risks <- capre_predict_superlearner(sl_anc, demo$df)$mean_risk
patient <- demo$df[which(risks > tau + 0.15)[1], ]

res <- capre_explain(
  query_row = patient, predict_fn = sl_anc, causal_predict_fn = sl_anc,
  train_df = demo$df, feature_columns = demo$feature_columns,
  outcome = demo$outcome, price_table = demo$price_table,
  dag = demo$dag, scm = scm, threshold = tau, budget = 5.0,
  mode = "causal_priced", lambda_md = 0.5, min_overlap_ess = 15
)
cat(capre_to_json(res))
Sources and technical reading
  1. Mothilal, Sharma & Tan · Explaining Machine Learning Classifiers through Diverse Counterfactual Explanations (DiCE) FAT* 2020. Direct inspiration for CAPRE: diverse counterfactual portfolios, feature-level bounds and proximity weights.
  2. Karimi, Schölkopf & Valera · Algorithmic Recourse: from Counterfactual Explanations to Interventions FAccT 2021. Why associative perturbations fail without structural causal equations.
  3. Heskes, Sijben, Bucur & Claassen · Causal Shapley Values: Exploiting Causal Knowledge to Explain Individual Predictions NeurIPS 2020. Interventional feature attribution respecting directed causal ancestry.
  4. Agniel, Kohane & Weber · Biases in electronic health record data due to processes within the healthcare system BMJ 2018. How laboratory ordering timing and frequency encode clinician concern.
  5. Coleman et al. · A New Pressure Ulcer Conceptual Framework Journal of Advanced Nursing 2014. Mechanical boundary conditions and internal tissue tolerance pathways.
  6. King & Zeng · The Dangers of Extreme Counterfactuals Political Analysis 2006. Counterfactual model dependence outside historical data support.
  7. van der Laan, Polley & Hubbard · Super Learner SAGMB 2007. Cross-validated oracle ensembling across diverse functional families.
  8. Parikh, Varjao, Xu & Tchetgen Tchetgen · Validating Causal Inference Methods (Credence) ICML 2022. Generative semi-synthetic benchmarking with known causal ground truth.
  9. Tobler · Three Presentations on Geographical Analysis and Modeling (Non-Isotropic Modeling & Time-Space Isochrones) NCGIA Technical Report 93-1 (1993), building on Map Transformations of Geographic Space (1961).
  10. Peel · Rock face in Llanberis Pass (Wikimedia Commons) Photograph by Mike Peel (www.mikepeel.net), licensed under CC BY-SA 4.0.
  11. CAPRE open-source repository Python and R packages (v0.3.0), PDF vignettes, Lean 4 formalization, manuscript and classroom workshops.