-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.r
1899 lines (1670 loc) · 82.2 KB
/
server.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
library(DT)
library(Rcpp)
library(RcppArmadillo)
library(ggplot2)
library(shinyjs)
library(data.table)
library(dplyr)
library(plotly)
library(openxlsx)
#library(gridExtra)
sourceCpp("Engine.cpp")
server <- function(input, output, clientData, session) {
# ***************************************************** #
# ********************* VARIABLES ********************* #
# ********************* --------- ********************* #
# ***************************************************** #
# TV to use complementary to generated divID for identifying Scenarios ID
Scenarios <<- c() #simple list of scenario ids, so will be [1,2,3] if three scenarios
Ranges <<- c() #simple list of range scenario ids, so will be [1,2,3] if three scenarios of ranges
# Define default matrix values
stage = c(1,2,3)
entries = c(1000,100,10)
years = c(1,1,2)
locs = c(1,4,8)
reps = c(1,2,3)
error = c(1,1,1)
h2 = c(0.5,0.5,0.5) # this is a calculated value initialised here
plotCost = c(10,10,10)
locCost = c(1000,1000,1000)
fixedCost = c(1000,1000,1000)
# varieties = c(1,1,1)
yt = cbind(stage,entries,years,locs,reps,error,h2,plotCost,locCost,fixedCost) #,varieties)
# Ranges DT has 3 cols for min max and samples
entries_r = c(100,1000,3)
years_r = c(1,5,3)
locs_r = c(1,5,3)
reps_r = c(1,5,3)
plotCost_r = 10
locCost_r = 1000
fixedCost_r = 1000
rt = rbind(entries_r, years_r, locs_r, reps_r)
# per-session reactive values object to store all results of this user session
rv <- reactiveValues(results_all = NULL, results_allxTime = NULL, results_allxCost = NULL, results_range = NULL, results_range_r = NULL)
# defines a common reactive list to store all scenario input info (stages DT + other) to replace reactDT
scenariosInput <- reactiveValues(stagesDT = list(), varG = list(), varGxL = list(), varGxY = list(), varieties = list()) # initially will store stages_current and updated accordingly
# Using reactiveVales to add a server side set of variable observable and mutable at the same time
yti <- reactiveValues(data = yt)
rti <- reactiveValues(data = rt)
fin = data.frame(stage_r = c("Final"), entries_r = c(1))
print(paste("The type of final entries DT is : ", mode(fin)))
yti$varieties <- fin
# initialize empty vector to stores status of chk_ranges for each scenario
rangesVec <- vector()
# initialize empty list to store data frames of reactiveValues created for each Scenario, e.g. reactDT1
reactDT.list <- reactiveValues() # list()
# ***************************************************** #
# ********************* FUNCTIONS ********************* #
# ********************* --------- ********************* #
# *********** All functions are defined here ********** #
# ***************************************************** #
# function calculates h2 for a given as input a row of a DT matrix and 3 variances (optional)
updateH2 <- function(stg = yti$data[1,], vG=input$varG, vGxY=input$varGxY, vGxL=input$varGxL){
h2 = round(vG/(vG + vGxY/stg[3] + vGxL/(stg[3]*stg[4]) + stg[6]/(stg[3]*stg[4]*stg[5])), 3)
return(h2)
}
# function returns total number of years for a scenario
totalYears <- function(scenarioDT = yti$data, selfingYears = input$negen) {
ty = sum(scenarioDT[,3]) + selfingYears
return(ty)
}
# function returns the total number of locations for a scenario
totalLocs <- function(scenarioDT = yti$data) {
tl = sum(scenarioDT[,3]*scenarioDT[,4])
return(tl)
}
# function calculates Total Plots given a stages matrix as input
totalPlots <- function(scenarioDT = yti$data) {
tp = 0
for (i in 1:nrow(scenarioDT))
tp = tp + prod(scenarioDT[i,2:5])
return(tp)
}
# function calculates total cost of locations
# totalLocsCost <-function(scenarioDT = yti$data, costPerLoc = input$costPerLoc) {
# tlc = totalLocs(scenarioDT) * costPerLoc
# return(tlc)
# }
totalLocsCost <-function(scenarioDT = yti$data) {
tlc = 0
for (i in 1:nrow(scenarioDT))
{
tlc = tlc + stageLocsCost(scenarioDT, i)
}
return(tlc)
}
# function calculates total cost of plots
# totalPlotsCost <-function(scenarioDT = yti$data, costPerPlot = input$costPerPlot) {
# tpc = totalPlots(scenarioDT) * costPerPlot
# return(tpc)
# }
totalPlotsCost <-function(scenarioDT = yti$data) {
tpc = 0
for (i in 1:nrow(scenarioDT))
{
tpc = tpc + stagePlotsCost(scenarioDT, i)
}
return(tpc)
}
# function calculates total cost of scenario
# totalCost <- function(scenarioDT = yti$data, costPerLoc = input$costPerLoc, costPerPlot = input$costPerPlot, costFixed = input$costFixed) {
# tc = totalLocsCost(scenarioDT, costPerLoc) + totalPlotsCost(scenarioDT, costPerPlot) + costFixed
# return(tc)
# }
totalCost <- function(scenarioDT = yti$data) {
tc = 0
for (i in 1:nrow(scenarioDT))
{
tc = tc + stageCost(scenarioDT, i)
}
return(tc)
}
# function returns total number of years passed until a particular stage is completed (default is stage 1)
stageTotalYears <- function(scenarioDT = yti$data, stage = 1, selfingYears = input$negen) {
scy = sum(scenarioDT[1:stage,3]) + selfingYears
return(scy)
}
# function calcucates Gain / Time dividing the gain with the number of years passed until a stage is completed
gainTime <- function(scenarioDT = yti$data, result = result, stage = 1) {
gt = result[stage,] / stageTotalYears(scenarioDT, stage)
return(gt)
}
# function returns total locs in a stage (default is stage 1)
stageTotalLocs <-function(scenarioDT = yti$data, stage = 1) {
stl = 0
for (i in 1:stage)
{
stl = stl + prod(scenarioDT[i,3:4])
}
# stl = sum(prod(scenarioDT[1:stage,1:4]))
return(stl)
}
# function returns total plots in a stage (default is stage 1)
stageTotalPlots <-function(scenarioDT = yti$data, stage = 1) {
# should be equal to the summary of products for up to that stage
stp = 0
for (i in 1:stage)
{
stp = stp + prod(scenarioDT[i,2:5])
}
#stp = sum(prod(scenarioDT[1:stage,1:4])) # + previous stages total plots
return(stp)
}
# function returns number of locs of a single stage
stageLocs <-function(scenarioDT = yti$data, stage = 1) {
sl = prod(scenarioDT[stage,3:4])
return(sl)
}
# function returns number of plots of a single stage
stagePlots <-function(scenarioDT = yti$data, stage = 1) {
sp = prod(scenarioDT[stage,2:5])
return(sp)
}
# function returns cost of Locs for a single stage
stageLocsCost <-function(scenarioDT = yti$data, stage = 1) {
slc = stageLocs(scenarioDT, stage) * scenarioDT[stage, 9]
return(slc)
}
# function returns cost of Plots for a single stage
stagePlotsCost <-function(scenarioDT = yti$data, stage = 1) {
spc = stagePlots(scenarioDT) * scenarioDT[stage, 8]
return(spc)
}
# function returns tolal cost of a single stage
stageCost <-function(scenarioDT = yti$data, stage = 1) {
stc = stageLocsCost(scenarioDT, stage) + stagePlotsCost(scenarioDT, stage) + scenarioDT[stage, 10] # + Fixed Cost
return(stc)
}
# function returns gain per cost for a single stage independently of previous stages cost ****** --- N O T U S E D ! ! ! --- ******
stageGainCost <-function(scenarioDT = yti$data, result = result, stage = 1) {
sgc = result[stage,] / stageCost(scenarioDT, stage)
return(sgc)
}
# Return the gain over cost up until the end of a stage in the whole program
# gainCost <- function(scenarioDT = yti$data, result = result, stage = 1, costPerPlot = input$costPerPlot, costPerLoc = input$costPerLoc) {
# gc = result[stage,] / (stageTotalPlots(scenarioDT, stage) * costPerPlot + stageTotalLocs(scenarioDT, stage) * costPerLoc)
# return(gc)
# }
gainCost <- function(scenarioDT = yti$data, result = result, stage = 1) {
gc = 0
for (i in 1:stage)
{
gc = gc + stagePlotsCost(scenarioDT, i) + stageLocsCost(scenarioDT, i) + scenarioDT[i, 10] # + Fixed Cost included!
}
gc = result[stage,] / gc
return(gc)
}
# function creates a new Tab in the UI for a given ScenarioID
createTab <- function(scenarioID = 1, withRanges = rangesVec) {
myTabs = lapply(1: scenarioID, function(i){
tabPanel(paste0('Scenario', i),
plotOutput(paste0('cyPlot', i)),
# input settings used for this scenario
DT::DTOutput(paste0('stages_summary', i)),
# update scenario button
actionButton(paste0("update_btn", i), "Update"),
# downloadButton(paste0("download_btn", i), "Download Report"), # Disabled
# cost table for this scenario
DT::DTOutput(paste0('costDT', i)),
# Start section with plots of ranges
#conditionalPanel(
# condition = "input.chk_ranges", # needs a different condition local to the scenario
#print(paste("Ranges is ", withRanges[i])),
if (withRanges[i])
{
tags$div(class = "div_plot_ranges", checked = NA,
tags$h3("Plots for ranges of parameters at first stage"),
# Drop down lists to select plots to view for each Scenario Tab
selectInput(inputId = paste0('rangePlots', i), label = "Show Range Plots:",
choices = c("Entries" = paste0('rangePlotEntries', i),
"Years" = paste0('rangePlotYears', i),
"Locs" = paste0('rangePlotLocs', i),
"Reps" = paste0('rangePlotReps', i),
"Entries by Years" = paste0('rangePlotEntriesYears', i),
"Entries by Locs" = paste0('rangePlotEntriesLocs', i),
"Entries by Reps" = paste0('rangePlotEntriesReps', i),
"Years by Locs" = paste0('rangePlotYearsLocs', i),
"Years by Reps" = paste0('rangePlotYearsReps', i),
"Locs by Reps" = paste0('rangePlotLocsReps', i)),
selected = NULL,
multiple = FALSE,
selectize = TRUE
),
textOutput(paste0('plotMe', i)),
# range plot overwrites first stage entries
plotOutput(paste0('rangePlotEntries', i)),
# range plot overwrites first stage years
plotOutput(paste0('rangePlotYears', i)),
# range plot overwrites first stage locs
plotOutput(paste0('rangePlotLocs', i)),
# range plot overwrites first stage reps
plotOutput(paste0('rangePlotReps', i)),
# bubble / plotly-heatmap range plot for x6 pairs of entries/years/locs/reps ranges in first stage
# Enable switching between plotlyOutput and plotOutput for bubble plots and heatmaps
# TODO
# hide plots and only show when selected in drop box
plotlyOutput(paste0('rangePlotEntriesYears', i)),
#
plotlyOutput(paste0('rangePlotEntriesLocs', i)),
#
plotlyOutput(paste0('rangePlotEntriesReps', i)),
#
plotlyOutput(paste0('rangePlotYearsLocs', i)),
#
plotlyOutput(paste0('rangePlotYearsReps', i)),
#
plotlyOutput(paste0('rangePlotLocsReps', i))
) # endof div plot ranges
} #) # endof Conditional Panel
) # endof Tab Panel
})
do.call("tabsetPanel", c(myTabs, id = "sc_tabs"))
}
# function updates Tab in the UI for a given ScenarioID and selectInput inputID with a list of plots (called by drop down list observer)
showPlot <- function(selectedID = input$rangePlots1, scenarioID = 1) { # (scenarioID = 1, inputID = "Entries by Reps") {
choices = c(paste0('rangePlotEntries', scenarioID),
paste0('rangePlotYears', scenarioID),
paste0('rangePlotLocs', scenarioID),
paste0('rangePlotReps', scenarioID),
paste0('rangePlotEntriesYears', scenarioID),
paste0('rangePlotEntriesLocs', scenarioID),
paste0('rangePlotEntriesReps', scenarioID),
paste0('rangePlotYearsLocs', scenarioID),
paste0('rangePlotYearsReps', scenarioID),
paste0('rangePlotLocsReps', scenarioID))
print("HIDE ALL")
for (i in choices)
{
hide(i)
if (i == selectedID)
{
print(paste("SELECTED ", i)) #
toggle(i) #show(i)
}
# else
# {
# print(paste("NOT SELECTED ", i))
# #toggle(i)
# hide(i)
# }
}
}
# Store results from all runs in a reactive matrix
storeScenarioResult <- function(result = result, results_all = rv$results_all, scenarioID = tail(Scenarios,1) ) {
for(i in 1:nrow(result))
{
results_all = cbind(results_all, rbind(Stage = i, Value = result[i,], Scenario = scenarioID))
}
return(results_all)
}
# Store all Gain results conditioned by Time
storeScenarioResultxTime <- function(result = result, results_all = rv$results_allxTime, scenarioID = tail(Scenarios,1), scenarioDT = yti$data) {
for(i in 1:nrow(result))
{
results_all = cbind(results_all, rbind(Stage = i, Value = gainTime(scenarioDT, result, i), Scenario = scenarioID))
}
return(results_all)
}
# Store all Gain results conditioned by Cost
storeScenarioResultxCost <- function(result = result, results_all = rv$results_allxCost, scenarioID = tail(Scenarios,1), scenarioDT = yti$data) {
for(i in 1:nrow(result))
{
results_all = cbind(results_all, rbind(Stage = i, Value = gainCost(scenarioDT, result, i), Scenario = scenarioID))
}
return(results_all)
}
# Remove scenario result from storage. By default remove last scenario.
removeScenarioResult <- function(scenarioID = tail(Scenarios,1), results_all = rv$results_all) {
results_all <- results_all[,results_all[3,] != scenarioID]
return(results_all)
}
# Ignore entries in first stage and instead run for a range of entries. Store the results in rv$results_range
runScenarioRange <- function(min_entries = input$entries_range[1], max_entries = input$entries_range[2],
min_years = input$years_range[1], max_years = input$years_range[2],
min_locs = input$locs_range[1], max_locs = input$locs_range[2],
min_reps = input$reps_range[1], max_reps = input$reps_range[2],
grain = input$grain,
scenarioDT = yti$data,
varG = input$varG,
varGxL = input$varGxL,
varGxY = input$varGxY,
varieties = as.numeric(yti$varieties[1,2]))
#varieties = input$varieties)
# results_range = rv$results_range)
{
print(scenarioDT)
stage = scenarioDT[,1]
entries = scenarioDT[,2]
min_entries = checkMinEntries(entries, min_entries) # entries at second stage must be less than the first
years = scenarioDT[,3]
locs = scenarioDT[,4]
reps = scenarioDT[,5]
error = scenarioDT[,6]
it = 0 # counter of iterations between range min max
range_entries = rangeGrain(min_entries, max_entries, grain)
range_years = rangeGrain(min_years, max_years, grain)
range_locs = rangeGrain(min_locs, max_locs, grain)
range_reps = rangeGrain(min_reps, max_reps, grain)
#print(range_reps)
# Show Progress Bar
withProgress(message = 'Calculating results', value = 0, {
rr = NULL
for (i in range_entries)
{
for (k in range_years)
{
for (l in range_locs)
{
for (j in range_reps)
{
# update progress bar after a single iteration of the nested loop
incProgress(1/(length(range_entries)*length(range_years)*length(range_locs)*length(range_reps)), detail = paste("Iteration", it, "of", length(range_entries)*length(range_years)*length(range_locs)*length(range_reps)))
it = it + 1
entries[1] = i # replace first stage entries with range_entries
years[1] = k
locs[1] = l
reps[1] = j # replace first stage reps with range_reps
resultLite = runScenarioLite(varG,
varGxL,
varGxY,
entries,
years,
locs,
reps,
error,
varieties)
#print(resultLite) # WORKS
resultLite = as.data.frame(resultLite) # convert to a df
colnames(resultLite) <- c("mean","sd")
# Create df with I/O data and bind this to rr from previous iterations
rr<-rbind(rr, cbind(scenario = tail(Scenarios,1), fs_entries = i, fs_years = k, fs_locs = l, fs_reps = j, it, stage, entries, years, locs, reps, error, resultLite))
}
}
}
}
})
return(rr)
}
# Previous function adjusted to separate tab for ranges not dependent on DT ------------------------------- NOT USED -----------------
# Ignore entries in first stage and instead run for a range of entries. Store the results in rv$results_range
# runScenarioRange_r_slider <- function(min_entries = input$entries_range_r[1], max_entries = input$entries_range_r[2],
# min_years = input$years_range_r[1], max_years = input$years_range_r[2],
# min_locs = input$locs_range_r[1], max_locs = input$locs_range_r[2],
# min_reps = input$reps_range_r[1], max_reps = input$reps_range_r[2],
# # min_error = input$error_range_r[1], max_error = input$error_range_r[2],
# grain = input$grain_r,
# #TV scenarioDT = yti$data,
# varG = input$varG_r,
# varGxL = input$varGxL_r,
# varGxY = input$varGxY_r,
# varErr = input$varErr_r,
# varieties = input$varieties_r)
# # results_range = rv$results_range)
# {
# #TV print(scenarioDT)
# #TV stage = scenarioDT[,1]
# #TV entries = scenarioDT[,2]
#
# min_entries = checkMinEntries(varieties, min_entries)
# # varieties must be less than min_entries
# if (varieties > min_entries)
# min_entries = varieties
# years = NA #TV scenarioDT[,3]
# locs = NA #TV scenarioDT[,4]
# reps = NA #TV scenarioDT[,5]
# error = varErr #TV scenarioDT[,6]
# it = 0 # counter of iterations between range min max
# range_entries = rangeGrain(min_entries, max_entries, grain)
# range_years = rangeGrain(min_years, max_years, grain)
# range_locs = rangeGrain(min_locs, max_locs, grain)
# range_reps = rangeGrain(min_reps, max_reps, grain)
# #range_error = rangeGrain(min_error, max_error, grain)
# #print(range_reps)
#
# # Show Progress Bar
# withProgress(message = 'Calculating results', value = 0, {
# rr = NULL
# for (i in range_entries)
# {
# for (k in range_years)
# {
# for (l in range_locs)
# {
# for (j in range_reps)
# {
# # for (e in range_error)
# # {
# # update progress bar after a single iteration of the nested loop
# # incProgress(1/(length(range_entries)*length(range_years)*length(range_locs)*length(range_reps)*length(range_error)), detail = paste("Iteration", it, "of", length(range_entries)*length(range_years)*length(range_locs)*length(range_reps)*length(range_error)))
# incProgress(1/(length(range_entries)*length(range_years)*length(range_locs)*length(range_reps)), detail = paste("Iteration", it, "of", length(range_entries)*length(range_years)*length(range_locs)*length(range_reps)))
#
# it = it + 1
# entries = i # replace first stage entries with range_entries
# years = k
# locs = l
# reps = j
# # error = e
#
# resultLite = runScenarioLite(varG,
# varGxL,
# varGxY,
# entries,
# years,
# locs,
# reps,
# error,
# varieties)
# #print(resultLite) # WORKS
# resultLite = as.data.frame(resultLite) # convert to a df
# colnames(resultLite) <- c("mean","sd")
# # Create df with I/O data and bind this to rr from previous iterations
# # rr<-rbind(rr, cbind(scenario = tail(Scenarios,1), fs_entries = i, fs_years = k, fs_locs = l, fs_reps = j, it, stage, entries, years, locs, reps, error, resultLite))
# rr<-rbind(rr, cbind(scenario = tail(Ranges,1), entries, years, locs, reps, error, it, resultLite))
# # }
# }
# }
# }
# }
# })
#
# colnames(rr) <- c("Scenario", "Entries", "Years", "Locs", "Reps", "Error", "IT", "Gain", "SD")
# #print(rr)
# #tail(rr)
# return(rr)
# }
# Uses Ranges DT instead of sliders to also include samples set for each parameter
runScenarioRange_r <- function(rangesDT = rti$data,
varG = input$varG_r,
varGxL = input$varGxL_r,
varGxY = input$varGxY_r,
varErr = input$varErr_r,
varieties = input$varieties_r,
plotCost = input$plotCost_r,
locCost = input$locCost_r,
fixedCost = input$fixedCost_r,
nRepeats = input$nRepeats)
{
min_entries = rangesDT[1,1]
max_entries = rangesDT[1,2]
sample_entries = rangesDT[1,3]
min_years = rangesDT[2,1]
max_years = rangesDT[2,2]
sample_years = rangesDT[2,3]
min_locs = rangesDT[3,1]
max_locs = rangesDT[3,2]
sample_locs = rangesDT[3,3]
min_reps = rangesDT[4,1]
max_reps = rangesDT[4,2]
sample_reps = rangesDT[4,3]
# Evaluation of range inputs is permissive allowing mistakes but it generates a warning message and updates input parameters to be valid.
if (varieties > min_entries)
{
shinyalert("Warning!", "Invalid input: Final Entries should not be larger than Min Entries. Otherwise they replace Min Entries.", type = "warning")
min_entries = varieties
}
if (varieties > max_entries)
max_entries = varieties
# try(
if (min_entries > max_entries || min_years > max_years || min_locs > max_locs || min_reps > max_reps)
{
shinyalert("Warning!", "Invalid input: Min should not be larger than Max for any parameter. Otherwise the simulation will try to run only for the smallest value of that parameter.", type = "warning")
# stop("Invalid input: min should not be more than max.")
}
years = NA #TV scenarioDT[,3]
locs = NA #TV scenarioDT[,4]
reps = NA #TV scenarioDT[,5]
error = varErr #TV scenarioDT[,6]
it = 0 # counter of iterations between range min max
range_entries = rangeGrain(min_entries, max_entries, sample_entries)
range_years = rangeGrain(min_years, max_years, sample_years)
range_locs = rangeGrain(min_locs, max_locs, sample_locs)
range_reps = rangeGrain(min_reps, max_reps, sample_reps)
# Show Progress Bar
withProgress(message = 'Calculating results', value = 0, {
rr = NULL
for (i in range_entries)
{
for (k in range_years)
{
for (l in range_locs)
{
for (j in range_reps)
{
# for (e in range_error)
# {
# update progress bar after a single iteration of the nested loop
# incProgress(1/(length(range_entries)*length(range_years)*length(range_locs)*length(range_reps)*length(range_error)), detail = paste("Iteration", it, "of", length(range_entries)*length(range_years)*length(range_locs)*length(range_reps)*length(range_error)))
incProgress(1/(length(range_entries)*length(range_years)*length(range_locs)*length(range_reps)), detail = paste("Iteration", it, "of", length(range_entries)*length(range_years)*length(range_locs)*length(range_reps)))
it = it + 1
entries = i # replace first stage entries with range_entries
years = k
locs = l
reps = j
# error = e
resultLite = runScenarioLite(varG,
varGxL,
varGxY,
entries,
years,
locs,
reps,
error,
varieties,
nRepeats = nRepeats)
#print(resultLite) # WORKS
resultLite = as.data.frame(resultLite) # convert to a df
colnames(resultLite) <- c("mean","sd")
# calculate mean gain per cost and bind it to rr
meanGainxCost_r = plotCost * prod(entries,years,locs,reps) + locCost * prod(years,locs) + fixedCost
meanGainxCost_r = resultLite$mean / meanGainxCost_r
# Create df with I/O data and bind this to rr from previous iterations
# rr<-rbind(rr, cbind(scenario = tail(Scenarios,1), fs_entries = i, fs_years = k, fs_locs = l, fs_reps = j, it, stage, entries, years, locs, reps, error, resultLite))
rr<-rbind(rr, cbind(scenario = tail(Ranges,1), entries, years, locs, reps, error, it, resultLite, meanGainxCost_r))
# }
}
}
}
}
})
colnames(rr) <- c("Scenario", "Entries", "Years", "Locs", "Reps", "Error", "IT", "Gain", "SD", "GainXCost")
#print(rr)
#tail(rr)
return(rr)
}
# function takes 2 vectors and returns a matrix with a grid between paired min max elements
rangeGrain <- function(min = input$range[1], max = input$range[2], grain = input$grain) {
qrt = NULL
for (i in 1:length(min)) {
if (min[i] < max[i] && grain>1) # && min[i]>entries[i+1]
{
qrt = c(qrt, round(seq(min[i], max[i], by = (max[i]-min[i])/(grain-1))))
}
else qrt = c(qrt, min(min[i], max[1]))
}
return(qrt)
}
# function corrects min_entries if found smaller than entries of second stage
checkMinEntries <- function(entries, min_entries) {
if (length(entries)>1)
{
if (min_entries < entries[2])
min_entries <- entries[2]
}
return(min_entries)
}
# function that creates a pop-up message and halts execution if entries vector is not in descending order
validInput <- function(scenarioDT = yti$data) {
entries = scenarioDT[,2]
if (is.unsorted(rev(entries)))
return(FALSE)
return(TRUE)
}
# function that checks if varieties is smaller than Entries in last stage and smaller than min_entries in range
validVarieties <- function(scenarioDT = yti$data, varieties = as.numeric(yti$varieties[1,2])) { # input$varieties) { #, min_entries = input$entries_range[1]) {
entries = scenarioDT[,2]
last_entries = tail(entries, 1)
if (varieties > last_entries )
return(FALSE)
return(TRUE)
}
# function that returns vector of the incremental mean gain per stage calculated from runScenario() result matrix
meanGain <- function(result = result) {
# first calculate aggregated mean gain for each stage
result <- round(apply(result, 1, mean), 3)
return(result)
}
# function that returns vector of the incremental mean gain per stage calculated from runScenario() result matrix
meanGainInc <- function(result = result) {
# first calculate aggregated mean gain for each stage
result <- round(apply(result, 1, mean), 2)
# replace accumulative gain with incremental gain per stage
gain <- result
if (length(gain)>1)
for (i in 2:length(gain)) {result[i] <- round(gain[i]-gain[i-1], 3)}
return(result)
}
# function that returns vector of the incremental mean gain per stage scaled by Time calculated from runScenario() result matrix
meanGainxTime <- function(result = result, scenarioDT = yti$data) {
# update contents of result with result by stage scaled by Years
for(i in 1:nrow(result))
{
result[i,] = gainTime(scenarioDT, result, i)
}
return(meanGain(result))
}
# function that returns vector of the incremental mean gain per stage scaled by Cost calculated from runScenario() result matrix
meanGainxCost <- function(result = result, scenarioDT = yti$data) {
# update contents of result with result by stage scaled by Cost
for(i in 1:nrow(result))
{
result[i,] = gainCost(scenarioDT, result, i) * 1000 # display gg per $1000
}
return(meanGain(result))
}
# function returns a summary matrix of mean genetic gain for each stage (rows) of all scenarios (cols)
meanGainSum <- function(result = rv$results_all) {
result = as.data.frame(t(result)) # transform to data frame with Stage, Value, Scenario as colnames
mtx = matrix(NA, nrow=50, ncol=tail(Scenarios,1)) # create large enough empty matrix to store all stages of the data
maxr = 1 # initialize max stages of rnows in matrix
for(i in 1:tail(Scenarios,1))
{
sc <- filter(result, Scenario == i)
for(j in 1:tail(sc$Stage, n=1))
{
st <- filter(sc, Stage == j)
mtx[j,i] <- mean(st$Value) # store mean in matrix - NOT ROUNDED !
}
if (maxr < tail(sc$Stage, n=1)) maxr <- tail(sc$Stage, n=1) # update max nrow for mtx
}
mtx <- mtx[1:maxr,, drop = FALSE] # truncate mtx at the end and avoid conversion into a vector if dim = 1.
rownames(mtx) <- c(paste0("Stage ", 1:maxr))
colnames(mtx) <- c(paste0("Scenario ", 1:ncol(mtx)))
return(mtx)
}
#********************************
#--------------------------------
# ************ PLOTS ************
# -------------------------------
#********************************
# function plots the results of a scenario
plotScenario <- function(result = result) {
boxplot(t(result),
xlab="Stage",
ylab="Mean Genetic Value")
}
# function plots the results of all scenarios
plotScenarioGroup <- function(results_all = rv$results_all, ylabel = "Gain", gtitle = "Genetic Gain by Stage") {
ggplot(as.data.frame(t(results_all)),aes(x=factor(Stage),y=Value,fill=factor(Scenario)))+
geom_boxplot()+
xlab("Stage")+
ylab(ylabel)+
scale_fill_discrete(name="Scenario")+
ggtitle(gtitle) +
theme(plot.title = element_text(size = 14, face = "bold"))
}
# Plot of mean value with margins for standard deviation (copied from alphasimrshiny)
plotMeanGrid = function(df = isolate(rv$results_range), myX = "fs_entries", myFilter = c("fs_years", "fs_locs", "fs_reps"), myXl = "First Stage Entries", title = "Gain by First Stage Entries") {
df <- transform(df, stage = as.character(stage)) # use categorical colour instead of ordered
# df <- filter(df, as.numeric(unlist(df[myFilter])) %in% df[myFilter][1,]) # filter rows not on the first occurrence (min) of myFilter
for (i in myFilter)
{
df <- filter(df, as.numeric(unlist(df[i])) %in% df[i][1,]) # filter rows not on the first occurrence (min) of myFilter
}
df <- filter(df, as.numeric(unlist(df["scenario"])) %in% df["scenario"][length(df[,1]),]) # filter rows which do not belong to the last scenario
myX <- as.numeric(unlist(df[myX]))
#print(df)
#print(sapply(df, mode))
#print(myX)
print("plotMeanGrid() called")
yMin = min(df$mean)-1.01*max(df$sd)
yMax = max(df$mean)+1.01*max(df$sd)
gp = ggplot(df,aes(x=myX,y=mean,group=stage,color=stage))+
geom_ribbon(aes(x=myX,ymin=mean-sd,ymax=mean+sd,
fill=stage),alpha=0.1,linetype=0)+
geom_line(size=1)+
guides(alpha=FALSE)+
scale_color_brewer(palette="Set1")+ #(palette="Spectral")+
scale_fill_brewer(palette="Set1")+ #(palette="Spectral")+ # palette="Set1")+
# theme_bw()+
# theme(legend.justification = c(0.02, 0.96),
# legend.background = element_blank(),
# legend.box.background = element_rect(colour = "black"),
# legend.position = c(0.02, 0.96))+
scale_x_continuous(myXl)+
scale_y_continuous("Gain",
limits=c(yMin,yMax))+
ggtitle(title)
return(gp)
}
# TODO: a 3D Surface Plot shows the effect of 2 variable ranges combined (entries and reps)
# ----
# Bubble plot instead of a 3D plot shows peaks of gain encoded with size in a grid of x = entries and y = reps
# see ggplot bug in https://stackoverflow.com/questions/34097133/passing-data-and-column-names-to-ggplot-via-another-function
plotMeanGridBubble <- function(df = isolate(rv$results_range), myFilter = c("fs_years", "fs_locs"), myX = entries, myY = reps, myXl = "First Stage Entries", myYl = "First Stage Reps", title = "Gain by Entries by Reps") {
df <- transform(df, stage = as.character(stage))
# df <- filter(df, as.numeric(unlist(df["fs_years"])) %in% df["fs_years"][1,]) # filter rows not on the first occurrence (min) of fs_years
# df <- filter(df, as.numeric(unlist(df["fs_locs"])) %in% df["fs_locs"][1,])
for (i in myFilter)
{
df <- filter(df, as.numeric(unlist(df[i])) %in% df[i][1,]) # filter rows not on the first occurrence (min) of myFilter
}
df <- filter(df, as.numeric(unlist(df["scenario"])) %in% df["scenario"][length(df[,1]),]) # filter rows which do not belong to the last scenario
arg <- match.call()
gp = ggplot(df, aes(x = eval(arg$myX), y = eval(arg$myY), color = stage))+ #,environment=environment())+
# gp = ggplot(df, aes(x=entries, y=reps, color = stage))+
geom_point(aes(size = mean, alpha=1))+
geom_point(aes(size = mean+sd, stroke = 1, alpha = 1/20))+ # SD margins shown as homocentric bubbles with lower opacity
scale_x_continuous(myXl)+
scale_y_continuous(myYl)+
ggtitle(title)
return(gp)
}
# Heatmap plot for ranges in grid
plotMeanGridHeatmap <- function(df = isolate(rv$results_range), myFilter = c("fs_years", "fs_locs"), myX = entries, myY = reps, myXl = "First Stage Entries", myYl = "First Stage Reps", title = "Gain by Entries by Reps") {
# df <- transform(df, stage = as.character(stage))
for (i in myFilter)
{
df <- filter(df, as.numeric(unlist(df[i])) %in% df[i][1,]) # filter rows not on the first occurrence (min) of myFilter
}
df <- filter(df, as.numeric(unlist(df["scenario"])) %in% df["scenario"][length(df[,1]),]) # filter rows which do not belong to the last scenario
df <- filter(df, as.numeric(unlist(df["stage"])) %in% df["stage"][1,]) # filter rows which do not belong to the first stage
arg <- match.call()
print("plotMeanGridHeatmap() called")
# Create extra column "text" for plotly tooltip
df <- df %>%
mutate(text = "tip!")# paste0("x: ", eval(arg$myX), "\n", "y: ", eval(arg$myY), "\n", "Value: ",round(mean,2)))
# Heatmap
gp = ggplot(df, aes(x = eval(arg$myX), y = eval(arg$myY)))+ #,environment=environment())+
geom_tile(aes(fill = mean)) +
scale_fill_gradient(low="white", high="blue") +
# scale_fill_distiller(palette = "RdPu") +
# theme_ipsum()
scale_x_continuous(myXl)+
scale_y_continuous(myYl)+
ggtitle(title)
gp <- ggplotly(gp, tooltip="text")
return(gp)
}
# Interactive X Y Heatmap
plotRangesHeatmap <- function(df = isolate(rv$results_range_r), param = 'Gain', myX = input$xAxis, myY = input$yAxis, myXl = input$xAxis, myYl = input$yAxis, subSel1 = input$subSel1, subSel2 = input$subSel2, title = paste("Gain by", input$xAxis, "by", input$yAxis))
{
df <- filter(df, as.numeric(unlist(df["Scenario"])) %in% df["Scenario"][length(df[,1]),]) # filter rows which do not belong to the last scenario
# more filters
myFilter = c("Entries", "Years", "Locs", "Reps")
toPlot = c(myX, myY)
# Remove toPlot elements from myFilter
myFilter = myFilter[!(myFilter %in% toPlot)]
print(myFilter)
# for (i in myFilter)
# {
# df <- filter(df, as.numeric(unlist(df[i])) %in% df[i][1,]) # filter rows not on the first occurrence (min) of myFilter
# }
subSel1 = as.numeric(subSel1)
subSel2 = as.numeric(subSel2)
print(subSel1)
print(subSel2)
df <- filter(df, as.numeric(unlist(df[myFilter[1]])) %in% subSel1) # Filter what is not selected in first dynamic selectInput subSel1
df <- filter(df, as.numeric(unlist(df[myFilter[2]])) %in% subSel2) # Filter what is not selected in second dynamic selectInput subSel2
print(df)
arg <- match.call()
# Heatmap
gp = ggplot(df, aes_string(x = eval(arg$myX), y = eval(arg$myY)))+
# geom_tile(aes(fill = Gain)) +
geom_tile(aes_string(fill = param)) +
scale_fill_gradient(low="white", high="blue") +
scale_x_continuous(myXl)+
scale_y_continuous(myYl)+
ggtitle(title)
gp <- ggplotly(gp)
return(gp)
}
# Interactive X Treatment Line Plot - - TODO
plotRangesLine <- function(df = isolate(rv$results_range_r), param = 'Gain', myX = input$xAxisLine, myT = input$treatment, myXl = input$xAxisLine, subSel3 = input$subSel3, subSel4 = input$subSel4, title = paste("Gain by", input$xAxisLine, "by", input$treatment))
{
# df <- transform(df, myT = as.character(myT)) # use categorical colour instead of ordered
tLegent = myT
df <- filter(df, as.numeric(unlist(df["Scenario"])) %in% df["Scenario"][length(df[,1]),]) # filter rows which do not belong to the last scenario
myFilter = c("Entries", "Years", "Locs", "Reps")
toPlot = c(myX, myT)
# Remove toPlot elements from myFilter
myFilter = myFilter[!(myFilter %in% toPlot)]
print(myFilter)
# for (i in myFilter)
# {
# df <- filter(df, as.numeric(unlist(df[i])) %in% df[i][1,]) # filter rows not on the first occurrence (min) of myFilter
# }
subSel3 = as.numeric(subSel3)
subSel4 = as.numeric(subSel4)
print(subSel3)
print(subSel4)
df <- filter(df, as.numeric(unlist(df[myFilter[1]])) %in% subSel3) # Filter what is not selected in first dynamic selectInput subSel1
df <- filter(df, as.numeric(unlist(df[myFilter[2]])) %in% subSel4) # Filter what is not selected in second dynamic selectInput subSel2
print(df)
myX <- as.numeric(unlist(df[myX]))
myT <- as.factor(unlist(df[myT]))
#print(df)
#print(sapply(df, mode))
#print(myX)
print("plotRangesLine() called")
print(df$SD)
yMin = min(df$Gain)-1.01*max(df$SD)
yMax = max(df$Gain)+1.01*max(df$SD)
# yMin = min(df[[param]])-1.01*max(df$SD)
# yMax = max(df[[param]])+1.01*max(df$SD)
gp = ggplot(df,aes(x=myX,y=Gain,group=myT,color=myT))+
# gp = ggplot(df,aes_string(x=myX,y=param,group=myT,color=myT))+
geom_ribbon(aes(x=myX,ymin=Gain-SD,ymax=Gain+SD,
fill=myT),alpha=0.1,linetype=0)+
geom_line(size=1)+
guides(alpha=FALSE)+
scale_color_brewer(palette="Set1")+ #(palette="Spectral")+
scale_fill_brewer(palette="Set1")+ #(palette="Spectral")+ # palette="Set1")+
# theme_bw()+
# theme(legend.justification = c(0.02, 0.96),
# legend.background = element_blank(),
# legend.box.background = element_rect(colour = "black"),
# legend.position = c(0.02, 0.96))+
scale_x_continuous(myXl)+
scale_y_continuous("Gain",
# scale_y_continuous(param,
limits=c(yMin,yMax))+
labs(colour = tLegent, fill = tLegent)
ggtitle(title)
#gp <- ggplotly(gp)
return(gp)
}
#*************************************
#-------------------------------------
# ************* RENDERERS ************
# ------------------------------------
#*************************************
# Render stages DT with default data entries
output$stages_table = DT::renderDT(yti$data,
options = list(
dom = 't', # only display the table, and nothing else
# searching = F, # no search box
# paginate = F, # no num of pages
# lengthChange = F, # no show entries
scrollX = T, # horizontal slider
ordering = F # suppressing sorting
),
class = "cell-border, compact, hover",
rownames = F, #TRUE,
colnames = c('Stage', 'Entries', 'Years', 'Locs', 'Reps', 'Plot Error Variance', toString(withMathJax('$$h^2$$')), 'Plot Cost($)', 'Loc Cost($)', 'Fixed Cost($)'), # 'Selected Parents'),
filter = "none",
escape = FALSE,
autoHideNavigation = TRUE,
selection = "none",
editable = list(target = "cell", disable = list(columns = c(0, 6))),
server = TRUE) # server = F doesn't work with replaceData() cell editing
# Render a DT table with total costs (Years, Locs, Plots) calculated based on stages input
output$cost_table = DT::renderDT(cbind(totalYears(yti$data), totalLocs(yti$data), totalPlots(yti$data), totalLocsCost(yti$data), totalPlotsCost(yti$data), totalCost(yti$data)),
options = list(
dom = 't', # only display the table, and nothing else
# searching = F, # no search box
# paginate = F, # no num of pages
# lengthChange = F, # no show entries
scrollX = T, # horizontal slider
ordering = F # suppressing sorting