-
Notifications
You must be signed in to change notification settings - Fork 0
/
Archr_Peak_Null.R
4930 lines (3979 loc) · 164 KB
/
Archr_Peak_Null.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
##########################################################################################
# Peak2Gene Links Methods
##########################################################################################
#' Add Peak2GeneLinks to an ArchRProject
#'
#' This function will add peak-to-gene links to a given ArchRProject
#'
#' @param ArchRProj An `ArchRProject` object.
#' @param reducedDims The name of the `reducedDims` object (i.e. "IterativeLSI") to retrieve from the designated `ArchRProject`.
#' @param dimsToUse A vector containing the dimensions from the `reducedDims` object to use in clustering.
#' @param scaleDims A boolean value that indicates whether to z-score the reduced dimensions for each cell. This is useful for minimizing
#' the contribution of strong biases (dominating early PCs) and lowly abundant populations. However, this may lead to stronger sample-specific
#' biases since it is over-weighting latent PCs. If set to `NULL` this will scale the dimensions based on the value of `scaleDims` when the
#' `reducedDims` were originally created during dimensionality reduction. This idea was introduced by Timothy Stuart.
#' @param corCutOff A numeric cutoff for the correlation of each dimension to the sequencing depth. If the dimension has a
#' correlation to sequencing depth that is greater than the `corCutOff`, it will be excluded from analysis.
#' @param k The number of k-nearest neighbors to use for creating single-cell groups for correlation analyses.
#' @param knnIteration The number of k-nearest neighbor groupings to test for passing the supplied `overlapCutoff`.
#' @param overlapCutoff The maximum allowable overlap between the current group and all previous groups to permit the current
#' group be added to the group list during k-nearest neighbor calculations.
#' @param maxDist The maximum allowable distance in basepairs between two peaks to consider for co-accessibility.
#' @param scaleTo The total insertion counts from the designated group of single cells is summed across all relevant peak regions
#' from the `peakSet` of the `ArchRProject` and normalized to the total depth provided by `scaleTo`.
#' @param log2Norm A boolean value indicating whether to log2 transform the single-cell groups prior to computing co-accessibility correlations.
#' @param predictionCutoff A numeric describing the cutoff for RNA integration to use when picking cells for groupings.
#' @param seed A number to be used as the seed for random number generation required in knn determination. It is recommended
#' to keep track of the seed used so that you can reproduce results downstream.
#' @param threads The number of threads to be used for parallel computing.
#' @param verbose A boolean value that determines whether standard output should be printed.
#' @param logFile The path to a file to be used for logging ArchR output.
#' @export
addPeak2GeneLinks <- function(
ArchRProj = NULL,
reducedDims = "IterativeLSI",
useMatrix = "GeneIntegrationMatrix",
dimsToUse = 1:30,
scaleDims = NULL,
corCutOff = 0.75,
k = 100,
knnIteration = 500,
overlapCutoff = 0.8,
maxDist = 250000,
scaleTo = 10^4,
log2Norm = TRUE,
predictionCutoff = 0.4,
seed = 1,
threads = max(floor(getArchRThreads() / 2), 1),
verbose = TRUE,
logFile = createLogFile("addPeak2GeneLinks")
){
.validInput(input = ArchRProj, name = "ArchRProj", valid = c("ArchRProj"))
.validInput(input = reducedDims, name = "reducedDims", valid = c("character"))
.validInput(input = dimsToUse, name = "dimsToUse", valid = c("numeric", "null"))
.validInput(input = scaleDims, name = "scaleDims", valid = c("boolean", "null"))
.validInput(input = corCutOff, name = "corCutOff", valid = c("numeric", "null"))
.validInput(input = k, name = "k", valid = c("integer"))
.validInput(input = knnIteration, name = "knnIteration", valid = c("integer"))
.validInput(input = overlapCutoff, name = "overlapCutoff", valid = c("numeric"))
.validInput(input = maxDist, name = "maxDist", valid = c("integer"))
.validInput(input = scaleTo, name = "scaleTo", valid = c("numeric"))
.validInput(input = log2Norm, name = "log2Norm", valid = c("boolean"))
.validInput(input = threads, name = "threads", valid = c("integer"))
.validInput(input = verbose, name = "verbose", valid = c("boolean"))
.validInput(input = logFile, name = "logFile", valid = c("character"))
tstart <- Sys.time()
.startLogging(logFile = logFile)
.logThis(mget(names(formals()),sys.frame(sys.nframe())), "addPeak2GeneLinks Input-Parameters", logFile = logFile)
.logDiffTime(main="Getting Available Matrices", t1=tstart, verbose=verbose, logFile=logFile)
AvailableMatrices <- getAvailableMatrices(ArchRProj)
if("PeakMatrix" %ni% AvailableMatrices){
stop("PeakMatrix not in AvailableMatrices")
}
if(useMatrix %ni% AvailableMatrices){
stop(paste0(useMatrix, " not in AvailableMatrices"))
}
ArrowFiles <- getArrowFiles(ArchRProj)
tstart <- Sys.time()
dfAll <- .safelapply(seq_along(ArrowFiles), function(x){
DataFrame(
cellNames = paste0(names(ArrowFiles)[x], "#", h5read(ArrowFiles[x], paste0(useMatrix, "/Info/CellNames"))),
predictionScore = h5read(ArrowFiles[x], paste0(useMatrix, "/Info/predictionScore"))
)
}, threads = threads) %>% Reduce("rbind", .)
.logDiffTime(
sprintf("Filtered Low Prediction Score Cells (%s of %s, %s)",
sum(dfAll[,2] < predictionCutoff),
nrow(dfAll),
round(sum(dfAll[,2] < predictionCutoff) / nrow(dfAll), 3)
), t1=tstart, verbose=verbose, logFile=logFile)
keep <- sum(dfAll[,2] >= predictionCutoff) / nrow(dfAll)
dfAll <- dfAll[which(dfAll[,2] > predictionCutoff),]
set.seed(seed)
#Get Peak Set
peakSet <- getPeakSet(ArchRProj)
.logThis(peakSet, "peakSet", logFile = logFile)
#Gene Info
geneSet <- .getFeatureDF(ArrowFiles, useMatrix, threads = threads)
geneStart <- GRanges(geneSet$seqnames, IRanges(geneSet$start, width = 1), name = geneSet$name, idx = geneSet$idx)
.logThis(geneStart, "geneStart", logFile = logFile)
#Get Reduced Dims
rD <- getReducedDims(ArchRProj, reducedDims = reducedDims, corCutOff = corCutOff, dimsToUse = dimsToUse)
#Subsample
idx <- sample(seq_len(nrow(rD)), knnIteration, replace = !nrow(rD) >= knnIteration)
#KNN Matrix
.logDiffTime(main="Computing KNN", t1=tstart, verbose=verbose, logFile=logFile)
knnObj <- .computeKNN(data = rD, query = rD[idx,], k = k)
#Determin Overlap
.logDiffTime(main="Identifying Non-Overlapping KNN pairs", t1=tstart, verbose=verbose, logFile=logFile)
keepKnn <- determineOverlapCpp(knnObj, floor(overlapCutoff * k))
#Keep Above Cutoff
knnObj <- knnObj[keepKnn==0,]
.logDiffTime(paste0("Identified ", nrow(knnObj), " Groupings!"), t1=tstart, verbose=verbose, logFile=logFile)
#Convert To Names List
knnObj <- lapply(seq_len(nrow(knnObj)), function(x){
rownames(rD)[knnObj[x, ]]
}) %>% SimpleList
#Check Chromosomes
chri <- gtools::mixedsort(unique(paste0(seqnames(peakSet))))
chrj <- gtools::mixedsort(unique(paste0(seqnames(geneStart))))
chrij <- intersect(chri, chrj)
#Features
geneDF <- mcols(geneStart)
peakDF <- mcols(peakSet)
geneDF$seqnames <- seqnames(geneStart)
peakDF$seqnames <- seqnames(peakSet)
#Group Matrix RNA
.logDiffTime(main="Getting Group RNA Matrix", t1=tstart, verbose=verbose, logFile=logFile)
groupMatRNA <- .getGroupMatrix(
ArrowFiles = getArrowFiles(ArchRProj),
featureDF = geneDF,
groupList = knnObj,
useMatrix = useMatrix,
threads = threads,
verbose = FALSE
)
.logThis(groupMatRNA, "groupMatRNA", logFile = logFile)
#Group Matrix ATAC
.logDiffTime(main="Getting Group ATAC Matrix", t1=tstart, verbose=verbose, logFile=logFile)
groupMatATAC <- .getGroupMatrix(
ArrowFiles = getArrowFiles(ArchRProj),
featureDF = peakDF,
groupList = knnObj,
useMatrix = "PeakMatrix",
threads = threads,
verbose = FALSE
)
.logThis(groupMatATAC, "groupMatATAC", logFile = logFile)
.logDiffTime(main="Normalizing Group Matrices", t1=tstart, verbose=verbose, logFile=logFile)
groupMatRNA <- t(t(groupMatRNA) / colSums(groupMatRNA)) * scaleTo
groupMatATAC <- t(t(groupMatATAC) / colSums(groupMatATAC)) * scaleTo
if(log2Norm){
groupMatRNA <- log2(groupMatRNA + 1)
groupMatATAC <- log2(groupMatATAC + 1)
}
names(geneStart) <- NULL
seRNA <- SummarizedExperiment(
assays = SimpleList(RNA = groupMatRNA),
rowRanges = geneStart
)
metadata(seRNA)$KNNList <- knnObj
.logThis(seRNA, "seRNA", logFile = logFile)
names(peakSet) <- NULL
seATAC <- SummarizedExperiment(
assays = SimpleList(ATAC = groupMatATAC),
rowRanges = peakSet
)
metadata(seATAC)$KNNList <- knnObj
.logThis(seATAC, "seATAC", logFile = logFile)
rm(groupMatRNA, groupMatATAC)
gc()
#Overlaps
.logDiffTime(main="Finding Peak Gene Pairings", t1=tstart, verbose=verbose, logFile=logFile)
o <- DataFrame(
findOverlaps(
.suppressAll(resize(seRNA, 2 * maxDist + 1, "center")),
resize(rowRanges(seATAC), 1, "center"),
ignore.strand = TRUE
)
)
#Get Distance from Fixed point A B
o$distance <- distance(rowRanges(seRNA)[o[,1]] , rowRanges(seATAC)[o[,2]] )
colnames(o) <- c("B", "A", "distance")
#Null Correlations
.logDiffTime(main="Computing Background Correlations", t1=tstart, verbose=verbose, logFile=logFile)
nullCor <- .getNullCorrelations(seATAC, seRNA, o, 1000)
.logDiffTime(main="Computing Correlations", t1=tstart, verbose=verbose, logFile=logFile)
o$Correlation <- rowCorCpp(as.integer(o$A), as.integer(o$B), assay(seATAC), assay(seRNA))
o$VarAssayA <- .getQuantiles(matrixStats::rowVars(assay(seATAC)))[o$A]
o$VarAssayB <- .getQuantiles(matrixStats::rowVars(assay(seRNA)))[o$B]
o$TStat <- (o$Correlation / sqrt((1-o$Correlation^2)/(ncol(seATAC)-2))) #T-statistic P-value
o$Pval <- 2*pt(-abs(o$TStat), ncol(seATAC) - 2)
o$FDR <- p.adjust(o$Pval, method = "fdr")
o$EmpPval <- 2*pnorm(-abs(((o$Correlation - mean(nullCor[[2]])) / sd(nullCor[[2]]))))
o$EmpFDR <- p.adjust(o$EmpPval, method = "fdr")
out <- o[, c("A", "B", "Correlation", "FDR", "VarAssayA", "VarAssayB","EmpPval","EmpFDR")]
colnames(out) <- c("idxATAC", "idxRNA", "Correlation", "FDR", "VarQATAC", "VarQRNA","EmpPval","EmpFDR")
mcols(peakSet) <- NULL
names(peakSet) <- NULL
metadata(out)$peakSet <- peakSet
metadata(out)$geneSet <- geneStart
#Save Group Matrices
dir.create(file.path(getOutputDirectory(ArchRProj), "Peak2GeneLinks"), showWarnings = FALSE)
outATAC <- file.path(getOutputDirectory(ArchRProj), "Peak2GeneLinks", "seATAC-Group-KNN.rds")
saveRDS(seATAC, outATAC, compress = FALSE)
outRNA <- file.path(getOutputDirectory(ArchRProj), "Peak2GeneLinks", "seRNA-Group-KNN.rds")
saveRDS(seRNA, outRNA, compress = FALSE)
metadata(out)$seATAC <- outATAC
metadata(out)$seRNA <- outRNA
metadata(ArchRProj@peakSet)$Peak2GeneLinks <- out
.logDiffTime(main="Completed Peak2Gene Correlations!", t1=tstart, verbose=verbose, logFile=logFile)
.endLogging(logFile = logFile)
ArchRProj
}
.getNullCorrelations <- function(seA, seB, o, n){
o$seq <- seqnames(seA)[o$A]
nullCor <- lapply(seq_along(unique(o$seq)), function(i){
#Get chr from olist
chri <- unique(o$seq)[i]
message(chri, " ", appendLF = FALSE)
#Randomly get n seA
id <- which(as.character(seqnames(seA)) != chri)
if(length(id) > n){
transAidx <- sample(id, n)
}else{
transAidx <- id
}
#Calculate Correlations
grid <- expand.grid(transAidx, unique(o[o$seq==chri,]$B))
idxA <- unique(grid[,1])
idxB <- unique(grid[,2])
seSubA <- seA[idxA]
seSubB <- seB[idxB]
grid[,3] <- match(grid[,1], idxA)
grid[,4] <- match(grid[,2], idxB)
colnames(grid) <- c("A", "B")
out <- rowCorCpp(grid[,3], grid[,4], assay(seSubA), assay(seSubB))
out <- na.omit(out)
return(out)
}) %>% SimpleList
message("")
summaryDF <- lapply(nullCor, function(x){
data.frame(mean = mean(x), sd = sd(x), median = median(x), n = length(x))
}) %>% Reduce("rbind",.)
return(list(summaryDF, unlist(nullCor)))
}
#' Get the peak-to-gene links from an ArchRProject
#'
#' This function obtains peak-to-gene links from an ArchRProject.
#'
#' @param ArchRProj An `ArchRProject` object.
#' @param corCutOff A numeric describing the minimum numeric peak-to-gene correlation to return.
#' @param FDRCutOff A numeric describing the maximum numeric peak-to-gene false discovery rate to return.
#' @param varCutOffATAC A numeric describing the minimum variance quantile of the ATAC peak accessibility when selecting links.
#' @param varCutOffRNA A numeric describing the minimum variance quantile of the RNA gene expression when selecting links.
#' @param resolution A numeric describing the bp resolution to return loops as. This helps with overplotting of correlated regions.
#' @param returnLoops A boolean indicating to return the peak-to-gene links as a `GRanges` "loops" object designed for use with
#' the `ArchRBrowser()` or as an `ArchRBrowserTrack()`.
#' @export
getPeak2GeneLinks <- function(
ArchRProj = NULL,
corCutOff = 0.45,
FDRCutOff = 0.0001,
varCutOffATAC = 0.25,
varCutOffRNA = 0.25,
resolution = 1,
returnLoops = TRUE
){
.validInput(input = ArchRProj, name = "ArchRProj", valid = "ArchRProject")
.validInput(input = corCutOff, name = "corCutOff", valid = "numeric")
.validInput(input = FDRCutOff, name = "FDRCutOff", valid = "numeric")
.validInput(input = varCutOffATAC, name = "varCutOffATAC", valid = "numeric")
.validInput(input = varCutOffRNA, name = "varCutOffRNA", valid = "numeric")
.validInput(input = resolution, name = "resolution", valid = c("integer", "null"))
.validInput(input = returnLoops, name = "returnLoops", valid = "boolean")
if(is.null(ArchRProj@peakSet)){
return(NULL)
}
if(is.null(metadata(ArchRProj@peakSet)$Peak2GeneLinks)){
return(NULL)
}else{
p2g <- metadata(ArchRProj@peakSet)$Peak2GeneLinks
p2g <- p2g[which(p2g$Correlation >= corCutOff & p2g$FDR <= FDRCutOff), ,drop=FALSE]
if(!is.null(varCutOffATAC)){
p2g <- p2g[which(p2g$VarQATAC > varCutOffATAC),]
}
if(!is.null(varCutOffRNA)){
p2g <- p2g[which(p2g$VarQRNA > varCutOffRNA),]
}
if(returnLoops){
peakSummits <- resize(metadata(p2g)$peakSet, 1, "center")
geneStarts <- resize(metadata(p2g)$geneSet, 1, "start")
if(!is.null(resolution)){
summitTiles <- floor(start(peakSummits) / resolution) * resolution + floor(resolution / 2)
geneTiles <- floor(start(geneStarts) / resolution) * resolution + floor(resolution / 2)
}else{
summitTiles <- start(peakSummits)
geneTiles <- start(geneTiles)
}
loops <- .constructGR(
seqnames = seqnames(peakSummits[p2g$idxATAC]),
start = summitTiles[p2g$idxATAC],
end = geneTiles[p2g$idxRNA]
)
mcols(loops)$value <- p2g$Correlation
mcols(loops)$FDR <- p2g$FDR
loops <- loops[order(mcols(loops)$value, decreasing=TRUE)]
loops <- unique(loops)
loops <- loops[width(loops) > 0]
loops <- sort(sortSeqlevels(loops))
loops <- SimpleList(Peak2GeneLinks = loops)
return(loops)
}else{
return(p2g)
}
}
}
# Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
rowCorCpp <- function(idxX, idxY, X, Y) {
.Call('_ArchR_rowCorCpp', PACKAGE = 'ArchR', idxX, idxY, X, Y)
}
rleSumsStrandedChr <- function(rle, x, strand, width) {
.Call('_ArchR_rleSumsStrandedChr', PACKAGE = 'ArchR', rle, x, strand, width)
}
rleSumsStranded <- function(rleList, grList, width, as_integer) {
.Call('_ArchR_rleSumsStranded', PACKAGE = 'ArchR', rleList, grList, width, as_integer)
}
tabulate2dCpp <- function(x, xmin, xmax, y, ymin, ymax) {
.Call('_ArchR_tabulate2dCpp', PACKAGE = 'ArchR', x, xmin, xmax, y, ymin, ymax)
}
computeSparseRowVariances <- function(j, val, rm, n) {
.Call('_ArchR_computeSparseRowVariances', PACKAGE = 'ArchR', j, val, rm, n)
}
determineOverlapCpp <- function(m, overlapCut) {
.Call('_ArchR_determineOverlapCpp', PACKAGE = 'ArchR', m, overlapCut)
}
kmerIdxCpp <- function(str, window, n, kmer) {
.Call('_ArchR_kmerIdxCpp', PACKAGE = 'ArchR', str, window, n, kmer)
}
kmerPositionFrequencyCpp <- function(string_vector, strand_vector, window, w, kmer) {
.Call('_ArchR_kmerPositionFrequencyCpp', PACKAGE = 'ArchR', string_vector, strand_vector, window, w, kmer)
}
kmerIDFrequencyCpp <- function(string_vector, id_vector, n_id, window, w, kmer) {
.Call('_ArchR_kmerIDFrequencyCpp', PACKAGE = 'ArchR', string_vector, id_vector, n_id, window, w, kmer)
}
##########################################################################################
# Validation Methods
##########################################################################################
.validInput <- function(input = NULL, name = NULL, valid = NULL){
valid <- unique(valid)
if(is.character(valid)){
valid <- tolower(valid)
}else{
stop("Validator must be a character!")
}
if(!is.character(name)){
stop("name must be a character!")
}
if("null" %in% tolower(valid)){
valid <- c("null", valid[which(tolower(valid) != "null")])
}
av <- FALSE
for(i in seq_along(valid)){
vi <- valid[i]
if(vi == "integer" | vi == "wholenumber"){
if(all(is.numeric(input))){
#https://stackoverflow.com/questions/3476782/check-if-the-number-is-integer
cv <- min(abs(c(input%%1, input%%1-1))) < .Machine$double.eps^0.5
}else{
cv <- FALSE
}
}else if(vi == "null"){
cv <- is.null(input)
}else if(vi == "bool" | vi == "boolean" | vi == "logical"){
cv <- is.logical(input)
}else if(vi == "numeric"){
cv <- is.numeric(input)
}else if(vi == "vector"){
cv <- is.vector(input)
}else if(vi == "matrix"){
cv <- is.matrix(input)
}else if(vi == "sparsematrix"){
cv <- is(input, "dgCMatrix")
}else if(vi == "character"){
cv <- is.character(input)
}else if(vi == "factor"){
cv <- is.factor(input)
}else if(vi == "rlecharacter"){
cv1 <- is(input, "Rle")
if(cv1){
cv <- is(input@values, "factor") || is(input@values, "character")
}else{
cv <- FALSE
}
}else if(vi == "palette"){
cv <- all(.isColor(input))
}else if(vi == "timestamp"){
cv <- is(input, "POSIXct")
}else if(vi == "dataframe" | vi == "data.frame" | vi == "df"){
cv1 <- is.data.frame(input)
cv2 <- is(input, "DataFrame")
cv <- any(cv1, cv2)
}else if(vi == "fileexists"){
cv <- all(file.exists(input))
}else if(vi == "direxists"){
cv <- all(dir.exists(input))
}else if(vi == "granges" | vi == "gr"){
cv <- is(input, "GRanges")
}else if(vi == "grangeslist" | vi == "grlist"){
cv <- .isGRList(input)
}else if(vi == "list" | vi == "simplelist"){
cv1 <- is.list(input)
cv2 <- is(input, "SimpleList")
cv <- any(cv1, cv2)
}else if(vi == "bsgenome"){
cv1 <- is(input, "BSgenome")
cv2 <- tryCatch({
library(input)
eval(parse(text=input))
}, error = function(e){
FALSE
})
cv <- any(cv1, cv2)
}else if(vi == "se" | vi == "summarizedexperiment"){
cv <- is(input, "SummarizedExperiment")
}else if(vi == "seurat" | vi == "seuratobject"){
cv <- is(input, "Seurat")
}else if(vi == "txdb"){
cv <- is(input, "TxDb")
}else if(vi == "orgdb"){
cv <- is(input, "OrgDb")
}else if(vi == "bsgenome"){
cv <- is(input, "BSgenome")
}else if(vi == "parallelparam"){
cv <- is(input, "BatchtoolsParam")
}else if(vi == "archrproj" | vi == "archrproject"){
cv <- is(input, "ArchRProject")
###validObject(input) check this doesnt break anything if we
###add it. Useful to make sure all ArrowFiles exist! QQQ
}else{
stop("Validator is not currently supported by ArchR!")
}
if(cv){
av <- TRUE
break
}
}
if(av){
return(invisible(TRUE))
}else{
stop("Input value for '", name,"' is not a ", paste(valid, collapse="," ), ", (",name," = ",class(input),") please supply valid input!")
}
}
#https://stackoverflow.com/questions/3476782/check-if-the-number-is-integer
.isWholenumber <- function(x, tol = .Machine$double.eps^0.5){
abs(x - round(x)) < tol
}
#https://stackoverflow.com/questions/13289009/check-if-character-string-is-a-valid-color-representation
.isColor <- function(x = NULL){
unlist(lapply(x, function(y) tryCatch(is.matrix(col2rgb(y)), error = function(e) FALSE)))
}
.isDiscrete <- function(x = NULL){
is.factor(x) || is.character(x) || is.logical(x)
}
.isGRList <- function(x){
isList <- grepl("list", class(x), ignore.case=TRUE)
if(!isList){
FALSE
}else{
allGR <- all(unlist(lapply(x, function(x) is(x, "GRanges") )))
if(allGR){
TRUE
}else{
FALSE
}
}
}
#' Get/Validate BSgenome
#'
#' This function will attempt to get or validate an input as a BSgenome.
#'
#' @param genome This option must be one of the following: (i) the name of a valid ArchR-supported genome ("hg38", "hg19", or "mm10"),
#' (ii) the name of a `BSgenome` package (for ex. "BSgenome.Hsapiens.UCSC.hg19"), or (iii) a `BSgenome` object.
#' @param masked A boolean describing whether or not to access the masked version of the selected genome. See `BSgenome::getBSgenome()`.
#' @export
validBSgenome <- function(genome = NULL, masked = FALSE){
.validInput(input = genome, name = "genome", valid = c("character", "bsgenome"))
.validInput(input = masked, name = "masked", valid = c("boolean"))
stopifnot(!is.null(genome))
if(inherits(genome, "BSgenome")){
return(genome)
}else if(is.character(genome)){
genome <- tryCatch({
.requirePackage(genome)
bsg <- eval(parse(text = genome))
if(inherits(bsg, "BSgenome")){
return(bsg)
}else{
stop("genome is not a BSgenome valid class!")
}
}, error = function(x){
BSgenome::getBSgenome(genome, masked = masked)
})
return(genome)
}else{
stop("Cannot validate BSgenome options are a valid BSgenome or character for getBSgenome")
}
}
.validTxDb <- function(TxDb = NULL){
stopifnot(!is.null(TxDb))
if(inherits(TxDb, "TxDb")){
return(TxDb)
}else if(is.character(TxDb)){
return(getTxDb(TxDb)) #change
}else{
stop("Cannot validate TxDb options are a valid TxDb or character for getTxDb")
}
}
.validOrgDb <- function(OrgDb = NULL){
stopifnot(!is.null(OrgDb))
if(inherits(OrgDb, "OrgDb")){
return(OrgDb)
}else if(is.character(OrgDb)){
return(getOrgDb(OrgDb)) #change
}else{
stop("Cannot validate OrgDb options are a valid OrgDb or character for getOrgDb")
}
}
.validGRanges <- function(gr = NULL){
stopifnot(!is.null(gr))
if(inherits(gr, "GRanges")){
return(gr)
}else{
stop("Error cannot validate genomic range!")
}
}
.validGeneAnnotation <- function(geneAnnotation = NULL){
if(!inherits(geneAnnotation, "SimpleList")){
if(inherits(geneAnnotation, "list")){
geneAnnotation <- as(geneAnnotation, "SimpleList")
}else{
stop("geneAnnotation must be a list/SimpleList of 3 GRanges for : Genes GRanges, Exons GRanges and TSS GRanges!")
}
}
if(identical(sort(tolower(names(geneAnnotation))), c("exons", "genes", "tss"))){
gA <- SimpleList()
gA$genes <- .validGRanges(geneAnnotation[[grep("genes", names(geneAnnotation), ignore.case = TRUE)]])
gA$exons <- .validGRanges(geneAnnotation[[grep("exons", names(geneAnnotation), ignore.case = TRUE)]])
gA$TSS <- .validGRanges(geneAnnotation[[grep("TSS", names(geneAnnotation), ignore.case = TRUE)]])
}else{
stop("geneAnnotation must be a list/SimpleList of 3 GRanges for : Genes GRanges, Exons GRanges and TSS GRanges!")
}
gA
}
.validGenomeAnnotation <- function(genomeAnnotation = NULL){
if(!inherits(genomeAnnotation, "SimpleList")){
if(inherits(genomeAnnotation, "list")){
genomeAnnotation <- as(genomeAnnotation, "SimpleList")
}else{
stop("genomeAnnotation must be a list/SimpleList of 3 GRanges for : blacklist GRanges, chromSizes GRanges and genome BSgenome package string (ie hg38 or BSgenome.Hsapiens.UCSC.hg38)!")
}
}
if(identical(sort(tolower(names(genomeAnnotation))), c("blacklist", "chromsizes", "genome"))){
gA <- SimpleList()
gA$blacklist <- .validGRanges(genomeAnnotation[[grep("blacklist", names(genomeAnnotation), ignore.case = TRUE)]])
if(genomeAnnotation[[grep("genome", names(genomeAnnotation), ignore.case = TRUE)]]=="nullGenome"){
gA$genome <- "nullGenome"
}else{
bsg <- validBSgenome(genomeAnnotation[[grep("genome", names(genomeAnnotation), ignore.case = TRUE)]])
gA$genome <- bsg@pkgname
}
gA$chromSizes <- .validGRanges(genomeAnnotation[[grep("chromsizes", names(genomeAnnotation), ignore.case = TRUE)]])
}else{
stop("genomeAnnotation must be a list/SimpleList of 3 GRanges for : blacklist GRanges, chromSizes GRanges and genome BSgenome package string (ie hg38 or BSgenome.Hsapiens.UCSC.hg38)!")
}
gA
}
.validGeneAnnoByGenomeAnno <- function(geneAnnotation, genomeAnnotation){
allSeqs <- unique(paste0(seqnames(genomeAnnotation$chromSizes)))
geneSeqs <- unique(paste0(seqnames(geneAnnotation$genes)))
if(!all(geneSeqs %in% allSeqs)){
geneNotIn <- geneSeqs[which(geneSeqs %ni% allSeqs)]
message("Found Gene Seqnames not in GenomeAnnotation chromSizes, Removing : ", paste0(geneNotIn, collapse=","))
geneAnnotation$genes <- .subsetSeqnamesGR(geneAnnotation$genes, names = allSeqs)
}
exonSeqs <- unique(paste0(seqnames(geneAnnotation$exons)))
if(!all(exonSeqs %in% allSeqs)){
exonNotIn <- exonSeqs[which(exonSeqs %ni% allSeqs)]
message("Found Exon Seqnames not in GenomeAnnotation chromSizes, Removing : ", paste0(exonNotIn, collapse=","))
geneAnnotation$exons <- .subsetSeqnamesGR(geneAnnotation$exons, names = allSeqs)
}
TSSSeqs <- unique(paste0(seqnames(geneAnnotation$TSS)))
if(!all(TSSSeqs %in% allSeqs)){
TSSNotIn <- TSSSeqs[which(TSSSeqs %ni% allSeqs)]
message("Found TSS Seqnames not in GenomeAnnotation chromSizes, Removing : ", paste0(TSSNotIn, collapse=","))
geneAnnotation$TSS <- .subsetSeqnamesGR(geneAnnotation$TSS, names = allSeqs)
}
geneAnnotation
}
.validArchRProject <- function(ArchRProj = NULL){
if(!inherits(ArchRProj, "ArchRProject")){
stop("Not a valid ArchRProject as input!")
}else{
ArchRProj
}
}
####################################
# Log Tools
####################################
#' Set ArchR Logging
#'
#' This function will set ArchR logging
#'
#' @param useLogs A boolean describing whether to use logging with ArchR.
#' @export
addArchRLogging <- function(useLogs = TRUE){
.validInput(input = useLogs, name = "useLogs", valid = "boolean")
message("Setting ArchRLogging = ", useLogs)
options(ArchR.logging = useLogs)
return(invisible(0))
}
#' Get ArchR Logging
#'
#' This function will get ArchR logging
#'
#' @export
getArchRLogging <- function(){
ArchRLogging <- options()[["ArchR.logging"]]
if(!is.logical(ArchRLogging)){
options(ArchR.logging = TRUE)
return(TRUE)
}
ArchRLogging
}
#' Set ArchR Debugging
#'
#' This function will set ArchR Debugging which will save an RDS if an error is encountered.
#'
#' @param debug A boolean describing whether to use logging with ArchR.
#' @export
addArchRDebugging <- function(debug = FALSE){
.validInput(input = debug, name = "debug", valid = "boolean")
message("Setting ArchRDebugging = ", debug)
options(ArchR.logging = debug)
return(invisible(0))
}
#' Get ArchR Debugging
#'
#' This function will get ArchR Debugging which will save an RDS if an error is encountered.
#'
#' @export
getArchRDebugging <- function(){
ArchRDebugging <- options()[["ArchR.debugging"]]
if(!is.logical(ArchRDebugging)){
options(ArchR.debugging = FALSE)
return(FALSE)
}
ArchRDebugging
}
#' Create a Log File for ArchR
#'
#' This function will create a log file for ArchR functions. If ArchRLogging is not TRUE
#' this function will return NULL.
#'
#' @param name A character string to add a more descriptive name in log file.
#' @param logDir The path to a directory where log files should be written.
#' @export
createLogFile <- function(
name = NULL,
logDir = "ArchRLogs",
useLogs = getArchRLogging()
){
.validInput(input = name, name = "name", valid = "character")
.validInput(input = logDir, name = "logDir", valid = "character")
.validInput(input = useLogs, name = "useLogs", valid = "boolean")
if(!useLogs){
return(NULL)
}
dir.create(logDir, showWarnings = FALSE)
if(is.null(name)){
logFile <- .tempfile(pattern = "ArchR", fileext = ".log", tmpdir = logDir)
}else{
logFile <- .tempfile(pattern = paste0("ArchR-", name), fileext = ".log", tmpdir = logDir)
}
logFile
}
.messageDiffTime <- function(...){ #Deprecated
.logDiffTime(...)
}
.logDiffTime <- function(
main = "",
t1 = NULL,
verbose = TRUE,
addHeader = FALSE,
t2 = Sys.time(),
units = "mins",
header = "###########",
tail = "elapsed.",
precision = 3,
logFile = NULL,
useLogs = getArchRLogging()
){
if(verbose){
timeStamp <- tryCatch({
dt <- abs(round(difftime(t2, t1, units = units),precision))
if(addHeader){
msg <- sprintf("%s\n%s : %s, %s %s %s\n%s", header, Sys.time(), main, dt, units, tail, header)
}else{
msg <- sprintf("%s : %s, %s %s %s", Sys.time(), main, dt, units, tail)
}
message(msg)
}, error = function(x){
message("Time Error : ", x)
})
}
if(!useLogs){
return(invisible(0))
}
if(!is.null(logFile)){
if(file.exists(logFile)){
logStamp <- tryCatch({
dt <- abs(round(difftime(t2, t1, units = units),precision))
if(addHeader){
msg <- sprintf("%s\n%s : %s, %s %s %s\n%s", header, Sys.time(), main, dt, units, tail, header)
}else{
msg <- sprintf("%s : %s, %s %s %s", Sys.time(), main, dt, units, tail)
}
cat(paste0(msg,"\n"), file = logFile, append = TRUE)
}, error = function(x){
0
})
}
}
return(invisible(0))
}
.startLogging <- function(
logFile = NULL,
useLogs = getArchRLogging()
){
if(!useLogs){
return(invisible(0))
}
if(is.null(logFile)){
return(invisible(0))
}
if(file.exists(logFile)){
return(invisible(0))
}
.getRam <- function(OS = .Platform$OS.type){
if(grepl("linux", OS, ignore.case = TRUE)){
ram <- paste0("Linux : ", as.numeric(system("awk '/MemTotal/ {print $2}' /proc/meminfo", intern = TRUE)))
}else if(grepl("unix", OS, ignore.case = TRUE)){
ram <- system("/usr/sbin/system_profiler SPHardwareDataType", intern = TRUE)
ram <- paste0("MAC : ", gsub("Memory:","",gsub(" ","", grep("Memory", ram, value = TRUE))))
}else{
ram <- NA
}
}
message("ArchR logging to : ", logFile,
"\nIf there is an issue, please report to github with logFile!")
#Begin With
cat(.ArchRLogo(ascii = "Package", messageLogo = FALSE), file = logFile, append = FALSE)
cat("\nLogging With ArchR!\n\n", file = logFile, append = TRUE)
cat(paste0("Start Time : ",Sys.time(),"\n\n"), file = logFile, append = TRUE)
#ArchR Info
cat("------- ArchR Info\n\n", file = logFile, append = TRUE)
cat(paste0("ArchRThreads = ", getArchRThreads()), file = logFile, append = TRUE)
tryCatch({
if(!is.null(getArchRGenome())){
cat(paste0("\nArchRGenome = ", getArchRGenome()), file = logFile, append = TRUE)
}
}, error = function(x){
})
cat("\n\n", file = logFile, append = TRUE)
#Add Info