Metadata-Version: 2.4
Name: rattus
Version: 0.3.1
Summary: Tree-based methods for Heterogeneous Treatment Effects
License: Copyright (c) 2026 hadjipantelis. 
        
        Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
        
        1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
        
        2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
        
        3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
        
        THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=2.1.0
Requires-Dist: scipy>=1.16
Requires-Dist: joblib>=1.3.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: graphviz>=0.20.1; extra == "dev"
Dynamic: license-file

# rattus

**Honest causal trees for heterogeneous treatment effects.**

`rattus` implements tree-based estimators for heterogeneous treatment effects, combining two complementary ideas from the literature:

- **Honest estimation** (Athey & Imbens, 2016): the sample is split so that the tree structure and the leaf-level treatment effect estimates are never computed on the same data. This eliminates the adaptive bias that makes confidence intervals from standard regression trees invalid, and delivers nominal coverage without sparsity assumptions.

- **Significance-based splitting** (Radcliffe & Surry, 2011): each candidate split is scored by the squared t-statistic on the treatment × side interaction term. This directly tests whether uplift differs across the two child nodes, rather than testing goodness-of-fit on outcomes — which can split on covariates that predict the outcome level but not the treatment effect.

The combination is, to the authors' knowledge, not available in existing open-source packages.

---

## Key Features

- **Honest confidence intervals** with valid coverage via sample splitting and Welch–Satterthwaite small-sample correction
- **Significance-based splitting** targeting treatment-effect heterogeneity (not outcome prediction)
- **Honest cross-validation pruning** to prevent overfitting
- **Multi-arm (MV) support** for K ≥ 2 treatment arms with contrast-specific estimation
- **Contrast types**: "dummy" (Arm k vs Control) and "sequential" (Arm k vs Arm k-1)
- **Categorical feature support** with empirical CATE ranking and ordered partitions
- **Native missing value handling** — NaN routing direction learned during training
- **GUIDE $G_I$ interaction framework** for unbiased variable selection (Loh et al., 2015)
- **Bagged forest ensemble** with infinitesimal jackknife variance estimation
- **Parallel tree fitting** via joblib with reproducible results across `n_jobs` values
- **Subsampling without replacement** for honest causal forests (Wager & Athey, 2018)
- **sklearn-compatible API**: `fit`, `predict`, `predict_interval`, `score`, `get_leaf_summary`
- **Export**: text summary (`to_text`) and Graphviz visualization (`to_graphviz`)

---

## When to use rattus

- You need **heterogeneous treatment effect** estimates (e.g., uplift modelling, personalized medicine, targeted policy)
- You require **valid confidence intervals** without sparsity assumptions
- Your features include **categorical variables** and/or **missing values**
- You want an **interpretable** model that shows exactly which subpopulations respond differently to treatment

---

## Quick Start

```bash
# Install from source
git clone https://codeberg.org/hadjipantelis/rattus.git
cd rattus
pip install -e .
```

```python
import numpy as np
from rattus import HonestSignificanceTree, HonestSignificanceForest

# Simulate data: true CATE = 0.5 * X[:, 0]
rng = np.random.default_rng(0)
n = 2000
X = rng.standard_normal((n, 5))
W = rng.binomial(1, 0.5, n)
y = 0.5 * (X[:, 0] + X[:, 1]) + 0.5 * (2 * W - 1) * (0.5 * X[:, 0]) + rng.normal(0, 0.1, n)

# Single honest causal tree (binary treatment)
tree = HonestSignificanceTree(
    max_depth=4,
    min_samples_leaf=30,
    alpha=1.0,
    use_honest_cv=True,
    random_state=0,
).fit(X, y, W)

tau_hat = tree.predict(X)          # estimated CATE, shape (n,)
ci = tree.predict_interval(X)      # 90% confidence intervals, shape (n, 2)

# Leaf-level summary
for leaf in tree.get_leaf_summary():
    print(f"tau={leaf['tau_hat']:+.3f}  "
          f"95%CI=[{leaf['ci_lower']:+.3f}, {leaf['ci_upper']:+.3f}]  "
          f"n_t={leaf['n_treat']}  n_c={leaf['n_control']}")

# Text summary (no extra dependencies)
print(tree.to_text(feature_names=[f"x{i}" for i in range(5)]))

# Bagged forest with parallel fitting
forest = HonestSignificanceForest(
    n_estimators=100,
    max_features="sqrt",
    max_depth=4,
    min_samples_leaf=30,
    alpha=1.0,
    use_honest_cv=True,
    n_jobs=-1,
    random_state=0,
).fit(X, y, W)

tau_forest = forest.predict(X)
```

---

## Documentation

| Document | Description |
|---|---|
| **[Getting Started](https://codeberg.org/hadjipantelis/rattus/src/branch/main/docs/guides/getting-started.md)** | Installation, first tree, key concepts, interpreting results |
| **[Advanced Usage](https://codeberg.org/hadjipantelis/rattus/src/branch/main/docs/guides/advanced-usage.md)** | Multi-arm, categorical features, missing values, observational data, GUIDE G_I, performance tips |
| **[API Reference](https://codeberg.org/hadjipantelis/rattus/src/branch/main/docs/api.md)** | Complete parameter and method documentation for `HonestSignificanceTree` and `HonestSignificanceForest` |
| **[FAQ](https://codeberg.org/hadjipantelis/rattus/src/branch/main/docs/faq.md)** | Common questions, troubleshooting, design decisions |

---

## Core Concepts

### Honest Estimation

Standard regression trees use the same data to choose splits *and* estimate leaf values, creating adaptive bias. `rattus` uses **sample splitting**:
- **Training half** (50%): Grows the tree structure
- **Estimation half** (50%): Estimates treatment effects in each leaf

Because the partition and estimates are independent, confidence intervals have **valid coverage** without sparsity assumptions.

### Significance-Based Splitting

Instead of minimizing outcome prediction error, `rattus` splits to maximize the **t-statistic on the treatment × side interaction**, directly testing whether the treatment effect differs between child nodes.

---

## Citation

If you use `rattus` in your research, please cite:

> **Significance-First Splitting: Aligning Treatment Heterogeneity Detection with Honest Estimation**  
> Pantelis Z. Hadjipantelis, Weng Man Chiang, Karthik Nagesh

### References

- Athey, S. & Imbens, G. (2016). Recursive partitioning for heterogeneous causal effects. *PNAS*, 113(27), 7353–7360.
- Radcliffe, N. J. & Surry, P. D. (2011). Real-world uplift modelling with significance-based uplift trees. *Stochastic Solutions White Paper* TR-2011-1.
- Loh, W.-Y., He, X. & Man, M. (2015). A regression tree approach to identifying subgroups with differential treatment effects. *Statist. Med.*, 34, 1818–1833.

---

## License

BSD 3-Clause. Copyright © 2026 hadjipantelis. See [LICENSE](LICENSE) for details.
