/
decon.R
1468 lines (1310 loc) · 44.1 KB
/
decon.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
#' @title Contamination estimation with decontX
#'
#' @description Identifies contamination from factors such as ambient RNA
#' in single cell genomic datasets.
#'
#' @name decontX
#'
#' @param x A numeric matrix of counts or a \linkS4class{SingleCellExperiment}
#' with the matrix located in the assay slot under \code{assayName}.
#' Cells in each batch will be subsetted and converted to a sparse matrix
#' of class \code{dgCMatrix} from package \link{Matrix} before analysis. This
#' object should only contain filtered cells after cell calling. Empty
#' cell barcodes (low expression droplets before cell calling) are not needed
#' to run DecontX.
#' @param assayName Character. Name of the assay to use if \code{x} is a
#' \linkS4class{SingleCellExperiment}.
#' @param z Numeric or character vector. Cell cluster labels. If NULL,
#' PCA will be used to reduce the dimensionality of the dataset initially,
#' '\link[uwot]{umap}' from the 'uwot' package
#' will be used to further reduce the dataset to 2 dimenions and
#' the '\link[dbscan]{dbscan}' function from the 'dbscan' package
#' will be used to identify clusters of broad cell types. Default NULL.
#' @param batch Numeric or character vector. Batch labels for cells.
#' If batch labels are supplied, DecontX is run on cells from each
#' batch separately. Cells run in different channels or assays
#' should be considered different batches. Default NULL.
#' @param background A numeric matrix of counts or a
#' \linkS4class{SingleCellExperiment} with the matrix located in the assay
#' slot under \code{assayName}. It should have the same data format as \code{x}
#' except it contains the empty droplets instead of cells. When supplied,
#' empirical distribution of transcripts from these empty droplets
#' will be used as the contamination distribution. Default NULL.
#' @param bgAssayName Character. Name of the assay to use if \code{background}
#' is a \linkS4class{SingleCellExperiment}. Default to same as
#' \code{assayName}.
#' @param bgBatch Numeric or character vector. Batch labels for
#' \code{background}. Its unique values should be the same as those in
#' \code{batch}, such that each batch of cells have their corresponding batch
#' of empty droplets as background, pointed by this parameter. Default to NULL.
#' @param maxIter Integer. Maximum iterations of the EM algorithm. Default 500.
#' @param convergence Numeric. The EM algorithm will be stopped if the maximum
#' difference in the contamination estimates between the previous and
#' current iterations is less than this. Default 0.001.
#' @param iterLogLik Integer. Calculate log likelihood every \code{iterLogLik}
#' iteration. Default 10.
#' @param delta Numeric Vector of length 2. Concentration parameters for
#' the Dirichlet prior for the contamination in each cell. The first element
#' is the prior for the native counts while the second element is the prior for
#' the contamination counts. These essentially act as pseudocounts for the
#' native and contamination in each cell. If \code{estimateDelta = TRUE},
#' this is only used to produce a random sample of proportions for an initial
#' value of contamination in each cell. Then
#' \code{\link[MCMCprecision]{fit_dirichlet}} is used to update
#' \code{delta} in each iteration.
#' If \code{estimateDelta = FALSE}, then \code{delta} is fixed with these
#' values for the entire inference procedure. Fixing \code{delta} and
#' setting a high number in the second element will force \code{decontX}
#' to be more aggressive and estimate higher levels of contamination at
#' the expense of potentially removing native expression.
#' Default \code{c(10, 10)}.
#' @param estimateDelta Boolean. Whether to update \code{delta} at each
#' iteration.
#' @param varGenes Integer. The number of variable genes to use in
#' dimensionality reduction before clustering. Variability is calcualted using
#' \code{\link[scran]{modelGeneVar}} function from the 'scran' package.
#' Used only when z is not provided. Default 5000.
#' @param dbscanEps Numeric. The clustering resolution parameter
#' used in '\link[dbscan]{dbscan}' to estimate broad cell clusters.
#' Used only when z is not provided. Default 1.
#' @param seed Integer. Passed to \link[withr]{with_seed}. For reproducibility,
#' a default value of 12345 is used. If NULL, no calls to
#' \link[withr]{with_seed} are made.
#' @param logfile Character. Messages will be redirected to a file named
#' `logfile`. If NULL, messages will be printed to stdout. Default NULL.
#' @param verbose Logical. Whether to print log messages. Default TRUE.
#' @param ... For the generic, further arguments to pass to each method.
#'
#' @return If \code{x} is a matrix-like object, a list will be returned
#' with the following items:
#' \describe{
#' \item{\code{decontXcounts}:}{The decontaminated matrix. Values obtained
#' from the variational inference procedure may be non-integer. However,
#' integer counts can be obtained by rounding,
#' e.g. \code{round(decontXcounts)}.}
#' \item{\code{contamination}:}{Percentage of contamination in each cell.}
#' \item{\code{estimates}:}{List of estimated parameters for each batch. If z
#' was not supplied, then the UMAP coordinates used to generated cell
#' cluster labels will also be stored here.}
#' \item{\code{z}:}{Cell population/cluster labels used for analysis.}
#' \item{\code{runParams}:}{List of arguments used in the function call.}
#' }
#'
#' If \code{x} is a \linkS4class{SingleCellExperiment}, then the decontaminated
#' counts will be stored as an assay and can be accessed with
#' \code{decontXcounts(x)}. The contamination values and cluster labels
#' will be stored in \code{colData(x)}. \code{estimates} and \code{runParams}
#' will be stored in \code{metadata(x)$decontX}. The UMAPs used to generated
#' cell cluster labels will be stored in
#' \code{reducedDims} slot in \code{x}.
#'
#' @author Shiyi Yang, Yuan Yin, Joshua Campbell
#'
#' @examples
#' # Generate matrix with contamination
#' s <- simulateContamination(seed = 12345)
#'
#' library(SingleCellExperiment)
#' sce <- SingleCellExperiment(list(counts = s$observedCounts))
#' sce <- decontX(sce)
#'
#' # Plot contamination on UMAP
#' plotDecontXContamination(sce)
#'
#' # Plot decontX cluster labels
#' umap <- reducedDim(sce)
#' plotDimReduceCluster(x = sce$decontX_clusters,
#' dim1 = umap[, 1], dim2 = umap[, 2], )
#'
#' # Plot percentage of marker genes detected
#' # in each cell cluster before decontamination
#' s$markers
#' plotDecontXMarkerPercentage(sce, markers = s$markers, assayName = "counts")
#'
#' # Plot percentage of marker genes detected
#' # in each cell cluster after contamination
#' plotDecontXMarkerPercentage(sce, markers = s$markers,
#' assayName = "decontXcounts")
#'
#' # Plot percentage of marker genes detected in each cell
#' # comparing original and decontaminated counts side-by-side
#' plotDecontXMarkerPercentage(sce, markers = s$markers,
#' assayName = c("counts", "decontXcounts"))
#'
#' # Plot raw counts of indiviual markers genes before
#' # and after decontamination
#' plotDecontXMarkerExpression(sce, unlist(s$markers))
NULL
#' @export
#' @rdname decontX
setGeneric("decontX", function(x, ...) standardGeneric("decontX"))
#########################
# Setting up S4 methods #
#########################
#' @export
#' @rdname decontX
#' @importClassesFrom SingleCellExperiment SingleCellExperiment
#' @importClassesFrom Matrix dgCMatrix
setMethod("decontX", "SingleCellExperiment", function(x,
assayName = "counts",
z = NULL,
batch = NULL,
background = NULL,
bgAssayName = NULL,
bgBatch = NULL,
maxIter = 500,
delta = c(10, 10),
estimateDelta = TRUE,
convergence = 0.001,
iterLogLik = 10,
varGenes = 5000,
dbscanEps = 1,
seed = 12345,
logfile = NULL,
verbose = TRUE) {
countsBackground <- NULL
if (!is.null(background)) {
# Remove cells with the same ID between x and the background matrix
# Also update bgBatch when background is updated and bgBatch is not null
temp <- .checkBackground(x = x,
background = background,
bgBatch = bgBatch,
logfile = logfile,
verbose = verbose)
background <- temp$background
bgBatch <- temp$bgBatch
if (is.null(bgAssayName)) {
bgAssayName <- assayName
}
countsBackground <- SummarizedExperiment::assay(background, i = bgAssayName)
}
mat <- SummarizedExperiment::assay(x, i = assayName)
result <- .decontX(
counts = mat,
z = z,
batch = batch,
countsBackground = countsBackground,
batchBackground = bgBatch,
maxIter = maxIter,
convergence = convergence,
iterLogLik = iterLogLik,
delta = delta,
estimateDelta = estimateDelta,
varGenes = varGenes,
dbscanEps = dbscanEps,
seed = seed,
logfile = logfile,
verbose = verbose
)
## Add results into column annotation
SummarizedExperiment::colData(x)$decontX_contamination <- result$contamination
SummarizedExperiment::colData(x)$decontX_clusters <- as.factor(result$z)
## Put estimated UMAPs into SCE
batchIndex <- unique(result$runParams$batch)
if (length(batchIndex) > 1) {
for (i in batchIndex) {
## Each individual UMAP will only be for one batch so need
## to put NAs in for cells in other batches
tempUMAP <- matrix(NA, ncol = 2, nrow = ncol(mat))
tempUMAP[result$runParams$batch == i, ] <- result$estimates[[i]]$UMAP
colnames(tempUMAP) <- c("UMAP_1", "UMAP_2")
rownames(tempUMAP) <- colnames(mat)
SingleCellExperiment::reducedDim(
x,
paste("decontX", i, "UMAP", sep = "_")
) <- tempUMAP
}
} else {
SingleCellExperiment::reducedDim(x, "decontX_UMAP") <-
result$estimates[[batchIndex]]$UMAP
}
## Save the rest of the result object into metadata
decontXcounts(x) <- result$decontXcounts
result$decontXcounts <- NULL
S4Vectors::metadata(x)$decontX <- result
return(x)
})
#' @export
#' @rdname decontX
setMethod("decontX", "ANY", function(x,
z = NULL,
batch = NULL,
background = NULL,
bgBatch = NULL,
maxIter = 500,
delta = c(10, 10),
estimateDelta = TRUE,
convergence = 0.001,
iterLogLik = 10,
varGenes = 5000,
dbscanEps = 1,
seed = 12345,
logfile = NULL,
verbose = TRUE) {
countsBackground <- NULL
if (!is.null(background)) {
# Remove cells with the same ID between x and the background matrix
# Also update bgBatch when background is updated and bgBatch is not null
temp <- .checkBackground(x = x,
background = background,
bgBatch = bgBatch,
logfile = logfile,
verbose = verbose)
background <- temp$background
countsBackground <- background
bgBatch <- temp$bgBatch
}
.decontX(
counts = x,
z = z,
batch = batch,
countsBackground = countsBackground,
batchBackground = bgBatch,
maxIter = maxIter,
convergence = convergence,
iterLogLik = iterLogLik,
delta = delta,
estimateDelta = estimateDelta,
varGenes = varGenes,
dbscanEps = dbscanEps,
seed = seed,
logfile = logfile,
verbose = verbose
)
})
## Copied from SingleCellExperiment Package
GET_FUN <- function(exprs_values, ...) {
(exprs_values) # To ensure evaluation
function(object, ...) {
SummarizedExperiment::assay(object, i = exprs_values, ...)
}
}
SET_FUN <- function(exprs_values, ...) {
(exprs_values) # To ensure evaluation
function(object, ..., value) {
SummarizedExperiment::assay(object, i = exprs_values, ...) <- value
object
}
}
#' @title Get or set decontaminated counts matrix
#'
#' @description Gets or sets the decontaminated counts matrix from a
#' a \linkS4class{SingleCellExperiment} object.
#' @name decontXcounts
#' @param object A \linkS4class{SingleCellExperiment} object.
#' @param value A matrix to save as an assay called \code{decontXcounts}
#' @param ... For the generic, further arguments to pass to each method.
#' @return If getting, the assay from \code{object} with the name
#' \code{decontXcounts} will be returned. If setting, a
#' \linkS4class{SingleCellExperiment} object will be returned with
#' \code{decontXcounts} listed in the \code{assay} slot.
#' @seealso \code{\link{assay}} and \code{\link{assay<-}}
NULL
#' @export
#' @rdname decontXcounts
setGeneric("decontXcounts", function(object, ...) {
standardGeneric("decontXcounts")
})
#' @export
#' @rdname decontXcounts
setGeneric("decontXcounts<-", function(object, ..., value) {
standardGeneric("decontXcounts<-")
})
#' @export
#' @rdname decontXcounts
setMethod("decontXcounts", "SingleCellExperiment", GET_FUN("decontXcounts"))
#' @export
#' @rdname decontXcounts
setMethod(
"decontXcounts<-", c("SingleCellExperiment", "ANY"),
SET_FUN("decontXcounts")
)
##########################
# Core Decontx Functions #
##########################
.decontX <- function(counts,
z = NULL,
batch = NULL,
countsBackground = NULL,
batchBackground = NULL,
maxIter = 200,
convergence = 0.001,
iterLogLik = 10,
delta = c(10, 10),
estimateDelta = TRUE,
varGenes = NULL,
dbscanEps = NULL,
seed = 12345,
logfile = NULL,
verbose = TRUE) {
startTime <- Sys.time()
.logMessages(paste(rep("-", 50), collapse = ""),
logfile = logfile,
append = TRUE,
verbose = verbose
)
.logMessages("Starting DecontX",
logfile = logfile,
append = TRUE,
verbose = verbose
)
.logMessages(paste(rep("-", 50), collapse = ""),
logfile = logfile,
append = TRUE,
verbose = verbose
)
runParams <- list(
z = z,
batch = batch,
batchBackground = batchBackground,
maxIter = maxIter,
delta = delta,
estimateDelta = estimateDelta,
convergence = convergence,
varGenes = varGenes,
dbscanEps = dbscanEps,
logfile = logfile,
verbose = verbose
)
totalGenes <- nrow(counts)
totalCells <- ncol(counts)
geneNames <- rownames(counts)
nC <- ncol(counts)
allCellNames <- colnames(counts)
## Set up final decontaminated matrix
estRmat <- Matrix::Matrix(
data = 0,
ncol = totalCells,
nrow = totalGenes,
sparse = TRUE,
dimnames = list(geneNames, allCellNames)
)
## Generate batch labels if none were supplied
if (is.null(batch)) {
batch <- rep("all_cells", nC)
# If batch null, bgBatch has to be null
if (!is.null(batchBackground)) {
stop(
"When experiment default to no bacth, background should ",
"also default to no batch."
)
}
if (!is.null(countsBackground)) {
batchBackground <- rep("all_cells", ncol(countsBackground))
}
} else {
# If batch not null and countsBackground supplied,
# user has to supply batchBackground as well
if (!is.null(countsBackground) & is.null(batchBackground)) {
stop(
"Cell batch, and background are supplied. Please also ",
"supply background batch."
)
}
}
runParams$batch <- batch
runParams$batchBackground <- batchBackground
batchIndex <- unique(batch)
## Set result lists upfront for all cells from different batches
logLikelihood <- c()
estConp <- rep(NA, nC)
returnZ <- rep(NA, nC)
resBatch <- list()
## Cycle through each sample/batch and run DecontX
for (bat in batchIndex) {
if (length(batchIndex) == 1) {
.logMessages(
date(),
".. Analyzing all cells",
logfile = logfile,
append = TRUE,
verbose = verbose
)
} else {
.logMessages(
date(),
" .. Analyzing cells in batch '",
bat, "'",
sep = "",
logfile = logfile,
append = TRUE,
verbose = verbose
)
}
zBat <- NULL
countsBat <- counts[, batch == bat]
bgBat <- countsBackground[, batchBackground == bat]
## Convert to sparse matrix
if (!inherits(countsBat, "dgCMatrix")) {
.logMessages(
date(),
".... Converting to sparse matrix",
logfile = logfile,
append = TRUE,
verbose = verbose
)
countsBat <- methods::as(countsBat, "CsparseMatrix")
}
if (!is.null(bgBat)) {
if (!inherits(bgBat, "dgCMatrix")) {
bgBat <- methods::as(bgBat, "CsparseMatrix")
}
}
if (!is.null(z)) {
zBat <- z[batch == bat]
}
if (is.null(seed)) {
res <- .decontXoneBatch(
counts = countsBat,
z = zBat,
batch = bat,
countsBackground = bgBat,
maxIter = maxIter,
delta = delta,
estimateDelta = estimateDelta,
convergence = convergence,
iterLogLik = iterLogLik,
logfile = logfile,
verbose = verbose,
varGenes = varGenes,
dbscanEps = dbscanEps,
seed = seed
)
} else {
withr::with_seed(
seed,
res <- .decontXoneBatch(
counts = countsBat,
z = zBat,
batch = bat,
countsBackground = bgBat,
maxIter = maxIter,
delta = delta,
estimateDelta = estimateDelta,
convergence = convergence,
iterLogLik = iterLogLik,
logfile = logfile,
verbose = verbose,
varGenes = varGenes,
dbscanEps = dbscanEps,
seed = seed
)
)
}
## Try to convert class of new matrix to class of original matrix
.logMessages(
date(),
".. Calculating final decontaminated matrix",
logfile = logfile,
append = TRUE,
verbose = verbose
)
estRmat.temp <- calculateNativeMatrix(
counts = countsBat,
theta = res$theta,
eta = res$eta,
phi = res$phi,
z = as.integer(res$z),
pseudocount = 1e-20
)
# Speed up sparse matrix value assignment by cbind -> order recovery
allCol <- paste0("col_", seq_len(ncol(estRmat)))
colnames(estRmat) <- allCol
subCol <- paste0("col_", which(batch == bat))
colnames(estRmat.temp) <- subCol
estRmat <- estRmat[, !(allCol %in% subCol)]
estRmat <- cbind(estRmat, estRmat.temp)
# Recover order and set names
estRmat <- estRmat[, allCol]
dimnames(estRmat) <- list(geneNames, allCellNames)
resBatch[[bat]] <- list(
z = res$z,
phi = res$phi,
eta = res$eta,
delta = res$delta,
theta = res$theta,
contamination = res$contamination,
logLikelihood = res$logLikelihood,
UMAP = res$UMAP,
z = res$z,
iteration = res$iteration
)
estConp[batch == bat] <- res$contamination
if (length(batchIndex) > 1) {
returnZ[batch == bat] <- paste0(bat, "-", res$z)
} else {
returnZ[batch == bat] <- res$z
}
}
names(resBatch) <- batchIndex
returnResult <- list(
"runParams" = runParams,
"estimates" = resBatch,
"decontXcounts" = estRmat,
"contamination" = estConp,
"z" = returnZ
)
if (inherits(counts, c("DelayedMatrix", "DelayedArray"))) {
.logMessages(
date(),
".. Converting decontaminated matrix to", class(counts),
logfile = logfile,
append = TRUE,
verbose = verbose
)
## Determine class of seed in DelayedArray
seed.class <- unique(DelayedArray::seedApply(counts, class))[[1]]
if (seed.class == "HDF5ArraySeed") {
returnResult$decontXcounts <-
methods::as(returnResult$decontXcounts, "HDF5Matrix")
} else {
if (isTRUE(methods::canCoerce(returnResult$decontXcounts, seed.class))) {
returnResult$decontXcounts <-
methods::as(returnResult$decontXcounts, seed.class)
}
}
returnResult$decontXcounts <-
DelayedArray::DelayedArray(returnResult$decontXcounts)
} else {
try({
if (methods::canCoerce(returnResult$decontXcounts, class(counts))) {
returnResult$decontXcounts <-
methods::as(returnResult$decontXcounts, class(counts))
}
},
silent = TRUE
)
}
endTime <- Sys.time()
.logMessages(paste(rep("-", 50), collapse = ""),
logfile = logfile,
append = TRUE,
verbose = verbose
)
.logMessages("Completed DecontX. Total time:",
format(difftime(endTime, startTime)),
logfile = logfile,
append = TRUE,
verbose = verbose
)
.logMessages(paste(rep("-", 50), collapse = ""),
logfile = logfile,
append = TRUE,
verbose = verbose
)
return(returnResult)
}
# This function updates decontamination for one batch
# seed passed to this function is to be furhter passed to
# function .decontxInitializeZ()
.decontXoneBatch <- function(counts,
z = NULL,
batch = NULL,
countsBackground = NULL,
maxIter = 200,
delta = c(10, 10),
estimateDelta = TRUE,
convergence = 0.01,
iterLogLik = 10,
logfile = NULL,
verbose = TRUE,
varGenes = NULL,
dbscanEps = NULL,
seed = 12345) {
.checkCountsDecon(counts)
.checkDelta(delta)
# nG <- nrow(counts)
nC <- ncol(counts)
deconMethod <- "clustering"
## Generating UMAP and cell cluster labels if none are provided
umap <- NULL
if (is.null(z)) {
m <- ".... Generating UMAP and estimating cell types"
estimateCellTypes <- TRUE
} else {
m <- ".... Generating UMAP"
estimateCellTypes <- FALSE
}
.logMessages(
date(),
m,
logfile = logfile,
append = TRUE,
verbose = verbose
)
varGenes <- .processvarGenes(varGenes)
dbscanEps <- .processdbscanEps(dbscanEps)
celda.init <- .decontxInitializeZ(
object = counts,
varGenes = varGenes,
dbscanEps = dbscanEps,
estimateCellTypes = estimateCellTypes,
seed = seed
)
if (is.null(z)) {
z <- celda.init$z
}
umap <- celda.init$umap
colnames(umap) <- c(
"DecontX_UMAP_1",
"DecontX_UMAP_2"
)
rownames(umap) <- colnames(counts)
z <- .processCellLabels(z, numCells = nC)
K <- length(unique(z))
iter <- 1L
numIterWithoutImprovement <- 0L
stopIter <- 3L
.logMessages(
date(),
".... Estimating contamination",
logfile = logfile,
append = TRUE,
verbose = verbose
)
if (deconMethod == "clustering") {
## Initialization
theta <- stats::rbeta(
n = nC,
shape1 = delta[1],
shape2 = delta[2]
)
nextDecon <- decontXInitialize(
counts = counts,
theta = theta,
z = z,
pseudocount = 1e-20
)
phi <- nextDecon$phi
eta <- nextDecon$eta
# if countsBackground is not null, use empirical dist. to replace eta
if (!is.null(countsBackground)) {
# Add pseudocount to each gene in eta
eta_tilda <- Matrix::rowSums(countsBackground) + 1e-20
eta <- eta_tilda / sum(eta_tilda)
# Make eta a matrix same dimension as phi
eta <- matrix(eta, length(eta), dim(phi)[2])
}
ll <- c()
llRound <- decontXLogLik(
counts = counts,
z = z,
phi = phi,
eta = eta,
theta = theta,
pseudocount = 1e-20
)
## EM updates
theta.previous <- theta
converged <- FALSE
counts.colsums <- Matrix::colSums(counts)
while (iter <= maxIter & !isTRUE(converged) &
numIterWithoutImprovement <= stopIter) {
if (is.null(countsBackground)) {
nextDecon <- decontXEM(
counts = counts,
counts_colsums = counts.colsums,
phi = phi,
estimate_eta = TRUE,
eta = eta,
theta = theta,
z = z,
estimate_delta = isTRUE(estimateDelta),
delta = delta,
pseudocount = 1e-20
)
} else {
nextDecon <- decontXEM(
counts = counts,
counts_colsums = counts.colsums,
phi = phi,
estimate_eta = FALSE,
eta = eta,
theta = theta,
z = z,
estimate_delta = isTRUE(estimateDelta),
delta = delta,
pseudocount = 1e-20
)
}
theta <- nextDecon$theta
phi <- nextDecon$phi
eta <- nextDecon$eta
delta <- nextDecon$delta
max.divergence <- max(abs(theta.previous - theta))
if (max.divergence < convergence) {
converged <- TRUE
}
theta.previous <- theta
## Calculate likelihood and check for convergence
if (iter %% iterLogLik == 0 || converged) {
llTemp <- decontXLogLik(
counts = counts,
z = z,
phi = phi,
eta = eta,
theta = theta,
pseudocount = 1e-20
)
ll <- c(ll, llTemp)
.logMessages(date(),
"...... Completed iteration:",
iter,
"| converge:",
signif(max.divergence, 4),
logfile = logfile,
append = TRUE,
verbose = verbose
)
}
iter <- iter + 1L
}
}
resConp <- nextDecon$contamination
names(resConp) <- colnames(counts)
return(list(
"logLikelihood" = ll,
"contamination" = resConp,
"theta" = theta,
"delta" = delta,
"phi" = phi,
"eta" = eta,
"UMAP" = umap,
"iteration" = iter - 1L,
"z" = z
))
}
# This function calculates the log-likelihood
#
# counts Numeric/Integer matrix. Observed count matrix, rows represent features
# and columns represent cells
# z Integer vector. Cell population labels
# phi Numeric matrix. Rows represent features and columns represent cell
# populations
# eta Numeric matrix. Rows represent features and columns represent cell
# populations
# theta Numeric vector. Proportion of truely expressed transcripts
.deconCalcLL <- function(counts, z, phi, eta, theta) {
# ll = sum( t(counts) * log( (1-conP )*geneDist[z,] + conP * conDist[z, ] +
# 1e-20 ) ) # when dist_mat are K x G matrices
ll <- sum(Matrix::t(counts) * log(theta * t(phi)[z, ] +
(1 - theta) * t(eta)[z, ] + 1e-20))
return(ll)
}
# DEPRECATED. This is not used, but is kept as it might be useful in the future
# This function calculates the log-likelihood of background distribution
# decontamination
# bgDist Numeric matrix. Rows represent feature and columns are the times that
# the background-distribution has been replicated.
.bgCalcLL <- function(counts, globalZ, cbZ, phi, eta, theta) {
# ll <- sum(t(counts) * log(theta * t(cellDist) +
# (1 - theta) * t(bgDist) + 1e-20))
ll <- sum(t(counts) * log(theta * t(phi)[cbZ, ] +
(1 - theta) * t(eta)[globalZ, ] + 1e-20))
return(ll)
}
# This function updates decontamination
# phi Numeric matrix. Rows represent features and columns represent cell
# populations
# eta Numeric matrix. Rows represent features and columns represent cell
# populations
# theta Numeric vector. Proportion of truely expressed transctripts
#' @importFrom MCMCprecision fit_dirichlet
.cDCalcEMDecontamination <- function(counts,
phi,
eta,
theta,
z,
K,
delta) {
## Notes: use fix-point iteration to update prior for theta, no need
## to feed delta anymore
logPr <- log(t(phi)[z, ] + 1e-20) + log(theta + 1e-20)
logPc <- log(t(eta)[z, ] + 1e-20) + log(1 - theta + 1e-20)
Pr.e <- exp(logPr)
Pc.e <- exp(logPc)
Pr <- Pr.e / (Pr.e + Pc.e)
estRmat <- t(Pr) * counts
rnGByK <- .colSumByGroupNumeric(estRmat, z, K)
cnGByK <- rowSums(rnGByK) - rnGByK
counts.cs <- colSums(counts)
estRmat.cs <- colSums(estRmat)
estRmat.cs.n <- estRmat.cs / counts.cs
estCmat.cs.n <- 1 - estRmat.cs.n
temp <- cbind(estRmat.cs.n, estCmat.cs.n)
deltaV2 <- MCMCprecision::fit_dirichlet(temp)$alpha
## Update parameters
theta <-
(estRmat.cs + deltaV2[1]) / (counts.cs + sum(deltaV2))
phi <- normalizeCounts(rnGByK,
normalize = "proportion",
pseudocountNormalize = 1e-20
)
eta <- normalizeCounts(cnGByK,
normalize = "proportion",
pseudocountNormalize = 1e-20
)
return(list(
"estRmat" = estRmat,
"theta" = theta,
"phi" = phi,
"eta" = eta,
"delta" = deltaV2
))
}
# DEPRECATED. This is not used, but is kept as it might be useful in the
# feature.
# This function updates decontamination using background distribution
.cDCalcEMbgDecontamination <-
function(counts, globalZ, cbZ, trZ, phi, eta, theta) {
logPr <- log(t(phi)[cbZ, ] + 1e-20) + log(theta + 1e-20)
logPc <-
log(t(eta)[globalZ, ] + 1e-20) + log(1 - theta + 1e-20)
Pr <- exp(logPr) / (exp(logPr) + exp(logPc))
Pc <- 1 - Pr
deltaV2 <-
MCMCprecision::fit_dirichlet(matrix(c(Pr, Pc), ncol = 2))$alpha
estRmat <- t(Pr) * counts
phiUnnormalized <-
.colSumByGroupNumeric(estRmat, cbZ, max(cbZ))
etaUnnormalized <-
rowSums(phiUnnormalized) - .colSumByGroupNumeric(
phiUnnormalized,
trZ, max(trZ)
)
## Update paramters
theta <-
(colSums(estRmat) + deltaV2[1]) / (colSums(counts) + sum(deltaV2))
phi <-
normalizeCounts(phiUnnormalized,
normalize = "proportion",
pseudocountNormalize = 1e-20
)
eta <-
normalizeCounts(etaUnnormalized,
normalize = "proportion",
pseudocountNormalize = 1e-20
)
return(list(
"estRmat" = estRmat,
"theta" = theta,
"phi" = phi,
"eta" = eta,