Metadata-Version: 2.4
Name: confetti-ts
Version: 1.0.1
Classifier: Development Status :: 5 - Production/Stable
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Dist: numpy>=2.3
Requires-Dist: pandas>=2.2.3
Requires-Dist: joblib>=1.2
Requires-Dist: scikit-learn>=1.7.2
Requires-Dist: matplotlib>=3.8
Requires-Dist: keras>=3.12.0 ; extra == 'all'
Requires-Dist: tensorflow>=2.20.0 ; extra == 'all'
Requires-Dist: torch>=2.0 ; extra == 'all'
Requires-Dist: keras>=3.12.0 ; extra == 'keras'
Requires-Dist: tensorflow>=2.20.0 ; extra == 'keras'
Requires-Dist: torch>=2.0 ; extra == 'torch'
Provides-Extra: all
Provides-Extra: keras
Provides-Extra: torch
License-File: LICENSE
Summary: A multi-objective counterfactual explanation method for time series classifiers.
Keywords: counterfactual explanations,time series,multi-objective optimization,deep learning
Author-email: Alan Paredes Cetina <alan.paredes@uni.lu>, Raoni Lourenco <raoni.lourenco@uni.lu>
License-Expression: MIT
Requires-Python: >=3.12
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Documentation, https://confetti-ts.readthedocs.io/en/latest/index.html
Project-URL: Homepage, https://github.com/serval-uni-lu/confetti
Project-URL: Issues, https://github.com/serval-uni-lu/confetti/issues
Project-URL: Repository, https://github.com/serval-uni-lu/confetti

<p align="center">
<!-- PyPi Version -->
  <a href="https://pypi.org/project/confetti-ts/">
    <img src="https://img.shields.io/pypi/v/confetti-ts?logo=pypi&logoColor=white" alt="PyPI Version">
  </a>
  
  <!-- Python Versions -->
  <a href="https://pypi.org/project/confetti-ts/">
    <img src="https://img.shields.io/pypi/pyversions/confetti-ts?logo=python&logoColor=white" alt="Python Versions">
  </a>
  
  <!-- Wheel -->
  <img src="https://img.shields.io/pypi/wheel/confetti-ts" alt="Wheel">
  
  <!-- Build Status -->
  <a href="https://github.com/serval-uni-lu/confetti/actions">
    <img src="https://img.shields.io/github/actions/workflow/status/serval-uni-lu/confetti/ci.yml?label=CI&logo=github" alt="CI Status">
  </a>
  
  <!-- Documentation -->
  <a href="https://confetti-ts.readthedocs.io/en/latest/">
    <img src="https://img.shields.io/readthedocs/confetti-ts?logo=readthedocs" alt="Documentation Status">
  </a>
  
  <!-- License -->
  <a href="https://github.com/serval-uni-lu/confetti/blob/main/LICENSE">
    <img src="https://img.shields.io/github/license/serval-uni-lu/confetti?color=4E65FF" alt="License">
  </a>

</p>

![CONFETTI Logo](https://raw.githubusercontent.com/serval-uni-lu/confetti/main/docs/artwork/confetti-logo.png)

---
# Counterfactual Explanations for Time Series



**CONFETTI** is a multi-objective method for generating **counterfactual explanations** for **multivariate time series** classifiers.
It identifies the most influential features or temporal regions, constructs a minimal perturbation, and optimizes it under multiple objectives to produce **sparse**, **realistic**, and **confidence-increasing** counterfactuals.

CONFETTI is model-agnostic and works with **any classifier** — Keras, PyTorch, or scikit-learn.

--- 
## ✨ Highlights

* Multi-objective optimization using **NSGA-III**
* **Time series**: works with any Torch/Keras/scikit-learn multivariate time series classifier
* **Rust-accelerated** backend for distances and NSGA-III
* Optional use of **class activation maps** for feature-weighted perturbations
* Built-in distance metrics: Euclidean, Manhattan, DTW, Soft-DTW, GAK, CTW
* Generates multiple diverse counterfactuals per instance
* Parallelized counterfactual generation

---
## 🚀 Installation

### PyPI Installation
```bash
pip install confetti-ts
```
Pre-built wheels are available for common platforms. If no wheel is available for your system, the install requires a [Rust toolchain](https://rustup.rs/).

### Development Installation
```bash
git clone https://github.com/serval-uni-lu/confetti.git
cd confetti

uv venv
source .venv/bin/activate
uv pip install -e .
```

Core dependencies:

* Python 3.12+
* NumPy, pandas, scikit-learn, joblib, matplotlib

Optional (model backends):

* Keras 3.x + TensorFlow (`pip install confetti-ts[keras]`)
* PyTorch (`pip install confetti-ts[torch]`)
* All backends (`pip install confetti-ts[all]`)

---

## ⚡ Quick Example — Time Series

Below is a minimal end-to-end example for multivariate time series counterfactuals.
It loads a trained model, prepares a dataset, and generates counterfactuals for a single instance.

> The example files are included in the repository under `examples/`.
> Clone it first with `git clone https://github.com/serval-uni-lu/confetti.git`.

```python
from confetti import CONFETTI
from confetti.attribution import cam
from confetti.utils import load_multivariate_ts_from_csv
from confetti.visualizations import plot_counterfactual
import keras

# Load model
model_path = "examples/models/toy_fcn.keras"
model = keras.models.load_model(model_path)

# Load dataset in (n_samples, time_steps, n_features) format
X_train, y_train = load_multivariate_ts_from_csv("examples/data/toy_train.csv")
X_test, y_test   = load_multivariate_ts_from_csv("examples/data/toy_test.csv")

# Select instance to explain
instance = X_test[0:1]

# Generate CAM weights for training data (optional)
training_weights = cam(model, X_train)

# Initialize explainer
explainer = CONFETTI(model_path=model_path)

# Generate counterfactuals
results = explainer.generate_counterfactuals(
    instances_to_explain=instance,
    reference_data=X_train,
    reference_weights=training_weights,      # or None if not available
)

# results is a CounterfactualResults list — one CounterfactualSet per instance.
# Each set contains the original instance, the best counterfactual, all
# candidates, and the NUN's CAM feature-importance weights (when provided).
cf_set = results[0]

# Visualize the best counterfactual
plot_counterfactual(
    original=cf_set.original_instance,
    counterfactual=cf_set.best,
    cam_weights=cf_set.feature_importance,
    cam_mode="heatmap",
    title="Counterfactual Explanation"
)
```

![Counterfactual Example](https://raw.githubusercontent.com/serval-uni-lu/confetti/main/docs/artwork/counterfactual_example.png)

In the visualization:

* green curves represent the original instance
* red curves represent the counterfactual subsequence
* the heatmap corresponds to CAM scores of the nearest unlike neighbor

---
## 🆕 What's New in v1.0.1

* **Stable release** — production-ready API with no breaking changes expected
* **Rust-accelerated backend** — distances (DTW, Soft-DTW, GAK, Manhattan) and NSGA-III components via PyO3
* **Custom NSGA-III** — zero-dependency genetic algorithm (pymoo removed)
* **Built-in distance metrics** — pure-numpy DTW, Soft-DTW, GAK, CTW, Manhattan (tslearn removed)
* **PyTorch adapter** — use PyTorch models alongside Keras and scikit-learn
* **Visualization theming** — light/dark theme support with improved plot aesthetics

See the full [CHANGELOG](CHANGELOG.md) for details.

---
## 📚 Documentation

The full documentation, including usage guides, API reference, and examples, is available at:

👉 **https://confetti-ts.readthedocs.io/en/latest/**

---
## 📄 License

CONFETTI is released under the [MIT License](LICENSE). 

---
## 📝 Citing CONFETTI
If you use CONFETTI in your research, please consider citing the following paper:

```
@inproceedings{cetina2026counterfactual,
  title={Counterfactual Explainable AI (XAI) Method for Deep Learning-Based Multivariate Time Series Classification},
  author={Cetina, Alan Gabriel Paredes and Benguessoum, Kaouther and Lourenco, Raoni and Kubler, Sylvain},
  booktitle={Proceedings of the AAAI Conference on Artificial Intelligence},
  volume={40},
  number={21},
  pages={17393--17400},
  year={2026}
}
```

The original code used when the method was published is at the **`paper` branch** of this
repository. It contains the experiment scripts, model configurations, and dataset handling
used in the publication.

