-
Notifications
You must be signed in to change notification settings - Fork 102
/
clustering.R
4158 lines (3638 loc) · 131 KB
/
clustering.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
#' @title doLeidenCluster
#' @name doLeidenCluster
#' @description cluster cells using a NN-network and the Leiden community
#' detection algorithm
#' @param gobject giotto object
#' @param spat_unit spatial unit (e.g. "cell")
#' @param feat_type feature type (e.g. "rna", "dna", "protein")
#' @param name name for cluster, default to "leiden_clus"
#' @param nn_network_to_use type of NN network to use (kNN vs sNN), default to
#' "sNN"
#' @param network_name name of NN network to use, default to "sNN.pca"
#' @param python_path specify specific path to python if required
#' @param resolution resolution, default = 1
#' @param weight_col weight column to use for edges, default to "weight"
#' @param partition_type The type of partition to use for optimization.
#' (e.g. "RBConfigurationVertexPartition", "ModularityVertexPartition")
#' @param init_membership initial membership of cells for the partition
#' @param n_iterations number of interactions to run the Leiden algorithm.
#' If the number of iterations is negative, the Leiden algorithm is run until
#' an iteration in which there was no improvement.
#' @param return_gobject logical. return giotto object (default = TRUE)
#' @param set_seed set seed
#' @param seed_number number for seed
#' @returns giotto object with new clusters appended to cell metadata
#' @details
#' This function is a wrapper for the Leiden algorithm implemented in python,
#' which can detect communities in graphs of millions of nodes (cells),
#' as long as they can fit in memory. See the
#' [leidenalg](https://github.com/vtraag/leidenalg)
#' github page or the
#' [readthedocs](https://leidenalg.readthedocs.io/en/stable/index.html)
#' page for more information.
#'
#' Partition types available and information:
#' * **RBConfigurationVertexPartition:** Implements Reichardt and Bornholdt’s
#' Potts model with a configuration null model. This quality function is
#' well-defined only for positive edge weights. This quality function uses a
#' linear resolution parameter.
#' * **ModularityVertexPartition:** Implements modularity. This quality
#' function is well-defined only for positive edge weights. It does \emph{not}
#' use the resolution parameter
#'
#' Set \emph{weight_col = NULL} to give equal weight (=1) to each edge.
#' @md
#' @examples
#' g <- GiottoData::loadGiottoMini("visium")
#'
#' doLeidenCluster(g)
#' @export
doLeidenCluster <- function(
gobject,
spat_unit = NULL,
feat_type = NULL,
name = "leiden_clus",
nn_network_to_use = "sNN",
network_name = "sNN.pca",
python_path = NULL,
resolution = 1,
weight_col = "weight",
partition_type = c(
"RBConfigurationVertexPartition",
"ModularityVertexPartition"
),
init_membership = NULL,
n_iterations = 1000,
return_gobject = TRUE,
set_seed = TRUE,
seed_number = 1234) {
# Set feat_type and spat_unit
spat_unit <- set_default_spat_unit(
gobject = gobject,
spat_unit = spat_unit
)
feat_type <- set_default_feat_type(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type
)
## get cell IDs ##
cell_ID_vec <- gobject@cell_ID[[spat_unit]]
## select network to use
igraph_object <- getNearestNetwork(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type,
nn_type = nn_network_to_use,
name = network_name,
output = "igraph"
)
## select partition type
partition_type <- match.arg(partition_type,
choices = c(
"RBConfigurationVertexPartition", "ModularityVertexPartition"
)
)
## check or make paths
# python path
if (is.null(python_path)) {
python_path <- readGiottoInstructions(gobject, param = "python_path")
}
## prepare python path and louvain script
reticulate::use_python(required = TRUE, python = python_path)
python_leiden_function <- system.file("python", "python_leiden.py",
package = "Giotto"
)
reticulate::source_python(file = python_leiden_function)
## set seed
if (isTRUE(set_seed)) {
seed_number <- as.integer(seed_number)
} else {
seed_number <- as.integer(sample(x = seq(10000), size = 1))
}
## extract NN network
network_edge_dt <- data.table::as.data.table(
igraph::as_data_frame(x = igraph_object, what = "edges")
)
# data.table variables
weight <- NULL
# add weight for edges or set to 1 for all
if (!is.null(weight_col)) {
if (!weight_col %in% colnames(network_edge_dt)) {
stop("weight column is not an igraph attribute")
} else {
# weight is defined by attribute of igraph object
network_edge_dt <- network_edge_dt[
, c("from", "to", weight_col),
with = FALSE
]
data.table::setnames(network_edge_dt, weight_col, "weight")
}
} else {
# weight is the same
network_edge_dt <- network_edge_dt[, c("from", "to"), with = FALSE]
network_edge_dt[, weight := 1]
}
## do python leiden clustering
reticulate::py_set_seed(
seed = seed_number,
disable_hash_randomization = TRUE
)
pyth_leid_result <- python_leiden(
df = network_edge_dt,
partition_type = partition_type,
initial_membership = init_membership,
weights = "weight",
n_iterations = n_iterations,
seed = seed_number,
resolution_parameter = resolution
)
ident_clusters_DT <- data.table::data.table(
cell_ID = pyth_leid_result[[1]], "name" = pyth_leid_result[[2]]
)
data.table::setnames(ident_clusters_DT, "name", name)
## add clusters to metadata ##
if (return_gobject == TRUE) {
cluster_names <- names(pDataDT(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type
))
if (name %in% cluster_names) {
cat(name, " has already been used, will be overwritten")
cell_metadata <- getCellMetadata(
gobject,
spat_unit = spat_unit,
feat_type = feat_type,
output = "cellMetaObj",
copy_obj = TRUE
)
cell_metadata[][, eval(name) := NULL]
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
gobject <- setCellMetadata(
gobject,
x = cell_metadata,
verbose = FALSE,
initialize = FALSE
)
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
}
gobject <- addCellMetadata(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type,
new_metadata = ident_clusters_DT[
, c("cell_ID", name),
with = FALSE
],
by_column = TRUE,
column_cell_ID = "cell_ID"
)
## update parameters used ##
gobject <- update_giotto_params(gobject, description = "_cluster")
return(gobject)
} else {
# else return clustering result
return(ident_clusters_DT)
}
}
#' @title doLeidenClusterIgraph
#' @name doLeidenClusterIgraph
#' @description cluster cells using a NN-network and the Leiden community
#' detection algorithm as implemented in igraph
#' @param gobject giotto object
#' @param spat_unit spatial unit (e.g. "cell")
#' @param feat_type feature type (e.g. "rna", "dna", "protein")
#' @param name name for cluster, default to "leiden_clus"
#' @param nn_network_to_use type of NN network to use (kNN vs sNN), default to
#' "sNN"
#' @param network_name name of NN network to use, default to "sNN.pca"
#' @param objective_function objective function for the leiden algo
#' @param weights weights of edges
#' @param resolution resolution, default = 1
#' @param resolution_parameter deprecated. Use `resolution` instead
#' @param beta leiden randomness
#' @param initial_membership initial membership of cells for the partition
#' @param n_iterations number of interations to run the Leiden algorithm.
#' @param return_gobject boolean: return giotto object (default = TRUE)
#' @param set_seed set seed
#' @param seed_number number for seed
#' @inheritDotParams igraph::cluster_leiden -graph -objective_function
#' -resolution_parameter -beta -weights -initial_membership -n_iterations
#' -resolution
#' @returns giotto object with new clusters appended to cell metadata
#' @details
#' This function is a wrapper for the Leiden algorithm implemented in igraph,
#' which can detect communities in graphs of millions of nodes (cells),
#' as long as they can fit in memory. See \code{\link[igraph]{cluster_leiden}}
#' for more information.
#'
#' Set \emph{weights = NULL} to use the vertices weights associated with the
#' igraph network.
#' Set \emph{weights = NA} if you don't want to use vertices weights
#'
#' @examples
#' g <- GiottoData::loadGiottoMini("visium")
#'
#' doLeidenClusterIgraph(g)
#' @export
doLeidenClusterIgraph <- function(
gobject,
spat_unit = NULL,
feat_type = NULL,
name = "leiden_clus",
nn_network_to_use = "sNN",
network_name = "sNN.pca",
objective_function = c("modularity", "CPM"),
weights = NULL,
resolution = 1,
resolution_parameter = deprecated(),
beta = 0.01,
initial_membership = NULL,
n_iterations = 1000,
return_gobject = TRUE,
set_seed = TRUE,
seed_number = 1234,
...) {
# Set feat_type and spat_unit
spat_unit <- set_default_spat_unit(
gobject = gobject,
spat_unit = spat_unit
)
feat_type <- set_default_feat_type(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type
)
resolution <- deprecate_param(
x = resolution_parameter,
y = resolution,
fun = "doLeidenClusterIgraph",
when = "4.1.4"
)
## get cell IDs ##
cell_ID_vec <- gobject@cell_ID[[spat_unit]]
## select network to use
igraph_object <- getNearestNetwork(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type,
nn_type = nn_network_to_use,
name = network_name,
output = "igraph"
)
## select partition type
objective_function <- match.arg(objective_function,
choices = c("modularity", "CPM")
)
## set seed
if (isTRUE(set_seed)) {
seed_number <- as.integer(seed_number)
set.seed(seed_number)
on.exit(expr = {
GiottoUtils::random_seed(set.seed = TRUE)
}, add = TRUE)
}
# make igraph network undirected
graph_object_undirected <- igraph::as.undirected(igraph_object)
leiden_clusters <- igraph::cluster_leiden(
graph = graph_object_undirected,
objective_function = objective_function,
resolution = resolution,
beta = beta,
weights = weights,
initial_membership = initial_membership,
n_iterations = n_iterations,
...
)
# summarize results
ident_clusters_DT <- data.table::data.table(
"cell_ID" = leiden_clusters$names, "name" = leiden_clusters$membership
)
data.table::setnames(ident_clusters_DT, "name", name)
## add clusters to metadata ##
if (isTRUE(return_gobject)) {
cluster_names <- names(pDataDT(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type
))
if (name %in% cluster_names) {
cat(name, " has already been used, will be overwritten")
cell_metadata <- getCellMetadata(gobject,
spat_unit = spat_unit,
feat_type = feat_type,
output = "cellMetaObj",
copy_obj = TRUE
)
cell_metadata[][, eval(name) := NULL]
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
gobject <- setCellMetadata(gobject,
x = cell_metadata,
verbose = FALSE,
initialize = FALSE
)
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
}
gobject <- addCellMetadata(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type,
new_metadata = ident_clusters_DT[
, c("cell_ID", name),
with = FALSE
],
by_column = TRUE,
column_cell_ID = "cell_ID"
)
## update parameters used ##
gobject <- update_giotto_params(gobject, description = "_cluster")
return(gobject)
} else {
# else return clustering result
return(ident_clusters_DT)
}
}
#' @title doGiottoClustree
#' @name doGiottoClustree
#' @description cluster cells using leiden methodology to visualize different
#' resolutions
#' @param gobject giotto object
#' @param res_vector vector of different resolutions to test
#' @param res_seq list of float numbers indicating start, end, and step size
#' for resolution testing, i.e. (0.1, 0.6, 0.1)
#' @param return_gobject default FALSE. See details for more info.
#' @param show_plot by default, pulls from provided gobject instructions
#' @param save_plot by default, pulls from provided gobject instructions
#' @param return_plot by default, pulls from provided gobject instructions
#' @param save_param list of saving parameters from
#' [GiottoVisuals::all_plots_save_function()]
#' @param default_save_name name of saved plot, default "clustree"
#' @param verbose be verbose
#' @inheritDotParams clustree::clustree -x
#' @returns a plot object (default), OR a giotto object (if specified)
#' @details This function tests different resolutions for Leiden clustering and
#' provides a visualization of cluster sizing as resolution varies.
#'
#' By default, the tested leiden clusters are NOT saved to the Giotto object,
#' and a plot is returned.
#'
#' If return_gobject is set to TRUE, and a giotto object with *all* tested
#' leiden cluster information
#' will be returned.
#' @seealso \code{\link{doLeidenCluster}}
#' @md
#' @examples
#' g <- GiottoData::loadGiottoMini("visium")
#'
#' doGiottoClustree(
#' gobject = g, res_vector = c(0.5, 0.8), return_plot = FALSE,
#' show_plot = FALSE, save_plot = FALSE
#' )
#' @export
doGiottoClustree <- function(
gobject,
res_vector = NULL,
res_seq = NULL,
return_gobject = FALSE,
show_plot = NULL,
save_plot = NULL,
return_plot = NULL,
save_param = list(),
default_save_name = "clustree",
verbose = TRUE,
...) {
package_check(pkg_name = "clustree", repository = "CRAN")
## setting resolutions to use
if (is.null(res_vector)) {
if (!is.null(res_seq)) {
res_vector <- seq(res_seq[1], res_seq[2], res_seq[3])
} else {
stop("Please input res_vector or res_seq parameters")
}
}
## performing multiple leiden clusters at resolutions specified
for (i in res_vector) {
if (isTRUE(verbose)) wrap_msg("Calculating leiden res:", i)
gobject <- doLeidenCluster(
gobject = gobject,
resolution = i,
name = paste0("leiden_clustree_", i)
)
}
## plotting clustree graph
pl <- clustree::clustree(
x = pDataDT(gobject),
prefix = "leiden_clustree_",
...
)
# output plot
return(GiottoVisuals::plot_output_handler(
gobject = gobject,
plot_object = pl,
save_plot = save_plot,
return_plot = return_plot,
show_plot = show_plot,
default_save_name = default_save_name,
save_param = save_param,
else_return = NULL
))
}
#' @title doLouvainCluster community
#' @name .doLouvainCluster_community
#' @description cluster cells using a NN-network and the Louvain algorithm
#' from the community module in Python
#' @param gobject giotto object
#' @param spat_unit spatial unit (e.g. "cell")
#' @param feat_type feature type (e.g. "rna", "dna", "protein")
#' @param name name for cluster, default to "louvain_clus"
#' @param nn_network_to_use type of NN network to use (kNN vs sNN), default to
#' "sNN"
#' @param network_name name of NN network to use, default to "sNN.pca"
#' @param python_path specify specific path to python if required
#' @param resolution resolution, default = 1
#' @param weight_col weight column to use for edges
#' @param louv_random Will randomize the node evaluation order and the
#' community evaluation order to get different partitions at each call
#' (default = FALSE)
#' @param return_gobject logical. return giotto object (default = TRUE)
#' @param set_seed set seed (default = FALSE)
#' @param seed_number number for seed
#' @param \dots additional params to pass
#' @returns giotto object with new clusters appended to cell metadata
#' @details This function is a wrapper for the Louvain algorithm implemented in
#' Python, which can detect communities in graphs of nodes (cells).
#' See the
#' [readthedocs](https://python-louvain.readthedocs.io/en/latest/index.html)
#' page for more information.
#'
#' Set \emph{weight_col = NULL} to give equal weight (=1) to each edge.
#' @md
#' @keywords internal
.doLouvainCluster_community <- function(
gobject,
spat_unit = NULL,
feat_type = NULL,
name = "louvain_clus",
nn_network_to_use = "sNN",
network_name = "sNN.pca",
python_path = NULL,
resolution = 1,
weight_col = NULL,
louv_random = FALSE,
return_gobject = TRUE,
set_seed = FALSE,
seed_number = 1234,
...) {
# Set feat_type and spat_unit
spat_unit <- set_default_spat_unit(
gobject = gobject,
spat_unit = spat_unit
)
feat_type <- set_default_feat_type(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type
)
## get cell IDs ##
cell_ID_vec <- gobject@cell_ID[[spat_unit]]
## select network to use
igraph_object <- getNearestNetwork(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type,
nn_type = nn_network_to_use,
name = network_name,
output = "igraph"
)
## check or make paths
# python path
if (is.null(python_path)) {
python_path <- readGiottoInstructions(gobject, param = "python_path")
}
# prepare python path and louvain script
reticulate::use_python(required = TRUE, python = python_path)
python_louvain_function <- system.file(
"python", "python_louvain.py",
package = "Giotto"
)
reticulate::source_python(file = python_louvain_function)
# set seed
if (isTRUE(set_seed)) {
seed_number <- as.integer(seed_number)
} else {
seed_number <- as.integer(sample(x = seq(10000), size = 1))
}
network_edge_dt <- data.table::as.data.table(igraph::as_data_frame(
x = igraph_object, what = "edges"
))
# data.table variables
weight <- NULL
if (!is.null(weight_col)) {
if (!weight_col %in% colnames(network_edge_dt)) {
stop("weight column is not an igraph attribute")
} else {
# weight is defined by attribute of igraph object
network_edge_dt <- network_edge_dt[
, c("from", "to", weight_col),
with = FALSE
]
setnames(network_edge_dt, weight_col, "weight")
}
} else {
# weight is the same
network_edge_dt <- network_edge_dt[, c("from", "to"), with = FALSE]
network_edge_dt[, weight := 1]
}
# do python louvain clustering
if (louv_random == FALSE) {
reticulate::py_set_seed(
seed = seed_number, disable_hash_randomization = TRUE
)
pyth_louv_result <- python_louvain(
df = network_edge_dt, resolution = resolution, randomize = FALSE
)
} else {
reticulate::py_set_seed(
seed = seed_number, disable_hash_randomization = TRUE
)
pyth_louv_result <- python_louvain(
df = network_edge_dt,
resolution = resolution,
random_state = seed_number
)
}
ident_clusters_DT <- data.table::data.table(
cell_ID = rownames(pyth_louv_result), "name" = pyth_louv_result[[1]]
)
data.table::setnames(ident_clusters_DT, "name", name)
## return
if (isTRUE(return_gobject)) {
# get cell metadata names
cluster_names <- names(pDataDT(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type
))
# set name/cluster results to NULL if already exist
if (name %in% cluster_names) {
cat(name, " has already been used, will be overwritten")
cell_metadata <- getCellMetadata(gobject,
spat_unit = spat_unit,
feat_type = feat_type,
output = "cellMetaObj",
copy_obj = TRUE
)
cell_metadata[][, eval(name) := NULL]
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
gobject <- setCellMetadata(gobject,
x = cell_metadata,
verbose = FALSE,
initialize = FALSE
)
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
}
# add new metadata information
gobject <- addCellMetadata(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type,
new_metadata = ident_clusters_DT[
, c("cell_ID", name),
with = FALSE
],
by_column = TRUE, column_cell_ID = "cell_ID"
)
## update parameters used ##
# 1. get parent function name
cl <- sys.call(-1)
# 2. check if this function call is within doLouvainCluster
if (is.null(cl)) {
gobject <- update_giotto_params(gobject, description = "_cluster")
} else {
fname <- as.character(cl[[1]])
if (fname == "doLouvainCluster") {
gobject <- update_giotto_params(gobject,
description = "_cluster",
toplevel = 3
)
} else {
gobject <- update_giotto_params(gobject,
description = "_cluster"
)
}
}
return(gobject)
} else {
# else return clustering result
return(ident_clusters_DT)
}
}
#' @title doLouvainCluster multinet
#' @name .doLouvainCluster_multinet
#' @description cluster cells using a NN-network and the Louvain algorithm from
#' the multinet package in R.
#' @param gobject giotto object
#' @param spat_unit spatial unit (e.g. "cell")
#' @param feat_type feature type (e.g. "rna", "dna", "protein")
#' @param name name for cluster, default to "louvain_clus"
#' @param nn_network_to_use type of NN network to use (kNN vs sNN), default to
#' "sNN"
#' @param network_name name of NN network to use, default to "sNN.pca"
#' @param gamma Resolution parameter for modularity in the generalized louvain
#' method. default = 1
#' @param omega Inter-layer weight parameter in the generalized louvain method.
#' default = 1
#' @param return_gobject boolean: return giotto object (default = TRUE)
#' @param set_seed set seed (default = FALSE)
#' @param seed_number number for seed
#' @returns giotto object with new clusters appended to cell metadata
#' @details See \code{\link[multinet]{glouvain_ml}} from the multinet package
#' in R for more information.
#'
#' @keywords internal
.doLouvainCluster_multinet <- function(
gobject,
spat_unit = NULL,
feat_type = NULL,
name = "louvain_clus",
nn_network_to_use = "sNN",
network_name = "sNN.pca",
gamma = 1,
omega = 1,
return_gobject = TRUE,
set_seed = FALSE,
seed_number = 1234) {
if ("multinet" %in% rownames(installed.packages()) == FALSE) {
stop(
"package 'multinet' is not yet installed \n",
"To install: \n",
"install.packages('multinet')"
)
}
# Set feat_type and spat_unit
spat_unit <- set_default_spat_unit(
gobject = gobject,
spat_unit = spat_unit
)
feat_type <- set_default_feat_type(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type
)
## get cell IDs ##
cell_ID_vec <- gobject@cell_ID[[spat_unit]]
## select network to use
igraph_object <- getNearestNetwork(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type,
nn_type = nn_network_to_use,
name = network_name,
output = "igraph"
)
# create mlnetworkobject
mln_object <- multinet::ml_empty()
# multinet::add_vertices_ml(
# n = mln_object, vertices = igraph::V(igraph_object))
multinet::add_igraph_layer_ml(
n = mln_object, g = igraph_object, name = name
)
# start seed
if (isTRUE(set_seed)) {
set.seed(seed = as.integer(seed_number))
}
# data.table variables
cell_ID <- actor <- weight_col <- NULL
louvain_clusters <- multinet::glouvain_ml(
n = mln_object, gamma = gamma, omega = omega
)
ident_clusters_DT <- data.table::as.data.table(louvain_clusters)
ident_clusters_DT[, cell_ID := actor]
data.table::setnames(ident_clusters_DT, "cid", name)
# exit seed
if (isTRUE(set_seed)) {
set.seed(Sys.time())
}
## return
if (isTRUE(return_gobject)) {
# get cell metadata names
cluster_names <- names(pDataDT(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type
))
# set name/cluster results to NULL if already exist
if (name %in% cluster_names) {
cat(name, " has already been used, will be overwritten")
cell_metadata <- getCellMetadata(gobject,
spat_unit = spat_unit,
feat_type = feat_type,
output = "cellMetaObj",
copy_obj = TRUE
)
cell_metadata[][, eval(name) := NULL]
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
gobject <- setCellMetadata(gobject,
x = cell_metadata,
verbose = FALSE,
initialize = FALSE
)
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
}
# add new metadata information
gobject <- addCellMetadata(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type,
new_metadata = ident_clusters_DT[
, c("cell_ID", name),
with = FALSE
],
by_column = TRUE, column_cell_ID = "cell_ID"
)
## update parameters used ##
# 1. get parent function name
cl <- sys.call(-1)
# 2. check if this function call is within doLouvainCluster
if (is.null(cl)) {
gobject <- update_giotto_params(gobject, description = "_cluster")
} else {
fname <- as.character(cl[[1]])
if (fname == "doLouvainCluster") {
gobject <- update_giotto_params(gobject,
description = "_cluster",
toplevel = 3
)
} else {
gobject <- update_giotto_params(gobject,
description = "_cluster"
)
}
}
return(gobject)
} else {
# else return clustering result
return(ident_clusters_DT)
}
}
#' @title doLouvainCluster
#' @name doLouvainCluster
#' @description cluster cells using a NN-network and the Louvain algorithm.
#'
#' @param gobject giotto object
#' @param spat_unit spatial unit (e.g. "cell")
#' @param feat_type feature type (e.g. "rna", "dna", "protein")
#' @param version implemented version of Louvain clustering to use
#' @param name name for cluster, default to "louvain_clus"
#' @param nn_network_to_use type of NN network to use (kNN vs sNN), default to
#' "sNN"
#' @param network_name name of NN network to use, default to "sNN.pca"
#' @param python_path [community] specify specific path to python if required
#' @param resolution [community] resolution, default = 1
#' @param louv_random [community] Will randomize the node evaluation order and
#' the community evaluation order to get different partitions at each call
#' (default = FALSE)
#' @param weight_col weight column name
#' @param gamma [multinet] Resolution parameter for modularity in the
#' generalized louvain method, default = 1
#' @param omega [multinet] Inter-layer weight parameter in the generalized
#' louvain method, default = 1
#' @param return_gobject boolean: return giotto object (default = TRUE)
#' @param set_seed set seed (default = FALSE)
#' @param ... arguments passed to \code{\link{.doLouvainCluster_community}} or
#' \code{\link{.doLouvainCluster_multinet}}
#' @param seed_number number for seed
#'
#' @returns giotto object with new clusters appended to cell metadata
#' @details Louvain clustering using the community or multinet implementation
#' of the louvain clustering algorithm.
#' @seealso \code{\link{.doLouvainCluster_community}} and
#' \code{\link{.doLouvainCluster_multinet}}
#' @examples
#' g <- GiottoData::loadGiottoMini("visium")
#'
#' doLouvainCluster(g)
#' @export
doLouvainCluster <- function(
gobject,
spat_unit = NULL,
feat_type = NULL,
version = c("community", "multinet"),
name = "louvain_clus",
nn_network_to_use = "sNN",
network_name = "sNN.pca",
python_path = NULL,
resolution = 1,
weight_col = NULL,
gamma = 1,
omega = 1,
louv_random = FALSE,
return_gobject = TRUE,
set_seed = FALSE,
seed_number = 1234,
...) {
# Set feat_type and spat_unit
spat_unit <- set_default_spat_unit(
gobject = gobject,
spat_unit = spat_unit
)
feat_type <- set_default_feat_type(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type
)
## louvain clustering version to use
version <- match.arg(version, c("community", "multinet"))
# python community implementation
if (version == "community") {
result <- .doLouvainCluster_community(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type,
name = name,
nn_network_to_use = nn_network_to_use,
network_name = network_name,
python_path = python_path,
resolution = resolution,
weight_col = weight_col,
louv_random = louv_random,
return_gobject = return_gobject,
set_seed = set_seed,
seed_number = seed_number,
...
)
return(result)
## r multinet implementation
} else if (version == "multinet") {
result <- .doLouvainCluster_multinet(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type,
name = name,
nn_network_to_use = nn_network_to_use,
network_name = network_name,
gamma = gamma,
omega = omega,
return_gobject = return_gobject,
set_seed = set_seed,
seed_number = seed_number
)
return(result)
}
}
#' @title doRandomWalkCluster
#' @name doRandomWalkCluster
#' @description Cluster cells using a random walk approach.
#' @param gobject giotto object
#' @param name name for cluster, default to "random_walk_clus"