-
Notifications
You must be signed in to change notification settings - Fork 78
/
preprocess.R
1422 lines (1367 loc) · 58.3 KB
/
preprocess.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
#################################### qc ########################################
#' General QC for liger object
#' @description Calculate number of UMIs, number of detected features and
#' percentage of feature subset (e.g. mito) expression per cell.
#' @param object \linkS4class{liger} object with \code{rawData} available in
#' each \linkS4class{ligerDataset} embedded
#' @param mito,ribo,hemo Whether to calculate the expression percentage of
#' mitochondrial, ribosomal or hemoglobin genes, respectively. Default
#' \code{TRUE}.
#' @param features Feature names matching the feature subsets that users want to
#' calculate the expression percentage with. A vector for a single subset, or a
#' named list for multiple subset. Default \code{NULL}.
#' @param pattern Regex patterns for matching the feature subsets that users
#' want to calculate the expression percentage with. A vector for a single
#' subset, or a named list for multiple subset. Default \code{NULL}.
#' @param useDatasets A character vector of the names, a numeric or logical
#' vector of the index of the datasets to be included for QC. Default
#' \code{NULL} performs QC on all datasets.
#' @param chunkSize Integer number of cells to include in a chunk when working
#' on HDF5 based dataset. Default \code{1000}
#' @param verbose Logical. Whether to show information of the progress. Default
#' \code{getOption("ligerVerbose")} or \code{TRUE} if users have not set.
#' @return Updated \code{object} with \code{nUMI}, \code{nGene} updated
#' in \code{cellMeta(object)}, as well as expression percentage value for each
#' feature subset.
#' @export
#' @examples
#' pbmc <- runGeneralQC(pbmc)
runGeneralQC <- function(
object,
mito = TRUE,
ribo = TRUE,
hemo = TRUE,
features = NULL,
pattern = NULL,
useDatasets = NULL,
chunkSize = 1000,
verbose = getOption("ligerVerbose", TRUE)
) {
.checkObjVersion(object)
useDatasets <- .checkUseDatasets(object, useDatasets)
# Process the the two arguments all into one named list of feature names
# before exactly calculate the percentage
featureSubsets <- list()
allFeatures <- unique(unlist(lapply(datasets(object), rownames),
use.names = FALSE))
# Work on the presets
if (isTRUE(mito))
featureSubsets$mito <- grep("^MT-", allFeatures, value = TRUE)
if (isTRUE(ribo))
featureSubsets$ribo <- grep("^RP[SL]", allFeatures, value = TRUE)
if (isTRUE(hemo))
featureSubsets$hemo <- grep("^HB[^(P)]", allFeatures, value = TRUE)
# Then process the user specified gene sets
if (!is.null(features)) {
if (is.list(features)) {
featureSubsets <- c(featureSubsets, features)
} else if (is.vector(features)) {
featureSubsets[["featureSubset_name"]] <- features
}
}
if (!is.null(pattern)) {
if (is.list(pattern)) {
pattern <- lapply(pattern, function(x) {
grep(x, allFeatures, value = TRUE)
})
featureSubsets <- c(featureSubsets, pattern)
} else if (is.vector(pattern)) {
pattern <- grep(pattern, allFeatures, value = TRUE)
featureSubsets[["featureSubset_pattern"]] <- pattern
}
}
# Start calculation on each dataset
newResultNames <- c("nUMI", "nGene", names(featureSubsets))
for (d in useDatasets) {
ld <- dataset(object, d)
if (isTRUE(verbose))
cliID <- cli::cli_process_start("calculating QC for dataset {.val {d}}")
if (isH5Liger(ld))
results <- runGeneralQC.h5(
ld,
featureSubsets = featureSubsets,
chunkSize = chunkSize,
verbose = verbose
)
else
results <- runGeneralQC.Matrix(
ld,
featureSubsets = featureSubsets,
verbose = verbose
)
object@cellMeta[object$dataset == d, newResultNames] <- results$cell
featureMeta(ld, check = FALSE)$nCell <- results$feature
datasets(object, check = FALSE)[[d]] <- ld
if (isTRUE(verbose)) cli::cli_process_done(id = cliID)
}
return(object)
}
#' Calculate general QC on H5 based ligerDataset object
#' @param object ligerDataset object
#' @param featureSubsets Named list passed from \code{runGeneralQC}
#' @param chunkSize Integer
#' @return data.frame
#' @noRd
runGeneralQC.h5 <- function(
object,
featureSubsets = NULL,
chunkSize = 1000,
verbose = getOption("ligerVerbose", TRUE)) {
allFeatures <- rownames(object)
# Initialize results
cell <- data.frame(row.names = colnames(object))
cell$nUMI <- 0
cell$nGene <- 0
for (i in names(featureSubsets)) {
cell[[i]] <- 0
}
nCell <- rep(0, nrow(object))
rowIndices <- lapply(featureSubsets, function(x) allFeatures %in% x)
# Calculate in only one iteration
H5Apply(
object,
init = list(cell = cell, feature = nCell),
useData = "rawData",
chunkSize = chunkSize,
verbose = verbose,
FUN = function(chunk, sparseXIdx, cellIdx, values) {
nUMI <- colSums(chunk)
values$cell$nUMI[cellIdx] <- nUMI
nonzero <- methods::as(chunk, "lMatrix")
values$cell$nGene[cellIdx] <- colSums(nonzero)
for (fs in names(rowIndices)) {
values$cell[[fs]][cellIdx] <-
colSums(chunk[rowIndices[[fs]], , drop = FALSE]) / nUMI *
100
}
values$feature <- values$feature + Matrix::rowSums(nonzero)
return(values)
}
)
}
#' Calculate general QC on in memory matrix based ligerDataset object
#' @param object ligerDataset object
#' @param featureSubsets Named list passed from \code{runGeneralQC}
#' @return data.frame
#' @noRd
runGeneralQC.Matrix <- function(
object,
featureSubsets = NULL,
verbose = getOption("ligerVerbose", TRUE)) {
nUMI <- Matrix::colSums(rawData(object))
# Instead of using `nonzero <- rawData > 0` which generates dense logical
# matrix, keep it sparse with 1 for TRUE
# nonzero <- rawData(object)
# nonzero@x <- rep(1, length(nonzero@x))
nonzero <- methods::as(rawData(object), "lMatrix")
nGene <- Matrix::colSums(nonzero)
nCell <- Matrix::rowSums(nonzero)
results <- data.frame(nUMI = nUMI, nGene = nGene,
row.names = colnames(object))
if (length(featureSubsets) > 0) {
percentages <- lapply(featureSubsets, function(x) {
rowIdx <- rownames(object) %in% x
if (sum(rowIdx) == 0) {
return(rep(0, ncol(object)))
} else {
return(colSums(rawData(object)[rowIdx, , drop = FALSE]) /
colSums(rawData(object)) * 100)
}
})
results <- cbind(results, as.data.frame(percentages))
}
list(cell = results, feature = nCell)
}
#' Calculate proportion mitochondrial contribution
#' @description
#' Calculates proportion of mitochondrial contribution based on raw or
#' normalized data.
#' @param object \code{liger} object.
#' @param use.norm \bold{Deprecated} Whether to use cell normalized data in
#' calculating contribution. Default \code{FALSE}.
#' @param pattern Regex pattern for identifying mitochondrial genes. Default
#' \code{"^mt-"} for mouse.
#' @return Named vector containing proportion of mitochondrial contribution for
#' each cell.
#' @export
#' @note
#' \code{getProportionMito} will be deprecated because
#' \code{\link{runGeneralQC}} generally covers and expands its use case.
#' @examples
#' # Example dataset does not contain MT genes, expected to see a message
#' pbmc$mito <- getProportionMito(pbmc)
getProportionMito <- function(object, use.norm = FALSE, pattern = "^mt-") {
lifecycle::deprecate_warn("1.99.0", "getProportionMito()",
"runGeneralQC()")
result <- numeric()
for (d in names(object)) {
ld <- dataset(object, d)
mitoGeneIdx <- grep(pattern, rownames(ld))
if (isTRUE(use.norm)) {
pctMT <- colSums(normData(ld)[mitoGeneIdx, , drop = FALSE]) /
colSums(normData(ld))
} else {
pctMT <- colSums(rawData(ld)[mitoGeneIdx, , drop = FALSE]) /
colSums(rawData(ld))
}
names(pctMT) <- colnames(ld)
result <- c(result, pctMT)
}
if (all(result == 0)) {
cli::cli_alert_warning("Zero proportion detected in all cells")
}
return(result)
}
#' Remove missing cells or features from liger object
#' @param object \linkS4class{liger} object
#' @param orient Choose to remove non-expressing features (\code{"feature"}),
#' empty barcodes (\code{"cell"}), or both of them (\code{"both"}). Default
#' \code{"both"}.
#' @param minCells Keep features that are expressed in at least this number of
#' cells, calculated on a per-dataset base. A single value for all datasets or
#' a vector for each dataset. Default \code{NULL} only removes none expressing
#' features.
#' @param minFeatures Keep cells that express at least this number of features,
#' calculated on a per-dataset base. A single value for all datasets or a vector
#' for each dataset. Default \code{NULL} only removes none expressing cells.
#' @param useDatasets A character vector of the names, a numeric or logical
#' vector of the index of the datasets to be processed. Default
#' \code{NULL} removes empty entries from all datasets.
#' @param newH5 Logical, whether to create a new H5 file on disk for each
#' H5-based dataset on subset. Default \code{TRUE}
#' @param filenameSuffix When subsetting H5-based datasets to new H5 files, this
#' suffix will be added to all the filenames. Default \code{"removeMissing"}.
#' @param verbose Logical. Whether to show information of the progress. Default
#' \code{getOption("ligerVerbose")} or \code{TRUE} if users have not set.
#' @param ... Arguments passed to \code{\link{subsetLigerDataset}}
#' @return Updated (subset) \code{object}.
#' @export
#' @rdname removeMissing
#' @examples
#' # The example dataset does not contain non-expressing genes or empty barcodes
#' pbmc <- removeMissing(pbmc)
removeMissing <- function(
object,
orient = c("both", "feature", "cell"),
minCells = NULL,
minFeatures = NULL,
useDatasets = NULL,
newH5 = TRUE,
filenameSuffix = "removeMissing",
verbose = getOption("ligerVerbose", TRUE),
...
) {
orient <- match.arg(orient)
useDatasets <- .checkUseDatasets(object, useDatasets)
minCells <- minCells %||% rep(0, length(useDatasets))
minCells <- .checkArgLen(minCells, length(useDatasets), class = "numeric")
names(minCells) <- useDatasets
minFeatures <- minFeatures %||% rep(0, length(useDatasets))
minFeatures <- .checkArgLen(minFeatures, length(useDatasets), class = "numeric")
names(minFeatures) <- useDatasets
rmFeature <- ifelse(orient %in% c("both", "feature"), TRUE, FALSE)
rmCell <- ifelse(orient %in% c("both", "cell"), TRUE, FALSE)
datasets.new <- list()
subsetted <- c()
for (d in useDatasets) {
ld <- dataset(object, d)
if (rmFeature) {
featureIdx <- which(featureMeta(ld)$nCell > minCells[d])
} else {
featureIdx <- seq_len(nrow(ld))
}
rmFeatureDataset <- length(featureIdx) != nrow(ld)
if (rmCell) {
cellIdx <- object$dataset == d & object$nGene > minFeatures[d]
cellIdx <- colnames(object)[cellIdx]
cellIdx <- which(colnames(ld) %in% cellIdx)
} else {
cellIdx <- seq_len(ncol(ld))
}
rmCellDataset <- length(cellIdx) != ncol(ld)
subsetted <- c(subsetted, any(c(rmFeatureDataset, rmCellDataset)))
if (any(c(rmFeatureDataset, rmCellDataset))) {
if (isTRUE(verbose)) {
cli::cli_alert_info("Removing missing in dataset: {.val {d}}")
}
datasets.new[[d]] <- subsetLigerDataset(
ld,
featureIdx = featureIdx,
cellIdx = cellIdx,
filenameSuffix = filenameSuffix,
verbose = verbose,
newH5 = newH5,
...
)
} else {
datasets.new[[d]] <- ld
}
}
if (any(subsetted)) {
allCells <- unlist(lapply(datasets.new, colnames), use.names = FALSE)
object <- methods::new(
"liger",
datasets = datasets.new,
cellMeta = cellMeta(object, cellIdx = allCells,
drop = FALSE),
varFeatures = character(),
H.norm = object@H.norm[allCells, , drop = FALSE]
)
}
return(object)
}
#' @rdname removeMissing
#' @export
#' @param slot.use \bold{Deprecated}. Always look at \code{rawData} slot of
#' inner \linkS4class{ligerDataset} objects.
#' @param use.cols \bold{Deprecated}. Previously means "treating each column as
#' a cell" when \code{TRUE}, now means \code{orient="cell"}.
#' @note
#' \code{removeMissingObs} will be deprecated. \code{removeMissing} covers and
#' expands the use case and should be easier to understand.
removeMissingObs <- function(
object,
slot.use = NULL,
use.cols = TRUE,
verbose = getOption("ligerVerbose", TRUE)) {
lifecycle::deprecate_warn("1.99.0", "removeMissingObs()",
"removeMissing()")
if (!missing(slot.use)) {
cli::cli_alert_warning("Argument {.code slot.use} is deprecated and ignored.")
}
orient <- ifelse(isTRUE(use.cols), "cell", "gene")
object <- removeMissing(object, orient, verbose = verbose)
return(object)
}
################################ Normalize #####################################
#' Normalize raw counts data
#' @description Perform library size normalization on raw counts input. As for
#' the preprocessing step of iNMF integration, by default we don't multiply the
#' normalized values with a scale factor, nor do we take the log transformation.
#' Applicable S3 methods can be found in Usage section.
#'
#' \code{normalizePeak} is designed for datasets of "atac" modality, i.e. stored
#' in \linkS4class{ligerATACDataset}. S3 method for various container object is
#' not supported yet due to difference in architecture design.
#' @param object \linkS4class{liger} object
#' @param ... Arguments to be passed to S3 methods. The "liger" method calls
#' the "ligerDataset" method, which then calls "dgCMatrix" method.
#' \code{normalizePeak} directly calls \code{normalize.dgCMatrix}.
#' @return Updated \code{object}.
#' \itemize{
#' \item{dgCMatrix method - Returns processed dgCMatrix object}
#' \item{ligerDataset method - Updates the \code{normData} slot of the object}
#' \item{liger method - Updates the \code{normData} slot of chosen datasets}
#' \item{Seurat method - Adds a named layer in chosen assay (V5), or update the
#' \code{data} slot of the chosen assay (<=V4)}
#' \item{\code{normalizePeak} - Updates the \code{normPeak} slot of chosen
#' datasets.}
#' }
#' @rdname normalize
#' @export
#' @examples
#' pbmc <- normalize(pbmc)
normalize <- function(object, ...) {
UseMethod("normalize", object)
}
#' @rdname normalize
#' @export
#' @method normalize dgCMatrix
#' @param log Logical. Whether to do a \code{log(x + 1)} transform on the
#' normalized data. Default \code{TRUE}.
#' @param scaleFactor Numeric. Scale the normalized expression value by this
#' factor before transformation. \code{NULL} for not scaling. Default
#' \code{1e4}.
normalize.dgCMatrix <- function(
object,
log = FALSE,
scaleFactor = NULL,
...
) {
scaleFactor <- .checkArgLen(scaleFactor, ncol(object), repN = TRUE, class = "numeric")
if (!is.null(scaleFactor) && any(scaleFactor <= 0)) {
cli::cli_alert_danger("Invalid {.code scaleFactor} given. Setting to {.code NULL}.")
scaleFactor <- NULL
}
normed <- object
normed@x <- object@x / rep.int(Matrix::colSums(object), diff(object@p))
if (!is.null(scaleFactor)) normed <- normed * scaleFactor
if (isTRUE(log)) normed <- log1p(normed)
return(normed)
}
#' @rdname normalize
#' @export
#' @param chunk Integer. Number of maximum number of cells in each chunk when
#' working on HDF5 file based ligerDataset. Default \code{1000}.
#' @param verbose Logical. Whether to show information of the progress. Default
#' \code{getOption("ligerVerbose")} or \code{TRUE} if users have not set.
#' @method normalize ligerDataset
normalize.ligerDataset <- function(
object,
chunk = 1000,
verbose = getOption("ligerVerbose", TRUE),
...
) {
if (!isH5Liger(object)) {
normData(object) <- normalize(rawData(object), ...)
} else {
# Initialize result
results <- list(
geneSumSq = rep(0, nrow(object)),
geneMeans = rep(0, nrow(object))
)
h5file <- getH5File(object)
resultH5Path <- "normData"
# Use safe create here in practice
## This creates the CSC sparse non-zero value array
safeH5Create(object = object, dataPath = resultH5Path,
dims = rawData(object)$dims, dtype = "double",
chunkSize = rawData(object)$chunk_dims)
# Chunk run
results <- H5Apply(
object,
function(chunk, sparseXIdx, cellIdx, values) {
normChunk <- normalize(chunk)
h5file[[resultH5Path]][sparseXIdx] <- normChunk@x
row_sums <- rowSums(normChunk)
values$geneSumSq <- values$geneSumSq +
rowSums(normChunk * normChunk)
values$geneMeans <- values$geneMeans + row_sums
return(values)
},
init = results, useData = "rawData",
chunkSize = chunk, verbose = verbose
)
results$geneMeans <- results$geneMeans / ncol(object)
featureMeta(object, check = FALSE)$geneMeans <- results$geneMeans
featureMeta(object, check = FALSE)$geneSumSq <- results$geneSumSq
normData(object, check = FALSE) <- h5file[[resultH5Path]]
h5fileInfo(object, "normData", check = FALSE) <- resultH5Path
}
return(object)
}
#' @rdname normalize
#' @export
#' @param useDatasets A character vector of the names, a numeric or logical
#' vector of the index of the datasets to be normalized. Should specify ATACseq
#' datasets when using \code{normalizePeak}. Default \code{NULL} normalizes all
#' valid datasets.
#' @param format.type,remove.missing \bold{Deprecated}. The functionality of
#' these is covered through other parts of the whole workflow and is no long
#' needed. Will be ignored if specified.
#' @method normalize liger
normalize.liger <- function(
object,
useDatasets = NULL,
verbose = getOption("ligerVerbose", TRUE),
format.type = NULL,
remove.missing = NULL,
...
) {
.deprecateArgs(defunct = c("format.type", "remove.missing"))
.checkObjVersion(object)
useDatasets <- .checkUseDatasets(object, useDatasets)
object <- recordCommand(object, ..., dependencies = "hdf5r")
for (d in useDatasets) {
if (isTRUE(verbose)) cliID <- cli::cli_process_start("Normalizing datasets {.val {d}}")
# `d` is the name of each dataset
ld <- dataset(object, d)
ld <- normalize(ld, verbose = verbose, ...)
datasets(object, check = FALSE)[[d]] <- ld
}
if (isTRUE(verbose)) cli::cli_process_done(id = cliID)
object
}
#' @rdname normalize
#' @export
#' @param assay Name of assay to use. Default \code{NULL} uses current active
#' assay.
#' @param save For Seurat>=4.9.9, the name of layer to store normalized data.
#' Default \code{"ligerNormData"}. For older Seurat, stored to \code{data} slot.
#' @param layer Where the input raw counts should be from. Default
#' \code{"counts"}. For older Seurat, always retrieve from \code{counts} slot.
#' @method normalize Seurat
normalize.Seurat <- function(
object,
assay = NULL,
layer = "counts",
save = "ligerNormData",
...
) {
raw <- .getSeuratData(object, layer = layer, slot = "counts",
assay = assay)
if (!is.list(raw)) normed <- normalize(raw, ...)
else normed <- lapply(raw, normalize, ...)
object <- .setSeuratData(object, layer = layer, save = save, slot = "data",
value = normed, assay = assay)
return(object)
}
#' @rdname normalize
#' @export
normalizePeak <- function(
object,
useDatasets = NULL,
verbose = getOption("ligerVerbose", TRUE),
...
) {
useDatasets <- .checkUseDatasets(object, useDatasets, modal = "atac")
object <- recordCommand(object, ..., dependencies = "hdf5r")
for (d in useDatasets) {
if (isTRUE(verbose)) cliID <- cli::cli_process_start("Normalizing peak of dataset: {.val {d}}")
# `d` is the name of each dataset
ld <- dataset(object, d)
normPeak(ld, check = FALSE) <- normalize(rawPeak(ld), ...)
datasets(object, check = FALSE)[[d]] <- ld
if (isTRUE(verbose)) cli::cli_process_done(id = cliID)
}
object
}
############################### Select Genes ###################################
#' Select a subset of informative genes
#' @description This function identifies highly variable genes from each dataset
#' and combines these gene sets (either by union or intersection) for use in
#' downstream analysis. Assuming that gene expression approximately follows a
#' Poisson distribution, this function identifies genes with gene expression
#' variance above a given variance threshold (relative to mean gene expression).
#' Alternatively, we allow selecting a desired number of genes for each dataset
#' by ranking the relative variance, and then take the combination.
#' @export
#' @rdname selectGenes
#' @param object A \linkS4class{liger}, \linkS4class{ligerDataset} or
#' \code{Seurat} object, with normalized data available (no scale factor
#' multipled nor log transformed).
#' @param thresh Variance threshold used to identify variable genes. Higher
#' threshold results in fewer selected genes. Liger and Seurat S3 methods accept
#' a single value or a vector with specific threshold for each dataset in
#' \code{useDatasets}.* Default \code{0.1}.
#' @param nGenes Number of genes to find for each dataset. By setting this,
#' we optimize the threshold used for each dataset so that we get \code{nGenes}
#' selected features for each dataset. Accepts single value or a vector for
#' dataset specific setting matching \code{useDataset}.* Default \code{NULL}
#' does not optimize.
#' @param alpha Alpha threshold. Controls upper bound for expected mean gene
#' expression. Lower threshold means higher upper bound. Default \code{0.99}.
#' @param combine How to combine variable genes selected from all datasets.
#' Choose from \code{"union"} or \code{"intersection"}. Default \code{"union"}.
#' @param verbose Logical. Whether to show information of the progress. Default
#' \code{getOption("ligerVerbose")} or \code{TRUE} if users have not set.
#' @param ... Arguments passed to other methods.
#' @return Updated object
#' \itemize{
#' \item{liger method - Each involved dataset stored in
#' \linkS4class{ligerDataset} is updated with its \code{\link{featureMeta}}
#' slot and \code{varUnsharedFeatures} slot (if requested with
#' \code{useUnsharedDatasets}), while \code{\link{varFeatures}(object)} will be
#' updated with the final combined gene set.}
#' \item{Seurat method - Final selection will be updated at
#' \code{Seurat::VariableFeatures(object)}. Per-dataset information is
#' stored in the \code{meta.features} slot of the chosen Assay.}
#' }
#' @examples
#' pbmc <- normalize(pbmc)
#' # Select basing on thresholding the relative variance
#' pbmc <- selectGenes(pbmc, thresh = .1)
#' # Select specified number for each dataset
#' pbmc <- selectGenes(pbmc, nGenes = c(60, 60))
selectGenes <- function(
object,
thresh = .1,
nGenes = NULL,
alpha = .99,
...
) {
UseMethod("selectGenes", object)
}
#' @export
#' @rdname selectGenes
#' @method selectGenes liger
#' @param useDatasets A character vector of the names, a numeric or logical
#' vector of the index of the datasets to use for shared variable feature
#' selection. Default \code{NULL} uses all datasets.
#' @param useUnsharedDatasets A character vector of the names, a numeric or
#' logical vector of the index of the datasets to use for finding unshared
#' variable features. Default \code{NULL} does not attempt to find unshared
#' features.
#' @param unsharedThresh The same thing as \code{thresh} that is applied to test
#' unshared features. A single value for all datasets in
#' \code{useUnsharedDatasets} or a vector for dataset-specific setting.* Default
#' \code{0.1}.
#' @param chunk Integer. Number of maximum number of cells in each chunk, when
#' gene selection is applied to any HDF5 based dataset. Default \code{1000}.
#' @param var.thresh,alpha.thresh,num.genes,datasets.use,unshared.datasets,unshared.thresh \bold{Deprecated}.
#' These arguments are renamed and will be removed in the future. Please see
#' function usage for replacement.
#' @param tol,do.plot,cex.use,unshared \bold{Deprecated}. Gene variability
#' metric is now visualized with separated function
#' \code{\link{plotVarFeatures}}. Users can now set none-NULL
#' \code{useUnsharedDatasets} to select unshared genes, instead of having to
#' switch \code{unshared} on.
selectGenes.liger <- function(
object,
thresh = .1,
nGenes = NULL,
alpha = .99,
useDatasets = NULL,
useUnsharedDatasets = NULL,
unsharedThresh = .1,
combine = c("union", "intersection"),
chunk = 1000,
verbose = getOption("ligerVerbose", TRUE),
var.thresh = thresh,
alpha.thresh = alpha,
num.genes = nGenes,
datasets.use = useDatasets,
unshared.datasets = useUnsharedDatasets,
unshared.thresh = unsharedThresh,
tol = NULL,
do.plot = NULL,
cex.use = NULL,
unshared = NULL,
...
) {
combine <- match.arg(combine)
.deprecateArgs(replace = list(var.thresh = "thresh",
alpha.thresh = "alpha",
num.genes = "nGenes",
datasets.use = "useDatasets",
unshared.datasets = "useUnsharedDatasets",
unshared.thresh = "unsharedThresh"),
defunct = c("tol", "do.plot", "cex.use"))
object <- recordCommand(object, ...)
datasetShared <- .checkUseDatasets(object, useDatasets)
if (!is.null(useUnsharedDatasets))
datasetUnshared <- .checkUseDatasets(object, useUnsharedDatasets)
else datasetUnshared <- NULL
useDatasets <- union(datasetShared, datasetUnshared)
thresh <- .checkArgLen(thresh, length(datasetShared), class = "numeric")
nGenes <- .checkArgLen(nGenes, length(datasetShared), class = "numeric")
unsharedThresh <- .checkArgLen(unsharedThresh, length(datasetUnshared), class = "numeric")
sharedFeature <- Reduce(intersect, lapply(datasets(object), rownames))
selectList <- list()
for (d in useDatasets) {
if (isTRUE(verbose))
cli::cli_alert_info("Selecting variable features for dataset {.val {d}}")
ld <- dataset(object, d)
thresh_i <- thresh[datasetShared == d]
nGenes_i <- nGenes[datasetShared == d]
unsharedThresh_i <- unsharedThresh[datasetUnshared == d]
ld <- .selectGenes.ligerDataset(
ld, sharedFeature = sharedFeature, thresh = thresh_i,
nGenes = nGenes_i, unshared = d %in% datasetUnshared,
unsharedThresh = unsharedThresh_i,
nUMI = cellMeta(object, "nUMI", useDatasets = d),
alpha = alpha, chunk = chunk, verbose = verbose
)
selectList[[d]] <- rownames(ld)[featureMeta(ld)$isVariable]
datasets(object, check = FALSE)[[d]] <- ld
}
if (combine == "union") selected <- Reduce(union, selectList)
else selected <- Reduce(intersect, selectList)
if (length(selected) == 0) {
cli::cli_alert_danger("No genes were selected. Lower {.code thresh} values or set {.code combine = 'union'}")
} else {
if (isTRUE(verbose))
cli::cli_alert_success("Finally {length(selected)} shared variable feature{?s} are selected.")
}
varFeatures(object) <- selected
for (d in names(object)) {
ld <- dataset(object, d)
featureMeta(ld, check = FALSE)$selected <- rownames(ld) %in% selected
datasets(object, check = FALSE)[[d]] <- ld
}
return(object)
}
#' @param sharedFeature Character vector, the feature names that are common to
#' all datasets involved for the selection. Mostly set internally by the liger
#' S3 method. Default \code{NULL} tests with all available features.
#' @param unshared Logical, whether to select variable ones from unshared
#' features.
#' @param nUMI A vector of prior QC information, number of total counts per cell
#' derived with the raw count matrix of a dataset. Mostly set internally by the
#' liger S3 method.
#' @note
#' For \code{thresh}, \code{unsharedThresh} and \code{nGenes}, ligerDataset S3
#' method only accept a single value, which most of the time got passed from
#' upstream method chain.
#' @noRd
.selectGenes.ligerDataset <- function(
object,
nUMI,
sharedFeature = NULL,
thresh = .1,
nGenes = NULL,
unshared = FALSE,
unsharedThresh = .1,
alpha = .99,
chunk = 1000,
verbose = getOption("ligerVerbose", TRUE)
) {
if (is.null(normData(object))) cli::cli_abort("Normalized data not available.")
if (is.null(sharedFeature)) sharedFeature <- rownames(object)
sharedFeature <- rownames(object) %in% sharedFeature
unsharedFeature <- !sharedFeature
selected.shared <- logical(sum(sharedFeature))
selected.unshared <- logical(sum(unsharedFeature))
if (isH5Liger(object)) {
object <- calcGeneVars.H5(object, chunkSize = chunk, verbose = verbose)
} else {
featureMeta(object, check = FALSE)$geneMeans <-
Matrix::rowMeans(normData(object))
featureMeta(object, check = FALSE)$geneVars <-
rowVars_sparse_rcpp(normData(object), featureMeta(object)$geneMeans)
}
selected.shared <- .selectGenes.withMetric(
genes = rownames(object)[sharedFeature],
means = featureMeta(object)$geneMeans[sharedFeature],
vars = featureMeta(object)$geneVars[sharedFeature],
nUMI = nUMI, dims = dim(object), thresh = thresh, alpha = alpha,
nGenes = nGenes
)
featureMeta(object, check = FALSE)$isVariable <-
rownames(object) %in% selected.shared
if (isTRUE(verbose)) {
cli::cli_alert_success("... {length(selected.shared)} feature{?s} selected out of {sum(sharedFeature)} shared feature{?s}.")
}
if (isTRUE(unshared) && length(unsharedFeature) > 0) {
selected.unshared <- .selectGenes.withMetric(
genes = rownames(object)[unsharedFeature],
means = featureMeta(object)$geneMeans[unsharedFeature],
vars = featureMeta(object)$geneVars[unsharedFeature],
nUMI = nUMI, dims = dim(object), thresh = unsharedThresh,
alpha = alpha, nGenes = nGenes
)
object@varUnsharedFeatures <- selected.unshared
if (isTRUE(verbose)) {
cli::cli_alert_success("... {length(selected.unshared)} feature{?s} selected out of {sum(unsharedFeature)} unshared feature{?s}.")
}
}
return(object)
}
#' Calculate Gene Variance for ligerDataset object
#' @param object ligerDataset object
#' @param chunkSize Integer for the maximum number of cells in each chunk.
#' Default \code{1000}.
#' @param verbose Logical. Whether to show a progress bar. Default
#' \code{getOption("ligerVerbose")} or \code{TRUE} if users have not set.
#' @return The input \code{object} with calculated var updated in the H5 file.
#' @noRd
calcGeneVars.H5 <- function(object, chunkSize = 1000,
verbose = getOption("ligerVerbose", TRUE)) {
geneVars <- rep(0, nrow(object))
geneMeans <- featureMeta(object)$geneMeans
geneVars <- H5Apply(
object,
function(chunk, sparseXIdx, cellIdx, values) {
values + sumSquaredDeviations(chunk, geneMeans)
},
init = geneVars,
useData = "normData",
chunkSize = chunkSize,
verbose = verbose
)
geneVars <- geneVars / (ncol(object) - 1)
featureMeta(object, check = FALSE)$geneVars <- geneVars
object
}
#' @export
#' @rdname selectGenes
#' @method selectGenes Seurat
#' @param layer Where the input normalized counts should be from. Default
#' \code{"ligerNormData"}. For older Seurat, always retrieve from \code{data}
#' slot.
#' @param assay Name of assay to use. Default \code{NULL} uses current active
#' assay.
#' @param datasetVar Metadata variable name that stores the dataset source
#' annotation. Default \code{"orig.ident"}.
selectGenes.Seurat <- function(
object,
thresh = .1,
nGenes = NULL,
alpha = .99,
useDatasets = NULL,
layer = "ligerNormData",
assay = NULL,
datasetVar = "orig.ident",
combine = c("union", "intersection"),
verbose = getOption("ligerVerbose", TRUE),
...
) {
combine <- match.arg(combine)
assay <- assay %||% SeuratObject::DefaultAssay(object)
matList <- .getSeuratData(object, layer = layer, slot = "data",
assay = assay)
if (is.list(matList)) {
# object contain split layers
names(matList) <- gsub(paste0(layer, "."), "", names(matList))
datasetVar <- factor(rep(names(matList), sapply(matList, ncol)),
levels = names(matList))
} else {
datasetVar <- object[[datasetVar, drop = TRUE]]
if (!is.factor(datasetVar)) datasetVar <- factor(datasetVar)
datasetVar <- droplevels(datasetVar)
matList <- splitRmMiss(matList, datasetVar)
}
useDatasets <- useDatasets %||% levels(datasetVar)
matList <- matList[unique(useDatasets)]
featureList <- lapply(matList, rownames)
allshared <- Reduce(intersect, featureList)
allFeatures <- SeuratObject::Features(object, assay = assay)
thresh <- .checkArgLen(thresh, nlevels(datasetVar), class = "numeric")
# Get nUMI metric into list
nUMIVar <- paste0("nCount_", assay)
nUMIAll <- object[[nUMIVar]][,1]
nUMIList <- split(nUMIAll, datasetVar)
selectList <- list()
hvg.info <- data.frame(row.names = allFeatures)
for (d in levels(datasetVar)) {
if (isTRUE(verbose))
cli::cli_alert_info("Selecting variable features for dataset: {.val {d}}")
submat <- matList[[d]]
# submat <- mat[, datasetVar == d, drop = FALSE]
# submat <- submat[sort(expressed), , drop = FALSE]
sharedFeature <- rownames(submat) %in% allshared
means <- Matrix::rowMeans(submat)
hvg.info[[paste0("liger.mean.", d)]] <- 0
hvg.info[rownames(submat), paste0("liger.mean.", d)] <- means
vars <- rowVars_sparse_rcpp(submat, means)
hvg.info[[paste0("liger.variance.", d)]] <- 0
hvg.info[rownames(submat), paste0("liger.variance.", d)] <- vars
thresh_i <- thresh[levels(datasetVar) == d]
selected <- .selectGenes.withMetric(
genes = rownames(submat)[sharedFeature],
means = means[sharedFeature],
vars = vars[sharedFeature],
nUMI = nUMIList[[d]],
dims = dim(submat),
thresh = thresh_i, alpha = alpha,
nGenes = nGenes
)
if (isTRUE(verbose)) {
cli::cli_alert_success("... {length(selected)} features selected out of {length(allshared)} shared features")
}
selectList[[d]] <- selected
}
if (combine == "union") selected <- Reduce(union, selectList)
else selected <- Reduce(intersect, selectList)
if (length(selected) == 0) {
cli::cli_alert_danger("No genes were selected. Lower {.code thresh} values or set {.code combine = 'union'}")
} else {
if (isTRUE(verbose))
cli::cli_alert_success("Finally {length(selected)} shared variable features selected.")
}
hvg.info$liger.variable <- allFeatures %in% selected
assayObj <- Seurat::GetAssay(object, assay = assay)
assayObj[[names(hvg.info)]] <- hvg.info
object[[assay]] <- assayObj
SeuratObject::VariableFeatures(object, assay = assay) <- selected
return(object)
}
# returns selected gene names
.selectGenes.withMetric <- function(
genes,
means,
vars,
nUMI,
dims,
thresh = .1,
alpha = .99,
nGenes = NULL
) {
nolan_constant <- mean((1 / nUMI))
alphathresh.corrected <- alpha / dims[1]
geneMeanUpper <- means +
stats::qnorm(1 - alphathresh.corrected / 2) *
sqrt(means * nolan_constant / dims[2])
basegenelower <- log10(means * nolan_constant)
if (!is.null(nGenes)) {
preselect <- vars / nolan_constant > geneMeanUpper &
log10(vars) > basegenelower
relativeVar <- log10(vars) - basegenelower
names(relativeVar) <- genes
relativeVar <- relativeVar[preselect]
relativeVar <- relativeVar[order(relativeVar, decreasing = TRUE)]
selected <- names(relativeVar[seq(nGenes)])
} else {
selected <- genes[vars / nolan_constant > geneMeanUpper &
log10(vars) > basegenelower + thresh]
}
return(selected)
}
#' Plot the variance vs mean of feature expression
#' @description For each dataset where the feature variablitity is calculated,
#' a plot of log10 feature expression variance and log10 mean will be produced.
#' Features that are considered as variable would be highlighted in red.
#' @param object \linkS4class{liger} object. \code{\link{selectGenes}} needs to
#' be run in advance.
#' @param combinePlot Logical. If \code{TRUE}, sub-figures for all datasets will
#' be combined into one plot. if \code{FALSE}, a list of plots will be returned.
#' Default \code{TRUE}.
#' @param dotSize Controls the size of dots in the main plot. Default
#' \code{0.8}.
#' @param ... More theme setting parameters passed to
#' \code{\link{.ggplotLigerTheme}}.
#' @return \code{ggplot} object when \code{combinePlot = TRUE}, a list of
#' \code{ggplot} objects when \code{combinePlot = FALSE}
#' @export
#' @examples
#' pbmc <- normalize(pbmc)
#' pbmc <- selectGenes(pbmc)
#' plotVarFeatures(pbmc)
plotVarFeatures <- function(
object,
combinePlot = TRUE,
dotSize = 1,
...
) {
plotList <- list()
maxVar <- max(sapply(datasets(object),
function(ld) max(log10(featureMeta(ld)$geneVars))))
minVar <- min(sapply(datasets(object),
function(ld) min(log10(featureMeta(ld)$geneVars))))
maxMean <- max(sapply(datasets(object),
function(ld) max(log10(featureMeta(ld)$geneMeans))))
minMean <- min(sapply(datasets(object),
function(ld) min(log10(featureMeta(ld)$geneMeans))))
for (d in names(object)) {
ld <- dataset(object, d)
trx_per_cell <- cellMeta(object, "nUMI", cellIdx = object$dataset == d)
nolan_constant <- mean((1 / trx_per_cell))
data <- .DataFrame.as.data.frame(featureMeta(ld))
nSelect <- sum(data$isVariable)
data$geneMeans <- log10(data$geneMeans)
data$geneVars <- log10(data$geneVars)
data$isVariable <- factor(data$isVariable,
levels = c("TRUE", "FALSE"))
p <- ggplot2::ggplot(
data,
ggplot2::aes(x = .data[["geneMeans"]],
y = .data[["geneVars"]],
color = .data[["isVariable"]])
) +
ggplot2::geom_point(size = dotSize, stroke = 0) +
ggplot2::geom_abline(intercept = log10(nolan_constant), slope = 1,
color = "purple") +
ggplot2::xlim(minMean, maxMean) +
ggplot2::ylim(minVar, maxVar)
p <- .ggplotLigerTheme(p, title = d,
subtitle = paste0(nSelect, " variable features"),
xlab = "Gene Expression Mean (log10)",
ylab = "Gene Expression Variance (log10)",
legendColorTitle = "Variable\nfeature",
colorLabels = c("TRUE", "FALSE"),
colorValues = c("RED", "BLACK"),
...)
plotList[[d]] <- p
}
if (isTRUE(combinePlot)) {
suppressWarnings({
legend <- cowplot::get_legend(plotList[[1]])
})
plotList <- lapply(plotList, function(x) {
x + ggplot2::theme(legend.position = "none")
})
combined <- cowplot::plot_grid(plotlist = plotList,
align = "hv",
axis = "tblr")
combined <- cowplot::plot_grid(combined, legend, rel_widths = c(5,1))