forked from satijalab/seurat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clustering.R
1762 lines (1732 loc) · 55.3 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
#' @include generics.R
#'
NULL
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Functions
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#' Construct weighted nearest neighbor graph
#'
#' This function will construct a weighted nearest neighbor (WNN) graph. For
#' each cell, we identify the nearest neighbors based on a weighted combination
#' of two modalities. Takes as input two dimensional reductions, one computed
#' for each modality.Other parameters are listed for debugging, but can be left
#' as default values.
#'
#' @param object A Seurat object
#' @param reduction.list A list of two dimensional reductions, one for each of
#' the modalities to be integrated
#' @param dims.list A list containing the dimensions for each reduction to use
#' @param k.nn the number of multimodal neighbors to compute. 20 by default
#' @param l2.norm Perform L2 normalization on the cell embeddings after
#' dimensional reduction. TRUE by default.
#' @param knn.graph.name Multimodal knn graph name
#' @param snn.graph.name Multimodal snn graph name
#' @param weighted.nn.name Multimodal neighbor object name
#' @param modality.weight.name Variable name to store modality weight in object
#' meta data
#' @param knn.range The number of approximate neighbors to compute
#' @param prune.SNN Cutoff not to discard edge in SNN graph
#' @param sd.scale The scaling factor for kernel width. 1 by default
#' @param cross.contant.list Constant used to avoid divide-by-zero errors. 1e-4
#' by default
#' @param smooth Smoothing modality score across each individual modality
#' neighbors. FALSE by default
#' @param return.intermediate Store intermediate results in misc
#' @param modality.weight A \code{\link{ModalityWeights}} object generated by
#' \code{FindModalityWeights}
#' @param verbose Print progress bars and output
#'
#' @return Seurat object containing a nearest-neighbor object, KNN graph, and
#' SNN graph - each based on a weighted combination of modalities.
#' @concept clustering
#' @export
#'
FindMultiModalNeighbors <- function(
object,
reduction.list,
dims.list,
k.nn = 20,
l2.norm = TRUE,
knn.graph.name = "wknn",
snn.graph.name = "wsnn",
weighted.nn.name = "weighted.nn",
modality.weight.name = NULL,
knn.range = 200,
prune.SNN = 1/15,
sd.scale = 1,
cross.contant.list = NULL,
smooth = FALSE,
return.intermediate = FALSE,
modality.weight = NULL,
verbose = TRUE
) {
cross.contant.list <- cross.contant.list %||%
as.list(x = rep(x = 1e-4, times = length(x = reduction.list)))
if (is.null(x = modality.weight)) {
if (verbose) {
message("Calculating cell-specific modality weights")
}
modality.weight <- FindModalityWeights(
object = object,
reduction.list = reduction.list,
dims.list = dims.list,
k.nn = k.nn,
sd.scale = sd.scale,
l2.norm = l2.norm,
cross.contant.list = cross.contant.list,
smooth = smooth,
verbose = verbose
)
}
modality.weight.name <- modality.weight.name %||% paste0([email protected], ".weight")
modality.assay <- slot(object = modality.weight, name = "modality.assay")
if (length(modality.weight.name) != length(reduction.list)) {
warning("The number of provided modality.weight.name is not equal to the number of modalities. ",
paste(paste0(modality.assay, ".weight"), collapse = " "),
" are used to store the modality weights" )
modality.weight.name <- paste0(modality.assay, ".weight")
}
first.assay <- modality.assay[1]
weighted.nn <- MultiModalNN(
object = object,
k.nn = k.nn,
modality.weight = modality.weight,
knn.range = knn.range,
verbose = verbose
)
select_nn <- Indices(object = weighted.nn)
select_nn_dist <- Distances(object = weighted.nn)
# compute KNN graph
if (verbose) {
message("Constructing multimodal KNN graph")
}
j <- as.numeric(x = t(x = select_nn ))
i <- ((1:length(x = j)) - 1) %/% k.nn + 1
nn.matrix <- sparseMatrix(
i = i,
j = j,
x = 1,
dims = c(ncol(x = object), ncol(x = object))
)
diag(x = nn.matrix) <- 1
rownames(x = nn.matrix) <- colnames(x = nn.matrix) <- colnames(x = object)
nn.matrix <- nn.matrix + t(x = nn.matrix) - t(x = nn.matrix) * nn.matrix
nn.matrix <- as.Graph(x = nn.matrix)
slot(object = nn.matrix, name = "assay.used") <- first.assay
object[[knn.graph.name]] <- nn.matrix
# compute SNN graph
if (verbose) {
message("Constructing multimodal SNN graph")
}
snn.matrix <- ComputeSNN(nn_ranked = select_nn, prune = prune.SNN)
rownames(x = snn.matrix) <- colnames(x = snn.matrix) <- Cells(x = object)
snn.matrix <- as.Graph(x = snn.matrix )
slot(object = snn.matrix, name = "assay.used") <- first.assay
object[[snn.graph.name]] <- snn.matrix
# add neighbors and modality weights
object[[weighted.nn.name]] <- weighted.nn
for (m in 1:length(x = modality.weight.name)) {
object[[modality.weight.name[[m]]]] <- slot(
object = modality.weight,
name = "modality.weight.list"
)[[m]]
}
# add command log
modality.weight.command <- slot(object = modality.weight, name = "command")
slot(object = modality.weight.command, name = "assay.used") <- first.assay
modality.weight.command.name <- slot(object = modality.weight.command, name = "name")
object[[modality.weight.command.name]] <- modality.weight.command
command <- LogSeuratCommand(object = object, return.command = TRUE)
slot(object = command, name = "params")$modality.weight <- NULL
slot(object = command, name = "assay.used") <- first.assay
command.name <- slot(object = command, name = "name")
object[[command.name]] <- command
if (return.intermediate) {
Misc(object = object, slot = "modality.weight") <- modality.weight
}
return (object)
}
#' Find subclusters under one cluster
#'
#' @inheritParams FindClusters
#' @param cluster the cluster to be sub-clustered
#' @param subcluster.name the name of sub cluster added in the meta.data
#'
#' @return return a object with sub cluster labels in the sub-cluster.name variable
#' @concept clustering
#' @export
#'
FindSubCluster <- function(
object,
cluster,
graph.name,
subcluster.name = "sub.cluster",
resolution = 0.5,
algorithm = 1
) {
sub.cell <- WhichCells(object = object, idents = cluster)
sub.graph <- as.Graph(x = object[[graph.name]][sub.cell, sub.cell])
sub.clusters <- FindClusters(
object = sub.graph,
resolution = resolution,
algorithm = algorithm
)
sub.clusters[, 1] <- paste(cluster, sub.clusters[, 1], sep = "_")
object[[subcluster.name]] <- as.character(x = Idents(object = object))
object[[subcluster.name]][sub.cell, ] <- sub.clusters[, 1]
return(object)
}
#' Predict value from nearest neighbors
#'
#' This function will predict expression or cell embeddings from its k nearest
#' neighbors index. For each cell, it will average its k neighbors value to get
#' its new imputed value. It can average expression value in assays and cell
#' embeddings from dimensional reductions.
#'
#' @param object The object used to calculate knn
#' @param nn.idx k near neighbour indices. A cells x k matrix.
#' @param assay Assay used for prediction
#' @param reduction Cell embedding of the reduction used for prediction
#' @param dims Number of dimensions of cell embedding
#' @param return.assay Return an assay or a predicted matrix
#' @param slot slot used for prediction
#' @param features features used for prediction
#' @param mean.function the function used to calculate row mean
#' @param seed Sets the random seed to check if the nearest neighbor is query
#' cell
#' @param verbose Print progress
#'
#' @return return an assay containing predicted expression value in the data
#' slot
#' @concept integration
#' @export
#'
PredictAssay <- function(
object,
nn.idx,
assay,
reduction = NULL,
dims = NULL,
return.assay = TRUE,
slot = "scale.data",
features = NULL,
mean.function = rowMeans,
seed = 4273,
verbose = TRUE
){
if (!inherits(x = mean.function, what = 'function')) {
stop("'mean.function' must be a function")
}
if (is.null(x = reduction)) {
reference.data <- GetAssayData(
object = object,
assay = assay,
slot = slot
)
features <- features %||% VariableFeatures(object = object[[assay]])
if (length(x = features) == 0) {
features <- rownames(x = reference.data)
if (verbose) {
message("VariableFeatures are empty in the ", assay,
" assay, features in the ", slot, " slot will be used" )
}
}
reference.data <- reference.data[features, , drop = FALSE]
} else {
if (is.null(x = dims)) {
stop("dims is empty")
}
reference.data <- t(x = Embeddings(object = object, reduction = reduction)[, dims])
}
set.seed(seed = seed)
nn.check <- sample(x = 1:nrow(x = nn.idx), size = min(50, nrow(x = nn.idx)))
if (all(nn.idx[nn.check, 1] == nn.check)) {
if(verbose){
message("The nearest neighbor is the query cell itself, and it will not be used for prediction")
}
nn.idx <- nn.idx[,-1]
}
predicted <- apply(
X = nn.idx,
MARGIN = 1,
FUN = function(x) mean.function(reference.data[, x] )
)
colnames(x = predicted) <- Cells(x = object)
if (return.assay) {
predicted.assay <- CreateAssayObject(data = predicted, check.matrix = FALSE)
return (predicted.assay)
} else {
return (predicted)
}
}
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Methods for Seurat-defined generics
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#' @importFrom pbapply pblapply
#' @importFrom future.apply future_lapply
#' @importFrom future nbrOfWorkers
#'
#' @param modularity.fxn Modularity function (1 = standard; 2 = alternative).
#' @param initial.membership,node.sizes Parameters to pass to the Python leidenalg function.
#' @param resolution Value of the resolution parameter, use a value above
#' (below) 1.0 if you want to obtain a larger (smaller) number of communities.
#' @param algorithm Algorithm for modularity optimization (1 = original Louvain
#' algorithm; 2 = Louvain algorithm with multilevel refinement; 3 = SLM
#' algorithm; 4 = Leiden algorithm). Leiden requires the leidenalg python.
#' @param method Method for running leiden (defaults to matrix which is fast for small datasets).
#' Enable method = "igraph" to avoid casting large data to a dense matrix.
#' @param n.start Number of random starts.
#' @param n.iter Maximal number of iterations per random start.
#' @param random.seed Seed of the random number generator.
#' @param group.singletons Group singletons into nearest cluster. If FALSE, assign all singletons to
#' a "singleton" group
#' @param temp.file.location Directory where intermediate files will be written.
#' Specify the ABSOLUTE path.
#' @param edge.file.name Edge file to use as input for modularity optimizer jar.
#' @param verbose Print output
#'
#' @rdname FindClusters
#' @concept clustering
#' @export
#'
FindClusters.default <- function(
object,
modularity.fxn = 1,
initial.membership = NULL,
node.sizes = NULL,
resolution = 0.8,
method = "matrix",
algorithm = 1,
n.start = 10,
n.iter = 10,
random.seed = 0,
group.singletons = TRUE,
temp.file.location = NULL,
edge.file.name = NULL,
verbose = TRUE,
...
) {
CheckDots(...)
if (is.null(x = object)) {
stop("Please provide an SNN graph")
}
if (tolower(x = algorithm) == "louvain") {
algorithm <- 1
}
if (tolower(x = algorithm) == "leiden") {
algorithm <- 4
}
if (nbrOfWorkers() > 1) {
clustering.results <- future_lapply(
X = resolution,
FUN = function(r) {
if (algorithm %in% c(1:3)) {
ids <- RunModularityClustering(
SNN = object,
modularity = modularity.fxn,
resolution = r,
algorithm = algorithm,
n.start = n.start,
n.iter = n.iter,
random.seed = random.seed,
print.output = verbose,
temp.file.location = temp.file.location,
edge.file.name = edge.file.name
)
} else if (algorithm == 4) {
ids <- RunLeiden(
object = object,
method = method,
partition.type = "RBConfigurationVertexPartition",
initial.membership = initial.membership,
node.sizes = node.sizes,
resolution.parameter = r,
random.seed = random.seed,
n.iter = n.iter
)
} else {
stop("algorithm not recognised, please specify as an integer or string")
}
names(x = ids) <- colnames(x = object)
ids <- GroupSingletons(ids = ids, SNN = object, verbose = verbose)
results <- list(factor(x = ids))
names(x = results) <- paste0('res.', r)
return(results)
}
)
clustering.results <- as.data.frame(x = clustering.results)
} else {
clustering.results <- data.frame(row.names = colnames(x = object))
for (r in resolution) {
if (algorithm %in% c(1:3)) {
ids <- RunModularityClustering(
SNN = object,
modularity = modularity.fxn,
resolution = r,
algorithm = algorithm,
n.start = n.start,
n.iter = n.iter,
random.seed = random.seed,
print.output = verbose,
temp.file.location = temp.file.location,
edge.file.name = edge.file.name)
} else if (algorithm == 4) {
ids <- RunLeiden(
object = object,
method = method,
partition.type = "RBConfigurationVertexPartition",
initial.membership = initial.membership,
node.sizes = node.sizes,
resolution.parameter = r,
random.seed = random.seed,
n.iter = n.iter
)
} else {
stop("algorithm not recognised, please specify as an integer or string")
}
names(x = ids) <- colnames(x = object)
ids <- GroupSingletons(ids = ids, SNN = object, group.singletons = group.singletons, verbose = verbose)
clustering.results[, paste0("res.", r)] <- factor(x = ids)
}
}
return(clustering.results)
}
#' @importFrom methods is
#'
#' @param graph.name Name of graph to use for the clustering algorithm
#'
#' @rdname FindClusters
#' @export
#' @concept clustering
#' @method FindClusters Seurat
#'
FindClusters.Seurat <- function(
object,
graph.name = NULL,
modularity.fxn = 1,
initial.membership = NULL,
node.sizes = NULL,
resolution = 0.8,
method = "matrix",
algorithm = 1,
n.start = 10,
n.iter = 10,
random.seed = 0,
group.singletons = TRUE,
temp.file.location = NULL,
edge.file.name = NULL,
verbose = TRUE,
...
) {
CheckDots(...)
graph.name <- graph.name %||% paste0(DefaultAssay(object = object), "_snn")
if (!graph.name %in% names(x = object)) {
stop("Provided graph.name not present in Seurat object")
}
if (!is(object = object[[graph.name]], class2 = "Graph")) {
stop("Provided graph.name does not correspond to a graph object.")
}
clustering.results <- FindClusters(
object = object[[graph.name]],
modularity.fxn = modularity.fxn,
initial.membership = initial.membership,
node.sizes = node.sizes,
resolution = resolution,
method = method,
algorithm = algorithm,
n.start = n.start,
n.iter = n.iter,
random.seed = random.seed,
group.singletons = group.singletons,
temp.file.location = temp.file.location,
edge.file.name = edge.file.name,
verbose = verbose,
...
)
colnames(x = clustering.results) <- paste0(graph.name, "_", colnames(x = clustering.results))
object <- AddMetaData(object = object, metadata = clustering.results)
Idents(object = object) <- colnames(x = clustering.results)[ncol(x = clustering.results)]
levels <- levels(x = object)
levels <- tryCatch(
expr = as.numeric(x = levels),
warning = function(...) {
return(levels)
},
error = function(...) {
return(levels)
}
)
Idents(object = object) <- factor(x = Idents(object = object), levels = sort(x = levels))
object[['seurat_clusters']] <- Idents(object = object)
cmd <- LogSeuratCommand(object = object, return.command = TRUE)
slot(object = cmd, name = 'assay.used') <- DefaultAssay(object = object[[graph.name]])
object[[slot(object = cmd, name = 'name')]] <- cmd
return(object)
}
#' @param query Matrix of data to query against object. If missing, defaults to
#' object.
#' @param distance.matrix Boolean value of whether the provided matrix is a
#' distance matrix; note, for objects of class \code{dist}, this parameter will
#' be set automatically
#' @param k.param Defines k for the k-nearest neighbor algorithm
#' @param return.neighbor Return result as \code{\link{Neighbor}} object. Not
#' used with distance matrix input.
#' @param compute.SNN also compute the shared nearest neighbor graph
#' @param prune.SNN Sets the cutoff for acceptable Jaccard index when
#' computing the neighborhood overlap for the SNN construction. Any edges with
#' values less than or equal to this will be set to 0 and removed from the SNN
#' graph. Essentially sets the stringency of pruning (0 --- no pruning, 1 ---
#' prune everything).
#' @param nn.method Method for nearest neighbor finding. Options include: rann,
#' annoy
#' @param annoy.metric Distance metric for annoy. Options include: euclidean,
#' cosine, manhattan, and hamming
#' @param n.trees More trees gives higher precision when using annoy approximate
#' nearest neighbor search
#' @param nn.eps Error bound when performing nearest neighbor seach using RANN;
#' default of 0.0 implies exact nearest neighbor search
#' @param verbose Whether or not to print output to the console
#' @param force.recalc Force recalculation of (S)NN.
#' @param l2.norm Take L2Norm of the data
#' @param cache.index Include cached index in returned Neighbor object
#' (only relevant if return.neighbor = TRUE)
#' @param index Precomputed index. Useful if querying new data against existing
#' index to avoid recomputing.
#'
#' @importFrom RANN nn2
#' @importFrom methods as
#'
#' @rdname FindNeighbors
#' @export
#' @concept clustering
#' @method FindNeighbors default
#'
FindNeighbors.default <- function(
object,
query = NULL,
distance.matrix = FALSE,
k.param = 20,
return.neighbor = FALSE,
compute.SNN = !return.neighbor,
prune.SNN = 1/15,
nn.method = "annoy",
n.trees = 50,
annoy.metric = "euclidean",
nn.eps = 0,
verbose = TRUE,
force.recalc = FALSE,
l2.norm = FALSE,
cache.index = FALSE,
index = NULL,
...
) {
CheckDots(...)
if (is.null(x = dim(x = object))) {
warning(
"Object should have two dimensions, attempting to coerce to matrix",
call. = FALSE
)
object <- as.matrix(x = object)
}
if (is.null(rownames(x = object))) {
stop("Please provide rownames (cell names) with the input object")
}
n.cells <- nrow(x = object)
if (n.cells < k.param) {
warning(
"k.param set larger than number of cells. Setting k.param to number of cells - 1.",
call. = FALSE
)
k.param <- n.cells - 1
}
if (l2.norm) {
object <- L2Norm(mat = object)
query <- query %iff% L2Norm(mat = query)
}
query <- query %||% object
# find the k-nearest neighbors for each single cell
if (!distance.matrix) {
if (verbose) {
if (return.neighbor) {
message("Computing nearest neighbors")
} else {
message("Computing nearest neighbor graph")
}
}
nn.ranked <- NNHelper(
data = object,
query = query,
k = k.param,
method = nn.method,
n.trees = n.trees,
searchtype = "standard",
eps = nn.eps,
metric = annoy.metric,
cache.index = cache.index,
index = index
)
if (return.neighbor) {
if (compute.SNN) {
warning("The SNN graph is not computed if return.neighbor is TRUE.", call. = FALSE)
}
return(nn.ranked)
}
nn.ranked <- Indices(object = nn.ranked)
} else {
if (verbose) {
message("Building SNN based on a provided distance matrix")
}
knn.mat <- matrix(data = 0, ncol = k.param, nrow = n.cells)
knd.mat <- knn.mat
for (i in 1:n.cells) {
knn.mat[i, ] <- order(object[i, ])[1:k.param]
knd.mat[i, ] <- object[i, knn.mat[i, ]]
}
nn.ranked <- knn.mat[, 1:k.param]
}
# convert nn.ranked into a Graph
j <- as.numeric(x = t(x = nn.ranked))
i <- ((1:length(x = j)) - 1) %/% k.param + 1
nn.matrix <- as(object = sparseMatrix(i = i, j = j, x = 1, dims = c(nrow(x = object), nrow(x = object))), Class = "Graph")
rownames(x = nn.matrix) <- rownames(x = object)
colnames(x = nn.matrix) <- rownames(x = object)
neighbor.graphs <- list(nn = nn.matrix)
if (compute.SNN) {
if (verbose) {
message("Computing SNN")
}
snn.matrix <- ComputeSNN(
nn_ranked = nn.ranked,
prune = prune.SNN
)
rownames(x = snn.matrix) <- rownames(x = object)
colnames(x = snn.matrix) <- rownames(x = object)
snn.matrix <- as.Graph(x = snn.matrix)
neighbor.graphs[["snn"]] <- snn.matrix
}
return(neighbor.graphs)
}
#' @rdname FindNeighbors
#' @export
#' @concept clustering
#' @method FindNeighbors Assay
#'
FindNeighbors.Assay <- function(
object,
features = NULL,
k.param = 20,
return.neighbor = FALSE,
compute.SNN = !return.neighbor,
prune.SNN = 1/15,
nn.method = "annoy",
n.trees = 50,
annoy.metric = "euclidean",
nn.eps = 0,
verbose = TRUE,
force.recalc = FALSE,
l2.norm = FALSE,
cache.index = FALSE,
...
) {
CheckDots(...)
features <- features %||% VariableFeatures(object = object)
data.use <- t(x = GetAssayData(object = object, slot = "data")[features, ])
neighbor.graphs <- FindNeighbors(
object = data.use,
k.param = k.param,
compute.SNN = compute.SNN,
prune.SNN = prune.SNN,
nn.method = nn.method,
n.trees = n.trees,
annoy.metric = annoy.metric,
nn.eps = nn.eps,
verbose = verbose,
force.recalc = force.recalc,
l2.norm = l2.norm,
return.neighbor = return.neighbor,
cache.index = cache.index,
...
)
return(neighbor.graphs)
}
#' @rdname FindNeighbors
#' @export
#' @concept clustering
#' @method FindNeighbors dist
#'
FindNeighbors.dist <- function(
object,
k.param = 20,
return.neighbor = FALSE,
compute.SNN = !return.neighbor,
prune.SNN = 1/15,
nn.method = "annoy",
n.trees = 50,
annoy.metric = "euclidean",
nn.eps = 0,
verbose = TRUE,
force.recalc = FALSE,
l2.norm = FALSE,
cache.index = FALSE,
...
) {
CheckDots(...)
return(FindNeighbors(
object = as.matrix(x = object),
distance.matrix = TRUE,
k.param = k.param,
compute.SNN = compute.SNN,
prune.SNN = prune.SNN,
nn.eps = nn.eps,
nn.method = nn.method,
n.trees = n.trees,
annoy.metric = annoy.metric,
verbose = verbose,
force.recalc = force.recalc,
l2.norm = l2.norm,
return.neighbor = return.neighbor,
cache.index = cache.index,
...
))
}
#' @param assay Assay to use in construction of (S)NN; used only when \code{dims}
#' is \code{NULL}
#' @param features Features to use as input for building the (S)NN; used only when
#' \code{dims} is \code{NULL}
#' @param reduction Reduction to use as input for building the (S)NN
#' @param dims Dimensions of reduction to use as input
#' @param do.plot Plot SNN graph on tSNE coordinates
#' @param graph.name Optional naming parameter for stored (S)NN graph
#' (or Neighbor object, if return.neighbor = TRUE). Default is assay.name_(s)nn.
#' To store both the neighbor graph and the shared nearest neighbor (SNN) graph,
#' you must supply a vector containing two names to the \code{graph.name}
#' parameter. The first element in the vector will be used to store the nearest
#' neighbor (NN) graph, and the second element used to store the SNN graph. If
#' only one name is supplied, only the NN graph is stored.
#'
#' @importFrom igraph graph.adjacency plot.igraph E
#'
#' @rdname FindNeighbors
#' @export
#' @concept clustering
#' @method FindNeighbors Seurat
#'
FindNeighbors.Seurat <- function(
object,
reduction = "pca",
dims = 1:10,
assay = NULL,
features = NULL,
k.param = 20,
return.neighbor = FALSE,
compute.SNN = !return.neighbor,
prune.SNN = 1/15,
nn.method = "annoy",
n.trees = 50,
annoy.metric = "euclidean",
nn.eps = 0,
verbose = TRUE,
force.recalc = FALSE,
do.plot = FALSE,
graph.name = NULL,
l2.norm = FALSE,
cache.index = FALSE,
...
) {
CheckDots(...)
if (!is.null(x = dims)) {
assay <- DefaultAssay(object = object[[reduction]])
data.use <- Embeddings(object = object[[reduction]])
if (max(dims) > ncol(x = data.use)) {
stop("More dimensions specified in dims than have been computed")
}
data.use <- data.use[, dims]
neighbor.graphs <- FindNeighbors(
object = data.use,
k.param = k.param,
compute.SNN = compute.SNN,
prune.SNN = prune.SNN,
nn.method = nn.method,
n.trees = n.trees,
annoy.metric = annoy.metric,
nn.eps = nn.eps,
verbose = verbose,
force.recalc = force.recalc,
l2.norm = l2.norm,
return.neighbor = return.neighbor,
cache.index = cache.index,
...
)
} else {
assay <- assay %||% DefaultAssay(object = object)
data.use <- GetAssay(object = object, assay = assay)
neighbor.graphs <- FindNeighbors(
object = data.use,
features = features,
k.param = k.param,
compute.SNN = compute.SNN,
prune.SNN = prune.SNN,
nn.method = nn.method,
n.trees = n.trees,
annoy.metric = annoy.metric,
nn.eps = nn.eps,
verbose = verbose,
force.recalc = force.recalc,
l2.norm = l2.norm,
return.neighbor = return.neighbor,
cache.index = cache.index,
...
)
}
if (length(x = neighbor.graphs) == 1) {
neighbor.graphs <- list(nn = neighbor.graphs)
}
graph.name <- graph.name %||%
if (return.neighbor) {
paste0(assay, ".", names(x = neighbor.graphs))
} else {
paste0(assay, "_", names(x = neighbor.graphs))
}
if (length(x = graph.name) == 1) {
message("Only one graph name supplied, storing nearest-neighbor graph only")
}
for (ii in 1:length(x = graph.name)) {
if (inherits(x = neighbor.graphs[[ii]], what = "Graph")) {
DefaultAssay(object = neighbor.graphs[[ii]]) <- assay
}
object[[graph.name[[ii]]]] <- neighbor.graphs[[ii]]
}
if (do.plot) {
if (!"tsne" %in% names(x = object@reductions)) {
warning("Please compute a tSNE for SNN visualization. See RunTSNE().")
} else {
if (nrow(x = Embeddings(object = object[["tsne"]])) != ncol(x = object)) {
warning("Please compute a tSNE for SNN visualization. See RunTSNE().")
} else {
net <- graph.adjacency(
adjmatrix = as.matrix(x = neighbor.graphs[[2]]),
mode = "undirected",
weighted = TRUE,
diag = FALSE
)
plot.igraph(
x = net,
layout = as.matrix(x = Embeddings(object = object[["tsne"]])),
edge.width = E(graph = net)$weight,
vertex.label = NA,
vertex.size = 0
)
}
}
}
object <- LogSeuratCommand(object = object)
return(object)
}
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Internal
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Run annoy
#
# @param data Data to build the index with
# @param query A set of data to be queried against data
# @param metric Distance metric; can be one of "euclidean", "cosine", "manhattan",
# "hamming"
# @param n.trees More trees gives higher precision when querying
# @param k Number of neighbors
# @param search.k During the query it will inspect up to search_k nodes which
# gives you a run-time tradeoff between better accuracy and speed.
# @param include.distance Include the corresponding distances
# @param index optional index object, will be recomputed if not provided
#
AnnoyNN <- function(data,
query = data,
metric = "euclidean",
n.trees = 50,
k,
search.k = -1,
include.distance = TRUE,
index = NULL
) {
idx <- index %||% AnnoyBuildIndex(
data = data,
metric = metric,
n.trees = n.trees)
nn <- AnnoySearch(
index = idx,
query = query,
k = k,
search.k = search.k,
include.distance = include.distance)
nn$idx <- idx
nn$alg.info <- list(metric = metric, ndim = ncol(x = data))
return(nn)
}
# Build the annoy index
#
# @param data Data to build the index with
# @param metric Distance metric; can be one of "euclidean", "cosine", "manhattan",
# "hamming"
# @param n.trees More trees gives higher precision when querying
#
#' @importFrom RcppAnnoy AnnoyEuclidean AnnoyAngular AnnoyManhattan AnnoyHamming
#
AnnoyBuildIndex <- function(data, metric = "euclidean", n.trees = 50) {
f <- ncol(x = data)
a <- switch(
EXPR = metric,
"euclidean" = new(Class = RcppAnnoy::AnnoyEuclidean, f),
"cosine" = new(Class = RcppAnnoy::AnnoyAngular, f),
"manhattan" = new(Class = RcppAnnoy::AnnoyManhattan, f),
"hamming" = new(Class = RcppAnnoy::AnnoyHamming, f),
stop ("Invalid metric")
)
for (ii in seq(nrow(x = data))) {
a$addItem(ii - 1, data[ii, ])
}
a$build(n.trees)
return(a)
}
# Search an Annoy approximate nearest neighbor index
#
# @param Annoy index, built with AnnoyBuildIndex
# @param query A set of data to be queried against the index
# @param k Number of neighbors
# @param search.k During the query it will inspect up to search_k nodes which
# gives you a run-time tradeoff between better accuracy and speed.
# @param include.distance Include the corresponding distances in the result
#
# @return A list with 'nn.idx' (for each element in 'query', the index of the
# nearest k elements in the index) and 'nn.dists' (the distances of the nearest
# k elements)
#
#' @importFrom future plan
#' @importFrom future.apply future_lapply
#
AnnoySearch <- function(index, query, k, search.k = -1, include.distance = TRUE) {
n <- nrow(x = query)
idx <- matrix(nrow = n, ncol = k)
dist <- matrix(nrow = n, ncol = k)
convert <- methods::is(index, "Rcpp_AnnoyAngular")
if (!inherits(x = plan(), what = "multicore")) {
oplan <- plan(strategy = "sequential")
on.exit(plan(oplan), add = TRUE)
}
res <- future_lapply(X = 1:n, FUN = function(x) {
res <- index$getNNsByVectorList(query[x, ], k, search.k, include.distance)
# Convert from Angular to Cosine distance
if (convert) {
res$dist <- 0.5 * (res$dist * res$dist)
}
list(res$item + 1, res$distance)
})
for (i in 1:n) {
idx[i, ] <- res[[i]][[1]]
if (include.distance) {
dist[i, ] <- res[[i]][[2]]
}
}
return(list(nn.idx = idx, nn.dists = dist))
}
# Calculate mean distance of the farthest neighbors from SNN graph
#
# This function will compute the average distance of the farthest k.nn
# neighbors with the lowest nonzero SNN edge weight. First, for each cell it
# finds the k.nn neighbors with the smallest edge weight. If there are multiple
# cells with the same edge weight at the k.nn-th index, consider all of those
# cells in the next step. Next, it computes the euclidean distance to all k.nn
# cells in the space defined by the embeddings matrix and returns the average
# distance to the farthest k.nn cells.
#
# @param snn.graph An SNN graph
# @param embeddings The cell embeddings used to calculate neighbor distances
# @param k.nn The number of neighbors to calculate
# @param l2.norm Perform L2 normalization on the cell embeddings
# @param nearest.dist The vector of distance to the nearest neighbors to
# subtract off from distance calculations
#
#
ComputeSNNwidth <- function(
snn.graph,
embeddings,
k.nn,
l2.norm = TRUE,
nearest.dist = NULL
) {
if (l2.norm) {
embeddings <- L2Norm(mat = embeddings)
}
nearest.dist <- nearest.dist %||% rep(x = 0, times = ncol(x = snn.graph))
if (length(x = nearest.dist) != ncol(x = snn.graph)) {
stop("Please provide a vector for nearest.dist that has as many elements as",
" there are columns in the snn.graph (", ncol(x = snn.graph), ").")
}
snn.width <- SNN_SmallestNonzero_Dist(
snn = snn.graph,
mat = embeddings,
n = k.nn,
nearest_dist = nearest.dist
)
return (snn.width)
}
# Create an Annoy index
#
# @note Function exists because it's not exported from \pkg{uwot}
#
# @param name Distance metric name
# @param ndim Number of dimensions
#
# @return An nn index object
#
#' @importFrom methods new
#' @importFrom RcppAnnoy AnnoyAngular AnnoyManhattan AnnoyEuclidean AnnoyHamming