Create a spatial transcriptomics segmentation and deconvolution validation.
- User
Create a spatial transcriptomics segmentation and deconvolution validation.
Assistant
Create a spatial transcriptomics segmentation and deconvolution validation.
The user wants a "spatial transcriptomics segmentation and deconvolution validation" example or workflow. This is a complex bioinformatics task.
1. Understand the Goal:
2. Determine the Scope & Tools:
Scanpy / Squidpy: Standard for ST analysis.Cell2location or RCTD: Popular for deconvolution.Cellpose or StarDist: Standard for segmentation.3. Drafting the Workflow (Mental Outline):
Step 1: Setup & Data Simulation.
Step 2: Deconvolution (The "Method").
cell2location might be heavy for a snippet, I'll implement a simple Non-Negative Matrix Factorization (NMF) or Linear Regression based deconvolution as a proxy. Or, stick to a high-level conceptual code using scanpy.numpy and scanpy to simulate data, run a simple regression-based deconvolution, and calculate validation metrics. This ensures the user can actually run it without installing 10 heavy dependencies (like pytorch/cellpose) if they just want the logic.4. Refining the Plan:
Let's split the response into two distinct parts:
5. Developing the Code (Mental Draft):
Deconvolution Logic:
Segmentation Logic:
skimage.metrics.6. Structuring the Response:
scanpy, squidpy, scikit-image, numpy).cell2location or Xenium ground truth datasets.7. Refining Code Details (Self-Correction during drafting):
scipy.optimize.nnls is great for deconvolution.skimage.draw.disk for simulating cells.skimage.metrics.adapted_rand_error or simple Intersection over Union.8. Final Polish: Add comments explaining why this is validation. (e.g., "We compare column X to column Y because...").
(Self-Correction): The user might want a "visual" validation too. I should include code to plot the correlation scatter plot and the mask overlay.
Let's stick to Python. It's the most standard for this. I will provide a complete, runnable script that simulates a dataset and validates the analysis. This is more useful than just describing the steps.
Plan:
skimage to create and segment blobs.Let's write the code.
Ref matrix (genes x cell_types). Generate Mix matrix (genes x spots) based on random proportions. Solve Mix = Ref @ Prop. Compare Prop_est vs Prop_true.This seems solid. It covers all bases requested.
Formatting: Use clear Markdown headers. Use code blocks. Explain the logic.
(Final check of the prompt): "Spatial transcriptomics segmentation and deconvolution validation." The "Validation" part is key. I must emphasize the comparison metric.
Let's proceed with generating the response. This guide provides a complete workflow for validating spatial transcriptomics segmentation and deconvolution. Since ground truth is rarely available for real biological tissue, the standard scientific approach is to generate synthetic data with known properties, run the analysis, and quantify the error.
We will use Python and standard libraries (scanpy, squidpy, scikit-image, numpy) to:
You will need the following libraries installed:
pip install scanpy squidpy numpy pandas matplotlib scikit-learn scipy scikit-image
First, we create a "dummy" dataset. This is the most critical step for validation. If you use real data, you never know if your model is "right." With synthetic data, you hold the answer key.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.spatial import cKDTree
from skimage.draw import disk
from skimage.segmentation import random_walker
# 1. Setup Parameters
img_size = 1000
n_cells = 50
n_genes = 100
n_cell_types = 3
# 2. Generate Ground Truth Segmentation Masks
# We create a blank image and place random non-overlapping disks as cells
gt_masks = np.zeros((img_size, img_size), dtype=int)
centers = []
radii = []
rng = np.random.default_rng(42)
for i in range(1, n_cells + 1):
while True:
# Random center and radius
r = rng.integers(20, 40)
cx, cy = rng.integers(r, img_size-r, size=2)
# Check for overlap with existing cells (simple distance check)
valid = True
for (pcx, pcy), pr in zip(centers, radii):
dist = np.sqrt((cx - pcx)**2 + (cy - pcy)**2)
if dist < (r + pr + 5): # 5 pixel buffer
valid = False
break
if valid:
rr, cc = disk((cx, cy), r, shape=(img_size, img_size))
gt_masks[rr, cc] = i
centers.append((cx, cy))
radii.append(r)
break
# 3. Assign Cell Types to Masks
# We randomly assign each cell ID to a cell type (0: Tumor, 1: Immune, 2: Stromal)
cell_ids = np.arange(1, n_cells + 1)
cell_types = rng.integers(0, n_cell_types, size=n_cells)
gt_cell_type_map = dict(zip(cell_ids, cell_types))
print(f"Generated {n_cells} synthetic cells.")
Now we simulate the sequencing data. We assume a technology like 10x Visium, where spots are larger than single cells, requiring deconvolution.
# 1. Create Reference Gene Signatures
# We create distinct expression profiles for 3 cell types
# Genes 0-33: Tumor, Genes 34-66: Immune, Genes 67-99: Stroma
gene_signatures = np.zeros((n_genes, n_cell_types))
gene_signatures[0:34, 0] = 1 # Tumor markers
gene_signatures[34:67, 1] = 1 # Immune markers
gene_signatures[67:100, 2] = 1 # Stroma markers
# Add noise to signatures
gene_signatures += rng.normal(0, 0.1, gene_signatures.shape)
gene_signatures = np.clip(gene_signatures, 0, None)
# 2. Generate Visium-style Spots
# Assume hexagonal grid, but here we just scatter points
n_spots = 200
spot_coords = rng.integers(0, img_size, size=(n_spots, 2))
spot_radius = 30 # Visium spots are ~55um diameter
# 3. Create Spot Composition (Ground Truth for Deconvolution)
# For each spot, calculate what fraction of it covers which cell type
gt_compositions = []
print("Simulating spot compositions...")
for sx, sy in spot_coords:
# Create a mask for the current spot
rr, cc = disk((sx, sy), spot_radius, shape=(img_size, img_size))
# Find which cells are under this spot
cells_in_spot = gt_masks[rr, cc]
unique, counts = np.unique(cells_in_spot[cells_in_spot > 0], return_counts=True)
# Calculate proportions based on pixel overlap
total_count = np.sum(counts)
if total_count == 0:
# Empty spot (background)
props = np.array([0.0] * n_cell_types)
else:
# Map cells to types and sum counts
type_counts = np.zeros(n_cell_types)
for cell_id, count in zip(unique, counts):
ctype = gt_cell_type_map[cell_id]
type_counts[ctype] += count
props = type_counts / total_count
gt_compositions.append(props)
gt_comp_df = pd.DataFrame(gt_compositions, columns=['Tumor', 'Immune', 'Stroma'])
# 4. Generate Gene Counts based on Compositions
# Counts = (Signature * Proportion) * Depth
counts_data = []
for props in gt_compositions:
profile = np.dot(gene_signatures, props)
# Add technical noise (Poisson)
counts = rng.poisson(profile * 10)
counts_data.append(counts)
counts_df = pd.DataFrame(counts_data, columns=[f"Gene_{i}" for i in range(n_genes)])
print("Simulation complete.")
Now we treat counts_df, spot_coords, and the raw image (derived from masks) as our "experimental data" and validate an analysis pipeline.
We assume we performed segmentation (e.g., using Cellpose or StarDist) and got pred_masks. For this simulation, let's assume our segmentation algorithm was "imperfect" and introduced some noise.
Metrics:
from skimage.metrics import adapted_rand_error
# Simulate a "Predicted" segmentation that isn't perfect
# (In reality, you would load the output of your segmentation model here)
pred_masks = gt_masks.copy()
# Add noise: shift some cells slightly or erode boundaries
for i in range(1, n_cells+1):
if rng.random() > 0.8: # 20% chance of error
# Erode the mask slightly to simulate boundary error
pred_masks[pred_masks == i] = 0
# Calculate Validation Metrics
# Note: Adapted Rand Error requires 0 as background
error, precision, recall = adapted_rand_error(image_true=gt_masks, image_test=pred_masks)
print(f"--- Segmentation Validation ---")
print(f"Adapted Rand Error: {error:.4f} (Lower is better)")
print(f"Precision: {precision:.4f}")
print(f"Recall: {recall:.4f}")
We treat gt_comp_df as the known answer. We compare it against the results of a deconvolution algorithm (like Cell2location, RCTD, or a simple Non-Negative Matrix Factorization).
Here, we simulate "Predicted" proportions and compare them.
from scipy.stats import pearsonr, spearmanr
from sklearn.metrics import mean_squared_error
# 1. Run a "Method" (Here we just simulate predictions that are noisy versions of truth)
# In a real workflow, this would be: pred_comp_df = run_cell2location(counts_df)
pred_comp_df = gt_comp_df.copy()
# Add noise to simulate model inaccuracy
noise = rng.normal(0, 0.05, pred_comp_df.shape)
pred_comp_df = pred_comp_df + noise
# Clip to [0, 1] and Renormalize rows to sum to 1
pred_comp_df = pred_comp_df.clip(0, 1)
pred_comp_df = pred_comp_df.div(pred_comp_df.sum(axis=1), axis=0)
# 2. Validation Metrics
# A. Correlation (Per Cell Type)
print(f"\n--- Deconvolution Validation (Per Cell Type) ---")
for col in ['Tumor', 'Immune', 'Stroma']:
r, _ = pearsonr(gt_comp_df[col], pred_comp_df[col])
rmse = np.sqrt(mean_squared_error(gt_comp_df[col], pred_comp_df[col]))
print(f"{col}: Pearson R={r:.3f}, RMSE={rmse:.3f}")
# B. Jenson-Shannon Divergence (Per Spot)
# This measures similarity between two probability distributions
from scipy.spatial.distance import jensenshannon
js_distances = []
for i in range(len(gt_comp_df)):
p = gt_comp_df.iloc[i].values
q = pred_comp_df.iloc[i].values
# JSD returns squared root of divergence usually, square it for variance metric
dist = jensenshannon(p, q)
js_distances.append(dist)
print(f"\n--- Global Validation ---")
print(f"Mean JS-Divergence: {np.mean(js_distances):.4f} (Lower is better, 0 is perfect)")
Visual inspection is crucial. We plot the Ground Truth vs. Prediction side-by-side.
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
# Plot 1: Spatial Ground Truth
gt_comp_df['Total_Immune'] = gt_comp_df['Immune'] # Just plotting one type
scatter1 = axes[0].scatter(spot_coords[:, 0], spot_coords[:, 1],
c=gt_comp_df['Total_Immune'], cmap='Reds', s=50)
axes[0].set_title('Ground Truth\n(Immune Cell Proportion)')
plt.colorbar(scatter1, ax=axes[0])
# Plot 2: Predicted Deconvolution
pred_comp_df['Total_Immune'] = pred_comp_df['Immune']
scatter2 = axes[1].scatter(spot_coords[:, 0], spot_coords[:, 1],
c=pred_comp_df['Total_Immune'], cmap='Reds', s=50)
axes[1].set_title('Predicted\n(Immune Cell Proportion)')
plt.colorbar(scatter2, ax=axes[1])
for ax in axes:
ax.invert_yaxis() # Images usually have origin at top-left
plt.tight_layout()
plt.show()
# Plot 3: Scatter of Correlation
plt.figure(figsize=(5, 5))
plt.scatter(gt_comp_df['Tumor'], pred_comp_df['Tumor'], alpha=0.5, label='Tumor')
plt.scatter(gt_comp_df['Immune'], pred_comp_df['Immune'], alpha=0.5, label='Immune')
plt.plot([0, 1], [0, 1], 'k--', label='Perfect Fit')
plt.xlabel('Ground Truth Proportion')
plt.ylabel('Predicted Proportion')
plt.title('Deconvolution Accuracy')
plt.legend()
plt.grid(True)
plt.show()
When you run this code, the "Validation" phase yields specific numbers:
Why this works: This removes the "black box" nature of bioinformatics tools. If your pipeline scores poorly on this synthetic data (where you know the truth), it will definitely fail on real biological data.