Metadata-Version: 2.4
Name: cctimeboost
Version: 0.1.0
Summary: Continuous-time boosted trees with time-varying Cox-style relative risk (nested case-control boosting).
Author: Rahul Goswami
Maintainer-email: Rahul Goswami <rahul@statml.in>
License-Expression: MIT
Project-URL: Homepage, https://cctimeboost.statml.in/
Project-URL: Documentation, https://cctimeboost.statml.in/
Project-URL: Repository, https://github.com/yuvrajiro/cctimeboost
Project-URL: Issues, https://github.com/yuvrajiro/cctimeboost/issues
Project-URL: Changelog, https://github.com/yuvrajiro/cctimeboost/blob/main/CHANGELOG.md
Keywords: survival analysis,gradient boosting,time-varying effects,nested case-control,xgboost,catboost
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: OS Independent
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Intended Audience :: Science/Research
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.21
Requires-Dist: scipy>=1.8
Requires-Dist: scikit-learn>=1.0
Requires-Dist: pandas>=1.3
Requires-Dist: xgboost>=2.0
Requires-Dist: joblib>=1.0
Provides-Extra: catboost
Requires-Dist: catboost>=1.2; extra == "catboost"
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: catboost>=1.2; extra == "dev"
Provides-Extra: docs
Requires-Dist: sphinx>=7; extra == "docs"
Requires-Dist: furo; extra == "docs"
Requires-Dist: myst-parser; extra == "docs"
Requires-Dist: matplotlib; extra == "docs"
Dynamic: license-file

# CCTimeBoost

**Continuous-time boosted trees with a time-varying Cox-style relative risk.**

[Documentation](https://cctimeboost.statml.in/) · [Getting started](https://cctimeboost.statml.in/guide/getting-started.html) · [Source](https://github.com/yuvrajiro/cctimeboost) · [Changelog](https://github.com/yuvrajiro/cctimeboost/blob/main/CHANGELOG.md)

CCTimeBoost models the hazard as

    h(t | x) = h₀(t) · exp{ η(t, x) },

where η is a gradient-boosted tree ensemble on the augmented input (x, φ(t)), so covariate
effects may change over follow-up time. It is trained with a **sampled risk-set
grouped-softmax objective**, the exact conditional likelihood under nested case-control
sampling, which reduces to the Cox partial likelihood on full risk sets. A Breslow baseline
on full risk sets turns η into survival curves by integrating the time-varying risk.

- Two backbones: **XGBoost** and **CatBoost**
- **Categorical covariates** handled natively by both backbones
- A composable **`TimeFeatures`** library of time embeddings
- Exact time compression, GPU support, vectorised objective, batched prediction
- Time-resolved explanations from exact TreeSHAP
- Antolini C-index and integrated Brier score without the pycox / PyTorch stack

## Installation

```bash
pip install cctimeboost                  # XGBoost backbone
pip install "cctimeboost[catboost]"      # + CatBoost backbone
```

From a source checkout:

```bash
pip install -e ".[dev]"          # + tests
pip install -e ".[docs]"         # + documentation toolchain
```

## Quickstart

```python
from cctimeboost import CCTimeBoost

model = CCTimeBoost().fit(X_train, y_train)          # y: (n, 2) [duration, event]
times, S = model.predict_survival(X_test)            # S: (n_test, n_times)
model.score(X_test, y_test)                          # Antolini time-dependent C-index
```

Targets may be an `(n, 2)` array, a `(T, E)` tuple, a dict/DataFrame with `duration`/`time`
and `event`/`status`, or a scikit-survival structured array.

Prediction helpers: `predict_survival`, `predict_cumulative_hazard`, `predict_risk(X, t)`,
`predict_median_survival_time`, `predict_log_risk(X, times)`, `predict_survival_frame`
(pycox layout). Persistence: `model.save(path)`, `CCTimeBoost.load(path)`.

## Defaults

| component | default |
|---|---|
| backbone | XGBoost, Newton boosting with g = p − y, h = p(1 − p) |
| time features | φ(t) = [t, log(1 + t)] (`"default"`) |
| sampling | nested case-control, `n_controls=4`, with replacement |
| baseline | Breslow on full risk sets, all unique event times |
| survival | `survival_mode="exact"` — Λ(t\|x) = Σ_{t_k ≤ t} ΔĤ₀(t_k) exp η(x, t_k) |
| early stopping | `use_best_iteration=False` — predicts with all trained trees |
| device | `"auto"` — the GPU only when the job is large enough to benefit |

For results that are reproducible across machines, pass `device="cpu"`: GPU histogram
construction differs numerically, giving statistically equivalent but not identical models.

## Time features

```python
from cctimeboost import CCTimeBoost, TimeFeatures
from cctimeboost.time_features import Fourier, GaussianRBF, RestrictedCubicSpline

CCTimeBoost(time_features="default")                   # [t, log(1+t)]
CCTimeBoost(time_features="t_log1p+fourier")            # composition by "+"
CCTimeBoost(time_features=["default", GaussianRBF(6)])  # objects and names
CCTimeBoost(time_features=lambda t: t ** 0.5)           # any callable
TimeFeatures("rcs").fit(T).describe()
```

| family | transforms |
|---|---|
| monotone (single column) | `Identity`, `Log1p`, `Log(shift)`, `Sqrt`, `Power(p)`, `Reciprocal`, `MinMax`, `Standardize`, `ECDF`, `BoxCox`, `YeoJohnson` |
| polynomial | `Polynomial`, `Legendre`, `Chebyshev` |
| piecewise | `Step` (quantile bins), `CutPoints` (clinical landmarks), `Hinge`, `BSpline`, `RestrictedCubicSpline` |
| smooth local | `GaussianRBF`, `ExpDecay` |
| periodic | `Fourier` |
| custom | `FunctionTransform` |

Presets: `default`/`t_log1p`, `raw`, `poly`, `logshift`, `step`, `spline`, `fourier`. All
transforms are fitted on the training durations.

**Trees and monotone transforms.** Histogram tree learners bin by quantiles, which commute
with strictly monotone maps, so a monotone transform of t used *alone* yields the same splits
as raw t (tested). Non-monotone bases (Fourier, RBF, step, splines, hinges) change the
hypothesis space. `transform.is_monotone` / `TimeFeatures.is_monotone` make this visible.

## Categorical covariates

```python
df = pd.DataFrame({"age": ..., "site": ["A", "B", ...], "stage": pd.Categorical(...)})
CCTimeBoost(backbone="catboost").fit(df, y)        # category/object/string columns auto-detected
CCTimeBoost(cat_features=["site"]).fit(df, y)      # or name them (indices work for arrays)
```

Categories are encoded once as integer codes; XGBoost splits on them natively
(`feature_types`), CatBoost uses its target statistics. Missing and unseen categories are
treated as missing. On CatBoost's `exact` route, categorical splits are one-hot, because
that route's placeholder label cannot drive CatBoost's target statistics.

## Backbones

```python
CCTimeBoost(backbone="xgboost")                                   # default
CCTimeBoost(backbone="catboost")                                  # catboost_objective="native"
CCTimeBoost(backbone="catboost", catboost_objective="exact")      # diagonal-Hessian Newton step
CCTimeBoost(backbone="catboost", grow_policy="Depthwise")         # default SymmetricTree
```

| | XGBoost | CatBoost `native` | CatBoost `exact` |
|---|---|---|---|
| loss | grouped softmax | `QuerySoftMax` = same loss (verified 1e−15) | grouped softmax |
| gradient | p − y | identical | p − y |
| Newton leaf | −Σg / (Σh + λ) | CatBoost's own curvature | −Σg / (Σh + λ) (verified 1e−8) |
| GPU | yes | yes | yes (but slower than CPU) |
| categorical | native | native (target statistics) | one-hot |

The `exact` route fits each tree by weighted least squares to the Newton target z = −g/h
with weights h; see the [design notes](https://cctimeboost.statml.in/reference/design-notes.html) for why a CatBoost custom objective is
not used. Shared hyper-parameters are mapped per library; anything else goes in
`backbone_params={...}`.

## Speed and GPU

- Training cost is set by the sampled design (≈ events × (1 + m) rows), **independent of
  risk-set size**; controls are drawn in index space at cost O(events · m).
- **Time compression** (`compress_time=True`, exact): trees are piecewise constant in t, so
  grid times on the same side of every time-feature split share η, and η is evaluated once
  per such class instead of at every event time.
- `baseline_method="auto"` switches from the dense n × K Breslow to suffix sums over time
  classes when n·K is large, so `n_time_grid=None` stays feasible at large n.
- Predictions at chosen horizons (`predict_survival(X, times=...)`, `predict_risk`) are
  computed from time classes when n·K is large, without forming full curves.
- `device="auto"` uses the GPU only when the sampled design is big enough for it to win
  (`AUTO_GPU_MIN_ROWS`). CatBoost's exact route always runs on CPU under `"auto"`.
- Opt-in approximations: `fast_sampler=True` (vectorised sampler, different random draws)
  and `n_time_grid=G` (quantile grid for the baseline and prediction).

## Explanations

```python
model.time_attribution(X, n_times=20)          # φ̄_j(t) = mean_i |φ_ij(t)|
model.time_interaction_scores(X)               # TI_j, largest = most time-varying
```

Both use the backbone's exact TreeSHAP on (x, φ(t)) at fixed times. TI_j sums a covariate's
interactions with the time features, averaged over subjects and times. These are model
explanations, not causal effects.

## Other options

- `ties="efron"` — Efron correction in the baseline (equals Breslow without ties).
- `sampling_design="full"` — every group is the whole risk set (exact Cox partial likelihood).
- `eval_set=[(X_val, y_val)], early_stopping_rounds=k`; `use_best_iteration=True` predicts
  with trees up to the best iteration only.

## Experimental (not defaults; warn on use)

- `sampling_design="counter_matched" | "case_cohort" | "adaptive"` — weighted designs via
  log-weight offsets.
- `hessian="bohning"` — constant curvature ½, a valid majoriser of the softmax Hessian.
- `cctimeboost.experimental.recalibrate_slope` — η → bη chosen on a calibration split.

## Tests

```bash
pytest -q
```

## Documentation

The documentation is published at <https://cctimeboost.statml.in/>. To build it locally:

```bash
pip install -e ".[docs]"
python docs/_scripts/make_figures.py          # regenerate the landing-page figure
sphinx-build -W -b html docs docs/_build/html  # warnings are errors
```

Open `docs/_build/html/index.html`.

## Citation

If you use this software, please cite it as:

> Goswami, R. (2026). *CCTimeBoost: continuous-time boosted trees with a time-varying
> relative risk* Neurips, 2026. <https://cctimeboost.statml.in>

```bibtex
@software{goswami2026cctimeboost,
  author  = {Goswami, Rahul},
  title   = {{CCTimeBoost}: continuous-time boosted trees
             with a time-varying relative risk},
  year    = {2026},
  version = {0.1.0},
  url     = {https://cctimeboost.statml.in}
}
```

## License

MIT © 2026 Rahul Goswami
