Metadata-Version: 2.4
Name: contrastive-cv
Version: 0.2.0
Summary: Contrastive PCA with out-of-sample projection — fork of Abid et al. (2018) with fixes for held-out data transform, symmetric eigendecomposition, and arbitrary n_components.
Author-email: Ali Abid <aabid1@cs.ucla.edu>
Maintainer-email: Yanruo Zhang <zhangyanruo1121@gmail.com>
License: MIT-NSFG License v1 (No Software for Genocide)
        
        Copyright (c) 2018 Ali Abid
        Modifications copyright (c) 2026 Yanruo Zhang
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        The Software may not be used by any individual, corporation, government, or
        other entity that has been found by the United Nations, the International
        Criminal Court, or the International Association of Genocide Scholars to be
        engaged in genocide or crimes against humanity, nor by any entity acting on
        their behalf or at their direction.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/yanruoz/contrastive-cv
Project-URL: Bug Tracker, https://github.com/yanruoz/contrastive-cv/issues
Project-URL: Original Paper, https://www.nature.com/articles/s41467-018-04608-8
Keywords: contrastive PCA,dimensionality reduction,scRNA-seq,cross-validation
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.20
Requires-Dist: scikit-learn>=1.0
Provides-Extra: plot
Requires-Dist: matplotlib; extra == "plot"
Provides-Extra: notebook
Requires-Dist: ipywidgets; extra == "notebook"
Requires-Dist: IPython; extra == "notebook"
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"
Dynamic: license-file

# contrastive-cv

**Contrastive PCA with out-of-sample projection and cross-validation support.**

A maintained fork of [abidlabs/contrastive](https://github.com/abidlabs/contrastive) (Abid et al., *Nature Communications* 2018) that fixes four bugs making the library unusable for held-out data and cross-validation workflows.

---

## What changed

The original library had four bugs that silently broke any train/test or cross-validation split:

| # | Bug | Effect |
|---|-----|--------|
| 1 | `fit()` discarded the PCA object — `self.pca_directions = None` | `transform()` on held-out data projected into the wrong space |
| 2 | `fit_transform()` passed already-preprocessed `self.fg` to `transform()` | Centering/standardization/PCA applied twice |
| 3 | `cpca_alpha()` used `LA.eig` on a symmetric matrix | Complex eigenvalues → silent NaN propagation |
| 4 | Sign-flip loop hardcoded columns 0 and 1 | Crash for `n_components=1`; missed normalization for components ≥ 3 |

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

---

## Installation

```bash
pip install contrastive-cv
```

Or from source:

```bash
git clone https://github.com/yanruoz/contrastive-cv
cd contrastive-cv
pip install -e .
```

The import name remains `contrastive` for backward compatibility with the original package.

---

## Usage

### Basic fit / transform (cross-validation safe)

```python
import numpy as np
from contrastive import CPCA

# Train split
cpca = CPCA(n_components=5, standardize=True)
cpca.fit(X_train_fg, X_train_bg)

# Project held-out data — applies the same centering/standardization/PCA
X_test_projected = cpca.transform(X_test_fg, alpha_selection='manual', alpha_value=2.0)
# X_test_projected: (n_test, 5)
```

### fit_transform (exploration)

```python
cpca = CPCA(n_components=2)
# Returns 4 projections at automatically selected alphas
projections, alphas = cpca.fit_transform(fg, bg, return_alphas=True)
```

### Single alpha

```python
cpca.fit(fg, bg)
proj = cpca.transform(fg, alpha_selection='manual', alpha_value=1.5)
```

### Cross-validation loop

```python
from sklearn.model_selection import KFold

results = []
for train_idx, test_idx in KFold(n_splits=5).split(fg):
    cpca = CPCA(n_components=10)
    cpca.fit(fg[train_idx], bg[train_idx])

    # pca_directions is now populated: (n_original_features, pca_dim)
    train_proj = cpca.transform(fg[train_idx], alpha_selection='manual', alpha_value=2.0)
    test_proj  = cpca.transform(fg[test_idx],  alpha_selection='manual', alpha_value=2.0)

    # evaluate downstream task on test_proj ...
```

---

## API

### `CPCA(n_components=2, standardize=True, verbose=False)`

| Method | Description |
|--------|-------------|
| `fit(fg, bg, preprocess_with_pca_dim=None)` | Fit covariance matrices; stores `_pca`, `_fg_mean`, `_fg_std` |
| `transform(dataset, alpha_selection, alpha_value, ...)` | Project new data using stored preprocessing + cPCA directions |
| `fit_transform(fg, bg, ...)` | Convenience wrapper; equivalent to `fit` then `transform(fg, ...)` |
| `cpca_alpha(dataset, alpha)` | Project `dataset` at a single alpha value |

### Key attributes after `fit()`

| Attribute | Shape | Description |
|-----------|-------|-------------|
| `pca_directions` | `(n_original_features, pca_dim)` | PCA loading matrix (or `None` if PCA not used) |
| `fg_cov` | `(d, d)` | Foreground covariance matrix |
| `bg_cov` | `(d, d)` | Background covariance matrix |

---

## Citation

If you use this library, please cite the original paper:

> Abid, A., Zhang, M. J., Bagaria, V. K., & Zou, J. (2018). Exploring patterns enriched in a dataset with contrastive principal component analysis. *Nature Communications*, 9(1), 2134. https://doi.org/10.1038/s41467-018-04608-8

---

## License

[MIT-NSFG License v1](LICENSE) — MIT with a restriction on use by entities found to be engaged in genocide or crimes against humanity.
