Metadata-Version: 2.4
Name: nonconform
Version: 1.0.0
Summary: Conformal Anomaly Detection
Project-URL: Homepage, https://github.com/OliverHennhoefer/nonconform
Project-URL: Documentation, https://oliverhennhoefer.github.io/nonconform/
Project-URL: Bugs, https://github.com/OliverHennhoefer/nonconform/issues
Author-email: Oliver Hennhoefer <oliver.hennhoefer@mail.de>
Maintainer-email: Oliver Hennhoefer <oliver.hennhoefer@mail.de>
License: BSD 3-Clause License
        
        Copyright (c) 2024, Oliver Hennhöfer
        
        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.
License-File: LICENSE
Keywords: anomaly detection,conformal anomaly detection,conformal inference,false discovery rate,uncertainty quantification
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: BSD License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Requires-Python: >=3.12
Requires-Dist: numpy>=2.2.0
Requires-Dist: pandas>=2.2.1
Requires-Dist: scikit-learn>=1.5.2
Requires-Dist: scipy>=1.13.0
Requires-Dist: tqdm>=4.66.2
Provides-Extra: all
Requires-Dist: kdepy>=1.1.12; extra == 'all'
Requires-Dist: oddball>=1.3.0; extra == 'all'
Requires-Dist: online-fdr>=0.0.3; extra == 'all'
Requires-Dist: optuna>=4.5.0; extra == 'all'
Requires-Dist: pyarrow>=16.1.0; extra == 'all'
Requires-Dist: pyod==2.0.7; extra == 'all'
Provides-Extra: data
Requires-Dist: oddball>=1.3.0; extra == 'data'
Requires-Dist: pyarrow>=16.1.0; extra == 'data'
Provides-Extra: fdr
Requires-Dist: online-fdr>=0.0.3; extra == 'fdr'
Provides-Extra: probabilistic
Requires-Dist: kdepy>=1.1.12; extra == 'probabilistic'
Requires-Dist: optuna>=4.5.0; extra == 'probabilistic'
Provides-Extra: pyod
Requires-Dist: pyod==2.0.7; extra == 'pyod'
Description-Content-Type: text/markdown

![Logo](https://raw.githubusercontent.com/OliverHennhoefer/nonconform/main/docs/img/banner_light.png)

---

![Python versions](https://img.shields.io/pypi/pyversions/nonconform.svg)
[![codecov](https://codecov.io/gh/OliverHennhoefer/nonconform/branch/main/graph/badge.svg?token=Z78HU3I26P)](https://codecov.io/gh/OliverHennhoefer/nonconform)
[![PyPI version](https://img.shields.io/pypi/v/nonconform.svg)](https://pypi.org/project/nonconform/)
[![Docs](https://github.com/OliverHennhoefer/nonconform/actions/workflows/docs.yml/badge.svg)](https://oliverhennhoefer.github.io/nonconform/)

## Conformal Anomaly Detection

Thresholds for anomaly detection are often arbitrary and lack theoretical guarantees. **nonconform** wraps anomaly detectors (from [PyOD](https://pyod.readthedocs.io/en/latest/), scikit-learn, or custom implementations) and transforms their raw anomaly scores into conformal *p*-values. Under the assumptions of the selected method, these p-values support controlled false discovery rate (FDR) workflows with explicit, assumption-dependent guarantees.

> **Note:** The methods in **nonconform** assume that training and test data are [*exchangeable*](https://en.wikipedia.org/wiki/Exchangeable_random_variables). The package is therefore not suited for spatial or temporal autocorrelation unless such dependencies are explicitly handled in preprocessing or model design.

**Guarantee scope:** nonconform calibrates detector scores; it does not make an
unsuitable detector or mismatched calibration set valid. Standard conformal
claims require exchangeability. Weighted workflows require plausible covariate
shift, support overlap, and reliable weights. FDR claims require valid p-values
and the relevant multiple-testing assumptions.

## Feature Overview

| Need | nonconform Functionality | Start Here |
| --- | --- | --- |
| Principled anomaly decisions | `ConformalDetector.select(...)` combines conformal *p*-values with FDR-controlled selection | [FDR Control](https://oliverhennhoefer.github.io/nonconform/user_guide/fdr_control/) |
| Flexible calibration strategies | `Split`, `CrossValidation`, and `JackknifeBootstrap` for different data/compute tradeoffs | [Conformalization Strategies](https://oliverhennhoefer.github.io/nonconform/user_guide/conformalization_strategies/) |
| Covariate-shift aware workflows | Weighted conformal prediction with density-ratio estimators and weighted FDR control (requires sufficient calibration/test support overlap) | [Weighted Conformal](https://oliverhennhoefer.github.io/nonconform/user_guide/weighted_conformal/) |
| Rich p-value estimation | Empirical, probabilistic KDE, and conditional calibration estimators | [Common Workflows](https://oliverhennhoefer.github.io/nonconform/api/common_workflows/) |
| Sequential monitoring | Exchangeability martingales (`PowerMartingale`, `SimpleMixtureMartingale`, `SimpleJumperMartingale`) | [Exchangeability Martingales](https://oliverhennhoefer.github.io/nonconform/user_guide/exchangeability_martingales/) |
| Custom detector integration | Support for protocol-compliant detectors (with strict-inductive caveats for blocked PyOD models) | [Detector Compatibility](https://oliverhennhoefer.github.io/nonconform/user_guide/detector_compatibility/) |

## Citation

If you use **nonconform** in academic work, reports, or other published
material, please cite the accompanying paper:

```bibtex
@misc{hennhöfer2026conformalanomalydetectionpython,
      title={Conformal Anomaly Detection in Python: Moving Beyond Heuristic Thresholds with 'nonconform'},
      author={Oliver Hennhöfer and Maximilian Kirsch and Christine Preisach},
      year={2026},
      eprint={2605.13642},
      archivePrefix={arXiv},
      primaryClass={stat.ML},
      url={https://arxiv.org/abs/2605.13642},
}
```

## Getting Started

Installation via [PyPI](https://pypi.org/project/nonconform/):

```sh
pip install nonconform
```

> **Note:** The example below uses an external dataset API. Install with `pip install oddball` or `pip install "nonconform[data]"`.

### Classical Conformal Workflow

**Example:** Isolation Forest on the Shuttle benchmark. This trains a base detector, calibrates conformal scores, then applies FDR-controlled selection through `select(...)`. Raw *p*-values remain available via `detector.last_result.p_values`.

```python
from pyod.models.iforest import IForest

from nonconform import ConformalDetector, Split
from nonconform.metrics import false_discovery_rate, statistical_power
from oddball import Dataset, load

x_train, x_test, y_test = load(Dataset.SHUTTLE, setup=True, seed=42)

detector = ConformalDetector(
    detector=IForest(),
    strategy=Split(n_calib=1_000),
    seed=42,
)
detector.fit(x_train)

decisions = detector.select(x_test, alpha=0.2)

print(f"Empirical FDR: {false_discovery_rate(y_test, decisions)}")
print(f"Statistical Power: {statistical_power(y_test, decisions)}")
```

Output:

```text
Empirical FDR: 0.18
Statistical Power: 0.99
```

## Advanced Methods

nonconform includes advanced workflows for practitioners who need more power or robustness:

- **Probabilistic Conformal Estimation** (`Probabilistic`): uses KDE-based modeling of calibration scores to produce continuous *p*-values instead of purely empirical stepwise values.
- **Weighted Conformal Prediction** (`weight_estimator=...`): reweights calibration evidence for covariate shift settings where test and calibration distributions differ, assuming enough support overlap between calibration and test features.
- **Exchangeability Martingales** (`nonconform.martingales`): sequential evidence monitoring over conformal *p*-value streams.

Probabilistic Conformal Setup:

```python
from pyod.models.iforest import IForest

from nonconform import ConformalDetector, Probabilistic, Split

detector = ConformalDetector(
    detector=IForest(),
    strategy=Split(n_calib=1_000),
    estimation=Probabilistic(n_trials=10),
    seed=42,
)
```

Weighted Conformal Setup:

```python
from pyod.models.iforest import IForest

from nonconform import ConformalDetector, Split, logistic_weight_estimator

detector = ConformalDetector(
    detector=IForest(),
    strategy=Split(n_calib=1_000),
    weight_estimator=logistic_weight_estimator(),
    seed=42,
)
```

> **Note:** In weighted mode, `ConformalDetector.select(...)` dispatches weighted FDR control automatically.

Martingale Setup for Sequential Monitoring:

```python
from nonconform.martingales import AlarmConfig, PowerMartingale

alpha = 0.01
martingale = PowerMartingale(
    epsilon=0.5,
    alarm_config=AlarmConfig(
        ville_threshold=1 / alpha,
        restarted_ville_threshold=1 / alpha,
    ),
)

state = martingale.update(p_t)
states = martingale.update_many(p_values_chunk)
```

> **Note:** `update(...)` already validates and normalizes numeric scalar p-values, so an explicit `float(...)` cast is optional.
> Use `ville_threshold` or `restarted_ville_threshold` when you need an anytime
> false-alarm bound for a monitored stream. CUSUM and Shiryaev-Roberts thresholds
> are change-evidence triggers for diagnosing possible stream changes; they need
> separate calibration and do not replace cross-hypothesis FDR control. See
> [Exchangeability Martingales](https://oliverhennhoefer.github.io/nonconform/user_guide/exchangeability_martingales/)
> for threshold interpretation details.

## Beyond Static Data

While primarily designed for static (single-batch) workflows, optional `onlinefdr` integration supports [streaming FDR procedures](https://oliverhennhoefer.github.io/nonconform/user_guide/streaming_evaluation/).

## Custom Detectors

Any detector implementing the [`AnomalyDetector`](https://oliverhennhoefer.github.io/nonconform/api/#nonconform.structures.AnomalyDetector) protocol can be integrated with nonconform:

```python
from typing import Self

import numpy as np

class MyDetector:
    def fit(self, X, y=None) -> Self: ...
    def decision_function(self, X) -> np.ndarray: ...  # higher = more anomalous
    def get_params(self, deep=True) -> dict: ...
    def set_params(self, **params) -> Self: ...
```

For custom detectors, either set `score_polarity` explicitly (`"higher_is_anomalous"` in most cases), or omit it to use the default score-polarity policy. Use `score_polarity="auto"` only when you want strict detector-family validation.

For strict inductive conformal/FDR pipelines, avoid batch-adaptive PyOD
detectors with non-frozen score maps (for example `ECOD` and `COPOD`, which are
blocked at runtime).

See [Detector Compatibility](https://oliverhennhoefer.github.io/nonconform/user_guide/detector_compatibility/) for details and examples.

## Optional Dependencies

_For additional features, you might need optional dependencies:_

- `pip install nonconform[pyod]` - Includes PyOD anomaly detection library
- `pip install nonconform[data]` - Includes oddball for loading benchmark datasets
- `pip install nonconform[fdr]` - Includes advanced FDR control methods (online-fdr)
- `pip install nonconform[probabilistic]` - Includes KDEpy and Optuna for probabilistic estimation/tuning
- `pip install nonconform[all]` - Includes all optional dependencies

_Please refer to the [pyproject.toml](https://github.com/OliverHennhoefer/nonconform/blob/main/pyproject.toml) for details._

## Contact

**Bug reporting:** [https://github.com/OliverHennhoefer/nonconform/issues](https://github.com/OliverHennhoefer/nonconform/issues)

---
