Download notebook

05 · Generate expression on another slice’s anatomy

Transfer measured DLPFC expression from 151675 to the known layer map of 151676. Reserve target counts for evaluation after generation. Data and environment setup

[1]:
from pathlib import Path
import sys
import numpy as np
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, gene_values, spatial_panel, cache_reference_counts
DATA = data_root()

OUT = TUTORIAL / "outputs" / "05"
OUT.mkdir(parents=True, exist_ok=True)
print("FEAST", FEAST.__version__)
FEAST 1.0.6

Build the target blueprint

Use target spot IDs, XY positions and layer labels. Keep layers with at least 20 source spots and use the genes shared by 151670, 151675 and 151676. Section 151670 contributes only its gene names.

[2]:
source = load_counts(DATA / "dlpfc/151675.h5ad", "ground_truth")
target_file = ad.read_h5ad(DATA / "dlpfc/151676.h5ad", backed="r")
panel_file = ad.read_h5ad(DATA / "dlpfc/151670.h5ad", backed="r")
genes = sorted(set(source.var_names) & set(target_file.var_names) & set(panel_file.var_names))
source = source[:, genes].copy()
# FEAST prefers spatial_3d when present; this tutorial explicitly uses XY.
source.obsm.pop("spatial_3d", None)
labels = target_file.obs["ground_truth"].astype(str)
support = source.obs["ground_truth"].astype(str).value_counts()
keep = labels.map(support).fillna(0).to_numpy() >= 20
ids = target_file.obs_names[keep].copy()
xy = np.asarray(target_file.obsm["spatial"])[keep, :2].copy()
obs = pd.DataFrame({"target_obs_id": ids, "ground_truth": labels.to_numpy()[keep]})
blueprint = FEAST.SliceBlueprint(coordinates=xy, domain_map=obs["ground_truth"].to_numpy(), obs=obs)
print(f"Target support: {keep.sum():,}/{len(keep):,} spots; {len(genes):,} genes")
target_file.file.close()
panel_file.file.close()
Target support: 3,431/3,431 spots; 17,391 genes

Generate counts

Fit the expression distributions within each source layer and transfer them to the corresponding target layer. Use assignment randomness 0.3 and seed 2026.

[3]:
from FEAST.de_novo import fit_reference
fit_config = FEAST.ReferenceFitConfig(min_gene_spots=0, min_gene_mean=0.0, max_gene_zero_prop=1.0)
cache_reference_counts(source)
model = fit_reference(source, label_key="ground_truth", config=fit_config)
transport = FEAST.SimulationConfig(
    assignment_randomness=0.3, epsilon=0.05, sinkhorn_iter=1000, sinkhorn_tol=1e-5,
    unbalanced_transport=True, reg_m=5.0, transport_nonconvergence="raise",
    transport_backend="numpy", transport_dtype="float64", max_transport_pairs=25_000_000,
)
generated = FEAST.simulate(model, target=blueprint, marginal_model="empirical_reference", transport=transport, seed=2026)
assert generated.obs["target_obs_id"].tolist() == ids.tolist()
generated.obs_names = generated.obs["target_obs_id"].astype(str)

Compare with measured expression

Plot observed and generated RELN counts at matching target positions using one log-scaled color range.

[4]:
observed = load_counts(DATA / "dlpfc/151676.h5ad", "ground_truth")[generated.obs_names, generated.var_names].copy()
gene = "RELN"
observed_values = np.log1p(gene_values(observed, gene))
generated_values = np.log1p(gene_values(generated, gene))
limit = max(observed_values.max(), generated_values.max())
fig, axes = plt.subplots(1, 3, figsize=(12, 4), layout="constrained")
spatial_panel(axes[0], xy, generated.obs["ground_truth"], "Known target layers", True)
spatial_panel(axes[1], xy, observed_values, f"Observed {gene} · log1p counts", vmax=limit)
spatial_panel(axes[2], xy, generated_values, f"Generated {gene} · log1p counts", vmax=limit)
plt.show()
generated.write_h5ad(OUT / "151675_to_151676.h5ad")
../_images/notebooks_05_2d_conditional_transfer_7_0.png

The layer map shows the anatomy supplied to FEAST. Compare the spatial pattern of RELN within each layer.