capre 0.3.0__tar.gz

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-0.3.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Andrew Wilson
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ include LICENSE
2
+ include README.md
3
+ recursive-include tests *.py *.dagitty
capre-0.3.0/PKG-INFO ADDED
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.4
2
+ Name: capre
3
+ Version: 0.3.0
4
+ Summary: CAPRE: Causal Price-Elastic Recourse via DAG gating, SuperLearner stacking, SCM propagation, and effort-warped surfaces
5
+ Author-email: Andrew Wilson <wilson.stats@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://andystats.github.io/capre/
8
+ Project-URL: Documentation, https://andystats.github.io/capre/vignettes/
9
+ Project-URL: Repository, https://github.com/andystats/capre
10
+ Project-URL: Issues, https://github.com/andystats/capre/issues
11
+ Keywords: causal-inference,counterfactual-explanations,algorithmic-recourse,superlearner,directed-acyclic-graphs,clinical-decision-support
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Intended Audience :: Healthcare Industry
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: numpy>=1.24
27
+ Requires-Dist: pandas>=2.0
28
+ Requires-Dist: scikit-learn>=1.3
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=7.4; extra == "dev"
31
+ Requires-Dist: build>=1.0; extra == "dev"
32
+ Requires-Dist: twine>=6.1; extra == "dev"
33
+ Requires-Dist: packaging>=24.2; extra == "dev"
34
+ Dynamic: license-file
35
+
36
+ # `capre`: Causal Price-Elastic Recourse for Clinical and Tabular Risk Models
37
+
38
+ `capre` (**Causal Price-Elastic Recourse**) generates actionable, budget-feasible counterfactual recourse plans by combining:
39
+
40
+ 1. **DAG & Partial-Knowledge Tier Gating (`DAGSpec`, `DAGSpec.from_tiers`):** Excludes non-ancestor diagnostic proxies (such as 48-hour laboratory draw counts and missingness indicators) without requiring a complete clinical DAG (supporting sink-only exclusions or coarse `(baseline, levers, mediators, sinks)` tiers), while flagging `confounded_ancestors` sharing unmeasured backdoor paths with the outcome.
41
+ 2. **Abduct-Act-Predict Propagation & Interventional Causal Shapley (`LinearStructuralModel`):** Propagates upstream interventions through ridge or cubic-spline structural mediator equations and ranks candidate levers by marginal-residual Interventional Causal Shapley efficiency.
42
+ 3. **Microeconomic Disutility & Effort-Isometric Surface Warping (`LeverSpec`, `PriceTable`):** Models shared domain initiation costs (economies of scope), directional convex marginal effort, Incremental Cost-Effectiveness Ratios (`icer`), Net Clinical Benefit (`net_benefit`), and effort-isometric coordinate maps `z = Psi_x(x')` (`PriceTable.elastic_warp_vector`), while selecting diverse candidate bundles across clinical domains and lever sets.
43
+ 4. **`SuperLearner` Stacking & Model-Dependence Bounds (`CapreSuperLearner`, `MahalanobisOverlapIndex`):** Pairs cross-validated log-loss ensemble predictions with inter-learner dispersion `sigma_MD(x')` (supporting conservative gating `p_SL(x') + lambda_MD * sigma_MD(x') <= tau*`) and Kish Effective Sample Size (`overlap_ess`) counterfactual support diagnostics.
44
+
45
+ ## Installation
46
+
47
+ ```bash
48
+ pip install capre
49
+ ```
50
+
51
+ ## Quick Example
52
+
53
+ ```python
54
+ from capre import CapreExplainer, CapreSuperLearner, make_icu_hapri_demo
55
+
56
+ demo = make_icu_hapri_demo(n=1000, seed=42)
57
+ sl_anc = CapreSuperLearner(feature_columns=demo.ancestor_columns, seed=42).fit(
58
+ demo.df, demo.df[demo.outcome]
59
+ )
60
+ tau = sl_anc.oof_youden_threshold()
61
+
62
+ explainer = CapreExplainer.from_superlearner(
63
+ causal_superlearner=sl_anc,
64
+ train_df=demo.df,
65
+ feature_columns=demo.feature_columns,
66
+ outcome=demo.outcome,
67
+ price_table=demo.price_table,
68
+ dag=demo.dag,
69
+ )
70
+
71
+ high_risk_row = demo.df.loc[sl_anc.predict_risk(demo.df) > tau + 0.15].iloc[0]
72
+ result = explainer.explain(high_risk_row, threshold=tau, budget=5.0, lambda_md=0.5)
73
+ print(result.to_json())
74
+ ```
75
+
76
+ ## Vignettes and Interactive Companion
77
+
78
+ - **Python PDF Vignette (LaTeX Mini-Manuscript):** https://andystats.github.io/capre/vignettes/capre-python-guide.pdf
79
+ - **Interactive Visual Primer:** https://andystats.github.io/capre/
80
+ - **CAPRE for the Classroom (R & Python Workshops):** https://andystats.github.io/capre/classroom/
capre-0.3.0/README.md ADDED
@@ -0,0 +1,45 @@
1
+ # `capre`: Causal Price-Elastic Recourse for Clinical and Tabular Risk Models
2
+
3
+ `capre` (**Causal Price-Elastic Recourse**) generates actionable, budget-feasible counterfactual recourse plans by combining:
4
+
5
+ 1. **DAG & Partial-Knowledge Tier Gating (`DAGSpec`, `DAGSpec.from_tiers`):** Excludes non-ancestor diagnostic proxies (such as 48-hour laboratory draw counts and missingness indicators) without requiring a complete clinical DAG (supporting sink-only exclusions or coarse `(baseline, levers, mediators, sinks)` tiers), while flagging `confounded_ancestors` sharing unmeasured backdoor paths with the outcome.
6
+ 2. **Abduct-Act-Predict Propagation & Interventional Causal Shapley (`LinearStructuralModel`):** Propagates upstream interventions through ridge or cubic-spline structural mediator equations and ranks candidate levers by marginal-residual Interventional Causal Shapley efficiency.
7
+ 3. **Microeconomic Disutility & Effort-Isometric Surface Warping (`LeverSpec`, `PriceTable`):** Models shared domain initiation costs (economies of scope), directional convex marginal effort, Incremental Cost-Effectiveness Ratios (`icer`), Net Clinical Benefit (`net_benefit`), and effort-isometric coordinate maps `z = Psi_x(x')` (`PriceTable.elastic_warp_vector`), while selecting diverse candidate bundles across clinical domains and lever sets.
8
+ 4. **`SuperLearner` Stacking & Model-Dependence Bounds (`CapreSuperLearner`, `MahalanobisOverlapIndex`):** Pairs cross-validated log-loss ensemble predictions with inter-learner dispersion `sigma_MD(x')` (supporting conservative gating `p_SL(x') + lambda_MD * sigma_MD(x') <= tau*`) and Kish Effective Sample Size (`overlap_ess`) counterfactual support diagnostics.
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ pip install capre
14
+ ```
15
+
16
+ ## Quick Example
17
+
18
+ ```python
19
+ from capre import CapreExplainer, CapreSuperLearner, make_icu_hapri_demo
20
+
21
+ demo = make_icu_hapri_demo(n=1000, seed=42)
22
+ sl_anc = CapreSuperLearner(feature_columns=demo.ancestor_columns, seed=42).fit(
23
+ demo.df, demo.df[demo.outcome]
24
+ )
25
+ tau = sl_anc.oof_youden_threshold()
26
+
27
+ explainer = CapreExplainer.from_superlearner(
28
+ causal_superlearner=sl_anc,
29
+ train_df=demo.df,
30
+ feature_columns=demo.feature_columns,
31
+ outcome=demo.outcome,
32
+ price_table=demo.price_table,
33
+ dag=demo.dag,
34
+ )
35
+
36
+ high_risk_row = demo.df.loc[sl_anc.predict_risk(demo.df) > tau + 0.15].iloc[0]
37
+ result = explainer.explain(high_risk_row, threshold=tau, budget=5.0, lambda_md=0.5)
38
+ print(result.to_json())
39
+ ```
40
+
41
+ ## Vignettes and Interactive Companion
42
+
43
+ - **Python PDF Vignette (LaTeX Mini-Manuscript):** https://andystats.github.io/capre/vignettes/capre-python-guide.pdf
44
+ - **Interactive Visual Primer:** https://andystats.github.io/capre/
45
+ - **CAPRE for the Classroom (R & Python Workshops):** https://andystats.github.io/capre/classroom/
@@ -0,0 +1,56 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "capre"
7
+ version = "0.3.0"
8
+ description = "CAPRE: Causal Price-Elastic Recourse via DAG gating, SuperLearner stacking, SCM propagation, and effort-warped surfaces"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [
14
+ { name = "Andrew Wilson", email = "wilson.stats@gmail.com" }
15
+ ]
16
+ keywords = [
17
+ "causal-inference",
18
+ "counterfactual-explanations",
19
+ "algorithmic-recourse",
20
+ "superlearner",
21
+ "directed-acyclic-graphs",
22
+ "clinical-decision-support"
23
+ ]
24
+ classifiers = [
25
+ "Development Status :: 4 - Beta",
26
+ "Intended Audience :: Science/Research",
27
+ "Intended Audience :: Healthcare Industry",
28
+ "Programming Language :: Python :: 3",
29
+ "Programming Language :: Python :: 3.10",
30
+ "Programming Language :: Python :: 3.11",
31
+ "Programming Language :: Python :: 3.12",
32
+ "Programming Language :: Python :: 3.13",
33
+ "Programming Language :: Python :: 3.14",
34
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
35
+ "Topic :: Scientific/Engineering :: Medical Science Apps."
36
+ ]
37
+ dependencies = [
38
+ "numpy>=1.24",
39
+ "pandas>=2.0",
40
+ "scikit-learn>=1.3"
41
+ ]
42
+
43
+ [project.urls]
44
+ Homepage = "https://andystats.github.io/capre/"
45
+ Documentation = "https://andystats.github.io/capre/vignettes/"
46
+ Repository = "https://github.com/andystats/capre"
47
+ Issues = "https://github.com/andystats/capre/issues"
48
+
49
+ [project.optional-dependencies]
50
+ dev = ["pytest>=7.4", "build>=1.0", "twine>=6.1", "packaging>=24.2"]
51
+
52
+ [tool.setuptools.packages.find]
53
+ where = ["src"]
54
+
55
+ [tool.setuptools.package-data]
56
+ capre = ["py.typed"]
capre-0.3.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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"
@@ -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
+ }