-
Notifications
You must be signed in to change notification settings - Fork 29
/
analysis.R
3135 lines (2822 loc) · 141 KB
/
analysis.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#' Compute and visualize the contribution of each ligand-receptor pair in the overall signaling pathways
#'
#' @param object CellChat object
#' @param signaling a signaling pathway name
#' @param signaling.name alternative signaling pathway name to show on the plot
#' @param sources.use a vector giving the index or the name of source cell groups
#' @param targets.use a vector giving the index or the name of target cell groups.
#' @param width the width of individual bar
#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot
#' @param thresh threshold of the p-value for determining significant interaction
#' @param return.data whether return the data.frame consisting of the predicted L-R pairs and their contribution
#' @param x.rotation rotation of x-label
#' @param title the title of the plot
#' @param font.size font size of the text
#' @param font.size.title font size of the title
#' @importFrom dplyr select
#' @importFrom ggplot2 ggplot geom_bar aes coord_flip scale_x_discrete element_text theme ggtitle
#' @importFrom cowplot ggdraw draw_label plot_grid
#'
#' @return
#' @export
#'
#' @examples
netAnalysis_contribution <- function(object, signaling, signaling.name = NULL, sources.use = NULL, targets.use = NULL,
width = 0.1, vertex.receiver = NULL, thresh = 0.05, return.data = FALSE,
x.rotation = 0, title = "Contribution of each L-R pair",
font.size = 10, font.size.title = 10) {
pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = "pathway_name", matching.exact = T, pair.only = T)
pair.name.use = select(object@DB$interaction[rownames(pairLR),],"interaction_name_2")
if (is.null(signaling.name)) {
signaling.name <- signaling
}
net <- object@net
pairLR.use.name <- dimnames(net$prob)[[3]]
pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)
pairLR <- pairLR[pairLR.name, ]
prob <- net$prob
pval <- net$pval
prob[pval > thresh] <- 0
if (!is.null(sources.use)) {
if (is.character(sources.use)) {
if (all(sources.use %in% dimnames(prob)[[1]])) {
sources.use <- match(sources.use, dimnames(prob)[[1]])
} else {
stop("The input `sources.use` should be cell group names or a numerical vector!")
}
}
idx.t <- setdiff(1:nrow(prob), sources.use)
prob[idx.t, , ] <- 0
}
if (!is.null(targets.use)) {
if (is.character(targets.use)) {
if (all(targets.use %in% dimnames(prob)[[1]])) {
targets.use <- match(targets.use, dimnames(prob)[[2]])
} else {
stop("The input `targets.use` should be cell group names or a numerical vector!")
}
}
idx.t <- setdiff(1:nrow(prob), targets.use)
prob[ ,idx.t, ] <- 0
}
if (length(pairLR.name) > 1) {
pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]
} else {
pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]
}
if (length(pairLR.name.use) == 0) {
stop(paste0('There is no significant communication of ', signaling.name))
} else {
pairLR <- pairLR[pairLR.name.use,]
}
prob <- prob[,,pairLR.name.use]
if (length(dim(prob)) == 2) {
prob <- replicate(1, prob, simplify="array")
dimnames(prob)[3] <- pairLR.name.use
}
prob <-(prob-min(prob))/(max(prob)-min(prob))
if (is.null(vertex.receiver)) {
pSum <- apply(prob, 3, sum)
pSum.max <- sum(prob)
pSum <- pSum/pSum.max
pSum[is.na(pSum)] <- 0
y.lim <- max(pSum)
pair.name <- unlist(dimnames(prob)[3])
pair.name <- factor(pair.name, levels = unique(pair.name))
if (!is.null(pairLR.name.use)) {
pair.name <- pair.name.use[as.character(pair.name),1]
pair.name <- factor(pair.name, levels = unique(pair.name))
}
mat <- pSum
df1 <- data.frame(name = pair.name, contribution = mat)
if(nrow(df1) < 10) {
df2 <- data.frame(name = as.character(1:(10-nrow(df1))), contribution = rep(0, 10-nrow(df1)))
df <- rbind(df1, df2)
} else {
df <- df1
}
df <- df[order(df$contribution, decreasing = TRUE), ]
# df$name <- factor(df$name, levels = unique(df$name))
df$name <- factor(df$name,levels=df$name[order(df$contribution, decreasing = TRUE)])
df1$name <- factor(df1$name,levels=df1$name[order(df1$contribution, decreasing = TRUE)])
gg <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat="identity", width = 0.7) +
theme_classic() + theme(axis.text.y = element_text(angle = x.rotation, hjust = 1,size=font.size, colour = 'black'), axis.text=element_text(size=font.size),
axis.title.y = element_text(size= font.size), axis.text.x = element_blank(), axis.ticks = element_blank()) +
xlab("") + ylab("Relative contribution") + ylim(0,y.lim) + coord_flip() + theme(legend.position="none") +
scale_x_discrete(limits = rev(levels(df$name)), labels = c(rep("", max(0, 10-nlevels(df1$name))),rev(levels(df1$name))))
if (!is.null(title)) {
gg <- gg + ggtitle(title)+ theme(plot.title = element_text(hjust = 0.5, size = font.size.title))
}
gg
} else {
pair.name <- factor(unlist(dimnames(prob)[3]), levels = unique(unlist(dimnames(prob)[3])))
# show all the communications
pSum <- apply(prob, 3, sum)
pSum.max <- sum(prob)
pSum <- pSum/pSum.max
pSum[is.na(pSum)] <- 0
y.lim <- max(pSum)
df<- data.frame(name = pair.name, contribution = pSum)
gg <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat="identity",width = 0.2) +
theme_classic() + theme(axis.text=element_text(size=10),axis.text.x = element_text(angle = x.rotation, hjust = 1,size=8),
axis.title.y = element_text(size=10)) +
xlab("") + ylab("Relative contribution") + ylim(0,y.lim)+ ggtitle("All")+ theme(plot.title = element_text(hjust = 0.5))#+
# show the communications in Hierarchy1
if (dim(prob)[3] > 1) {
pSum <- apply(prob[,vertex.receiver,], 3, sum)
} else {
pSum <- sum(prob[,vertex.receiver,])
}
pSum <- pSum/pSum.max
pSum[is.na(pSum)] <- 0
df<- data.frame(name = pair.name, contribution = pSum)
gg1 <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat="identity",width = 0.2) +
theme_classic() + theme(axis.text=element_text(size=10),axis.text.x = element_text(angle = x.rotation, hjust = 1,size=8), axis.title.y = element_text(size=10)) +
xlab("") + ylab("Relative contribution") + ylim(0,y.lim)+ ggtitle("Hierarchy1") + theme(plot.title = element_text(hjust = 0.5))#+
#scale_x_discrete(limits = c(0,1))
# show the communications in Hierarchy2
if (dim(prob)[3] > 1) {
pSum <- apply(prob[,setdiff(1:dim(prob)[1],vertex.receiver),], 3, sum)
} else {
pSum <- sum(prob[,setdiff(1:dim(prob)[1],vertex.receiver),])
}
pSum <- pSum/pSum.max
pSum[is.na(pSum)] <- 0
df<- data.frame(name = pair.name, contribution = pSum)
gg2 <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat="identity", width=0.9) +
theme_classic() + theme(axis.text=element_text(size=10),axis.text.x = element_text(angle = x.rotation, hjust = 1,size=8), axis.title.y = element_text(size=10)) +
xlab("") + ylab("Relative contribution") + ylim(0,y.lim)+ ggtitle("Hierarchy2")+ theme(plot.title = element_text(hjust = 0.5))#+
#scale_x_discrete(limits = c(0,1))
title <- cowplot::ggdraw() + cowplot::draw_label(paste0("Contribution of each signaling in ", signaling.name, " pathway"), fontface='bold', size = 10)
gg.combined <- cowplot::plot_grid(gg, gg1, gg2, nrow = 1)
gg.combined <- cowplot::plot_grid(title, gg.combined, ncol = 1, rel_heights=c(0.1, 1))
gg <- gg.combined
gg
}
if (return.data) {
df <- subset(df, contribution > 0)
return(list(LR.contribution = df, gg.obj = gg))
} else {
return(gg)
}
}
#' Compute the network centrality scores allowing identification of dominant senders, receivers, mediators and influencers in all inferred communication networks
#'
#' NB: This function was previously named as `netAnalysis_signalingRole`. The previous function `netVisual_signalingRole` is now named as `netAnalysis_signalingRole_network`.
#'
#' @param object CellChat object; If object = NULL, USER must provide `net`
#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks. Setting slot.name = "netP" to compute the network centrality scores at the level of signaling pathways, and setting slot.name = "net" to compute the network centrality scores at the level of ligand-receptor pairs
#' @param net compute the centrality measures on a specific signaling network given by a 2 or 3 dimemsional array net
#' @param net.name a character vector giving the name of signaling networks
#' @param thresh threshold of the p-value for determining significant interaction
#' @importFrom future nbrOfWorkers
#' @importFrom methods slot
#' @importFrom future.apply future_sapply
#' @importFrom pbapply pbsapply
#'
#' @return
#' @export
#'
netAnalysis_computeCentrality <- function(object = NULL, slot.name = "netP", net = NULL, net.name = NULL, thresh = 0.05) {
if (is.null(net)) {
prob <- methods::slot(object, slot.name)$prob
pval <- methods::slot(object, slot.name)$pval
pval[prob == 0] <- 1
prob[pval >= thresh] <- 0
net = prob
}
if (is.null(net.name)) {
net.name <- dimnames(net)[[3]]
}
if (length(dim(net)) == 3) {
nrun <- dim(net)[3]
my.sapply <- ifelse(
test = future::nbrOfWorkers() == 1,
yes = pbapply::pbsapply,
no = future.apply::future_sapply
)
centr.all = my.sapply(
X = 1:nrun,
FUN = function(x) {
net0 <- net[ , , x]
return(computeCentralityLocal(net0))
},
simplify = FALSE
)
} else {
centr.all <- as.list(computeCentralityLocal(net))
}
names(centr.all) <- net.name
if (is.null(object)) {
return(centr.all)
} else {
slot(object, slot.name)$centr <- centr.all
return(object)
}
}
#' Compute Centrality measures for a signaling network
#'
#' @param net compute the centrality measures on a specific signaling network given by a 2 or 3 dimemsional array net
#' @importFrom igraph graph_from_adjacency_matrix strength hub_score authority_score eigen_centrality page_rank betweenness E
#' @importFrom sna flowbet infocent
#'
#' @return
computeCentralityLocal <- function(net) {
centr <- vector("list")
G <- igraph::graph_from_adjacency_matrix(net, mode = "directed", weighted = T)
centr$outdeg_unweighted <- rowSums(net > 0)
centr$indeg_unweighted <- colSums(net > 0)
centr$outdeg <- igraph::strength(G, mode="out")
centr$indeg <- igraph::strength(G, mode="in")
centr$hub <- igraph::hub_score(G)$vector
centr$authority <- igraph::authority_score(G)$vector # A node has high authority when it is linked by many other nodes that are linking many other nodes.
centr$eigen <- igraph::eigen_centrality(G)$vector # A measure of influence in the network that takes into account second-order connections
centr$page_rank <- igraph::page_rank(G)$vector
igraph::E(G)$weight <- 1/igraph::E(G)$weight
centr$betweenness <- igraph::betweenness(G)
#centr$flowbet <- try(sna::flowbet(net)) # a measure of its role as a gatekeeper for the flow of communication between any two cells; the total maximum flow (aggregated across all pairs of third parties) mediated by v.
#centr$info <- try(sna::infocent(net)) # actors with higher information centrality are predicted to have greater control over the flow of information within a network; highly information-central individuals tend to have a large number of short paths to many others within the social structure.
centr$flowbet <- tryCatch({
sna::flowbet(net)
}, error = function(e) {
as.vector(matrix(0, nrow = nrow(net), ncol = 1))
})
centr$info <- tryCatch({
sna::infocent(net, diag = T, rescale = T, cmode = "lower")
# sna::infocent(net, diag = T, rescale = T, cmode = "weak")
}, error = function(e) {
as.vector(matrix(0, nrow = nrow(net), ncol = 1))
})
return(centr)
}
#' Select the number of the patterns for running `identifyCommunicationPatterns`
#'
#' We infer the number of patterns based on two metrics that have been implemented in the NMF R package, including Cophenetic and Silhouette. Both metrics measure the stability for a particular number of patterns based on a hierarchical clustering of the consensus matrix. For a range of the number of patterns, a suitable number of patterns is the one at which Cophenetic and Silhouette values begin to drop suddenly.
#'
#' @param object CellChat object
#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks
#' @param pattern "outgoing" or "incoming"
#' @param k.range a range of the number of patterns
#' @param title.name title of plot
#' @param do.facet whether use facet plot showing the two measures
#' @param nrun number of runs when performing NMF
#' @param seed.use seed when performing NMF
#' @importFrom methods slot
# #' @importFrom NMF nmfEstimateRank
#' @import NMF
# #' @importFrom ggplot2 scale_color_brewer
#' @import ggplot2
#' @return a ggplot object
#' @export
#'
#' @examples
selectK <- function(object, slot.name = "netP", pattern = c("outgoing","incoming"), title.name = NULL, do.facet = TRUE, k.range = seq(2,10), nrun = 30, seed.use = 10) {
pattern <- match.arg(pattern)
prob <- methods::slot(object, slot.name)$prob
if (pattern == "outgoing") {
data_sender <- apply(prob, c(1,3), sum)
data_sender = sweep(data_sender, 2L, apply(data_sender, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)
data0 = as.matrix(data_sender)
} else if (pattern == "incoming") {
data_receiver <- apply(prob, c(2,3), sum)
data_receiver = sweep(data_receiver, 2L, apply(data_receiver, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)
data0 = as.matrix(data_receiver)
}
options(warn = -1)
data <- data0
data <- data[rowSums(data)!=0,]
if (is.null(title.name)) {
title.name <- paste0(pattern, " signaling \n")
# title.name <- paste0(pattern, " signaling \n (nrun = ", nrun, ", seed = ", seed.use, ")")
}
res <- NMF::nmfEstimateRank(data, range = k.range, method = 'lee', nrun=nrun, seed = seed.use)
df1 <- data.frame(k = res$measures$rank, score = res$measures$cophenetic, Measure = "Cophenetic")
df2 <- data.frame(k = res$measures$rank, score = res$measures$silhouette.consensus, Measure = "Silhouette")
# df3 <- data.frame(k = res$measures$rank, score = res$measures$dispersion, Measure = "Dispersion")
df <- rbind(df1, df2)
#df <- rbind(df1, df2, df3)
gg <- ggplot(df, aes(x = k, y = score, group = Measure, color = Measure)) + geom_line(size=1) +
geom_point() +
theme_classic() + labs(x = 'Number of patterns', y='Measure score') +
labs(title = title.name) + theme(plot.title = element_text(size = 10, face = "bold", hjust = 0.5)) +
theme(legend.position = "right") + theme(text = element_text(size = 10)) + scale_x_discrete(limits = (unique(df$k))) +
scale_color_brewer(palette="Set2") + guides(color=guide_legend("Measure type"))
if (do.facet) {
gg <- gg + facet_wrap(~ Measure, scales='free')
}
gg
return(gg)
}
#' Identification of major signals for specific cell groups and general communication patterns
#'
#' @param object CellChat object
#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks
#' @param pattern "outgoing" or "incoming"
#' @param k the number of patterns
#' @param k.range a range of the number of patterns
#' @param heatmap.show whether showing heatmap
#' @param color.use the character vector defining the color of each cell group
#' @param color.heatmap a color name in brewer.pal
#' @param title.legend the title of legend in heatmap
#' @param width width of heatmap
#' @param height height of heatmap
#' @param font.size fontsize in heatmap
#' @importFrom methods slot
#' @importFrom NMF nmfEstimateRank nmf
#' @importFrom grDevices colorRampPalette
#' @importFrom RColorBrewer brewer.pal
#' @importFrom ComplexHeatmap Heatmap HeatmapAnnotation draw
#' @importFrom stats setNames
#' @importFrom grid grid.grabExpr grid.newpage pushViewport grid.draw unit gpar viewport popViewport
#'
#' @return
#' @export
#'
#' @examples
identifyCommunicationPatterns <- function(object, slot.name = "netP", pattern = c("outgoing","incoming"), k = NULL, k.range = seq(2,10), heatmap.show = TRUE,
color.use = NULL, color.heatmap = "Spectral", title.legend = "Contributions",
width = 4, height = 6, font.size = 8) {
pattern <- match.arg(pattern)
prob <- methods::slot(object, slot.name)$prob
if (pattern == "outgoing") {
data_sender <- apply(prob, c(1,3), sum)
data_sender = sweep(data_sender, 2L, apply(data_sender, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)
data0 = as.matrix(data_sender)
} else if (pattern == "incoming") {
data_receiver <- apply(prob, c(2,3), sum)
data_receiver = sweep(data_receiver, 2L, apply(data_receiver, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)
data0 = as.matrix(data_receiver)
}
options(warn = -1)
data <- data0
data <- data[rowSums(data)!=0,]
if (is.null(k)) {
stop("Please run the function `selectK` for selecting a suitable k!")
}
outs_NMF <- NMF::nmf(data, rank = k, method = 'lee', seed = 'nndsvd')
W <- scaleMat(outs_NMF@fit@W, 'r1')
H <- scaleMat(outs_NMF@fit@H, 'c1')
colnames(W) <- paste0("Pattern ", seq(1,ncol(W))); rownames(H) <- paste0("Pattern ", seq(1,nrow(H)));
if (heatmap.show) {
net <- W
if (is.null(color.use)) {
color.use <- scPalette(length(rownames(net)))
}
color.heatmap = grDevices::colorRampPalette(rev(RColorBrewer::brewer.pal(n = 9, name = color.heatmap)))(255)
df<- data.frame(group = rownames(net)); rownames(df) <- rownames(net)
cell.cols.assigned <- setNames(color.use, unique(as.character(df$group)))
row_annotation <- HeatmapAnnotation(df = df, col = list(group = cell.cols.assigned),which = "row",
show_legend = FALSE, show_annotation_name = FALSE,
simple_anno_size = grid::unit(0.2, "cm"))
ht1 = Heatmap(net, col = color.heatmap, na_col = "white", name = "Contribution",
left_annotation = row_annotation,
cluster_rows = T,cluster_columns = F,clustering_method_rows = "average",
row_names_side = "left",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),
width = unit(width, "cm"), height = unit(height, "cm"),
show_heatmap_legend = F,
column_title = "Cell patterns",column_title_gp = gpar(fontsize = 10)
)
net <- t(H)
ht2 = Heatmap(net, col = color.heatmap, na_col = "white", name = "Contribution",
cluster_rows = T,cluster_columns = F,clustering_method_rows = "average",
row_names_side = "left",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),
width = unit(width, "cm"), height = unit(height, "cm"),
column_title = "Communication patterns",column_title_gp = gpar(fontsize = 10),
heatmap_legend_param = list(title = title.legend, title_gp = gpar(fontsize = 8, fontface = "plain"),title_position = "leftcenter-rot",
border = NA, at = c(round(min(net, na.rm = T), digits = 1), round(max(net, na.rm = T), digits = 1)),
legend_height = unit(20, "mm"),labels_gp = gpar(fontsize = 6),grid_width = unit(2, "mm"))
)
gb_ht1 = grid.grabExpr(draw(ht1))
gb_ht2 = grid.grabExpr(draw(ht2))
#grid.newpage()
pushViewport(viewport(x = 0.1, y = 0.1, width = 0.2, height = 0.5, just = c("left", "bottom")))
grid.draw(gb_ht1)
popViewport()
pushViewport(viewport(x = 0.6, y = 0.1, width = 0.2, height = 0.5, just = c("left", "bottom")))
grid.draw(gb_ht2)
popViewport()
}
data_W <- as.data.frame(as.table(W)); colnames(data_W) <- c("CellGroup","Pattern","Contribution")
data_H <- as.data.frame(as.table(H)); colnames(data_H) <- c("Pattern","Signaling","Contribution")
res.pattern = list("cell" = data_W, "signaling" = data_H)
methods::slot(object, slot.name)$pattern[[pattern]] <- list(data = data0, pattern = res.pattern)
return(object)
}
#' Compute signaling network similarity for any pair of signaling networks
#'
#' @param object CellChat object
#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks
#' @param type "functional","structural"
#' @param k the number of nearest neighbors
#' @param thresh the fraction (0 to 0.25) of interactions to be trimmed before computing network similarity
#' @importFrom methods slot
#'
#' @return
#' @export
#'
#' @examples
computeNetSimilarity <- function(object, slot.name = "netP", type = c("functional","structural"), k = NULL, thresh = NULL) {
type <- match.arg(type)
prob = methods::slot(object, slot.name)$prob
if (is.null(k)) {
if (dim(prob)[3] <= 25) {
k <- ceiling(sqrt(dim(prob)[3]))
} else {
k <- ceiling(sqrt(dim(prob)[3])) + 1
}
}
if (!is.null(thresh)) {
prob[prob < quantile(c(prob[prob != 0]), thresh)] <- 0
}
if (type == "functional") {
# compute the functional similarity
D_signalings <- matrix(0, nrow = dim(prob)[3], ncol = dim(prob)[3])
S2 <- D_signalings; S3 <- D_signalings;
for (i in 1:(dim(prob)[3]-1)) {
for (j in (i+1):dim(prob)[3]) {
Gi <- (prob[ , ,i] > 0)*1
Gj <- (prob[ , ,j] > 0)*1
S3[i,j] <- sum(Gi * Gj)/sum(Gi+Gj-Gi*Gj,na.rm=TRUE)
}
}
# define the similarity matrix
S3[is.na(S3)] <- 0; S3 <- S3 + t(S3); diag(S3) <- 1
# S_signalings <- S1 *S2
S_signalings <- S3
} else if (type == "structural") {
# compute the structure distance
D_signalings <- matrix(0, nrow = dim(prob)[3], ncol = dim(prob)[3])
for (i in 1:(dim(prob)[3]-1)) {
for (j in (i+1):dim(prob)[3]) {
Gi <- (prob[ , ,i] > 0)*1
Gj <- (prob[ , ,j] > 0)*1
D_signalings[i,j] <- computeNetD_structure(Gi,Gj)
}
}
# define the structure similarity matrix
D_signalings[is.infinite(D_signalings)] <- 0
D_signalings[is.na(D_signalings)] <- 0
D_signalings <- D_signalings + t(D_signalings)
S_signalings <- 1-D_signalings
}
# smooth the similarity matrix using SNN
SNN <- buildSNN(S_signalings, k = k, prune.SNN = 1/15)
Similarity <- as.matrix(S_signalings*SNN)
rownames(Similarity) <- dimnames(prob)[[3]]
colnames(Similarity) <- dimnames(prob)[[3]]
comparison <- "single"
comparison.name <- paste(comparison, collapse = "-")
if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$matrix)) {
methods::slot(object, slot.name)$similarity[[type]]$matrix <- NULL
}
methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]] <- Similarity
return(object)
}
#' Compute signaling network similarity for any pair of datasets
#'
#' @param object A merged CellChat object
#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks
#' @param type "functional","structural"
#' @param comparison a numerical vector giving the datasets for comparison
#' @param k the number of nearest neighbors
#' @param thresh the fraction (0 to 0.25) of interactions to be trimmed before computing network similarity
#' @importFrom methods slot
#'
#' @return
#' @export
#'
computeNetSimilarityPairwise <- function(object, slot.name = "netP", type = c("functional","structural"), comparison = NULL, k = NULL, thresh = NULL) {
type <- match.arg(type)
if (is.null(comparison)) {
comparison <- 1:length(unique(object@meta$datasets))
}
cat("Compute signaling network similarity for datasets", as.character(comparison), '\n')
comparison.name <- paste(comparison, collapse = "-")
net <- list()
signalingAll <- c()
object.net.nameAll <- c()
# 1:length(setdiff(names(methods::slot(object, slot.name)), "similarity"))
for (i in 1:length(comparison)) {
object.net <- methods::slot(object, slot.name)[[comparison[i]]]
object.net.name <- names(methods::slot(object, slot.name))[comparison[i]]
object.net.nameAll <- c(object.net.nameAll, object.net.name)
net[[i]] = object.net$prob
signalingAll <- c(signalingAll, paste0(dimnames(net[[i]])[[3]], "--", object.net.name))
# signalingAll <- c(signalingAll, dimnames(net[[i]])[[3]])
}
names(net) <- object.net.nameAll
net.dim <- sapply(net, dim)[3,]
nnet <- sum(net.dim)
position <- cumsum(net.dim); position <- c(0,position)
if (is.null(k)) {
if (nnet <= 25) {
k <- ceiling(sqrt(nnet))
} else {
k <- ceiling(sqrt(nnet)) + 1
}
}
if (!is.null(thresh)) {
for (i in 1:length(net)) {
neti <- net[[i]]
neti[neti < quantile(c(neti[neti != 0]), thresh)] <- 0
net[[i]] <- neti
}
}
if (type == "functional") {
# compute the functional similarity
S3 <- matrix(0, nrow = nnet, ncol = nnet)
for (i in 1:nnet) {
for (j in 1:nnet) {
idx.i <- which(position - i >= 0)[1]
idx.j <- which(position - j >= 0)[1]
net.i <- net[[idx.i-1]]
net.j <- net[[idx.j-1]]
Gi <- (net.i[ , ,i-position[idx.i-1]] > 0)*1
Gj <- (net.j[ , ,j-position[idx.j-1]] > 0)*1
S3[i,j] <- sum(Gi * Gj)/sum(Gi+Gj-Gi*Gj,na.rm=TRUE)
}
}
# define the similarity matrix
S3[is.na(S3)] <- 0; diag(S3) <- 1
S_signalings <- S3
} else if (type == "structural") {
# compute the structure distance
D_signalings <- matrix(0, nrow = nnet, ncol = nnet)
for (i in 1:nnet) {
for (j in 1:nnet) {
idx.i <- which(position - i >= 0)[1]
idx.j <- which(position - j >= 0)[1]
net.i <- net[[idx.i-1]]
net.j <- net[[idx.j-1]]
Gi <- (net.i[ , ,i-position[idx.i-1]] > 0)*1
Gj <- (net.j[ , ,j-position[idx.j-1]] > 0)*1
D_signalings[i,j] <- computeNetD_structure(Gi,Gj)
}
}
# define the structure similarity matrix
D_signalings[is.infinite(D_signalings)] <- 0
D_signalings[is.na(D_signalings)] <- 0
S_signalings <- 1-D_signalings
}
# smooth the similarity matrix using SNN
SNN <- buildSNN(S_signalings, k = k, prune.SNN = 1/15)
Similarity <- as.matrix(S_signalings*SNN)
rownames(Similarity) <- signalingAll
colnames(Similarity) <- rownames(Similarity)
if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$matrix)) {
methods::slot(object, slot.name)$similarity[[type]]$matrix <- NULL
}
# methods::slot(object, slot.name)$similarity[[type]]$matrix <- Similarity
methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]] <- Similarity
return(object)
}
#' Manifold learning of the signaling networks based on their similarity
#'
#' @param object CellChat object
#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks
#' @param type "functional","structural"
#' @param comparison a numerical vector giving the datasets for comparison. No need to define for a single dataset. Default are all datasets when object is a merged object
#' @param pathway.remove a range of the number of patterns
#' @param umap.method UMAP implementation to run.
#'
#' Can be umap-learn: Run the python umap-learn package; uwot: Runs umap via the uwot R package; If umap.method = "uwot", please make sure you have installed the 'uwot' (https://github.com/jlmelville/uwot)
#'
#' @param n_neighbors the number of nearest neighbors in running umap
#' @param min_dist This controls how tightly the embedding is allowed compress points together.
#' Larger values ensure embedded points are moreevenly distributed, while smaller values allow the
#' algorithm to optimise more accurately with regard to local structure. Sensible values are in the range 0.001 to 0.5.
#' @param ... Parameters passing to umap
#' @importFrom methods slot
#' @return
#' @export
#'
#' @examples
netEmbedding <- function(object, slot.name = "netP", type = c("functional","structural"), comparison = NULL, pathway.remove = NULL,
umap.method = c("umap-learn", "uwot"), n_neighbors = NULL,min_dist = 0.3,...) {
umap.method <- match.arg(umap.method)
if (object@options$mode == "single") {
comparison <- "single"
cat("Manifold learning of the signaling networks for a single dataset", '\n')
} else if (object@options$mode == "merged") {
if (is.null(comparison)) {
comparison <- 1:length(unique(object@meta$datasets))
}
cat("Manifold learning of the signaling networks for datasets", as.character(comparison), '\n')
}
comparison.name <- paste(comparison, collapse = "-")
Similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]
if (is.null(pathway.remove)) {
pathway.remove <- rownames(Similarity)[which(colSums(Similarity) == 1)]
}
if (length(pathway.remove) > 0) {
pathway.remove.idx <- which(rownames(Similarity) %in% pathway.remove)
Similarity <- Similarity[-pathway.remove.idx, -pathway.remove.idx]
}
if (is.null(n_neighbors)) {
n_neighbors <- ceiling(sqrt(dim(Similarity)[1])) + 1
}
options(warn = -1)
# dimension reduction
if (umap.method == "umap-learn") {
Y <- runUMAP(Similarity, min_dist = min_dist, n_neighbors = n_neighbors,...)
} else if (umap.method == "uwot") {
Y <- uwot::umap(Similarity, min_dist = min_dist, n_neighbors = n_neighbors,...)
colnames(Y) <- paste0('UMAP', 1:ncol(Y))
rownames(Y) <- colnames(Similarity)
}
if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$dr)) {
methods::slot(object, slot.name)$similarity[[type]]$dr <- NULL
}
methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]] <- Y
return(object)
}
#' Classification learning of the signaling networks
#'
#' @param object CellChat object
#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks
#' @param type "functional","structural"
#' @param comparison a numerical vector giving the datasets for comparison. No need to define for a single dataset. Default are all datasets when object is a merged object
#' @param k the number of signaling groups when running kmeans
#' @param methods the methods for clustering: "kmeans" or "spectral"
#' @param do.plot whether showing the eigenspectrum for inferring number of clusters; Default will save the plot
#' @param fig.id add a unique figure id when saving the plot
#' @param do.parallel whether doing parallel when inferring the number of signaling groups when running kmeans
#' @param nCores number of workers when doing parallel
#' @param k.eigen the number of eigenvalues used when doing spectral clustering
#' @importFrom methods slot
#' @importFrom future nbrOfWorkers plan
#' @importFrom future.apply future_sapply
#' @importFrom pbapply pbsapply
#' @return
#' @export
#'
#' @examples
netClustering <- function(object, slot.name = "netP", type = c("functional","structural"), comparison = NULL, k = NULL, methods = "kmeans", do.plot = TRUE, fig.id = NULL, do.parallel = TRUE, nCores = 4, k.eigen = NULL) {
type <- match.arg(type)
if (object@options$mode == "single") {
comparison <- "single"
cat("Classification learning of the signaling networks for a single dataset", '\n')
} else if (object@options$mode == "merged") {
if (is.null(comparison)) {
comparison <- 1:length(unique(object@meta$datasets))
}
cat("Classification learning of the signaling networks for datasets", as.character(comparison), '\n')
}
comparison.name <- paste(comparison, collapse = "-")
Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]
data.use <- Y
if (methods == "kmeans") {
if (!is.null(k)) {
clusters = kmeans(data.use,k,nstart=10)$cluster
} else {
N <- nrow(data.use)
kRange <- seq(2,min(N-1, 10),by = 1)
if (do.parallel) {
future::plan("multisession", workers = nCores)
options(future.globals.maxSize = 1000 * 1024^2)
}
my.sapply <- ifelse(
test = future::nbrOfWorkers() == 1,
yes = pbapply::pbsapply,
no = future.apply::future_sapply
)
results = my.sapply(
X = 1:length(kRange),
FUN = function(x) {
idents <- kmeans(data.use,kRange[x],nstart=10)$cluster
clusIndex <- idents
#adjMat0 <- as.numeric(outer(clusIndex, clusIndex, FUN = "==")) - outer(1:N, 1:N, "==")
adjMat0 <- Matrix::Matrix(as.numeric(outer(clusIndex, clusIndex, FUN = "==")), nrow = N, ncol = N)
return(list(adjMat = adjMat0, ncluster = length(unique(idents))))
},
simplify = FALSE
)
adjMat <- lapply(results, "[[", 1)
CM <- Reduce('+', adjMat)/length(kRange)
res <- computeEigengap(as.matrix(CM))
numCluster <- res$upper_bound
clusters = kmeans(data.use,numCluster,nstart=10)$cluster
if (do.plot) {
gg <- res$gg.obj
ggsave(filename= paste0("estimationNumCluster_",fig.id,"_",type,"_dataset_",comparison.name,".pdf"), plot=gg, width = 3.5, height = 3, units = 'in', dpi = 300)
}
}
} else if (methods == "spectral") {
A <- as.matrix(data.use)
D <- apply(A, 1, sum)
L <- diag(D)-A # unnormalized version
L <- diag(D^-0.5)%*%L%*% diag(D^-0.5) # normalized version
evL <- eigen(L,symmetric=TRUE) # evL$values is decreasing sorted when symmetric=TRUE
# pick the first k first k eigenvectors (corresponding k smallest) as data points in spectral space
plot(rev(evL$values)[1:30])
Z <- evL$vectors[,(ncol(evL$vectors)-k.eigen+1):ncol(evL$vectors)]
clusters = kmeans(Z,k,nstart=20)$cluster
}
if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$group)) {
methods::slot(object, slot.name)$similarity[[type]]$group <- NULL
}
methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]] <- clusters
return(object)
}
#' Build SNN matrix
# #' Adapted from swne (https://github.com/yanwu2014/swne)
#' @param data.use Features x samples matrix to use to build the SNN
#' @param k Defines k for the k-nearest neighbor algorithm
#' @param k.scale Granularity option for k.param
#' @param prune.SNN Sets the cutoff for acceptable Jaccard distances when
#' computing the neighborhood overlap for the SNN construction.
#'
#' @return Returns similarity matrix in sparse matrix format
#'
#' @importFrom FNN get.knn
#' @importFrom Matrix sparseMatrix
#' @export
#'
buildSNN <- function(data.use, k = 10, k.scale = 10, prune.SNN = 1/15) {
n.cells <- ncol(data.use)
if (n.cells < k) {
stop("k cannot be greater than the number of samples")
}
## find the k-nearest neighbors for each single cell
my.knn <- FNN::get.knn(t(as.matrix(data.use)), k = min(k.scale * k, n.cells - 1))
nn.ranked <- cbind(1:n.cells, my.knn$nn.index[, 1:(k - 1)])
nn.large <- my.knn$nn.index
w <- ComputeSNN(nn.ranked, prune.SNN)
colnames(w) <- rownames(w) <- colnames(data.use)
Matrix::diag(w) <- 1
return(w)
}
#' Compute the eigengap of a given matrix for inferring the number of clusters
#'
#' @param CM consensus matrix
#' @param tau truncated consensus matrix
#' @param tol tolerance
#' @return
#' @import ggplot2
#' @export
computeEigengap <- function(CM, tau = NULL, tol = 0.01){
# compute the drop tolerance, enforcing parsimony of components
K.init <- computeLaplacian(CM, tol = tol)$n_zeros
if (is.null(tau)) {
if (K.init <= 5) {
tau = 0.3
} else if (K.init <= 10){
tau = 0.4
} else {
tau = 0.5
}
}
# truncate the ensemble consensus matrix
CM[CM <= tau] <- 0;
# normalize and make symmetric
CM <- (CM + t(CM))/2
eigs <- computeLaplacian(CM, tol = tol)
# compute the largest eigengap
gaps <- diff(eigs$val)
upper_bound <- which(gaps == max(gaps))
# compute the number of zero eigenvalues
lower_bound <- eigs$n_zeros
df <- data.frame(nCluster = 1:min(c(30,length(eigs$val))), eigenVal = eigs$val[1:min(c(30,length(eigs$val)))])
g <- ggplot(df, aes(x = nCluster, y = eigenVal)) + geom_point(size = 1) +
geom_point(aes(x= upper_bound, y= eigs$val[upper_bound]), colour="red", size = 3, pch = 1) + theme(legend.position="none")
title.name <- paste0('Inferred number of clusters: ', upper_bound,'; Min number: ', lower_bound)
g <- g + labs(title = title.name) + theme_bw() + scale_x_continuous(breaks=seq(0,30,5)) +
theme(plot.title = element_text(size = 10, face = "bold", hjust = 0.5)) +
theme(text = element_text(size = 10)) + labs(x = 'Number of clusters', y = 'Eigenvalue of graph Laplacian')+
theme(axis.text.x = element_text(size = 8), axis.text.y = element_text(size = 8))
# ggsave(filename= paste0("estimationNumCluster_eigenspectrum",sample.int(100,1),".pdf"), plot=g, width = 3.5, height = 3, units = 'in', dpi = 300)
return(list(upper_bound = upper_bound,
lower_bound = lower_bound,
eigs = eigs,
gg.obj = g))
}
#' Compute eigenvalues of associated Laplacian matrix of a given matrix
#'
#' @param CM consensus matrix
#' @param tol tolerance
#' @return
#' @importFrom RSpectra eigs_sym
#' @importFrom Matrix colSums
#' @export
computeLaplacian <- function(CM, tol = 0.01) {
# Normalized Laplacian:
Dsq <- sqrt(Matrix::colSums(CM))
L <- -Matrix::t(CM / Dsq) / Dsq
Matrix::diag(L) <- 1 + Matrix::diag(L)
numEigs <- min(100,nrow(CM))
res <- RSpectra::eigs_sym(L, k = numEigs, which = "SM", opt = list(tol = 1e-4))
eigs <- abs(Re(res$values))
n_zeros <- sum(eigs <= tol)
return(list(val = sort(eigs), n_zeros = n_zeros))
}
#' Rank the similarity of the shared signaling pathways based on their joint manifold learning
#'
#' @param object CellChat object
#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks
#' @param type "functional","structural"
#' @param comparison1 a numerical vector giving the datasets for comparison. This should be the same as `comparison` in `computeNetSimilarityPairwise`
#' @param comparison2 a numerical vector with two elements giving the datasets for comparison.
#'
#' If there are more than 2 datasets defined in `comparison1`, `comparison2` can be defined to indicate which two datasets used for computing the distance.
#' e.g., comparison2 = c(1,3) indicates the first and third datasets defined in `comparison1` will be used for comparison.
#' @param x.rotation rotation of x-labels
#' @param title main title of the plot
#' @param bar.w the width of bar plot
#' @param color.use defining the color
#' @param font.size font size
#' @import ggplot2
#' @importFrom methods slot
#' @return
#' @export
#'
#' @examples
rankSimilarity <- function(object, slot.name = "netP", type = c("functional","structural"), comparison1 = NULL, comparison2 = c(1,2),
x.rotation = 90, title = NULL, color.use = NULL, bar.w = NULL, font.size = 8) {
type <- match.arg(type)
if (is.null(comparison1)) {
comparison1 <- 1:length(unique(object@meta$datasets))
}
comparison.name <- paste(comparison1, collapse = "-")
cat("Compute the distance of signaling networks between datasets", as.character(comparison1[comparison2]), '\n')
comparison2.name <- names(methods::slot(object, slot.name))[comparison1[comparison2]]
# net <- list()
# for (i in 1:length(comparison2)) {
# net[[i]] = methods::slot(object, slot.name)[[comparison1[comparison2[i]]]]$prob
# }
#net.dim <- sapply(net, dim)[3,]
#position <- cumsum(net.dim); position <- c(0,position)
# if (is.null(pathway.remove)) {
# similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]
# pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]
# pathway.remove.idx <- which(rownames(similarity) %in% pathway.remove)
# }
# if (length(pathway.remove.idx) > 0) {
# for (i in 1:length(pathway.remove.idx)) {
# idx <- which(position - pathway.remove.idx[i] > 0)
# if (!is.null(idx)) {
# position[idx[1]] <- position[idx[1]] - 1
# if (idx[1] == 2) {
# position[3] <- position[3] - 1
# }
# }
# }
# }
Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]
group <- sub(".*--", "", rownames(Y))
data1 <- Y[group %in% comparison2.name[1], ]
data2 <- Y[group %in% comparison2.name[2], ]
rownames(data1) <- sub("--.*", "", rownames(data1))
rownames(data2) <- sub("--.*", "", rownames(data2))
pathway.show = as.character(intersect(rownames(data1), rownames(data2)))
data1 <- data1[pathway.show, ]
data2 <- data2[pathway.show, ]
euc.dist <- function(x1, x2) sqrt(sum((x1 - x2) ^ 2))
dist <- NULL
for(i in 1:nrow(data1)) dist[i] <- euc.dist(data1[i,],data2[i,])
df <- data.frame(name = pathway.show, dist = dist, row.names = pathway.show)
df <- df[order(df$dist), , drop = F]
df$name <- factor(df$name, levels = as.character(df$name))
gg <- ggplot(df, aes(x=name, y=dist)) + geom_bar(stat="identity",width = bar.w) +
theme_classic() + theme(text=element_text(size=font.size),axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.title.y = element_text(size=font.size)) +
xlab("") + ylab("Pathway distance") + coord_flip()#+
if (!is.null(title)) {
gg <- gg + ggtitle(title)+ theme(plot.title = element_text(hjust = 0.5))
}
if (!is.null(color.use)) {
gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = 1), drop = FALSE, na.value = "white")
gg <- gg + scale_colour_manual(values = color.use, drop = FALSE, na.value = "white")
}
return(gg)
}
#' Rank signaling networks based on the information flow or the number of interactions
#'
#' This function can also be used to rank signaling from certain cell groups to other cell groups
#'
#' @param object CellChat object
#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks
#' @param measure "weight" or "count". "weight": comparing the total interaction weights (strength); "count": comparing the number of interactions;
#' @param mode "single","comparison"
#' @param comparison a numerical vector giving the datasets for comparison; a single value means ranking for only one dataset and two values means ranking comparison for two datasets
#' @param color.use defining the color for each cell group
#' @param stacked whether plot the stacked bar plot
#' @param sources.use a vector giving the index or the name of source cell groups
#' @param targets.use a vector giving the index or the name of target cell groups.
#' @param signaling a vector giving the signaling pathway to show
#' @param pairLR a vector giving the names of L-R pairs to show (e.g, pairLR = c("IL1A_IL1R1_IL1RAP","IL1B_IL1R1_IL1RAP"))
#' @param signaling.type a char giving the types of signaling from the three categories c("Secreted Signaling", "ECM-Receptor", "Cell-Cell Contact")