Skip to main content

Spatial Kernel-based Reduced Rank CCA for spatial transcriptomics

Project description

CoPro (Python)

Unsupervised detection of coordinated spatial progressions in spatial transcriptomics

Python PyPI GitHub License: MIT

CoPro detects coordinated spatial progressions between cell types in spatial transcriptomics data. Given the spatial positions and gene expression profiles of cells, CoPro finds a low-dimensional axis along which cells of one type are spatially co-organized with cells of another type — or within a single cell type — revealing continuous tissue structure that discrete clustering misses.

The method is built on Spatial Kernel-based Reduced Rank CCA (SkrCCA): a power-method optimization that maximizes a spatially-weighted cross-covariance between cell type-specific PC score matrices.

R package: The original R implementation is available at github.com/Zhen-Miao/CoPro.


Installation

pip install pycopro

Or install from source:

git clone https://github.com/Zhen-Miao/copro-python.git
cd copro-python
pip install -e .

Requirements: Python ≥ 3.10, NumPy, SciPy, pandas, scikit-learn.


Quick start

import numpy as np
import pandas as pd
import copro as cp

# Inputs
# expr_norm : np.ndarray  (cells × genes, normalized)
# location  : pd.DataFrame with columns "x", "y"
# cell_types: np.ndarray  (per-cell type labels)

obj = cp.CoProSingle(
    normalized_data=expr_norm,
    location_data=location,
    meta_data=meta,
    cell_types=cell_types,
)

obj = cp.subset_data(obj, ["Cell type A", "Cell type B"])
obj = cp.compute_pca(obj, n_pca=30)
obj = cp.compute_distance(obj, normalize=False)
obj = cp.compute_kernel_matrix(obj, sigma_values=[0.1, 0.2, 0.5])
obj = cp.run_skr_cca(obj, scale_pcs=True, n_cc=2)
obj = cp.compute_normalized_correlation(obj)
obj = cp.compute_gene_and_cell_scores(obj)

print("Selected sigma:", obj.sigma_value_choice)

# Cell scores for the optimal sigma
sigma = obj.sigma_value_choice
scores_A = obj.cell_scores[f"cellScores|sigma{sigma}|Cell type A"][:, 0]
scores_B = obj.cell_scores[f"cellScores|sigma{sigma}|Cell type B"][:, 0]

How it works

CoPro runs a seven-step pipeline:

Step Function Description
1 subset_data Filter to cell types of interest
2 compute_pca Truncated PCA per cell type (ARPACK, matching R IRLBA)
3 compute_distance Pairwise Euclidean distances (within and between types)
4 compute_kernel_matrix Gaussian RBF kernel: K = exp(−d²/2σ²)
5 run_skr_cca SkrCCA power-method optimization over σ values
6 compute_normalized_correlation Spectral-norm normalized CCA correlation per σ and CC
7 compute_gene_and_cell_scores Project CCA weights to cell and gene space

Sigma selection is automatic: the σ that maximizes the mean CC1 normalized correlation is chosen as obj.sigma_value_choice.

Multi-slide support: Use CoProMulti for datasets spanning multiple tissue sections. CCA weights are learned jointly across slides; cell scores are computed per slide.


Tutorials

Notebook Dataset Description
tutorials/tutorial_one_cell_type.ipynb Intestinal organoid (seqFISH) Within-type spatial self-organization of epithelial cells along the crypt–villus axis
tutorials/tutorial_two_cell_types.ipynb Mouse brain MERFISH (Zhang et al. Nature 2023) Cross-type co-progression between D1 and D2 striatal neurons

API reference

Data containers

CoProSingle(normalized_data, location_data, meta_data, cell_types) Single-slide state container. All pipeline functions modify and return this object.

CoProMulti(normalized_data, location_data, meta_data, cell_types) Multi-slide variant. Requires a slideID column in meta_data.

Pipeline functions

cp.subset_data(obj, cell_types_of_interest)
cp.compute_pca(obj, n_pca=30, center=True, scale=True)
cp.compute_distance(obj, normalize=False)
cp.compute_kernel_matrix(obj, sigma_values, upper_quantile=0.85, lower_limit=5e-7)
cp.run_skr_cca(obj, scale_pcs=True, n_cc=2, max_iter=500, tol=1e-5)
cp.compute_normalized_correlation(obj, tol=1e-4)
cp.compute_gene_and_cell_scores(obj)

Key output slots

Attribute Type Description
obj.sigma_value_choice float Automatically selected σ
obj.normalized_correlation dict[str, DataFrame] Normalized correlation per σ and CC
obj.cell_scores dict[str, ndarray] Cell scores, keyed "cellScores|sigma{s}|{ct}"
obj.gene_scores dict[str, ndarray] Gene scores, keyed "geneScores|sigma{s}|{ct}"
obj.kernel_matrices dict[str, ndarray] Kernel matrices, keyed "kernel|sigma{s}|{ct_i}|{ct_j}"

Numerical equivalence with R

The Python implementation is numerically validated against the R package on simulation and real datasets. Key design choices ensuring equivalence:

  • PCA uses scipy.sparse.linalg.svds (ARPACK), the same Krylov-subspace family as R's irlba::prcomp_irlba
  • Sign convention matches prcomp_irlba via sklearn.utils.extmath.svd_flip
  • Distance and kernel computations are algebraically identical to R's fields::rdist + Gaussian RBF
  • Kernel matrices agree to machine epsilon (~10⁻¹⁶)
  • Cell score Pearson |r| vs R ≥ 0.9999 across all tested datasets and sigma values

Citation

If you use CoPro in your research, please cite:

Miao Z. et al. CoPro: Unsupervised detection of coordinated spatial progressions in spatial transcriptomics (in preparation).

MERFISH tutorial data:

Zhang, M., Pan, X., Jung, W. et al. Molecularly defined and spatially resolved cell atlas of the whole mouse brain. Nature 624, 343–354 (2023). https://doi.org/10.1038/s41586-023-06808-9


License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pycopro-0.1.1.tar.gz (24.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pycopro-0.1.1-py3-none-any.whl (21.6 kB view details)

Uploaded Python 3

File details

Details for the file pycopro-0.1.1.tar.gz.

File metadata

  • Download URL: pycopro-0.1.1.tar.gz
  • Upload date:
  • Size: 24.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.13

File hashes

Hashes for pycopro-0.1.1.tar.gz
Algorithm Hash digest
SHA256 6e9e5f2126eec6581f856a603bb199169152af24be1cd4d104d3ab48d305c6bd
MD5 f3e992a2b6948f97157ac2d84643d3e0
BLAKE2b-256 d7541c04ce56449a2f08ec3eb39e41325b983d0e900d54f920c80560450a0684

See more details on using hashes here.

File details

Details for the file pycopro-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: pycopro-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 21.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.13

File hashes

Hashes for pycopro-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 ee6e7404533ad8a0b631e447c2e0d1b2caf1f8bab267ae0a0347022a96e15753
MD5 2402c1be08adda67a98b50c6dfe5cd79
BLAKE2b-256 5494a24f1973a5bc976774f8a4f3a2fd786c5918d3a25c681cd3b716b39a2e6b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page