Spatial Transcriptomics Analysis Workflow: ATERA WTA FFPE breast cancer example#
Authors and Contributors: Sara Jimenez, Lukas Heumos, Severin Dicks
Tutorial notebook for the ATERA WTA FFPE breast cancer 10x image-based spatial transcriptomics dataset (170,057 cells × 18,028 genes, whole-transcriptome add-on panel), loaded as a SpatialData zarr store from the scverse example data.
Analysis outline:
Load the data
Preprocessing
1.1 QC
1.2 normalizationBuild the spatial graph
Cell type annotation
Spatial structure —
4.1 spatially aware clustering (niches)
4.2 niche characterization
4.3 co-occurrence / neighborhood enrichment / ligand-receptor signalingSpatially variable genes & gene-level tasks
import warnings
warnings.filterwarnings("ignore")
import os
import zipfile
from pathlib import Path
import time
import numpy as np
import cupy as cp
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import anndata as ad
import scanpy as sc
import squidpy as sq
import rapids_singlecell as rsc
import spatialdata as sd
import omnipath as op
sns.set_style("whitegrid")
plt.rcParams["figure.dpi"] = 110
RANDOM_STATE = 0
0. Load the Atera dataset#
Everything downstream in this tutorial starts here.
We download
atera_breast_cancer.zarr.zipfrom the scverse example data server (see00_DO_FIRST.ipynbfor the other datasets), unzip it, and load it withspatialdata.read_zarr.The resulting
SpatialDataobject holds the morphology image, cell boundary shapes, and the cell x gene expression table in one coordinate system, so it can also drive zoomed-region figures. This tutorial works at the cell-table level, not the transcript/pixel level.
notebook_start = time.time()
DATA_DIR = Path("./zarr")
DATA_DIR.mkdir(exist_ok=True)
zip_path = DATA_DIR / "atera_breast_cancer.zarr.zip"
zarr_path = DATA_DIR / "atera_breast_cancer.zarr"
if not zarr_path.exists():
if not zip_path.exists():
os.system(
f"wget -O {zip_path} "
"https://exampledata.scverse.org/rapids-singlecell/atera_breast_cancer.zarr.zip"
)
with zipfile.ZipFile(zip_path) as zf:
zf.extractall(DATA_DIR)
zip_path.unlink() # the zip is large and no longer needed once extracted
sdata = sd.read_zarr(zarr_path)
sdata
SpatialData object, with associated Zarr store: /home/sdicks/git/rapids-singlecell-tutorials/zarr/atera_breast_cancer.zarr
├── Images
│ └── 'morphology_focus': DataTree[cyx] (4, 28048, 46543), (4, 14024, 23271), (4, 7012, 11635), (4, 3506, 5817), (4, 1753, 2908)
├── Shapes
│ └── 'cell_boundaries': GeoDataFrame shape: (170057, 1) (2D shapes)
└── Tables
└── 'table': AnnData (170057, 18028)
with coordinate systems:
▸ 'global', with elements:
morphology_focus (Images), cell_boundaries (Shapes)
Prepare AnnData from SpatialData object#
spatialdata-plot needs the table to annotate the shapes element it will be rendered against.
By default the table’s region metadata points at the label image we didn’t load (
cells_labels), so we repoint it at the cell-boundary polygons we did load (cell_boundaries).Move the AnnData object to GPU.
table = sdata.tables["table"]
table.obs["region"] = pd.Categorical(["cell_boundaries"] * table.n_obs)
sdata.set_table_annotates_spatialelement(
"table", region="cell_boundaries", region_key="region", instance_key="cell_id"
)
adata = sdata.tables["table"].copy()
adata.var_names_make_unique()
adata.layers["counts"] = adata.X.copy() # keep raw counts around explicitly
rsc.get.anndata_to_GPU(adata, convert_all=True)
adata
AnnData object with n_obs × n_vars = 170057 × 18028
obs: 'cell_id', 'transcript_counts', 'control_probe_counts', 'genomic_control_counts', 'control_codeword_counts', 'unassigned_codeword_counts', 'deprecated_codeword_counts', 'total_counts', 'cell_area', 'nucleus_area', 'nucleus_count', 'segmentation_method', 'region', 'z_level'
var: 'gene_ids', 'feature_types', 'genome'
uns: 'spatialdata_attrs'
obsm: 'spatial'
layers: None (.X), 'counts'
1. Preprocessing#
1.1 Quality control#
We compute standard QC metrics with rsc.pp.calculate_qc_metrics
(GPU) and use percentile-based thresholds as an illustrative starting
point.
rsc.pp.calculate_qc_metrics(
adata,
expr_type="counts",
var_type="genes",
log1p=True
)
fig, axes = plt.subplots(1, 2, figsize=(15, 4))
sns.histplot(adata.obs["total_counts"], bins=100, ax=axes[0])
axes[0].set_title("total_counts (pre-filter)")
sns.histplot(adata.obs["n_genes_by_counts"], bins=100, ax=axes[1])
axes[1].set_title("n_genes_by_counts (pre-filter)")
fig.tight_layout()
# Drop failed segmentations: empty cells and anucleate fragments.
keep = (adata.obs["total_counts"] >= 10) & (adata.obs["nucleus_count"] >= 1)
adata = adata[keep].copy()
rsc.pp.filter_genes(adata, min_cells=3)
1.2 Normalization and dimensionality reduction#
We use the standard scanpy-style size-factor normalization; used as the single normalized layer (
lognorm) for everything downstream.We choose 2000 HVG and 50 PCs.
rsc.pp.normalize_total(adata)
rsc.pp.log1p(adata)
adata.layers["lognorm"] = adata.X.copy()
rsc.pp.highly_variable_genes(
adata,
n_top_genes=2000,
flavor="seurat_v3",
layer="counts"
)
rsc.pp.pca(
adata,
n_comps=50,
mask_var="highly_variable",
random_state=RANDOM_STATE
)
2. Build spatial graph#
We build the spatial neighborhood graph by Delaunay triangulation with
rsc.gr.spatial_neighbors_delaunay. Triangulation on its own connects
cells across tissue gaps and around the convex hull, producing edges far
longer than any real cell-cell contact, so percentile=99 prunes the
longest 1% of edges.
%%time
rsc.gr.spatial_neighbors_delaunay(adata, percentile=99)
CPU times: user 87.1 ms, sys: 43.2 ms, total: 130 ms
Wall time: 132 ms
3. Cell type annotation#
No reference atlas is wired up in this tutorial, so we use a
marker-gene-set scoring approach via rsc.dcg.ulm
(decoupler_gpu’s univariate linear model.
Scores are averaged within each unsupervised leiden cluster and the label is assigned by argmax on the cluster means. Averaging over a cluster is far more robust than scoring each cell independently.
Marker panel
Tumor substates reported for this dataset in Janesick et al 2026, AACR poster for the 10x introduction of the Atera technology (breast-cancer section).
CELL_TYPE_MARKERS: dict[str, list[str]] = {
# -- tumour epithelium (Janesick et al. AACR 2026 poster) --
"Invasive_Tumor": ["CCND1", "MYEOV", "TPCN2", "LTO1", "SMIM38", "FGF19", "FGF4", "FADD", "CTTN"], # 11q13, Fig. 9C
"Invasive_Tumor_G1S": ["PCNA", "MCM2", "MCM5", "TYMS", "FEN1", "GINS2"], # S-phase, Fig. 8
"Invasive_Tumor_Mitotic": ["C21orf58", "ESPL1", "MELK", "NCAPG2", "TOP2A", "CENPF"], # Fig. 8 + G2/M
"DCIS_Basal_like": ["KIT", "PROM1", "GABRP", "SYNM", "CCL28"], # Fig. 7A
"DCIS_Luminal_like": ["ANKRD30A", "ESR1", "NIBAN1", "BMPR1B", "SEC23B", "SLC24A3", "BARX2", "TSKU"], # Fig. 7B
"Apocrine": ["PIP", "AR", "HPGD", "ACSM1"], # PIP per Fig. 6
"Myoepithelial": ["TP63", "OXTR", "KRT14", "KRT17", "KRT5", "ACTA2", "MYLK"], # epithelial + contractile
# -- stroma / vasculature --
"CAF_Neoplastic": ["PDGFRA", "DCN", "LUM", "COL1A2", "CFD", "C7"], # pan-CAF + non-activated
"CAF_Invasive": ["COL11A1", "COL10A1", "MMP11", "INHBA", "THBS2", "CTHRC1"], # invasion-associated stroma
"CXCL14_pos": ["CXCL14"], # only marker given in Fig. 6
"Pericyte": ["RGS5", "NOTCH3", "KCNJ8", "HIGD1B", "ABCC9"], # PDGFRB dropped (CAFs)
"Endothelial": ["PECAM1", "VWF", "CDH5", "CLDN5", "EMCN", "PLVAP"],
# -- immune --
"T_Cell": ["CD3D", "CD3E", "CD3G", "CD2", "CD247", "CD6"], # CD4 / IL7R dropped
"B_Cell": ["MS4A1", "CD19", "PAX5", "BANK1", "BLK", "FCRL1"], # Fig. 4B genes; CD79A/B dropped
"Plasma_Cell": ["MZB1", "JCHAIN", "TNFRSF17", "DERL3"], # non-Ig -> less spill-over
"Macrophage": ["CD68", "CD163", "C1QA", "C1QB", "C1QC", "MS4A7"],
"Dendritic_Cell": ["FLT3", "CLEC9A", "XCR1", "CD1C", "CLEC10A", "LAMP3"],
# -- not labelled in Fig. 6: candidates for its 2 small unlabelled clusters --
"Lymphatic_Endothelial": ["PROX1", "CCL21", "MMRN1", "FLT4", "LYVE1"], # PDPN dropped
"Mast_Cell": ["TPSAB1", "TPSB2", "CPA3", "MS4A2", "HDC"], # KIT left to DCIS_Basal_like
}
celltype_net = (
pd.Series(CELL_TYPE_MARKERS).explode().rename_axis("source").reset_index(name="target")
)
celltype_net.groupby("source").size()
source
Apocrine 4
B_Cell 6
CAF_Invasive 6
CAF_Neoplastic 6
CXCL14_pos 1
DCIS_Basal_like 5
DCIS_Luminal_like 8
Dendritic_Cell 6
Endothelial 6
Invasive_Tumor 9
Invasive_Tumor_G1S 6
Invasive_Tumor_Mitotic 6
Lymphatic_Endothelial 5
Macrophage 6
Mast_Cell 5
Myoepithelial 7
Pericyte 5
Plasma_Cell 4
T_Cell 6
dtype: int64
adata.X = adata.layers["lognorm"]
rsc.dcg.ulm(adata, celltype_net, layer="lognorm", tmin=2)
adata.obsm["score_celltype"] = adata.obsm.pop("score_ulm")
adata.obsm.pop("padj_ulm", None)
score_ct = adata.obsm["score_celltype"]
rsc.pp.neighbors(adata, n_neighbors=15, use_rep="X_pca", random_state=RANDOM_STATE)
rsc.tl.leiden(adata, resolution=1.0, key_added="leiden_expr", random_state=RANDOM_STATE)
rsc.tl.umap(adata, random_state=RANDOM_STATE)
# Robust label: mean decoupler score per expression cluster
cluster_mean_score = score_ct.groupby(adata.obs["leiden_expr"].values).mean()
cluster_to_celltype = cluster_mean_score.idxmax(axis=1)
adata.obs["cell_type"] = (
adata.obs["leiden_expr"].map(cluster_to_celltype).astype("category")
)
adata.obs["cell_type"].value_counts()
cell_type
Invasive_Tumor 77509
CAF_Neoplastic 30038
DCIS_Luminal_like 12464
Endothelial 10203
T_Cell 9786
Macrophage 7526
Myoepithelial 7181
Pericyte 5352
DCIS_Basal_like 5246
Plasma_Cell 1278
Mast_Cell 664
Lymphatic_Endothelial 476
Apocrine 415
Invasive_Tumor_Mitotic 165
Name: count, dtype: int64
fig, axes = plt.subplots(1, 2, figsize=(13, 5.5))
sc.pl.umap(adata, color="leiden_expr", ax=axes[0], show=False, legend_loc="on data", title="Leiden (expression)")
sc.pl.umap(adata, color="cell_type", ax=axes[1], show=False, title="Cell type (cluster-level argmax)")
<Axes: title={'center': 'Cell type (cluster-level argmax)'}, xlabel='UMAP1', ylabel='UMAP2'>
# Categorical spatial layout via squidpy
sq.pl.spatial_scatter(
adata, color="cell_type", shape=None, img=False,
palette="tab20", size=1.5, figsize=(7, 6),
)
WARNING: Please specify a valid `library_id` or set it permanently in `adata.uns['spatial']`
4. Identifying spatial structure#
4.1 Spatially aware clustering (spatial domains / niches)#
rsc.gr.calculate_niche_cellcharter builds the CellCharter feature matrix
concatenating expression with its mean over the 1-, 2- and 3-hop shells of
the spatial graph, then PCA-reduces it and fits a Gaussian mixture.
Aggregation in PCA space, not raw expression. With 18,028 genes and
distance=3, the default feature matrix is 72,112 columns wide, and each shell productÂₖ @ Xis a sparse × sparse multiply that fails on this dataset withCUSPARSE_STATUS_INSUFFICIENT_RESOURCES. We instead aggregate the dense 50-componentX_pca, which makes every shell product a cheap sparse × dense matmul and matches the original CellCharter paper, which also aggregates in PCA space rather than over raw counts.Choosing
k.n_componentsis fixed per run, we use k=9, fine enough to separate tumor, stromal and immune sub-niches while staying interpretable, and in the same range as the ~10 spatial clusters reported for this dataset in Janesick et al 2026, AACR neighborhood analysis.
%%time
niche_ad = ad.AnnData(
X=rsc.get.X_to_CPU(adata.obsm["X_pca"]),
obs=pd.DataFrame(index=adata.obs_names),
)
niche_ad.obsp["spatial_connectivities"] = adata.obsp["spatial_connectivities"]
rsc.gr.calculate_niche_cellcharter(niche_ad, n_components=9, random_state=RANDOM_STATE)
adata.obs["cellcharter_niche"] = niche_ad.obs["cellcharter_niche"].astype("category").values
adata.obs["cellcharter_niche"].value_counts()
CPU times: user 98.5 ms, sys: 28.6 ms, total: 127 ms
Wall time: 141 ms
cellcharter_niche
0 28669
4 28335
8 19833
5 19344
2 17716
6 17248
3 14084
7 12799
1 10275
Name: count, dtype: int64
sq.pl.spatial_scatter(
adata,
library_id='region',
color="cellcharter_niche",
shape=None,
img=False,
size=1
)
4.2 Niche characterization#
Characterize the spatial domains from 4.1 two ways:
Composition — cell-type mixture per niche (from Section 3 labels).
Function — mean PROGENy footprint score per niche, via
rsc.dcg.ulm. PROGENy is retrieved fromOmniPath, and its 14 pathways carry signed, fitted weights per gene, so a score reflects how far a cell’s expression departs from the pathway footprint in both directions.
composition = (
pd.crosstab(adata.obs["cellcharter_niche"], adata.obs["cell_type"], normalize="index") * 100
)
fig, ax = plt.subplots(figsize=(10, 5))
composition.plot(kind="bar", stacked=True, ax=ax)
ax.set_ylabel("% of cells in niche")
ax.set_title(f"Cell-type composition per spatial domain")
ax.legend(bbox_to_anchor=(1.02, 1), loc="upper left", fontsize=7)
fig.tight_layout()
composition.round(1)
| cell_type | Apocrine | CAF_Neoplastic | DCIS_Basal_like | DCIS_Luminal_like | Endothelial | Invasive_Tumor | Invasive_Tumor_Mitotic | Lymphatic_Endothelial | Macrophage | Mast_Cell | Myoepithelial | Pericyte | Plasma_Cell | T_Cell |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| cellcharter_niche | ||||||||||||||
| 0 | 0.0 | 67.7 | 0.0 | 0.0 | 15.7 | 3.2 | 0.0 | 1.5 | 0.1 | 0.1 | 0.1 | 11.5 | 0.0 | 0.2 |
| 1 | 0.0 | 4.3 | 3.7 | 0.5 | 0.6 | 55.3 | 1.6 | 0.0 | 20.0 | 0.5 | 4.3 | 0.2 | 0.0 | 9.2 |
| 2 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 99.9 | 0.0 | 0.0 | 0.1 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 3 | 2.9 | 0.0 | 9.2 | 40.7 | 0.0 | 1.2 | 0.0 | 0.0 | 0.0 | 0.0 | 45.9 | 0.0 | 0.0 | 0.0 |
| 4 | 0.0 | 0.0 | 0.1 | 0.0 | 0.0 | 99.9 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 5 | 0.0 | 51.3 | 0.0 | 0.1 | 29.2 | 6.5 | 0.0 | 0.2 | 0.5 | 0.2 | 1.2 | 10.6 | 0.1 | 0.3 |
| 6 | 0.0 | 1.6 | 0.0 | 0.0 | 0.0 | 6.6 | 0.0 | 0.0 | 30.8 | 3.2 | 0.0 | 0.0 | 7.3 | 50.5 |
| 7 | 0.0 | 0.0 | 27.6 | 52.1 | 0.0 | 19.9 | 0.0 | 0.0 | 0.3 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 8 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 99.9 | 0.0 | 0.0 | 0.0 | 0.0 | 0.1 | 0.0 | 0.0 | 0.0 |
# PROGENy pathway footprints, retrieved from OmniPath. Weights are signed, which is
# what ulm expects; the curated lists this replaces were effectively unweighted.
N_PROGENY_GENES = 500
progeny_net = (
op.requests.Annotations.get(resources="PROGENy")
.pivot(index=["record_id", "genesymbol"], columns="label", values="value")
.reset_index()
.rename(columns={"pathway": "source", "genesymbol": "target"})
.astype({"weight": float, "p_value": float})
.sort_values("p_value")
.drop_duplicates(subset=["source", "target"])
.groupby("source")
.head(N_PROGENY_GENES)[["source", "target", "weight"]]
.reset_index(drop=True)
)
rsc.dcg.ulm(adata, progeny_net, layer="lognorm")
adata.obsm["score_pathway"] = adata.obsm.pop("score_ulm")
adata.obsm.pop("padj_ulm", None)
score_pw = adata.obsm["score_pathway"]
niche_pathway = score_pw.groupby(adata.obs["cellcharter_niche"].values).mean()
fig, ax = plt.subplots(figsize=(12, 5))
sns.heatmap(niche_pathway, cmap="vlag", center=0, annot=True, fmt=".1f", ax=ax)
ax.set_title("Mean PROGENy pathway activity per spatial domain")
fig.tight_layout()
4.3 Spatial structure metrics:#
co-occurrence, neighborhood enrichment, ligand-receptor signaling
Three classic squidpy-style analyses, complementary to the niches above (which summarize local neighborhoods; these instead summarize pairwise spatial relationships between cell types):
rsc.gr.co_occurrence— GPU. For each cell-type pair, how does the probability of finding the second type change with distance from the first? We highlight the hypoxic-tumor state against immune/stromal types.squidpy.gr.nhood_enrichment— CPU (norsc.grequivalent yet). Permutation test for whether cell-type pairs are spatial neighbors more/less often than chance, summarized as a z-score matrix.rsc.gr.ligrec— GPU. Squidpy-style permutation test for ligand–receptor pairs enriched between cluster pairs. We retrieved LR ineraction netwrok fromomnipath– ~11k pairs, restricted to those whose partners are all on the panel — because on GPU the full screen costs seconds, filtering happens only at the plotting step: a dotplot of ~10k rows is unreadable, so we show the interactions significant across the most cluster pairs.
%%time
rsc.gr.co_occurrence(
adata,
cluster_key="cell_type",
interval=np.linspace(0, 250, 26),
multi_gpu=False,
)
sq.pl.co_occurrence(
adata,
cluster_key="cell_type",
clusters="Invasive_Tumor",
figsize=(7, 5),
)
CPU times: user 102 ms, sys: 4.95 ms, total: 107 ms
Wall time: 106 ms
rsc.gr.nhood_enrichment(adata, cluster_key="cell_type", n_perms=500, seed=RANDOM_STATE)
sq.pl.nhood_enrichment(adata, cluster_key="cell_type", figsize=(8, 7))
interactions = rsc.squidpy_gpu._ligrec._get_interactions()
%%time
lr_genes = (
interactions[["source", "target"]]
.stack()
.astype(str)
.str.split("_")
.explode()
.unique()
)
lr_genes = adata.var_names[adata.var_names.isin(lr_genes)]
adata_lr = adata[:, lr_genes].copy()
adata_lr.X = adata_lr.layers["lognorm"]
adata_lr.obs["cell_type"] = adata_lr.obs["cell_type"].cat.remove_unused_categories()
rsc.get.anndata_to_CPU(adata_lr, convert_all=True) # ligrec's setup is host-side pandas; it moves the matrix to GPU itself
cp.random.seed(RANDOM_STATE) # rsc.gr.ligrec takes no seed argument
ligrec_res = rsc.gr.ligrec(
adata_lr,
n_perms=1000,
interactions=interactions,
cluster_key="cell_type",
copy=True,
use_raw=False,
corr_method="fdr_bh",
)
del adata_lr
CPU times: user 2.42 s, sys: 300 ms, total: 2.72 s
Wall time: 2.74 s
lr_clusters = [
"Invasive_Tumor", "DCIS_Basal_like", "T_Cell",
"Macrophage", "CAF_Neoplastic", "Endothelial",
]
ALPHA, TOP_N, MIN_SIG = 0.01, 10, 5
pv, mu = ligrec_res["pvalues"], ligrec_res["means"]
# Rank only over the cluster pairs that will actually be drawn.
cols = [c for c in pv.columns if c[0] in lr_clusters and c[1] in lr_clusters]
# Densify first: boolean reductions on sparse frames are not reliable across pandas versions.
pv_d, mu_d = pv[cols].sparse.to_dense(), mu[cols].sparse.to_dense()
sig = pv_d <= ALPHA
rank = pd.DataFrame({
"n_sig": sig.sum(axis=1),
"max_mean": mu_d.where(sig).max(axis=1),
})
# Keep interactions significant in at least MIN_SIG cluster pairs, then rank by
# their strongest significant mean expression.
top = (
rank[rank["n_sig"] >= MIN_SIG]
.sort_values("max_mean", ascending=False)
.head(TOP_N)
.index
)
ligrec_top = {k: df.loc[top] for k, df in ligrec_res.items()}
sq.pl.ligrec(
ligrec_top,
source_groups=lr_clusters,
target_groups=lr_clusters,
alpha=ALPHA,
pvalue_threshold=ALPHA,
title="Top ligand-receptor interactions across cell-type pairs",
figsize=(0.7 * len(lr_clusters) + 4, 4),
)
5. Spatially variable genes & gene-level tasks#
Spatially variable gene (SVG) detection via Moran’s I,
rsc.gr.spatial_autocorr(..., mode="moran") — the GPU-accelerated
drop-in for squidpy.gr.spatial_autocorr.
%%time
moran_df = rsc.gr.spatial_autocorr(adata, mode="moran", layer="lognorm", copy=True)
moran_df = moran_df.sort_values("I", ascending=False)
moran_df.head(10)
CPU times: user 50 ms, sys: 3 ms, total: 53 ms
Wall time: 52.6 ms
| I | pval_norm | var_norm | pval_norm_fdr_bh | |
|---|---|---|---|---|
| CCND1 | 0.729848 | 0.0 | 0.000002 | 0.0 |
| ELAPOR1 | 0.686595 | 0.0 | 0.000002 | 0.0 |
| TAT | 0.644998 | 0.0 | 0.000002 | 0.0 |
| MSMB | 0.635659 | 0.0 | 0.000002 | 0.0 |
| TFF1 | 0.608555 | 0.0 | 0.000002 | 0.0 |
| TFF3 | 0.607828 | 0.0 | 0.000002 | 0.0 |
| PLAT | 0.594066 | 0.0 | 0.000002 | 0.0 |
| STC2 | 0.593283 | 0.0 | 0.000002 | 0.0 |
| AGR3 | 0.580912 | 0.0 | 0.000002 | 0.0 |
| PRPF19 | 0.580699 | 0.0 | 0.000002 | 0.0 |
%%time
top_svgs = moran_df.index[:6].tolist()
# squidpy plotting is CPU/matplotlib-based and can't read CuPy-backed
# layers directly, so pull this AnnData back to host once before plotting
rsc.get.anndata_to_CPU(adata, convert_all=True)
titles = {g: f"{g} (Moran's I={moran_df.loc[g, 'I']:.2f})" for g in top_svgs}
axes = sq.pl.spatial_scatter(
adata,
library_id='region',
color=top_svgs,
layer="lognorm",
shape=None,
img=False,
cmap="viridis",
size=1.5,
ncols=3,
figsize=(15, 9),
return_ax=True,
)
for ax, gene in zip(np.atleast_1d(axes), top_svgs):
ax.set_title(titles[gene])
CPU times: user 1.24 s, sys: 265 ms, total: 1.5 s
Wall time: 1.48 s
CCND1 is the most spatially variable gene (Moran’s I = 0.73). Expression is highest in the large invasive nests (centre/right) and low in the in-situ ducts on the left and in stroma. This matches the 11q13 (CCND1) gain restricted to invasive cells in Janesick et al., AACR 2026.
print("Total Processing time: %s" % (time.time() - notebook_start))
Total Processing time: 39.16972494125366