forked from satijalab/seurat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintegration.R
5462 lines (5385 loc) · 196 KB
/
integration.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
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#' Find integration anchors
#'
#' Find a set of anchors between a list of \code{\link{Seurat}} objects.
#' These anchors can later be used to integrate the objects using the
#' \code{\link{IntegrateData}} function.
#'
#' The main steps of this procedure are outlined below. For a more detailed
#' description of the methodology, please see Stuart, Butler, et al Cell 2019:
#' \doi{10.1016/j.cell.2019.05.031}; \doi{10.1101/460147}
#'
#' First, determine anchor.features if not explicitly specified using
#' \code{\link{SelectIntegrationFeatures}}. Then for all pairwise combinations
#' of reference and query datasets:
#'
#' \itemize{
#' \item{Perform dimensional reduction on the dataset pair as specified via
#' the \code{reduction} parameter. If \code{l2.norm} is set to \code{TRUE},
#' perform L2 normalization of the embedding vectors.}
#' \item{Identify anchors - pairs of cells from each dataset
#' that are contained within each other's neighborhoods (also known as mutual
#' nearest neighbors).}
#' \item{Filter low confidence anchors to ensure anchors in the low dimension
#' space are in broad agreement with the high dimensional measurements. This
#' is done by looking at the neighbors of each query cell in the reference
#' dataset using \code{max.features} to define this space. If the reference
#' cell isn't found within the first \code{k.filter} neighbors, remove the
#' anchor.}
#' \item{Assign each remaining anchor a score. For each anchor cell, determine
#' the nearest \code{k.score} anchors within its own dataset and within its
#' pair's dataset. Based on these neighborhoods, construct an overall neighbor
#' graph and then compute the shared neighbor overlap between anchor and query
#' cells (analogous to an SNN graph). We use the 0.01 and 0.90 quantiles on
#' these scores to dampen outlier effects and rescale to range between 0-1.}
#' }
#'
#' @param object.list A list of \code{\link{Seurat}} objects between which to
#' find anchors for downstream integration.
#' @param assay A vector of assay names specifying which assay to use when
#' constructing anchors. If NULL, the current default assay for each object is
#' used.
#' @param reference A vector specifying the object/s to be used as a reference
#' during integration. If NULL (default), all pairwise anchors are found (no
#' reference/s). If not NULL, the corresponding objects in \code{object.list}
#' will be used as references. When using a set of specified references, anchors
#' are first found between each query and each reference. The references are
#' then integrated through pairwise integration. Each query is then mapped to
#' the integrated reference.
#' @param anchor.features Can be either:
#' \itemize{
#' \item{A numeric value. This will call \code{\link{SelectIntegrationFeatures}}
#' to select the provided number of features to be used in anchor finding}
#' \item{A vector of features to be used as input to the anchor finding process}
#' }
#' @param scale Whether or not to scale the features provided. Only set to FALSE
#' if you have previously scaled the features you want to use for each object in
#' the object.list
#' @param normalization.method Name of normalization method used: LogNormalize
#' or SCT
#' @param sct.clip.range Numeric of length two specifying the min and max values
#' the Pearson residual will be clipped to
#' @param reduction Dimensional reduction to perform when finding anchors. Can
#' be one of:
#' \itemize{
#' \item{cca: Canonical correlation analysis}
#' \item{rpca: Reciprocal PCA}
#' \item{rlsi: Reciprocal LSI}
#' }
#' @param l2.norm Perform L2 normalization on the CCA cell embeddings after
#' dimensional reduction
#' @param dims Which dimensions to use from the CCA to specify the neighbor
#' search space
#' @param k.anchor How many neighbors (k) to use when picking anchors
#' @param k.filter How many neighbors (k) to use when filtering anchors
#' @param k.score How many neighbors (k) to use when scoring anchors
#' @param max.features The maximum number of features to use when specifying the
#' neighborhood search space in the anchor filtering
#' @param nn.method Method for nearest neighbor finding. Options include: rann,
#' annoy
#' @param n.trees More trees gives higher precision when using annoy approximate
#' nearest neighbor search
#' @param eps Error bound on the neighbor finding algorithm (from RANN/Annoy)
#' @param verbose Print progress bars and output
#'
#' @return Returns an \code{\link{AnchorSet}} object that can be used as input to
#' \code{\link{IntegrateData}}.
#'
#' @references Stuart T, Butler A, et al. Comprehensive Integration of
#' Single-Cell Data. Cell. 2019;177:1888-1902 \doi{10.1016/j.cell.2019.05.031}
#'
#' @importFrom pbapply pblapply
#' @importFrom future.apply future_lapply
#' @importFrom future nbrOfWorkers
#'
#' @export
#' @concept integration
#'
#' @examples
#' \dontrun{
#' # to install the SeuratData package see https://github.com/satijalab/seurat-data
#' library(SeuratData)
#' data("panc8")
#'
#' # panc8 is a merged Seurat object containing 8 separate pancreas datasets
#' # split the object by dataset
#' pancreas.list <- SplitObject(panc8, split.by = "tech")
#'
#' # perform standard preprocessing on each object
#' for (i in 1:length(pancreas.list)) {
#' pancreas.list[[i]] <- NormalizeData(pancreas.list[[i]], verbose = FALSE)
#' pancreas.list[[i]] <- FindVariableFeatures(
#' pancreas.list[[i]], selection.method = "vst",
#' nfeatures = 2000, verbose = FALSE
#' )
#' }
#'
#' # find anchors
#' anchors <- FindIntegrationAnchors(object.list = pancreas.list)
#'
#' # integrate data
#' integrated <- IntegrateData(anchorset = anchors)
#' }
#'
FindIntegrationAnchors <- function(
object.list = NULL,
assay = NULL,
reference = NULL,
anchor.features = 2000,
scale = TRUE,
normalization.method = c("LogNormalize", "SCT"),
sct.clip.range = NULL,
reduction = c("cca", "rpca", "rlsi"),
l2.norm = TRUE,
dims = 1:30,
k.anchor = 5,
k.filter = 200,
k.score = 30,
max.features = 200,
nn.method = "annoy",
n.trees = 50,
eps = 0,
verbose = TRUE
) {
normalization.method <- match.arg(arg = normalization.method)
reduction <- match.arg(arg = reduction)
if (reduction == "rpca") {
reduction <- "pca"
}
if (reduction == "rlsi") {
reduction <- "lsi"
if (normalization.method == "SCT") {
warning("Requested normalization method 'SCT' is not applicable for LSI")
normalization.method <- "LogNormalize"
}
scale <- FALSE
k.filter <- NA
}
my.lapply <- ifelse(
test = verbose && nbrOfWorkers() == 1,
yes = pblapply,
no = future_lapply
)
object.ncells <- sapply(X = object.list, FUN = function(x) dim(x = x)[2])
if (any(object.ncells <= max(dims))) {
bad.obs <- which(x = object.ncells <= max(dims))
stop("Max dimension too large: objects ", paste(bad.obs, collapse = ", "),
" contain fewer than ", max(dims), " cells. \n Please specify a",
" maximum dimensions that is less than the number of cells in any ",
"object (", min(object.ncells), ").")
}
if (!is.null(x = assay)) {
if (length(x = assay) != length(x = object.list)) {
stop("If specifying the assay, please specify one assay per object in the object.list")
}
object.list <- sapply(
X = 1:length(x = object.list),
FUN = function(x) {
DefaultAssay(object = object.list[[x]]) <- assay[x]
return(object.list[[x]])
}
)
} else {
assay <- sapply(X = object.list, FUN = DefaultAssay)
}
# check tool
object.list <- lapply(
X = object.list,
FUN = function (obj) {
slot(object = obj, name = "tools")$Integration <- NULL
return(obj)
})
object.list <- CheckDuplicateCellNames(object.list = object.list)
slot <- "data"
if (reduction == "lsi") {
all.rownames <- lapply(X = object.list, FUN = rownames)
anchor.features <- Reduce(f = intersect, x = all.rownames)
}
if (normalization.method == "SCT") {
slot <- "scale.data"
scale <- FALSE
if (is.numeric(x = anchor.features)) {
stop("Please specify the anchor.features to be used. The expected ",
"workflow for integratinge assays produced by SCTransform is ",
"SelectIntegrationFeatures -> PrepSCTIntegration -> ",
"FindIntegrationAnchors.")
}
sct.check <- sapply(
X = 1:length(x = object.list),
FUN = function(x) {
sct.cmd <- grep(
pattern = 'PrepSCTIntegration',
x = Command(object = object.list[[x]]),
value = TRUE
)
# check assay has gone through PrepSCTIntegration
if (!any(grepl(pattern = "PrepSCTIntegration", x = Command(object = object.list[[x]]))) ||
Command(object = object.list[[x]], command = sct.cmd, value = "assay") != assay[x]) {
stop("Object ", x, " assay - ", assay[x], " has not been processed ",
"by PrepSCTIntegration. Please run PrepSCTIntegration prior to ",
"FindIntegrationAnchors if using assays generated by SCTransform.", call. = FALSE)
}
# check that the correct features are being used
if (all(Command(object = object.list[[x]], command = sct.cmd, value = "anchor.features") != anchor.features)) {
stop("Object ", x, " assay - ", assay[x], " was processed using a ",
"different feature set than in PrepSCTIntegration. Please rerun ",
"PrepSCTIntegration with the same anchor.features for all objects in ",
"the object.list.", call. = FALSE)
}
}
)
}
if (is.numeric(x = anchor.features) && normalization.method != "SCT") {
if (verbose) {
message("Computing ", anchor.features, " integration features")
}
anchor.features <- SelectIntegrationFeatures(
object.list = object.list,
nfeatures = anchor.features,
assay = assay
)
}
if (scale) {
if (verbose) {
message("Scaling features for provided objects")
}
object.list <- my.lapply(
X = object.list,
FUN = function(object) {
ScaleData(object = object, features = anchor.features, verbose = FALSE)
}
)
}
nn.reduction <- reduction
# if using pca or lsi, only need to compute the internal neighborhood structure once
# for each dataset
internal.neighbors <- list()
if (nn.reduction %in% c("pca", "lsi")) {
k.filter <- NA
if (verbose) {
message("Computing within dataset neighborhoods")
}
k.neighbor <- max(k.anchor, k.score)
internal.neighbors <- my.lapply(
X = 1:length(x = object.list),
FUN = function(x) {
NNHelper(
data = Embeddings(object = object.list[[x]][[nn.reduction]])[, dims],
k = k.neighbor + 1,
method = nn.method,
n.trees = n.trees,
eps = eps
)
}
)
}
# determine pairwise combinations
combinations <- expand.grid(1:length(x = object.list), 1:length(x = object.list))
combinations <- combinations[combinations$Var1 < combinations$Var2, , drop = FALSE]
# determine the proper offsets for indexing anchors
objects.ncell <- sapply(X = object.list, FUN = ncol)
offsets <- as.vector(x = cumsum(x = c(0, objects.ncell)))[1:length(x = object.list)]
if (is.null(x = reference)) {
# case for all pairwise, leave the combinations matrix the same
if (verbose) {
message("Finding all pairwise anchors")
}
} else {
reference <- unique(x = sort(x = reference))
if (max(reference) > length(x = object.list)) {
stop('Error: requested reference object ', max(reference), " but only ",
length(x = object.list), " objects provided")
}
# modify the combinations matrix to retain only R-R and R-Q comparisons
if (verbose) {
message("Finding anchors between all query and reference datasets")
ok.rows <- (combinations$Var1 %in% reference) | (combinations$Var2 %in% reference)
combinations <- combinations[ok.rows, ]
}
}
# determine all anchors
anchoring.fxn <- function(row) {
i <- combinations[row, 1]
j <- combinations[row, 2]
object.1 <- DietSeurat(
object = object.list[[i]],
assays = assay[i],
features = anchor.features,
counts = FALSE,
scale.data = TRUE,
dimreducs = reduction
)
object.2 <- DietSeurat(
object = object.list[[j]],
assays = assay[j],
features = anchor.features,
counts = FALSE,
scale.data = TRUE,
dimreducs = reduction
)
# suppress key duplication warning
suppressWarnings(object.1[["ToIntegrate"]] <- object.1[[assay[i]]])
DefaultAssay(object = object.1) <- "ToIntegrate"
if (reduction %in% Reductions(object = object.1)) {
slot(object = object.1[[reduction]], name = "assay.used") <- "ToIntegrate"
}
object.1 <- DietSeurat(object = object.1, assays = "ToIntegrate", scale.data = TRUE, dimreducs = reduction)
suppressWarnings(object.2[["ToIntegrate"]] <- object.2[[assay[j]]])
DefaultAssay(object = object.2) <- "ToIntegrate"
if (reduction %in% Reductions(object = object.2)) {
slot(object = object.2[[reduction]], name = "assay.used") <- "ToIntegrate"
}
object.2 <- DietSeurat(object = object.2, assays = "ToIntegrate", scale.data = TRUE, dimreducs = reduction)
object.pair <- switch(
EXPR = reduction,
'cca' = {
object.pair <- RunCCA(
object1 = object.1,
object2 = object.2,
assay1 = "ToIntegrate",
assay2 = "ToIntegrate",
features = anchor.features,
num.cc = max(dims),
renormalize = FALSE,
rescale = FALSE,
verbose = verbose
)
if (l2.norm){
object.pair <- L2Dim(object = object.pair, reduction = reduction)
reduction <- paste0(reduction, ".l2")
nn.reduction <- reduction
}
reduction.2 <- character()
object.pair
},
'pca' = {
object.pair <- ReciprocalProject(
object.1 = object.1,
object.2 = object.2,
reduction = 'pca',
projected.name = 'projectedpca',
features = anchor.features,
do.scale = FALSE,
do.center = FALSE,
slot = 'scale.data',
l2.norm = l2.norm,
verbose = verbose
)
reduction <- "projectedpca.ref"
reduction.2 <- "projectedpca.query"
if (l2.norm) {
reduction <- paste0(reduction, ".l2")
reduction.2 <- paste0(reduction.2, ".l2")
}
object.pair
},
'lsi' = {
object.pair <- ReciprocalProject(
object.1 = object.1,
object.2 = object.2,
reduction = 'lsi',
projected.name = 'projectedlsi',
features = anchor.features,
do.center = TRUE,
do.scale = FALSE,
slot = 'data',
l2.norm = l2.norm,
verbose = verbose
)
reduction <- "projectedlsi.ref"
reduction.2 <- "projectedlsi.query"
if (l2.norm) {
reduction <- paste0(reduction, ".l2")
reduction.2 <- paste0(reduction.2, ".l2")
}
object.pair
},
stop("Invalid reduction parameter. Please choose either cca, rpca, or rlsi")
)
internal.neighbors <- internal.neighbors[c(i, j)]
anchors <- FindAnchors(
object.pair = object.pair,
assay = c("ToIntegrate", "ToIntegrate"),
slot = slot,
cells1 = colnames(x = object.1),
cells2 = colnames(x = object.2),
internal.neighbors = internal.neighbors,
reduction = reduction,
reduction.2 = reduction.2,
nn.reduction = nn.reduction,
dims = dims,
k.anchor = k.anchor,
k.filter = k.filter,
k.score = k.score,
max.features = max.features,
nn.method = nn.method,
n.trees = n.trees,
eps = eps,
verbose = verbose
)
anchors[, 1] <- anchors[, 1] + offsets[i]
anchors[, 2] <- anchors[, 2] + offsets[j]
return(anchors)
}
if (nbrOfWorkers() == 1) {
all.anchors <- pblapply(
X = 1:nrow(x = combinations),
FUN = anchoring.fxn
)
} else {
all.anchors <- future_lapply(
X = 1:nrow(x = combinations),
FUN = anchoring.fxn,
future.seed = TRUE
)
}
all.anchors <- do.call(what = 'rbind', args = all.anchors)
all.anchors <- rbind(all.anchors, all.anchors[, c(2, 1, 3)])
all.anchors <- AddDatasetID(anchor.df = all.anchors, offsets = offsets, obj.lengths = objects.ncell)
command <- LogSeuratCommand(object = object.list[[1]], return.command = TRUE)
anchor.set <- new(Class = "IntegrationAnchorSet",
object.list = object.list,
reference.objects = reference %||% seq_along(object.list),
anchors = all.anchors,
offsets = offsets,
anchor.features = anchor.features,
command = command
)
return(anchor.set)
}
# Merge dataset and perform reciprocal SVD projection, adding new dimreducs
# for each projection and the merged original SVDs.
#
# @param object.1 First Seurat object to merge
# @param object.2 Second Seurat object to merge
# @param reduction Name of DimReduc to use. Must be an SVD-based DimReduc (eg, PCA or LSI)
# so that the loadings can be used to project new embeddings. Must be present
# in both input objects, with a substantial overlap in the features use to construct
# the SVDs.
# @param dims dimensions used for rpca
# @param projected.name Name to store projected SVDs under (eg, "projectedpca")
# @param features Features to use. Will subset the SVD loadings to use these features
# before performing projection. Typically uses the anchor.features for integration.
# @param do.center Center projected values (subtract mean)
# @param do.scale Scale projected values (divide by SD)
# @param slot Name of slot to pull data from. Should be scale.data for PCA and data for LSI
# @param verbose Display messages
# @return Returns a merged Seurat object with two projected SVDs (object.1 -> object.2, object.2 -> object.1)
# and a merged SVD (needed for within-dataset neighbors)
ReciprocalProject <- function(
object.1,
object.2,
reduction,
dims,
projected.name,
features,
do.scale,
do.center,
slot,
l2.norm,
verbose = TRUE
) {
common.features <- intersect(
x = rownames(x = Loadings(object = object.1[[reduction]])),
y = rownames(x = Loadings(object = object.2[[reduction]]))
)
common.features <- intersect(
x = common.features,
y = features
)
object.pair <- merge(x = object.1, y = object.2, merge.data = TRUE)
data.1 <- GetAssayData(
object = object.1,
slot = slot
)
data.2 <- GetAssayData(
object = object.2,
slot = slot
)
proj.1 <- ProjectSVD(
reduction = object.2[[reduction]],
data = data.1,
mode = reduction,
features = common.features,
do.scale = do.scale,
do.center = do.center,
use.original.stats = FALSE,
verbose = verbose
)
proj.2 <- ProjectSVD(
reduction = object.1[[reduction]],
data = data.2,
mode = reduction,
features = common.features,
do.scale = do.scale,
do.center = do.center,
use.original.stats = FALSE,
verbose = verbose
)
# object.1 is ref, and object.2 is query
reduction.dr.name.1 <- paste0(projected.name, ".ref")
reduction.dr.name.2 <- paste0(projected.name, ".query")
object.pair[[reduction.dr.name.1]] <- CreateDimReducObject(
embeddings = rbind(Embeddings(object = object.1[[reduction]]), proj.2)[,dims],
loadings = Loadings(object = object.1[[reduction]])[,dims],
assay = DefaultAssay(object = object.1),
key = paste0(projected.name, "ref_")
)
object.pair[[reduction.dr.name.2]] <- CreateDimReducObject(
embeddings = rbind(proj.1, Embeddings(object = object.2[[reduction]]))[,dims],
loadings = Loadings(object = object.2[[reduction]])[,dims],
assay = DefaultAssay(object = object.2),
key = paste0(projected.name, "query_")
)
object.pair[[reduction]] <- CreateDimReducObject(
embeddings = rbind(
Embeddings(object = object.1[[reduction]]),
Embeddings(object = object.2[[reduction]]))[,dims],
loadings = Loadings(object = object.1[[reduction]])[,dims],
assay = DefaultAssay(object = object.1),
key = paste0(projected.name, "_")
)
if (l2.norm) {
slot(object = object.pair[[reduction.dr.name.1]], name = "cell.embeddings") <- Sweep(
x = Embeddings(object = object.pair[[reduction.dr.name.1]]),
MARGIN = 2,
STATS = apply(X = Embeddings(object = object.pair[[reduction.dr.name.1]]), MARGIN = 2, FUN = sd),
FUN = "/"
)
slot(object = object.pair[[reduction.dr.name.2]], name = "cell.embeddings") <- Sweep(
x = Embeddings(object = object.pair[[reduction.dr.name.2]]),
MARGIN = 2,
STATS = apply(X = Embeddings(object = object.pair[[reduction.dr.name.2]]), MARGIN = 2, FUN = sd),
FUN = "/"
)
object.pair <- L2Dim(object = object.pair, reduction = reduction.dr.name.1)
object.pair <- L2Dim(object = object.pair, reduction = reduction.dr.name.2)
}
return(object.pair)
}
#' Find transfer anchors
#'
#' Find a set of anchors between a reference and query object. These
#' anchors can later be used to transfer data from the reference to
#' query object using the \code{\link{TransferData}} object.
#'
#' The main steps of this procedure are outlined below. For a more detailed
#' description of the methodology, please see Stuart, Butler, et al Cell 2019.
#' \doi{10.1016/j.cell.2019.05.031}; \doi{10.1101/460147}
#'
#' \itemize{
#'
#' \item{Perform dimensional reduction. Exactly what is done here depends on
#' the values set for the \code{reduction} and \code{project.query}
#' parameters. If \code{reduction = "pcaproject"}, a PCA is performed on
#' either the reference (if \code{project.query = FALSE}) or the query (if
#' \code{project.query = TRUE}), using the \code{features} specified. The data
#' from the other dataset is then projected onto this learned PCA structure.
#' If \code{reduction = "cca"}, then CCA is performed on the reference and
#' query for this dimensional reduction step. If
#' \code{reduction = "lsiproject"}, the stored LSI dimension reduction in the
#' reference object is used to project the query dataset onto the reference.
#' If \code{l2.norm} is set to \code{TRUE}, perform L2 normalization of the
#' embedding vectors.}
#' \item{Identify anchors between the reference and query - pairs of cells
#' from each dataset that are contained within each other's neighborhoods
#' (also known as mutual nearest neighbors).}
#' \item{Filter low confidence anchors to ensure anchors in the low dimension
#' space are in broad agreement with the high dimensional measurements. This
#' is done by looking at the neighbors of each query cell in the reference
#' dataset using \code{max.features} to define this space. If the reference
#' cell isn't found within the first \code{k.filter} neighbors, remove the
#' anchor.}
#' \item{Assign each remaining anchor a score. For each anchor cell, determine
#' the nearest \code{k.score} anchors within its own dataset and within its
#' pair's dataset. Based on these neighborhoods, construct an overall neighbor
#' graph and then compute the shared neighbor overlap between anchor and query
#' cells (analogous to an SNN graph). We use the 0.01 and 0.90 quantiles on
#' these scores to dampen outlier effects and rescale to range between 0-1.}
#' }
#'
#' @param reference \code{\link{Seurat}} object to use as the reference
#' @param query \code{\link{Seurat}} object to use as the query
#' @param reference.assay Name of the Assay to use from reference
#' @param reference.neighbors Name of the Neighbor to use from the reference.
#' Optionally enables reuse of precomputed neighbors.
#' @param query.assay Name of the Assay to use from query
#' @param reduction Dimensional reduction to perform when finding anchors.
#' Options are:
#' \itemize{
#' \item{pcaproject: Project the PCA from the reference onto the query. We
#' recommend using PCA when reference and query datasets are from scRNA-seq}
#' \item{lsiproject: Project the LSI from the reference onto the query. We
#' recommend using LSI when reference and query datasets are from scATAC-seq.
#' This requires that LSI has been computed for the reference dataset, and the
#' same features (eg, peaks or genome bins) are present in both the reference
#' and query. See \code{\link[Signac]{RunTFIDF}} and
#' \code{\link[Signac]{RunSVD}}}
#' \item{rpca: Project the PCA from the reference onto the query, and the PCA
#' from the query onto the reference (reciprocal PCA projection).}
#' \item{cca: Run a CCA on the reference and query }
#' }
#' @param reference.reduction Name of dimensional reduction to use from the
#' reference if running the pcaproject workflow. Optionally enables reuse of
#' precomputed reference dimensional reduction. If NULL (default), use a PCA
#' computed on the reference object.
#' @param project.query Project the PCA from the query dataset onto the
#' reference. Use only in rare cases where the query dataset has a much larger
#' cell number, but the reference dataset has a unique assay for transfer. In
#' this case, the default features will be set to the variable features of the
#' query object that are alos present in the reference.
#' @param features Features to use for dimensional reduction. If not specified,
#' set as variable features of the reference object which are also present in
#' the query.
#' @param scale Scale query data.
#' @param normalization.method Name of normalization method used: LogNormalize
#' or SCT.
#' @param recompute.residuals If using SCT as a normalization method, compute
#' query Pearson residuals using the reference SCT model parameters.
#' @param npcs Number of PCs to compute on reference if reference.reduction is
#' not provided.
#' @param l2.norm Perform L2 normalization on the cell embeddings after
#' dimensional reduction
#' @param dims Which dimensions to use from the reduction to specify the
#' neighbor search space
#' @param k.anchor How many neighbors (k) to use when finding anchors
#' @param k.filter How many neighbors (k) to use when filtering anchors. Set to
#' NA to turn off filtering.
#' @param k.score How many neighbors (k) to use when scoring anchors
#' @param max.features The maximum number of features to use when specifying the
#' neighborhood search space in the anchor filtering
#' @param nn.method Method for nearest neighbor finding. Options include: rann,
#' annoy
#' @param n.trees More trees gives higher precision when using annoy approximate
#' nearest neighbor search
#' @param eps Error bound on the neighbor finding algorithm (from
#' \code{\link{RANN}} or \code{\link{RcppAnnoy}})
#' @param approx.pca Use truncated singular value decomposition to approximate
#' PCA
#' @param mapping.score.k Compute and store nearest k query neighbors in the
#' AnchorSet object that is returned. You can optionally set this if you plan
#' on computing the mapping score and want to enable reuse of some downstream
#' neighbor calculations to make the mapping score function more efficient.
#' @param verbose Print progress bars and output
#'
#' @return Returns an \code{AnchorSet} object that can be used as input to
#' \code{\link{TransferData}}, \code{\link{IntegrateEmbeddings}} and
#' \code{\link{MapQuery}}. The dimension reduction used for finding anchors is
#' stored in the \code{AnchorSet} object and can be used for computing anchor
#' weights in downstream functions. Note that only the requested dimensions are
#' stored in the dimension reduction object in the \code{AnchorSet}. This means
#' that if \code{dims=2:20} is used, for example, the dimension of the stored
#' reduction is \code{1:19}.
#'
#' @references Stuart T, Butler A, et al. Comprehensive Integration of
#' Single-Cell Data. Cell. 2019;177:1888-1902 \doi{10.1016/j.cell.2019.05.031};
#'
#' @export
#' @importFrom methods slot slot<-
#' @concept integration
#' @examples
#' \dontrun{
#' # to install the SeuratData package see https://github.com/satijalab/seurat-data
#' library(SeuratData)
#' data("pbmc3k")
#'
#' # for demonstration, split the object into reference and query
#' pbmc.reference <- pbmc3k[, 1:1350]
#' pbmc.query <- pbmc3k[, 1351:2700]
#'
#' # perform standard preprocessing on each object
#' pbmc.reference <- NormalizeData(pbmc.reference)
#' pbmc.reference <- FindVariableFeatures(pbmc.reference)
#' pbmc.reference <- ScaleData(pbmc.reference)
#'
#' pbmc.query <- NormalizeData(pbmc.query)
#' pbmc.query <- FindVariableFeatures(pbmc.query)
#' pbmc.query <- ScaleData(pbmc.query)
#'
#' # find anchors
#' anchors <- FindTransferAnchors(reference = pbmc.reference, query = pbmc.query)
#'
#' # transfer labels
#' predictions <- TransferData(
#' anchorset = anchors,
#' refdata = pbmc.reference$seurat_annotations
#' )
#' pbmc.query <- AddMetaData(object = pbmc.query, metadata = predictions)
#' }
#'
FindTransferAnchors <- function(
reference,
query,
normalization.method = "LogNormalize",
recompute.residuals = TRUE,
reference.assay = NULL,
reference.neighbors = NULL,
query.assay = NULL,
reduction = "pcaproject",
reference.reduction = NULL,
project.query = FALSE,
features = NULL,
scale = TRUE,
npcs = 30,
l2.norm = TRUE,
dims = 1:30,
k.anchor = 5,
k.filter = 200,
k.score = 30,
max.features = 200,
nn.method = "annoy",
n.trees = 50,
eps = 0,
approx.pca = TRUE,
mapping.score.k = NULL,
verbose = TRUE
) {
# input validation
ValidateParams_FindTransferAnchors(
reference = reference,
query = query,
normalization.method = normalization.method,
recompute.residuals = recompute.residuals,
reference.assay = reference.assay,
reference.neighbors = reference.neighbors,
query.assay = query.assay,
reduction = reduction,
reference.reduction = reference.reduction,
project.query = project.query,
features = features,
scale = scale,
npcs = npcs,
l2.norm = l2.norm,
dims = dims,
k.anchor = k.anchor,
k.filter = k.filter,
k.score = k.score,
max.features = max.features,
nn.method = nn.method,
n.trees = n.trees,
eps = eps,
approx.pca = approx.pca,
mapping.score.k = mapping.score.k,
verbose = verbose
)
projected <- ifelse(test = reduction == "pcaproject", yes = TRUE, no = FALSE)
reduction.2 <- character()
feature.mean <- NULL
reference.reduction.init <- reference.reduction
if (normalization.method == "SCT") {
# ensure all residuals required are computed
query <- suppressWarnings(expr = GetResidual(object = query, assay = query.assay, features = features, verbose = FALSE))
if (is.null(x = reference.reduction)) {
reference <- suppressWarnings(expr = GetResidual(object = reference, assay = reference.assay, features = features, verbose = FALSE))
features <- intersect(
x = features,
y = intersect(
x = rownames(x = GetAssayData(object = query[[query.assay]], slot = "scale.data")),
y = rownames(x = GetAssayData(object = reference[[reference.assay]], slot = "scale.data"))
)
)
reference[[reference.assay]] <- as(
object = CreateAssayObject(
data = GetAssayData(object = reference[[reference.assay]], slot = "scale.data")[features, ]),
Class = "SCTAssay"
)
reference <- SetAssayData(
object = reference,
slot = "scale.data",
assay = reference.assay,
new.data = as.matrix(x = GetAssayData(object = reference[[reference.assay]], slot = "data"))
)
}
query[[query.assay]] <- as(
object = CreateAssayObject(
data = GetAssayData(object = query[[query.assay]], slot = "scale.data")[features, ]),
Class = "SCTAssay"
)
query <- SetAssayData(
object = query,
slot = "scale.data",
assay = query.assay,
new.data = as.matrix(x = GetAssayData(object = query[[query.assay]], slot = "data"))
)
feature.mean <- "SCT"
}
# only keep necessary info from objects
query <- DietSeurat(
object = query,
assays = query.assay,
dimreducs = reference.reduction,
features = features,
scale.data = TRUE
)
# check assay in the reference.reduction
if (!is.null(reference.reduction) &&
slot(object = reference[[reference.reduction]], name = "assay.used") != reference.assay) {
warnings("reference assay is diffrent from the assay.used in", reference.reduction)
slot(object = reference[[reference.reduction]], name = "assay.used") <- reference.assay
}
reference <- DietSeurat(
object = reference,
assays = reference.assay,
dimreducs = reference.reduction,
features = features,
scale.data = TRUE
)
# append query and reference to cell names - mainly to avoid name conflicts
query <- RenameCells(
object = query,
new.names = paste0(Cells(x = query), "_", "query")
)
reference <- RenameCells(
object = reference,
new.names = paste0(Cells(x = reference), "_", "reference")
)
# Perform PCA projection
if (reduction == 'pcaproject') {
if (project.query) {
if (is.null(x = reference.reduction)) {
reference.reduction <- "pca"
if (verbose) {
message("Performing PCA on the provided query using ", length(x = features), " features as input.")
}
if (normalization.method == "LogNormalize") {
query <- ScaleData(
object = query,
features = features,
do.scale = scale,
verbose = FALSE
)
}
query <- RunPCA(
object = query,
npcs = npcs,
reduction.name = reference.reduction,
verbose = FALSE,
features = features,
approx = approx.pca
)
}
projected.pca <- ProjectCellEmbeddings(
reference = query,
reduction = reference.reduction,
query = reference,
scale = scale,
dims = dims,
verbose = verbose
)
orig.embeddings <- Embeddings(object = query[[reference.reduction]])[, dims]
orig.loadings <- Loadings(object = query[[reference.reduction]])
} else {
if (is.null(x = reference.reduction)) {
reference.reduction <- "pca"
if (verbose) {
message("Performing PCA on the provided reference using ", length(x = features), " features as input.")
}
if (normalization.method == "LogNormalize") {
reference <- ScaleData(object = reference, features = features, do.scale = scale, verbose = FALSE)
}
reference <- RunPCA(
object = reference,
npcs = npcs,
verbose = FALSE,
features = features,
approx = approx.pca
)
}
projected.pca <- ProjectCellEmbeddings(
reference = reference,
reduction = reference.reduction,
query = query,
scale = scale,
dims = dims,
feature.mean = feature.mean,
verbose = verbose
)
orig.embeddings <- Embeddings(object = reference[[reference.reduction]])[, dims]
orig.loadings <- Loadings(object = reference[[reference.reduction]])
}
combined.pca <- CreateDimReducObject(
embeddings = as.matrix(x = rbind(orig.embeddings, projected.pca)),
key = "ProjectPC_",
assay = reference.assay
)
combined.ob <- suppressWarnings(expr = merge(
x = DietSeurat(object = reference, counts = FALSE),
y = DietSeurat(object = query, counts = FALSE),
))
combined.ob[["pcaproject"]] <- combined.pca
colnames(x = orig.loadings) <- paste0("ProjectPC_", 1:ncol(x = orig.loadings))
Loadings(object = combined.ob[["pcaproject"]]) <- orig.loadings[, dims]
}
# Use reciprocal PCA projection in anchor finding
if (reduction == "rpca") {
# Run PCA on reference and query
if (is.null(x = reference.reduction)) {
reference.reduction <- "pca"
if (verbose) {
message("Performing PCA on the provided reference using ", length(x = features), " features as input.")
}
if (normalization.method == "LogNormalize") {
reference <- ScaleData(
object = reference,
features = features,
do.scale = scale,
verbose = verbose
)
}
reference <- RunPCA(
object = reference,
npcs = npcs,
verbose = FALSE,
features = features,
approx = approx.pca
)
}
if (verbose) {
message("Performing PCA on the provided query using ", length(x = features), " features as input.")
}
if (normalization.method == "LogNormalize") {
query <- ScaleData(
object = query,
features = features,
do.scale = scale,
verbose = verbose
)
}
query <- RunPCA(
object = query,
npcs = ncol(x = reference[[reference.reduction]]),
reduction.name = reference.reduction,
verbose = FALSE,
features = features,
approx = approx.pca
)
combined.ob <- ReciprocalProject(
object.1 = reference,
object.2 = query,
reduction = reference.reduction,
dims = dims,
projected.name = reduction,
features = features,
do.scale = FALSE,
do.center = FALSE,
slot = 'scale.data',
l2.norm = l2.norm,
verbose = verbose
)
# pcaproject is used as the weight.matrix in MapQuery
projected.pca <- ProjectCellEmbeddings(
reference = reference,
reduction = reference.reduction,
query = query,
scale = scale,
dims = dims,
feature.mean = feature.mean,
verbose = verbose
)
orig.embeddings <- Embeddings(object = reference[[reference.reduction]])[, dims]
orig.loadings <- Loadings(object = reference[[reference.reduction]])
combined.pca <- CreateDimReducObject(
embeddings = as.matrix(x = rbind(orig.embeddings, projected.pca)),
key = "ProjectPC_",
assay = reference.assay
)
combined.ob[["pcaproject"]] <- combined.pca