forked from satijalab/seurat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobjects.R
5792 lines (5630 loc) · 178 KB
/
objects.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
#' @importFrom Rcpp evalCpp
#' @importFrom Matrix colSums rowSums colMeans rowMeans
#' @importFrom methods setClass setOldClass setClassUnion slot
#' slot<- setMethod new signature slotNames is
#' @importClassesFrom Matrix dgCMatrix
#' @useDynLib Seurat
#'
NULL
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Class definitions
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
setOldClass(Classes = 'package_version')
setClassUnion(name = 'AnyMatrix', c("matrix", "dgCMatrix"))
#' The AnchorSet Class
#'
#' The AnchorSet class is an intermediate data storage class that stores the anchors and other
#' related information needed for performing downstream analyses - namely data integration
#' (\code{\link{IntegrateData}}) and data transfer (\code{\link{TransferData}}).
#'
#' @slot object.list List of objects used to create anchors
#' @slot reference.cells List of cell names in the reference dataset - needed when performing data
#' transfer.
#' @slot query.cells List of cell names in the query dataset - needed when performing data transfer
#' @slot anchors The anchor matrix. This contains the cell indices of both anchor pair cells, the
#' anchor score, and the index of the original dataset in the object.list for cell1 and cell2 of
#' the anchor.
#' @slot offsets The offsets used to enable cell look up in downstream functions
#' @slot anchor.features The features used when performing anchor finding.
#' @slot command Store log of parameters that were used
#'
#' @name AnchorSet-class
#' @rdname AnchorSet-class
#' @exportClass AnchorSet
#'
AnchorSet <- setClass(
Class = "AnchorSet",
slots = list(
object.list = "list",
reference.cells = "vector",
query.cells = "vector",
anchors = "ANY",
offsets = "ANY",
anchor.features = "ANY",
command = "ANY"
)
)
#' The Assay Class
#'
#' The Assay object is the basic unit of Seurat; each Assay stores raw, normalized, and scaled data
#' as well as cluster information, variable features, and any other assay-specific metadata.
#' Assays should contain single cell expression data such as RNA-seq, protein, or imputed expression
#' data.
#'
#' @slot counts Unnormalized data such as raw counts or TPMs
#' @slot data Normalized expression data
#' @slot scale.data Scaled expression data
#' @slot key Key for the Assay
#' @slot var.features Vector of features exhibiting high variance across single cells
#' @slot meta.features Feature-level metadata
#' @slot misc Utility slot for storing additional data associated with the assay
#'
#' @name Assay-class
#' @rdname Assay-class
#' @exportClass Assay
#'
Assay <- setClass(
Class = 'Assay',
slots = c(
counts = 'AnyMatrix',
data = 'AnyMatrix',
scale.data = 'matrix',
key = 'character',
var.features = 'vector',
meta.features = 'data.frame',
misc = 'ANY'
)
)
#' The JackStrawData Class
#'
#' The JackStrawData is used to store the results of a JackStraw computation.
#'
#' @slot empirical.p.values Empirical p-values
#' @slot fake.reduction.scores Fake reduction scores
#' @slot empirical.p.values.full Empirical p-values on full
#' @slot overall.p.values Overall p-values from ScoreJackStraw
#'
#' @name JackStrawData-class
#' @rdname JackStrawData-class
#' @exportClass JackStrawData
#'
JackStrawData <- setClass(
Class = "JackStrawData",
slots = list(
empirical.p.values = "matrix",
fake.reduction.scores = "matrix",
empirical.p.values.full = "matrix",
overall.p.values = "matrix"
)
)
#' The Dimmensional Reduction Class
#'
#' The DimReduc object stores a dimensionality reduction taken out in Seurat; each DimReduc
#' consists of a cell embeddings matrix, a feature loadings matrix, and a projected feature
#' loadings matrix.
#'
#' @slot cell.embeddings Cell embeddings matrix (required)
#' @slot feature.loadings Feature loadings matrix (optional)
#' @slot feature.loadings.projected Projected feature loadings matrix (optional)
#' @slot assay.used Name of assay used to generate DimReduc object
#' @slot stdev A vector of standard deviations
#' @slot key Key for the DimReduc, must be alphanumerics followed by an underscore
#' @slot jackstraw A \code{\link{JackStrawData-class}} object associated with this DimReduc
#' @slot misc Utility slot for storing additional data associated with the DimReduc
#' (e.g. the total variance of the PCA)
#'
#' @name DimReduc-class
#' @rdname DimReduc-class
#' @exportClass DimReduc
#'
DimReduc <- setClass(
Class = 'DimReduc',
slots = c(
cell.embeddings = 'matrix',
feature.loadings = 'matrix',
feature.loadings.projected = 'matrix',
assay.used = 'character',
stdev = 'numeric',
key = 'character',
jackstraw = 'JackStrawData',
misc = 'list'
)
)
#' The Graph Class
#'
#' The Graph class simply inherits from dgCMatrix. We do this to enable future expandability of graphs.
#'
#' @name Graph-class
#' @rdname Graph-class
#' @exportClass Graph
#'
#' @seealso \code{\link[Matrix]{dgCMatrix-class}}
#'
Graph <- setClass(
Class = 'Graph',
contains = "dgCMatrix"
)
#' The IntegrationData Class
#'
#' The IntegrationData object is an intermediate storage container used internally throughout the
#' integration procedure to hold bits of data that are useful downstream.
#'
#' @slot neighbors List of neighborhood information for cells (outputs of \code{RANN::nn2})
#' @slot weights Anchor weight matrix
#' @slot integration.matrix Integration matrix
#' @slot anchors Anchor matrix
#' @slot offsets The offsets used to enable cell look up in downstream functions
#' @slot objects.ncell Number of cells in each object in the object.list
#' @slot sample.tree Sample tree used for ordering multi-dataset integration
#'
#' @name IntegrationData-class
#' @rdname IntegrationData-class
#' @exportClass IntegrationData
#'
IntegrationData <- setClass(
Class = "IntegrationData",
slots = list(
neighbors = "ANY",
weights = "ANY",
integration.matrix = "ANY",
anchors = "ANY",
offsets = "ANY",
objects.ncell = "ANY",
sample.tree = "ANY"
)
)
#' The SeuratCommand Class
#'
#' The SeuratCommand is used for logging commands that are run on a SeuratObject. It stores parameters and timestamps
#'
#' @slot name Command name
#' @slot time.stamp Timestamp of when command was tun
#' @slot call.string String of the command call
#' @slot params List of parameters used in the command call
#'
#' @name SeuratCommand-class
#' @name SeuratCommand-class
#' @exportClass SeuratCommand
#'
SeuratCommand <- setClass(
Class = 'SeuratCommand',
slots = c(
name = 'character',
time.stamp = 'POSIXct',
call.string = 'character',
params = 'ANY'
)
)
#' The Seurat Class
#'
#' The Seurat object is a representation of single-cell expression data for R; each Seurat
#' object revolves around a set of cells and consists of one or more \code{\link{Assay-class}}
#' objects, or individual representations of expression data (eg. RNA-seq, ATAC-seq, etc).
#' These assays can be reduced from their high-dimensional state to a lower-dimension state
#' and stored as \code{\link{DimReduc-class}} objects. Seurat objects also store additional
#' meta data, both at the cell and feature level (contained within individual assays). The
#' object was designed to be as self-contained as possible, and easily extendible to new methods.
#'
#' @slot assays A list of assays for this project
#' @slot meta.data Contains meta-information about each cell, starting with number of genes detected (nGene)
#' and the original identity class (orig.ident); more information is added using \code{AddMetaData}
#' @slot active.assay Name of the active, or default, assay; settable using \code{\link{DefaultAssay}}
#' @slot active.ident The active cluster identity for this Seurat object; settable using \code{\link{Idents}}
#' @slot graphs A list of \code{\link{Graph-class}} objects
#' @slot neighbors ...
#' @slot reductions A list of dimmensional reduction objects for this object
#' @slot project.name Name of the project
#' @slot misc A list of miscellaneous information
#' @slot version Version of Seurat this object was built under
#' @slot commands A list of logged commands run on this \code{Seurat} object
#' @slot tools A list of miscellaneous data generated by other tools, should be filled by developers only using \code{\link{Tool}<-}
#'
#' @name Seurat-class
#' @rdname Seurat-class
#' @exportClass Seurat
#'
Seurat <- setClass(
Class = 'Seurat',
slots = c(
assays = 'list',
meta.data = 'data.frame',
active.assay = 'character',
active.ident = 'factor',
graphs = 'list',
neighbors = 'list',
reductions = 'list',
project.name = 'character',
misc = 'list',
version = 'package_version',
commands = 'list',
tools = 'list'
)
)
#' 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.
#'
#' @slot raw.data The raw project data
#' @slot data The normalized expression matrix (log-scale)
#' @slot scale.data scaled (default is z-scoring each gene) expression matrix; used for dimmensional reduction and heatmap visualization
#' @slot var.genes Vector of genes exhibiting high variance across single cells
#' @slot is.expr Expression threshold to determine if a gene is expressed (0 by default)
#' @slot ident THe 'identity class' for each cell
#' @slot meta.data Contains meta-information about each cell, starting with number of genes detected (nGene)
#' and the original identity class (orig.ident); more information is added using \code{AddMetaData}
#' @slot project.name Name of the project (for record keeping)
#' @slot dr List of stored dimmensional reductions; named by technique
#' @slot assay List of additional assays for multimodal analysis; named by technique
#' @slot hvg.info The output of the mean/variability analysis for all genes
#' @slot imputed Matrix of imputed gene scores
#' @slot cell.names Names of all single cells (column names of the expression matrix)
#' @slot cluster.tree List where the first element is a phylo object containing the phylogenetic tree relating different identity classes
#' @slot snn Spare matrix object representation of the SNN graph
#' @slot calc.params Named list to store all calculation-related parameter choices
#' @slot kmeans Stores output of gene-based clustering from \code{DoKMeans}
#' @slot spatial Stores internal data and calculations for spatial mapping of single cells
#' @slot misc Miscellaneous spot to store any data alongisde the object (for example, gene lists)
#' @slot version Version of package used in object creation
#'
#' @name seurat-class
#' @rdname oldseurat-class
#' @aliases seurat-class
#'
seurat <- setClass(
Class = "seurat",
slots = c(
raw.data = "ANY",
data = "ANY",
scale.data = "ANY",
var.genes = "vector",
is.expr = "numeric",
ident = "factor",
meta.data = "data.frame",
project.name = "character",
dr = "list",
assay = "list",
hvg.info = "data.frame",
imputed = "data.frame",
cell.names = "vector",
cluster.tree = "list",
snn = "dgCMatrix",
calc.params = "list",
kmeans = "ANY",
spatial = "ANY",
misc = "ANY",
version = "ANY"
)
)
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Functions
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#' Create an Assay object
#'
#' Create an Assay object from a feature (e.g. gene) expression matrix. The
#' expected format of the input matrix is features x cells.
#'
#' Non-unique cell or feature names are not allowed. Please make unique before
#' calling this function.
#'
#' @param counts Unnormalized data such as raw counts or TPMs
#' @param data Prenormalized data; if provided, do not pass \code{counts}
#' @param min.cells Include features detected in at least this many cells. Will
#' subset the counts matrix as well. To reintroduce excluded features, create a
#' new object with a lower cutoff.
#' @param min.features Include cells where at least this many features are
#' detected.
#'
#' @importFrom methods as
#' @importFrom Matrix colSums rowSums
#'
#' @export
#'
#' @examples
#' pbmc_raw <- read.table(
#' file = system.file('extdata', 'pbmc_raw.txt', package = 'Seurat'),
#' as.is = TRUE
#' )
#' pbmc_rna <- CreateAssayObject(counts = pbmc_raw)
#' pbmc_rna
#'
CreateAssayObject <- function(
counts,
data,
min.cells = 0,
min.features = 0
) {
if (missing(x = counts) && missing(x = data)) {
stop("Must provide either 'counts' or 'data'")
} else if (!missing(x = counts) && !missing(x = data)) {
stop("Either 'counts' or 'data' must be missing; both cannot be provided")
} else if (!missing(x = counts)) {
# check that dimnames of input counts are unique
if (anyDuplicated(rownames(x = counts))) {
warning(
"Non-unique features (rownames) present in the input matrix, making unique",
call. = FALSE,
immediate. = TRUE
)
rownames(x = counts) <- make.unique(names = rownames(x = counts))
}
if (anyDuplicated(colnames(x = counts))) {
warning(
"Non-unique cell names (colnames) present in the input matrix, making unique",
call. = FALSE,
immediate. = TRUE
)
colnames(x = counts) <- make.unique(names = colnames(x = counts))
}
if (is.null(x = colnames(x = counts))) {
stop("No cell names (colnames) names present in the input matrix")
}
if (nrow(x = counts) > 0 && is.null(x = rownames(x = counts))) {
stop("No feature names (rownames) names present in the input matrix")
}
if (!inherits(x = counts, what = 'dgCMatrix')) {
counts <- as(object = as.matrix(x = counts), Class = 'dgCMatrix')
}
# Filter based on min.features
if (min.features > 0) {
nfeatures <- Matrix::colSums(x = counts > 0)
counts <- counts[, which(x = nfeatures >= min.features)]
}
# filter genes on the number of cells expressing
if (min.cells > 0) {
num.cells <- Matrix::rowSums(x = counts > 0)
counts <- counts[which(x = num.cells >= min.cells), ]
}
data <- counts
} else if (!missing(x = data)) {
# check that dimnames of input data are unique
if (anyDuplicated(rownames(x = data))) {
warning(
"Non-unique features (rownames) present in the input matrix, making unique",
call. = FALSE,
immediate. = TRUE
)
rownames(x = data) <- make.unique(names = rownames(x = data))
}
if (anyDuplicated(colnames(x = data))) {
warning(
"Non-unique cell names (colnames) present in the input matrix, making unique",
call. = FALSE,
immediate. = TRUE
)
colnames(x = data) <- make.unique(names = colnames(x = data))
}
if (is.null(x = colnames(x = data))) {
stop("No cell names (colnames) names present in the input matrix")
}
if (nrow(x = data) > 0 && is.null(x = rownames(x = data))) {
stop("No feature names (rownames) names present in the input matrix")
}
if (min.cells != 0 | min.features != 0) {
warning(
"No filtering performed if passing to data rather than counts",
call. = FALSE,
immediate. = TRUE
)
}
counts <- new(Class = 'matrix')
}
if (any(grepl(pattern = '_', x = rownames(x = counts))) || any(grepl(pattern = '_', x = rownames(x = data)))) {
warning(
"Feature names cannot have underscores ('_'), replacing with dashes ('-')",
call. = FALSE,
immediate. = TRUE
)
rownames(x = counts) <- gsub(
pattern = '_',
replacement = '-',
x = rownames(x = counts)
)
rownames(x = data) <- gsub(
pattern = '_',
replacement = '-',
x = rownames(x = data)
)
}
# Initialize meta.features
init.meta.features <- data.frame(row.names = rownames(x = data))
assay <- new(
Class = 'Assay',
counts = counts,
data = data,
scale.data = new(Class = 'matrix'),
meta.features = init.meta.features
)
return(assay)
}
#' Create a DimReduc object
#'
#' @param embeddings A matrix with the cell embeddings
#' @param loadings A matrix with the feature loadings
#' @param projected A matrix with the projected feature loadings
#' @param assay Assay used to calculate this dimensional reduction
#' @param stdev Standard deviation (if applicable) for the dimensional reduction
#' @param key A character string to facilitate looking up features from a
#' specific DimReduc
#' @param jackstraw Results from the JackStraw function
#' @param misc list for the user to store any additional information associated
#' with the dimensional reduction
#'
#' @aliases SetDimReduction
#'
#' @export
#'
#' @examples
#' data <- GetAssayData(pbmc_small[["RNA"]], slot = "scale.data")
#' pcs <- prcomp(x = data)
#' pca.dr <- CreateDimReducObject(
#' embeddings = pcs$rotation,
#' loadings = pcs$x,
#' stdev = pcs$sdev,
#' key = "PC",
#' assay = "RNA"
#' )
#'
CreateDimReducObject <- function(
embeddings = new(Class = 'matrix'),
loadings = new(Class = 'matrix'),
projected = new(Class = 'matrix'),
assay = NULL,
stdev = numeric(),
key = NULL,
jackstraw = NULL,
misc = list()
) {
if (is.null(x = assay)) {
warning(
"No assay specified, setting assay as RNA by default.",
call. = FALSE,
immediate. = TRUE
)
assay <- "RNA"
}
# Try to infer key from column names
if (is.null(x = key) && is.null(x = colnames(x = embeddings))) {
stop("Please specify a key for the DimReduc object")
} else if (is.null(x = key)) {
key <- regmatches(
x = colnames(x = embeddings),
m = regexec(pattern = '^[[:alnum:]]+_', text = colnames(x = embeddings))
)
key <- unique(x = unlist(x = key, use.names = FALSE))
}
if (length(x = key) != 1) {
stop("Please specify a key for the DimReduc object")
} else if (!grepl(pattern = '^[[:alnum:]]+_$', x = key)) {
# New SetKey function
key <- regmatches(
x = key,
m = regexec(pattern = '[[:alnum:]]+', text = key)
)
key <- paste0(paste(key, collapse = ''), '_')
warning(
"All keys should be one or more alphanumeric characters followed by an underscore '_', setting key to ",
key,
call. = FALSE,
immediate. = TRUE
)
}
# ensure colnames of the embeddings are the key followed by a numeric
if (is.null(x = colnames(x = embeddings))) {
warning(
"No columnames present in cell embeddings, setting to '",
key,
"1:",
ncol(x = embeddings),
"'",
call. = FALSE,
immediate. = TRUE
)
colnames(x = embeddings) <- paste0(key, 1:ncol(x = embeddings))
} else if (!all(grepl(pattern = paste0('^', key, "[[:digit:]]+$"), x = colnames(x = embeddings)))) {
digits <- unlist(x = regmatches(
x = colnames(x = embeddings),
m = regexec(pattern = '[[:digit:]]+$', text = colnames(x = embeddings))
))
if (length(x = digits) != ncol(x = embeddings)) {
stop("Please ensure all column names in the embeddings matrix are the key plus a digit representing a dimension number")
}
colnames(x = embeddings) <- paste0(key, digits)
}
if (!IsMatrixEmpty(x = loadings)) {
colnames(x = loadings) <- colnames(x = embeddings)
}
if (!IsMatrixEmpty(x = projected)) {
colnames(x = projected) <- colnames(x = embeddings)
}
jackstraw <- jackstraw %||% new(Class = 'JackStrawData')
dim.reduc <- new(
Class = 'DimReduc',
cell.embeddings = embeddings,
feature.loadings = loadings,
feature.loadings.projected = projected,
assay.used = assay,
stdev = stdev,
key = key,
jackstraw = jackstraw,
misc = misc
)
return(dim.reduc)
}
#' Create a Seurat object
#'
#' Create a Seurat object from a feature (e.g. gene) expression matrix. The expected format of the
#' input matrix is features x cells.
#'
#'
#' Note: In previous versions (<3.0), this function also accepted a parameter to set the expression
#' threshold for a 'detected' feature (gene). This functionality has been removed to simplify the
#' initialization process/assumptions. If you would still like to impose this threshold for your
#' particular dataset, simply filter the input expression matrix before calling this function.
#'
#' @inheritParams CreateAssayObject
#' @param project Sets the project name for the Seurat object.
#' @param assay Name of the assay corresponding to the initial input data.
#' @param names.field For the initial identity class for each cell, choose this field from the
#' cell's name. E.g. If your cells are named as BARCODE_CLUSTER_CELLTYPE in the input matrix, set
#' names.field to 3 to set the initial identities to CELLTYPE.
#' @param names.delim For the initial identity class for each cell, choose this delimiter from the
#' cell's column name. E.g. If your cells are named as BARCODE-CLUSTER-CELLTYPE, set this to "-" to
#' separate the cell name into its component parts for picking the relevant field.
#' @param meta.data Additional cell-level 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.
#'
#' @importFrom utils packageVersion
#' @importFrom Matrix colSums
#' @export
#'
#' @examples
#' pbmc_raw <- read.table(
#' file = system.file('extdata', 'pbmc_raw.txt', package = 'Seurat'),
#' as.is = TRUE
#' )
#' pbmc_small <- CreateSeuratObject(counts = pbmc_raw)
#' pbmc_small
#'
CreateSeuratObject <- function(
counts,
project = 'SeuratProject',
assay = 'RNA',
min.cells = 0,
min.features = 0,
names.field = 1,
names.delim = "_",
meta.data = NULL
) {
assay.data <- CreateAssayObject(
counts = counts,
min.cells = min.cells,
min.features = min.features
)
Key(object = assay.data) <- paste0(tolower(x = assay), '_')
assay.list <- list(assay.data)
names(x = assay.list) <- assay
init.meta.data <- data.frame(row.names = colnames(x = assay.list[[assay]]))
# Set idents
idents <- factor(x = unlist(x = lapply(
X = colnames(x = assay.data),
FUN = ExtractField,
field = names.field,
delim = names.delim
)))
if (any(is.na(x = idents))) {
warning("Input parameters result in NA values for initial cell identities. Setting all initial idents to the project name")
}
# if there are more than 100 idents, set all idents to ... name
ident.levels <- length(x = unique(x = idents))
if (ident.levels > 100 || ident.levels == 0 || ident.levels == length(x = idents)) {
idents <- rep.int(x = factor(x = project), times = ncol(x = assay.data))
}
names(x = idents) <- colnames(x = assay.data)
object <- new(
Class = 'Seurat',
assays = assay.list,
meta.data = init.meta.data,
active.assay = assay,
active.ident = idents,
project.name = project,
version = packageVersion(pkg = 'Seurat')
)
object[['orig.ident']] <- idents
# Calculate nCount and nFeature
n.calc <- CalcN(object = assay.data)
if (!is.null(x = n.calc)) {
names(x = n.calc) <- paste(names(x = n.calc), assay, sep = '_')
object[[names(x = n.calc)]] <- n.calc
}
if (!is.null(x = meta.data)) {
object <- AddMetaData(object = object, metadata = meta.data)
}
return(object)
}
#' Slim down a Seurat object
#'
#' Keep only certain aspects of the Seurat object. Can be useful in functions that utilize merge as
#' it reduces the amount of data in the merge.
#'
#' @param object Seurat object
#' @param counts Preserve the count matrices for the assays specified
#' @param data Preserve the data slot for the assays specified
#' @param scale.data Preserve the scale.data slot for the assays specified
#' @param features Only keep a subset of features, defaults to all features
#' @param assays Only keep a subset of assays specified here
#'
#' @export
#'
DietSeurat <- function(
object,
counts = TRUE,
data = TRUE,
scale.data = FALSE,
features = NULL,
assays = NULL
) {
assays <- assays %||% FilterObjects(object = object, classes.keep = "Assay")
assays <- assays[assays %in% FilterObjects(object = object, classes.keep = 'Assay')]
if (length(x = assays) == 0) {
stop("No assays provided were found in the Seurat object")
}
if (!DefaultAssay(object = object) %in% assays) {
stop("The default assay is slated to be removed, please change the default assay")
}
if (!counts && !data) {
stop("Either one or both of 'counts' and 'data' must be kept")
}
for (assay in FilterObjects(object = object, classes.keep = 'Assay')) {
if (!(assay %in% assays)) {
object[[assay]] <- NULL
} else {
features.assay <- features %||% rownames(x = object[[assay]])
features.assay <- intersect(x = features.assay, y = rownames(x = object[[assay]]))
if (length(x = features.assay) == 0) {
if (assay == DefaultAssay(object = object)) {
stop("The default assay is slated to be removed, please change the default assay")
} else {
warning("No features found in assay '", assay, "', removing...")
object[[assay]] <- NULL
}
} else {
if (counts) {
slot(object = object[[assay]], name = 'counts') <- slot(object = object[[assay]], name = 'counts')[features.assay, ]
} else {
slot(object = object[[assay]], name = 'counts') <- new(Class = 'matrix')
}
if (data) {
slot(object = object[[assay]], name = 'data') <- slot(object = object[[assay]], name = 'data')[features.assay, ]
} else {
stop('data = FALSE currently not supported')
slot(object = object[[assay]], name = 'data') <- new(Class = 'matrix')
}
features.scaled <- features.assay[features.assay %in% rownames(x = slot(object = object[[assay]], name = 'scale.data'))]
if (scale.data && length(x = features.scaled) > 0) {
slot(object = object[[assay]], name = 'scale.data') <- slot(object = object[[assay]], name = 'scale.data')[features.scaled, ]
} else {
slot(object = object[[assay]], name = 'scale.data') <- new(Class = 'matrix')
}
}
}
}
return(object)
}
#' Access cellular data
#'
#' Retreives data (feature expression, PCA scores, metrics, etc.) for a set
#' of cells in a Seurat object
#'
#' @param object Seurat object
#' @param vars List of all variables to fetch, use keyword 'ident' to pull identity classes
#' @param cells Cells to collect data for (default is all cells)
#' @param slot Slot to pull feature data for
#'
#' @return A data frame with cells as rows and cellular data as columns
#'
#' @export
#'
#' @examples
#' pc1 <- FetchData(object = pbmc_small, vars = 'PC_1')
#' head(x = pc1)
#' head(x = FetchData(object = pbmc_small, vars = c('groups', 'ident')))
#'
FetchData <- function(object, vars, cells = NULL, slot = 'data') {
cells <- cells %||% colnames(x = object)
if (is.numeric(x = cells)) {
cells <- colnames(x = object)[cells]
}
objects.use <- FilterObjects(object = object)
object.keys <- sapply(X = objects.use, FUN = function(i) {return(Key(object[[i]]))})
keyed.vars <- lapply(
X = object.keys,
FUN = function(key) {
if (length(x = key) == 0) {
return(integer(length = 0L))
}
return(grep(pattern = paste0('^', key), x = vars))
}
)
keyed.vars <- Filter(f = length, x = keyed.vars)
data.fetched <- lapply(
X = names(x = keyed.vars),
FUN = function(x) {
vars.use <- vars[keyed.vars[[x]]]
key.use <- object.keys[x]
data.return <- switch(
EXPR = class(x = object[[x]]),
'DimReduc' = {
vars.use <- grep(
pattern = paste0('^', key.use, '[[:digit:]]+$'),
x = vars.use,
value = TRUE
)
if (length(x = vars.use) > 0) {
tryCatch(
expr = object[[x]][[cells, vars.use, drop = FALSE]],
error = function(e) NULL
)
} else {
NULL
}
},
'Assay' = {
vars.use <- gsub(pattern = paste0('^', key.use), replacement = '', x = vars.use)
data.assay <- GetAssayData(
object = object,
slot = slot,
assay = x
)
vars.use <- vars.use[vars.use %in% rownames(x = data.assay)]
data.vars <- t(x = as.matrix(data.assay[vars.use, cells, drop = FALSE]))
if (ncol(data.vars) > 0) {
colnames(x = data.vars) <- paste0(key.use, vars.use)
}
data.vars
}
)
data.return <- as.list(x = as.data.frame(x = data.return))
return(data.return)
}
)
data.fetched <- unlist(x = data.fetched, recursive = FALSE)
meta.vars <- vars[vars %in% colnames(x = object[[]])]
data.fetched <- c(data.fetched, object[[meta.vars]][cells, , drop = FALSE])
default.vars <- vars[vars %in% rownames(x = object)]
data.fetched <- c(
data.fetched,
as.data.frame(x = t(x = as.matrix(x = GetAssayData(
object = object,
slot = slot
)[default.vars, cells, drop = FALSE])))
)
if ('ident' %in% vars && !'ident' %in% colnames(x = object[[]])) {
data.fetched[['ident']] <- Idents(object = object)
}
fetched <- names(x = data.fetched)
vars.missing <- setdiff(x = vars, y = fetched)
if (length(x = vars.missing) > 0) {
vars.alt <- vector(mode = 'list', length = length(x = vars.missing))
names(x = vars.alt) <- vars.missing
for (assay in FilterObjects(object = object, classes.keep = 'Assay')) {
vars.assay <- Filter(
f = function(x) {
return(x %in% rownames(x = object[[assay]]))
},
x = vars.missing
)
for (var in vars.assay) {
vars.alt[[var]] <- append(x = vars.alt[[var]], values = assay)
}
}
vars.many <- names(x = Filter(
f = function(x) {
return(length(x = x) > 1)
},
x = vars.alt
))
if (length(x = vars.many) > 0) {
warning(
"Found the following features in more than one assay, excluding the default. We will not include these in the final dataframe: ",
paste(vars.many, collapse = ', '),
call. = FALSE,
immediate. = TRUE
)
}
vars.missing <- names(x = Filter(
f = function(x) {
return(length(x = x) != 1)
},
x = vars.alt
))
vars.alt <- Filter(
f = function(x) {
return(length(x = x) == 1)
},
x = vars.alt
)
for (var in names(x = vars.alt)) {
assay <- vars.alt[[var]]
warning(
'Could not find ',
var,
' in the default search locations, found in ',
assay,
' assay instead',
immediate. = TRUE,
call. = FALSE
)
keyed.var <- paste0(Key(object = object[[assay]]), var)
data.fetched[[keyed.var]] <- as.vector(
x = object[[assay]][var, cells]
)
vars <- sub(
pattern = paste0('^', var, '$'),
replacement = keyed.var,
x = vars
)
}
fetched <- names(x = data.fetched)
}
m2 <- if (length(x = vars.missing) > 10) {
paste0(' (10 out of ', length(x = vars.missing), ' shown)')
} else {
''
}
if (length(x = vars.missing) == length(x = vars)) {
stop(
"None of the requested variables were found",
m2,
': ',
paste(head(x = vars.missing, n = 10L), collapse = ', ')
)
} else if (length(x = vars.missing) > 0) {
warning(
"The following requested variables were not found",
m2,
': ',
paste(head(x = vars.missing, n = 10L), collapse = ', ')
)
}
data.fetched <- as.data.frame(
x = data.fetched,
row.names = cells,
stringsAsFactors = FALSE
)
data.order <- na.omit(object = pmatch(
x = vars,
table = fetched
))
if (length(x = data.order) > 1) {
data.fetched <- data.fetched[, data.order]
}
colnames(x = data.fetched) <- vars[vars %in% fetched]
return(data.fetched)
}
#' Get integation data
#'
#' @param object Seurat object
#' @param integration.name Name of integration object
#' @param slot Which slot in integration object to get
#'
#' @return Returns data from the requested slot within the integrated object
#'
#' @export
#'
GetIntegrationData <- function(object, integration.name, slot) {
tools <- slot(object = object, name = 'tools')
if (!(integration.name %in% names(tools))) {
stop('Requested integration key does not exist')
}
int.data <- tools[[integration.name]]
return(slot(object = int.data, name = slot))
}
#' Set integation data
#'
#' @param object Seurat object
#' @param integration.name Name of integration object
#' @param slot Which slot in integration object to set
#' @param new.data New data to insert
#'
#' @return Returns a \code{\link{Seurat}} object
#'
#' @export
#'
SetIntegrationData <- function(object, integration.name, slot, new.data) {
tools <- slot(object = object, name = 'tools')
if (!(integration.name %in% names(tools))) {
new.integrated <- new(Class = 'IntegrationData')
slot(object = new.integrated, name = slot) <- new.data
tools[[integration.name]] <- new.integrated
slot(object = object, name = 'tools') <- tools
return(object)
}
int.data <- tools[[integration.name]]
slot(object = int.data, name = slot) <- new.data
tools[[integration.name]] <- int.data
slot(object = object, name = 'tools') <- tools
return(object)
}
#' Splits object into a list of subsetted objects.
#'
#' Splits object based on a single attribute into a list of subsetted objects,
#' one for each level of the attribute. For example, useful for taking an object
#' that contains cells from many patients, and subdividing it into
#' patient-specific objects.
#'
#' @param object Seurat object
#' @param split.by Attribute for splitting. Default is "ident". Currently
#' only supported for class-level (i.e. non-quantitative) attributes.
#' @param ... Ignored
#'
#' @return A named list of Seurat objects, each containing a subset of cells
#' from the original object.
#'
#' @export
#'
#' @examples
#' # Assign the test object a three level attribute
#' groups <- sample(c("group1", "group2", "group3"), size = 80, replace = TRUE)
#' names(groups) <- colnames(pbmc_small)
#' pbmc_small <- AddMetaData(object = pbmc_small, metadata = groups, col.name = "group")
#' obj.list <- SplitObject(pbmc_small, split.by = "group")
#'
SplitObject <- function(object, split.by = "ident", ...) {
if (split.by == 'ident') {