forked from satijalab/seurat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdifferential_expression.R
1556 lines (1540 loc) · 52.5 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 seurat.R
NULL
globalVariables(names = 'avg_logFC', package = 'Seurat', add = TRUE)
#' Gene expression markers of identity classes
#'
#' Finds markers (differentially expressed genes) for identity classes
#'
#' @param object Seurat object
#' @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 genes.use 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"} : Wilcoxon rank sum test (default)
##' \item{"bimod"} : Likelihood-ratio test for single cell gene expression,
##' (McDavid et al., Bioinformatics, 2013)
##' \item{"roc"} : Standard AUC classifier
##' \item{"t"} : Student's t-test
##' \item{"tobit"} : Tobit-test for differential gene expression (Trapnell et
##' al., Nature Biotech, 2014)
##' \item{"poisson"} : Likelihood ratio test assuming an underlying poisson
##' distribution. Use only for UMI-based datasets
##' \item{"negbinom"} : Likelihood ratio test assuming an underlying negative
##' binomial distribution. Use only for UMI-based datasets
##' \item{"MAST} : GLM-framework that treates cellular detection rate as a
##' covariate (Finak et al, Genome Biology, 2015)
##' \item{"DESeq2} : DE based on a model using the negative binomial
##' distribution (Love et al, Genome Biology, 2014)
##' }
#' @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 print.bar Print a progress bar once expression testing begins (uses
#' pbapply to do this)
#' @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
#' 'negbinom', 'poisson', or 'MAST'
#' @param min.cells.gene Minimum number of cells expressing the gene 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 assay.type Type of assay to fetch data for (default is RNA)
#' @param \dots Additional parameters to pass to specific DE functions
#' @seealso \code{\link{MASTDETest}}, and \code{\link{DESeq2DETest}} for more information on these methods
#' @return Matrix containing a ranked list of putative markers, and associated
#' statistics (p-values, ROC score, etc.)
#' @details p-value adjustment is performed using bonferroni correction based on
#' the total number of genes in the dataset. Other correction methods are not
#' recommended, as Seurat pre-filters genes using the arguments above, reducing
#' the number of tests performed. Lastly, as Aaron Lun has pointed out, p-values
#' should be interpreted cautiously, as the genes used for clustering are the
#' same genes tested for differential expression.
#' @import pbapply
#' @importFrom lmtest lrtest
#'
#' @seealso \code{\link{NegBinomDETest}}
#'
#' @export
#'
#' @examples
#' markers <- FindMarkers(object = pbmc_small, ident.1 = 3)
#' head(markers)
#'
FindMarkers <- function(
object,
ident.1,
ident.2 = NULL,
genes.use = NULL,
logfc.threshold = 0.25,
test.use = "wilcox",
min.pct = 0.1,
min.diff.pct = -Inf,
print.bar = TRUE,
only.pos = FALSE,
max.cells.per.ident = Inf,
random.seed = 1,
latent.vars = NULL,
min.cells.gene = 3,
min.cells.group = 3,
pseudocount.use = 1,
assay.type = "RNA",
...
) {
data.use <- GetAssayData(object = object,assay.type = assay.type,slot = "data")
genes.use <- SetIfNull(x = genes.use, default = rownames(x = data.use))
methods.noprefiliter <- c("DESeq2", "zingeR")
if (test.use %in% methods.noprefiliter) {
genes.use <- rownames(x = data.use)
min.diff.pct <- -Inf
logfc.threshold <- 0
}
# in case the user passed in cells instead of identity classes
if (length(x = as.vector(x = ident.1) > 1) && any(as.character(x = ident.1) %in% [email protected])) {
cells.1 <- intersect(x = ident.1, y = [email protected])
} else {
cells.1 <- WhichCells(object = object, ident = ident.1)
}
# if NULL for ident.2, use all other cells
if (length(x = as.vector(x = ident.2) > 1) && any(as.character(x = ident.2) %in% [email protected])) {
cells.2 <- intersect(x = ident.2, y = [email protected])
} else {
if (is.null(x = ident.2)) {
# cells.2 <- [email protected]
cells.2 <- WhichCells(object = object,cells.use = setdiff([email protected],cells.1))
} else {
cells.2 <- WhichCells(object = object, ident = ident.2)
}
}
cells.2 <- setdiff(x = cells.2, y = cells.1)
# error checking
if (length(x = cells.1) == 0) {
message(paste("Cell group 1 is empty - no cells with identity class", ident.1))
return(NULL)
}
if (length(x = cells.2) == 0) {
message(paste("Cell group 2 is empty - no cells with identity class", ident.2))
return(NULL)
}
if (length(cells.1) < min.cells.group) {
stop(paste("Cell group 1 has fewer than", as.character(min.cells.group), "cells in identity class", ident.1))
}
if (length(cells.2) < min.cells.group) {
stop(paste("Cell group 2 has fewer than", as.character(min.cells.group), " cells in identity class", ident.2))
}
# gene selection (based on percent expressed)
thresh.min <- 0
data.temp1 <- round(
x = apply(
X = data.use[genes.use, cells.1, drop = F],
MARGIN = 1,
FUN = function(x) {
return(sum(x > thresh.min) / length(x = x))
# return(length(x = x[x>thresh.min]) / length(x = x))
}
),
digits = 3
)
data.temp2 <- round(
x = apply(
X = data.use[genes.use, cells.2, drop = F],
MARGIN = 1,
FUN = function(x) {
return(sum(x > thresh.min) / length(x = x))
# return(length(x = x[x > thresh.min]) / length(x = x))
}
),
digits = 3
)
data.alpha <- cbind(data.temp1, data.temp2)
colnames(x = data.alpha) <- c("pct.1","pct.2")
alpha.min <- apply(X = data.alpha, MARGIN = 1, FUN = max)
names(x = alpha.min) <- rownames(x = data.alpha)
genes.use <- names(x = which(x = alpha.min > min.pct))
if (length(x = genes.use) == 0) {
stop("No genes pass min.pct threshold")
}
alpha.diff <- alpha.min - apply(X = data.alpha, MARGIN = 1, FUN = min)
genes.use <- names(
x = which(x = alpha.min > min.pct & alpha.diff > min.diff.pct)
)
if (length(x = genes.use) == 0) {
stop("No genes pass min.diff.pct threshold")
}
#gene selection (based on average difference)
data.1 <- apply(X = data.use[genes.use, cells.1, drop = F], MARGIN = 1, FUN = function(x) log(x = mean(x = expm1(x = x)) + pseudocount.use))
data.2 <- apply(X = data.use[genes.use, cells.2, drop = F], MARGIN = 1, FUN = function(x) log(x = mean(x = expm1(x = x)) + pseudocount.use))
total.diff <- (data.1 - data.2)
if (!only.pos) genes.diff <- names(x = which(x = abs(x = total.diff) > logfc.threshold))
if (only.pos) genes.diff <- names(x = which(x = total.diff > logfc.threshold))
genes.use <- intersect(x = genes.use, y = genes.diff)
if (length(x = genes.use) == 0) {
stop("No genes pass logfc.threshold threshold")
}
if (max.cells.per.ident < Inf) {
set.seed(seed = random.seed)
if (length(cells.1) > max.cells.per.ident) cells.1 = sample(x = cells.1, size = max.cells.per.ident)
if (length(cells.2) > max.cells.per.ident) cells.2 = sample(x = cells.2, size = max.cells.per.ident)
}
#perform DR
if (!(test.use %in% c('negbinom', 'poisson', 'MAST')) && !is.null(x = latent.vars)) {
warning("'latent.vars' is only used for 'negbinom', 'poisson', and 'MAST' tests")
}
if (test.use == "bimod") {
to.return <- DiffExpTest(
object = object,
assay.type = assay.type,
cells.1 = cells.1,
cells.2 = cells.2,
genes.use = genes.use,
print.bar = print.bar
)
}
if (test.use == "roc") {
to.return <- MarkerTest(
object = object,
assay.type = assay.type,
cells.1 = cells.1,
cells.2 = cells.2,
genes.use = genes.use,
print.bar = print.bar
)
}
if (test.use == "t") {
to.return <- DiffTTest(
object = object,
assay.type = assay.type,
cells.1 = cells.1,
cells.2 = cells.2,
genes.use = genes.use,
print.bar = print.bar
)
}
if (test.use == "tobit") {
to.return <- TobitTest(
object = object,
assay.type = assay.type,
cells.1 = cells.1,
cells.2 = cells.2,
genes.use = genes.use,
print.bar = print.bar
)
}
if (test.use == "negbinom") {
to.return <- NegBinomDETest(
object = object,
assay.type = assay.type,
cells.1 = cells.1,
cells.2 = cells.2,
genes.use = genes.use,
latent.vars = latent.vars,
print.bar = print.bar,
min.cells = min.cells.gene
)
}
if (test.use == "poisson") {
to.return <- PoissonDETest(
object = object,
assay.type = assay.type,
cells.1 = cells.1,
cells.2 = cells.2,
genes.use = genes.use,
latent.vars = latent.vars,
print.bar = print.bar,
min.cells = min.cells.gene
)
}
if (test.use == "MAST") {
to.return <- MASTDETest(
object = object,
assay.type = assay.type,
cells.1 = cells.1,
cells.2 = cells.2,
genes.use = genes.use,
latent.vars = latent.vars,
...
)
}
if (test.use == "wilcox") {
to.return <- WilcoxDETest(
object = object,
assay.type = assay.type,
cells.1 = cells.1,
cells.2 = cells.2,
genes.use = genes.use,
print.bar = print.bar,
...
)
}
if (test.use == "LR") {
to.return <- LRDETest(
object = object,
assay.type = assay.type,
cells.1 = cells.1,
cells.2 = cells.2,
genes.use = genes.use,
print.bar = print.bar,
...
)
}
if (test.use == "DESeq2") {
to.return <- DESeq2DETest(
object = object,
assay.type = assay.type,
cells.1 = cells.1,
cells.2 = cells.2,
genes.use = genes.use,
...
)
}
#return results
to.return[, "avg_logFC"] <- total.diff[rownames(x = to.return)]
to.return <- cbind(to.return, data.alpha[rownames(x = to.return), , drop = FALSE])
to.return$p_val_adj = p.adjust(
p = to.return$p_val,method = "bonferroni",
n = nrow(x = GetAssayData(
object = object,
assay.type = assay.type,
slot = "data"
))
)
if (test.use == "roc") {
to.return <- to.return[order(-to.return$power, -to.return$avg_logFC), ]
} else {
to.return <- to.return[order(to.return$p_val, -to.return$avg_logFC), ]
}
if (only.pos) {
to.return <- subset(x = to.return, subset = avg_logFC > 0)
}
return(to.return)
}
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 print.bar Print a progress bar once expression testing begins (uses pbapply to do this)
#' @param max.cells.per.ident Down sample each identity class to a max number. Default is no downsampling.
#' @param random.seed Random seed for downsampling
#' @param return.thresh Only return markers that have a p-value < return.thresh, or a power > return.thresh (if the test is ROC)
#' @param do.print FALSE by default. If TRUE, outputs updates on progress.
#' @param min.cells.gene Minimum number of cells expressing the gene 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 latent.vars Remove the effects of these variables, used only when \code{test.use} is one of
#' 'negbinom', 'poisson', or 'MAST'
#' @param assay.type Type of assay to perform DE for (default is RNA)
#' @param \dots Additional parameters to pass to specific DE functions
#'
#' @return Matrix containing a ranked list of putative markers, and associated
#' statistics (p-values, ROC score, etc.)
#'
#' @export
#' @examples
#' all_markers <- FindAllMarkers(object = pbmc_small)
#' head(x = all_markers)
#'
FindAllMarkers <- function(
object,
genes.use = NULL,
logfc.threshold = 0.25,
test.use = "wilcox",
min.pct = 0.1,
min.diff.pct = -Inf,
print.bar = TRUE,
only.pos = FALSE,
max.cells.per.ident = Inf,
return.thresh = 1e-2,
do.print = FALSE,
random.seed = 1,
min.cells.gene = 3,
min.cells.group = 3,
latent.vars = NULL,
assay.type = "RNA",
...
) {
data.1 <- GetAssayData(object = object,assay.type = assay.type,slot = "data")
genes.use <- SetIfNull(x = genes.use, default = rownames(x = data.1))
if ((test.use == "roc") && (return.thresh == 1e-2)) {
return.thresh = 0.7
}
idents.all <- sort(x = unique(x = object@ident))
genes.de <- list()
#if (max.cells.per.ident < Inf) {
# object <- SubsetData(
# object = object,
# max.cells.per.ident = max.cells.per.ident,
# random.seed = random.seed
# )
#}
for (i in 1:length(x = idents.all)) {
genes.de[[i]] <- tryCatch(
{
FindMarkers(
object = object,
assay.type = assay.type,
ident.1 = idents.all[i],
ident.2 = NULL,
genes.use = genes.use,
logfc.threshold = logfc.threshold,
test.use = test.use,
min.pct = min.pct,
min.diff.pct = min.diff.pct,
print.bar = print.bar,
min.cells.gene = min.cells.gene,
min.cells.group = min.cells.group,
latent.vars = latent.vars,
max.cells.per.ident = max.cells.per.ident,
...
)
},
error = function(cond){
return(NULL)
}
)
if (do.print) {
message(paste("Calculating cluster", idents.all[i]))
}
}
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 {
gde <- gde[order(gde$p_val, -gde$avg_logFC), ]
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(gde.all) > 0) {
return(subset(x = gde.all, subset = avg_logFC > 0))
}
rownames(x = gde.all) <- make.unique(names = as.character(x = gde.all$gene))
if (nrow(gde.all) == 0) {
warning("No DE genes identified.")
}
return(gde.all)
}
#' Gene expression markers of identity classes defined by a phylogenetic clade
#'
#' Finds markers (differentially expressed genes) based on a branching point (node) in
#' the phylogenetic tree. Markers that define clusters in the left branch are positive markers.
#' Markers that define the right branch are negative markers.
#'
#' @inheritParams FindMarkers
#' @param node The node in the phylogenetic tree to use as a branch point
#' @param tree.use Can optionally pass the tree to be used. Default uses the tree in object@@cluster.tree
#' @param assay.type Type of assay to fetch data for (default is RNA)
#' @param ... Additional arguments passed to FindMarkers
#'
#' @return Matrix containing a ranked list of putative markers, and associated
#' statistics (p-values, ROC score, etc.)
#'
#' @export
#'
#' @examples
#' FindMarkersNode(pbmc_small, 5)
#'
FindMarkersNode <- function(
object,
node,
tree.use = NULL,
genes.use = NULL,
logfc.threshold = 0.25,
test.use = "wilcox",
assay.type = "RNA",
...
) {
data.use <- GetAssayData(
object = object,
assay.type = assay.type
)
genes.use <- SetIfNull(x = genes.use, default = rownames(x = data.use))
tree <- SetIfNull(x = tree.use, default = [email protected][[1]])
ident.order <- tree$tip.label
nodes.1 <- ident.order[GetLeftDescendants(tree = tree, node = node)]
nodes.2 <- ident.order[GetRightDescendants(tree = tree, node = node)]
#print(nodes.1)
#print(nodes.2)
to.return <- FindMarkers(
object = object,
assay.type = assay.type,
ident.1 = nodes.1,
ident.2 = nodes.2,
genes.use = genes.use,
logfc.threshold = logfc.threshold,
test.use = test.use,
...
)
return(to.return)
}
globalVariables(names = c('myAUC', 'p_val'), package = 'Seurat', add = TRUE)
#' Find all markers for a node
#'
#' This function finds markers for all splits at or below the specified node
#'
#' @param object Seurat object. Must have object@@cluster.tree slot filled. Use BuildClusterTree() if not.
#' @param node Node from which to start identifying split markers, default is top node.
#' @param genes.use 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.
#' @param test.use Denotes which test to use. Seurat currently implements
#' "bimod" (likelihood-ratio test for single cell gene expression, McDavid et
#' al., Bioinformatics, 2013, default), "roc" (standard AUC classifier), "t"
#' (Students t-test), and "tobit" (Tobit-test for differential gene expression,
#' as in Trapnell et al., Nature Biotech, 2014), 'poisson', and 'negbinom'.
#' The latter two options should only be used on UMI datasets, and assume an underlying
#' poisson or negative-binomial distribution.
#' @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 expression
#' @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 print.bar Print a progress bar once expression testing begins (uses pbapply to do this)
#' @param max.cells.per.ident Down sample each identity class to a max number. Default is no downsampling.
#' @param random.seed Random seed for downsampling
#' @param return.thresh Only return markers that have a p-value < return.thresh, or a power > return.thresh (if the test is ROC)
#' @param do.print Print status updates
#' @param min.cells.gene Minimum number of cells expressing the gene 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 assay.type Type of assay to fetch data for (default is RNA)
#' @param \dots Additional parameters to pass to specific DE functions
#'
#' @return Returns a dataframe with a ranked list of putative markers for each node and associated statistics
#'
#' @importFrom ape drop.tip
#'
#' @export
#'
#' @examples
#' pbmc_small
#'
#' FindAllMarkersNode(pbmc_small)
#'
FindAllMarkersNode <- function(
object,
node = NULL,
genes.use = NULL,
logfc.threshold = 0.25,
test.use = "wilcox",
min.pct = 0.1,
min.diff.pct = 0.05,
print.bar = TRUE,
only.pos = FALSE,
max.cells.per.ident = Inf,
return.thresh = 1e-2,
do.print = FALSE,
random.seed = 1,
min.cells.gene = 3,
min.cells.group = 3,
assay.type = "RNA",
...
) {
if (length([email protected]) == 0) {
stop("Tree hasn't been built yet. Run BuildClusterTree to build.")
}
data.use <- GetAssayData(object = object,assay.type = assay.type,slot = "data")
genes.use <- SetIfNull(x = genes.use, default = rownames(x = data.use))
node <- SetIfNull(x = node, default = [email protected][[1]]$edge[1, 1])
tree.use <- [email protected][[1]]
descendants <- DFT(tree = tree.use, node = node, path = NULL, include.children = TRUE)
all.children <- sort(x = tree.use$edge[,2][!tree.use$edge[,2] %in% tree.use$edge[,1]])
descendants <- MapVals(v = descendants, from = all.children, to = tree.use$tip.label)
drop.children <- setdiff(tree.use$tip.label, descendants)
keep.children <- setdiff(tree.use$tip.label, drop.children)
orig.nodes <- c(node, as.numeric(setdiff(descendants, keep.children)))
tree.use <- drop.tip(tree.use, drop.children)
new.nodes <- unique(tree.use$edge[,1])
if ((test.use == 'roc') && (return.thresh == 1e-2)) {
return.thresh <- 0.7
}
genes.de <- list()
for (i in ((tree.use$Nnode + 2):max(tree.use$edge))) {
genes.de[[i]] <- FindMarkersNode(
object = object,
assay.type = assay.type,
node = i,
tree.use = tree.use,
genes.use = genes.use,
logfc.threshold = logfc.threshold,
test.use = test.use,
min.pct = min.pct,
min.diff.pct = min.diff.pct,
print.bar = print.bar,
only.pos = only.pos,
max.cells.per.ident = max.cells.per.ident,
random.seed = random.seed,
min.cells.gene = min.cells.gene,
min.cells.group = min.cells.group
)
if (do.print) {
message(paste("Calculating node", i))
}
}
gde.all <- data.frame()
for (i in ((tree.use$Nnode + 2):max(tree.use$edge))) {
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))
)
}
if ( (test.use == 'bimod') || (test.use == 't')) {
gde <- gde[order(gde$p_val,-gde$avg_logFC), ]
gde <- subset(x = gde, subset = p_val < return.thresh)
}
if (nrow(x = gde) > 0) {
gde$cluster <- i
gde$gene <- rownames(x = gde)
}
if (nrow(x = gde) > 0) {
gde.all <- rbind(gde.all,gde)
}
}
}
gde.all$cluster <- MapVals(
v = gde.all$cluster,
from = new.nodes,
to = orig.nodes
)
return(gde.all)
}
#' Finds markers that are conserved between the two groups
#'
#' @param object Seurat object
#' @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.type Type 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 Matrix 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 MetaDE package),
#' percentage of cells expressing the marker, average differences)
#'
#' @import metap
#' @export
#'
#' @examples
#' \dontrun{
#' pbmc_small
#' # Create a simulated grouping variable
#' [email protected]$groups <- sample(
#' x = c("g1", "g2"),
#' size = length(x = [email protected]),
#' 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.type = "RNA",
meta.method = minimump,
...
) {
if(class(meta.method) != "function") {
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 detail description of the available functions.")
}
object.var <- FetchData(object = object, vars.all = grouping.var)
object <- SetIdent(
object = object,
cells.use = [email protected],
ident.use = paste(object@ident, 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
for (i in 1:num.groups) {
level.use <- levels.split[i]
ident.use.1 <- paste(ident.1, level.use, sep = "_")
if(!ident.use.1 %in% object@ident) {
stop(paste0("Identity: ", ident.1, " not present in group ", level.use))
}
cells.1 <- WhichCells(object = object, ident = ident.use.1)
if (is.null(x = ident.2)) {
cells.2 <- setdiff(x = cells[[i]], y = cells.1)
ident.use.2 <- names(x = which(x = table(object@ident[cells.2]) > 0))
if (length(x = ident.use.2) == 0) {
stop(paste("Only one identity class present:", ident.1))
}
}
if (! is.null(x = ident.2)) {
ident.use.2 <- paste(ident.2, level.use, sep = "_")
}
cat(
paste0(
"Testing ",
ident.use.1,
" vs ",
paste(ident.use.2, collapse = ", "), "\n"
),
file = stderr()
)
if(!ident.use.2 %in% object@ident) {
stop(paste0("Identity: ", ident.2, " not present in group ", level.use))
}
marker.test[[i]] <- FindMarkers(
object = object,
assay.type = assay.type,
ident.1 = ident.use.1,
ident.2 = ident.use.2,
...
)
}
genes.conserved <- Reduce(intersect, lapply(marker.test, FUN = function(x) rownames(x)))
markers.conserved <- list()
for (i in 1:num.groups) {
markers.conserved[[i]] <- marker.test[[i]][genes.conserved, ]
colnames(x = markers.conserved[[i]]) <- paste(
levels.split[i],
colnames(x = markers.conserved[[i]]),
sep="_"
)
}
markers.combined <- Reduce(cbind, markers.conserved)
pval.codes <- paste(levels.split, "p_val", sep = "_")
markers.combined$max_pval <- apply(
X = markers.combined[, pval.codes],
MARGIN = 1,
FUN = max
)
combined.pval <- data.frame(cp = apply(X = markers.combined[, pval.codes], MARGIN = 1, FUN = function(x) meta.method(x)$p))
colnames(combined.pval) <- paste0(as.character(formals()$meta.method), "_p_val")
markers.combined <- cbind(markers.combined, combined.pval)
markers.combined <- markers.combined[order(markers.combined[,paste0(as.character(formals()$meta.method), "_p_val")]), ]
return(markers.combined)
}
#' Likelihood ratio test for zero-inflated data
#'
#' Identifies differentially expressed genes between two groups of cells using
#' the LRT model proposed in McDavid et al, Bioinformatics, 2013
#'
#' @inheritParams FindMarkers
#' @param object Seurat object
#' @param cells.1 Group 1 cells
#' @param cells.2 Group 2 cells
#' @param assay.type Type of assay to fetch data for (default is RNA)
#' @return Returns a p-value ranked matrix of putative differentially expressed
#' genes.
#'
#' @export
#' @examples
#' pbmc_small
#' DiffExpTest(pbmc_small, cells.1 = WhichCells(object = pbmc_small, ident = 1),
#' cells.2 = WhichCells(object = pbmc_small, ident = 2))
#'
DiffExpTest <- function(
object,
cells.1,
cells.2,
assay.type = "RNA",
genes.use = NULL,
print.bar = TRUE
) {
data.test <- GetAssayData(object = object,assay.type = assay.type,slot = "data")
genes.use <- SetIfNull(x = genes.use, default = rownames(data.test))
if (print.bar) {
iterate.fxn <- pblapply
} else {
iterate.fxn <- lapply
}
p_val <- unlist(
x = iterate.fxn(
X = genes.use,
FUN = function(x) {
return(
DifferentialLRT(
x = as.numeric(x = data.test[x, cells.1]),
y = as.numeric(x = data.test[x, cells.2])
)
)
}
)
)
to.return <- data.frame(p_val, row.names = genes.use)
return(to.return)
}
#' Negative binomial test for UMI-count based data
#'
#' Identifies differentially expressed genes between two groups of cells using
#' a negative binomial generalized linear model
#'
#' @param object Seurat object
#' @param cells.1 Group 1 cells
#' @param cells.2 Group 2 cells
#' @param genes.use Genes to use for test
#' @param latent.vars Latent variables to test
#' @param print.bar Print progress bar
#' @param min.cells Minimum number of cells threshold
#' @param assay.type Type of assay to fetch data for (default is RNA)
#'
#' @return Returns a p-value ranked matrix of putative differentially expressed
#' genes.
#'
#' @importFrom MASS glm.nb
#' @importFrom pbapply pbapply
#' @importFrom stats var as.formula
#'
#' @export
#'
#'@examples
#' pbmc_small
#' # Note, not recommended for particularly small datasets - expect warnings
#' NegBinomDETest(pbmc_small, cells.1 = WhichCells(object = pbmc_small, ident = 1),
#' cells.2 = WhichCells(object = pbmc_small, ident = 2))
#'
NegBinomDETest <- function(
object,
cells.1,
cells.2,
genes.use = NULL,
latent.vars = NULL,
print.bar = TRUE,
min.cells = 3,
assay.type = "RNA"
) {
genes.use <- SetIfNull(x = genes.use, default = rownames(x = GetAssayData(object = object,assay.type = assay.type,slot = "data")))
# check that the gene made it through the any filtering that was done
genes.use <- genes.use[genes.use %in% rownames(x = GetAssayData(object = object,assay.type = assay.type,slot = "data"))]
my.latent <- FetchData(
object = object,
vars.all = latent.vars,
cells.use = c(cells.1, cells.2),
use.raw = TRUE
)
to.test.data <- GetAssayData(object = object,assay.type = assay.type,slot = "raw.data")[genes.use, c(cells.1, cells.2)]
to.test <- data.frame(my.latent, row.names = c(cells.1, cells.2))
to.test[cells.1, "group"] <- "A"
to.test[cells.2, "group"] <- "B"
to.test$group <- factor(x = to.test$group)
latent.vars <- c("group", latent.vars)
if (print.bar) {
iterate.fxn <- pblapply
} else {
iterate.fxn <- lapply
}
p_val <- unlist(
x = iterate.fxn(
X = genes.use,
FUN = function(x) {
to.test[, "GENE"] <- as.numeric(x = to.test.data[x, ])
# check that gene is expressed in specified number of cells in one group
if (sum(to.test$GENE[to.test$group == "A"]) < min.cells ||
sum(to.test$GENE[to.test$group == "B"]) < min.cells) {
warning(paste0(
"Skipping gene --- ",
x,
". Fewer than ",
min.cells,
" in at least one of the two clusters."
))
return(2)
}
# check that variance between groups is not 0
if (var(x = to.test$GENE) == 0) {
warning(paste0(
"Skipping gene -- ",
x,
". No variance in expression between the two clusters."
))
return(2)
}
fmla <- as.formula(paste0("GENE ", " ~ ", paste(latent.vars, collapse = "+")))
p.estimate <- 2
try(
expr = p.estimate <- summary(
object = glm.nb(formula = fmla, data = to.test)
)$coef[2, 4],
silent = TRUE
)
return(p.estimate)
}
)
)
if (length(x = which(x = p_val == 2)) > 0){
genes.use <- genes.use[-which(x = p_val == 2)]
p_val <- p_val[! p_val == 2]
}
to.return <- data.frame(p_val, row.names = genes.use)
return(to.return)
}
#' Negative binomial test for UMI-count based data (regularized version)
#'
#' Identifies differentially expressed genes between two groups of cells using
#' a likelihood ratio test of negative binomial generalized linear models where
#' the overdispersion parameter theta is determined by pooling information
#' across genes.
#'
#' @inheritParams FindMarkers
#' @param object Seurat object
#' @param cells.1 Group 1 cells
#' @param cells.2 Group 2 cells
#' @param genes.use Genes to use for test
#' @param latent.vars Latent variables to test
#' @param print.bar Print progress bar
#' @param min.cells Minimum number of cells threshold
#' @param assay.type Type of assay to fetch data for (default is RNA)
#'
#' @return Returns a p-value ranked data frame of test results.
#'
#' @importFrom stats p.adjust
#' @importFrom utils txtProgressBar setTxtProgressBar
#'
#' @export
#'
#' @examples
#' # Note, not recommended for particularly small datasets - expect warnings
#' NegBinomDETest(
#' object = pbmc_small,
#' cells.1 = WhichCells(object = pbmc_small, ident = 1),
#' cells.2 = WhichCells(object = pbmc_small, ident = 2)
#' )
#'
NegBinomRegDETest <- function(
object,
cells.1,
cells.2,
genes.use = NULL,
latent.vars = NULL,
print.bar = TRUE,
min.cells = 3,
assay.type = "RNA"
) {
if (!is.null(genes.use)) {
message('Make sure that genes.use contains mostly genes that are not expected to be
differentially expressed to allow unbiased theta estimation')
}
genes.use <- SetIfNull(x = genes.use, default = rownames(x = GetAssayData(object = object,assay.type = assay.type,slot = "data")))
# check that the gene made it through the any filtering that was done
genes.use <- genes.use[genes.use %in% rownames(x = GetAssayData(object = object,assay.type = assay.type,slot = "data"))]
message(
sprintf(
'NegBinomRegDETest for %d genes and %d and %d cells',
length(x = genes.use),
length(x = cells.1),
length(x = cells.2)
)
)
grp.fac <- factor(
x = c(
rep.int(x = 'A', times = length(x = cells.1)),
rep.int(x = 'B', times = length(x = cells.2))
)
)
to.test.data <- GetAssayData(object = object,assay.type = assay.type,slot = "raw.data")[genes.use, c(cells.1, cells.2), drop = FALSE]
message('Calculating mean per gene per group')
above.threshold <- pmax(
apply(X = to.test.data[, cells.1] > 0, MARGIN = 1, FUN = mean),
apply(X = to.test.data[, cells.2] > 0, MARGIN = 1, FUN = mean)
) >= 0.02
message(
sprintf(
'%d genes are detected in at least 2%% of the cells in at least one of the groups and will be tested',
sum(above.threshold)
)
)
genes.use <- genes.use[above.threshold]
to.test.data <- to.test.data[genes.use, , drop = FALSE]
my.latent <- FetchData(
object = object,
vars.all = latent.vars,
cells.use = c(cells.1, cells.2),
use.raw = TRUE