Metadata-Version: 2.5
Name: grassmann-ot
Version: 0.3.2
Summary: Cell-to-cell anchoring via Grassmann subspace distance and Optimal Transport, with fast selectable backends.
Project-URL: Homepage, https://github.com/ZengFLab/grassmann-ot
Project-URL: Issues, https://github.com/ZengFLab/grassmann-ot/issues
Author-email: Your Name <you@example.com>
License: MIT License
        
        Copyright (c) 2026 Your Name
        
        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 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.
License-File: LICENSE
Keywords: anchors,grassmann,optimal-transport,single-cell
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Requires-Python: >=3.8
Requires-Dist: numpy>=1.20
Requires-Dist: pot>=0.8
Requires-Dist: scikit-learn>=1.0
Requires-Dist: scipy>=1.6
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: scanpy; extra == 'dev'
Provides-Extra: faiss
Requires-Dist: faiss-cpu; extra == 'faiss'
Provides-Extra: full
Requires-Dist: faiss-gpu; extra == 'full'
Requires-Dist: pytest>=7.0; extra == 'full'
Requires-Dist: scanpy; extra == 'full'
Requires-Dist: torch; extra == 'full'
Provides-Extra: gpu
Requires-Dist: faiss-gpu; extra == 'gpu'
Requires-Dist: torch; extra == 'gpu'
Provides-Extra: test
Requires-Dist: pytest>=7.0; extra == 'test'
Provides-Extra: torch
Requires-Dist: torch; extra == 'torch'
Description-Content-Type: text/markdown

# grassmann-ot

Cell-to-cell anchoring via **Grassmann subspace distance + Optimal Transport**,
now with **fast, selectable construction backends** for large `n`.

## Install

```bash
pip install grassmann-ot
```

For the GPU backends:

```bash
pip install torch faiss-gpu   # or faiss-cpu
```

## Quick start

```python
import numpy as np
from grassmann_ot import GrassmannOT

# H_X, H_Y come from any external tool (NMF, scVI, Harmony, ...)
# shape: (n_gene_programs, n_cells)
H_X, H_Y = np.random.rand(20, 300), np.random.rand(20, 250)

ot = GrassmannOT(k=30, p=3, reg=0.1, backend="batched")
gamma   = ot.fit(H_X, H_Y)        # soft coupling, shape (n_X, n_Y)
matches = ot.get_hard_anchors()   # one-to-one anchors, shape (K, 2)
```

## Backends (new in 0.3.0)

`cells_to_grassmann` and `GrassmannOT` now accept a `backend` parameter:

| Backend         | Requirements      | Use when                          |
|-----------------|-------------------|-----------------------------------|
| `loop`          | numpy             | Baseline / debugging              |
| `batched`       | torch             | **Default; medium datasets**      |
| `pca`           | scipy, numpy      | Want 10-20x speed, accept small precision loss |
| `subsampling`   | sklearn, scipy    | Very large n, tolerate interpolation |
| `faiss`         | faiss + torch     | Largest datasets, GPU available   |

```python
from grassmann_ot import cells_to_grassmann

U = cells_to_grassmann(H_X, k=30, p=3, backend="pca")
V = cells_to_grassmann(H_Y, k=30, p=3, backend="pca")
```

Extra options: `batch_size`, `subsample_rate`, `inner_backend`, `device`,
`faiss_prefer` ('auto' | 'gpu' | 'cpu'; only used when backend='faiss').

### Faiss CPU/GPU auto-detection (new in 0.3.2)

The `faiss` backend automatically detects whether your installed faiss
supports GPU and falls back to CPU if it does not. You do not need a
different code path for `faiss-cpu` vs `faiss-gpu`:

```python
# Works unchanged whether you have faiss-cpu or faiss-gpu installed.
ot = GrassmannOT(k=30, p=3, reg=0.1, backend="faiss")  # auto: GPU if available
gamma = ot.fit(H_X, H_Y)

# Or force a specific mode:
cells_to_grassmann(H_X, backend="faiss", faiss_prefer="cpu")   # force CPU
cells_to_grassmann(H_X, backend="faiss", faiss_prefer="gpu")   # error if no GPU
```

`faiss_prefer='auto'` (the default) silently uses CPU when
`faiss.StandardGpuResources` is unavailable, so `faiss-cpu` users no
longer hit `AttributeError: module 'faiss' has no attribute
'StandardGpuResources'`. The detection is independent of the torch SVD
stage, so you can use faiss-CPU kNN with torch GPU SVD or any mix.

You can also skip construction and feed precomputed points directly:

```python
ot = GrassmannOT(k=30, p=3, reg=0.1)
gamma = ot.fit_points(U_list, V_list)
```

## Parameters

| Parameter         | Default | Meaning                                  |
|-------------------|---------|------------------------------------------|
| `k`               | 30      | Neighborhood size                        |
| `p`               | 3       | Subspace dimension                       |
| `metric`          | cosine  | Neighbor metric                          |
| `reg`             | 0.1     | Sinkhorn entropic regularization         |
| `backend`         | batched | Grassmann construction strategy          |
| `batch_size`      | 512     | Batch size for torch SVD                 |
| `subsample_rate`  | 0.1     | Fraction exact-computed in `subsampling` |
| `inner_backend`   | pca     | Backend for seed cells in `subsampling`  |
| `faiss_prefer`    | auto    | 'auto'/`gpu`/`cpu` for backend='faiss'   |
| `a`, `b`          | None    | Source / target marginals (uniform)      |

## Benchmark

```bash
python examples/benchmark_backends.py
```

## Fast hard anchors (new in 0.3.1)

`get_hard_anchors()` used to call `linear_sum_assignment` on a padded cost
matrix, which is **O(N^3)** in the number of cells and becomes the bottleneck
at a few thousand cells. The default is now `'mutual'`, which derives a
one-to-one matching directly from the soft coupling `gamma` in **O(n)** time:

```python
ot = GrassmannOT(k=30, p=3, reg=0.1, backend="batched")
ot.fit(H_X, H_Y)

anchors = ot.get_hard_anchors()                       # default: mutual, O(n)
anchors = ot.get_hard_anchors(method="row_argmax")    # fastest, may repeat targets
anchors = ot.get_hard_anchors(method="hungarian")     # exact, slow O(N^3)
anchors = ot.get_hard_anchors(method="hungarian_topk", k=200)  # balanced
anchors = ot.get_hard_anchors(method="lapjv")         # pip install lapjv
costs   = ot.get_hard_anchors(method="mutual", return_cost=True)[1]
```

| Method             | Complexity | One-to-one | Needs extra dep |
|--------------------|-----------:|:----------:|-----------------|
| `mutual` (default) | O(n)       | yes        | -               |
| `row_argmax`       | O(n)       | no         | -               |
| `col_argmax`       | O(n)       | no         | -               |
| `hungarian_topk`   | O(n·k^2)   | yes        | -               |
| `hungarian`        | O(N^3)     | yes        | -               |
| `lapjv`            | ~O(N^3)    | yes        | `lapjv`         |

Calling `get_hard_anchors()` with no arguments keeps the old return shape,
so existing code works unchanged.

## Changelog

### 0.3.2
- The `faiss` backend now auto-detects GPU/CPU and falls back to CPU
  when `faiss.StandardGpuResources` is unavailable, so `faiss-cpu`
  users no longer hit `AttributeError`.
- New `faiss_prefer` parameter (`'auto'` / `'gpu'` / `'cpu'`) on both
  `cells_to_grassmann` and `GrassmannOT`.
- Faiss import is now guarded against `NameError` and other non-ImportError
  failures during faiss initialization, so a broken faiss install no
  longer breaks `import grassmann_ot`.
- Backend selection is independent of the torch SVD device, allowing
  faiss-CPU kNN with torch GPU SVD (or any combination).

### 0.3.1
- `get_hard_anchors` now accepts a `method` argument; the default
  `'mutual'` is O(n) instead of O(N^3), fixing the large-n slowdown.
- New methods: `mutual`, `row_argmax`, `col_argmax`, `hungarian_topk`
  (with full-Hungarian fallback on infeasible restricted problems), and
  `lapjv`.
- The zero-argument call signature and return shape are unchanged.

### 0.3.0
- New module `grassmann_ot._grassmann_fast` with five backends.
- `GrassmannOT` exposes `backend`, `batch_size`, `subsample_rate`,
  `inner_backend`, `device`.
- New `fit_points()` to use precomputed Grassmann point lists.
- Fixed `linear_sum_assignment` result unpacking.
