-
Notifications
You must be signed in to change notification settings - Fork 0
/
oncoFunctions.R
1722 lines (1377 loc) · 53.4 KB
/
oncoFunctions.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
### LIBRARIES & SETTINGS
###
library(compiler)
enableJIT(3)
setCompilerOptions(optimize = 3)
options(stringsAsFactors = FALSE)
library(OncoSimulR)
library(parallel)
library(pryr)
library(dplyr)
library(testthat)
library(stringr)
library(combinat)
library(pbapply)
library(pbmcapply)
### FUNCTIONS
###
# prompt: where to get files from/save files to?
askDir <- function(defaultDir=".",message="Choose a directory.") {
# ask for directory
cat(message)
cat("\n")
cat(paste("Leave blank for default: ",defaultDir,sep=""))
cat("\n")
cat(" > Enter path: ")
input <- readLines("stdin",1)
cat("\n")
# set default directory if input was blank
if (input == "") input <- defaultDir
# change dot (.) by current directory
if (grepl(".",input)) {
input <- sub(".",getwd(),input,fixed=T)
}
# show a warning if directory doesn't exist
if (!dir.exists(input)) {
cat("WARNING: Provided directory doesn't exist")
cat("\n")
cat("Continue? [y/n] ")
check <- readLines("stdin",1)
cat("\n")
if(check!="y") stop()
}
return(input)
}
# get number of genes from a file name
numGenesFromFile <- function(filename) {
case1 <- as.numeric(str_match(filename, "ng_(.*?)_fl")[2])
case2 <- as.numeric(str_match(filename, "ngenes_(.*?)__")[2])
out <- c(case1,case2)
out <- out[!is.na(out)]
return(out)
}
# get fitness landscape ID from file names
flIDFromFile <- function(filename) {
str_match(filename, "ID_(.*?)_")[2]
}
# get size_split from file names
sizeSplitFromFile <- function(filename) {
paste("size_split_",
str_match(filename, "size_split_(.*?)_")[2],
sep="")
}
# get detection regime from file names
detectFromFile <- function(filename) {
paste("detect_",
str_match(filename, "_detect_(.*?).RData")[2],
sep="")
}
# get landscape type from file names
flTypeFromFile <- function(filename) {
str_match(filename, "_typeLandscape_(.*?)_")[2]
}
# find number of mutations of a genotype given its name
nMut <- function(genotype) {
f <- function(genotype) {
out <- length(strsplit(genotype,",")[[1]])
if (genotype=="none" | genotype=="end" | genotype=="any") out <- NA
if (tolower(genotype)=="wt" | tolower(genotype)=="root") out <- 0
return(out)
}
out <- sapply(genotype,f)
names(out) <- NULL
return(out)
}
# generate genotype names, IDs, etc
makeGenotypes <- function(numGenes) {
# undo repeated number of genes
numGenes <- unique(numGenes)
# function: convert genotype IDs to names
genotypeIDtoName <- function(ID) {
paste(LETTERS[which(strsplit(ID,"")[[1]]==1)],collapse=", ")
}
# function: get gentoype names and IDs from given number of genes
allGenotypes <- function(numGenes) {
# full list of genotypes
numGenotypes <- 2^numGenes
genotypeIDs <- do.call(expand.grid,rep(list(0:1),numGenes))
genotypeIDs <- apply(genotypeIDs,1,paste,collapse="")
genotypeNames <- sapply(genotypeIDs,genotypeIDtoName)
genotypeMuts <- nMut(genotypeNames)
names(genotypeMuts) <- genotypeNames
names(genotypeIDs) <- genotypeNames
out <- list(numGenes=numGenes,numGenotypes=numGenotypes,
genotypeIDs=genotypeIDs,genotypeNames=genotypeNames,
genotypeMuts=genotypeMuts)
return(out)
}
aux <- vector(mode="list",length=length(numGenes))
names(aux) <- numGenes
# get all required genotype names and IDs for all possible numGenes in the files
for (i in 1:length(numGenes)) {
aux[[as.character(numGenes[i])]] <- allGenotypes(numGenes[i])
}
return(aux)
}
# find chain of (n+1)-genotypes given a POM (i.e. chain of n-genotypes)
nextInLOD <- function(lod,pom) {
# find (n+1)-genotype in a LOD given a n-genotype
nextInLOD_n <- function(genotype,lod) {
nextGenotype <- lod[nMut(lod)==nMut(genotype)+1]
# return "end" or "none" if there is no next genotype
if (length(nextGenotype)==0) {
if(genotype==lod[length(lod)]) {
nextGenotype <- "end"
} else {
nextGenotype <- "none"
}
}
return(nextGenotype)
}
# apply to full LOD
out <- sapply(pom,nextInLOD_n,lod=lod)
names(out) <- NULL
return(out)
}
# output of nextInLOD() in transition matrix form
nextInLOD_transitionMatrix <- function(lod,pom,allGenotypes) {
numGenotypes <- length(allGenotypes)
t <- matrix(0,nrow=numGenotypes,ncol=numGenotypes+2)
rownames(t) <- allGenotypes
colnames(t) <- c(allGenotypes,"none","end")
rows <- pom
cols <- nextInLOD(lod,pom)
for (j in 1:length(rows)) {
t[rows[j]==rownames(t),cols[j]==colnames(t)] <-
t[rows[j]==rownames(t),cols[j]==colnames(t)] + 1
}
# row normalization
tNorm <- matrix(rep(rowSums(t),numGenotypes+2),
nrow=numGenotypes,ncol=numGenotypes+2)
tNorm[tNorm==0] <- 1
t <- t/tNorm
# return t or update transitionMatrix
return(t)
}
# check which genotypes out of a given array are in a POM
whichInPOM <- function(genotypes,pom) {
# check if a certain genotype is in a given POM
isInPOM <- function(genotype,pom) {
as.numeric(genotype %in% pom)
}
out <- sapply(genotypes,isInPOM,pom=pom)
names(out) <- NULL
return(out)
}
# unfuse columns/rows of the kind X_Y_Z_... (X, Y, Z, ... = gene names)
unfuseGenotype <- function(genotype) {
# remove everything after first "_"
f <- function(genotype) {
paste(gsub("_.*","",
strsplit(genotype,", ")[[1]]),
collapse=", ")
}
unfusedGenotype <- sapply(genotype,f)
names(unfusedGenotype) <- NULL
# flag if something was done
n <- unfusedGenotype == genotype
if (sum(n) != length(n)) {
flag <- paste("unfused genotype(s):",paste(genotype[!n],collapse=" ; "))
} else {
flag <- NULL
}
out <- list(unfusedGenotype=unfusedGenotype,
flags=flag)
return(out)
}
# adjust the order of the letters that appear in a genotype name
orderGenotype <- function(genotype) {
f <- function(genotype) {
paste(sort(strsplit(genotype,", ")[[1]]),collapse=", ")
}
orderedGenotype <- sapply(genotype,f)
names(orderedGenotype) <- NULL
# return flag if something was done
n <- genotype != orderedGenotype
if (sum(n)>0) {
flag <- paste("ordered genotype(s):",paste(genotype[n],collapse=" ; "))
} else {
flag <- NULL
}
out <- list(orderedGenotype=orderedGenotype,
flags=flag)
return(out)
}
# take a matrix from CPM output, format it into a transition matrix
structTransitionMatrix <- function(transitionMatrix_in,allGenotypes) {
numGenotypes <- length(allGenotypes)
# proceed only if there is a matrix
if (is.matrix(transitionMatrix_in)) {
# initialize output (formatted matrix)
out <- transitionMatrix_in
# rename "WT" genotype to "" in matrix
colnames(out)[colnames(out)=="WT"] <- ""
rownames(out)[rownames(out)=="WT"] <- ""
# unfuse genotype names in rows/columns
unfG <- unfuseGenotype(colnames(out))
flags <- unfG$flags
colnames(out) <- unfG$unfusedGenotype
rownames(out) <- unfG$unfusedGenotype
# adjust order of letters in genotype names
ordG <- orderGenotype(colnames(out))
flags <- c(flags,ordG$flags)
colnames(out) <- ordG$orderedGenotype
rownames(out) <- ordG$orderedGenotype
# flags to return
flags <- paste(flags,collapse=" | ")
# add "end" column
genotypeEnd <- which(rowSums(out)==0)
out <- cbind(out,end=0)
out[genotypeEnd,"end"] <- 1
# diagonal elements interpreted as "end" entries (remaining in the same state)
out[,"end"] <- out[,"end"] + diag(out)
diag(out) <- 0
# how many genotypes are missing? (not accessible according to CPM)
accGenotypes <- dim(out)[1]
missGenotypes <- numGenotypes - accGenotypes
# if >0 gentoypes are missing, add those to the matrix (as "zero" entries)
if (missGenotypes>0) {
out <- cbind(out,matrix(0,ncol=missGenotypes,nrow=nrow(out)))
out <- rbind(out,matrix(0,nrow=missGenotypes,ncol=ncol(out)))
missGenotypeNames <- allGenotypes[!(allGenotypes %in% rownames(out))]
rownames(out)[(accGenotypes+1):nrow(out)] <- missGenotypeNames
colnames(out)[(accGenotypes+2):ncol(out)] <- missGenotypeNames
}
# rearrange rows and columns
newColOrder <- c(match(allGenotypes,colnames(out)),accGenotypes+1)
newRowOrder <- match(allGenotypes,rownames(out))
out <- out[newRowOrder,newColOrder]
# add "none" column
out <- cbind(out[,-ncol(out)],none=0,end=out[,ncol(out)])
# row-normalize (probably not needed at this point?)
# this IS needed since some of the un-structured CPM output matrices are
# not row-normalized to begin with
if(T) {
tNorm <- matrix(rep(rowSums(out),ncol(out)),
nrow=nrow(out),ncol=ncol(out))
tNorm[tNorm==0] <- 1
out <- out/tNorm
}
} else {
# flag if input is not a matrix
flags <- paste("not a matrix:",transitionMatrix_in)
# return NULL if input is not a matrix
out <- NULL
}
# return restructured matrix and flags
out <- list(transitionMatrix=out,flags=flags)
return(out)
}
# make a null matrix from an input matrix with row and column names
nullMatrix <- function(A) {
# not-normalized null matrix
muts <- nMut(rownames(A))
N <- matrix(0,ncol=ncol(A),nrow=nrow(A))
colnames(N) <- colnames(A)
rownames(N) <- rownames(A)
for (i in 0:(max(muts)-1)){
N[muts==i,c(muts,Inf,Inf)==(i+1)] <- 1
}
N[,"end"] <- 1
N[!rownames(N)=="","none"] <- 1
# normalized null matrix
Nn <- do.call(cbind,replicate(ncol(N),
rowSums(N),simplify=F))
Nn <- N/Nn
return(list(raw=N,norm=Nn))
}
# check what genotypes are accessible given a transition matrix
isAccessible <- function(A) {
# if A is not a matrix, return NULL
if(!is.matrix(A)) {
return(NULL)
} else {
out <- colSums(A[,1:nrow(A)])>0
out[names(out) %in% c("","WT","root")] <- TRUE
return(out)
}
}
# average square of differences (square-rooted)
sqDiff <- function(p, q, fix=F) {
pq <- c(p, q)
if(any(is.na(pq))) return(NA)
if(any(pq > 1)) stop("some prob. > 1")
if(any(pq < 0)) stop("some prob. < 0")
stopifnot(isTRUE(all.equal(sum(p), 1.0)) | isTRUE(all.equal(sum(p), 0.0)))
stopifnot(isTRUE(all.equal(sum(q), 1.0)) | isTRUE(all.equal(sum(q), 0.0)))
stopifnot(identical(length(p), length(q)))
if (all(pq==0)) return(0) # minimum possible value
if ((any(p>0) & all(q==0)) | (all(p==0) & any(q>0))) {
if(fix) {
if(any(p>0)) q <- rep(1/length(q),length(q))
if(all(p==0)) p <- rep(1/length(p),length(p))
return(sqDiff(p,q))
} else {
return(1) # max possible value
}
}
if(any(p>0) & any(q>0)) return(sqrt(mean((p-q)^2)))
}
## See below for improved code: my_kldiv_2
# Kullback-Leibler distance: Dkl = D(x || y)
my_kldiv <- function(x, y) {
## Based on https://stackoverflow.com/a/27953616
## with modification for removal of 0 in numerator of Kullback-Leibler as per
## https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence#Definition
## Using log2 so that max is 1. See wikipedia or
## Lin, J. (1991). "Divergence measures based on the shannon entropy"
## IEEE Transactions on Information Theory. 37 (1): 145–151.
## remove zeros in x
rmx <- which(x == 0)
if(length(rmx))
return(sum(x[-rmx] * log2(x[-rmx]/y[-rmx])))
else
return(sum(x * log2(x/y)))
}
## See below for improved code. jensen_shannon_2
# Jensen-Shannon entropy
jensen_shannon <- function(p, q, fix=F) {
## FIXME: could have checked none in m is 0?
## well, one could pass a silly c(a, b, 0), c(e, f, 0)
## and should we not allow for that?
## KL will not crash (we remove those, as we should, and they are really
## irrelevant anyway)
## FIXME: generalized function so it can handle all-zeros vectors as input
pq <- c(p, q)
if(any(is.na(pq))) return(NA)
if(any(pq > 1)) stop("some prob. > 1")
if(any(pq < 0)) stop("some prob. < 0")
stopifnot(isTRUE(all.equal(sum(p), 1.0)) | isTRUE(all.equal(sum(p), 0.0)))
stopifnot(isTRUE(all.equal(sum(q), 1.0)) | isTRUE(all.equal(sum(q), 0.0)))
stopifnot(identical(length(p), length(q)))
m <- 0.5 * (p + q)
if (all(pq==0)) return(0) # minimum possible value
if ((any(p>0) & all(q==0)) | (all(p==0) & any(q>0))) {
# return(1) #max. value
### FIXME: the output of this (p is all 0 and q is finite or vice-versa)
### now depends on the "eq" flag: if F it will return 1, if T it will
### equiprobabilize the all 0 input and calculate jensen_shannon as usual
if(fix) {
if(any(p>0)) q <- rep(1/length(q),length(q))
if(all(p==0)) p <- rep(1/length(p),length(p))
return(jensen_shannon(p,q))
} else {
return(1) # max. possible value
}
}
if(any(p>0) & any(q>0)) return(0.5 * (my_kldiv(p, m) + my_kldiv(q, m)))
## FIXME: yes, FIXME for the future.
## how do we know we never fail to fall into those cases?
## stop("JS undefined")
## rmp <- which(p == 0)
## rmq <- which(q == 0)
## kl1 <- sum(p[-rmp] * log(p[-rmp]/m[-rmp]))
## kl2 <- sum(q[-rmq] * log(q[-rmq]/m[-rmq]))
## return(0.5 * (kl1 + kl2))
## <- 0.5 * (sum(p * log(p / m)) + sum(q * log(q / m)))
}
# simplified Jensen-Shannon
easyJS <- function(p,q,fixNulls=F) {
# sanity checks
pq <- c(p, q)
if(any(is.na(pq))) return(NA)
if(any(pq > 1)) stop("some prob. > 1")
if(any(pq < 0)) stop("some prob. < 0")
stopifnot(isTRUE(all.equal(sum(p), 1.0)) | isTRUE(all.equal(sum(p), 0.0)))
stopifnot(isTRUE(all.equal(sum(q), 1.0)) | isTRUE(all.equal(sum(q), 0.0)))
stopifnot(identical(length(p), length(q)))
# if fixNulls, use null model instead of all-zero vectors
if(fixNulls) {
if(all(p==0)) p <- rep(1/length(p),length(p))
if(all(q==0)) q <- rep(1/length(q),length(q))
}
# "standard" case: both p and q are non-zero
m <- 0.5 * (p + q)
if(any(p>0) & any(q>0))
return(0.5 * (my_kldiv(p, m) + my_kldiv(q, m)))
else
return(NA)
}
# Hellinger distance
hellinger_distance <- function(p, q, fix=F) {
pq <- c(p, q)
if(any(is.na(pq))) return(NA)
if(any(pq > 1)) stop("some prob. > 1")
if(any(pq < 0)) stop("some prob. < 0")
stopifnot(isTRUE(all.equal(sum(p), 1.0)) | isTRUE(all.equal(sum(p), 0.0)))
stopifnot(isTRUE(all.equal(sum(q), 1.0)) | isTRUE(all.equal(sum(q), 0.0)))
stopifnot(identical(length(p), length(q)))
if (all(pq==0)) return(0) # minimum possible value
if ((any(p>0) & all(q==0)) | (all(p==0) & any(q>0))) {
if(fix) {
if(any(p>0)) q <- rep(1/length(q),length(q))
if(all(p==0)) p <- rep(1/length(p),length(p))
return(hellinger_distance(p,q))
} else {
return(1) # max possible value
}
}
if(any(p>0) & any(q>0)) return( (1/sqrt(2)) * sqrt(sum((sqrt(p) - sqrt(q))^2)) )
}
# Spearman correlation
spearman_corr <- function(p, q) {
pq <- c(p, q)
if(any(is.na(pq))) return(c(rho=NA,
pval=NA))
if(any(pq > 1)) stop("some prob. > 1")
if(any(pq < 0)) stop("some prob. < 0")
stopifnot(isTRUE(all.equal(sum(p), 1.0)) | isTRUE(all.equal(sum(p), 0.0)))
stopifnot(isTRUE(all.equal(sum(q), 1.0)) | isTRUE(all.equal(sum(q), 0.0)))
stopifnot(identical(length(p), length(q)))
if (all(pq==0)) return(c(rho=1, # maximum possible value
pval=1))
if ((any(p>0) & all(q==0)) | (all(p==0) & any(q>0))) {
return(c(rho=0, # min possible value
pval=1))
}
if(any(p>0) & any(q>0)) {
ct <- suppressWarnings(cor.test(p, q, method = "spearman"))
# if output is NA (p and/or q equiprobable), return 0 instead
if (is.na(ct$estimate[["rho"]])) {
ct$estimate[["rho"]] <- 0
ct$p.value <- 1
}
return(c(rho=ct$estimate[["rho"]],
pval=ct$p.value))
}
}
eq <- function(p,threshold=0) {
if(any(is.na(p))) return(NA)
if(any(p > 1)) stop("some prob. > 1")
if(any(p < 0)) stop("some prob. < 0")
stopifnot(isTRUE(all.equal(sum(p), 1.0)) | isTRUE(all.equal(sum(p), 0.0)))
p[p<=threshold] <- 0
p[p>threshold] <- 1
if (any(p>0)) p <- p/sum(p)
return(p)
}
# wrapper: all statistics
allStats <- function(x, y, threshold=c(0,0)) {
c(sqDiff = sqDiff(x, y),
sqDiff_fix = sqDiff(x, y, fix=T),
sqDiff_eq = sqDiff(eq(x,threshold=threshold[1]),eq(y,threshold=threshold[2])),
sqDiff_eq_fix = sqDiff(eq(x,threshold=threshold[1]),eq(y,threshold=threshold[2]),fix=T),
JS = sqrt(jensen_shannon(x, y)),
JS_fix = sqrt(jensen_shannon(x, y, fix=T)),
JS_eq = sqrt(jensen_shannon(eq(x,threshold=threshold[1]),eq(y,threshold=threshold[2]))),
JS_eq_fix = sqrt(jensen_shannon(eq(x,threshold=threshold[1]),eq(y,threshold=threshold[2]),fix=T)),
He = hellinger_distance(x, y),
He_fix = hellinger_distance(x, y, fix=T),
He_eq = hellinger_distance(eq(x,threshold=threshold[1]),eq(y,threshold=threshold[2])),
He_eq_fix = hellinger_distance(eq(x,threshold=threshold[1]),eq(y,threshold=threshold[2]),fix=T),
rank_corr = spearman_corr(x, y)[["rho"]],
rank_corr_p = spearman_corr(x, y)[["pval"]])
}
# compare matrices
compareMatrices <- function(A, B, rowWeights=NULL, threshold=c(0,0)) {
# output NAs in certain situations (see conditions below)
statsNA <- allStats(NA,NA)
# return NAs if at least one input is not a matrix
if(!is.matrix(A) | !is.matrix(B)) {
if (is.matrix(A)) X <- A
if (is.matrix(B)) X <- B
out <- as.data.frame(matrix(NA,nrow=nrow(X)+1,ncol=length(statsNA)))
colnames(out) <- names(statsNA)
rownames(out) <- c(rownames(X),"any")
} else {
# check matrix dimensions and row/column names match
if (ncol(A) != ncol(B) | nrow(A) != nrow(B)) {
stop("matrix dimensions must agree")
}
if (any(colnames(A) != colnames(B)) | any(rownames(A) != rownames(B))) {
stop("matrix row and column names must agree")
}
# if there was no input for rowWeights, make them uniform
if (!length(rowWeights)) rowWeights <- rep(1,nrow(A))
if (length(rowWeights) != nrow(A)) {
stop("length of weights vector and number of matrix rows differ")
}
# null matrix (for non-trivial element access)
N <- nullMatrix(A)$raw
# row-wise stats
rowStats <- lapply(1:nrow(A),
function(row) {
p <- A[row,N[row,]==1]
q <- B[row,N[row,]==1]
return(allStats(p,q,
threshold=threshold))
})
rowStats <- matrix(unlist(rowStats),nrow=length(rowStats),byrow=T)
colnames(rowStats) <- names(statsNA)
rownames(rowStats) <- rownames(A)
# identify trivial rows (all zeros in A and B, or only one non-trivial element)
trivialRows <- (!rowSums(A) & !rowSums(B)) | rowSums(N)==1
# adjust weights
rowWeights[trivialRows] <- 0
rowWeights <- rowWeights/sum(rowWeights)
rowWeights <- do.call(cbind,replicate(ncol(rowStats),rowWeights,simplify=F))
# get full matrix stats (average)
matrixStats <- colSums(rowStats[!trivialRows,]*rowWeights[!trivialRows,])
# final output
out <- as.data.frame(rbind(rowStats,any=matrixStats))
}
names(out) <- c("sqDiff","sqDiff_fix","sqDiff_eq","sqDiff_eq_fix",
"js","js_fix","js_eq","js_eq_fix",
"hellinger","hellinger_fix","hellinger_eq","hellinger_eq_fix",
"spearman","spearman_pval")
return(out)
}
# simplified compareMatrices
easyCompare <- function(A,B,numGenes,fixNulls=F) {
# return NAs if at least one input is not a matrix
if(!is.matrix(A) | !is.matrix(B)) {
g <- makeGenotypes(numGenes)[[1]]$genotypeNames
out <- rep("err_no_matrix",length(g))
names(out) <- g
} else {
# null matrix (for non-trivial element access)
N <- nullMatrix(A)$raw
# row-wise JS
out <- sapply(1:nrow(A),
function(row) {
p <- A[row,N[row,]==1]
q <- B[row,N[row,]==1]
return(easyJS(p,q,fixNulls))
})
names(out) <- rownames(A)
}
return(out)
}
## x: oncoSimulIndiv output -> table of most abundant genotype at each
## sampling time.
## correct_length: if TRUE, all individuals contribute the same to
## the estimates (i.e., individuals with longer runs do not contribute
## more)
## called from trueFreqs, below.
maxg_freqs2 <- function(x, correct_length) {
## Yes, loop much faster here
tmp <- x$pops.by.time[, -1]
r <- nrow(tmp)
out <- rep(-9, r)
for(i in seq(r)) out[i] <- which.max(tmp[i, ])
tt <- table(x$GenotypesLabels[out])
if(correct_length) tt <- tt/sum(tt)
data.frame(v1 = names(tt),
v2 = c(tt),
row.names = NULL,
fix.empty.names = FALSE,
check.names = FALSE,
stringsAsFactors = FALSE)
}
## x: a simulation output object, simobj -> frequencies of most abundant
## genotypes
## if correct_length = TRUE, all individuals contribute the same
## to the estimates (i.e., individuals with longer runs do not contribute
## more)
true_Freqs <- function(x, correct_length = TRUE) {
cat("\n starting true_Freqs")
lex <- length(x)
stopifnot(lex <= 20000)
if(lex > 20000) warning("\n More than 20000 \n")
## FIXME: if we get failures or warnings:
## pass filename (i.e., file)
## and return it under each condition
## simpler and faster than tryCatch
t22 <- Sys.time()
## all_maxg_freqs <- lapply(x, maxg_freqs2, correct_length)
all_maxg_freqs <- mclapply(x, maxg_freqs2,
correct_length, mc.cores = detectCores())
cat("\n done maxg_freqs2; took ", Sys.time() - t22, "\n")
## all_maxg_freqs <- mlp(x)
all_maxg_freqs_C <- dplyr::bind_rows(all_maxg_freqs)
## dplgb <- dplyr::group_by(all_maxg_freqs_C, v1)
## true_freqs <- as.data.frame(dplyr::summarize(dplgb, Freq = sum(v2)))
## colnames(true_freqs)[1] <- "Genotype"
true_freqs <- aggregate( v2 ~ v1, data = all_maxg_freqs_C, FUN = sum)
colnames(true_freqs) <- c("Genotype", "TrueFreq")
true_freqs$TrueProp <- true_freqs$TrueFreq/sum(true_freqs$TrueFreq)
true_freqs
}
## true frequencies, but you pass a file and also get
## all the info: ID.
true_Freqs_full <- function(x, correct_length = TRUE) {
if(exists("simo")) stop("A simo here!")
## try(rm(simo), silent = TRUE)
cat("\n Doing simul file ", x, "...")
cat(" ... loading file;")
t1 <- Sys.time()
simo <- loadRData(x)
t2 <- Sys.time()
cat("loaded; took", t2 - t1, "\n")
ID <- strsplit(strsplit(x, "simobj_ID_")[[1]][2],
"_ng_")[[1]][1]
## stopifnot(nchar(ID) == 16)
gg <- true_Freqs(simo)
rm(simo)
whichwt <- (gg$Genotype == "")
stopifnot(sum(whichwt) == 1)
gg$Genotype[whichwt] <- "WT"
return(
cbind(ID = ID,
gg,
stringsAsFactors = FALSE, row.names = NULL)
)
}
## Possibly faster versions of the above?
## load inside the inner function, so do not pass big things
## and parallelize inside
## x: a simulation output object, simobj -> frequencies of most abundant
## genotypes
## if correct_length = TRUE, all individuals contribute the same
## to the estimates (i.e., individuals with longer runs do not contribute
## more)
true_Freqs_2 <- function(file, correct_length = TRUE) {
if(exists("simo")) stop("A simo here!")
## try(rm(simo), silent = TRUE)
cat(" ... loading file;")
t1 <- Sys.time()
simo <- loadRData(file)
t2 <- Sys.time()
cat("loaded; took", t2 - t1, "\n")
lex <- length(simo)
stopifnot(lex <= 20000)
if(lex > 20000) warning("\n More than 20000 \n")
## FIXME: if we get failures or warnings:
## pass filename (i.e., file)
## and return it under each condition
## simpler and faster than tryCatch
## mclapply, called from another mclapply, blows up ram
all_maxg_freqs <- lapply(simo, maxg_freqs2, correct_length)
## all_maxg_freqs <- mclapply(simo, maxg_freqs2,
## correct_length, mc.cores = detectCores())
cat("\n done maxg_freqs2; took ", Sys.time() - t2, "\n")
rm(simo)
## all_maxg_freqs <- mlp(x)
all_maxg_freqs_C <- dplyr::bind_rows(all_maxg_freqs)
## dplgb <- dplyr::group_by(all_maxg_freqs_C, v1)
## true_freqs <- as.data.frame(dplyr::summarize(dplgb, Freq = sum(v2)))
## colnames(true_freqs)[1] <- "Genotype"
true_freqs <- aggregate( v2 ~ v1, data = all_maxg_freqs_C, FUN = sum)
colnames(true_freqs) <- c("Genotype", "TrueFreq")
true_freqs$TrueProp <- true_freqs$TrueFreq/sum(true_freqs$TrueFreq)
true_freqs
}
## true frequencies, but you pass a file, and also get
## all the info: ID.
true_Freqs_full_2 <- function(x, correct_length = TRUE) {
cat("\n Doing simul file ", x, "...")
ID <- strsplit(strsplit(x, "simobj_ID_")[[1]][2],
"_ng_")[[1]][1]
## stopifnot(nchar(ID) == 16)
gg <- true_Freqs_2(file = x)
cat(" ; done true_Freqs_2\n")
whichwt <- (gg$Genotype == "")
stopifnot(sum(whichwt) == 1)
gg$Genotype[whichwt] <- "WT"
return(
cbind(ID = ID,
gg,
stringsAsFactors = FALSE, row.names = NULL)
)
}
## file of all_paths* and vector of ANALYZED_ files -> file from ANALYZED_
## with matching sampling scheme, but always sample size of 4000
get_4000_file <- function(file, filesANALYZED) {
ID <- strsplit(strsplit(file, "_ID_")[[1]][2], "__rnst_")[[1]][1]
idf <- grep(paste0("ANALYZED__ID_", ID,
"_rnst_"),
filesANALYZED, value = TRUE)
idf4000 <- grep("_size_split_4000\\.rds", idf, value = TRUE)
if(grepl("__detect_large\\.rds", file)) {
idf4000_s <- grep("_beta_A_5_beta_B_3_size_split_", idf4000, value = TRUE)
} else if(grepl("__detect_small\\.rds", file)) {
idf4000_s <- grep("_beta_A_3_beta_B_5_size_split_", idf4000, value = TRUE)
} else if(grepl("__detect_unif\\.rds", file)) {
idf4000_s <- grep("_beta_A_1_beta_B_1_size_split_", idf4000, value = TRUE)
}
stopifnot(length(idf4000_s) == 1)
return(idf4000_s)
}
## ANALYZED file -> genotype frequencies from 20000 samples
freqs_from_sampling <- function(file) {
x <- readRDS(file)
aid <- do.call(rbind, lapply(x$allM, function(x) x$input_data))
## Get genotypes
sampledGenot <- OncoSimulR::sampledGenotypes(aid)
colnames(sampledGenot) <- c("Genotype", "SampledFreq")
sampledGenot$SampledProp <-
sampledGenot$SampledFreq/sum(sampledGenot$SampledFreq)
sampledGenot
}
## ANALYZED file -> genotype frequencies from 20000 samples and full info ID,
## sampling, etc
freqs_from_sampling_full <- function(file) {
## cat("\n Doing sampling file ", file, "\n")
x <- readRDS(file)
stopifnot(x$size_split == 4000)
aid <- do.call(rbind, lapply(x$allM, function(x) x$input_data))
stopifnot(nrow(aid) == 20000)
## Get genotypes
sampledGenot <- OncoSimulR::sampledGenotypes(aid)
## rm the sampledGenotypes class
class(sampledGenot) <- "data.frame"
colnames(sampledGenot) <- c("Genotype", "SampledFreq")
sampledGenot$SampledProp <-
sampledGenot$SampledFreq/sum(sampledGenot$SampledFreq)
## sampledGenot
## Only ID and detect are needed for matching. The rest are for
## paranoid checks. Since files are huge, removed.
return(
cbind(ID = x$ID,
detect = x$detect,
## rnst = x$rnst,
## ngenes = x$ngenes,
## initSize = x$initSize,
sampledGenot,
stringsAsFactors = FALSE, row.names = NULL))
}
## Wrapper to OncoSimulR::sampledGenotypes
## with a check
obs_freq_dataset <- function(datat, size_split, replicate_num) {
stopifnot(nrow(datat) == size_split)
sG <- OncoSimulR::sampledGenotypes(datat)
## rm the sampledGenotypes class
class(sG) <- "data.frame"
colnames(sG) <- c("Genotype", "ObservedFreq")
sumF <- sum(sG$ObservedFreq)
stopifnot(sumF == size_split)
sG$ObservedProp <-
sG$ObservedFreq/sumF
return(cbind(replicate = replicate_num,
sG,
stringsAsFactors = FALSE, row.names = NULL))
}
## ANALYZED file -> genotype frequencies from samples and full info ID,
## sampling, etc
obs_freqs_in_sample <- function(file) {
## cat("\n Doing sampling file ", file, "\n")
x <- readRDS(file)
size_split <- x$size_split
## Don't : waiting, and too many processes'
## of <- mclapply(1:length(x$allM),
## function(i) fsg(x$allM[[i]]$input_data,
## size_split,
## i),
## mc.cores = detectCores()
## )
stopifnot(length(x$allM) == 5)
of <- lapply(1:length(x$allM),
function(i) obs_freq_dataset(x$allM[[i]]$input_data,
size_split,
i)
)
ofu <- dplyr::bind_rows(of)
## Only ID and detect are needed for matching. The rest are for
## paranoid checks. Since files are huge, removed.
return(
cbind(ID = x$ID,
detect = x$detect,
size_split = size_split,
## rnst = x$rnst,
## ngenes = x$ngenes,
## initSize = x$initSize,
ofu,
stringsAsFactors = FALSE, row.names = NULL))
}
## fitness landscape file -> rank of genotypes (two columns, second
## with non-viable genots set to NA)
fitness_rank_genotypes <- function(file) {
x <- readRDS(file)
ID <- x$landscape
ngenes <- ncol(x$fitness_landscape) - 1
stopifnot(ngenes %in% c(7, 10) )
stopifnot(x$fitness_landscape[, "Fitness"] > 0)
geneNames <- LETTERS[1:ngenes]
genots <- apply(x$fitness_landscape[, -(ngenes + 1)],
1,
function(u)
paste(sort(geneNames[as.logical(u)]), collapse = ", ")
)
genots[genots == ""] <- "WT"
whichwt <- which(genots == "WT")
stopifnot(x$fitness_landscape[whichwt, "Fitness"] == 1)
## largest fitness gets 1st rank
fitnessRank <- rank( -(x$fitness_landscape[, "Fitness"]) )
fitnessRank2 <- fitnessRank
fitnessRank2[x$fitness_landscape[, "Fitness"] <= 1e-9] <- NA
## marank <- max(fitnessRank)
mirank <- min(fitnessRank)
wtr <- fitnessRank[whichwt]
stopifnot(wtr > mirank)