Protocol for reconstructing spatially aware receptor-TF-target signaling cascades using spatial transcriptomics Authors: Yao Li, Xiaobin Liu, Xinkai Yan, Guangyi Fan, Mengyang Xu Published: 2025 ABSTRACT SummaryConventional protocols for inferring gene regulatory networks from spatial transcriptomics data often neglect spatial constraints. Here, we present a protocol using SpaGRN, a statistical framework integrating extracellular signaling and spatial dependencies, to reconstruct spatially aware receptor-transcription factor-target regulatory cascades. This protocol details steps for data preprocessing, spatial autocorrelation, co-expression construction, cis-regulatory motif enrichment, receptor-associated regulon inference, and 3D visualization. This approach enables the systematic mapping of signaling pathways in complex tissues such as developing embryos and tumors.For complete details on the use and execution of this protocol, please refer to Li et al.1Subject areas: Bioinformatics, Single cell, Developmental biology, Systems biology, Computer sciences Before you begin Spatially resolved transcriptomics (SRT) technologies enable comprehensive mapping of gene expression within intact tissues, preserving spatial context essential for understanding biological systems. While these technologies capture both gene expression levels and their precise spatial coordinates, conventional computational methods for inferring gene regulatory networks (GRNs) exhibit critical limitations when applied to SRT data. Specifically, they often disregard tissue spatial heterogeneity and intercellular signaling mediated by ligand-receptor interactions, key mechanisms modulating transcription factor (TF) activity, and downstream gene expression. To overcome these constraints, we developed SpaGRN, a computational framework that reconstructs dynamic and spatially aware GRNs by integrating intracellular regulatory causality with extracellular signaling cues. This approach leverages spatial co-expression patterns and cis-regulatory motif analysis to identify context-dependent regulons, providing a more comprehensive understanding of gene regulation in tissue microenvironments. The protocol outlined below details SpaGRN’s application to SRT data analysis. It is benchmarked using mouse brain data generated via the Stereo-seq platform, as detailed in our associated research paper.1 Critically, SpaGRN’s versatility extends to other SRT platforms and tissue types, such as human colorectal cancer datasets and three-dimensional (3D) developing Drosophila embryos. This broad applicability positions SpaGRN as a robust tool for dissecting gene regulation across diverse biological systems. Innovation This work presents a fully automated, computationally integrated protocol for reconstructing end-to-end signaling cascades from receptors through transcription factors and their target genes within native spatial contexts. By coupling intercellular communication inference with intracellular motif-guided cis-regulatory network reconstruction in a unified spatial framework, our protocol overcomes a major limitation of existing methods, which typically analyze each spot or cell independently. It provides a cohesive spatial representation of gene regulatory events and demonstrates improved accuracy in identifying context-specific regulons, along with enhanced computational efficiency. Unlike prior scRNA-centric or correlation-only tools, this spatially aware, receptor-anchored GRN inference is delivered as an open-source Python toolkit featuring interactive 3D visualization. Designed for broad applicability, it supports data from multiple high-resolution spatial transcriptomics platforms, including 10x Visium, Stereo-seq, and MERFISH, thereby empowering systematic investigation of signaling mechanisms underlying complex biological processes such as organogenesis and tumorigenesis. Setting up the computational environment Timing: 30 min This section details the setup of the computational environment for running SpaGRN. Note: SpaGRN has been validated on Linux systems (Ubuntu 22.04 LTS or equivalent) with 16 CPU threads and 128 GB RAM across multiple spatial transcriptomics platforms (Stereo-seq, STARmap, MERFISH, CosMx, Slide-seq, and 10x Visium). The following steps should be performed in a Unix-based shell, such as Bash on Linux/macOS or Command Prompt on Windows. 1.Install Miniconda.Note: For optimal reproducibility, we recommend using Miniconda (v24.4.0 or later) to manage Python dependencies and isolate installations.a.Download the Linux-compatible Miniconda installer.>wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.shb.Execute the installer and follow prompts.>bash Miniconda3-latest-Linux-x86_64.shc.Restart your terminal to activate the installation. Install Miniconda.Note: For optimal reproducibility, we recommend using Miniconda (v24.4.0 or later) to manage Python dependencies and isolate installations.a.Download the Linux-compatible Miniconda installer.>wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.shb.Execute the installer and follow prompts.>bash Miniconda3-latest-Linux-x86_64.shc.Restart your terminal to activate the installation. Note: For optimal reproducibility, we recommend using Miniconda (v24.4.0 or later) to manage Python dependencies and isolate installations. a.Download the Linux-compatible Miniconda installer.>wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh Download the Linux-compatible Miniconda installer.>wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh >wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh b.Execute the installer and follow prompts.>bash Miniconda3-latest-Linux-x86_64.sh Execute the installer and follow prompts.>bash Miniconda3-latest-Linux-x86_64.sh >bash Miniconda3-latest-Linux-x86_64.sh c.Restart your terminal to activate the installation. Restart your terminal to activate the installation. 2.Create a dedicated conda environment.a.Initialize the environment with Python 3.8 and activate. Create a dedicated conda environment.a.Initialize the environment with Python 3.8 and activate. a.Initialize the environment with Python 3.8 and activate. Initialize the environment with Python 3.8 and activate. >conda create -n spagrn_env python=3.8 >conda activate spagrn_env Note: SpaGRN was developed and tested with Python 3.8.19. To avoid compatibility issues from Python updates, please use Python 3.8 or newer. 3.Install the latest version of SpaGRN.Note: Choose ONE of the following methods. We recommend Method A (PyPI) for most users as it automatically manages all complex dependencies.a.Method A: Via PyPI.>pip install spagrn==1.1.4b.Method B: Install the development mode of SpaGRN.i.Clone the repository to use the latest version of the main branch on GitHub, and enter the directory.>git clone -b main https://github.com/BGI-Qingdao/SpaGRN.git.>cd SpaGRNCRITICAL: To ensure reproducible results, please install the exact versions (or compatible later ones) of all dependencies listed in the software and algorithms section of the key resources table section.ii.Install all required dependencies. Install the latest version of SpaGRN.Note: Choose ONE of the following methods. We recommend Method A (PyPI) for most users as it automatically manages all complex dependencies.a.Method A: Via PyPI.>pip install spagrn==1.1.4b.Method B: Install the development mode of SpaGRN.i.Clone the repository to use the latest version of the main branch on GitHub, and enter the directory.>git clone -b main https://github.com/BGI-Qingdao/SpaGRN.git.>cd SpaGRNCRITICAL: To ensure reproducible results, please install the exact versions (or compatible later ones) of all dependencies listed in the software and algorithms section of the key resources table section.ii.Install all required dependencies. Note: Choose ONE of the following methods. We recommend Method A (PyPI) for most users as it automatically manages all complex dependencies. a.Method A: Via PyPI.>pip install spagrn==1.1.4 Method A: Via PyPI.>pip install spagrn==1.1.4 >pip install spagrn==1.1.4 b.Method B: Install the development mode of SpaGRN.i.Clone the repository to use the latest version of the main branch on GitHub, and enter the directory.>git clone -b main https://github.com/BGI-Qingdao/SpaGRN.git.>cd SpaGRNCRITICAL: To ensure reproducible results, please install the exact versions (or compatible later ones) of all dependencies listed in the software and algorithms section of the key resources table section.ii.Install all required dependencies. Method B: Install the development mode of SpaGRN.i.Clone the repository to use the latest version of the main branch on GitHub, and enter the directory.>git clone -b main https://github.com/BGI-Qingdao/SpaGRN.git.>cd SpaGRNCRITICAL: To ensure reproducible results, please install the exact versions (or compatible later ones) of all dependencies listed in the software and algorithms section of the key resources table section.ii.Install all required dependencies. i.Clone the repository to use the latest version of the main branch on GitHub, and enter the directory.>git clone -b main https://github.com/BGI-Qingdao/SpaGRN.git.>cd SpaGRNCRITICAL: To ensure reproducible results, please install the exact versions (or compatible later ones) of all dependencies listed in the software and algorithms section of the key resources table section. Clone the repository to use the latest version of the main branch on GitHub, and enter the directory.>git clone -b main https://github.com/BGI-Qingdao/SpaGRN.git.>cd SpaGRNCRITICAL: To ensure reproducible results, please install the exact versions (or compatible later ones) of all dependencies listed in the software and algorithms section of the key resources table section. >git clone -b main https://github.com/BGI-Qingdao/SpaGRN.git. >cd SpaGRN CRITICAL: To ensure reproducible results, please install the exact versions (or compatible later ones) of all dependencies listed in the software and algorithms section of the key resources table section. ii.Install all required dependencies. Install all required dependencies. >pip install -e 4.Verify installation.a.Run diagnostic checks. Verify installation.a.Run diagnostic checks. a.Run diagnostic checks. Run diagnostic checks. >python -c "import spagrn" Key resources table REAGENT or RESOURCESOURCEIDENTIFIERDeposited dataMouse_brain_cell_binChen et al.2https://db.cngb.org/stomics/mosta/downloadTF listAibar et al.3https://resources.aertslab.org/cistarget/tf_listsRanked whole genome databasesAibar et al.3https://resources.aertslab.org/cistarget/databasesMotif-to-TF annotation databasesAibar et al.3https://resources.aertslab.org/cistarget/motif2tfSoftware and algorithmsSpaGRN v.1.1.4Li et al.1https://github.com/BGI-Qingdao/SpaGRNhttps://doi.org/10.5281/zenodo.14925041VT3D v.1.0Guo et al.4https://github.com/BGI-Qingdao/VT3DPython 3.8.19Pythonhttps://www.python.orgpySCENIC v.0.12.1Aibar et al.3https://github.com/aertslab/pySCENICHotspot v.1.1.1DeTomaso et al.5https://github.com/YosefLab/HotspotNicheNet v.2.0Browaeys et al.6https://github.com/saeyslab/nichenetrMatplotlib v.3.5.2Hunter et al.7https://github.com/matplotlib/matplotlibSeaborn v.0.11.2Waskom et al.8https://github.com/mwaskom/seabornPlotly v.5.15.0Inc, P.T.9https://github.com/plotlyStereopy v.0.14.0b1Fang et al.10https://github.com/STOmics/StereopyCytoscape v.3.9.1Shannon et al.11https://cytoscape.orgOtherIntel Core Processor (Broadwell, IBRS) @ 1.70 GHz, 4 CPU cores, with 64 GB RAMN/AN/A Step-by-step method details This section delineates the methodology for inferring and analyzing spatial GRNs using SpaGRN. All code referenced herein is reproducible and accessible via official tutorials at https://spagrn.readthedocs.io/en/latest/Tutorials/index.html. Scripts may be directly copied from these tutorials to execute the described analytical procedures. Input data preparation Timing: 15 min This section prepared the foundational inputs for the analysis, which involved preprocessing the raw data to remove low-quality cells and create a cleaned dataset, along with gathering the required resources for network construction, including TFs, motif annotations, and ligand-receptor data. CRITICAL: This section describes the steps for preparing the three essential input files required by SpaGRN to infer spatial GRNs: (1) SRT Data (in .h5ad format): A processed AnnData object containing gene expression counts and spatial coordinates; (2) Motif-to-TF Annotation File (in .tbl format): A database mapping TF binding motifs to their corresponding gene symbols; and (3) Gene-to-Motif Ranking Database (in .feather format): A pre-computed, genome-wide ranking of genes for each transcription factor motif, used for regulon inference. 1.Import the SpaGRN package. Import the SpaGRN package. >import pandas as pd >import scanpy as sc >from spagrn.regulatory_network import InferNetwork as irn 2.Import SRT data.CRITICAL: SpaGRN requires SRT data in AnnData format (.h5ad file) as input. The AnnData object must include:a.A gene expression matrix stores in adata.X or any layer (e.g., adata.layer[‘counts’]). By default, SpaGRN will use adata.X for network inference. Rows correspond to cells/spots (obs) and columns to genes (var).b.A spatial coordinate matrix must be stored as a 2-dimensional numpy array (preferred) or pandas DataFrame in adata.obsm. SpaGRN will automatically look for spatial coordinates in adata.obsm[‘spatial’] by default. If the coordinates are stored under a different key (e.g., ‘X_spatial’), users must specify it using the spatial_coords_key parameter. The coordinate matrix must have rows corresponding to individual cells/spots and columns representing spatial axes. Column 0 is the X-coordinate, column 1 is the Y-coordinate, and column 2 (optional) is the Z-coordinate for 3D SRT data. Import SRT data.CRITICAL: SpaGRN requires SRT data in AnnData format (.h5ad file) as input. The AnnData object must include:a.A gene expression matrix stores in adata.X or any layer (e.g., adata.layer[‘counts’]). By default, SpaGRN will use adata.X for network inference. Rows correspond to cells/spots (obs) and columns to genes (var).b.A spatial coordinate matrix must be stored as a 2-dimensional numpy array (preferred) or pandas DataFrame in adata.obsm. SpaGRN will automatically look for spatial coordinates in adata.obsm[‘spatial’] by default. If the coordinates are stored under a different key (e.g., ‘X_spatial’), users must specify it using the spatial_coords_key parameter. The coordinate matrix must have rows corresponding to individual cells/spots and columns representing spatial axes. Column 0 is the X-coordinate, column 1 is the Y-coordinate, and column 2 (optional) is the Z-coordinate for 3D SRT data. CRITICAL: SpaGRN requires SRT data in AnnData format (.h5ad file) as input. The AnnData object must include: a.A gene expression matrix stores in adata.X or any layer (e.g., adata.layer[‘counts’]). By default, SpaGRN will use adata.X for network inference. Rows correspond to cells/spots (obs) and columns to genes (var). A gene expression matrix stores in adata.X or any layer (e.g., adata.layer[‘counts’]). By default, SpaGRN will use adata.X for network inference. Rows correspond to cells/spots (obs) and columns to genes (var). b.A spatial coordinate matrix must be stored as a 2-dimensional numpy array (preferred) or pandas DataFrame in adata.obsm. SpaGRN will automatically look for spatial coordinates in adata.obsm[‘spatial’] by default. If the coordinates are stored under a different key (e.g., ‘X_spatial’), users must specify it using the spatial_coords_key parameter. The coordinate matrix must have rows corresponding to individual cells/spots and columns representing spatial axes. Column 0 is the X-coordinate, column 1 is the Y-coordinate, and column 2 (optional) is the Z-coordinate for 3D SRT data. A spatial coordinate matrix must be stored as a 2-dimensional numpy array (preferred) or pandas DataFrame in adata.obsm. SpaGRN will automatically look for spatial coordinates in adata.obsm[‘spatial’] by default. If the coordinates are stored under a different key (e.g., ‘X_spatial’), users must specify it using the spatial_coords_key parameter. The coordinate matrix must have rows corresponding to individual cells/spots and columns representing spatial axes. Column 0 is the X-coordinate, column 1 is the Y-coordinate, and column 2 (optional) is the Z-coordinate for 3D SRT data. Note: Gene expression values may be raw counts (recommended) or normalized values. For cell/spot spatial coordinates, a numpy array (np.array) is preferred over pandas DataFrame for optimal computational efficiency. It is the user’s responsibility to ensure the spatial coordinates provided in adata.obsm[spatial_coords_key] are in the same order and correspond to the observations (obs) in the AnnData object. Pre-computed cluster assignments or cell-type annotations should be included if available. >fn = ‘Mouse_brain_cell_bin.h5ad’ #mouse_brain stereo_seq >adata = irn.read_file(fn) Note: The example dataset ‘Mouse_brain_cell_bin.h5ad’ can be downloaded via URL: https://db.cngb.org/stomics/mosta/download/. 3.Perform data cleaning and quality control on the imported data prior to GRN construction.a.Filter spots/cells with fewer than min_genes number of expressed genes.b.Retain genes meeting either criterion: expressed in at least min_cells spots/cells, or with total counts ≥ min_counts.c.Exclude spots/cells exceeding max_genes expressed genes. Perform data cleaning and quality control on the imported data prior to GRN construction.a.Filter spots/cells with fewer than min_genes number of expressed genes.b.Retain genes meeting either criterion: expressed in at least min_cells spots/cells, or with total counts ≥ min_counts.c.Exclude spots/cells exceeding max_genes expressed genes. a.Filter spots/cells with fewer than min_genes number of expressed genes. Filter spots/cells with fewer than min_genes number of expressed genes. b.Retain genes meeting either criterion: expressed in at least min_cells spots/cells, or with total counts ≥ min_counts. Retain genes meeting either criterion: expressed in at least min_cells spots/cells, or with total counts ≥ min_counts. c.Exclude spots/cells exceeding max_genes expressed genes. Exclude spots/cells exceeding max_genes expressed genes. >adata = irn.preprocess(adata, min_genes=1000, min_cells=300, min_counts=10, max_gene_num=4000) CRITICAL: It is mandatory to perform minimal quality control, which removes genes with zero expression in all cells and cells with zero expressed genes before downstream analysis. Failure to perform this basic filtering will cause a division-by-zero error in subsequent calculations. Quality control with custom parameters/strict thresholds is optional if prior quality control exists. 4.Visualization of preprocessed data (optional).>sc.tl.pca(adata)>sc.pp.neighbors(adata)>sc.pl.pca(adata, color='annotation')a.Visualize cell type spatial distribution before reconstructing regulons (Figures 1A–1C); detailed code is available in the GitHub repository at https://github.com/BGI-Qingdao/SpaGRN-STARProtocols.Note: To generate this type of visualization, users must provide cluster or cell-type annotations in the data. Visualization of preprocessed data (optional).>sc.tl.pca(adata)>sc.pp.neighbors(adata)>sc.pl.pca(adata, color='annotation')a.Visualize cell type spatial distribution before reconstructing regulons (Figures 1A–1C); detailed code is available in the GitHub repository at https://github.com/BGI-Qingdao/SpaGRN-STARProtocols.Note: To generate this type of visualization, users must provide cluster or cell-type annotations in the data. >sc.tl.pca(adata) >sc.pp.neighbors(adata) >sc.pl.pca(adata, color='annotation') a.Visualize cell type spatial distribution before reconstructing regulons (Figures 1A–1C); detailed code is available in the GitHub repository at https://github.com/BGI-Qingdao/SpaGRN-STARProtocols.Note: To generate this type of visualization, users must provide cluster or cell-type annotations in the data. Visualize cell type spatial distribution before reconstructing regulons (Figures 1A–1C); detailed code is available in the GitHub repository at https://github.com/BGI-Qingdao/SpaGRN-STARProtocols.Note: To generate this type of visualization, users must provide cluster or cell-type annotations in the data. Note: To generate this type of visualization, users must provide cluster or cell-type annotations in the data. 5.Load auxiliary datasets:a.TF list: a list of TFs of interest. This list is required for the network inference step. Download via pySCENIC_TF_list (https://github.com/aertslab/pySCENIC/tree/master/resources) and TF_lists (https://resources.aertslab.org/cistarget/tf_lists/).b.Ranked whole genome databases: species-specific databases in .feather format. Download via public cisTarget databases (https://resources.aertslab.org/cistarget/databases/).c.Motif-to-TF annotation databases: reference for TF binding sites (in .tbl format). Download via Motif2TF annotations (https://resources.aertslab.org/cistarget/motif2tf/). Load auxiliary datasets:a.TF list: a list of TFs of interest. This list is required for the network inference step. Download via pySCENIC_TF_list (https://github.com/aertslab/pySCENIC/tree/master/resources) and TF_lists (https://resources.aertslab.org/cistarget/tf_lists/).b.Ranked whole genome databases: species-specific databases in .feather format. Download via public cisTarget databases (https://resources.aertslab.org/cistarget/databases/).c.Motif-to-TF annotation databases: reference for TF binding sites (in .tbl format). Download via Motif2TF annotations (https://resources.aertslab.org/cistarget/motif2tf/). a.TF list: a list of TFs of interest. This list is required for the network inference step. Download via pySCENIC_TF_list (https://github.com/aertslab/pySCENIC/tree/master/resources) and TF_lists (https://resources.aertslab.org/cistarget/tf_lists/). TF list: a list of TFs of interest. This list is required for the network inference step. Download via pySCENIC_TF_list (https://github.com/aertslab/pySCENIC/tree/master/resources) and TF_lists (https://resources.aertslab.org/cistarget/tf_lists/). b.Ranked whole genome databases: species-specific databases in .feather format. Download via public cisTarget databases (https://resources.aertslab.org/cistarget/databases/). Ranked whole genome databases: species-specific databases in .feather format. Download via public cisTarget databases (https://resources.aertslab.org/cistarget/databases/). c.Motif-to-TF annotation databases: reference for TF binding sites (in .tbl format). Download via Motif2TF annotations (https://resources.aertslab.org/cistarget/motif2tf/). Motif-to-TF annotation databases: reference for TF binding sites (in .tbl format). Download via Motif2TF annotations (https://resources.aertslab.org/cistarget/motif2tf/). >tfs_fn = 'mouse_tfs.txt' >database_fn = 'mm10_10kbp_up_10kbp_down_full_tx_v10_clust.genes_vs_motifs.rankings.feather' >motif_anno_fn = 'motifs-v10nr_clust-nr.mgi-m0.001-o0.0.tbl' Note: When no TF list is provided, all genes in the expression matrix will be utilized. Alternatively, users may input gene sets of interest, such as highly variable genes. For organisms beyond human, mouse, or Drosophila melanogaster, precomputed whole-genome ranking databases and motif-to-TF annotation files are generally not available from public repositories. In such cases, users must generate custom database files using the Python package create_cisTarget_databases (https://github.com/aertslab/create_cisTarget_databases). 6.Configure ligand-receptor data.a.Import the ligand-receptor data table, and concatenate databases when using multiple ligand-receptor databases. Configure ligand-receptor data.a.Import the ligand-receptor data table, and concatenate databases when using multiple ligand-receptor databases. a.Import the ligand-receptor data table, and concatenate databases when using multiple ligand-receptor databases. Import the ligand-receptor data table, and concatenate databases when using multiple ligand-receptor databases. >niche_human = pd.read_csv('resource/lr_network_human.csv') >niche_mouse = pd.read_csv('resource/lr_network_mouse.csv') >niches = pd.concat([niche_mouse, niche_human]) Note: The pre-compiled ligand-receptor data is provided by NicheNet. This step is optional if ligand-receptor interactions are not being investigated in the GRN inference. Stepwise data analysis and visual representation (A) Spatial distribution of adult mouse hemisphere brain data colored by annotation. (B) UMAP plot of the raw data. Dots are colored by annotation. (C) UMAP plot post gene filtering. Dots are colored by annotation. (D) Retained 2670 genes (10%) after autocorrelation filtering. (E) False Discovery Rate (FDR) density distributions across different spatial co-expression methods. (F) Heatmap displaying ISR scores for receptor-involved regulons. (G–J) Spatial distribution of selected cluster-specific regulons, with color bars indicating normalized ISR scores. Infer the network Timing: 3 h This section accomplishes the core task of GRN inference. The preprocessed data is loaded to create the primary analysis object, followed by configuring the required parameters. The network inference pipeline is then executed via the infer() method call, which ultimately identifies and outputs a list of key TFs and their inferred target genes. Note: Benchmarking was performed on a filtered data matrix (13,408 × 9,799). Using 20 CPU cores and 256 GB of RAM, the total runtime was ∼2 h, with a peak memory usage of ∼30 GB. 7.Create a spagrn object.a.To create a spagrn.InferNetwork class instance, pass in the SRT data (an AnnData object) as the key parameter.b.Specify a project_name parameter that serves as the naming prefix for all output files generated during the analysis. Create a spagrn object.a.To create a spagrn.InferNetwork class instance, pass in the SRT data (an AnnData object) as the key parameter.b.Specify a project_name parameter that serves as the naming prefix for all output files generated during the analysis. a.To create a spagrn.InferNetwork class instance, pass in the SRT data (an AnnData object) as the key parameter. To create a spagrn.InferNetwork class instance, pass in the SRT data (an AnnData object) as the key parameter. b.Specify a project_name parameter that serves as the naming prefix for all output files generated during the analysis. Specify a project_name parameter that serves as the naming prefix for all output files generated during the analysis. Note: If no project_name is explicitly provided, the system will automatically use “project” as the default value. >grn = irn(adata, project_name='mouse_brain') 8.Configure model parameters (Optional).>grn.add_params({'prune_auc_threshold': 0.05, 'rank_threshold': 9000, 'auc_threshold': 0.05})Note: Customization adapts the model to diverse data scenarios. Parameters persist across executions. Key adjustable parameters:a.rank_threshold: size of ranked gene list (default: 1500).b.prune_auc_threshold: AUC fraction during module pruning (default: 0.05).c.nes_threshold: minimum normalized enrichment score for motifs (default: 3.0).d.auc_threshold: fraction of the ranked genome when computing AUC (default: 0.05). Configure model parameters (Optional).>grn.add_params({'prune_auc_threshold': 0.05, 'rank_threshold': 9000, 'auc_threshold': 0.05})Note: Customization adapts the model to diverse data scenarios. Parameters persist across executions. Key adjustable parameters:a.rank_threshold: size of ranked gene list (default: 1500).b.prune_auc_threshold: AUC fraction during module pruning (default: 0.05).c.nes_threshold: minimum normalized enrichment score for motifs (default: 3.0).d.auc_threshold: fraction of the ranked genome when computing AUC (default: 0.05). >grn.add_params({'prune_auc_threshold': 0.05, 'rank_threshold': 9000, 'auc_threshold': 0.05}) Note: Customization adapts the model to diverse data scenarios. Parameters persist across executions. Key adjustable parameters: a.rank_threshold: size of ranked gene list (default: 1500). rank_threshold: size of ranked gene list (default: 1500). b.prune_auc_threshold: AUC fraction during module pruning (default: 0.05). prune_auc_threshold: AUC fraction during module pruning (default: 0.05). c.nes_threshold: minimum normalized enrichment score for motifs (default: 3.0). nes_threshold: minimum normalized enrichment score for motifs (default: 3.0). d.auc_threshold: fraction of the ranked genome when computing AUC (default: 0.05). auc_threshold: fraction of the ranked genome when computing AUC (default: 0.05). 9.Construct GRNs.Note: GRN reconstruction commences upon instantiation of the SpaGRN.InferNetwork object. This step enables customization of computational parameters, categorized below.Note: Parameters are classified as mandatory or optional. Mandatory parameters must be specified, while optional parameters may be adjusted per analytical requirements.a.The mandatory parameters are as follows (see Step 5 for details):b.database_fn: file name of a gene-to-motif ranking file in .feather format.c.motif_anno_fn: a .tbl file contains motif-to-TF annotation.d.tfs_fn: a text file listing known/interested TF genes.i.The optional parameters are as follows:e.gene_list: a list of interested genes for co-expression analysis with TF genes (e.g., a list of highly variable genes, default: None).f.num_workers: number of computational threads (default: None).g.cache: whether to reuse intermediate results (default: False).h.output_dir: output directory path (default: None).i.save_tmp: whether to save intermediate results to disk (default: False).j.layers: key in adata.layers containing count data (uses adata.X if None, default: ‘raw_counts’).k.latent_obsm_key: key in adata.obsm storing cell/spot coordinates (default: ‘spatial’).l.cluster_label: key in adata.obs for cluster/cell type labels (default: ‘annotation’).m.model: null model for gene expression (default: ‘bernoulli’).n.n_neighbors: number of cells/spots to be considered as “neighbors” when computing spatial autocorrelation and gene co-expression (default: 30).o.methods: a list of spatial autocorrelation statistics, options are ‘FDR_C’, ‘FDR_I’, ‘FDR_G’, ‘FDR’ (default: None).p.operation: integration strategy. Options are ‘intersection’ and ‘union’ (default: ‘intersection’).q.mode: bi-variate Geary’s C or bi-variate Moran’s I when computing gene co-expression. Options are ‘moran’ and ‘geary’ (default: ‘moran’).Note: Regarding the operation parameter, the default strict intersection approach prioritizes high-confidence results by exclusively retaining genes identified by all analytical methods. While this minimizes false positives, it may exclude genes exhibiting weaker but biologically relevant spatial expression patterns. For exploratory analyses where sensitivity is paramount, the union approach is recommended, as it aggregates genes identified by any method. This increases sensitivity to potential signals at the cost of a higher risk of false positives. Therefore, the intersection approach is generally recommended for confirmatory analyses demanding high confidence.Note: Regarding the methods parameter, to achieve maximum stringency in gene selection, employing all four statistical methods concurrently is recommended. This multi-method consensus ensures high confidence in identifying genes with robust spatial autocorrelation patterns. Conversely, utilizing fewer methods yields a more inclusive gene set, enhancing sensitivity to potential signals but potentially reducing specificity by increasing false positives. This flexible design allows researchers to calibrate the balance between precision and coverage according to their specific analytical objectives and the required level of evidence.a.Reconstruct the regulatory network by running the following function. Construct GRNs.Note: GRN reconstruction commences upon instantiation of the SpaGRN.InferNetwork object. This step enables customization of computational parameters, categorized below.Note: Parameters are classified as mandatory or optional. Mandatory parameters must be specified, while optional parameters may be adjusted per analytical requirements.a.The mandatory parameters are as follows (see Step 5 for details):b.database_fn: file name of a gene-to-motif ranking file in .feather format.c.motif_anno_fn: a .tbl file contains motif-to-TF annotation.d.tfs_fn: a text file listing known/interested TF genes.i.The optional parameters are as follows:e.gene_list: a list of interested genes for co-expression analysis with TF genes (e.g., a list of highly variable genes, default: None).f.num_workers: number of computational threads (default: None).g.cache: whether to reuse intermediate results (default: False).h.output_dir: output directory path (default: None).i.save_tmp: whether to save intermediate results to disk (default: False).j.layers: key in adata.layers containing count data (uses adata.X if None, default: ‘raw_counts’).k.latent_obsm_key: key in adata.obsm storing cell/spot coordinates (default: ‘spatial’).l.cluster_label: key in adata.obs for cluster/cell type labels (default: ‘annotation’).m.model: null model for gene expression (default: ‘bernoulli’).n.n_neighbors: number of cells/spots to be considered as “neighbors” when computing spatial autocorrelation and gene co-expression (default: 30).o.methods: a list of spatial autocorrelation statistics, options are ‘FDR_C’, ‘FDR_I’, ‘FDR_G’, ‘FDR’ (default: None).p.operation: integration strategy. Options are ‘intersection’ and ‘union’ (default: ‘intersection’).q.mode: bi-variate Geary’s C or bi-variate Moran’s I when computing gene co-expression. Options are ‘moran’ and ‘geary’ (default: ‘moran’).Note: Regarding the operation parameter, the default strict intersection approach prioritizes high-confidence results by exclusively retaining genes identified by all analytical methods. While this minimizes false positives, it may exclude genes exhibiting weaker but biologically relevant spatial expression patterns. For exploratory analyses where sensitivity is paramount, the union approach is recommended, as it aggregates genes identified by any method. This increases sensitivity to potential signals at the cost of a higher risk of false positives. Therefore, the intersection approach is generally recommended for confirmatory analyses demanding high confidence.Note: Regarding the methods parameter, to achieve maximum stringency in gene selection, employing all four statistical methods concurrently is recommended. This multi-method consensus ensures high confidence in identifying genes with robust spatial autocorrelation patterns. Conversely, utilizing fewer methods yields a more inclusive gene set, enhancing sensitivity to potential signals but potentially reducing specificity by increasing false positives. This flexible design allows researchers to calibrate the balance between precision and coverage according to their specific analytical objectives and the required level of evidence.a.Reconstruct the regulatory network by running the following function. Note: GRN reconstruction commences upon instantiation of the SpaGRN.InferNetwork object. This step enables customization of computational parameters, categorized below. Note: Parameters are classified as mandatory or optional. Mandatory parameters must be specified, while optional parameters may be adjusted per analytical requirements. a.The mandatory parameters are as follows (see Step 5 for details): The mandatory parameters are as follows (see Step 5 for details): b.database_fn: file name of a gene-to-motif ranking file in .feather format. database_fn: file name of a gene-to-motif ranking file in .feather format. c.motif_anno_fn: a .tbl file contains motif-to-TF annotation. motif_anno_fn: a .tbl file contains motif-to-TF annotation. d.tfs_fn: a text file listing known/interested TF genes.i.The optional parameters are as follows: tfs_fn: a text file listing known/interested TF genes.i.The optional parameters are as follows: i.The optional parameters are as follows: The optional parameters are as follows: e.gene_list: a list of interested genes for co-expression analysis with TF genes (e.g., a list of highly variable genes, default: None). gene_list: a list of interested genes for co-expression analysis with TF genes (e.g., a list of highly variable genes, default: None). f.num_workers: number of computational threads (default: None). num_workers: number of computational threads (default: None). g.cache: whether to reuse intermediate results (default: False). cache: whether to reuse intermediate results (default: False). h.output_dir: output directory path (default: None). output_dir: output directory path (default: None). i.save_tmp: whether to save intermediate results to disk (default: False). save_tmp: whether to save intermediate results to disk (default: False). j.layers: key in adata.layers containing count data (uses adata.X if None, default: ‘raw_counts’). layers: key in adata.layers containing count data (uses adata.X if None, default: ‘raw_counts’). k.latent_obsm_key: key in adata.obsm storing cell/spot coordinates (default: ‘spatial’). latent_obsm_key: key in adata.obsm storing cell/spot coordinates (default: ‘spatial’). l.cluster_label: key in adata.obs for cluster/cell type labels (default: ‘annotation’). cluster_label: key in adata.obs for cluster/cell type labels (default: ‘annotation’). m.model: null model for gene expression (default: ‘bernoulli’). model: null model for gene expression (default: ‘bernoulli’). n.n_neighbors: number of cells/spots to be considered as “neighbors” when computing spatial autocorrelation and gene co-expression (default: 30). n_neighbors: number of cells/spots to be considered as “neighbors” when computing spatial autocorrelation and gene co-expression (default: 30). o.methods: a list of spatial autocorrelation statistics, options are ‘FDR_C’, ‘FDR_I’, ‘FDR_G’, ‘FDR’ (default: None). methods: a list of spatial autocorrelation statistics, options are ‘FDR_C’, ‘FDR_I’, ‘FDR_G’, ‘FDR’ (default: None). p.operation: integration strategy. Options are ‘intersection’ and ‘union’ (default: ‘intersection’). operation: integration strategy. Options are ‘intersection’ and ‘union’ (default: ‘intersection’). q.mode: bi-variate Geary’s C or bi-variate Moran’s I when computing gene co-expression. Options are ‘moran’ and ‘geary’ (default: ‘moran’).Note: Regarding the operation parameter, the default strict intersection approach prioritizes high-confidence results by exclusively retaining genes identified by all analytical methods. While this minimizes false positives, it may exclude genes exhibiting weaker but biologically relevant spatial expression patterns. For exploratory analyses where sensitivity is paramount, the union approach is recommended, as it aggregates genes identified by any method. This increases sensitivity to potential signals at the cost of a higher risk of false positives. Therefore, the intersection approach is generally recommended for confirmatory analyses demanding high confidence.Note: Regarding the methods parameter, to achieve maximum stringency in gene selection, employing all four statistical methods concurrently is recommended. This multi-method consensus ensures high confidence in identifying genes with robust spatial autocorrelation patterns. Conversely, utilizing fewer methods yields a more inclusive gene set, enhancing sensitivity to potential signals but potentially reducing specificity by increasing false positives. This flexible design allows researchers to calibrate the balance between precision and coverage according to their specific analytical objectives and the required level of evidence. mode: bi-variate Geary’s C or bi-variate Moran’s I when computing gene co-expression. Options are ‘moran’ and ‘geary’ (default: ‘moran’).Note: Regarding the operation parameter, the default strict intersection approach prioritizes high-confidence results by exclusively retaining genes identified by all analytical methods. While this minimizes false positives, it may exclude genes exhibiting weaker but biologically relevant spatial expression patterns. For exploratory analyses where sensitivity is paramount, the union approach is recommended, as it aggregates genes identified by any method. This increases sensitivity to potential signals at the cost of a higher risk of false positives. Therefore, the intersection approach is generally recommended for confirmatory analyses demanding high confidence.Note: Regarding the methods parameter, to achieve maximum stringency in gene selection, employing all four statistical methods concurrently is recommended. This multi-method consensus ensures high confidence in identifying genes with robust spatial autocorrelation patterns. Conversely, utilizing fewer methods yields a more inclusive gene set, enhancing sensitivity to potential signals but potentially reducing specificity by increasing false positives. This flexible design allows researchers to calibrate the balance between precision and coverage according to their specific analytical objectives and the required level of evidence. Note: Regarding the operation parameter, the default strict intersection approach prioritizes high-confidence results by exclusively retaining genes identified by all analytical methods. While this minimizes false positives, it may exclude genes exhibiting weaker but biologically relevant spatial expression patterns. For exploratory analyses where sensitivity is paramount, the union approach is recommended, as it aggregates genes identified by any method. This increases sensitivity to potential signals at the cost of a higher risk of false positives. Therefore, the intersection approach is generally recommended for confirmatory analyses demanding high confidence. Note: Regarding the methods parameter, to achieve maximum stringency in gene selection, employing all four statistical methods concurrently is recommended. This multi-method consensus ensures high confidence in identifying genes with robust spatial autocorrelation patterns. Conversely, utilizing fewer methods yields a more inclusive gene set, enhancing sensitivity to potential signals but potentially reducing specificity by increasing false positives. This flexible design allows researchers to calibrate the balance between precision and coverage according to their specific analytical objectives and the required level of evidence. a.Reconstruct the regulatory network by running the following function. Reconstruct the regulatory network by running the following function. >grn.infer(database_fn, motif_anno_fn, tfs_fn, niche_df=niches, gene_list=None, num_workers=20, cache=True, output_dir='exp/output', save_tmp=True, layers='counts', latent_obsm_key='spatial', cluster_label='annotation', model='bernoulli', n_neighbors=10, methods=['FDR_I','FDR_C','FDR_G'], operation='intersection', mode='geary') CRITICAL: The primary output of the network inference step is a comprehensive AnnData object. SpaGRN integrates all results into this single, structured object for downstream analysis and visualization (see Step 10 for details). Optional: If the save_tmp=True parameter is enabled, intermediate files will be saved (see Step 14 for details). Visualization of results Timing: 30 min This section focuses on extracting and graphically summarizing the results from the AnnData object generated in the previous step. It details the methods for data access and visualization, which transform the complex network data into interpretable plots, including the spatial distribution of regulons and regulon activity heatmaps. 10.Interpret results.Note: The GRN results are stored in the AnnData object. Load the results file by running:>adata = sc.read_h5ad('project_spagrn.h5ad')a.Receptors for each regulon reside in adata.uns[‘receptor_dict’] as a dictionary. Access the regulon dictionary for network details using:>adata.uns['regulon_dict']b.Receptors of each regulon are stored in adata.uns under key receptor_dict in dictionary format. To retrieve the receptors for each regulon, access the dictionary in:>adata.uns['receptor_dict']c.Intracellular Signaling Regulation (ISR) scores (n cells × m regulons) reside in adata.obsm[‘isr’] as a pd.DataFrame. Extract the ISR scores with: Interpret results.Note: The GRN results are stored in the AnnData object. Load the results file by running:>adata = sc.read_h5ad('project_spagrn.h5ad')a.Receptors for each regulon reside in adata.uns[‘receptor_dict’] as a dictionary. Access the regulon dictionary for network details using:>adata.uns['regulon_dict']b.Receptors of each regulon are stored in adata.uns under key receptor_dict in dictionary format. To retrieve the receptors for each regulon, access the dictionary in:>adata.uns['receptor_dict']c.Intracellular Signaling Regulation (ISR) scores (n cells × m regulons) reside in adata.obsm[‘isr’] as a pd.DataFrame. Extract the ISR scores with: Note: The GRN results are stored in the AnnData object. Load the results file by running: >adata = sc.read_h5ad('project_spagrn.h5ad') a.Receptors for each regulon reside in adata.uns[‘receptor_dict’] as a dictionary. Access the regulon dictionary for network details using:>adata.uns['regulon_dict'] Receptors for each regulon reside in adata.uns[‘receptor_dict’] as a dictionary. Access the regulon dictionary for network details using:>adata.uns['regulon_dict'] >adata.uns['regulon_dict'] b.Receptors of each regulon are stored in adata.uns under key receptor_dict in dictionary format. To retrieve the receptors for each regulon, access the dictionary in:>adata.uns['receptor_dict'] Receptors of each regulon are stored in adata.uns under key receptor_dict in dictionary format. To retrieve the receptors for each regulon, access the dictionary in:>adata.uns['receptor_dict'] >adata.uns['receptor_dict'] c.Intracellular Signaling Regulation (ISR) scores (n cells × m regulons) reside in adata.obsm[‘isr’] as a pd.DataFrame. Extract the ISR scores with: Intracellular Signaling Regulation (ISR) scores (n cells × m regulons) reside in adata.obsm[‘isr’] as a pd.DataFrame. Extract the ISR scores with: >adata.obsm['isr'] 11.Plot the spatial distribution of regulons in 2D.a.Plot the 2D spatial distribution of a regulon using plot_2d(). Plot the spatial distribution of regulons in 2D.a.Plot the 2D spatial distribution of a regulon using plot_2d(). a.Plot the 2D spatial distribution of a regulon using plot_2d(). Plot the 2D spatial distribution of a regulon using plot_2d(). Note: Points denote spatial coordinates; color intensity reflects normalized ISR values. >import spagrn.plot as prn >prn.plot_2d(adata, adata.obsm['isr'], pos_label='spatial', reg_name=' Pbx1(+)', fn='Pbx1.png') 12.Plot the spatial distribution of regulons in 3D.a.Visualize regulon activity in 3D using plot_3d_reg(). Adjust parameters like vmin, vmax, and alpha to control the color scale and point transparency. Plot the spatial distribution of regulons in 3D.a.Visualize regulon activity in 3D using plot_3d_reg(). Adjust parameters like vmin, vmax, and alpha to control the color scale and point transparency. a.Visualize regulon activity in 3D using plot_3d_reg(). Adjust parameters like vmin, vmax, and alpha to control the color scale and point transparency. Visualize regulon activity in 3D using plot_3d_reg(). Adjust parameters like vmin, vmax, and alpha to control the color scale and point transparency. Note: Points denote spatial coordinates; color intensity reflects normalized ISR values. >prn.plot_3d_reg(adata, adata.obsm['isr'], pos_label='spatial', reg_name=' Pdp1', vmin=0, vmax=4, alpha=0.3, fn='Pdp1.pdf') 13.Plot regulon activity heatmaps.Note: isr_heatmap visualizes regulon activity across cells, enabling comparative analysis of cellular states. Clustering reveals groups of cells with co-activated regulons, highlighting recurrent network states.a.Generate an ISR score heatmap by running the following: Plot regulon activity heatmaps.Note: isr_heatmap visualizes regulon activity across cells, enabling comparative analysis of cellular states. Clustering reveals groups of cells with co-activated regulons, highlighting recurrent network states.a.Generate an ISR score heatmap by running the following: Note: isr_heatmap visualizes regulon activity across cells, enabling comparative analysis of cellular states. Clustering reveals groups of cells with co-activated regulons, highlighting recurrent network states. a.Generate an ISR score heatmap by running the following: Generate an ISR score heatmap by running the following: >prn.isr_heatmap(adata, adata.obsm['isr'], cluster_label='annotation', rss_fn=f'{out_di/{method}_regulon_specificity_scores.txt', topn=3, subset=False, save=True, fn=f'{out_dir}/{method}_clusters_heatmap_top10.png', legend_fn=f"{out_dir}/{method}_rss_celltype_legend_top10.png") Note: isr_heatmap has O(n3) time complexity with cell count. For datasets exceeding 10,000 cells, the runtime may exceed 3 h. Set subset to True and choose a subset_size number to reduce computation and prevent memory issues. 14.Analyze intermediate results.Note: When save_tmp=True is enabled in Step 9, the pipeline saves intermediate files at multiple stages of the analysis. These include:a.more_stats.csv: a genes-by-methods of adjusted p-values. This file can be used in adjusting methods selection strategy. Quickly diagnose if an overly stringent filter accidentally removed too much data.b.selected_genes.txt: a list of genes that were significantly spatial autocorrelated, adjusted p-values > 0.05, and were used for spatial co-expression computation. This file can be used to understand which genes were deemed biologically relevant for spatial network analysis.c.adj.csv: a gene-gene adjacency matrix, representing the strength of spatial co-expression between pairs of genes. The file shows how different parameters affect the network topology. It can also be used for custom network analysis in software like Cytoscape.d.modules.pkl: stores a serialized Python object containing the TF-gene modules prior to cis-regulatory motif enrichment analysis. This enables the inspection of the raw modules to understand the initial grouping of genes before regulatory filtering is applied. This helps verify that the co-expression logic is sound.e.motifs.csv: a table of enriched motifs, containing motif ID, corresponding TF, p-values, and annotation, etc. The file can be used for investigating the basis for regulon inference and validating the biological plausibility of the inferred regulons.f.regulons.json: stores a list of all inferred regulons in a standardized JSON format. Keys are TFs of the regulons, and the values are a list of genes regulated by the TF. The file allows for quick inspection of regulon composition.g.isr_mtx.csv: a cells-by-regulons matrix containing the ISR scores for each regulon in each cell. This matrix serves as the direct input for generating heatmaps to display and compare regulon activity levels across cells. Furthermore, when combined with the spatial coordinates, this file can be used for the visualization of regulon activity in 2D or 3D space.Note: Together with the final h5ad output, these intermediate files allow users to perform quality checks at each step, compare alternative parameter settings, and integrate intermediate matrices with external tools for custom downstream analyses. Additionally, saving intermediate files enables a caching mechanism, which can save computational time. Analyze intermediate results.Note: When save_tmp=True is enabled in Step 9, the pipeline saves intermediate files at multiple stages of the analysis. These include:a.more_stats.csv: a genes-by-methods of adjusted p-values. This file can be used in adjusting methods selection strategy. Quickly diagnose if an overly stringent filter accidentally removed too much data.b.selected_genes.txt: a list of genes that were significantly spatial autocorrelated, adjusted p-values > 0.05, and were used for spatial co-expression computation. This file can be used to understand which genes were deemed biologically relevant for spatial network analysis.c.adj.csv: a gene-gene adjacency matrix, representing the strength of spatial co-expression between pairs of genes. The file shows how different parameters affect the network topology. It can also be used for custom network analysis in software like Cytoscape.d.modules.pkl: stores a serialized Python object containing the TF-gene modules prior to cis-regulatory motif enrichment analysis. This enables the inspection of the raw modules to understand the initial grouping of genes before regulatory filtering is applied. This helps verify that the co-expression logic is sound.e.motifs.csv: a table of enriched motifs, containing motif ID, corresponding TF, p-values, and annotation, etc. The file can be used for investigating the basis for regulon inference and validating the biological plausibility of the inferred regulons.f.regulons.json: stores a list of all inferred regulons in a standardized JSON format. Keys are TFs of the regulons, and the values are a list of genes regulated by the TF. The file allows for quick inspection of regulon composition.g.isr_mtx.csv: a cells-by-regulons matrix containing the ISR scores for each regulon in each cell. This matrix serves as the direct input for generating heatmaps to display and compare regulon activity levels across cells. Furthermore, when combined with the spatial coordinates, this file can be used for the visualization of regulon activity in 2D or 3D space.Note: Together with the final h5ad output, these intermediate files allow users to perform quality checks at each step, compare alternative parameter settings, and integrate intermediate matrices with external tools for custom downstream analyses. Additionally, saving intermediate files enables a caching mechanism, which can save computational time. Note: When save_tmp=True is enabled in Step 9, the pipeline saves intermediate files at multiple stages of the analysis. These include: a.more_stats.csv: a genes-by-methods of adjusted p-values. This file can be used in adjusting methods selection strategy. Quickly diagnose if an overly stringent filter accidentally removed too much data. more_stats.csv: a genes-by-methods of adjusted p-values. This file can be used in adjusting methods selection strategy. Quickly diagnose if an overly stringent filter accidentally removed too much data. b.selected_genes.txt: a list of genes that were significantly spatial autocorrelated, adjusted p-values > 0.05, and were used for spatial co-expression computation. This file can be used to understand which genes were deemed biologically relevant for spatial network analysis. selected_genes.txt: a list of genes that were significantly spatial autocorrelated, adjusted p-values > 0.05, and were used for spatial co-expression computation. This file can be used to understand which genes were deemed biologically relevant for spatial network analysis. c.adj.csv: a gene-gene adjacency matrix, representing the strength of spatial co-expression between pairs of genes. The file shows how different parameters affect the network topology. It can also be used for custom network analysis in software like Cytoscape. adj.csv: a gene-gene adjacency matrix, representing the strength of spatial co-expression between pairs of genes. The file shows how different parameters affect the network topology. It can also be used for custom network analysis in software like Cytoscape. d.modules.pkl: stores a serialized Python object containing the TF-gene modules prior to cis-regulatory motif enrichment analysis. This enables the inspection of the raw modules to understand the initial grouping of genes before regulatory filtering is applied. This helps verify that the co-expression logic is sound. modules.pkl: stores a serialized Python object containing the TF-gene modules prior to cis-regulatory motif enrichment analysis. This enables the inspection of the raw modules to understand the initial grouping of genes before regulatory filtering is applied. This helps verify that the co-expression logic is sound. e.motifs.csv: a table of enriched motifs, containing motif ID, corresponding TF, p-values, and annotation, etc. The file can be used for investigating the basis for regulon inference and validating the biological plausibility of the inferred regulons. motifs.csv: a table of enriched motifs, containing motif ID, corresponding TF, p-values, and annotation, etc. The file can be used for investigating the basis for regulon inference and validating the biological plausibility of the inferred regulons. f.regulons.json: stores a list of all inferred regulons in a standardized JSON format. Keys are TFs of the regulons, and the values are a list of genes regulated by the TF. The file allows for quick inspection of regulon composition. regulons.json: stores a list of all inferred regulons in a standardized JSON format. Keys are TFs of the regulons, and the values are a list of genes regulated by the TF. The file allows for quick inspection of regulon composition. g.isr_mtx.csv: a cells-by-regulons matrix containing the ISR scores for each regulon in each cell. This matrix serves as the direct input for generating heatmaps to display and compare regulon activity levels across cells. Furthermore, when combined with the spatial coordinates, this file can be used for the visualization of regulon activity in 2D or 3D space.Note: Together with the final h5ad output, these intermediate files allow users to perform quality checks at each step, compare alternative parameter settings, and integrate intermediate matrices with external tools for custom downstream analyses. Additionally, saving intermediate files enables a caching mechanism, which can save computational time. isr_mtx.csv: a cells-by-regulons matrix containing the ISR scores for each regulon in each cell. This matrix serves as the direct input for generating heatmaps to display and compare regulon activity levels across cells. Furthermore, when combined with the spatial coordinates, this file can be used for the visualization of regulon activity in 2D or 3D space.Note: Together with the final h5ad output, these intermediate files allow users to perform quality checks at each step, compare alternative parameter settings, and integrate intermediate matrices with external tools for custom downstream analyses. Additionally, saving intermediate files enables a caching mechanism, which can save computational time. Note: Together with the final h5ad output, these intermediate files allow users to perform quality checks at each step, compare alternative parameter settings, and integrate intermediate matrices with external tools for custom downstream analyses. Additionally, saving intermediate files enables a caching mechanism, which can save computational time. 15.Interactively navigate atlas (optional). Interactively navigate atlas (optional). Note: The atlas facilitates simultaneous visualization of cell-type distributions, gene expression patterns, and regulatory network architectures within their native spatial contexts. Its customizable interactive features markedly improve the efficiency of data exploration and analytical validation. A tutorial video illustrating atlas navigation and functionality is included as supplementary material (Methods Video S1). Methods Video S1. Navigating the SpaGRN online database and its interactive 3D visualization interface, related to Step 15 Expected outcomes Upon completion of the analysis, an AnnData file (e.g., Mouse_brain_cell_bin.h5ad) that encapsulates all analytical results is generated in the specified output directory. Within this file, the.uns attribute stores the inferred regulons and their associated receptor-TF regulatory dictionaries. These represent putative transcriptional modules regulated by upstream receptors. Users can interpret these dictionaries to identify which TFs are linked to specific signaling pathways. Concurrently, the.obsm attribute contains the ISR activity matrix, which quantifies regulon activity per cell or spatial location. Higher ISR scores indicate stronger predicted activity of the corresponding regulon. Users should compare ISR score distributions across cell types or regions to identify cluster-specific or spatially restricted regulatory programs. These data can be visualized in multiple ways. For example, the spatial distribution of annotated cell types across the adult mouse hemisphere is shown in Figure 1A, and dimensionality reduction before and after gene filtering is illustrated in Figures 1B and 1C. These plots allow users to evaluate the effect of gene filtering on clustering structure. If clusters remain consistent while the number of retained genes is reduced, it suggests that filtering preserves biological signal while removing noise. The pie chart in Figure 1D illustrates the proportion of genes exhibiting significant spatial autocorrelation among all expressed genes. The impact of different spatial co-expression methods on FDR is depicted in Figure 1E. The density plots help assess the stringency of different spatial co-expression methods. A left-shifted FDR distribution indicates more confident regulon detection. Regulatory programs can be further explored through heatmaps of ISR scores (Figure 1F) and spatial maps of cluster-specific regulons (Figures 1G–1J). Heatmap of ISR scores highlights cell-type-specific regulons. Rows correspond to regulons, and columns to cell types; high values (warmer colors) denote strong activity. Users can identify which regulons are enriched in particular cell types. Spatial distribution maps visualize the spatial heterogeneity of selected regulons. Distinct regional enrichment patterns can reveal how microenvironmental cues shape regulatory programs in situ. Collectively, these outputs elucidate the intricate gene regulatory programs within the tissue that are fundamentally shaped by the spatial microenvironment. The code to generate Figures 1A–1E is available in the GitHub repository at https://github.com/BGI-Qingdao/SpaGRN-STARProtocols. The code for Figures 1F–1J can be found in Steps 11 and 13. Quantification and statistical analysis To validate SpaGRN’s accuracy in identifying spatial patterns, we employed an authentic mouse brain SRT dataset. Regarding computational performance, the core regulon inference procedure (grn.infer()) represents the primary computational bottleneck in SpaGRN. Runtime scales with dataset dimensions (number of cells/spots and genes) and user-defined parameters (e.g., num_workers specifying parallel CPU cores). To facilitate resource estimation, we conducted benchmark tests using the same Stereo-seq mouse brain dataset (50,140 cells × 25,879 genes) (Figure 2). Firstly, we performed minimal filtering to remove genes that have zero expression values across all cells and cells that have zero genes. Following filtering, the dataset dimensions were reduced to 50,140 cells and 23,472 genes. As the number of cells (Figure 2A) or genes (Figure 2B) increases, both computation time and memory usage rise accordingly. On a Linux system (20 CPU cores, 256 GB RAM), SpaGRN completed inference in approximately 1 hour, demonstrating substantial efficiency for large-scale analyses. Time and maximum memory usage of SpaGRN on the mouse brain Stereo-seq data (A) Memory and time requirements of SpaGRN at various cell counts (1000, 2500, 5,000, 10,000, 20,000, 30,000, 40,000, and 50,140), with a constant gene count of 23,472. When the number of cells is set to 1,000, all data are filtered out during quality control, preventing any downstream analysis. The blue dots indicate the peak memory required for SpaGRN at each parameter setting. The red asterisks represent the time taken to run SpaGRN under each parameter setting. (B) Memory and time requirements of SpaGRN with varying gene counts (1,000, 5,000, 10,000, 15,000, 20,000, and 23,472), with a constant cell count of 50,140. When the number of genes is set to 1,000, 5,000, or 10,000, all data are filtered out during quality control, preventing any downstream analysis. The red asterisks and the blue dots have the same meaning as in (A). Following regulon derivation and single-cell ISR score matrix generation, quantitative analyses enable mechanistic insights into cellular signaling networks. Integration of receptors, TFs, and target genes permits reconstruction of cell-cell communication pathways, visualized as Sankey diagrams (Figures 3A and 3B) to illustrate directional signaling cascades (e.g., ligand-receptor interactions triggering downstream transcriptional responses); detailed code is available in the GitHub repository at https://github.com/BGI-Qingdao/SpaGRN-STARProtocols. SpaGRN enables mechanistic insights into inter-intracellular signaling networks by integrating receptors, TFs, and target genes (A and B) Sankey diagram depicting the flow from potential receptor genes to downstream TFs and subsequently to target genes. Line thickness is weighted uniformly (A) or based on quantitative measures of interest (B). (C) Co-regulation network for two regulons: Maf(+) and Dlx1(+). TFs appear in orange, shared target genes in green, exclusive target genes in blue, and influential receptor genes in magenta. Two complementary Sankey visualization modes accommodate diverse analytical needs. 1.Uniform mode: Depicts molecular interactions with fixed-width edges (Figure 3A). Uniform mode: Depicts molecular interactions with fixed-width edges (Figure 3A). 2.Weighted mode: Dynamically scales edge thickness to reflect quantitative differences (e.g., expression fold-changes), with gradient coloring indicating directional effects (Figure 3B). Weighted mode: Dynamically scales edge thickness to reflect quantitative differences (e.g., expression fold-changes), with gradient coloring indicating directional effects (Figure 3B). Alternatively, users can perform basic topological and other network analyses on the GRNs, which are visualized in Cytoscape (Figure 3C) and built from the receptor-TF-target results in the AnnData object (adata.uns[‘regulon_dict’] and adata.uns[‘receptor_dict’]). This allows for the identification of key regulators, hub genes, and comparative analysis of network architecture. The ISR regulon activity matrix (analogous to SCENIC’s AUC matrix) enables clustering analysis to group cells or conditions by regulatory activity patterns. This reveals key differences in signaling regulation across samples, mapping signaling hierarchies while identifying functionally distinct cellular states driven by pathway activation heterogeneity. Furthermore, SpaGRN integrates SRT data across multiple tissue types and SRT platforms to construct an interactive 3D online atlas. This comprehensive resource encompasses diverse biological systems (including human brain, mouse brain, and Drosophila embryonic development), delivering a multi-tissue spatial atlas for researchers. Limitations While SpaGRN represents a powerful framework, users must acknowledge its inherent constraints. First, inferred regulatory relationships are prone to false positives and false negatives; thus, critical findings require experimental validation for confirmation. Second, SpaGRN’s performance depends critically on input data quality and the accuracy and completeness of underlying knowledge bases, such as TF motif and ligand-receptor databases. Inaccurate inputs or incomplete annotations may yield an insufficiently characterized regulatory network. Moreover, as these knowledge bases are primarily derived from model organisms like human and mouse, the framework’s applicability and accuracy may diminish for non-model organisms or poorly characterized tissues. Finally, the current design focuses on spatially proximate regulatory interactions and may not adequately capture long-range intercellular interactions or non-cell-autonomous regulatory mechanisms. Troubleshooting Problem 1 Users may encounter errors such as “A GDAL API version must be specified. Provide a path to gdal-config using a GDAL_CONFIG environment variable or use a GDAL_VERSION environment variable” and “Failed to build installable wheels for some pyproject.toml based projects (h5py)”. This issue is related to setting up the computational environment (related to Step 3, Method A of before you begin). Potential solution These errors are compilation issues caused by outdated versions of dependent packages in the environment. Update all dependent packages to their latest compatible versions, as outdated packages often lead to compilation conflicts. If the problem persists, install the problematic packages individually using conda, which can resolve version-specific compilation issues by managing dependencies more effectively within its environment. Problem 2 Users may encounter dependency conflicts when installing the latest version of SpaGRN on GitHub (related to Step 3, Method B of before you begin). Potential solution First, confirm the Python version is 3.8. Next, identify any conflicting packages, create a new requirements.txt, and install the dependencies using pip install -r requirements.txt. Problem 3 The intermediate file more_stats.csv contains numerous genes with zero values (related to Steps 9 and 14). Potential solution The more_stats.csv file stores p-values and adjusted p-values generated from spatial autocorrelation statistics for each gene. A small p-value indicates that the observed spatial gene expression pattern is statistically significant and unlikely to occur by chance. Problem 4 A gene of interest is absent from the selected_genes.txt file (related to Steps 9 and 14). Potential solution The selected_genes.txt file lists genes exhibiting strong spatial autocorrelation. Omission of a specific gene suggests its spatial expression pattern lacks statistically significant spatial dependency. To increase gene retention during selection, modify the filtering strategy as follows. •Union-based approach: Combine the output (union) of all spatial autocorrelation statistical methods instead of using their intersection (the default conservative approach). Union-based approach: Combine the output (union) of all spatial autocorrelation statistical methods instead of using their intersection (the default conservative approach). •Method reduction: Apply fewer statistical methods and take the intersection of genes selected by the remaining methods. Method reduction: Apply fewer statistical methods and take the intersection of genes selected by the remaining methods. Problem 5 Encountering AssertionError: Signatures dataframe is empty! (related to Step 9). Potential solution This error indicates that no regulons were detected. To reconstruct potential regulons, increase the rank_threshold or decrease the auc_threshold. Problem 6 No regulons regulated by the specified TF were identified in the results (related to Step 9). Potential solution Regulon identification employs a rigorous multi-step validation process that distinguishes true regulons from simple co-expression modules. The workflow initiates with establishing TF-motif associations based on documented motif positions within the genome. Subsequently, motif enrichment analysis is performed on experimental data to detect potential target genes downstream of these motifs. A TF-target set qualifies as a valid regulon only upon satisfying two stringent criteria: (1) demonstration of robust co-expression or association within the dataset, and (2) statistically significant enrichment of corresponding motifs, as quantified by the Normalized Enrichment Score (NES). In the current analysis, genes of interest failed to satisfy the selection criteria during this process. This typically occurs when genes do not meet either the gene ranking threshold (rank_threshold) or the motif enrichment significance threshold (nes_threshold). To recover potential regulons, consider parameter adjustment. •Increase rank_threshold to expand the pool of candidate genes. Increase rank_threshold to expand the pool of candidate genes. •Decrease nes_threshold to relax the requirement for motif enrichment significance. Decrease nes_threshold to relax the requirement for motif enrichment significance. While threshold adjustment may expand regulon detection, it inherently reduces result specificity by increasing false positives. Problem 7 Regulons lack target genes (related to Step 9). Potential solution To recover potential target genes, adjust filtering thresholds. •Increase rank_threshold to expand candidate gene inclusion. Increase rank_threshold to expand candidate gene inclusion. •Decrease nes_threshold to relax motif enrichment significance requirements. Decrease nes_threshold to relax motif enrichment significance requirements. Problem 8 ValueError: A gene signature must have at least one gene (related to Step 9). Potential solution This error occurs when lenient parameters (e.g., high rank_threshold or low nes_threshold) permit motifs without target genes to pass filtering. Resolve by: a. Applying stricter filtering thresholds, or b. Modifying the error-handling code to retain only non-empty “TargetGenes” columns while maintaining current thresholds. Problem 9 When a step encounters an error causing pipeline termination, can analysis resume from the failed step rather than restarting entirely? (related to Step 9). Potential solution SpaGRN’s caching mechanism allows restarting from the point of failure when cache=True and save_tmp=True are enabled. The framework reloads intermediate files generated during prior executions, bypassing redundant computations through efficient reuse of previously calculated results. Problem 10 Runtime encounters ModuleNotFoundError for the pysal module (related to Step 9). Potential solution This error indicates that pysal, a critical dependency for the SpaGRN framework responsible for spatial statistical computations, is not installed or accessible within the active Python environment. To resolve this issue, activate the correct Python environment in your terminal and execute the following command to install the required package: This error arises when the pysal library—a critical dependency for the SpaGRN framework that facilitates spatial statistical computations (e.g., spatial weight matrix generation, spatial autocorrelation analysis, and spatial regression modeling)—is either not installed or inaccessible within the active Python environment. To resolve this issue, activate the target Python environment in your terminal (e.g., using Conda: conda activate spagrn). Install pysal using the following commands: $pip install pysal Problem 11 “KeyError: ‘counts’” occurs during the network inference step (grn.infer()) (related to Step 9). Potential solution The key name for the count data in adata.layers is not ‘counts’. You can print the ‘adata’ object in Step 2 to view the key names. >print(adata) Problem 12 OverflowError: cannot convert float infinity to integer in grn.infer() (related to Step 9). Potential solution This occurs when the AnnData object passed to grn.infer() is empty due to excessively stringent preprocessing filters. Mitigate by. •Relaxing filtering parameters in Step 3 of before you begin. Relaxing filtering parameters in Step 3 of before you begin. •Validating data retention post-filtering using print(adata.shape) before inference. Validating data retention post-filtering using print(adata.shape) before inference. Problem 13 The network inference step, grn.infer(), exhibits excessively slow computational performance (related to Setting up the computational environment). Potential solution This typically results from insufficient allocation of parallel processing resources. SpaGRN leverages parallel computing architectures. To accelerate computation, set the num_workers parameter to match the number of available CPU cores on your system (or slightly fewer to avoid resource contention). For example: num_workers=40. Problem 14 Failure to detect regulons in rare cell types or small tissue regions (related to Step 9 and expected outcomes). Potential solution Signals from rare cell types or spatially restricted regions can be masked by dominant adjacent signals due to sample size imbalance. Mitigate this via. •Prioritize the use of the ‘moran’ mode within the grn.infer() function (i.e., mode=‘moran’). Moran’s I spatial autocorrelation statistic demonstrates superior sensitivity for rare cell populations. Prioritize the use of the ‘moran’ mode within the grn.infer() function (i.e., mode=‘moran’). Moran’s I spatial autocorrelation statistic demonstrates superior sensitivity for rare cell populations. •Manually subset tissue data to the target region before analysis. This increases the relative abundance of target cells, enhancing detection sensitivity. Isolate regions of interest to increase target population representation. Manually subset tissue data to the target region before analysis. This increases the relative abundance of target cells, enhancing detection sensitivity. Isolate regions of interest to increase target population representation. Problem 15 The spatial patterns of inferred regulons lack specificity (related to Expected outcome). Potential solution This may arise from mismatched statistical methods or suboptimal parameterization. •The selected statistical method for identifying spatial genes may be unsuitable for the current dataset. Test alternative methods parameter configurations (e.g., methods=[‘FDR_I’] or methods=[‘FDR_C’]) to identify optimal gene-expression spatial dependency modeling. The selected statistical method for identifying spatial genes may be unsuitable for the current dataset. Test alternative methods parameter configurations (e.g., methods=[‘FDR_I’] or methods=[‘FDR_C’]) to identify optimal gene-expression spatial dependency modeling. •The n_neighbors parameter may not accurately reflect the tissue’s underlying spatial architecture. Adjust this parameter (default is 10) based on the resolution and cell density of your data. High cell density: Use smaller values (e.g., 5–15) to prioritize local neighborhoods. Low cell density: Use larger values (e.g., 20–50) to capture broader spatial contexts. The n_neighbors parameter may not accurately reflect the tissue’s underlying spatial architecture. Adjust this parameter (default is 10) based on the resolution and cell density of your data. High cell density: Use smaller values (e.g., 5–15) to prioritize local neighborhoods. Low cell density: Use larger values (e.g., 20–50) to capture broader spatial contexts. Resource availability Lead contact Further information and requests for resources should be directed to and will be fulfilled by the lead contact, Mengyang Xu (xumengyang@genomics.cn). Technical contact Questions about the technical specifics of performing the protocol should be directed to and will be answered by the technical contact, Yao Li (liyao1@genomics.cn). Materials availability This study did not generate unique reagents. Data and code availability •All datasets reported in this study are publicly available and listed in the key resources table. All datasets reported in this study are publicly available and listed in the key resources table. •The original code is accessible via our GitHub repository (https://github.com/BGI-Qingdao/SpaGRN) and has been permanently archived in Zenodo (https://doi.org/10.5281/zenodo.14925041). An open-source interactive database for querying and visualizing SpaGRN’s results is hosted at https://www.bgiocean.com/SpaGRN, where all related data and transcription factor databases can be downloaded. The original code is accessible via our GitHub repository (https://github.com/BGI-Qingdao/SpaGRN) and has been permanently archived in Zenodo (https://doi.org/10.5281/zenodo.14925041). An open-source interactive database for querying and visualizing SpaGRN’s results is hosted at https://www.bgiocean.com/SpaGRN, where all related data and transcription factor databases can be downloaded. •Any additional information required to reanalyze the data reported in this paper is available from the lead contact upon request. Any additional information required to reanalyze the data reported in this paper is available from the lead contact upon request. Acknowledgments This work was supported by the Shenzhen Science and Technology Program (JCYJ20250604191305008), the National Natural Science Foundation of China (no. 32100514), the Guangdong Natural Science Funds for Distinguished Young Scholar (2025B1515020038), and the High-performance Computing Platform of YZBSTCACC. The author would like to thank the reviewers for their reading and constructive comments. Author contributions Y.L. developed SpaGRN and performed algorithm verification, bioinformatics analysis, and drafted the manuscript. X.L. conducted algorithm verification and generated figures. X.Y. executed functional validation of SpaGRN. M.X. conceived the study, critically revised the manuscript, and provided overall supervision. G.F. critically reviewed the manuscript and provided overall supervision. Declaration of interests The authors declare no competing interests. Footnotes Supplemental information can be found online at https://doi.org/10.1016/j.xpro.2025.104237. Contributor Information Yao Li, Email: liyao1@genomics.cn. Guangyi Fan, Email: fanguangyi@genomics.cn. Mengyang Xu, Email: xumengyang@genomics.cn. References Associated Data Supplementary Materials Methods Video S1. Navigating the SpaGRN online database and its interactive 3D visualization interface, related to Step 15 Data Availability Statement •All datasets reported in this study are publicly available and listed in the key resources table. All datasets reported in this study are publicly available and listed in the key resources table. •The original code is accessible via our GitHub repository (https://github.com/BGI-Qingdao/SpaGRN) and has been permanently archived in Zenodo (https://doi.org/10.5281/zenodo.14925041). An open-source interactive database for querying and visualizing SpaGRN’s results is hosted at https://www.bgiocean.com/SpaGRN, where all related data and transcription factor databases can be downloaded. The original code is accessible via our GitHub repository (https://github.com/BGI-Qingdao/SpaGRN) and has been permanently archived in Zenodo (https://doi.org/10.5281/zenodo.14925041). An open-source interactive database for querying and visualizing SpaGRN’s results is hosted at https://www.bgiocean.com/SpaGRN, where all related data and transcription factor databases can be downloaded. •Any additional information required to reanalyze the data reported in this paper is available from the lead contact upon request. Any additional information required to reanalyze the data reported in this paper is available from the lead contact upon request.