pycrr 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.
- pycrr-0.1.0/LICENSE +21 -0
- pycrr-0.1.0/PKG-INFO +297 -0
- pycrr-0.1.0/README.md +273 -0
- pycrr-0.1.0/pycrr/__init__.py +19 -0
- pycrr-0.1.0/pycrr/compare.py +176 -0
- pycrr-0.1.0/pycrr/core.py +78 -0
- pycrr-0.1.0/pycrr/estimator.py +255 -0
- pycrr-0.1.0/pycrr/metrics.py +183 -0
- pycrr-0.1.0/pycrr/model.py +995 -0
- pycrr-0.1.0/pycrr/plot.py +186 -0
- pycrr-0.1.0/pycrr/surv.py +91 -0
- pycrr-0.1.0/pycrr.egg-info/PKG-INFO +297 -0
- pycrr-0.1.0/pycrr.egg-info/SOURCES.txt +23 -0
- pycrr-0.1.0/pycrr.egg-info/dependency_links.txt +1 -0
- pycrr-0.1.0/pycrr.egg-info/requires.txt +8 -0
- pycrr-0.1.0/pycrr.egg-info/top_level.txt +1 -0
- pycrr-0.1.0/pyproject.toml +41 -0
- pycrr-0.1.0/setup.cfg +4 -0
- pycrr-0.1.0/tests/test_compare.py +154 -0
- pycrr-0.1.0/tests/test_estimator.py +169 -0
- pycrr-0.1.0/tests/test_metrics.py +148 -0
- pycrr-0.1.0/tests/test_model.py +202 -0
- pycrr-0.1.0/tests/test_new_features.py +438 -0
- pycrr-0.1.0/tests/test_surv.py +158 -0
- pycrr-0.1.0/tests/test_validation_matrix.py +695 -0
pycrr-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jiwoo Bae
|
|
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.
|
pycrr-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pycrr
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Fine-Gray competing risks regression with diagnostic inference in Python
|
|
5
|
+
Author: Jiwoo Bae
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Repository, https://github.com/jiwoobae7/pycrr
|
|
8
|
+
Keywords: survival analysis,competing risks,Fine-Gray,statistics,epidemiology
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: numpy>=1.24
|
|
17
|
+
Requires-Dist: scipy>=1.10
|
|
18
|
+
Requires-Dist: pandas>=1.5
|
|
19
|
+
Requires-Dist: lifelines>=0.27
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
22
|
+
Requires-Dist: pytest-cov; extra == "dev"
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# pycrr
|
|
26
|
+
|
|
27
|
+
[](https://doi.org/10.5281/zenodo.22685247)
|
|
28
|
+
|
|
29
|
+
**Fine-Gray competing risks regression with diagnostic inference in Python.**
|
|
30
|
+
|
|
31
|
+
`pycrr` implements the subdistribution hazard model of Fine & Gray (1999) for
|
|
32
|
+
time-to-event data with competing events. Beyond coefficient estimation, it
|
|
33
|
+
provides a focused **inference and diagnostic workflow**: robust sandwich standard
|
|
34
|
+
errors, per-subject score residuals, a proportional subdistribution hazards test,
|
|
35
|
+
and time-varying covariate effects — matching the R `cmprsk::crr` interface and
|
|
36
|
+
validated numerically against it.
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## Installation
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install pycrr
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Dependencies: `numpy`, `scipy`, `pandas`, `lifelines`.
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## Quick start
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
import numpy as np
|
|
54
|
+
from pycrr import FineGrayModel, Surv
|
|
55
|
+
|
|
56
|
+
# event: 0=censored, 1=event of interest, 2=competing event
|
|
57
|
+
model = FineGrayModel().fit(X, Surv(time, event))
|
|
58
|
+
model.summary(feature_names=["age", "treatment"])
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
```
|
|
62
|
+
Variable coef HR se robust_se z p 95% CI (model-based)
|
|
63
|
+
------------------------------------------------------------------------------------------------
|
|
64
|
+
age 0.0312 1.0317 0.0081 0.0094 3.852 0.0001 [0.0153, 0.0471]
|
|
65
|
+
treatment 0.4201 1.5222 0.1034 0.1187 4.062 0.0000 [0.2175, 0.6228]
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
---
|
|
69
|
+
|
|
70
|
+
## Diagnostic workflow
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
# Proportional subdistribution hazards test
|
|
74
|
+
model.check_proportionality(feature_names=["age", "treatment"])
|
|
75
|
+
# Variable rho chisq df p
|
|
76
|
+
# age 0.031 0.423 1 0.515
|
|
77
|
+
# treatment 0.018 0.141 1 0.707
|
|
78
|
+
# GLOBAL -- 0.564 2 0.754
|
|
79
|
+
|
|
80
|
+
# Score residuals (n x p) — sum to zero at MLE, reconstruct robust covariance
|
|
81
|
+
U = model.score_residuals_ # shape (n, p)
|
|
82
|
+
print(U.sum(axis=0)) # ≈ [0, 0]
|
|
83
|
+
|
|
84
|
+
# Robust (sandwich) SE — accounts for estimated censoring weights
|
|
85
|
+
print(model.robust_se_) # Lin-Wei-Ying sqrt(diag(A⁻¹ B A⁻¹))
|
|
86
|
+
print(model.robust_p_) # p-values from robust SE
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
---
|
|
90
|
+
|
|
91
|
+
## Time-varying covariate effects
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
# Matches R's crr(cov1=X, cov2=X, tf=log) interface
|
|
95
|
+
model_tv = FineGrayModel().fit(X, Surv(time, event), cov2=X, tf=np.log)
|
|
96
|
+
# Effective covariate at time t: [x_i ; x_i * log(t)]
|
|
97
|
+
# Detects whether the hazard ratio changes over time
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
---
|
|
101
|
+
|
|
102
|
+
## CIF prediction
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
times = np.linspace(0, 10, 200)
|
|
106
|
+
cif = model.predict_cif(X_new, times) # shape (n_new, 200)
|
|
107
|
+
|
|
108
|
+
import matplotlib.pyplot as plt
|
|
109
|
+
plt.plot(times, cif[0], label="Profile 1")
|
|
110
|
+
plt.plot(times, cif[1], label="Profile 2")
|
|
111
|
+
plt.xlabel("Time"); plt.ylabel("CIF"); plt.legend()
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
---
|
|
115
|
+
|
|
116
|
+
## Full API
|
|
117
|
+
|
|
118
|
+
### `Surv(time, event)`
|
|
119
|
+
|
|
120
|
+
R-like survival object accepted by all fitting and testing functions.
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
sv = Surv(time, event)
|
|
124
|
+
sv.causes # sorted list of non-zero event codes
|
|
125
|
+
sv.n_events # total non-censored count
|
|
126
|
+
sv.event_table() # dict with counts per cause and censored
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
---
|
|
130
|
+
|
|
131
|
+
### `FineGrayModel(l2=0.0)`
|
|
132
|
+
|
|
133
|
+
#### `.fit(X, time, event=None, event_of_interest=1, ipcw=None, cov2=None, tf=None)`
|
|
134
|
+
|
|
135
|
+
| Parameter | Description |
|
|
136
|
+
|-----------|-------------|
|
|
137
|
+
| `X` | `(n, p)` covariate matrix. Center/scale if covariates are on different scales. |
|
|
138
|
+
| `time` | `(n,)` observed times, or a `Surv(time, event)` object. |
|
|
139
|
+
| `event` | `(n,)` event indicators. Omit if `time` is a `Surv` object. |
|
|
140
|
+
| `event_of_interest` | Event code to model. Default 1. |
|
|
141
|
+
| `ipcw` | Pre-computed static weights. If `None`, time-varying IPCW are used (recommended). |
|
|
142
|
+
| `cov2` | `(n, q)` covariates for time-varying effects (R's `cov2`). |
|
|
143
|
+
| `tf` | Function of time applied to `cov2` (e.g. `np.log`). Required if `cov2` is given. |
|
|
144
|
+
|
|
145
|
+
**Attributes after fitting:**
|
|
146
|
+
|
|
147
|
+
| Attribute | Description |
|
|
148
|
+
|-----------|-------------|
|
|
149
|
+
| `coef_` | Coefficients $\hat\beta$ |
|
|
150
|
+
| `standard_errors_` | Model-based SE (matches R `fit$invinf`) |
|
|
151
|
+
| `robust_se_` | Lin-Wei-Ying sandwich SE (matches R `fit$var`) |
|
|
152
|
+
| `robust_p_` | Two-sided p-values from robust SE |
|
|
153
|
+
| `score_residuals_` | `(n, p)` per-subject score residuals |
|
|
154
|
+
| `schoenfeld_residuals_` | Per-event Schoenfeld residuals |
|
|
155
|
+
| `cov_matrix_` | Model-based covariance (inverse information) |
|
|
156
|
+
| `hazard_ratios_` via `.hazard_ratios()` | `exp(coef_)` |
|
|
157
|
+
|
|
158
|
+
#### `.check_proportionality(tf=None, feature_names=None)`
|
|
159
|
+
|
|
160
|
+
Tests the proportional subdistribution hazards assumption. Returns a DataFrame
|
|
161
|
+
with columns `variable`, `rho`, `chisq`, `df`, `p`. Uses Schoenfeld-type
|
|
162
|
+
residuals correlated with event time (or `tf(time)` if provided).
|
|
163
|
+
|
|
164
|
+
#### `.predict_cif(X_new, times=None, cov2_new=None)`
|
|
165
|
+
|
|
166
|
+
Returns predicted CIF as `(n_new, len(times))` array.
|
|
167
|
+
|
|
168
|
+
#### `.summary(feature_names=None, robust=False)`
|
|
169
|
+
|
|
170
|
+
Prints a formatted regression table. Set `robust=True` to use robust SEs.
|
|
171
|
+
|
|
172
|
+
---
|
|
173
|
+
|
|
174
|
+
### `AalenJohansen()`
|
|
175
|
+
|
|
176
|
+
Non-parametric CIF estimator with log-log confidence intervals.
|
|
177
|
+
|
|
178
|
+
```python
|
|
179
|
+
aj = AalenJohansen().fit(Surv(time, event))
|
|
180
|
+
t_grid, cif = aj.predict(cause=1)
|
|
181
|
+
lo, hi = aj.confidence_intervals(cause=1)
|
|
182
|
+
aj.summary()
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
---
|
|
186
|
+
|
|
187
|
+
### `gray_test(time, event, group, cause=1, rho=0)`
|
|
188
|
+
|
|
189
|
+
Gray's K-sample test for equality of CIFs across groups.
|
|
190
|
+
|
|
191
|
+
```python
|
|
192
|
+
from pycrr.compare import gray_test
|
|
193
|
+
|
|
194
|
+
result = gray_test(Surv(time, event), group)
|
|
195
|
+
result.summary()
|
|
196
|
+
# Gray's test — chi-squared = 5.12, df = 1, p = 0.024
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
---
|
|
200
|
+
|
|
201
|
+
### Metrics
|
|
202
|
+
|
|
203
|
+
```python
|
|
204
|
+
from pycrr.metrics import brier_score, integrated_brier_score, concordance
|
|
205
|
+
|
|
206
|
+
bs = brier_score(model, X_test, time_test, event_test, t=5.0)
|
|
207
|
+
ibs = integrated_brier_score(model, X_test, time_test, event_test,
|
|
208
|
+
times=np.linspace(0.5, 8, 50))
|
|
209
|
+
c = concordance(model, X_test, time_test, event_test)
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
---
|
|
213
|
+
|
|
214
|
+
## Validation
|
|
215
|
+
|
|
216
|
+
`pycrr` was validated against `cmprsk::crr` (R 4.5.0, v2.2-12) on:
|
|
217
|
+
|
|
218
|
+
**Synthetic dataset** (`n=500`, generated with `set.seed(42)` in R):
|
|
219
|
+
|
|
220
|
+
| Output | Max \|diff vs R\| |
|
|
221
|
+
|--------|-------------------|
|
|
222
|
+
| Coefficients | 2 × 10⁻⁶ |
|
|
223
|
+
| Model-based SE | 2 × 10⁻⁶ |
|
|
224
|
+
| Robust SE | 5 × 10⁻⁵ |
|
|
225
|
+
| Full 2×2 robust cov matrix | 1 × 10⁻⁴ |
|
|
226
|
+
|
|
227
|
+
**MGUS2** (`n=1,384`, from the R `survival` package, real clinical data):
|
|
228
|
+
|
|
229
|
+
| Output | Max \|diff vs R\| |
|
|
230
|
+
|--------|-------------------|
|
|
231
|
+
| Coefficients | 3 × 10⁻⁵ |
|
|
232
|
+
| Model-based SE | 3 × 10⁻⁵ |
|
|
233
|
+
| Robust SE | 2 × 10⁻⁵ |
|
|
234
|
+
| Full 2×2 robust cov matrix | 1 × 10⁻⁴ |
|
|
235
|
+
|
|
236
|
+
Score residuals satisfy $\sum_i U_i = 0$ to $10^{-11}$ and reconstruct the
|
|
237
|
+
robust covariance matrix exactly. The proportionality test detects crossing
|
|
238
|
+
subdistribution hazards (Schoenfeld ρ ≈ −0.65, p < 10⁻⁴) and correctly finds
|
|
239
|
+
no violation on proportional data. Full validation scripts are in `examples/`.
|
|
240
|
+
|
|
241
|
+
---
|
|
242
|
+
|
|
243
|
+
## Related packages
|
|
244
|
+
|
|
245
|
+
`pycrr` focuses on inference and diagnostics. Other Python competing-risks
|
|
246
|
+
packages take different approaches:
|
|
247
|
+
|
|
248
|
+
| Package | Focus |
|
|
249
|
+
|---------|-------|
|
|
250
|
+
| `comprisk` | Fine-Gray + penalized FG + cause-specific Cox + competing-risks forest + sklearn API |
|
|
251
|
+
| `pycmprsk` | Systematic port of R `cmprsk`, including censoring strata |
|
|
252
|
+
| `CompRiskReg` | Translation of R `cmprsk` with `cov2`/`tf` interface |
|
|
253
|
+
| `lifelines` | Broad survival analysis; Aalen-Johansen but not Fine-Gray |
|
|
254
|
+
| `scikit-survival` | ML-focused survival; non-parametric CIF only |
|
|
255
|
+
|
|
256
|
+
`pycrr`'s distinct focus is the **diagnostic layer**: score residuals whose
|
|
257
|
+
estimating equations balance, exact sandwich covariance reconstruction, and a
|
|
258
|
+
proportional subdistribution hazards test with both negative- and
|
|
259
|
+
positive-control validation.
|
|
260
|
+
|
|
261
|
+
---
|
|
262
|
+
|
|
263
|
+
## Background
|
|
264
|
+
|
|
265
|
+
Fine & Gray (1999) model the subdistribution hazard:
|
|
266
|
+
|
|
267
|
+
$$\lambda_1(t \mid x) = \lambda_{10}(t) \exp(\beta^\top x)$$
|
|
268
|
+
|
|
269
|
+
Subjects who experienced a competing event remain in the risk set with
|
|
270
|
+
time-varying weight $G(t^-)/G(T_i^-) \le 1$, where $G$ is the Kaplan-Meier
|
|
271
|
+
censoring survival function. `pycrr` implements this with a Breslow tie
|
|
272
|
+
correction (matching `cmprsk::crr`) and L-BFGS-B optimization with analytically
|
|
273
|
+
derived gradients.
|
|
274
|
+
|
|
275
|
+
---
|
|
276
|
+
|
|
277
|
+
## Best practices
|
|
278
|
+
|
|
279
|
+
- **Standardize covariates** when scales differ. R's `crr` uses Newton-Raphson
|
|
280
|
+
(scale-invariant); `pycrr` uses L-BFGS-B which can be slow on poorly scaled
|
|
281
|
+
inputs.
|
|
282
|
+
- **Use `Surv(time, event)`** to bundle outcomes and avoid argument order errors.
|
|
283
|
+
- **Check proportionality** before interpreting coefficients as time-constant.
|
|
284
|
+
|
|
285
|
+
---
|
|
286
|
+
|
|
287
|
+
## Running tests
|
|
288
|
+
|
|
289
|
+
```bash
|
|
290
|
+
pytest # 235 tests across 4 files
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
---
|
|
294
|
+
|
|
295
|
+
## License
|
|
296
|
+
|
|
297
|
+
MIT
|
pycrr-0.1.0/README.md
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
# pycrr
|
|
2
|
+
|
|
3
|
+
[](https://doi.org/10.5281/zenodo.22685247)
|
|
4
|
+
|
|
5
|
+
**Fine-Gray competing risks regression with diagnostic inference in Python.**
|
|
6
|
+
|
|
7
|
+
`pycrr` implements the subdistribution hazard model of Fine & Gray (1999) for
|
|
8
|
+
time-to-event data with competing events. Beyond coefficient estimation, it
|
|
9
|
+
provides a focused **inference and diagnostic workflow**: robust sandwich standard
|
|
10
|
+
errors, per-subject score residuals, a proportional subdistribution hazards test,
|
|
11
|
+
and time-varying covariate effects — matching the R `cmprsk::crr` interface and
|
|
12
|
+
validated numerically against it.
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
## Installation
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pip install pycrr
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Dependencies: `numpy`, `scipy`, `pandas`, `lifelines`.
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## Quick start
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
import numpy as np
|
|
30
|
+
from pycrr import FineGrayModel, Surv
|
|
31
|
+
|
|
32
|
+
# event: 0=censored, 1=event of interest, 2=competing event
|
|
33
|
+
model = FineGrayModel().fit(X, Surv(time, event))
|
|
34
|
+
model.summary(feature_names=["age", "treatment"])
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
```
|
|
38
|
+
Variable coef HR se robust_se z p 95% CI (model-based)
|
|
39
|
+
------------------------------------------------------------------------------------------------
|
|
40
|
+
age 0.0312 1.0317 0.0081 0.0094 3.852 0.0001 [0.0153, 0.0471]
|
|
41
|
+
treatment 0.4201 1.5222 0.1034 0.1187 4.062 0.0000 [0.2175, 0.6228]
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
## Diagnostic workflow
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
# Proportional subdistribution hazards test
|
|
50
|
+
model.check_proportionality(feature_names=["age", "treatment"])
|
|
51
|
+
# Variable rho chisq df p
|
|
52
|
+
# age 0.031 0.423 1 0.515
|
|
53
|
+
# treatment 0.018 0.141 1 0.707
|
|
54
|
+
# GLOBAL -- 0.564 2 0.754
|
|
55
|
+
|
|
56
|
+
# Score residuals (n x p) — sum to zero at MLE, reconstruct robust covariance
|
|
57
|
+
U = model.score_residuals_ # shape (n, p)
|
|
58
|
+
print(U.sum(axis=0)) # ≈ [0, 0]
|
|
59
|
+
|
|
60
|
+
# Robust (sandwich) SE — accounts for estimated censoring weights
|
|
61
|
+
print(model.robust_se_) # Lin-Wei-Ying sqrt(diag(A⁻¹ B A⁻¹))
|
|
62
|
+
print(model.robust_p_) # p-values from robust SE
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## Time-varying covariate effects
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
# Matches R's crr(cov1=X, cov2=X, tf=log) interface
|
|
71
|
+
model_tv = FineGrayModel().fit(X, Surv(time, event), cov2=X, tf=np.log)
|
|
72
|
+
# Effective covariate at time t: [x_i ; x_i * log(t)]
|
|
73
|
+
# Detects whether the hazard ratio changes over time
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
---
|
|
77
|
+
|
|
78
|
+
## CIF prediction
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
times = np.linspace(0, 10, 200)
|
|
82
|
+
cif = model.predict_cif(X_new, times) # shape (n_new, 200)
|
|
83
|
+
|
|
84
|
+
import matplotlib.pyplot as plt
|
|
85
|
+
plt.plot(times, cif[0], label="Profile 1")
|
|
86
|
+
plt.plot(times, cif[1], label="Profile 2")
|
|
87
|
+
plt.xlabel("Time"); plt.ylabel("CIF"); plt.legend()
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## Full API
|
|
93
|
+
|
|
94
|
+
### `Surv(time, event)`
|
|
95
|
+
|
|
96
|
+
R-like survival object accepted by all fitting and testing functions.
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
sv = Surv(time, event)
|
|
100
|
+
sv.causes # sorted list of non-zero event codes
|
|
101
|
+
sv.n_events # total non-censored count
|
|
102
|
+
sv.event_table() # dict with counts per cause and censored
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
---
|
|
106
|
+
|
|
107
|
+
### `FineGrayModel(l2=0.0)`
|
|
108
|
+
|
|
109
|
+
#### `.fit(X, time, event=None, event_of_interest=1, ipcw=None, cov2=None, tf=None)`
|
|
110
|
+
|
|
111
|
+
| Parameter | Description |
|
|
112
|
+
|-----------|-------------|
|
|
113
|
+
| `X` | `(n, p)` covariate matrix. Center/scale if covariates are on different scales. |
|
|
114
|
+
| `time` | `(n,)` observed times, or a `Surv(time, event)` object. |
|
|
115
|
+
| `event` | `(n,)` event indicators. Omit if `time` is a `Surv` object. |
|
|
116
|
+
| `event_of_interest` | Event code to model. Default 1. |
|
|
117
|
+
| `ipcw` | Pre-computed static weights. If `None`, time-varying IPCW are used (recommended). |
|
|
118
|
+
| `cov2` | `(n, q)` covariates for time-varying effects (R's `cov2`). |
|
|
119
|
+
| `tf` | Function of time applied to `cov2` (e.g. `np.log`). Required if `cov2` is given. |
|
|
120
|
+
|
|
121
|
+
**Attributes after fitting:**
|
|
122
|
+
|
|
123
|
+
| Attribute | Description |
|
|
124
|
+
|-----------|-------------|
|
|
125
|
+
| `coef_` | Coefficients $\hat\beta$ |
|
|
126
|
+
| `standard_errors_` | Model-based SE (matches R `fit$invinf`) |
|
|
127
|
+
| `robust_se_` | Lin-Wei-Ying sandwich SE (matches R `fit$var`) |
|
|
128
|
+
| `robust_p_` | Two-sided p-values from robust SE |
|
|
129
|
+
| `score_residuals_` | `(n, p)` per-subject score residuals |
|
|
130
|
+
| `schoenfeld_residuals_` | Per-event Schoenfeld residuals |
|
|
131
|
+
| `cov_matrix_` | Model-based covariance (inverse information) |
|
|
132
|
+
| `hazard_ratios_` via `.hazard_ratios()` | `exp(coef_)` |
|
|
133
|
+
|
|
134
|
+
#### `.check_proportionality(tf=None, feature_names=None)`
|
|
135
|
+
|
|
136
|
+
Tests the proportional subdistribution hazards assumption. Returns a DataFrame
|
|
137
|
+
with columns `variable`, `rho`, `chisq`, `df`, `p`. Uses Schoenfeld-type
|
|
138
|
+
residuals correlated with event time (or `tf(time)` if provided).
|
|
139
|
+
|
|
140
|
+
#### `.predict_cif(X_new, times=None, cov2_new=None)`
|
|
141
|
+
|
|
142
|
+
Returns predicted CIF as `(n_new, len(times))` array.
|
|
143
|
+
|
|
144
|
+
#### `.summary(feature_names=None, robust=False)`
|
|
145
|
+
|
|
146
|
+
Prints a formatted regression table. Set `robust=True` to use robust SEs.
|
|
147
|
+
|
|
148
|
+
---
|
|
149
|
+
|
|
150
|
+
### `AalenJohansen()`
|
|
151
|
+
|
|
152
|
+
Non-parametric CIF estimator with log-log confidence intervals.
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
aj = AalenJohansen().fit(Surv(time, event))
|
|
156
|
+
t_grid, cif = aj.predict(cause=1)
|
|
157
|
+
lo, hi = aj.confidence_intervals(cause=1)
|
|
158
|
+
aj.summary()
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
---
|
|
162
|
+
|
|
163
|
+
### `gray_test(time, event, group, cause=1, rho=0)`
|
|
164
|
+
|
|
165
|
+
Gray's K-sample test for equality of CIFs across groups.
|
|
166
|
+
|
|
167
|
+
```python
|
|
168
|
+
from pycrr.compare import gray_test
|
|
169
|
+
|
|
170
|
+
result = gray_test(Surv(time, event), group)
|
|
171
|
+
result.summary()
|
|
172
|
+
# Gray's test — chi-squared = 5.12, df = 1, p = 0.024
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
---
|
|
176
|
+
|
|
177
|
+
### Metrics
|
|
178
|
+
|
|
179
|
+
```python
|
|
180
|
+
from pycrr.metrics import brier_score, integrated_brier_score, concordance
|
|
181
|
+
|
|
182
|
+
bs = brier_score(model, X_test, time_test, event_test, t=5.0)
|
|
183
|
+
ibs = integrated_brier_score(model, X_test, time_test, event_test,
|
|
184
|
+
times=np.linspace(0.5, 8, 50))
|
|
185
|
+
c = concordance(model, X_test, time_test, event_test)
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
---
|
|
189
|
+
|
|
190
|
+
## Validation
|
|
191
|
+
|
|
192
|
+
`pycrr` was validated against `cmprsk::crr` (R 4.5.0, v2.2-12) on:
|
|
193
|
+
|
|
194
|
+
**Synthetic dataset** (`n=500`, generated with `set.seed(42)` in R):
|
|
195
|
+
|
|
196
|
+
| Output | Max \|diff vs R\| |
|
|
197
|
+
|--------|-------------------|
|
|
198
|
+
| Coefficients | 2 × 10⁻⁶ |
|
|
199
|
+
| Model-based SE | 2 × 10⁻⁶ |
|
|
200
|
+
| Robust SE | 5 × 10⁻⁵ |
|
|
201
|
+
| Full 2×2 robust cov matrix | 1 × 10⁻⁴ |
|
|
202
|
+
|
|
203
|
+
**MGUS2** (`n=1,384`, from the R `survival` package, real clinical data):
|
|
204
|
+
|
|
205
|
+
| Output | Max \|diff vs R\| |
|
|
206
|
+
|--------|-------------------|
|
|
207
|
+
| Coefficients | 3 × 10⁻⁵ |
|
|
208
|
+
| Model-based SE | 3 × 10⁻⁵ |
|
|
209
|
+
| Robust SE | 2 × 10⁻⁵ |
|
|
210
|
+
| Full 2×2 robust cov matrix | 1 × 10⁻⁴ |
|
|
211
|
+
|
|
212
|
+
Score residuals satisfy $\sum_i U_i = 0$ to $10^{-11}$ and reconstruct the
|
|
213
|
+
robust covariance matrix exactly. The proportionality test detects crossing
|
|
214
|
+
subdistribution hazards (Schoenfeld ρ ≈ −0.65, p < 10⁻⁴) and correctly finds
|
|
215
|
+
no violation on proportional data. Full validation scripts are in `examples/`.
|
|
216
|
+
|
|
217
|
+
---
|
|
218
|
+
|
|
219
|
+
## Related packages
|
|
220
|
+
|
|
221
|
+
`pycrr` focuses on inference and diagnostics. Other Python competing-risks
|
|
222
|
+
packages take different approaches:
|
|
223
|
+
|
|
224
|
+
| Package | Focus |
|
|
225
|
+
|---------|-------|
|
|
226
|
+
| `comprisk` | Fine-Gray + penalized FG + cause-specific Cox + competing-risks forest + sklearn API |
|
|
227
|
+
| `pycmprsk` | Systematic port of R `cmprsk`, including censoring strata |
|
|
228
|
+
| `CompRiskReg` | Translation of R `cmprsk` with `cov2`/`tf` interface |
|
|
229
|
+
| `lifelines` | Broad survival analysis; Aalen-Johansen but not Fine-Gray |
|
|
230
|
+
| `scikit-survival` | ML-focused survival; non-parametric CIF only |
|
|
231
|
+
|
|
232
|
+
`pycrr`'s distinct focus is the **diagnostic layer**: score residuals whose
|
|
233
|
+
estimating equations balance, exact sandwich covariance reconstruction, and a
|
|
234
|
+
proportional subdistribution hazards test with both negative- and
|
|
235
|
+
positive-control validation.
|
|
236
|
+
|
|
237
|
+
---
|
|
238
|
+
|
|
239
|
+
## Background
|
|
240
|
+
|
|
241
|
+
Fine & Gray (1999) model the subdistribution hazard:
|
|
242
|
+
|
|
243
|
+
$$\lambda_1(t \mid x) = \lambda_{10}(t) \exp(\beta^\top x)$$
|
|
244
|
+
|
|
245
|
+
Subjects who experienced a competing event remain in the risk set with
|
|
246
|
+
time-varying weight $G(t^-)/G(T_i^-) \le 1$, where $G$ is the Kaplan-Meier
|
|
247
|
+
censoring survival function. `pycrr` implements this with a Breslow tie
|
|
248
|
+
correction (matching `cmprsk::crr`) and L-BFGS-B optimization with analytically
|
|
249
|
+
derived gradients.
|
|
250
|
+
|
|
251
|
+
---
|
|
252
|
+
|
|
253
|
+
## Best practices
|
|
254
|
+
|
|
255
|
+
- **Standardize covariates** when scales differ. R's `crr` uses Newton-Raphson
|
|
256
|
+
(scale-invariant); `pycrr` uses L-BFGS-B which can be slow on poorly scaled
|
|
257
|
+
inputs.
|
|
258
|
+
- **Use `Surv(time, event)`** to bundle outcomes and avoid argument order errors.
|
|
259
|
+
- **Check proportionality** before interpreting coefficients as time-constant.
|
|
260
|
+
|
|
261
|
+
---
|
|
262
|
+
|
|
263
|
+
## Running tests
|
|
264
|
+
|
|
265
|
+
```bash
|
|
266
|
+
pytest # 235 tests across 4 files
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
---
|
|
270
|
+
|
|
271
|
+
## License
|
|
272
|
+
|
|
273
|
+
MIT
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from pycrr.surv import Surv
|
|
2
|
+
from pycrr.model import FineGrayModel
|
|
3
|
+
from pycrr.core import estimate_ipcw_weights
|
|
4
|
+
from pycrr.estimator import AalenJohansen
|
|
5
|
+
from pycrr.compare import gray_test, GrayTestResult
|
|
6
|
+
from pycrr.metrics import brier_score, integrated_brier_score, concordance
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"Surv",
|
|
10
|
+
"FineGrayModel",
|
|
11
|
+
"estimate_ipcw_weights",
|
|
12
|
+
"AalenJohansen",
|
|
13
|
+
"gray_test",
|
|
14
|
+
"GrayTestResult",
|
|
15
|
+
"brier_score",
|
|
16
|
+
"integrated_brier_score",
|
|
17
|
+
"concordance",
|
|
18
|
+
]
|
|
19
|
+
__version__ = "0.1.0"
|