-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathJABBA_SELECTv1.1.R
2388 lines (1853 loc) · 87.6 KB
/
JABBA_SELECTv1.1.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
##><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><><><
## JABBA-SELECT: JABBA extension to integrate Life History and Selectivity Distortion
## #Executeable to JABBA-SELECT
## written by Henning Winker
## henning.winker@gmail.com
##><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>
Mod.names = "JS"
cat(paste0("\n","- Run Model ",Mod.names,"\n"))
#setwd(paste(File))
dir.create(paste0(File,"/",assessment,"/",Scenario,"_",Mod.names),showWarnings = F)
dir.create(paste0(File,"/",assessment,"/",Scenario,"_",Mod.names,"/Input"),showWarnings = F)
input.dir = paste0(File,"/",assessment,"/",Scenario,"_",Mod.names,"/Input")
#><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>
# Define objects to make sure they exist
#><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>
if(exists("proc.type")==FALSE) proc.type = "igamma" # Produces JABBA Kobe plot
if(exists("pr.proc")==FALSE) igamma = c(4,0.01) # Produces JABBA Kobe plot
if(exists("Plim")==FALSE) Plim = 0 # Produces JABBA Kobe plot
if(exists("KOBE.plot")==FALSE) KOBE.plot = TRUE # Produces JABBA Kobe plot
if(exists("KOBE.type")==FALSE) KOBE.type = c("ICCAT","IOTC")[2] # ICCAT uses 3 colors; IOTC 4 (incl. orange)
if(exists("SP.plot")==FALSE) SP.plot = c("standard","phase")[2] # Produces standard or 'Kobe phase' SP plot
if(exists("Biplot")==FALSE) Biplot= TRUE # Produces a "post-modern" biplot with buffer and target zones (Quinn & Collie 2005)
if(exists("save.trajectories")==FALSE) save.trajectories =FALSE # saves posteriors of P=B/K, B/Bmsy and H/Hmsy as .RData object
if(exists("catch.metric")==FALSE) catch.metric = "(t)" # Runs state-tool to produce "alligned" multi-CPUE plot
if(exists("harvest.label")==FALSE) harvest.label = c("Hmsy","Fmsy")[1] # choose label preference H/Hmsy versus Fmsy
if(exists("CPUE.plot")==FALSE) CPUE.plot= TRUE # Runs state-tool to produce "alligned" multi-CPUE plot
if(exists("meanCPUE")==FALSE) meanCPUE = TRUE # Uses averaged CPUE from state-space tool instead of individual indices
if(exists("Projection")==FALSE) Projection = FALSE # Use Projections: requires to define TACs vectors
if(exists("TACint")==FALSE) TACint = mean(apply(catch[(nrow(catch)-2):nrow(catch),-1],1,sum,na.rm=TRUE)) # use mean catch from last years
if(exists("save.projections")==FALSE) save.projections = FALSE# saves projection posteriors as .RData object
if(exists("imp.yr")==FALSE) imp.yr = max(catch[,1])+1
if(exists("Reproduce.seed")==FALSE) Reproduce.seed = FALSE # If FALSE a random seed assigned to each run (default)
if(exists("P_bound")==FALSE) P_bound = c(0.02,1.3) # Soft penalty bounds for P
if(exists("q_bounds")==FALSE) q_bounds= c(10^-30,1000) # Defines lower and upper bounds for q
if(exists("sigmaobs_bound")==FALSE) sigmaobs_bound = 1 # Adds an upper bound to the observation variance
if(exists("sigmaproc_bound")==FALSE) sigmaproc_bound = 0.2 # Adds an upper bound to the process variance
if(exists("SB0_bounds")==FALSE) SB0_bounds= c(0.01,10^10) # Defines lower and upper bounds for q
if(exists("runASEM")==FALSE) runASEM = TRUE # Run Monte-Carlo ASEM
if(exists("PlusGroup")==FALSE) PlusGroup = FALSE # if TRUE add PlusGroup to ASEM
if(exists("init.values")==FALSE) init.values = FALSE # Option to fix init values of q's and SB0
if(exists("nsexes")==FALSE) nsexes = 1
if(exists("SELECT")==FALSE) SELECT = TRUE
if(exists("save.all")==FALSE) save.all = FALSE #
if(exists("SBmsy_SB0")==FALSE) SBmsy_SB0 = NULL
if(exists("proc.dev.all")==FALSE) proc.dev.all=TRUE
refB = ifelse(is.null(SBmsy_SB0)==FALSE,paste(SBmsy_SB0*100),"MSY")
if(exists("p")==FALSE) p=0
if(exists("GFUN")==FALSE) GFUN = 1 # Plan to implement alternative growth function
if(exists("jabba2FRL")==FALSE) jabba2FRL = FALSE
if(sigma.proc==FALSE){
pr.proc=c(2,2)
}
#><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>
#-------------------------
# Prepare input data
#-------------------------
indices = names(cpue)[2:ncol(cpue)]
n.indices = max(length(indices),1)
catches = names(catch)[2:ncol(catch)]
n.catches = length(catches)
years=catch[,1]
styr = min(years)
endyr = max(years)
n.years = length(years)
styr.cpue = min(cpue[,1])
styr.I = styr.cpue-styr+1
# Convert input data to matrices
conv.cpue = as.numeric(rbind(matrix(rep(NA,(styr.I-1)*n.indices),styr.I-1,n.indices),as.matrix(cpue[,-1])))
CPUE=matrix(conv.cpue,nrow=n.years,ncol=n.indices)
if(SE.I==FALSE){
se = cpue
conv.se = as.numeric(rbind(matrix(rep(NA,(styr.I-1)*n.indices),styr.I-1,n.indices),as.matrix(cpue[,-1])))
se2 = matrix(ifelse(fixed.obsE>0,fixed.obsE^2,10^-10),n.years,n.indices)#/2
} else{
conv.se = as.numeric(rbind(matrix(rep(NA,(styr.I-1)*n.indices),styr.I-1,n.indices),as.matrix(se[,-1])))
#conv.se = sqrt(conv.se^2+fixed.obsE^2)
se2 = matrix(ifelse(is.na(conv.se),0.3^2,conv.se)^2,n.years,n.indices)+fixed.obsE^2#/2
}
conv.catch = 0.00001+as.numeric(rbind(matrix(rep(NA,(styr.I-1)*n.catches),styr.I-1,n.catches),as.matrix(catch[,-1])))
Catch=matrix(conv.catch,nrow=n.years,ncol=n.catches)
Catch[is.na(Catch)] = 0.00001 # Replace any NA by zero
# Total Catch
TC = apply(Catch,1,sum)
# hindcast option
if(exists("tails")==FALSE) tails = max(years)
if(tails<max(years)){
cpue.raw = read.csv(paste0(File,"/",assessment,"/cpue",assessment,".csv"))
cpue.raw = cpue.raw[which(cpue.raw$Yr%in%years),which(colnames(cpue.raw)%in%colnames(cpue))]
} else {
cpue.raw = cpue
}
#---------------------
# Index color palette
#---------------------
jabba.colors = as.character(c("#e6194b", "#0082c8","#3cb44b",
"#f58231", "#911eb4",
"#46f0f0", "#f032e6", "#d2f53c",
"#fabebe", "#008080","#e6beff", "#aa6e28","#ffe119",rainbow(12)[seq(1,12,3)],rainbow(12)[seq(2,12,3)],rainbow(12)[seq(3,12,3)]))
#####################################################################################
# Plot Catch
cat(paste0("\n","- Plot Catch in Input subfolder","\n"))
Par = list(mfrow=c(1,1),mar = c(5, 5, 1, 1), mgp =c(3,1,0), tck = -0.02,cex=0.8)
png(file = paste0(input.dir,"/Catches_",assessment,".png"), width = 7, height = 5,
res = 200, units = "in")
par(Par)
catch[is.na(catch)]=0
xpol = c(years,rev(years))
plot(years,TC,ylim=c(0,max(TC)),ylab=paste0("Catch ",catch.metric),xlab="Year",type="n")
Cacc = rep(0,length(catch[,1]))
for(i in 2:ncol(catch)){
polygon(xpol,c(Cacc,rev(Cacc+catch[,i])),col=jabba.colors[i])
Cacc=Cacc+catch[,i]
lines(catch[,1],Cacc,lty=(1),lwd=1,col=1)
}
legend("topleft",paste(names(catch)[2:ncol(catch)]),pt.cex=1.5,pch=22,pt.bg=jabba.colors[-1],bty="n",cex=1)
dev.off()
#--------------------------
# Capture Stock Parameters
#--------------------------
stockpars = list(minage=minage,maxage=maxage,nsexes=nsexes,PlusGroup=PlusGroup,
Growth= paste0("VBGF (Linf, k, t0)"), vb.female= c(Linf[1],kappa[1],t0[1]),vb.male= c(Linf[1],kappa[1],t0[1]),
LW = paste0("Length-Weight relationship (a,b)"),
lw.female = as.numeric(c(aW[1],bW[1])),
lw.male = as.numeric(c(aW[2],bW[2])),
Maturation= paste0("Maturity@", ifelse(maturity[3]==1,"Age","Length"),"(50%, 95%)"),
maturity = maturity[1:2],
NatMortality = "Natural Mortality (M): Mean, CV",
M = c(M,CV.M),
SSR = "B&H steepness (h): mean, CV",
h = c(h,CV.h)
)
#------------------------------------------------
# Selectivity will determine changes in r (Fmsy)
#------------------------------------------------
# Selectivity SL50 must be sufficiently different (+-5%) to seperate r
# only unique SL50 values (no replicates)
# Selectivity SL50 must be sufficiently different (+-5%) between "fleets" to seperate r
SL50 <- as.numeric(selex[1,-1])
SL95 <- as.numeric(selex[2,-1]) # If unknown set to 0.05*SL50 ~ knife-edge
# Define point where descening limb starts (set Linf for logistic)
SL.desc <-as.numeric(selex[3,-1]) # mean of half-normal
# Define rate of decreasing selectivity
CV.desc <- as.numeric(selex[4,-1]) # CV of half-normal
# Define minimum descending limp between 0 and 1
min.desc =as.numeric(selex[5,-1])
# number of different Hmsy (r) priors
nSel = length(SL50)
# Translate NAs
SL.desc[is.na(SL.desc)] =rep(Linf,nSel)
CV.desc[is.na(CV.desc)] =rep(0.1,nSel)
min.desc[is.na(min.desc)] =rep(0.001,nSel)
#---------------------------------------------------------------
# Compile fleet/index settings from selex and select input files
#---------------------------------------------------------------
# Assign Selectivity to abundance indices
sets.I = select$Selectivity[select$CPUE]
# Assign Selectivity to catch series
sets.C = select$Selectivity[select$Catch] # here 1: South, 2: South-East, 3: Trawl
# Define if index is in numbers: 0 or biomass: 1
I.unit = select$CPUE.units[select$CPUE]
# Reduce JABBA-Select to Pella-Tomlison Model
if(SELECT==FALSE){nSel = 1; nsexes=1; sets.C = rep(1,length(sets.C));sets.I = rep(1,length(sets.I));I.unit = rep(1,length(I.unit))}
#--------------------
# Set seed
#--------------------
if(Reproduce.seed==FALSE){
get_seed = ceiling(runif(1,min=0,max=1e6)) } else {get_seed = 123}
set.seed(get_seed)
#---------------------------------------------------------------------------
# CPUE run State-Space model for averaging CPUE
#---------------------------------------------------------------------------
if(CPUE.plot==TRUE){
cat(paste0("\n","><> Run State-Space CPUE averaging tool","\n"))
#find first time-series with first CPUE
q1.y = c(1:n.years)[is.na(apply(CPUE,1,mean,na.rm=TRUE))==FALSE][1] #first year with CPUE
q1.I = which.max(CPUE[q1.y,])
qs = c(q1.I,c(1:(ncol(cpue)-1))[-q1.I])
sink("cpueAVG.jags")
cat("
model {
# Prior specifications
eps <- 0.0000000000001 # small constant
iq[1] ~ dgamma(1000,1000)
q[1] <- pow(iq[1],-1)
logq[1] <- log(1)
for(i in 2:nI){
iq[i] ~ dgamma(0.001,0.001)
q[i] <- pow(iq[i],-1)
logq[i] <- log(q[i])
}
")
if(sigma.proc==TRUE){
cat("
# Process variance
isigma2 <- isigma2.est
sigma2 <- pow(isigma2,-1)
sigma <- sqrt(sigma2)
fakesigma.fixed <- sigma.fixed # Prevent unused variable error msg
",append=TRUE)
}else{ cat("
isigma2 <- pow(sigma.fixed+eps,-2)
sigma2 <- pow(isigma2,-1)
sigma <- sqrt(sigma2)
",append=TRUE)}
if(sigma.est==TRUE){
cat("
# Obsevation variance
# Observation error
itau2~ dgamma(0.001,0.001)
tau2 <- 1/itau2
for(i in 1:nI)
{
for(t in 1:N)
{
var.obs[t,i] <- SE2[t,i]+tau2
ivar.obs[t,i] <- 1/var.obs[t,i]
# note total observation error (TOE)
TOE[t,i] <- sqrt(var.obs[t,i])
}}
",append=TRUE)
}else{ cat("
# Obsevation variance
# Observation error
itau2~ dgamma(2,2)
tau2 <- 1/itau2
for(i in 1:nI)
{
for(t in 1:N)
{
var.obs[t,i] <- SE2[t,i] # drop tau2
fake.tau[t,i] <- tau2
ivar.obs[t,i] <- 1/var.obs[t,i]
# note total observation error (TOE)
TOE[t,i] <- sqrt(var.obs[t,i])
}}
",append=TRUE)}
# Run rest of code
cat("
# Process variance prior
isigma2.est ~ dgamma(0.001,0.001)
# Priors and constraints
logY.est[1] ~ dnorm(logY1, 1) # Prior for initial population size
mean.r ~ dnorm(1, 0.001) # Prior for mean growth rate
# Likelihood
# State process
for (t in 1:(N-1)){
r[t] ~ dnorm(mean.r, isigma2)
logY.est[t+1] <- logY.est[t] + r[t] }
# Observation process
for (t in 1:N) {
for(i in 1:nI){
y[t,i] ~ dnorm(logY.est[t]+logq[i], ivar.obs[t,i])
}}
# Population sizes on real scale
for (t in 1:N) {
Y.est[t] <- exp(logY.est[t])
}
}
",fill = TRUE)
sink()
q.init = 1
mCPUE = as.matrix(CPUE[q1.y:n.years,qs])
mSE2 = as.matrix(se2[q1.y:n.years,qs])
if(n.indices>1) for(i in 2:n.indices){q.init[i] = mean(mCPUE[,i],na.rm=TRUE)/mean(mCPUE[,1],na.rm=TRUE)}
# Bundle data
jags.data <- list(y = log(mCPUE),SE2=mSE2, logY1 = log(mCPUE[1,1]), N = length(q1.y:n.years),nI=n.indices,sigma.fixed=ifelse(sigma.proc==TRUE,0,sigma.proc))
# Initial values
inits <- function(){list(isigma2.est=runif(1,20,100), itau2=runif(1,80,200), mean.r = rnorm(1),iq = 1/q.init)}
# Parameters monitored
parameters <- c("mean.r", "sigma","r", "Y.est","q")
# Call JAGS from R (BRT 3 min)
mod.cpue <- jags(jags.data, inits, parameters, "cpueAVG.jags", n.chains = nc, n.thin = max(nt,2), n.iter = max(ni/5,10000), n.burnin = nb/10)
cat(paste0("\n","><> Plot State-Space CPUE fits in Input subfolder <><","\n"))
# get individual trends
fitted <- lower <- upper <- NULL
cpue.yrs = years[q1.y:n.years]
for (t in 1:nrow(mCPUE)){
fitted[t] <- median(mod.cpue$BUGSoutput$sims.list$Y.est[,t])
lower[t] <- quantile(mod.cpue$BUGSoutput$sims.list$Y.est[,t], 0.025)
upper[t] <- quantile(mod.cpue$BUGSoutput$sims.list$Y.est[,t], 0.975)}
q.adj = apply(mod.cpue$BUGSoutput$sims.list$q,2,median)
Par = list(mfrow=c(1,1),mar = c(3.5, 3.5, 0.1, 0.1), mgp =c(2.,0.5,0), tck = -0.02,cex=0.8)
png(file = paste0(input.dir,"/CPUE_",assessment,"_",Scenario,".png"), width = 5, height = 3.5,
res = 200, units = "in")
par(Par)
u.ylim = NULL
for(i in 1:n.indices){ u.ylim = c(u.ylim,exp(log(mCPUE[,i]/q.adj[i])+1.96*sqrt(mSE2[,i])))}
ylim = c(0,max(u.ylim,na.rm=TRUE))
plot(0, 0, ylim = ylim, xlim = range(cpue.yrs), ylab = "Expected CPUE", xlab = "Year", col = "black", type = "n")
legend("topright",paste(indices),lwd=2,col=(jabba.colors)[1:n.indices],bty="n")
polygon(x = c(cpue.yrs,rev(cpue.yrs)), y = c(lower,rev(upper)), col = "gray", border = "gray90")
for(i in 1:n.indices)
{
shift = runif(1,-0.1,0.1)
cols=jabba.colors[qs[i]]
plotCI(cpue.yrs+shift,mCPUE[,i]/q.adj[i],ui=exp(log(mCPUE[,i]/q.adj[i])+1.96*sqrt(mSE2[,i])),li=exp(log(mCPUE[,i]/q.adj[i])-1.96*sqrt(mSE2[,i])),add=TRUE,col= cols,pt.bg = cols,pch=21,gap=0)
lines(cpue.yrs+shift,mCPUE[,i]/q.adj[i], col = cols,lwd=2)
points(cpue.yrs+shift,mCPUE[,i]/q.adj[i], bg = cols,pch=21)
}
lines(cpue.yrs,fitted,lwd=2)
dev.off()
logSE = apply(log(mod.cpue$BUGSoutput$sims.list$Y.est),2,sd)
if(nrow(mCPUE)<n.years) {
fitted = c(rep(NA,q1.y-1),fitted)
logSE = c(rep(0.2,q1.y-1),logSE)
}
avgCPUE = data.frame(Year=years,CPUE= fitted,logSE=logSE)
write.csv(avgCPUE,paste0(input.dir,"/avgCPUE_",assessment,"_",Scenario,".csv"))
if(meanCPUE==TRUE){
cat(paste0("\n","><> Use average CPUE as input for JABBA <><","\n"))
CPUE = as.matrix(avgCPUE[,2])
cpue.check = cpue[,-1]
cpue.check[is.na(cpue[,-1])]=0
CPUE[,1] = ifelse(apply(cpue.check,1,sum)==0,rep(NA,length(CPUE[,1])),CPUE[,1])
se2 = as.matrix(avgCPUE[,3]^2)
n.indices=1
indices = "All"
sets.q =1
sets.var =1
}
}
#--------------------------------------------------------------------------
# END of CPUE State-Space tool
#--------------------------------------------------------------------------
#################################################################
# FUNCTIONS
#################################################################
#--------------------------------------------------
# Function to get beta prior parameters
#--------------------------------------------------
get_beta <- function(mu,CV,Min=0,Prior="x"){
a = seq(0.0001,5000,0.001)
b= (a-mu*a)/mu
s2 = a*b/((a+b)^2*(a+b+1))
sdev = sqrt(s2)
# find beta )parameter a
CV.check = (sdev/mu-CV)^2
a = a[CV.check==min(CV.check)]
#find beta parameter
b = (a-mu*a)/mu
x = seq(Min,1,0.001)
pdf = dbeta(x,a,b)
plot(x,pdf,type="l",xlim=range(x[pdf>0.01]),xlab=paste(Prior),ylab="",yaxt="n",ylim=c(0,max(pdf*1.2)))
polygon(c(x,rev(x)),c(rep(0,length(x)),rev(ifelse(pdf==Inf,100000,pdf))),col="grey")
return(c(a,b))
}
get_gamma <- function(mu,CV,Prior="x"){
a = seq(0.0001,5000,0.0001)
b = a/mu
s2 = (a/b^2)
sdev = sqrt(s2)
# find beta )parameter a
CV.check = (sdev/mu-CV)^2
a = a[CV.check==min(CV.check)]
#find beta parameter b
b = a/mu
x = sort(rgamma(1000,a,b))
pdf = dgamma(x,a,b)
plot(x,pdf,type="l",xlim=range(x[pdf>0.01]),xlab=paste(Prior),ylab="",yaxt="n")
polygon(c(x,rev(x)),c(rep(0,length(x)),rev(ifelse(pdf==Inf,100000,pdf))),col="grey")
return(c(a,b))
}
# Bias corrected lognormal
plot_lnorm <- function(mu,CV,Prior="x"){
sdev= sqrt(log(CV^2+1))
rand.pr = rlnorm(1000,log(mu)-0.5*sdev^2,sdev)
x = seq(min(rand.pr),quantile(rand.pr,0.995),max(rand.pr/500))
pdf = dlnorm(x,log(mu)-0.5*sdev^2,sdev)
plot(x,pdf,type="l",xlim=range(x),xlab=paste(Prior),ylab="",yaxt="n")
polygon(c(x,rev(x)),c(rep(0,length(x)),rev(ifelse(pdf==Inf,100000,pdf))),col="grey")
return(c(exp(log(mu)-0.5*sdev^2),sdev))
}
#------------------------------------
# Function kobeJabba for FLR
#------------------------------------
kobeJabba<-function(x,minyear=1){
out=cbind(melt(x[,,2]),c(x[,,3]))
names(out)=c("iter","year","stock","harvest")
out$year=out$year+minyear-1
out}
#-------------------------------------------------
# Function kobeJabbaProj for projections with FLR
#-------------------------------------------------
kobeJabbaProj<-function(x,minyear=1,tac=NULL){
out=cbind(melt(x[,,,2]),c(x[,,,3]))
names(out)=c("iter","year","tac","stock","harvest")
out$year=out$year+minyear-1
out}
#---------------------------------------------------------------------------
# Equilibrium Age-structured Function:
# Computes Spawner Biomass (SB), Yield and Exploitable Biomass (EB)
# with Beverton and Holt spawner-recruitment relationship (S-R)
#---------------------------------------------------------------------------
# Input paramters
# Growth: Linf, K, t0 (Female,Male)
# Length-weight: aW (Female), bW (Male)
# Maturity: Lm50, dM (logistic)
# Longivity: tmax
# Harvest rate: H (Catch/Exploitable Biomass)
# Selectivity: SL50, dS (logistic)
# steepness: z
# Natural Mortality: M
# Harvest rate: H (Catch/Exploitable Biomass)
get_ASEM <- function(Linf,kappa,t0,aW,bW,minage,maxage,maturity,selpars,h,M,F_i,R0,PlusGroup=FALSE,nsexes=1,SELECT=TRUE){
age = minage:maxage
nages = length(age)
ntilda_f = mat.or.vec(length(F_i),nages)
ntilda_m = mat.or.vec(length(F_i),nages)
#Length-at-age
L_f = Linf[1]*(1-exp(-kappa[1]*(age-t0[1])))
L_m = Linf[nsexes]*(1-exp(-kappa[nsexes]*(age-t0[nsexes])))
if(t0[1]>=0) L_f[1] = 0.1
if(t0[nsexes]>=0) L_f[2] = 0.1
# Weight-at-age
W_f = aW[1]*L_f^bW[1]
W_m = aW[nsexes]*L_f^bW[nsexes]
# Maturity-at-age
if(maturity[3]==1){
mat = 1/(1+exp(-log(19)*(age-maturity[1])/(maturity[2]-maturity[1])))
} else {
mat = 1/(1+exp(-log(19)*(L_f-maturity[1])/(maturity[2]-maturity[1])))
}
#Selectivity-at-age (logistic/Domeshaped)
if(SELECT==TRUE){
sel_a_f = 1/(1+exp(-log(19)*(L_f-selpars[1])/(selpars[2]-selpars[1])))
sel_b_f = dnorm(L_f,selpars[3],selpars[3]*selpars[4])/max(dnorm(L_f,selpars[3],selpars[3]*selpars[4]))
sel_c_f = 1+(selpars[5]-1)*(sel_b_f-1)/(-1)
sel_f = as.numeric(ifelse(rep(selpars[3],length(L_f))>=L_f,sel_a_f,sel_c_f))
sel_a_m = 1/(1+exp(-log(19)*(L_m-selpars[1])/(selpars[2]-selpars[1])))
sel_b_m = dnorm(L_m,selpars[3],selpars[3]*selpars[4])/max(dnorm(L_m,selpars[3],selpars[3]*selpars[4]))
sel_c_m = 1+(selpars[5]-1)*(sel_b_m-1)/(-1)
sel_m = as.numeric(ifelse(rep(selpars[3],length(L_m))>=L_m,sel_a_m,sel_c_m))
} else {
sel_f = sel_m = mat
}
# Length-based for plotting
Li = seq(0,max(L_m,L_f),1)
LW=cbind(aW[1]*Li^bW[1],aW[nsexes]*Li^bW[nsexes])
if(maturity[3]==1){
aLi = t0[1]-1/kappa[1]*log(1-Li/Linf[1])
Lmat = 1/(1+exp(-log(19)*(aLi-maturity[1])/(maturity[2]-maturity[1])))
} else {
Lmat = 1/(1+exp(-log(19)*(Li-maturity[1])/(maturity[2]-maturity[1])))
}
if(SELECT==TRUE){
Lsel_a = 1/(1+exp(-log(19)*(Li-selpars[1])/(selpars[2]-selpars[1])))
Lsel_b = dnorm(Li,selpars[3],selpars[3]*selpars[4])/max(dnorm(Li,selpars[3],selpars[3]*selpars[4]))
Lsel_c = 1+(selpars[5]-1)*(Lsel_b-1)/(-1)
Lsel = as.numeric(ifelse(rep(selpars[3],length(Li))>=Li,Lsel_a,Lsel_c))
} else {
Lsel = Lmat
}
Ldat = data.frame(Li,LW,Lmat,Lsel)
Adat = data.frame(age,L_f,W_f,mat,L_m,W_m,sel_m)
# compute unfished Spawning biomass per recruit (SBR0)
n0_f = 0.5*exp(-(M*(0:(nages-1))))
if(PlusGroup==TRUE){
n0_f[nages] <- n0_f[nages]/(1-exp(-M))
}
# Only female spawning if 2 sexes
SBR0 = sum(n0_f*W_f*mat)*(2/nsexes)
# compute Spawning Biomass per rectuit as a function of F (SBR)
for (t in 1:nages)
{
if(t==1) ntilda_f[,t] <- 0.5
if(t>1) ntilda_f[,t] <- ntilda_f[,t-1]*exp(-(M+sel_f[t-1]*F_i))
if(PlusGroup==FALSE){
if(t==nages) ntilda_f[,t] <- ntilda_f[,t]
} else {
if(t==nages) ntilda_f[,t] <- ntilda_f[,t]/(1-exp(-(M+sel_f[t]*F_i)))
}
}
for (t in 1:nages)
{
if(t==1) ntilda_m[,t] <- 0.5
if(t>1) ntilda_m[,t] <- ntilda_m[,t-1]*exp(-(M+sel_m[t-1]*F_i))
if(PlusGroup==FALSE){
if(t==nages) ntilda_m[,t] <- ntilda_m[,t]
} else {
if(t==nages) ntilda_m[,t] <- ntilda_m[,t]/(1-exp(-(M+sel_m[t]*F_i)))
}
}
ntilda_f[ntilda_f < 0] = 0
ntilda_m[ntilda_m < 0] = 0
#get spawner biomass per recruit
SBR= apply(ntilda_f %*% diag(W_f) %*% diag(mat),1,sum)*(2/nsexes)
#get Yield per recruit
# get Z matrix
Z_f = M+t(sel_f%*%t(F_i))
Z_m = M+t(sel_m%*%t(F_i))
# Yield-per-recruit matrix
YPR = apply(ntilda_f %*% diag(W_f) %*% diag(sel_f)*F_i/Z_f*(1-exp(-Z_f)),1,sum)
YPR = YPR + apply(ntilda_m %*% diag(W_m) %*% diag(sel_m)*F_i/Z_m*(1-exp(-Z_m)),1,sum)
#get Exploitable Biomass per recruit
EBR = apply(ntilda_f %*% diag(W_f) %*% diag(sel_f),1,sum)
EBR = EBR + apply(ntilda_m %*% diag(W_m) %*% diag(sel_m),1,sum)
#get Exploitable Numbers per recruit
ENR = apply(ntilda_f %*% diag(sel_f),1,sum)
ENR = ENR + apply(ntilda_m %*% diag(sel_m),1,sum)
# equilibrium recruitment
RF = R0*(4*h*SBR-(1-h)*SBR0)/(SBR*(5*h-1))
recruits = ifelse(RF<0,0,RF)
# get spawner biomass depletion
SBtoSB0 = SBR*recruits/SBR0
# return Spawning Biomass as fraction of unfished levels
return(list(SBtoSB0=SBR*recruits/SBR0,Yield=YPR*recruits, EB=EBR*recruits,SB=SBR*recruits,EN=ENR*recruits,Ldat=Ldat,Adat=Adat))
}
#-----------------------------------------------------------
# Section for JABBA-SELECT
#-----------------------------------------------------------
# Plot stock functions
if(SELECT==TRUE){selpars = rbind(SL50,SL95,SL.desc,CV.desc,min.desc)}else{
selpars = rbind(Linf/3,Linf/2,SL.desc,CV.desc,min.desc)} # Unused place holder if SELECT == FALSE
stock = get_ASEM(Linf,kappa,t0,aW,bW,minage,maxage,maturity,selpars[,1],h=h,M=M,0,R0=1,PlusGroup,nsexes,SELECT)
Par = list(mfrow=c(2,2),mai=c(0.45,0.45,0,.15),omi = c(0.1,0.1,0.1,0) + 0.1,mgp=c(2,1,0), tck = -0.02,cex=0.7)
png(file = paste0(input.dir,"/StockFunctions_",assessment,".png"), width = 7, height = 6,
res = 200, units = "in")
cols=jabba.colors
par(Par)
plot(stock$Adat[,1],stock$Adat[,2],type="l",lwd=2,col=1,ylim=c(0,max(Linf)),xlab="Age",ylab="Length")
if(nsexes==2){lines(stock$Adat[,1],stock$Adat[,2],col=cols[1],lwd=2)
lines(stock$Adat[,1],stock$Adat[,5],col=cols[2],lwd=2)}
plot(stock$Ldat[,1],stock$Ldat[,2],type="l",lwd=2,col=1,ylim=c(0,max(stock$Ldat[,2])),xlab="Length",ylab="Weigth")
if(nsexes==2) {lines(stock$Ldat[,1],stock$Ldat[,2],col=cols[1],lwd=2)
lines(stock$Ldat[,1],stock$Ldat[,3],col=cols[2],lwd=2)}
plot(stock$Adat[,1],stock$Adat[,3],type="l",lwd=2,col=1,ylim=c(0,max(stock$Ldat[,2])),xlab="Length",ylab="Weigth")
if(nsexes==2){ lines(stock$Adat[,1],stock$Adat[,3],col=cols[1],lwd=2)
lines(stock$Adat[,1],stock$Adat[,6],col=cols[2],lwd=2)}
plot(stock$Ldat[,1],stock$Ldat[,4],type="l",lwd=2,col=cols[1],ylim=c(0,max(1)),xlab="Length",ylab="Proportion")
for(j in 1:nSel){
stock = get_ASEM(Linf,kappa,t0,aW,bW,minage,maxage,maturity,selpars[,j],h=h,M=M,0,R0=1,PlusGroup,nsexes,SELECT)
lines(stock$Ldat[,1],stock$Ldat[,5],col=cols[j+1],lwd=2)
#points(stock$Adat[,2],stock$Adat[,4],pch=15,cex=0.8,col=cols[j+4])
}
lines(stock$Ldat[,1],stock$Ldat[,4],col=cols[1],lwd=2)
legend(ifelse(min(selpars[1,])>max(Linf)-max(selpars[1,]),"topleft","right"),c("Mature",paste0("Sel",1:nSel)),col=cols[c(1,2:(1+nSel))],bty="n",lwd=2,cex=0.9)
dev.off()
#-----------------------------------------------------------
# Generate Priors
#-----------------------------------------------------------
Par = list(mfrow=c(2,2),mai=c(0.6,0.1,0,.1),omi = c(0.1,0.1,0.1,0) + 0.1,mgp=c(2.2,1,0), tck = -0.02,cex=0.75)
png(file = paste0(input.dir,"/Prior_hM_",assessment,".png"), width = 7.2, height = 7.,
res = 200, units = "in")
par(Par)
SB0.pr = plot_lnorm(mu=mu.SB0,CV=CV.SB0,Prior=paste0("Prior B(",years[1],")/B0"))
if(psi.prior=="beta"){
psi.pr = get_beta(mu=mu.psi,CV=CV.psi,Min=0,Prior=paste0("Prior B(",years[1],")/B0"))} else {
psi.pr = plot_lnorm(mu=mu.psi,CV=CV.psi,Prior=paste0("Prior B(",years[1],")/B0"))
}
h.pr = get_beta(mu=h,CV=CV.h,Min=0.2,Prior="Steepness h")
M.pr = get_gamma(M,CV.M,Prior="M")
mtext(paste("Density"), side=2, outer=T, at=0.5,line=0.4,cex=0.8)
dev.off()
# number of simulations for Monte-Carlo
nsim =1000
# Admit uncertainty for M
sim.M = rgamma(nsim,M.pr[1],M.pr[2])
# Random variates of z
sim.h = rbeta(nsim, h.pr[1], h.pr[2])
sim.h=ifelse(sim.h<0.21,0.21,sim.h) # truncate at 0.2
if(runASEM==TRUE){
# matrices for storage
EBmsy.sim = matrix(rep(0,nsim*nSel),nsim,nSel)
Fmsy = matrix(rep(0,nsim*nSel),nsim,nSel)
Hmsy.sim = matrix(rep(0,nsim*nSel),nsim,nSel)
MSY.sim = matrix(rep(0,nsim*nSel),nsim,nSel)
SBmsy.sim = matrix(rep(0,nsim*nSel),nsim,nSel)
shape.sim = matrix(rep(0,nsim*nSel),nsim,nSel)
SPmax = matrix(rep(0,nsim*nSel),nsim,nSel)
cat(paste0("\n","- Generate informative priors for Hmsy and m","\n"))
ci = rep(c(1,rep(0,(round(nsim/50,1)-1))),nsim)
cat(paste0("\n","- Running Monte-Carlo with ",nsim," runs\n"))
for(i in 1:nsim)
{
if(i==1) cat(paste("\n","|"))
if(ci[i]==1) cat("*")
if(i==nsim) cat(paste("|","\n"))
for(j in 1:nSel)
{
F_i = (exp(seq(log(M*0.1),log(M*5),0.01)))
# Find Hmsy
depletion = get_ASEM(Linf,kappa,t0,aW,bW,minage,maxage,maturity,selpars[,j],h=sim.h[i],M=sim.M[i],F_i,R0=1,PlusGroup,nsexes,SELECT)
getYield = depletion$Yield
SPmax[i,j] = ifelse(depletion$Yield[length(depletion$Yield)]<max(depletion$Yield),1,0)
# Hmsy at maximum yield
Fmsy[i,j] = ifelse(SPmax[i,j]==0,1,F_i[getYield==max(getYield)])
pop_Fmsy = get_ASEM(Linf,kappa,t0,aW,bW,minage,maxage,maturity,selpars[,j],h=sim.h[i],M=sim.M[i],F_i=Fmsy[i,j],R0=1,PlusGroup,nsexes,SELECT)
EBmsy.sim[i,j] = pop_Fmsy$EB
MSY.sim[i,j] = pop_Fmsy$Yield
SBmsy.sim[i,j] = pop_Fmsy$SB
Hmsy.sim[i,j] = MSY.sim[i,j]/SBmsy.sim[i,j]
SBmsySB0 = ifelse(SPmax[i,j]==0,0.37,pop_Fmsy$SBtoSB0)
rshape = 0
# Find shape for SBmsytoK
rshape = seq(0.1,5,0.001)
check.shape =((rshape)^(-1/(rshape-1))-SBmsySB0)^2
shape.sim[i,j] = rshape[check.shape==min(check.shape)]
} # end of 2st loop
} # end of sim
}
# Determine non-linear relationship between SB and EB as a function of P = SB/K
# Determine correlation prior for Hmsy and m
Hmsy_m_sim =matrix(rep(0,nsim*nSel),nsim,2)
Hmsy_m_sim[,1] = (MSY.sim[,1]/apply(SBmsy.sim,1,mean))
Hmsy_m_sim[,2] = as.numeric(apply(shape.sim,1,mean))
# Take viable pair that attained max SP
if(length(which(SPmax[,1]==0))>0){
Hmsy_m_sim[which(SPmax[,1]==0),] = exp(rmvnorm(length(which(SPmax[,1]==0)),log(apply(Hmsy_m_sim[which(SPmax[,1]==1),],2,median)),cov(log(Hmsy_m_sim[which(SPmax[,1]==1),]))))
}
# if more than ne fishery (selectivity) express Hmsy as ratio
if(nSel>1){
ratio.Hmsy = matrix(rep(0,nsim*(nSel-1)),nsim,nSel-1)
dHmsy.pr=NULL
for(j in 2:nSel) {
ratio.Hmsy [,j-1] = (MSY.sim[,j]/MSY.sim[,1])
dHmsy.pr = cbind(dHmsy.pr,as.numeric(fitdist(ratio.Hmsy[,j-1], "gamma",method="mme")$estimate))# conditioned on 1 period for linefish selectivity
}}
# get JAGS dmnrom prior
mu_prod_prior = apply(log(Hmsy_m_sim),2,mean)
cov_prod_prior = cov(log(Hmsy_m_sim))
ln_Hmsy_m_devs = rmvnorm(nsim*10 ,mean = mu_prod_prior,sigma = cov_prod_prior)
Hmsy_m_devs = exp(ln_Hmsy_m_devs)
Par = list(mfrow=c(round((nSel+1)/2+.33,0)+1,2),mai=c(0.6,0.3,0,.15),omi = c(0.2,0.2,0.2,0) + 0.1,mgp=c(2,1,0), tck = -0.02,cex=1)
png(file = paste0(input.dir,"/PriorsInput",assessment,".png"), width = 8, height = 2.5*round((nSel+1)/2+2.5,0),
res = 200, units = "in")
par(Par)
M.pr = get_gamma(M,CV.M,Prior="M'")
legend("topright",c("gamma"),col=c("grey",rgb(0,0,1,0.5)),pch=15,bty="n",cex=1,pt.cex=1.5)
h.pr = get_beta(mu=h,CV=CV.h,Min=0.2,Prior="h'")
legend("topright",c("beta"),col=c("grey",rgb(0,0,1,0.5)),pch=15,bty="n",cex=1,pt.cex=1.5)
d=stats::density(Hmsy_m_devs[,1],adjust=2)
plot(d,type="l",xlim=range(d$x),xlab=bquote(H[MSY*","*S1]),yaxt="n",ylim=c(0,max(d$y)*1.25),main="")
polygon(c(d$x,rev(d$x)),c(d$y,rep(0,length(d$y))),col="grey")
d=stats::density(Hmsy_m_sim[,1],adjust=2)
polygon(c(d$x,rev(d$x)),c(d$y,rep(0,length(d$y))),col=rgb(0,0,1,0.3))
legend("topright",c("Monte-Carlo","MVN"),col=c("grey",rgb(0,0,1,0.5)),pch=15,bty="n",cex=1,pt.cex=1.5)
d=stats::density(Hmsy_m_devs[,2],adjust=2)
plot(d,type="l",xlim=range(d$x),xlab="shape m",yaxt="n",main="")
polygon(c(d$x,rev(d$x)),c(d$y,rep(0,length(d$y))),col="grey")
d=stats::density(Hmsy_m_sim[,2],adjust=2)
polygon(c(d$x,rev(d$x)),c(d$y,rep(0,length(d$y))),col=rgb(0,0,1,0.3))
legend("topright",c("Monte-Carlo","MVN"),col=c("grey",rgb(0,0,1,0.5)),pch=15,bty="n",cex=1,pt.cex=1.5)
mtext(paste("Density"), side=2, outer=T, at=0.5,line=0.5,cex=1.1)
if(nSel>1){
# Express next priors as ratio to Hmsy1
for(j in 2:nSel){
d=stats::density(rgamma(5000,dHmsy.pr[1,j-1],dHmsy.pr[2,j-1]),adjust=2)
plot(d,type="l",xlim=range(c(0.9,1.2,d$x)),xlab=bquote(H[MSY*",S"*.(j)] ~ "/" ~H[MSY*","*S1]),yaxt="n",main="")
polygon(c(d$x,rev(d$x)),c(d$y,rep(0,length(d$y))),col="grey")
d=stats::density(ratio.Hmsy[,j-1],adjust=2)
polygon(c(d$x,rev(d$x)),c(d$y,rep(0,length(d$y))),col=rgb(0,0,1,0.3))
abline(v=1,lty=2)
legend("topright",c("Monte-Carlo","gamma"),col=c("grey",rgb(0,0,1,0.5)),pch=15,bty="n",cex=1,pt.cex=1.5)
}
}
dev.off()
# Hmsy_vs_m
# Prior correlation
Par = list(mfrow=c(1,2),mai=c(0.45,0.45,0,.15),omi = c(0.1,0.1,0.1,0) + 0.1,mgp=c(2.2,1,0), tck = -0.02,cex=0.7)
png(file = paste0(input.dir,"/Cor_m_Hmsy_",assessment,".png"), width = 7, height = 3,
res = 200, units = "in")
par(Par)
plot(log(Hmsy_m_devs[,1]),log(Hmsy_m_devs[,2]),type="n",ylab="log_m'",xlab=bquote(log_H[MSY*","*S1]),pch=19,col=grey(0.5,0.4))
points(log(Hmsy_m_devs[,1]),log(Hmsy_m_devs[,2]),col=rgb(0,0,1,0.2),pch=19)
points(log(Hmsy_m_sim[,1]),log(Hmsy_m_sim[,2]),pch=21,bg=grey(0.6,1),cex=1.2)
legend("topright",c("Monte-Carlo","MVN approximation"),col=c(1,4),pch=19,cex=1.1,bty="n")
plot(Hmsy_m_sim[,1],Hmsy_m_sim[,2],ylab="m",xlab=bquote(H[MSY*","*S1]),pch=19,col=rgb(0.,0.,1,0.5),type="n")
points(Hmsy_m_devs[,1],Hmsy_m_devs[,2],col=rgb(0,0,1,0.2),pch=19)
points(Hmsy_m_sim[,1],Hmsy_m_sim[,2],pch=21,bg=grey(0.6,1),cex=1.2)
legend("topright",c("Monte-Carlo","MVN approximation"),col=c(1,4),pch=19,cex=1.1,bty="n")
dev.off()
Par = list(mfrow=c(1,1),mai=c(0.55,0.3,0,.15),omi = c(0.0,0.2,0.2,0) + 0.1,mgp=c(2.5,1,0), tck = -0.02,cex=0.8)
png(file = paste0(input.dir,"/EBtoSB",assessment,".png"), width = 5.5, height = 4,
res = 200, units = "in")
par(Par)
ylim = c(0,5)
xlim=c(0,1)
cols = jabba.colors# rainbow(nSel+1)
# Find sets.EB
nI = length(sets.I)
sets.EB = selEB = unitEB = qEB= check.q =NULL
k=l=1
for(j in 1:nI){
sets.EB[j] = which((paste0(sets.I,I.unit))[j]==unique(paste0(sets.I,I.unit)) )
if(length(which(sets.EB%in%sets.EB[j]))==1){
selEB[k] = sets.I[j]
unitEB[k] = I.unit[j]
k = k+1
}
}
nEB = length(unique(sets.EB))
coefT = matrix(0,5,nEB)
ymax=ymin=NULL
for(j in 1:nEB)
{
depletion = get_ASEM(Linf,kappa,t0,aW,bW,minage,maxage,maturity,selpars[,selEB[j]],h=h,M=M,F_i,R0=1,PlusGroup,nsexes,SELECT)
y = (depletion$EB/(depletion$SB+0.000001))
y = y[depletion$SBtoSB0>0.1]
ymax = max(y,ymax)
ymin = min(y[y>0.01],ymin)
}
plot(1,1,type="n",xlab=expression(SB/SB[0]),ylab="",ylim=c(min(ymin,0.7),max(ymax,1.3)),xlim=c(0,0.9))
EBSB = NULL
for(j in 1:nEB){
depletion = get_ASEM(Linf,kappa,t0,aW,bW,minage,maxage,maturity,selpars[,selEB[j]],h=h,M=M,F_i,R0=1,PlusGroup,nsexes,SELECT)
y = (depletion$EB/depletion$SB)
if(unitEB[j]!=1){ y = depletion$EN/depletion$SB*depletion$EB[1]/depletion$EN[1]
#y = y*depletion$EB[1]/depletion$EN[1]
}
x = depletion$SBtoSB0
dat = data.frame(x,y)
dat=subset(dat,x>0.1 & x<0.9)
EBSB[j] = mean(dat$y)
#dat$y=dat$y/max(dat$y)
P1 = min(dat$x)
P2 = max(dat$x)
if(coef(lm(y~x,data=dat))[1] < 0.97 | coef(lm(y~x,data=dat))[1] > 1.03 & abs(coef(lm(y~x,data=dat))[2]) >0.001){
fit = nls((y)~v1+(v2-v1)*((1-exp(-v3*((x)-P1)))/(1-exp(-v3*(P2-P1)))),data=dat,start=list(v1=dat[nrow(dat),2],v2=dat[1,2],v3=1))
coefT[,j] = c(as.numeric(coef(fit)),P1,P2)
} else {
fit = lm(y~x,data=dat)
coefT[,j] = c(0.999999,0.99999,0.0000001,0.1,0.9)
}
if(unitEB[j]==1){
points(dat$x,dat$y,cex=0.5)
lines(dat$x,(predict(fit)),col=cols[j+1],lwd=2)} else {
points(dat$x,dat$y,cex=0.5)
lines(dat$x,(predict(fit)),col=cols[j+1],lwd=2)
}
abline(h=1,lty=2,col=cols[1])
}
legend("topright",c("Maturity",paste0("Sel",selEB[1:nEB],".",ifelse(unitEB[1:nEB]==rep(1,nEB),"Bio","N"))),lwd=c(1,rep(2,100)),lty=c(2,rep(1,100)),col=cols[1:(j+1)],bty="n")
mtext(paste("EB/SB"), side=2, outer=T, at=0.6,line=0.6,cex=0.8)
# mtext(paste("B/K"), side=1, outer=T, at=0.5,line=1,cex=0.9)
dev.off()
# Plot MSY
Par = list(mfrow=c(1,1),mai=c(0.6,0.3,0,.15),omi = c(0.1,0.2,0.2,0) + 0.1,mgp=c(2.5,1,0), tck = -0.02,cex=0.8)
png(file = paste0(input.dir,"/Prodution",assessment,".png"), width = 6, height = 5,
res = 200, units = "in")
par(Par)
colsp = cols[-1] # jabba.colors[c(4,5,6,7,2,11,12,3,8)]
j = 1
ymax = NULL
for(j in 1:nSel){
Y.it = get_ASEM(Linf,kappa,t0,aW,bW,minage,maxage,maturity,selpars[,j],h=h,M=M,F_i,R0=1,PlusGroup,nsexes,SELECT)$Yield
ymax = c(ymax,max(Y.it))
}
ymax = max(ymax)
plot(Y.it,Y.it,type="n",ylab="Yield",xlab="SB/SB0",lwd=2,yaxt="n",xlim=c(0,1),ylim=c(0,ymax))
SBR0 = get_ASEM(Linf,kappa,t0,aW,bW,minage,maxage,maturity,selpars[,j],h=h,M=M,0,R0=1,PlusGroup,nsexes,SELECT)$SB
P = seq(0.0001,1,0.001)
B = P*SBR0
for(j in 1:nSel){
SB_K = get_ASEM(Linf,kappa,t0,aW,bW,minage,maxage,maturity,selpars[,j],h=h,M=M,F_i,R0=1,PlusGroup,nsexes,SELECT)$SBtoSB0
Y.it = get_ASEM(Linf,kappa,t0,aW,bW,minage,maxage,maturity,selpars[,j],h=h,M=M,F_i,R0=1,PlusGroup,nsexes,SELECT)$Yield
dens = stats::density(Y.it)
lines(SB_K,Y.it,col=colsp[j],lwd=2)
Fmsy = F_i[Y.it==max(Y.it)]
pop_SP = get_ASEM(Linf,kappa,t0,aW,bW,minage,maxage,maturity,selpars[,j],h=h,M=M,F_i=Fmsy,R0=1,PlusGroup,nsexes,SELECT)
MSY = pop_SP$Yield
SBmsy = pop_SP$SB
Hmsy = MSY/SBmsy
SBmsySB0 = SBmsy/get_ASEM(Linf,kappa,t0,aW,bW,minage,maxage,maturity,selpars[,j],h=h,M=M,F_i=0,R0=1,PlusGroup,nsexes,SELECT)$SB
rshape = 0
# Find shape for SBmsytoK
rshape = seq(0.1,5,0.001)
check.shape =((rshape)^(-1/(rshape-1))-SBmsySB0)^2
shape = rshape[check.shape==min(check.shape)]
SP = Hmsy/(1-1/shape)*B*(1-(B/SBR0)^(shape-1))
lines(P,SP,lty=3,col=colsp[j],lwd=2)
#PMSP = P[SP==max(SP)]
PMSY = SB_K[Y.it==max(Y.it)]
lines(rep(PMSY,2),c(0,max(SP)),lty=1,col=colsp[j])
}
mtext(paste("Yield"), side=2, outer=T, at=0.6,line=0.5,cex=0.9)
legend("topright",c("ASPM","SPM",paste("Sel",1:nSel)),col=c(1,1,colsp),lwd=2,lty=c(1,3,rep(1,nSel)),bty="n")
dev.off()
# PRIORS
SB0.prior = c(round(SB0.pr[1],0),sqrt(log(CV.SB0^2+1)))
Psi.prior = c(mu.psi,CV.psi)
Hmsy_m.prior = NULL
for(i in 1:2) Hmsy_m.prior = cbind(Hmsy_m.prior ,round(c(mean(Hmsy_m_devs[,i]),sd(Hmsy_m_devs[,i])/mean(Hmsy_m_devs[,i])),3))
M.prior = c(M,CV.M)
h.prior = c(h, CV.h)
Priors =rbind(SB0.prior,Psi.prior,t(Hmsy_m.prior),M.prior,h.prior)
row.names(Priors) = c("SB0","Psi","Hmsy1","shape m","M","h")
colnames(Priors) = c("Mean","CV")
write.csv(Priors,paste0(input.dir,"/Priors",assessment,".S",s,".csv"))
#><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>
#---------------------------------------------------------------
# Setup JABBA-SELECT
#---------------------------------------------------------------
#><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>><>
# remove scientific numbers
#options(scipen=999)
##########################################################################
# starting values
nq = length(unique(sets.q))
nvar = length(unique(sets.var))
nI = ncol(CPUE)