Skip to content
chthubPublic

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Latest commit

 

History

157 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

DeepSAS

DeepSAS (Deep-learning framework for cell-type-specific SnCs And SnGs) is a computational framework designed to identify senescent cells and senescence-associated genes from single-cell RNA sequencing data.

Overview

Cellular senescence is a state of permanent cell cycle arrest that plays important roles in development, tissue homeostasis, aging, and disease. Identifying senescent cells in heterogeneous tissues is challenging due to the lack of universal markers. DeepSAS leverages graph neural networks and contrastive learning to identify senescent cells and their associated gene signatures from single-cell RNA sequencing data.

The framework integrates several key components:

  1. Graph representation of cell-gene interactions
  2. Graph Attention Networks (GAT) for capturing complex relationships
  3. Contrastive learning with multi-level distance optimization
  4. Attention mechanisms for identifying senescence-associated genes

Features

  • Identifies senescent cells in heterogeneous tissues with cell-type specificity
  • Discovers senescence-associated genes specific to each cell type
  • Leverages both gene expression patterns and cell-cell interactions
  • Robust to batch effects and technical variations through built-in normalization
  • Works across different cell types and senescence induction methods
  • Scales to large datasets with optimized sampling strategies
  • Provides comprehensive visualization and analysis tools

Installation

This project is developed and tested on Linux and macOS environments.

  1. Clone the Repository:

    git clone https://github.com/chthub/deepsas.git
    cd deepsas/
    git checkout deepsas-v1
  2. Set Up a uv Environment (recommended): We recommend to use uv for the environment mangement. Check this link to install uv.

    uv venv --python 3.8.20
    source .venv/bin/activate
  3. Install Pinned Dependencies:

    uv pip install -r requirements.txt
    uv pip check

    requirements.txt pins the DeepSAS runtime, notebook tools, and key scientific dependencies to versions in our compatible test environment: Python 3.8.20, Linux x86_64, PyTorch 2.4.0, CUDA 12.1, and PyG 2.6.1. It includes matching prebuilt PyTorch/PyG wheel sources to avoid compiling extensions or mixing incompatible builds. Use a fresh environment; the NVIDIA driver must support CUDA 12.1.

    These CUDA-specific wheels do not target macOS or CPU-only installations. For those platforms or a different CUDA version, adapt the PyTorch and PyG wheel sources and build pins together using the PyTorch and PyG installation guides. Dependencies for the comparison methods are kept in separate benchmarking/requirements-*.txt files; do not install them into the DeepSAS environment.

Quick Start

Basic Usage

The default parameters are used only for running on the sample dataset and paper reproduce. They have been validated on the bundled example dataset and are not universal settings. Before running DeepSAS on another dataset, adapt and validate the preprocessing, cell-type annotations, gene set, CCC settings, candidate thresholds, projection mode, optimization settings, and stopping criteria for that dataset. Do not assume that the example defaults or resulting SnC/SnG calls transfer unchanged. example_data/example_data.h5ad is merely a toy dataset to explain and describe the usage of the code. It holds no real biological significance and is unrelated to the conclusions drawn in the paper. Please use the data from the article to make biological evaluation and discoveries.

Run the following commands from the repository directory. The first command trains on the bundled example with the default parameters; the second generates tables from its final result. On a cluster, run training on a compute node.

uv run python -u deepsas_v1.py --exp_name example --device_index 0 --retrain > ./example.log 2>&1
uv run python -u generate_3tables.py --output_dir ./outputs --exp_name example --device_index 0

Outputs are written to ./outputs/example/. --output_dir specifies the base directory and is honored by both commands; use the same value and experiment name for training and table generation. The training log and example_run_summary.json report how refinement stopped.

A new end-to-end run should use --retrain; checkpoints made with a different projection mode are rejected explicitly. Result counts are dataset- and configuration-dependent. The outputs can be inspected with:

uv run python scripts/check_reviewer_example.py ./outputs/example

Analysis Workflow

DeepSAS follows a 4-step workflow:

  1. Data Loading & Preprocessing: Filters genes/cells and constructs the cell-gene graph
  2. Initial Embedding Generation: Creates UMAP embeddings via scanpy
  3. Graph Attention Network Training: Learns the graph structure with GATConv layers
  4. Contrastive Learning: Refines embeddings to identify senescent cells and genes

Results Analysis

After running DeepSAS, generate tables of senescence-associated cells and genes:

uv run python -u generate_3tables.py --output_dir ./outputs --exp_name example --device_index 0

By default, this reads example_sencellgene-final.data and the saved preprocessed data, preserving the training cell and gene indices. It does not assume a particular final iteration. To inspect an existing iteration explicitly, add --epoch N, where N is its zero-based iteration number. For a custom cell-type column, pass the same --cell_type_col used during training.

If no SnCs are detected, the cell score table still contains every processed cell, and DEG and summary gene tables retain their column definitions. Cell types without enough SnCs or control cells for differential expression are skipped with an explanation in the table-generation log.

This generates several output tables:

  1. Cell-level analysis:

    • Cell senescence scores and binary classification (senescent/non-senescent)
    • Distribution of senescent cells across cell types
  2. Gene-level analysis:

    • Differentially expressed genes between senescent and non-senescent cells
    • Cell-type specific senescence-associated genes with statistical measures
    • Aggregated gene information across multiple cell types
  3. Statistical measures:

    • p-values and adjusted p-values from Wilcoxon rank-sum tests
    • Log fold-changes showing expression differences
    • Senescence-associated gene (SnG) scores derived from attention weights

For visualization and downstream analysis, follow the tutorial in tutorial.ipynb, which demonstrates:

  • UMAP visualization of senescent cells
  • Gene set enrichment analysis of identified senescence markers
  • Cell-type specific senescence marker analysis and interpretation

Large Dataset Analysis

For datasets with many cells (>50,000), use the sampling approach detailed in Sampling_Tutorial.md, which provides:

  • Subsampling strategies
  • Batch processing scripts
  • Result integration methods

Phenotype related Analysis

The supported phenotype_analysis entry point uses the current DeepSAS pipeline and additionally selects SnCs within a configurable phenotype column such as treatment or disease state.

Input Data Format

DeepSAS works with h5ad format (AnnData objects from Scanpy). The input data should include:

  • Gene expression matrix (cells × genes) in sparse or dense format
  • Cell type annotations in adata.obs['clusters'] or another specified column
  • (Optional) Additional metadata like batch information for batch effect correction

DeepSAS expects raw, unnormalized gene-expression counts in adata.X. DeepSAS handles normalization and scaling using scanpy functions. Batch correction is optional and enabled with --batch_remove.

adata.var_names must hold gene symbols in the same nomenclature as the senescence marker list. The bundled list uses human HGNC symbols (CDKN1A); mouse and rat data use MGI/RGD symbols (Cdkn1a) and match almost nothing in it. DeepSAS therefore checks the marker overlap immediately after loading the data and stops with an explicit message rather than training on an empty senescence seed; see Senescence Marker List and Species.

Parameters

Run uv run python deepsas_v1.py --help for the full command-line interface. The following settings are used by deepsas_v1.py.

Input/Output Parameters

  • --input_data_count: Input h5ad file; default example_data/example_data.h5ad.
  • --output_dir: Base output directory; default ./outputs. Run files are stored under {output_dir}/{exp_name}/.
  • --exp_name: Required experiment name.
  • --device_index: CUDA device index; default 0. CPU is used when CUDA is unavailable.
  • --retrain: Train the graph model and create its graph files; otherwise load existing files for the experiment.
  • --cell_type_col: Cell-type annotation column; default clusters.
  • --batch_col: Batch annotation column for optional ComBat correction; default Sample.
  • --batch_remove: Enable ComBat before the cell UMAP embedding; default off.
  • --epoch: Table generation only; default is the final result, or select an existing zero-based iteration number.

Preprocessing

Parameter Default Role and valid range
--min_genes_per_cell 200 Minimum detected genes per retained cell; positive integer
--min_cells_per_gene 10 Minimum cells expressing a retained gene; positive integer
--normalization_target_sum 10000 Target total count used beforelog1p; positive number
--scale_max_value 10 Upper clipping value applied after scaling; positive number
--umap_n_neighbors 10 Neighbor count used to construct the UMAP graph; positive integer
--umap_n_pcs 40 Principal components supplied to the neighbor graph; positive integer

These defaults are the values used before they were exposed as options. Omitting the new options therefore preserves the previous computation.

Model Configuration

Parameter Default Role
--seed 40 Random seed, including PCA and UMAP
--n_genes full All retained genes, or a requested number of highly variable genes plus available marker genes
--gene_set full Gene sets taken from the marker list; a column name of that file, or several joined with+
--emb_size 12 Cell and gene embedding dimension
--type_specific_projections / --no_type_specific_projections enabled Use separate gene/cell input projections by default, or explicitly select a shared GAT projection
--ccc type1 Binary CCC edges;type3 omits CCC edges
--ccc_threshold 0.8 Signaling-score threshold φ for retaining CCC edges
--lr_panel Built-in panel Optional ligand–receptor CSV withligand and receptor columns

The graph uses binary connectivity: cell–gene expression presence and thresholded CCC connections are represented by graph topology. The GAT therefore accepts node features and edge indices only.

--gene_set full combines SenMayo, FRIDMAN, CellAge, and the unchanged 11-gene legacy cell-cycle marker seed from DeepSAS v1. The named alternatives select only the marker collections stated in their option value. The built-in L–R panel is the eight-ligand SASP panel from Supplementary Table S19.

Senescence Marker List and Species

Parameter Default Role and valid range
--marker_list bundled CSV Senescence marker CSV that seeds the initial SnG candidates
--species human Species of the input data:human, mouse, rat, or other
--min_marker_overlap 0.05 Fraction of marker genes that must be present in the data; number in [0, 1]
--skip_marker_check off Report a failing marker/data symbol check as a warning instead of stopping the run

--marker_list takes a CSV with one column per gene set and one gene symbol per row, shorter columns padded with empty cells — the layout of the bundled senescence_marker_list.csv:

SenMayo,FRIDMAN,CellAge,GO
ACVR1B,ALDH1A3,AAK1,TERF2
ANG,AOPEP,ABI3,CDK2

Column names are the values accepted by --gene_set, matched case-insensitively and combined with + (for example --gene_set senmayo+cellage). A name that is not a column of the file is rejected with the list of available gene sets. The default file keeps the DeepSAS v1 grouping exactly: GO is reported but not used for seeding, and the 11-gene legacy cell-cycle seed is appended. A user-supplied file is used as given — its columns are the gene sets, and nothing is added to them.

--species declares the species of the input data. Gene symbols are species specific — human HGNC symbols are uppercase (CDKN1A), mouse and rat MGI/RGD symbols are capitalized (Cdkn1a) — so a marker list written for one species matches almost nothing in another. Right after the data is loaded, DeepSAS reports how many marker genes were found and stops when fewer than --min_marker_overlap of them are present:

Marker genes found in the data: 2/317 (0.6%); required: 5.0%
	Data gene symbols: Capitalized symbols, e.g. Cdkn1a (mouse/rat MGI style)
	Marker gene symbols: UPPERCASE symbols, e.g. CDKN1A (human HGNC style)
Ligand-receptor panel genes found in the data: 1/62 (1.6%)
WARNING: only 1 of 62 genes of the built-in human ligand-receptor panel (1.6%) are present in the input data, so --ccc type1 will add few or no cell-cell edges. Pass --lr_panel with a panel whose gene symbols match the data (mouse), or --ccc type3 to run without cell-cell edges.
ValueError: Only 2 of 317 senescence marker genes (0.6%) are present in the input data, which is below --min_marker_overlap (5.0%).
  --species            : mouse (expects Capitalized symbols, e.g. Cdkn1a (mouse/rat MGI style))
  data gene symbols    : Capitalized symbols, e.g. Cdkn1a (mouse/rat MGI style), 16547 genes, e.g. Noc2l, Hes4, Isg15, Agrn, C1orf159
  marker gene symbols  : UPPERCASE symbols, e.g. CDKN1A (human HGNC style), e.g. AAK1, ABI3, ACLY, ACVR1B, ADCK5
  Ignoring capitalization, 303 marker genes would match, so the two sets differ in nomenclature rather than in content.

The ligand–receptor panel is checked the same way and on the same threshold, because it is a second species-specific gene list. A panel that does not match the data is only a warning, not an error: it leaves the CCC part of the graph without edges instead of making the run meaningless. The warning is printed on both paths, so a run that stops on the marker list also states whether the L–R panel matches. It is suppressed by --ccc type3, which drops cell-cell edges altogether.

For non-human data, either map the expression matrix to the species of the marker list (Ensembl BioMart, pyensembl, babelgene) before running DeepSAS, or supply a senescence hallmark gene list for that species (this is an example input):

uv run python -u deepsas_v1.py --exp_name mouse_run \
    --input_data_count mouse_data.h5ad \
    --species mouse --marker_list mouse_senescence_markers.csv \
    --lr_panel mouse_lr_panel.csv --retrain

Capitalization is not converted for you, because case folding is not a valid ortholog mapping. With --species set to a non-human value the built-in human cell-cycle seed is not added either. Both sets of match statistics — marker list and L–R panel — are recorded under marker_match in {exp_name}_run_summary.json.

Training and Candidate Selection

Parameter Default Role
--gat_epoch 30 Graph autoencoder training epochs
--gat_learning_rate 0.001 Graph autoencoder Adam learning rate
--gat_hidden_size 32 GAT hidden width
--gat_dropout 0.6 Attention dropout during GAT training; disabled for candidate scoring
--cell_optim_epoch 50 Cell embedding optimization epochs per outer iteration
--cell_hidden_size 128 Hidden width of the cell embedding network
--distance_levels 0 0 4 Initial learnable targets for within-type SnC, between-type SnC, and same-type non-SnC distances
--learning_rate 0.01 Initial Adam learning rate for cell embedding optimization
--weight_decay 0.001 Cell optimizer weight decay
--lr_decay 0.85 Cell learning-rate multiplier after each outer iteration
--iqr_multiplier 1.5 Upper-fence multiplier for SnC scores and for SnG scores iniqr mode
--sng_update_mode iqr SnG update rule: the default threshold-driven IQR policy or the optionalfixed10 policy
--min_snc_per_type 10 At least this many above-fence SnCs are required to retain a cell type's candidates
--max_iter 10 Maximum number of completed outer refinement iterations
--convergence_tol 0.9 Required Jaccard overlap for both candidate sets

Downstream Reporting

Parameter Default Role and valid range
--deg_min_snc 6 Minimum SnCs required for a cell-type DEG comparison; positive integer
--deg_min_control 2 Minimum controls required for a cell-type DEG comparison; positive integer
--deg_min_logfc 0.25 Minimum log fold change retained in the combined DEG/SnG table; finite number

These three options affect only downstream tables; they do not change predicted SnC or SnG candidates.

Phenotype-aware Extension

Parameter Default Role and valid range
--phenotype_aware off Add phenotype-stratified SnC selection; enabled automatically by the phenotype training entry point
--phenotype_col Condition AnnData.obs column containing phenotype labels
--min_snc_per_phenotype 1 Minimum above-fence SnCs retained for a phenotype; positive integer
--use_hvg_deg off Retain per-cell-type HVGs plus configured senescence and L–R genes before standard gene selection
--phenotype_hvg_count 1000 HVGs requested per cell type; positive integer
--phenotype_zscore_threshold 2.0 Finite reporting cutoff for phenotype-specific SnGs

These options are inactive in the standard pipeline unless --phenotype_aware or the phenotype entry point is used. See the extension README for its selection rule, commands, and outputs.

These example-dataset defaults are exposed for reproducibility and must be adapted and validated for other datasets. Fixed architecture choices include:

  • By default, separate learned projections map gene and cell embeddings into the shared GAT feature space. Pass --no_type_specific_projections to use the shared projection path instead; switching modes requires retraining the GAT checkpoint.
  • The graph encoder has two GAT layers. Its explicit settings—matching the original PyG defaults—are one attention head, concatenation, self-loops, and a LeakyReLU negative slope of 0.2. These are fixed architecture choices, not dataset-tuning parameters.
  • GAT training uses Adam. Cell embedding optimization uses Adam followed by an exponential learning-rate scheduler; their numeric settings are exposed above.
  • The cell embedding network uses six linear transformations, CELU activations, two residual additions, and layer normalization. Its hidden width and initial distance targets are configurable through --cell_hidden_size and --distance_levels.
  • PCA uses the deterministic arpack solver, followed by UMAP. Input thresholds and numeric embedding preprocessing settings are exposed in the preprocessing table.

Obsolete options that did not affect the main pipeline have been removed. SnC candidates are determined by their score thresholds; SnG updates follow --sng_update_mode; initial embeddings use UMAP.

SnG Updates and Stopping

We have incorporated performance optimizations into the code; although the implementation may differ slightly from the description in the paper, it is logically equivalent.

In iqr mode, the convergence log records D2* as sng_outlier_count and the accepted count D2 as sng_swaps. In fixed10 mode, sng_outlier_count records the requested count of 10. The sng_update_mode column identifies the active rule.

To use the alternative fixed-count SnG update policy, pass --sng_update_mode fixed10. This mode requests ten replacements per iteration: the ten highest-scoring genes outside the current candidate set replace the ten lowest-scoring current candidates (or all available genes when either side has fewer than ten). Candidate IDs remain unique. The default iqr mode uses the threshold-driven rule described above.

After updating embeddings, attention, and genes, SnC labels are recalculated to produce a complete iteration state. Outer convergence uses J(A, B) = |A ∩ B| / |A ∪ B| between adjacent completed states: both SnC and SnG Jaccard values must reach --convergence_tol, and both previous and current sets must be nonempty. The default tolerance is 0.9; --convergence_tol 1 requests exact membership equality. Loss is optimized within each iteration; it is not the outer stopping criterion. In fixed10 mode, compulsory gene turnover can keep the SnG Jaccard below 1, while iqr mode can make zero replacements and attain exact stability. Convergence is not guaranteed within the iteration limit. Individual genes or cells can enter and exit the candidate sets between iterations, so the default 0.9 threshold allows limited membership changes rather than requiring identical sets.

Output Files

DeepSAS generates the following files under {output_dir}/{exp_name}/:

  • {exp_name}_new_data.h5ad: Processed AnnData object with filtered genes/cells
  • {exp_name}_graphnx.data: NetworkX graph representation of cell-gene interactions
  • {exp_name}_graphpyg.data: PyTorch Geometric graph representation for GAT model
  • {exp_name}_GAT.pt: Trained Graph Attention Network model
  • {exp_name}_cellmodel.pt: Cell embedding model, when cell optimization was performed
  • {exp_name}_sencellgene-epoch{epoch}.data: Candidate state at each completed outer iteration
  • {exp_name}_sencellgene-final.data: Final available candidate state, used by table generation
  • {exp_name}_convergence.csv: Per-iteration candidate counts, Jaccard overlaps, loss, gene threshold and replacements, cell-type counts, and stop status
  • {exp_name}_run_summary.json: Run configuration, marker/species match statistics (marker_match), final iteration, candidate counts, final-result filename, and stop status

The summary distinguishes converged (both nonempty candidate sets meet the overlap criterion), max_iter (the cap was reached without convergence), and empty_candidates (SnC or SnG candidates are empty). A running summary has not recorded a completed run and cannot be used for default final-table generation. Empty candidates are never reported as convergence.

Each iteration and final .data file stores the SnC dictionary, unique candidate SnG indices, attention weights, and graph edge indices. Candidate genes are stored by index, not ranked by score. The associated {exp_name}_new_data.h5ad defines the cell and gene ordering.

After running generate_3tables.py, you'll also get a folder Senescent_Tables in the output path. In this folder you have:

  1. Cell_Table1_SnC_scores.csv: Information about each cell and its senescence score

    • Contains cell IDs, names, types, binary senescent indicator, and senescence scores
  2. Gene_Table2_DEG_ct_SnG_score.csv: Differentially expressed genes between senescent and non-senescent cells

    • Includes gene names, cell types, p-values, log fold-changes, adjusted p-values, and senescence scores
  3. Gene_Table3_gene_ct_count.csv: Gene summaries across cell types, including initial-marker membership

    • Gene_newTable3_gene_ct_count.csv contains the subset reported in one cell type
  4. Additional tables:

    • Cell_Table2_SnCs_per_ct.csv: Counts of total cells and senescent cells per cell type
    • Gene_Table1_SnG_scores_per_ct.csv: Candidate gene attention scores for each cell type with SnCs
    • table2ByCelltype.csv: Table 2 grouped by cell type
    • table2ByGene.csv: Table 2 grouped by gene

For detailed explanations of each table and column, see Senescent_Tables_Explanation.md

Citation

If you use DeepSAS in your research, please cite:

@article{ma2025intrinsic,
  title={An Intrinsic-hoc Framework for Heterogeneous Cellular Senescence Elucidation Using Deep Graph Representation Learning and Experimental Validation},
  author={Ma, Anjun and Cheng, Hao and Vanegas, Natalia Del Pilar and Ghobashi, Ahmed and Chen, Hu and Rodriguez, Jhonny and Rosas, Lorena and Wang, Cankun and Shao, Jianming and Jiang, Yi and others},
  journal={bioRxiv},
  pages={2025--07},
  year={2025},
  publisher={Cold Spring Harbor Laboratory}
}

License

This project is licensed under the MIT License - see the LICENSE file for details.

Contact

For questions or issues, please open an issue on GitHub or contact the authors.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages