A unified framework for scalable differential testing for spatial omics

a-unified-framework-for-scalable-differential-testing-for-spatial-omics

Main

Spatial barcoding technologies have transformed molecular profiling by enabling high-resolution, multimodal mapping of the chromatin state, transcriptome, RNA splicing and protein abundance within intact tissue. Advances such as Slide-seq1, Stereo-seq2, high-definition spatial transcriptomics3 and Visium HD now achieve subcellular resolution, while platforms such as spatial ATAC-seq4 and long-read spatial sequencing5 extend spatial profiling beyond gene expression. These technologies allow the study of how molecular programs vary across tissue microenvironments. However, the rapid increase in spatial resolution and multimodality has created statistical challenges that existing analytical frameworks are not designed to address.

A central task in spatial omics is identifying molecular features whose variation depends jointly on cell type and local spatial context. In spatial barcoding technologies, each coordinate typically contains mixtures of multiple cell types. Consequently, cell-type-specific responses to local spatial environment must be inferred from aggregated spot-level measurements. While deconvolution methods estimate cell type proportions, they do not provide a statistical framework for testing cell-type-specific niche effects. Existing approaches for spatial differential expression, such as C-SIDE6 and NicheDE7, are primarily tailored to count-based RNA data and assume specific distributional forms. These methods do not generalize naturally to other spatial modalities, such as isoform proportions from long-read sequencing or motif accessibility scores from spatial ATAC-seq. Moreover, their computational cost becomes prohibitive at the scale of current high-resolution datasets.

Therefore, two conceptual challenges arise. The first is mixture confounding; spot-level measurements represent weighted aggregates across cell types and naive analyses that assign each spot to a dominant cell type or perform region-level stratification can inflate false discoveries or obscure true cell-type-specific effects. The second is scalability; as spatial datasets approach millions of coordinates, full-resolution statistical modeling becomes computationally impractical without sacrificing statistical power.

To address these challenges, we introduce two complementary innovations. First, we develop SpotGLM, a mixture-aware generalized linear model (GLM) framework for cell-type-specific differential testing across spatial modalities. SpotGLM extends the classical GLM by explicitly modeling spot-level observations as mixtures of cell-type-specific exponential-family distributions. This formulation accommodates diverse data types, including count-based gene expression, binomial isoform proportions and approximately Gaussian chromatin accessibility scores, within a unified statistical framework. By deriving the likelihood, gradient and Fisher information for the mixture model, SpotGLM enables calibrated hypothesis testing of cell-type-specific niche effects from spot-level data.

Second, we introduce SPARROW (scalable power-adaptive reduction for representative omics workflows), a power-preserving data distillation strategy that enables bounded-runtime inference. SPARROW leverages optimal design principles and greedy subset selection to select spatial coordinates that retain power for downstream inference. Unlike heuristic downsampling, geometric sketching8 or rasterization9, SPARROW explicitly optimizes a power-based objective tied to the downstream model, allowing bounded-runtime inference even as dataset size increases. The name SPARROW comes from the idiom ‘a sparrow may be small but it is fully formed with all vital organs’.

Together, SpotGLM and SPARROW form a unified framework for scalable, mixture-aware spatial differential testing.

We demonstrate the breadth and necessity of this framework across four distinct spatial omics applications. In Visium HD colorectal cancer (CRC), we perform serial-slice cross-platform validation against single-cell-resolved Xenium data, demonstrating accurate recovery of cell-type-specific niche programs from spot-level mixtures. In mouse kidney, we model a continuous physiological osmolarity gradient and uncover spatially structured fibroblast transcriptional programs not captured by anatomical region labels alone. In spatial long-read transcriptomics of the olfactory bulb, we provide a cell-type-resolved analysis of spatial isoform switching, formally distinguishing within-cell-type splicing changes from confounding effects of gene expression and cell composition. Lastly, in spatial ATAC-seq of mouse brain, we enable mixture-aware, cell-type-specific inference of regulatory motif accessibility, extending spatial modeling beyond RNA to chromatin regulation.

Results

SpotGLM: a general framework for cell-type-specific differential testing across spatial modalities

We first describe SpotGLM for identifying cell type-specific niche differential signals in compositional spatially barcoded data. Although our model is for measurements taken at the spot level, to motivate the model, we first considered the setting where we observe individual cells in space. Focusing on one feature at a time, let Yi be the readout of the given feature for cell i. For example, to model RNA expression Yi would be the count of a gene, to model isoform switching Yi would be the isoform-specific read counts and to model chromatin accessibility Yi would be the summarized activity (that is, total normalized accessibility) of a gene or motif (Fig. 1a). Let Ti be the cell type of cell i, which we assume is given. Our goal would be to test the cell-type-specific spatial niche dependency of the feature, where spatial niche would be encoded by a n × p design matrix X, where n is the number of cells and p is the dimension of the spatial niche encoding.

Fig. 1: Overview of the SpotGLM framework and SPARROW data reduction strategy.

a, SpotGLM enables cell-type-specific differential testing in spatial omics data by modeling measurements at the spot level as a mixture of cell-type-resolved GLMs. The model accommodates diverse data types by specifying an appropriate link function: log for counts (for example, gene expression), logit for proportions (for example, splicing) and identity for continuous data (for example, motif or gene activity scores in ATAC-seq). b, SPARROW is a power-preserving data reduction method that greedily selects an informative subset for downstream differential testing. c, SPARROW constructs the subset iteratively, adding the data point that most reduces an A-optimal trace-inverse Fisher information criterion.

In this hypothetical single-cell scenario, to allow flexibility for different data modalities, we would use a GLM that assumes that the conditional expectation of Y given X is linear after transformation F(⋅). F is called the link function of the GLM. Let Xi be the ith row of X (a 1 × p vector); then, we would have

$$Fleft(Eleft[{{Y}_{i}|X}_{i}right]right)={X}_{i}{beta }_{{T}_{i}},$$

(1)

where the p × 1 coefficient vector β would depend on cell type Ti. Our goal would be to estimate, for each spatial covariate j and each cell type t, the cell-type-specific coefficient βt,j that quantifies the relationship between the covariate and the feature. We would further like to distinguish those niche covariates and cell types for which βt,j are nonzero.

The choice of the link function F would depend on data modality. If the readout Y were approximately normal, such as in the case of ATAC motif or gene activity scores, then the natural link function corresponding to the normal distribution would be the identity function. For alternative splicing analysis, where Y|X would be binomial, the natural choice for F would be the logit function. For count-based data, the natural choice for F corresponding to Poisson or negative binomial regression would be the log function (Fig. 1a).

However, in spatial barcoding technologies, instead of individual cells, we observe spots with predefined spatial coordinates. Thus, instead of observing Yi directly, we observe spot-level readouts Zs, where each spot s is allowed to contain a mixture of multiple cells (Fig. 1a). Thus, cell-type-specific effects (the parameter vectors βt as defined above) must be resolved from aggregate spot-level readouts. To derive a spot-level model from equation (1), we assume that the spatial niche encodings Xi are the same for all cells of the same type within each spot; thus, we denote the spot-specific and cell-type-specific covariate matrix as Xt,s (in many cases, we can assume that they are shared by all cell types within each spot and, thus, can drop the subscript t). Then, we directly aggregate the single-cell model in equation (1) across the cells in each spot to yield the relation

$$Eleft[{Z}_{s}|Xright]=mathop{sum }limits_{t=1}^{T}{C}_{s,t}{F}^{-1}left({X}_{s,t}{beta }_{t}right),$$

(2)

where Cs,t is a measure of representation of cell type t in spot s, which can be estimated by spot deconvolution methods (Methods). We emphasize here that βt is a vector of dimension p. Model derivation, parameter estimation and inference are also provided in Methods.

By this construction, the coefficient vectors βt in equation (2) have the same interpretation as in the single-cell model in equation (1). For example, when Y represents proportion spliced-in of an exon in isoform sequencing data, we would use the logit link function and βt,j could, thus, be interpreted as the increase in log odds of retaining the exon if a cell of type t is in spatial niche j. This interpretation holds whether we are in the single-cell model in equation (1) or in the spatial mixture model in equation (2). In other words, under the model in equation (2), we can interpret the estimated coefficients as if we observe single cells, even though our data are compositional (Fig. 1a). The model in equation (2) accommodates a broader range of modalities as compared to existing methods such as NicheDE7 and C-Side10, which are limited to count-based gene expression analysis.

In practice, spotGLM integrates naturally into standard spatially barcoded omics analysis pipelines, as we illustrate later through applications. First, users should perform cell type deconvolution of spatial spots and set up their analysis through an appropriate encoding of the spatial neighborhood. The choice of spatial niche encoding should be guided by the biological question of interest, as we demonstrate later through examples. For large datasets (for example, Visium HD), we propose SPARROW (described next), a method for selecting a power-preserving subset of spots. SpotGLM can then used to estimate and test cell-type-specific associations of each feature (gene, isoform or transcription factor (TF) motif) with the spatial niche encoding. SpotGLM is decoupled from the underlying deconvolution and niche encoding steps and is designed to integrate modularly into existing spatial analysis workflows.

SPARROW: data distillation for power-preserving bounded-runtime analysis

Spatial omics technologies can now profile hundreds of thousands to millions of cells or spots within a single experiment. However, as dataset sizes increase, feature association testing becomes computationally demanding, often requiring days to weeks of runtime. This motivates the need for principled data distillation strategies that preserve statistical power while controlling computational cost.

To design such a strategy, we need to first ask what large spatial datasets provide. Increasing the number of observations (that is, spots or cells) reduces standard errors and improves statistical power for detecting small effect sizes. However, in practice, we are not interested in detecting arbitrarily small effects, which are likely not biologically interesting. Beyond a certain sample size, statistical power for effect sizes of practical interest saturates. Then, what do we gain from large data? The value of large spatial omics datasets lies instead in their ability to capture rare cell types and rare niche configurations with sufficient representation. These rare configurations are often undersampled in smaller datasets yet may be where critical biological insights reside. Large spatial omics datasets power the testing of hypotheses involving low-abundance cell states or rare disease-specific microenvironments.

Traditional downsampling methods, such as random subsampling, discards rare but biologically relevant configurations while oversampling common configurations. Geometric sketching8 tries to address this problem but is sensitive to outliers and noise. Rasterization reduces data to lower resolution, which can be helpful in reducing data sparsity but may blur rare cell states and short-range interactions. Unlike these existing methods, SPARROW optimizes subset selection relative to the analysis at hand, as represented by the niche context matrix X. Specifically, SPARROW selects a subset of spots that maximizes power for testing the null hypothesis βt,j = 0 across all coefficients βt,j in the model in equation (2). This ensures that both common and rare configurations in the model matrix X remain well represented (Fig. 1b); thus, high power is maintained in the subsample for signal detection across all configurations.

Here, we provide an intuitive introduction to SPARROW, with full derivation and algorithmic details given in Methods. Consider first the simplest case of a multiple regression ({Y}_{ntimes 1}sim {X}_{ntimes p}{beta }_{ptimes 1}), where our goal is to select a subset S of size K among ({1,2,ldots ,n}) that retains maximal power for downstream testing of the parameters β. The power for testing ({beta }_{j}ne 0) versus the null hypothesis ({beta }_{j}=0) is inversely proportional to the standard error in the estimation of βj. For a subsample S of spots, the sum of squared standard errors of the maximum likelihood estimate of ({beta }_{ptimes 1}) is equal to the trace of the inverse Fisher information matrix (f(S)={rm{tr}}[{({X}_{S}^{{{top }}}{X}_{S})}^{-1}]) (Fig. 1c). This is the classical A-optimal design criterion. We use it as the default SPARROW objective because it directly targets the marginal variances of the regression coefficients, which are the quantities entering coefficient-wise Wald tests and the power retention stopping rule below. Thus, we choose S by minimizing the function f(S),

$${S}^{star }=mathop{{{arg }},min }limits_{S:|S|=K}fleft(Sright).$$

(3)

To extend the above logic to the GLM in equation (1) and SpotGLM in equation (2), note that the covariance matrix in GLMs follows the form (XTWX)−1 where W is a diagonal weight matrix that can be explicitly computed given the data. In SpotGLM, the covariance matrix must further account for cell type mixing within spatial spots but can still be explicitly and efficiently computed (Methods and Supplementary Notes 1 and 2). Hence, we can use the optimization criterion in equation (3) for GLM and SpotGLM.

Because of the combinatorial search space across subsets of size K, an exhaustive search for the A-optimal subset in equation (3) is computationally intractable for large datasets. SPARROW therefore uses a stochastic greedy design algorithm: starting from an initial regularized information matrix, it iteratively adds the data point that most reduces ({rm{tr}}{I{(S)}^{-1}}), where I(S) is the plug-in Fisher information for the selected subset. This A-optimal objective is monotone and directly interpretable as reducing the sum of marginal coefficient variances, although it is not generally submodular for arbitrary multivariate designs. For theoretical reference, a regularized D-optimal variant maximizing ({rm{logdet}}left{varLambda +Ileft(Sright)right}-{rm{logdet}}left(varLambda right)) is monotone submodular and admits the standard greedy approximation guarantee. In practice, the A-optimal and D-optimal variants showed similar performance across benchmarks (Supplementary Fig. 1) and we use A-optimality by default because of its direct connection to coefficient-wise standard errors and power.

SPARROW data distillation maintains high power for diverse downstream tasks

First, we evaluated the performance of SPARROW on four large-scale spatial transcriptomic datasets, performing diverse downstream analyses. For each analysis, we compared SPARROW to existing data reduction methods (random selection, geometric sketching8 and rasterization9) using results obtained from the full dataset as the gold standard. Power was measured by recall, computed as the proportion of signals recovered in the subsampled data relative to those identified in the full dataset, stratified by signal strength as measured by the log false discovery q value in the full data (Fig. 2a). We focus on recall because data reduction primarily affects statistical power rather than error control; subsampling reduces sensitivity by decreasing effective sample size, while the calibration of false discoveries is governed by the downstream statistical method. Specificity curves, shown in Supplementary Fig. 2, are comparable across methods. Hence, recall provides the most direct measure of how well biological signal is preserved under data distillation.

Fig. 2: SPARROW enables power-preserving data distillation across diverse spatial transcriptomic analyses.

a, Benchmarking recall (y axis) versus signal strength (x axis) across four spatial transcriptomics datasets demonstrates that SPARROW outperforms existing data reduction methods—including random sampling, geometric sketching and rasterization—across all settings. Each analysis uses results from the full dataset as the gold standard. b, In MERFISH CRC data, SPARROW selects a balanced subset of cells across all cell types, avoiding the power saturation in tumor cells seen in other methods. c, Spatial locations of tumor cells in the full MERFISH CRC dataset and in subsets obtained by random selection, geometric sketching and SPARROW, colored by annotated spatial niche. SPARROW retains tumor cells from all five niches, including rare niche configurations. d, Quantification of the tumor-cell niche composition shown in c, displaying the proportion of tumor cells from each annotated niche for the full dataset and for each data reduction method; numbers above the bars indicate cell counts. For the rarest configuration, Niche 3, SPARROW reaches sampling saturation: all tumor cells observed in the full dataset are retained in the selected subset. e, SPARROW’s performance on simulated data ranging from 10,000 to 5 million data points. Left: statistical power relative to full-data analysis. Middle: number of spots selected by SPARROW (y axis) as a function of full-data size (x axis). Right: runtime comparison between SPARROW and full-data analysis.

As Sparrow can be applied to both cell-level and spot-level spatial data, for benchmarking, we included both data types: MERFISH, where each observational unit is a cell, and 10x Visium HD, where each observational unit is a spot (or grid point). The datasets used are described in detail in Methods. Each task in our benchmark relies on a different encoding of spatial covariates, derived from anatomical domains or from cell–cell interactions, resulting in distinct covariate matrices used by SPARROW to determine the optimal subset. This demonstrates how SPARROW can tailor data distillation to the analysis at hand, where covariates can be discrete or continuous.

Below, we summarize the four benchmark tasks and results. Details of the models and hypotheses tested are given in Methods. Note that all analyses here are linear in the number of spots; thus, a 10% reduction by SPARROW equates to a 10× speed-up. As data size (in terms of the number of spots) grows, we expect the number of spots in the distilled data to plateau, leading to bounded runtime, as we demonstrate in a simulation at the end.

Our first example uses a MERFISH CRC dataset, profiling 500 genes across 750,000 cells and five annotated regions11. Cells were assigned to 15 cell types. In this starting example, for illustration, we performed the simplest analysis; we used region labels as covariates and screened for region-specific differential expression within each cell type. For signals identified at 5% false discovery rate in the full data, SPARROW achieved over 90% recall using only 10% of the data, while other subsampling methods achieved less than 70% recall at the same sampling rate (Fig. 2a). Across varying data retention levels, SPARROW consistently achieved the highest recall (Supplementary Fig. 3). Note that rasterization and geometric sketching failed to recover some of the most significant signals identified in the full dataset.

To understand why SPARROW achieves such high recall, we examined the subsample composition. While random and geometric sketching-based methods heavily sampled tumor cells, SPARROW selected a balanced representation across all (cell type, region) combinations (Fig. 2b). As shown in Fig. 2c,d, SPARROW captured tumor cells from all regions, including all tumor cells from niche 3, which was extremely rare. In contrast, random and sketching-based methods largely missed the rare configurations.

Thus, when covariates are categorical (for example, cell type × region with one-hot encoding), SPARROW can be approximated by stratified sampling, both aiming to achieve balanced representation across groups. However, stratified sampling cannot be applied to analyses that involve mixture-based spot measurements or continuous covariates (such as local neighborhood cell type density or spatial gradients). In contrast, SPARROW operates directly on the model matrix and optimizes a power-based objective, allowing principled subset selection across categorical and continuous designs.

The case of a continuous niche covariate is demonstrated in our second example, which uses Visium HD CRC data with 300,000 spots and eight deconvolved cell types. Here, we encoded the spatial niche of each spot as the average cell type composition across all spots within a distance of 64 μm. We used SpotGLM to identify genes with cell-type-specific niche dependence, with the negative binomial model and cell type composition as the covariate (Methods). As shown in Fig. 2a, SPARROW achieves >95% recall for strong signals and >80% recall for weak signals with just 20% of the data, outperforming all baseline methods. This example illustrates the capacity of SPARROW to handle continuous covariates and spot-level measurements.

The third example uses a Xenium liver dataset with 200,000 cells12; we again used cell type composition as the niche encoding, as in the Visium HD analysis, but now included a baseline cell type (hepatocytes) to identify relative expression differences (Methods). This reflects a common analysis setup where the goal is to identify differential niche dependency relative to a dominant or reference population. The resulting model tested 5,600 hypotheses. Figure 2a shows that, with around 33% of the data, SPARROW achieves ≥99% recall for strong signals and nearly 80% recall even for borderline signals, while other methods have recall around 60% at the same data reduction.

Lastly, our fourth example evaluated SPARROW on a public Visium HD kidney data for cell-type-specific spatially variable gene (SVG) analysis using CELINA13. This dataset contains 400,000 spots, which we rasterized to 100,000 spots to overcome extreme data sparsity. Unlike previous analyses, CELINA relies on a spatial kernel matrix rather than an explicit covariate matrix. To apply SPARROW, we performed a low-rank decomposition of the kernel and used the top components in the low-rank embedding as the covariate matrix X. As CELINA is run separately for each cell type, we also applied SPARROW separately per cell type. As shown in Fig. 2a, using only 15% of the data for each cell type, SPARROW achieved near-perfect recall, while baseline methods remained under 75% recall. This demonstrates SPARROW’s application beyond regression-based analyses to an exploratory analysis based on a spatial kernel matrix.

As subsampling primarily affects statistical power, our focus has been on recall. Now, we verify that data reduction does not inflate false discoveries. Because true negatives are unknown in real data, we define precision and specificity relative to discoveries in the full dataset as an empirical reference. Supplementary Fig. 2 shows that all methods including SPARROW maintain high precision and specificity.

Bounded runtime of SPARROW

The size of spatial omic datasets is rapidly increasing and reaching millions of data points per experiment. To illustrate the bounded runtime of SPARROW, we performed a simulation study designed to quantify how many data points are required to retain near-full statistical power as dataset size grows. Specifically, we simulated datasets ranging from 10,000 to 5 million observations and measured the subsample size needed to retain 97.5% of the power of the full dataset for detecting biological signals above a minimal effect size threshold.

As shown in Fig. 2e, the power of the subsample exhibits two distinct regimes. In the first regime, when the full dataset itself is insufficient to detect effects of the target magnitude, SPARROW selects a constant fraction of the data (~55% for the specific simulation), reflecting the fact that power remains limited by sample size. In the second regime, beyond 500,000 observations in this simulation, saturation is reached by the full data for the targeted effect sizes. Beyond this point, SPARROW is able to select a decreasing number of optimally chosen data points while still guaranteeing power across all covariate configurations. Notably, while the runtime of full-data analysis grows linearly, SPARROW’s runtime plateaus and then decreases once we reach the saturated regime, maintaining nearly identical power with bounded runtime (Fig. 2e). We also show power and runtime at log scale (Supplementary Fig. 4). This demonstrates how SPARROW enables bounded-runtime inference as spatial omics datasets become increasingly large.

SpotGLM enables accurate and scalable cell-type-specific niche differential testing

Although SpotGLM is designed to generalize beyond count-based RNA data, we first evaluated its performance in the canonical RNA spatial transcriptomics setting. We generated spot-by-gene counts from a Poisson distribution under a predefined mixture model (Methods). In this framework, true cell-type-specific and niche-associated coefficients were known, enabling direct comparison between estimated and ground-truth parameters.

We benchmarked SpotGLM against existing approaches for cell-type-specific spatial differential analysis, including C-SIDE10, NicheDE7, spVC14 and a commonly used baseline that assigns each spot to its dominant cell type and performs differential testing without modeling mixture proportions. For spVC, which does not explicitly parameterize cell-type-specific niche effects, we augmented the design matrix with cell type proportions and their interactions with niche covariates to approximate a cell-type-level analysis. Details of this benchmark are in Supplementary Information.

Across increasing sample sizes, methods that explicitly model cell-type-specific niche effects achieved low estimation error and high statistical power (Supplementary Fig. 5). In contrast, the dominant-cell baseline exhibited substantially inflated type I error and biased coefficient estimates, demonstrating that ignoring cell mixing leads to spurious differential expression. spVC showed reduced accuracy and substantially higher computational cost in this setting.

When paired with SPARROW, SpotGLM scaled efficiently with increasing data size, enabling large-scale analyses that are computationally infeasible for existing methods. While statistical performance in moderate-scale RNA settings was comparable across mixture-aware methods, SpotGLM integrates naturally with a power-preserving subsampling framework that maintains statistical calibration while achieving bounded runtime.

Resolving niche-dependent fibroblast programs from spot-level mixtures in colorectal cancer

We first demonstrate SpotGLM and SPARROW in the context of spatial niche differential expression analysis using two Visium HD CRC datasets15. These datasets contain approximately 300,000 spatially barcoded spots with nine annotated cell types. Because of the substantial computational cost of full-data analysis, we applied SPARROW to distill the dataset to 75,000 spots and applied SpotGLM on this reduced dataset. Our objective is to identify niche-specific transcriptional programs within fibroblasts, which are key participants of extracellular matrix remodeling, immune modulation and tumor progression16,17.

To evaluate whether SpotGLM can resolve cell-type-specific niche effects from such mixture-based data, we leveraged serial adjacent tissue sections profiled using Xenium human immuno-oncology profiling panel18 (Fig. 3a). Xenium provides true single-cell spatial transcriptomics data without mixture confounding; thus, this serial-slice design enables direct comparison of estimated niche-effect coefficients across modalities. However, Xenium profiles only a targeted panel of 380 genes, not the entire transcriptome. Thus, we focus on the intersection of genes available in both the Xenium panel and the Visium HD dataset.

Fig. 3: SpotGLM coupled with SPARROW identify cell-type-specific gene expression changes in tumor-associated niches.

a, Schematic workflow of Visium HD and Xenium cross-platform validation. Matched serial sections of a colorectal tumor were profiled by Visium HD (top; 8 μm × 8 μm spots) and Xenium (bottom; single cells). On each platform, spots and cells are annotated by cell type (left maps) and scored spatial cell type composition niches (for example, a fibroblast niche, a T cell niche and a set of control niches). SpotGLM is applied to Visium HD and standard GLM is applied to Xenium data. b, Comparison of effect sizes of fibroblast-specific tumor niche-associated and T cell niche-associated genes in Xenium versus Visium HD in CRC participant 1. Spearman’s correlations are high and statistically significant (Spearman’s rank correlation test against the null hypothesis of no monotonic association ρ = 0 is <10−16). Upregulated genes are labeled and sized by −log10(adjusted P value). The blue line is the regression line. Black dots indicate genes with concordant effect size direction between Visium HD and Xenium, whereas red dots denote genes with discordant effect size direction across platforms. c, CRC P1 enrichment plot of fibroblast genes near tumor, T cell and B cell niches identified by SpotGLM, compared to existing CAF subtype markers (CAF-cancer, CAF-immune and CAF-myeloid subtypes). d, Comparison of effect sizes of fibroblast-specific tumor niche-associated and T cell niche-associated genes in Xenium versus Visium HD in CRC participant 2, as in b. e, CRC P2 enrichment plot of fibroblast genes near tumor, T cell and B cell niches identified by SpotGLM, compared to existing CAF subtype markers (CAF-cancer, CAF-immune and CAF-myeloid subtypes). f, Left: QQ plot of upregulated genes in fibroblast cells associated with tumor niche in participant 1. Blue color indicates genes that overlap CAF-tumor subtype. Orange color indicates genes identified by SpotGLM but not reported in CAF-tumor subtype. All labeled genes are statistically significant. Right: gene set enrichment analysis (GSEA) pathway enrichment of top upregulated fibroblast genes associated with tumor niche in participant 1. g, Left: QQ plot of upregulated genes in fibroblast cells associated with T cell niche in participant 1. Blue color indicates genes that overlap CAF-immune subtype. Orange color indicates genes identified by SpotGLM but not reported in CAF-immune subtype. All labeled genes are statistically significant. Right: GSEA pathway enrichment of top upregulated fibroblast genes associated with T cell niche in participant 1.

Specifically, we first quantified the spatial niche for each Visium HD spot and each Xenium cell. In Visium HD, the niche was defined by averaging deconvolved cell type proportions within a 100-µm radius surrounding each spot. In Xenium, the niche was defined analogously using directly observed cell type identities within the same radius. For each gene, we then estimated its association with the neighborhood abundance of specific cell types, after adjusting for other neighborhood cell types. In Visium HD, we applied SpotGLM under a negative binomial model; for Xenium, in the absence of mixtures, we applied a standard negative binomial GLM (Fig. 3a).

To ensure a meaningful cross-platform comparison, we imposed two criteria. First, we restricted analysis to niche cell types whose spatial distributions were reproducible across Xenium and Visium. Second, within each data modality, we verified that distinct niche effects remained statistically separable, thereby ensuring adequate discriminatory power for coefficient estimation. These criteria identified three robust niche cell types (tumor, T cells and B cells) on which subsequent analyses focused. We then directly compared fibroblast niche-effect coefficients, estimated for these cell types, from Visium HD SpotGLM versus those from Xenium single-cell GLM (Fig. 3a).

Despite the differences in platform technology, we observed strong concordance between the SpotGLM coefficients estimated from Visium HD and the GLM coefficients estimated from Xenium. Spearman correlation coefficients of the estimated niche-effect sizes were high across participants. For tumor niche effects, correlations were 0.79 and 0.80 in participants 1 and 2, respectively (Fig. 3b,d). For T cell niche effects, correlations were 0.80 and 0.86 in participants 1 and 2, respectively (Fig. 3b,d). For B cell niche effects, correlations were slightly lower at 0.61 and 0.88 in participants 1 and 2, respectively (Supplementary Fig. 6). This coefficient-level agreement across serial tissue sections demonstrates that SpotGLM accurately recovers cell-type-specific niche effects from spot-level mixture measurements.

To further contextualize these findings, we compared our tumor-associated and immune-associated fibroblast gene sets with recently defined cancer-associated fibroblast (CAF) subtypes identified using single-cell spatial transcriptomics across multiple cancer types19. We observed statistically significant enrichment of our tumor niche genes within tumor-associated CAF subtype signatures and enrichment of immune niche genes within CAF-immune subtype markers across both CRC participants (Fig. 3c,e). Given the known plasticity and interindividual variability of CAF programs, this concordance supports the biological validity of SpotGLM-derived niche signatures.

Beyond methodological validation, SpotGLM identified distinct fibroblast transcriptional programs associated with tumor and immune niches. In this analysis, we modeled gene expression using a spot-level negative binomial GLM (Methods). We discovered that fibroblasts near tumor niches exhibit elevated expression of COL11A1, COL5A1 and COL4A1, which overlap with established tumor-associated CAF subtype markers19,20,21. Additional genes identified included COL1A1, COL3A1 and SPARC. SPARC has been shown to induce COL1A1 and COL3A1 expression in CRC-associated fibroblasts22 and COL1A1 serves as a sensitive and specific CAF marker associated with poor prognosis across multiple cancer types23,24. Pathway enrichment analysis confirmed that collagen organization and extracellular matrix remodeling were dominant biological processes (Fig. 3f), consistent with the known biology of CAF-mediated tumor progression25,26.

In contrast, fibroblasts in T cell-dense niches showed enrichment of inflammatory programs, including CCL19 (Fig. 3g). CCL19-producing fibroblasts are also shown to promote tertiary lymphoid structure formation27. Pathway enrichment analysis of T cell niche fibroblast genes revealed significant enrichment of TNF signaling and cytokine-mediated signaling pathways (Fig. 3g), highlighting a niche-dependent inflammatory fibroblast state that may contribute to localized immune organization.

The scale of whole-transcriptome Visium HD datasets presents substantial computational challenges for existing spatial differential expression methods. Direct full-resolution analysis of 300,000 spots per sample was computationally impractical under high-memory cloud configurations. In contrast, pairing SpotGLM with SPARROW enabled power-preserving subsampling (~75,000 spots) and completion of the analysis within practical runtime while maintaining concordance with full-data results.

Continuous osmolarity gradient modeling reveals spatially structured fibroblast programs in mouse kidney

We next applied SpotGLM to a Visium HD dataset of healthy adult mouse kidney28, in which the spatial niche was defined by osmolarity level and anatomic zone. Osmolarity is a fundamental determinant of kidney physiology, reflecting the kidney’s role in maintaining systemic water and electrolyte homeostasis. Along the corticomedullary axis, osmolarity increases progressively from the cortex to the papilla. The cortex is characterized by relatively low osmolarity, whereas the inner medulla and papilla sustain hyperosmotic conditions that enable urine concentration. Despite this well-established physiological gradient, the cell-type-specific transcriptional programs associated with osmolarity variation remain incompletely characterized, particularly in stromal populations such as fibroblasts, whose roles in adapting to osmotic stress and mediating regional functions are not well understood.

In Visium HD analysis, we first defined anatomical zones using histological features extracted from the same-slide hematoxylin and eosin (H&E) image. We clustered these features and manually annotated five distinct zones: cortex, outer stripe of the outer medulla, inner stripe of the outer medulla, inner medulla and papilla (Methods). These annotations were consistent with established mouse kidney anatomy29 (Fig. 4a). Next, we quantified osmolarity as a continuous spatial covariate. For each spot, we computed an osmolarity gradient score on the basis of its relative position along the corticomedullary axis. Specifically, the score was defined using the relative straight-line distance to the cortical edge versus the papillary edge, ensuring a monotonic increase from cortex to papilla (Methods and Fig. 4b). This continuous gradient served as the primary spatial niche covariate in the SpotGLM model, while discrete anatomical region indicators were included to control for baseline regional expression differences (Fig. 4b). Cell type proportions for each spot were estimated using RCTD6 with reference single-cell kidney cell type expression profiles30. Because fibroblast-containing spots were distributed across all anatomical zones (Fig. 4c), this design enabled separation of gradient-associated transcriptional effects from purely region-specific differences. The processed Visium HD data comprised 470,883 spatial spots and 19,059 genes. After filtering genes with fewer than 30 total counts, 14,961 genes were retained for analysis.

Fig. 4: SpotGLM coupled with SPARROW identify cell-type-specific spatial gene expression programs in the adult mouse kidney.

a, H&E staining and anatomic region for Visium HD mouse kidney data annotated using low-dimensional H&E features (regions annotated include cortex, outer stripe, inner stripe, inner medulla and papilla). b, Spatial location of osmolarity gradient of Visium HD data. c, Deconvolution proportion of fibroblast cells. d, Anatomic regions annotated in Xenium mouse kidney. Gray areas indicate cells not used in this analysis but included in the original dataset. e, Left: spatial location of osmolarity gradient of Xenium data. The spatial location of fibroblast cells is colored in red. Gray areas are as in d. f, QQ plot of upregulated genes in fibroblast cells associated with high osmolarity. Red color indicates genes that overlap with full data and are statistically significant. g, Gene expression of top marker gene, Igfbp5, in fibroblast cells associated with high osmolarity in Visium HD. h, Scatter plot of precision curves for top-ranked genes in the SPARROW subset and the full dataset, each evaluated against the other dataset’s significant gene set. The y axis shows the proportion of overlapping genes and the x axis shows gene rank from differential expression testing. The blue curve represents the fraction of top-ranked SPARROW genes identified as significant in the full dataset, while the red curve represents the fraction of top-ranked full-dataset genes identified as significant in the SPARROW subset. i, Pathway enrichment of top upregulated fibroblast genes associated with high osmolarity. P values were computed using the GSEA function in the clusterProfiler R package and adjusted P values were obtained using the Benjamini–Hochberg procedure. j, Gene expression of top marker gene, Igfbp5, in fibroblast cells associated with high osmolarity in Xenium. Gray areas are as in d. k, Effect size of differentially expressed genes in Xenium versus Visium HD. Spearman’s correlation is 0.83 (Spearman’s rank correlation test against the null hypothesis of no monotonic association ρ = 0 is <10−16). Upregulated genes are labeled and sized by −log10(adjusted P value). The blue line is the regression line.

To establish an independent validation framework, we also analyzed a Xenium dataset from healthy mouse kidney. Anatomical regions were defined from the spatial distributions of cell populations associated with the cortex, papilla and inner medulla (Fig. 4d). We then constructed an analogous corticomedullary osmolarity gradient proxy and confirmed that fibroblasts were represented across this gradient (Fig. 4e). Although the Visium HD and Xenium datasets were obtained from independent tissue samples, the parallel spatial encodings enabled comparison of fibroblast-specific osmolarity effects across platforms.

We applied a negative binomial SpotGLM to model cell-type-specific gene expression as a function of the osmolarity gradient while adjusting for anatomical region effects (Methods). To reduce computational cost with minimal loss of statistical power, we applied SPARROW to select 70,000 representative spots and applied SpotGLM on both the full and subsampled datasets. The analysis identified a substantial set of fibroblast-specific genes significantly associated with increasing osmolarity (Fig. 4f). Among the top differentially expressed genes, Igfbp5 (Fig. 4g) emerged as a prominent marker enriched in fibroblasts residing in high-osmolarity regions. Igfbp5 is a well-established mediator of fibroblast activation and extracellular matrix regulation, promoting fibrosis through Egr1-dependent mechanisms31,32,33. Igfbp5 has been implicated in promoting endothelial-to-mesenchymal transition and extracellular matrix (ECM) deposition through crosstalk with TGFβ1 signaling34,35. While prior work has linked hypertonic environments to profibrotic signaling in the renal medulla36, our analysis reveals that, even within the medulla, Igfbp5 expression varies continuously with the osmolarity gradient, highlighting gradient-dependent regulation beyond coarse anatomical boundaries.

In addition, Spon1 was enriched in fibroblasts localized to high-osmolarity regions such as the papilla. The Spon1 extracellular matrix protein is involved in cell adhesion and single-cell transcriptomic profiling of mouse kidney confirmed its expression in renal medullary fibroblast populations37. The association of Spon1 with the osmolarity gradient links extracellular matrix remodeling with spatial osmotic stress. Pathway enrichment analysis revealed focal adhesion and ECM receptor interaction as the top enriched pathways among osmolarity-associated fibroblast genes (Fig. 4h), consistent with the established role of these pathways in fibroblast-mediated matrix remodeling in the kidney38,39,40. Together, these findings reveal a spatially structured, osmolarity-associated fibroblast program that is not captured by anatomic region alone.

To evaluate computational efficiency and signal preservation, we compared differential expression results from the SPARROW-selected subset with those from the full dataset. In the subsampled data, 173 fibroblast-specific high-osmolarity genes were identified and more than 70% of the top-ranked genes were also significant in the full dataset, indicating strong concordance with full-data discoveries (Fig. 4i). The full dataset identified 400 upregulated genes; approximately 50% of its top-ranked genes were recovered in the SPARROW subset. When the comparison was restricted to the top 50 genes ranked by statistical significance in the full analysis, precision exceeded 90%. These results indicate that SPARROW retains the highest-confidence signals from the full dataset, with overlap increasing substantially among the most highly ranked genes. Together, these results indicate that power-preserving data distillation retains strong-effect niche associations while primarily attenuating marginal, low-effect findings.

We then tested whether the Visium HD findings were reproduced in the independent Xenium dataset. Despite the more limited gene panel, Igfbp5 again showed increased fibroblast expression toward high-osmolarity regions (Fig. 4j). More broadly, the estimated fibroblast-specific osmolarity effects were strongly concordant between Xenium and Visium HD (Spearman ρ = 0.83; Fig. 4k). This cross-platform agreement supports the ability of SpotGLM to recover cell-type-specific spatial expression effects from spot-level mixture measurements.

SpotGLM identifies spatial isoform switching patterns in mouse brain

To demonstrate the application of SpotGLM to spatial RNA splicing analysis, we analyzed a spatially barcoded long-read sequencing dataset of the mouse olfactory bulb. This dataset, generated by Lebrigand et al.5, consists of spatial long-read transcriptomic data from adult C57BL/6 mouse olfactory bulb, with reads spanning full exon–exon junctions and enabling confident identification of transcript isoforms at single-spot resolution. After quality filtering, isoform-level expression was quantified across 918 spatial spots, with over 23,000 detected reference isoforms from more than 13,000 genes.

Unlike gene-level expression, isoform usage is inherently compositional; the relevant quantity is the relative proportion of one isoform among all transcripts of a gene. In spot-based spatial long-read data, this proportion is a mixture-weighted average across cell types, confounding within-cell-type splicing changes with variation in cell type abundance and total gene expression. Existing approaches do not formally disentangle these effects when identifying cell-type-specific isoform switching from spot-level spatial data.

We first estimated the cell type compositions per spot using SPOTlight41, leveraging a reference single-cell RNA-seq dataset of the olfactory bulb. In total, 11 major cell types were identified, including neurons, astrocytes, oligodendrocytes and immune and vascular populations. Lebrigand et al. manually annotated five distinct anatomical layers: the granule cell layer, mitral cell layer, external plexiform layer, glomerular layer and olfactory nerve layer (Fig. 5e).

Fig. 5: SpotGLM identifies cell-type-specific isoform switching in spatial long-read transcriptomics of the mouse olfactory bulb.

a,b, Simulation example where both cell types switch isoform usage between regions. Marginal tests detect switching but cannot assign it to specific cell types; correlation with cell type abundance fails because of equal usage. SpotGLM correctly identifies switching in both cell types. c,d, Simulation where only cell type 2 switches isoform usage. SpotGLM accurately assigns switching to cell type 2, while marginal tests miss it and correlation-based methods misattribute the signal. e, Annotated anatomical regions of the mouse olfactory bulb used in the analysis: the granule cell layer, mitral cell layer, external plexiform layer, glomerular layer and olfactory nerve layer. f, Counts of number of detected isoform switching events for each cell type, along with QQ plot of P values across 11,081 tests. Strong deviation from null indicates widespread spatial switching, with significant P values at a 10% false discovery rate highlighted in red. Cell type labels are as follows: Neuron, neurons; OEC, olfactory ensheathing cells; Astro, astrocytes; OPC, oligodendrocyte precursor cells; Oligo, oligodendrocytes; Mono, monocytes; Mes, mesenchymal cells; Mural, mural cells; Microglia, microglia; EC, endothelial cells. g, Example gene Ap3s1. SpotGLM identifies isoform Ap3s1-201 to have neuron-specific isoform switching across layers. Left: plot showing estimated relative expression with 95% confidence intervals across layers. Standard errors are computed on the basis of inverse Fisher information, as described in Supplementary Information (n = 918). Middle: plot showing the percentage of RNA detected transcripts assigned to neurons for each spot, showing that transcripts of this gene are predominantly assigned to neurons across layers. Right: plot showing the marginal fraction of transcripts assigned to the Ap3s1-201 variant at each spot. h, As in g, but for gene Myl6. Despite neuron expression varying across layers, SpotGLM resolves a neuron-specific isoform switch from Myl6-201 to Myl6-206 across the layers of the olfactory bulb.

We aimed to identify cell-type-specific spatial isoform switching, defined as a change in relative isoform expression of a gene within a given cell type across spatial regions. We applied SpotGLM using a binomial distribution with logit link function, modeling the log odds of a read mapping to a given isoform versus to the alternate isoform(s) within each cell type, conditioned on anatomic layer. This binomial model directly captures isoform switching and enables explicit estimation of layer-specific splicing effects with cell type specificity (Methods).

For comparison, we considered two alternative data analysis approaches: (1) marginal analysis, which compares isoform usage between regions without accounting for cell type composition, and (2) correlation-based inference, which relates isoform usage to the abundance of a cell type within each spot to infer likely cell type of origin5. These approaches have key limitations. Marginal analysis cannot resolve the cell type responsible for isoform switching, while correlation-based inference may attribute the source of isoform switching inaccurately; high correlation does not imply differential isoform usage within a specific cell type. Before analyzing the real data, we first illustrate two common confounding scenarios that arise in spatial splicing analysis and how the above-described methods would lead to different conclusions.

First, consider a scenario with two cell types (1 and 2) and two regions (A and B) and a gene with two isoforms (isoform 1 and isoform 2). Assume that both cell types switch their relative expression of isoform 1 from 25% in region A to 75% in region B (Fig. 5a). A marginal test identifies overall isoform switching but cannot distinguish which cell types contributed to it (the correct answer is both). Meanwhile, correlation-based inference fails entirely because isoform proportion is independent of cell type abundance (Fig. 5b). In contrast, SpotGLM estimates cell-type-specific switching directly by modeling isoform usage as a mixture of binomial distributions and correctly identifies switching in both cell types.

The second toy example (Fig. 5c) corresponds to the scenario where cell type 1 exhibits no change in relative isoform expression across regions but cell type 2 exhibits change in isoform 1 from 50% in region A to 100% in region B. Simultaneously, the relative cell type abundance changes, from 75% cell type 1 in region A to only 25% in region B. As seen in Fig. 5d, SpotGLM properly identifies cell type 2 as the only source of the isoform switching, while the correlation-based test mistakenly attributes the isoform switching to both cell types. Furthermore, because of the change in cell type abundance between regions, there exists no change in marginal isoform relative expression across regions. This shows that isoform switching within a cell type does not imply global isoform switching. It is not hard to see that the converse is also false; global isoform switching may be caused simply by cell type composition changes and not necessarily by within-cell-type isoform switching.

We now return to the analysis of the mouse olfactory bulb data. We focused on genes with exactly two isoforms comprising at least 20% of total gene expression and with total expression greater than 50 unique molecular identifiers (UMIs) across spots, yielding 643 genes. For each gene, we identified cell types with sufficient deconvolved expression and tested cell-type-specific isoform switching across all layer pairs. Across genes, cell types and regions, 11,081 tests were performed. The resulting quantile–quantile (QQ) plot showed strong enrichment of small P values (Fig. 5f); at a false discovery rate of 0.1, we identified 128 significant instances of cell-type-specific spatial isoform switching involving 64 genes. The cell type with the most identified genes that switch isoforms across layers was neurons, followed by olfactory ensheathing cell.

Figure 5g,h illustrates two representative genes, Ap3s1 and Myl6. Ap3s1 expresses two major isoforms, Ap3s1-201 and Ap3s1-202, that in total comprise 91% of all transcripts across spots. In Fig. 5g, we plot the estimated neuron-specific relative expression of Ap3s1-201 from the innermost granule cell layer to the outermost olfactory nerve layer. Figure 5g also shows a spatial plot of the estimated proportion of all Ap3s1 RNAs in each spot originating from neurons, juxtaposed with a spatial plot of the fraction of reads mapping to Ap3s1-201 among all reads mapping to the gene. This is an ‘easy’ case in the sense that almost 100% of the total expression of Ap3s1 can be attributed to neurons; thus, SpotGLM assigns the layer-specific isoform switching of this gene to neurons. Figure 5g plots the relative fraction of Ap3s1-201 and its 95% confidence interval, allowing us to clearly observe a switch from Ap3s1-201 in the inner layers to Ap3s1-202 in the middle layers and then back to Ap3s1-201.

Similar plots are shown for Myl6, which expresses two major isoforms, Myl6-201 and Myl6-206 that differ by five of the last nine residues in the C-terminal region. The neuron contribution to the total expression of this gene increases from 0 in the olfactory nerve layer to around 75% in the granule cell layer (Fig. 5h, middle). Thus, this is a more ‘difficult’ case in the sense that neurons are not the only cells that express this gene and neuron contribution to total gene expression also changes across layers. However, SpotGLM was able to confidently assign this isoform switching event to neurons and estimated the relative expression of Myl6-201 to be around 75% in neurons in granule cell layer, decreasing to around 40% in the olfactory nerve layer.

Cell-type-resolved regulatory programs revealed by mixture-aware spatial ATAC modeling

Our final example focuses on the identification of niche differential signals in spatial ATAC data. Unlike spatial transcriptomics, current spatial ATAC-seq technologies rely exclusively on spatial barcoding and, therefore, measure chromatin accessibility at spot resolution, where each spot contains a mixture of multiple cell types. Thus, cell-type-specific regulatory inference necessarily requires mixture-aware modeling. Here, we demonstrate that SpotGLM enables cell-type-resolved analysis of spatial ATAC regulatory activity.

Chromatin accessibility serves as proxy for regulatory potential, with open chromatin regions containing active enhancers and promoters. To interrogate regulatory activity, we considered two complementary data features (Fig. 6a): (1) genome-wide TF motif activity accessibility and (2) accessibility of TF genes, computed from aggregate accessibility near gene transcription start sites (TSSs). For both data features, we applied SpotGLM to identify cell-type-specific differences across brain regions. In the motif-level analysis, we used chromVAR to compute TF motif enrichment scores42. Peaks identified by MACS2 (ref. 43) were scanned against a TF motif database (for example, JASPAR44,45,46) and enrichment scores were computed per spot by quantifying deviations in motif-associated accessibility from background. In the gene-level analysis, peaks were assigned to genes on the basis of proximity to TSS and gene activity scores were computed as the sum of counts across those peaks.

Fig. 6: SpotGLM identifies cell-type-specific differential motif accessibility in spatial ATAC of the mouse brain.

a, Schematic overview of spatial ATAC analysis workflow. The data input is a spot-by-fragment matrix, followed by peak calling to generate a spot-by-peak matrix. This matrix can then be transformed into either a spot-by-motif score matrix (Y1), using an external motif database (for example, JASPAR), or a spot-by-gene activity score matrix (Y2), using a regulatory potential model. Spatial niches are assigned to each spot as covariates and the SpotGLM model is applied to identify cell-type-specific differences in motif or gene activity scores across spatial regions. b, Spatial tissue map annotated with anatomical regions. C0, cortex; C3, corpus callosum. c, Left: estimated oligodendrocyte proportions from deconvolution. Right: expression of the oligodendrocyte marker gene Mbp from RNA-seq data modality. d, QQ plot of upregulated gene activity scores in oligodendrocytes comparing cortex versus corpus callosum. Genes encoding TFs are highlighted in red. e, QQ plot of enriched motifs in oligodendrocytes comparing cortex versus corpus callosum. TF motifs overlapping with TF genes identified in d are highlighted in red. f, Spatial maps of Sox10 and Sox8 gene activity scores in cortex and corpus callosum regions. g, Spatial maps of Sox10 and Sox8 motif enrichment scores in cortex and corpus callosum regions.

To detect cell-type-specific differential accessibility between anatomic brain regions, we modeled each spot’s chromVAR or gene activity score using a Gaussian SpotGLM. Although peak counts are discrete, aggregation across large numbers of peaks yields approximately continuous, normally distributed scores, justifying the use of a normal family with identity link function. We tested for region differences for each motif (or gene) in each cell type (Methods). Motifs (or genes) that are found to be significant for a given region are reported as cell-type-specific markers.

We analyzed spatial ATAC-seq data from the postnatal day 22 mouse brain4 using two complementary representations of chromatin accessibility. The dataset contained 14 annotated brain regions. For a focused comparison, we contrasted the corpus callosum with the cortex (Fig. 6b). The corpus callosum is a heavily myelinated white-matter tract enriched in oligodendrocytes, whereas the cortex contains a more heterogeneous mixture of cell types. Same-slide transcriptomic measurements were used for cell type deconvolution. The estimated oligodendrocyte proportions were spatially concordant with expression of the oligodendrocyte marker Mbp, supporting the estimated mixture proportions used by SpotGLM (Fig. 6c).

We first examined gene activity scores, which summarize accessibility near gene TSSs. Across 24,027 genes, including 746 genes encoding TFs, SpotGLM identified 223 TF genes with increased activity in oligodendrocytes in the corpus callosum relative to the cortex (Fig. 6d). These included regulators associated with oligodendrocyte differentiation and myelination, such as Sox10, Nkx2-2 and Olig1.

We next tested whether accessibility at TF-binding motifs showed corresponding regional differences. Among 746 motifs, SpotGLM identified 23 motifs enriched in oligodendrocytes in the corpus callosum, including motifs from the Sox family (Fig. 6e). In particular many of the Sox family motifs found using the chromVAR scores, such as Sox8 and Sox10, were also found when using gene activity for the TF genes, reinforcing a coherent oligodendrocyte-specific regulatory program. The spatial distribution of Sox10 and Sox8, in terms of gene activity score (Fig. 6f) and motif enrichment (Fig. 6g), confirms their localization to the corpus collosum. Together, these results demonstrate concordance between motif-level and gene-level deconvolution of cell-type-specific signals and highlight region-specific regulatory activation within a defined cell type.

Discussion

Spatially resolved omics technologies are transforming our understanding of tissue organization by enabling high-throughput molecular profiling within intact tissues, preserving their spatial context. As these technologies evolve toward high-resolution and multimodal profiling, statistical frameworks must address two emerging challenges: mixture confounding at spot resolution and computational scalability at increasing data volumes. In this work, we introduce spotGLM, a mixture-aware GLM framework for cell-type-specific differential testing across spatial modalities, together with SPARROW, a power-preserving submodular data selection strategy for scalable inference.

SpotGLM extends the GLM to spatial data where each spatial coordinate can contain compositional mixtures of multiple cell types. By explicitly modeling modality-specific sampling noise and spatial mixing, SpotGLM enables hypothesis testing across a wide range of omics modalities, including gene expression, chromatin accessibility and RNA splicing. Through simulations and real-data applications, we demonstrate accurate recovery of cell-type-specific niche effects under mixture, including differential gene expression, spatial isoform switching and regulatory motif accessibility.

The biological applications presented here also yield findings beyond methodological validation. In CRC, serial-slice cross-platform comparison between Visium HD and Xenium provided a stringent test of mixture-aware inference, demonstrating coefficient-level concordance of fibroblast niche effects across technologies. This validation establishes that spotGLM can recover cell-type-specific niche programs from spot-level whole-transcriptome data with accuracy comparable to single-cell-resolved measurements. In mouse kidney, modeling a continuous corticomedullary osmolarity gradient revealed fibroblast transcriptional programs associated with increasing osmotic stress that are not captured by coarse anatomical region labels. In spatial long-read data, spotGLM enabled cell-type-resolved analysis of spatial isoform switching, clarifying fundamental distinctions between global isoform changes and within-cell-type splicing regulation. Lastly, in spatial ATAC-seq of mouse brain, mixture-aware modeling uncovered oligodendrocyte-specific regulatory motif enrichment across brain regions, extending spatial differential testing to chromatin-level regulatory programs. Together, these examples illustrate how mixture-aware modeling enables discovery of spatially structured, cell-type-specific molecular programs across modalities.

Complementing spotGLM, SPARROW addresses the computational bottleneck posed by large spatial datasets while reflecting a broader statistical insight. As spatial technologies scale to hundreds of thousands or millions of observations per experiment, statistical power for detecting biologically meaningful effect sizes eventually saturates; beyond a certain sample size, additional observations primarily reduce standard errors for increasingly small effects that may be of limited practical relevance. The true advantage of large spatial datasets lies instead in their ability to capture rare cell types and rare niche configurations with sufficient representation. SPARROW leverages an A-optimality-based proxy for statistical power, selecting subsets that preserve information across covariate configurations, including rare ones. As a result, the number of observations required for inference can plateau even as total dataset size continues to grow, yielding bounded-runtime analysis without sacrificing sensitivity for effect sizes of interest. This regime is increasingly important as next-generation spatial omics platforms routinely generate millions of spatial measurements per sample, shifting the statistical challenge from sample scarcity to configuration coverage.

While our framework provides a scalable and flexible foundation for spatial analysis, several caveats merit discussion. First, like all cell-type-specific inference methods from spatially barcoded sequencing data, the accuracy of spotGLM relies on the quality of the deconvolution method used to estimate cell type proportions. To quantify the impact of this effect, we performed in silico spatial aggregation experiments using datasets with known cell type labels, allowing direct comparison between analyses based on true and deconvolution-estimated proportions (Supplementary Note 9 and Supplementary Figs. 7 and 8). These results show that deconvolution error primarily reduces sensitivity, with recall decreasing in proportion to cell-type-specific estimation accuracy, while precision remains consistently high (≥0.98) across datasets. This indicates that spotGLM behaves as a conservative two-stage procedure, preserving high-confidence signals without inflating false discoveries.

Second, we explored multiple criteria for subset selection in SPARROW. While our primary results are based on A-optimality, which minimizes the trace of the covariance matrix of (hat{beta }), we also evaluated D-optimality, which minimizes (log {det [{({X}^{{{top }}}X)}^{-1}]}) and corresponds to minimizing the entropy of the error distribution. D-optimality is also submodular and invariant to linear transformations of the feature space. As shown in Supplementary Fig. 1, the two criteria have similar performance across datasets but we chose A-optimality as it relates to the standard errors of the estimated coefficients, a quantity that is easier to interpret.

Third, while SPARROW enables dramatic reduction in data volume for analysis, it does not reduce sparsity. In high-resolution technologies such as Visium HD, where per-spot counts are low, rasterization—the aggregation of neighboring spots—may be necessary to ameliorate data sparsity and improve signal-to-noise ratios. SPARROW and rasterization are complementary and can be used in combination, as demonstrated in our CRC and kidney example.

Lastly, an important consideration is the specification of spatial covariates. In this work, we primarily used anatomically or experimentally defined covariates (for example, neighborhood composition or physiological gradients such as the corticomedullary axis). This choice ensures interpretability and avoids potential circularity, where gene expression data are used both to define spatial structure and to test for associations. At the same time, recent methods such as GASTON47 and COPRO48 learn low-dimensional spatial axes directly from transcriptomic data. These unsupervised representations can be valuable for discovering previously uncharacterized spatial gradients. In such settings, spotGLM can be applied downstream using learned axes as covariates, providing a flexible framework that integrates unsupervised spatial representation learning with cell-type-specific hypothesis testing. The choice between anatomically defined and data-driven covariates, therefore, reflects a trade-off between interpretability and discovery and depends on the underlying biological question.

In summary, SpotGLM and SPARROW together form an integrated framework for the analysis of spatial omics data, enabling scalable and interpretable detection of spatially contextualized molecular programs with cell type specificity.

Methods

SpotGLM model formulation and parameter estimation

To motivate the model, we start first with the simpler scenario where we have single-cell-resolution data. Assume that we observe n cells, with ({Y}_{ntimes 1}) being the feature of interest, which could be the expression of a gene, the splicing proportion of an isoform or the ATAC-derived activity of a TF. The detailed definition of Y is given in later sections. Let ({X}_{ntimes p}) be the covariate matrix of p spatial factors, which we also refer to as the multivariate encoding of the cell’s niche. In each of our examples, spatial niche is encoded differently, with details given later. We assume a GLM where the conditional expectation of Y given X, properly transformed, is linear in X,

$$Fleft(Eleft[{Y}_{i}|{X}_{i}right]right)={X}_{i}{beta }_{{T}_{i}}.$$

(4)

Here, Yi is the measurement for the ith cell, Xi is the ith row of the covariate matrix X and Ti is the cell type assignment for cell i. Our parameters of interest are the coefficient vectors ({beta }_{t}in {{mathbb{R}}}^{p}), for all cell types i, which encode the cell-type-specific dependence of Y on each column in X. Our goal is to estimate and conduct inference on βt. When our data are at single-cell resolution and all cells are labeled by cell type, this can be achieved by fitting the model in equation (4) separately for each cell type.

In spot-based spatial transcriptomic data, features are measured at prefixed spots, which may straddle multiple cells. Our goal remains the same: to estimate the p × 1 coefficient vector βt for all cell types t = 1, …, T from equation (4); however, in this setting, the feature values and niche covariates are only observed at spot resolution. Let the cells be grouped into S disjoint spots such that each spot s contains some nonempty subset of the n cells. Denote by ({m}_{s}) the set of indices of cells that belong to spot s, ({mathop{cup }nolimits^{S}}_{s=1}{m}_{s}=left{1,ldots ,nright},{m}_{s}cap {m}_{{s}^{{prime} }}={rmvarnothing },mathrm{for},mathrm{all},s,,{s}^{{prime} }.)

That is, each cell belongs to one spot and each spot contains at least one cell. Now, our observed data across S spots is ZS × 1, where

$$Eleft[{Z}_{s}|{X}_{s}right]=sum _{i:,iin {m}_{s}}{C}_{s,i}Eleft[{Y}_{i}|{X}_{i}right],$$

(5)

where Cs,i is an (unobserved) per-spot weight for each cell (iin {m}_{s}). Examples of Cs,i are as follows:

  • ({C}_{s,i}=1), where a spot’s feature value is the sum of the feature values of each cell in the spot. We use this for spatial transcriptomic data, when it is not library normalized, where a spot’s gene count is the sum of counts across cells within the spot.

  • ({C}_{s,i}=frac{1}{|{m}_{s}|}), where a spot’s feature value is the average of the feature values of each cell in the spot. We use this for library-normalized spatial transcriptomic data.

  • ({C}_{s,i}=frac{{w}_{i}}{{sum }_{j:jin {m}_{s}}{w}_{j}}), where a spot’s feature value is the weighted average of the feature values of each cell in the spot with cell i’s weight being wi. We use this for isoform relative expression, which depends on the overall gene expression across cell types.

Substituting equation (4) into equation (5), we have (Eleft[{Z}_{s}|{X}_{s}right]=mathopsumnolimits _{i:,iin {m}_{s}}{C}_{s,i}Eleft[{Y}_{i}|{X}_{i}right])(=mathopsumnolimits _{i:,iin {m}_{s}}{C}_{s,i}{F}^{-1}left({X}_{i}{beta }_{{T}_{i}}right).) Now, assume that, for cells (a,bin {m}_{s}), ({X}_{a}={X}_{b}={X}_{s}) (that is, the spatial niche for two cells in the same spot are the same). Furthermore, assume that the weights Cs,t depend only on cell type and, for two cells of the same type sharing a spot, their weights are the same. Then, we have

$$Eleft[{Z}_{s}|Xright]=sum _{i:,iin {m}_{s}}{C}_{s,i}{F}^{-1}left({X}_{i}{beta }_{{T}_{i}}right)=mathop{sum }limits_{t=1}^{T}{n}_{s,t}{C}_{s,t},{F}^{-1}left({X}_{s}{beta }_{t}right)=mathop{sum }limits_{t=1}^{T}{widetilde{C}}_{s,t}{F}^{-1}left({X}_{s}{beta }_{t}right),$$

(6)

where ns,t is the number of cells of type t in spot s, and ({widetilde{C}}_{s,t}={n}_{s,t}{C}_{s,t}). Note that because Cs,t is spot and cell type specific, we do not actually need to know ns,t. When we introduced the model in equation (2), we simply absorbed ns,t into Cs,t. For the binomial model, the weights need to be normalized to sum to 1.

We note here the subtle distinction that the assumption given by equation (5) is not the same as

$${Z}_{s}=sum _{i:iin {m}_{s}}{C}_{s,i}{Y}_{i}.$$

(7)

Equation (5) relates the conditional expectation of Zs to the conditional expectation of Yi; thus, we have the flexibility to model the distribution of the response Zs. In contrast, equation (7) is a stronger assumption in that the distribution of Zs is necessarily a convolution of the individual distributions of Yi.

The model in equation (6), which we call a SpotGLM, is a generalization of a standard GLM for the case where the data are in the form of mixtures. To fit this model, we use gradient descent on βt to maximize its log likelihood. In Supplementary Notes 1 and 2, we show that, under certain assumptions, the gradient and Hessian matrix of the log likelihood of equation (6) with respect to βt can be computed. The formulas for the Fisher information matrix in Supplementary Information yield the approximate standard errors for the maximum likelihood estimates of (beta). Assuming reasonable sample size (that is number of spots and coverage), this allows us to quickly compute confidence intervals and conduct hypothesis testing without permutations.

Now, we describe the iterative algorithm for fitting the model. Model parameters are initiated through a dominant-cell approximation strategy. Each spot is assigned to the cell type with the highest estimated proportion and treated as a single cell. For each cell type t, ({beta }_{t}) is initialized by fitting a weighted GLM of the same distribution family and with the same covariates. Each spot is weighted by the proportion of the dominant cell type in the spot, derived from deconvolution. Covariates with fewer than five nonzero observations having a positive cell type proportion are initialized to zero and excluded from the model fitting process.

After initialization, estimation of βt is performed through minibatch gradient descent using Adam49 with a first moment weighting coefficient of 0.9 and second moment weighting coefficient of 0.999. The dispersion parameter in the case of the negative binomial model is fitted between epochs. We first choose an initial learning rate λ. Between batches, the learning rate is halved if the log likelihood decreases by a factor greater than 1 + 10−6 on the given batch. This makes the optimization more robust to the choice of initial learning rate. Denote the ratio of the full-data log likelihood between epoch e to that of epoch e + 1 as r. Convergence occurs when (min (r,1/r)) is greater than a constant c, which defaults to 1 − 10−6. Convergence also occurs if, for M consecutive epochs, the change in r is less than (epsilon), with the default values of M and (epsilon) being 10 and 10−6, respectively.

We recommend scaling covariates to a consistent range (for example, between −1 and 1 or 0 and 1). We also recommend starting with a large initial learning rate ({lambda }_{0}). As long as the user chooses a large enough starting value for ({lambda }_{0}), the parameter fitting of the SpotGLM should converge.

SPARROW formulation and algorithmic details

Formulation of SPARROW objective

Our data consist of responses ({Y}_{ntimes 1}) and covariates ({X}_{ntimes p}), where n is the number of data points and p is the number of covariates. Our analyses assume that ({Y}_{i}{rm{| }}{X}_{i}) follows a mixture-aware GLM of the form in equation (2). Let (beta) be the coefficients for this model, where ({beta }_{t,j}) measures the effect of the jth covariate on Y in cell type t. To simplify ensuing notation, we flatten (beta) and refer to each of its elements as ({beta }_{j}). We use the term ‘data point’ rather than ‘cell’ or ‘spot’ to stress that SPARROW is applicable to both cell-level and spot-level data (for cell-level data, we would simply replace the generalized mixed linear model with a standard GLM). For a subset of data points (S={{s}_{1},ldots ,{s}_{K}}subset {1,ldots ,n}) of size K, we use the notation ({X}_{S}={left[{X}_{{s}_{1}},ldots ,{X}_{{s}_{K}}right]}^{{{T}}},{Y}_{S}={left[{Y}_{{s}_{1}},ldots ,{Y}_{{s}_{K}}right]}^{{rm{T}}}) to denote the subseted rows of (X,Y). Fixing the false positive rate at (alpha), let the power of the analysis for testing the null hypothesis ({H}_{0}:{beta }_{j}=0) using subset S be ({P}_{alpha }(S,j)). The goal in data subsampling is to find a subset S such that

$$forall j:{P}_{alpha }left(S,jright) < ctimes {P}_{alpha }left(left{1,ldots ,nright},jright),$$

(8)

where c, the power retention threshold, is close to 1. To achieve this, we first fix the subset size K and identify the subset ({S}_{K}^{star }) with criterion

$${S}_{K}^{star }=mathop{min }limits_{S:|S|=K}fleft(Sright),$$

(9)

where

$$f(S)={rm{tr}}{left({X}_{S}^{{{top }}}W{X}_{S}right)}^{-1},$$

(10)

and W is a diagonal matrix that depends on the specific model used in the analysis. The explicit form of W for different models is derived in Supplementary Notes 1 and 2. The criterion in equation (10) is the A-optimal design criterion. As ({X}_{S}^{{{top }}}W{X}_{S}) is the Fisher information matrix, f(S) is the sum of the asymptotic marginal variances of the coefficient estimates. We use this criterion because the marginal standard errors directly determine power for coefficient-wise Wald tests.

Greedy optimization of the A-optimal subset

The optimization in equation (9) is a cardinality-constrained A-optimal design problem. Because exhaustive search is infeasible, SPARROW uses a stochastic greedy algorithm. Let ({M}_{S}={Lambda }+{Z}_{S}^{{top }}{Z}_{S}), where (Z={W}^{1/2}X) and (Lambda succ 0) is a small ridge term or initial information matrix. At each iteration, SPARROW samples a candidate batch from the unselected observations and adds the candidate u that minimizes ({rm{tr}}{{M}_{Scup {u}}^{-1}}). The ridge term ensures that the inverse is well defined even at early iterations.

The A-optimal objective is monotone; adding observations can only increase the information matrix and, therefore, can only decrease ({rm{tr}}({M}_{S}^{-1})). A regularized D-optimal variant, ({G}_{D}left(Sright)=mathrm{logdet}left({M}_{S}right)-mathrm{logdet}left({Lambda }right)), is monotone submodular for fixed positive semidefinite per-observation information contributions. We use the A-optimal objective as the default because it is directly interpretable as the sum of coefficient variances; empirically, A-optimal selection and D-optimal selection give similar performance (Supplementary Fig. 1).

Finding the optimal subset size

The goal of SPARROW is to identify a subsample of the data such that the subsampled data can approximately attain the power of the original data for the downstream analysis as specified by the design matrix X. To determine the suitable subsample size ({K}^{star }), we perform an approximate power calculation. The power of the Wald tests for testing ({H}_{0}:{beta }_{j}=0) when the standard error is (sigma) and the true value is ({beta }_{j}=b > 0) can be approximated under asymptotic normality by

$${P}_{text{theory}}left(sigma ,bright)=1-varPhi left({z}_{1-{alpha }/{2}}-frac{b}{sigma }right)-varPhi left(-{z}_{1-alpha /2}-frac{b}{sigma }right),$$

(11)

where (alpha) is the level of the test and ({Z}_{1-alpha }) is the inverse cumulative distribution function of a standard normal evaluated at (1-alpha). We use the notation ({P}_{text{theory}}(sigma ,b)) in equation (11) to distinguish this theoretical quantity from the achieved power ({P}_{alpha }(S,j)) in equation (8).

Now, for a given subset ({S}_{K}) of size (K), let ({rm{SE}}({hat{beta }}_{{S}_{K},j})) be the standard error of the estimate of ({beta }_{j}) if only the data in ({S}_{K}) were used to fit the model. Note that ({rm{SE}}({hat{beta }}_{{S}_{K},j})) can be explicitly approximated using the square root of the diagonal terms of the covariance matrix (that is, the inverse Fisher information matrix), the explicit form of which is given in the Supplementary Notes 1 and 2. Thus, given a candidate value of (beta), we could choose (K) such that

$$text{for all covariates},j:,{P}_{text{theory}}left({rm{SE}}({hat{beta }}_{{S}_{K}^{* },j}),{beta }_{j}right) > ctimes {P}_{text{theory}}left({rm{SE}}left({hat{beta }}_{left{1,ldots ,nright},j}right),{beta }_{j}right)$$

(12)

where c is what we call the ‘power retention ratio’. We would usually set c close to 1.

The power formulas above assume that we know the true value of each coefficient ({beta }_{j}) and their standard errors. As we do not know the true values, we assume a minimum effect size of interest, which we call ({delta }_{min }). For example, in the case of Poisson regression, one may not care about identifying log fold changes less than 5% and, thus, set ({delta }_{min }=0.05). Note that ({delta }_{min }) is a global threshold applied to all covariates. We strongly recommend standardizing the covariates such that the same value of ({delta }_{min }) can be applied across covariates. The value of ({delta }_{min }) could be made covariate dependent if needed, but that would add unnecessary complexity. For each covariate j, define ({delta }_{j}^{* }=inf {delta :{P}_{text{theory}})(({rm{SE}}({hat{beta}}_{rm{full}},{j}),)({delta}) > 0.999},) which is the minimum effect size that can be detected with almost certainty. Then, let ({delta }_{max ,j})(=max ({delta }_{j}^{* },{delta }_{min }).)

Our power analysis assumes that ({beta }_{j}) is uniform within the interval ([{delta }_{min },{delta }_{max ,j}]). This assumption cannot really be tested but we believe it is reasonable because, for values larger than ({delta }_{max ,j}), any method will achieve power near 1 and, for values less than ({delta }_{min }), the effect size is too small to be of interest. The assumed range for ({beta }_{j}) and the formula for its standard error allow us to compute the expected power of testing ({H}_{0}:)βj = 0 on any subset S, assuming a uniform prior distribution:

$$Eleft[{P}_{text{theory}}left({rm{SE}}({hat{beta }}_{S,j}),{beta }_{j}right)right]=frac{1}{{delta }_{max ,j}-{delta }_{min }}{int }_{{delta }_{min }}^{{delta }_{max ,j}}{P}_{text{theory}}left({rm{SE}}({hat{beta }}_{S,j}),delta right)ddelta .$$

(13)

In the case where ({delta }_{j}^{* } < {delta }_{min }), that is, even the minimum effect size can be detected with almost certainty, then (E[{P}_{text{theory}}({rm{SE}}({hat{beta }}_{j}),{beta }_{j})]=1). Using equation (13) we can first compute the expected power on the full dataset. Then, we can use it to deduct the target standard error for ({beta }_{j}) to achieve on the subsample ({{rm{SE}}}_{text{target},j}=mathop{max }limits_{{sigma }_{j}}left{E[{P}_{text{theory}}({sigma }_{j},{beta }_{j})]right.)(left. > cE[{P}_{text{theory}}({rm{SE}}({hat{beta }}_{{1,ldots ,n},j}),{beta }_{j})]right}).

({{rm{SE}}}_{text{target},j}) represents the largest standard error at which we can recover at least c of the power achievable on the full dataset for covariate (j). Lastly, we use as our stopping criterion for subset size K that achieves

$$mathrm{SE}left({hat{beta }}_{{S}_{K}^{* },j}right) < {mathrm{SE}}_{text{target},j},text{for all},j.$$

(14)

That is, the approximate standard error for the optimal subset ({S}_{K}^{* }) must be lower than the target standard error for all covariates.

The complete SPARROW algorithm

In the previous sections, we introduced how SPARROW uses greedy selection to iteratively add data points to the subsample to maximize the statistical power of downstream analyses. We also introduced a natural stopping criterion to achieve a specified proportion of the power attainable with the complete dataset. Integrating these ideas, we now describe in detail the SPARROW algorithm.

We start by scaling each column j of (Z={W}^{1/2}X) by the corresponding target standard error ({{rm{SE}}}_{text{target},j}). This normalization ensures that no single covariate dominates the greedy selection, as this standardizes the diagonal elements of ({({Z}^{{top }}Z)}^{-1}) representing the squared standard errors of coefficient estimates. After scaling, a standard error ≤ 1 would indicate that the target precision in the estimation of the coefficient has been attained by the data subsample:

$${mathrm{SE}}left({hat{beta }}_{S,j}right)le 1,{text{for}}, {rm{all}},j.$$

(15)

When, for a coefficient j, the above criterion is achieved for a subset S, we say that the coefficient has converged.

We start with a data subsample of S = ∅. In each iteration, the algorithm greedily selects the data point i that minimizes

$${rm{trace}}left[{({Z}_{Scup {i}}^{{top }}{Z}_{Scup {i}})}^{-1}right]$$

(16)

and set S←S∪i. The process continues iteratively until all coefficients have converged; that is, for all j, equation (15) has been achieved by subset S.

To further improve the runtime of the algorithm, we consider, for each iteration, only those data points that contribute information for the nonconverged coefficients (in other words, all data points i for which ({X}_{i,j}=0) for all nonconverged coefficients (j) are excluded).

Note that ({delta }_{max ,j}), being dependent on the full-data standard errors, decreases monotonically as n increases. Thus, as full-data size grows, it eventually reaches a value n* for which (forall j,,{delta }_{j}^{* } < {delta }_{min }) (in other words, the minimum effect size of interest can be detected with near certainty). Consequently, when full-data size satisfies n > n*, the greedy A-optimal subset size may actually decrease with increasing n, because the optimization is conducted over an increasingly larger set and, thus, the target standard error can be achieved earlier. This explains the decrease after a dataset size of 1 million in Fig. 2e. Such a trend indicates that sufficient data size has been reached for near-perfect power on the effect sizes of interest. This phenomenon underlies SPARROW’s bounded runtime, as demonstrated in Fig. 2e.

Algorithm 1:

SPARROW Algorithm

1. Input: Data matrix (Z=X{W}^{1/2}), target standard errors ({{rm{SE}}}_{text{target},j}), batch size C

2. Scale each column j of Z by ({{rm{SE}}}_{text{target},j})

3. Initialize subset (S={rm{varnothing }})

4: while not all coefficients converged do

5. Sample C data points among all data points informative on at least one nonconverged coefficient

6. Find data point i minimizing

$${rm{trace}}left[{left({Z}_{Scup left{iright}}^{{{top }}}{Z}_{Scup left{iright}}right)}^{-1}right]$$

(17)

7. Update subset: (Sto Scup {i})

8: Update convergence status based on standard errors computed using current S

9: end while

10: Output: S

Details of the scalability simulation

We performed a scalability assessment for evaluating the optimal subset size and computation time needed of SPARROW to retain close to full power (power retention ratio: 0.975) for datasets of varying size, shown in Fig. 2e. We simulated according to the simplest Poisson model, ({Y}_{i}sim text{Poisson}left({lambda }_{i}right),,{lambda }_{i}=exp left({X}_{i}{beta }_{{T}_{i}}right).)

The mixture model in SpotGLM is more complicated and would require the simulation of per-spot mixture components. However, the main factors that determine optimal subset size are the true values of ({beta }_{t}) and the minimum effect threshold ({delta }_{min }), which can be explored in the Poisson model that is more directly interpretable. In practice, data would also be expected to exhibit overdispersion, which is better captured by the negative binomial model, but we expect the negative binomial model to follow the Poisson model in terms of power–sample size trade-offs, while requiring an additional overdispersion parameter that in practice is estimated from the data and incorporated into the standard error computation. All this adds complexity without changing the major trends that can be demonstrated by the simple Poisson model.

We simulated datasets with number of spots n increasing from 10,000 to 5 million: (nin left{10,000,25,000,50,000,100,000,right.)(left.qquad150,000,200,000,ldots ,5,000,000right}.)

Each data point was assigned a random cell type among six types, and a covariate matrix (Xin {{mathbb{R}}}^{ntimes 6}) was generated with entries from (text{Uniform})(−1, 1) × (text{Bernoulli}(0.25)). Cell-type-specific coefficients ({beta }_{t}in {{mathbb{R}}}^{7}) were drawn from N(0, 1/4), with intercepts from (text{Uniform}) (−5, −6.25). SPARROW was run with a power retention threshold of 0.975 and effect size threshold ({delta }_{min }=0.05). Thus, we aim to detect a minimum of approximately ({e}^{0.05}approx 1.05) fold change in mean expression per unit increase in X. Our goal is to detect such signals with 97.5% of the power of the full dataset. For each value of (n), 100 datasets were simulated from the Poisson model above. For each iteration, Poisson regression was run on both the full and subsampled datasets to estimate β. Power and runtime were assessed both for the full-data analysis and for the SPARROW subsampled data analysis.

The above simulation parameters intend to mimic a scenario where the detection problem is hard but not impossible. With different parameters, the sample size requirements would differ; however, the trends displayed in Fig. 2e would be the same. The required subset size ({K}^{* }) would at first be equal to the full-data size (that is, no data reduction) when the full-data size is small, to retain the desired power. As data size increases, the required subset size would plateau, achieving constant runtime. Despite the plateauing subset size, the SPARROW subset would be optimized on the basis of the entire dataset and, thus, all of the data are used for the selection.

Details of data analysis

Software versions in benchmarking

For benchmarking against geometric sketching, rasterization and random selection, we implemented the geosketch package in Python using reticulate, the SEraster package in R and the sample function in R, respectively.

Simulation and benchmarking against C-SIDE, NicheDE and single-cell baseline method

To systematically evaluate performance, we conducted 100 simulation replicates under a mixture setting. We simulated data with six cell types and ten covariates, where each spot contained two cell types to reflect Visium HD doublet mode deconvolution. Cell type proportions and covariates were fixed across simulations. For each gene, true cell-type-specific and niche-associated coefficients were randomly sampled from a uniform distribution between −0.6 and 0.6. Spot-level gene counts were generated from a Poisson distribution, as spVC is designed for Poisson distribution.

Within each replicate, we subsampled the dataset to 2,000, 4,000, 6,000, 8,000, 10,000 and 20,000 spots to assess scalability and statistical performance. All methods were run on the same subsampled data in each setting to ensure a fair comparison. We compared SpotGLM to spVC, C-SIDE, NicheDE and a single-cell baseline that assigns each spot to its dominant cell type.

SpotGLM, C-SIDE and NicheDE explicitly model cell-type-specific and niche-associated effects, enabling direct comparison between estimated and true coefficients. The single-cell baseline ignores mixture structure and treats each spot as a pure cell type. Because spVC is not inherently designed for cell-type-specific or niche-associated testing, we extended it by incorporating cell type deconvolution proportions and their interactions with niche covariates to approximate comparable effects.

We evaluated performance using the mean squared error of coefficient estimates, type I error, statistical power and runtime.

MERFISH CRC region-specific differential expression analysis

MERFISH data of human colon tissue affected by colon cancer were collected50. For the MERFISH CRC analyses shown in Fig. 2a–d, filtering out cells with fewer than 20 total UMIs yielded a dataset containing 766,757 cells, each profiled for 500 genes and annotated to one of the five tissue regions11. Cells were assigned to one of 15 cell types: absorptive, B, DC, endothelial, fibroblast, macrophage, malignant, mast, monocyte, myofibroblast, neuronal, pericyte, plasma, secretory and TNKILC.

To identify region-specific differential expression, we constructed a covariate matrix (Xin {{mathbb{R}}}^{ntimes 5}) by one-hot encoding the region label for each cell. For each gene g and each cell type t, we fit a Poisson GLM of the form ({Y}_{i,g}sim text{Poisson}left({lambda }_{i,g}right),,log {lambda }_{i,g}={X}_{i}{beta }_{t,g}+log {L}_{i},) where Yi,g is the observed count for gene (g) in cell i, Li is the library size of cell i and βt,g is the 5 × 1 vector of region coefficients for each cell type and gene. For Fig. 2, Wald contrast tests were performed for pairwise comparisons of the ({beta }_{t,g}) parameters between regions within each cell type, that is, with the null hypothesis ({H}_{0}:{beta }_{t,g,r}={beta }_{t,g,{r}^{{prime} }}) for two regions r and r′. This results in a total of (5 regions)2 × (15 cell types) × (500 genes) = 187,500 tests. SPARROW was applied to select a subset of cells using the cell type expanded region covariate matrix, with each region and cell type combination forming a column.

Xenium liver niche differential expression analysis

This dataset, available at 10x Genomics, is a Xenium spatial transcriptomics dataset derived from healthy human liver tissue51,52. For the Xenium liver analysis shown in Fig. 2a, filtering out cells with fewer than 50 detected transcripts yielded a dataset that included 182,158 cells profiled for the expression of 377 genes. These cells were classified into eight distinct cell types: lymphocytes, fibroblasts, endothelial cells, pericentral hepatocytes, stellate cells, Kupffer cells, periportal hepatocytes and cholangiocytes.

For each cell, we computed the average neighborhood cell type proportions within a 50-μm radius. These were used as continuous-valued covariates to capture each cell’s local niche context. Because the niche context covariates represent percentages, a standard regression suffers from rank deficiency of the covariate matrix when adding an intercept. To circumvent this, we introduce an intercept column and remove one of the cell types (periportal hepatocytes) from the columns of X, ensuring that the model remains well conditioned and interpretable. Thus, the parameters can be interpreted as differences from periportal hepatocytes. For all genes, we modeled the expression of gene g in cell i of type t as ({Y}_{i,g}sim text{NB}left({mu }_{i,g},{gamma }_{g}right),,{mu }_{i,g})(=exp left({X}_{i}{beta }_{{T}_{i},g}+log {L}_{i}right)), where ({Y}_{i,g}) is the observed gene count for gene g in cell i, ({X}_{i}) is the niche context for cell i as described above and ({beta }_{{T}_{i},g}) is the vector of niche parameters for gene g and cell type ({T}_{i}). For Fig. 2, Wald tests were performed for each nonintercept coefficient in ({beta }_{t,g}) across all cell types and across the top 100 highly expressed genes. That is, the null hypothesis was ({H}_{0}:{beta }_{t,g,j}=0,j=2,ldots ,8). This resulted in a total of 5,600 tests. SPARROW was applied to select a subset of cells using the cell type expanded covariate matrix, with each neighborhood cell type–cell type combination forming a column.

Visium HD kidney SVG analysis

Here, we describe the analysis in Fig. 2 meant to demonstrate the coupling of SPARROW with cell-type-specific SVG (ct-SVG)13. For Fig. 2, we performed ct-SVG analysis13 using a Gaussian spatial kernel. The Visium HD kidney dataset contains 470,883 spatial spots. To overcome the extreme sparsity in this dataset, we rasterized the data to 100,000 pseudospots by aggregating local neighborhoods. Unlike the other analyses where the covariate matrix X is explicitly defined on the basis of local niche composition or spatial domain designation, ct-SVG analyses use a kernel matrix ({K}_{Stimes S}) that is generally chosen to be a Gaussian kernel evaluated on the spatial positions of the spots with some prespecified bandwidth. To this end, we conducted a singular value decomposition on K and set X to be the p-dimensional cell embedding that best approximates K, that is, ({X}^{{{top }}}Xapprox K). X was further normalized such that the diagonal elements of ({X}^{{{top }}}X) were 1. SPARROW was applied separately for each cell type, using this embedding as the covariate matrix.

Visium HD CRC niche differential expression analysis

This Visium HD dataset comes from human CRC15,52. After filtering out spots with low expression and aggregating spots into 8 µm × 8 µm regions and deconvolving using RCTD doublet mode that fits at most two cell types per spot6, the final data contained 309,034 spatial barcoded spots, each deconvolved into six main cell types: B cells, fibroblasts, intestinal epithelial, macrophages, T cells and tumor cells. For each spot, we computed the average neighboring cell type proportions within a 64-μm radius, ({X}_{s}=frac{1}{|{N}_{s}|}sum _{{s}^{{prime} }in {N}_{s}}{pi }_{{s}^{{prime} }},) where ({pi }_{{s}^{{prime} }}) is the 6 × 1 cell type proportion vector at spot s′. These were used as continuous-valued covariates to capture local niche context. In general, the rows of X are normalized to sum to one making its columns rank deficient. To circumvent this, we introduced an intercept column and remove one of the cell types from the columns of X, ensuring that the model remains well conditioned and interpretable. We modeled gene expression using a spot-level negative binomial GLM: ({Z}_{s,g}sim text{NB}left({mu }_{s,g},{gamma }_{g}right),)(,{mu }_{s,g}=sum _{t}{pi }_{s,t}exp left(sum _{{t}^{{prime} }}{X}_{s,{t}^{{prime} }}{beta }_{{t}^{{prime} },t}^{g}+log {L}_{s}right).) Here, ({Z}_{s,g}) is the count for gene g in spot s, ({pi }_{s,t}) is the proportion of cell type t in spot s and serves as our SpotGLM weight constant ({C}_{s,t}), ({X}_{s}) are the niche covariates as defined above and ({L}_{s}) is the library size of spot s. The parameters of interest are ({beta }_{{t}^{{prime} },t}^{g}), the gene-specific niche-effect of cell type ({t}^{{prime} }) on cell type t. We test the null hypothesis ({H}_{0}:{beta }_{{t}^{{prime} },t}^{g}=0) using Wald tests. If ({beta }_{{t}^{{prime} },t}^{g}ne 0), then the presence of cell type ({t}^{{prime} }) influences the gene expression of gene g in cell type t.

For the analysis in Fig. 2, for each of the top 100 highly expressed genes, pairwise contrasts were performed on ({beta }^{g}) coefficients across cell types, for a total of 6 × 15 × 100 = 9,000 tests. SPARROW selected informative spots using the SpotGLM-aware expansion of the covariate matrix.

For the analysis in Fig. 3, we considered all genes. Because this analysis focuses on the effect of tumor cells on its surrounding spatial niche, a natural choice for the intercept is the column corresponding to the proportion of the tumor cells. For cell type k, we call a gene g a tumor niche marker gene relative to niche j if ({beta }_{k,j,g} < 0).

Because of the substantial computational cost of full-data analysis, we applied SPARROW to reduce the dataset to 75,000 spots. Running SpotGLM on 18,000 genes at this reduced scale required approximately 22 h of computation, while analysis of the full data required approximately 6 days of computation.

Xenium CRC data analysis and comparison to serial-slide Visium HD

We used Xenium colon cancer slide from 10x genomics. We first annotated cells using canonical marker genes and annotated nine cell types. We then performed standard GLM to identify fibroblast-specific differential genes. We modeled gene expression using a standard negative binomial GLM: ({Y}_{c,g}|{X}_{c},cin text{type}Tsim text{NB}({mu }_{c,g},{gamma }_{g}))(,,{mu }_{c,g}=exp ({X}_{c,{t}^{{prime} }}{beta }_{T,{t}^{{prime} }}^{g}+log {L}_{c}).) Here, ({Y}_{c,g}) is the count for gene g in cell c, T is the cell type of cell c, ({X}_{c}) are the niche covariates as defined above and ({L}_{c}) is the library size of cell c. The parameters of interest are ({beta }_{T,{t}^{{prime} }}^{g}), the gene-specific niche-effect of cell type T on niche ({t}^{{prime} }). We test the null hypothesis ({beta }_{T,{t}^{{prime} }}^{g}=0) using Wald tests. If ({beta }_{T,{t}^{{prime} }}^{g}ne 0), then the presence of niche ({t}^{{prime} }) influences the gene expression of gene g in cell type T.

To compare to Visium HD colon cancer, we modeled gene expression using a mixture negative binomial GLM: ({Z}_{s,g}|{X}_{s}sim text{NB}left({mu }_{s,g},{gamma }_{g}right),)({mu }_{s,g}=sum _{t}{pi }_{t}exp ({X}_{s,{t}^{{prime} }}{beta }_{{t}^{{prime} },t}^{g}+log {L}_{s})). Here, ({Z}_{s,g}) is the count for gene g in spot s, ({pi }_{t}) is cell type deconvolution proportion, ({X}_{s,{t}^{{prime} }}) are the niche covariates as defined above and ({L}_{s}) is the library size of spot s. The parameters of interest are ({beta }_{{t}^{{prime} },t}^{g}), the gene-specific niche-effect of cell type t on niche ({t}^{{prime} }). We test the null hypothesis ({beta }_{{t}^{{prime} },t}^{g}=0) using Wald tests. If ({beta }_{{t}^{{prime} },t}^{g}ne 0), then the presence of niche ({t}^{{prime} }) influences the gene expression of gene g in cell type t.

Mouse kidney anatomical region annotation

In Visium HD, spatial transcriptomic datasets are often accompanied by high-resolution histology images, which encode meaningful low-dimensional histology features that can effectively reflect the anatomical structure. To leverage this, we used histology image features to annotate anatomical regions in the mouse kidney. Specifically, we applied ISTAR, a method that uses a pretrained self-supervised model, DINO, to hierarchically train vision transformer models on publicly available histology images from The Cancer Genome Atlas53. This approach captures histological characteristics at the 8 µm × 8 µm superpixel level and generates low-dimensional embeddings that represent both global and local tissue architectures53. In our analysis of the Visium HD mouse kidney dataset, we used the 8 µm × 8 µm resolution to match the superpixel granularity. We then clustered superpixels on the basis of their histology feature embeddings and mapped each spot to the nearest superpixel in spatial coordinates. The cluster label of the matched superpixel was assigned to the corresponding spot, generating spot-level clusters derived from histological features. Lastly, we manually annotated each cluster by referencing known anatomical regions of the mouse kidney29. This enabled us to define biologically meaningful regions including the cortex, outer stripe, inner stripe, inner medulla and papilla.

For the Xenium dataset, matched histology images were not available. Therefore, we annotated anatomical regions on the basis of the spatial distribution of region-specific cell types. For each cell, we computed the local neighborhood density of marker cell types using a spatial kernel. On the basis of established kidney anatomy and annotations from the original study54, we used the following cell type markers to define anatomical regions: S1 proximal tubule cells, which are exclusive to the cortex, principal cells, which are predominantly localized to the inner medulla, and thick ascending limb cells, which are enriched in the outer medulla. Each cell was assigned to the anatomical region corresponding to its highest marker cell type density. Our cell-type-based anatomical annotations were consistent with the region annotations reported in the original study54.

Computation of the mouse kidney osmolarity gradient

To model the corticomedullary osmolarity gradient in Visium HD data, we first identified boundary spots between anatomical regions. Boundary spots were defined on the basis of local region density; a spot was classified as a boundary spot if the proportion of neighboring spots belonging to each of two adjacent regions was approximately equal (that is, ~50% each). Specifically, papilla boundary spots were identified at the interface between the papilla and inner medulla regions, while cortex boundary spots were identified at the interface between the cortex and outer stripe regions.

For each spot i, we computed the osmolarity proxy Oi as the normalized distance along the corticomedullary axis:

$${O}_{i}=frac{dleft(i,text{cortex boundary}right)}{dleft(i,text{cortex boundary}right)+dleft(i,text{papilla boundary}right)}$$

(18)

where d(i, cortex boundary) denotes the Euclidean distance from spot i to the nearest cortex boundary spot and d(i, papilla boundary) denotes the distance to the nearest papilla boundary spot. This formulation yields ({O}_{i}in [0,1]), where values approaching 1 indicate proximity to the papilla (high osmolarity) and values approaching 0 indicate proximity to the cortex (low osmolarity), consistent with the physiological osmolality gradient of the mammalian kidney.

The Xenium kidney tissue section exhibited a radial anatomical organization, with the papilla located centrally and the cortex at the periphery. To construct an osmolarity proxy, we identified a reference cell located within the inner papilla region as the central anchor point. For each cell i, we computed the osmolarity proxy ({O}_{i}) on the basis of its radial position:

$${O}_{i}=1-frac{dleft(i,text{papilla center}right)}{R}$$

(19)

where d(i, papilla center) denotes the Euclidean distance from cell i to the papilla reference cell and (R) denotes the radius of the tissue section (that is, the maximum distance from the papilla center to the tissue boundary). This formulation yields ({O}_{i}in [0,1]), where values approaching 1 indicate proximity to the papilla center (high osmolarity) and values approaching 0 indicate proximity to the cortical periphery (low osmolarity).

Visium HD kidney SpotGLM model setup and analysis

To enable efficient analysis while preserving statistical power, we applied SPARROW to select 70,000 representative spots and subsequently fit SpotGLM to both the full and subsampled datasets. Analysis of the full data required approximately 5.7 days of computation and analysis of the subsampled data required approximately 18.7 h of computation. We modeled gene expression using a spot-level negative binomial GLM: ({Z}_{s,g}sim text{NB}left({mu }_{s,g},{gamma }_{g}right),,{mu }_{s,g}=sum _{t}{pi }_{s,t}exp ({X}_{s,text{pap}}{beta }_{t,,text{papilla}}^{g}+{X}_{s,text{cor}}{beta }_{t,,text{cortex}}^{g})(+{O}_{s}{beta }_{t,,text{osmolarity}}^{g}+log {L}_{s}).). Here, ({Z}_{s,g}) is the count for gene g in spot s, ({pi }_{s,t}) is the proportion of cell type t in spot s and corresponds to the ({C}_{s,t}) in the SpotGLM model, ({X}_{s}) is a one-hot-encoded matrix consisting of the region identity of each spot, ({O}_{s}) is the continuous osmolarity gradient at spot s and ({L}_{s}) is the library size of spot s. The parameters of interest are ({beta }_{t,,text{osmolarity}}^{g}), the gene-specific osmolarity-effect on cell type t. This model is also used to compare fitted coefficients of Xenium and Visium HD mouse kidney data. We test the null hypothesis using Wald tests ({H}_{0}:{beta }_{t,text{osmolarity}}^{g}=0.) If ({beta }_{t,text{osmolarity}}^{g}ne 0), then the osmolarity level influences the gene expression of gene g in cell type t.

Xenium kidney standard GLM model setup and analysis

As Xenium measures single cells and not mixtures of cells, we modeled gene expression using a standard negative binomial GLM: ({Y}_{c,g}|cin text{type}Tsim text{NB}left({mu }_{c,g},{gamma }_{g}right),,{mu }_{c,g}=exp ({X}_{c,text{pap}}{beta }_{T,,text{papilla}}^{g}+{X}_{c,text{cor}}{beta }_{T,,text{cortex}}^{g})(+{O}_{c}{beta }_{T,,text{osmolarity}}^{g}+log {L}_{c})). Here, ({Y}_{c,g}) is the count for gene g in cell c, ({X}_{c}) is a one-hot-encoded matrix consisting of the region identity of each cell, ({O}_{c}) is the continuous osmolarity gradient for cell c and ({L}_{c}) is the library size of cell c. The parameters of interest are ({beta }_{T,,text{osmolarity}}^{g}), the gene-specific osmolarity-effect on cell type T. We test the null hypothesis using Wald tests ({H}_{0}:{beta }_{T,text{osmolarity}}^{g}=0). If ({beta }_{T,text{osmolarity}}^{g}ne 0), then the osmolarity level influences the gene expression of gene g in a specific cell type T.

Spatial isoform switching analysis in mouse olfactory bulb

This dataset, generated and analyzed by Lebrigand et al.5, contains spatial long read of adult C57BL/6 mice olfactory bulbs aged over 2 months, includes 74 million long reads, filtered to retain only UMIs that fully span all exon–exon junctions for their mapped isoform. After filtering, 2.19 million UMIs with unambiguous transcript structure were retained, spanning 918 spatial spots, with a mean of 1,917 UMIs and a median of 974 isoforms per spot. In total, 23,560 Gencode reference isoforms from 13,291 genes were detected.

For gene g, assume for simplicity that there are two splice variants (isoform 1 versus isoform 2). Let the true relative proportion of isoform 1 in spot s be ({gamma }_{s}^{g}). This spot-level quantity ({gamma }_{s}^{g}) is a weighted average of the cell-specific isoform relative proportions across the cells that make up spot s, weighted by each cell’s total expression of gene g. Aggregating across cells in spot s of the same type, we have ({gamma }_{s,g}=frac{{sum }_{iin s}{gamma }_{i,g{mu }_{{T}_{i},g}}}{{sum }_{iin s}{mu }_{{T}_{i},g}}=frac{{sum }_{t}{gamma }_{t,g}{pi }_{s,t},{mu }_{t,g}}{{sum }_{t}{pi }_{s,t}{mu }_{t,g}}).

At the single-cell level, we use logistic regression to model the dependence of splicing (isoform 1 versus isoform 2) on the spatial niche X, which, for the mouse olfactory bulb data, is simply the one-hot-encoded region for each cell. We assume that this dependence is cell type specific. That is, we assume ({Y}_{i,g}sim text{Bin}left({n}_{i,g},{gamma }_{{T}_{i},g}right))(,,text{logit}left({gamma }_{{T}_{i},g}right)=X{beta }_{{T}_{i},g}), where ({Y}_{i,g}) represents the number of reads mapping to isoform 1 for gene g in cell i, ({n}_{i,g}) represents the total number of reads mapping to gene g, ({beta }_{t,g}) is a vector (({beta }_{t,g,r}:r=1,ldots ,R)), representing the increase in log odds of a read belonging to isoform 1, for type t cells if they lie in region r. The equivalent spot-level model is ({Y}_{s,g}sim text{Bin}({n}_{s,g},{p}_{s,g}),,{p}_{s,g}=sum _{t}{w}_{s,g,t}{text{Logit}}^{-1}({X}_{s}{beta }_{t,g}),,{w}_{s,g,t}=frac{{pi }_{s,t}{mu }_{g,t}}{{sum }_{{t}^{{prime} }}{pi }_{s,{t}^{{prime} }}{mu }_{g,{t}^{{prime} }}}), where ({Y}_{s,g}) is the count of isoform 1 of gene g in spot s, ({n}_{s,g}) is the total expression of gene g in spot s, ({pi }_{s,t}) is the deconvolution proportion of cell type t in spot s and ({mu }_{s,g,t}) is the expected expression of gene g in cell type t in spot s. ({mu }_{g,t}) is estimated by the model ({Y}_{s,g}sim text{Pois}left(sum _{t}{pi }_{s,t}{mu }_{g,t}right)), which is equivalent to a SpotGLM with the covariate being solely an intercept vector.

To detect cell-type-specific isoform switching between regions r and r′ in cell type t, we test the null hypothesis ({H}_{0}:{beta }_{t,g,r}={beta }_{t,g,{r}^{{prime} }}) using a Wald contrast test. Thus, for 11 cell types and five regions in the mouse olfactory bulb data, a maximum possible of (11times left(genfrac{}{}{0ex}{}{5}{2}right)=110) tests can be performed for each gene. For a region where the cell type t is not present or if the gene is adequately expressed in fewer than five spots, the test is not performed. A gene g is defined as being adequately expressed within a cell type t if the total estimated proportion of transcripts belonging to gene g in cell type t within spot s is greater than 1/50,000.

P22 mouse brain spatial ATAC-seq analysis

This dataset contains 9,215 spots of dimension 50 µm × 50 µm. Each spot was assigned to one of 14 annotated spatial domains on the basis of their spatial location. For each spot, peaks were called of length 50 bp. Then, peaks were aggregated either by gene or by TF motif. When aggregated by gene, 24,027 genes were represented. When aggregated by TF motif, 746 motifs were represented. We model the motif score for each region as ({Y}_{s,m}sim Nleft(sum _{t}{pi }_{s,t}{X}_{s}{beta }_{t},{sigma }_{m}^{2}right)), where ({pi }_{s,t}) is the deconvolution proportion of cell type t in spot s, ({X}_{s}) is the one-hot-encoded region membership for spot s, ({sigma }_{m}^{2}) is a motif specific variance and ({beta }_{t}) is the region coefficient vector for cell type t. The entry ({beta }_{t,r}) of the vector ({beta }_{t}) encodes the cell-type-specific enrichment of the given TF or gene for cells that reside in region r. To detect differential accessibility, we tested for region contrasts using a Wald contrast test,

$${H}_{0}:{beta}_{t,r,m}={beta}_{t,{r}^{{prime}}!,m},text{vs},{H}_{1}:{beta}_{t,r,m}ne {beta}_{t,{r}^{{prime}}!,m}$$

(20)

Motifs for which the test above is rejected can be said to be marker motifs for region r in cell type t.

Reporting summary

Further information on research design is available in the Nature Portfolio Reporting Summary linked to this article.