capre 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- capre/__init__.py +46 -0
- capre/credence.py +354 -0
- capre/datasets.py +251 -0
- capre/navigator.py +581 -0
- capre/py.typed +0 -0
- capre/scm.py +347 -0
- capre/solver.py +747 -0
- capre/spec.py +581 -0
- capre/superlearner.py +382 -0
- capre-0.3.0.dist-info/METADATA +80 -0
- capre-0.3.0.dist-info/RECORD +14 -0
- capre-0.3.0.dist-info/WHEEL +5 -0
- capre-0.3.0.dist-info/licenses/LICENSE +21 -0
- capre-0.3.0.dist-info/top_level.txt +1 -0
capre/__init__.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
from .spec import DAGSpec, LeverSpec, PriceTable, CounterfactualOption, RecourseResult
|
|
2
|
+
from .scm import LinearStructuralModel
|
|
3
|
+
from .solver import CapreExplainer, PriceDiceExplainer
|
|
4
|
+
from .superlearner import CapreSuperLearner, MahalanobisOverlapIndex, SuperLearnerPrediction
|
|
5
|
+
from .datasets import CapreDemoBundle, make_icu_hapri_demo
|
|
6
|
+
from .credence import CredenceTabularVAE, credence_realism_diagnostics
|
|
7
|
+
from .navigator import (
|
|
8
|
+
BRADEN_PRE_20261017_RENAME,
|
|
9
|
+
HAPRI_AJCC_FEATURES,
|
|
10
|
+
NAVIGATOR_CONCEPT_MAP,
|
|
11
|
+
build_safe_recourse_summary,
|
|
12
|
+
ensure_braden_d_items_labels,
|
|
13
|
+
expand_conceptual_dag,
|
|
14
|
+
fetch_navigator_study_dag,
|
|
15
|
+
hapri_ajcc_price_table,
|
|
16
|
+
remap_pre20261017_braden_feature,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"DAGSpec",
|
|
21
|
+
"LeverSpec",
|
|
22
|
+
"PriceTable",
|
|
23
|
+
"CounterfactualOption",
|
|
24
|
+
"RecourseResult",
|
|
25
|
+
"LinearStructuralModel",
|
|
26
|
+
"CapreExplainer",
|
|
27
|
+
"PriceDiceExplainer",
|
|
28
|
+
"CapreSuperLearner",
|
|
29
|
+
"MahalanobisOverlapIndex",
|
|
30
|
+
"SuperLearnerPrediction",
|
|
31
|
+
"CapreDemoBundle",
|
|
32
|
+
"make_icu_hapri_demo",
|
|
33
|
+
"CredenceTabularVAE",
|
|
34
|
+
"credence_realism_diagnostics",
|
|
35
|
+
"BRADEN_PRE_20261017_RENAME",
|
|
36
|
+
"HAPRI_AJCC_FEATURES",
|
|
37
|
+
"NAVIGATOR_CONCEPT_MAP",
|
|
38
|
+
"ensure_braden_d_items_labels",
|
|
39
|
+
"remap_pre20261017_braden_feature",
|
|
40
|
+
"fetch_navigator_study_dag",
|
|
41
|
+
"expand_conceptual_dag",
|
|
42
|
+
"hapri_ajcc_price_table",
|
|
43
|
+
"build_safe_recourse_summary",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
__version__ = "0.3.0"
|
capre/credence.py
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
"""Credence semi-synthetic covariate generator and realism diagnostics for CAPRE.
|
|
2
|
+
|
|
3
|
+
Adapts the Credence framework (Parikh, Varjao, Xu, & Tchetgen Tchetgen, ICML 2022)
|
|
4
|
+
to validate counterfactual recourse algorithms on realistic clinical covariates
|
|
5
|
+
with user-seeded causal structural equations and user-seeded modification costs:
|
|
6
|
+
1. Realism half (`CredenceTabularVAE`): Fits a minibatch Tabular Variational
|
|
7
|
+
Autoencoder in pure NumPy (zero GPU/PyTorch dependency) on observed clinical
|
|
8
|
+
covariates without ever seeing outcomes, restoring residual decoder dispersion
|
|
9
|
+
and respecting empirical support bounds and integer/binary types.
|
|
10
|
+
2. Realism verification (`credence_realism_diagnostics`): Evaluates generated vs.
|
|
11
|
+
held-out source covariates via Standardized Mean Differences (SMD), two-sample
|
|
12
|
+
Kolmogorov-Smirnov (KS) distances, and 5-fold cross-validated real-vs.-synthetic
|
|
13
|
+
discriminator AUROC.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import math
|
|
19
|
+
from typing import Dict, List, Optional, Sequence
|
|
20
|
+
import numpy as np
|
|
21
|
+
import pandas as pd
|
|
22
|
+
from sklearn.linear_model import LogisticRegression
|
|
23
|
+
from sklearn.metrics import roc_auc_score
|
|
24
|
+
from sklearn.model_selection import StratifiedKFold
|
|
25
|
+
from sklearn.preprocessing import StandardScaler
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _relu(x: np.ndarray) -> np.ndarray:
|
|
29
|
+
return np.maximum(0.0, x)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _sigmoid(x: np.ndarray) -> np.ndarray:
|
|
33
|
+
z = np.clip(x, -500.0, 500.0)
|
|
34
|
+
return 1.0 / (1.0 + np.exp(-z))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class CredenceTabularVAE:
|
|
38
|
+
"""Minibatch Tabular Variational Autoencoder for mixed clinical covariates."""
|
|
39
|
+
|
|
40
|
+
def __init__(
|
|
41
|
+
self,
|
|
42
|
+
latent_dim: int = 10,
|
|
43
|
+
hidden_dim: int = 64,
|
|
44
|
+
beta: float = 0.45,
|
|
45
|
+
lr: float = 2e-3,
|
|
46
|
+
epochs: int = 75,
|
|
47
|
+
batch_size: int = 256,
|
|
48
|
+
seed: int = 20261128,
|
|
49
|
+
) -> None:
|
|
50
|
+
if int(batch_size) < 1 or int(latent_dim) < 1 or int(hidden_dim) < 1 or int(epochs) < 1:
|
|
51
|
+
raise ValueError("latent_dim, hidden_dim, epochs, and batch_size must be positive integers.")
|
|
52
|
+
self.latent_dim = int(latent_dim)
|
|
53
|
+
self.hidden_dim = int(hidden_dim)
|
|
54
|
+
self.beta = float(beta)
|
|
55
|
+
self.lr = float(lr)
|
|
56
|
+
self.epochs = int(epochs)
|
|
57
|
+
self.batch_size = int(batch_size)
|
|
58
|
+
self.seed = int(seed)
|
|
59
|
+
|
|
60
|
+
self.columns_: List[str] = []
|
|
61
|
+
self.binary_cols_: List[str] = []
|
|
62
|
+
self.cont_cols_: List[str] = []
|
|
63
|
+
self.integer_cols_: set[str] = set()
|
|
64
|
+
self.cont_bounds_: Dict[str, tuple[float, float]] = {}
|
|
65
|
+
self.cont_mean_: Optional[np.ndarray] = None
|
|
66
|
+
self.cont_sd_: Optional[np.ndarray] = None
|
|
67
|
+
self.cont_resid_sd_: Optional[np.ndarray] = None
|
|
68
|
+
self.params_: Dict[str, np.ndarray] = {}
|
|
69
|
+
self.history_: List[Dict[str, float]] = []
|
|
70
|
+
|
|
71
|
+
def fit(
|
|
72
|
+
self,
|
|
73
|
+
df: pd.DataFrame,
|
|
74
|
+
binary_cols: Optional[Sequence[str]] = None,
|
|
75
|
+
integer_cols: Optional[Sequence[str]] = None,
|
|
76
|
+
) -> "CredenceTabularVAE":
|
|
77
|
+
if not isinstance(df, pd.DataFrame) or len(df) < 2 or len(df.columns) == 0:
|
|
78
|
+
raise ValueError("CredenceTabularVAE.fit requires a DataFrame with >= 2 rows and >= 1 column.")
|
|
79
|
+
rng = np.random.default_rng(self.seed)
|
|
80
|
+
clean = df.copy()
|
|
81
|
+
self.columns_ = list(clean.columns)
|
|
82
|
+
for c in self.columns_:
|
|
83
|
+
vals = clean[c].to_numpy(dtype=float)
|
|
84
|
+
if np.any(np.isinf(vals)):
|
|
85
|
+
raise ValueError(f"Column {c!r} contains infinite values in CredenceTabularVAE.fit.")
|
|
86
|
+
med = float(np.nanmedian(vals)) if not np.all(np.isnan(vals)) else 0.0
|
|
87
|
+
clean[c] = clean[c].fillna(med)
|
|
88
|
+
|
|
89
|
+
if binary_cols is None:
|
|
90
|
+
detected_bin = []
|
|
91
|
+
for c in self.columns_:
|
|
92
|
+
u = np.unique(clean[c].to_numpy(dtype=float))
|
|
93
|
+
if len(u) <= 2 and set(u).issubset({0.0, 1.0}):
|
|
94
|
+
detected_bin.append(c)
|
|
95
|
+
self.binary_cols_ = detected_bin
|
|
96
|
+
else:
|
|
97
|
+
self.binary_cols_ = [c for c in binary_cols if c in clean.columns]
|
|
98
|
+
|
|
99
|
+
self.cont_cols_ = [c for c in self.columns_ if c not in set(self.binary_cols_)]
|
|
100
|
+
if integer_cols is None:
|
|
101
|
+
self.integer_cols_ = {
|
|
102
|
+
c for c in self.cont_cols_
|
|
103
|
+
if np.all(np.isclose(clean[c].to_numpy(dtype=float), np.round(clean[c].to_numpy(dtype=float))))
|
|
104
|
+
}
|
|
105
|
+
else:
|
|
106
|
+
self.integer_cols_ = set(integer_cols)
|
|
107
|
+
|
|
108
|
+
X_bin = (
|
|
109
|
+
clean[self.binary_cols_].to_numpy(dtype=float)
|
|
110
|
+
if self.binary_cols_
|
|
111
|
+
else np.zeros((len(clean), 0), dtype=float)
|
|
112
|
+
)
|
|
113
|
+
X_cont_raw = (
|
|
114
|
+
clean[self.cont_cols_].to_numpy(dtype=float)
|
|
115
|
+
if self.cont_cols_
|
|
116
|
+
else np.zeros((len(clean), 0), dtype=float)
|
|
117
|
+
)
|
|
118
|
+
for idx, c in enumerate(self.cont_cols_):
|
|
119
|
+
col_v = X_cont_raw[:, idx]
|
|
120
|
+
self.cont_bounds_[c] = (float(np.min(col_v)), float(np.max(col_v)))
|
|
121
|
+
|
|
122
|
+
if X_cont_raw.shape[1] > 0:
|
|
123
|
+
self.cont_mean_ = X_cont_raw.mean(axis=0)
|
|
124
|
+
sd = X_cont_raw.std(axis=0, ddof=0)
|
|
125
|
+
self.cont_sd_ = np.where(sd > 1e-9, sd, 1.0)
|
|
126
|
+
Z_cont = (X_cont_raw - self.cont_mean_) / self.cont_sd_
|
|
127
|
+
else:
|
|
128
|
+
self.cont_mean_ = np.zeros(0, dtype=float)
|
|
129
|
+
self.cont_sd_ = np.ones(0, dtype=float)
|
|
130
|
+
Z_cont = X_cont_raw
|
|
131
|
+
|
|
132
|
+
XZ = np.hstack([X_bin, Z_cont])
|
|
133
|
+
n_rows, in_dim = XZ.shape
|
|
134
|
+
b_dim = X_bin.shape[1]
|
|
135
|
+
c_dim = Z_cont.shape[1]
|
|
136
|
+
h_dim = self.hidden_dim
|
|
137
|
+
l_dim = self.latent_dim
|
|
138
|
+
|
|
139
|
+
def he_init(fan_in: int, fan_out: int) -> np.ndarray:
|
|
140
|
+
return rng.normal(0.0, np.sqrt(2.0 / max(1, fan_in)), size=(fan_in, fan_out))
|
|
141
|
+
|
|
142
|
+
params: Dict[str, np.ndarray] = {
|
|
143
|
+
"W_e1": he_init(in_dim, h_dim),
|
|
144
|
+
"b_e1": np.zeros(h_dim),
|
|
145
|
+
"W_mu": he_init(h_dim, l_dim) * 0.5,
|
|
146
|
+
"b_mu": np.zeros(l_dim),
|
|
147
|
+
"W_lv": he_init(h_dim, l_dim) * 0.2,
|
|
148
|
+
"b_lv": np.zeros(l_dim),
|
|
149
|
+
"W_d1": he_init(l_dim, h_dim),
|
|
150
|
+
"b_d1": np.zeros(h_dim),
|
|
151
|
+
"W_out": he_init(h_dim, in_dim) * 0.5,
|
|
152
|
+
"b_out": np.zeros(in_dim),
|
|
153
|
+
}
|
|
154
|
+
m_adam = {k: np.zeros_like(v) for k, v in params.items()}
|
|
155
|
+
v_adam = {k: np.zeros_like(v) for k, v in params.items()}
|
|
156
|
+
step_t = 0
|
|
157
|
+
self.history_ = []
|
|
158
|
+
|
|
159
|
+
for ep in range(self.epochs):
|
|
160
|
+
perm = rng.permutation(n_rows)
|
|
161
|
+
ep_recon, ep_kl, n_seen = 0.0, 0.0, 0
|
|
162
|
+
|
|
163
|
+
for start in range(0, n_rows, self.batch_size):
|
|
164
|
+
batch = XZ[perm[start : start + self.batch_size]]
|
|
165
|
+
bs = len(batch)
|
|
166
|
+
if bs == 0:
|
|
167
|
+
continue
|
|
168
|
+
step_t += 1
|
|
169
|
+
|
|
170
|
+
# Forward pass
|
|
171
|
+
pre_e1 = batch @ params["W_e1"] + params["b_e1"]
|
|
172
|
+
h_e = _relu(pre_e1)
|
|
173
|
+
mu = h_e @ params["W_mu"] + params["b_mu"]
|
|
174
|
+
logvar = np.clip(h_e @ params["W_lv"] + params["b_lv"], -8.0, 6.0)
|
|
175
|
+
std = np.exp(0.5 * logvar)
|
|
176
|
+
eps = rng.normal(0.0, 1.0, size=mu.shape)
|
|
177
|
+
u = mu + std * eps
|
|
178
|
+
|
|
179
|
+
pre_d1 = u @ params["W_d1"] + params["b_d1"]
|
|
180
|
+
h_d = _relu(pre_d1)
|
|
181
|
+
out = h_d @ params["W_out"] + params["b_out"]
|
|
182
|
+
|
|
183
|
+
# Losses and output gradients (averaged over batch)
|
|
184
|
+
g_out = np.zeros_like(out)
|
|
185
|
+
recon_loss = 0.0
|
|
186
|
+
if b_dim > 0:
|
|
187
|
+
logits_b = out[:, :b_dim]
|
|
188
|
+
target_b = batch[:, :b_dim]
|
|
189
|
+
probs_b = _sigmoid(logits_b)
|
|
190
|
+
bce = np.maximum(logits_b, 0.0) - logits_b * target_b + np.log1p(np.exp(-np.abs(logits_b)))
|
|
191
|
+
recon_loss += float(np.sum(bce)) / bs
|
|
192
|
+
g_out[:, :b_dim] = (probs_b - target_b) / bs
|
|
193
|
+
if c_dim > 0:
|
|
194
|
+
pred_c = out[:, b_dim:]
|
|
195
|
+
target_c = batch[:, b_dim:]
|
|
196
|
+
diff_c = pred_c - target_c
|
|
197
|
+
recon_loss += float(np.sum(diff_c ** 2)) / bs
|
|
198
|
+
g_out[:, b_dim:] = (2.0 * diff_c) / bs
|
|
199
|
+
|
|
200
|
+
kl_loss = float(-0.5 * np.sum(1.0 + logvar - mu ** 2 - np.exp(logvar))) / bs
|
|
201
|
+
ep_recon += recon_loss * bs
|
|
202
|
+
ep_kl += kl_loss * bs
|
|
203
|
+
n_seen += bs
|
|
204
|
+
|
|
205
|
+
# Backward pass
|
|
206
|
+
grads: Dict[str, np.ndarray] = {}
|
|
207
|
+
grads["W_out"] = h_d.T @ g_out
|
|
208
|
+
grads["b_out"] = np.sum(g_out, axis=0)
|
|
209
|
+
|
|
210
|
+
g_hd = g_out @ params["W_out"].T
|
|
211
|
+
g_pre_d1 = g_hd * (pre_d1 > 0.0)
|
|
212
|
+
grads["W_d1"] = u.T @ g_pre_d1
|
|
213
|
+
grads["b_d1"] = np.sum(g_pre_d1, axis=0)
|
|
214
|
+
|
|
215
|
+
g_u = g_pre_d1 @ params["W_d1"].T
|
|
216
|
+
g_mu = g_u + (self.beta * mu) / bs
|
|
217
|
+
g_lv = g_u * (0.5 * std * eps) + (0.5 * self.beta * (np.exp(logvar) - 1.0)) / bs
|
|
218
|
+
|
|
219
|
+
grads["W_mu"] = h_e.T @ g_mu
|
|
220
|
+
grads["b_mu"] = np.sum(g_mu, axis=0)
|
|
221
|
+
grads["W_lv"] = h_e.T @ g_lv
|
|
222
|
+
grads["b_lv"] = np.sum(g_lv, axis=0)
|
|
223
|
+
|
|
224
|
+
g_he = g_mu @ params["W_mu"].T + g_lv @ params["W_lv"].T
|
|
225
|
+
g_pre_e1 = g_he * (pre_e1 > 0.0)
|
|
226
|
+
grads["W_e1"] = batch.T @ g_pre_e1
|
|
227
|
+
grads["b_e1"] = np.sum(g_pre_e1, axis=0)
|
|
228
|
+
|
|
229
|
+
# Minibatch Adam step
|
|
230
|
+
b1, b2, eps_a = 0.9, 0.999, 1e-8
|
|
231
|
+
bc1 = 1.0 - b1 ** step_t
|
|
232
|
+
bc2 = 1.0 - b2 ** step_t
|
|
233
|
+
for k in params:
|
|
234
|
+
g_clip = np.clip(grads[k], -5.0, 5.0)
|
|
235
|
+
m_adam[k] = b1 * m_adam[k] + (1.0 - b1) * g_clip
|
|
236
|
+
v_adam[k] = b2 * v_adam[k] + (1.0 - b2) * (g_clip ** 2)
|
|
237
|
+
m_hat = m_adam[k] / bc1
|
|
238
|
+
v_hat = v_adam[k] / bc2
|
|
239
|
+
params[k] -= self.lr * m_hat / (np.sqrt(v_hat) + eps_a)
|
|
240
|
+
|
|
241
|
+
self.history_.append({
|
|
242
|
+
"epoch": ep + 1,
|
|
243
|
+
"recon_loss": round(ep_recon / max(1, n_seen), 4),
|
|
244
|
+
"kl_loss": round(ep_kl / max(1, n_seen), 4),
|
|
245
|
+
})
|
|
246
|
+
|
|
247
|
+
# Estimate continuous observation residual dispersion from posterior means (Credence fidelity step)
|
|
248
|
+
h_e_all = _relu(XZ @ params["W_e1"] + params["b_e1"])
|
|
249
|
+
mu_all = h_e_all @ params["W_mu"] + params["b_mu"]
|
|
250
|
+
out_all = _relu(mu_all @ params["W_d1"] + params["b_d1"]) @ params["W_out"] + params["b_out"]
|
|
251
|
+
if c_dim > 0:
|
|
252
|
+
resid = Z_cont - out_all[:, b_dim:]
|
|
253
|
+
self.cont_resid_sd_ = np.std(resid, axis=0, ddof=0)
|
|
254
|
+
else:
|
|
255
|
+
self.cont_resid_sd_ = np.zeros(0, dtype=float)
|
|
256
|
+
|
|
257
|
+
self.params_ = params
|
|
258
|
+
return self
|
|
259
|
+
|
|
260
|
+
def sample(self, n: int, seed: Optional[int] = None) -> pd.DataFrame:
|
|
261
|
+
if not self.params_:
|
|
262
|
+
raise RuntimeError("Call `fit()` before `sample()` on CredenceTabularVAE.")
|
|
263
|
+
if int(n) < 1:
|
|
264
|
+
raise ValueError("n must be >= 1 in CredenceTabularVAE.sample.")
|
|
265
|
+
rng = np.random.default_rng(self.seed + 99 if seed is None else int(seed))
|
|
266
|
+
u = rng.normal(0.0, 1.0, size=(int(n), self.latent_dim))
|
|
267
|
+
h_d = _relu(u @ self.params_["W_d1"] + self.params_["b_d1"])
|
|
268
|
+
out = h_d @ self.params_["W_out"] + self.params_["b_out"]
|
|
269
|
+
|
|
270
|
+
b_dim = len(self.binary_cols_)
|
|
271
|
+
c_dim = len(self.cont_cols_)
|
|
272
|
+
cols_out: Dict[str, np.ndarray] = {}
|
|
273
|
+
|
|
274
|
+
if b_dim > 0:
|
|
275
|
+
probs = _sigmoid(out[:, :b_dim])
|
|
276
|
+
draws_b = rng.binomial(1, probs).astype(float)
|
|
277
|
+
for idx, col in enumerate(self.binary_cols_):
|
|
278
|
+
cols_out[col] = draws_b[:, idx]
|
|
279
|
+
|
|
280
|
+
if c_dim > 0 and self.cont_mean_ is not None and self.cont_sd_ is not None and self.cont_resid_sd_ is not None:
|
|
281
|
+
z_dec = out[:, b_dim:] + rng.normal(0.0, 1.0, size=(int(n), c_dim)) * self.cont_resid_sd_
|
|
282
|
+
x_raw = z_dec * self.cont_sd_ + self.cont_mean_
|
|
283
|
+
for idx, col in enumerate(self.cont_cols_):
|
|
284
|
+
lo, hi = self.cont_bounds_[col]
|
|
285
|
+
vals = np.clip(x_raw[:, idx], lo, hi)
|
|
286
|
+
if col in self.integer_cols_:
|
|
287
|
+
vals = np.round(vals)
|
|
288
|
+
cols_out[col] = vals
|
|
289
|
+
|
|
290
|
+
return pd.DataFrame({c: cols_out[c] for c in self.columns_})
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _ks_two_sample(a: np.ndarray, b: np.ndarray) -> float:
|
|
294
|
+
a_s = np.sort(a)
|
|
295
|
+
b_s = np.sort(b)
|
|
296
|
+
grid = np.unique(np.concatenate([a_s, b_s]))
|
|
297
|
+
cdf_a = np.searchsorted(a_s, grid, side="right") / max(1, len(a_s))
|
|
298
|
+
cdf_b = np.searchsorted(b_s, grid, side="right") / max(1, len(b_s))
|
|
299
|
+
return float(np.max(np.abs(cdf_a - cdf_b)))
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def credence_realism_diagnostics(
|
|
303
|
+
real_df: pd.DataFrame, synth_df: pd.DataFrame, seed: int = 20261128
|
|
304
|
+
) -> Dict[str, object]:
|
|
305
|
+
"""Compare held-out real covariates against Credence-generated covariates (SMD, KS, Discriminator AUC)."""
|
|
306
|
+
cols = [c for c in real_df.columns if c in synth_df.columns]
|
|
307
|
+
if not cols:
|
|
308
|
+
raise ValueError("real_df and synth_df share no common columns.")
|
|
309
|
+
if len(real_df) < 2 or len(synth_df) < 2:
|
|
310
|
+
raise ValueError("real_df and synth_df must each contain at least 2 rows.")
|
|
311
|
+
smds: Dict[str, float] = {}
|
|
312
|
+
ks_map: Dict[str, float] = {}
|
|
313
|
+
|
|
314
|
+
r_clean = real_df[cols].copy()
|
|
315
|
+
s_clean = synth_df[cols].copy()
|
|
316
|
+
for c in cols:
|
|
317
|
+
r_raw = r_clean[c].to_numpy(dtype=float)
|
|
318
|
+
s_raw = s_clean[c].to_numpy(dtype=float)
|
|
319
|
+
if np.any(np.isinf(r_raw)) or np.any(np.isinf(s_raw)):
|
|
320
|
+
raise ValueError(f"Column {c!r} contains infinite values in credence_realism_diagnostics.")
|
|
321
|
+
med = float(np.nanmedian(r_raw)) if not np.all(np.isnan(r_raw)) else 0.0
|
|
322
|
+
r_v = r_clean[c].fillna(med).to_numpy(dtype=float)
|
|
323
|
+
s_v = s_clean[c].fillna(med).to_numpy(dtype=float)
|
|
324
|
+
r_clean[c] = r_v
|
|
325
|
+
s_clean[c] = s_v
|
|
326
|
+
pooled_sd = math.sqrt(0.5 * (float(np.var(r_v, ddof=1)) + float(np.var(s_v, ddof=1))))
|
|
327
|
+
smds[c] = round(abs(float(np.mean(r_v)) - float(np.mean(s_v))) / max(1e-9, pooled_sd), 4)
|
|
328
|
+
ks_map[c] = round(_ks_two_sample(r_v, s_v), 4)
|
|
329
|
+
|
|
330
|
+
X_disc = np.vstack([r_clean.to_numpy(dtype=float), s_clean.to_numpy(dtype=float)])
|
|
331
|
+
y_disc = np.concatenate([np.zeros(len(r_clean), dtype=int), np.ones(len(s_clean), dtype=int)])
|
|
332
|
+
|
|
333
|
+
n_splits = min(5, len(r_clean), len(s_clean))
|
|
334
|
+
skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=seed)
|
|
335
|
+
aucs: List[float] = []
|
|
336
|
+
for tr_idx, te_idx in skf.split(X_disc, y_disc):
|
|
337
|
+
scaler = StandardScaler().fit(X_disc[tr_idx])
|
|
338
|
+
clf = LogisticRegression(max_iter=500).fit(scaler.transform(X_disc[tr_idx]), y_disc[tr_idx])
|
|
339
|
+
probs = clf.predict_proba(scaler.transform(X_disc[te_idx]))[:, 1]
|
|
340
|
+
aucs.append(float(roc_auc_score(y_disc[te_idx], probs)))
|
|
341
|
+
|
|
342
|
+
smd_vals = list(smds.values())
|
|
343
|
+
ks_vals = list(ks_map.values())
|
|
344
|
+
return {
|
|
345
|
+
"n_real_holdout": int(len(r_clean)),
|
|
346
|
+
"n_synthetic": int(len(s_clean)),
|
|
347
|
+
"median_smd": round(float(np.median(smd_vals)), 4),
|
|
348
|
+
"max_smd": round(float(np.max(smd_vals)), 4),
|
|
349
|
+
"median_ks": round(float(np.median(ks_vals)), 4),
|
|
350
|
+
"max_ks": round(float(np.max(ks_vals)), 4),
|
|
351
|
+
"discriminator_5fold_auc": round(float(np.mean(aucs)), 4),
|
|
352
|
+
"per_feature_smd": smds,
|
|
353
|
+
"per_feature_ks": ks_map,
|
|
354
|
+
}
|
capre/datasets.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"""Built-in synthetic clinical benchmark datasets for CAPRE examples and vignettes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
import math
|
|
7
|
+
from typing import Tuple
|
|
8
|
+
import numpy as np
|
|
9
|
+
import pandas as pd
|
|
10
|
+
|
|
11
|
+
from .spec import DAGSpec, LeverSpec, PriceTable
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class CapreDemoBundle:
|
|
16
|
+
"""Self-contained two-pathway ICU pressure-injury demo cohort, DAG, and PriceTable."""
|
|
17
|
+
|
|
18
|
+
df: pd.DataFrame
|
|
19
|
+
dag: DAGSpec
|
|
20
|
+
price_table: PriceTable
|
|
21
|
+
feature_columns: Tuple[str, ...]
|
|
22
|
+
ancestor_columns: Tuple[str, ...]
|
|
23
|
+
outcome: str = "hapri"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def make_icu_hapri_demo(
|
|
27
|
+
n: int = 1200,
|
|
28
|
+
gamma_u: float = 1.0,
|
|
29
|
+
seed: int = 42,
|
|
30
|
+
) -> CapreDemoBundle:
|
|
31
|
+
"""Generate a realistic two-pathway ICU pressure-injury demo dataset.
|
|
32
|
+
|
|
33
|
+
Includes:
|
|
34
|
+
- Three modifiable upstream nursing/nutritional ancestors (`braden_mobility`,
|
|
35
|
+
`turning_q2h_pct`, `enteral_nutrition_pct`), with shared turn-team setup cost
|
|
36
|
+
on `mobility`.
|
|
37
|
+
- One high-cost chronic baseline ancestor (`bmi`).
|
|
38
|
+
- Two locked physiological states (`serum_albumin`, `tissue_tolerance`).
|
|
39
|
+
- Two cheap diagnostic surveillance proxies (`lab_count_48h`, `lactate_draws_48h`)
|
|
40
|
+
driven by latent severity `U_severity` with zero causal path to `hapri`.
|
|
41
|
+
"""
|
|
42
|
+
if not isinstance(n, (int, np.integer)) or isinstance(n, bool) or int(n) < 1:
|
|
43
|
+
raise ValueError("n must be a positive integer >= 1.")
|
|
44
|
+
if not math.isfinite(float(gamma_u)):
|
|
45
|
+
raise ValueError("gamma_u must be a finite severity coefficient.")
|
|
46
|
+
n = int(n)
|
|
47
|
+
gamma_u = float(gamma_u)
|
|
48
|
+
rng = np.random.default_rng(seed)
|
|
49
|
+
u_sev = rng.normal(0.0, 1.0, size=n)
|
|
50
|
+
|
|
51
|
+
bmi = np.clip(28.5 + 5.2 * rng.normal(size=n), 16.5, 52.0)
|
|
52
|
+
braden_mobility = np.clip(
|
|
53
|
+
np.round(2.7 - 0.55 * gamma_u * u_sev + rng.normal(0.0, 0.65, size=n)),
|
|
54
|
+
1.0,
|
|
55
|
+
4.0,
|
|
56
|
+
)
|
|
57
|
+
turning_q2h_pct = np.clip(
|
|
58
|
+
68.0 - 11.0 * gamma_u * u_sev + 6.5 * (braden_mobility - 2.5) + rng.normal(0.0, 11.0, size=n),
|
|
59
|
+
10.0,
|
|
60
|
+
100.0,
|
|
61
|
+
)
|
|
62
|
+
enteral_nutrition_pct = np.clip(
|
|
63
|
+
64.0 - 12.0 * gamma_u * u_sev + rng.normal(0.0, 15.0, size=n),
|
|
64
|
+
0.0,
|
|
65
|
+
100.0,
|
|
66
|
+
)
|
|
67
|
+
serum_albumin = np.clip(
|
|
68
|
+
3.25 - 0.42 * u_sev + 0.0012 * (enteral_nutrition_pct - 60.0) + rng.normal(0.0, 0.28, size=n),
|
|
69
|
+
1.4,
|
|
70
|
+
4.6,
|
|
71
|
+
)
|
|
72
|
+
tissue_tolerance = (
|
|
73
|
+
0.62 * (braden_mobility - 2.5)
|
|
74
|
+
+ 0.024 * (turning_q2h_pct - 65.0)
|
|
75
|
+
+ 0.011 * (enteral_nutrition_pct - 60.0)
|
|
76
|
+
- 0.022 * np.maximum(0.0, bmi - 30.0)
|
|
77
|
+
+ 0.35 * (serum_albumin - 3.2)
|
|
78
|
+
- 0.45 * u_sev
|
|
79
|
+
+ rng.normal(0.0, 0.45, size=n)
|
|
80
|
+
)
|
|
81
|
+
lab_count_48h = np.clip(
|
|
82
|
+
np.round(26.0 + 11.5 * np.exp(0.45 * u_sev) + rng.normal(0.0, 4.0, size=n)),
|
|
83
|
+
4.0,
|
|
84
|
+
140.0,
|
|
85
|
+
)
|
|
86
|
+
lactate_draws_48h = np.clip(
|
|
87
|
+
np.round(2.2 + 2.4 * np.exp(0.50 * u_sev) + rng.normal(0.0, 1.0, size=n)),
|
|
88
|
+
0.0,
|
|
89
|
+
24.0,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
logit_y = -1.35 - 1.30 * tissue_tolerance - 0.38 * (braden_mobility - 2.5) + 0.55 * u_sev
|
|
93
|
+
prob_y = 1.0 / (1.0 + np.exp(-logit_y))
|
|
94
|
+
hapri = rng.binomial(1, prob_y, size=n).astype(int)
|
|
95
|
+
|
|
96
|
+
df = pd.DataFrame(
|
|
97
|
+
{
|
|
98
|
+
"bmi": bmi,
|
|
99
|
+
"braden_mobility": braden_mobility,
|
|
100
|
+
"turning_q2h_pct": turning_q2h_pct,
|
|
101
|
+
"enteral_nutrition_pct": enteral_nutrition_pct,
|
|
102
|
+
"serum_albumin": serum_albumin,
|
|
103
|
+
"tissue_tolerance": tissue_tolerance,
|
|
104
|
+
"lab_count_48h": lab_count_48h,
|
|
105
|
+
"lactate_draws_48h": lactate_draws_48h,
|
|
106
|
+
"hapri": hapri,
|
|
107
|
+
}
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
dag = DAGSpec.from_dagitty(
|
|
111
|
+
"""
|
|
112
|
+
dag {
|
|
113
|
+
U_severity [latent]
|
|
114
|
+
U_severity -> braden_mobility
|
|
115
|
+
U_severity -> turning_q2h_pct
|
|
116
|
+
U_severity -> enteral_nutrition_pct
|
|
117
|
+
U_severity -> serum_albumin
|
|
118
|
+
U_severity -> tissue_tolerance
|
|
119
|
+
U_severity -> lab_count_48h
|
|
120
|
+
U_severity -> lactate_draws_48h
|
|
121
|
+
U_severity -> hapri
|
|
122
|
+
bmi -> tissue_tolerance
|
|
123
|
+
bmi -> hapri
|
|
124
|
+
braden_mobility -> turning_q2h_pct
|
|
125
|
+
braden_mobility -> tissue_tolerance
|
|
126
|
+
braden_mobility -> hapri
|
|
127
|
+
turning_q2h_pct -> tissue_tolerance
|
|
128
|
+
enteral_nutrition_pct -> serum_albumin
|
|
129
|
+
enteral_nutrition_pct -> tissue_tolerance
|
|
130
|
+
serum_albumin -> tissue_tolerance
|
|
131
|
+
tissue_tolerance -> hapri
|
|
132
|
+
}
|
|
133
|
+
"""
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
price_table = PriceTable.from_list(
|
|
137
|
+
[
|
|
138
|
+
LeverSpec(
|
|
139
|
+
"braden_mobility",
|
|
140
|
+
modifiable=True,
|
|
141
|
+
setup_cost=0.45,
|
|
142
|
+
cost_up=1.05,
|
|
143
|
+
cost_down=math.inf,
|
|
144
|
+
convexity=1.15,
|
|
145
|
+
bounds=(1.0, 4.0),
|
|
146
|
+
step=1.0,
|
|
147
|
+
domain="mobility",
|
|
148
|
+
rationale="Assisted bedside mobilization progression",
|
|
149
|
+
),
|
|
150
|
+
LeverSpec(
|
|
151
|
+
"turning_q2h_pct",
|
|
152
|
+
modifiable=True,
|
|
153
|
+
setup_cost=0.45,
|
|
154
|
+
cost_up=0.85,
|
|
155
|
+
cost_down=math.inf,
|
|
156
|
+
convexity=1.15,
|
|
157
|
+
bounds=(20.0, 100.0),
|
|
158
|
+
step=10.0,
|
|
159
|
+
domain="mobility",
|
|
160
|
+
rationale="Scheduled q2h repositioning compliance",
|
|
161
|
+
),
|
|
162
|
+
LeverSpec(
|
|
163
|
+
"enteral_nutrition_pct",
|
|
164
|
+
modifiable=True,
|
|
165
|
+
setup_cost=0.35,
|
|
166
|
+
cost_up=0.95,
|
|
167
|
+
cost_down=math.inf,
|
|
168
|
+
convexity=1.20,
|
|
169
|
+
bounds=(20.0, 100.0),
|
|
170
|
+
step=15.0,
|
|
171
|
+
domain="nutrition",
|
|
172
|
+
rationale="Dietitian-guided enteral caloric delivery",
|
|
173
|
+
),
|
|
174
|
+
LeverSpec(
|
|
175
|
+
"bmi",
|
|
176
|
+
modifiable=True,
|
|
177
|
+
setup_cost=8.0,
|
|
178
|
+
cost_up=14.0,
|
|
179
|
+
cost_down=14.0,
|
|
180
|
+
bounds=(16.5, 52.0),
|
|
181
|
+
domain="chronic",
|
|
182
|
+
rationale="Chronic body habitus cannot shift within an ICU shift",
|
|
183
|
+
),
|
|
184
|
+
LeverSpec(
|
|
185
|
+
"serum_albumin",
|
|
186
|
+
modifiable=False,
|
|
187
|
+
cost_up=math.inf,
|
|
188
|
+
cost_down=math.inf,
|
|
189
|
+
domain="acute_phase",
|
|
190
|
+
rationale="Negative acute-phase reactant",
|
|
191
|
+
),
|
|
192
|
+
LeverSpec(
|
|
193
|
+
"tissue_tolerance",
|
|
194
|
+
modifiable=False,
|
|
195
|
+
cost_up=math.inf,
|
|
196
|
+
cost_down=math.inf,
|
|
197
|
+
domain="endogenous_mediator",
|
|
198
|
+
rationale="Endogenous microvascular tissue tolerance",
|
|
199
|
+
),
|
|
200
|
+
LeverSpec(
|
|
201
|
+
"lab_count_48h",
|
|
202
|
+
modifiable=True,
|
|
203
|
+
setup_cost=0.10,
|
|
204
|
+
cost_up=0.18,
|
|
205
|
+
cost_down=0.18,
|
|
206
|
+
bounds=(4.0, 140.0),
|
|
207
|
+
step=5.0,
|
|
208
|
+
domain="surveillance_proxy",
|
|
209
|
+
rationale="Routine laboratory draw frequency (non-ancestor proxy)",
|
|
210
|
+
),
|
|
211
|
+
LeverSpec(
|
|
212
|
+
"lactate_draws_48h",
|
|
213
|
+
modifiable=True,
|
|
214
|
+
setup_cost=0.10,
|
|
215
|
+
cost_up=0.18,
|
|
216
|
+
cost_down=0.18,
|
|
217
|
+
bounds=(0.0, 24.0),
|
|
218
|
+
step=1.0,
|
|
219
|
+
domain="surveillance_proxy",
|
|
220
|
+
rationale="Serial lactate check count (non-ancestor proxy)",
|
|
221
|
+
),
|
|
222
|
+
],
|
|
223
|
+
domain_setup_costs={"mobility": 0.45},
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
feat_cols = (
|
|
227
|
+
"bmi",
|
|
228
|
+
"braden_mobility",
|
|
229
|
+
"turning_q2h_pct",
|
|
230
|
+
"enteral_nutrition_pct",
|
|
231
|
+
"serum_albumin",
|
|
232
|
+
"tissue_tolerance",
|
|
233
|
+
"lab_count_48h",
|
|
234
|
+
"lactate_draws_48h",
|
|
235
|
+
)
|
|
236
|
+
anc_cols = (
|
|
237
|
+
"bmi",
|
|
238
|
+
"braden_mobility",
|
|
239
|
+
"turning_q2h_pct",
|
|
240
|
+
"enteral_nutrition_pct",
|
|
241
|
+
"serum_albumin",
|
|
242
|
+
"tissue_tolerance",
|
|
243
|
+
)
|
|
244
|
+
return CapreDemoBundle(
|
|
245
|
+
df=df,
|
|
246
|
+
dag=dag,
|
|
247
|
+
price_table=price_table,
|
|
248
|
+
feature_columns=feat_cols,
|
|
249
|
+
ancestor_columns=anc_cols,
|
|
250
|
+
outcome="hapri",
|
|
251
|
+
)
|