caretrace 0.1.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.
Files changed (79) hide show
  1. caretrace-0.1.0/LICENSE +21 -0
  2. caretrace-0.1.0/PKG-INFO +101 -0
  3. caretrace-0.1.0/README.md +74 -0
  4. caretrace-0.1.0/pyproject.toml +43 -0
  5. caretrace-0.1.0/setup.cfg +4 -0
  6. caretrace-0.1.0/src/care_trace/__init__.py +7 -0
  7. caretrace-0.1.0/src/care_trace/acic.py +17 -0
  8. caretrace-0.1.0/src/care_trace/aipw.py +183 -0
  9. caretrace-0.1.0/src/care_trace/analyze_milestone5_final.py +518 -0
  10. caretrace-0.1.0/src/care_trace/arms.py +87 -0
  11. caretrace-0.1.0/src/care_trace/audit.py +85 -0
  12. caretrace-0.1.0/src/care_trace/cli.py +94 -0
  13. caretrace-0.1.0/src/care_trace/clinical/__init__.py +8 -0
  14. caretrace-0.1.0/src/care_trace/clinical/features.py +120 -0
  15. caretrace-0.1.0/src/care_trace/clinical/prepare.py +385 -0
  16. caretrace-0.1.0/src/care_trace/clinical/pubmed.py +148 -0
  17. caretrace-0.1.0/src/care_trace/clinical/selection.py +44 -0
  18. caretrace-0.1.0/src/care_trace/designs.py +157 -0
  19. caretrace-0.1.0/src/care_trace/evidence/__init__.py +5 -0
  20. caretrace-0.1.0/src/care_trace/evidence/corpus.py +67 -0
  21. caretrace-0.1.0/src/care_trace/evidence/decision_cache.py +62 -0
  22. caretrace-0.1.0/src/care_trace/evidence/development_audit.py +192 -0
  23. caretrace-0.1.0/src/care_trace/evidence/freeze.py +60 -0
  24. caretrace-0.1.0/src/care_trace/evidence/graphs.py +273 -0
  25. caretrace-0.1.0/src/care_trace/evidence/hard_evidence.py +206 -0
  26. caretrace-0.1.0/src/care_trace/evidence/heldout_estimation.py +247 -0
  27. caretrace-0.1.0/src/care_trace/evidence/milestone6_cases.py +116 -0
  28. caretrace-0.1.0/src/care_trace/evidence/milestone6_policy.py +106 -0
  29. caretrace-0.1.0/src/care_trace/evidence/milestone6_simulation.py +248 -0
  30. caretrace-0.1.0/src/care_trace/evidence/retrieve.py +211 -0
  31. caretrace-0.1.0/src/care_trace/evidence/revised_cases.py +247 -0
  32. caretrace-0.1.0/src/care_trace/evidence/revised_controls.py +90 -0
  33. caretrace-0.1.0/src/care_trace/evidence/revised_models.py +141 -0
  34. caretrace-0.1.0/src/care_trace/evidence/revised_policy.py +243 -0
  35. caretrace-0.1.0/src/care_trace/evidence/revised_score.py +130 -0
  36. caretrace-0.1.0/src/care_trace/evidence/revised_simulation.py +166 -0
  37. caretrace-0.1.0/src/care_trace/evidence/roles.py +369 -0
  38. caretrace-0.1.0/src/care_trace/evidence/selection.py +243 -0
  39. caretrace-0.1.0/src/care_trace/evidence/structures.py +364 -0
  40. caretrace-0.1.0/src/care_trace/ihdp.py +127 -0
  41. caretrace-0.1.0/src/care_trace/negative_controls.py +71 -0
  42. caretrace-0.1.0/src/care_trace/propensity.py +65 -0
  43. caretrace-0.1.0/src/care_trace/representations.py +199 -0
  44. caretrace-0.1.0/src/care_trace/run_clinical.py +153 -0
  45. caretrace-0.1.0/src/care_trace/run_clinical_llm.py +73 -0
  46. caretrace-0.1.0/src/care_trace/run_milestone1.py +217 -0
  47. caretrace-0.1.0/src/care_trace/run_milestone2.py +157 -0
  48. caretrace-0.1.0/src/care_trace/run_milestone4.py +233 -0
  49. caretrace-0.1.0/src/care_trace/run_milestone4_awq.py +241 -0
  50. caretrace-0.1.0/src/care_trace/run_milestone4_diagnostic.py +247 -0
  51. caretrace-0.1.0/src/care_trace/run_milestone4_extended.py +587 -0
  52. caretrace-0.1.0/src/care_trace/run_milestone5.py +208 -0
  53. caretrace-0.1.0/src/care_trace/run_milestone5_heldout_llm.py +268 -0
  54. caretrace-0.1.0/src/care_trace/run_milestone6.py +417 -0
  55. caretrace-0.1.0/src/care_trace/run_milestone6_llm.py +222 -0
  56. caretrace-0.1.0/src/care_trace/treatment.py +30 -0
  57. caretrace-0.1.0/src/caretrace.egg-info/PKG-INFO +101 -0
  58. caretrace-0.1.0/src/caretrace.egg-info/SOURCES.txt +77 -0
  59. caretrace-0.1.0/src/caretrace.egg-info/dependency_links.txt +1 -0
  60. caretrace-0.1.0/src/caretrace.egg-info/entry_points.txt +2 -0
  61. caretrace-0.1.0/src/caretrace.egg-info/requires.txt +12 -0
  62. caretrace-0.1.0/src/caretrace.egg-info/top_level.txt +1 -0
  63. caretrace-0.1.0/tests/test_acic_columns.py +15 -0
  64. caretrace-0.1.0/tests/test_aipw_interval.py +50 -0
  65. caretrace-0.1.0/tests/test_arm_exit.py +24 -0
  66. caretrace-0.1.0/tests/test_audit.py +67 -0
  67. caretrace-0.1.0/tests/test_clinical.py +192 -0
  68. caretrace-0.1.0/tests/test_evidence_milestone4.py +148 -0
  69. caretrace-0.1.0/tests/test_ihdp_columns.py +55 -0
  70. caretrace-0.1.0/tests/test_milestone4_diagnostic.py +168 -0
  71. caretrace-0.1.0/tests/test_milestone4_extended.py +79 -0
  72. caretrace-0.1.0/tests/test_milestone4_freeze.py +178 -0
  73. caretrace-0.1.0/tests/test_milestone5.py +200 -0
  74. caretrace-0.1.0/tests/test_milestone6.py +115 -0
  75. caretrace-0.1.0/tests/test_negative_controls.py +63 -0
  76. caretrace-0.1.0/tests/test_propensity.py +48 -0
  77. caretrace-0.1.0/tests/test_representation_exit.py +46 -0
  78. caretrace-0.1.0/tests/test_representations.py +85 -0
  79. caretrace-0.1.0/tests/test_treatment_coding.py +30 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Elyas Irankhah
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,101 @@
1
+ Metadata-Version: 2.4
2
+ Name: caretrace
3
+ Version: 0.1.0
4
+ Summary: Audit literature-grounded covariate decisions. An include list is not a validated adjustment set.
5
+ Author: Elyas Irankhah
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/Elyasirankhah/CARE_TRACE
8
+ Project-URL: Repository, https://github.com/Elyasirankhah/CARE_TRACE
9
+ Keywords: causal-inference,covariate-selection,retrieval,audit
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Intended Audience :: Science/Research
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: numpy>=1.24
17
+ Requires-Dist: pandas>=2.0
18
+ Requires-Dist: scikit-learn>=1.3
19
+ Requires-Dist: scipy>=1.11
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest>=8.0; extra == "dev"
22
+ Provides-Extra: local
23
+ Requires-Dist: torch>=2.2; extra == "local"
24
+ Requires-Dist: sentence-transformers>=3.0; extra == "local"
25
+ Requires-Dist: faiss-cpu>=1.7; extra == "local"
26
+ Dynamic: license-file
27
+
28
+ # CARE-TRACE
29
+
30
+ Audit a literature-grounded covariate decision before anyone treats the include list as an adjustment set.
31
+
32
+ [![Python](https://img.shields.io/badge/python-3.10%2B-3776AB)](https://www.python.org/)
33
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
34
+
35
+ CARE-TRACE retrieves passages, applies the study's include / exclude / unresolved rule, and scores a decision on synthetic data where the effect is known. A completed include can be the wrong include. The package does not certify a causal adjustment, and it does not recommend a treatment.
36
+
37
+ ![CARE-TRACE workflow](figures/caretrace-flowchart.png)
38
+
39
+ ```bash
40
+ pip install -e .
41
+ caretrace demo
42
+ ```
43
+
44
+ `caretrace demo` builds two synthetic passages, labels one cited record and one citation that was not shown, and fits a cross-validated augmented inverse-probability estimate on a synthetic draw. Nothing in that command reads a patient file or calls an external model.
45
+
46
+ ## What the package does
47
+
48
+ | Piece | Where |
49
+ | --- | --- |
50
+ | BM25, top 3, identifier bonus off | `care_trace.audit.bm25_hits` |
51
+ | Embedding scores as a dot product of L2-normalized vectors | `care_trace.audit.embedding_hits` |
52
+ | Include, exclude, or unresolved | `care_trace.audit.label_decision` |
53
+ | Baseline report, with non-baseline covariates removed | `care_trace.audit.covariate_report` |
54
+ | Synthetic effect and cross-fit AIPW | `care_trace.designs`, `care_trace.aipw` |
55
+ | Worked example | `examples/synthetic_audit.py` |
56
+
57
+ ```python
58
+ from care_trace.audit import label_decision
59
+
60
+ label_decision(
61
+ {
62
+ "truncated": False,
63
+ "json_valid": True,
64
+ "generated_role": "confounder",
65
+ "final_adjustment": "adjust",
66
+ "generated_citations": ["age:relevant"],
67
+ "known_timing": "baseline",
68
+ },
69
+ shown_ids={"age:relevant"},
70
+ arm="bm25",
71
+ )
72
+ ```
73
+
74
+ That call returns `"include"`. The same record with a citation that was not shown returns `"unresolved"`. `covariate_report` always sets `validated_causal_estimate` to false.
75
+
76
+ Local embedding models and FAISS are optional:
77
+
78
+ ```bash
79
+ pip install -e ".[local]"
80
+ ```
81
+
82
+ The base install uses the hashing embedder in the demo. That embedder is a deterministic stand-in. The study embedding was `Qwen/Qwen3-Embedding-0.6B`.
83
+
84
+ ## What stays out of this install
85
+
86
+ The All of Us reproduction is the cohort notebook and the job scripts in `scripts/`. Those scripts are not installed by `pip`. Do not put participant-level rows, clinical JSON from the workbench, or an API key in this repository. Do not send participant text to an external model API.
87
+
88
+ `requirements.txt` is the pinned research environment, including torch. The installable package does not require torch.
89
+
90
+ ## Tests
91
+
92
+ ```bash
93
+ pip install -e ".[dev]"
94
+ python -m pytest tests/test_audit.py
95
+ ```
96
+
97
+ ## Citation
98
+
99
+ The journal record and its DOI will be added when the tagged release is archived. Until then, cite the software repository:
100
+
101
+ https://github.com/Elyasirankhah/CARE_TRACE
@@ -0,0 +1,74 @@
1
+ # CARE-TRACE
2
+
3
+ Audit a literature-grounded covariate decision before anyone treats the include list as an adjustment set.
4
+
5
+ [![Python](https://img.shields.io/badge/python-3.10%2B-3776AB)](https://www.python.org/)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
7
+
8
+ CARE-TRACE retrieves passages, applies the study's include / exclude / unresolved rule, and scores a decision on synthetic data where the effect is known. A completed include can be the wrong include. The package does not certify a causal adjustment, and it does not recommend a treatment.
9
+
10
+ ![CARE-TRACE workflow](figures/caretrace-flowchart.png)
11
+
12
+ ```bash
13
+ pip install -e .
14
+ caretrace demo
15
+ ```
16
+
17
+ `caretrace demo` builds two synthetic passages, labels one cited record and one citation that was not shown, and fits a cross-validated augmented inverse-probability estimate on a synthetic draw. Nothing in that command reads a patient file or calls an external model.
18
+
19
+ ## What the package does
20
+
21
+ | Piece | Where |
22
+ | --- | --- |
23
+ | BM25, top 3, identifier bonus off | `care_trace.audit.bm25_hits` |
24
+ | Embedding scores as a dot product of L2-normalized vectors | `care_trace.audit.embedding_hits` |
25
+ | Include, exclude, or unresolved | `care_trace.audit.label_decision` |
26
+ | Baseline report, with non-baseline covariates removed | `care_trace.audit.covariate_report` |
27
+ | Synthetic effect and cross-fit AIPW | `care_trace.designs`, `care_trace.aipw` |
28
+ | Worked example | `examples/synthetic_audit.py` |
29
+
30
+ ```python
31
+ from care_trace.audit import label_decision
32
+
33
+ label_decision(
34
+ {
35
+ "truncated": False,
36
+ "json_valid": True,
37
+ "generated_role": "confounder",
38
+ "final_adjustment": "adjust",
39
+ "generated_citations": ["age:relevant"],
40
+ "known_timing": "baseline",
41
+ },
42
+ shown_ids={"age:relevant"},
43
+ arm="bm25",
44
+ )
45
+ ```
46
+
47
+ That call returns `"include"`. The same record with a citation that was not shown returns `"unresolved"`. `covariate_report` always sets `validated_causal_estimate` to false.
48
+
49
+ Local embedding models and FAISS are optional:
50
+
51
+ ```bash
52
+ pip install -e ".[local]"
53
+ ```
54
+
55
+ The base install uses the hashing embedder in the demo. That embedder is a deterministic stand-in. The study embedding was `Qwen/Qwen3-Embedding-0.6B`.
56
+
57
+ ## What stays out of this install
58
+
59
+ The All of Us reproduction is the cohort notebook and the job scripts in `scripts/`. Those scripts are not installed by `pip`. Do not put participant-level rows, clinical JSON from the workbench, or an API key in this repository. Do not send participant text to an external model API.
60
+
61
+ `requirements.txt` is the pinned research environment, including torch. The installable package does not require torch.
62
+
63
+ ## Tests
64
+
65
+ ```bash
66
+ pip install -e ".[dev]"
67
+ python -m pytest tests/test_audit.py
68
+ ```
69
+
70
+ ## Citation
71
+
72
+ The journal record and its DOI will be added when the tagged release is archived. Until then, cite the software repository:
73
+
74
+ https://github.com/Elyasirankhah/CARE_TRACE
@@ -0,0 +1,43 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "caretrace"
7
+ version = "0.1.0"
8
+ description = "Audit literature-grounded covariate decisions. An include list is not a validated adjustment set."
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.10"
12
+ authors = [{ name = "Elyas Irankhah" }]
13
+ keywords = ["causal-inference", "covariate-selection", "retrieval", "audit"]
14
+ dependencies = [
15
+ "numpy>=1.24",
16
+ "pandas>=2.0",
17
+ "scikit-learn>=1.3",
18
+ "scipy>=1.11",
19
+ ]
20
+ classifiers = [
21
+ "License :: OSI Approved :: MIT License",
22
+ "Programming Language :: Python :: 3",
23
+ "Intended Audience :: Science/Research",
24
+ ]
25
+
26
+ [project.urls]
27
+ Homepage = "https://github.com/Elyasirankhah/CARE_TRACE"
28
+ Repository = "https://github.com/Elyasirankhah/CARE_TRACE"
29
+
30
+ [project.scripts]
31
+ caretrace = "care_trace.cli:main"
32
+
33
+ [project.optional-dependencies]
34
+ dev = ["pytest>=8.0"]
35
+ local = ["torch>=2.2", "sentence-transformers>=3.0", "faiss-cpu>=1.7"]
36
+
37
+ [tool.setuptools.packages.find]
38
+ where = ["src"]
39
+ include = ["care_trace*"]
40
+
41
+ [tool.pytest.ini_options]
42
+ pythonpath = ["src"]
43
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,7 @@
1
+ """CARE-TRACE: an audit of literature-grounded covariate decisions.
2
+
3
+ An include list is not a validated adjustment set. This package does not
4
+ read a participant table and does not call an external model.
5
+ """
6
+
7
+ __version__ = "0.1.0"
@@ -0,0 +1,17 @@
1
+ """ACIC 2016 column guard.
2
+
3
+ ``input_2016`` names its columns ``x_1`` through ``x_58``. The package
4
+ manual lists Collaborative Perinatal Project variables and does not state
5
+ that this list is the column order. Arm B is not built from that list.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+
11
+ def deidentified_names(n_columns: int = 58) -> list[str]:
12
+ return [f"x_{index}" for index in range(1, n_columns + 1)]
13
+
14
+
15
+ def arm_b_is_defined(column_names: list[str]) -> bool:
16
+ """Return whether the file itself names demographic and clinical columns."""
17
+ return list(column_names) != deidentified_names(len(column_names))
@@ -0,0 +1,183 @@
1
+ """Cross-fit augmented inverse probability weighting.
2
+
3
+ The primary interval is the normal approximation to the cross-fit
4
+ influence function. It is not a bootstrap of frozen scores. Propensity
5
+ clipping keeps every unit in the sample; it does not change the
6
+ population the way trimming would.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+
13
+ import numpy as np
14
+ from scipy.stats import norm
15
+ from sklearn.linear_model import LinearRegression, LogisticRegression
16
+ from sklearn.model_selection import StratifiedKFold
17
+ from sklearn.preprocessing import StandardScaler
18
+
19
+
20
+ PRIMARY_INTERVAL = "cross_fit_influence_function"
21
+ FROZEN_SCORE_BOOTSTRAP = "frozen_score_bootstrap"
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class IntervalResult:
26
+ estimate: float
27
+ se: float
28
+ ci_low: float
29
+ ci_high: float
30
+ procedure: str
31
+ scores: np.ndarray
32
+
33
+
34
+ def _logistic() -> LogisticRegression:
35
+ return LogisticRegression(max_iter=2000, solver="lbfgs", C=1.0)
36
+
37
+
38
+ def nuisance_predictions(
39
+ x_train: np.ndarray,
40
+ t_train: np.ndarray,
41
+ y_train: np.ndarray,
42
+ x_test: np.ndarray,
43
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
44
+ """Out-of-fold propensity and outcome predictions for one test fold."""
45
+ t_train = np.asarray(t_train).astype(int)
46
+ y_train = np.asarray(y_train, dtype=float)
47
+ if len(np.unique(t_train)) < 2:
48
+ raise ValueError("a training fold has only one treatment class")
49
+ treated = t_train == 1
50
+ if treated.sum() < 2 or (~treated).sum() < 2:
51
+ raise ValueError("a training fold has fewer than two units in a class")
52
+
53
+ scaler = StandardScaler()
54
+ scaled_train = scaler.fit_transform(x_train)
55
+ scaled_test = scaler.transform(x_test)
56
+ propensity_model = _logistic()
57
+ propensity_model.fit(scaled_train, t_train)
58
+ propensity = propensity_model.predict_proba(scaled_test)[:, 1]
59
+
60
+ outcome_treated = LinearRegression().fit(x_train[treated], y_train[treated])
61
+ outcome_control = LinearRegression().fit(x_train[~treated], y_train[~treated])
62
+ return (
63
+ propensity,
64
+ outcome_control.predict(x_test),
65
+ outcome_treated.predict(x_test),
66
+ )
67
+
68
+
69
+ def influence_scores(
70
+ t: np.ndarray,
71
+ y: np.ndarray,
72
+ propensity: np.ndarray,
73
+ mu0: np.ndarray,
74
+ mu1: np.ndarray,
75
+ ) -> np.ndarray:
76
+ """AIPW scores. Their mean is the ATE estimate."""
77
+ t = np.asarray(t, dtype=float)
78
+ y = np.asarray(y, dtype=float)
79
+ propensity = np.asarray(propensity, dtype=float)
80
+ mu0 = np.asarray(mu0, dtype=float)
81
+ mu1 = np.asarray(mu1, dtype=float)
82
+ return (
83
+ (mu1 - mu0)
84
+ + t * (y - mu1) / propensity
85
+ - (1.0 - t) * (y - mu0) / (1.0 - propensity)
86
+ )
87
+
88
+
89
+ def interval_from_scores(
90
+ scores: np.ndarray,
91
+ procedure: str,
92
+ quantile: float = 0.975,
93
+ ) -> IntervalResult:
94
+ scores = np.asarray(scores, dtype=float)
95
+ estimate = float(scores.mean())
96
+ se = float(scores.std(ddof=1) / np.sqrt(len(scores)))
97
+ z = float(norm.ppf(quantile))
98
+ return IntervalResult(
99
+ estimate=estimate,
100
+ se=se,
101
+ ci_low=estimate - z * se,
102
+ ci_high=estimate + z * se,
103
+ procedure=procedure,
104
+ scores=scores,
105
+ )
106
+
107
+
108
+ def cross_fit_aipw(
109
+ X: np.ndarray,
110
+ t: np.ndarray,
111
+ y: np.ndarray,
112
+ n_splits: int = 5,
113
+ seed: int = 0,
114
+ clip: float = 1e-3,
115
+ quantile: float = 0.975,
116
+ ) -> IntervalResult:
117
+ """Fit propensity and outcome models out of fold, then form the AIPW interval.
118
+
119
+ ``seed`` fixes the stratified fold assignment. The interval uses the
120
+ influence scores from those folds. It does not resample them.
121
+ """
122
+ X = np.asarray(X, dtype=float)
123
+ t = np.asarray(t).astype(int)
124
+ y = np.asarray(y, dtype=float)
125
+ if not (len(X) == len(t) == len(y)):
126
+ raise ValueError("X, t, and y must have the same number of rows")
127
+ if n_splits < 2:
128
+ raise ValueError("n_splits must be at least 2")
129
+ if len(np.unique(t)) < 2:
130
+ raise ValueError("treatment must contain both 0 and 1")
131
+ if not 0 < clip < 0.5:
132
+ raise ValueError("clip must lie in (0, 0.5)")
133
+
134
+ counts = np.bincount(t)
135
+ if counts.min() < n_splits:
136
+ raise ValueError("each treatment class needs at least n_splits rows")
137
+
138
+ propensity = np.empty(len(t), dtype=float)
139
+ mu0 = np.empty(len(t), dtype=float)
140
+ mu1 = np.empty(len(t), dtype=float)
141
+ splitter = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=seed)
142
+ for train_idx, test_idx in splitter.split(X, t):
143
+ propensity[test_idx], mu0[test_idx], mu1[test_idx] = nuisance_predictions(
144
+ X[train_idx],
145
+ t[train_idx],
146
+ y[train_idx],
147
+ X[test_idx],
148
+ )
149
+
150
+ propensity = np.clip(propensity, clip, 1.0 - clip)
151
+ scores = influence_scores(t, y, propensity, mu0, mu1)
152
+ return interval_from_scores(scores, PRIMARY_INTERVAL, quantile=quantile)
153
+
154
+
155
+ def frozen_score_bootstrap(
156
+ scores: np.ndarray,
157
+ n_boot: int = 200,
158
+ seed: int = 0,
159
+ ) -> IntervalResult:
160
+ """Percentile interval from resampling scores that were already computed.
161
+
162
+ This does not refit the propensity or outcome models. It is not the
163
+ primary interval.
164
+ """
165
+ scores = np.asarray(scores, dtype=float)
166
+ if n_boot < 2:
167
+ raise ValueError("n_boot must be at least 2")
168
+ rng = np.random.default_rng(seed)
169
+ n = len(scores)
170
+ draws = np.empty(n_boot, dtype=float)
171
+ for draw in range(n_boot):
172
+ draws[draw] = scores[rng.integers(0, n, size=n)].mean()
173
+ estimate = float(scores.mean())
174
+ se = float(scores.std(ddof=1) / np.sqrt(n))
175
+ low, high = np.quantile(draws, [0.025, 0.975])
176
+ return IntervalResult(
177
+ estimate=estimate,
178
+ se=se,
179
+ ci_low=float(low),
180
+ ci_high=float(high),
181
+ procedure=FROZEN_SCORE_BOOTSTRAP,
182
+ scores=scores,
183
+ )