04 · Simulate a batch effect and correct it with scVI
Generate two batches from DLPFC section 151675 and compare their separation before and after scVI correction. Data and environment setup
[1]:
from pathlib import Path
import sys
import pandas as pd
import matplotlib.pyplot as plt
import anndata as ad
import FEAST
TUTORIAL = Path.cwd() if Path.cwd().name == "tutorial" else Path.cwd() / "tutorial"
sys.path.insert(0, str(TUTORIAL))
from _utils import data_root, load_counts, spatial_panel
DATA = data_root()
OUT = TUTORIAL / "outputs" / "04"
OUT.mkdir(parents=True, exist_ok=True)
print("FEAST", FEAST.__version__)
FEAST 1.0.6
[2]:
reference = load_counts(DATA / "dlpfc/151675.h5ad", "ground_truth")
Generate paired batches
The scale and shift coefficients were estimated from sections 151673 and 151508. Apply them to 151675 with the same seed for both batches. An alpha of 0 generates a simulated baseline and 1 applies the full deformation.
[3]:
%%capture --no-stderr
deformation = FEAST.BatchDeformation(
D=[0.9506859713168332, 0.5067732090337828, 0.9215737834857423],
b=[-0.9666024309148558, 0.011108308402325857, 1.0822184425747938],
name="study04_fixed_deformation_on_151675",
)
base = FEAST.simulate_batch_effect(reference, D=deformation.D, b=deformation.b, alpha=0.0, random_seed=42)
query = FEAST.simulate_batch_effect(reference, D=deformation.D, b=deformation.b, alpha=1.0, random_seed=42)
[4]:
assert base.obs_names.equals(query.obs_names)
pd.DataFrame({"D": deformation.D, "b": deformation.b},
index=["log mean", "log dispersion", "logit zero proportion"])
[4]:
| D | b | |
|---|---|---|
| log mean | 0.950686 | -0.966602 |
| log dispersion | 0.506773 | 0.011108 |
| logit zero proportion | 0.921574 | 1.082218 |
Prepare raw counts for scVI
Select 2,000 variable genes on the original slice and use the same panel in both batches. Preserve the source spot ID when joining them.
[5]:
import scanpy as sc
panel_source = reference.copy()
sc.pp.highly_variable_genes(panel_source, n_top_genes=2000, flavor="seurat_v3")
genes = panel_source.var_names[panel_source.var["highly_variable"]]
pair = ad.concat({"ref": base[:, genes], "query": query[:, genes]}, label="batch", index_unique="__")
pair.obs["source_spot_id"] = list(base.obs_names) + list(query.obs_names)
pair.layers["counts"] = pair.X.copy()
pair.write_h5ad(OUT / "batch_input.h5ad")
Correct the batch effect
The scVI worker trains a ten-dimensional latent representation on raw counts and batch labels. It uses one hidden layer, a ZINB count model and early stopping within 400 epochs.
[6]:
import os
import subprocess
with (OUT / "scvi.log").open("w") as log:
subprocess.run([
os.environ["SCVI_PYTHON"], str(TUTORIAL / "scvi_step.py"),
str(OUT / "batch_input.h5ad"), str(OUT / "scvi_result.h5ad"),
], check=True, stdout=log, stderr=subprocess.STDOUT)
corrected = ad.read_h5ad(OUT / "scvi_result.h5ad")
Compare batch mixing and tissue layers
Compare PCA of normalized input counts with a two-dimensional projection of the scVI representation. Look for overlap between batches while distinct tissue layers stay distinguishable.
[7]:
from sklearn.decomposition import PCA
before = corrected.copy()
before.X = before.layers["counts"].copy()
sc.pp.normalize_total(before, target_sum=1e4)
sc.pp.log1p(before)
sc.pp.pca(before, n_comps=10, random_state=42)
projections = {"Before (count PCA)": before.obsm["X_pca"][:, :2],
"After (scVI projection)": PCA(n_components=2, random_state=42).fit_transform(corrected.obsm["X_scVI"])}
fig, axes = plt.subplots(2, 2, figsize=(10, 7), layout="constrained")
for col, (title, xy) in enumerate(projections.items()):
for row, key in enumerate(["batch", "ground_truth"]):
spatial_panel(axes[row, col], xy, corrected.obs[key], f"{title} · {key}", True)
plt.show()
legacy_api_wrap/__init__.py:88: UserWarning: Some cells have zero counts
return fn(*args_all, **kw)
The two projections have different axes. Use the colored groups to assess mixing and layer structure in this paired simulation.