Below is an end‑to‑end “hello‑world” style workflow that starts from the standard SAW (Spatial Analysis Workflow) outputs and ends with an interactive spatial UMAP that you can view either in a notebook or inside STOmics’ GUI tools.
Everything is done with STOmics‑maintained packages so that versions, data structures and plotting defaults stay consistent. Feel free to copy–paste the code blocks into a Jupyter notebook or an interactive Python shell (≥ 3.8).
1. What you should already have from SAW
After running SAW in --bin 1 or --bin 50 (etc.) mode you normally get something like:
<your_project>/
├── bin1/
│ ├── cell_bin_gene.h5ad # expression matrix (AnnData)
│ ├── tissue_cut.tiff # optional, tissue mask
│ ├── QC.txt # basic QC stats
│ └── ... # other SAW intermediates
└── fig/ # quick‑QC images
The only file we need for a UMAP is cell_bin_gene.h5ad.
Everything else (mask, HE image, etc.) can be added later for nicer plots but is not required.
2. Set up a fresh conda / virtualenv (recommended)
# 1) create env
conda create -n stereo_umap python=3.9 -y
conda activate stereo_umap
# 2) core STOmics packages
pip install stereopy[scanpy] # installs stereopy + scanpy & plotting deps
# optional but handy
pip install squidpy # neighbours & image tools
pip install notebook # if you like Jupyter
Check versions (July 2024):
import stereopy, scanpy as sc, anndata, umap
print(stereopy.__version__) # e.g. '0.9.5'
print(sc.__version__) # ≥1.9
3. Load the SAW output
import stereopy as st
# path to *bin1* or whichever resolution you prefer
adata_path = "/path/to/bin1/cell_bin_gene.h5ad"
# StereoExpData wraps AnnData and adds spatial helpers
sdata = st.io.read_adata(adata_path)
# Peek
print(sdata) # <StereoExpData: n_obs × n_vars = 85 000 × 25 630>
sdata.obs.head()
The spatial coordinates (x, y) are already stored in sdata.obsm['spatial'] by SAW.
4. Minimal preprocessing
If you already applied SAW’s built‑in filters you can skip heavy QC, but three lightweight steps are generally useful:
# Keep SAW's default QC but confirm #genes per spot >200 (example)
st.pp.filter_cells(sdata, min_genes=200)
# 1) Normalise each bin to 10 000 counts, then log1p
st.pp.normalize_total(sdata, target_sum=1e4)
st.pp.log1p(sdata)
# 2) Highly variable genes (HVG) – 2 000 is standard
st.pp.highly_variable_genes(sdata, n_top_genes=2000, flavor="seurat_v3")
sdata = sdata[:, sdata.var['highly_variable']]
# 3) Scale and regress out n_counts if desired
st.pp.scale(sdata, max_value=10)
5. Dimensionality reduction & neighbours
st.tl.pca(sdata, n_comps=50, svd_solver='arpack')
st.pp.neighbors(sdata, n_neighbors=15, n_pcs=30) # builds kNN graph
6. Generate the UMAP
st.tl.umap(sdata, min_dist=0.3, spread=1.0)
Resulting coordinates live in sdata.obsm['X_umap'].
7. Visualise
7.1 Classical gene‑expression UMAP
import matplotlib.pyplot as plt
st.pl.umap(
sdata,
color=["total_counts", "n_genes"], # or cluster labels later
wspace=0.4
)
7.2 “Spatial UMAP” overlay on tissue
Strictly speaking a UMAP is already 2‑D, but the “spatial UMAP” phrase is often used to mean:
a) plot the UMAP embedding while colouring each dot by its x, y location,
b) or plot physical spots and colour them by their UMAP cluster assignment.
Here’s option (b):
# First cluster so the spatial view has discrete colours
st.tl.leiden(sdata, resolution=0.5, key_added='leiden_0.5')
# Physical space plot (image behind optional)
st.pl.spatial_scatter(
sdata,
color='leiden_0.5',
spot_size=20,
img_key='hires' # only if you have an HE/tissue image loaded
)
And the more literal “colour UMAP by x coordinate”:
import numpy as np
sdata.obs['x_coord'] = sdata.obsm['spatial'][:,0]
st.pl.umap(sdata, color='x_coord', cmap='viridis')
8. Make it interactive with STOmics stViewer
- Export the processed AnnData:
sdata.write_h5ad("bin1_processed_umap.h5ad", compression="gzip")
- Open
stViewer → “Load project” → point to the folder containing:
bin1_processed_umap.h5ad
- the SAW generated
tissue_cut.tiff (optional)
- Choose “UMAP” from the dimensionality‑reduction panel; clusters & gene overlays are clickable.
9. A few common extensions
• Spatially‑aware UMAP
– Instead of using plain expression distances, build a joint neighbour graph that mixes expression with physical adjacency:
import squidpy as sq
sq.gr.spatial_neighbors(sdata, coord_type='grid') # or 'generic'
sq.gr.spatial_autocorr(sdata, mode='ripley') # QC
# combine with expression neighbours
sq.gr.nhood_graph(sdata) # saves to .obsp
st.tl.umap(sdata, neighbors_key="spatial_nhood") # new embedding
• Use Harmony or Scanorama before UMAP when integrating multiple chips or batches.
• Save the UMAP as a high‑res figure:
fig = st.pl.umap(sdata, color='leiden_0.5', return_fig=True)
fig.savefig("umap_leiden.png", dpi=300, bbox_inches='tight')
10. Troubleshooting cheat‑sheet
| Issue | Quick fix |
|---|
KeyError: 'spatial' when plotting | SAW version < v1.3 didn’t write coordinates to obsm. Re‑export with --add.coordinates or load from bin?coords.tsv. |
| UMAP looks “cloudy” / no clusters | Increase min_genes filter; raise n_neighbors (30–50) or decrease min_dist (0.1). |
| Memory crash | Downsample bins (--bin 10) or subset genes to top 1 000 HVGs first. |
| stViewer doesn’t recognise .h5ad | Make sure the file ends with .h5ad exactly and is in the same folder as the tissue_cut.tiff (or edit the JSON in the GUI to find the image). |
🎉 That’s it — you now have a reproducible STOmics‑native pipeline from SAW output to a spatially contextual UMAP.
Experiment with resolutions, clustering parameters, and Squidpy’s spatial statistics to squeeze out maximal biological insight. Happy mapping!