forked from satijalab/seurat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdifferential_expression.R
2335 lines (2291 loc) · 73.1 KB
/
differential_expression.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
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
globalVariables(
names = c('myAUC', 'p_val', 'avg_logFC'),
package = 'Seurat',
add = TRUE
)
#' Gene expression markers for all identity classes
#'
#' Finds markers (differentially expressed genes) for each of the identity classes in a dataset
#'
#' @inheritParams FindMarkers
#' @param node A node to find markers for and all its children; requires
#' \code{\link{BuildClusterTree}} to have been run previously; replaces \code{FindAllMarkersNode}
#' @param return.thresh Only return markers that have a p-value < return.thresh, or a power > return.thresh (if the test is ROC)
#'
#' @return Matrix containing a ranked list of putative markers, and associated
#' statistics (p-values, ROC score, etc.)
#'
#' @importFrom stats setNames
#'
#' @export
#'
#' @aliases FindAllMarkersNode
#' @concept differential_expression
#'
#' @examples
#' data("pbmc_small")
#' # Find markers for all clusters
#' all.markers <- FindAllMarkers(object = pbmc_small)
#' head(x = all.markers)
#' \dontrun{
#' # Pass a value to node as a replacement for FindAllMarkersNode
#' pbmc_small <- BuildClusterTree(object = pbmc_small)
#' all.markers <- FindAllMarkers(object = pbmc_small, node = 4)
#' head(x = all.markers)
#' }
#'
FindAllMarkers <- function(
object,
assay = NULL,
features = NULL,
logfc.threshold = 0.25,
test.use = 'wilcox',
slot = 'data',
min.pct = 0.1,
min.diff.pct = -Inf,
node = NULL,
verbose = TRUE,
only.pos = FALSE,
max.cells.per.ident = Inf,
random.seed = 1,
latent.vars = NULL,
min.cells.feature = 3,
min.cells.group = 3,
mean.fxn = NULL,
fc.name = NULL,
base = 2,
return.thresh = 1e-2,
densify = FALSE,
...
) {
MapVals <- function(vec, from, to) {
vec2 <- setNames(object = to, nm = from)[as.character(x = vec)]
vec2[is.na(x = vec2)] <- vec[is.na(x = vec2)]
return(unname(obj = vec2))
}
if ((test.use == "roc") && (return.thresh == 1e-2)) {
return.thresh <- 0.7
}
if (is.null(x = node)) {
idents.all <- sort(x = unique(x = Idents(object = object)))
} else {
if (!PackageCheck('ape', error = FALSE)) {
stop(cluster.ape, call. = FALSE)
}
tree <- Tool(object = object, slot = 'BuildClusterTree')
if (is.null(x = tree)) {
stop("Please run 'BuildClusterTree' before finding markers on nodes")
}
descendants <- DFT(tree = tree, node = node, include.children = TRUE)
all.children <- sort(x = tree$edge[, 2][!tree$edge[, 2] %in% tree$edge[, 1]])
descendants <- MapVals(
vec = descendants,
from = all.children,
to = tree$tip.label
)
drop.children <- setdiff(x = tree$tip.label, y = descendants)
keep.children <- setdiff(x = tree$tip.label, y = drop.children)
orig.nodes <- c(
node,
as.numeric(x = setdiff(x = descendants, y = keep.children))
)
tree <- ape::drop.tip(phy = tree, tip = drop.children)
new.nodes <- unique(x = tree$edge[, 1, drop = TRUE])
idents.all <- (tree$Nnode + 2):max(tree$edge)
}
genes.de <- list()
messages <- list()
for (i in 1:length(x = idents.all)) {
if (verbose) {
message("Calculating cluster ", idents.all[i])
}
genes.de[[i]] <- tryCatch(
expr = {
FindMarkers(
object = object,
assay = assay,
ident.1 = if (is.null(x = node)) {
idents.all[i]
} else {
tree
},
ident.2 = if (is.null(x = node)) {
NULL
} else {
idents.all[i]
},
features = features,
logfc.threshold = logfc.threshold,
test.use = test.use,
slot = slot,
min.pct = min.pct,
min.diff.pct = min.diff.pct,
verbose = verbose,
only.pos = only.pos,
max.cells.per.ident = max.cells.per.ident,
random.seed = random.seed,
latent.vars = latent.vars,
min.cells.feature = min.cells.feature,
min.cells.group = min.cells.group,
mean.fxn = mean.fxn,
fc.name = fc.name,
base = base,
densify = densify,
...
)
},
error = function(cond) {
return(cond$message)
}
)
if (is.character(x = genes.de[[i]])) {
messages[[i]] <- genes.de[[i]]
genes.de[[i]] <- NULL
}
}
gde.all <- data.frame()
for (i in 1:length(x = idents.all)) {
if (is.null(x = unlist(x = genes.de[i]))) {
next
}
gde <- genes.de[[i]]
if (nrow(x = gde) > 0) {
if (test.use == "roc") {
gde <- subset(
x = gde,
subset = (myAUC > return.thresh | myAUC < (1 - return.thresh))
)
} else if (is.null(x = node) || test.use %in% c('bimod', 't')) {
gde <- gde[order(gde$p_val, -gde[, 2]), ]
gde <- subset(x = gde, subset = p_val < return.thresh)
}
if (nrow(x = gde) > 0) {
gde$cluster <- idents.all[i]
gde$gene <- rownames(x = gde)
}
if (nrow(x = gde) > 0) {
gde.all <- rbind(gde.all, gde)
}
}
}
if ((only.pos) && nrow(x = gde.all) > 0) {
return(subset(x = gde.all, subset = gde.all[, 2] > 0))
}
rownames(x = gde.all) <- make.unique(names = as.character(x = gde.all$gene))
if (nrow(x = gde.all) == 0) {
warning("No DE genes identified", call. = FALSE, immediate. = TRUE)
}
if (length(x = messages) > 0) {
warning("The following tests were not performed: ", call. = FALSE, immediate. = TRUE)
for (i in 1:length(x = messages)) {
if (!is.null(x = messages[[i]])) {
warning("When testing ", idents.all[i], " versus all:\n\t", messages[[i]], call. = FALSE, immediate. = TRUE)
}
}
}
if (!is.null(x = node)) {
gde.all$cluster <- MapVals(
vec = gde.all$cluster,
from = new.nodes,
to = orig.nodes
)
}
return(gde.all)
}
#' Finds markers that are conserved between the groups
#'
#' @inheritParams FindMarkers
#' @param ident.1 Identity class to define markers for
#' @param ident.2 A second identity class for comparison. If NULL (default) -
#' use all other cells for comparison.
#' @param grouping.var grouping variable
#' @param assay of assay to fetch data for (default is RNA)
#' @param meta.method method for combining p-values. Should be a function from
#' the metap package (NOTE: pass the function, not a string)
#' @param \dots parameters to pass to FindMarkers
#'
#' @return data.frame containing a ranked list of putative conserved markers, and
#' associated statistics (p-values within each group and a combined p-value
#' (such as Fishers combined p-value or others from the metap package),
#' percentage of cells expressing the marker, average differences). Name of group is appended to each
#' associated output column (e.g. CTRL_p_val). If only one group is tested in the grouping.var, max
#' and combined p-values are not returned.
#'
#' @export
#' @concept differential_expression
#'
#' @examples
#' \dontrun{
#' data("pbmc_small")
#' pbmc_small
#' # Create a simulated grouping variable
#' pbmc_small[['groups']] <- sample(x = c('g1', 'g2'), size = ncol(x = pbmc_small), replace = TRUE)
#' FindConservedMarkers(pbmc_small, ident.1 = 0, ident.2 = 1, grouping.var = "groups")
#' }
#'
FindConservedMarkers <- function(
object,
ident.1,
ident.2 = NULL,
grouping.var,
assay = 'RNA',
slot = 'data',
min.cells.group = 3,
meta.method = metap::minimump,
verbose = TRUE,
...
) {
metap.installed <- PackageCheck("metap", error = FALSE)
if (!metap.installed[1]) {
stop(
"Please install the metap package to use FindConservedMarkers.",
"\nThis can be accomplished with the following commands: ",
"\n----------------------------------------",
"\ninstall.packages('BiocManager')",
"\nBiocManager::install('multtest')",
"\ninstall.packages('metap')",
"\n----------------------------------------",
call. = FALSE
)
}
if (!is.function(x = meta.method)) {
stop("meta.method should be a function from the metap package. Please see https://cran.r-project.org/web/packages/metap/metap.pdf for a detailed description of the available functions.")
}
object.var <- FetchData(object = object, vars = grouping.var)
object <- SetIdent(
object = object,
cells = colnames(x = object),
value = paste(Idents(object = object), object.var[, 1], sep = "_")
)
levels.split <- names(x = sort(x = table(object.var[, 1])))
num.groups <- length(levels.split)
cells <- list()
for (i in 1:num.groups) {
cells[[i]] <- rownames(
x = object.var[object.var[, 1] == levels.split[i], , drop = FALSE]
)
}
marker.test <- list()
# do marker tests
ident.2.save <- ident.2
for (i in 1:num.groups) {
level.use <- levels.split[i]
ident.use.1 <- paste(ident.1, level.use, sep = "_")
ident.use.1.exists <- ident.use.1 %in% Idents(object = object)
if (!all(ident.use.1.exists)) {
bad.ids <- ident.1[!ident.use.1.exists]
warning(
"Identity: ",
paste(bad.ids, collapse = ", "),
" not present in group ",
level.use,
". Skipping ",
level.use,
call. = FALSE,
immediate. = TRUE
)
next
}
ident.2 <- ident.2.save
cells.1 <- WhichCells(object = object, idents = ident.use.1)
if (length(cells.1) < min.cells.group) {
warning(
level.use,
" has fewer than ",
min.cells.group,
" cells in Identity: ",
paste(ident.1, collapse = ", "),
". Skipping ",
level.use,
call. = FALSE,
immediate. = TRUE
)
next
}
if (is.null(x = ident.2)) {
cells.2 <- setdiff(x = cells[[i]], y = cells.1)
ident.use.2 <- names(x = which(x = table(Idents(object = object)[cells.2]) > 0))
ident.2 <- gsub(pattern = paste0("_", level.use), replacement = "", x = ident.use.2)
if (length(x = ident.use.2) == 0) {
stop(paste("Only one identity class present:", ident.1))
}
} else {
ident.use.2 <- paste(ident.2, level.use, sep = "_")
}
if (verbose) {
message(
"Testing group ",
level.use,
": (",
paste(ident.1, collapse = ", "),
") vs (",
paste(ident.2, collapse = ", "),
")"
)
}
ident.use.2.exists <- ident.use.2 %in% Idents(object = object)
if (!all(ident.use.2.exists)) {
bad.ids <- ident.2[!ident.use.2.exists]
warning(
"Identity: ",
paste(bad.ids, collapse = ", "),
" not present in group ",
level.use,
". Skipping ",
level.use,
call. = FALSE,
immediate. = TRUE
)
next
}
marker.test[[i]] <- FindMarkers(
object = object,
assay = assay,
slot = slot,
ident.1 = ident.use.1,
ident.2 = ident.use.2,
verbose = verbose,
...
)
names(x = marker.test)[i] <- levels.split[i]
}
marker.test <- Filter(f = Negate(f = is.null), x = marker.test)
genes.conserved <- Reduce(
f = intersect,
x = lapply(
X = marker.test,
FUN = function(x) {
return(rownames(x = x))
}
)
)
markers.conserved <- list()
for (i in 1:length(x = marker.test)) {
markers.conserved[[i]] <- marker.test[[i]][genes.conserved, ]
colnames(x = markers.conserved[[i]]) <- paste(
names(x = marker.test)[i],
colnames(x = markers.conserved[[i]]),
sep = "_"
)
}
markers.combined <- Reduce(cbind, markers.conserved)
pval.codes <- colnames(x = markers.combined)[grepl(pattern = "*_p_val$", x = colnames(x = markers.combined))]
if (length(x = pval.codes) > 1) {
markers.combined$max_pval <- apply(
X = markers.combined[, pval.codes, drop = FALSE],
MARGIN = 1,
FUN = max
)
combined.pval <- data.frame(cp = apply(
X = markers.combined[, pval.codes, drop = FALSE],
MARGIN = 1,
FUN = function(x) {
return(meta.method(x)$p)
}
))
meta.method.name <- as.character(x = formals()$meta.method)
if (length(x = meta.method.name) == 3) {
meta.method.name <- meta.method.name[3]
}
colnames(x = combined.pval) <- paste0(meta.method.name, "_p_val")
markers.combined <- cbind(markers.combined, combined.pval)
markers.combined <- markers.combined[order(markers.combined[, paste0(meta.method.name, "_p_val")]), ]
} else {
warning("Only a single group was tested", call. = FALSE, immediate. = TRUE)
}
return(markers.combined)
}
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Methods for Seurat-defined generics
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#' @param cells.1 Vector of cell names belonging to group 1
#' @param cells.2 Vector of cell names belonging to group 2
#' @param counts Count matrix if using scale.data for DE tests. This is used for
#' computing pct.1 and pct.2 and for filtering features based on fraction
#' expressing
#' @param features Genes to test. Default is to use all genes
#' @param logfc.threshold Limit testing to genes which show, on average, at least
#' X-fold difference (log-scale) between the two groups of cells. Default is 0.25
#' Increasing logfc.threshold speeds up the function, but can miss weaker signals.
#' @param test.use Denotes which test to use. Available options are:
#' \itemize{
#' \item{"wilcox"} : Identifies differentially expressed genes between two
#' groups of cells using a Wilcoxon Rank Sum test (default)
#' \item{"bimod"} : Likelihood-ratio test for single cell gene expression,
#' (McDavid et al., Bioinformatics, 2013)
#' \item{"roc"} : Identifies 'markers' of gene expression using ROC analysis.
#' For each gene, evaluates (using AUC) a classifier built on that gene alone,
#' to classify between two groups of cells. An AUC value of 1 means that
#' expression values for this gene alone can perfectly classify the two
#' groupings (i.e. Each of the cells in cells.1 exhibit a higher level than
#' each of the cells in cells.2). An AUC value of 0 also means there is perfect
#' classification, but in the other direction. A value of 0.5 implies that
#' the gene has no predictive power to classify the two groups. Returns a
#' 'predictive power' (abs(AUC-0.5) * 2) ranked matrix of putative differentially
#' expressed genes.
#' \item{"t"} : Identify differentially expressed genes between two groups of
#' cells using the Student's t-test.
#' \item{"negbinom"} : Identifies differentially expressed genes between two
#' groups of cells using a negative binomial generalized linear model.
#' Use only for UMI-based datasets
#' \item{"poisson"} : Identifies differentially expressed genes between two
#' groups of cells using a poisson generalized linear model.
#' Use only for UMI-based datasets
#' \item{"LR"} : Uses a logistic regression framework to determine differentially
#' expressed genes. Constructs a logistic regression model predicting group
#' membership based on each feature individually and compares this to a null
#' model with a likelihood ratio test.
#' \item{"MAST"} : Identifies differentially expressed genes between two groups
#' of cells using a hurdle model tailored to scRNA-seq data. Utilizes the MAST
#' package to run the DE testing.
#' \item{"DESeq2"} : Identifies differentially expressed genes between two groups
#' of cells based on a model using DESeq2 which uses a negative binomial
#' distribution (Love et al, Genome Biology, 2014).This test does not support
#' pre-filtering of genes based on average difference (or percent detection rate)
#' between cell groups. However, genes may be pre-filtered based on their
#' minimum detection rate (min.pct) across both cell groups. To use this method,
#' please install DESeq2, using the instructions at
#' https://bioconductor.org/packages/release/bioc/html/DESeq2.html
#' }
#' @param min.pct only test genes that are detected in a minimum fraction of
#' min.pct cells in either of the two populations. Meant to speed up the function
#' by not testing genes that are very infrequently expressed. Default is 0.1
#' @param min.diff.pct only test genes that show a minimum difference in the
#' fraction of detection between the two groups. Set to -Inf by default
#' @param only.pos Only return positive markers (FALSE by default)
#' @param verbose Print a progress bar once expression testing begins
#' @param max.cells.per.ident Down sample each identity class to a max number.
#' Default is no downsampling. Not activated by default (set to Inf)
#' @param random.seed Random seed for downsampling
#' @param latent.vars Variables to test, used only when \code{test.use} is one of
#' 'LR', 'negbinom', 'poisson', or 'MAST'
#' @param min.cells.feature Minimum number of cells expressing the feature in at least one
#' of the two groups, currently only used for poisson and negative binomial tests
#' @param min.cells.group Minimum number of cells in one of the groups
#' @param pseudocount.use Pseudocount to add to averaged expression values when
#' calculating logFC. 1 by default.
#' @param fc.results data.frame from FoldChange
#' @param densify Convert the sparse matrix to a dense form before running the DE test. This can provide speedups but might require higher memory; default is FALSE
#'
#'
#' @importFrom Matrix rowMeans
#' @importFrom stats p.adjust
#'
#' @rdname FindMarkers
#' @concept differential_expression
#' @export
#' @method FindMarkers default
#'
FindMarkers.default <- function(
object,
slot = "data",
counts = numeric(),
cells.1 = NULL,
cells.2 = NULL,
features = NULL,
logfc.threshold = 0.25,
test.use = 'wilcox',
min.pct = 0.1,
min.diff.pct = -Inf,
verbose = TRUE,
only.pos = FALSE,
max.cells.per.ident = Inf,
random.seed = 1,
latent.vars = NULL,
min.cells.feature = 3,
min.cells.group = 3,
pseudocount.use = 1,
fc.results = NULL,
densify = FALSE,
...
) {
pseudocount.use <- pseudocount.use %||% 1
ValidateCellGroups(
object = object,
cells.1 = cells.1,
cells.2 = cells.2,
min.cells.group = min.cells.group
)
features <- features %||% rownames(x = object)
# reset parameters so no feature filtering is performed
if (test.use %in% DEmethods_noprefilter()) {
features <- rownames(x = object)
min.diff.pct <- -Inf
logfc.threshold <- 0
}
data <- switch(
EXPR = slot,
'scale.data' = counts,
object
)
# feature selection (based on percentages)
alpha.min <- pmax(fc.results$pct.1, fc.results$pct.2)
names(x = alpha.min) <- rownames(x = fc.results)
features <- names(x = which(x = alpha.min >= min.pct))
if (length(x = features) == 0) {
warning("No features pass min.pct threshold; returning empty data.frame")
return(fc.results[features, ])
}
alpha.diff <- alpha.min - pmin(fc.results$pct.1, fc.results$pct.2)
features <- names(
x = which(x = alpha.min >= min.pct & alpha.diff >= min.diff.pct)
)
if (length(x = features) == 0) {
warning("No features pass min.diff.pct threshold; returning empty data.frame")
return(fc.results[features, ])
}
# feature selection (based on logFC)
if (slot != "scale.data") {
total.diff <- fc.results[, 1] #first column is logFC
names(total.diff) <- rownames(fc.results)
features.diff <- if (only.pos) {
names(x = which(x = total.diff >= logfc.threshold))
} else {
names(x = which(x = abs(x = total.diff) >= logfc.threshold))
}
features <- intersect(x = features, y = features.diff)
if (length(x = features) == 0) {
warning("No features pass logfc.threshold threshold; returning empty data.frame")
return(fc.results[features, ])
}
}
# subsample cell groups if they are too large
if (max.cells.per.ident < Inf) {
set.seed(seed = random.seed)
if (length(x = cells.1) > max.cells.per.ident) {
cells.1 <- sample(x = cells.1, size = max.cells.per.ident)
}
if (length(x = cells.2) > max.cells.per.ident) {
cells.2 <- sample(x = cells.2, size = max.cells.per.ident)
}
if (!is.null(x = latent.vars)) {
latent.vars <- latent.vars[c(cells.1, cells.2), , drop = FALSE]
}
}
de.results <- PerformDE(
object = object,
cells.1 = cells.1,
cells.2 = cells.2,
features = features,
test.use = test.use,
verbose = verbose,
min.cells.feature = min.cells.feature,
latent.vars = latent.vars,
densify = densify,
...
)
de.results <- cbind(de.results, fc.results[rownames(x = de.results), , drop = FALSE])
if (only.pos) {
de.results <- de.results[de.results[, 2] > 0, , drop = FALSE]
}
if (test.use %in% DEmethods_nocorrect()) {
de.results <- de.results[order(-de.results$power, -de.results[, 1]), ]
} else {
de.results <- de.results[order(de.results$p_val, -de.results[, 1]), ]
de.results$p_val_adj = p.adjust(
p = de.results$p_val,
method = "bonferroni",
n = nrow(x = object)
)
}
return(de.results)
}
#' @param norm.method Normalization method for fold change calculation when
#' \code{slot} is \dQuote{\code{data}}
#'
#' @rdname FindMarkers
#' @concept differential_expression
#' @export
#' @method FindMarkers Assay
#'
FindMarkers.Assay <- function(
object,
slot = "data",
cells.1 = NULL,
cells.2 = NULL,
features = NULL,
logfc.threshold = 0.25,
test.use = 'wilcox',
min.pct = 0.1,
min.diff.pct = -Inf,
verbose = TRUE,
only.pos = FALSE,
max.cells.per.ident = Inf,
random.seed = 1,
latent.vars = NULL,
min.cells.feature = 3,
min.cells.group = 3,
pseudocount.use = 1,
mean.fxn = NULL,
fc.name = NULL,
base = 2,
densify = FALSE,
norm.method = NULL,
...
) {
pseudocount.use <- pseudocount.use %||% 1
data.slot <- ifelse(
test = test.use %in% DEmethods_counts(),
yes = 'counts',
no = slot
)
data.use <- GetAssayData(object = object, slot = data.slot)
counts <- switch(
EXPR = data.slot,
'scale.data' = GetAssayData(object = object, slot = "counts"),
numeric()
)
fc.results <- FoldChange(
object = object,
slot = data.slot,
cells.1 = cells.1,
cells.2 = cells.2,
features = features,
pseudocount.use = pseudocount.use,
mean.fxn = mean.fxn,
fc.name = fc.name,
base = base,
norm.method = norm.method
)
de.results <- FindMarkers(
object = data.use,
slot = data.slot,
counts = counts,
cells.1 = cells.1,
cells.2 = cells.2,
features = features,
logfc.threshold = logfc.threshold,
test.use = test.use,
min.pct = min.pct,
min.diff.pct = min.diff.pct,
verbose = verbose,
only.pos = only.pos,
max.cells.per.ident = max.cells.per.ident,
random.seed = random.seed,
latent.vars = latent.vars,
min.cells.feature = min.cells.feature,
min.cells.group = min.cells.group,
pseudocount.use = pseudocount.use,
fc.results = fc.results,
densify = densify,
...
)
return(de.results)
}
#' @param recorrect_umi Recalculate corrected UMI counts using minimum of the median UMIs when performing DE using multiple SCT objects; default is TRUE
#'
#' @rdname FindMarkers
#' @concept differential_expression
#' @export
#' @method FindMarkers SCTAssay
#'
FindMarkers.SCTAssay <- function(
object,
slot = "data",
cells.1 = NULL,
cells.2 = NULL,
features = NULL,
logfc.threshold = 0.25,
test.use = 'wilcox',
min.pct = 0.1,
min.diff.pct = -Inf,
verbose = TRUE,
only.pos = FALSE,
max.cells.per.ident = Inf,
random.seed = 1,
latent.vars = NULL,
min.cells.feature = 3,
min.cells.group = 3,
pseudocount.use = 1,
mean.fxn = NULL,
fc.name = NULL,
base = 2,
densify = FALSE,
recorrect_umi = TRUE,
...
) {
pseudocount.use <- pseudocount.use %||% 1
data.slot <- ifelse(
test = test.use %in% DEmethods_counts(),
yes = 'counts',
no = slot
)
if (recorrect_umi && length(x = levels(x = object)) > 1) {
cell_attributes <- SCTResults(object = object, slot = "cell.attributes")
observed_median_umis <- lapply(
X = cell_attributes,
FUN = function(x) median(x[, "umi"])
)
model.list <- slot(object = object, "SCTModel.list")
median_umi.status <- lapply(X = model.list,
FUN = function(x) { return(tryCatch(
expr = slot(object = x, name = 'median_umi'),
error = function(...) {return(NULL)})
)})
if (any(is.null(unlist(median_umi.status)))){
stop("SCT assay does not contain median UMI information.",
"Run `PrepSCTFindMarkers()` before running `FindMarkers()` or invoke `FindMarkers(recorrect_umi=FALSE)`.")
}
model_median_umis <- SCTResults(object = object, slot = "median_umi")
min_median_umi <- min(unlist(x = observed_median_umis))
if (any(unlist(model_median_umis) != min_median_umi)){
stop("Object contains multiple models with unequal library sizes. Run `PrepSCTFindMarkers()` before running `FindMarkers()`.")
}
}
data.use <- GetAssayData(object = object, slot = data.slot)
counts <- switch(
EXPR = data.slot,
'scale.data' = GetAssayData(object = object, slot = "counts"),
numeric()
)
if (is.null(x = mean.fxn)){
mean.fxn <- function(x) {
return(log(x = rowMeans(x = expm1(x = x)) + pseudocount.use, base = base))
}
}
fc.results <- FoldChange(
object = object,
slot = data.slot,
cells.1 = cells.1,
cells.2 = cells.2,
features = features,
pseudocount.use = pseudocount.use,
mean.fxn = mean.fxn,
fc.name = fc.name,
base = base
)
de.results <- FindMarkers(
object = data.use,
slot = data.slot,
counts = counts,
cells.1 = cells.1,
cells.2 = cells.2,
features = features,
logfc.threshold = logfc.threshold,
test.use = test.use,
min.pct = min.pct,
min.diff.pct = min.diff.pct,
verbose = verbose,
only.pos = only.pos,
max.cells.per.ident = max.cells.per.ident,
random.seed = random.seed,
latent.vars = latent.vars,
min.cells.feature = min.cells.feature,
min.cells.group = min.cells.group,
pseudocount.use = pseudocount.use,
fc.results = fc.results,
densify = densify,
...
)
return(de.results)
}
#' @importFrom Matrix rowMeans
#' @rdname FindMarkers
#' @concept differential_expression
#' @export
#' @method FindMarkers DimReduc
#'
FindMarkers.DimReduc <- function(
object,
cells.1 = NULL,
cells.2 = NULL,
features = NULL,
logfc.threshold = 0.25,
test.use = "wilcox",
min.pct = 0.1,
min.diff.pct = -Inf,
verbose = TRUE,
only.pos = FALSE,
max.cells.per.ident = Inf,
random.seed = 1,
latent.vars = NULL,
min.cells.feature = 3,
min.cells.group = 3,
pseudocount.use = 1,
mean.fxn = rowMeans,
fc.name = NULL,
densify = FALSE,
...
) {
pseudocount.use <- pseudocount.use %||% 1
if (test.use %in% DEmethods_counts()) {
stop("The following tests cannot be used for differential expression on a reduction as they assume a count model: ",
paste(DEmethods_counts(), collapse=", "))
}
data <- t(x = Embeddings(object = object))
ValidateCellGroups(
object = data,
cells.1 = cells.1,
cells.2 = cells.2,
min.cells.group = min.cells.group
)
features <- features %||% rownames(x = data)
# reset parameters so no feature filtering is performed
if (test.use %in% DEmethods_noprefilter()) {
features <- rownames(x = data)
min.diff.pct <- -Inf
logfc.threshold <- 0
}
fc.results <- FoldChange(
object = object,
cells.1 = cells.1,
cells.2 = cells.2,
features = features,
mean.fxn = mean.fxn,
fc.name = fc.name
)
# subsample cell groups if they are too large
if (max.cells.per.ident < Inf) {
set.seed(seed = random.seed)
if (length(x = cells.1) > max.cells.per.ident) {
cells.1 <- sample(x = cells.1, size = max.cells.per.ident)
}
if (length(x = cells.2) > max.cells.per.ident) {
cells.2 <- sample(x = cells.2, size = max.cells.per.ident)
}
if (!is.null(x = latent.vars)) {
latent.vars <- latent.vars[c(cells.1, cells.2), , drop = FALSE]
}
}
de.results <- PerformDE(
object = data,
cells.1 = cells.1,
cells.2 = cells.2,
features = features,
test.use = test.use,
verbose = verbose,
min.cells.feature = min.cells.feature,
latent.vars = latent.vars,
densify = densify,
...
)
de.results <- cbind(de.results, fc.results)
if (only.pos) {
de.results <- de.results[de.results$avg_diff > 0, , drop = FALSE]
}
if (test.use %in% DEmethods_nocorrect()) {
de.results <- de.results[order(-de.results$power, -de.results$avg_diff), ]
} else {
de.results <- de.results[order(de.results$p_val, -de.results$avg_diff), ]
de.results$p_val_adj = p.adjust(
p = de.results$p_val,
method = "bonferroni",
n = nrow(x = object)
)
}
return(de.results)
}
#' @param ident.1 Identity class to define markers for; pass an object of class
#' \code{phylo} or 'clustertree' to find markers for a node in a cluster tree;
#' passing 'clustertree' requires \code{\link{BuildClusterTree}} to have been run
#' @param ident.2 A second identity class for comparison; if \code{NULL},
#' use all other cells for comparison; if an object of class \code{phylo} or
#' 'clustertree' is passed to \code{ident.1}, must pass a node to find markers for
#' @param reduction Reduction to use in differential expression testing - will test for DE on cell embeddings
#' @param group.by Regroup cells into a different identity class prior to performing differential expression (see example)
#' @param subset.ident Subset a particular identity class prior to regrouping. Only relevant if group.by is set (see example)
#' @param assay Assay to use in differential expression testing
#' @param slot Slot to pull data from; note that if \code{test.use} is "negbinom", "poisson", or "DESeq2",
#' \code{slot} will be set to "counts"
#' @param mean.fxn Function to use for fold change or average difference calculation.
#' If NULL, the appropriate function will be chose according to the slot used
#' @param fc.name Name of the fold change, average difference, or custom function column
#' in the output data.frame. If NULL, the fold change column will be named
#' according to the logarithm base (eg, "avg_log2FC"), or if using the scale.data
#' slot "avg_diff".
#' @param base The base with respect to which logarithms are computed.
#'
#' @rdname FindMarkers
#' @concept differential_expression
#' @export
#' @method FindMarkers Seurat
#'
FindMarkers.Seurat <- function(
object,
ident.1 = NULL,
ident.2 = NULL,
group.by = NULL,
subset.ident = NULL,
assay = NULL,
slot = 'data',
reduction = NULL,
features = NULL,
logfc.threshold = 0.25,
test.use = "wilcox",
min.pct = 0.1,
min.diff.pct = -Inf,
verbose = TRUE,
only.pos = FALSE,
max.cells.per.ident = Inf,
random.seed = 1,
latent.vars = NULL,
min.cells.feature = 3,
min.cells.group = 3,
mean.fxn = NULL,
fc.name = NULL,
base = 2,
densify = FALSE,
...
) {
if (!is.null(x = group.by)) {
if (!is.null(x = subset.ident)) {
object <- subset(x = object, idents = subset.ident)
}
Idents(object = object) <- group.by
}
if (!is.null(x = assay) && !is.null(x = reduction)) {
stop("Please only specify either assay or reduction.")
}
if (length(x = ident.1) == 0) {
stop("At least 1 ident must be specified in `ident.1`")
}
# select which data to use
if (is.null(x = reduction)) {
assay <- assay %||% DefaultAssay(object = object)
data.use <- object[[assay]]
cellnames.use <- colnames(x = data.use)
} else {
data.use <- object[[reduction]]
cellnames.use <- rownames(x = data.use)
}
cells <- IdentsToCells(
object = object,
ident.1 = ident.1,
ident.2 = ident.2,
cellnames.use = cellnames.use
)
# fetch latent.vars
if (!is.null(x = latent.vars)) {
latent.vars <- FetchData(
object = object,
vars = latent.vars,
cells = c(cells$cells.1, cells$cells.2)
)
}
# check normalization method
norm.command <- paste0("NormalizeData.", assay)
norm.method <- if (norm.command %in% Command(object = object) && is.null(x = reduction)) {
Command(
object = object,
command = norm.command,
value = "normalization.method"
)
} else if (length(x = intersect(x = c("FindIntegrationAnchors", "FindTransferAnchors"), y = Command(object = object)))) {
command <- intersect(x = c("FindIntegrationAnchors", "FindTransferAnchors"), y = Command(object = object))[1]
Command(
object = object,
command = command,
value = "normalization.method"
)
} else {
NULL