cellrank.kernels.ConnectivityKernel#

class cellrank.kernels.ConnectivityKernel(adata, conn_key='connectivities', check_connectivity=False)[source]#

Kernel which computes transition probabilities based on similarities among cells.

As a measure of similarity, we currently support:

The resulting transition matrix is symmetric and thus cannot be used to learn about the direction of the biological process. To include this direction, consider combining with a velocity-derived transition matrix via VelocityKernel.

Optionally, we apply a density correction as described in [Coifman et al., 2005], where we use the implementation of [Haghverdi et al., 2016].

Parameters:
adata AnnData

Annotated data object.

conn_key str

Key in obsp where connectivity matrix describing cell-cell similarity is stored.

check_connectivity bool

Check whether the underlying kNN graph is connected.

Attributes table#

adata

Annotated data object.

backward

None.

connectivities

Underlying connectivity matrix.

kernels

Underlying base kernels.

params

Parameters which are used to compute the transition matrix.

shape

(n_cells, n_cells).

transition_matrix

Row-normalized transition matrix.

Methods table#

cbc(source, target, cluster_key, rep[, ...])

Compute cross-boundary correctness score between source and target cluster.

compute_transition_matrix([density_normalize])

Compute transition matrix based on transcriptomic similarity.

copy(*[, deep])

Return a copy of self.

from_adata(adata, key[, copy])

Read the kernel saved using write_to_adata().

plot_projection([basis, key_added, ...])

Plot transition_matrix as a stream or a grid plot.

plot_random_walks([n_sims, max_iter, seed, ...])

Plot random walks in an embedding.

plot_single_flow(cluster, cluster_key, time_key)

Visualize outgoing flow from a cluster of cells [Mittnenzweig et al., 2021].

read(fname[, adata, copy])

De-serialize self from a file.

write(fname[, write_adata])

Serialize self to a file using pickle.

write_to_adata([key, copy])

Write the transition matrix and parameters used for computation to the underlying adata object.

Attributes#

adata#

ConnectivityKernel.adata#

Annotated data object.

backward#

ConnectivityKernel.backward#

None.

connectivities#

ConnectivityKernel.connectivities#

Underlying connectivity matrix.

kernels#

ConnectivityKernel.kernels#

Underlying base kernels.

params#

ConnectivityKernel.params#

Parameters which are used to compute the transition matrix.

shape#

ConnectivityKernel.shape#

(n_cells, n_cells).

transition_matrix#

ConnectivityKernel.transition_matrix#

Row-normalized transition matrix.

Methods#

cbc#

ConnectivityKernel.cbc(source, target, cluster_key, rep, graph_key='distances')#

Compute cross-boundary correctness score between source and target cluster.

Parameters:
source str

Name of the source cluster.

target str

Name of the target cluster.

cluster_key str

Key in obs to obtain cluster annotations.

rep str

Key in obsm to use as data representation.

graph_key str

Name of graph representation to use from obsp.

Return type:

ndarray

Returns:

Cross-boundary correctness score for each observation.

compute_transition_matrix#

ConnectivityKernel.compute_transition_matrix(density_normalize=True)[source]#

Compute transition matrix based on transcriptomic similarity.

Uses symmetric, weighted kNN graph to compute symmetric transition matrix. The connectivities are computed using neighbors(). Depending on the parameters used there, they can be UMAP connectivities or Gaussian-kernel-based connectivities with adaptive kernel width.

Parameters:
density_normalize bool

Whether to use the underlying kNN graph for density normalization.

Return type:

ConnectivityKernel

Returns:

Returns self and updates transition_matrix and params.

copy#

ConnectivityKernel.copy(*, deep=False)#

Return a copy of self.

Parameters:
deep bool

Whether to use deepcopy().

Return type:

Kernel

Returns:

Copy of self.

from_adata#

classmethod ConnectivityKernel.from_adata(adata, key, copy=False)#

Read the kernel saved using write_to_adata().

Parameters:
adata AnnData

Annotated data object.

key str

Key in obsp where the transition matrix is stored. The parameters should be stored in adata.uns['{key}_params'].

copy bool

Whether to copy the transition matrix.

Return type:

Kernel

Returns:

The kernel with explicitly initialized properties:

plot_projection#

ConnectivityKernel.plot_projection(basis='umap', key_added=None, recompute=False, stream=True, connectivities=None, **kwargs)#

Plot transition_matrix as a stream or a grid plot.

Parameters:
basis str

Key in obsm containing the basis.

key_added str | None

If not None, save the result to adata.obsm['{key_added}']. Otherwise, save the result to 'T_fwd_{basis}' or 'T_bwd_{basis}', depending on the direction.

recompute bool

Whether to recompute the projection if it already exists.

stream bool

If True, use velocity_embedding_stream(). Otherwise, use velocity_embedding_grid().

connectivities spmatrix | None

Connectivity matrix to use for projection. If None, use ones from the underlying kernel, is possible.

kwargs Any

Keyword argument for the above-mentioned plotting function. To save the figure, either pass save='<name>.pdf' (forwarded to scvelo, which writes to its figdir directory, by default './figures/'), or pass show=False and use savefig():

import matplotlib.pyplot as plt

kernel.plot_projection(basis="umap", show=False)
plt.savefig("projection.pdf", bbox_inches="tight")

Return type:

None

Returns:

Nothing, just plots and modifies obsm with a key based on the key_added.

plot_random_walks#

ConnectivityKernel.plot_random_walks(n_sims=100, max_iter=0.25, seed=None, successive_hits=0, start_ixs=None, stop_ixs=None, basis='umap', cmap='gnuplot', linewidth=1.0, linealpha=0.3, ixs_legend_loc=None, n_jobs=None, backend='loky', show_progress_bar=True, figsize=None, dpi=None, save=None, **kwargs)#

Plot random walks in an embedding.

This method simulates random walks on the Markov chain defined though the corresponding transition matrix. The method is intended to give qualitative rather than quantitative insights into the transition matrix. Random walks are simulated by iteratively choosing the next cell based on the current cell’s transition probabilities.

Parameters:
n_sims int

Number of random walks to simulate.

max_iter int | float

Maximum number of steps of a random walk. If a float, it can be specified as a fraction of the number of cells.

seed int | None

Random seed.

successive_hits int

Number of successive hits in the stop_ixs required to stop prematurely.

start_ixs Sequence[str] | Mapping[str, str | Sequence[str] | tuple[float, float]] | None

Cells from which to sample the starting points. If None, use all cells. Can be specified as:

  • dict - dictionary with 1 key in obs with values corresponding to either 1 or more clusters (if the column is categorical) or a tuple specifying \([min, max]\) interval from which to select the indices.

  • Sequence - sequence of cell ids in obs_names.

For example {'dpt_pseudotime': [0, 0.1]} means that starting points for random walks will be sampled uniformly from cells whose pseudotime is in \([0, 0.1]\).

stop_ixs Sequence[str] | Mapping[str, str | Sequence[str] | tuple[float, float]] | None

Cells which when hit, the random walk is terminated. If None, terminate after max_iters. Can be specified as:

  • dict - dictionary with 1 key in obs with values corresponding to either 1 or more clusters (if the column is categorical) or a tuple specifying \([min, max]\) interval from which to select the indices.

  • Sequence - sequence of cell ids in obs_names.

For example {'clusters': ['Alpha', 'Beta']} and successive_hits = 3 means that the random walk will stop prematurely after cells in the above specified clusters have been visited successively 3 times in a row.

basis str

Basis in obsm to use as an embedding.

cmap str | LinearSegmentedColormap

Colormap for the random walk lines.

linewidth float

Width of the random walk lines.

linealpha float

Alpha value of the random walk lines.

ixs_legend_loc str | None

Legend location for the start/top indices.

show_progress_bar bool

Whether to show a progress bar. Disabling it may slightly improve performance.

n_jobs int | None

Number of parallel jobs. If -1, use all available cores. If None or 1, the execution is sequential.

backend str

Which backend to use for parallelization. See Parallel for valid options.

figsize tuple[float, float] | None

Size of the figure.

dpi int | None

Dots per inch.

save str | Path | None

Filename where to save the plot.

kwargs Any

Keyword arguments for embedding().

Return type:

None

Returns:

Nothing, just plots the figure. Optionally saves it based on save. For each random walk, the first/last cell is marked by the start/end colors of cmap.

plot_single_flow#

ConnectivityKernel.plot_single_flow(cluster, cluster_key, time_key, clusters=None, time_points=None, min_flow=0, remove_empty_clusters=True, ascending=False, legend_loc='upper right out', alpha=0.8, xticks_step_size=1, figsize=None, dpi=None, save=None, show=True)#

Visualize outgoing flow from a cluster of cells [Mittnenzweig et al., 2021].

Parameters:
cluster str

Cluster for which to visualize outgoing flow.

cluster_key str

Key in obs where clustering is stored.

time_key str

Key in obs where experimental time is stored.

clusters Sequence[Any] | None

Visualize flow only for these clusters. If None, use all clusters.

time_points Sequence[int | float] | None

Visualize flow only for these time points. If None, use all time points.

min_flow float

Only show flow edges with flow greater than this value. Flow values are always in \([0, 1]\).

remove_empty_clusters bool

Whether to remove clusters with no incoming flow edges.

ascending bool | None

Whether to sort the cluster by ascending or descending incoming flow. If None, use the order as in defined by clusters.

alpha float | None

Alpha value for cell proportions.

xticks_step_size int | None

Show only every other n-th tick on the x-axis. If None, don’t show any ticks.

legend_loc str | None

Position of the legend. If None, do not show the legend.

figsize tuple[float, float] | None

Size of the figure.

dpi int | None

Dots per inch.

figsize

Size of the figure.

dpi

Dots per inch.

save str | Path | None

Filename where to save the plot.

show bool

If False, return Axes.

Return type:

Axes | None

Returns:

The axes object, if show = False. Nothing, just plots the figure. Optionally saves it based on save.

Notes

This function is a Python re-implementation of the following original R function with some minor stylistic differences. This function will not recreate the results from [Mittnenzweig et al., 2021], because there, the Metacell model [Baran et al., 2019] was used to compute the flow, whereas here the transition matrix is used.

read#

static ConnectivityKernel.read(fname, adata=None, copy=False)#

De-serialize self from a file.

Parameters:
fname str | Path

Path from which to read the object.

adata AnnData | None

AnnData object to assign to the saved object. Only used when the saved object has adata and it was saved without it.

copy bool

Whether to copy adata before assigning it. If adata is a view, it is always copied.

Return type:

IOMixin

Returns:

The de-serialized object.

write#

ConnectivityKernel.write(fname, write_adata=True)#

Serialize self to a file using pickle.

Parameters:
fname str | Path

Path where to save the object.

write_adata bool

Whether to save adata object.

Return type:

None

Returns:

Nothing, just writes itself to a file.

write_to_adata#

ConnectivityKernel.write_to_adata(key=None, copy=False)#

Write the transition matrix and parameters used for computation to the underlying adata object.

Parameters:
key str | None

Key used when writing transition matrix to adata. If None, the key will be determined automatically.

copy bool

Whether to copy the transition_matrix.

Return type:

None

Returns:

Updates the adata with the following fields: