forked from zhanghao-njmu/SCP
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSCP-workflow.R
3629 lines (3445 loc) · 157 KB
/
SCP-workflow.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
#' Check and report the type of data
#'
#' @param srt A Seurat object
#' @param data Use a data instead of getting it from a Seurat object.
#' @param slot Specific slot to get data from.
#' @param assay Specific assay to get data from.
#'
#' @importFrom Seurat DefaultAssay GetAssayData
#' @export
check_DataType <- function(srt, data = NULL, slot = "data", assay = NULL) {
if (is.null(data)) {
assay <- assay %||% DefaultAssay(srt)
data <- GetAssayData(srt, slot = slot, assay = assay)
}
isfinite <- all(is.finite(range(data, na.rm = TRUE)))
if (inherits(data, "dgCMatrix")) {
isfloat <- any(data@x %% 1 != 0, na.rm = TRUE)
} else {
isfloat <- any(data[, sample(seq_len(ncol(data)), min(ncol(data), 1000))] %% 1 != 0, na.rm = TRUE)
}
islog <- is.finite(expm1(x = max(data, na.rm = TRUE)))
isnegative <- any(data < 0)
if (!isTRUE(isfinite)) {
warning("Infinite values detected!", immediate. = TRUE)
return("unknown")
} else if (isTRUE(isnegative)) {
warning("Negative values detected!", immediate. = TRUE)
return("unknown")
} else {
if (!isfloat) {
return("raw_counts")
} else if (isfloat && islog) {
return("log_normalized_counts")
} else if (isfloat && !islog) {
if (isFALSE(isnegative)) {
return("raw_normalized_counts")
} else {
return("unknown")
}
}
}
}
#' Check and preprocess a list of seurat objects
#'
#' @inheritParams Integration_SCP
#'
#' @importFrom Seurat SplitObject GetAssayData Assays NormalizeData FindVariableFeatures SCTransform SCTResults SelectIntegrationFeatures PrepSCTIntegration DefaultAssay DefaultAssay<- VariableFeatures VariableFeatures<-
#' @importFrom Signac RunTFIDF
#' @importFrom Matrix rowSums
#' @importFrom utils head
#' @export
#'
check_srtList <- function(srtList, batch = NULL, assay = NULL,
do_normalization = NULL, normalization_method = "LogNormalize",
do_HVF_finding = TRUE, HVF_source = "separate", HVF_method = "vst",
nHVF = 2000, HVF_min_intersection = 1, HVF = NULL,
vars_to_regress = NULL, seed = 11, ...) {
cat(paste0("[", Sys.time(), "]", " Checking srtList... ...\n"))
set.seed(seed)
if (!inherits(srtList, "list") || any(sapply(srtList, function(x) !inherits(x, "Seurat")))) {
stop("'srtList' is not a list of Seurat object.")
}
if (!normalization_method %in% c("LogNormalize", "SCT", "TFIDF")) {
stop("'normalization_method' must be one of: 'LogNormalize', 'SCT', 'TFIDF'")
}
if (normalization_method %in% c("SCT")) {
check_R("glmGamPoi")
}
if (!HVF_source %in% c("global", "separate")) {
stop("'HVF_source' must be one of: 'global', 'separate'")
}
if (any(sapply(srtList, ncol) < 3)) {
stop(paste0(
"Seurat objects in srtList contain less than 3 cells. srtList index: ",
paste0(which(sapply(srtList, ncol) < 3), collapse = ",")
))
}
if (is.null(assay)) {
default_assay <- unique(sapply(srtList, DefaultAssay))
if (length(default_assay) != 1) {
stop("The default assay name of the Seurat object in the srtlist is inconsistent.")
} else {
assay <- default_assay
}
}
assay_type <- unique(sapply(srtList, function(srt) class(srt[[assay]])))
if (length(assay_type) != 1) {
stop("The assay type of the Seurat object in the srtlist is inconsistent.")
} else {
if (assay_type == "Assay") {
type <- "RNA"
} else if (assay_type == "ChromatinAssay") {
type <- "Chromatin"
}
}
features_list <- lapply(srtList, function(srt) {
sort(rownames(srt[[assay]]))
})
if (length(unique(features_list)) != 1) {
if (type == "Chromatin") {
warning("The peaks in assay ", assay, " is different between batches. Creating a common set of peaks and may take a long time...")
srtMerge <- Reduce(merge, srtList)
srtList <- SplitObject(object = srtMerge, split.by = batch)
}
cf <- Reduce(intersect, lapply(srtList, function(srt) rownames(srt[[assay]])))
warning("'srtList' have different feature names! Will subset the common features(", length(cf), ") for downstream analysis!", immediate. = TRUE)
for (i in seq_along(srtList)) {
srtList[[i]][[assay]] <- subset(srtList[[i]][[assay]], features = cf)
}
}
celllist <- unlist(lapply(srtList, colnames))
if (length(celllist) != length(unique(celllist))) {
stop("'srtList' have duplicated cell names!")
}
if (length(batch) != 1 && length(batch) != length(srtList)) {
stop("'batch' must be a character to specify the batch column in the meta.data or a vector of the same length of the srtList!")
}
if (length(batch) == length(srtList)) {
srtList_tmp <- list()
for (bat in unique(batch)) {
srtList_tmp[[bat]] <- Reduce(merge, srtList[batch == bat])
}
srtList <- srtList_tmp
} else {
if (!all(sapply(srtList, function(x) {
batch %in% colnames([email protected])
}))) {
stop(paste0("batch column('", batch, "') was not found in one or more object of the srtList!"))
}
for (i in seq_along(srtList)) {
u <- unique(srtList[[i]][[batch, drop = TRUE]])
if (length(u) > 1) {
x <- SplitObject(srtList[[i]], split.by = batch)
srtList[[i]] <- character(0)
srtList <- c(srtList, x)
}
}
srtList <- srtList[sapply(srtList, length) > 0]
srtList_batch <- sapply(srtList, function(x) unique(x[[batch, drop = TRUE]]))
batch_to_merge <- names(which(table(srtList_batch) > 1))
if (length(batch_to_merge) > 0) {
for (b in batch_to_merge) {
index <- which(srtList_batch == b)
srtList_tmp <- Reduce(merge, srtList[index])
for (i in index) {
srtList[[i]] <- character(0)
}
srtList <- c(srtList, srtList_tmp)
}
}
srtList <- srtList[sapply(srtList, length) > 0]
}
for (i in seq_along(srtList)) {
if (!assay %in% Assays(srtList[[i]])) {
stop(paste0("srtList ", i, " does not contain '", assay, "' assay."))
}
DefaultAssay(srtList[[i]]) <- assay
if (isTRUE(do_normalization)) {
if (normalization_method == "LogNormalize") {
cat("Perform NormalizeData(LogNormalize) on the data ", i, "/", length(srtList), " of the srtList...\n", sep = "")
srtList[[i]] <- suppressWarnings(NormalizeData(object = srtList[[i]], assay = assay, normalization.method = "LogNormalize", verbose = FALSE))
}
if (normalization_method == "TFIDF") {
cat("Perform RunTFIDF on the data ", i, "/", length(srtList), " of the srtList...\n", sep = "")
srtList[[i]] <- suppressWarnings(RunTFIDF(object = srtList[[i]], assay = assay, verbose = FALSE))
}
} else if (is.null(do_normalization)) {
status <- check_DataType(srtList[[i]], slot = "data", assay = assay)
if (status == "log_normalized_counts") {
cat("Data ", i, "/", length(srtList), " of the srtList has been log-normalized.\n", sep = "")
}
if (status %in% c("raw_counts", "raw_normalized_counts")) {
if (normalization_method == "LogNormalize") {
cat("Data ", i, "/", length(srtList), " of the srtList is ", status, ". Perform NormalizeData(LogNormalize) on the data ...\n", sep = "")
srtList[[i]] <- suppressWarnings(NormalizeData(object = srtList[[i]], assay = assay, normalization.method = "LogNormalize", verbose = FALSE))
}
if (normalization_method == "TFIDF") {
cat("Data ", i, "/", length(srtList), " of the srtList is ", status, ". Perform RunTFIDF on the data ...\n", sep = "")
srtList[[i]] <- suppressWarnings(RunTFIDF(object = srtList[[i]], assay = assay, verbose = FALSE))
}
}
if (status == "unknown") {
warning("Can not determine whether data ", i, " is log-normalized...\n", immediate. = TRUE)
}
}
if (is.null(HVF)) {
if (isTRUE(do_HVF_finding) || is.null(do_HVF_finding) || length(VariableFeatures(srtList[[i]], assay = assay)) == 0) {
# if (type == "RNA") {
cat("Perform FindVariableFeatures on the data ", i, "/", length(srtList), " of the srtList...\n", sep = "")
srtList[[i]] <- suppressWarnings(FindVariableFeatures(srtList[[i]], assay = assay, nfeatures = nHVF, selection.method = HVF_method, verbose = FALSE))
# }
# if (type == "Chromatin") {
# cat("Perform FindTopFeatures on the data ", i, "/", length(srtList), " of the srtList...\n", sep = "")
# srtList[[i]] <- suppressWarnings(FindTopFeatures(srtList[[i]], assay = assay, min.cutoff = HVF_min_cutoff, verbose = FALSE))
# }
}
}
if (normalization_method %in% c("SCT") && type == "RNA") {
if (isTRUE(do_normalization) || isTRUE(do_HVF_finding) || !"SCT" %in% Assays(srtList[[i]])) {
cat("Perform SCTransform on the data", i, "of the srtList...\n")
srtList[[i]] <- SCTransform(
object = srtList[[i]],
variable.features.n = nHVF,
vars.to.regress = vars_to_regress,
assay = assay,
method = "glmGamPoi",
new.assay.name = "SCT",
verbose = FALSE
)
} else {
DefaultAssay(srtList[[i]]) <- "SCT"
}
if (!"residual_variance" %in% colnames(srtList[[i]]@[email protected])) {
if (length(srtList[[i]]@[email protected]) > 1) {
index <- which(sapply(srtList[[i]]@[email protected], function(x) nrow([email protected]) == ncol(srtList[[i]])))
} else {
index <- 1
}
model <- srtList[[i]]@[email protected][[index]]
feature.attr <- SCTResults(object = model, slot = "feature.attributes")
} else {
feature.attr <- srtList[[i]]@[email protected]
}
nfeatures <- min(nHVF, nrow(x = feature.attr))
top.features <- rownames(x = feature.attr)[head(order(feature.attr$residual_variance, decreasing = TRUE), n = nfeatures)]
VariableFeatures(srtList[[i]], assay = DefaultAssay(srtList[[i]])) <- top.features
srtList[[i]]@[email protected] <- feature.attr
}
}
if (is.null(HVF)) {
if (HVF_source == "global") {
cat("Use the global HVF from merged dataset...\n")
srtMerge <- Reduce(merge, srtList)
# if (type == "RNA") {
srtMerge <- FindVariableFeatures(srtMerge, assay = DefaultAssay(srtMerge), nfeatures = nHVF, selection.method = HVF_method, verbose = FALSE)
# }
# if (type == "Chromatin") {
# srtMerge <- FindTopFeatures(srtMerge, assay = DefaultAssay(srtMerge), min.cutoff = HVF_min_cutoff, verbose = FALSE)
# }
HVF <- VariableFeatures(srtMerge)
}
if (HVF_source == "separate") {
cat("Use the separate HVF from srtList...\n")
# if (type == "RNA") {
HVF <- SelectIntegrationFeatures(object.list = srtList, nfeatures = nHVF, verbose = FALSE)
HVF_sort <- sort(table(unlist(lapply(srtList, VariableFeatures))), decreasing = TRUE)
HVF_filter <- HVF_sort[HVF_sort >= HVF_min_intersection]
HVF <- intersect(HVF, names(HVF_filter))
# }
# if (type == "Chromatin") {
# nHVF <- min(sapply(srtList, function(srt) length(VariableFeatures(srt))))
# HVF_sort <- sort(table(unlist(lapply(srtList, VariableFeatures))), decreasing = TRUE)
# HVF_filter <- HVF_sort[HVF_sort >= HVF_min_intersection]
# HVF <- names(head(HVF_filter, nHVF))
# }
if (length(HVF) == 0) {
stop("No HVF available.")
}
}
} else {
cf <- Reduce(intersect, lapply(srtList, function(srt) {
rownames(GetAssayData(srt, slot = "counts", assay = DefaultAssay(srt)))
}))
HVF <- HVF[HVF %in% cf]
}
message("Number of available HVF: ", length(HVF))
hvf_sum <- lapply(srtList, function(srt) {
colSums(GetAssayData(srt, slot = "counts", assay = DefaultAssay(srt))[HVF, , drop = FALSE])
})
cell_all <- unlist(unname(hvf_sum))
cell_abnormal <- names(cell_all)[cell_all == 0]
if (length(cell_abnormal) > 0) {
warning("Some cells do not express any of the highly variable features: ", paste(cell_abnormal, collapse = ","), immediate. = TRUE)
}
if (normalization_method == "SCT" && type == "RNA") {
srtList <- PrepSCTIntegration(object.list = srtList, anchor.features = HVF, assay = "SCT", verbose = FALSE)
}
cat(paste0("[", Sys.time(), "]", " Finished checking.\n"))
return(list(
srtList = srtList,
HVF = HVF,
assay = assay,
type = type
))
}
#' Check and preprocess a merged seurat object
#' @inheritParams Integration_SCP
#' @importFrom Seurat GetAssayData SplitObject SetAssayData VariableFeatures VariableFeatures<-
#' @export
check_srtMerge <- function(srtMerge, batch = NULL, assay = NULL,
do_normalization = NULL, normalization_method = "LogNormalize",
do_HVF_finding = TRUE, HVF_source = "separate", HVF_method = "vst",
nHVF = 2000, HVF_min_intersection = 1, HVF = NULL,
vars_to_regress = NULL, seed = 11, ...) {
if (!inherits(srtMerge, "Seurat")) {
stop("'srtMerge' is not a Seurat object.")
}
if (length(batch) != 1) {
stop("'batch' must be provided to specify the batch column in the meta.data")
}
if (!batch %in% colnames([email protected])) {
stop(paste0("No batch column('", batch, "') found in the meta.data"))
}
if (!is.factor(srtMerge[[batch, drop = TRUE]])) {
srtMerge[[batch, drop = TRUE]] <- factor(srtMerge[[batch, drop = TRUE]],
levels = unique(srtMerge[[batch, drop = TRUE]])
)
}
assay <- assay %||% DefaultAssay(srtMerge)
srtMerge_raw <- srtMerge
cat(paste0("[", Sys.time(), "]", " Spliting srtMerge into srtList by column ", batch, "... ...\n"))
srtList <- SplitObject(object = srtMerge_raw, split.by = batch)
checked <- check_srtList(
srtList = srtList, batch = batch, assay = assay,
do_normalization = do_normalization, do_HVF_finding = do_HVF_finding,
normalization_method = normalization_method,
HVF_source = HVF_source, HVF_method = HVF_method, nHVF = nHVF, HVF_min_intersection = HVF_min_intersection, HVF = HVF,
vars_to_regress = vars_to_regress, seed = seed
)
srtList <- checked[["srtList"]]
HVF <- checked[["HVF"]]
assay <- checked[["assay"]]
type <- checked[["type"]]
srtMerge <- Reduce(merge, srtList)
srtMerge <- SrtAppend(
srt_raw = srtMerge, srt_append = srtMerge_raw, pattern = "",
slots = "reductions", overwrite = TRUE, verbose = FALSE
)
if (normalization_method == "SCT" && type == "RNA") {
DefaultAssay(srtMerge) <- "SCT"
} else {
DefaultAssay(srtMerge) <- assay
}
VariableFeatures(srtMerge) <- HVF
return(list(
srtMerge = srtMerge,
srtList = srtList,
HVF = HVF,
assay = assay,
type = type
))
}
#' Attempt to recover raw counts from the normalized matrix.
#'
#' @param srt A Seurat object.
#' @param assay Name of assay to recover counts.
#' @param trans The transformation function to applied when data is presumed to be log-normalized.
#' @param min_count Minimum UMI count of genes.
#' @param tolerance When recovering the raw counts, the nCount of each cell is theoretically calculated as an integer.
#' However, due to decimal point preservation during normalization, the calculated nCount is usually a floating point number close to the integer.
#' The tolerance is its difference from the integer. Default is 0.1
#' @param sf Set the scaling factor manually.
#' @param verbose Show messages.
#'
#' @examples
#' data("pancreas_sub")
#' raw_counts <- pancreas_sub@assays$RNA@counts
#'
#' # Normalized the data
#' pancreas_sub <- Seurat::NormalizeData(pancreas_sub)
#'
#' # Now replace counts with the log-normalized data matrix
#' pancreas_sub@assays$RNA@counts <- pancreas_sub@assays$RNA@data
#'
#' # Recover the counts and compare with the raw counts matrix
#' pancreas_sub <- RecoverCounts(pancreas_sub)
#' identical(raw_counts, pancreas_sub@assays$RNA@counts)
#' @importFrom Seurat GetAssayData SetAssayData
#' @importFrom SeuratObject as.sparse
#' @export
RecoverCounts <- function(srt, assay = NULL, trans = c("expm1", "exp", "none"), min_count = c(1, 2, 3), tolerance = 0.1, sf = NULL, verbose = TRUE) {
assay <- assay %||% DefaultAssay(srt)
counts <- GetAssayData(srt, assay = assay, slot = "counts")
if (!inherits(counts, "dgCMatrix")) {
counts <- as.sparse(counts[1:nrow(counts), ])
}
status <- check_DataType(data = counts)
if (status == "raw_counts") {
if (isTRUE(verbose)) {
message("The data is already raw counts.")
}
return(srt)
}
if (status == "log_normalized_counts") {
if (isTRUE(verbose)) {
message("The data is presumed to be log-normalized.")
}
trans <- match.arg(trans)
if (trans %in% c("expm1", "exp")) {
if (isTRUE(verbose)) {
message("Perform ", trans, " on the raw data.")
}
counts <- do.call(trans, list(counts))
}
}
if (status == "raw_normalized_counts") {
if (isTRUE(verbose)) {
message("The data is presumed to be normalized without log transformation.")
}
}
if (is.null(sf)) {
sf <- unique(round(colSums(counts)))
if (isTRUE(verbose)) {
message("The presumed scale factor: ", paste0(head(sf, 10), collapse = ", "))
}
}
if (length(sf) == 1) {
counts <- counts / sf
elements <- split(counts@x, rep(1:ncol(counts), diff(counts@p)))
min_norm <- sapply(elements, min)
nCount <- NULL
for (m in min_count) {
if (is.null(nCount)) {
presumed_nCount <- m / min_norm
diff_value <- abs(presumed_nCount - round(presumed_nCount))
if (max(diff_value) < tolerance) {
nCount <- round(presumed_nCount)
}
}
}
if (is.null(nCount)) {
warning("The presumed nCount of some cells is not valid: ", paste0(head(colnames(counts)[diff_value < tolerance], 10), collapse = ","), ", ...", immediate. = TRUE)
return(srt)
}
counts@x <- round(counts@x * rep(nCount, diff(counts@p)))
srt <- SetAssayData(srt, new.data = counts, assay = assay, slot = "counts")
srt[[paste0("nCount_", assay)]] <- nCount
} else {
warning("Scale factor is not unique. No changes to be made.", immediate. = TRUE)
}
return(srt)
}
#' Rename features for the Seurat object
#'
#' @param srt A Seurat object.
#' @param newnames A vector with the same length of features in Seurat object, or characters named with old features.
#' @param assays Assays to rename.
#'
#' @examples
#' data("panc8_sub")
#' head(rownames(panc8_sub))
#' # Simply convert genes from human to mouse and preprocess the data
#' genenames <- make.unique(capitalize(rownames(panc8_sub), force_tolower = TRUE))
#' panc8_rename <- RenameFeatures(panc8_sub, newnames = genenames)
#' head(rownames(panc8_rename))
#'
#' @importFrom Seurat Assays GetAssay
#' @importFrom methods slot
#' @export
RenameFeatures <- function(srt, newnames = NULL, assays = NULL) {
assays <- assays[assays %in% Assays(srt)] %||% Assays(srt)
if (is.null(names(newnames))) {
if (!identical(length(newnames), nrow(srt))) {
stop("'newnames' must be named or the length of features in the srt.")
}
if (length(unique(sapply(pancreas_sub@assays[assays], nrow))) > 1) {
stop("Assays in the srt object have different number of features. Please use a named vectors.")
}
names(newnames) <- rownames(srt[[assays[1]]])
}
for (assay in assays) {
message("Rename features for the assay: ", assay)
assay_obj <- GetAssay(srt, assay)
for (d in c("meta.features", "scale.data", "counts", "data")) {
index <- which(rownames(slot(assay_obj, d)) %in% names(newnames))
rownames(slot(assay_obj, d))[index] <- newnames[rownames(slot(assay_obj, d))[index]]
}
if (length(slot(assay_obj, "var.features")) > 0) {
index <- which(slot(assay_obj, "var.features") %in% names(newnames))
slot(assay_obj, "var.features")[index] <- newnames[slot(assay_obj, "var.features")[index]]
}
srt[[assay]] <- assay_obj
}
return(srt)
}
#' Rename clusters for the Seurat object
#'
#' @param srt A Seurat object.
#' @param group.by The old group used to rename cells.
#' @param nameslist A named list of new cluster value.
#' @param name The name of the new cluster stored in the Seurat object.
#' @param keep_levels If the old group is a factor, keep the order of the levels.
#'
#' @examples
#' data("pancreas_sub")
#' levels([email protected][["SubCellType"]])
#'
#' # Rename all clusters
#' pancreas_sub <- RenameClusters(pancreas_sub, group.by = "SubCellType", nameslist = letters[1:8])
#' ClassDimPlot(pancreas_sub, "newclusters")
#'
#' # Rename specified clusters
#' pancreas_sub <- RenameClusters(pancreas_sub,
#' group.by = "SubCellType",
#' nameslist = list("a" = "Alpha", "b" = "Beta")
#' )
#' ClassDimPlot(pancreas_sub, "newclusters")
#'
#' # Merge and rename clusters
#' pancreas_sub <- RenameClusters(pancreas_sub,
#' group.by = "SubCellType",
#' nameslist = list("EndocrineClusters" = c("Alpha", "Beta", "Epsilon", "Delta")),
#' name = "Merged", keep_levels = TRUE
#' )
#' ClassDimPlot(pancreas_sub, "Merged")
#'
#' @importFrom stats setNames
#' @export
RenameClusters <- function(srt, group.by, nameslist = list(), name = "newclusters", keep_levels = FALSE) {
if (missing(group.by)) {
stop("group.by must be provided")
}
if (!group.by %in% colnames([email protected])) {
stop(paste0(group.by, " is not in the meta.data of srt object."))
}
if (length(nameslist) > 0 && is.null(names(nameslist))) {
names(nameslist) <- levels([email protected][[group.by]])
}
if (is.list(nameslist) && length(nameslist) > 0) {
names_assign <- setNames(rep(names(nameslist), sapply(nameslist, length)), nm = unlist(nameslist))
} else {
if (is.null(names(nameslist))) {
if (!is.factor([email protected][[group.by]])) {
stop("'nameslist' must be named when [email protected][[group.by]] is not a factor")
}
if (!identical(length(nameslist), length(unique([email protected][[group.by]])))) {
stop("'nameslist' must be named or the length of ", length(unique([email protected][[group.by]])))
}
names(nameslist) <- levels([email protected][[group.by]])
}
names_assign <- nameslist
}
if (all(!names(names_assign) %in% [email protected][[group.by]])) {
stop("No group name mapped.")
}
if (is.factor([email protected][[group.by]])) {
levels <- levels([email protected][[group.by]])
} else {
levels <- NULL
}
index <- which(as.character([email protected][[group.by]]) %in% names(names_assign))
[email protected][[name]] <- as.character([email protected][[group.by]])
[email protected][[name]][index] <- names_assign[[email protected][[name]][index]]
if (!is.null(levels)) {
levels[levels %in% names(names_assign)] <- names_assign[levels[levels %in% names(names_assign)]]
if (isFALSE(keep_levels)) {
levels <- unique(c(names_assign, levels))
} else {
levels <- unique(levels)
}
[email protected][[name]] <- factor([email protected][[name]], levels = levels)
}
return(srt)
}
#' Reorder idents by the gene expression
#'
#' @param srt A Seurat object.
#' @param features Features used to reorder idents.
#' @param reorder_by Reorder groups instead of idents.
#' @param slot Specific slot to get data from.
#' @param assay Specific assay to get data from.
#' @param log Whether log1p transformation needs to be applied. Default is \code{TRUE}.
#' @param distance_metric Metric to compute distance. Default is "euclidean".
#'
#' @importFrom Seurat VariableFeatures DefaultAssay DefaultAssay<- AverageExpression Idents<-
#' @importFrom SeuratObject as.sparse
#' @importFrom stats hclust reorder as.dendrogram as.dist
#' @importFrom Matrix t colMeans
#' @export
SrtReorder <- function(srt, features = NULL, reorder_by = NULL, slot = "data", assay = NULL, log = TRUE,
distance_metric = "euclidean") {
assay <- assay %||% DefaultAssay(srt)
if (is.null(features)) {
features <- VariableFeatures(srt, assay = assay)
}
features <- intersect(x = features, y = rownames(x = srt))
if (is.null(reorder_by)) {
srt$ident <- Idents(srt)
} else {
srt$ident <- srt[[reorder_by, drop = TRUE]]
}
if (length(unique(srt[[reorder_by, drop = TRUE]])) == 1) {
warning("Only one cluter found.", immediate. = TRUE)
return(srt)
}
simil_method <- c(
"cosine", "correlation", "jaccard", "ejaccard", "dice", "edice", "hamman",
"simple matching", "faith"
)
dist_method <- c(
"euclidean", "chisquared", "kullback", "manhattan", "maximum", "canberra",
"minkowski", "hamming"
)
if (!distance_metric %in% c(simil_method, dist_method, "pearson", "spearman")) {
stop(distance_metric, " method is invalid.")
}
data.avg <- AverageExpression(object = srt, features = features, slot = slot, assays = assay, group.by = "ident", verbose = FALSE)[[1]][features, ]
if (isTRUE(log)) {
data.avg <- log1p(data.avg)
}
mat <- t(x = data.avg[features, ])
if (!inherits(mat, "dgCMatrix")) {
mat <- as.sparse(mat[1:nrow(mat), ])
}
if (distance_metric %in% c(simil_method, "pearson", "spearman")) {
if (distance_metric %in% c("pearson", "spearman")) {
if (distance_metric == "spearman") {
mat <- t(apply(mat, 1, rank))
}
distance_metric <- "correlation"
}
d <- 1 - proxyC::simil(as.sparse(mat[1:nrow(mat), ]), method = distance_metric)
} else if (distance_metric %in% dist_method) {
d <- proxyC::dist(as.sparse(mat[1:nrow(mat), ]), method = distance_metric)
}
data.dist <- as.dist(d)
hc <- hclust(d = data.dist)
dd <- as.dendrogram(hc)
dd_ordered <- reorder(dd, wts = colMeans(data.avg[features, , drop = FALSE]), agglo.FUN = base::mean)
ident_new <- unname(setNames(object = seq_along(labels(dd_ordered)), nm = labels(dd_ordered))[as.character(srt$ident)])
ident_new <- factor(ident_new, levels = seq_along(labels(dd_ordered)))
Idents(srt) <- srt$ident <- ident_new
return(srt)
}
#' Append a Seurat object to another
#'
#' @param srt_raw A Seurat object to be appended.
#' @param srt_append New Seurat object to append.
#' @param slots slots names.
#' @param pattern A character string containing a regular expression. All data with matching names will be considered for appending.
#' @param overwrite Whether to overwrite.
#' @param verbose Show messages.
#'
#' @importFrom methods slotNames slot slot<-
#' @export
SrtAppend <- function(srt_raw, srt_append,
slots = slotNames(srt_append), pattern = NULL, overwrite = FALSE,
verbose = TRUE) {
if (!inherits(srt_raw, "Seurat") || !inherits(srt_append, "Seurat")) {
stop("'srt_raw' or 'srt_append' is not a Seurat object.")
}
pattern <- pattern %||% ""
for (slot_nm in slotNames(srt_append)) {
if (!slot_nm %in% slots) {
if (isTRUE(verbose)) {
message("Slot ", slot_nm, " is not appended.")
}
next
}
if (identical(slot_nm, "active.ident") && isTRUE(overwrite)) {
slot(srt_raw, name = "active.ident") <- slot(srt_append, name = "active.ident")
next
}
for (info in names(slot(srt_append, name = slot_nm))) {
if (is.null(info)) {
if (length(slot(srt_append, name = slot_nm)) > 0 && isTRUE(overwrite)) {
slot(srt_raw, name = slot_nm) <- slot(srt_append, name = slot_nm)
}
next
}
if (!grepl(pattern = pattern, x = info)) {
if (isTRUE(verbose)) {
message(info, " in slot ", slot_nm, " is not appended.")
}
next
}
if (!info %in% names(slot(srt_raw, name = slot_nm)) || isTRUE(overwrite)) {
if (slot_nm %in% c("assays", "graphs", "neighbors", "reductions", "images")) {
if (identical(slot_nm, "graphs")) {
srt_raw@graphs[[info]] <- srt_append[[info]]
} else if (identical(slot_nm, "assays")) {
if (!info %in% Assays(srt_raw)) {
srt_raw[[info]] <- srt_append[[info]]
} else {
srt_raw[[info]]@counts <- srt_append[[info]]@counts
srt_raw[[info]]@data <- srt_append[[info]]@data
srt_raw[[info]]@key <- srt_append[[info]]@key
srt_raw[[info]]@var.features <- srt_append[[info]]@var.features
srt_raw[[info]]@misc <- srt_append[[info]]@misc
srt_raw[[info]]@meta.features <- cbind(srt_raw[[info]]@meta.features, srt_append[[info]]@meta.features[
rownames(srt_raw[[info]]@meta.features),
setdiff(colnames(srt_append[[info]]@meta.features), colnames(srt_raw[[info]]@meta.features))
])
}
} else {
srt_raw[[info]] <- srt_append[[info]]
}
} else if (identical(slot_nm, "meta.data")) {
[email protected][, info] <- NULL
[email protected][[info]] <- [email protected][colnames(srt_raw), info]
} else {
slot(srt_raw, name = slot_nm)[[info]] <- slot(srt_append, name = slot_nm)[[info]]
}
}
}
}
return(srt_raw)
}
#' Run dimensionality reduction
#'
#' @param srt A Seurat object.
#' @param prefix The prefix used to name the result.
#' @param features Use features expression data to run linear or nonlinear dimensionality reduction.
#' @param assay Specific assay to get data from.
#' @param slot Specific slot to get data from.
#' @param linear_reduction Method of linear dimensionality reduction. Options are "pca", "ica", "nmf", "mds", "glmpca".
#' @param linear_reduction_dims Total number of dimensions to compute and store for \code{linear_reduction}.
#' @param linear_reduction_params Other parameters passed to the \code{linear_reduction} method.
#' @param force_linear_reduction Whether force to do linear dimensionality reduction.
#' @param nonlinear_reduction Method of nonlinear dimensionality reduction. Options are "umap", "umap-naive", "tsne", "dm", "phate", "pacmap", "trimap", "largevis"
#' @param nonlinear_reduction_dims Total number of dimensions to compute and store for \code{nonlinear_reduction}.
#' @param reduction_use Which dimensional reduction to use as input for \code{nonlinear_reduction}.
#' @param reduction_dims Which dimensions to use as input for \code{nonlinear_reduction}, used only if \code{features} is \code{NULL}.
#' @param neighbor_use Name of neighbor to use for the \code{nonlinear_reduction}.
#' @param graph_use Name of graph to use for the \code{nonlinear_reduction}.
#' @param nonlinear_reduction_params Other parameters passed to the \code{nonlinear_reduction} method.
#' @param force_nonlinear_reduction Whether force to do nonlinear dimensionality reduction.
#' @param verbose Show messages.
#' @param seed Set a seed.
#'
#' @importFrom Seurat Embeddings RunPCA RunICA RunTSNE Reductions DefaultAssay DefaultAssay<- Key Key<-
#' @importFrom Signac RunSVD
#' @export
RunDimReduction <- function(srt, prefix = "", features = NULL, assay = NULL, slot = "data",
linear_reduction = NULL, linear_reduction_dims = 50,
linear_reduction_params = list(), force_linear_reduction = FALSE,
nonlinear_reduction = NULL, nonlinear_reduction_dims = 2,
reduction_use = NULL, reduction_dims = NULL,
graph_use = NULL, neighbor_use = NULL,
nonlinear_reduction_params = list(), force_nonlinear_reduction = TRUE,
verbose = TRUE, seed = 11) {
set.seed(seed)
assay <- assay %||% DefaultAssay(srt)
if (inherits(srt[[assay]], "ChromatinAssay")) {
type <- "Chromatin"
} else {
type <- "RNA"
}
linear_reduction_dims <- min(linear_reduction_dims, nrow(srt[[assay]]) - 1, ncol(srt[[assay]]) - 1, na.rm = TRUE)
nonlinear_reduction_dims <- min(nonlinear_reduction_dims, nrow(srt[[assay]]) - 1, ncol(srt[[assay]]) - 1, na.rm = TRUE)
if (!is.null(linear_reduction)) {
if (any(!linear_reduction %in% c("pca", "svd", "ica", "nmf", "mds", "glmpca", Reductions(srt))) || length(linear_reduction) > 1) {
stop("'linear_reduction' must be one of 'pca','svd', 'ica', 'nmf', 'mds', 'glmpca'.")
}
}
if (!is.null(nonlinear_reduction)) {
if (any(!nonlinear_reduction %in% c("umap", "umap-naive", "tsne", "dm", "phate", "pacmap", "trimap", "largevis", Reductions(srt))) || length(nonlinear_reduction) > 1) {
stop("'nonlinear_reduction' must be one of 'umap', 'tsne', 'dm', 'phate', 'pacmap', 'trimap', 'largevis'.")
}
if (is.null(features) && is.null(reduction_use) && is.null(neighbor_use) && is.null(graph_use)) {
stop("'features', 'reduction_use', 'graph_use', or 'neighbor_use' must be provided when running non-linear dimensionality reduction.")
}
if (!is.null(features)) {
message("Non-linear dimensionality reduction(", nonlinear_reduction, ") using Features(length:", length(features), ") as input")
}
if (!is.null(reduction_use)) {
message("Non-linear dimensionality reduction(", nonlinear_reduction, ") using Reduction(", reduction_use, ", dims_range:", min(reduction_dims), "-", max(reduction_dims), ") as input")
}
if (!is.null(neighbor_use)) {
message("Non-linear dimensionality reduction(", nonlinear_reduction, ") using Neighbors(", neighbor_use, ") as input")
}
if (!is.null(graph_use)) {
message("Non-linear dimensionality reduction(", nonlinear_reduction, ") using Graphs(", graph_use, ") as input")
}
}
if (!is.null(linear_reduction)) {
if (!isTRUE(force_linear_reduction)) {
if (linear_reduction %in% Reductions(srt)) {
if (srt[[linear_reduction]]@assay.used == assay) {
message("linear_reduction(", linear_reduction, ") is already existed. Skip calculation.")
reduc <- srt[[linear_reduction]]
Key(reduc) <- paste0(prefix, linear_reduction, "_")
srt[[paste0(prefix, linear_reduction)]] <- reduc
srt@misc[["Default_reduction"]] <- paste0(prefix, linear_reduction)
return(srt)
} else {
message("assay.used is ", srt[[linear_reduction]]@assay.used, ", which is not the same as the ", assay, " specified. Recalculate the linear reduction")
}
}
}
if (is.null(features) || length(features) == 0) {
message("No features provided. Use variable features.")
if (length(VariableFeatures(srt, assay = assay)) == 0) {
srt <- FindVariableFeatures(srt, assay = assay, verbose = FALSE)
}
features <- VariableFeatures(srt, assay = assay)
}
fun_use <- switch(linear_reduction,
"pca" = "RunPCA",
"svd" = "RunSVD",
"ica" = "RunICA",
"nmf" = "RunNMF",
"mds" = "RunMDS",
"glmpca" = "RunGLMPCA"
)
key_use <- switch(linear_reduction,
"pca" = "PC_",
"svd" = "LSI_",
"ica" = "IC_",
"nmf" = "BE_",
"mds" = "MDS_",
"glmpca" = "GLMPC_"
)
components_nm <- switch(linear_reduction,
"pca" = "npcs",
"svd" = "n",
"ica" = "nics",
"nmf" = "nbes",
"mds" = "nmds",
"glmpca" = "L"
)
params <- list(
object = srt, assay = assay, slot = slot,
features = features, components_nm = linear_reduction_dims,
reduction.name = paste0(prefix, linear_reduction),
reduction.key = paste0(prefix, key_use),
verbose = verbose, seed.use = seed
)
if (fun_use %in% c("RunSVD", "RunICA")) {
params <- params[!names(params) %in% "slot"]
}
if (fun_use == "RunGLMPCA") {
params[["slot"]] <- "counts"
}
names(params)[names(params) == "components_nm"] <- components_nm
for (nm in names(linear_reduction_params)) {
params[[nm]] <- linear_reduction_params[[nm]]
}
srt <- invoke(.fn = fun_use, .args = params)
if (is.null(rownames(srt[[paste0(prefix, linear_reduction)]]))) {
rownames(srt[[paste0(prefix, linear_reduction)]]@cell.embeddings) <- colnames(srt)
}
if (linear_reduction == "pca") {
pca.out <- srt[[paste0(prefix, linear_reduction)]]
center <- rowMeans(GetAssayData(object = srt, slot = "scale.data", assay = assay)[features, , drop = FALSE])
model <- list(sdev = pca.out@stdev, rotation = [email protected], center = center, scale = FALSE, x = [email protected])
class(model) <- "prcomp"
srt@reductions[[paste0(prefix, linear_reduction)]]@misc[["model"]] <- model
}
if (linear_reduction %in% c("glmpca", "nmf")) {
dims_estimate <- 1:linear_reduction_dims
} else {
dim_est <- tryCatch(expr = {
min(
intrinsicDimension::maxLikGlobalDimEst(data = Embeddings(srt, reduction = paste0(prefix, linear_reduction)), k = 20)[["dim.est"]],
ncol(Embeddings(srt, reduction = paste0(prefix, linear_reduction)))
)
}, error = function(e) {
message("Can not estimate intrinsic dimensions with maxLikGlobalDimEst.")
return(NA)
})
if (!is.na(dim_est)) {
dims_estimate <- seq_len(max(min(ncol(Embeddings(srt, reduction = paste0(prefix, linear_reduction))), 10), ceiling(dim_est)))
} else {
dims_estimate <- seq_len(min(ncol(Embeddings(srt, reduction = paste0(prefix, linear_reduction))), 30))
}
}
srt@reductions[[paste0(prefix, linear_reduction)]]@misc[["dims_estimate"]] <- dims_estimate
srt@misc[["Default_reduction"]] <- paste0(prefix, linear_reduction)
} else if (!is.null(nonlinear_reduction)) {
if (!isTRUE(force_nonlinear_reduction)) {
if (nonlinear_reduction %in% Reductions(srt)) {
if (srt[[nonlinear_reduction]]@assay.used == assay) {
message("nonlinear_reduction(", nonlinear_reduction, ") is already existed. Skip calculation.")
reduc <- srt[[nonlinear_reduction]]
Key(reduc) <- paste0(prefix, nonlinear_reduction, "_")
srt[[paste0(prefix, nonlinear_reduction)]] <- reduc
srt@misc[["Default_reduction"]] <- paste0(prefix, nonlinear_reduction)
return(srt)
} else {
message("assay.used is ", srt[[nonlinear_reduction]]@assay.used, ", which is not the same as the ", assay, " specified. Recalculate the linear reduction")
}
}
}
if (!is.null(neighbor_use) && !nonlinear_reduction %in% c("umap", "umap-naive")) {
stop("'neighbor_use' only support 'umap' or 'umap-naive' method")
}
if (!is.null(graph_use) && !nonlinear_reduction %in% c("umap", "umap-naive")) {
stop("'graph_use' only support 'umap' or 'umap-naive' method")
}
fun_use <- switch(nonlinear_reduction,
"umap" = "RunUMAP2",
"umap-naive" = "RunUMAP2",
"tsne" = "RunTSNE",
"dm" = "RunDM",
"phate" = "RunPHATE",
"pacmap" = "RunPaCMAP",
"trimap" = "RunTriMap",
"largevis" = "RunLargeVis"
)
components_nm <- switch(nonlinear_reduction,
"umap" = "n.components",
"umap-naive" = "n.components",
"tsne" = "dim.embed",
"dm" = "ndcs",
"phate" = "n_components",
"pacmap" = "n_components",
"trimap" = "n_components",
"largevis" = "n_components"
)
other_params <- switch(nonlinear_reduction,
"umap" = list(umap.method = "uwot", return.model = TRUE),
"umap-naive" = list(umap.method = "naive", return.model = TRUE),
"tsne" = list(tsne.method = "Rtsne", num_threads = 0, check_duplicates = FALSE),
"dm" = list(),
"phate" = list(),
"pacmap" = list(),
"trimap" = list(),
"largevis" = list()
)
nonlinear_reduction_sim <- toupper(gsub(pattern = "-.*", replacement = "", x = nonlinear_reduction))
params <- list(
object = srt, assay = assay, slot = slot, components_nm = nonlinear_reduction_dims,
features = features, reduction = reduction_use, dims = reduction_dims,
reduction.name = paste0(prefix, nonlinear_reduction_sim, nonlinear_reduction_dims, "D"),
reduction.key = paste0(prefix, nonlinear_reduction_sim, nonlinear_reduction_dims, "D_"),
verbose = verbose, seed.use = seed
)
if (!is.null(neighbor_use)) {
params[["neighbor"]] <- neighbor_use
}
if (!is.null(graph_use)) {
params[["graph"]] <- graph_use
}
names(params)[names(params) == "components_nm"] <- components_nm
for (nm in names(other_params)) {
params[[nm]] <- other_params[[nm]]
}
for (nm in names(nonlinear_reduction_params)) {
params[[nm]] <- nonlinear_reduction_params[[nm]]
}
srt <- invoke(.fn = fun_use, .args = params)
srt@reductions[[paste0(prefix, nonlinear_reduction_sim, nonlinear_reduction_dims, "D")]]@misc[["reduction_dims"]] <- reduction_dims
srt@reductions[[paste0(prefix, nonlinear_reduction_sim, nonlinear_reduction_dims, "D")]]@misc[["reduction_use"]] <- reduction_use
srt@misc[["Default_reduction"]] <- paste0(prefix, nonlinear_reduction_sim)
}
return(srt)
}
#' Uncorrected_integrate
#'
#' @inheritParams Integration_SCP
#'
#' @importFrom Seurat GetAssayData SetAssayData VariableFeatures VariableFeatures<-
#' @export
Uncorrected_integrate <- function(srtMerge = NULL, batch = NULL, append = TRUE, srtList = NULL, assay = NULL,
do_normalization = NULL, normalization_method = "LogNormalize",
do_HVF_finding = TRUE, HVF_source = "separate", HVF_method = "vst", nHVF = 2000, HVF_min_intersection = 1, HVF = NULL,
do_scaling = TRUE, vars_to_regress = NULL, regression_model = "linear",
linear_reduction = "pca", linear_reduction_dims = 50, linear_reduction_dims_use = NULL, linear_reduction_params = list(), force_linear_reduction = FALSE,
nonlinear_reduction = "umap", nonlinear_reduction_dims = c(2, 3), nonlinear_reduction_params = list(), force_nonlinear_reduction = TRUE,
do_cluster_finding = TRUE, cluster_algorithm = "louvain", cluster_resolution = 0.6, cluster_reorder = TRUE,
seed = 11) {
if (length(linear_reduction) > 1) {
warning("Only the first method in the 'linear_reduction' will be used.", immediate. = TRUE)
linear_reduction <- linear_reduction[1]
}
reduc_test <- c("pca", "ica", "nmf", "mds", "glmpca")
if (!is.null(srtMerge)) {
reduc_test <- c(reduc_test, Reductions(srtMerge))
}
if (any(!linear_reduction %in% reduc_test)) {
stop("'linear_reduction' must be one of 'pca', 'ica', 'nmf', 'mds', 'glmpca'.")
}
if (any(!nonlinear_reduction %in% c("umap", "umap-naive", "tsne", "dm", "phate", "pacmap", "trimap", "largevis"))) {
stop("'nonlinear_reduction' must be one of 'umap', 'tsne', 'dm', 'phate', 'pacmap', 'trimap', 'largevis'.")
}
if (!cluster_algorithm %in% c("louvain", "slm", "leiden")) {
stop("'cluster_algorithm' must be one of 'louvain', 'slm', 'leiden'.")
}
if (cluster_algorithm == "leiden") {