-
Notifications
You must be signed in to change notification settings - Fork 2
/
evaluateTimings_safetosource.R
2163 lines (1975 loc) · 143 KB
/
evaluateTimings_safetosource.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
## First do all the stuff in README.postprocessing.txt.
library( "parallel" ); # for mclapply
library( "glmnet" ); # for cv.glmnet
library( "glmnetUtils" ); # for formula interface (cv.glmnet.formula): see https://github.com/Hong-Revo/glmnetUtils
source( "readIdentifyFounders_safetosource.R" );
source( "getDaysSinceInfection_safetosource.R" );
source( "getArtificialBounds_safetosource.R" );
source( "getResultsByRegionAndTime_safetosource.R" );
source( "writeResultsTables_safetosource.R" );
source( "summarizeCovariatesOnePerParticipant_safetosource.R" );
## These should be set externally.
# GOLD.STANDARD.DIR <- "/fh/fast/edlefsen_p/bakeoff/gold_standard/";
#
# RESULTS.DIR <- "/fast/bakeoff_merged_analysis_sequences_filteredPre2017/results/";
# RESULTS.DIRNAME <- "raw_fixed";
#
# HELPFUL.ADDITIONAL.COLS.WITH.INTERACTIONS <- c(); #c( "v3_not_nflg", "X6m.not.1m" );
#
# ## Run it in all four configurations of INCLUDE.INTERCEPT and HELPFUL.ADDITIONAL.COLS to match what was done for the paper:
#
# #HELPFUL.ADDITIONAL.COLS <- c( "lPVL" );
# HELPFUL.ADDITIONAL.COLS <- c();
#
# INCLUDE.INTERCEPT <- FALSE;
# #INCLUDE.INTERCEPT <- TRUE;
THE.RESULTS.DIR <- RESULTS.DIR; # to avoid "promise already under evaluation" errors
########################################################
## Other fns
evaluateTimings.compute.config.string <- function (
include.intercept = INCLUDE.INTERCEPT,
include.all.vars.in.lasso = TRUE,
helpful.additional.cols = c( "lPVL" ),
helpful.additional.cols.with.interactions = c( "v3_not_nflg", "X6m.not.1m" ),
use.gold.is.multiple = FALSE,
mutation.rate.calibration = FALSE
) {
config.string <- "";
if( include.intercept ) {
config.string <- "include.intercept";
stopifnot( !mutation.rate.calibration );
} else if( mutation.rate.calibration ) {
config.string <- "mutation.rate.calibration";
}
if( length( helpful.additional.cols ) > 0 ) {
.new.config.string.part <-
paste( "covs.", paste( helpful.additional.cols, collapse = "." ), sep = "" );
if( config.string == "" ) {
config.string <- .new.config.string.part;
} else {
config.string <- paste( config.string, .new.config.string.part, sep = "_" );
}
}
if( length( helpful.additional.cols.with.interactions ) > 0 ) {
.new.config.string.part <-
paste( "interactingCovs.", paste( helpful.additional.cols.with.interactions, collapse = "." ), sep = "" );
if( config.string == "" ) {
config.string <- .new.config.string.part;
} else {
config.string <- paste( config.string, .new.config.string.part, sep = "_" );
}
}
if( !include.all.vars.in.lasso ) {
if( config.string == "" ) {
config.string <- "lassoFromNonlasso";
} else {
config.string <- paste( config.string, "lassoFromNonlasso", sep = "_" );
}
}
if( use.gold.is.multiple ) {
if( config.string == "" ) {
config.string <- "with.gold.is.multiple";
} else {
config.string <- paste( config.string, "with.gold.is.multiple", sep = "_" );
}
}
return( config.string );
} # evaluateTimings.compute.config.string (..)
########################################################
#' Evaluate timings estimates and produce results tables.
#'
#' This function runs the BakeOff results analysis for the timings results.
#'
#' The "center of bounds" (COB) approach is the way that we do it at the
#' VTN, and the way it was done in RV144, etc: use the midpoint
#' between the bounds on the actual infection time computed from the
#' dates and results of the HIV positivity tests (antibody or PCR).
#' The typical approach is to perform antibody testing every X days
#' (historically this is 6 months in most HIV vaccine trials, except
#' during the vaccination phase there are more frequent visits and on
#' every visit HIV testing is conducted). The (fake) bounds used here
#' are calculated in the createArtificialBoundsOnInfectionDate.R file.
#' The actual bounds would be too tight, since the participants were
#' detected HIV+ earlier in these people than what we expect to see in
#' a trial in which testing is conducted every X days. For the center
#' of bounds approach we load the bounds files in subdirs of the
#' "bounds" subdirectory eg at
#' /fh/fast/edlefsen_p/bakeoff/analysis_sequences/raw_edited_20160216/bounds/nflg/1m/.
#' This will also look for plasma viral load measurements in files
#' called
#' /fh/fast/edlefsen_p/bakeoff/gold_standard/caprisa_002/caprisa_002_viralloads.csv
#' and
#' /fh/fast/edlefsen_p/bakeoff/gold_standard/rv217/rv217_viralloads.csv. These
#' files have three important columns: ptid,viralload,timepoint. For
#' each ptid the viral loads at timepoints 1,2,3 correspond to the
#' gold-standard, 1m, and 6m time points. Viral loads are not logged
#' in the input file.
#'
#' These files have names beginning with "artificialBounds_" and
#' ending with ".tab".
#'
#' @param use.bounds compute results for the COB approach, and also return evaluations of bounded versions of the other results.
#' @param use.infer compute results for the PREAST approach.
#' @param use.anchre compute results for the anchre approach.
#' @param use.glm.validate evaluate predicted values from leave-one-out cross-validation, using a model with one predictor, maybe with helpful.additional.cols or with the bounds.
#' @param use.step.validate evaluate predicted values from leave-one-out cross-validation, using a model with one predictor and a step-selected subset of other predictors, maybe with the bounds.
#' @param use.lasso.validate evaluate predicted values from leave-one-out cross-validation, using a model with one predictor and a lasso-selected subset of other predictors, maybe with the bounds.
#' @param use.gold.is.multiple include gold.is.multiple and interactions between gold.is.multiple and helpful.additional.cols (but not with helpful.additional.cols.with.interactions).
#' @param include.intercept if TRUE, include an intercept term, and for time-pooled analyses also include a term to shift the intercept for 6m.not.1m samples. Note that this analysis is affected by the low variance in the true dates in the training data, which for 1m samples has SD around 5 and for 6m samples has an SD around 10, so even the "none" results do pretty well, and it is difficult to improve the estimators beyond this.
#' @param mutation.rate.calibration if TRUE, do not include anything that is not in interaction with (whatever the variable is), and no intercept (note this requires include.intercept == FALSE).
#' @param include.all.vars.in.lasso if FALSE, include only the "helpful.additional.cols" and "helpful.additional.cols.with.interactions" and the estimators and interactors among these vars that are tested via the non-lasso anaylsis (if use.glm.validate = TRUE). If include.all.vars.in.lasso = TRUE (the default), then as many additional covariates as possible will be included by parsing output from the identify-founders script (but note that apart from "lPVL" - log plasma viral load - these are mostly sequence statistics, eg. PFitter-computed maximum and mean Hamming distances among sequences.
#' @param helpful.additional.cols extra cols to be included in the glm and lasso: Note that interactions will be added only with members of the other set (helpful.additional.cols.with.interactions), not, with each other in this set.
#' @param helpful.additional.cols.with.interactions extra cols to be included in the glm both as-is and interacting with each other and with members of the helpful.additional.cols set.
#' @param results.dirname the subdirectory of RESULTS.DIR
#' @param force.recomputation if FALSE (default) and if there is a saved version called timings.results.by.region.and.time.Rda (under bakeoff_analysis_results/results.dirname), then that file will be loaded; otherwise the results will be recomputed and saved in that location.
#' @param partition.bootstrap.seed the random seed to use when bootstrapping samples by selecting one partition number per ptid, repeatedly; we do it this way because there are an unequal number of partitions, depending on sampling depth.
#' @param partition.bootstrap.samples the number of bootstrap replicates to conduct; the idea is to get an estimate of the variation in estimates and results (errors) across these samples.
#' @param partition.bootstrap.num.cores the number of cores to run the boostrap replicates on (defaults to all of the cores returned by parallel::detectCores()).
#' @return the filename of the Rda output. If you load( filename ), it will add "results.by.region.and.time" to your environment.
#' @export
evaluateTimings <- function (
use.bounds = TRUE,
use.infer = TRUE,
use.anchre = FALSE,
use.glm.validate = TRUE,
use.step.validate = FALSE,
use.lasso.validate = FALSE,
use.gold.is.multiple = FALSE,
include.intercept = INCLUDE.INTERCEPT,
mutation.rate.calibration = FALSE,
include.all.vars.in.lasso = TRUE,
helpful.additional.cols = HELPFUL.ADDITIONAL.COLS,
helpful.additional.cols.with.interactions = HELPFUL.ADDITIONAL.COLS.WITH.INTERACTIONS,
RESULTS.DIR = THE.RESULTS.DIR,
results.dirname = RESULTS.DIRNAME,
force.recomputation = TRUE,
partition.bootstrap.seed = 98103,
partition.bootstrap.samples = 100,
partition.bootstrap.num.cores = detectCores(),
regions = c( "nflg", "v3" ),
times = c( "1w", "1m", "6m" )
#regions = c( "nflg", "v3", "rv217_v3" ),
#times = c( "1m", "6m", "1m6m" )
)
{
## For debugging: start from .results.for.region in evaluate.specific.timings.model.formula from ~/src/from-git/hiv-founder-id/getFilteredResultsTables_safetosource.R
# use.bounds = TRUE; use.infer = TRUE; use.anchre = FALSE; use.glm.validate = TRUE; use.step.validate = FALSE; use.lasso.validate = FALSE; use.gold.is.multiple = FALSE; include.intercept = INCLUDE.INTERCEPT; mutation.rate.calibration = FALSE; include.all.vars.in.lasso = TRUE; helpful.additional.cols = HELPFUL.ADDITIONAL.COLS; helpful.additional.cols.with.interactions = HELPFUL.ADDITIONAL.COLS.WITH.INTERACTIONS; results.dirname = RESULTS.DIRNAME; force.recomputation = TRUE; partition.bootstrap.seed = 98103; partition.bootstrap.samples = 100; partition.bootstrap.num.cores = detectCores(); regions = c( "nflg", "v3" ); times = c( "1m", "6m" )
# results.per.person = .results.for.region[[ the.time ]][["results.per.person" ]]; days.since.infection = .results.for.region[[ the.time ]][["days.since.infection" ]]; results.covars.per.person.with.extra.cols = .results.for.region[[ the.time ]][["results.covars.per.person.with.extra.cols" ]]; the.artificial.bounds = .results.for.region[[ the.time ]][["bounds" ]]
# use.bounds = TRUE; use.infer = TRUE; use.anchre = FALSE; use.glm.validate = TRUE; use.step.validate = FALSE; use.lasso.validate = FALSE; results.dirname = "raw_edited_20160216"; force.recomputation = FALSE; partition.bootstrap.seed = 98103; partition.bootstrap.samples = 100; partition.bootstrap.num.cores = detectCores();
if( mutation.rate.calibration ) {
stopifnot( !( include.intercept ) );
}
config.string <- evaluateTimings.compute.config.string(
include.intercept = include.intercept,
include.all.vars.in.lasso = include.all.vars.in.lasso,
helpful.additional.cols = helpful.additional.cols,
helpful.additional.cols.with.interactions = helpful.additional.cols.with.interactions,
use.gold.is.multiple = use.gold.is.multiple,
mutation.rate.calibration = mutation.rate.calibration
);
results.by.region.and.time.Rda.filename <-
paste( RESULTS.DIR, results.dirname, "/Timings.results.by.region.and.time.", config.string, ".Rda", sep = "" );
if( config.string == "" ) {
evaluateTimings.tab.file.suffix <- "_evaluateTimings.tab";
} else {
evaluateTimings.tab.file.suffix <- paste( "_evaluateTimings_", config.string, ".tab", sep = "" );
}
MINIMUM.DF <- 2; # how much more should nrow( .lasso.mat ) be than ncol( .lasso.mat ) at minimum?
if( include.intercept ) {
MINIMUM.DF <- MINIMUM.DF + 1;
}
MINIMUM.CORRELATION.WITH.OUTCOME <- 0.1;
rv217.gold.standard.infection.dates.in <- read.csv( paste( GOLD.STANDARD.DIR, "rv217/rv217_gold_standard_timings.csv", sep = "" ) );
rv217.gold.standard.infection.dates <- as.Date( as.character( rv217.gold.standard.infection.dates.in[,2] ), "%m/%d/%y" );
names( rv217.gold.standard.infection.dates ) <- as.character( rv217.gold.standard.infection.dates.in[,1] );
caprisa002.gold.standard.infection.dates.in <- read.csv( paste( GOLD.STANDARD.DIR, "caprisa_002/caprisa_002_gold_standard_timings.csv", sep = "" ) );
caprisa002.gold.standard.infection.dates <- as.Date( as.character( caprisa002.gold.standard.infection.dates.in[,2] ), "%Y/%m/%d" );
names( caprisa002.gold.standard.infection.dates ) <- as.character( caprisa002.gold.standard.infection.dates.in[,1] );
if( use.gold.is.multiple ) {
rv217.gold.standards.in <- read.csv( paste( GOLD.STANDARD.DIR, "rv217/RV217_gold_standards.csv", sep = "" ) );
rv217.gold.is.multiple <- rv217.gold.standards.in[ , "gold.is.multiple" ];
names( rv217.gold.is.multiple ) <- rv217.gold.standards.in[ , "ptid" ];
caprisa002.gold.standards.in <- read.csv( paste( GOLD.STANDARD.DIR, "caprisa_002/caprisa_002_gold_standards.csv", sep = "" ) );
caprisa002.gold.is.multiple <- caprisa002.gold.standards.in[ , "gold.is.multiple" ];
names( caprisa002.gold.is.multiple ) <- caprisa002.gold.standards.in[ , "ptid" ];
}
rv217.pvl.in <- read.csv( paste( GOLD.STANDARD.DIR, "rv217/rv217_viralloads.csv", sep = "" ) );
caprisa002.pvl.in <- read.csv( paste( GOLD.STANDARD.DIR, "caprisa_002/caprisa_002_viralloads.csv", sep = "" ) );
rmse <- function( x, na.rm = FALSE ) {
if( na.rm ) {
x <- x[ !is.na( x ) ];
}
return( sqrt( mean( x ** 2 ) ) );
}
compute.results.per.person <- function ( results, weights ) {
apply( results, 2, function ( .column ) {
.rv <-
sapply( unique( rownames( results ) ), function( .ppt ) {
print( .ppt );
.ppt.cells <- as.numeric( as.character( .column[ rownames( results ) == .ppt ] ) );
if( all( is.na( .ppt.cells ) ) ) {
return( NA );
}
.ppt.weights <- apply( weights[ rownames( results ) == .ppt, , drop = FALSE ], 1, mean );
.ppt.weights <- .ppt.weights / sum( .ppt.weights, na.rm = TRUE );
sum( .ppt.cells * .ppt.weights, na.rm = TRUE );
} );
names( .rv ) <- unique( rownames( results ) );
return( .rv );
} );
} # compute.results.per.person
get.infer.results.columns <-
function ( the.region, the.time, the.ptids, partition.size = NA ) {
## Add to results: "infer" results.
if( is.na( partition.size ) ) {
infer.results.directories <- dir( paste( RESULTS.DIR, results.dirname, "/", the.region, "/", the.time, sep = "" ), "founder-inference-bakeoff_", full.name = TRUE );
} else {
#infer.results.directories <- dir( paste( RESULTS.DIR, results.dirname, "/", the.region, "/", the.time, "/partitions", sep = "" ), "founder-inference-bakeoff_", full.name = TRUE );
stop( "TODO: When there are some Infer results run on partitions, evaluate the results here" );
}
# Special: for v3, separate out the caprisa seqs from the rv217 seqs
if( the.region == "v3" ) {
infer.results.directories <- grep( "_100\\d\\d\\d$", infer.results.directories, value = TRUE );
} else if( the.region == "rv217_v3" ) {
infer.results.directories <- grep( "_100\\d\\d\\d$", infer.results.directories, value = TRUE, invert = TRUE );
}
# For now only use the sampledwidth ones, so exclude the other artificialBounds results.
infer.results.directories.sampledwidth <-
grep( "sampledwidth", infer.results.directories, value = TRUE );
infer.results.directories.unbounded <-
grep( "artificialBounds", infer.results.directories, value = TRUE, invert = TRUE );
infer.results.directories <- c( infer.results.directories.unbounded, infer.results.directories.sampledwidth );
infer.results.files <- sapply( infer.results.directories, dir, "toi.csv", full.name = TRUE );
if( length( infer.results.files ) == 0 ) {
return( NULL );
}
infer.results.list <-
lapply( unlist( infer.results.files ), function( .file ) {
.rv <- as.matrix( read.csv( .file, header = FALSE ), nrow = 1 );
stopifnot( ncol( .rv ) == 3 );
return( .rv );
} );
names( infer.results.list ) <- unlist( infer.results.files );
if( length( infer.results.list ) == 0 ) {
return( NULL );
} else {
## TODO: REMOVE
print( infer.results.list );
}
infer.results <- do.call( rbind, infer.results.list );
colnames( infer.results ) <- c( "Infer", "Infer.CI.high", "Infer.CI.low" );
## reorder them
infer.results <- infer.results[ , c( "Infer", "Infer.CI.low", "Infer.CI.high" ), drop = FALSE ];
infer.results.bounds.ptid <- gsub( "^.+_(\\d+)/.+$", "\\1", names( infer.results.list ) );
rownames( infer.results ) <- infer.results.bounds.ptid;
## Separate it into separate tables by bounds type.
infer.results.bounds.type <-
gsub( "^.+_artificialBounds_(.+)_\\d+/.+$", "\\1", names( infer.results.list ) );
infer.results.bounds.type[ grep( "csv$", infer.results.bounds.type ) ] <- NA;
infer.results.nobounds.table <- infer.results[ is.na( infer.results.bounds.type ), , drop = FALSE ];
infer.results.bounds.types <- setdiff( unique( infer.results.bounds.type ), NA );
## Exclude old/outdated bounds
infer.results.bounds.types <-
grep( "(one|six)month", infer.results.bounds.types, invert = TRUE, value = TRUE );
## TODO: Handle shifted results.
infer.results.bounds.types <-
grep( "shifted", infer.results.bounds.types, invert = TRUE, value = TRUE );
infer.results.bounds.tables <- lapply( infer.results.bounds.types, function ( .bounds.type ) {
return( infer.results[ !is.na( infer.results.bounds.type ) & ( infer.results.bounds.type == .bounds.type ), , drop = FALSE ] );
} );
names( infer.results.bounds.tables ) <- infer.results.bounds.types;
# Add just the estimates from infer (not the CIs) to the results table.
if( nrow( infer.results.nobounds.table ) > 0 ) {
new.results.columns <-
matrix( NA, nrow = length( the.ptids ), ncol = 1 + length( infer.results.bounds.tables ) );
rownames( new.results.columns ) <- the.ptids;
colnames( new.results.columns ) <- c( "Infer.time.est", infer.results.bounds.types );
.shared.ptids.nobounds <-
intersect( the.ptids, rownames( infer.results.nobounds.table ) );
.result.ignored <- sapply( .shared.ptids.nobounds, function( .ptid ) {
.infer.subtable <-
infer.results.nobounds.table[ rownames( infer.results.nobounds.table ) == .ptid, 1, drop = FALSE ];
#stopifnot( sum( rownames( infer.results.nobounds.table ) == .ptid ) == nrow( .infer.subtable ) );
if( sum( rownames( infer.results.nobounds.table ) == .ptid ) != nrow( .infer.subtable ) ) {
## TODO: REMOVE
cat( paste( "There are missing unbounded Infer results for ptid", .ptid, "in region", the.region, "at time", the.time ), fill = TRUE );
}
# But there might be fewer of these than there are rows in the results.table (if eg there are 3 input fasta files and infer results for only 2 of them).
#stopifnot( nrow( .infer.subtable ) <= sum( rownames( new.results.columns ) == .ptid ) );
if( nrow( .infer.subtable ) < sum( rownames( new.results.columns ) == .ptid ) ) {
.infer.subtable <- rbind( .infer.subtable, matrix( NA, nrow = ( sum( rownames( new.results.columns ) == .ptid ) - nrow( .infer.subtable ) ), ncol = ncol( .infer.subtable ) ) );
}
new.results.columns[ rownames( new.results.columns ) == .ptid, 1 ] <<-
.infer.subtable;
return( NULL );
} );
} else {
new.results.columns <-
matrix( NA, nrow = length( the.ptids ), ncol = length( infer.results.bounds.tables ) );
rownames( new.results.columns ) <- the.ptids;
colnames( new.results.columns ) <- infer.results.bounds.types;
.shared.ptids.nobounds <- c();
}
.result.ignored <- sapply( names( infer.results.bounds.tables ), function ( .bounds.type ) {
print( .bounds.type );
.shared.ptids <-
intersect( rownames( new.results.columns ), rownames( infer.results.bounds.tables[[ .bounds.type ]] ) );
..result.ignored <- sapply( .shared.ptids, function( .ptid ) {
print( .ptid );
.infer.subtable <-
infer.results.bounds.tables[[ .bounds.type ]][ rownames( infer.results.bounds.tables[[ .bounds.type ]] ) == .ptid, 1, drop = FALSE ];
#stopifnot( sum( rownames( infer.results.bounds.tables[[ .bounds.type ]] ) == .ptid ) == nrow( .infer.subtable ) );
if( sum( rownames( infer.results.bounds.tables[[ .bounds.type ]] ) == .ptid ) != nrow( .infer.subtable ) ) {
## TODO: REMOVE
cat( paste( "There are missing bounded Infer results for ptid", .ptid, "in region", the.region, "at time", the.time, "using bounds", .bounds.type ), fill = TRUE );
}
# But there might be fewer of these than there are rows in the results.table (if eg there are 3 input fasta files and infer results for only 2 of them).
stopifnot( nrow( .infer.subtable ) <= sum( rownames( new.results.columns ) == .ptid ) );
if( nrow( .infer.subtable ) < sum( rownames( new.results.columns ) == .ptid ) ) {
.infer.subtable <- rbind( .infer.subtable, matrix( NA, nrow = ( sum( rownames( new.results.columns ) == .ptid ) - nrow( .infer.subtable ) ), ncol = ncol( .infer.subtable ) ) );
}
new.results.columns[ rownames( new.results.columns ) == .ptid, .bounds.type ] <<-
.infer.subtable;
return( NULL );
} );
return( NULL );
} );
if( nrow( infer.results.nobounds.table ) > 0 ) {
colnames( new.results.columns ) <- c( "Infer.time.est", paste( "Infer", gsub( "_", ".", infer.results.bounds.types ), "time.est", sep = "." ) );
} else {
colnames( new.results.columns ) <- paste( "Infer", gsub( "_", ".", infer.results.bounds.types ), "time.est", sep = "." );
}
return( new.results.columns );
} # get.infer.results.columns (..)
get.anchre.results.columns <- function ( the.region, the.time, sample.dates.in, partition.size = NA ) {
## Add to results: "infer" results.
stopifnot( is.na( partition.size ) ); # TODO: Implement support for anchre on partitions.
stopifnot( the.time == "1m6m" ); # There's only anchre results for longitudinal data.
## Add to results: "anchre" results. (only at 1m6m)
anchre.results.directories <- dir( paste( RESULTS.DIR, results.dirname, "/", the.region, "/1m6m", sep = "" ), "anchre", full.name = TRUE );
if( length( anchre.results.directories ) == 0 ) {
return( NULL );
}
anchre.results.files <-
sapply( anchre.results.directories, dir, "mrca.csv", full.name = TRUE );
anchre.results <- do.call( rbind,
lapply( unlist( anchre.results.files ), function( .file ) {
stopifnot( file.exists( .file ) );
.file.short <-
gsub( "^.*?\\/?([^\\/]+?)$", "\\1", .file, perl = TRUE );
.file.short.nosuffix <-
gsub( "^([^\\.]+)(\\..+)?$", "\\1", .file.short, perl = TRUE );
.file.converted <-
paste( RESULTS.DIR, results.dirname, "/", the.region, "/1m6m/", .file.short.nosuffix, ".anc2tsv.tab", sep = "" );
# convert it.
system( paste( "./anc2tsv.sh", .file, ">", .file.converted ) );
stopifnot( file.exists( .file.converted ) );
.rv <- as.matrix( read.delim( .file.converted, header = TRUE, sep = "\t" ), nrow = 1 );
## No negative dates! Just call it NA.
.rv <- apply( .rv, 1:2, function( .str ) { if( length( grep( "^-", .str ) ) > 0 ) { NA } else { .str } } );
stopifnot( ncol( .rv ) == 4 );
return( .rv );
} ) );
colnames( anchre.results ) <- c( "Anchre.r2t.est", "Anchre.est", "Anchre.CI.low", "Anchre.CI.high" );
rownames( anchre.results ) <-
gsub( "^.+_(\\d+)$", "\\1", names( unlist( anchre.results.files ) ) );
# Special: for v3, only use caprisa seqs (not rv217, for now).
if( the.region == "v3" ) {
anchre.results <-
anchre.results[ grep( "^100\\d\\d\\d", rownames( anchre.results ) ), , drop = FALSE ];
} else if( the.region == "rv217_v3" ) {
anchre.results <-
anchre.results[ grep( "^100\\d\\d\\d", rownames( anchre.results ), invert = TRUE ), , drop = FALSE ];
}
# Add just the estimate from anchre.
sample.dates <- as.Date( as.character( sample.dates.in[ , 2 ] ) );
names( sample.dates ) <- sample.dates.in[ , 1 ];
anchre.r2t.days.before.sample <- sapply( 1:nrow( anchre.results ), function( .i ) { 0 - as.numeric( as.Date( anchre.results[ .i, 1 ] ) - sample.dates[ rownames( anchre.results )[ .i ] ] ) } );
names( anchre.r2t.days.before.sample ) <- rownames( anchre.results );
anchre.days.before.sample <- sapply( 1:nrow( anchre.results ), function( .i ) { 0 - as.numeric( as.Date( anchre.results[ .i, 2 ] ) - sample.dates[ rownames( anchre.results )[ .i ] ] ) } );
names( anchre.days.before.sample ) <- rownames( anchre.results );
anchre.columns <- cbind( anchre.r2t.days.before.sample, anchre.days.before.sample );
colnames( anchre.columns ) <- c( "Anchre.r2t.time.est", "Anchre.bst.time.est" );
return( anchre.columns );
} # get.anchre.results.columns (..)
compute.diffs.by.stat <- function ( results.per.person, days.since.infection ) {
diffs.by.stat <-
lapply( colnames( results.per.person ), function( .stat ) {
.rv <- ( as.numeric( results.per.person[ , .stat ] ) - as.numeric( days.since.infection[ rownames( results.per.person ) ] ) );
names( .rv ) <- rownames( results.per.person );
return( .rv );
} );
names( diffs.by.stat ) <- colnames( results.per.person );
return( diffs.by.stat );
} # compute.diffs.by.stat ( results.per.person, days.since.infection )
bound.and.evaluate.results.per.ppt <-
function ( results.per.person, days.since.infection, results.covars.per.person.with.extra.cols, the.time, the.artificial.bounds = NA, ppt.suffix.pattern = "\\..+", return.step.coefs = TRUE, return.lasso.coefs = TRUE, return.formulas = TRUE, return.results.per.person = TRUE ) {
## Special: the ppt names might have suffices in results.per.person; if so, strip off the suffix for purposes of matching ppts to the covars, etc.
ppt.names <- rownames( results.per.person );
ppt.suffices <- NULL;
if( !is.na( ppt.suffix.pattern ) && ( length( grep( ppt.suffix.pattern, ppt.names ) ) > 0 ) ) {
# if one has it, they should all have it.
stopifnot( length( grep( ppt.suffix.pattern, ppt.names ) ) == length( ppt.names ) );
.ppt.names <- ppt.names;
ppt.names <- gsub( ppt.suffix.pattern, "", .ppt.names );
names( ppt.names ) <- .ppt.names;
ppt.suffices <- gsub( paste( "^.+?(", ppt.suffix.pattern, ")$", sep = "" ), "\\1", .ppt.names, perl = TRUE );
names( ppt.suffices ) <- .ppt.names;
}
all.ptids <- unique( ppt.names );
## Also include all of the date estimates, which is
## everything in "results.per.person" so
## far. (However we will exclude some bounded
## results with deterministic bounds from the
## optimization, see below). It's also redundant to
## use PFitter-based days estimates, since we are
## using the mutation rate coefs, which are a
## linear fn of the corresponding days ests (I have
## confirmed that the predictions are the same
## (within +- 0.6 days, due to the rounding that
## PFitter does to its days estimates). So
## basically unless we added non-PFitter results
## (PREAST/infer, anchre, or center-of-bounds), there won't be
## anything to do here.
days.est.cols <- colnames( results.per.person );
days.est.cols <- grep( "deterministic", days.est.cols, invert = TRUE, value = TRUE );
days.est.cols <- grep( "PFitter|(DS)?Star[Pp]hy(Test)?", days.est.cols, invert = TRUE, perl = TRUE, value = TRUE );
# Also exclude anything time-dependent with times we don't use anymore.
days.est.cols <- grep( "(one|six)month", days.est.cols, invert = TRUE, perl = TRUE, value = TRUE );
## TODO: handle shifted
days.est.cols <- grep( "shifted", days.est.cols, invert = TRUE, perl = TRUE, value = TRUE );
if( the.time == "1m.6m" ) {
# Then keep the 1mmtn003.6mhvtn502 results, but not each separately.
days.est.cols <- grep( "\\.mtn|\\.hvtn", days.est.cols, invert = TRUE, perl = TRUE, value = TRUE );
}
if( use.glm.validate || use.step.validate || use.lasso.validate ) {
results.covars.per.person.with.extra.cols <-
cbind( results.per.person[ , days.est.cols, drop = FALSE ], results.covars.per.person.with.extra.cols );
.keep.cols <-
grep( "num.*\\.seqs|totalbases|upper|lower", colnames( results.covars.per.person.with.extra.cols ), value = TRUE, perl = TRUE, invert = TRUE );
# There are redundancies because the mut.rate.coef for DS is identical to PFitter's and for Bayesian it is very similar.
.keep.cols <-
grep( "(DS)?Star[pP]hy(Test)?\\.mut\\.rate\\.coef", .keep.cols, value = TRUE, invert = TRUE );
# Also exclude this strange test.
.keep.cols <-
grep( "DS\\.(DS)?Star[pP]hy(Test)?\\.is\\.starlike", .keep.cols, value = TRUE, invert = TRUE );
# Also exclude this, which is based on the strange test.
.keep.cols <-
grep( "StarPhy\\.is\\.one\\.founder", .keep.cols, value = TRUE, invert = TRUE );
.keep.cols <-
grep( "(DS)?Star[pP]hy(Test)?\\.fits", .keep.cols, value = TRUE, invert = TRUE );
.keep.cols <-
grep( "(DS)?Star[pP]hy(Test)?\\.founders", .keep.cols, value = TRUE, invert = TRUE );
# For COB and infer, use only the real-data sources (mtn003 or hvtn502). So exclude the "mtn003" and "sixmonths" ones.
.keep.cols <-
grep( "\\.(one|six)months?\\.", .keep.cols, value = TRUE, invert = TRUE );
## TODO: ADD OPTION TO KEEP and USE SHIFTED RESULTS
.keep.cols <-
grep( "shifted", .keep.cols, value = TRUE, invert = TRUE );
.donotkeep.cols <- c( grep( "DS\\.Star[pP]y\\.(fits|founders|is.starlike)", .keep.cols, value = TRUE ) );
.donotkeep.cols <- c( .donotkeep.cols, "StarPhy.founders", "InSites.founders", "multifounder.DS.Starphy.fits" );
.keep.cols <- setdiff( .keep.cols, .donotkeep.cols );
## Keep only the mut.rate.coef cols and priv.sites and multifounder.Synonymous.PFitter.is.poisson, and Infer and anchre cols.
Infer.cols <- grep( "Infer", .keep.cols, value = TRUE );
## Exclude Infer cols for obsolete bounds.
Infer.cols <- grep( "(one|six)month", Infer.cols, value = TRUE, invert = TRUE );
## TODO: hanlde shifted
Infer.cols <- grep( "shifted", Infer.cols, value = TRUE, invert = TRUE );
## Actually also exclude the ones that don't match the time
if( the.time == "1m.6m" ) {
Infer.cols <- grep( "\\.mtn|\\.hvtn", Infer.cols, value = TRUE, invert = TRUE );
}
anchre.cols <- grep( "anchre", .keep.cols, value = TRUE );
mut.rate.coef.cols <- grep( "mut\\.rate\\.coef", .keep.cols, value = TRUE );
COB.cols <- grep( "^COB", .keep.cols, value = TRUE );
## Exclude COB cols for obsolete bounds.
COB.cols <- grep( "(one|six)month", COB.cols, value = TRUE, invert = TRUE );
## TODO: Handle shifted
COB.cols <- grep( "shifted", COB.cols, value = TRUE, invert = TRUE );
## Actually also exclude the ones that don't match the time
if( the.time == "1m.6m" ) {
COB.cols <- grep( "\\.mtn|\\.hvtn", COB.cols, value = TRUE, invert = TRUE );
}
estimate.cols <- c( COB.cols, mut.rate.coef.cols, Infer.cols, anchre.cols );
all.additional.cols <- setdiff( .keep.cols, estimate.cols );
if( use.lasso.validate && include.all.vars.in.lasso ) {
keep.cols <- unique( c( helpful.additional.cols, helpful.additional.cols.with.interactions, all.additional.cols, estimate.cols ) );
} else {
keep.cols <- unique( c( helpful.additional.cols, helpful.additional.cols.with.interactions, estimate.cols ) );
}
if( use.gold.is.multiple ) {
keep.cols <- c( "gold.is.multiple", keep.cols );
}
# Don't evaluate estimators that have no variation at
# all. Note that technically we could/should do this after holding
# out each person, in case a value has no variation among the
# subset excluding that person. But we do it here only.
estimators.to.exclude <-
apply( results.covars.per.person.with.extra.cols[ , estimate.cols, drop = FALSE ], 2, function ( .col ) {
return( ( sum( !is.na( .col ) ) <= 1 ) || ( var( .col, na.rm = TRUE ) == 0 ) );
} );
estimate.cols <- setdiff( estimate.cols, names( which( estimators.to.exclude ) ) );
# Also always evaluate no-estimate: "none".
estimate.cols <- c( "none", estimate.cols );
# To make things consistent we actually change this _to_ X6m.not.1m.
colnames( results.covars.per.person.with.extra.cols )[ colnames( results.covars.per.person.with.extra.cols ) == "6m.not.1m" ] <- "X6m.not.1m";
# Some cols from "helpful.additional.cols" or "helpful.additional.cols.with.interactions" might be missing
keep.cols <-
intersect( keep.cols, colnames( results.covars.per.person.with.extra.cols ) );
results.covars.per.person <-
results.covars.per.person.with.extra.cols[ , keep.cols, drop = FALSE ];
results.covars.per.person.df <-
data.frame( results.covars.per.person );
## DO NOT Undo conversion of the colnames (X is added before "6m.not.1m"). We want it to be called "X6m.not.1m" so it can work in the regression formulas.
#colnames( results.covars.per.person.df ) <- colnames( results.covars.per.person.with.extra.cols );
regression.df <- cbind( data.frame( days.since.infection = days.since.infection[ rownames( results.covars.per.person.df ) ] ), results.covars.per.person.df, lapply( the.artificial.bounds[ grep( "shifted", grep( "(one|six)month", names( the.artificial.bounds ), invert = TRUE, value = TRUE ), invert = TRUE, value = TRUE ) ], function( .mat ) { .mat[ rownames( results.covars.per.person.df ), , drop = FALSE ] } ) );
## Ok build a regression model, including only the helpful.additional.cols and helpful.additional.cols.with.interactions (and interactions among them), and also the lower and upper bounds associated with either 5 weeks or 30 weeks, depending on the.time (if there's a 1m sample, uses "mtn003").
if( ( the.time == "6m" ) || ( the.time == "1m6m" ) ) {
.lower.bound.colname <- "sampledwidth_uniform_hvtn502.lower";
.upper.bound.colname <- "sampledwidth_uniform_hvtn502.upper";
} else if( the.time == "1m.6m" ) {
.lower.bound.colname <- "sampledwidth_uniform_1mmtn003_6mhvtn502.lower";
.upper.bound.colname <- "sampledwidth_uniform_1mmtn003_6mhvtn502.upper";
} else { # 1m or 1w
.lower.bound.colname <- "sampledwidth_uniform_mtn003.lower";
.upper.bound.colname <- "sampledwidth_uniform_mtn003.upper";
}
if( use.glm.validate ) {
#glm.fit.statistics <- matrix( 0, nrow = length( all.ptids ), nrow( results.covars.per.person.df ), ncol = 0 );
## Note that there might be multiple rows per ppt in the regression.df and in this prediction output matrix; the values will be filled in using leave-one-ptid-out xv, ie in each iteration there might be multiple rows filled in, since multiple rows correspond to one held-out ptid.
glm.validation.results.per.person <- matrix( NA, nrow = nrow( results.covars.per.person.df ), ncol = length( estimate.cols ) );
glm.withbounds.validation.results.per.person <- matrix( NA, nrow = nrow( results.covars.per.person.df ), ncol = length( estimate.cols ) );
if( return.formulas ) {
## glm:
glm.formulas.per.person <-
matrix( NA, nrow = length( all.ptids ), ncol = length( estimate.cols ) );
colnames( glm.formulas.per.person ) <-
estimate.cols;
rownames( glm.formulas.per.person ) <-
all.ptids;
## glm.withbounds:
glm.withbounds.formulas.per.person <-
matrix( NA, nrow = length( all.ptids ), ncol = length( estimate.cols ) );
colnames( glm.withbounds.formulas.per.person ) <-
estimate.cols;
rownames( glm.withbounds.formulas.per.person ) <-
all.ptids;
}
}
if( use.step.validate ) {
## These are again per-sample, see above Note.
step.validation.results.per.person <-
matrix( NA, nrow = nrow( results.covars.per.person.df ), ncol = length( estimate.cols ) );
step.withbounds.validation.results.per.person <- matrix( NA, nrow = nrow( results.covars.per.person.df ), ncol = length( estimate.cols ) );
if( return.formulas ) {
## step:
step.formulas.per.person <-
matrix( NA, nrow = length( all.ptids ), ncol = length( estimate.cols ) );
colnames( step.formulas.per.person ) <-
estimate.cols;
rownames( step.formulas.per.person ) <-
all.ptids;
## step.withbounds:
step.withbounds.formulas.per.person <-
matrix( NA, nrow = length( all.ptids ), ncol = length( estimate.cols ) );
colnames( step.withbounds.formulas.per.person ) <-
estimate.cols;
rownames( step.withbounds.formulas.per.person ) <-
all.ptids;
}
if( return.step.coefs ) {
## This is really a 3D array, but I'm just lazily representing it directly this way. Note this is by removed ppt, not by regression row (there might be multiple rows per ppt in the regression.df and the prediction output matrices).
# and these are per-ptid!
step.validation.results.per.person.coefs <-
as.list( rep( NA, length( all.ptids ) ) );
names( step.validation.results.per.person.coefs ) <-
all.ptids;
step.withbounds.validation.results.per.person.coefs <-
as.list( rep( NA, length( all.ptids ) ) );
names( step.withbounds.validation.results.per.person.coefs ) <-
all.ptids;
}
}
if( use.lasso.validate ) {
## These are again per-sample, see above Note.
lasso.validation.results.per.person <-
matrix( NA, nrow = nrow( results.covars.per.person.df ), ncol = length( estimate.cols ) );
lasso.withbounds.validation.results.per.person <- matrix( NA, nrow = nrow( results.covars.per.person.df ), ncol = length( estimate.cols ) );
if( return.formulas ) {
## lasso:
lasso.formulas.per.person <-
matrix( NA, nrow = length( all.ptids ), ncol = length( estimate.cols ) );
colnames( lasso.formulas.per.person ) <-
estimate.cols;
rownames( lasso.formulas.per.person ) <-
all.ptids;
## lasso.withbounds:
lasso.withbounds.formulas.per.person <-
matrix( NA, nrow = length( all.ptids ), ncol = length( estimate.cols ) );
colnames( lasso.withbounds.formulas.per.person ) <-
estimate.cols;
rownames( lasso.withbounds.formulas.per.person ) <-
all.ptids;
}
if( return.lasso.coefs ) {
## This is really a 3D array, but I'm just lazily representing it directly this way. Note this is by removed ppt, not by regression row (there might be multiple rows per ppt in the regression.df and the prediction output matrices).
# and these are per-ptid!
lasso.validation.results.per.person.coefs <-
as.list( rep( NA, length( all.ptids ) ) );
names( lasso.validation.results.per.person.coefs ) <-
all.ptids;
lasso.withbounds.validation.results.per.person.coefs <-
as.list( rep( NA, length( all.ptids ) ) );
names( lasso.withbounds.validation.results.per.person.coefs ) <-
all.ptids;
}
}
for( .ptid.i in 1:length( all.ptids ) ) {
the.ptid <- all.ptids[ .ptid.i ];
the.rows.for.ptid <- which( ppt.names == the.ptid );
names( the.rows.for.ptid ) <- rownames( results.per.person )[ the.rows.for.ptid ];
the.rows.excluding.ptid <- which( ppt.names != the.ptid );
## TODO: REMOVE
print( paste( "PTID", .ptid.i, "removed:", the.ptid, "rows:(", paste( names( the.rows.for.ptid ), collapse = ", " ), ")" ) );
if( use.step.validate && return.step.coefs ) {
.step.validation.results.per.person.coefs.row <-
as.list( rep( NA, length( estimate.cols ) ) );
names( .step.validation.results.per.person.coefs.row ) <-
estimate.cols;
.step.withbounds.validation.results.per.person.coefs.row <-
as.list( rep( NA, length( estimate.cols ) ) );
names( .step.withbounds.validation.results.per.person.coefs.row ) <-
estimate.cols;
}
if( use.lasso.validate && return.lasso.coefs ) {
.lasso.validation.results.per.person.coefs.row <-
as.list( rep( NA, length( estimate.cols ) ) );
names( .lasso.validation.results.per.person.coefs.row ) <-
estimate.cols;
.lasso.withbounds.validation.results.per.person.coefs.row <-
as.list( rep( NA, length( estimate.cols ) ) );
names( .lasso.withbounds.validation.results.per.person.coefs.row ) <-
estimate.cols;
}
regression.df.without.ptid.i <-
regression.df[ the.rows.excluding.ptid, , drop = FALSE ];
## But now also exclude columns for which ptid has only NA values, as these can't be used for predicting ptid's excluded days.since.infection.
ptid.has.nonmissing.data.by.col <-
apply( regression.df[ the.rows.for.ptid, , drop = FALSE ], 2, function( .col ) { !all( is.na( .col ) ) } );
regression.df.without.ptid.i <-
regression.df.without.ptid.i[ , ptid.has.nonmissing.data.by.col, drop = FALSE ];
for( .col.i in 1:length( estimate.cols ) ) {
.estimate.colname <- estimate.cols[ .col.i ];
if( ( .estimate.colname != "none" ) && ( ptid.has.nonmissing.data.by.col[ .estimate.colname ] == FALSE ) ) {
# This estimator is missing for this participant.
next;
}
## TODO: REMOVE
#print( .estimate.colname );
if( use.glm.validate || use.step.validate || ( use.lasso.validate && !include.all.vars.in.lasso ) ) {
# covariates for glm
.covariates.glm <-
c( helpful.additional.cols, helpful.additional.cols.with.interactions );
# covariates for glm.withbounds
.covariates.glm.withbounds <-
c( helpful.additional.cols, helpful.additional.cols.with.interactions, .upper.bound.colname );
if( use.gold.is.multiple ) {
.covariates.glm <- c( "gold.is.multiple", .covariates.glm );
.covariates.glm.withbounds <- c( "gold.is.multiple", .covariates.glm.withbounds );
}
.covars.to.exclude <- apply( regression.df.without.ptid.i, 2, function ( .col ) {
return( ( sum( !is.na( .col ) ) <= 1 ) || ( var( as.numeric( .col ), na.rm = TRUE ) == 0 ) );
} );
# Also exclude covars that are too highly correlated.
.retained.covars <-
setdiff( colnames( regression.df.without.ptid.i ), names( which( .covars.to.exclude ) ) );
if( ( .estimate.colname == "none" ) || ( .estimate.colname %in% .retained.covars ) ) {
.interactors <-
intersect( .retained.covars, helpful.additional.cols.with.interactions );
# Add interactions among the interactors.
if( length( .interactors ) > 1 ) {
## NOTE that for now it is up to the caller to ensure that the df is not too high in this case.
.interactions.among.interactors <- c();
for( .interactor.i in 1:( length( .interactors ) - 1 ) ) {
.interactor <- .interactors[ .interactor.i ];
.remaining.interactors <-
.interactors[ ( .interactor.i + 1 ):length( .interactors ) ];
.interactions.among.interactors <-
c( .interactions.among.interactors,
paste( .interactor, .remaining.interactors, collapse = "+", sep = ":" ) );
} # End foreach .interactor.i
.interactors <- c( .interactors, .interactions.among.interactors );
} # End if there's more than one "interactor"
if( use.gold.is.multiple ) {
.interactors <- c( "gold.is.multiple", .interactors );
}
if( .estimate.colname == "none" ) {
.cv.glm <- intersect( .retained.covars, .covariates.glm );
if( length( .cv.glm ) == 0 ) {
.cv.glm <- 1;
}
## SEE NOTE BELOW ABOUT USE OF AN INTERCEPT. WHEN we're using "none", then we always do use an intercept (only for the non-bounded result).
if( include.intercept ) {
.formula <- paste( "days.since.infection ~ 1 + ", paste( .cv.glm, collapse = "+" ) );
.formula.withbounds <- paste( "days.since.infection ~ 1 + ", paste( intersect( .retained.covars, .covariates.glm.withbounds ), collapse = "+" ) );
} else {
.cv.glm.nointercept <- intersect( .retained.covars, .covariates.glm );
if( length( .cv.glm.nointercept ) == 0 ) {
.formula.nointercept <- "days.since.infection ~ 1"; # _only_ intercept!
} else {
.formula.nointercept <- paste( "days.since.infection ~ 0 + ", paste( .cv.glm.nointercept, collapse = "+" ) );
}
.covariates.glm.withbounds.nointercept <- .covariates.glm.withbounds;
.formula.withbounds.nointercept <- paste( "days.since.infection ~ 0 + ", paste( intersect( .retained.covars, .covariates.glm.withbounds.nointercept ), collapse = "+" ) );
.formula <- .formula.nointercept;
.formula.withbounds <- .formula.withbounds.nointercept;
}
} else {
## NOTE WE MUST BE CAREFUL ABOUT USING AN INTERCEPT, BECAUSE THEN WE JUST CHEAT BY PREDICTING EVERYTHING IS CENTERED AT the tight true bounds on the days.since.infection in our training data (when looking at one time at a time, and now with 6m.not.1m this should be true for both times as well.).
if( include.intercept ) {
.formula <- paste( "days.since.infection ~ 1 + ", paste( intersect( .retained.covars, c( .covariates.glm, .estimate.colname ) ), collapse = "+" ) );
.formula.withbounds <- paste( "days.since.infection ~ 1 + ", paste( intersect( .retained.covars, c( .covariates.glm.withbounds, .estimate.colname ) ), collapse = "+" ) );
} else {
.covariates.glm.nointercept <- .covariates.glm;
.formula.nointercept <- paste( "days.since.infection ~ 0 + ", paste( intersect( .retained.covars, c( .covariates.glm.nointercept, .estimate.colname ) ), collapse = "+" ) );
.formula <- .formula.nointercept;
.covariates.glm.withbounds.nointercept <- .covariates.glm.withbounds;
.formula.withbounds.nointercept <-
paste( "days.since.infection ~ 0 + ", paste( intersect( .retained.covars, c( .covariates.glm.withbounds.nointercept, .estimate.colname ) ), collapse = "+" ) );
.formula.withbounds <- .formula.withbounds.nointercept;
}
}
.interactees <-
setdiff( intersect( .retained.covars, .covariates.glm ), .interactors );
if( ( length( .interactors ) > 0 ) && ( length( .interactees ) > 0 ) ) {
## NOTE that for now it is up to the caller to ensure that the df is not too high in this case.
.interactions.formula.part.components <- c();
for( .interactor.i in 1:length( .interactors ) ) {
.interactor <- .interactors[ .interactor.i ];
.interactions.formula.part.components <-
c( .interactions.formula.part.components,
paste( .interactor, .interactees, collapse = "+", sep = ":" ) );
} # End foreach .interactor.i
.interactions.formula.part <-
paste( .interactions.formula.part.components, collapse =" + " );
.formula <-
paste( .formula, .interactions.formula.part, sep = " + " );
} # End if there's any "interactees"
## Also add interactions with the estimate colname and everything included so far.
if( .estimate.colname != "none" ) {
.everything.included.so.far.in.formula <-
strsplit( .formula, split = "\\s*\\+\\s*" )[[1]];
# Add interactions.
.new.interactions.with.estimator.in.formula <-
sapply( setdiff( .everything.included.so.far.in.formula[ -1 ], .estimate.colname ), function ( .existing.part ) {
paste( .existing.part, .estimate.colname, sep = ":" )
} );
.formula <- paste( c( .everything.included.so.far.in.formula, .new.interactions.with.estimator.in.formula ), collapse = " + " );
} # End if .estimate.colname != "none"
## withbounds
.interactees.withbounds <-
setdiff( intersect( .retained.covars, .covariates.glm.withbounds ), .interactors );
if( ( length( .interactors ) > 0 ) && ( length( .interactees.withbounds ) > 0 ) ) {
## NOTE that for now it is up to the caller to ensure that the df is not too high in this case.
.interactions.withbounds.formula.part.components <- c();
for( .interactor.i in 1:length( .interactors ) ) {
.interactor <- .interactors[ .interactor.i ];
.interactions.withbounds.formula.part.components <-
c( .interactions.withbounds.formula.part.components,
paste( .interactor, .interactees.withbounds, collapse = "+", sep = ":" ) );
} # End foreach .interactor.i
.interactions.withbounds.formula.part <-
paste( .interactions.withbounds.formula.part.components, collapse =" + " );
.formula.withbounds <-
paste( .formula.withbounds, .interactions.withbounds.formula.part, sep = " + " );
} # End if there's any "interactees.withbounds"
## Also add interactions with the estimate colname and everything included so far.
if( .estimate.colname != "none" ) {
.everything.included.so.far.in.formula.withbounds <-
strsplit( .formula.withbounds, split = "\\s*\\+\\s*" )[[1]];
# Add interactions with the bound.
.new.interactions.with.estimator.in.formula.withbounds <-
sapply( setdiff( .everything.included.so.far.in.formula.withbounds[ -1 ], .estimate.colname ), function ( .existing.part ) {
paste( .existing.part, .estimate.colname, sep = ":" )
} );
.formula.withbounds <- paste( c( .everything.included.so.far.in.formula.withbounds, .new.interactions.with.estimator.in.formula.withbounds ), collapse = " + " );
} # End if .estimate.colname != "none"
## If the intercept isn't included, then also don't include any combo of the pseudo-intercepts denoting the time or region.
if( !include.intercept ) {
## TODO: MOVE UP. MAGIC #s
pseudo.intercepts <- c( "X6m.not.1m", "v3_not_nflg", "X6m.not.1m:v3_not_nflg", "v3_not_nflg:X6m.not.1m" );
.everything.included.so.far.in.formula <-
strsplit( .formula, split = "\\s*\\+\\s*" )[[1]];
# Remove the pseudointercepts.
.everything.that.should.be.in.formula <-
setdiff(
.everything.included.so.far.in.formula[ -1 ],
pseudo.intercepts
);
.formula <- paste( c( .everything.included.so.far.in.formula[ 1 ], .everything.that.should.be.in.formula ), collapse = " + " );
.everything.included.so.far.in.formula.withbounds <-
strsplit( .formula.withbounds, split = "\\s*\\+\\s*" )[[1]];
# Remove the pseudointercepts.
.everything.that.should.be.in.formula.withbounds <-
setdiff(
.everything.included.so.far.in.formula.withbounds[ -1 ],
pseudo.intercepts
);
.formula.withbounds <- paste( c( .everything.included.so.far.in.formula.withbounds[ 1 ], .everything.that.should.be.in.formula.withbounds ), collapse = " + " );
} # End if !include.intercept
## If the intercept isn't included, then also don't include any combo of the pseudo-intercepts denoting the time or region.
if( mutation.rate.calibration && ( .estimate.colname != "none" ) ) {
.everything.included.so.far.in.formula <-
strsplit( .formula, split = "\\s*\\+\\s*" )[[1]];
# Remove anything not including the estimate.colname
.everything.that.should.be.in.formula <-
grep( .estimate.colname, .everything.included.so.far.in.formula[ -1 ], value = TRUE );
.formula <- paste( c( .everything.included.so.far.in.formula[ 1 ], .everything.that.should.be.in.formula ), collapse = " + " );
.everything.included.so.far.in.formula.withbounds <-
strsplit( .formula.withbounds, split = "\\s*\\+\\s*" )[[1]];
# Remove anything not including the estimate.colname
.everything.that.should.be.in.formula.withbounds <-
grep( .estimate.colname, .everything.included.so.far.in.formula.withbounds[ -1 ], value = TRUE );
.formula.withbounds <- paste( c( .everything.included.so.far.in.formula.withbounds[ 1 ], .everything.that.should.be.in.formula.withbounds ), collapse = " + " );
} # End if mutation.rate.calibration && ( estimate.colname != "none" )
# To this point these are still strings:
#.formula <- as.formula( .formula );
#.formula.withbounds <- as.formula( .formula.withbounds );
# The condition below is required now that we also compute the above for the cases with use.step.validate and ( use.lasso.validate && !include.all.vars.in.lasso )
if( use.glm.validate ) {
.glm.result <- lm( .formula, data = regression.df.without.ptid.i );
if( return.formulas ) {
glm.formulas.per.person[ .ptid.i, .col.i ] <-
.formula;
}
for( .row.i in the.rows.for.ptid ) {
.pred.value.glm <- predict( .glm.result, regression.df[ .row.i, , drop = FALSE ] );
glm.validation.results.per.person[ .row.i, .col.i ] <-
.pred.value.glm;
}
# glm.withbounds:
.glm.withbounds.result <-
lm( .formula.withbounds, data = regression.df.without.ptid.i );
if( return.formulas ) {
glm.withbounds.formulas.per.person[ .ptid.i, .col.i ] <-
.formula.withbounds;
}
for( .row.i in the.rows.for.ptid ) {
.pred.value.glm.withbounds <-
predict( .glm.withbounds.result, regression.df[ .row.i, , drop = FALSE ] );
glm.withbounds.validation.results.per.person[ .row.i, .col.i ] <-
.pred.value.glm.withbounds;
}
} # End if use.glm.validate
} # End if the estimate can be used
} # End if use.glm.validate || ( use.lasso.validate && !include.all.vars.in.lasso )
if( use.step.validate ) {
## step (not withbounds)
## Use .formula already defined.
## NOTE: in the below, the .retained.covars and .glm.result and .glm.withbounds.result are defined above, with the computation of the non-withbounds ("glm") results.
if( ( .estimate.colname == "none" ) || ( .estimate.colname %in% .retained.covars ) ) {
if( .estimate.colname == "none" ) {
.step.result <- suppressWarnings( step( .glm.result, trace = FALSE ) );
} else {
# This forces keeping the .estimate.colname
tryCatch( {
.glm.result.na.omit <-
lm( .formula, data = na.omit( regression.df.without.ptid.i ) );
.step.result <-
suppressWarnings( step( .glm.result.na.omit, trace = FALSE, scope = c( lower = paste( "~", .estimate.colname ), upper = ( .glm.result.na.omit$terms ) ) ) );
}, error = function( e ) {
# Sometimes for unknown reasons it fails with a bounded scope but not without one.
.step.result <-
suppressWarnings( step( .glm.result.na.omit, trace = FALSE ) );
} );
}
if( return.formulas ) {
step.formulas.per.person[ .ptid.i, .col.i ] <-
as.character( ( ( .step.result )$call )[ 2 ] );
}
.pred.value.step <-
predict( .step.result, regression.df[ .row.i, , drop = FALSE ] );
step.validation.results.per.person[ .row.i, .col.i ] <-
.pred.value.step;
if( return.step.coefs ) {
.step.validation.results.per.person.coefs.cell <-
coef( .step.result );
.step.validation.results.per.person.coefs.row[[ .col.i ]] <-
.step.validation.results.per.person.coefs.cell;
}
## step.withbounds:
if( .estimate.colname == "none" ) {
.step.withbounds.result <-
suppressWarnings( step( .glm.withbounds.result, trace = FALSE ) );
} else {
# This forces keeping the .estimate.colname and .upper.bound.colname
tryCatch( {
.glm.withbounds.result.na.omit <-
lm( .formula.withbounds, data = na.omit( regression.df.without.ptid.i ) );
.step.withbounds.result <-
suppressWarnings( step( .glm.withbounds.result.na.omit, trace = FALSE, scope = c( lower = paste( "~", paste( .estimate.colname, .upper.bound.colname, sep = "+" ) ), upper = ( .glm.withbounds.result.na.omit$terms ) ) ) );
}, error = function( e ) {
# Sometimes for unknown reasons it fails with a bounded scope but not without one.
.step.withbounds.result <-
suppressWarnings( step( .glm.withbounds.result.na.omit, trace = FALSE ) );
} );
}
if( return.formulas ) {
step.withbounds.formulas.per.person[ .ptid.i, .col.i ] <-