forked from satijalab/seurat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobjects.R
2887 lines (2777 loc) · 88.7 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 reexports.R
#' @include generics.R
#' @importFrom Rcpp evalCpp
#' @importFrom Matrix colSums rowSums colMeans rowMeans
#' @importFrom methods setClass setOldClass setClassUnion slot
#' slot<- setMethod new signature slotNames is setAs setValidity .hasSlot
#' @importClassesFrom Matrix dgCMatrix
#' @useDynLib Seurat
#'
NULL
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Class definitions
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
setOldClass(Classes = 'package_version')
#' 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 neighbors List containing Neighbor objects for reuse later (e.g. mapping)
#' @slot command Store log of parameters that were used
#'
#' @name AnchorSet-class
#' @rdname AnchorSet-class
#' @concept objects
#' @exportClass AnchorSet
#'
AnchorSet <- setClass(
Class = "AnchorSet",
contains = 'VIRTUAL',
slots = list(
object.list = "list",
reference.cells = "vector",
reference.objects = "vector",
query.cells = "vector",
anchors = "ANY",
offsets = "ANY",
anchor.features = "ANY",
neighbors = "list",
command = "ANY"
)
)
#' The TransferAnchorSet Class
#'
#' Inherits from the Anchorset class. Implemented mainly for method dispatch
#' purposes. See \code{\link{AnchorSet}} for slot details.
#'
#' @name TransferAnchorSet-class
#' @rdname TransferAnchorSet-class
#' @concept objects
#' @exportClass TransferAnchorSet
#'
TransferAnchorSet <- setClass(
Class = "TransferAnchorSet",
contains = "AnchorSet"
)
#' The IntegrationAnchorSet Class
#'
#' Inherits from the Anchorset class. Implemented mainly for method dispatch
#' purposes. See \code{\link{AnchorSet}} for slot details.
#'
#' @name IntegrationAnchorSet-class
#' @rdname IntegrationAnchorSet-class
#' @concept objects
#' @exportClass IntegrationAnchorSet
#'
IntegrationAnchorSet <- setClass(
Class = "IntegrationAnchorSet",
contains = "AnchorSet"
)
#' The ModalityWeights Class
#'
#' The ModalityWeights class is an intermediate data storage class that stores the modality weight and other
#' related information needed for performing downstream analyses - namely data integration
#' (\code{FindModalityWeights}) and data transfer (\code{\link{FindMultiModalNeighbors}}).
#'
#' @slot modality.weight.list A list of modality weights value from all modalities
#' @slot modality.assay Names of assays for the list of dimensional reductions
#' @slot params A list of parameters used in the FindModalityWeights
#' @slot score.matrix a list of score matrices representing cross and within-modality prediction
#' score, and kernel value
#' @slot command Store log of parameters that were used
#'
#' @name ModalityWeights-class
#' @rdname ModalityWeights-class
#' @concept objects
#' @exportClass ModalityWeights
#'
ModalityWeights <- setClass(
Class = "ModalityWeights",
slots = list(
modality.weight.list = "list",
modality.assay = "vector",
params = "list",
score.matrix = "list",
command = "ANY"
)
)
#' 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
#' @concept objects
#' @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 SCTModel Class
#'
#' The SCTModel object is a model and parameters storage from SCTransform.
#' It can be used to calculate Pearson residuals for new genes.
#'
#' @slot feature.attributes A data.frame with feature attributes in SCTransform
#' @slot cell.attributes A data.frame with cell attributes in SCTransform
#' @slot clips A list of two numeric of length two specifying the min and max
#' values the Pearson residual will be clipped to. One for vst and one for
#' SCTransform
#' @slot umi.assay Name of the assay of the seurat object containing UMI matrix
#' and the default is RNA
#' @slot model A formula used in SCTransform
#' @slot arguments other information used in SCTransform
#' @slot median_umi Median UMI (or scale factor) used to calculate corrected counts
#'
#' @seealso \code{\link{Assay}}
#'
#' @name SCTAssay-class
#' @rdname SCTAssay-class
#' @concept objects
#'
#' @examples
#' \dontrun{
#' # SCTAssay objects are generated from SCTransform
#' pbmc_small <- SCTransform(pbmc_small)
#' }
#'
SCTModel <- setClass(
Class = 'SCTModel',
slots = c(
feature.attributes = 'data.frame',
cell.attributes = 'data.frame',
clips = 'list',
umi.assay = 'character',
model = 'character',
arguments = 'list',
median_umi = 'numeric'
)
)
#' The SCTAssay Class
#'
#' The SCTAssay object contains all the information found in an \code{\link{Assay}}
#' object, with extra information from the results of \code{\link{SCTransform}}
#'
#' @slot SCTModel.list A list containing SCT models
#'
#' @seealso \code{\link{Assay}}
#'
#' @name SCTAssay-class
#' @rdname SCTAssay-class
#' @concept objects
#'
#' @examples
#' # SCTAssay objects are generated from SCTransform
#' pbmc_small <- SCTransform(pbmc_small)
#' pbmc_small[["SCT"]]
#'
SCTAssay <- setClass(
Class = 'SCTAssay',
contains = 'Assay',
slots = c(
SCTModel.list = 'list'
)
)
#' @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
#' @concept objects
#' @concept spatial
#' @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 SlideSeq class
#'
#' The SlideSeq class represents spatial information from the Slide-seq platform
#'
#' @inheritSection SeuratObject::SpatialImage Slots
#' @slot coordinates ...
#' @concept spatial
#'
SlideSeq <- setClass(
Class = 'SlideSeq',
contains = 'SpatialImage',
slots = list(
'coordinates' = 'data.frame'
)
)
#' The STARmap class
#'
#'
#' @inheritSection SeuratObject::SpatialImage Slots
#' @concept objects
#' @concept spatial
#'
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
#' @concept objects
#' @concept spatial
#' @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
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#' 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 a SCT Assay object
#'
#' Create a SCT object from a feature (e.g. gene) expression matrix and a list of SCTModels.
#' 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 scale.data a residual matrix
#' @param SCTModel.list list of SCTModels
#' @param umi.assay The UMI assay name. Default is RNA
#' @inheritParams SeuratObject::CreateAssayObject
#'
#' @importFrom methods as
#' @importFrom Matrix colSums rowSums
#'
#' @export
#' @concept objects
#'
CreateSCTAssayObject <- function(
counts,
data,
scale.data = NULL,
umi.assay = "RNA",
min.cells = 0,
min.features = 0,
SCTModel.list = NULL
) {
assay <- CreateAssayObject(
counts = counts,
data = data,
min.cells = min.cells,
min.features = min.features
)
if (!is.null(scale.data)) {
assay <- SetAssayData(object = assay, slot = "scale.data", new.data = scale.data)
}
slot(object = assay, name = "assay.orig") <- umi.assay
#checking SCTModel.list format
if (is.null(x = SCTModel.list)) {
SCTModel.type <- "none"
warning("An empty SCTModel will be generated due to no SCTModel input")
} else {
if (inherits(x = SCTModel.list, what = "SCTModel")) {
SCTModel.list <- list(model1 = SCTModel.list)
SCTModel.type <- "SCTModel.list"
} else if (inherits(x = SCTModel.list, what = "list")) {
if (inherits(x = SCTModel.list[[1]], what = "SCTModel")){
SCTModel.type <- "SCTModel.list"
} else if (IsVSTout(vst.out = SCTModel.list)){
SCTModel.type <- "vst.out"
} else if (IsVSTout(SCTModel.list[[1]])) {
SCTModel.type <- "vst.set"
} else {
stop("SCTModel input is not a correct format")
}
}
}
model.list <- switch(
EXPR = SCTModel.type,
"none" = {
list()
},
"SCTModel.list" = {
SCTModel.list <- lapply(X = SCTModel.list, FUN = function(model) {
select.cell <- intersect(x = Cells(x = model), Cells(x = assay))
if (length(x = select.cell) == 0) {
stop("Cells in SCTModel.list don't match Cells in assay")
} else {
[email protected] <- [email protected][select.cell, , drop = FALSE]
}
return(model)
})
SCTModel.list
},
"vst.out" = {
SCTModel.list$umi.assay <- umi.assay
SCTModel.list <- PrepVSTResults(
vst.res = SCTModel.list,
cell.names = Cells(x = assay)
)
list(model1 = SCTModel.list)
},
"vst.set" = {
new.model <- lapply(
X = SCTModel.list,
FUN = function(vst.res) {
vst.res$umi.assay <- umi.assay
return(PrepVSTResults(vst.res = vst.res, cell.names = colnames(x = assay)))
}
)
names(x = new.model) <- paste0("model", 1:length(x = new.model))
new.model
}
)
assay <- new(
Class = "SCTAssay",
assay,
SCTModel.list = model.list
)
return(assay)
}
#' 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
#' @param dimreducs Only keep a subset of DimReducs specified here (if NULL,
#' remove all DimReducs)
#' @param graphs Only keep a subset of Graphs specified here (if NULL, remove
#' all Graphs)
#' @param misc Preserve the \code{misc} slot; default is \code{TRUE}
#'
#' @export
#' @concept objects
#'
DietSeurat <- function(
object,
counts = TRUE,
data = TRUE,
scale.data = FALSE,
features = NULL,
assays = NULL,
dimreducs = NULL,
graphs = NULL,
misc = TRUE
) {
object <- UpdateSlots(object = object)
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 {
if (!is.null(x = features)) {
features.assay <- intersect(x = features, 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 {
object[[assay]] <- subset(x = object[[assay]], features = features.assay)
}
}
if (!counts) {
slot(object = object[[assay]], name = 'counts') <- new(Class = 'matrix')
}
if (!data) {
stop('data = FALSE currently not supported')
}
if (!scale.data) {
slot(object = object[[assay]], name = 'scale.data') <- new(Class = 'matrix')
}
}
}
# remove misc when desired
if (!isTRUE(x = misc)) {
slot(object = object, name = "misc") <- list()
}
# remove unspecified DimReducs and Graphs
all.objects <- FilterObjects(object = object, classes.keep = c('DimReduc', 'Graph'))
objects.to.remove <- all.objects[!all.objects %in% c(dimreducs, graphs)]
for (ob in objects.to.remove) {
object[[ob]] <- NULL
}
return(object)
}
#' Filter stray beads from Slide-seq puck
#'
#' This function is useful for removing stray beads that fall outside the main
#' Slide-seq puck area. Essentially, it's a circular filter where you set a
#' center and radius defining a circle of beads to keep. If the center is not
#' set, it will be estimated from the bead coordinates (removing the 1st and
#' 99th quantile to avoid skewing the center by the stray beads). By default,
#' this function will display a \code{\link{SpatialDimPlot}} showing which cells
#' were removed for easy adjustment of the center and/or radius.
#'
#' @param object Seurat object with slide-seq data
#' @param image Name of the image where the coordinates are stored
#' @param center Vector specifying the x and y coordinates for the center of the
#' inclusion circle
#' @param radius Radius of the circle of inclusion
#' @param do.plot Display a \code{\link{SpatialDimPlot}} with the cells being
#' removed labeled.
#'
#' @return Returns a Seurat object with only the subset of cells that pass the
#' circular filter
#'
#' @concept objects
#' @concept spatial
#' @examples
#' \dontrun{
#' # This example uses the ssHippo dataset which you can download
#' # using the SeuratData package.
#' library(SeuratData)
#' data('ssHippo')
#' # perform filtering of beads
#' ssHippo.filtered <- FilterSlideSeq(ssHippo, radius = 2300)
#' # This radius looks to small so increase and repeat until satisfied
#' }
#' @export
#'
FilterSlideSeq <- function(
object,
image = "image",
center = NULL,
radius = NULL,
do.plot = TRUE
) {
if (!inherits(x = object[[image]], what = "SlideSeq")) {
warning(
"This fxn is intended for filtering SlideSeq data and is untested ",
"outside of that context."
)
}
dat <- GetTissueCoordinates(object[[image]])
if (is.null(x = center)) {
# heuristic for determining center of puck
center <- c()
x.vals <- dat[, 1]
center[1] <- mean(
x = x.vals[x.vals < quantile(x = x.vals, probs = 0.99) &
x.vals > quantile(x = x.vals, probs = 0.01)]
)
y.vals <- dat[, 2]
center[2] <- mean(
x = y.vals[y.vals < quantile(x = y.vals, probs = 0.99) &
y.vals > quantile(x = y.vals, probs = 0.01)]
)
}
if (is.null(x = radius)) {
stop("Please provide a radius.")
}
dists <- apply(X = dat, MARGIN = 1, FUN = function(x) {
as.numeric(dist(rbind(x[c(1, 2)], center)))
})
cells.to.remove <- names(x = which(x = (dists > radius)))
if (do.plot) {
Idents(object) <- "keep"
object <- SetIdent(object = object, cells = cells.to.remove, value = "remove")
print(SpatialDimPlot(object = object))
}
return(subset(x = object, cells = cells.to.remove, invert = TRUE))
}
#' Get integration 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
#' @concept objects
#'
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 integration 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
#' @concept objects
#'
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.
#'
#' @return A named list of Seurat objects, each containing a subset of cells
#' from the original object.
#'
#' @export
#' @concept objects
#'
#' @examples
#' data("pbmc_small")
#' # 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') {
groupings <- Idents(object = object)
} else {
groupings <- FetchData(object = object, vars = split.by)[, 1]
}
groupings <- unique(x = as.character(x = groupings))
obj.list <- list()
for (i in groupings) {
if (split.by == "ident") {
obj.list[[i]] <- subset(x = object, idents = i)
}
else {
cells <- which(x = object[[split.by, drop = TRUE]] == i)
cells <- colnames(x = object)[cells]
obj.list[[i]] <- subset(x = object, cells = cells)
}
}
return(obj.list)
}
#' Find features with highest scores for a given dimensional reduction technique
#'
#' Return a list of features with the strongest contribution to a set of components
#'
#' @param object DimReduc object
#' @param dim Dimension to use
#' @param nfeatures Number of features to return
#' @param projected Use the projected feature loadings
#' @param balanced Return an equal number of features with both + and - scores.
#' @param ... Extra parameters passed to \code{\link{Loadings}}
#'
#' @return Returns a vector of features
#'
#' @export
#' @concept objects
#'
#' @examples
#' data("pbmc_small")
#' pbmc_small
#' TopFeatures(object = pbmc_small[["pca"]], dim = 1)
#' # After projection:
#' TopFeatures(object = pbmc_small[["pca"]], dim = 1, projected = TRUE)
#'
TopFeatures <- function(
object,
dim = 1,
nfeatures = 20,
projected = FALSE,
balanced = FALSE,
...
) {
loadings <- Loadings(object = object, projected = projected, ...)[, dim, drop = FALSE]
return(Top(
data = loadings,
num = nfeatures,
balanced = balanced
))
}
#' Find cells with highest scores for a given dimensional reduction technique
#'
#' Return a list of genes with the strongest contribution to a set of components
#'
#' @param object DimReduc object
#' @param dim Dimension to use
#' @param ncells Number of cells to return
#' @param balanced Return an equal number of cells with both + and - scores.
#' @param ... Extra parameters passed to \code{\link{Embeddings}}
#'
#' @return Returns a vector of cells
#'
#' @export
#' @concept objects
#'
#' @examples
#' data("pbmc_small")
#' pbmc_small
#' head(TopCells(object = pbmc_small[["pca"]]))
#' # Can specify which dimension and how many cells to return
#' TopCells(object = pbmc_small[["pca"]], dim = 2, ncells = 5)
#'
TopCells <- function(object, dim = 1, ncells = 20, balanced = FALSE, ...) {
embeddings <- Embeddings(object = object, ...)[, dim, drop = FALSE]
return(Top(
data = embeddings,
num = ncells,
balanced = balanced
))
}
#' Get nearest neighbors for given cell
#'
#' Return a vector of cell names of the nearest n cells.
#'
#' @param object \code{\link{Neighbor}} object
#' @param cell Cell of interest
#' @param n Number of neighbors to return
#'
#' @return Returns a vector of cell names
#'
#' @export
#' @concept objects
#'
TopNeighbors <- function(object, cell, n = 5) {
indices <- Indices(object = object)[cell, 1:n]
return(Cells(x = object)[indices])
}
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Methods for Seurat-defined generics
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#' @param assay Assay to convert
#' @param reduction Name of DimReduc to set to main reducedDim in cds
#'
#' @rdname as.CellDataSet
#' @concept objects
#' @export
#' @method as.CellDataSet Seurat
#'
as.CellDataSet.Seurat <- function(x, assay = NULL, reduction = NULL, ...) {
CheckDots(...)
if (!PackageCheck('monocle', error = FALSE)) {
stop("Please install monocle from Bioconductor before converting to a CellDataSet object")
} else if (packageVersion(pkg = 'monocle') >= package_version(x = '2.99.0')) {
stop("Seurat can only convert to/from Monocle v2.X objects")
}
assay <- assay %||% DefaultAssay(object = x)
# make variables, then run `newCellDataSet`
# create cellData counts
counts <- GetAssayData(object = x, assay = assay, slot = "counts")
# metadata
cell.metadata <- x[[]]
feature.metadata <- x[[assay]][[]]
if (!"gene_short_name" %in% colnames(x = feature.metadata)) {
feature.metadata$gene_short_name <- rownames(x = feature.metadata)
}
pd <- new(Class = "AnnotatedDataFrame", data = cell.metadata)
fd <- new(Class = "AnnotatedDataFrame", data = feature.metadata)
# Now, determine the expressionFamily
if ("monocle" %in% names(x = Misc(object = x))) {
expressionFamily <- Misc(object = x, slot = "monocle")[["expressionFamily"]]
} else {
if (all(counts == floor(x = counts))) {
expressionFamily <- VGAM::negbinomial.size()
} else if (any(counts < 0)) {
expressionFamily <- VGAM::uninormal()
} else {
expressionFamily <- VGAM::tobit()
}
}
cds <- monocle::newCellDataSet(
cellData = counts,
phenoData = pd,
featureData = fd,
expressionFamily = expressionFamily
)
if ("monocle" %in% names(x = Misc(object = x))) {
monocle::cellPairwiseDistances(cds = cds) <- Misc(object = x, slot = "monocle")[["cellPairwiseDistances"]]
monocle::minSpanningTree(cds = cds) <- Misc(object = x, slot = "monocle")[["minSpanningTree"]]
Biobase::experimentData(cds = cds) <- Misc(object = x, slot = "monocle")[["experimentData"]]
Biobase::protocolData(cds = cds) <- Misc(object = x, slot = "monocle")[["protocolData"]]
Biobase::classVersion(cds = cds) <- Misc(object = x, slot = "monocle")[["classVersion"]]
# no setter methods found for following slots
slot(object = cds, name = "lowerDetectionLimit") <- Misc(object = x, slot = "monocle")[["lowerDetectionLimit"]]
slot(object = cds, name = "dispFitInfo") <- Misc(object = x, slot = "monocle")[["dispFitInfo"]]
slot(object = cds, name = "auxOrderingData") <- Misc(object = x, slot = "monocle")[["auxOrderingData"]]
slot(object = cds, name = "auxClusteringData") <- Misc(object = x, slot = "monocle")[["auxClusteringData"]]
}
# adding dimensionality reduction data to the CDS
dr.slots <- c("reducedDimS", "reducedDimK", "reducedDimW", "reducedDimA")
reduction <- reduction %||% DefaultDimReduc(object = x, assay = assay)
if (!is.null(x = reduction)) {
if (grepl(pattern = 'tsne', x = tolower(x = reduction))) {
slot(object = cds, name = "dim_reduce_type") <- "tSNE"
monocle::reducedDimA(cds = cds) <- t(x = Embeddings(object = x[[reduction]]))
} else {
slot(object = cds, name = "dim_reduce_type") <- reduction
monocle::reducedDimA(cds = cds) <- Loadings(object = x[[reduction]])
slot(object = cds, name = "reducedDimS") <- Embeddings(object = x[[reduction]])
}
for (ii in dr.slots) {
if (ii %in% names(x = slot(object = x[[reduction]], name = "misc"))) {
slot(object = cds, name = ii) <- slot(object = x[[reduction]], name = "misc")[[ii]]
}
}
}
return(cds)
}
#' Convert objects to \code{Seurat} objects
#'
#' @inheritParams SeuratObject::as.Seurat
#' @param slot Slot to store expression data as
#' @param verbose Show progress updates
#'
#' @return A \code{Seurat} object generated from \code{x}
#'
#' @importFrom utils packageVersion
#'
#' @rdname as.Seurat
#' @concept objects
#' @export
#' @method as.Seurat CellDataSet
#'
#' @seealso \code{\link[SeuratObject:as.Seurat]{SeuratObject::as.Seurat}}
#'
as.Seurat.CellDataSet <- function(
x,
slot = 'counts',
assay = 'RNA',
verbose = TRUE,
...
) {
CheckDots(...)
if (!PackageCheck('monocle', error = FALSE)) {
stop("Please install monocle from Bioconductor before converting to a CellDataSet object")
} else if (packageVersion(pkg = 'monocle') >= package_version(x = '2.99.0')) {
stop("Seurat can only convert to/from Monocle v2.X objects")
}
slot <- match.arg(arg = slot, choices = c('counts', 'data'))
if (verbose) {
message("Pulling expression data")
}
expr <- Biobase::exprs(object = x)
if (IsMatrixEmpty(x = expr)) {
stop("No data provided in this CellDataSet object", call. = FALSE)
}
meta.data <- as.data.frame(x = Biobase::pData(object = x))
# if cell names are NULL, fill with cell_X
if (is.null(x = colnames(x = expr))) {
warning(
"The column names of the 'counts' and 'data' matrices are NULL. Setting cell names to cell_columnidx (e.g 'cell_1').",
call. = FALSE,
immediate. = TRUE
)
rownames(x = meta.data) <- colnames(x = expr) <- paste0("cell_", 1:ncol(x = expr))
}
# Creating the object
if (verbose) {
message("Building Seurat object")
}
if (slot == 'data') {
assays <- list(CreateAssayObject(data = expr))
names(x = assays) <- assay
Key(object = assays[[assay]]) <- suppressWarnings(expr = UpdateKey(key = assay))
object <- new(
Class = 'Seurat',
assays = assays,
meta.data = meta.data,
version = packageVersion(pkg = 'Seurat'),
project.name = 'SeuratProject'
)
DefaultAssay(object = object) <- assay
} else {
object <- CreateSeuratObject(
counts = expr,
meta.data = meta.data,
assay = assay
)
}
# feature metadata
if (verbose) {
message("Adding feature-level metadata")
}
feature.metadata <- Biobase::fData(object = x)
object[[assay]][[names(x = feature.metadata)]] <- feature.metadata
# mean/dispersion values
disp.table <- tryCatch(
expr = suppressWarnings(expr = monocle::dispersionTable(cds = x)),
error = function(...) {
return(NULL)
}
)
if (!is.null(x = disp.table)) {
if (verbose) {
message("Adding dispersion information")
}
rownames(x = disp.table) <- disp.table[, 1]
disp.table[, 1] <- NULL
colnames(x = disp.table) <- paste0('monocle_', colnames(x = disp.table))
object[[assay]][[names(x = disp.table)]] <- disp.table
} else if (verbose) {
message("No dispersion information in CellDataSet object")
}
# variable features
if ("use_for_ordering" %in% colnames(x = feature.metadata)) {
if (verbose) {
message("Setting variable features")
}
VariableFeatures(object = object, assay = assay) <- rownames(x = feature.metadata)[which(x = feature.metadata[, "use_for_ordering"])]
} else if (verbose) {
message("No variable features present")
}
# add dim reduction
dr.name <- slot(object = x, name = "dim_reduce_type")
if (length(x = dr.name) > 0) {
if (verbose) {
message("Adding ", dr.name, " dimensional reduction")
}
reduced.A <- t(x = slot(object = x, name = 'reducedDimA'))
reduced.S <- t(x = slot(object = x, name = 'reducedDimS'))
if (IsMatrixEmpty(x = reduced.S)) {
embeddings <- reduced.A
loadings <- new(Class = 'matrix')
} else {
embeddings <- reduced.S
loadings <- t(x = reduced.A)
}
rownames(x = embeddings) <- colnames(x = object)
misc.dr <- list(
reducedDimS = slot(object = x, name = "reducedDimS"),
reducedDimK = slot(object = x, name = "reducedDimK"),
reducedDimW = slot(object = x, name = "reducedDimW"),
reducedDimA = slot(object = x, name = "reducedDimA")
)
dr <- suppressWarnings(expr = CreateDimReducObject(
embeddings = embeddings,
loadings = loadings,
assay = assay,
key = UpdateKey(key = tolower(x = dr.name)),
misc = misc.dr