-
Notifications
You must be signed in to change notification settings - Fork 0
/
COTS_Model.Rmd
1316 lines (1073 loc) · 56.8 KB
/
COTS_Model.Rmd
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
---
title: "COTS_Model"
author: "Samuel Matthews"
date: "21 November 2018"
output:
html_document:
toc: true
code_folding: hide
toc_float: true
theme: cosmo
highlight: haddock
---
# Major Challenges
1. I think we need to move everything to a reef level instead of a pixel based scenario.. Having multiple COTS populations on a ref make its hard to intigate a reef wide collapse.
2. following a collapse COTS numbers stay at 0 until returning to directly to carrying capacity
3. need to build a matlines plot to show each different replicate
# Preparing the Workspace
This section of the model sets up the directories to access data and to save files
```{r cars, cache=T, eval=T}
# CLEAR THE WORKSPACE ----
#######################!
rm(list=ls())
####
# SET USER ----
####
USER = "SAM_UNI"
# USER = "SAM_RENO"
#################!
# SET GLOBAL VARIABLES (USER SPECIFIED PARAMS) ----
####
# NREPS <- 10
NYEARS <- 22
NSEASONS <- 2
seasons <- c("summer","winter")
npops = 15802 #number of reefs we want to test
VERBOSE <- TRUE # flag whether functions should return detailed information
DEBUG <- TRUE # flag whether to output debug files etc.
projection <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0" #"+proj=lcc +lat_1=33 +lat_2=45 +lat_0=39 +lon_0=-96 +x_0=0 +y_0=0 +ellps=GRS80 +units=m +no_defs"
stagenames <- c('J_1', 'J_2', 'A')
COTSmort <- c(0.8,0.7,0.2)
names(COTSmort) <- stagenames
COTSremain <- c(0.02,0.2,1) # proportion remianing in each life stage --> we can make this a function of resource
names(COTSremain) <- stagenames
#VBG.Params = VBG.Models[[2]]
COTS_StableStage <- c(0.9803, 0.0171, 0.0026) # very approximate stable stage distribution (J1, J2, Adult: see below for back-of-the-envelope calculation)
```
## Set Project Directories
```{r Project Directories,eval=T, cache=TRUE}
####
# SET PROJECT DIRECTORIES ----
####
# (this should be the only place where local directories should be referenced)
if(USER=="KEVIN") BASE_DIRECTORY <- "C:\\Users\\Kevin\\Dropbox\\CoTS_Model" # NOTE: this should link to the Dropbox folder with shared project resources
if(USER=="KEVIN") CODE_DIRECTORY <- "C:\\Users\\Kevin\\GIT\\COTS_Model" # NOTE: code directory should be your local copy of the GitHub repository
if(USER=="SAM") BASE_DIRECTORY <- "C:\\Users\\jc312264\\Dropbox\\CoTS_Model"
if(USER=="SAM") CODE_DIRECTORY <- "C:\\Users\\jc312264\\Documents\\GitHub\\COTS_Model"
if(USER=="SAM_UNI") BASE_DIRECTORY <- "C:\\Users\\jc312264\\Dropbox\\CoTS_Model"
if(USER=="SAM_UNI") CODE_DIRECTORY <- "C:\\Users\\jc312264\\OneDrive - James Cook University\\GitHub\\COTS_Model"
if(USER=="SAM_RENO") BASE_DIRECTORY <- "C:\\Users\\kshoemaker\\Dropbox\\CoTS_Model"
if(USER=="SAM_RENO") CODE_DIRECTORY <- "C:\\Users\\kshoemaker\\Documents\\GitHub\\COTS_Model"
SPATIALDATA_DIRECTORY <- paste(BASE_DIRECTORY,"\\Spatial Layers",sep="") # directory for storing relevant spatial data (ASC, SHP files)
if(is.na(file.info(SPATIALDATA_DIRECTORY)[1,"isdir"])) dir.create(SPATIALDATA_DIRECTORY)
DATA_DIRECTORY <- paste(BASE_DIRECTORY,"\\Data",sep="") # directory for storing data (CSV files)
if(is.na(file.info(DATA_DIRECTORY)[1,"isdir"])) dir.create(DATA_DIRECTORY)
ENVDATA_DIRECTORY <- paste(DATA_DIRECTORY,"\\Environmental",sep="") # directory for storing data (CSV files)
if(is.na(file.info(ENVDATA_DIRECTORY)[1,"isdir"])) dir.create(ENVDATA_DIRECTORY)
FIGURES_DIRECTORY <- paste(BASE_DIRECTORY,"\\Figures\\RawFigures",sep="") # directory for storing raw figures generated from R
if(is.na(file.info(FIGURES_DIRECTORY)[1,"isdir"])) dir.create(FIGURES_DIRECTORY)
RESULTS_DIRECTORY <- paste(BASE_DIRECTORY,"\\Results",sep="") # directory for storing relevant results
if(is.na(file.info(RESULTS_DIRECTORY)[1,"isdir"])) dir.create(RESULTS_DIRECTORY)
RDATA_DIRECTORY <- paste(BASE_DIRECTORY,"\\R_Workspaces",sep="") # directory for storing .RData files (R workspaces and data objects)
if(is.na(file.info(RDATA_DIRECTORY)[1,"isdir"])) dir.create(RDATA_DIRECTORY)
cat(sprintf("The current user is %s",USER))
```
## Load Functions, Packages and Data
```{r Load, eval=T, cache=T}
##################!
# LOAD FUNCTIONS AND SCRIPTS FROM SOURCE CODE (your local GitHub repository) ----
##################!
setwd(CODE_DIRECTORY)
source("COTSModel_Utilityfunctions.R") # load utility functions, e.g., for loading packages etc.
source("COTSModel_COTSfunctions.R") # load functions for implementing COTS demography and dispersal
source("COTSModel_Coralfunctions.R") # load functions for implemeting coral growth/recovery and dispersal
source("COTSModel_GISfunctions.R") # load functions for implemeting coral growth/recovery and dispersal
#####################!
# LOAD PACKAGES ----
#####################!
# note: 'loadPackage' should install the package from CRAN automatically if it is not already installed
loadPackages() # load all packages into the global environment
# THis only installs packages now.. everything else will be defined inline
`%>%` <- magrittr::`%>%` # bringt the pipe operator into the global environment
#####################!
# LOAD DATA FOR MODELLING ----
#####################!
setwd(CODE_DIRECTORY)
source("COTSModel_LoadObjectsForModelling.R")
# CC_Per_CC = (data.grid$PercentReef/10000)*1e6*1e4
# COTS_Per_CC = CC_Per_CC/(250*365)
# Crash=5
# save global params
saveWorkspace(filename="GlobalParams.RData", dir=RDATA_DIRECTORY)
```
# Model Structure and Functions
FIgure 1 below describes the general framework for the COTS model. A dataframe is set up to create latin hypercube samples, then the model is run for each sample and stored as a `.Rdata` file. Each function is described in detail below.
![Model Structure](C:/Users//jc312264//Dropbox//CoTS_Model//MindMaps//Structure.png)
$$CoralCover_{t+1} = CoralCover_{t} + $$
## makeLHSsamples
+ __Objective__: This function creates _n_ replicates across paremeter space for an individual model run
+ __Paremeters__:
+ __NREPS__: number of replicate samples we wish to draw from parameter space
+ __Returns__:
+ __masterDF__: n x 14 dataframe containing the parameters for that
+ __.csv__: masterDF is written to the Results Directory
+ _Major Issues_: No major issues at this time, the biggest concern is developing more realisic densit dependent parameters to sample across
```{r makeLHSSample, eval=T}
MakeLHSSamples <- function(NREPS){
# Information necessary to translate standard uniform LHS sample into parameters of interest
specifyLHSParam <- function(paramslist,name,type,lb,ub){
newlist <- paramslist
eval(parse(text=sprintf("newlist$%s <- list()",name)))
eval(parse(text=sprintf("newlist$%s$type <- \"%s\"",name,type)))
eval(parse(text=sprintf("newlist$%s$lb <- %s",name,lb)))
eval(parse(text=sprintf("newlist$%s$ub <- %s",name,ub)))
return(newlist)
}
LHSParms <- list() # initialize the container for parameter bounds
### SEXRATIO : 1 = 0.1M:0.9F
LHSParms <- specifyLHSParam(paramslist=LHSParms,name="SexRatio",type="CAT",lb=0,ub=9)
#### WINTER CONSUMPTION RATE
LHSParms <- specifyLHSParam(LHSParms,"ConsRateW",type="CONT",lb=100,ub=200)
#### SUMMER CONSUMPTION RATE
LHSParms <- specifyLHSParam(LHSParms,"ConsRateS",type="CONT",lb=150,ub=400)
### AVERAGE PER CAPITA FECUNDITY
LHSParms <- specifyLHSParam(LHSParms,"avgPCF",type="CONT",lb=42e5,ub=21e6)
### STD DEV PER CAPITA FECUNDITY
LHSParms <- specifyLHSParam(LHSParms,"sdPCF",type="CONT",lb=6e4,ub=14.6e4)
### % JUVENILE1 MORTALITY PER TIME STEP
LHSParms <- specifyLHSParam(LHSParms,"mortJ1",type="CONT",lb=0.9,ub=0.99)
### % JUVENILE2 MORTALITY PER TIME STEP
LHSParms <- specifyLHSParam(LHSParms,"mortJ2",type="CONT",lb=0.6,ub=0.99)
### % ADULT MORTALITY PER TIME STEP
LHSParms <- specifyLHSParam(LHSParms,"mortA",type="CONT",lb=0.1,ub=0.6)
### % JUVENILE1 TO REMIAIN during transition
LHSParms <- specifyLHSParam(LHSParms,"remJ1",type="CONT",lb=0.01,ub=0.5)
### % JUVENILE2 TO REMIAIN during transition
LHSParms <- specifyLHSParam(LHSParms,"remJ2",type="CONT",lb=0.1,ub=0.5)
### % ADULT TO REMIAIN during transition
LHSParms <- specifyLHSParam(LHSParms,"remA",type="CONT",lb=1,ub=1)
### PROPORTIONAL STABLE STAGE DISTRIBUTION J1
LHSParms <- specifyLHSParam(LHSParms,"cssJ1",type="CONT",lb=0.9803,ub=0.9803)
### PROPORTIONAL STABLE STAGE DISTRIBUTION J2
LHSParms <- specifyLHSParam(LHSParms,"cssJ2",type="CONT",lb=0.0171,ub=0.0171)
### PROPORTIONAL STABLE STAGE DISTRIBUTION a
LHSParms <- specifyLHSParam(LHSParms,"cssA",type="CONT",lb=0.0026,ub=0.0026)
##### GENERATE LATIN HYPERCUBE SAMPLE
nVars <- length(names(LHSParms))
LHS <- lhs::randomLHS(NREPS, nVars ) # generate multiple samples from parameter space according to a LHS sampling scheme
masterDF <- as.data.frame(LHS) # storage container (data frame) to record relevant details for each file. Rows LHS samples. Cols: relevant variables
### translate raw lhs samples into desired parameter space
colnames(masterDF) <- names(LHSParms)
parm=1
for(parm in 1:nVars){
if(LHSParms[[parm]]$type=="CONT"){
masterDF[,parm] <- LHSParms[[parm]]$lb + LHS[,parm]*(LHSParms[[parm]]$ub-LHSParms[[parm]]$lb)
}
if(LHSParms[[parm]]$type=="CAT"){
masterDF[,parm] <- ceiling(LHSParms[[parm]]$lb + LHS[,parm]*(LHSParms[[parm]]$ub-LHSParms[[parm]]$lb))
}
}
setwd(RESULTS_DIRECTORY)
## name file for LHS parameters
write.csv(masterDF,"masterDF_prelimCOTS.csv",row.names=F)
return(masterDF)
}
####################!
# GENERATE LATIN HYPERCUBESAMPLE ----
####################!
masterDF = MakeLHSSamples(NREPS = 10)
```
## initalizeCOTSabund
+ __Objective__: Create a npops x 3 matrix to store COTS abundances (COTSabund) as the model progress
+ __Paremeters__:
+ __data.grid__: XYZ grid conatining all metadata for each pixel and environmental variables
+ __data.COTS__: interpolated COTS per manta tow dataframe used to initialize the COTS populations
+ __Year__: which year we choose to start from (usually 1996)
+ __stagenames__: character vector containing the names of the COTS stages (e.g J_1, J_2, A)
+ __COTS_StableStage__: 3 element vector conatinin the estimated proportions of J_1 and J_2 COTS to support the initialized adult population
+ __Returns__:
+ __COTSabund__: npops x 3 matrix containing our starting values of COTS
+ _Major Issues_: I need to make a more reliable estimate of the stable stage distribution, I can probably get this from Cameron Fletcher
```{r initializeCOTSabund}
initializeCOTSabund <- function(data.grid, data.COTS, Year, stagenames, COTS_StableStage){
# browser()
### set NA Values in interpolation CoTS.init to 0
data.COTS[is.na(data.COTS)] <- 0
nstages <- length(stagenames)
### Set up the COTS abundance object
COTSabund <- matrix(0,nrow=npops, ncol=nstages)
colnames(COTSabund) <- stagenames
### Set up reference for year
colname <- paste('COTS_', Year, sep="")
### Update abundances based from interpolated manta tow data
COTSabund[,'A'] <- round(data.COTS.bckp[,colname] * 666 * (data.grid$PercentReef/100),0) # 666 converts manta tow to 1kmx1km
COTSabund[,'J_2'] <- round(COTSabund[,'A'] * as.numeric(COTS_StableStage[2]/COTS_StableStage[3]),0)
COTSabund[,'J_1'] <- round(COTSabund[,'A'] * as.numeric(COTS_StableStage[1]/COTS_StableStage[3]),0)
return(COTSabund)
}
COTSabund = initializeCOTSabund(data.grid, data.COTS, 1996, stagenames, COTS_StableStage)
```
## doCOTSDispersal
+ __Objective__: This function computes the larvae produced for each population and then distributes them to the other reefs withn the system via Karlo's mean Connectivity network.
+ __Paremeters__:
+ __season__: `"summer"` or `"winter"`
+ __COTSabund__: npops x 3 matrix containing COTS abundances for the 3 stages
+ __SexRatio__: 1-10 indicating the ratio of F:M in the population
+ __ConnMat__: Connectivity Matrix filtered by only the reefs selected in npops
+ __PCFParams__: 2 element vector containg the average and sd of percapita fecundity
+ __Pred__: Proportion of larve lost to predation (NEEDS to be included as at unable parameter)
+ __FvDparams__: Fertilisation by Density parameters
+ __Returns__:
+ __COTSabund__
+ _Major Issues_:
+ We need a standard deviation for the connectivity network as well as the mean.
+ I would like to make Per-Capita fecundity density dependent, or related to food availability
+ Needs an element of maternual condition
+ We need another stageclass to represent larger more fertile individuals
```{r}
doCOTSDispersal = function(season, COTSabund, SexRatio, ConnMat, PCFParams, Pred, FvDParams){
# browser()
COTSabund = COTSabund
if (season=="summer"){
nEggs = COTSabund[,'A']*rnorm(1, PCFParams[1], PCFParams[2])*((10-SexRatio)/10)
fEggs = FvDParams[SexRatio,"Linf"] * (1 - exp(-FvDParams[SexRatio,"K"] * (COTSabund[,'A'] - FvDParams[SexRatio,"t0"])))
nLarvae = nEggs * fEggs
# Do Dispersal ----
nLarvae = ifelse(nLarvae < 0 , 0, nLarvae)
nLarvae = as.matrix((1-Pred)*nLarvae) # assume 80% lost to the sea
row.names(nLarvae) = data.grid$REEF_NAME
nLarvae_Reef = rowsum(nLarvae, row.names(nLarvae), reorder = F)
nArriving_Reef = ConnMat
nArriving_Reef[nArriving_Reef > 0] = 0
for (i in 1:length(nLarvae_Reef)) {
nArriving_Reef[i,] = signif(nLarvae_Reef[i]*(ConnMat[i,]),3)
}
nArriving_Reef = base::colSums(nArriving_Reef, na.rm = T) # create total juveniles arriving at a reef
nArriving_Reef_PerPix = nArriving_Reef/Pixels$Pixels
names(nArriving_Reef_PerPix) = colnames(ConnMat)
nArriving = nArriving_Reef_PerPix[match(data.grid$REEF_NAME, colnames(ConnMat))]
COTSabund[,'J_1'] = COTSabund[,'J_1'] + nArriving # add these to our abundance
}
return(COTSabund)
}
```
## doCOTSDemography
+ __Objective__: To transition COTS throughout their life stages
+ __Paremeters__:
+ __season__: `"summer"` or `"winter"`
+ __COTSabund__: npops x 3 matrix containing COTS abundances for the 3 stages
+ __COTSmort__: 3 element vector containg the fixed mortality rates per lifestage **PLACEHOLDER**
+ __COTSremain__: 3 element vector conatingin the proportion of individuals that will not progress to the next, but remain alive **PLACEHOLDER**
+ __Returns__:
+ __COTSabund__:
+ _Major Issues_: Transitions NEED to become food limited --> `COTSmort` & `COTSremain`
```{r doCOTSdemography}
doCOTSDemography = function(season, COTSabund, COTSmort, COTSremain){
newCOTSabund = COTSabund
if (season=="winter"){
#Set up matrices
newCOTSabund <- matrix(0,nrow=nrow(COTSabund), ncol=ncol(COTSabund))
colnames(newCOTSabund) <- colnames(COTSabund)
COTS_Mort <- matrix(0,nrow=nrow(COTSabund), ncol=ncol(COTSabund))
colnames(COTS_Mort) <- colnames(COTSabund)
COTS_Remain <- matrix(0,nrow=nrow(COTSabund), ncol=ncol(COTSabund))
colnames(COTS_Remain) <- colnames(COTSabund)
COTS_Trans <- matrix(0,nrow=nrow(COTSabund), ncol=ncol(COTSabund))
colnames(COTS_Trans) <- colnames(COTSabund)
# apply mortality
COTS_Mort <- sweep(COTSabund,MARGIN=2,COTSmort,`*`)
# update abundance
newCOTSabund <- COTSabund - COTS_Mort
# number of COTS remaining and transitioning for each stage based on post-mortality abundaces
COTS_Remain <- sweep(newCOTSabund,MARGIN=2,COTSremain,`*`)
COTS_Trans <- sweep(newCOTSabund,MARGIN=2,1-COTSremain,`*`)
# update newCOTSabund
newCOTSabund[, 'J_1'] <- round(COTS_Remain[,'J_1'],0)
newCOTSabund[, 'J_2'] <- round(COTS_Remain[,'J_2'] + COTS_Trans[,'J_1'],0)
newCOTSabund[, 'A'] <- round(COTS_Remain[,'A'] + COTS_Trans[,'J_2'],0)
}
return(newCOTSabund)
}
```
## doCoralDisturbance
+ __Objective__:
+ __Paremeters__:
+ __Returns__:
+ _Major Issues_: Not implemented yet
```{r doCoralDisturbance}
doCoralDisturbance = function (i, j, season, CoralCover, COTSfromCoralModel = F) {
CoralCover = log(CoralCover)
if (season =="summer"){
# browser()
### Apply disturbances (bleaching, CoTS, disease, storms) in year 1994+i (starting from 1996)
storms.rsmpl[,i,j][WQ > (-1)*B.STORMS[j]/WQ_Cyclone[1]] <- 0
CoralCover[storms.rsmpl[,i,j]>0] <- CoralCover[storms.rsmpl[,i,j]>0] +
storms.rsmpl[,i,j][storms.rsmpl[,i,j]>0] * (B.STORMS[j] + WQ[storms.rsmpl[,i,j]>0] * WQ_Cyclone[1])
if (COTSfromCoralModel == TRUE) {
CoralCover[COTS.rsmpl[,i,j]>0] <- CoralCover[COTS.rsmpl[,i,j]>0] +
COTS.rsmpl[,i,j][COTS.rsmpl[,i,j]>0] * (B.COTS[j] + WQ[COTS.rsmpl[,i,j]>0] * WQ_CoTS[1])
}
CoralCover[bleaching.rsmpl[,i,j]>0] <- CoralCover[bleaching.rsmpl[,i,j]>0] +
bleaching.rsmpl[,i,j][bleaching.rsmpl[,i,j]>0] * (B.BLEACHING[j] + WQ[bleaching.rsmpl[,i,j]>0] * WQ_bleach[1])
CoralCover[disease.rsmpl[,i,j]>0] <- CoralCover[disease.rsmpl[,i,j]>0] + B.DISEASE[j]
CoralCover[unknown.rsmpl[,i,j]>0] <- CoralCover[unknown.rsmpl[,i,j]>0] + B.UNKNOWN[j]
CoralCover[CoralCover < log(0.1)] <- log(0.1) # sets minimal value to 10% (as 0% does not allow for recovery. 10% is the minimum HC cover observed in the LTMP data)
# CoralCover <- b0 + (1 - b1)* CoralCover
}
return(exp(CoralCover))
### Store results
#res[,year,j] <- exp(CoralCover)
}
```
## doPredPreyDynamics
+ __Objective__: To limit COTS growth to Carrying Capacity. Includes a population crash mechanism `Crash` (0-7%Coral Cover) the level at which a COTS populaion will die off due to low amount of food.
+ __Paremeters__:
+ __season__: `"summer"` or `"winter"`
+ __COTSabund__: npops x 3 matrix containing COTS abundances for the 3 stages
+ __year__: current year in the model
+ __KC__: upper carrying capicity, estimated from highest obseved population levels (~200/mant tow) assuming 50% detectability for this methodolgy
+ __CoralCover__: Coral Cover for the current year
+ __Crash__: coral cover level at which the population will crash
+ __Returns__:
+ __COTSabund__: npops x 3 matrix containing COTS abundances for the 3 stages
+ _Major Issues_: This is the biggest issue with the model.
```{r doPredPreyDynamics}
COTSRecruit = function(h, R0, COTS, K, ey) {
exp(ey) * (4*h*R0*COTS/K) / ((1-h) + (5*h-1)*COTS/K)
}
switchfunc = function(CC, K) {
exp(-5*CC/K)
}
plot(switchfunc(seq(0,50), 50))
rec.res = matrix(NA, 200,10)
for( i in 2:10){
rec.res[,i] = COTSRecruit(h=i/10, R0 = 1, COTS = seq(1,200), K = 100, ey = 1)
}
matplot(rec.res, pch = 1:10, type = "o", col = rainbow(ncol(rec.res)))
CoralCOTSMort = function(p,CoralCover) {
(1 - (p*CoralCover/(10+CoralCover)))
}
plot(CoralCOTSMort(0.2,seq(0,100, 1)))
doPredPreyDynamics = function(COTSabund, CoralCover, p, Crash) {
# incroporates natural mortality and coral cover
COTSabund[which(CoralCover < Crash),] = c(0,0,0)
COTS.m.CC = CoralCOTSMort(p, CoralCover)
COTSabund[,"A"] = COTSabund[,"A"]*exp(-COTS.m.CC*COTSmort[3])
COTSabund[,"J_2"] = COTSabund[,"J_2"]*exp(-COTS.m.CC*COTSmort[2])
COTSabund[,"J_1"] = COTSabund[,"J_1"]*exp(-COTS.m.CC*COTSmort[1])
return(COTSabund)
}
testmat =matrix(c(0,0,100),1,3, dimnames = list(NULL, c("J_1", "J_2", "A")))
doPredPreyDynamics(testmat, 30, 0.25, 3, 0.8)
#CoralCOTSMort(1,1.4)
# doPredPreyDynamics(season, year, COTSabund, KC, CoralCover, Crash, p=1)
```
## doCoralConsumption
+ __Objective__: Allow COTS to consume coral
+ __Paremeters__:
+ __year__: current year in the model
+ __season__: `"summer"` or `"winter"`
+ __COTSabund__: npops x 3 matrix containing COTS abundances for the 3 stages
+ __CoralCover__: Coral Cover for the current year
+ __ConsRateS__: cm2 consumed per day in summer
+ __ConsRateW__: cm2 consumed per day in winter
+ __Returns__:
+ __CRemaining__: Coral cover remaining
+ __CConsumed__: Coral cover consumed
+ __Major Issues__: Consumption rate should be size dependent, requiring another age stage
```{r doCoralConsumption}
doCoralConsumption = function(season, COTSabund, CoralCover, ConsRate) {
if (season =="summer") {
# browser()
#CoralCover= Results[(Results$Year==year-1) & (Results$Season=="winter"),"CoralCover"]
CAvailable = (CoralCover*data.grid$PercentReef/10000)*1e6*1e4 # in cm2
CConsumed = ConsRate[,1]*COTSabund[,"A"]*182
CRemaining=((CAvailable-CConsumed)/1e10)*(10000/data.grid$PercentReef)
CChange = CRemaining-CoralCover
CRemaining[CRemaining < 0.5] <- 0.5
}
if (season =="winter") {
#CoralCover= Results[(Results$Year==year) & (Results$Season=="summer"),"CoralCover"]
CAvailable = (CoralCover*data.grid$PercentReef/10000)*1e6*1e4 # in cm2
CConsumed = ConsRate[,2]*COTSabund[,"A"]*182
CRemaining=((CAvailable-CConsumed)/1e10)*(10000/data.grid$PercentReef)
CChange = CRemaining-CoralCover
CRemaining[CRemaining < 0.5] <- 0.5
}
return(cbind(CRemaining, CChange))
}
```
## doCoralGrowth
+ __Objective__: Using Aaron's Coral growth estimates, apply the growth function to the current timestep
+ __Paremeters__:
+ __CoralCover__: Coral Cover for the current year (vector of length `npops`)
+ __B0__: intrinsic rate of growth for the pixel (vector of length `npops`)
+ __WQ__: WQ index for the pixel (vector of length `npops`)
+ __HC.asym__: Maximum hard coral cover for the pixel (vector of length `npops`)
+ __Returns__:
+ __CoralCover__: Updated coral cover
+ __CoralGrowth__: % Coral cover increase from growth
+ _Major Issues_: This function seems to work fine
```{r doCoralGrowth}
doCoralGrowth = function(season, CoralCover) {
if(season == "summer") {
# b0.wq <- B0 + WQ * rnorm(length(WQ), mean=WQ.mn.sd[1], sd=WQ.mn.sd[2])
# b1.wq <- b0.wq / log(HC.asym)
CoralCover <- log(CoralCover)
# CoralCover.t1 <- b0.wq + (1 - b1.wq)*CoralCover
CoralCover.t1 = b0 + (1 - b1)*CoralCover
return(cbind(CoralCover=exp(CoralCover.t1), CoralGrowth=(exp(CoralCover.t1)-exp(CoralCover))))
}
return(cbind(CoralCover=CoralCover, CoralGrowth=NA))
}
test = doCoralGrowth(CoralCover)
```
## RunModel
+ __Objective__: To run the model for over the time series for `npops` (i.e pixels)
+ __Paremeters__:
+ __MasterDF__: dataframe holding the LHS selected parameters
+ __PopData__: dataframe holding metadata for each pixel
+ __COTS.data__: dataframe holding the interpolated COTS data, ussed to initialize abundances
+ __Years__: vector of years to run the model over. i.e `1996:2015`
+ __data.grid__: dataframe containignt all environmental variables and Coral growth parameters
+ __rep__: which replicate to run, i.e which row of master DF to use the parameters from
+ __Pred__: predation rate, proportion of larvae consumed
+ __Returns__:
+ __Results__: dataframe holding the ime series results for each pixels, saved as an .Rdata file
+ _Major Issues_: THis function performs well and quickly, issues only arise from the demography within.
```{r RunModel}
# Define initial parameters for jth simulation
nsimul = 100
LHS <- lhs::randomLHS(nsimul,9)
B.BLEACHING <- qnorm(LHS[,1], mean=bleaching.mn.sd[1], sd=bleaching.mn.sd[2])
B.COTS <- qnorm(LHS[,2], mean=COTS.mn.sd[1], sd=COTS.mn.sd[2])
B.DISEASE <- qnorm(LHS[,3], mean=disease.mn.sd[1], sd=disease.mn.sd[2])
B.STORMS <- qnorm(LHS[,4], mean=storms.mn.sd[1], sd=storms.mn.sd[2])
B.UNKNOWN <- qnorm(LHS[,5], mean=unknown.mn.sd[1], sd=unknown.mn.sd[2])
B.WQ <- qnorm(LHS[,6], mean=WQ.mn.sd[1], sd=WQ.mn.sd[2])
A <- B0 <- HCINI <- HCMAX <- matrix(NA, ncol = nsimul, nrow = dim(data.grid)[1])
for (i in 1:nsimul) {
A[,i] <- qnorm(LHS[i,7], mean=data.grid$pred.a.mean, sd=data.grid$pred.a.sd)
B0[,i] <- qnorm(LHS[i,8], mean=data.grid$pred.b0.mean, sd=data.grid$pred.b0.sd)
HCINI[,i] <- qnorm(LHS[i,9], mean=data.grid$pred.HCini.mean, sd=data.grid$pred.HCini.sd)
HCMAX[,i] <- qnorm(LHS[i,9], mean=data.grid$pred.HCmax.mean, sd=data.grid$pred.HCmax.sd)
}
HCMAX[HCINI > HCMAX] <- HCINI[HCINI > HCMAX]
nyears <- length(1996:2017)
res <- array(NA, dim=c(dim(data.grid)[1], nyears, nsimul)) ## Stores the coral cover values for each grid cell (rows), year (columns) and simulation (third dimension)
bleaching.rsmpl <- COTS.rsmpl <- disease.rsmpl <- storms.rsmpl <- unknown.rsmpl <- array(NA, dim=c(dim(data.grid)[1], nyears, nsimul)) ## Stores the actual (i.e. resampled) disturbance intensity values for each grid cell (rows), year (columns) and simulation (third dimension)
# Create back up files of disturbance tables ----
data.bleaching[is.na(data.bleaching)] <- 0
data.COTS[is.na(data.COTS)] <- 0
data.storms[is.na(data.storms)] <- 0
data.bleaching.bckp <- data.bleaching
data.COTS.bckp <- data.COTS
data.storms.bckp <- data.storms
# Resample Distrubances for each simulation
for (j in 1:nsimul) {
HC.1996 <- HCINI[,j]
b0 <- B0[,j]
#b1 <- A[,j]
b1 <- B0[,j]/log(HCMAX[,j])
res[,1,j] <- as.numeric(HC.1996)
#CoralCover <- log(HC.1996)
CoralCover = HC.1996
# Re-initialize disturbance data
data.bleaching <- data.bleaching.bckp
data.COTS <- data.COTS.bckp
data.storms <- data.storms.bckp
# Resample disturbance data in each year
data.unknown <- data.disease <- data.COTS
colnames(data.unknown)[6:38] = paste0("UNKN_", 1985:2017)
colnames(data.disease)[6:38] = paste0("DIS_", 1985:2017)
data.unknown[,6:38] <- data.disease[,6:38] <- 0
for (i in 1:nyears) {
## Simulate disease and unknown disturbance based on observed frequencies
data.unknown[,i+16] <- sampling::srswor(round(length(data.unknown[,i+16])*0.01),length(data.unknown[,i+16]))
data.disease[,i+16] <- sampling::srswor(round(length(data.disease[,i+16])*0.01),length(data.disease[,i+16]))
## Resample other disturbance based on P(Impact|Disturbance)
count.cots <- length(data.COTS[,i+16][data.COTS[,i+16]>0])
count.storms <- length(data.storms[,i+16][data.storms[,i+16]>0])
count.bleaching <- length(data.bleaching[,i+16][data.bleaching[,i+16]>0])
if (count.cots>0) data.COTS[,i+16][data.COTS[,i+16]>0][sample(count.cots, count.cots*.5)] <- 0
if (count.storms>0) data.storms[,i+16][data.storms[,i+16]>0][sample(count.storms, round(count.storms*.5))] <- 0
if (count.bleaching>0) data.bleaching[,i+16][data.bleaching[,i+16]>0][sample(count.bleaching, count.bleaching*.1)] <- 0
}
data.disease[,-(1:5)][data.disease[,-(1:5)]>1] <- 1
data.unknown[,-(1:5)][data.unknown[,-(1:5)]>1] <- 1
data.storms[,"Hs4MW_2009"] <- data.storms[,"Hs4MW_2009"]*.5
data.storms[,"Hs4MW_2013"] <- data.storms[,"Hs4MW_2013"]*.5
data.storms[,"Hs4MW_2014"] <- data.storms[,"Hs4MW_2014"]*.5
data.storms[,"Hs4MW_2015"] <- data.storms[,"Hs4MW_2015"]*.5
# Add known disturbance for LTMP reefs
data.bleaching[,-(1:16)][!is.na(data.ltmp.bleaching[,-(1:5)])] <- data.ltmp.bleaching[,-(1:5)][!is.na(data.ltmp.bleaching[,-(1:5)])]
data.COTS[,-(1:16)][!is.na(data.ltmp.COTS[,-(1:5)])] <- data.ltmp.COTS[,-(1:5)][!is.na(data.ltmp.COTS[,-(1:5)])]
data.storms[,-(1:16)][!is.na(data.ltmp.storms[,-(1:5)])] <- data.ltmp.storms[,-(1:5)][!is.na(data.ltmp.storms[,-(1:5)])]
data.disease[,-(1:16)][!is.na(data.ltmp.disease[,-(1:5)])] <- data.ltmp.disease[,-(1:5)][!is.na(data.ltmp.disease[,-(1:5)])]
data.unknown[,-(1:16)][!is.na(data.ltmp.unknown[,-(1:5)])] <- data.ltmp.unknown[,-(1:5)][!is.na(data.ltmp.unknown[,-(1:5)])]
# store the resampled distrubances for the replicate j
bleaching.rsmpl[,,j] <- as.matrix(data.bleaching[,-(1:16)])
COTS.rsmpl[,,j] <- as.matrix(data.COTS[,-(1:16)])
disease.rsmpl[,,j] <- as.matrix(data.disease[,-(1:16)])
storms.rsmpl[,,j] <- as.matrix(data.storms[,-(1:16)])
unknown.rsmpl[,,j] <- as.matrix(data.unknown[,-(1:16)])
for (i in 1:nsimul) bleaching.rsmpl[,,i][is.na(bleaching.rsmpl[,,i])] <- 0
bleaching.mn <- apply(bleaching.rsmpl, c(1,2), mean, na.rm=T)
COTS.mn <- apply(COTS.rsmpl, c(1,2), mean, na.rm=T)
disease.mn <- apply(disease.rsmpl, c(1,2), mean, na.rm=T)
storms.mn <- apply(storms.rsmpl, c(1,2), mean, na.rm=T)
unknown.mn <- apply(unknown.rsmpl, c(1,2), mean, na.rm=T)
}
masterDF = data.frame("SexRatio" = 5,
"ConsRateW" = 150,
"ConsRateS" = 250,
"avgPCF" = 10000000,
"sdPCF" = 1000000,
"mortJ1" = 0.99,
"mortJ2" = 0.95,
"mortA" = 0.6,
"remJ1" = 0,
"remJ2" = 0,
"remA" = 1,
"cssJ1" = 0.9803,
"cssJ2" = 0.0171,
"cssA" = 0.0026,
"Pred" = 0.98,
"p" = 0.25,
"Crash" = 3)
res.cc = array(NA, dim=c(dim(data.grid)[1], nyears*2, nsimul))
res.cots = array(NA, dim=c(dim(data.grid)[1], nyears*2, nsimul))
runModel = function(masterDF, PopData, data.COTS, Years = Years,
data.grid, rep, Pred, p,
Crash, nsimul,
COTSfromCoralModel=FALSE, COTSfromSimul=TRUE, browse = FALSE, inityear = 1995, OutbreakCrash = 4) {
NYEARS = length(Years)
# browser()
## MAKE THESE FIXED FOR NOW
SexRatio = masterDF[rep, "SexRatio"]
ConsRate = as.vector(masterDF[rep, 2:3])
PCFParams = c(masterDF[rep, "avgPCF"], masterDF[rep,"sdPCF"])
# avgPCF = masterDF[1, "avgPCF"]
# sdPCF = masterDF[1, "sdPCF"]
COTSmort = as.numeric(masterDF[rep, c("mortJ1", "mortJ2", "mortA")])
COTSremain = as.numeric(masterDF[rep, c("remJ1", "remJ2", "remA")])
COTS_StableStage = as.numeric(masterDF[rep, c("cssJ1", "cssJ2", "cssA")])
Pred = masterDF[,"Pred"]
p = masterDF[,"p"]
Crash = masterDF[,"Crash"]
# Initialize
npops=npops
seasons=seasons
PopData = PopData[1:npops, ]
data.COTS = data.COTS[1:npops, ]
data.grid = data.grid[1:npops, ]
# Work out which reefs from our connectivity matrix are to be included
# which reefs from npops are being used in the analysis
whichreefs = unique(data.grid$REEF_NAME[1:npops])
ConnMat = COTS.ConnMat[1:length(whichreefs), 1:length(whichreefs)]
Pixels = Pixels[1:length(colnames(ConnMat)),]
FvDParams=FvDParams
# CoralCover=data.grid$pred.HCini.mean[1:npops]
# # B0=data.grid$pred.b0.mean[1:npops]
# # HC.asym=data.grid$pred.HCmax.mean[1:npops]
# # WQ <- data.grid$Primary + data.grid$Secondary + data.grid$Tertiary
if(COTSfromSimul==F){
COTSabund <- matrix(0,nrow=npops, ncol=3)
}
COTSabund = initializeCOTSabund(data.grid, data.COTS, inityear, stagenames, COTS_StableStage) # initialize the COTS abundance object (for year 0)
print(length(COTSabund[,3]))
Results = data.frame(sapply(PopData[1:4], rep, times=NYEARS*NSEASONS),
sapply(PopData[5:7], rep, times=NYEARS*NSEASONS),
Year=rep(Years,each=2*npops), Season=rep(c("summer", "winter"),each=npops),
COTSJ1=NA, COTSJ2=NA, COTSA=NA, CoralCover=NA, CoralCover.DistLoss=NA)
Results$CoralCover.Consum = NA
Results$CoralCover.Growth = NA
######
res.cc = array(NA, dim=c(dim(data.grid)[1], nyears*2, nsimul))
res.cots = array(NA, dim=c(dim(data.grid)[1], nyears*2, nsimul))
##### TURN OFF COTS FUNCTIONS TO RUN CORAL GROWTH AND DISTURBANCE
# Simulation loop
for (j in 1:nsimul) {
# year Loop
for(i in 1:length(Years)){
print(i + 1995)# loop through years
for(season in seasons){
if(browse == TRUE) {
browser()
}
COTSabund = doPredPreyDynamics(COTSabund, CoralCover, p, Crash)
COTSabund = doCOTSDispersal(season,COTSabund,SexRatio,ConnMat, PCFParams, Pred, FvDParams) #Pruducing NAS
COTSabund = doCOTSDemography(season, COTSabund, COTSmort, COTSremain)
Consumption = doCoralConsumption(season, COTSabund, CoralCover, ConsRate)
CoralCover = Consumption[,'CRemaining']
CoralConsum = round(Consumption[,'CChange'],4)
CoralCover.Dist = doCoralDisturbance(i, j, season, CoralCover,
COTSfromCoralModel = COTSfromCoralModel)
Disturbance = CoralCover.Dist - CoralCover
CoralCover = CoralCover.Dist
Growth = doCoralGrowth(season, CoralCover)
CoralCover = Growth[,'CoralCover']
CoralGrowth = round(Growth[,'CoralGrowth'],4)
# Calculate COTS/Manta at Reef Level for 4 years, if its >1 for 4 consecutive years then crash pop
# browser()
# Results[(Results$Year==i+1995) & (Results$Season==season),
# c("COTSJ1", "COTSJ2", "COTSA", "CoralCover", "CoralCover.DistLoss", "CoralCover.Consum", 'CoralCover.Growth')] =
# cbind(COTSabund, CoralCover, Disturbance, CoralConsum, CoralGrowth)
if(i>3 & season =="winter") {
OutbreakCrasher = Results %>%
dplyr::filter(Year > (i+1995-OutbreakCrash) & Year <= i+1995) %>%
group_by(REEF_NAME, Year) %>%
summarise(Mean.COTS = mean(COTSA)) %>%
mutate(is.outbreak = ifelse(Mean.COTS > 1, 1,0)) %>%
group_by(REEF_NAME) %>%
summarise(Crash = ifelse(sum(is.outbreak)==6,1,0)) %>%
filter(Crash==1)
matchit = match(data.grid$REEF_NAME,OutbreakCrasher$REEF_NAME)
COTSabund[which(!is.na(matchit)),] = c(0,0,0)
} # Close outbreak crasher
# Store in array
if (season=="summer") {
res.cc[,i,j] = CoralCover
res.cots[,i,j] = COTSabund[,3]
}
res.cc[,i+1,j] = CoralCover
res.cots[,i+1,j] = COTSabund[,3]
} # close season loop
} # close Year loop
# setwd(RESULTS_DIRECTORY)
# name <- sprintf("Sample_%s.Rdata",j)
# save(Results, file=name)
# print(j)
}
# Summarise Results Array
### Compute HC stats at reef, cluster and bioregion levels in each year {
resCC.reef <- array(0, dim=c(length(unique(data.grid$REEF_ID)), nyears*2, nsimul))
resCC.cluster <- array(0, dim=c(length(unique(data.grid$bent.clust)), nyears*2, nsimul))
resCOTS.reef <- array(0, dim=c(length(unique(data.grid$REEF_ID)), nyears*2, nsimul))
resCOTS.cluster <- array(0, dim=c(length(unique(data.grid$bent.clust)), nyears*2, nsimul))
# res.bioregion <- array(0, dim=c(length(unique(data.grid$BIOREGION)), nyears, nsimul))
for (i in 1:dim(res.cc)[3]) {
resCC.reef[,,i] <- as.matrix(aggregate(res.cc[,,i], by=list(data.grid$REEF_ID),
FUN=mean, na.rm=T)[-1])
resCC.cluster[,,i] <- as.matrix(aggregate(res.cc[,,i], by=list(data.grid$bent.clust),
FUN=mean, na.rm=T)[-1])
resCOTS.reef[,,i] <- as.matrix(aggregate(res.cots[,,i], by=list(data.grid$REEF_ID),
FUN=mean, na.rm=T)[-1])
resCOTS.cluster[,,i] <- as.matrix(aggregate(res.cots[,,i], by=list(data.grid$bent.clust),
FUN=mean, na.rm=T)[-1])
# res.bioregion[,,i] <- as.matrix(aggregate(res[,,i], by=list(data.grid$BIOREGION), FUN=mean, na.rm=T)[-1])
}
### Compute HC stats for each grid cell and reef/cluster/bioregion and in each year
# (e.g. median, quartiles, 95% CI) and store them each in a matrix
# resCC.mn <- apply(res.cc, c(1,2), mean, na.rm=T)
# resCC.med <- apply(res.cc, c(1,2), median, na.rm=T)
# resCC.min <- apply(res.cc, c(1,2), quantile, probs=0.05, na.rm=T)
# resCC.max <- apply(res.cc, c(1,2), quantile, probs=0.95, na.rm=T)
# resCC.25 <- apply(res.cc, c(1,2), quantile, probs=0.25, na.rm=T)
# resCC.75 <- apply(res.cc, c(1,2), quantile, probs=0.75, na.rm=T)
#
# resCOTS.mn <- apply(res.cots, c(1,2), mean, na.rm=T)
# resCOTS.med <- apply(res.cots, c(1,2), median, na.rm=T)
# resCOTS.min <- apply(res.cots, c(1,2), quantile, probs=0.05, na.rm=T)
# resCOTS.max <- apply(res.cots, c(1,2), quantile, probs=0.95, na.rm=T)
# resCOTS.25 <- apply(res.cots, c(1,2), quantile, probs=0.25, na.rm=T)
# resCOTS.75 <- apply(res.cots, c(1,2), quantile, probs=0.75, na.rm=T)
#
# resCC.gbr.mn <- colMeans(resCC.mn, na.rm=T)
# resCC.gbr.med <- colMeans(resCC.med, na.rm=T)
# resCC.gbr.min <- colMeans(resCC.min, na.rm=T)
# resCC.gbr.max <- colMeans(resCC.max, na.rm=T)
# resCC.gbr.25 <- colMeans(resCC.25, na.rm=T)
# resCC.gbr.75 <- colMeans(resCC.75, na.rm=T)
#
# resCOTS.gbr.mn <- colMeans(resCOTS.mn, na.rm=T)
# resCOTS.gbr.med <- colMeans(resCOTS.med, na.rm=T)
# resCOTS.gbr.min <- colMeans(resCOTS.min, na.rm=T)
# resCOTS.gbr.max <- colMeans(resCOTS.max, na.rm=T)
# resCOTS.gbr.25 <- colMeans(resCOTS.25, na.rm=T)
# resCOTS.gbr.75 <- colMeans(resCOTS.75, na.rm=T)
resCC.reef.mn <- apply(resCC.reef, c(1,2), mean, na.rm=T)
resCC.reef.med <- apply(resCC.reef, c(1,2), median, na.rm=T)
resCC.reef.min <- apply(resCC.reef, c(1,2), quantile, probs=0.05, na.rm=T)
resCC.reef.max <- apply(resCC.reef, c(1,2), quantile, probs=0.95, na.rm=T)
resCC.reef.25 <- apply(resCC.reef, c(1,2), quantile, probs=0.25, na.rm=T)
resCC.reef.75 <- apply(resCC.reef, c(1,2), quantile, probs=0.75, na.rm=T)
resCOTS.reef.mn <- apply(resCOTS.reef, c(1,2), mean, na.rm=T)
resCOTS.reef.med <- apply(resCOTS.reef, c(1,2), median, na.rm=T)
resCOTS.reef.min <- apply(resCOTS.reef, c(1,2), quantile, probs=0.05, na.rm=T)
resCOTS.reef.max <- apply(resCOTS.reef, c(1,2), quantile, probs=0.95, na.rm=T)
resCOTS.reef.25 <- apply(resCOTS.reef, c(1,2), quantile, probs=0.25, na.rm=T)
resCOTS.reef.75 <- apply(resCOTS.reef, c(1,2), quantile, probs=0.75, na.rm=T)
# resCC.cluster.med <- apply(resCC.cluster, c(1,2), median, na.rm=T)
# resCC.cluster.mn <- apply(resCC.cluster, c(1,2), mean, na.rm=T)
# resCC.cluster.min <- apply(resCC.cluster, c(1,2), quantile, probs=0.05, na.rm=T)
# resCC.cluster.max <- apply(resCC.cluster, c(1,2), quantile, probs=0.95, na.rm=T)
# resCC.cluster.25 <- apply(resCC.cluster, c(1,2), quantile, probs=0.25, na.rm=T)
# resCC.cluster.75 <- apply(resCC.cluster, c(1,2), quantile, probs=0.75, na.rm=T)
#
# resCOTS.cluster.med <- apply(resCOTS.cluster, c(1,2), median, na.rm=T)
# resCOTS.cluster.mn <- apply(resCOTS.cluster, c(1,2), mean, na.rm=T)
# resCOTS.cluster.min <- apply(resCOTS.cluster, c(1,2), quantile, probs=0.05, na.rm=T)
# resCOTS.cluster.max <- apply(resCOTS.cluster, c(1,2), quantile, probs=0.95, na.rm=T)
# resCOTS.cluster.25 <- apply(resCOTS.cluster, c(1,2), quantile, probs=0.25, na.rm=T)
# resCOTS.cluster.75 <- apply(resCOTS.cluster, c(1,2), quantile, probs=0.75, na.rm=T)
nReefs = length(unique(data.grid$REEF_ID))
# Results df for Dashboard -- Reef Level
ResultsDash = data.frame(sapply(unique(data.grid[4:5]), rep, times=NYEARS*NSEASONS),
Year=rep(Years,each=2*nReefs),
Season=rep(c("summer", "winter"),each=nReefs),
COTS.mn=(as.vector(resCOTS.reef.mn)/100)*15,
COTS.Q50=(as.vector(resCOTS.reef.med)/100)*15,
COTS.Q05=(as.vector(resCOTS.reef.min)/100)*15,
COTS.Q95=(as.vector(resCOTS.reef.max)/100)*15,
COTS.Q25=(as.vector(resCOTS.reef.25)/100)*15,
COTS.Q75=(as.vector(resCOTS.reef.75)/100)*15,
CC.mn=as.vector(resCC.reef.mn),
CC.Q50=as.vector(resCC.reef.med),
CC.Q05=as.vector(resCC.reef.min),
CC.Q95=as.vector(resCC.reef.max),
CC.Q25=as.vector(resCC.reef.25),
CC.Q75=as.vector(resCC.reef.75))
# Compute mean disturbance impact across simulations
for (i in 1:nsimul) bleaching.rsmpl[,,i][is.na(bleaching.rsmpl[,,i])] <- 0
bleaching.mn <- apply(bleaching.rsmpl, c(1,2), mean, na.rm=T)
COTS.mn <- apply(COTS.rsmpl, c(1,2), mean, na.rm=T)
disease.mn <- apply(disease.rsmpl, c(1,2), mean, na.rm=T)
storms.mn <- apply(storms.rsmpl, c(1,2), mean, na.rm=T)
unknown.mn <- apply(unknown.rsmpl, c(1,2), mean, na.rm=T)
# Make list of objects to save --> all results and disturbances
setwd(RESULTS_DIRECTORY)
name <- sprintf("Results_%s.Rdata",j)
save(res.cc, res.cots, ResultsDash, file=name)
}
```
# Simulations
## COTS initiated via interpolated manta tow densities
## COTS initiated via Hypothesised initiation locations (Lizard + Green Island)
# Power BI Interactive Results Viewer
```{r, eval=F}
##### TESTING ----
# for (j in 1:10){
# runModel(masterDF=masterDF, Years = 1996:2017, PopData=PopData[1:npops,],data.COTS = data.COTS[1:npops,],
# data.grid = data.grid[1:npops,], rep=1, Pred=0.98, p=0.25, Crash = 3,
# nsimul = 10, j=j, COTSfromCoralModel = FALSE, COTSfromSimul = TRUE, browse = F, inityear = 1996)
# }
# NREPS = 10
# DataHarvest.TEST = HarvestData(RESULTS_DIRECTORY)
# CC.TEST = as.data.frame(DataHarvest.TEST[[2]]) %>%
# tidyr::gather(key = "Simulation", value = "CoralCover", 4:13) %>%
# group_by(PIXEL_ID, Year, Season) %>%
# summarise(Avg.CC1 = mean(CoralCover),
# Serr.CC1 = sd(CoralCover)/sqrt(n()))
# COTS.TEST = as.data.frame(DataHarvest.TEST[[1]]) %>%
# tidyr::gather(key = "Simulation", value = "COTS", 4:13) %>%
# dplyr::group_by(PIXEL_ID, Year, Season) %>%
# mutate(COTS = (COTS/100)*0.15) %>%
# dplyr::summarise(Avg.COTS = mean(COTS),
# Serr.COTS = sd(COTS)/sqrt(n()))
# ForDashboard.TEST = dplyr::left_join(COTS.TEST, data.grid[,1:7], by="PIXEL_ID") #%>% dplyr::select(1,14:19,2:14)
#####
runModel(masterDF=masterDF, Years = 1996:2017, PopData=PopData[1:npops,],data.COTS = data.COTS[1:npops,],
data.grid = data.grid[1:npops,], rep=1, Pred=0.98, p=0.25, Crash = 3,
nsimul = 10, COTSfromCoralModel = TRUE, COTSfromSimul = FALSE, browse = F, inityear = 1996,)
library(dplyr)
NREPS = 100
for (j in 1:nsimul){
runModel(masterDF=masterDF, Years = 1996:2017, PopData=PopData[1:npops,],data.COTS = data.COTS[1:npops,],
data.grid = data.grid[1:npops,], rep=1, Pred=0.98, p=0.25, Crash = 3,
nsimul = 100, j=j, COTSfromCoralModel = TRUE, COTSfromSimul = FALSE, browse = F, inityear = 1996)
}
DataHarvest.NoCOTS = HarvestData(RESULTS_DIRECTORY)
for (j in 1:nsimul){
runModel(masterDF=masterDF, Years = 1996:2017, PopData=PopData[1:npops,],data.COTS = data.COTS[1:npops,],
data.grid = data.grid[1:npops,], rep=1, Pred=0.98, p=0.25, Crash = 3,
nsimul = 100, j=j, COTSfromCoralModel = FALSE, COTSfromSimul = TRUE, browse = F, inityear = 1996, OutbreakCrash = 4)
}
DataHarvest.4YearCrash = HarvestData(RESULTS_DIRECTORY)
for (j in 1:nsimul){
runModel(masterDF=masterDF, Years = 1996:2017, PopData=PopData[1:npops,],data.COTS = data.COTS[1:npops,],
data.grid = data.grid[1:npops,], rep=1, Pred=0.98, p=0.25, Crash = 3,
nsimul = 100, j=j, COTSfromCoralModel = FALSE, COTSfromSimul = TRUE, browse = F, inityear = 1996, OutbreakCrash = 5)
}
DataHarvest.5YearCrash = HarvestData(RESULTS_DIRECTORY)
for (j in 1:nsimul){
runModel(masterDF=masterDF, Years = 1996:2017, PopData=PopData[1:npops,],data.COTS = data.COTS[1:npops,],
data.grid = data.grid[1:npops,], rep=1, Pred=0.98, p=0.25, Crash = 3,
nsimul = 100, j=j, COTSfromCoralModel = FALSE, COTSfromSimul = TRUE, browse = F, inityear = 1996, OutbreakCrash = 6)
}
DataHarvest.6YearCrash = HarvestData(RESULTS_DIRECTORY)
# nsimul = 100
# for (j in 1:nsimul){
# runModel(masterDF=masterDF, Years = 1996:2017, PopData=PopData[1:npops,],data.COTS = data.COTS[1:npops,],
# data.grid = data.grid[1:npops,], rep=1, Pred=0.98, p=0.25, Crash = 3,
# nsimul = 100, j=j, COTSfromCoralModel = FALSE, COTSfromSimul = TRUE, browse = F, inityear = 1994)
# }
# DataHarvest.wCOTS94 = HarvestData(RESULTS_DIRECTORY)
# CC.NoCOTS = as.data.frame(DataHarvest.NoCOTS[[2]]) %>%
# tidyr::gather(key = "Simulation", value = "CoralCover", 4:103) %>%
# group_by(PIXEL_ID, Year, Season) %>%
# summarise(Avg.CC = mean(CoralCover),
# Serr.CC = sd(CoralCover)/sqrt(n()))