forked from satijalab/seurat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathseurat.R
4540 lines (4258 loc) · 221 KB
/
seurat.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
################################################################################
### Seurat
#' The Seurat Class
#'
#' The Seurat object is the center of each single cell analysis. It stores all information
#' associated with the dataset, including data, annotations, analyes, etc. All that is needed
#' to construct a Seurat object is an expression matrix (rows are genes, columns are cells), which
#' should be log-scale
#'
#' Each Seurat object has a number of slots which store information. Key slots to access
#' are listed below.
#'
#'
#'@section Slots:
#' \describe{
#' \item{\code{raw.data}:}{\code{"ANY"}, The raw project data }
#' \item{\code{data}:}{\code{"ANY"}, The expression matrix (log-scale) }
#' \item{\code{scale.data}:}{\code{"ANY"}, The scaled (after z-scoring
#' each gene) expression matrix. Used for PCA, ICA, and heatmap plotting}
#' \item{\code{var.genes}:}{\code{"vector"}, Variable genes across single cells }
#' \item{\code{is.expr}:}{\code{"numeric"}, Expression threshold to determine if a gene is expressed }
#' \item{\code{ident}:}{\code{"vector"}, The 'identity class' for each single cell }
#' \item{\code{data.info}:}{\code{"data.frame"}, Contains information about each cell, starting with # of genes detected (nGene)
#' the original identity class (orig.ident), user-provided information (through AddMetaData), etc. }
#' \item{\code{project.name}:}{\code{"character"}, Name of the project (for record keeping) }
#' \item{\code{pca.x}:}{\code{"data.frame"}, Gene projection scores for the PCA analysis }
#' \item{\code{pca.x.full}:}{\code{"data.frame"}, Gene projection scores for the projected PCA (contains all genes) }
#' \item{\code{pca.rot}:}{\code{"data.frame"}, The rotation matrix (eigenvectors) of the PCA }
#' \item{\code{ica.x}:}{\code{"data.frame"}, Gene projection scores for ICA }
#' \item{\code{ica.rot}:}{\code{"data.frame"}, The estimated source matrix from ICA }
#' \item{\code{tsne.rot}:}{\code{"data.frame"}, Cell coordinates on the t-SNE map }
#' \item{\code{mean.var}:}{\code{"data.frame"}, The output of the mean/variability analysis for all genes }
#' \item{\code{imputed}:}{\code{"data.frame"}, Matrix of imputed gene scores }
#' \item{\code{final.prob}:}{\code{"data.frame"}, For spatial inference, posterior probability of each cell mapping to each bin }
#' \item{\code{insitu.matrix}:}{\code{"data.frame"}, For spatial inference, the discretized spatial reference map }
#' \item{\code{cell.names}:}{\code{"vector"}, Names of all single cells (column names of the expression matrix) }
#' \item{\code{cluster.tree}:}{\code{"list"}, List where the first element is a phylo object containing the
#' phylogenetic tree relating different identity classes }
#' \item{\code{snn.sparse}:}{\code{"dgCMatrix"}, Sparse matrix object representation of the SNN graph }
#' \item{\code{snn.dense}:}{\code{"matrix"}, Dense matrix object representation of the SNN graph }
#' \item{\code{snn.k}:}{\code{"numeric"}, k used in the construction of the SNN graph }
#'
#'}
#' @name seurat
#' @rdname seurat
#' @aliases seurat-class
#' @exportClass seurat
#' @importFrom Rcpp evalCpp
#' @useDynLib Seurat
seurat <- setClass("seurat", slots =
c(raw.data = "ANY", data="ANY",scale.data="ANY",var.genes="vector",is.expr="numeric",
ident="vector",pca.x="data.frame",pca.rot="data.frame",
emp.pval="data.frame",kmeans.obj="list",pca.obj="list",
gene.scores="data.frame", drop.coefs="data.frame",
wt.matrix="data.frame", drop.wt.matrix="data.frame",trusted.genes="vector",drop.expr="numeric",data.info="data.frame",
project.name="character", kmeans.gene="list", kmeans.cell="list",jackStraw.empP="data.frame",
jackStraw.fakePC = "data.frame",jackStraw.empP.full="data.frame",pca.x.full="data.frame", kmeans.col="list",mean.var="data.frame", imputed="data.frame",mix.probs="data.frame",
mix.param="data.frame",final.prob="data.frame",insitu.matrix="data.frame",
tsne.rot="data.frame", ica.rot="data.frame", ica.x="data.frame", ica.obj="list",cell.names="vector",cluster.tree="list",
snn.sparse="dgCMatrix", snn.dense="matrix", snn.k="numeric"))
#' Setup Seurat object
#'
#' Setup and initialize basic parameters of the Seurat object
#'
#'
#' @param object Seurat object
#' @param project Project name (string)
#' @param min.cells Include genes with detected expression in at least this
#' many cells
#' @param min.genes Include cells where at least this many genes are detected
#' @param is.expr Expression threshold for 'detected' gene
#' @param do.logNormalize whether to normalize the expression data per cell and transform to log space.
#' @param total.expr scale factor in the log normalization
#' @param do.scale In object@@scale.data, perform row-scaling (gene-based
#' z-score)
#' @param do.center In object@@scale.data, perform row-centering (gene-based
#' centering)
#' @param names.field For the initial identity class for each cell, choose this
#' field from the cell's column name
#' @param names.delim For the initial identity class for each cell, choose this
#' delimiter from the cell's column name
#' @param meta.data Additional metadata to add to the Seurat object. Should be
#' a data frame where the rows are cell names, and the columns are additional
#' metadata fields
#' @param save.raw TRUE by default. If FALSE, do not save the unmodified data in object@@raw.data
#' which will save memory downstream for large datasets
#' @return Seurat object. Fields modified include object@@data,
#' object@@scale.data, object@@data.info, object@@ident
#' @import stringr
#' @import pbapply
#' @importFrom Matrix colSums rowSums
#' @export
setGeneric("Setup", function(object, project, min.cells=3, min.genes=1000, is.expr=0, do.logNormalize=T,total.expr=1e4,do.scale=TRUE, do.center=TRUE,names.field=1,names.delim="_",meta.data=NULL,save.raw=TRUE) standardGeneric("Setup"))
#' @export
setMethod("Setup","seurat",
function(object, project, min.cells=3, min.genes=1000, is.expr=0, do.logNormalize=T,total.expr=1e4,do.scale=TRUE, do.center=TRUE,names.field=1,names.delim="_",meta.data=NULL,save.raw=TRUE) {
[email protected] <- is.expr
num.genes <- colSums([email protected] > is.expr)
num.mol=colSums([email protected])
cells.use <- names(num.genes[which(num.genes > min.genes)])
object@data <- [email protected][, cells.use]
if (do.logNormalize) {
object@data=LogNormalize(object@data,scale.factor = total.expr)
}
#to save memory downstream, especially for large object
if (!(save.raw)) [email protected] <- matrix();
genes.use <- rownames(object@data)
if (min.cells > 0) {
num.cells <- rowSums(object@data > is.expr)
genes.use <- names(num.cells[which(num.cells >= min.cells)])
object@data <- object@data[genes.use, ]
}
object@ident <- factor(unlist(lapply(colnames(object@data), extract_field, names.field, names.delim)))
names(object@ident) <- colnames(object@data)
[email protected] <- names(object@ident)
# if there are more than 100 idents, set all ident to project name
ident.levels=length(unique(object@ident))
if((ident.levels > 100 || ident.levels == 0)||ident.levels==length(object@ident)) {
object <- SetIdent(object, ident.use = project)
}
data.ngene <- num.genes[cells.use]
data.nmol <- num.mol[cells.use]
[email protected] <- data.frame(data.ngene)
colnames([email protected])[1] <- "nGene"
nGene=data.ngene; nUMI=data.nmol
[email protected] <- data.frame(nGene,nUMI)
if (!is.null(meta.data)) {
object <- AddMetaData(object ,metadata = meta.data)
}
[email protected] <- data.frame(data.ngene)
colnames([email protected])[1] <- "nGene"
rownames([email protected]) <- colnames(object@data)
[email protected][names(object@ident),"orig.ident"] <- object@ident
[email protected] <- project
[email protected] <- matrix()
if(do.scale | do.center) {
object <- ScaleData(object,do.scale = do.scale, do.center = do.center)
}
#if(calc.noise) {
# object=CalcNoiseModels(object,...)
# object=GetWeightMatrix(object)
#}
return(object)
}
)
#' Load in data from 10X
#'
#' Enables easy loading of sparse data matrices provided by 10X genomics.
#'
#' @param data.dir Directory containing the matrix.mtx, genes.tsv, and barcodes.tsv
#' files provided by 10X. A vector or named vector can be given in order to load
#' several data directories. If a named vector is given, the cell barcode names
#' will be prefixed with the name.
#' @return Returns a sparse matrix with rows and columns labeled
#' @importFrom Matrix readMM
setGeneric("Read10X", function(data.dir = NULL) standardGeneric("Read10X"))
#' @export
setMethod("Read10X", "character", function(data.dir = NULL){
full_data <- list()
for(i in seq_along(data.dir)){
run <- data.dir[i]
if (!dir.exists(run)){
stop("Directory provided does not exist")
}
if(!grepl("\\/$", run)){
run <- paste(run, "/", sep = "")
}
barcode.loc <- paste(run, "barcodes.tsv", sep ="")
gene.loc <- paste(run, "genes.tsv", sep ="")
matrix.loc <- paste(run, "matrix.mtx", sep ="")
if (!file.exists(barcode.loc)){
stop("Barcode file missing")
}
if (!file.exists(gene.loc)){
stop("Gene name file missing")
}
if (!file.exists(matrix.loc)){
stop("Expression matrix file missing")
}
data <- readMM(matrix.loc)
cell.names <- readLines(barcode.loc)
gene.names <- readLines(gene.loc)
if(all(grepl("\\-1$", cell.names)) == TRUE) {
cell.names <- as.vector(as.character(sapply(cell.names, extract_field, 1, delim = "-")))
}
rownames(data) <- make.unique(as.character(sapply(gene.names, extract_field, 2, delim = "\\t")))
if(is.null(names(data.dir))){
if(i < 2){
colnames(data) <- cell.names
}
else {
colnames(data) <- paste0(i, "_", cell.names, sep = "")
}
} else {
colnames(data) <- paste0(names(data.dir)[i],"_",cell.names)
}
full_data <- append(full_data, data)
}
full_data <- do.call(cbind, full_data)
return(full_data)
})
#' Scale and center the data
#'
#'
#' @param object Seurat object
#' @param genes.use Vector of gene names to scale/center. Default is all genes in object@@data.
#' @param data.use Can optionally pass a matrix of data to scale, default is object@data[genes.use,]
#' @param do.scale Whether to scale the data.
#' @param do.center Whether to center the data.
#' @param scale.max Max value to accept for scaled data. The default is 10. Setting this can help
#' reduce the effects of genes that are only expressed in a very small number of cells.
#' @return Returns a seurat object with object@@scale.data updated with scaled and/or centered data.
setGeneric("ScaleData", function(object, genes.use=NULL, data.use=NULL, do.scale=TRUE, do.center=TRUE, scale.max=10) standardGeneric("ScaleData"))
#' @export
setMethod("ScaleData", "seurat",
function(object, genes.use=NULL, data.use=NULL, do.scale=TRUE, do.center=TRUE, scale.max=10) {
genes.use <- set.ifnull(genes.use,rownames(object@data))
genes.use=ainb(genes.use,rownames(object@data))
data.use <- set.ifnull(data.use,object@data[genes.use, ])
[email protected] <- matrix(NA, nrow = length(genes.use), ncol = ncol(object@data))
#rownames([email protected]) <- genes.use
#colnames([email protected]) <- colnames(object@data)
dimnames([email protected]) <- dimnames(data.use)
if(do.scale | do.center) {
bin.size <- 1000
max.bin <- floor(length(genes.use)/bin.size) + 1
print("Scaling data matrix")
pb <- txtProgressBar(min = 0, max = max.bin, style = 3)
for(i in 1:max.bin) {
my.inds <- ((bin.size * (i - 1)):(bin.size * i - 1))+1
my.inds <- my.inds[my.inds <= length(genes.use)]
#print(my.inds)
new.data <- t(scale(t(as.matrix(data.use[genes.use[my.inds], ])), center = do.center, scale = do.scale))
new.data[new.data>scale.max] <- scale.max
[email protected][genes.use[my.inds], ] <- new.data
setTxtProgressBar(pb, i)
}
close(pb)
}
return(object)
}
)
#' Normalize raw data
#'
#' Normalize count data per cell and transform to log scale
#'
#'
#' @param data Matrix with the raw count data
#' @param scale.factor Scale the data. Default is 1e4
#' @param display.progress Print progress
#' @return Returns a matrix with the normalize and log transformed data
#' @import Matrix
#' @export
setGeneric("LogNormalize", function(data, scale.factor = 1e4, display.progress = T) standardGeneric("LogNormalize"))
#' @export
setMethod("LogNormalize", "ANY",
function(data, scale.factor = 1e4, display.progress = T) {
if(class(data) == "data.frame") {
data <- as.matrix(data)
}
if(class(data) != "dgCMatrix") {
data <- as(data, "dgCMatrix")
}
# call Rcpp function to normalize
if(display.progress){
print("Performing log-normalization")
}
norm.data <- LogNorm(data, scale_factor = scale.factor, display_progress = display.progress)
colnames(norm.data) <- colnames(data)
rownames(norm.data) <- rownames(data)
return(norm.data)
}
)
#' Make object sparse
#'
#' Converts stored data matrices to sparse matrices to save space. Converts object@@raw.data and object@@data to sparse matrices.
#' If the snn has been stored as a dense matrix, this will convert it to a sparse matrix, store it in object@@snn.sparse and
#' remove object@@snn.dense.
#'
#'
#' @param object Seurat object
#' @return Returns a seurat object with data converted to sparse matrices.
#' @import Matrix
#' @export
setGeneric("MakeSparse", function(object) standardGeneric("MakeSparse"))
#' @export
setMethod("MakeSparse", "seurat",
function(object){
if (class([email protected]) == "data.frame"){
[email protected] <- as.matrix([email protected])
}
if (class(object@data) == "data.frame"){
object@data <- as.matrix(object@data)
}
if (length([email protected]) == 1 && length([email protected]) > 1) {
if (class([email protected]) == "data.frame"){
[email protected] <- as.matrix([email protected])
}
[email protected] <- as([email protected], "dgCMatrix")
[email protected] <- matrix()
}
[email protected] <- as([email protected], "dgCMatrix")
object@data <- as(object@data, "dgCMatrix")
return(object)
}
)
#' Sample UMI
#'
#' Downsample each cell to a specified number of UMIs. Includes
#' an option to upsample cells below specified UMI as well.
#'
#'
#' @param data Matrix with the raw count data
#' @param max.umi Number of UMIs to sample to
#' @param upsample Upsamples all cells with fewer than max.umi
#' @param progress.bar Display the progress bar
#' @import Matrix
#' @return Matrix with downsampled data
#' @export
setGeneric("SampleUMI", function(data, max.umi = 1000, upsample = F, progress.bar = T) standardGeneric("SampleUMI"))
#' @export
setMethod("SampleUMI", "ANY",
function(data, max.umi = 1000, upsample = F, progress.bar = T){
data <- as(data, "dgCMatrix")
if(length(max.umi) == 1){
return(RunUMISampling(data = data, sample_val = max.umi, upsample = upsample, display_progress = T))
}
else{
if(length(max.umi) != ncol(data)){
stop("max.umi vector not equal to number of cells")
}
return(RunUMISamplingPerCell(data = data, sample_val = max.umi, upsample = upsample, display_progress = T))
}
}
)
#' Add samples into existing Seurat object.
#'
#' @param object Seurat object
#' @param project Project name (string)
#' @param new.data Data matrix for samples to be added
#' @param min.cells Include genes with detected expression in at least this
#' many cells
#' @param min.genes Include cells where at least this many genes are detected
#' @param is.expr Expression threshold for 'detected' gene
#' @param do.logNormalize whether to normalize the expression data per cell and transform to log space.
#' @param total.expr scale factor in the log normalization
#' @param do.scale In object@@scale.data, perform row-scaling (gene-based
#' z-score)
#' @param do.center In object@@scale.data, perform row-centering (gene-based
#' centering)
#' @param names.field For the initial identity class for each cell, choose this
#' field from the cell's column name
#' @param names.delim For the initial identity class for each cell, choose this
#' delimiter from the cell's column name
#' @param meta.data Additional metadata to add to the Seurat object. Should be
#' a data frame where the rows are cell names, and the columns are additional
#' metadata fields
#' @param save.raw TRUE by default. If FALSE, do not save the unmodified data in object@@raw.data
#' which will save memory downstream for large datasets
#' @param add.cell.id String to be appended to the names of all cells in new.data. E.g. if add.cell.id = "rep1",
#' "cell1" becomes "cell1.rep1"
#' @import Matrix
#' @importFrom dplyr full_join
#' @export
setGeneric("AddSamples", function(object, new.data, project = NULL, min.cells=3, min.genes=1000, is.expr=0, do.logNormalize=T,
total.expr=1e4, do.scale=TRUE, do.center=TRUE, names.field=1, names.delim="_",
meta.data=NULL, save.raw = T, add.cell.id = NULL) standardGeneric("AddSamples"))
#' @export
setMethod("AddSamples","seurat",
function(object, new.data, project = NULL, min.cells=3, min.genes=1000, is.expr=0, do.logNormalize=T, total.expr=1e4,
do.scale=TRUE, do.center=TRUE, names.field=1, names.delim="_", meta.data=NULL, save.raw = T, add.cell.id = NULL) {
if(length([email protected]) < 2){
stop("Object provided has an empty raw.data slot. Adding/Merging performed on raw count data.")
}
if (!missing(add.cell.id)){
colnames(new.data) <- paste(colnames(new.data), add.cell.id, sep = ".")
}
if (any(colnames(new.data) %in% [email protected])) {
warning("Duplicate cell names, enforcing uniqueness via make.unique()")
new.data.names <- as.list(make.unique(c(colnames([email protected]), colnames(new.data)))[(ncol([email protected])+1):(ncol([email protected]) + ncol(new.data))])
names(new.data.names) <- colnames(new.data)
colnames(new.data) <- new.data.names
if(!is.null(meta.data)){
rownames(meta.data) <- unlist(unname(new.data.names[rownames(meta.data)]))
}
}
combined.data <- RowMergeSparseMatrices([email protected][,[email protected]], new.data)
new.object <- new("seurat", raw.data = combined.data)
if (is.null(meta.data)){
filler <- matrix(NA, nrow = ncol(new.data), ncol = ncol([email protected]))
rownames(filler) <- colnames(new.data)
colnames(filler) <- colnames([email protected])
filler <- as.data.frame(filler)
combined.meta.data <- rbind([email protected], filler)
}
else{
combined.meta.data <- suppressMessages(suppressWarnings(full_join([email protected], meta.data)))
}
project = set.ifnull(project, [email protected])
new.object <- Setup(new.object, project, min.cells = min.cells, min.genes = min.genes, is.expr = is.expr, do.logNormalize = do.logNormalize,
total.expr = total.expr, do.scale = do.scale, do.center = do.center, names.field = names.field,
names.delim = names.delim, save.raw = save.raw)
[email protected] <- combined.meta.data[[email protected],]
return(new.object)
}
)
#' Merge Seurat Objects
#'
#' Merge two Seurat objects
#'
#'
#' @param object1 First Seurat object to merge
#' @param object2 Second Seurat object to merge
#' @param min.cells Include genes with detected expression in at least this
#' many cells
#' @param min.genes Include cells where at least this many genes are detected
#' @param is.expr Expression threshold for 'detected' gene
#' @param do.logNormalize whether to normalize the expression data per cell and transform to log space.
#' @param total.expr scale factor in the log normalization
#' @param do.scale In object@@scale.data, perform row-scaling (gene-based
#' z-score)
#' @param do.center In object@@scale.data, perform row-centering (gene-based
#' centering)
#' @param names.field For the initial identity class for each cell, choose this
#' field from the cell's column name
#' @param names.delim For the initial identity class for each cell, choose this
#' delimiter from the cell's column name
#' @param meta.data Additional metadata to add to the Seurat object. Should be
#' a data frame where the rows are cell names, and the columns are additional
#' metadata fields
#' @param save.raw TRUE by default. If FALSE, do not save the unmodified data in object@@raw.data
#' which will save memory downstream for large datasets
#' @param add.cell.id1 String to be appended to the names of all cells in object1
#' @param add.cell.id2 String to be appended to the names of all cells in object2
#'
#' @return Merged Seurat object
#' @import Matrix
#' @importFrom dplyr full_join filter
#' @export
setGeneric("MergeSeurat", function(object1, object2, project = NULL, min.cells=0, min.genes=0, is.expr=0, do.logNormalize=T,
total.expr=1e4, do.scale=TRUE, do.center=TRUE, names.field=1, names.delim="_",
save.raw = T, add.cell.id1 = NULL, add.cell.id2 = NULL) standardGeneric("MergeSeurat"))
#' @export
setMethod("MergeSeurat", "seurat",
function(object1, object2, project = NULL, min.cells=0, min.genes=0, is.expr=0, do.logNormalize=T,
total.expr=1e4, do.scale=TRUE, do.center=TRUE, names.field=1, names.delim="_",
save.raw = T, add.cell.id1 = NULL, add.cell.id2 = NULL) {
if(length([email protected]) < 2){
stop("First object provided has an empty raw.data slot. Adding/Merging performed on raw count data.")
}
if(length([email protected]) < 2){
stop("Second object provided has an empty raw.data slot. Adding/Merging performed on raw count data.")
}
if (!missing(add.cell.id1)){
[email protected] <- paste([email protected], add.cell.id1, sep = ".")
colnames([email protected]) <- paste(colnames([email protected]), add.cell.id1, sep = ".")
rownames([email protected]) <- paste(rownames([email protected]), add.cell.id1, sep = ".")
}
if (!missing(add.cell.id2)){
[email protected] <- paste([email protected], add.cell.id2, sep = ".")
colnames([email protected]) <- paste(colnames([email protected]), add.cell.id2, sep = ".")
rownames([email protected]) <- paste(rownames([email protected]), add.cell.id2, sep = ".")
}
if (any([email protected] %in% [email protected])) {
warning("Duplicate cell names, enforcing uniqueness via make.unique()")
object2.names <- as.list(make.unique(c(colnames([email protected]), colnames([email protected])))[(ncol([email protected])+1):(ncol([email protected]) + ncol([email protected]))])
names(object2.names) <- colnames([email protected])
colnames([email protected]) <- object2.names
[email protected] <- unlist(unname(object2.names[[email protected]]))
rownames([email protected]) <- unlist(unname(object2.names[rownames([email protected])]))
}
merged.raw.data <- RowMergeSparseMatrices([email protected][,[email protected]], [email protected][,[email protected]])
new.object <- new("seurat", raw.data = merged.raw.data)
project = set.ifnull(project, [email protected])
[email protected]$cell.name <- rownames([email protected])
[email protected]$cell.name <- rownames([email protected])
merged.meta.data <- suppressMessages(suppressWarnings(full_join([email protected], [email protected])))
merged.object <- Setup(new.object, project = project, min.cells = min.cells, min.genes = min.genes, is.expr = is.expr, do.logNormalize = do.logNormalize,
total.expr = total.expr, do.scale = do.scale, do.center = do.center, names.field = names.field,
names.delim = names.delim, save.raw = save.raw)
merged.meta.data %>% filter(cell.name %in% [email protected]) -> merged.meta.data
rownames(merged.meta.data)[email protected]
merged.meta.data$cell.name <- NULL
[email protected] <- merged.meta.data
return(merged.object)
}
)
# Internal function for merging two matrices by rowname
RowMergeSparseMatrices <- function(mat1, mat2){
if(class(mat1) == "data.frame"){
mat1 = as.matrix(mat1)
}
if(class(mat2) == "data.frame"){
mat2 = as.matrix(mat2)
}
mat1 <- as(mat1, "RsparseMatrix")
mat2 <- as(mat2, "RsparseMatrix")
mat1.names <- rownames(mat1)
mat2.names <- rownames(mat2)
all.names <- union(mat1.names, mat2.names)
new.mat <- RowMergeMatrices(mat1 = mat1, mat2 = mat2, mat1_rownames = mat1.names, mat2_rownames = mat2.names, all_rownames = all.names)
rownames(new.mat) <- make.unique(all.names)
#colnames(mat2) <- sprintf('%s_2', colnames(mat2))
colnames(new.mat) <- make.unique(c(colnames(mat1), colnames(mat2)))
return(new.mat)
}
#' Classify New Data
#'
#' Classify new data based on the cluster information of the provided object.
#' Random Forests are used as the basis of the classification.
#'
#'
#' @param object Seurat object on which to train the classifier
#' @param classifier Random Forest classifier from BuildRFClassifier. If not provided,
#' it will be built from the training data provided.
#' @param training.genes Vector of genes to build the classifier on
#' @param training.classes Vector of classes to build the classifier on
#' @param new.data New data to classify
#' @param ... additional parameters passed to ranger
#' @return Vector of cluster ids
#' @import Matrix
#' @importFrom ranger ranger
#' @importFrom plyr mapvalues
#' @export
setGeneric("ClassifyCells", function(object, classifier, training.genes = NULL, training.classes = NULL, new.data = NULL, ... ) standardGeneric("ClassifyCells"))
#' @export
setMethod("ClassifyCells", "seurat",
function(object, classifier, training.genes = NULL, training.classes = NULL, new.data = NULL, ...) {
# build the classifier
if (missing(classifier)){
classifier <- BuildRFClassifier(object, training.genes = training.genes, training.classes = training.classes,...)
}
# run the classifier on the new data
features <- classifier$forest$independent.variable.names
genes.to.add <- setdiff(features, rownames(new.data))
data.to.add <- matrix(0, nrow = length(genes.to.add), ncol = ncol(new.data))
rownames(data.to.add) <- genes.to.add
new.data <- rbind(new.data, data.to.add)
new.data <- new.data[features, ]
new.data <- as.matrix(t(new.data))
print("Running Classifier ...")
prediction <- predict(classifier, new.data)
new.classes <- prediction$predictions
return(new.classes)
}
)
#' Build Random Forest Classifier
#'
#' Train the random forest classifier
#'
#'
#' @param object Seurat object on which to train the classifier
#' @param training.genes Vector of genes to build the classifier on
#' @param training.classes Vector of classes to build the classifier on
#' @param verbose Additional progress print statements
#' @param ... additional parameters passed to ranger
#' @return Returns the random forest classifier
#' @import Matrix
#' @importFrom ranger ranger
#' @importFrom plyr mapvalues
#' @export
setGeneric("BuildRFClassifier", function(object, training.genes = NULL, training.classes = NULL, verbose = TRUE, ... ) standardGeneric("BuildRFClassifier"))
#' @export
setMethod("BuildRFClassifier", "seurat",
function(object, training.genes = NULL, training.classes = NULL, verbose = TRUE, ...) {
training.classes <- as.vector(training.classes)
training.genes <- set.ifnull(training.genes, rownames(object@data))
training.data <- as.data.frame(as.matrix(t(object@data[training.genes, ])))
training.data$class <- factor(training.classes)
if (verbose) print("Training Classifier ...")
classifier <- ranger(data = training.data, dependent.variable.name = "class", classification = T,
write.forest = T, ...)
return(classifier)
}
)
#' Highlight classification results
#'
#' This function is useful to view where proportionally the clusters returned from
#' classification map to the clusters present in the given object. Utilizes the FeaturePlot()
#' function to color clusters in object.
#'
#'
#' @param object Seurat object on which the classifier was trained and
#' onto which the classification results will be highlighted
#' @param clusters vector of cluster ids (output of ClassifyCells)
#' @param ... additional parameters to pass to FeaturePlot()
#' @return Returns a feature plot with clusters highlighted by proportion of cells
#' mapping to that cluster
#' @export
setGeneric("VizClassification", function(object, clusters, ... ) standardGeneric("VizClassification"))
#' @export
setMethod("VizClassification", "seurat",
function(object, clusters, ...) {
cluster.dist <- prop.table(table(out))
[email protected]$Classification <- numeric(nrow([email protected]))
for (cluster in 1:length(cluster.dist)) {
cells.to.highlight <- WhichCells(object, names(cluster.dist[cluster]))
if(length(cells.to.highlight) > 0){
[email protected][cells.to.highlight, ]$Classification <- cluster.dist[cluster]
}
}
if(any(grepl("cols.use", deparse(match.call())))){
return(FeaturePlot(object, "Classification", ...))
}
cols.use = c("#f6f6f6", "black")
return(FeaturePlot(object, "Classification", cols.use = cols.use, ...))
}
)
calc.drop.prob=function(x,a,b) {
return(exp(a+b*x)/(1+exp(a+b*x)))
}
#' 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 variable genes (object@@var.genes)
#' @param thresh.use 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, 2011, 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 min.cells Minimum number of cells expressing the gene in at least one of the two groups
#' @return Returns a dataframe with a ranked list of putative markers for each node and associated statistics
#' @importFrom ape drop.tip
#' @export
setGeneric("FindAllMarkersNode", function(object, node = NULL, genes.use=NULL,thresh.use=0.25,test.use="bimod",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 = 3) standardGeneric("FindAllMarkersNode"))
setMethod("FindAllMarkersNode","seurat",
function(object, node = NULL, genes.use=NULL,thresh.use=0.25,test.use="bimod",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 = 3) {
genes.use <- set.ifnull(genes.use, rownames(object@data))
node <- set.ifnull(node, tree$edge[1,1])
ident.use <- object@ident
tree.use <- [email protected][[1]]
descendants = DFT(tree.use, node, path = NULL, include.children = T)
all.children <- sort(tree.use$edge[,2][!tree.use$edge[,2] %in% tree.use$edge[,1]])
descendants <- suppressMessages(mapvalues(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, i, tree.use = tree.use, genes.use = genes.use, thresh.use = thresh.use, 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 = min.cells)
if (do.print) print(paste("Calculating node", i))
}
gde.all=data.frame()
for(i in ((tree.use$Nnode+2):max(tree.use$edge))) {
gde=genes.de[[i]]
if (is.null(gde)) next;
if (nrow(gde)>0) {
if (test.use=="roc") gde=subset(gde,(myAUC>return.thresh|myAUC<(1-return.thresh)))
if ((test.use=="bimod")||(test.use=="t")) {
gde=gde[order(gde$p_val,-gde$avg_diff),]
gde=subset(gde,p_val<return.thresh)
}
if (nrow(gde)>0) gde$cluster=i; gde$gene=rownames(gde)
if (nrow(gde)>0) gde.all=rbind(gde.all,gde)
}
}
gde.all$cluster <- mapvalues(gde.all$cluster, from = new.nodes, to = orig.nodes)
return(gde.all)
}
)
weighted.euclidean=function(x,y,w) {
v.dist=sum(sqrt(w*(x-y)^2))
return(v.dist)
}
#from Jean Fan - thanks!!
custom.dist <- function(my.mat, my.function,...) {
n <- ncol(my.mat)
mat <- matrix(0, ncol = n, nrow = n)
colnames(mat) <- rownames(mat) <- colnames(my.mat)
for(i in 1:nrow(mat)) {
for(j in 1:ncol(mat)) {
mat[i,j] <- my.function(my.mat[,i],my.mat[,j],...)
}}
return(as.dist(mat))
}
#' Phylogenetic Analysis of Identity Classes
#'
#' Constructs a phylogenetic tree relating the 'average' cell from each
#' identity class. Tree is estimated based on a distance matrix constructed in
#' either gene expression space or PCA space.
#'
#' Note that the tree is calculated for an 'average' cell, so gene expression
#' or PC scores are averaged across all cells in an identity class before the
#' tree is constructed.
#'
#' @param object Seurat object
#' @param genes.use Genes to use for the analysis. Default is the set of
#' variable genes (object@@var.genes). Assumes pcs.use=NULL (tree calculated in
#' gene expression space)
#' @param pcs.use If set, tree is calculated in PCA space, using the
#' eigenvalue-weighted euclidean distance across these PC scores.
#' @param SNN.use If SNN is passed, build tree based on SNN graph connectivity between clusters
#' @param do.plot Plot the resulting phylogenetic tree
#' @param do.reorder Re-order identity classes (factor ordering), according to
#' position on the tree. This groups similar classes together which can be
#' helpful, for example, when drawing violin plots.
#' @param reorder.numeric Re-order identity classes according to position on
#' the tree, assigning a numeric value ('1' is the leftmost node)
#' @return A Seurat object where the cluster tree is stored in
#' object@@cluster.tree[[1]]
#' @importFrom ape as.phylo
#' @export
setGeneric("BuildClusterTree", function(object, genes.use=NULL,pcs.use=NULL, SNN.use=NULL, do.plot=TRUE,do.reorder=FALSE,reorder.numeric=FALSE) standardGeneric("BuildClusterTree"))
#' @export
setMethod("BuildClusterTree","seurat",
function(object,genes.use=NULL,pcs.use=NULL, SNN.use=NULL, do.plot=TRUE,do.reorder=FALSE,reorder.numeric=FALSE) {
genes.use=set.ifnull(genes.use,[email protected])
ident.names=as.character(unique(object@ident))
if (!is.null(genes.use)) {
genes.use=ainb(genes.use,rownames(object@data))
data.avg=AverageExpression(object,genes.use = genes.use)
data.dist=dist(t(data.avg[genes.use,]))
}
if (!is.null(pcs.use)) {
data.pca=AveragePCA(object)
data.use=data.pca[pcs.use,]
if (is.null([email protected][[1]]$sdev)) data.eigenval=([email protected][[1]]$d)^2
else data.eigenval=([email protected][[1]]$sdev)^2
data.weights=(data.eigenval/sum(data.eigenval))[pcs.use]; data.weights=data.weights/sum(data.weights)
data.dist=custom.dist(data.pca[pcs.use,],weighted.euclidean,data.weights)
}
if(!is.null(SNN.use)){
num_clusters = length(ident.names)
data.dist = matrix(0, nrow=num_clusters, ncol= num_clusters)
for (i in 1:num_clusters-1){
for (j in (i+1):num_clusters){
subSNN = SNN.use[match(WhichCells(object, i), colnames(SNN.use)), match(WhichCells(object, j), rownames(SNN.use))]
d = mean(subSNN)
if(is.na(d)) data.dist[i,j] = 0
else data.dist[i,j] = d
}
}
diag(data.dist)=1
data.dist=dist(data.dist)
}
data.tree=as.phylo(hclust(data.dist))
[email protected][[1]]=data.tree
if (do.reorder) {
old.ident.order=sort(unique(object@ident))
[email protected][[1]]
all.desc=getDescendants(data.tree,data.tree$Nnode+2); all.desc=old.ident.order[all.desc[all.desc<=(data.tree$Nnode+1)]]
object@ident=factor(object@ident,levels = all.desc,ordered = TRUE)
if (reorder.numeric) {
object=SetIdent(object,[email protected],as.integer(object@ident))
[email protected][[email protected],"tree.ident"]=as.integer(object@ident)
}
object=BuildClusterTree(object,genes.use,pcs.use,do.plot=FALSE,do.reorder=FALSE)
}
if (do.plot) PlotClusterTree(object)
return(object)
}
)
#' Plot phylogenetic tree
#'
#' Plots previously computed phylogenetic tree (from BuildClusterTree)
#'
#' @param object Seurat object
#' @param \dots Additional arguments for plotting the phylogeny
#' @return Plots dendogram (must be precomputed using BuildClusterTree), returns no value
#' @importFrom ape plot.phylo
#' @importFrom ape nodelabels
#' @export
setGeneric("PlotClusterTree", function(object,...) standardGeneric("PlotClusterTree"))
#' @export
setMethod("PlotClusterTree","seurat",
function(object,...) {
if (length([email protected])==0) stop("Phylogenetic tree does not exist, build using BuildClusterTree")
[email protected][[1]]
plot.phylo(data.tree,direction="downwards",...)
nodelabels()
}
)
#' Visualize expression/dropout curve
#'
#' Plot the probability of detection vs average expression of a gene.
#'
#' Assumes that this 'noise' model has been precomputed with CalcNoiseModels
#'
#'
#' @param object Seurat object
#' @param cell.ids Cells to use
#' @param col.use Color code or name
#' @param lwd.use Line width for curve
#' @param do.new Create a new plot (default) or add to existing
#' @param x.lim Maximum value for X axis
#' @param \dots Additional arguments to pass to lines function
#' @return Returns no value, displays a plot
#' @export
setGeneric("PlotNoiseModel", function(object, cell.ids=c(1,2), col.use="black",lwd.use=2,do.new=TRUE,x.lim=10,...) standardGeneric("PlotNoiseModel"))
#' @export
setMethod("PlotNoiseModel","seurat",
function(object, cell.ids=c(1,2), col.use="black",lwd.use=2,do.new=TRUE,x.lim=10,...) {
[email protected][cell.ids,]
if (do.new) plot(1,1,pch=16,type="n",xlab="Average expression",ylab="Probability of detection",xlim=c(0,x.lim),ylim=c(0,1))
unlist(lapply(1:length(cell.ids), function(y) {
x.vals=seq(0,x.lim,0.05)
y.vals=unlist(lapply(x.vals,calc.drop.prob,cell.coefs[y,1],cell.coefs[y,2]))
lines(x.vals,y.vals,lwd=lwd.use,col=col.use,...)
}))
}
)
#' Regress out technical effects and cell cycle
#'
#' Remove unwanted effects from scale.data
#'
#'
#' @param object Seurat object
#' @param latent.vars effects to regress out
#' @param genes.regress gene to run regression for (default is all genes)
#' @param model.use Use a linear model or generalized linear model (poisson, negative binomial) for the regression. Options are 'linear' (default), 'poisson', and 'negbinom'
#' @param use.umi Regress on UMI count data. Default is FALSE for linear modeling, but automatically set to TRUE if model.use is 'negbinom' or 'poisson'
#' @param do.scale Whether to scale the data.
#' @param do.center Whether to center the data.
#' @param scale.max Max value to accept for scaled data. The default is 10. Setting this can help
#' reduce the effects of genes that are only expressed in a very small number of cells.
#' @return Returns Seurat object with the scale.data ([email protected]) genes returning the residuals from the regression model
#' @import Matrix
#' @export
setGeneric("RegressOut", function(object,latent.vars,genes.regress=NULL, model.use="linear", use.umi=F, do.scale = T, do.center = T, scale.max = 10) standardGeneric("RegressOut"))
#' @export
setMethod("RegressOut", "seurat",
function(object,latent.vars,genes.regress=NULL, model.use="linear", use.umi=F, do.scale = T, do.center = T, scale.max = 10) {
genes.regress=set.ifnull(genes.regress,rownames(object@data))
genes.regress=ainb(genes.regress,rownames(object@data))
latent.data=FetchData(object,latent.vars)
bin.size <- 100;
if (model.use=="negbinom") bin.size=5;
bin.ind <- ceiling(1:length(genes.regress)/bin.size)
max.bin <- max(bin.ind)
print(paste("Regressing out",latent.vars))
pb <- txtProgressBar(min = 0, max = max.bin, style = 3)
data.resid=c()
data.use=object@data[genes.regress, , drop=FALSE];
if (model.use != "linear") {
use.umi=T
}
if (use.umi) [email protected][genes.regress,[email protected], drop=FALSE]
for(i in 1:max.bin) {
genes.bin.regress <- rownames(data.use)[bin.ind == i]
gene.expr <- as.matrix(data.use[genes.bin.regress, , drop=FALSE])
new.data <- do.call(rbind, lapply(genes.bin.regress, function(x) {
regression.mat = cbind(latent.data, gene.expr[x,])
colnames(regression.mat) <- c(colnames(latent.data), "GENE")
fmla=as.formula(paste("GENE ", " ~ ", paste(latent.vars,collapse="+"),sep=""));
if (model.use=="linear") return(lm(fmla,data = regression.mat)$residuals)
if (model.use=="poisson") return(residuals(glm(fmla,data = regression.mat,family = "poisson"), type='pearson'))
if (model.use=="negbinom") return(nb.residuals(fmla, regression.mat, x))
}))
if (i==1) data.resid=new.data
if (i>1) data.resid=rbind(data.resid,new.data)
setTxtProgressBar(pb, i)
}
close(pb)
rownames(data.resid) <- genes.regress
if (use.umi) {
data.resid=log1p(sweep(data.resid,MARGIN = 1,apply(data.resid,1,min),"-"))
}
[email protected]=data.resid
if (do.scale==TRUE) {
if(use.umi && missing(scale.max)){
scale.max <- 50
}
object=ScaleData(object,genes.use = rownames(data.resid), data.use = data.resid, do.center = do.center, do.scale = do.scale, scale.max = scale.max)
}
[email protected][is.na([email protected])]=0
return(object)
}
)
#' Return a subset of the Seurat object
#'
#' Creates a Seurat object containing only a subset of the cells in the
#' original object. Takes either a list of cells to use as a subset, or a
#' parameter (for example, a gene), to subset on.
#'
#' @param object Seurat object
#' @param cells.use A vector of cell names to use as a subset. If NULL
#' (default), then this list will be computed based on the next three
#' arguments. Otherwise, will return an object consissting only of these cells
#' @param subset.name Parameter to subset on. Eg, the name of a gene, PC1, a
#' column name in object@@data.info, etc. Any argument that can be retreived
#' using FetchData
#' @param ident.use Create a cell subset based on the provided identity classes
#' @param accept.low Low cutoff for the parameter (default is -Inf)
#' @param accept.high High cutoff for the parameter (default is Inf)
#' @param do.center Recenter the new object@@scale.data
#' @param do.scale Rescale the new object@@scale.data. FALSE by default
#' @param max.cells.per.ident Can be used to downsample the data to a certain max per cell ident. Default is inf.
#' @param random.seed Random seed for downsampling
#' @param \dots Additional arguments to be passed to FetchData (for example,
#' use.imputed=TRUE)
#' @return Returns a Seurat object containing only the relevant subset of cells
#' @export
setGeneric("SubsetData", function(object,cells.use=NULL,subset.name=NULL,ident.use=NULL,accept.low=-Inf, accept.high=Inf,do.center=F,do.scale=F,max.cells.per.ident=Inf, random.seed = 1,...) standardGeneric("SubsetData"))
#' @export
setMethod("SubsetData","seurat",
function(object,cells.use=NULL,subset.name=NULL,ident.use=NULL,accept.low=-Inf, accept.high=Inf,do.center=F,do.scale=F,max.cells.per.ident=Inf, random.seed = 1,...) {
data.use=NULL
cells.use=set.ifnull(cells.use,[email protected])
if (!is.null(ident.use)) {
cells.use=WhichCells(object,ident.use)
}
if (!is.null(subset.name)) {
data.use=FetchData(object,subset.name,...)
if (length(data.use)==0) return(object)
subset.data=data.use[,subset.name]
pass.inds=which((subset.data>accept.low) & (subset.data<accept.high))
cells.use=rownames(data.use)[pass.inds]
}
cells.use=ainb(cells.use,[email protected])
cells.use = WhichCells(object, cells.use = cells.use, max.cells.per.ident = max.cells.per.ident, random.seed = random.seed)
object@data=object@data[,cells.use]
if(!(is.null([email protected]))) {
if (length(colnames([email protected])>0)) {
[email protected][,cells.use]
}
}
if (do.scale) {
object=ScaleData(object,do.scale = do.scale,do.center = do.center)