forked from satijalab/seurat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdimensional_reduction.R
2584 lines (2522 loc) · 79.9 KB
/
dimensional_reduction.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
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#' Determine statistical significance of PCA scores.
#'
#' Randomly permutes a subset of data, and calculates projected PCA scores for
#' these 'random' genes. Then compares the PCA scores for the 'random' genes
#' with the observed PCA scores to determine statistical signifance. End result
#' is a p-value for each gene's association with each principal component.
#'
#' @param object Seurat object
#' @param reduction DimReduc to use. ONLY PCA CURRENTLY SUPPORTED.
#' @param assay Assay used to calculate reduction.
#' @param dims Number of PCs to compute significance for
#' @param num.replicate Number of replicate samplings to perform
#' @param prop.freq Proportion of the data to randomly permute for each
#' replicate
#' @param verbose Print progress bar showing the number of replicates
#' that have been processed.
#' @param maxit maximum number of iterations to be performed by the irlba function of RunPCA
#'
#' @return Returns a Seurat object where JS(object = object[['pca']], slot = 'empirical')
#' represents p-values for each gene in the PCA analysis. If ProjectPCA is
#' subsequently run, JS(object = object[['pca']], slot = 'full') then
#' represents p-values for all genes.
#'
#' @importFrom methods new
#' @importFrom pbapply pblapply pbsapply
#' @importFrom future.apply future_lapply future_sapply
#' @importFrom future nbrOfWorkers
#'
#' @references Inspired by Chung et al, Bioinformatics (2014)
#' @concept dimensional_reduction
#'
#' @export
#'
#' @examples
#' \dontrun{
#' data("pbmc_small")
#' pbmc_small = suppressWarnings(JackStraw(pbmc_small))
#' head(JS(object = pbmc_small[['pca']], slot = 'empirical'))
#' }
#'
JackStraw <- function(
object,
reduction = "pca",
assay = NULL,
dims = 20,
num.replicate = 100,
prop.freq = 0.01,
verbose = TRUE,
maxit = 1000
) {
if (reduction != "pca") {
stop("Only pca for reduction is currently supported")
}
if (verbose && nbrOfWorkers() == 1) {
my.lapply <- pblapply
my.sapply <- pbsapply
} else {
my.lapply <- future_lapply
my.sapply <- future_sapply
}
assay <- assay %||% DefaultAssay(object = object)
if (IsSCT(assay = object[[assay]])) {
stop("JackStraw cannot be run on SCTransform-normalized data.
Please supply a non-SCT assay.")
}
if (dims > length(x = object[[reduction]])) {
dims <- length(x = object[[reduction]])
warning("Number of dimensions specified is greater than those available. Setting dims to ", dims, " and continuing", immediate. = TRUE)
}
if (dims > nrow(x = object)) {
dims <- nrow(x = object)
warning("Number of dimensions specified is greater than the number of cells. Setting dims to ", dims, " and continuing", immediate. = TRUE)
}
loadings <- Loadings(object = object[[reduction]], projected = FALSE)
reduc.features <- rownames(x = loadings)
if (length(x = reduc.features) < 3) {
stop("Too few features")
}
if (length(x = reduc.features) * prop.freq < 3) {
warning(
"Number of variable genes given ",
prop.freq,
" as the prop.freq is low. Consider including more variable genes and/or increasing prop.freq. ",
"Continuing with 3 genes in every random sampling."
)
}
data.use <- GetAssayData(object = object, assay = assay, slot = "scale.data")[reduc.features, ]
rev.pca <- object[[paste0('RunPCA.', assay)]]$rev.pca
weight.by.var <- object[[paste0('RunPCA.', assay)]]$weight.by.var
fake.vals.raw <- my.lapply(
X = 1:num.replicate,
FUN = JackRandom,
scaled.data = data.use,
prop.use = prop.freq,
r1.use = 1,
r2.use = dims,
rev.pca = rev.pca,
weight.by.var = weight.by.var,
maxit = maxit
)
fake.vals <- sapply(
X = 1:dims,
FUN = function(x) {
return(as.numeric(x = unlist(x = lapply(
X = 1:num.replicate,
FUN = function(y) {
return(fake.vals.raw[[y]][, x])
}
))))
}
)
fake.vals <- as.matrix(x = fake.vals)
jackStraw.empP <- as.matrix(
my.sapply(
X = 1:dims,
FUN = function(x) {
return(unlist(x = lapply(
X = abs(loadings[, x]),
FUN = EmpiricalP,
nullval = abs(fake.vals[,x])
)))
}
)
)
colnames(x = jackStraw.empP) <- paste0("PC", 1:ncol(x = jackStraw.empP))
jackstraw.obj <- new(
Class = "JackStrawData",
empirical.p.values = jackStraw.empP,
fake.reduction.scores = fake.vals,
empirical.p.values.full = matrix()
)
JS(object = object[[reduction]]) <- jackstraw.obj
object <- LogSeuratCommand(object = object)
return(object)
}
#' L2-normalization
#'
#' Perform l2 normalization on given dimensional reduction
#'
#' @param object Seurat object
#' @param reduction Dimensional reduction to normalize
#' @param new.dr name of new dimensional reduction to store
#' (default is olddr.l2)
#' @param new.key name of key for new dimensional reduction
#'
#' @return Returns a \code{\link{Seurat}} object
#' @concept dimensional_reduction
#'
#' @export
#'
L2Dim <- function(object, reduction, new.dr = NULL, new.key = NULL) {
l2.norm <- L2Norm(mat = Embeddings(object[[reduction]]))
if(is.null(new.dr)){
new.dr <- paste0(reduction, ".l2")
}
if(is.null(new.key)){
new.key <- paste0("L2", Key(object[[reduction]]))
}
colnames(x = l2.norm) <- paste0(new.key, 1:ncol(x = l2.norm))
l2.dr <- CreateDimReducObject(
embeddings = l2.norm,
loadings = Loadings(object = object[[reduction]], projected = FALSE),
projected = Loadings(object = object[[reduction]], projected = TRUE),
assay = DefaultAssay(object = object),
stdev = slot(object = object[[reduction]], name = 'stdev'),
key = new.key,
jackstraw = slot(object = object[[reduction]], name = 'jackstraw'),
misc = slot(object = object[[reduction]], name = 'misc')
)
object[[new.dr]] <- l2.dr
return(object)
}
#' L2-Normalize CCA
#'
#' Perform l2 normalization on CCs
#'
#' @param object Seurat object
#' @param \dots Additional parameters to L2Dim.
#' @concept dimensional_reduction
#'
#' @export
#'
L2CCA <- function(object, ...){
CheckDots(..., fxns = 'L2Dim')
return(L2Dim(object = object, reduction = "cca", ...))
}
#' Significant genes from a PCA
#'
#' Returns a set of genes, based on the JackStraw analysis, that have
#' statistically significant associations with a set of PCs.
#'
#' @param object Seurat object
#' @param pcs.use PCS to use.
#' @param pval.cut P-value cutoff
#' @param use.full Use the full list of genes (from the projected PCA). Assumes
#' that \code{ProjectDim} has been run. Currently, must be set to FALSE.
#' @param max.per.pc Maximum number of genes to return per PC. Used to avoid genes from one PC dominating the entire analysis.
#'
#' @return A vector of genes whose p-values are statistically significant for
#' at least one of the given PCs.
#'
#' @export
#' @concept dimensional_reduction
#'
#' @seealso \code{\link{ProjectDim}} \code{\link{JackStraw}}
#'
#' @examples
#' data("pbmc_small")
#' PCASigGenes(pbmc_small, pcs.use = 1:2)
#'
PCASigGenes <- function(
object,
pcs.use,
pval.cut = 0.1,
use.full = FALSE,
max.per.pc = NULL
) {
# pvals.use <- GetDimReduction(object,reduction.type = "pca",slot = "jackstraw")@empirical.p.values
empirical.use <- ifelse(test = use.full, yes = 'full', no = 'empirical')
pvals.use <- JS(object = object[['pca']], slot = empirical.use)
if (length(x = pcs.use) == 1) {
pvals.min <- pvals.use[, pcs.use]
}
if (length(x = pcs.use) > 1) {
pvals.min <- apply(X = pvals.use[, pcs.use], MARGIN = 1, FUN = min)
}
names(x = pvals.min) <- rownames(x = pvals.use)
features <- names(x = pvals.min)[pvals.min < pval.cut]
if (!is.null(x = max.per.pc)) {
top.features <- TopFeatures(
object = object[['pca']],
dim = pcs.use,
nfeatures = max.per.pc,
projected = use.full,
balanced = FALSE
)
features <- intersect(x = top.features, y = features)
}
return(features)
}
#' Project Dimensional reduction onto full dataset
#'
#' Takes a pre-computed dimensional reduction (typically calculated on a subset
#' of genes) and projects this onto the entire dataset (all genes). Note that
#' the cell loadings will remain unchanged, but now there are gene loadings for
#' all genes.
#'
#' @param object Seurat object
#' @param reduction Reduction to use
#' @param assay Assay to use
#' @param dims.print Number of dims to print features for
#' @param nfeatures.print Number of features with highest/lowest loadings to print for
#' each dimension
#' @param overwrite Replace the existing data in feature.loadings
#' @param do.center Center the dataset prior to projection (should be set to TRUE)
#' @param verbose Print top genes associated with the projected dimensions
#'
#' @return Returns Seurat object with the projected values
#'
#' @export
#' @concept dimensional_reduction
#'
#' @examples
#' data("pbmc_small")
#' pbmc_small
#' pbmc_small <- ProjectDim(object = pbmc_small, reduction = "pca")
#' # Vizualize top projected genes in heatmap
#' DimHeatmap(object = pbmc_small, reduction = "pca", dims = 1, balanced = TRUE)
#'
ProjectDim <- function(
object,
reduction = "pca",
assay = NULL,
dims.print = 1:5,
nfeatures.print = 20,
overwrite = FALSE,
do.center = FALSE,
verbose = TRUE
) {
redeuc <- object[[reduction]]
assay <- assay %||% DefaultAssay(object = redeuc)
data.use <- GetAssayData(
object = object[[assay]],
slot = "scale.data"
)
if (do.center) {
data.use <- scale(x = as.matrix(x = data.use), center = TRUE, scale = FALSE)
}
cell.embeddings <- Embeddings(object = redeuc)
new.feature.loadings.full <- data.use %*% cell.embeddings
rownames(x = new.feature.loadings.full) <- rownames(x = data.use)
colnames(x = new.feature.loadings.full) <- colnames(x = cell.embeddings)
Loadings(object = redeuc, projected = TRUE) <- new.feature.loadings.full
if (overwrite) {
Loadings(object = redeuc, projected = FALSE) <- new.feature.loadings.full
}
object[[reduction]] <- redeuc
if (verbose) {
print(
x = redeuc,
dims = dims.print,
nfeatures = nfeatures.print,
projected = TRUE
)
}
object <- LogSeuratCommand(object = object)
return(object)
}
#' @param query.dims Dimensions (columns) to use from query
#' @param reference.dims Dimensions (columns) to use from reference
#' @param ... Additional parameters to \code{\link{RunUMAP}}
#'
#' @inheritParams FindNeighbors
#' @inheritParams RunUMAP
#'
#' @rdname ProjectUMAP
#' @concept dimensional_reduction
#' @export
#'
ProjectUMAP.default <- function(
query,
query.dims = NULL,
reference,
reference.dims = NULL,
k.param = 30,
nn.method = "annoy",
n.trees = 50,
annoy.metric = "cosine",
l2.norm = FALSE,
cache.index = TRUE,
index = NULL,
neighbor.name = "query_ref.nn",
reduction.model,
...
) {
query.dims <- query.dims %||% 1:ncol(x = query)
reference.dims <- reference.dims %||% query.dims
if (length(x = reference.dims) != length(x = query.dims)) {
stop("Length of Reference and Query number of dimensions are not equal")
}
if (any(reference.dims > ncol(x = reference))) {
stop("Reference dims is larger than the number of dimensions present.", call. = FALSE)
}
if (any(query.dims > ncol(x = query))) {
stop("Query dims is larger than the number of dimensions present.", call. = FALSE)
}
if (length(x = Misc(object = reduction.model, slot = 'model')) == 0) {
stop(
"The provided reduction.model does not have a model stored. Please try ",
"running umot-learn on the object first", call. = FALSE
)
}
query.neighbor <- FindNeighbors(
object = reference[, reference.dims],
query = query[, query.dims],
k.param = k.param,
nn.method = nn.method,
n.trees = n.trees,
annoy.metric = annoy.metric,
cache.index = cache.index,
index = index,
return.neighbor = TRUE,
l2.norm = l2.norm
)
proj.umap <- RunUMAP(object = query.neighbor, reduction.model = reduction.model, ...)
return(list(proj.umap = proj.umap, query.neighbor = query.neighbor))
}
#' @rdname ProjectUMAP
#' @concept dimensional_reduction
#' @export
#' @method ProjectUMAP DimReduc
#'
ProjectUMAP.DimReduc <- function(
query,
query.dims = NULL,
reference,
reference.dims = NULL,
k.param = 30,
nn.method = "annoy",
n.trees = 50,
annoy.metric = "cosine",
l2.norm = FALSE,
cache.index = TRUE,
index = NULL,
neighbor.name = "query_ref.nn",
reduction.model,
...
) {
proj.umap <- ProjectUMAP(
query = Embeddings(object = query),
query.dims = query.dims,
reference = Embeddings(object = reference),
reference.dims = reference.dims,
k.param = k.param,
nn.method = nn.method,
n.trees = 50,
annoy.metric = annoy.metric,
l2.norm = l2.norm,
cache.index = cache.index,
index = index,
neighbor.name = neighbor.name,
reduction.model = reduction.model,
...
)
return(proj.umap)
}
#' @param reference Reference dataset
#' @param query.reduction Name of reduction to use from the query for neighbor
#' finding
#' @param reference.reduction Name of reduction to use from the reference for
#' neighbor finding
#' @param neighbor.name Name to store neighbor information in the query
#' @param reduction.name Name of projected UMAP to store in the query
#' @param reduction.key Value for the projected UMAP key
#' @rdname ProjectUMAP
#' @concept dimensional_reduction
#' @export
#' @method ProjectUMAP Seurat
#'
ProjectUMAP.Seurat <- function(
query,
query.reduction,
query.dims = NULL,
reference,
reference.reduction,
reference.dims = NULL,
k.param = 30,
nn.method = "annoy",
n.trees = 50,
annoy.metric = "cosine",
l2.norm = FALSE,
cache.index = TRUE,
index = NULL,
neighbor.name = "query_ref.nn",
reduction.model,
reduction.name = "ref.umap",
reduction.key = "refUMAP_",
...
) {
if (!query.reduction %in% Reductions(object = query)) {
stop("The query.reduction (", query.reduction, ") is not present in the ",
"provided query", call. = FALSE)
}
if (!reference.reduction %in% Reductions(object = reference)) {
stop("The reference.reduction (", reference.reduction, ") is not present in the ",
"provided reference.", call. = FALSE)
}
if (!reduction.model %in% Reductions(object = reference)) {
stop("The reduction.model (", reduction.model, ") is not present in the ",
"provided reference.", call. = FALSE)
}
proj.umap <- ProjectUMAP(
query = query[[query.reduction]],
query.dims = query.dims,
reference = reference[[reference.reduction]],
reference.dims = reference.dims,
k.param = k.param,
nn.method = nn.method,
n.trees = n.trees,
annoy.metric = annoy.metric,
l2.norm = l2.norm,
cache.index = cache.index,
index = index,
neighbor.name = neighbor.name,
reduction.model = reference[[reduction.model]],
reduction.key = reduction.key,
assay = DefaultAssay(query),
...
)
query[[reduction.name]] <- proj.umap$proj.umap
query[[neighbor.name]] <- proj.umap$query.neighbor
return(query)
}
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Methods for Seurat-defined generics
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#' @param standardize Standardize matrices - scales columns to have unit variance
#' and mean 0
#' @param num.cc Number of canonical vectors to calculate
#' @param seed.use Random seed to set. If NULL, does not set a seed
#' @param verbose Show progress messages
#'
#' @importFrom irlba irlba
#'
#' @rdname RunCCA
#' @concept dimensional_reduction
#' @export
#'
RunCCA.default <- function(
object1,
object2,
standardize = TRUE,
num.cc = 20,
seed.use = 42,
verbose = FALSE,
...
) {
if (!is.null(x = seed.use)) {
set.seed(seed = seed.use)
}
cells1 <- colnames(x = object1)
cells2 <- colnames(x = object2)
if (standardize) {
object1 <- Standardize(mat = object1, display_progress = FALSE)
object2 <- Standardize(mat = object2, display_progress = FALSE)
}
mat3 <- crossprod(x = object1, y = object2)
cca.svd <- irlba(A = mat3, nv = num.cc)
cca.data <- rbind(cca.svd$u, cca.svd$v)
colnames(x = cca.data) <- paste0("CC", 1:num.cc)
rownames(cca.data) <- c(cells1, cells2)
cca.data <- apply(
X = cca.data,
MARGIN = 2,
FUN = function(x) {
if (sign(x[1]) == -1) {
x <- x * -1
}
return(x)
}
)
return(list(ccv = cca.data, d = cca.svd$d))
}
#' @param assay1,assay2 Assays to pull from in the first and second objects, respectively
#' @param features Set of genes to use in CCA. Default is the union of both
#' the variable features sets present in both objects.
#' @param renormalize Renormalize raw data after merging the objects. If FALSE,
#' merge the data matrices also.
#' @param rescale Rescale the datasets prior to CCA. If FALSE, uses existing data in the scale data slots.
#' @param compute.gene.loadings Also compute the gene loadings. NOTE - this will
#' scale every gene in the dataset which may impose a high memory cost.
#' @param add.cell.id1,add.cell.id2 Add ...
#' @param ... Extra parameters (passed onto MergeSeurat in case with two objects
#' passed, passed onto ScaleData in case with single object and rescale.groups
#' set to TRUE)
#'
#' @rdname RunCCA
#' @concept dimensional_reduction
#' @export
#' @method RunCCA Seurat
#'
RunCCA.Seurat <- function(
object1,
object2,
assay1 = NULL,
assay2 = NULL,
num.cc = 20,
features = NULL,
renormalize = FALSE,
rescale = FALSE,
compute.gene.loadings = TRUE,
add.cell.id1 = NULL,
add.cell.id2 = NULL,
verbose = TRUE,
...
) {
assay1 <- assay1 %||% DefaultAssay(object = object1)
assay2 <- assay2 %||% DefaultAssay(object = object2)
if (assay1 != assay2) {
warning("Running CCA on different assays")
}
if (is.null(x = features)) {
if (length(x = VariableFeatures(object = object1, assay = assay1)) == 0) {
stop(paste0("VariableFeatures not computed for the ", assay1, " assay in object1"))
}
if (length(x = VariableFeatures(object = object2, assay = assay2)) == 0) {
stop(paste0("VariableFeatures not computed for the ", assay2, " assay in object2"))
}
features <- union(x = VariableFeatures(object = object1), y = VariableFeatures(object = object2))
if (length(x = features) == 0) {
stop("Zero features in the union of the VariableFeature sets ")
}
}
nfeatures <- length(x = features)
if (!(rescale)) {
data.use1 <- GetAssayData(object = object1, assay = assay1, slot = "scale.data")
data.use2 <- GetAssayData(object = object2, assay = assay2, slot = "scale.data")
features <- CheckFeatures(data.use = data.use1, features = features, object.name = "object1", verbose = FALSE)
features <- CheckFeatures(data.use = data.use2, features = features, object.name = "object2", verbose = FALSE)
data1 <- data.use1[features, ]
data2 <- data.use2[features, ]
}
if (rescale) {
data.use1 <- GetAssayData(object = object1, assay = assay1, slot = "data")
data.use2 <- GetAssayData(object = object2, assay = assay2, slot = "data")
features <- CheckFeatures(data.use = data.use1, features = features, object.name = "object1", verbose = FALSE)
features <- CheckFeatures(data.use = data.use2, features = features, object.name = "object2", verbose = FALSE)
data1 <- data.use1[features,]
data2 <- data.use2[features,]
if (verbose) message("Rescaling groups")
data1 <- FastRowScale(as.matrix(data1))
dimnames(data1) <- list(features, colnames(x = object1))
data2 <- FastRowScale(as.matrix(data2))
dimnames(data2) <- list(features, colnames(x = object2))
}
if (length(x = features) / nfeatures < 0.1 & verbose) {
warning("More than 10% of provided features filtered out. Please check that the given features are present in the scale.data slot for both the assays provided here and that they have non-zero variance.")
}
if (length(x = features) < 50) {
warning("Fewer than 50 features used as input for CCA.")
}
if (verbose) {
message("Running CCA")
}
cca.results <- RunCCA(
object1 = data1,
object2 = data2,
standardize = TRUE,
num.cc = num.cc,
verbose = verbose,
)
if (verbose) {
message("Merging objects")
}
combined.object <- merge(
x = object1,
y = object2,
merge.data = TRUE,
...
)
rownames(x = cca.results$ccv) <- Cells(x = combined.object)
colnames(x = data1) <- Cells(x = combined.object)[1:ncol(x = data1)]
colnames(x = data2) <- Cells(x = combined.object)[(ncol(x = data1) + 1):length(x = Cells(x = combined.object))]
combined.object[['cca']] <- CreateDimReducObject(
embeddings = cca.results$ccv[colnames(combined.object), ],
assay = assay1,
key = "CC_"
)
combined.object[['cca']]@assay.used <- DefaultAssay(combined.object)
if (ncol(combined.object) != (ncol(object1) + ncol(object2))) {
warning("Some cells removed after object merge due to minimum feature count cutoff")
}
combined.scale <- cbind(data1,data2)
combined.object <- SetAssayData(object = combined.object,new.data = combined.scale, slot = "scale.data")
if (renormalize) {
combined.object <- NormalizeData(
object = combined.object,
assay = assay1,
normalization.method = object1[[paste0("NormalizeData.", assay1)]]$normalization.method,
scale.factor = object1[[paste0("NormalizeData.", assay1)]]$scale.factor
)
}
if (compute.gene.loadings) {
combined.object <- ProjectDim(
object = combined.object,
reduction = "cca",
verbose = FALSE,
overwrite = TRUE)
}
return(combined.object)
}
#' @param assay Name of Assay ICA is being run on
#' @param nics Number of ICs to compute
#' @param rev.ica By default, computes the dimensional reduction on the cell x
#' feature matrix. Setting to true will compute it on the transpose (feature x cell
#' matrix).
#' @param ica.function ICA function from ica package to run (options: icafast,
#' icaimax, icajade)
#' @param verbose Print the top genes associated with high/low loadings for
#' the ICs
#' @param ndims.print ICs to print genes for
#' @param nfeatures.print Number of genes to print for each IC
#' @param reduction.key dimensional reduction key, specifies the string before
#' the number for the dimension names.
#' @param seed.use Set a random seed. Setting NULL will not set a seed.
#' @param \dots Additional arguments to be passed to fastica
#'
#' @importFrom ica icafast icaimax icajade
#'
#' @rdname RunICA
#' @concept dimensional_reduction
#' @export
#' @method RunICA default
#'
RunICA.default <- function(
object,
assay = NULL,
nics = 50,
rev.ica = FALSE,
ica.function = "icafast",
verbose = TRUE,
ndims.print = 1:5,
nfeatures.print = 30,
reduction.name = "ica",
reduction.key = "ica_",
seed.use = 42,
...
) {
CheckDots(..., fxns = ica.function)
if (!is.null(x = seed.use)) {
set.seed(seed = seed.use)
}
nics <- min(nics, ncol(x = object))
ica.fxn <- eval(expr = parse(text = ica.function))
if (rev.ica) {
ica.results <- ica.fxn(object, nc = nics,...)
cell.embeddings <- ica.results$M
} else {
ica.results <- ica.fxn(t(x = object), nc = nics,...)
cell.embeddings <- ica.results$S
}
feature.loadings <- (as.matrix(x = object ) %*% as.matrix(x = cell.embeddings))
colnames(x = feature.loadings) <- paste0(reduction.key, 1:ncol(x = feature.loadings))
colnames(x = cell.embeddings) <- paste0(reduction.key, 1:ncol(x = cell.embeddings))
reduction.data <- CreateDimReducObject(
embeddings = cell.embeddings,
loadings = feature.loadings,
assay = assay,
key = reduction.key
)
if (verbose) {
print(x = reduction.data, dims = ndims.print, nfeatures = nfeatures.print)
}
return(reduction.data)
}
#' @param features Features to compute ICA on
#'
#' @rdname RunICA
#' @concept dimensional_reduction
#' @export
#' @method RunICA Assay
#'
RunICA.Assay <- function(
object,
assay = NULL,
features = NULL,
nics = 50,
rev.ica = FALSE,
ica.function = "icafast",
verbose = TRUE,
ndims.print = 1:5,
nfeatures.print = 30,
reduction.name = "ica",
reduction.key = "ica_",
seed.use = 42,
...
) {
data.use <- PrepDR(
object = object,
features = features,
verbose = verbose
)
reduction.data <- RunICA(
object = data.use,
assay = assay,
nics = nics,
rev.ica = rev.ica,
ica.function = ica.function,
verbose = verbose,
ndims.print = ndims.print,
nfeatures.print = nfeatures.print,
reduction.key = reduction.key,
seed.use = seed.use,
...
)
return(reduction.data)
}
#' @param reduction.name dimensional reduction name
#'
#' @rdname RunICA
#' @concept dimensional_reduction
#' @method RunICA Seurat
#' @export
#'
RunICA.Seurat <- function(
object,
assay = NULL,
features = NULL,
nics = 50,
rev.ica = FALSE,
ica.function = "icafast",
verbose = TRUE,
ndims.print = 1:5,
nfeatures.print = 30,
reduction.name = "ica",
reduction.key = "IC_",
seed.use = 42,
...
) {
assay <- assay %||% DefaultAssay(object = object)
assay.data <- GetAssay(object = object, assay = assay)
reduction.data <- RunICA(
object = assay.data,
assay = assay,
features = features,
nics = nics,
rev.ica = rev.ica,
ica.function = ica.function,
verbose = verbose,
ndims.print = ndims.print,
nfeatures.print = nfeatures.print,
reduction.key = reduction.key,
seed.use = seed.use,
...
)
object[[reduction.name]] <- reduction.data
object <- LogSeuratCommand(object = object)
return(object)
}
#' @param assay Name of Assay PCA is being run on
#' @param npcs Total Number of PCs to compute and store (50 by default)
#' @param rev.pca By default computes the PCA on the cell x gene matrix. Setting
#' to true will compute it on gene x cell matrix.
#' @param weight.by.var Weight the cell embeddings by the variance of each PC
#' (weights the gene loadings if rev.pca is TRUE)
#' @param verbose Print the top genes associated with high/low loadings for
#' the PCs
#' @param ndims.print PCs to print genes for
#' @param nfeatures.print Number of genes to print for each PC
#' @param reduction.key dimensional reduction key, specifies the string before
#' the number for the dimension names. PC by default
#' @param seed.use Set a random seed. By default, sets the seed to 42. Setting
#' NULL will not set a seed.
#' @param approx Use truncated singular value decomposition to approximate PCA
#'
#' @importFrom irlba irlba
#' @importFrom stats prcomp
#' @importFrom utils capture.output
#'
#' @rdname RunPCA
#' @concept dimensional_reduction
#' @export
#'
RunPCA.default <- function(
object,
assay = NULL,
npcs = 50,
rev.pca = FALSE,
weight.by.var = TRUE,
verbose = TRUE,
ndims.print = 1:5,
nfeatures.print = 30,
reduction.key = "PC_",
seed.use = 42,
approx = TRUE,
...
) {
if (!is.null(x = seed.use)) {
set.seed(seed = seed.use)
}
if (rev.pca) {
npcs <- min(npcs, ncol(x = object) - 1)
pca.results <- irlba(A = object, nv = npcs, ...)
total.variance <- sum(RowVar(x = t(x = object)))
sdev <- pca.results$d/sqrt(max(1, nrow(x = object) - 1))
if (weight.by.var) {
feature.loadings <- pca.results$u %*% diag(pca.results$d)
} else{
feature.loadings <- pca.results$u
}
cell.embeddings <- pca.results$v
}
else {
total.variance <- sum(RowVar(x = object))
if (approx) {
npcs <- min(npcs, nrow(x = object) - 1)
pca.results <- irlba(A = t(x = object), nv = npcs, ...)
feature.loadings <- pca.results$v
sdev <- pca.results$d/sqrt(max(1, ncol(object) - 1))
if (weight.by.var) {
cell.embeddings <- pca.results$u %*% diag(pca.results$d)
} else {
cell.embeddings <- pca.results$u
}
} else {
npcs <- min(npcs, nrow(x = object))
pca.results <- prcomp(x = t(object), rank. = npcs, ...)
feature.loadings <- pca.results$rotation
sdev <- pca.results$sdev
if (weight.by.var) {
cell.embeddings <- pca.results$x
} else {
cell.embeddings <- pca.results$x / (pca.results$sdev[1:npcs] * sqrt(x = ncol(x = object) - 1))
}
}
}
rownames(x = feature.loadings) <- rownames(x = object)
colnames(x = feature.loadings) <- paste0(reduction.key, 1:npcs)
rownames(x = cell.embeddings) <- colnames(x = object)
colnames(x = cell.embeddings) <- colnames(x = feature.loadings)
reduction.data <- CreateDimReducObject(
embeddings = cell.embeddings,
loadings = feature.loadings,
assay = assay,
stdev = sdev,
key = reduction.key,
misc = list(total.variance = total.variance)
)
if (verbose) {
msg <- capture.output(print(
x = reduction.data,
dims = ndims.print,
nfeatures = nfeatures.print
))
message(paste(msg, collapse = '\n'))
}
return(reduction.data)
}
#' @param features Features to compute PCA on. If features=NULL, PCA will be run
#' using the variable features for the Assay. Note that the features must be present
#' in the scaled data. Any requested features that are not scaled or have 0 variance
#' will be dropped, and the PCA will be run using the remaining features.
#'
#' @rdname RunPCA
#' @concept dimensional_reduction
#' @export
#' @method RunPCA Assay
#'
RunPCA.Assay <- function(
object,
assay = NULL,
features = NULL,
npcs = 50,
rev.pca = FALSE,
weight.by.var = TRUE,
verbose = TRUE,
ndims.print = 1:5,
nfeatures.print = 30,
reduction.key = "PC_",
seed.use = 42,
...
) {
data.use <- PrepDR(
object = object,
features = features,
verbose = verbose
)
reduction.data <- RunPCA(
object = data.use,
assay = assay,
npcs = npcs,
rev.pca = rev.pca,
weight.by.var = weight.by.var,
verbose = verbose,
ndims.print = ndims.print,
nfeatures.print = nfeatures.print,
reduction.key = reduction.key,
seed.use = seed.use,
...
)
return(reduction.data)
}
#' @param reduction.name dimensional reduction name, pca by default
#'
#' @rdname RunPCA
#' @concept dimensional_reduction
#' @export
#' @method RunPCA Seurat
#'
RunPCA.Seurat <- function(
object,
assay = NULL,
features = NULL,
npcs = 50,
rev.pca = FALSE,
weight.by.var = TRUE,
verbose = TRUE,
ndims.print = 1:5,
nfeatures.print = 30,
reduction.name = "pca",
reduction.key = "PC_",
seed.use = 42,
...
) {
assay <- assay %||% DefaultAssay(object = object)
assay.data <- GetAssay(object = object, assay = assay)
reduction.data <- RunPCA(
object = assay.data,
assay = assay,
features = features,
npcs = npcs,
rev.pca = rev.pca,
weight.by.var = weight.by.var,
verbose = verbose,