Metadata-Version: 2.4
Name: sctopo
Version: 0.1.0
Summary: Topological analysis of single-cell data: per-cluster persistent homology and periodicity-based topogene discovery.
Author: Binglun Shao
License: BSD 3-Clause License
        
        Copyright (c) 2026, Binglun Shao and the totopos authors
        All rights reserved.
        
        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.
        
Project-URL: Homepage, https://github.com/binglunshao/sctopo
Project-URL: Documentation, https://github.com/binglunshao/sctopo/tree/main/docs
Project-URL: Repository, https://github.com/binglunshao/sctopo
Project-URL: Issues, https://github.com/binglunshao/sctopo/issues
Keywords: single-cell,scRNA-seq,persistent homology,topological data analysis,TDA,computational biology,circular coordinates,cell cycle
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: BSD License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Classifier: Topic :: Scientific/Engineering :: Mathematics
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.22
Requires-Dist: scipy>=1.9
Requires-Dist: pandas>=1.5
Requires-Dist: scikit-learn>=1.1
Requires-Dist: networkx>=2.8
Requires-Dist: tqdm>=4.60
Requires-Dist: matplotlib>=3.5
Requires-Dist: plotly>=5.10
Requires-Dist: anndata>=0.9
Requires-Dist: scanpy>=1.9
Requires-Dist: ripser>=0.6
Requires-Dist: persim>=0.3
Requires-Dist: dreimac>=0.3
Requires-Dist: torch>=1.12
Provides-Extra: test
Requires-Dist: pytest>=7.0; extra == "test"
Requires-Dist: pytest-cov>=4.0; extra == "test"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: ruff>=0.1; extra == "dev"
Requires-Dist: black>=23.0; extra == "dev"
Requires-Dist: jupyter; extra == "dev"
Requires-Dist: ipykernel; extra == "dev"
Provides-Extra: docs
Requires-Dist: sphinx>=6.0; extra == "docs"
Requires-Dist: sphinx-rtd-theme>=1.3; extra == "docs"
Requires-Dist: nbsphinx>=0.9; extra == "docs"
Requires-Dist: myst-parser>=2.0; extra == "docs"
Dynamic: license-file

# sctopo

**Topological analysis of single-cell data.** `sctopo` extracts statistically
significant 1-dimensional homological features (loops) in single-cell
embeddings, scores genes by how strongly their expression is locked to each
loop, and visualizes both geometry and gene-expression structure in three
complementary 3-D views per cycle.

[![License: BSD-3-Clause](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](LICENSE)
[![Python: 3.9+](https://img.shields.io/badge/python-3.9%2B-blue.svg)](https://www.python.org)

---

## What it does

Given a single-cell embedding (typically PCA or Concord) and Leiden cluster
labels, `sctopo` runs the following pipeline per cluster:

1. **Per-cluster persistent homology.** Compute Vietoris–Rips persistent
   homology on the cluster's embedding (Ripser).
2. **Significance filtering.** Keep only H1 classes whose persistence exceeds
   the (1 − α) quantile of a column-permutation null distribution, *and*
   whose birth radius is below a quantile of nearest-neighbor distances.
3. **Critical-edge cycle recovery.** For each surviving class, extract a
   representative cycle via shortest-path on the 1-skeleton.
4. **Circular coordinates.** Assign a continuous angle θ ∈ [0, 2π) to every
   topocell (cells in a neighborhood of the cycle) using DREiMac.
5. **Topogene discovery.** Rank genes by the amplitude of their circular
   correlation with θ:

   $$r_{\\text{circ}}(g) = \\sqrt{\\,\\operatorname{corr}(x_g, \\cos\\theta)^2 + \\operatorname{corr}(x_g, \\sin\\theta)^2\\,}$$

   This is the first Fourier-mode amplitude along the cycle. A permutation
   test gives per-gene p-values and a family-wise significance threshold.
6. **Visualization.** Three 3-D views per loop (cluster PCA / global UMAP /
   topogene PCA), plus per-loop matplotlib panels for PDF export.

---

## Installation

```bash
git clone https://github.com/binglunshao/sctopo.git
cd sctopo
pip install -e .
```

Development install:

```bash
pip install -e ".[dev]"
```

Core dependencies: `numpy`, `scipy`, `scikit-learn`, `networkx`, `pandas`,
`matplotlib`, `plotly`, `anndata`, `scanpy`, `ripser`, `persim`, `dreimac`,
`torch` (legacy gradient scoring only). `torch` is only required if you
call `sctopo.genes.topo_scores_rep_sampling`; the default periodicity
scoring is pure NumPy.

---

## Quick start

```python
import anndata as ad
import sctopo.cells as tpc
import sctopo.genes as tpg
import sctopo.viz as tpv

# Load and subset to one cluster
adata = ad.read_h5ad("brain_dev_concord.h5ad")
adata_cluster = adata[adata.obs["leiden"] == "2"].copy()

# 1. Per-cluster PH with significance filtering
X = adata_cluster.obsm["X_pca"]
topological_loops = tpc.critical_edge_method_significant(
    X,
    n_subsamples=50,
    alpha=0.05,
    birth_dist_nn_quantile=0.75,
    verbose=True,
)
tpv.quick_loop_summary(topological_loops)

# 2. Circular coords + topogenes for each loop
results = []
for i in range(len(topological_loops)):
    cc = tpg.get_circular_coords(topological_loops, loop_index=i)
    res = tpg.compute_topogenes(
        adata_cluster, topological_loops, cc,
        loop_index=i, n_genes=100,
    )
    results.append({"cc": cc, **res})
    print(f"Loop {i+1}: top genes = {res['topogenes'][:5]}")

# 3. Per-gene permutation significance
sig = tpg.topogenes_significance(
    adata_cluster, topological_loops, results[0]["cc"],
    loop_index=0, n_perms=100,
)
print(f"Family-wise α=0.05 threshold: {sig['max_threshold_0p05']:.3f}")

# 4. Visualize
import scanpy as sc
topocell_ixs = topological_loops[0]["topocell_ixs"]
adata_cc = adata_cluster[topocell_ixs, results[0]["topogenes"]].copy()
sc.tl.pca(adata_cc, n_comps=3)

fig = tpv.plot_topocells_subplots(
    adata_cluster, adata_cc, topological_loops,
    loop_index=0, color_col="phase",
)
fig.show()
```

A complete walk-through is in [`notebooks/example_pipeline.ipynb`](notebooks/example_pipeline.ipynb).

---

## Topogene scoring: two methods

`sctopo` ships two topogene-scoring algorithms. The periodicity method is the
default and recommended choice; the gradient method is preserved for
reproducibility with earlier analyses.

| | Periodicity (default) | Gradient (legacy) |
|---|---|---|
| **Function** | `topo_scores_periodicity` | `topo_scores_rep_sampling` |
| **Definition** | √(corr(x, cos θ)² + corr(x, sin θ)²) | ‖∇₍x₎ Σ subsample-cycle-perimeter‖₂ |
| **Determinism** | Deterministic | Monte-Carlo over `n_reps` |
| **Interpretation** | First Fourier amplitude along cycle | Sensitivity of cycle length to expression |
| **Dependencies** | NumPy + SciPy | PyTorch |
| **Per-gene p-value** | Yes (cheap permutation) | Yes (more expensive) |

Both methods accept the same arguments and return the same shape of output, so
you can swap via `compute_topogenes(..., method="periodicity"|"rep_sampling")`.

---

## Package layout

```
sctopo/
├── pp/              preprocessing utilities
│   ├── pca.py             gap-based PCA cutoff (sparse-aware)
│   └── outliers.py        Isolation Forest on PCA coords
├── cells/           per-cluster PH, significance, loop extraction
│   ├── graph.py        VR 1-skeleton construction
│   ├── significance.py permutation null
│   ├── loops.py        critical_edge_method[_significant]
│   └── cycle_assign.py project all cells onto a cycle
├── genes/           circular coords + topogene scoring
│   ├── circular_coords.py   DREiMac wrapper, circular variance
│   ├── periodicity.py       default scoring (Fourier amplitude)
│   ├── rep_sampling.py      legacy gradient scoring
│   └── topogenes.py         compute_topogenes, topogenes_significance
└── viz/             plotly + matplotlib visualizations
    ├── cloud.py             3-D topocell views
    ├── diagrams.py          persistence diagrams
    └── summary.py           text summaries
```

---

## Citing

If you use `sctopo` in published work, please cite:

```bibtex
@software{sctopo2026,
  author  = {Shao, Binglun},
  title   = {sctopo: topological analysis of single-cell data},
  year    = {2026},
  url     = {https://github.com/binglunshao/sctopo},
  version = {0.1.0},
}
```

A paper describing the method is in preparation; please also cite the
underlying tools `ripser` ([Tralie et al. 2018](https://joss.theoj.org/papers/10.21105/joss.00925))
and `dreimac` ([Perea et al.](https://github.com/scikit-tda/DREiMac)).

---

## Acknowledgements

`sctopo` builds on ideas from an earlier prototype
[`totopos`](https://github.com/manuflores/totopos), developed in
collaboration with Emanuel Flores Bautista. Per-cluster persistent
homology, periodicity-based topogene scoring, permutation-null
significance testing, and the unified visualization API are new in this
package.

---

## License

BSD 3-Clause License. See [LICENSE](LICENSE).
