Skip to content

Latest commit

 

History

56 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

STACAME

STACAME overview

STACAME is a Python package for cross-species alignment and integration of spatial transcriptomics data. It uses spatial neighbor graphs, orthologous genes, cross-species mutual nearest neighbors, graph attention networks, and domain-adaptation losses to learn a shared embedding across species.

The package supports cross-species domain alignment, shared and divergent spatially variable gene analysis, comparative developmental analysis, cell-type transfer, and three-dimensional integration of spatial transcriptomics sections.

Project structure and license

The notebooks include executable code, saved outputs where available, and commands that write the expected result files. The repository can be used either from the public source repository or from a local copy of this directory.

Reference software versions

For the reference analyses, use the environment.yml export in the top-level project directory as the authoritative environment file. The pip.txt and conda.txt files in this directory are supplementary installation lists; they should not be mixed with the exported environment when exact reproduction is required.

Component Reference version
STACAME 1.1.0
Python 3.11.8
R 4.3.3
R mclust 6.1.1
anndata 0.11.4
colorcet 3.2.1
gseapy 1.1.10
harmonypy 0.0.10
leidenalg 0.10.2
matplotlib 3.10.3
numba 0.61.2
numpy 2.2.6
pandas 2.3.0
plotly 6.1.2
rpy2 3.5.11
scanorama 1.7.4
scanpy 1.11.2
scikit-learn 1.7.0
scipy 1.14.1
seaborn 0.13.2
statannot 0.2.3
statsmodels 0.14.4
torch 2.12.0
torch-geometric 2.8.0
umap-learn 0.5.7

The complete transitive dependency list, including build information, is in environment.yml. The reference GPU build also records CUDA 13.0.2, torch-scatter 2.1.2+pt212cu130, and torch-sparse 0.6.18+pt212cu130. For a different CUDA version or a CPU-only installation, install a matching PyTorch/PyG build using the official installation instructions and do not copy compiled CUDA wheels between environments.

Hardware requirements

  • A GPU is recommended for the default tutorials and large datasets. CPU execution is supported for small datasets and smoke tests, but CPU runtimes have not been benchmarked.
  • No non-standard hardware is mandatory for the small Tutorial 4 demo.
  • The tutorial-specific GPU-memory targets are summarized in the Practical Resource Guide above. The values are approximate and vary with input size, model parameters, CUDA/PyTorch versions, and available system memory.
  • The 3-D cerebellum and breast-cancer tutorials are substantially larger and may require a high-memory GPU and sufficient system RAM. If CUDA is unavailable, the notebooks fall back to torch.device('cpu'), but execution may be much slower.

Installation

Create the reference environment

Run this command from the top-level project directory, where environment.yml is located:

conda env create -f environment.yml
conda activate stacame

Then install the local package if it was not already installed by the environment export:

cd STACAME-main
python -m pip install -e .
python -m ipykernel install --user --name stacame --display-name "STACAME"
python -c "import STACAME; print('STACAME import OK')"

Because an exported Conda environment can contain a local stacame==1.1.0 pip entry, an environment creation error at that entry can be resolved by omitting that one local-package line from a temporary copy of environment.yml and then running python -m pip install -e . from the source directory.

If the repository was unpacked into a directory named STACAME rather than STACAME-main, use that directory in the cd command. The notebooks use paths relative to Tutorials, so launch Jupyter from that directory when running a tutorial:

cd Tutorials
jupyter lab

Manual installation

Use the exported environment.yml for exact reproduction of the reference analyses. If it is unavailable, the following creates a portable environment. It is not a byte-for-byte replacement for the exported environment:

conda create -n stacame python=3.11.8
conda activate stacame

conda install -c conda-forge r-base=4.3.3 r-mclust=6.1.1
python -m pip install -r pip.txt

# Packages not included in pip.txt.
python -m pip install rpy2==3.5.11
python -m pip install torch==2.12.0 torch-geometric==2.8.0

# Align packages that are pinned differently in supplementary lists.
python -m pip install scipy==1.14.1 colorcet==3.2.1
python -m pip install -e .
python -m ipykernel install --user --name stacame --display-name "STACAME"
python -c "import STACAME; print('STACAME import OK')"

For a GPU installation, select a PyTorch build compatible with the target CUDA driver and then install a compatible PyTorch Geometric build. The reference compiled wheels are Linux-specific and should not be reused on another platform. The mclust_R function requires both the Python package rpy2 and the R package mclust.

Installation time

On a typical desktop with an SSD and a stable network connection, environment creation and package installation are expected to take approximately 10-30 minutes. Installing large PyTorch/CUDA packages or resolving Conda packages from a slow mirror can take longer. Tutorial data are downloaded or unpacked separately and are not required for package installation.

Tutorials and demo data

Ten step-by-step tutorials are included in Tutorials/. Shared demo data are available from Google Drive. Individual notebook data links are also provided at the beginning of the relevant notebooks.

Tutorial Analysis Recorded GPU memory Recorded run time
1 Human-macaque DLPFC 18 GB 9 min 23 s
1 minibatch Human-macaque DLPFC, minibatch <7 GB 21 min 28 s
2 Mouse-marmoset-macaque hippocampus 11 GB 9 min 23 s
3 Cross-platform hippocampus 16.7 GB 10 min
4 Mouse-human MERFISH cortex 1.76 GB 7 min 16 s
5 Mouse-zebrafish multi-stage embryos 18 GB 29 min 02 s
6 Human-mouse-zebrafish embryos 12 GB 15 min 23 s
7 Alzheimer's disease hippocampus 13 GB 10min
8 Mouse-human breast cancer 15 GB 80min
9 Three-dimensional cerebellum 15 GB 120min
10 Spatial cell-type prediction 21.5 GB (provisional) 18min

The times above are the running-time notes recorded in the included notebooks and are hardware-dependent GPU reference times, not guarantees for CPU execution. Tutorial 4 is the recommended small demo for a normal desktop. Some notebooks specify memory requirements but do not contain a complete timing record. The current Tutorial 10 notebook contains a 21.5 GB resource note but is labelled Tutorial 8 in its opening cell; verify that notebook before treating this value as authoritative for Tutorial 10.

If a notebook opens with the old kernel name env_stasage, select the installed STACAME/stacame kernel instead. The old kernel name is notebook metadata and is not a package requirement.

Expected outputs

The standard tutorials write results under Data/<tutorial>/output_STACAME/. Exact filenames are defined in each notebook. The standard output set includes:

  • <species_id>.h5ad: processed species-level AnnData objects;
  • adata_<species_id>_expression.h5ad: expression matrices after the tutorial's feature selection;
  • adata_embedding.h5ad: merged cross-species embedding;
  • adata.obsm['STACAME']: the learned embedding for each processed object;
  • adata.obs['mclust']: clustering labels when the mclust step is run;
  • checkpoints/best_checkpoint.pth: the best saved model checkpoint when model_save_path is provided; and
  • PNG figures such as common_mclust.png, common_domain.png, and UMAP/spatial plots.

The returned objects remain standard AnnData objects and can be reloaded with scanpy.read_h5ad or anndata.read_h5ad.

Instructions for running STACAME on your own data

Required input format

STACAME expects one AnnData object per species or section:

  1. adata.X contains the expression matrix with spots/cells as observations and genes as variables.
  2. adata.obsm['spatial'] contains a numeric coordinate matrix with shape n_obs x 2 for 2-D data. Use the subgraph processor for 3-D or multi-section workflows.
  3. A gene-ortholog table is supplied through Gene_map_raw_path. Its column names must match species_ortholog_column_dict; homology-type columns are supplied through species_ortholog_type_dict when available.
  4. species_section_ids, species_id_map, and rad_cutoff_dict must contain an entry for every species/section.
  5. For multiple sections, use unique section/sample identifiers and keep the same naming scheme in the input metadata and configuration dictionaries.

Minimal processing and training example

The following is a template. Replace the paths, species names, ortholog column names, and radius values with values appropriate for the data. Tutorial 1 is the complete runnable example.

import os
import torch
import STACAME
from STACAME.analysis import merge_embedding

root_data_path = './Data/your_dataset/'
output_path = root_data_path + 'output_STACAME/'
os.makedirs(output_path, exist_ok=True)

Gene_map_raw_path = './Data/your_dataset/orthologs.tsv'
species_section_ids = {
    'SpeciesA': ['section_A'],
    'SpeciesB': ['section_B'],
}
species_ortholog_column_dict = {
    'SpeciesA': 'SpeciesA gene name',
    'SpeciesB': 'SpeciesB gene name',
}
species_ortholog_type_dict = {
    'SpeciesA': 'SpeciesA homology type',
    'SpeciesB': 'SpeciesB homology type',
}
species_id_map = {'SpeciesA': 0, 'SpeciesB': 1}
rad_cutoff_dict = {'SpeciesA': 1.0, 'SpeciesB': 1.0}

processor = STACAME.STACAME_processer(
    root_data_path=root_data_path,
    Gene_map_raw_path=Gene_map_raw_path,
    species_section_ids=species_section_ids,
    species_ortholog_column_dict=species_ortholog_column_dict,
    species_ortholog_type_dict=species_ortholog_type_dict,
    species_id_map=species_id_map,
    rad_cutoff_dict=rad_cutoff_dict,
    gene_cap_upper_dict={'SpeciesA': 'upper', 'SpeciesB': 'upper'},
    n_top_genes=500,
    homo_n_top_genes=5000,
    cross_species_neibors_K_mnn=20,
    total_normalize={'SpeciesA': 1e4, 'SpeciesB': 1e4},
    if_return_concat_adata=True,
)
adata_dict, triplet_ind_species_dict, edge_ndarray_species, adata_whole = processor.load_process_adata()

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
trainer = STACAME.STACAME_trainer(
    adata_dict,
    triplet_ind_species_dict,
    edge_ndarray_species,
    device=device,
    pretrain_device=device,
    adata_whole=adata_whole,
    random_seed=666,
    model_save_path=output_path,
    verbose=True,
)
adata_dict = trainer.run()

for species_id, adata in adata_dict.items():
    adata.write(output_path + f'{species_id}.h5ad')

adata_embedding = merge_embedding(adata_dict, key_umap='STACAME')
adata_embedding.write(output_path + 'adata_embedding.h5ad')

# Optional clustering; requires R mclust and Python rpy2.
STACAME.mclust_R(
    adata_embedding,
    num_cluster=7,
    used_obsm='STACAME',
    random_seed=666,
)
adata_embedding.write(output_path + 'adata_embedding_clustered.h5ad')

For 3-D or multi-section data, use STACAME_processer_subgraph and the corresponding subgraph trainer. The relevant workflow is demonstrated in Tutorial 9. For the GAN or auxiliary training variants, use train_STACAME_GAN, train_STACAME_subgraph_GAN, or train_STACAME_subgraph_auxiliary as shown in the tutorials.

Reproducibility

The trainer and mclust interfaces expose random_seed, with 666 used by the supplied tutorials and trainer defaults. The package also initializes random generators in its main module. For exact reproduction, keep the reference environment, input files, preprocessing parameters, model parameters, random seed, CUDA version, and hardware fixed. GPU and library differences can cause small numerical differences even with the same seed.

Reproducing the reported analyses

The tutorial notebooks correspond to the analyses and figures described in the accompanying paper. To reproduce a figure or quantitative result:

  1. Install the reference environment.
  2. Download or unpack the corresponding tutorial data.
  3. Start Jupyter from the Tutorials directory.
  4. Run the tutorial matching the analysis and retain the default parameters described in the Methods.
  5. Compare the generated adata_embedding.h5ad, clustering/embedding outputs, and figures with the source data and figure panels provided with the project.

Source data for Figures 2-6 are included with the project. All datasets analyzed in the study are from public resources; data sources and accessions are listed in the Data availability statement and Supplementary Table 1.

Practical resource guide

The two computers described in the next section are example test platforms, not required hardware. The practical GPU-memory targets below are taken from the resource notes in the tutorial notebooks and should be treated as approximate lower bounds for the stated settings; leave additional memory for the operating system, data loading, and other applications. Tutorial 4 is the smallest example and is the recommended starting point for a modest computer. CPU execution is possible for small datasets, but it can be substantially slower. A single system-RAM minimum cannot be specified because it depends on the input data and preprocessing; 16 GB is a reasonable starting point for Tutorial 4, whereas larger tutorials should be run with more system memory.

Tutorial Practical GPU-memory target Resource note
1 ~18 GB with default settings; ≤7 GB with minibatch The minibatch notebook trades memory for longer runtime.
2 ~11 GB Recorded in the notebook.
3 ~16.7 GB Recorded in the notebook.
4 ~1.76 GB Smallest recorded example; a GPU with about 2 GB available memory is a practical starting point.
5 ~18 GB Recorded in the notebook.
6 ~12 GB Recorded in the notebook.
7 ~13 GB Recorded in the notebook.
8 ~15 GB The lower-memory GAN variant may be preferable when available.
9 ~15 GB The 3-D workflow also benefits from ample system RAM.
10 ~21.5 GB Recorded in the notebook.

These values are practical starting points rather than formal hardware guarantees. Reduce the number of selected genes, hidden dimensions, or batch size when memory is limited; the Tutorial 1 minibatch workflow provides a concrete example.

System requirements and tested platforms

STACAME has been tested on both Ubuntu/Linux and Windows.

Ubuntu/Linux reference test platform

The Ubuntu reference run was performed on a server with the following hardware information from lshw -short:

  • 2 x AMD EPYC 9654 96-Core Processor;
  • 770 GiB system memory; and
  • NVIDIA display adapters detected. The supplied lshw output does not report the exact NVIDIA model or GPU memory.

The reference software environment is Linux x86_64 with Conda or Mamba, Python 3.11.8, and R 4.3.3.

Windows test platform

The code has also been tested on the current Windows Local computer. The command-line query of that test machine reported:

  • Windows version 25H2, build 26200 (the registry-reported product name is Windows 10 Pro);
  • Intel(R) Core(TM) Ultra 9 285K processor;
  • 24 logical processors and a 64-bit operating system;
  • 63.37 GB total physical memory; and
  • Intel Graphics with display driver version 32.0.101.5869.

The reported Intel Graphics memory is shared/system-managed memory rather than a separately verified dedicated GPU-memory value. The hardware above is a reference test configuration, not a minimum requirement.

The package has not been benchmarked on every Windows or Ubuntu hardware configuration. Runtime and GPU memory use depend on the dataset, model parameters, CUDA driver, and available memory.

Troubleshooting

  • CUDA out of memory: use the Tutorial 1 minibatch notebook, reduce homo_n_top_genes or hidden dimensions, or use the lower-memory training variant demonstrated in the relevant tutorial.
  • R or mclust import error: confirm that r-base, r-mclust, and rpy2 are installed in the same environment used by Jupyter.
  • Missing data files: launch notebooks from Tutorials or update root_data_path to the location of Tutorials/Data.
  • Notebook kernel not found: register the environment with python -m ipykernel install --user --name stacame --display-name "STACAME" and select that kernel in Jupyter.
  • Different numerical results: confirm the package versions, CUDA/PyTorch build, seed, input data, and training parameters before comparing outputs.

Support

For questions, contact biaozhang@ysu.edu.cn or biaozhang2022@126.com.

Citation

Biao Zhang, Xiang Zhou, Shuqin Zhang* and Shihua Zhang*. "Deciphering shared and divergent tissue architectures from cross-species spatial transcriptomics". bioRxiv Preprint. 2026. DOI: https://doi.org/10.64898/2026.06.16.732760

About

Code for STACAME

Resources

Stars

4 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages