comflow 0.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,794 @@
1
+ from typing import Optional, Union
2
+ import ot
3
+ import sys
4
+ import anndata
5
+ import numpy as np
6
+ import pandas as pd
7
+ import scanpy as sc
8
+ from matplotlib import cm
9
+ import matplotlib.pyplot as plt
10
+ import matplotlib as mpl
11
+ from matplotlib.lines import Line2D
12
+ import plotly
13
+ import seaborn as sns
14
+ from scipy import sparse
15
+ from scipy.spatial import distance_matrix
16
+ from scipy.stats import spearmanr, pearsonr
17
+ from sklearn.preprocessing import normalize
18
+ from sklearn.decomposition import PCA
19
+
20
+ from .._utils import plot_cluster_signaling_chord
21
+ from .._utils import plot_cluster_signaling_network
22
+ from .._utils import plot_cluster_signaling_network_multipair
23
+ from .._utils import plot_cell_signaling
24
+ from .._utils import plot_cell_signaling_compare
25
+ from .._utils import get_cmap_qualitative
26
+ from .._utils import leiden_clustering
27
+
28
+ def plot_cell_communication(
29
+ adata: anndata.AnnData,
30
+ database_name: str = None,
31
+ pathway_name: str = None,
32
+ lr_pair = None,
33
+ keys = None,
34
+ plot_method: str = "cell",
35
+ background: str = "summary",
36
+ background_legend: bool=False,
37
+ clustering: str = None,
38
+ summary: str = "sender",
39
+ cmap: str = "coolwarm",
40
+ cluster_cmap: dict = None,
41
+ pos_idx: np.ndarray = np.array([0,1],int),
42
+ ndsize: float = 1,
43
+ scale: float = 1.0,
44
+ normalize_v: bool = False,
45
+ normalize_v_quantile: float = 0.95,
46
+ arrow_color: str = "#333333",
47
+ grid_density: float = 1.0,
48
+ grid_knn: int = None,
49
+ grid_scale: float = 1.0,
50
+ grid_thresh: float = 1.0,
51
+ grid_width: float = 0.005,
52
+ stream_density: float = 1.0,
53
+ stream_linewidth: float = 1,
54
+ stream_cutoff_perc: float = 5,
55
+ filename: str = None,
56
+ ax: Optional[mpl.axes.Axes] = None
57
+ ):
58
+ """
59
+ Plot spatial directions of cell-cell communication.
60
+
61
+ .. image:: cell_communication.png
62
+ :width: 500pt
63
+
64
+ The cell-cell communication should have been computed by the function :func:`commot.tl.spatial_communication`.
65
+ The cell-cell communication direction should have been computed by the function :func:`commot.tl.communication_direction`.
66
+
67
+ Parameters
68
+ ----------
69
+ adata
70
+ The data matrix of shape ``n_obs`` × ``n_var``.
71
+ Rows correspond to cells or positions and columns to genes.
72
+ database_name
73
+ Name of the ligand-receptor interaction database.
74
+ pathway_name
75
+ Name of the signaling pathway to be plotted. Will be used only when ``lr_pair`` and ``keys`` are None.
76
+ If none of ``pathway_name``, ``lr_pair``, and ``keys`` are given, the total signaling through all pairs will be plotted.
77
+ lr_pair
78
+ A tuple of ligand name and receptor name. If given, ``pathway_name`` will be ignored. Will be ignored if ``keys`` is given.
79
+ keys
80
+ A list of keys for example 'ligA-recA' for a LR pair or 'pathwayX' for a signaling pathway 'pathwayX'.
81
+ If given, pathway_name and lr_pair will be ignored.
82
+ If more than one is given, the average will be plotted.
83
+ plot_method
84
+ 'cell' plot vectors on individual cells.
85
+ 'grid' plot interpolated vectors on regular grids.
86
+ 'stream' streamline plot.
87
+ background
88
+ 'summary': scatter plot with color representing total sent or received signal.
89
+ 'image': the image in Visium data.
90
+ 'cluster': scatter plot with color representing cell clusters.
91
+ background_legend
92
+ Whether to include the background legend when background is set to `summary` or `cluster`.
93
+ clustering
94
+ The key for clustering result. Needed if background is set to `cluster`.
95
+ For example, if ``clustering=='leiden'``, the clustering result should be available in ``.obs['leiden']``.
96
+ summary
97
+ If background is set to 'summary', the numerical value to plot for background.
98
+ 'sender': node color represents sender weight.
99
+ 'receiver': node color represents receiver weight.
100
+ cmap
101
+ matplotlib colormap name for node summary if numerical (background set to 'summary'), e.g., 'coolwarm'.
102
+ plotly colormap name for node color if summary is (background set to 'cluster'). e.g., 'Alphabet'.
103
+ cluster_cmap
104
+ A dictionary that maps cluster names to colors when setting background to 'cluster'. If given, ``cmap`` will be ignored.
105
+ pos_idx
106
+ The coordinates to use for plotting (2D plot).
107
+ ndsize
108
+ The node size of the spots.
109
+ scale
110
+ The scale parameter passed to the matplotlib quiver function :func:`matplotlib.pyplot.quiver` for vector field plots.
111
+ The smaller the value, the longer the arrows.
112
+ normalize_v
113
+ Whether the normalize the vector field to uniform lengths to highlight the directions without showing magnitudes.
114
+ normalize_v_quantile
115
+ The vector length quantile to use to normalize the vector field.
116
+ arrow_color
117
+ The color of the arrows.
118
+ grid_density
119
+ The density of grid if ``plot_method=='grid'``.
120
+ grid_knn
121
+ If ``plot_method=='grid'``, the number of nearest neighbors to interpolate the signaling directions from spots to grid points.
122
+ grid_scale
123
+ The scale parameter (relative to grid size) for the kernel function of mapping directions of spots to grid points.
124
+ grid_thresh
125
+ The threshold of interpolation weights determining whether to include a grid point. A smaller value gives a tighter cover of the tissue by the grid points.
126
+ grid_width
127
+ The value passed to the ``width`` parameter of the function :func:`matplotlib.pyplot.quiver` when ``plot_method=='grid'``.
128
+ stream_density
129
+ The density of stream lines passed to the ``density`` parameter of the function :func:`matplotlib.pyplot.streamplot` when ``plot_method=='stream'``.
130
+ stream_linewidth
131
+ The width of stream lines passed to the ``linewidth`` parameter of the function :func:`matplotlib.pyplot.streamplot` when ``plot_method=='stream'``.
132
+ stream_cutoff_perc
133
+ The quantile cutoff to ignore the weak vectors. Default to 5 that the vectors shorter than the 5% quantile will not be plotted.
134
+ filename
135
+ If given, save to the filename. For example 'ccc_direction.pdf'.
136
+ ax
137
+ An existing matplotlib ax (`matplotlib.axis.Axis`).
138
+
139
+ Returns
140
+ -------
141
+ ax : matplotlib.axis.Axis
142
+ The matplotlib ax object of the plot.
143
+
144
+ """
145
+
146
+ if not keys is None:
147
+ ncell = adata.shape[0]
148
+ V = np.zeros([ncell, 2], float)
149
+ signal_sum = np.zeros([ncell], float)
150
+ for key in keys:
151
+ if summary == 'sender':
152
+ V = V + adata.obsm['commot_sender_vf-'+database_name+'-'+key][:,pos_idx]
153
+ signal_sum = signal_sum + adata.obsm['commot-'+database_name+"-sum-sender"]['s-'+key]
154
+ elif summary == 'receiver':
155
+ V = V + adata.obsm['commot_receiver_vf-'+database_name+'-'+key][:,pos_idx]
156
+ signal_sum = signal_sum + adata.obsm['commot-'+database_name+"-sum-receiver"]['r-'+key]
157
+ V = V / float( len( keys ) )
158
+ signal_sum = signal_sum / float( len( keys ) )
159
+ elif keys is None:
160
+ if not lr_pair is None:
161
+ vf_name = database_name+'-'+lr_pair[0]+'-'+lr_pair[1]
162
+ sum_name = lr_pair[0]+'-'+lr_pair[1]
163
+ elif not pathway_name is None:
164
+ vf_name = database_name+'-'+pathway_name
165
+ sum_name = pathway_name
166
+ else:
167
+ vf_name = database_name+'-total-total'
168
+ sum_name = 'total-total'
169
+ if summary == 'sender':
170
+ V = adata.obsm['commot_sender_vf-'+vf_name][:,pos_idx]
171
+ signal_sum = adata.obsm['commot-'+database_name+"-sum-sender"]['s-'+sum_name]
172
+ elif summary == 'receiver':
173
+ V = adata.obsm['commot_receiver_vf-'+vf_name][:,pos_idx]
174
+ signal_sum = adata.obsm['commot-'+database_name+"-sum-receiver"]['r-'+sum_name]
175
+
176
+ if background=='cluster' and not cmap in ['Plotly','Light24','Dark24','Alphabet']:
177
+ cmap='Alphabet'
178
+ if ax is None:
179
+ fig, ax = plt.subplots()
180
+ if normalize_v:
181
+ V = V / np.quantile(np.linalg.norm(V, axis=1), normalize_v_quantile)
182
+ plot_cell_signaling(
183
+ adata.obsm["spatial"][:,pos_idx],
184
+ V,
185
+ signal_sum,
186
+ cmap = cmap,
187
+ cluster_cmap = cluster_cmap,
188
+ plot_method = plot_method,
189
+ background = background,
190
+ clustering = clustering,
191
+ background_legend = background_legend,
192
+ adata = adata,
193
+ summary = summary,
194
+ scale = scale,
195
+ ndsize = ndsize,
196
+ filename = filename,
197
+ arrow_color = arrow_color,
198
+ grid_density = grid_density,
199
+ grid_knn = grid_knn,
200
+ grid_scale = grid_scale,
201
+ grid_thresh = grid_thresh,
202
+ grid_width = grid_width,
203
+ stream_density = stream_density,
204
+ stream_linewidth = stream_linewidth,
205
+ stream_cutoff_perc = stream_cutoff_perc,
206
+ ax = ax,
207
+ # fig = fig,
208
+ )
209
+ return ax
210
+
211
+ def plot_cluster_communication_network(
212
+ adata: anndata.AnnData,
213
+ uns_names: list = None,
214
+ clustering: str = None,
215
+ quantile_cutoff: float = 0.99,
216
+ p_value_cutoff: float = 0.05,
217
+ self_communication_off: bool = False,
218
+ filename: str = None,
219
+ nx_node_size: float = 0.2,
220
+ nx_node_cmap: str = "Plotly",
221
+ nx_node_cluster_cmap: dict = None,
222
+ nx_pos_idx: np.ndarray = np.array([0,1],int),
223
+ nx_node_pos: str = "cluster",
224
+ nx_edge_width_lb_quantile: float = 0.05,
225
+ nx_edge_width_ub_quantile: float = 0.95,
226
+ nx_edge_width_min: float = 1,
227
+ nx_edge_width_max: float = 4,
228
+ nx_edge_color: Union[str, np.ndarray] = "node",
229
+ nx_edge_colormap = cm.Greys,
230
+ nx_bg_pos: bool = True,
231
+ nx_bg_color: str = "lavender",
232
+ nx_bg_ndsize: float = 0.05,
233
+ ):
234
+ """
235
+ Plot cluster-cluster communication as network.
236
+
237
+ .. image:: cluster_communication.png
238
+ :width: 500pt
239
+
240
+
241
+ Parameters
242
+ ----------
243
+ adata
244
+ The data matrix of shape ``n_obs`` × ``n_var``.
245
+ Rows correspond to cells or positions and columns to genes.
246
+ uns_names
247
+ A list of keys for the cluster-level CCC stored in ``.uns`` data slot.
248
+ When more than one is given, the average score will be used.
249
+ For example, ``'commot_cluster-leiden-cellchat-Fgf7-Fgfr1'`` will plot the CCC inferred
250
+ with 'cellchat' LR database through 'Fgf7-Fgfr1' LR pair and for clustering stored in ``.obs['leiden']``.
251
+ clustering
252
+ Name of the clustering. The cluster labels should be available in ``.obs[clustering]``.
253
+ quantile_cutoff
254
+ The quantile cutoff for including an edge. Set to 1 to disable this criterion.
255
+ The quantile_cutoff and p_value_cutoff works in the "or" logic to avoid missing
256
+ significant signaling connections.
257
+ p_value_cutoff
258
+ The cutoff of p-value to include an edge.
259
+ self_communication_off
260
+ Whether to exclude self communications in the visualization.
261
+ filename
262
+ Filename for saving the figure. Set the name to end with '.pdf' or 'png'
263
+ to specify format.
264
+ nx_node_size
265
+ Size of node representing clusters.
266
+ nx_node_cmap
267
+ The discrete color map to use for clusters. Choices:
268
+ 'Plotly', 'Alphabet', 'Light24', 'Dark24'. Recommend to use 'Plotly'
269
+ for ten clusters or fewer and 'Alphabet' for 10-24 clusters.
270
+ nx_pos_idx
271
+ Coordinates to use for the 2D plot.
272
+ nx_node_pos
273
+ 'cluster', the predicted spatial location of clusters will be used.
274
+ If setting to 'cluster', run the function :func:`cluster_position` first to set the cluster positions.
275
+ If None, the 'dot' layout from Graphviz package will be used.
276
+ nx_edge_width_lb_quantile
277
+ The quantile of communication connections to set for the lower bound of edge
278
+ width.
279
+ nx_edge_width_ub_quantile
280
+ The quantile of communication connections to set for the upper bound of edge
281
+ width.
282
+ nx_edge_width_min
283
+ Minimum width for plotted edges.
284
+ nx_edge_width_max
285
+ Maximum width for plotted edges.
286
+ nx_edge_color
287
+ If 'node', the color of an edge will be the same as the source node.
288
+ If an array of numbers between [0,1], the nx_edge_colormap will be used
289
+ to determine the edge colors.
290
+ nx_edge_colormap
291
+ The color map to use when nx_edge_color is an array of weights.
292
+ nx_bg_pos
293
+ Whether to plot the cells/positions as spatial background.
294
+ Set to False when not using the spatial layout of clusters.
295
+ nx_bg_color
296
+ Color of the spatial background.
297
+ nx_bg_ndsize
298
+ Node size of the spatial background.
299
+
300
+ """
301
+
302
+ X_tmp = adata.uns[uns_names[0]]['communication_matrix'].copy()
303
+ labels = list( X_tmp.columns.values )
304
+ X = np.zeros_like(X_tmp.values, float)
305
+ for i in range(len(uns_names)):
306
+ X_tmp = adata.uns[uns_names[i]]['communication_matrix'].values.copy()
307
+ p_values_tmp = adata.uns[uns_names[i]]['communication_pvalue'].values.copy()
308
+ if not quantile_cutoff is None:
309
+ cutoff = np.quantile(X_tmp.reshape(-1), quantile_cutoff)
310
+ else:
311
+ cutoff = np.inf
312
+ tmp_mask = ( X_tmp < cutoff ) * ( p_values_tmp > p_value_cutoff )
313
+ X_tmp[tmp_mask] = 0
314
+ X = X + X_tmp
315
+ X = X / len(uns_names)
316
+ if self_communication_off:
317
+ for i in range(X.shape[0]):
318
+ X[i,i] = 0
319
+
320
+ if nx_node_pos == "cluster":
321
+ node_pos = [adata.uns["cluster_pos-"+clustering][labels[i]] for i in range(len(labels)) ]
322
+ node_pos = np.array(node_pos)
323
+ node_pos = node_pos[:, nx_pos_idx]
324
+ lx = np.max(node_pos[:,0])-np.min(node_pos[:,0])
325
+ ly = np.max(node_pos[:,1])-np.min(node_pos[:,1])
326
+ pos_scale = max(lx, ly)
327
+ node_pos = node_pos / pos_scale * 8.0
328
+ else:
329
+ node_pos = None
330
+ if nx_bg_pos:
331
+ background_pos = adata.obsm["spatial"][:,nx_pos_idx]
332
+ background_pos = background_pos / pos_scale * 8.0
333
+ else:
334
+ background_pos = None
335
+ plot_cluster_signaling_network(X,
336
+ labels = labels,
337
+ filename = filename,
338
+ node_size = nx_node_size,
339
+ node_colormap = nx_node_cmap,
340
+ node_cluster_colormap = nx_node_cluster_cmap,
341
+ node_pos = node_pos,
342
+ edge_width_lb_quantile = nx_edge_width_lb_quantile,
343
+ edge_width_ub_quantile = nx_edge_width_ub_quantile,
344
+ edge_width_min = nx_edge_width_min,
345
+ edge_width_max = nx_edge_width_max,
346
+ edge_color = nx_edge_color,
347
+ edge_colormap = nx_edge_colormap,
348
+ background_pos = background_pos,
349
+ background_ndcolor = nx_bg_color,
350
+ background_ndsize = nx_bg_ndsize
351
+ )
352
+
353
+
354
+ legend_elements = []
355
+ if nx_node_cluster_cmap is None:
356
+ cluster_cmap = get_cmap_qualitative(nx_node_cmap)
357
+ for i in range(len(labels)):
358
+ legend_elements.append(Line2D([0],[0], marker='o',color='w', markerfacecolor=cluster_cmap[i], label=labels[i], markersize=10))
359
+ elif not nx_node_cluster_cmap is None:
360
+ for i in range(len(labels)):
361
+ legend_elements.append(Line2D([0],[0], marker='o',color='w', markerfacecolor=nx_node_cluster_cmap[labels[i]], label=labels[i], markersize=10))
362
+
363
+ fig, ax = plt.subplots()
364
+ tmp_filename,tmp_type = filename.split('.')
365
+ ax.legend(handles=legend_elements, loc='center')
366
+ ax.axis('off')
367
+ fig.savefig(tmp_filename+"_cluster_legend."+tmp_type, bbox_inches='tight')
368
+
369
+
370
+
371
+
372
+ def plot_communication_dependent_genes(
373
+ df_deg: pd.DataFrame,
374
+ df_yhat: pd.DataFrame,
375
+ show_gene_names: bool = True,
376
+ top_ngene_per_cluster: int = -1,
377
+ colormap: str = 'magma',
378
+ cluster_colormap: str = 'Plotly',
379
+ font_scale: float = 1.4,
380
+ filename = None,
381
+ return_genes = False
382
+ ):
383
+ """
384
+ Plot smoothed gene expression of the detected communication-dependent genes.
385
+ Takes input from the function :func:`commot.tl.communication_deg_clustering`.
386
+
387
+ .. image:: communication_deg.png
388
+ :width: 500pt
389
+
390
+ Parameters
391
+ ----------
392
+ df_deg
393
+ A data frame where each row is a gene and
394
+ the columns should include 'waldStat', 'pvalue', 'cluster'.
395
+ Output of ``tl.communication_deg_clustering``
396
+ df_yhat
397
+ A data frame where each row is the smoothed expression of a gene.
398
+ Output of ``tl.communication_deg_clustering``.
399
+ show_gene_names
400
+ Whether to plot the gene names.
401
+ top_ngene_per_cluster
402
+ If non-negative, plot the top_ngene_per_cluster genes
403
+ with highest wald statistics.
404
+ colormap
405
+ The colormap for the heatmap. Choose from available colormaps from ``seaborn``.
406
+ cluster_colormap
407
+ The qualitative colormap for annotating gene cluster labels.
408
+ Choose from 'Plotly', 'Alphabet', 'Light24', 'Dark24'.
409
+ font_scale
410
+ Font size.
411
+ filename
412
+ Filename for saving the figure. Set the name to end with '.pdf' or 'png'
413
+ to specify format.
414
+ return_genes
415
+ Whether to return the list of plotted genes.
416
+
417
+ Returns
418
+ -------
419
+ genes
420
+ Returns the gene list being plotted if return_genes is True.
421
+ """
422
+ cmap = get_cmap_qualitative(cluster_colormap)
423
+ wald_stats = df_deg['waldStat'].values
424
+ pvalue = df_deg['pvalue'].values
425
+ labels = np.array( df_deg['cluster'].values, int)
426
+ nlabel = np.max(labels)+1
427
+ yhat_mat = df_yhat.values
428
+ peak_locs = []
429
+ for i in range(nlabel):
430
+ tmp_idx = np.where(labels==i)[0]
431
+ tmp_y = yhat_mat[tmp_idx,:]
432
+ peak_locs.append(np.mean(np.argmax(tmp_y, axis=1)))
433
+ cluster_order = np.argsort(peak_locs)
434
+ idx = np.array([])
435
+ row_colors = []
436
+ for i in cluster_order:
437
+ tmp_idx = np.where(labels==i)[0]
438
+ tmp_order = np.argsort(-wald_stats[tmp_idx])
439
+ if top_ngene_per_cluster >= 0:
440
+ top_ngene = min(len(tmp_idx), top_ngene_per_cluster)
441
+ else:
442
+ top_ngene = len(tmp_idx)
443
+ idx = np.concatenate((idx, tmp_idx[tmp_order][:top_ngene]))
444
+ for j in range(top_ngene):
445
+ row_colors.append(cmap[i % len(cmap)])
446
+
447
+ sns.set(font_scale=font_scale)
448
+ g = sns.clustermap(df_yhat.iloc[idx],
449
+ row_cluster=False,
450
+ col_cluster=False,
451
+ row_colors=row_colors,
452
+ cmap = colormap,
453
+ xticklabels = False,
454
+ yticklabels = show_gene_names,
455
+ linewidths=0)
456
+ g.cax.set_position([.1, .2, .03, .45])
457
+ plt.savefig(filename, dpi=300)
458
+
459
+ if return_genes:
460
+ return list( df_deg.iloc[idx].index )
461
+
462
+ def plot_communication_impact(
463
+ df_impact: pd.DataFrame,
464
+ summary: str = None,
465
+ show_gene_names: str = True,
466
+ show_comm_names: str = True,
467
+ top_ngene: int = -1,
468
+ top_ncomm: int = -1,
469
+ colormap: str = 'rocket',
470
+ font_scale: float = 1.4,
471
+ filename: str = None,
472
+ cluster_knn: str = 5,
473
+ cluster_res: float = 0.5,
474
+ cluster_colormap: str = "Plotly",
475
+ linewidth = 0.0,
476
+ vmin = 0.0,
477
+ vmax = 1.0
478
+ ):
479
+ """
480
+ Plot communication impact obtained by running the function :func:`commot.tl.communication_impact`.
481
+
482
+ .. image:: communication_impact.png
483
+ :width: 300pt
484
+
485
+ Parameters
486
+ ----------
487
+ df_impact
488
+ The output from ``tl.communication_impact``.
489
+ summary
490
+ If 'receiver', the received signals are plotted as rows.
491
+ If 'sender', the sent signals are plotted as rows.
492
+ If None, both are plotted.
493
+ show_gene_names
494
+ Whether to plot gene names as x ticks.
495
+ show_comm_names
496
+ Whether to plot communication names as y ticks.
497
+ top_ngene
498
+ The number of most impacted genes to plot as columns.
499
+ If -1, all genes in ``df_impact`` are plotted.
500
+ top_ncomm
501
+ The number of communications with most impacts to plot as rows.
502
+ If -1, all communications in ``df_impact`` are plotted.
503
+ colormap
504
+ The colormap for the heatmap. Choose from available colormaps from ``seaborn``.
505
+ font_scale
506
+ Font size.
507
+ filename
508
+ Filename for saving the figure. Set the name to end with '.pdf' or 'png'
509
+ to specify format.
510
+ cluster_knn
511
+ Number of nearest neighbors when clustering the rows and columns.
512
+ cluster_res
513
+ The resolution paratemeter when running leiden clustering.
514
+ cluster_colormap
515
+ The qualitative colormap for annotating gene cluster labels.
516
+ Choose from 'Plotly', 'Alphabet', 'Light24', 'Dark24'.
517
+
518
+ """
519
+ index_names = list( df_impact.index )
520
+ tmp_idx = []
521
+ if summary == 'receiver':
522
+ for i in range(len(index_names)):
523
+ index_name = index_names[i]
524
+ tmp_n = min(len(index_name), 8)
525
+ if index_name[0] == 'r':
526
+ tmp_idx.append(i)
527
+ elif summary == 'sender':
528
+ for i in range(len(index_names)):
529
+ index_name = index_names[i]
530
+ tmp_n = min(len(index_name), 6)
531
+ if index_name[0] == 's':
532
+ tmp_idx.append(i)
533
+ elif summary is None:
534
+ tmp_idx = [i for i in range(len(index_names))]
535
+ tmp_idx = np.array(tmp_idx, int)
536
+ df_plot = df_impact.iloc[tmp_idx]
537
+
538
+ mat = df_plot.values
539
+ sum_gene = np.sum(np.abs(mat), axis=0)
540
+ sum_comm = np.sum(np.abs(mat), axis=1)
541
+ if top_ngene == -1:
542
+ top_ngene = mat.shape[1]
543
+ else:
544
+ top_ngene = min(top_ngene, mat.shape[1])
545
+ if top_ncomm == -1:
546
+ top_ncomm = mat.shape[0]
547
+ else:
548
+ top_ncomm = min(top_ncomm, mat.shape[0])
549
+ row_idx = np.argsort(-sum_comm)[:top_ncomm]
550
+ col_idx = np.argsort(-sum_gene)[:top_ngene]
551
+
552
+ df_plot = ( df_plot.iloc[row_idx,:] ).iloc[:,col_idx]
553
+ mat = df_plot.values
554
+ cmap = get_cmap_qualitative(cluster_colormap)
555
+ if mat.shape[1] > 10:
556
+ mat_pca = PCA(n_components=np.min([10,mat.shape[1],mat.shape[0]]), svd_solver='full').fit_transform(mat)
557
+ else:
558
+ mat_pca = mat
559
+ D = distance_matrix(mat_pca, mat_pca)
560
+ labels = leiden_clustering(D, k=cluster_knn, resolution=cluster_res)
561
+ row_idx, row_colors = reorder(labels, -np.abs(mat.sum(axis=1)), -np.abs(mat.sum(axis=1)), cmap)
562
+ if mat.shape[0] > 10:
563
+ mat_pca = PCA(n_components=np.min([10,mat.shape[1],mat.shape[0]]), svd_solver='full').fit_transform(mat.T)
564
+ else:
565
+ mat_pca = mat.T
566
+ D = distance_matrix(mat_pca, mat_pca)
567
+ labels = leiden_clustering(D, k=cluster_knn, resolution=cluster_res)
568
+ col_idx, col_colors = reorder(labels, -np.abs(mat.sum(axis=0)), -np.abs(mat.sum(axis=0)), cmap)
569
+
570
+ sns.set(font_scale=font_scale)
571
+ g = sns.clustermap( ( df_plot.iloc[row_idx,:] ).iloc[:,col_idx],
572
+ row_cluster = False,
573
+ col_cluster =False,
574
+ row_colors = row_colors,
575
+ col_colors = col_colors,
576
+ cmap = colormap,
577
+ xticklabels = show_gene_names,
578
+ yticklabels = show_comm_names,
579
+ linewidths = linewidth,
580
+ square = True,
581
+ vmin = vmin,
582
+ vmax = vmax)
583
+ g.cax.set_position([0.01, .2, .03, .45])
584
+ plt.savefig(filename, dpi=300)
585
+
586
+
587
+ def reorder(labels, cofactor_cluster, cofactor_sample, cmap):
588
+ nlabels = np.max(labels) + 1
589
+ cofactor = []
590
+ for i in range(nlabels):
591
+ tmp_idx = np.where(labels==i)[0]
592
+ cofactor.append(cofactor_cluster[tmp_idx].mean())
593
+ cluster_order = np.argsort(cofactor)
594
+ idx = np.array([])
595
+ colors = []
596
+ for i in cluster_order:
597
+ tmp_idx = np.where(labels==i)[0]
598
+ tmp_order = np.argsort(cofactor_sample[tmp_idx])
599
+ idx = np.concatenate((idx, tmp_idx[tmp_order]))
600
+ for j in range(len(tmp_idx)):
601
+ colors.append(cmap[i % len(cmap)])
602
+ return np.array(idx, int), colors
603
+
604
+
605
+ class pvalueNormalize(mpl.colors.Normalize):
606
+ def __init__(self, vmin=None, vmax=None, clip=False):
607
+ mpl.colors.Normalize.__init__(self, vmin, vmax, clip)
608
+
609
+ def __call__(self, value, clip=None):
610
+ left = np.log10(self.vmax); right = np.log10(self.vmin)
611
+ value_log10 = np.log10(value)
612
+ y = (value_log10 - left) / (right - left)
613
+ return y
614
+
615
+
616
+ def plot_cluster_communication_dotplot(
617
+ adata: anndata.AnnData,
618
+ database_name: str = None,
619
+ pathway_name: str = None,
620
+ clustering: str = None,
621
+ keys = None,
622
+ p_value_cutoff: float = 0.05,
623
+ p_value_vmin: float = 1e-3,
624
+ size_max = 20,
625
+ size_min = 10,
626
+ vmax_quantile = 0.99,
627
+ vmin_quantile = 0.0,
628
+ cmap = 'cool',
629
+ filename = None,
630
+ font_scale = 0.5,
631
+ top_nclus = -1,
632
+ top_ncomm = -1,
633
+ cluster_x = False,
634
+ cluster_y = False,
635
+ cluster_knn = 5,
636
+ cluster_res = 1.0
637
+ ):
638
+ """
639
+ Plot cluster-cluster communication through multiple ligand-receptor pairs as dotplot.
640
+
641
+ .. image:: cluster_communication_dotplot.png
642
+ :width: 300pt
643
+
644
+ Parameters
645
+ ----------
646
+ adata
647
+ The data matrix of shape ``n_obs`` × ``n_var`` after running ``tl.spatial_communication``.
648
+ Rows correspond to cells or positions and columns to genes.
649
+ database_name
650
+ The name of the LR database.
651
+ pathway_name
652
+ Name of the a signaling pathway or a list of several signaling pathways.
653
+ If given, all LR pairs of this signaling pathway(s) will be plotted.
654
+ If ``keys`` is specified, ``pathway_name`` will be ignored.
655
+ clustering
656
+ Name of the clustering.
657
+ keys
658
+ A list of keys for example 'ligA-recA' for a LR pair or 'pathwayX' for a signaling pathway 'pathwayX'.
659
+ If given, ``pathway_name`` will be ignored.
660
+ p_value_cutoff
661
+ Cutoff for being considered significant.
662
+ p_value_vmin
663
+ The lower bound of p-value corresponding to the biggest dot size.
664
+ size_max
665
+ Size of biggest dot (corresponding to p-value <= p_value_min).
666
+ size_min
667
+ Size of smallest dot (corresponding to p-value = p_value_cutoff).
668
+ vmax_quantile
669
+ The quantile of cluster-cluster communication weights for setting vmax of colormap.
670
+ vmin_quantile
671
+ The quantile of cluster-cluster communication weights for setting vmin of colormap.
672
+ cmap
673
+ The colormap for the nodes.
674
+ filename
675
+ Filename for saving the figure. Set the name to end with '.pdf' or 'png'
676
+ to specify format.
677
+ font_scale
678
+ Font size.
679
+ top_nclus
680
+ If not -1, the top number of cluster-cluster pairs with the highest total communication
681
+ weight among the signaling pathways are plotted.
682
+ top_ncomm
683
+ If not -1, the top number of ligand-recepter pairs with the highest total communication
684
+ weight among the cluster-cluster pairs are plotted.
685
+ cluster_x
686
+ Whether to reorder the cluster-cluster pairs according to their patterns among
687
+ the ligand-receptor pairs.
688
+ cluster_y
689
+ Whether to reorder the ligand-receptor pairs according to their patterns among
690
+ the cluster-cluster pairs.
691
+ cluster_knn
692
+ The k value of knn graph for clustering if cluster_x or cluster_y is True.
693
+ cluster_res
694
+ The resolution of leiden clustering algorithm if cluster_x or cluster_y is True.
695
+
696
+ """
697
+ if keys is None:
698
+ keys = []
699
+ if isinstance(pathway_name, str):
700
+ pathways = [pathway_name]
701
+ elif isinstance(pathway_name, list):
702
+ pathways = pathway_name
703
+ df_ligrec = adata.uns['commot-%s-info' % database_name]['df_ligrec']
704
+ for i in range(df_ligrec.shape[0]):
705
+ if df_ligrec.iloc[i][2] in pathways:
706
+ keys.append(df_ligrec.iloc[i][0]+'-'+df_ligrec.iloc[i][1])
707
+ keys.extend( pathways )
708
+
709
+ X_tmp = adata.uns['commot_cluster-'+clustering+'-'+database_name+'-'+keys[0]]['communication_matrix'].copy()
710
+ labels = list( X_tmp.columns.values )
711
+ name_matrix = np.empty([len(labels), len(labels)], object)
712
+ for i in range(len(labels)):
713
+ for j in range(len(labels)):
714
+ name_matrix[i,j] = labels[i]+'->'+labels[j]
715
+ x_names = name_matrix.flatten()
716
+
717
+ y_names = []
718
+ S = np.empty([len(x_names), len(keys)], float)
719
+ P = np.empty([len(x_names), len(keys)], float)
720
+ for ikey in range(len(keys)):
721
+ key = keys[ikey]
722
+ y_names.append(key)
723
+ S_tmp = adata.uns['commot_cluster-%s-%s-%s' % (clustering, database_name, key)]['communication_matrix'].values.copy()
724
+ P_tmp = adata.uns['commot_cluster-%s-%s-%s' % (clustering, database_name, key)]['communication_pvalue'].values.copy()
725
+ S[:,ikey] = S_tmp.flatten()[:]
726
+ P[:,ikey] = P_tmp.flatten()[:]
727
+ y_names = np.array( y_names, str )
728
+
729
+ P_mask = P <= p_value_cutoff
730
+ P_mask_row = P_mask.sum(axis=1).astype(bool)
731
+ P_mask_col = P_mask.sum(axis=0).astype(bool)
732
+
733
+ P = P[P_mask_row,:][:,P_mask_col]
734
+ S = S[P_mask_row,:][:,P_mask_col]
735
+ x_names = x_names[P_mask_row]
736
+ y_names = y_names[P_mask_col]
737
+
738
+ if top_nclus > 0:
739
+ tmp_idx = np.argsort(-S.sum(axis=1))[:top_nclus]
740
+ P = P[tmp_idx,:]; S = S[tmp_idx,:]; x_names = x_names[tmp_idx]
741
+ if top_ncomm > 0:
742
+ tmp_idx = np.argsort(-S.sum(axis=0))[:top_ncomm]
743
+ P = P[:,tmp_idx]; S = S[:,tmp_idx]; y_names = y_names[tmp_idx]
744
+
745
+ if cluster_x:
746
+ mat = S
747
+ dummy_cmap = ['r']
748
+ if mat.shape[1] > 10:
749
+ mat_pca = PCA(n_components=np.min([10,mat.shape[1],mat.shape[0]]), svd_solver='full').fit_transform(mat)
750
+ else:
751
+ mat_pca = mat
752
+ D = distance_matrix(mat_pca, mat_pca)
753
+ labels = leiden_clustering(D, k=cluster_knn, resolution=cluster_res)
754
+ x_idx, _ = reorder(labels, -np.abs(mat.sum(axis=1)), -np.abs(mat.sum(axis=1)), dummy_cmap)
755
+ P = P[x_idx,:]; S = S[x_idx,:]; x_names = x_names[x_idx]
756
+ if cluster_y:
757
+ mat = S
758
+ dummy_cmap = ['r']
759
+ if mat.shape[0] > 10:
760
+ mat_pca = PCA(n_components=np.min([10,mat.shape[1],mat.shape[0]]), svd_solver='full').fit_transform(mat.T)
761
+ else:
762
+ mat_pca = mat.T
763
+ D = distance_matrix(mat_pca, mat_pca)
764
+ labels = leiden_clustering(D, k=cluster_knn, resolution=cluster_res)
765
+ y_idx, _ = reorder(labels, -np.abs(mat.sum(axis=0)), -np.abs(mat.sum(axis=0)), dummy_cmap)
766
+ P = P[:,y_idx]; S = S[:,y_idx]; y_names = y_names[y_idx]
767
+
768
+ vmax = np.quantile(S, vmax_quantile)
769
+ vmin = np.quantile(S, vmin_quantile)
770
+
771
+ data_plot = []
772
+ for i in range(P.shape[0]):
773
+ for j in range(P.shape[1]):
774
+ if P[i,j] <= p_value_cutoff:
775
+ data_plot.append([x_names[i], y_names[j], S[i,j], max(P[i,j], p_value_vmin)])
776
+ df_plot = pd.DataFrame(data=data_plot, columns=['x','y','color_col','size_col'])
777
+
778
+ sns.set_theme(style="whitegrid", font_scale=font_scale)
779
+ g = sns.relplot(
780
+ data=df_plot,
781
+ x="x", y="y", hue="color_col", size="size_col",
782
+ palette=cmap, hue_norm=(vmin, vmax), edgecolor=".7", legend='brief',
783
+ height=10, sizes=(size_min, size_max), size_norm=pvalueNormalize(vmin=p_value_vmin, vmax=p_value_cutoff),
784
+ )
785
+ g.set(xlabel="", ylabel="", aspect="equal")
786
+ g.despine(left=True, bottom=True)
787
+ g.ax.margins(.02)
788
+ for label in g.ax.get_xticklabels():
789
+ label.set_rotation(90)
790
+ for artist in g.legend.legendHandles:
791
+ artist.set_edgecolor(".7")
792
+ plt.savefig(filename, dpi=500, bbox_inches = 'tight')
793
+
794
+ return