-
Notifications
You must be signed in to change notification settings - Fork 0
/
average-and-array-statistics.R
1536 lines (1181 loc) · 53.7 KB
/
average-and-array-statistics.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
## Compute the statistics averaged over genotypes
## weighting by POM frequency
## Beware: need to deal with NAs. A lot of boring stuff related to it
## below.
date()
rm(list = ls())
library(data.table)
library(dplyr)
## slow!
system.time(df <- readRDS("table-replicates.rds"))
## Simpler for now
data <- df$data
## We take averages, etc, and it is much simpler to average over the relevant
## columns of the relevant variables, but the constant ID-level or sample-level
## variables take that info from fl_sampl.
## So we will be merging info. Load here the file and
## rename variables. Leave ID and Detection as those
## are not output later
flDirectory <- "/home/jdc/next-genotype/fitland"
load(file.path(flDirectory, "fl_sampl.RData"))
fl_sampl$Detection[fl_sampl$Detection=="unif"] <- "uniform"
## Redundant
stopifnot(with(fl_sampl, all(Sampling == Detection)))
fl_sampl <- fl_sampl[, !(names(fl_sampl) %in% c("Sampling"))]
fl_sampl <- dplyr::rename(fl_sampl,
"numMuts_mean" = "Mean_muts",
"numMuts_median" = "Median_muts",
"numMuts_var" = "Var_muts",
"numMuts_stDev" = "Stdev_muts",
"numMuts_kurtosis" = "Kurtosis_muts",
"numMuts_skewness" = "Skewness_muts",
"initSize" = "Init_Size",
"mutationRate" = "Mutation",
"numGenes" = "Ngenes",
"numLocalPeaks" = "num_local_peaks",
"numObservedPeaks" = "num_observed_peaks",
"numAccessibleGenotypes" = "num_accessible_genots",
"diversityObservedPeaks" = "diversity_observed_peaks",
"epistMagn" = "epist_magn",
"epistSign" = "epist_sign",
"epistRSign" = "epist_rsign",
"w1" = "w.1.",
"w2" = "w.2.",
"w3" = "w.3..",
"typeLandscape" = "type_Landscape"
)
#### Explanation of each column
## Common to a lot of code below
columnsExplained <- list(
note = list(note = "Not all columns need to be present, depending on what was averaged over"),
identification=list(
id="Data identifier",
replicate = "Replicate number"
),
cpm_and_input=list(
method="Method used for next genotype prediction",
size_split="Sample size: size of the input matrix given to the method"
),
statistics=list(
js_w_real = "Weighted average JS distance, genotype weights proportional to true frequency during simulations",
js_w_sampl = "Weighted average JS distance, genotype weights proportional to frequency during simulations on sampling regime used",
sqDiff="Square root of average of squared differences",
sqDiff_eq="Square root of average of squared differences (equiprobabilized)",
js="Jensen-Shannon distance (square root of the Jensen-Shannon divergence), in log base 2 units",
js_eq="Jensen-Shannon distance (equiprobabilized)",
hellinger="Hellinger distance",
hellinger_eq="Hellinger distance (equiprobabilized)",
spearman="Spearman's rank correlation value",
spearman_pval="P-value of the rank correlation"
),
flags=list(
flags="Warnings shown when unfusing or rearranging genotype names"
),
properties_of_source_genotype=list(
sourceGenotype="Name of the source genotype (if set to 'any', the statistical parameters correspond to the averages across all source genotypes, weighted by their frequency in the POM)",
sourceGenotype_nMut="Number of mutations of the source genotype",
sourceGenotype_freqInPOM="Frequency of appearance of the source genotype in the POM",
sourceGenotype_accessible="Fraction of the replicates in which the source genotype was accessible according to the method",
sampledFreq = "Frequency of genotype in the 20000 samples corresponding to the actual detection regime used (so over a simulation*detection, all genotypes add to 20000).",
sampledProp = "Proportion of genotype in the 20000 samples corresponding to the actual detection regime used (so over a simulation*detection, all genotypes add to 1).",
trueFreq = "Frecuency of genotype as the most common genotype during the simulations, computed over all the regularly spaced full population samples of each simulation (i.e., from the pops.by.time object); scaled to give equal weight to all 20000 simulations, these add up to 20000 for every simulation. These numbers are the same for all detection regimes.",
trueProp = "Like trueFreq, but proportion; these add up to 1 for every simulation.",
fitnessRank = "The rank of genotypes' fitness (where 1 is largest fitness).",
fitnessRankNoZero = "The rank of genotypes' fitness (where 1 is largest fitness), but NA for non-viable genotypes (fitness <= 1e-9).",
observedFreq = "Observed frequency of the genotype in the specific sample from which the CPM was built.",
observedProp = "Observed proportion of the genotype in the specific sample from which the CPM was built (so sums to 1 in the replicate).",
freqLocalMax = "Frequency with which the genotype is a local maximum (end of LOD)",
propLocalMax = "Proportion of times the genotype is a local maximum (end of LOD); sums to 1 over the landscape"
),
sampling=list(
detect="Detection regime: when tumors are sampled (large, small, uniform)",
sampledGenotypesDiversity="Diversity of sampled genotypes",
sampledGenotypesNumber="Number of unique genotypes in the sample",
sampledGenotypesGenesAbove_0.01="Number of unique genotypes with a frequency above 0.01 present in the sample",
sampledGenotypesGenesAbove_0.1="Number of unique genotypes with a frequency above 0.1 present in the sample",
numMuts_mean="Average number of mutations in the sample",
numMuts_median="Median number of mutations in the sample",
numMuts_var="Variance of the number of mutations in the sample",
numMuts_stDev="Standard deviation of the number of mutations in the sample",
numMuts_kurtosis="Kurtosis of the distribution of the number of mutations in the sample",
numMuts_skewness="Skewness of the distribution of the number of mutations in the sample",
pom_h="POM diversity",
lod_h="LOD diversity",
freq_most_freq_mean_no450="Frequency of the most frequent genotype in the sample",
how_many_gt_5p_mean_no450="How many genotypes have a frequency > 5% in the sample"
),
simulation_and_evolutionary_process=list(
numAccessibleGenotypes="Number of accesible genotypes in the fitness landscape",
initSize="Initial number of wild-type cells in the simulation",
mutationRate="Mutation rate regime"
),
fitness_landscape=list(
rnst="Fitness landscape identifier (redundant check: one-to-one between id and rnst)",
numGenes="Number of driver genes (7 or 10)",
## Ngenes = "Number of driver genes (7 or 10)", ## redundant
typeLandscape="Type of fitness landscape",
## type_Landscape="Type of fitness landscape",
numLocalPeaks="Number of local peaks (maxima) in the fitness landscape under the no-back mutation assumption",
numObservedPeaks="Number of local peaks in the landscape that are actually visited in the evolutionary simulations",
diversityObservedPeaks = "Diversity of observed local peaks"
),
epistasis=list(
epistMagn="Fraction of pairs of loci with magnitude epistasis in the landscape",
epistSign="Fraction of pairs of loci with sign epistasis",
epistRSign="Fraction of pairs of loci with reciprocal sign epistasis",
w1="Fourier expansion of the landscape: fraction of coefficients of order 1",
w2="Fourier expansion of the landscape: fraction of coefficients of order 2",
w3="Fourier expansion of the landscape: fraction of coefficients of order 3 or higher",
gamma="Correlation in fitness effects between genotypes that differ by one locus (Ferretti et al., 2016)"
)
)
## This helps to verify the column names
allv <- sort(unname(unlist(lapply(columnsExplained, function(x) names(x)))))
###############################################
#####
##### Prechecks of NAs and nrows
#####
###############################################
data_any <- dplyr::filter(data, sourceGenotype == "any")
data_any_null <- dplyr::filter(data_any, method == "null")
data_any_no_null <- dplyr::filter(data_any, method != "null")
data_no_any <- dplyr::filter(data, sourceGenotype != "any")
nrow(data_no_any)
##### Check number of replicates with valid data
nrow(data_any)
stopifnot(nrow(data_any) == (1260 * 9 * 5 * (length(unique(data$method)) - 1)+ 1260 * 3))
## There should be no NAs in the null model, ever
summary(data_any_null$js)
stopifnot(!any(is.na(data_any_null$js)))
## There should be NAs in the non-null. Those with CPM crashes
summary(data_any_no_null$js) ## some NAs
stopifnot(any(is.na(data_any_no_null$js)))
## Verify those are all NAs
which_crash_any <- grep("ERROR_CPM_ANALYSIS", data_any$flags)
stopifnot(all(is.na(data_any[which_crash_any, "js"])))
## But there are NAs in some of those without CPM crashes
stopifnot(any(is.na(data_any[-which_crash_any, "js"])))
which(is.na(data_any[-which_crash_any, "js"]))
## and 6 cases total
sum(is.na(data_any[-which_crash_any, "js"]))
## Check one example
dplyr::filter(data, (id == "Dv8B7RHWDguRzH1W") &
(size_split == 50) &
(detect == "large") &
(replicate == 1) &
(method == "OT")
)[, c(1, 4, 5, 6, 7, 8, 10, 14, 51, 52, 55, 56, 20)]
## js returned a NaN
## Do we have many NaNs?
sum(is.nan(data_no_any$js)) ## 6, as above
stopifnot(sum(is.nan(data_no_any$js)) == 6)
## over all, 12
sum(is.nan(data$js)) ## 12, as we add the 6 for genotypes to those for the corresponding array
stopifnot(sum(is.nan(data$js)) == 12)
## See them all. Of course, any is irrelevant
dplyr::filter(data, (is.nan(js)) &
(sourceGenotype != "any")
)[, c(1, 4, 5, 6, 7, 8, 10, 12, 14, 16, 18, 51, 52, 55, 56, 20)]
## the 12 is shown to compare
## and check
## Those NaNs are to be turned to 0s. See all gory details in why-the-NaN.R
## basically, a numerical issue in borderline cases (hey, 6 out of > 39 million)
## with KL divergence.
## Do!
data$js[is.nan(data$js)] <- 0
## Recreate and redo checks
data_any <- dplyr::filter(data, sourceGenotype == "any")
data_any_null <- dplyr::filter(data_any, method == "null")
data_any_no_null <- dplyr::filter(data_any, method != "null")
data_no_any <- dplyr::filter(data, sourceGenotype != "any")
nrow(data_no_any)
##### Check number of replicates with valid data
nrow(data_any)
stopifnot(nrow(data_any) == (1260 * 9 * 5 * (length(unique(data$method)) - 1)+ 1260 * 3))
## There should be no NAs in the null model, ever
summary(data_any_null$js)
stopifnot(!any(is.na(data_any_null$js)))
## There should be NAs in the non-null. Those with CPM crashes
summary(data_any_no_null$js) ## some NAs
stopifnot(any(is.na(data_any_no_null$js)))
## Verify those are all NAs
which_crash_any <- grep("ERROR_CPM_ANALYSIS", data_any$flags)
stopifnot(all(is.na(data_any[which_crash_any, "js"])))
## Now, no NAs when no CPM crashes
stopifnot(!any(is.na(data_any[-which_crash_any, "js"])))
which(is.na(data_any[-which_crash_any, "js"]))
##################################################
######
###### Array-level averages of statistics
######
##################################################
unique_combs <- c("id", "replicate", "method", "size_split", "detect")
#### Verify no need to scale, as the props (true and sampled) sum to 1.
## tmp files to check scaling
tmp_true <-
dplyr::group_by_at(data_no_any[, c("trueProp", unique_combs)],
vars(one_of(unique_combs)))
tmp_sampled <-
dplyr::group_by_at(data_no_any[, c("sampledProp", unique_combs)],
vars(one_of(unique_combs)))
ds_true_nonarm <- dplyr::summarize(tmp_true,
sum = sum(.data[["trueProp"]],
na.rm = FALSE))
ds_true <- dplyr::summarize(tmp_true,
sum = sum(.data[["trueProp"]],
na.rm = TRUE))
ds_sampled_nonarm <- dplyr::summarize(tmp_sampled,
sum = sum(.data[["sampledProp"]],
na.rm = FALSE))
ds_sampled <- dplyr::summarize(tmp_sampled,
sum = sum(.data[["sampledProp"]],
na.rm = TRUE))
## There are NAs here
summary(ds_true_nonarm[, "sum"])
## No NAs
summary(ds_true[, "sum"])
## Both add up to one
stopifnot(isTRUE(all.equal(ds_sampled$sum, rep(1, nrow(ds_sampled)))))
stopifnot(isTRUE(all.equal(ds_true$sum, rep(1, nrow(ds_true)))))
### </Verify no need to scale
####### Matrix-level
### Logic
### Subset and keep only
### Multiply by weights the statistic, then sum
### Then, merge the data with fl_statistics
## Yes, keep sourceGenotype initially, before merging, so we can
## check if needed
matsum <- data_no_any[, c(unique_combs, "sourceGenotype",
"trueProp", "sampledProp", "js")]
matsum$js_real <- with(matsum, js * trueProp)
matsum$js_samp <- with(matsum, js * sampledProp)
matsum2 <- dplyr::group_by_at(matsum,
vars(one_of(unique_combs)))
## None of these are good ideas. See below when we explain mysum
## matsum3 <- dplyr::summarize(matsum2,
## js_w_real = sum(.data[["js_real"]],
## na.rm = TRUE),
## js_w_sampl = sum(.data[["js_samp"]],
## na.rm = TRUE)
## )
## matsum4 <- dplyr::summarize(matsum2,
## js_w_real = sum(.data[["js_real"]],
## na.rm = FALSE),
## js_w_sampl = sum(.data[["js_samp"]],
## na.rm = FALSE)
## )
## See below for the reason of mysum
mysum <- function(x) if (all(is.na(x))) NA else sum(x, na.rm=TRUE)
matsum5 <- dplyr::summarize(matsum2,
js_w_real = mysum(.data[["js_real"]]),
js_w_sampl = mysum(.data[["js_samp"]])
)
matsum5b <- dplyr::summarize(matsum2,
js_w_real = mysum(js_real),
js_w_sampl = mysum(js_samp)
)
stopifnot(identical(matsum5, matsum5b))
rm(matsum5b)
#### What about NAs?
## Recall: NAs can arise from NAs in weights or NAs in js
### NAs in js
## Remember many js as NA...
which_na_js <- which(is.na(data_no_any$js))
## ... but all when ERROR_CPM_ANALYSIS
error_cpm <- grep("ERROR_CPM_ANALYSIS", data_no_any$flag, fixed = TRUE)
stopifnot(!any(is.na(data_no_any[-error_cpm, "js"])))
## An example
data_no_any[error_cpm[1:3], c(1, 4, 5, 6, 7, 8, 10, 14, 51, 52, 55, 56, 20)]
### NAs in weights:
nas_weight_true <- which(is.na(data_no_any$trueProp))
## Yes, a bunch
head(data_no_any[nas_weight_true, c(1, 4, 5, 6, 7, 8, 10, 14, 51, 52, 55, 56)])
nrow(data_no_any[nas_weight_true, c(1, 4, 5, 6, 7, 8, 10, 14, 51, 52, 55, 56)])
## For example, genotype D,I: it appears once in POM but not in the true genotypes
dplyr::filter(data_no_any, (id == "10aJ10EAqKH7VA3ccp") &
(method == "CAPRESE") &
(size_split == 50) &
(detect == "large") &
(replicate == 1)
)[, c(1, 4, 5, 6, 7, 8, 10, 14, 51, 52, 55, 56)]
## This was documented in merge-additional-info.R
tmp_true_Prop_na <-
data_no_any[nas_weight_true, c(1, 4, 5, 6, 7, 8, 10, 14, 51, 52, 55, 56)]
tmp_id_genot_prop_na <-
paste0(tmp_true_Prop_na$id,"_", tmp_true_Prop_na$sourceGenotype)
length(unique(tmp_id_genot_prop_na)) ## 97 different instances
## out of the
length(
unique(paste0(data_no_any[data_no_any$method != "null", "id"],
"_",
data_no_any[data_no_any$method != "null", "sourceGenotype"])))
## 66864
## With
max(tmp_true_Prop_na$sourceGenotype_freqInPOM) ## 0.00015
## so 3 cases out of the 20000 simulations as max
## Of course, this happens much more with sampled. Sure.
## We want to keep all level combinations, even if NA for all (e.g., those
## crashed) and for those with missing values in some genotypes (e.g., one
## of the props) the sum with those removed.
##
## Example of crash
## Definitely want the NAs here, and we want to keep the level combination
dplyr::filter(matsum5, (id == "10H8qiQAOoVrnY9T3") &
(method == "CAPRESE") &
(size_split == 50) &
(detect == "small") &
(replicate == 2)
)
## An example where a genotype did not have a value for trueProp
## We want an average over the non-NA rows
dplyr::filter(matsum5, (id == "10aJ10EAqKH7VA3ccp") &
(method == "CAPRESE") &
(size_split == 50) &
(detect == "large") &
(replicate == 1)
)
## Check. The two statistics 0 <= x <= 1
stopifnot(na.omit(matsum5$js_w_real) <= 1)
stopifnot(na.omit(matsum5$js_w_real) >= 0)
stopifnot(na.omit(matsum5$js_w_sampl) <= 1)
stopifnot(na.omit(matsum5$js_w_sampl) >= 0)
## Dimensions
stopifnot(
nrow(matsum5) == (1260 * 9 * 5 * (length(unique(data_no_any$method)) - 1)+ 1260 * 3)
)
stopifnot(nrow(matsum5[matsum5$method == "null",]) == 1260 * 3)
## Average over replicates
unique_combs_over_repl <- c("id", "method", "size_split", "detect")
## same as setdiff(unique_combs, "replicate")
matsum6 <- dplyr::group_by_at(matsum5,
vars(one_of(unique_combs_over_repl)))
array_statistics_over_replicate <-
dplyr::summarize(matsum6,
js_w_real = mean(.data[["js_w_real"]], na.rm = TRUE),
js_w_sampl = mean(.data[["js_w_sampl"]], na.rm = TRUE)
)
## Check specific cases and dimensions
stopifnot(nrow(array_statistics_over_replicate) ==
((1260 * 9 * (length(unique(matsum6$method)) - 1) ) + (1260 * 3)))
stopifnot(
nrow(
array_statistics_over_replicate[
array_statistics_over_replicate$method == "null", ]) ==
(1260 * 3))
## this crashed in one replicate
dplyr::filter(array_statistics_over_replicate, (id == "10H8qiQAOoVrnY9T3") &
(method == "CAPRESE") &
(size_split == 50) &
(detect == "small"))
## trueProp missing in one case
dplyr::filter(array_statistics_over_replicate, (id == "10aJ10EAqKH7VA3ccp") &
(method == "CAPRESE") &
(size_split == 50) &
(detect == "large"))
array_statistics <- dplyr::left_join(matsum5, fl_sampl,
by = c("id" = "ID", "detect" = "Detection"))
array_statistics_over_replicate <-
dplyr::left_join(array_statistics_over_replicate, fl_sampl,
by = c("id" = "ID", "detect" = "Detection"))
stopifnot(
nrow(array_statistics) ==
(1260 * 9 * 5 * (length(unique(data_no_any$method)) - 1)+ 1260 * 3)
)
stopifnot(nrow(array_statistics[array_statistics$method == "null",]) == 1260 * 3)
stopifnot(nrow(array_statistics_over_replicate) ==
((1260 * 9 * (length(unique(matsum6$method)) - 1) ) + (1260 * 3)))
stopifnot(
nrow(
array_statistics_over_replicate[
array_statistics_over_replicate$method == "null", ]) ==
(1260 * 3))
system.time(saveRDS(list(data = array_statistics,
columnsExplained = columnsExplained),
file = "array_statistics.rds",
compress = FALSE
))
system.time(saveRDS(list(data = array_statistics_over_replicate,
columnsExplained = columnsExplained),
file = "array_statistics_over_replicate.rds",
compress = FALSE
))
### Checking COLUMN NAMES array column names
setdiff(allv, sort(colnames(array_statistics)))
setdiff(allv, sort(colnames(array_statistics_over_replicate)))
setdiff(sort(colnames(array_statistics)), allv)
setdiff(sort(colnames(array_statistics_over_replicate)), allv)
##################################################
######
###### Full data for models, without null
######
##################################################
## Just for the the hell of it. Well, to really drive that
## data.table is much better for me.
system.time(
data_no_any_tibble <- as_tibble(data_no_any)
) ## 0.004
## note: not using setDT
system.time(
data_no_any_dt <- as.data.table(data_no_any)
) ## 8.97
system.time(
data_no_any_no_null_tibble <- dplyr::filter(data_no_any_tibble,
method != "null")
) ## 12.4
system.time(
data_no_any_no_null_dt <- data_no_any_dt[method != "null", ]
) ## 5.4
system.time(saveRDS(list(data = data_no_any_no_null_dt,
columnsExplained = columnsExplained),
file = "data_no_any_no_null.rds",
compress = FALSE
))
## Merge over replicates
data_no_any_no_null_merged <-
data_no_any_no_null_dt[,
.(js = mean(js, na.rm = TRUE),
sampledFreq = mean(sampledFreq, na.rm = TRUE),
sampledFreq_unique = length(unique(sampledFreq)),
sampledProp = mean(sampledProp, na.rm = TRUE),
sampledProp_unique = length(unique(sampledProp)),
trueFreq = mean(trueFreq, na.rm = TRUE),
trueFreq_unique = length(unique(trueFreq)),
trueProp = mean(trueProp, na.rm = TRUE),
trueProp_unique = length(unique(trueProp)),
observedFreq = mean(observedFreq, na.rm = TRUE),
observedFreq_unique = length(unique(observedFreq)),
observedProp = mean(observedProp, na.rm = TRUE),
observedProp_unique = length(unique(observedProp)),
fitnessRank = mean(fitnessRank, na.rm = TRUE),
fitnessRank_unique = length(unique(fitnessRank)),
fitnessRankNoZero = mean(fitnessRankNoZero, na.rm = TRUE),
fitnessRankNoZero_unique = length(unique(fitnessRankNoZero)),
freqLocalMax = mean(freqLocalMax, na.rm = TRUE),
freqLocalMax_unique = length(unique(freqLocalMax)),
propLocalMax = mean(propLocalMax, na.rm = TRUE),
propLocalMax_unique = length(unique(propLocalMax))
## , flags = paste(unique(flags))
## , flags_unique = length(unique(flags))
, sourceGenotype_accessible =
mean(sourceGenotype_accessible, na.rm = TRUE)
, sourceGenotype_accessible_unique =
length(unique(sourceGenotype_accessible))
),
by = list(id, sourceGenotype, method, size_split, detect,
## this is not a unique comb. but we want it in
## output
sourceGenotype_nMut)]
nrow(data_no_any_no_null_merged)
## checks
stopifnot(
all(data_no_any_no_null_merged$sampledFreq_unique ==1)
)
stopifnot(
all(data_no_any_no_null_merged$sampledProp_unique ==1)
)
stopifnot(
all(data_no_any_no_null_merged$trueFreq_unique ==1)
)
stopifnot(
all(data_no_any_no_null_merged$trueProp_unique ==1)
)
stopifnot(
!all(data_no_any_no_null_merged$observedFreq_unique ==1)
)
stopifnot(
!all(data_no_any_no_null_merged$observedProp_unique ==1)
)
stopifnot(
all(data_no_any_no_null_merged$fitnessRank_unique ==1)
)
stopifnot(
all(data_no_any_no_null_merged$fitnessRankNoZero_unique ==1)
)
stopifnot(
all(data_no_any_no_null_merged$freqLocalMax_unique ==1)
)
stopifnot(
all(data_no_any_no_null_merged$propLocalMax_unique ==1)
)
## Those columns are not fully useless. Any column with a non-1 value
## helps remember those are not constant over replicates
fl_sampl_dt <- as.data.table(fl_sampl)
data_no_any_no_null_over_replicate <- merge(
data_no_any_no_null_merged,
fl_sampl,
all.x = TRUE,
by.x = c("id", "detect"),
by.y = c("ID", "Detection")
)
nrow(data_no_any_no_null_merged)
nrow(data_no_any_no_null_dt)/nrow(data_no_any_no_null_merged)
system.time(saveRDS(list(data = data_no_any_no_null_over_replicate,
columnsExplained = columnsExplained),
file = "data_no_any_no_null_over_replicate.rds",
compress = FALSE
))
### Checking COLUMN NAMES full data column names
setdiff(allv, sort(colnames(data_no_any_no_null_dt)))
setdiff(allv, sort(colnames(data_no_any_no_null_over_replicate)))
setdiff(sort(colnames(data_no_any_no_null_dt)), allv)
setdiff(sort(colnames(data_no_any_no_null_over_replicate)), allv)
rm(data_no_any_dt)
rm(data_no_any_no_null_tibble)
rm(data_no_any_tibble)
rm(data_no_any_no_null_dt)
rm(data_no_any_no_null_merged)
rm(data_no_any_no_null_over_replicate)
gc()
##################################################
######
###### Full data for models
######
##################################################
## Just for the the hell of it. Well, to really drive that
## data.table is much better for me.
## Note: I want to preserve the null
## Sure, there are no replicates of the null
## so the merged is as good as the non-merged if we just want
## to use the null
## Yes, many steps from above repeated
system.time(
data_no_any_tibble <- as_tibble(data_no_any)
) ## 0.004
## Note: not using setDT
system.time(
data_no_any_dt <- as.data.table(data_no_any)
) ## 8.97
system.time(saveRDS(list(data = data_no_any_dt,
columnsExplained = columnsExplained),
file = "data_no_any.rds",
compress = FALSE
))
## Merge over replicates
data_no_any_merged <-
data_no_any_dt[,
.(js = mean(js, na.rm = TRUE),
sampledFreq = mean(sampledFreq, na.rm = TRUE),
sampledFreq_unique = length(unique(sampledFreq)),
sampledProp = mean(sampledProp, na.rm = TRUE),
sampledProp_unique = length(unique(sampledProp)),
trueFreq = mean(trueFreq, na.rm = TRUE),
trueFreq_unique = length(unique(trueFreq)),
trueProp = mean(trueProp, na.rm = TRUE),
trueProp_unique = length(unique(trueProp)),
observedFreq = mean(observedFreq, na.rm = TRUE),
observedFreq_unique = length(unique(observedFreq)),
observedProp = mean(observedProp, na.rm = TRUE),
observedProp_unique = length(unique(observedProp)),
fitnessRank = mean(fitnessRank, na.rm = TRUE),
fitnessRank_unique = length(unique(fitnessRank)),
fitnessRankNoZero = mean(fitnessRankNoZero, na.rm = TRUE),
fitnessRankNoZero_unique = length(unique(fitnessRankNoZero)),
freqLocalMax = mean(freqLocalMax, na.rm = TRUE),
freqLocalMax_unique = length(unique(freqLocalMax)),
propLocalMax = mean(propLocalMax, na.rm = TRUE),
propLocalMax_unique = length(unique(propLocalMax))
## , flags = paste(unique(flags))
## , flags_unique = length(unique(flags))
, sourceGenotype_accessible =
mean(sourceGenotype_accessible, na.rm = TRUE)
, sourceGenotype_accessible_unique =
length(unique(sourceGenotype_accessible))
),
by = list(id, sourceGenotype, method, size_split, detect,
sourceGenotype_nMut)]
nrow(data_no_any_merged)
## checks
stopifnot(
all(data_no_any_merged$sampledFreq_unique ==1)
)
stopifnot(
all(data_no_any_merged$sampledProp_unique ==1)
)
stopifnot(
all(data_no_any_merged$trueFreq_unique ==1)
)
stopifnot(
all(data_no_any_merged$trueProp_unique ==1)
)
stopifnot(
!all(data_no_any_merged$observedFreq_unique ==1)
)
stopifnot(
!all(data_no_any_merged$observedProp_unique ==1)
)
stopifnot(
all(data_no_any_merged$fitnessRank_unique ==1)
)
stopifnot(
all(data_no_any_merged$fitnessRankNoZero_unique ==1)
)
stopifnot(
all(data_no_any_merged$freqLocalMax_unique ==1)
)
stopifnot(
all(data_no_any_merged$propLocalMax_unique ==1)
)
## Those columns are not fully useless. Any column with a non-1 value
## helps remember those are not constant over replicates
fl_sampl_dt <- as.data.table(fl_sampl)
data_no_any_over_replicate <- merge(
data_no_any_merged,
fl_sampl,
all.x = TRUE,
by.x = c("id", "detect"),
by.y = c("ID", "Detection")
)
nrow(data_no_any_merged)
nrow(data_no_any_over_replicate)
nrow(data_no_any_dt)/nrow(data_no_any_over_replicate)
system.time(saveRDS(list(data = data_no_any_over_replicate,
columnsExplained = columnsExplained),
file = "data_no_any_over_replicate.rds",
compress = FALSE
))
### Checking COLUMN NAMES full data column names
setdiff(allv, sort(colnames(data_no_any_dt)))
setdiff(allv, sort(colnames(data_no_any_over_replicate)))
setdiff(sort(colnames(data_no_any_dt)), allv)
setdiff(sort(colnames(data_no_any_over_replicate)), allv)
rm(data_no_any_dt)
rm(data_no_any_tibble)
rm(data_no_any_merged)
gc()
##################################################
######
###### Number of mutations averages of statistics
######
##################################################
unique_combs_muts <- c("id", "replicate", "sourceGenotype_nMut",
"method", "size_split", "detect")
unique_combs_muts_over_repl <- c("id", "sourceGenotype_nMut",
"method", "size_split", "detect")
mutsum <- data_no_any[, c(unique_combs_muts,
"sourceGenotype",
"trueProp", "sampledProp", "js")]
## Do now use weighted.mean. See help: Missing values in ‘w’ are
## nothandled specially and so give a missing value as the result.
## See, e.g., https://stackoverflow.com/questions/40269022/weighted-average-in-r-using-na-weights
## See examples below
## my_weighted_mean <- function(x, w){
## df_omit <- na.omit(data.frame(x, w))
## weighted.mean(df_omit$x, df_omit$w)
## }
my_weighted_mean2 <- function(x, w){
df_omit <- na.omit(cbind(x, w))
weighted.mean(df_omit[, 1], df_omit[, 2])
}
## Use data table
dtmutsum <- as.data.table( data_no_any[, c(unique_combs_muts,
"sourceGenotype",
"trueProp", "sampledProp", "js")])
system.time(
setkeyv(dtmutsum, cols = unique_combs_muts)
) ## 1.7
system.time(
dtmutsum4 <- dtmutsum[ ,
.(js_w_real = my_weighted_mean2(js, trueProp),
js_w_sampl = my_weighted_mean2(js, sampledProp)),
by = unique_combs_muts]
) ## 174
stopifnot(nrow(dtmutsum4) <=
(1260 * 9 * 5 * (length(unique(data$method)) - 1) * 0.5 * (8 + 11)
+ 1260 * 3 * 0.5 * (8 + 11)))
## Some rows are expected to be missing, as not all simulations have the
## genotype with all mutations. For example:
maxminmut <- dtmutsum[ ,
.(max_muts = max(sourceGenotype_nMut),
min_muts = min(sourceGenotype_nMut)),
by = "id"]
stopifnot(all(maxminmut$min_muts == 0))
stopifnot(all(maxminmut$max_muts <= 10))
## This is not just 7 or 10.
table(maxminmut$max_muts)
maxmut_full <- dtmutsum[ ,
.(max_muts = max(sourceGenotype_nMut)),
by = list(id, replicate, method, size_split, detect)]
## Why? Because not all intermediate levels present
nrow(dtmutsum4) < sum(1 + maxmut_full$max_muts)
## Check null for ease
Null_dtmutsum4 <- dtmutsum4[ method == "null", ]
Null_maxmut_full <- maxmut_full[ method == "null", ]
Null_dtmutsum <- dtmutsum[ method == "null", ]
stopifnot(nrow(Null_dtmutsum4) < sum(1 + Null_maxmut_full$max_muts))
table(Null_maxmut_full$max_muts)
## No monotonic decrease. Missing intermediate genotypes
table(Null_dtmutsum4$sourceGenotype_nMut)
missing_muts <- function(x) {
maxm <- max(x)
missing <- setdiff(1:maxm, unique(x))
if(length(missing)) {
return(paste(missing, collapse = ", "))
} else {
return("None")
}
}
Null_which_missing <- Null_dtmutsum[ ,
.(which_missing_mut = missing_muts(sourceGenotype_nMut)),
by = list(id, replicate)
]
## Yes, missing intermediate genotypes
table(Null_which_missing$which_missing_mut)
## For instance
Null_which_missing[which(Null_which_missing$which_missing_mut == "2, 6"), ]
dtmutsum[ (id == "utFV4f4ZwaTtF6F7") & (method == "null") ]
sum(dtmutsum[ (id == "utFV4f4ZwaTtF6F7") & (method == "null") & (detect == "large")]$trueProp)
## We are missing these many: total, minus None and add two for the two
## cases that miss two
sum(table(Null_which_missing$which_missing_mut)) - 1206 + 2 ## 56
sum(1 + Null_maxmut_full$max_muts) - nrow(Null_dtmutsum4) ## = 3 * 56
## the 3 * is because we had the three detect in the null but no sizes
## yes, yes, in the Null_which_missing, we do not look over detect, either.
stopifnot(sum(1 + Null_maxmut_full$max_muts) - nrow(Null_dtmutsum4) == (3 * 56))
## With the non null
No_null_dtmutsum4 <- dtmutsum4[ method != "null", ]
No_null_maxmut_full <- maxmut_full[ method != "null", ]
No_null_dtmutsum <- dtmutsum[ method != "null", ]
stopifnot(nrow(No_null_dtmutsum4) < sum(1 + No_null_maxmut_full$max_muts))
sum(1 + No_null_maxmut_full$max_muts) - nrow(No_null_dtmutsum4) ## 32760
table(No_null_maxmut_full$max_muts)
table(No_null_dtmutsum4$sourceGenotype_nMut)
table(No_null_dtmutsum4$sourceGenotype_nMut)/
table(Null_dtmutsum4$sourceGenotype_nMut)
## a constant of 195 = 3 * 5 * (length(unique(data$method)) - 1)
## where the 3 instead of 9 is because we have 3 detect and no sizes
stopifnot(all(
(table(No_null_dtmutsum4$sourceGenotype_nMut)/
table(Null_dtmutsum4$sourceGenotype_nMut)) == 195))
## Repeat missing combinations. Just a multipe of the null.
No_null_which_missing <- No_null_dtmutsum[ ,
.(which_missing_mut = missing_muts(sourceGenotype_nMut)),
by = list(id, replicate, method, size_split, detect)
]
table(No_null_which_missing$which_missing_mut)
table(No_null_which_missing$which_missing_mut)/table(Null_which_missing$which_missing_mut)
## 585
## these are the combinations for each ID
9 * 5 * (length(unique(data$method)) - 1) ## 585
stopifnot(
all(
(table(No_null_which_missing$which_missing_mut)/
table(Null_which_missing$which_missing_mut)) == 585)
)
## Missing these many total
sum(table(No_null_which_missing$which_missing_mut)) - 705510 + 2 * 585
## 32760
sum(1 + No_null_maxmut_full$max_muts) - nrow(No_null_dtmutsum4)
## 32760
stopifnot(
(sum(table(No_null_which_missing$which_missing_mut)) - 705510 + 2 * 585) ==
(sum(1 + No_null_maxmut_full$max_muts) - nrow(No_null_dtmutsum4))
)
sum(1 + maxmut_full$max_muts) - nrow(dtmutsum4) ## 32928
32760 + 3 * 56 ## 32928
stopifnot(
(sum(1 + maxmut_full$max_muts) - nrow(dtmutsum4) ) ==
32760 + 3 * 56
)
## Average over replicates
system.time(