Plot random walks

This example shows how to plot random walks on a Markov chain in an embedding.

import cellrank as cr

adata = cr.datasets.pancreas_preprocessed("../example.h5ad")
adata

Out:

AnnData object with n_obs × n_vars = 2531 × 2000
    obs: 'day', 'proliferation', 'G2M_score', 'S_score', 'phase', 'clusters_coarse', 'clusters', 'clusters_fine', 'louvain_Alpha', 'louvain_Beta', 'initial_size_unspliced', 'initial_size_spliced', 'initial_size', 'n_counts', 'velocity_self_transition', 'dpt_pseudotime'
    var: 'highly_variable_genes', 'gene_count_corr', 'means', 'dispersions', 'dispersions_norm', 'fit_r2', 'fit_alpha', 'fit_beta', 'fit_gamma', 'fit_t_', 'fit_scaling', 'fit_std_u', 'fit_std_s', 'fit_likelihood', 'fit_u0', 'fit_s0', 'fit_pval_steady', 'fit_steady_u', 'fit_steady_s', 'fit_variance', 'fit_alignment_scaling', 'velocity_genes'
    uns: 'clusters_colors', 'clusters_fine_colors', 'diffmap_evals', 'iroot', 'louvain_Alpha_colors', 'louvain_Beta_colors', 'neighbors', 'pca', 'recover_dynamics', 'velocity_graph', 'velocity_graph_neg', 'velocity_params'
    obsm: 'X_diffmap', 'X_pca', 'X_umap', 'velocity_umap'
    varm: 'PCs', 'loss'
    layers: 'Ms', 'Mu', 'fit_t', 'fit_tau', 'fit_tau_', 'spliced', 'unspliced', 'velocity', 'velocity_u'
    obsp: 'connectivities', 'distances'

First, we create the kernel using the high-level function cellrank.tl.transition_matrix(), but any instance of cellrank.tl.kernels.Kernel would do.

k = cr.tl.transition_matrix(
    adata, weight_connectivities=0.2, softmax_scale=4, show_progress_bar=False
)
k

Out:

((0.8 * <VelocityKernel>) + (0.2 * <ConnectivityKernel>))

Next, we simulate and plot random walks. Below we simulate 100 random walks of length 100 where starting points are uniformly sampled from the Ngn3 low EP cluster.

k.plot_random_walks(
    100,
    start_ixs={"clusters": "Ngn3 low EP"},
    max_iter=100,
    show_progress_bar=False,
    ixs_legend_loc="best",
    seed=42,
)
clusters

Apart from start_ixs, we can also specify stop_ixs and successive_hits to control when random walks stop. Random walk is stopped if the maximum number of iterations is reached or when states in stop_ixs is visited successively successive_hits times.

k.plot_random_walks(
    100,
    start_ixs={"clusters": "Ngn3 low EP"},
    stop_ixs={"clusters": ["Alpha", "Beta"]},
    max_iter=100,
    successive_hits=5,
    show_progress_bar=False,
    cmap="viridis",
    seed=42,
)
clusters

Another way of visualizing the transition matrix is to project it onto an embedding, see Plot projection for more information.

Total running time of the script: ( 0 minutes 8.397 seconds)

Estimated memory usage: 304 MB

Gallery generated by Sphinx-Gallery