Skip to content

Trajectories

Palantir pseudotime, PAGA graph abstraction and gene trends.

Palantir orders cells along differentiation and gives each cell a fate probability per terminal state, PAGA abstracts the kNN graph into a cluster graph, and run_gene_trends fits a curve per gene along each Palantir branch. Start with run_paga to see the topology, then run_palantir with a start cell (and terminal states, if you know them), then run_gene_trends on its result. Trees over every cell live in bv.trees.

What lands where. Nothing. All three take a SingleCells, SingleCellsSubset or MetaCells, read the cached kNN graph (and obs, for the PAGA clusters) and return a frozen result keyed by cell id. To colour by pseudotime, join res.pseudotime onto obs on cell_id with sc.add_obs.

import polars as pl

bv.graph.find_clusters(sc, res=0.5, name="leiden_clusters")
paga = bv.traj.run_paga(sc, "leiden_clusters")

early_cell = sc.obs()["cell_id"][0]
res = bv.traj.run_palantir(sc, early_cell)
trends = bv.traj.run_gene_trends(sc, res, features=["gene_0001", "gene_0002"])

obs = sc.obs(cols=["cell_idx", "cell_id"], filtered=True)
sc.add_obs(
    obs.join(res.pseudotime, on="cell_id", how="left").select(
        "cell_idx", pl.col("pseudotime").alias("palantir_pseudotime")
    )
)

Gotchas. Run bv.pp.find_hvg, bv.pp.calculate_pca and bv.graph.find_neighbours first. A stale kNN raises; a missing one warns and run_palantir and run_paga return None. Palantir's start and terminal cells must be ids the kNN was built over. Without terminal states it detects them, and res.terminal_states names them by cell id. A disconnected kNN graph is patched with repair edges, counted in res.run_info. The kNN metric should be Euclidean or cosine, or Palantir warns. run_gene_trends needs features, or use_magic=True after bv.pp.run_magic on a SingleCells or subset (not on MetaCells). The Gaussian process defaults are prior-dominated, so shorten length_scale before believing a bump. The PAGA graphs are dense arrays, one row and column per cluster.

Worked through in Trajectory inference with Palantir and PAGA.

Palantir

Palantir pseudotime, PAGA graph abstraction and gene trends.

Palantir orders cells along differentiation and gives each cell a fate probability per terminal state, PAGA abstracts the kNN graph into a cluster graph, and run_gene_trends fits a curve per gene along each Palantir branch. Start with run_paga to see the topology, then run_palantir with a start cell (and terminal states, if you know them), then run_gene_trends on its result. Trees over every cell live in bv.trees.

What lands where. Nothing. All three take a SingleCells, SingleCellsSubset or MetaCells, read the cached kNN graph (and obs, for the PAGA clusters) and return a frozen result keyed by cell id. To colour by pseudotime, join res.pseudotime onto obs on cell_id with sc.add_obs.

import polars as pl

bv.graph.find_clusters(sc, res=0.5, name="leiden_clusters")
paga = bv.traj.run_paga(sc, "leiden_clusters")

early_cell = sc.obs()["cell_id"][0]
res = bv.traj.run_palantir(sc, early_cell)
trends = bv.traj.run_gene_trends(sc, res, features=["gene_0001", "gene_0002"])

obs = sc.obs(cols=["cell_idx", "cell_id"], filtered=True)
sc.add_obs(
    obs.join(res.pseudotime, on="cell_id", how="left").select(
        "cell_idx", pl.col("pseudotime").alias("palantir_pseudotime")
    )
)

Gotchas. Run bv.pp.find_hvg, bv.pp.calculate_pca and bv.graph.find_neighbours first. A stale kNN raises; a missing one warns and run_palantir and run_paga return None. Palantir's start and terminal cells must be ids the kNN was built over. Without terminal states it detects them, and res.terminal_states names them by cell id. A disconnected kNN graph is patched with repair edges, counted in res.run_info. The kNN metric should be Euclidean or cosine, or Palantir warns. run_gene_trends needs features, or use_magic=True after bv.pp.run_magic on a SingleCells or subset (not on MetaCells). The Gaussian process defaults are prior-dominated, so shorten length_scale before believing a bump. The PAGA graphs are dense arrays, one row and column per cluster.

PalantirRes dataclass

PalantirRes(
    pseudotime: DataFrame,
    branch_probs: DataFrame,
    terminal_states: dict[str, str],
    waypoints: tuple[str, ...],
    start_cell: str,
    multiscale: DataFrame,
    run_info: dict[str, object],
)

A Palantir run.

Attributes:

Name Type Description
pseudotime DataFrame

cell_id, pseudotime (min-max scaled to [0, 1]; the start cell is not pinned to 0) and entropy per cell.

branch_probs DataFrame

cell_id and one column per terminal state with the fate probabilities. Rows need not sum to one, as sub-threshold values are zeroed without renormalisation.

terminal_states dict[str, str]

Branch name to terminal state cell id, in the column order of branch_probs. The name is the caller's label, or the cell id itself for unlabelled or detected states.

waypoints tuple[str, ...]

The waypoint cell ids; the first is the start cell.

start_cell str

The start cell actually used.

multiscale DataFrame

cell_id and the multiscale diffusion components MS_1, MS_2, ...

run_info dict[str, object]

iterations, converged, eigen_converged, eigen_residual, repair_edges, stranded_waypoints, n_waypoints and modality. An eigen_converged of False means the diffusion eigensolve ran out of restarts.

branches property

branches: list[str]

The branch names, the fate columns of branch_probs.

run_palantir

run_palantir(
    sc: ScOrMc,
    early_cell: str,
    *,
    terminal_states: Sequence[str]
    | dict[str, str]
    | None = None,
    modality: Modality = "rna",
    palantir_params: PalantirParams | None = None,
    seed: int = 42,
    verbose: Verbose = True,
) -> PalantirRes | None

Palantir trajectory inference over the cached kNN graph.

Models differentiation as a Markov chain over a diffusion map of the cells: a pseudotime per cell, the probability of each cell reaching each terminal state, and the differentiation entropy of those probabilities. The kNN graph feeds the diffusion kernel; the geodesics are measured over a second kNN graph built on the multiscale space, sized by palantir_params.knn.

Parameters:

Name Type Description Default
sc ScOrMc

The experiment, a subset or meta cells, with the kNN.

required
early_cell str

Id of the start cell, one the kNN was built over.

required
terminal_states Sequence[str] | dict[str, str] | None

Terminal state cell ids, or label to cell id, the labels then naming the branch_probs columns. None detects them from the waypoint Markov chain.

None
modality Modality

The kNN graph: "rna", or "adt" / "atac" / "wnn" on a SingleCellsMultiModal.

'rna'
palantir_params PalantirParams | None

The parameters. None uses the defaults.

None
seed int

Seed for the eigensolver, the waypoints and the multiscale kNN.

42
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
PalantirRes | None

The PalantirRes, or None with a warning if there is no kNN.

Raises:

Type Description
ValueError

On a stale kNN, a non-RNA modality without a multi-modal object, or a cell not in the kNN graph.

References

Setty, et al., Nat. Biotechnol., 2019.

Examples:

>>> early_cell = "cell_0001"
>>> res = bv.traj.run_palantir(sc, early_cell)
>>> params = bv.params.PalantirParams(n_eigs=10, knn=30)
>>> res = bv.traj.run_palantir(sc, early_cell, palantir_params=params)
>>> ends = {"branch_a": "cell_0100", "branch_b": "cell_0200"}
>>> res = bv.traj.run_palantir(sc, early_cell, terminal_states=ends)

PAGA

Palantir pseudotime, PAGA graph abstraction and gene trends.

Palantir orders cells along differentiation and gives each cell a fate probability per terminal state, PAGA abstracts the kNN graph into a cluster graph, and run_gene_trends fits a curve per gene along each Palantir branch. Start with run_paga to see the topology, then run_palantir with a start cell (and terminal states, if you know them), then run_gene_trends on its result. Trees over every cell live in bv.trees.

What lands where. Nothing. All three take a SingleCells, SingleCellsSubset or MetaCells, read the cached kNN graph (and obs, for the PAGA clusters) and return a frozen result keyed by cell id. To colour by pseudotime, join res.pseudotime onto obs on cell_id with sc.add_obs.

import polars as pl

bv.graph.find_clusters(sc, res=0.5, name="leiden_clusters")
paga = bv.traj.run_paga(sc, "leiden_clusters")

early_cell = sc.obs()["cell_id"][0]
res = bv.traj.run_palantir(sc, early_cell)
trends = bv.traj.run_gene_trends(sc, res, features=["gene_0001", "gene_0002"])

obs = sc.obs(cols=["cell_idx", "cell_id"], filtered=True)
sc.add_obs(
    obs.join(res.pseudotime, on="cell_id", how="left").select(
        "cell_idx", pl.col("pseudotime").alias("palantir_pseudotime")
    )
)

Gotchas. Run bv.pp.find_hvg, bv.pp.calculate_pca and bv.graph.find_neighbours first. A stale kNN raises; a missing one warns and run_palantir and run_paga return None. Palantir's start and terminal cells must be ids the kNN was built over. Without terminal states it detects them, and res.terminal_states names them by cell id. A disconnected kNN graph is patched with repair edges, counted in res.run_info. The kNN metric should be Euclidean or cosine, or Palantir warns. run_gene_trends needs features, or use_magic=True after bv.pp.run_magic on a SingleCells or subset (not on MetaCells). The Gaussian process defaults are prior-dominated, so shorten length_scale before believing a bump. The PAGA graphs are dense arrays, one row and column per cluster.

PagaRes dataclass

PagaRes(
    connectivities: ndarray,
    connectivities_tree: ndarray,
    clusters: tuple[str, ...],
    sizes: DataFrame,
    params: dict[str, str],
)

A PAGA graph abstraction.

Attributes:

Name Type Description
connectivities ndarray

(n_clusters, n_clusters) float64, symmetric with a zero diagonal, values in (0, 1] on the edges.

connectivities_tree ndarray

The maximum spanning forest of connectivities, carrying its values on the retained edges.

clusters tuple[str, ...]

The cluster levels, the rows and columns of both graphs.

sizes DataFrame

cluster and n_cells.

params dict[str, str]

cluster_col and modality.

run_paga

run_paga(
    sc: ScOrMc,
    cluster_col: str,
    *,
    modality: Modality = "rna",
    verbose: Verbose = True,
) -> PagaRes | None

PAGA graph abstraction of the cached kNN graph.

Abstracts the kNN graph into a cluster graph whose edge weights measure how much more two clusters connect than a random null model expects, plus its maximum spanning forest. Only the kNN indices are read.

Parameters:

Name Type Description Default
sc ScOrMc

The experiment, a subset or meta cells, with the kNN and a clustering.

required
cluster_col str

obs column with the clusters. Empty levels of an Enum are kept; other columns are sorted into levels.

required
modality Modality

The kNN graph: "rna", or "adt" / "atac" / "wnn" on a SingleCellsMultiModal.

'rna'
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
PagaRes | None

The PagaRes, or None with a warning if there is no kNN.

Raises:

Type Description
ValueError

On a stale kNN, a non-RNA modality without a multi-modal object, a missing column or missing cluster labels.

References

Wolf, et al., Genome Biol., 2019.

Examples:

>>> bv.graph.find_clusters(sc, res=0.5, name="leiden_clusters")
>>> paga = bv.traj.run_paga(sc, "leiden_clusters")
>>> tree = paga.connectivities_tree

Palantir pseudotime, PAGA graph abstraction and gene trends.

Palantir orders cells along differentiation and gives each cell a fate probability per terminal state, PAGA abstracts the kNN graph into a cluster graph, and run_gene_trends fits a curve per gene along each Palantir branch. Start with run_paga to see the topology, then run_palantir with a start cell (and terminal states, if you know them), then run_gene_trends on its result. Trees over every cell live in bv.trees.

What lands where. Nothing. All three take a SingleCells, SingleCellsSubset or MetaCells, read the cached kNN graph (and obs, for the PAGA clusters) and return a frozen result keyed by cell id. To colour by pseudotime, join res.pseudotime onto obs on cell_id with sc.add_obs.

import polars as pl

bv.graph.find_clusters(sc, res=0.5, name="leiden_clusters")
paga = bv.traj.run_paga(sc, "leiden_clusters")

early_cell = sc.obs()["cell_id"][0]
res = bv.traj.run_palantir(sc, early_cell)
trends = bv.traj.run_gene_trends(sc, res, features=["gene_0001", "gene_0002"])

obs = sc.obs(cols=["cell_idx", "cell_id"], filtered=True)
sc.add_obs(
    obs.join(res.pseudotime, on="cell_id", how="left").select(
        "cell_idx", pl.col("pseudotime").alias("palantir_pseudotime")
    )
)

Gotchas. Run bv.pp.find_hvg, bv.pp.calculate_pca and bv.graph.find_neighbours first. A stale kNN raises; a missing one warns and run_palantir and run_paga return None. Palantir's start and terminal cells must be ids the kNN was built over. Without terminal states it detects them, and res.terminal_states names them by cell id. A disconnected kNN graph is patched with repair edges, counted in res.run_info. The kNN metric should be Euclidean or cosine, or Palantir warns. run_gene_trends needs features, or use_magic=True after bv.pp.run_magic on a SingleCells or subset (not on MetaCells). The Gaussian process defaults are prior-dominated, so shorten length_scale before believing a bump. The PAGA graphs are dense arrays, one row and column per cluster.

GeneTrendsRes dataclass

GeneTrendsRes(
    trends: DataFrame,
    branch_cells: dict[str, tuple[str, ...]],
    branches: tuple[str, ...],
    params: dict[str, object],
    run_info: dict[str, object],
)

Gene trends along the Palantir branches.

Attributes:

Name Type Description
trends DataFrame

Long frame with branch and gene (Enums in branch and feature order), pseudotime and expression, one row per grid point, gene and branch.

branch_cells dict[str, tuple[str, ...]]

Branch name to the cell ids selected for it.

branches tuple[str, ...]

The branch names, the fate columns of the Palantir result.

params dict[str, object]

use_magic, branch_params and gene_trend_params.

run_info dict[str, object]

n_cells and jitter_used per branch, and the grid resolution.

run_gene_trends(
    sc: ScOrMc,
    palantir_res: PalantirRes,
    *,
    features: Sequence[str] | None = None,
    use_magic: bool = False,
    branch_params: BranchSelectionParams | None = None,
    gene_trend_params: GeneTrendsParams | None = None,
    verbose: Verbose = True,
) -> GeneTrendsRes

Gene trends over the Palantir pseudotime.

Assigns cells to branches from their fate probabilities, then fits a landmark Gaussian process with a Matern-5/2 kernel per branch, the Mellon-based estimator of the reference. One smooth curve per gene and branch on a common grid.

The defaults are prior-dominated: the pseudotime spans [0, 1], so a length_scale of 1 covers the whole domain. Shorten it before believing a bump.

Parameters:

Name Type Description Default
sc ScOrMc

The experiment, a subset or meta cells, the one Palantir ran on.

required
palantir_res PalantirRes

The run_palantir result over the same cells.

required
features Sequence[str] | None

Gene ids to fit. None takes every gene of the imputed layer, so needs use_magic. Unknown ids warn and drop.

None
use_magic bool

Fit the MAGIC imputed layer instead of the normalised counts; SingleCells and SingleCellsSubset only.

False
branch_params BranchSelectionParams | None

Branch cell selection. None uses the defaults.

None
gene_trend_params GeneTrendsParams | None

The Gaussian process. None uses the defaults.

None
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
GeneTrendsRes

The GeneTrendsRes.

Raises:

Type Description
ValueError

If features is missing without MAGIC, the Palantir result does not cover the cells, or the imputed layer is unusable.

References

Setty, et al., Nat. Biotechnol., 2019.

Examples:

>>> genes = ["gene_0001", "gene_0002"]
>>> res = bv.traj.run_palantir(sc, "cell_0001")
>>> trends = bv.traj.run_gene_trends(sc, res, features=genes)
>>> bv.pp.run_magic(sc, genes)
>>> trends = bv.traj.run_gene_trends(sc, res, use_magic=True)