Metadata-Version: 2.5
Name: robustmodels
Version: 0.5.0
Summary: Robust statistics for Python: covariance, PCA, regression, GLMs, rank methods, clustering, depth, density estimation and diagnostics.
Project-URL: Homepage, https://github.com/omarbecerrasierra/robustmodels
Project-URL: Documentation, https://omarbecerrasierra.github.io/robustmodels/
Project-URL: Repository, https://github.com/omarbecerrasierra/robustmodels
Project-URL: Issues, https://github.com/omarbecerrasierra/robustmodels/issues
Project-URL: Changelog, https://github.com/omarbecerrasierra/robustmodels/blob/main/CHANGELOG.md
Author: Omar Becerra Sierra
License-Expression: BSD-3-Clause
License-File: LICENSE
Keywords: Hodges-Lehmann,MCD,MM-estimator,MRCD,MVE,Mahalanobis distance,OGK,Qn,ROBPCA,S-estimator,Sn,Wilcoxon test,bagplot,bandwidth matrix,discriminant analysis,halfspace depth,highest density regions,kernel density estimation,log-concave density,medcouple,minimum covariance determinant,outlier detection,rank regression,robust PCA,robust clustering,robust covariance,robust generalized linear models,robust statistics,robustbase,score matching,tclust
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Scientific/Engineering :: Mathematics
Requires-Python: >=3.10
Requires-Dist: matplotlib>=3.7
Requires-Dist: numpy>=1.24
Requires-Dist: scikit-learn>=1.6
Requires-Dist: scipy>=1.10
Description-Content-Type: text/markdown

# robustmodels

**Robust statistics for Python, from individual measurements to multivariate data.**

[![PyPI version](https://img.shields.io/pypi/v/robustmodels)](https://pypi.org/project/robustmodels/)
[![Python versions](https://img.shields.io/pypi/pyversions/robustmodels)](https://pypi.org/project/robustmodels/)
[![CI](https://github.com/omarbecerrasierra/robustmodels/actions/workflows/ci.yml/badge.svg)](https://github.com/omarbecerrasierra/robustmodels/actions/workflows/ci.yml)
[![Coverage](https://codecov.io/gh/omarbecerrasierra/robustmodels/graph/badge.svg)](https://codecov.io/gh/omarbecerrasierra/robustmodels)
[![Installs (pip/uv, no mirrors or bots)](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fsql-clickhouse.clickhouse.com%2F%3Fuser%3Ddemo%26query%3DSELECT%2520count%2528%2529%2520AS%2520n%2520FROM%2520pypi.pypi%2520WHERE%2520project%253D%2527robustmodels%2527%2520AND%2520installer%2520IN%2520%2528%2527pip%2527%252C%2527uv%2527%252C%2527poetry%2527%252C%2527pdm%2527%2529%2520AND%2520ci%2520%2521%253D%2520%2527true%2527%2520AND%2520arrayMap%2528x%2520-%253E%2520toUInt32OrZero%2528x%2529%252C%2520splitByChar%2528%2527.%2527%252C%2520python_minor%2529%2529%2520%253E%253D%2520%255B3%252C%252010%255D%2520FORMAT%2520JSONEachRow&query=%24.n&label=installs&color=blue&cacheSeconds=86400)](https://clickpy.clickhouse.com/dashboard/robustmodels)
[![License: BSD 3-Clause](https://img.shields.io/badge/license-BSD%203--Clause-blue)](https://github.com/omarbecerrasierra/robustmodels/blob/main/LICENSE)
[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.24169655.svg)](https://doi.org/10.5281/zenodo.24169655)

[User guide](https://omarbecerrasierra.github.io/robustmodels/)
· [Method references](https://omarbecerrasierra.github.io/robustmodels/references.html)
· [Source code](https://github.com/omarbecerrasierra/robustmodels)
· [Report an issue](https://github.com/omarbecerrasierra/robustmodels/issues)

A few extreme observations can pull a mean away from the bulk of your data,
inflate a standard deviation, or distort a covariance matrix. **robustmodels**
brings established robust estimators into a consistent Python API so you can
compare summaries, estimate multivariate structure, and investigate unusual
observations.

- **Summarize a sample:** robust location, scale, skewness and tail-weight measures.
- **Model multivariate data:** eight location and covariance estimators, including
  regularized covariance for data with more variables than observations and
  Peña–Prieto (KSD) directions for many variables.
- **Reduce, classify and test:** robust principal components (ROBPCA and
  projection pursuit), linear and quadratic discriminant analysis, Hotelling's
  T² and one-way MANOVA.
- **Cluster with outliers present:** TCLUST and trimmed k-means.
- **Estimate densities:** multivariate kernel density estimation with a full
  bandwidth matrix (plug-in and smoothed cross-validation), density
  derivatives, highest density regions and a two-sample test; log-concave
  density estimation without a bandwidth.
- **Detect outliers:** Stahel-Donoho, adjusted and directional outlyingness;
  halfspace depth (exact in any dimension) and regression depth, Tukey medians
  and bagplots.
- **Fit robust regressions:** MM, S and least trimmed squares estimators,
  resistant to vertical outliers and bad leverage points; nonlinear Huber
  regression, rank-based (Wilcoxon) regression, regression by antitonic score
  matching (a convex loss estimated from the data) and robust logistic and
  Poisson generalized linear models.
- **Test with ties:** exact Wilcoxon rank-sum and signed-rank tests conditional
  on ties and zeros.
- **Publish the diagnostics:** regression and PCA outlier maps, residual and quantile plots,
  distance-distance plots, tolerance ellipses, biplots, scree plots,
  classification regions, adjusted boxplots, bagplots, outlyingness plots, highest density
  regions, log-concave densities and antitonic scores; and, for decisions, coefficient
  plots comparing robust and classical fits, depth-depth plots of two samples and
  trimmed likelihood curves for the number of clusters, with Matplotlib.
- **Work with familiar tools:** NumPy-compatible inputs and the scikit-learn
  estimator interface for covariance and regression models.
- **Inspect the methods:** documented formulas, scientific references, numerical
  conventions and executable examples.

## Installation

```bash
python -m pip install robustmodels
```

Requires **Python 3.10+**. NumPy, SciPy, scikit-learn and Matplotlib are installed as dependencies.
CI tests Python 3.10–3.15 on Linux, Windows and macOS.

## Start with one sample

Compare ordinary and robust summaries of a sample containing one extreme value:

```python
import numpy as np
from robustmodels import location, scale

x = [1, 2, 2, 3, 4, 100]

print(f"Mean:           {np.mean(x):.2f}")
print(f"Hodges–Lehmann:  {location.hodges_lehmann(x):.2f}")
print(f"Standard dev.:  {np.std(x, ddof=1):.2f}")
print(f"Qn scale:       {scale.qn(x):.2f}")
```

```text
Mean:           18.67
Hodges–Lehmann:  3.00
Standard dev.:  39.86
Qn scale:       1.36
```

The robust summaries remain close to the location and spread of the five values
between 1 and 4. Qn is calibrated to estimate the normal standard deviation and
includes a finite-sample correction by default.

You can also use `location.m_location(x)`, `scale.mad(x)` or
`scale.medcouple(x)` to estimate a robust center, scale or skewness. The
[location guide](https://omarbecerrasierra.github.io/robustmodels/location.html)
and [scale guide](https://omarbecerrasierra.github.io/robustmodels/scale.html)
explain their tuning and tradeoffs.

## Explore multivariate outliers

Fit a Minimum Covariance Determinant model and compute squared robust
Mahalanobis distances. This example adds a shift to ten observations:

```python
import numpy as np
from scipy.stats import chi2
from robustmodels.covariance import MCD

X = np.random.default_rng(0).normal(size=(100, 2))
X[:10] += 10

model = MCD(random_state=0).fit(X)
distances = model.mahalanobis(X)
cutoff = chi2.ppf(0.975, df=X.shape[1])

print("Robust center:", model.location_.round(2).tolist())
print("Rows to inspect:", np.flatnonzero(distances > cutoff).tolist())
```

```text
Robust center: [0.01, 0.1]
Rows to inspect: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 69]
```

The ten shifted observations are flagged, along with one unshifted observation
in the tail. Treat these as candidates for investigation. The chi-square cutoff
is a reference under a multivariate normal model, not an exact finite-sample
test or a guaranteed false-positive rate.

The fitted model exposes `location_`, `covariance_`, `precision_` and `support_`.
Use `mahalanobis(new_X)` to score new observations; it returns **squared**
distances. Covariance estimators support `get_params`, `set_params` and
`sklearn.base.clone`.

For skewed data, where a symmetric scale masks outliers on the short side,
use adjusted outlyingness:

```python
from robustmodels.outliers import AdjustedOutlyingness

X = np.random.default_rng(0).lognormal(size=(100, 2))
X[:5] = [-3, -3]  # five outliers on the short side
ao = AdjustedOutlyingness(random_state=0).fit(X)
print("Flagged:", np.flatnonzero(ao.predict(X) == -1).tolist())
```

```text
Flagged: [0, 1, 2, 3, 4]
```

See the [outlier detection guide](https://omarbecerrasierra.github.io/robustmodels/outliers.html).

## Fit a robust regression

Robust regression fits the bulk of the data when some responses are wrong.
Least trimmed squares also tells you which observations it used:

```python
import numpy as np
from robustmodels.regression import LTSRegressor

rng = np.random.default_rng(0)
X = rng.normal(size=(100, 1))
y = 1 + 2 * X[:, 0] + rng.normal(scale=0.5, size=100)
y[:20] += 15  # twenty outliers

lts = LTSRegressor(random_state=0).fit(X, y)
print(f"Intercept {lts.intercept_:.2f}, slope {lts.coef_[0]:.2f}")
print("Outliers used:", int(lts.support_[:20].sum()))
```

```text
Intercept 0.95, slope 2.04
Outliers used: 0
```

The true line is `1 + 2x`; least squares gives an intercept of 4.04 and a slope
of 1.17. `MMRegressor` combines a 50% breakdown
point with 95% efficiency under normal errors, and reports standard errors and
p-values with `summary()`. See the
[regression guide](https://omarbecerrasierra.github.io/robustmodels/regression.html)
to choose an estimator and detect outliers.

For nonlinear curves, use `NonlinearMRegressor(model, start)`; its
[guide](https://omarbecerrasierra.github.io/robustmodels/regression.html#nonlinear-robust-regression)
explains starting values and standard errors. Binary and Poisson responses have
[dedicated robust GLMs](https://omarbecerrasierra.github.io/robustmodels/glm.html).
The [depth guide](https://omarbecerrasierra.github.io/robustmodels/depth.html)
adds halfspace and regression depth, Tukey medians and a bagplot gallery, and the
[rank guide](https://omarbecerrasierra.github.io/robustmodels/rank.html) rank
regression and exact Wilcoxon tests with ties.

## Find robust principal components

Classical PCA follows the directions of largest variance, which a few outliers
can create. ROBPCA estimates the subspace of the bulk of the data and measures
how far each observation lies from it:

```python
import numpy as np
from robustmodels.multivariate import ROBPCA

rng = np.random.default_rng(0)
X = rng.normal(size=(100, 2)) @ rng.normal(size=(2, 20))  # a plane in 20-D
X += 0.1 * rng.normal(size=X.shape)
X[:10] += 5  # ten outliers away from the plane

pca = ROBPCA(random_state=0).fit(X)
print("Components:", pca.n_components_)
print("Rows to inspect:", np.flatnonzero(~pca.support_).tolist())
```

```text
Components: 2
Rows to inspect: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 40, 69, 70]
```

The fitted plane is within 0.1 degrees of the plane of the 90 regular rows;
classical PCA of all rows is 45 degrees away. The same module provides
`RobustLDA` and `RobustQDA` classifiers and the `hotelling_t2` and `manova`
tests. See the
[multivariate guide](https://omarbecerrasierra.github.io/robustmodels/multivariate.html).

## Plot the diagnostics

Use a fitted estimator to inspect the observations behind its flags:

```python
import matplotlib.pyplot as plt
from robustmodels import plots

ax = plots.outlyingness_plot(ao)
plt.show()
```

Every plotting function returns a Matplotlib `Axes` and accepts `ax=` for
subplots. Save with `ax.figure.savefig("outlyingness.png", dpi=300)`.
Legends omit empty classes and include observation counts; labels use
zero-based row positions. The
[diagnostic guide](https://omarbecerrasierra.github.io/robustmodels/plots.html)
includes rendered examples of every plot, formulas and interpretation.
The [validation notes](https://omarbecerrasierra.github.io/robustmodels/validation.html)
explain the pre-release checks and differences from R.

## Choose an estimator

| Your task | A starting point | What to consider |
| --- | --- | --- |
| Estimate the center of one sample | `location.hodges_lehmann` | No tuning parameter; based on pairwise averages. |
| Estimate spread with resistance to outliers | `scale.qn` or `scale.mad` | Qn uses pairwise differences; MAD uses deviations from a center. |
| Describe asymmetry | `scale.medcouple` | Robust skewness; `lmc` and `rmc` describe the tails. |
| Estimate covariance when observations outnumber variables | `MCD` | Supports random or deterministic starts. |
| Estimate covariance when variables outnumber observations | `MRCD` | Regularizes toward an identity target in standardized coordinates. |
| Explore other multivariate approaches | `OGK`, `MVE`, `StahelDonoho`, `PenaPrieto`, `SEstimator`, `MMEstimator` | Different robustness, efficiency and computational tradeoffs. |
| Reduce dimension with outliers present | `ROBPCA` | Also for more variables than observations; `ProjectionPursuitPCA` needs no covariance. |
| Classify when training data contain outliers | `RobustLDA` or `RobustQDA` | MCD-based; every class needs more observations than variables. |
| Test mean vectors | `hotelling_t2`, `manova` | One sample or paired differences; two or more groups. |
| Flag outliers in skewed multivariate data | `AdjustedOutlyingness` or `DirectionalOutlyingness` | Adjusted whiskers or side-specific robust scales; `StahelDonohoOutlyingness` for symmetric data. |
| Fit a linear regression with outliers | `MMRegressor` | 50% breakdown and 95% efficiency; `LTSRegressor` and `SRegressor` are alternatives. |
| Fit a linear regression with heavy-tailed errors | `RankRegressor` | No tuning constant; resists response outliers, not leverage points. |
| Compare two samples or paired data with ties | `rank_sum_test`, `signed_rank_test` | Exact p-values conditional on the observed ties. |
| Group observations when some are outliers | `TClust` | Trims a fraction `alpha`; restricts how different the cluster shapes may be. |
| Estimate a multivariate density, its modes or its derivatives | `KernelDensity` | Full bandwidth matrix chosen from the data; `hdr_level` gives highest density regions. |
| Test whether two samples have the same distribution | `kde_test` | Any dimension; compares kernel density estimates. |
| Estimate a unimodal density without a bandwidth | `LogConcaveDensity` | Maximum likelihood under log-concavity. |
| Fit a linear regression with the most efficient convex loss | `ScoreMatchingRegressor` | Loss estimated from the residuals; resists response outliers, not leverage points. |
| Test whether some MM slopes are zero | `mm_test` | Robust deviance or Wald test, as `anova.lmrob`. |
| Fit a nonlinear response curve | `NonlinearMRegressor` | Huber weights; supply the model callable and starting parameters. |
| Classify two groups with robust logistic regression | `MallowsLogisticRegression` or `BYLogisticRegression` | Bounded residual influence; optional leverage protection. |
| Fit nonnegative responses with a Poisson model | `MallowsPoissonRegressor` or `MTPoissonRegressor` | MT uses a bounded transformed loss and random starts. |
| Describe bivariate centrality and outliers | `halfspace_depth`, `halfspace_median`, `plots.bagplot` | Exact bivariate depths; subset-based bag for large samples. |

For example, regularized covariance can be fitted to a wide matrix:

```python
import numpy as np
from robustmodels.covariance import MRCD

wide = np.random.default_rng(0).normal(size=(20, 50))
regularized = MRCD().fit(wide)
print(regularized.covariance_.shape)
```

```text
(50, 50)
```

See the [covariance guide](https://omarbecerrasierra.github.io/robustmodels/covariance.html)
for sample-size requirements, parameters and worked examples.

## Available methods

| Module | Public estimators |
| --- | --- |
| `robustmodels.location` | `hodges_lehmann`, `m_location`, `tau_location`, `trimmed_mean`, `winsorized_mean` |
| `robustmodels.scale` | `mad`, `qn`, `sn`, `pn`, `tau_scale`, `m_scale`, `medcouple`, `lmc`, `rmc` |
| `robustmodels.covariance` | `MCD`, `MRCD`, `MVE`, `OGK`, `StahelDonoho`, `PenaPrieto`, `SEstimator`, `MMEstimator` |
| `robustmodels.multivariate` | `ROBPCA`, `ProjectionPursuitPCA`, `RobustLDA`, `RobustQDA`, `hotelling_t2`, `manova` |
| `robustmodels.regression` | `MMRegressor`, `SRegressor`, `LTSRegressor`, `NonlinearMRegressor`, `mm_test` |
| `robustmodels.cluster` | `TClust` |
| `robustmodels.density` | `KernelDensity`, `plugin_bandwidth`, `scv_bandwidth`, `kde_test` |
| `robustmodels.shape` | `LogConcaveDensity`, `ScoreMatchingRegressor` |
| `robustmodels.rank` | `RankRegressor`, `drop_test`, `rank_anova`, `rank_sum_test`, `signed_rank_test` |
| `robustmodels.glm` | `MallowsLogisticRegression`, `MallowsPoissonRegressor`, `BYLogisticRegression`, `MTPoissonRegressor` |
| `robustmodels.depth` | `halfspace_depth`, `halfspace_median`, `regression_depth`, `bagplot_stats` |
| `robustmodels.outliers` | `StahelDonohoOutlyingness`, `AdjustedOutlyingness`, `DirectionalOutlyingness` |
| `robustmodels.plots` | `outlier_map`, `residual_plot`, `residual_qq`, `distance_distance`, `distance_qq`, `tolerance_ellipse`, `adjusted_boxplot`, `outlyingness_plot`, `pca_outlier_map`, `scree_plot`, `biplot`, `discriminant_plot`, `cluster_plot`, `bagplot`, `hdr_plot`, `log_concave_plot`, `score_plot`, `coefficient_plot`, `dd_plot`, `ctl_curves` |

The covariance module also exposes `h_alpha_n`, `mcd_consistency` and
`mcd_small_sample`. Each public method has a docstring with parameters,
return values, examples and references.

## Conventions and scope

- Univariate estimators take finite, one-dimensional samples. Empty samples
  return `NaN`; a single observation has zero scale. Handle missing and infinite
  values before fitting.
- Covariance and regression models take matrices with **observations in rows**
  and variables in columns. Set `random_state` for methods that use random starts.
- Qn, Sn and Pn apply finite-sample corrections by default. Use
  `finite_correction=False` when you need the asymptotic calibration.
- Robustness depends on the estimator, sample size, dimension and data. No method
  in this package is immune to arbitrary contamination. Multivariate subset
  searches are approximations and do not certify global optima.
- The package is in **early development**. Its API may change before version 1.0.

Coming from R? The [R equivalents](https://omarbecerrasierra.github.io/robustmodels/from-r.html)
page maps robustbase, rrcov and base R functions to robustmodels. The
[method references](https://omarbecerrasierra.github.io/robustmodels/references.html)
connect the implementations to their scientific sources and explain differences
from other software conventions. Tests check defining equations, exact small
problems, statistical properties, numerical derivatives, edge cases and
scikit-learn compatibility. Frozen software outputs retain their provenance
as supplementary regression checks; they are not correctness criteria. See
the [validation notes](https://omarbecerrasierra.github.io/robustmodels/validation.html)
for the independent theoretical audit and its limits.

## Documentation, contributions and citation

- **Learn:** the [user guide](https://omarbecerrasierra.github.io/robustmodels/)
  includes the API reference and examples tested alongside the package.
- **Contribute:** see the [development guide](https://github.com/omarbecerrasierra/robustmodels/blob/main/CONTRIBUTING.md)
  for setup, checks and release instructions. Bug reports and reproducible
  examples are welcome in [Issues](https://github.com/omarbecerrasierra/robustmodels/issues).
- **Follow changes:** read the [changelog](https://github.com/omarbecerrasierra/robustmodels/blob/main/CHANGELOG.md)
  and the [roadmap](https://github.com/omarbecerrasierra/robustmodels/blob/main/ROADMAP.md)
  of planned methods.
- **Cite:** the DOI [10.5281/zenodo.24169655](https://doi.org/10.5281/zenodo.24169655)
  refers to all versions; Zenodo also lists a DOI for each release. Citation
  metadata are in [CITATION.cff](https://github.com/omarbecerrasierra/robustmodels/blob/main/CITATION.cff)
  and GitHub's “Cite this repository” option.

Released under the [BSD 3-Clause license](https://github.com/omarbecerrasierra/robustmodels/blob/main/LICENSE).
