forked from satijalab/seurat
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutilities.R
1974 lines (1924 loc) · 58.9 KB
/
utilities.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
#'
NULL
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Functions
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#' Calculate module scores for feature expression programs in single cells
#'
#' Calculate the average expression levels of each program (cluster) on single cell level,
#' subtracted by the aggregated expression of control feature sets.
#' All analyzed features are binned based on averaged expression, and the control features are
#' randomly selected from each bin.
#'
#' @param object Seurat object
#' @param features Feature expression programs in list
#' @param pool List of features to check expression levels agains, defaults to \code{rownames(x = object)}
#' @param nbin Number of bins of aggregate expression levels for all analyzed features
#' @param ctrl Number of control features selected from the same bin per analyzed feature
#' @param k Use feature clusters returned from DoKMeans
#' @param assay Name of assay to use
#' @param name Name for the expression programs
#' @param seed Set a random seed. If NULL, seed is not set.
#' @param search Search for symbol synonyms for features in \code{features} that
#' don't match features in \code{object}? Searches the HGNC's gene names database;
#' see \code{\link{UpdateSymbolList}} for more details
#' @param ... Extra parameters passed to \code{\link{UpdateSymbolList}}
#'
#' @return Returns a Seurat object with module scores added to object meta data
#'
#' @importFrom ggplot2 cut_number
#' @importFrom Matrix rowMeans colMeans
#'
#' @references Tirosh et al, Science (2016)
#'
#' @export
#'
#' @examples
#' \dontrun{
#' cd_features <- list(c(
#' 'CD79B',
#' 'CD79A',
#' 'CD19',
#' 'CD180',
#' 'CD200',
#' 'CD3D',
#' 'CD2',
#' 'CD3E',
#' 'CD7',
#' 'CD8A',
#' 'CD14',
#' 'CD1C',
#' 'CD68',
#' 'CD9',
#' 'CD247'
#' ))
#' pbmc_small <- AddModuleScore(
#' object = pbmc_small,
#' features = cd_features,
#' ctrl = 5,
#' name = 'CD_Features'
#' )
#' head(x = pbmc_small[])
#' }
#'
AddModuleScore <- function(
object,
features,
pool = NULL,
nbin = 24,
ctrl = 100,
k = FALSE,
assay = NULL,
name = 'Cluster',
seed = 1,
search = FALSE,
...
) {
if (!is.null(x = seed)) {
set.seed(seed = seed)
}
assay.old <- DefaultAssay(object = object)
assay <- assay %||% assay.old
DefaultAssay(object = object) <- assay
assay.data <- GetAssayData(object = object)
features.old <- features
if (k) {
.NotYetUsed(arg = 'k')
features <- list()
for (i in as.numeric(x = names(x = table([email protected][[1]]$cluster)))) {
features[[i]] <- names(x = which(x = [email protected][[1]]$cluster == i))
}
cluster.length <- length(x = features)
} else {
if (is.null(x = features)) {
stop("Missing input feature list")
}
features <- lapply(
X = features,
FUN = function(x) {
missing.features <- setdiff(x = x, y = rownames(x = object))
if (length(x = missing.features) > 0) {
warning(
"The following features are not present in the object: ",
paste(missing.features, collapse = ", "),
ifelse(
test = search,
yes = ", attempting to find updated synonyms",
no = ", not searching for symbol synonyms"
),
call. = FALSE,
immediate. = TRUE
)
if (search) {
tryCatch(
expr = {
updated.features <- UpdateSymbolList(symbols = missing.features, ...)
names(x = updated.features) <- missing.features
for (miss in names(x = updated.features)) {
index <- which(x == miss)
x[index] <- updated.features[miss]
}
},
error = function(...) {
warning(
"Could not reach HGNC's gene names database",
call. = FALSE,
immediate. = TRUE
)
}
)
missing.features <- setdiff(x = x, y = rownames(x = object))
if (length(x = missing.features) > 0) {
warning(
"The following features are still not present in the object: ",
paste(missing.features, collapse = ", "),
call. = FALSE,
immediate. = TRUE
)
}
}
}
return(intersect(x = x, y = rownames(x = object)))
}
)
cluster.length <- length(x = features)
}
if (!all(LengthCheck(values = features))) {
warning(paste(
'Could not find enough features in the object from the following feature lists:',
paste(names(x = which(x = !LengthCheck(values = features)))),
'Attempting to match case...'
))
features <- lapply(
X = features.old,
FUN = CaseMatch,
match = rownames(x = object)
)
}
if (!all(LengthCheck(values = features))) {
stop(paste(
'The following feature lists do not have enough features present in the object:',
paste(names(x = which(x = !LengthCheck(values = features)))),
'exiting...'
))
}
pool <- pool %||% rownames(x = object)
data.avg <- Matrix::rowMeans(x = assay.data[pool, ])
data.avg <- data.avg[order(data.avg)]
data.cut <- cut_number(x = data.avg + rnorm(n = length(data.avg))/1e30, n = nbin, labels = FALSE, right = FALSE)
#data.cut <- as.numeric(x = Hmisc::cut2(x = data.avg, m = round(x = length(x = data.avg) / (nbin + 1))))
names(x = data.cut) <- names(x = data.avg)
ctrl.use <- vector(mode = "list", length = cluster.length)
for (i in 1:cluster.length) {
features.use <- features[[i]]
for (j in 1:length(x = features.use)) {
ctrl.use[[i]] <- c(
ctrl.use[[i]],
names(x = sample(
x = data.cut[which(x = data.cut == data.cut[features.use[j]])],
size = ctrl,
replace = FALSE
))
)
}
}
ctrl.use <- lapply(X = ctrl.use, FUN = unique)
ctrl.scores <- matrix(
data = numeric(length = 1L),
nrow = length(x = ctrl.use),
ncol = ncol(x = object)
)
for (i in 1:length(ctrl.use)) {
features.use <- ctrl.use[[i]]
ctrl.scores[i, ] <- Matrix::colMeans(x = assay.data[features.use, ])
}
features.scores <- matrix(
data = numeric(length = 1L),
nrow = cluster.length,
ncol = ncol(x = object)
)
for (i in 1:cluster.length) {
features.use <- features[[i]]
data.use <- assay.data[features.use, , drop = FALSE]
features.scores[i, ] <- Matrix::colMeans(x = data.use)
}
features.scores.use <- features.scores - ctrl.scores
rownames(x = features.scores.use) <- paste0(name, 1:cluster.length)
features.scores.use <- as.data.frame(x = t(x = features.scores.use))
rownames(x = features.scores.use) <- colnames(x = object)
object[[colnames(x = features.scores.use)]] <- features.scores.use
CheckGC()
DefaultAssay(object = object) <- assay.old
return(object)
}
#' Averaged feature expression by identity class
#'
#' Returns expression for an 'average' single cell in each identity class
#'
#' Output is in log-space when \code{return.seurat = TRUE}, otherwise it's in non-log space.
#' Averaging is done in non-log space.
#'
#' @param object Seurat object
#' @param assays Which assays to use. Default is all assays
#' @param features Features to analyze. Default is all features in the assay
#' @param return.seurat Whether to return the data as a Seurat object. Default is FALSE
#' @param add.ident Place an additional label on each cell prior to averaging (very useful if you want to observe cluster averages, separated by replicate, for example)
#' @param slot Slot to use; will be overriden by \code{use.scale} and \code{use.counts}
#' @param use.scale Use scaled values for feature expression
#' @param use.counts Use count values for feature expression
#' @param verbose Print messages and show progress bar
#' @param ... Arguments to be passed to methods such as \code{\link{CreateSeuratObject}}
#'
#' @return Returns a matrix with genes as rows, identity classes as columns.
#' If return.seurat is TRUE, returns an object of class \code{\link{Seurat}}.
#'
#' @importFrom Matrix rowMeans
#' @export
#'
#' @examples
#' head(AverageExpression(object = pbmc_small))
#'
AverageExpression <- function(
object,
assays = NULL,
features = NULL,
return.seurat = FALSE,
add.ident = NULL,
slot = 'data',
use.scale = FALSE,
use.counts = FALSE,
verbose = TRUE,
...
) {
CheckDots(..., fxns = 'CreateSeuratObject')
if (use.scale) {
.Deprecated(msg = "'use.scale' is a deprecated argument, please use the 'slot' argument instead")
slot <- 'scale.data'
}
if (use.counts) {
.Deprecated(msg = "'use.counts' is a deprecated argument, please use the 'slot' argument instead")
if (use.scale) {
warning("Both 'use.scale' and 'use.counts' were set; using counts", call. = FALSE, immediate. = TRUE)
}
slot <- 'counts'
}
fxn.average <- switch(
EXPR = slot,
'data' = function(x) {
rowMeans(x = expm1(x = x))
},
rowMeans
)
object.assays <- FilterObjects(object = object, classes.keep = 'Assay')
assays <- assays %||% object.assays
ident.orig <- Idents(object = object)
orig.levels <- levels(x = Idents(object = object))
ident.new <- c()
if (!all(assays %in% object.assays)) {
assays <- assays[assays %in% object.assays]
if (length(assays) == 0) {
stop("None of the requested assays are present in the object")
} else {
warning("Requested assays that do not exist in object. Proceeding with existing assays only.")
}
}
if (!is.null(x = add.ident)) {
new.data <- FetchData(object = object, vars = add.ident)
new.ident <- paste(
Idents(object)[rownames(x = new.data)],
new.data[, 1],
sep = '_'
)
Idents(object, cells = rownames(new.data)) <- new.ident
}
data.return <- list()
for (i in 1:length(x = assays)) {
data.use <- GetAssayData(
object = object,
assay = assays[i],
slot = slot
)
features.assay <- features
if (length(x = intersect(x = features, y = rownames(x = data.use))) < 1 ) {
features.assay <- rownames(x = data.use)
}
data.all <- list(data.frame(row.names = features.assay))
for (j in levels(x = Idents(object))) {
temp.cells <- WhichCells(object = object, idents = j)
features.assay <- unique(x = intersect(x = features.assay, y = rownames(x = data.use)))
if (length(x = temp.cells) == 1) {
data.temp <- (data.use[features.assay, temp.cells])
# transform data if needed (alternative: apply fxn.average to single value above)
# if (!(use.scale | use.counts)) { # equivalent: slot.use == "data"
if (slot == 'data') {
data.temp <- expm1(x = data.temp)
}
}
if (length(x = temp.cells) > 1 ) {
data.temp <- fxn.average(data.use[features.assay, temp.cells, drop = FALSE])
}
data.all[[j]] <- data.temp
if (verbose) {
message(paste("Finished averaging", assays[i], "for cluster", j))
}
if (i == 1) {
ident.new <- c(ident.new, as.character(x = ident.orig[temp.cells[1]]))
}
}
names(x = ident.new) <- levels(x = Idents(object))
data.return[[i]] <- do.call(cbind, data.all)
names(x = data.return)[i] <- assays[[i]]
}
if (return.seurat) {
toRet <- CreateSeuratObject(
counts = data.return[[1]],
project = "Average",
assay = names(x = data.return)[1],
...
)
#for multimodal data
if (length(x = data.return) > 1) {
for (i in 2:length(x = data.return)) {
toRet[[names(x = data.return)[i]]] <- CreateAssayObject(counts = data.return[[i]])
}
}
if (DefaultAssay(object = object) %in% names(x = data.return)) {
DefaultAssay(object = toRet) <- DefaultAssay(object = object)
}
Idents(toRet, cells = colnames(x = toRet)) <- ident.new[colnames(x = toRet)]
Idents(object = toRet) <- factor(
x = Idents(object = toRet),
levels = as.character(x = orig.levels),
ordered = TRUE
)
# finish setting up object if it is to be returned
toRet <- NormalizeData(object = toRet, verbose = verbose)
toRet <- ScaleData(object = toRet, verbose = verbose)
return(toRet)
} else {
return(data.return)
}
}
#' Match the case of character vectors
#'
#' @param search A vector of search terms
#' @param match A vector of characters whose case should be matched
#'
#' @return Values from search present in match with the case of match
#'
#' @export
#'
#' @examples
#' cd_genes <- c('Cd79b', 'Cd19', 'Cd200')
#' CaseMatch(search = cd_genes, match = rownames(x = pbmc_small))
#'
CaseMatch <- function(search, match) {
search.match <- sapply(
X = search,
FUN = function(s) {
return(grep(
pattern = paste0('^', s, '$'),
x = match,
ignore.case = TRUE,
perl = TRUE,
value = TRUE
))
}
)
return(unlist(x = search.match))
}
#' Score cell cycle phases
#'
#' @param object A Seurat object
#' @param s.features A vector of features associated with S phase
#' @param g2m.features A vector of features associated with G2M phase
#' @param set.ident If true, sets identity to phase assignments
#' @param ... Arguments to be passed to \code{\link{AddModuleScore}}
#' Stashes old identities in 'old.ident'
#'
#' @return A Seurat object with the following columns added to object meta data: S.Score, G2M.Score, and Phase
#'
#' @seealso \code{AddModuleScore}
#'
#' @export
#'
#' @examples
#' \dontrun{
#' # pbmc_small doesn't have any cell-cycle genes
#' # To run CellCycleScoring, please use a dataset with cell-cycle genes
#' # An example is available at http://satijalab.org/seurat/cell_cycle_vignette.html
#' pbmc_small <- CellCycleScoring(
#' object = pbmc_small,
#' g2m.features = cc.genes$g2m.genes,
#' s.features = cc.genes$s.genes
#' )
#' head(x = [email protected])
#' }
#'
CellCycleScoring <- function(
object,
s.features,
g2m.features,
set.ident = FALSE,
...
) {
name <- 'Cell.Cycle'
features <- list('S.Score' = s.features, 'G2M.Score' = g2m.features)
object.cc <- AddModuleScore(
object = object,
features = features,
name = name,
ctrl = min(vapply(X = features, FUN = length, FUN.VALUE = numeric(length = 1))),
...
)
cc.columns <- grep(pattern = name, x = colnames(x = object.cc[[]]), value = TRUE)
cc.scores <- object.cc[[cc.columns]]
rm(object.cc)
CheckGC()
assignments <- apply(
X = cc.scores,
MARGIN = 1,
FUN = function(scores, first = 'S', second = 'G2M', null = 'G1') {
if (all(scores < 0)) {
return(null)
} else {
if (length(which(x = scores == max(scores))) > 1) {
return('Undecided')
} else {
return(c(first, second)[which(x = scores == max(scores))])
}
}
}
)
cc.scores <- merge(x = cc.scores, y = data.frame(assignments), by = 0)
colnames(x = cc.scores) <- c('rownames', 'S.Score', 'G2M.Score', 'Phase')
rownames(x = cc.scores) <- cc.scores$rownames
cc.scores <- cc.scores[, c('S.Score', 'G2M.Score', 'Phase')]
object[[colnames(x = cc.scores)]] <- cc.scores
if (set.ident) {
object[['old.ident']] <- Idents(object = object)
Idents(object = object) <- 'Phase'
}
return(object)
}
#' Slim down a multi-species expression matrix, when only one species is primarily of interenst.
#'
#' Valuable for CITE-seq analyses, where we typically spike in rare populations of 'negative control' cells from a different species.
#'
#' @param object A UMI count matrix. Should contain rownames that start with
#' the ensuing arguments prefix.1 or prefix.2
#' @param prefix The prefix denoting rownames for the species of interest.
#' Default is "HUMAN_". These rownames will have this prefix removed in the returned matrix.
#' @param controls The prefix denoting rownames for the species of 'negative
#' control' cells. Default is "MOUSE_".
#' @param ncontrols How many of the most highly expressed (average) negative
#' control features (by default, 100 mouse genes), should be kept? All other
#' rownames starting with prefix.2 are discarded.
#'
#' @return A UMI count matrix. Rownames that started with \code{prefix} have this
#' prefix discarded. For rownames starting with \code{controls}, only the
#' \code{ncontrols} most highly expressed features are kept, and the
#' prefix is kept. All other rows are retained.
#'
#' @importFrom Matrix rowSums
#'
#' @export
#'
#' @examples
#' \dontrun{
#' cbmc.rna.collapsed <- CollapseSpeciesExpressionMatrix(cbmc.rna)
#' }
#'
CollapseSpeciesExpressionMatrix <- function(
object,
prefix = "HUMAN_",
controls = "MOUSE_",
ncontrols = 100
) {
features <- grep(pattern = prefix, x = rownames(x = object), value = TRUE)
controls <- grep(pattern = controls, x = rownames(x = object), value = TRUE)
others <- setdiff(x = rownames(x = object), y = c(features, controls))
controls <- rowSums(x = object[controls, ])
controls <- names(x = head(
x = sort(x = controls, decreasing = TRUE),
n = ncontrols
))
object <- object[c(features, controls, others), ]
rownames(x = object) <- gsub(
pattern = prefix,
replacement = '',
x = rownames(x = object)
)
return(object)
}
#' Run a custom distance function on an input data matrix
#'
#' @author Jean Fan
#'
#' @param my.mat A matrix to calculate distance on
#' @param my.function A function to calculate distance
#' @param ... Extra parameters to my.function
#'
#' @return A distance matrix
#'
#' @importFrom stats as.dist
#'
#' @export
#'
#' @examples
#' # Define custom distance matrix
#' manhattan.distance <- function(x, y) return(sum(abs(x-y)))
#'
#' input.data <- GetAssayData(pbmc_small, assay.type = "RNA", slot = "scale.data")
#' cell.manhattan.dist <- CustomDistance(input.data, manhattan.distance)
#'
CustomDistance <- function(my.mat, my.function, ...) {
CheckDots(..., fxns = my.function)
n <- ncol(x = my.mat)
mat <- matrix(data = 0, ncol = n, nrow = n)
colnames(x = mat) <- rownames(x = mat) <- colnames(x = my.mat)
for (i in 1:nrow(x = mat)) {
for (j in 1:ncol(x = mat)) {
mat[i,j] <- my.function(my.mat[, i], my.mat[, j], ...)
}
}
return(as.dist(m = mat))
}
#' Calculate the mean of logged values
#'
#' Calculate mean of logged values in non-log space (return answer in log-space)
#'
#' @param x A vector of values
#' @param ... Other arguments (not used)
#'
#' @return Returns the mean in log-space
#'
#' @export
#'
#' @examples
#' ExpMean(x = c(1, 2, 3))
#'
ExpMean <- function(x, ...) {
if (inherits(x = x, what = 'AnyMatrix')) {
return(apply(X = x, FUN = function(i) {log(x = mean(x = exp(x = i) - 1) + 1)}, MARGIN = 1))
} else {
return(log(x = mean(x = exp(x = x) - 1) + 1))
}
}
#' Export Seurat object for UCSC cell browser
#'
#' @param object Seurat object
#' @param dir path to directory where to save exported files. These are:
#' exprMatrix.tsv, tsne.coords.tsv, meta.tsv, markers.tsv and a default cellbrowser.conf
#' @param dataset.name name of the dataset. Defaults to Seurat project name
#' @param reductions vector of reduction names to export
#' @param markers.file path to file with marker genes
#' @param cluster.field name of the metadata field containing cell cluster
#' @param cb.dir path to directory where to create UCSC cellbrowser static
#' website content root, e.g. an index.html, .json files, etc. These files
#' can be copied to any webserver. If this is specified, the cellbrowser
#' package has to be accessible from R via reticulate.
#' @param port on which port to run UCSC cellbrowser webserver after export
#' @param skip.expr.matrix whether to skip exporting expression matrix
#' @param skip.metadata whether to skip exporting metadata
#' @param skip.reductions whether to skip exporting reductions
#' @param ... specifies the metadata fields to export. To supply field with
#' human readable name, pass name as \code{field="name"} parameter.
#'
#' @return This function exports Seurat object as a set of tsv files
#' to \code{dir} directory, copying the \code{markers.file} if it is
#' passed. It also creates the default \code{cellbrowser.conf} in the
#' directory. This directory could be read by \code{cbBuild} to
#' create a static website viewer for the dataset. If \code{cb.dir}
#' parameter is passed, the function runs \code{cbBuild} (if it is
#' installed) to create this static website in \code{cb.dir} directory.
#' If \code{port} parameter is passed, it also runs the webserver for
#' that directory and opens a browser.
#'
#' @author Maximilian Haeussler, Nikolay Markov
#'
#' @importFrom utils browseURL
#' @importFrom reticulate py_module_available import
#' @importFrom tools file_ext
#'
#' @export
#'
#' @examples
#' \dontrun{
#' ExportToCellbrowser(object = pbmc_small, dataset.name = "PBMC", dir = "out")
#' }
#'
ExportToCellbrowser <- function(
object,
dir,
dataset.name = Project(object = object),
reductions = "tsne",
markers.file = NULL,
cluster.field = "Cluster",
cb.dir = NULL,
port = NULL,
skip.expr.matrix = FALSE,
skip.metadata = FALSE,
skip.reductions = FALSE,
...
) {
vars <- c(...)
if (is.null(x = vars)) {
vars <- c("nCount_RNA", "nFeature_RNA")
if (length(x = levels(x = Idents(object = object))) > 1) {
vars <- c(vars, cluster.field)
names(x = vars) <- c("", "", "ident")
}
}
names(x = vars) <- names(x = vars) %||% vars
names(x = vars) <- sapply(
X = 1:length(x = vars),
FUN = function(i) {
return(ifelse(
test = nchar(x = names(x = vars)[i]) > 0,
yes = names(x = vars[i]),
no = vars[i]
))
}
)
if (!is.null(x = port) && is.null(x = cb.dir)) {
stop("cb.dir parameter is needed when port is set")
}
if (!dir.exists(paths = dir)) {
dir.create(path = dir)
}
if (!dir.exists(paths = dir)) {
stop("Output directory ", dir, " cannot be created or is a file")
}
if (dataset.name == "SeuratProject") {
warning("Using default project name means that you may overwrite project with the same name in the cellbrowser html output folder")
}
order <- colnames(x = object)
enum.fields <- c()
# Export expression matrix:
if (!skip.expr.matrix) {
# Relatively memory inefficient - maybe better to convert to sparse-row and write in a loop, row-by-row?
df <- as.data.frame(x = as.matrix(x = GetAssayData(object = object)))
df <- data.frame(gene = rownames(x = object), df, check.names = FALSE)
gzPath <- file.path(dir, "exprMatrix.tsv.gz")
z <- gzfile(gzPath, "w")
message("Writing expression matrix to ", gzPath)
write.table(x = df, sep = "\t", file = z, quote = FALSE, row.names = FALSE)
close(con = z)
}
# Export cell embeddings
embeddings.conf <- c()
for (reduction in reductions) {
if (!skip.reductions) {
df <- Embeddings(object = object, reduction = reduction)
if (ncol(x = df) > 2) {
warning(
'Embedding ',
reduction,
' has more than 2 coordinates, taking only the first 2'
)
df <- df[, 1:2]
}
colnames(x = df) <- c("x", "y")
df <- data.frame(cellId = rownames(x = df), df)
fname <- file.path(dir, paste0(reduction, '.coords.tsv'))
message("Writing embeddings to ", fname)
write.table(
x = df[order, ],
sep = "\t",
file = fname,
quote = FALSE,
row.names = FALSE
)
}
conf <- sprintf(
'{"file": "%s.coords.tsv", "shortLabel": "Seurat %1$s"}',
reduction
)
embeddings.conf <- c(embeddings.conf, conf)
}
# Export metadata
df <- data.frame(row.names = rownames(x = object[[]]))
df <- FetchData(object = object, vars = names(x = vars))
colnames(x = df) <- vars
enum.fields <- Filter(
f = function(name) {!is.numeric(x = df[[name]])},
x = vars
)
if (!skip.metadata) {
fname <- file.path(dir, "meta.tsv")
message("Writing meta data to ", fname)
df <- data.frame(Cell = rownames(x = df), df, check.names = FALSE)
write.table(
x = df[order, ],
sep = "\t",
file = fname,
quote = FALSE,
row.names = FALSE
)
}
# Export markers
markers.string <- ''
if (!is.null(x = markers.file)) {
ext <- file_ext(x = markers.file)
fname <- paste0("markers.", ext)
file.copy(from = markers.file, to = file.path(dir, fname))
markers.string <- sprintf(
'markers = [{"file": "%s", "shortLabel": "Seurat Cluster Markers"}]',
fname
)
}
config <- c(
'name="%s"',
'shortLabel="%1$s"',
'exprMatrix="exprMatrix.tsv.gz"',
'#tags = ["10x", "smartseq2"]',
'meta="meta.tsv"',
'# possible values: "gencode-human", "gencode-mouse", "symbol" or "auto"',
'geneIdType="auto"',
'clusterField="%s"',
'labelField="%2$s"',
'enumFields=%s',
'%s',
'coords=%s'
)
config <- paste(config, collapse = '\n')
enum.string <- paste0(
"[",
paste(paste0('"', enum.fields, '"'), collapse = ", "),
"]"
)
coords.string <- paste0(
"[",
paste(embeddings.conf, collapse = ",\n"),
"]"
)
config <- sprintf(
config,
dataset.name,
cluster.field,
enum.string,
markers.string,
coords.string
)
fname <- file.path(dir, "cellbrowser.conf")
if (file.exists(fname)) {
message(
"`cellbrowser.conf` already exists in target directory, refusing to ",
"overwrite it"
)
} else {
cat(config, file = fname)
}
message("Prepared cellbrowser directory ", dir)
if (!is.null(x = cb.dir)) {
if (!py_module_available(module = "cellbrowser")) {
stop(
"The Python package `cellbrowser` is required to prepare and run ",
"Cellbrowser. Please install it ",
"on the Unix command line with `sudo pip install cellbrowser` (if root) ",
"or `pip install cellbrowser --user` (as a non-root user). ",
"To adapt the Python that is used, you can either set the env. variable RETICULATE_PYTHON ",
"or do `require(reticulate) and use one of these functions: use_python(), use_virtualenv(), use_condaenv(). ",
"See https://rstudio.github.io/reticulate/articles/versions.html; ",
"at the moment, R's reticulate is using this Python: ",
import(module = 'sys')$executable,
". "
)
}
if (!is.null(x = port)) {
port <- as.integer(x = port)
}
message("Converting cellbrowser directory to html/json files")
cb <- import(module = "cellbrowser")
cb$cellbrowser$build(dir, cb.dir)
if (!is.null(port)) {
message("Starting http server")
cb$cellbrowser$stop()
cb$cellbrowser$serve(cb.dir, port)
Sys.sleep(time = 0.4)
browseURL(url = paste0("http://localhost:", port))
}
}
}
#' Calculate the standard deviation of logged values
#'
#' Calculate SD of logged values in non-log space (return answer in log-space)
#'
#' @param x A vector of values
#'
#' @return Returns the standard deviation in log-space
#'
#' @importFrom stats sd
#'
#' @export
#'
#' @examples
#' ExpSD(x = c(1, 2, 3))
#'
ExpSD <- function(x) {
return(log1p(x = sd(x = expm1(x = x))))
}
#' Calculate the variance of logged values
#'
#' Calculate variance of logged values in non-log space (return answer in
#' log-space)
#'
#' @param x A vector of values
#'
#' @return Returns the variance in log-space
#'
#' @importFrom stats var
#'
#' @export
#'
#' @examples
#' ExpVar(x = c(1, 2, 3))
#'
ExpVar <- function(x) {
return(log1p(x = var(x = expm1(x = x))))
}
#' Get updated synonyms for gene symbols
#'
#' Find current gene symbols based on old or alias symbols using the gene
#' names database from the HUGO Gene Nomenclature Committee (HGNC)
#'
#' @details For each symbol passed, we query the HGNC gene names database for
#' current symbols that have the provided symbol as either an alias
#' (\code{alias_symbol}) or old (\code{prev_symbol}) symbol. All other queries
#' are \strong{not} supported.
#'
#' @note This function requires internet access
#'
#' @param symbols A vector of gene symbols
#' @param timeout Time to wait before cancelling query in seconds
#' @param several.ok Allow several current gene sybmols for each provided symbol
#' @param verbose Show a progress bar depicting search progress
#' @param ... Extra parameters passed to \code{\link[httr]{GET}}
#'
#' @return For \code{GeneSymbolThesarus}, if \code{several.ok}, a named list
#' where each entry is the current symbol found for each symbol provided and the
#' names are the provided symbols. Otherwise, a named vector with the same information.
#'
#' @source \url{https://www.genenames.org/} \url{http://rest.genenames.org/}
#'
#' @importFrom utils txtProgressBar setTxtProgressBar
#' @importFrom httr GET accept_json timeout status_code content
#'
#' @rdname UpdateSymbolList
#' @name UpdateSymbolList
#'
#' @export
#'
#' @seealso \code{\link[httr]{GET}}
#'
#' @examples
#' \dontrun{
#' GeneSybmolThesarus(symbols = c("FAM64A"))
#' }
#'
GeneSymbolThesarus <- function(
symbols,
timeout = 10,
several.ok = FALSE,
verbose = TRUE,
...
) {
db.url <- 'http://rest.genenames.org/fetch'
search.types <- c('alias_symbol', 'prev_symbol')
synonyms <- vector(mode = 'list', length = length(x = symbols))
not.found <- vector(mode = 'logical', length = length(x = symbols))
multiple.found <- vector(mode = 'logical', length = length(x = symbols))
names(x = multiple.found) <- names(x = not.found) <- names(x = synonyms) <- symbols
if (verbose) {
pb <- txtProgressBar(max = length(x = symbols), style = 3, file = stderr())
}
for (symbol in symbols) {
sym.syn <- character()
for (type in search.types) {
response <- GET(
url = paste(db.url, type, symbol, sep = '/'),
config = c(accept_json(), timeout(seconds = timeout)),
...
)
if (!identical(x = status_code(x = response), y = 200L)) {
next
}
response <- content(x = response)
if (response$response$numFound != 1) {
if (response$response$numFound > 1) {
warning(
"Multiple hits found for ",
symbol,
" as ",
type,
", skipping",
call. = FALSE,
immediate. = TRUE
)
}
next
}
sym.syn <- c(sym.syn, response$response$docs[[1]]$symbol)
}
not.found[symbol] <- length(x = sym.syn) < 1
multiple.found[symbol] <- length(x = sym.syn) > 1
if (length(x = sym.syn) == 1 || (length(x = sym.syn) > 1 && several.ok)) {
synonyms[[symbol]] <- sym.syn
}
if (verbose) {
setTxtProgressBar(pb = pb, value = pb$getVal() + 1)
}
}
if (verbose) {
close(con = pb)
}
if (sum(not.found) > 0) {
warning(
"The following symbols had no synonyms: ",
paste(names(x = which(x = not.found)), collapse = ', '),
call. = FALSE,
immediate. = TRUE
)
}
if (sum(multiple.found) > 0) {
msg <- paste(
"The following symbols had multiple synonyms:",
paste(names(x = which(x = multiple.found)), sep = ', ')
)
if (several.ok) {
message(msg)
message("Including anyways")
} else {
warning(msg, call. = FALSE, immediate. = TRUE)
}
}
synonyms <- Filter(f = Negate(f = is.null), x = synonyms)
if (!several.ok) {
synonyms <- unlist(x = synonyms)
}
return(synonyms)
}
#' Calculate the variance to mean ratio of logged values
#'
#' Calculate the variance to mean ratio (VMR) in non-logspace (return answer in
#' log-space)
#'
#' @param x A vector of values
#' @param ... Other arguments (not used)
#'
#' @return Returns the VMR in log-space
#'
#' @importFrom stats var
#'
#' @export
#'
#' @examples
#' LogVMR(x = c(1, 2, 3))
#'
LogVMR <- function(x, ...) {
if (inherits(x = x, what = 'AnyMatrix')) {
return(apply(X = x, FUN = function(i) {log(x = var(x = exp(x = i) - 1) / mean(x = exp(x = i) - 1))}, MARGIN = 1))
} else {
return(log(x = var(x = exp(x = x) - 1) / mean(x = exp(x = x) - 1)))
}
}