Skip to content

Cell trajectories and diffusion pseudotime

A trajectory places different cells along an inferred process. It does not follow one cell through time. The distinction matters when an expression graph produces a convincing path but the recorded experimental stages overlap along it.

This Python lesson uses the mouse embryo measurements from Moignard and colleagues. These are single-cell qPCR measurements, not RNA-seq counts. Their recorded embryo stages and flow sorting gates provide information outside the expression matrix against which to examine an inferred trajectory.

The analysis computes diffusion pseudotime with Scanpy and uses PAGA to examine connections between expression clusters. It retains every cell in the fit. Experimental group labels stay outside the graph calculation, but the earliest group supplies the root. Later group labels provide a descriptive check of the result; they are not unseen cells in a prediction exercise.

Read the measured expression and experimental groups

Section titled “Read the measured expression and experimental groups”

Download the normalized expression table and place it under inputs/. The table preserves the dCt_values.txt sheet of Supplementary Table 7. The source manifest identifies the workbook and its checksum.

The study supplies three sequential groups, primitive streak PS, neural plate NP, and head fold HF. The two four-somite groups, 4SG and 4SFG, differ in their flow sorting gates and GFP status. They share a developmental stage; they are not two successive time points.

These values already have the study’s qPCR normalization and detection floor. Keep that scale. RNA-seq library normalization or another logarithm would change the measurement. A value at the detection floor is not a measured zero transcript count.

from pathlib import Path
import anndata as ad
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scanpy as sc
from scipy.sparse.csgraph import connected_components
from scipy.stats import spearmanr
output = Path("outputs")
output.mkdir(exist_ok=True)
sc.settings.verbosity = 0
expression = pd.read_csv("inputs/moignard_dct.csv.gz", index_col=0)
assert expression.index.is_unique and expression.columns.is_unique
assert np.isfinite(expression.to_numpy()).all()
expression = expression.drop(columns=["Eif2b1", "Mrpl19", "Polr2a", "Ubc"])
groups = ["PS", "NP", "HF", "4SG", "4SFG"]
labels = expression.index.str.extract(r"^(4SFG|4SG|HF|NP|PS)", expand=False)
assert labels.notna().all()
metadata = pd.DataFrame(index=expression.index)
metadata["group"] = pd.Categorical(labels, categories=groups, ordered=True)
metadata["stage_order"] = metadata["group"].astype(str).map(
{"PS": 0, "NP": 1, "HF": 2, "4SG": 3, "4SFG": 3}
)
print(f"Cells: {len(expression)}; analyzed genes: {expression.shape[1]}")
print(metadata.groupby("group", observed=True).size().to_string())
Cells: 3934; analyzed genes: 42
group
PS 624
NP 552
HF 1005
4SG 983
4SFG 770

The four excluded genes served as reference assays. The remaining panel was selected for blood development by the study; this is not a search across all genes. For an RNA-seq experiment, establish count quality, transformation, and feature selection before this stage of the analysis.

Choose a root and compute diffusion distance

Section titled “Choose a root and compute diffusion distance”

The root gives the distance an origin. Here it is the first PS barcode in lexical order, an explicit and reproducible teaching choice. The experiment supports the choice of an early group, but it does not establish that this particular cell is the ancestor of the others.

The function below receives expression and the selected barcode. It never reads the stage labels. A Gaussian neighbor graph connects nearby measurements, diffusion components describe that graph, and DPT computes distance from the root. The code stops if the graph is disconnected rather than presenting infinite distances as a complete trajectory.

def fit_trajectory(values, root_id, neighbor_count):
"""Compute diffusion pseudotime from expression and one declared root.
Args:
values: Cell by gene dataframe on the published normalized scale.
root_id: Cell barcode used as the origin of diffusion distance.
neighbor_count: Number of neighbors used to construct the graph.
Returns:
An AnnData object containing the graph and diffusion pseudotime.
Raises:
ValueError: The root is absent or the graph is disconnected.
"""
if root_id not in values.index:
raise ValueError("The root barcode is absent.")
result = ad.AnnData(values.copy())
sc.pp.neighbors(result, n_neighbors=neighbor_count, use_rep="X",
method="gauss", transformer="sklearn", random_state=0)
components = connected_components(result.obsp["connectivities"])[0]
if components != 1:
raise ValueError("The graph is disconnected; inspect its components.")
sc.tl.diffmap(result, n_comps=15, random_state=0)
result.uns["iroot"] = int(result.obs_names.get_loc(root_id))
sc.tl.dpt(result, n_dcs=10)
return result
early_ids = sorted(metadata.index[metadata["group"] == "PS"])
root_id = early_ids[0]
trajectory = fit_trajectory(expression, root_id, 30)
pseudotime = trajectory.obs["dpt_pseudotime"].copy()
assert np.isfinite(pseudotime).all()
assert pseudotime.loc[root_id] == 0
print(f"Root cell: {root_id}")
print(f"Finite pseudotimes: {np.isfinite(pseudotime).sum()}")
print(f"Pseudotime range: {pseudotime.min():.3f} to {pseudotime.max():.3f}")
Root cell: PSA1_001
Finite pseudotimes: 3934
Pseudotime range: 0.000 to 1.000

DPT scales these distances within this dataset. A difference of 0.2 is not 0.2 days, and distances along different branches need not represent equal amounts of biological development.

Leiden partitions the expression graph without experimental labels. PAGA then estimates the connectivity between those partitions. This separates the pseudotime calculation from a forced choice of a branching count.

sc.tl.leiden(trajectory, resolution=0.45, flavor="igraph", n_iterations=2,
directed=False, random_state=0, key_added="graph_cluster")
sc.tl.paga(trajectory, groups="graph_cluster")
clusters = trajectory.obs["graph_cluster"]
cluster_ids = list(clusters.cat.categories)
connectivity = pd.DataFrame(
trajectory.uns["paga"]["connectivities"].toarray(),
index=cluster_ids, columns=cluster_ids
)
composition = pd.crosstab(clusters, metadata["group"])
composition.to_csv(output / "trajectory_cluster_groups.csv")
connectivity.to_csv(output / "trajectory_paga_connectivity.csv")
print("Experimental groups within expression clusters:")
print(composition.to_string())
Experimental groups within expression clusters:
group PS NP HF 4SG 4SFG
graph_cluster
0 50 86 580 4 417
1 181 112 138 2 339
2 135 193 201 81 0
3 258 159 86 2 14
4 0 2 0 894 0

The cross-table is an interpretation step after the graph fit. Its labels do not change a cluster assignment. A cluster concentrated in one late gate supplies a candidate endpoint, while a cluster containing several stages exposes their overlap. PAGA edges are undirected connections, not observed transitions or lineage tracing evidence.

colors = ["#32658b", "#65a572", "#c39538", "#b34a45", "#8062a7"]
coordinates = trajectory.obsm["X_diffmap"][:, 1:3]
figure, axes = plt.subplots(1, 3, figsize=(15, 4.6), layout="constrained")
for group, color in zip(groups, colors, strict=True):
selected = metadata["group"] == group
axes[0].scatter(*coordinates[selected].T, s=5, alpha=0.55,
color=color, label=group, rasterized=True)
axes[0].legend(markerscale=2, fontsize=9, frameon=False)
axes[0].set_title("Recorded groups after the fit")
points = axes[1].scatter(*coordinates.T, c=pseudotime, s=5,
cmap="viridis", rasterized=True)
axes[1].set_title("Diffusion pseudotime")
figure.colorbar(points, ax=axes[1], label="DPT distance")
angles = np.linspace(0, 2 * np.pi, len(cluster_ids), endpoint=False)
positions = np.column_stack([np.cos(angles), np.sin(angles)])
for first in range(len(cluster_ids)):
for second in range(first + 1, len(cluster_ids)):
weight = connectivity.iloc[first, second]
if weight >= 0.02:
axes[2].plot(positions[[first, second], 0],
positions[[first, second], 1], color="#939ca5",
linewidth=0.5 + 12 * weight, zorder=1)
axes[2].scatter(*positions.T, s=650, color="#dce6ee", zorder=2)
for index, cluster in enumerate(cluster_ids):
axes[2].text(*positions[index], cluster, ha="center", va="center")
axes[2].set_title("PAGA connectivity, edges >= 0.02")
axes[2].set_aspect("equal")
axes[2].set_axis_off()
for axis in axes[:2]:
axis.set_xlabel("Diffusion component 1")
axis.set_ylabel("Diffusion component 2")
figure.savefig(output / "trajectory_graph.png", dpi=170)
plt.close(figure)

The diffusion map shows recorded groups and pseudotime beside the weighted PAGA connections between expression clusters.

The PAGA nodes use a circular display layout. Their positions have no biological distance interpretation, and the edge threshold controls the display only. Compare the full exported connectivity matrix before deciding that a weak edge is absent. The two diffusion components are a view of the graph, not the full space used by DPT.

The two four-somite gates receive the same stage rank. We exclude the root group from the rank comparison because its label already informed the root choice. The remaining labels did not enter the fit, although all of their cells contributed expression measurements to the graph.

results = metadata.join(pseudotime).join(clusters)
summary = results.groupby("group", observed=True)["dpt_pseudotime"].agg(
["size", "median", "min", "max"]
)
later = results["stage_order"] > 0
stage_agreement = spearmanr(
results.loc[later, "stage_order"],
results.loc[later, "dpt_pseudotime"]
).statistic
results.to_csv(output / "trajectory_cells.csv")
summary.to_csv(output / "trajectory_stage_summary.csv")
print(summary.to_string(float_format="%.3f"))
print(f"Later-stage descriptive Spearman correlation: {stage_agreement:.3f}")
figure, axis = plt.subplots(figsize=(8, 4.8), layout="constrained")
values = [results.loc[results["group"] == group, "dpt_pseudotime"]
for group in groups]
boxes = axis.boxplot(values, tick_labels=groups, showfliers=False,
patch_artist=True)
for box, color in zip(boxes["boxes"], colors, strict=True):
box.set_facecolor(color)
box.set_alpha(0.7)
axis.set_ylabel("Diffusion pseudotime")
axis.set_xlabel("Recorded experimental group")
axis.set_title("Experimental stages overlap along the inferred order")
figure.savefig(output / "trajectory_stage_check.png", dpi=170)
plt.close(figure)
size median min max
group
PS 624 0.408 0.000 0.620
NP 552 0.532 0.005 0.849
HF 1005 0.548 0.004 0.748
4SG 983 0.924 0.015 1.000
4SFG 770 0.532 0.009 0.560
Later-stage descriptive Spearman correlation: 0.392

Boxplots compare diffusion pseudotime across the recorded embryo stages and the two four-somite gates.

The blood-associated four-somite gate extends toward high pseudotime, but the other four-somite gate overlaps earlier groups. This result does not support one shared chronological clock across both gates. The correlation describes the sampled cells; a cell-level significance test would ignore cells shared among embryos and the selected measurement panel.

A useful trajectory report shows whether another reasonable choice changes the order. The comparison below uses smaller and larger neighborhoods and an alternative early root nearest the mean expression of the PS cells. Neither alternative uses later-stage agreement to select its root.

early_values = expression.loc[early_ids].to_numpy()
root_distance = ((early_values - early_values.mean(axis=0)) ** 2).sum(axis=1)
central_root = early_ids[int(np.argmin(root_distance))]
choices = [("15 neighbors", root_id, 15),
("60 neighbors", root_id, 60),
("central PS root", central_root, 30)]
sensitivity = []
for label, candidate_root, neighbor_count in choices:
candidate = fit_trajectory(expression, candidate_root, neighbor_count)
candidate_time = candidate.obs["dpt_pseudotime"]
rank_agreement = spearmanr(pseudotime, candidate_time).statistic
later_agreement = spearmanr(
results.loc[later, "stage_order"], candidate_time.loc[later]
).statistic
sensitivity.append({
"choice": label, "root": candidate_root,
"rank_agreement": rank_agreement,
"later_stage_agreement": later_agreement,
})
sensitivity = pd.DataFrame(sensitivity)
sensitivity.to_csv(output / "trajectory_sensitivity.csv", index=False)
print(sensitivity.to_string(index=False, float_format="%.3f"))
trajectory.write_h5ad(output / "trajectory_fit.h5ad")
choice root rank_agreement later_stage_agreement
15 neighbors PSA1_001 0.997 0.391
60 neighbors PSA1_001 0.998 0.393
central PS root PSA4_023 0.509 0.260

Root sensitivity belongs in the interpretation because the earliest sampled group contains heterogeneous cells. A reproducible barcode choice does not resolve that uncertainty. Additional time points, perturbations, or lineage tracing would test the proposed paths more directly than another expression embedding of these same cells.

Moignard and colleagues, 2015 describe the mouse embryo experiment and publish the single-cell qPCR measurements and experimental groups used here.

Haghverdi and colleagues, 2016 describe diffusion pseudotime and its use for expression trajectories.

Wolf, Angerer, and Theis, 2018 describe Scanpy, the Python toolkit for large-scale single-cell expression analysis.

Wolf and colleagues, 2019 describe PAGA and its abstraction of connectivity between cell partitions.

Traag, Waltman, and van Eck, 2019 describe the Leiden community detection algorithm used to form the expression partitions.

The Scanpy DPT documentation explains the root requirement and diffusion components. It recommends separate graph abstraction for branch analysis rather than forcing DPT to find a chosen branching count.

The PAGA documentation describes the connectivity estimate and its dependence on the supplied partitions. Read it before interpreting a plotted edge as evidence of a specific developmental path.

The dataset documentation identifies the normalized qPCR scale and experimental group labels. It helps distinguish this assay from the RNA-seq count examples elsewhere in the section.