-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.R
More file actions
1628 lines (1372 loc) · 91.3 KB
/
app.R
File metadata and controls
1628 lines (1372 loc) · 91.3 KB
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
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#TrapSim Tool - Multi Method - now developed for NSC project
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Code developed by Andrew Gormley, Manaaki Whenua - Landcare Research
#Originally developed for the NSC Eco-economics project and CISS
#Updated for Margaret etc
library("shiny")
library("shinythemes")
library("leaflet")
library("maptools")
library("spatstat") #For the owin command...and for runifpoint
library("RColorBrewer")
library("leaflet")
library("rgdal")
library("rgeos")
library("proxy")
library("sf")
library("raster")
library("DT")
library("shinyvalidate")
library("dplyr")
library("shinycssloaders")
# library("shinyalert")
# setwd("C:\\Users\\gormleya\\OneDrive - MWLR\\Documents\\CAEM\\IslandConservation\\TrapSimFeasibility\\Shiny")
def.shp<-"WhakatipuMahia"
# cols.tst<-brewer.pal(6,"Blues")
cols.vec<-brewer.pal(8,"Paired")
cols.eff<-brewer.pal(8,"Reds")
proj4string <- "+proj=tmerc +lat_0=0.0 +lon_0=173.0 +k=0.9996 +x_0=1600000.0 +y_0=10000000.0 +datum=WGS84 +units=m"
#4326 is the EPSG for WGS84...
trap_lut<-read.csv("data//trap_lut.csv", stringsAsFactors = FALSE)
#~~~~~~~~~~~~~~~ A bunch of functions ~~~~~~~~~~~~~~~~~~~~~~~~
#Define the resampling function
resamp <- function(x,...){if(length(x)==1) x else sample(x,...)}
#~~~~~~~~~~~~~~~~COST FUNCTIONS~~~~~~~~~~~~~
#Calculate the cost of trapping
trap.cost.func<-function(a,b,c,d,e){
#e.g. trap.cost.func(a=number of checks, b=n.traps, c=input$traps.per.day, d=input$day.rate,e=cost.per.trap)
fixed.cost<-b*e #n.traps x cost.per.trap
labor.cost<-ceiling(2*b/c)/2*a*d #- scales up to a half day, mostly works
trap.cost<-as.integer(labor.cost+fixed.cost)
# trap.cost<-as.integer((((b*checks)/c)*d)+(b*e))
return(trap.cost)
}
# bait.cost.a
#Cost of bait-stations
bait.cost.func<-function(a,b,c,d,e,f){
#e.g. trap.cost.func(a=number of checks, b=n.traps, c=input$traps.per.day, d=input$day.rate, e=cost.per.trap, fbait cost per station per day)
fixed.cost<-b*e #n.traps x cost.per.trap
bait.cost<-b*a*f
labor.cost<-ceiling(2*b/c)/2*a*d #- scales up to a half day, mostly works
trap.cost<-as.integer(labor.cost+fixed.cost+bait.cost)
# trap.cost<-as.integer((((b*checks)/c)*d)+(b*e))
return(trap.cost)
}
#For a given mean/sd, calculate the alpha & beta parameters
get.alpha.beta<-function(g0.mean, g0.sd){
g0.var<-g0.sd^2
paren<- (g0.var + g0.mean^2 - g0.mean)
alpha<- -g0.mean*paren/g0.var
beta<- paren*(g0.mean-1)/g0.var
return(list(alpha=alpha, beta=beta))
}
#For a given mean/sd, calculate the location and shape parameters for a log-normal distribution
get.loc.shape<-function(sigma.mean, sigma.sd){
m<-sigma.mean
s<-sigma.sd
location <- log(m^2 / sqrt(s^2 + m^2))
shape <- sqrt(log(1 + (s^2 / m^2)))
return(list(location=location, shape=shape))
}
#Function to make animal locations from a raster of relative abundance/habitat.
# Takes the raster, the number of possums and the shapefile
get.pest.locs<-function(ras, n.poss, shp){
#
buff<-n.poss*5
# Get the celll resolution
res.x<-res(ras)[1]
res.y<-res(ras)[1]
df <- as.data.frame(ras, xy = T, na.rm = T)
# sampled_cells <- sample(1:nrow(df), size = n.poss+buff, prob = df$habitat_specific, replace = T)
sampled_cells <- sample(1:nrow(df), size = n.poss+buff, prob = df[,3], replace = T)
x.val<-df$x[(sampled_cells)]+res.x*(runif(n.poss+buff)-0.5)
y.val<-df$y[(sampled_cells)]+res.y*(runif(n.poss+buff)-0.5)
coords<-data.frame('x'=x.val, 'y'=y.val)
coords<-coords[inside.owin(coords[,1], coords[,2], shp),] #Remove the ones from outside the shapefile...
# coords<-coords[sample(1:dim(coords)[1], size=n.poss, replace=FALSE),] #Then sample to get the desired actual sample size
if(dim(coords)[1]>0){
coords<-coords[sample(1:dim(coords)[1], size=n.poss, replace=FALSE),] #Then sample to get the desired actual sample size
}else{
showModal(modalDialog(
title = "Error","Raster and shapefile do not overlap.",easyClose = TRUE, fade=FALSE, size="s",
footer = modalButton("OK")
))
validate(need(dim(coords)[1]>0,"Raster does not overlap with the shapefile"))
}
return(coords)
}
# Make the trap locations from a x/y spacing, buffer and shapefile - and if supplied, a masking raster of 0/1
make.trap.locs<-function(x.space,y.space,buff,shp, ras=NULL){
b.box<-bbox(shp)
traps.x<-seq(from=b.box[1,1], by=x.space, to=b.box[1,2])
traps.y<-seq(from=b.box[2,1], by=y.space, to=b.box[2,2])
traps<-as.data.frame((expand.grid(traps.x, traps.y)))
colnames(traps)<-c("X","Y")
shp.buff<-gBuffer(shp,width=-buff) #Buffer in from the shapefuile edge
#Remove traps that are outside the window,,,
traps<-traps[inside.owin(traps[,1], traps[,2], shp.buff),]
if(is.null(ras)){
}else{
cell.trap<-which(values(ras)%in%1) #Which cells are in the raster mask
cell.idx<-cellFromXY(ras,traps) #which raster cells are the traps in...?
traps<-traps[which(cell.idx%in%cell.trap),]
}
return(traps)
}
#Error handling for Delete buttons
modal_confirm_2 <- modalDialog(
"Are you sure you want to continue?",
title = "This will delete all scenarios",
footer = tagList(
actionButton("ok_all_scen", "Delete", class = "btn btn-danger"),
actionButton("cancel", "Cancel")
)
)
modal_confirm_1 <- modalDialog(
"Are you sure you want to continue?",
title = "This will delete selected scenarios",
footer = tagList(
actionButton("ok_sel_scen", "Delete", class = "btn btn-danger"),
actionButton("cancel", "Cancel")
)
)
#~~~~~~~~~~~~~~~~~ End functions ~~~~~~~~~~~~~~~~~~~~~~
server<-function(input, output, session) {
iv <- InputValidator$new()
iv$add_rule("scenname", sv_required())
iv$add_rule("numb.poss.1", sv_required())
iv$add_rule("numb.poss.2", sv_required())
iv$enable()
#~~~~~~ Set up the scenarios
scenParam <- reactiveVal() #Can't recall why needed..
#Event to delete all scenarios when the Delete All Rows is pressed
observeEvent(input$deleteAllRows,{
showModal(modal_confirm_2)
})
observeEvent(input$ok_all_scen, { #When OK is pressed - remove em all
t<-scenParam()
t <- t[-(1:dim(t)[1]),]
scenParam(t)
removeModal()
})
#Event to delete selected scenarios when Delete Selected Rows is pressed
observeEvent(input$deleteRows,{
showModal(modal_confirm_1)
})
observeEvent(input$ok_sel_scen, { #When OK is pressed - remove the selected
t<-scenParam()
if (!is.null(input$tableDT_rows_selected)) {
t <- t[-as.numeric(input$tableDT_rows_selected),]
rownames(t)<-1:dim(t)[1]
}
scenParam(t)
removeModal()
})
#Close the modal - Cancel button is same for both
observeEvent(input$cancel, {
removeModal()
})
#When the dropdown is selected, update the numericInputs
observeEvent(input$trap_type,{
updateNumericInput(session, "g0.mean.a", value=trap_lut$g0_poss[trap_lut$Device == input$trap_type])
updateNumericInput(session, "max.catch.a", value=trap_lut$Max[trap_lut$Device == input$trap_type])
updateNumericInput(session, "cost.per.trap.a", value=trap_lut$Cost[trap_lut$Device == input$trap_type])
})
#Code to add a scenario when the Add Scenario button is pressed - with error handling
observeEvent(input$update,{
shp<-mydata.shp()$shp
if(input$scenname==""){
showModal(modalDialog(
title = "Error","Add a scenario name",easyClose = TRUE, fade=FALSE, size="s",
footer = modalButton("OK")
))
}
validate(need(!input$scenname=="", "Provide a scenario name"))
scen.name=input$scenname
#~~~ Trapping ~~~
trap.name = NA
x.space.a = NA
y.space.a = NA
trap.start.a = NA
trap.nights.a = NA
check.interval.a = NA
g.mean.a=NA
g.zero.a=NA #This is the proportion that is untrappable, not g0....
trap.mask=NA
trap.max=NA
trap.cost=0
#~~~ Bait Stations ~~~
bait.start.a = NA
bait.nights.a = NA
bait.check.a = NA
bait.x.space.a = NA
bait.y.space.a = NA
bait.g.mean.a = NA
bait.g.zero.a = NA
bait.mask = NA
bait.cost = 0
#Add the trap stuff
if(input$trap_methods==1){
trap.name=input$trap_type
x.space.a = input$traps.x.space.a
y.space.a = input$traps.y.space.a
trap.start.a = input$trap.start.a
trap.nights.a = input$trap.nights.a
check.interval.a = input$n.check.a
g.mean.a=input$g0.mean.a
# g.mean.a=trap_lut$g0_poss[trap_lut$Device == input$trap_type]
g.zero.a=input$g0.zero.a
if(input$trap_mask==1){ #Work out the trapped area and save the file path to the raster that will be used.
trap.mask = mydata.trap()$myraster
}
trap.max=input$max.catch.a
checks<-ceiling(input$trap.nights.a/input$n.check.a)+1
n.traps.a<-dim(make.trap.locs(x.space.a, y.space.a, 100, shp))[1]
trap.cost=trap.cost.func(a=checks, b=n.traps.a, c=input$traps.per.day.a, d=input$day.rate.a, e=input$cost.per.trap.a)
}
if(input$bait_methods==1){
bait.start.a = input$bait.start.a
bait.nights.a = input$bait.nights.a
bait.check.a = input$bait.check.a
bait.x.space.a = input$bait.x.space.a
bait.y.space.a = input$bait.y.space.a
bait.g.mean.a = input$bait.g0.mean.a
bait.g.zero.a = input$bait.g.zero.a
if(input$bait_mask==1){ #Work out the trapped area and save the file path to the raster that will be used.
bait.mask = mydata.bait()$myraster
}
checks<-ceiling(input$bait.nights.a/input$bait.check.a)+1
n.bait.a<-dim(make.trap.locs(bait.x.space.a, bait.y.space.a, 100, shp))[1]
bait.cost<-bait.cost.func(a=checks, b=n.bait.a, c=input$bait.per.day.a, d=input$bait.day.rate.a, e=input$cost.per.bait.a, f=input$bait.cost.a)
}
#The letter codes used to help build up the 'Methods' part of the scenario names
scen.code = ""
if(input$trap_methods==1){
scen.code<-paste0(scen.code,"T") #trapping
}
if(input$bait_methods==1){
scen.code<-paste0(scen.code,"B") #baiting
}
#Full scenario to add.
to_add <- data.frame(
scen.name = scen.name,
trap.name = trap.name,
x.space.a = x.space.a,
y.space.a = y.space.a,
trap.start.a = trap.start.a,
trap.nights.a = trap.nights.a,
check.interval.a = check.interval.a,
g.mean.a=g.mean.a,
g.zero.a=g.zero.a,
trap.mask=trap.mask,
trap.max=trap.max,
bait.start.a = bait.start.a,
bait.nights.a = bait.nights.a,
bait.check.a = bait.check.a,
bait.x.space.a = bait.x.space.a,
bait.y.space.a = bait.y.space.a,
bait.g.mean.a = bait.g.mean.a,
bait.g.zero.a = bait.g.zero.a,
bait.mask = bait.mask,
trap.cost=trap.cost,
bait.cost=bait.cost,
methods = scen.code
)
newScenParam <- rbind(scenParam(),to_add) # adding new data
scenParam(newScenParam) # updating data
#Test for duplicates and blank scenarios
t<-scenParam()
if(sum(duplicated(t[,2:21]))==1){
t<-t[!duplicated(t[,2:21]), ] #Dont add duplicates
showModal(modalDialog(
title = "Error: Duplicate scenario!","This control scenario has already been added",easyClose = TRUE, fade=FALSE, size="s",
footer = modalButton("Cancel", icon=icon("exclamation"))
))
}else if (sum(rowSums(is.na(t))==dim(t)[2]-2)==1){
t<-t[!rowSums(is.na(t))==dim(t)[2]-2,] #Dont add blank scenarios
showModal(modalDialog(
title = "Error: Blank scenario!","No control methods were selected",easyClose = TRUE, fade=FALSE, size="s",
footer = modalButton("Cancel", icon=icon("exclamation"))
))
}else{#Use a showNotification rather than a popup modal
showNotification(paste0(input$scenname," added"), type="message", duration=1)
id<-dim((t))[1]+1
updateTextInput(session,"scenname", "Scenario name", value=sprintf("S%03d", id))
}
scenParam(t)
return(list(scenParam=scenParam))
})
#Read in the trapping mask. And output the raster as well as the path to it.
mydata.trap<-reactive({
if(input$trap_mask==1){
if(is.null(input$trap_asc)==FALSE){
myraster<-input$trap_asc$datapath #basename for filename, dirname
ras.trap<-raster(myraster)
}}
return(list(ras.trap=ras.trap, myraster=myraster))
})
#Read in the bait station mask. And output the raster as well as the path to it.
mydata.bait<-reactive({
if(input$bait_mask==1){
if(is.null(input$bait_asc)==FALSE){
myraster<-input$bait_asc$datapath #basename for filename, dirname
ras.bait<-raster(myraster)
}}
return(list(ras.bait=ras.bait, myraster=myraster))
})
#Read in the habitat mask
mydata.habitat<-reactive({
if(input$ras_hab=='Hab'){
if(is.null(input$habitat_asc)==FALSE){
myraster<-input$habitat_asc$datapath
ras.habitat<-raster(myraster)
}}
return(list(ras.habitat=ras.habitat, myraster=myraster))
})
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Read in the main shapefile - default has it loaded with Mahia (area_type=RC)
mydata.shp<-reactive({
#1. The default shape - Mahia Peninsula - defined at the very top
shp<-readOGR("Shapefiles",def.shp)
proj4string<-crs(shp)
if(input$area_type=="MP"){
shp<-readOGR("Shapefiles",def.shp)
}
#2. 'Upload Shapefile, then read in all the components,
if(input$area_type=="Map"){
if(is.null(input$shp.file)==FALSE){
myshape<-input$shp.file
if(nrow(myshape)==1){ #zipped files
dir<- dirname(myshape$datapath[1])
unzip(myshape$datapath, exdir = dir)
}else{
dir<-dirname(myshape[1,4])
for ( i in 1:nrow(myshape)) {
file.rename(myshape[i,4], paste0(dir,"/",myshape[i,1]))
}}
getshp <- list.files(dir, pattern="*.shp", full.names=TRUE)
shp<-readOGR(getshp)
}
}
proj4string<-crs(shp) #get the proj string from the shapefile itself
shp<-gBuffer(shp, width=1) #Can fix some orphaned holes issues
ha<-sapply(slot(shp, "polygons"), slot, "area")/10000
return(list(shp=shp, p4s=proj4string, ha=ha))
})
# Make the traps and animals on the interactive map. Not linked to the actual simulation
mydata.map<-reactive({
shp<-mydata.shp()$shp
traps.x.space<-as.numeric(input$traps.x.space.i)
traps.y.space<-as.numeric(input$traps.y.space.i)
buff<-as.numeric(input$traps.buff.i)
traps<-make.trap.locs(traps.x.space, traps.y.space, buff, shp)
#Temporary pest animal coordinates...
n.poss<-input$numb.poss.1#.i
if(is.na(n.poss)){
n.poss<-0
}
#Temporary commented out.
# if(is.null(input$ras.1)==TRUE){
if((input$ras_hab)=="Ran"){
#1. Random locations.
n.poss.tmp<-(runifpoint(n.poss,shp))
animals.xy.ini<-as.data.frame(n.poss.tmp)
}else{
#2. Grid specific densities
#Call the function
validate(need(input$habitat_asc !="","Upload a habitat raster"))
# need(input$traps.x.space.a != "", "Please enter a value for the X trap spacing"),
ras.habitat<-raster(mydata.habitat()$myraster)
shp.buff<-gBuffer(shp, width=100)
ras.habitat<-crop(ras.habitat, shp.buff)
animals.xy.ini<-get.pest.locs(ras.habitat, n.poss, shp)
}
colnames(animals.xy.ini)<-c("X","Y")
return(list(traps=traps, animals.xy.ini=animals.xy.ini))
})
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~ Now simulate the actual trapping...~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#When the simulations get set to run, automatically switch to the results tab. Noice!
observeEvent(input$act.btn.trapsim,{
updateTabsetPanel(session, "inTabset", selected = '4')#"4. Results")
})
#After pushing the RunTrapSim button,...
datab<-eventReactive(input$act.btn.trapsim,{
buffer<-100 #A single buffer
#Some validation stuff - need to fill this out more completely. - actually this wont work - now that we make a table of scenarios...
validate(
# need(input$traps.buff.a != "", "Please enter a value for the trap buffer"),
need(input$traps.x.space.a != "", "Please enter a value for the X trap spacing"),
need(input$traps.y.space.a != "", "Please enter a value for the Y trap spacing"),
need(input$n.nights != "", "Please enter a value for the number of Nights"),
need(input$n.check.a != "", "Please enter a value for the Check interval"),
need(input$p.bycatch.a != "", "Please enter a value for the Daily bycatch rate"),
need(input$max.catch.a != "", "Please enter a value for the prob of Max catch"),
need(input$numb.poss.1 != "", "Please enter a value for the min number of animals "),
need(input$numb.poss.2 != "", "Please enter a value for the max number of animals ")
)
#Read in all the parameter values for the scenarios
params<-as.data.frame(scenParam())
#Set up some places to store results
n.scen<-dim(params)[1]
pop.size.list<-vector("list",n.scen)
trap.catch.list<-vector("list",n.scen)
# hunt.catch.list<-vector("list",n.scen)
bait.catch.list<-vector("list",n.scen)
# pois.catch.list<-vector("list",n.scen)
# pop.size.zone.mat[[ii]][,t+1]
withProgress(message="Running simulation ",value=0,{
#Go through the scenarios one by one...
for(kk in 1:n.scen){ #For each scenario...
incProgress(kk/n.scen, detail = paste("Doing scenario ", kk," of", n.scen))
#Pass the parameters from params to a parameter name that will be used..
# Traps
trap.start.a<-params$trap.start.a[kk]
trap.nights.a<-params$trap.nights.a[kk]
n.check.a<-params$check.interval.a[kk]
x.space.a<-params$x.space.a[kk]
y.space.a<-params$y.space.a[kk]
buffer.a<-buffer
g0.mean.a<-params$g.mean.a[kk]
g.zero.a<-params$g.zero.a[kk]
trap.mask<-params$trap.mask[kk]
trap.max<-params$trap.max[kk]
#Bait
bait.start.a<-params$bait.start.a[kk]
bait.nights.a<-params$bait.nights.a[kk]
bait.check.a<-params$bait.check.a[kk]
bait.x.space.a<-params$bait.x.space.a[kk]
bait.y.space.a<-params$bait.y.space.a[kk]
bait.buff.a<-buffer
bait.g0.mean.a<-params$bait.g.mean.a[kk]
bait.g.zero.a<- params$bait.g.zero.a[kk]
bait.mask<-params$bait.mask[kk]
#How long to run the simulation for.
n.nights<-input$n.nights
# #The g0 uncertainty, and sigma values for traps and bait. The sds are not in params - but should be!!
# g0.sd.a<-input$g0.sd.a
# bait.g0.sd.a<-input$bait.g0.sd.a
g0.sd.a<-0.001
bait.g0.sd.a<-0.001
hr.ha<-input$hr.ha
sigma.mean<-sqrt(hr.ha*10000/pi)/2.45
sigma.sd<-sigma.mean/20
# sigma.mean<-input$sigma.mean
# sigma.sd<-input$sigma.sd
# rmax.poss<-input$rmax.poss
ann.growth.poss<-input$ann.growth.poss
K.poss<-10 #input$K.poss
#When the reproductive period starts and how long it lasts (i.e. spread out over...)
rep.start<-input$rep.start
rep.nights<-input$rep.nights
rep.tmp<-seq(from=rep.start, by=1, to=(rep.nights+rep.start-1))
aa<-ceiling(n.nights/365) #basically the number of years
bb<-((1:aa)-1)*365
repro.interval<-rep(rep.tmp,aa)+rep(bb, each=rep.nights)
rep.start.vec<-(bb+rep.start)
ha<-mydata.shp()$ha
shp<-mydata.shp()$shp
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Make the trap & bait station locations
if(is.na(trap.start.a)==FALSE){
if(is.na(trap.mask)==TRUE){
traps.a<-make.trap.locs(x.space.a, y.space.a,buffer.a,shp)
}else{
traps.a<-make.trap.locs(x.space.a, y.space.a,buffer.a,shp, ras=raster(trap.mask))
}
coordinates(traps.a) <- c( "X", "Y" )
proj4string(traps.a) <- CRS(proj4string)
traps.xy.a<-as.data.frame(traps.a)
n.traps.a<-dim(traps.xy.a)[1]
}
#Make the bait station locations
if(is.na(bait.start.a)==FALSE){
if(is.na(bait.mask)==TRUE){
baits.a<-make.trap.locs(bait.x.space.a, bait.y.space.a, bait.buff.a, shp)
}else{
baits.a<-make.trap.locs(bait.x.space.a, bait.y.space.a, bait.buff.a, shp, ras=raster(bait.mask))
# traps.a<-make.trap.locs(x.space.a, y.space.a,buffer.a,shp, ras=raster(trap.mask))
}
coordinates(baits.a) <- c( "X", "Y" )
proj4string(baits.a) <- CRS(proj4string)
baits.xy.a<-as.data.frame(baits.a)
n.baits.a<-dim(baits.xy.a)[1]
}
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# When we have traps//baits etc, then calculate the interval and the checking interval and bycatch/failure
#for the traps and the bait stations
if(is.na(trap.start.a)==FALSE){
trap.period.a<-seq(from=trap.start.a, to=(trap.start.a+trap.nights.a-1), by=1)
# #This sets the trap checking interval. i.e. traps are cleared and reset on these nights only...
check.vec.a<-seq(from=trap.start.a, to=(trap.start.a+trap.nights.a), by=n.check.a)
p.bycatch.a<-input$p.bycatch.a
}
if(is.na(bait.start.a)==FALSE){
bait.period.a<-seq(from=bait.start.a, to=(bait.start.a+bait.nights.a-1), by=1)
# #This sets the checking interval. - cleared and reset on these nights only...
bait.check.vec.a<-seq(from=bait.start.a, to=(bait.start.a+bait.nights.a), by=bait.check.a)
p.failure.a<-0#input$p.bycatch.a
}
#Carrying capacity for the area in terms of total number of animals - should be grid based?
K.tot<-K.poss*ha
n.poss.in.1<-input$numb.poss.1 #- should this be a parameter...? Or better to leave - maybe leave cause can re-run with same params.
n.poss.in.2<-input$numb.poss.2 #- should this be a parameter...? Or better to leave - maybe leave cause can re-run with same params.
if(is.na(n.poss.in.1)){
n.poss<-0
}
max.catch.a<-trap.max#input$max.catch.a
#~~~~Calculate the costs~~~~
trap.cost.sim<-params$trap.cost[kk]
bait.cost.sim<-params$bait.cost[kk]
# if(is.na(bait.start.a)==FALSE){
# checks<-ceiling(input$bait.nights.a/input$bait.check.a)+1
# # bait.cost.sim<-trap.cost.func(a=bait.check.vec.a, b=n.baits.a, c=input$bait.per.day.a, d=input$bait.day.rate.a, e=input$cost.per.bait.a)
# bait.cost.sim<-bait.cost.func(a=checks, b=n.baits.a, c=input$bait.per.day.a, d=input$bait.day.rate.a, e=input$cost.per.bait.a, f=input$bait.cost.a)
# }
n_its<-input$n.its #Number of iterations
pop.size.mat<-matrix(NA,nrow=n_its,ncol=n.nights+1)
trap.catch.mat<-matrix(NA,nrow=n_its,ncol=n.nights) #To keep track of trapping - for each iteration - how many that night/day
bait.catch.mat<-matrix(NA,nrow=n_its,ncol=n.nights) #To keep track of baiting - for each iteration - how many that night/day
n.poss.vec<-floor(runif(n_its, min=n.poss.in.1, max=n.poss.in.2))
for(ii in 1:n_its){
n.poss<-n.poss.vec[ii]
pop.size.mat[ii,1]<-n.poss
#~~~~~~~~~Make some animals~~~~~~~~~~
if((input$ras_hab)=="Ran"){
#1. Random locations.
n.poss.tmp<-(runifpoint(n.poss,shp))
animals.xy<-as.data.frame(n.poss.tmp)
}else{
#2. Grid specific densities
ras.habitat<-raster(mydata.habitat()$myraster)
shp.buff<-gBuffer(shp, width=100)
ras.habitat<-crop(ras.habitat, shp.buff)
animals.xy<-get.pest.locs(ras.habitat, n.poss, shp)
}
colnames(animals.xy)<-c("X","Y")
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
n.animals<-dim(animals.xy)[1]
animals.xy$Dead<-0
coordinates(animals.xy) <- ~ X+Y
proj4string(animals.xy) <- proj4string(shp)
#Calculate the g0 values...
#g0 for traps
if(is.na(trap.start.a)==FALSE){
alpbet.a<-get.alpha.beta(g0.mean.a, g0.sd.a)
animals.xy$g0.a<-rbeta(n.animals, alpbet.a$alpha, alpbet.a$beta)
animals.xy$g0.a[animals.xy$g0.a<0]<-0 #Probably not needed
animals.xy$g0.a[sample(x=n.animals,size=round(n.animals*g.zero.a),replace=F)]<-0 #Make some of the g0 values zero - untrappable animals...
}else{
animals.xy$g0.a<-0
}
#g0 for bait stations
if(is.na(bait.start.a)==FALSE){
alpbet.bait<-get.alpha.beta(bait.g0.mean.a, bait.g0.sd.a)
animals.xy$g0.bait<-rbeta(n.animals, alpbet.bait$alpha, alpbet.bait$beta)
animals.xy$g0.bait[animals.xy$g0.bait<0]<-0 #Probably not needed
animals.xy$g0.bait[sample(x=n.animals,size=round(n.animals*bait.g.zero.a),replace=F)]<-0
# if(is.na(g.zero.b)==FALSE){
# animals.xy$g0.b[sample(x=n.animals,size=round(n.animals*g.zero.b),replace=F)]<-0
# }
}else{
animals.xy$g0.bait<-0
}
locshp<-get.loc.shape(sigma.mean, sigma.sd)
animals.xy$Sigma<-rlnorm(n.animals ,meanlog=locshp$location, sdlog=locshp$shape)
if(is.na(trap.start.a)==FALSE){
dist2.xy.a<-matrix(NA,n.traps.a,n.animals)
prob.xy.a<-matrix(0,n.traps.a,n.animals)
dist.xy.a<-dist(as.data.frame(traps.xy.a), as.data.frame(animals.xy)[,1:2], method="euclidean") #Distance (not squared) - faster than using outer
prob.xy.a<-exp(-(dist.xy.a^2)/(2*animals.xy$Sigma^2))*animals.xy$g0.a #Use the g0u for sampling...
rm(dist.xy.a)
}
#Bait stations
if(is.na(bait.start.a)==FALSE){
dist2.xy.c<-matrix(NA,n.baits.a,n.animals)
prob.xy.c<-matrix(0,n.baits.a,n.animals)
dist.xy.c<-dist(as.data.frame(baits.xy.a), as.data.frame(animals.xy)[,1:2], method="euclidean") #Distance (not squared) - faster than using outer
prob.xy.c<-exp(-(dist.xy.c^2)/(2*animals.xy$Sigma^2))*animals.xy$g0.bait #Use the g0u for sampling...
rm(dist.xy.c)
}
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~Now run the simulation of trapping the animals...
# withProgress(message="Running Simulation",value=0,{
#Set up some storage matrices
trap.catch.vec<-rep(0, n.nights)
if(is.na(trap.start.a)==FALSE){
trap.catch.a<-matrix(0,n.traps.a,n.nights) #Trap.catch stores the captures in each trap each night
trap.remain.a<-rep(max.catch.a, n.traps.a)
}
if(is.na(bait.start.a)==FALSE){
bait.catch.a<-matrix(0,n.baits.a,n.nights) #Trap.catch stores the captures in each trap each night
# bait.remain.a<-rep(max.catch.b, n.traps.b)
}
for (t in 1:n.nights){ #For each night
not.caught<-(1:n.animals)[animals.xy$Dead==0] #Animals not already caught
if(is.na(trap.start.a)==FALSE){
if(t%in%trap.period.a==TRUE){
if(t%in%check.vec.a==TRUE){#If it is a trap clearance day...then reset the traps to T *before* trappig starts!
# trap.remain<-rep(T,n.traps)
trap.remain.a<-rep(max.catch.a,n.traps.a)
# if (sim_type=='grid'){
# grid.traps<-grid.traps.master
# }
}
#Turn off some of the traps according to the random probability
# trap.remain[rbinom(n.traps,1, p.bycatch)==1]<-FALSE #Nedd to only turn off those that are on...Might be okay...
trap.remain.a<-trap.remain.a-rbinom(n.traps.a, trap.remain.a, p.bycatch.a) #This modifcation deals with multiple capture traps
trap.remain.a[trap.remain.a<0]<-0
if(sum(not.caught)>0){
for (j in not.caught){ #For each animal not already caught
#New code based on Multinomial (from Dean...
prob.tmp<-prob.xy.a[,j]*(trap.remain.a>0) #Adjust the probabilities with trap.remain so previous traps cannot catch anything
cumulative.capture.prob<-1-prod(1-prob.tmp) #Cumulative probability of possum i getting captured
if(rbinom(1,1,prob=cumulative.capture.prob)==1){#If the animal is going to get caught...
trap.id<-match(1,rmultinom(1,1,prob.tmp))#Which was the successful trap...
trap.catch.a[trap.id,t]<-trap.catch.a[trap.id,t]+1
# trap.animals[j]<-1 #Set trapped animal to 1
animals.xy$Dead[j]<-1
# animals.xy$Day2[j]<-t
# trap.remain[trap.id]<-(trap.catch[trap.id,t]<max.catch) #Calculate whether the trap is full or not!!
trap.remain.a[trap.id]<-trap.remain.a[trap.id]-1
}
}
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Module for immigration to go in here...
}
} #End of if t %in% trap.period
}
#Now do some baiting....
if(is.na(bait.start.a)==FALSE){
if(t%in%bait.period.a==TRUE){
if(sum(not.caught)>0){
for (j in not.caught){ #For each animal not already caught
#New code based on Multinomial (from Dean...
prob.tmp<-prob.xy.c[,j]#*(trap.remain.b>0) #Adjust the probabilities with trap.remain so previous traps cannot catch anything
cumulative.capture.prob<-1-prod(1-prob.tmp) #Cumulative probability of possum i getting captured
if(rbinom(1,1,prob=cumulative.capture.prob)==1){#If the animal is going to get caught...
trap.id<-match(1,rmultinom(1,1,prob.tmp))#Which was the successful trap...
bait.catch.a[trap.id,t]<-bait.catch.a[trap.id,t]+1
animals.xy$Dead[j]<-1
}
}
}
} #End of if t %in% trap.period
}
#~~~~~~~~~~~~~~~~~~~~~Reproduction~~~~~~~~~~~~~~~~~~~~~~~~~
#Get the reproductive vector when we hit the start of the interval...
#If t is one of the start days of the breeding season...
if(t%in%rep.start.vec){
#Discrete version of rmax
# rd<-exp(rmax.poss)-1
rd<-ann.growth.poss/100
N0<-sum(animals.xy$Dead==0) #Current population
K<-K.tot
new.animals<-rd*N0*((K-N0)/K)#Number of new animals
mu.animals<-new.animals/rep.nights #new animals per night
if(mu.animals>0){ #Draw animals when mu is positive
new.animal.vec<-(rpois(rep.nights, lambda=mu.animals))
new.animal.vec[(N0+cumsum(new.animal.vec))>(K*1.1)]<-0
}else{
new.animal.vec<-rep(0,rep.nights) #new animals is 0 when mu is negative
}
yr<-match(t, rep.start.vec) #What year are we in...?
}
if(t%in%repro.interval==TRUE){
#Get the index from the number of new animals
t.idx<-t-(365*(yr-1)) #TO adjust for multi years
N.new<-new.animal.vec[match(t.idx,repro.interval)]
if(N.new>0){
#Make the new locations randomly...
# if(is.null(input$ras.1)==TRUE){
if((input$ras_hab)=="Ran"){
#1. Random locations.
new.animals.xy<-as.data.frame(runifpoint(N.new,shp))
}else{
#2. Grid specific densities
#Call the function
ras.habitat<-raster(mydata.habitat()$myraster)
shp.buff<-gBuffer(shp, width=100)
ras.habitat<-crop(ras.habitat, shp.buff)
new.animals.xy<-get.pest.locs(ras.habitat, N.new, shp)
}
# new.animals.xy<-as.data.frame(runifpoint(N.new,shp))
colnames(new.animals.xy)<-c("X","Y")
new.animals.SP<-new.animals.xy #Why dis?
coordinates(new.animals.SP) <- c( "X", "Y" )
proj4string(new.animals.SP) <- CRS(proj4string)
# new.animals.xy$g0<-g0.mean
# new.animals.xy$Sigma<-sigma.mean
new.animals.xy$Dead<-0
new.animals.xy$g0.a<-rbeta(N.new, alpbet.a$alpha, alpbet.a$beta)
new.animals.xy$g0.a[new.animals.xy$g0.a<0]<-0.000001
new.animals.xy$g0.a[sample(x=N.new,size=round(N.new*g.zero.a),replace=F)]<-0
if(is.na(bait.start.a)==FALSE){
new.animals.xy$g0.bait<-rbeta(N.new, alpbet.bait$alpha, alpbet.bait$beta)
new.animals.xy$g0.bait[new.animals.xy$g0.bait<0]<-0 #Probably not needed
}else{
new.animals.xy$g0.bait<-0
}
new.animals.xy$Sigma<-rlnorm(N.new ,meanlog=locshp$location, sdlog=locshp$shape)
# #Calculate the probabilities for these new ones...
if(is.na(trap.start.a)==FALSE){
dist.xy.new<-matrix(NA,n.traps.a,N.new)
prob.xy.new<-matrix(0,n.traps.a,N.new)
dist.xy.new<-dist(as.data.frame(traps.xy.a), as.data.frame(new.animals.xy)[,1:2], method="euclidean") #Distance (not squared) - faster than using outer
prob.xy.new<-exp(-(dist.xy.new^2)/(2*new.animals.xy$Sigma^2))*new.animals.xy$g0.a #Use the g0u for sampling...
rm(dist.xy.new)
prob.xy.a<-cbind(prob.xy.a, prob.xy.new)
}
if(is.na(bait.start.a)==FALSE){
dist2.xy.new.c<-matrix(NA,n.baits.a,N.new)
prob.xy.new.c<-matrix(0,n.baits.a,N.new)
dist.xy.new.c<-dist(as.data.frame(baits.xy.a), as.data.frame(new.animals.xy)[,1:2], method="euclidean") #Distance (not squared) - faster than using outer
prob.xy.new.c<-exp(-(dist.xy.new.c^2)/(2*new.animals.xy$Sigma^2))*new.animals.xy$g0.bait #Use the g0u for sampling...
rm(dist.xy.new.c)
prob.xy.c<-cbind(prob.xy.c, prob.xy.new.c)
}
coordinates(new.animals.xy) <- ~ X+Y
proj4string(new.animals.xy) <- proj4string(shp)
animals.xy<-rbind(animals.xy,new.animals.xy)
n.animals<-dim(animals.xy)[1]
}}
#Update the age-class...
pop.size.mat[ii,t+1]<-sum(animals.xy$Dead==0)
#This calculates the number of alive animals in each zone.
# pop.size.zone.vec[[ii]][,t+1]<-table(over(animals.xy[animals.xy$Dead==0,], shp.2))
} #End of the night
if(is.na(trap.start.a)==FALSE){
trap.catch.mat[ii,]<-colSums(trap.catch.a)
}else{
trap.catch.mat[ii,]<-rep(0, n.nights)
}
if(is.na(bait.start.a)==FALSE){
bait.catch.mat[ii,]<-colSums(bait.catch.a)
}else{
bait.catch.mat[ii,]<-rep(0, n.nights)
}
}#End of iteration ii
params$TrapCost[kk]<-trap.cost.sim
params$BaitCost[kk]<-bait.cost.sim
params$TotalCost[kk]<-trap.cost.sim+bait.cost.sim
params$MeanPopSize[kk]<-round(mean(pop.size.mat[,n.nights+1]),2)
pop.size.list[[kk]]<-pop.size.mat
trap.catch.list[[kk]]<-trap.catch.mat
bait.catch.list[[kk]]<-bait.catch.mat
} #End kk - end of scenario
}) #End of progress
#Re-order parameters for the table
params<-params[,c(1,22,26,25,23:24,2:19)]
return(list(trap.catch.mat=trap.catch.mat, bait.catch.mat=bait.catch.mat, pop.size.mat=pop.size.mat, animals.xy=animals.xy, params=params, pop.size.list=pop.size.list, trap.catch.list=trap.catch.list, bait.catch.list=bait.catch.list))#, pop.zone.list=pop.zone.list))#, animals.done.xy=animals.xy))
}
)
output$mymap<-renderLeaflet({
shp<-mydata.shp()$shp
shp.proj<-spTransform(shp,CRS("+proj=longlat +datum=WGS84"))
m<-leaflet() %>%
addTiles(group="Default")%>%
addProviderTiles("OpenTopoMap", group = "Topo")%>%
addProviderTiles("Esri.WorldImagery", group = "Aerial")%>%
addPolygons(data=shp.proj, weight=2, fillColor="grey40", color="black", fillOpacity=0.2)
m
})
observe({
# validate(need(dim(coords)[1]>0,"Raster does not overlap with the shapefile"))
traps<-mydata.map()$traps
animals.xy<-mydata.map()$animals.xy.ini
proj4string<-mydata.shp()$p4s
traps.proj<-proj4::project(traps, proj=proj4string, inverse=T)
tmp<-(proj4::project(animals.xy[,1:2], proj=proj4string, inverse=T))
animals.xy$Lat<-tmp$y
animals.xy$Lon<-tmp$x
map<-leafletProxy("mymap")
map%>%clearMarkers()
map%>%addCircleMarkers(lng=traps.proj$x,lat=traps.proj$y, radius=3, color="black", weight=1, fill=TRUE, fillColor="red", fillOpacity=1, stroke=TRUE, group="Devices")
map%>%addCircleMarkers(lng=animals.xy$Lon,lat=animals.xy$Lat, radius=5, color="black", weight=1, fill=TRUE, fillColor=cols.vec[2], fillOpacity=1, stroke=TRUE, group="Animals")
map%>%addLayersControl(
baseGroups = c("Default","Topo","Aerial"),
overlayGroups=c("Devices","Animals"),
options = layersControlOptions(collapsed = FALSE)
)
})
output$plot1<-renderPlot({
#This is the plot of cost vs number left...First plot on Results tab
# validate(need(input$results.table_rows_selected !="","Select a results row"))
idx<-as.numeric(input$results.table_rows_selected)
res<-datab()$params
par(mar=c(4,4,3,2), tcl=-.2, mgp=c(2.5,1,0))
plot(res$MeanPopSize, res$TotalCost, xlab="Final population", ylab="Total cost", type='n')
points(res$MeanPopSize, res$TotalCost, pch=21, bg=cols.vec[2], cex=1.5)
points(res$MeanPopSize[idx], res$TotalCost[idx], pch=21, bg=cols.vec[6], cex=2)
mtext("Total Cost vs Animals Remaining",3, cex=1.5, line=1)
})
output$plot2<-renderPlot({
validate(need(input$results.table_rows_selected !="","Select a results row from the table below"))
idx<-as.numeric(input$results.table_rows_selected)
trap.catch.list<-datab()$trap.catch.list
trap.catch.mat<-trap.catch.list[[idx]]
bait.catch.list<-datab()$bait.catch.list
bait.catch.mat<-bait.catch.list[[idx]]
nights.vec<-1:input$n.nights
ymax.t<-max(apply(trap.catch.mat,1,cumsum))
ymax.b<-max(apply(bait.catch.mat,1,cumsum))
ymax<-max(ymax.b, ymax.t)
par(mar=c(4,4,3,2), tcl=-.2, mgp=c(2.5,1,0))
plot(1,1,xlim=c(0,input$n.nights), ylim=c(0,ymax), type='n', xlab="Nights", ylab="Cumulative kills", las=1)
for(i in 1:input$n.its){
lines(nights.vec,cumsum(trap.catch.mat[i,]), col=cols.vec[1])
lines(nights.vec,cumsum(bait.catch.mat[i,]), col=cols.vec[3])
}
lines(nights.vec,cumsum(colMeans(trap.catch.mat)), col=cols.vec[2])
points(nights.vec,cumsum(colMeans(trap.catch.mat)), bg=cols.vec[2], pch=21)
lines(nights.vec,cumsum(colMeans(bait.catch.mat)), col=cols.vec[4])
points(nights.vec,cumsum(colMeans(bait.catch.mat)), bg=cols.vec[4], pch=22)
legend("topleft", legend=c("Traps","Bait station"), pch=c(21,22), pt.bg=cols.vec[c(2,4)], bty="n")
mtext("Cumulative kills",3, cex=1.5, line=1)
})
output$plot4<-renderPlot({
validate(need(input$results.table_rows_selected !="","Select a results row"))
idx<-as.numeric(input$results.table_rows_selected)
pop.size.list<-datab()$pop.size.list
# pop.size.mat<-pop.size.list[[as.numeric(input$result_scenario)]]
pop.size.mat<-pop.size.list[[idx]]
# pop.size.mat<-datab()$pop.size.mat
par(mar=c(4,4,3,2), tcl=-.2, mgp=c(2.5,1,0))
plot(1,1,xlim=c(0,input$n.nights), ylim=c(0,max(pop.size.mat)), type='n', xlab="Nights", ylab="Population Size", las=1)
grid()
for(i in 1:input$n.its){
lines(0:input$n.nights,pop.size.mat[i,], col="grey")
}
lines(0:input$n.nights,colMeans(pop.size.mat), col="black")
points(0:input$n.nights,colMeans(pop.size.mat), bg="black", pch=21)
mtext("Population size",3, cex=1.5, line=1)
})
#This updates the dropdown box in the results section
observe({
# updateSelectInput(session=session, inputId="result_scenario",choices=mydata.scen()$params$Scenario)