Single-cell workflow on a real AnnData object#
This notebook runs a practical single-cell workflow on data/kang.h5ad: preprocessing, Leiden clustering, marker visualization, gene-set scoring, pseudobulk DESeq2, and the main sctk.pl plotting helpers.
from __future__ import annotations
import os
import time
from pathlib import Path
os.environ.setdefault("NUMBA_CACHE_DIR", "/tmp/sctk_numba_cache")
os.environ.setdefault("MPLCONFIGDIR", "/tmp/sctk_mpl_config")
os.environ.setdefault("XDG_CACHE_HOME", "/tmp/sctk_xdg_cache")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scanpy as sc
import sctk
plt.rcParams["figure.constrained_layout.use"] = False
Load data#
The data file is local and ignored by git. The notebook creates a temporary counts layer from adata.X.
data_path = Path("data/kang.h5ad")
if not data_path.exists():
data_path = Path("../data/kang.h5ad")
adata = sc.read_h5ad(data_path)
adata.layers["counts"] = adata.X.copy()
adata
AnnData object with n_obs × n_vars = 24673 × 15706
obs: 'label', 'cluster', 'cell_type', 'replicate'
var: 'name'
layers: 'counts'
adata.obs
| label | cluster | cell_type | replicate | |
|---|---|---|---|---|
| index | ||||
| AAACATACATTTCC-1 | ctrl | 9 | CD14+ Monocytes | patient_1016 |
| AAACATACCAGAAA-1 | ctrl | 9 | CD14+ Monocytes | patient_1256 |
| AAACATACCATGCA-1 | ctrl | 3 | CD4 T cells | patient_1488 |
| AAACATACCTCGCT-1 | ctrl | 9 | CD14+ Monocytes | patient_1256 |
| AAACATACCTGGTA-1 | ctrl | 4 | Dendritic cells | patient_1039 |
| ... | ... | ... | ... | ... |
| TTTGCATGCCTGAA-2 | stim | 6 | CD4 T cells | patient_1244 |
| TTTGCATGCCTGTC-2 | stim | 4 | B cells | patient_1256 |
| TTTGCATGCTAAGC-2 | stim | 6 | CD4 T cells | patient_107 |
| TTTGCATGGGACGA-2 | stim | 6 | CD4 T cells | patient_1488 |
| TTTGCATGTCTTAC-2 | stim | 5 | CD4 T cells | patient_1016 |
24673 rows × 4 columns
adata.X.max()
np.float32(3828.0)
Preprocess and cluster#
sctk.pp.calculate_qc_metrics(
adata,
layer="counts",
species="human",
)
sc.pl.violin(
adata,
keys=['total_counts', 'n_genes_by_counts', 'pct_counts_mt'],
stripplot=False, multi_panel=True)
sc.pl.scatter(adata, "total_counts", "n_genes_by_counts", color="pct_counts_mt")
sctk.pp.normalize_layer(
adata,
layer='counts',
target_sum=1e4,
log_base=10,
overwrite_x='norm_layer',
)
print(f"Max value in adata.X: {adata.X.max()}")
print(f"Max value in adata.layers['log1p_norm']: {adata.layers['log1p_norm'].max()}")
print(f"Max value in adata.layers['counts']: {adata.layers['counts'].max()}")
Max value in adata.X: 3.9370694160461426
Max value in adata.layers['log1p_norm']: 3.9370694160461426
Max value in adata.layers['counts']: 3828.0
sc.pp.highly_variable_genes(
adata,
layer='counts',
flavor='seurat_v3',
n_top_genes=3000,
# batch_key=batch_key,
subset=False,
)
ad = adata.copy()
sc.tl.pca(adata, use_highly_variable=True, svd_solver="arpack")
/home/mowp/mambaforge/envs/sctk/lib/python3.11/site-packages/scanpy/preprocessing/_pca/__init__.py:226: FutureWarning: Argument `use_highly_variable` is deprecated, consider using the mask argument. Use_highly_variable=True can be called through mask_var="highly_variable". Use_highly_variable=False can be called through mask_var=None
mask_var_param, mask_var = _handle_mask_var(
adata.obsm["X_pca"].shape
(24673, 50)
import scanpy.external as sce
adata.obs["replicate"].value_counts()
replicate
patient_1015 5090
patient_1488 4580
patient_1256 4134
patient_1016 3358
patient_1244 3343
patient_101 2024
patient_1039 1102
patient_107 1042
Name: count, dtype: int64
sctk.pp.harmony_integrate(
adata,
key="replicate",
)
2026-06-07 12:58:18,912 - harmonypy - INFO - Running Harmony
2026-06-07 12:58:18,913 - harmonypy - INFO - Parameters:
2026-06-07 12:58:18,913 - harmonypy - INFO - max_iter_harmony: 10
2026-06-07 12:58:18,914 - harmonypy - INFO - max_iter_kmeans: 4
2026-06-07 12:58:18,915 - harmonypy - INFO - epsilon_cluster: 0.001
2026-06-07 12:58:18,915 - harmonypy - INFO - epsilon_harmony: 0.01
2026-06-07 12:58:18,916 - harmonypy - INFO - nclust: 100
2026-06-07 12:58:18,917 - harmonypy - INFO - block_size: 0.05
2026-06-07 12:58:18,918 - harmonypy - INFO - lamb: dynamic (alpha=0.2)
2026-06-07 12:58:18,918 - harmonypy - INFO - theta: [2. 2. 2. 2. 2. 2. 2. 2.]
2026-06-07 12:58:18,919 - harmonypy - INFO - sigma: [0.1 0.1 0.1 0.1 0.1]...
2026-06-07 12:58:18,920 - harmonypy - INFO - verbose: True
2026-06-07 12:58:18,921 - harmonypy - INFO - random_state: 0
2026-06-07 12:58:18,921 - harmonypy - INFO - Data: 50 PCs × 24673 cells
2026-06-07 12:58:18,922 - harmonypy - INFO - Batch variables: ['replicate']
2026-06-07 12:58:18,962 - harmonypy - INFO - Computing initial centroids...
2026-06-07 12:58:19,737 - harmonypy - INFO - Initialization complete.
Input X_pca shape: (24673, 50)
replicate
patient_1015 5090
patient_1488 4580
patient_1256 4134
patient_1016 3358
patient_1244 3343
patient_101 2024
patient_1039 1102
patient_107 1042
Name: count, dtype: int64
2026-06-07 12:58:19,738 - harmonypy - INFO - Iteration 1 of 10
2026-06-07 12:58:20,348 - harmonypy - INFO - Iteration 2 of 10
2026-06-07 12:58:21,003 - harmonypy - INFO - Iteration 3 of 10
2026-06-07 12:58:21,629 - harmonypy - INFO - Iteration 4 of 10
2026-06-07 12:58:22,287 - harmonypy - INFO - Converged after 4 iterations
Harmony Z_corr shape: (24673, 50)
Saved corrected embedding to adata.obsm['X_pca_harmony']
sc.pp.neighbors(adata, use_rep="X_pca_harmony")
sc.tl.umap(adata)
sctk.pp.leiden_grid(
adata,
start=.1,
stop=.5,
step=.1,
)
['leiden_0.1', 'leiden_0.2', 'leiden_0.3', 'leiden_0.4', 'leiden_0.5']
cluster_key = "leiden_0.5"
Embedding and composition plots#
sctk.pl.set_colors(adata, "cell_type", palette="tableau20")
sctk.pl.set_colors(adata, "label", mapping={"ctrl": "#4E79A7", "stim": "#E15759"})
sctk.pl.set_colors(adata, cluster_key, palette="glasbey_like")
fig, axes = plt.subplots(1, 3, figsize=(14, 3.6))
for ax, color, title in zip(axes, ["cell_type", "label", cluster_key], ["Cell type", "Condition", cluster_key]):
sctk.pl.embedding(
adata,
basis="umap",
color=color,
ax=ax,
show=False,
frameon=False,
size=7,
title=title,
legend_loc="right margin",
)
plt.tight_layout()
plt.show()
# Plotting functions are available directly from the public API.
sctk.pl
<module 'sctk' from '/data/user/mowp/workspace/sctk/src/sctk/__init__.py'>
sctk.pl.embedding(
adata,
basis="umap",
color=["cell_type", "label", 'replicate', cluster_key],
show=False,
frameon=False,
size=7,
title=title,
legend_loc="right margin",
ncols=2,
wspace=0.4,
figsize=(4, 4)
)
WARNING: The title list is shorter than the number of panels. Using 'color' value instead for some plots.
WARNING: The title list is shorter than the number of panels. Using 'color' value instead for some plots.
WARNING: The title list is shorter than the number of panels. Using 'color' value instead for some plots.
[<Axes: title={'center': 'leiden_0.5'}, xlabel='UMAP1', ylabel='UMAP2'>,
<Axes: title={'center': 'label'}, xlabel='UMAP1', ylabel='UMAP2'>,
<Axes: title={'center': 'replicate'}, xlabel='UMAP1', ylabel='UMAP2'>,
<Axes: title={'center': 'leiden_0.5'}, xlabel='UMAP1', ylabel='UMAP2'>]
ax = sctk.pl.composition(
adata,
groupby="cell_type",
splitby="label",
palette="tableau20",
show_counts=True,
figsize=(5.5, 3.2),
)
ax.set_title("Cell type composition by condition");
Marker genes and gene-set scores#
marker_sets = {
"T cell": ["CD3D", "CD3E", "IL7R", "CCR7"],
"B cell": ["MS4A1", "CD79A", "CD74"],
"Monocyte": ["LYZ", "S100A8", "S100A9", "FCGR3A"],
"NK": ["NKG7", "GNLY", "PRF1"],
"Dendritic": ["FCER1A", "CST3", "HLA-DRA"],
}
markers = sctk.tl.markers_in_data(adata, marker_sets)
markers
{'T cell': ['CD3D', 'CD3E', 'IL7R', 'CCR7'],
'B cell': ['MS4A1', 'CD79A', 'CD74'],
'Monocyte': ['LYZ', 'S100A8', 'S100A9', 'FCGR3A'],
'NK': ['NKG7', 'GNLY', 'PRF1'],
'Dendritic': ['FCER1A', 'CST3', 'HLA-DRA']}
sctk.pl.dotplot(
adata,
markers,
groupby="cell_type",
layer="log1p_norm",
standard_scale="var",
show=False,
);
gene_sets = {
"IFN response": ["ISG15", "IFIT1", "IFIT3", "LY6E", "MX1", "OAS1"],
"Cytotoxic": ["NKG7", "GNLY", "GZMB", "PRF1"],
}
gene_sets = sctk.tl.markers_in_data(adata, gene_sets)
sctk.tl.score_gene_sets(adata, gene_sets, layer="log1p_norm", key_added="score")
score_cols = [f"score_{name}" for name in gene_sets]
adata.obs[["cell_type", "label", *score_cols]].head()
| cell_type | label | score_IFN response | score_Cytotoxic | |
|---|---|---|---|---|
| index | ||||
| AAACATACATTTCC-1 | CD14+ Monocytes | ctrl | 0.105823 | 0.000000 |
| AAACATACCAGAAA-1 | CD14+ Monocytes | ctrl | 0.000000 | 0.000000 |
| AAACATACCATGCA-1 | CD4 T cells | ctrl | 0.000000 | 0.000000 |
| AAACATACCTCGCT-1 | CD14+ Monocytes | ctrl | 0.098954 | 0.000000 |
| AAACATACCTGGTA-1 | Dendritic cells | ctrl | 0.206593 | 0.216322 |
fig, axes = plt.subplots(1, 3, figsize=(14, 3.6))
sctk.pl.violinplot(
adata,
x="cell_type",
y="score_IFN response",
groupby="label",
palette={"ctrl": "#4E79A7", "stim": "#E15759"},
scale="width",
ax=axes[0],
)
axes[0].set_title("IFN response by cell type")
sctk.pl.boxplot(
adata,
x="label",
y="score_IFN response",
groupby="label",
palette={"ctrl": "#4E79A7", "stim": "#E15759"},
ax=axes[1],
)
axes[1].set_title("IFN response by condition")
sctk.pl.stripplot(
adata[adata.obs["cell_type"].isin(["CD4 T cells", "CD14+ Monocytes", "B cells", "NK cells"])].copy(),
x="cell_type", y="score_Cytotoxic",
groupby="label",
palette={"ctrl": "#4E79A7", "stim": "#E15759"},
dodge=True,
alpha=0.35,
size=1.5,
ax=axes[2],
)
axes[2].set_title("Cytotoxic score")
plt.show()
/data/user/mowp/workspace/sctk/src/sctk/pl/_basic.py:391: FutureWarning:
The `scale` parameter has been renamed and will be removed in v0.15.0. Pass `density_norm='width'` for the same effect.
func(**plot_kwargs)
Marker ranking#
sc.tl.rank_genes_groups(adata, groupby="cell_type", layer="log1p_norm", method="wilcoxon")
ranked_markers = sctk.tl.rank_genes_table(adata, group="CD14+ Monocytes", n_genes=10)
ranked_markers[["names", "scores", "logfoldchanges", "pvals_adj"]].head(10)
| names | scores | logfoldchanges | pvals_adj | |
|---|---|---|---|---|
| 0 | FTL | 111.371704 | 5.376429 | 0.0 |
| 1 | C15orf48 | 105.665062 | 6.827734 | 0.0 |
| 2 | CD63 | 104.587166 | 5.110891 | 0.0 |
| 3 | TYROBP | 104.534111 | 5.868842 | 0.0 |
| 4 | FCER1G | 101.607933 | 5.710850 | 0.0 |
| 5 | FTH1 | 100.447777 | 3.086356 | 0.0 |
| 6 | TIMP1 | 100.312737 | 6.252238 | 0.0 |
| 7 | SOD2 | 100.134590 | 5.718648 | 0.0 |
| 8 | ANXA5 | 99.789474 | 4.834092 | 0.0 |
| 9 | S100A10 | 99.523911 | 4.077960 | 0.0 |
Pseudobulk DESeq2: stim vs ctrl within cell types#
The pseudobulk sample combines replicate and label so that paired patient-condition samples remain distinct.
adata.obs["pseudobulk_sample"] = adata.obs["replicate"].astype(str) + "_" + adata.obs["label"].astype(str)
pb = sctk.tl.create_pseudobulk(
adata,
sample_key="pseudobulk_sample",
groupby="cell_type",
layer="counts",
min_cells=30,
)
pb.obs["label"] = pb.obs["pseudobulk_sample"].str.rsplit("_", n=1).str[-1].values
pb.obs["replicate"] = pb.obs["pseudobulk_sample"].str.rsplit("_", n=1).str[0].values
pb.obs.groupby(["cell_type", "label"], observed=True).size().unstack(fill_value=0)
| label | ctrl | stim |
|---|---|---|
| cell_type | ||
| B cells | 8 | 8 |
| CD14+ Monocytes | 8 | 8 |
| CD4 T cells | 8 | 8 |
| CD8 T cells | 8 | 8 |
| Dendritic cells | 8 | 8 |
| FCGR3A+ Monocytes | 8 | 8 |
| Megakaryocytes | 8 | 8 |
| NK cells | 8 | 8 |
de_cell_types = ["CD4 T cells", "CD14+ Monocytes", "B cells", "NK cells"]
de_results = {}
de_summary = []
for cell_type in de_cell_types:
sub = pb[pb.obs["cell_type"] == cell_type].copy()
try:
started = time.perf_counter()
de, _ = sctk.tl.run_deseq2(
sub,
condition_key="label",
treatment="stim",
control="ctrl",
n_cpus=16,
lfc_shrink=False,
quiet=True,
)
de_results[cell_type] = de
de_summary.append(
{
"cell_type": cell_type,
"n_genes": int(de.shape[0]),
"padj_lt_0.05": int((de["padj"] < 0.05).sum()),
"elapsed_seconds": round(time.perf_counter() - started, 2),
"status": "ok",
}
)
except Exception as exc:
de_summary.append({"cell_type": cell_type, "status": f"failed: {exc}"})
de_summary = pd.DataFrame(de_summary)
de_summary
| cell_type | n_genes | padj_lt_0.05 | elapsed_seconds | status | |
|---|---|---|---|---|---|
| 0 | CD4 T cells | 15706 | 973 | 27.06 | ok |
| 1 | CD14+ Monocytes | 15706 | 3426 | 24.52 | ok |
| 2 | B cells | 15706 | 757 | 23.85 | ok |
| 3 | NK cells | 15706 | 463 | 22.59 | ok |
representative = "CD14+ Monocytes"
de = de_results[representative]
ax = sctk.pl.volcano(
de,
pvalue="padj",
logfc="log2FoldChange",
pvalue_threshold=0.05,
logfc_threshold=1.0,
top=12,
figsize=(5.2, 4.2),
s=12,
alpha=0.7,
)
ax.set_title(f"{representative}: stim vs ctrl");
Enrichment analysis from DESeq2 results#
A small curated gene-set network validates enrichment wrappers and enrichment plots on real DESeq2 output. The same API works with larger GMT-derived networks.
pathway_net = pd.DataFrame(
{
"source": (
["IFN response"] * 8
+ ["Monocyte activation"] * 7
+ ["Cytotoxicity"] * 6
+ ["Antigen presentation"] * 6
+ ["T cell activation"] * 6
+ ["B cell activation"] * 5
),
"target": [
"ISG15", "IFIT1", "IFIT3", "MX1", "OAS1", "OASL", "IFI6", "IRF7",
"LYZ", "S100A8", "S100A9", "FCGR3A", "IL1RN", "LST1", "CTSS",
"NKG7", "GNLY", "GZMB", "PRF1", "KLRD1", "KLRB1",
"HLA-DRA", "HLA-DRB1", "HLA-DPA1", "HLA-DPB1", "CD74", "CTSS",
"CD3D", "CD3E", "IL7R", "CCR7", "LTB", "TRAC",
"MS4A1", "CD79A", "CD79B", "CD74", "BANK1",
],
}
)
pathway_net = pathway_net[pathway_net["target"].isin(adata.var_names)].drop_duplicates()
up_gene_sets = {}
for cell_type, result in de_results.items():
up = result[(result["padj"] < 0.05) & (result["log2FoldChange"] > 1)].index.astype(str).tolist()
if len(up) < 10:
up = result.sort_values("stat", ascending=False).head(100).index.astype(str).tolist()
up_gene_sets[cell_type] = up
ora_results = sctk.tl.run_ora(up_gene_sets, pathway_net, tmin=2)
gsea_results = sctk.tl.run_gsea(
de_results[representative]["stat"].dropna(),
pathway_net,
min_size=2,
max_size=500,
permutations=100,
threads=4,
seed=0,
)
print("ORA columns:", ora_results.columns.tolist())
print("GSEA columns:", gsea_results.columns.tolist())
display(ora_results.sort_values("padj").head(10))
display(gsea_results.sort_values("padj").head(10))
ORA columns: ['name', 'Term', 'score', 'pvalue', 'method', 'padj']
GSEA columns: ['name', 'Term', 'score', 'pvalue', 'method', 'padj']
| name | Term | score | pvalue | method | padj | |
|---|---|---|---|---|---|---|
| 8 | NK cells | IFN response | 13.429473 | 1.577207e-30 | ora | 1.577207e-30 |
| 0 | CD4 T cells | IFN response | 10.596160 | 2.270184e-24 | ora | 4.540368e-24 |
| 7 | B cells | IFN response | 10.453109 | 2.206465e-21 | ora | 2.206465e-21 |
| 4 | CD14+ Monocytes | IFN response | 9.497297 | 5.409421e-22 | ora | 2.704711e-21 |
| 3 | CD14+ Monocytes | Cytotoxicity | 9.406375 | 6.826024e-10 | ora | 1.706506e-09 |
| 6 | CD14+ Monocytes | T cell activation | 8.986522 | 7.583712e-07 | ora | 1.263952e-06 |
| 1 | CD4 T cells | Monocyte activation | 7.762946 | 8.998200e-04 | ora | 8.998200e-04 |
| 2 | CD14+ Monocytes | Antigen presentation | 7.300073 | 1.399545e-03 | ora | 1.399545e-03 |
| 5 | CD14+ Monocytes | Monocyte activation | 7.300073 | 1.399545e-03 | ora | 1.399545e-03 |
| name | Term | score | pvalue | method | padj | |
|---|---|---|---|---|---|---|
| 0 | contrast | Antigen presentation | 1.0 | 1.0 | gsea | 1.0 |
| 1 | contrast | B cell activation | 1.0 | 1.0 | gsea | 1.0 |
| 2 | contrast | Cytotoxicity | 1.0 | 1.0 | gsea | 1.0 |
| 3 | contrast | IFN response | 1.0 | 1.0 | gsea | 1.0 |
| 4 | contrast | Monocyte activation | 1.0 | 1.0 | gsea | 1.0 |
| 5 | contrast | T cell activation | 1.0 | 1.0 | gsea | 1.0 |
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
sctk.pl.enrichment_dotplot(
ora_results, term="Term", source="name", score="score", pvalue="padj", top=20, ax=axes[0]
)
axes[0].set_title("ORA: up-regulated DE genes")
sctk.pl.enrichment_barplot(
gsea_results, term="Term", score="score", pvalue="padj", top=10, ax=axes[1]
)
axes[1].set_title(f"GSEA: {representative}")
plt.show()