forked from satijalab/seurat
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathobjects.R
8224 lines (7986 loc) · 252 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 .hasSlot
#' @importClassesFrom Matrix dgCMatrix
#' @useDynLib Seurat
#'
NULL
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Class definitions
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
setOldClass(Classes = 'package_version')
setClassUnion(name = 'AnyMatrix', members = c("matrix", "dgCMatrix"))
setClassUnion(name = 'OptionalCharacter', members = c('NULL', 'character'))
#' 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 reference.objects Position of reference object/s in object.list
#' @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",
reference.objects = "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 assay.orig Original assay that this assay is based off of. Used to track
#' assay provenence
#' @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',
assay.orig = 'OptionalCharacter',
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 \code{DimReduc} object
#' @slot global Is this \code{DimReduc} global/persistent? If so, it will not be
#' removed when removing its associated assay
#' @slot stdev A vector of standard deviations
#' @slot key Key for the \code{DimReduc}, must be alphanumerics followed by an underscore
#' @slot jackstraw A \code{\link{JackStrawData-class}} object associated with
#' this \code{DimReduc}
#' @slot misc Utility slot for storing additional data associated with the
#' \code{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',
global = 'logical',
stdev = 'numeric',
key = 'character',
jackstraw = 'JackStrawData',
misc = 'list'
)
)
#' The Graph Class
#'
#' The Graph class inherits from dgCMatrix. We do this to enable future expandability of graphs.
#'
#' @slot assay.used Optional name of assay used to generate \code{Graph} object
#'
#' @name Graph-class
#' @rdname Graph-class
#' @exportClass Graph
#'
#' @seealso \code{\link[Matrix]{dgCMatrix-class}}
#'
Graph <- setClass(
Class = 'Graph',
contains = "dgCMatrix",
slots = list(
assay.used = 'OptionalCharacter'
)
)
#' 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"
)
)
#' @note \code{scalefactors} objects can be created with \code{scalefactors()}
#'
#' @param spot Spot full resolution scale factor
#' @param fiducial Fiducial full resolution scale factor
#' @param hires High resolutoin scale factor
#' @param lowres Low resolution scale factor
#'
#' @rdname ScaleFactors
#' @export
#'
scalefactors <- function(spot, fiducial, hires, lowres) {
object <- list(
spot = spot,
fiducial = fiducial,
hires = hires,
lowres = lowres
)
object <- sapply(X = object, FUN = as.numeric, simplify = FALSE, USE.NAMES = TRUE)
return(structure(.Data = object, class = 'scalefactors'))
}
setOldClass(Classes = c('scalefactors'))
#' 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 assay.used Optional name of assay used to generate \code{SeuratCommand} object
#' @slot call.string String of the command call
#' @slot params List of parameters used in the command call
#'
#' @name SeuratCommand-class
#' @rdname SeuratCommand-class
#' @exportClass SeuratCommand
#'
SeuratCommand <- setClass(
Class = 'SeuratCommand',
slots = c(
name = 'character',
time.stamp = 'POSIXct',
assay.used = 'OptionalCharacter',
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 Unused at this time
#' @slot reductions A list of dimmensional reduction objects for this object
#' @slot images A list of spatial image objects
#' @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',
images = '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"
)
)
#' The SpatialImage class
#'
#' The SpatialImage class is a virtual class representing spatial information for
#' Seurat. All spatial image information must inherit from this class for use with
#' \code{Seurat} objects
#'
#' @slot assay Name of assay to associate image data with; will give this image
#' priority for visualization when the assay is set as the active/default assay
#' in a \code{Seurat} object
#' @slot key Key for the image
#'
#' @section Provided methods:
#' These methods are defined on the \code{SpatialImage} object and should not be
#' overwritten without careful thought
#' \itemize{
#' \item \code{\link{DefaultAssay}} and \code{\link{DefaultAssay<-}}
#' \item \code{\link{Key}} and \code{\link{Key<-}}
#' \item \code{\link{IsGlobal}}
#' \item \code{\link{Radius}}; this method \emph{can} be overridden to provide
#' a spot radius for image objects
#' }
#'
#' @section Required methods:
#' All subclasses of the \code{SpatialImage} class must define the following methods;
#' simply relying on the \code{SpatialImage} method will result in errors. For required
#' parameters and their values, see the \code{Usage} and \code{Arguments} sections
#' \describe{
#' \item{\code{\link{Cells}}}{Return the cell/spot barcodes associated with each position}
#' \item{\code{\link{dim}}}{Return the dimensions of the image for plotting in \code{(Y, X)} format}
#' \item{\code{\link{GetImage}}}{Return image data; by default, must return a grob object}
#' \item{\code{\link{GetTissueCoordinates}}}{Return tissue coordinates; by default,
#' must return a two-column data.frame with x-coordinates in the first column and y-coordiantes
#' in the second}
#' \item{\code{\link{Radius}}}{Return the spot radius; returns \code{NULL} by
#' default for use with non-spot image technologies}
#' \item{\code{\link{RenameCells}}}{Rename the cell/spot barcodes for this image}
#' \item{\code{\link{subset}} and \code{[}}{Subset the image data by cells/spots;
#' \code{[} should only take \code{i} for subsetting by cells/spots}
#' }
#' These methods are used throughout Seurat, so defining them and setting the proper
#' defaults will allow subclasses of \code{SpatialImage} to work seamlessly
#'
#' @name SpatialImage-class
#' @rdname SpatialImage-class
#' @exportClass SpatialImage
#'
SpatialImage <- setClass(
Class = 'SpatialImage',
contains = 'VIRTUAL',
slots = list(
'assay' = 'character',
'key' = 'character'
)
)
#' The SlideSeq class
#'
#' The SlideSeq class represents spatial information from the Slide-seq platform
#'
#' @inheritSection SpatialImage Slots
#' @slot coordinates ...
#' @slot ...
#'
SlideSeq <- setClass(
Class = 'SlideSeq',
contains = 'SpatialImage',
slots = list(
'coordinates' = 'data.frame'
)
)
#' The STARmap class
#'
#' The STARmap class represents spatial information from the STARmap platform
#'
#' @inheritSection SpatialImage Slots
#' @slot ...
#'
STARmap <- setClass(
Class = 'STARmap',
contains = 'SpatialImage',
slots = list(
'coordinates' = 'data.frame',
'qhulls' = 'data.frame'
)
)
#' The VisiumV1 class
#'
#' The VisiumV1 class represents spatial information from the 10X Genomics Visium
#' platform
#'
#' @slot image A three-dimensional array with PNG image data, see
#' \code{\link[png]{readPNG}} for more details
#' @slot scale.factors An object of class \code{\link{scalefactors}}; see
#' \code{\link{scalefactors}} for more information
#' @slot coordinates A data frame with tissue coordinate information
#' @slot spot.radius Single numeric value giving the radius of the spots
#'
#' @name VisiumV1-class
#' @rdname VisiumV1-class
#' @exportClass VisiumV1
#'
VisiumV1 <- setClass(
Class = 'VisiumV1',
contains = 'SpatialImage',
slots = list(
'image' = 'array',
'scale.factors' = 'scalefactors',
'coordinates' = 'data.frame',
'spot.radius' = 'numeric'
)
)
setClass(Class = 'SliceImage', contains = 'VisiumV1')
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Functions
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#' Pull Assays or assay names
#'
#' Lists the names of \code{\link{Assay}} objects present in
#' a Seurat object. If slot is provided, pulls specified Assay object.
#'
#' @param object A Seurat object
#' @param slot Name of Assay to return
#'
#' @return If \code{slot} is \code{NULL}, the names of all \code{Assay} objects
#' in this Seurat object. Otherwise, the \code{Assay} object specified
#'
#' @export
#'
#' @examples
#' Assays(object = pbmc_small)
#'
Assays <- function(object, slot = NULL) {
assays <- FilterObjects(object = object, classes.keep = 'Assay')
if (is.null(x = slot)) {
return(assays)
}
if (!slot %in% assays) {
warning(
"Cannot find an assay of name ",
slot,
" in this Seurat object",
call. = FALSE,
immediate. = TRUE
)
}
return(slot(object = object, name = 'assays')[[slot]])
}
#' Get cell names grouped by identity class
#'
#' @param object A Seurat object
#' @param idents A vector of identity class levels to limit resulting list to;
#' defaults to all identity class levels
#' @param cells A vector of cells to grouping to
#'
#' @return A named list where names are identity classes and values are vectors
#' of cells beloning to that class
#'
#' @export
#'
#' @examples
#' CellsByIdentities(object = pbmc_small)
#'
CellsByIdentities <- function(object, idents = NULL, cells = NULL) {
cells <- cells %||% colnames(x = object)
cells <- intersect(x = cells, y = colnames(x = object))
if (length(x = cells) == 0) {
stop("Cannot find cells provided")
}
idents <- idents %||% levels(x = object)
idents <- intersect(x = idents, y = levels(x = object))
if (length(x = idents) == 0) {
stop("None of the provided identity class levels were found", call. = FALSE)
}
cells.idents <- sapply(
X = idents,
FUN = function(i) {
return(cells[as.vector(x = Idents(object = object)[cells]) == i])
},
simplify = FALSE,
USE.NAMES = TRUE
)
if (any(is.na(x = Idents(object = object)[cells]))) {
cells.idents["NA"] <- names(x = which(x = is.na(x = Idents(object = object)[cells])))
}
return(cells.idents)
}
#' Get a vector of cell names associated with an image (or set of images)
#'
#' @param object Seurat object
#' @param images Vector of image names
#' @param unlist Return as a single vector of cell names as opposed to a list,
#' named by image name.
#'
#' @return A vector of cell names
#'
#' @examples
#' \dontrun{
#' CellsByImage(object = object, images = "slice1")
#' }
#'
CellsByImage <- function(object, images = NULL, unlist = FALSE) {
images <- images %||% Images(object = object)
cells <- sapply(
X = images,
FUN = function(x) {
Cells(x = object[[x]])
},
simplify = FALSE,
USE.NAMES = TRUE
)
if (unlist) {
cells <- unname(obj = unlist(x = cells))
}
return(cells)
}
#' 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 (any(rownames(x = counts) == '')) {
stop("Feature names of counts matrix cannot be empty", call. = FALSE)
}
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 (any(rownames(x = data) == '')) {
stop("Feature names of data matrix cannot be empty", call. = FALSE)
}
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')
}
# Ensure row- and column-names are vectors, not arrays
if (!is.vector(x = rownames(x = counts))) {
rownames(x = counts) <- as.vector(x = rownames(x = counts))
}
if (!is.vector(x = colnames(x = counts))) {
colnames(x = counts) <- as.vector(x = colnames(x = counts))
}
if (!is.vector(x = rownames(x = data))) {
rownames(x = data) <- as.vector(x = rownames(x = data))
}
if (!is.vector(x = colnames(x = data))) {
colnames(x = data) <- as.vector(x = colnames(x = data))
}
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)
)
}
if (any(grepl(pattern = '|', x = rownames(x = counts), fixed = TRUE)) || any(grepl(pattern = '|', x = rownames(x = data), fixed = TRUE))) {
warning(
"Feature names cannot have pipe characters ('|'), replacing with dashes ('-')",
call. = FALSE,
immediate. = TRUE
)
rownames(x = counts) <- gsub(
pattern = '|',
replacement = '-',
x = rownames(x = counts),
fixed = TRUE
)
rownames(x = data) <- gsub(
pattern = '|',
replacement = '-',
x = rownames(x = data),
fixed = TRUE
)
}
# Initialize meta.features
init.meta.features <- data.frame(row.names = rownames(x = data))
object.list <- list(
'Class' = 'Assay',
'counts' = counts,
'data' = data,
'scale.data' = new(Class = 'matrix'),
'meta.features' = init.meta.features
)
assay <- do.call(what = 'new', args = object.list)
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 global Specify this as a global reduction (useful for visualizations)
#' @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,
global = FALSE,
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)) {
old.key <- key
key <- UpdateKey(key = old.key)
colnames(x = embeddings) <- gsub(
x = colnames(x = embeddings),
pattern = old.key,
replacement = key
)
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)) {
if (any(rownames(x = loadings) == '')) {
stop("Feature names of loadings matrix cannot be empty", call. = FALSE)
}
colnames(x = loadings) <- colnames(x = embeddings)
}
if (!IsMatrixEmpty(x = projected)) {
if (any(rownames(x = loadings) == '')) {
stop("Feature names of projected loadings matrix cannot be empty", call. = FALSE)
}
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,
global = global,
stdev = stdev,
key = key,
jackstraw = jackstraw,
misc = misc
)
return(dim.reduc)
}
#' @inheritParams CreateAssayObject
#'
#' @rdname CreateSeuratObject
#' @method CreateSeuratObject default
#' @export
#'
CreateSeuratObject.default <- function(
counts,
project = 'SeuratProject',
assay = 'RNA',
names.field = 1,
names.delim = '_',
meta.data = NULL,
min.cells = 0,
min.features = 0,
...
) {
if (!is.null(x = meta.data)) {
if (!all(rownames(x = meta.data) %in% colnames(x = counts))) {
warning("Some cells in meta.data not present in provided counts matrix")
}
}
assay.data <- CreateAssayObject(
counts = counts,
min.cells = min.cells,
min.features = min.features
)
if (!is.null(x = meta.data)) {
common.cells <- intersect(
x = rownames(x = meta.data), y = colnames(x = assay.data)
)
meta.data <- meta.data[common.cells, , drop = FALSE]
}
Key(object = assay.data) <- suppressWarnings(expr = UpdateKey(key = tolower(
x = assay
)))
return(CreateSeuratObject(
counts = assay.data,
project = project,
assay = assay,
names.field = names.field,
names.delim = names.delim,
meta.data = meta.data,
...
))
}
#' @rdname CreateSeuratObject
#' @method CreateSeuratObject Assay
#' @export
#'
CreateSeuratObject.Assay <- function(
counts,
project = 'SeuratProject',
assay = 'RNA',
names.field = 1,
names.delim = '_',
meta.data = NULL,
...
) {
if (!is.null(x = meta.data)) {
if (is.null(x = rownames(x = meta.data))) {
stop("Row names not set in metadata. Please ensure that rownames of metadata match column names of data matrix")
}
if (length(x = setdiff(x = rownames(x = meta.data), y = colnames(x = counts)))) {
warning("Some cells in meta.data not present in provided counts matrix.")
meta.data <- meta.data[intersect(x = rownames(x = meta.data), y = colnames(x = counts)), , drop = FALSE]
}
if (is.data.frame(x = meta.data)) {
new.meta.data <- data.frame(row.names = colnames(x = counts))
for (ii in 1:ncol(x = meta.data)) {
new.meta.data[rownames(x = meta.data), colnames(x = meta.data)[ii]] <- meta.data[, ii, drop = FALSE]
}
meta.data <- new.meta.data
}
}
assay.list <- list(counts)
names(x = assay.list) <- assay
# Set idents
idents <- factor(x = unlist(x = lapply(
X = colnames(x = counts),
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",
call. = FALSE,
immediate. = TRUE
)
}
# 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 = counts))
}
names(x = idents) <- colnames(x = counts)
object <- new(
Class = 'Seurat',
assays = assay.list,
meta.data = data.frame(row.names = colnames(x = counts)),
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 = counts)
if (!is.null(x = n.calc)) {
names(x = n.calc) <- paste(names(x = n.calc), assay, sep = '_')
object[[names(x = n.calc)]] <- n.calc
}
# Add metadata
if (!is.null(x = meta.data)) {