cellrank.kernels.PrecomputedKernel#

class cellrank.kernels.PrecomputedKernel(object, adata=None, obsp_key=None, **kwargs)[source]#

Kernel which is initialized based on a precomputed transition matrix.

This kernel serves as CellRank’s interface with other methods that compute cell-cell transition matrices; you can use this kernel to input you own custom transition matrix and continue to use all CellRank functionality. In particular, you can use a percomputed kernel, just like any other kernel, to initialize an estimator and compute initial and terminal states, fate probabilities, and driver genes.

Parameters:
  • object (Union[str, bool, ndarray, spmatrix, AnnData, KernelExpression]) –

    Can be one of the following types:

    • anndata.AnnData - annotated data object.

    • scipy.sparse.spmatrix, numpy.ndarray - row-normalized transition matrix.

    • cellrank.kernels.KernelExpression - kernel expression.

    • str - key in anndata.AnnData.obsp where the transition matrix is stored. adata must be provided in this case.

    • bool - directionality of the transition matrix that will be used to infer its storage location. If None, the directionality will be determined automatically. adata must be provided in this case.

  • adata (anndata.AnnData) – Annotated data object. Must be provided when object is str or bool.

  • obsp_key (Optional[str]) – Key in anndata.AnnData.obsp where the transition matrix is stored. If None, it will be determined automatically. Only used when object is anndata.AnnData.

  • copy – Whether or not to copy the stored transition matrix.

  • backward – Hint whether this is a forward, backward or a unidirectional kernel. Only used when object is anndata.AnnData.

Notes

If object is anndata.AnnData and neither obsp_key nor backward is specified, default forward and backward are tried and first one is used.

Attributes table#

adata

Annotated data object.

backward

Direction of the process.

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#

compute_transition_matrix(*_, **__)

Do nothing and return self.

copy(*[, deep])

Return a copy of self.

from_adata(adata, key[, copy])

Read kernel object 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, ext])

Serialize self to a file.

write_to_adata([key, copy])

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

Attributes#

adata#

PrecomputedKernel.adata#

Annotated data object.

backward#

PrecomputedKernel.backward#

Direction of the process.

kernels#

PrecomputedKernel.kernels#

Underlying base kernels.

params#

PrecomputedKernel.params#

Parameters which are used to compute the transition matrix.

shape#

PrecomputedKernel.shape#

(n_cells, n_cells).

transition_matrix#

PrecomputedKernel.transition_matrix#

Row-normalized transition matrix.

Methods#

compute_transition_matrix#

PrecomputedKernel.compute_transition_matrix(*_, **__)[source]#

Do nothing and return self.

Return type:

PrecomputedKernel

copy#

PrecomputedKernel.copy(*, deep=False)#

Return a copy of self.

Return type:

Kernel

from_adata#

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

Read kernel object saved using write_to_adata().

Parameters:
Return type:

Kernel

Returns:

: The kernel with explicitly initialized properties:

plot_projection#

PrecomputedKernel.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:
Return type:

None

Returns:

: Nothing, just plots and modifies anndata.AnnData.obsm with a key based on key_added.

plot_random_walks#

PrecomputedKernel.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 (Union[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 (Optional[int]) – Random seed.

  • successive_hits (int) – Number of successive hits in the stop_ixs required to stop prematurely.

  • start_ixs (Union[Sequence[str], Mapping[str, Union[str, Sequence[str], Tuple[float, float]]], None]) –

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

    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 (Union[Sequence[str], Mapping[str, Union[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:

    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 anndata.AnnData.obsm to use as an embedding.

  • cmap (Union[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 (Optional[str]) – 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 (Optional[int]) – 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 joblib.Parallel for valid options.

  • figsize (Optional[Tuple[float, float]]) – Size of the figure.

  • dpi (Optional[int]) – Dots per inch.

  • save (Union[str, Path, None]) – Filename where to save the plot.

  • kwargs (Any) – Keyword arguments for scvelo.pl.scatter().

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#

PrecomputedKernel.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 anndata.AnnData.obs where clustering is stored.

  • time_key (str) – Key in anndata.AnnData.obs where experimental time is stored.

  • clusters (Optional[Sequence[Any]]) – Visualize flow only for these clusters. If None, use all clusters.

  • time_points (Optional[Sequence[Union[float, int]]]) – 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 (Optional[bool]) – Whether to sort the cluster by ascending or descending incoming flow. If None, use the order as in defined by clusters.

  • alpha (Optional[float]) – Alpha value for cell proportions.

  • xticks_step_size (Optional[int]) – Show only every other n-th tick on the x-axis. If None, don’t show any ticks.

  • legend_loc (Optional[str]) – Position of the legend. If None, do not show the legend.

  • figsize (Optional[Tuple[float, float]]) – Size of the figure.

  • dpi (Optional[int]) – Dots per inch.

  • save (Union[str, Path, None]) – Filename where to save the plot.

  • show (bool) – If False, return matplotlib.pyplot.Axes.

Return type:

Optional[Axes]

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 PrecomputedKernel.read(fname, adata=None, copy=False)#

De-serialize self from a file.

Parameters:
  • fname (Union[str, Path]) – Filename from which to read the object.

  • adata (Optional[AnnData]) – anndata.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 or not. If adata is a view, it is always copied.

Return type:

IOMixin

Returns:

: The de-serialized object.

write#

PrecomputedKernel.write(fname, write_adata=True, ext='pickle')#

Serialize self to a file.

Parameters:
  • fname (Union[str, Path]) – Filename where to save the object.

  • write_adata (bool) – Whether to save adata object or not, if present.

  • ext (Optional[str]) – Filename extension to use. If None, don’t append any extension.

Return type:

None

Returns:

: Nothing, just writes itself to a file using pickle.

write_to_adata#

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

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

Parameters:

key (Optional[str]) – Key used when writing transition matrix to adata. If None, the key will be determined automatically.

Return type:

None

Returns:

: Updates the adata with the following fields:

  • .obsp['{key}'] - the transition matrix.

  • .uns['{key}_params'] - parameters used for the calculation.