generated from SEFSC/SEFSC-Template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Allocation_forecasting.R
1495 lines (1329 loc) · 75 KB
/
Allocation_forecasting.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
##---------------------------------------------------------------------##
# #
# SS projection package to achieve target equilibrium stock status, #
# constant annual fishing mortality rate, fixed group catch #
# allocations, and historic relative fishing effort between fleets #
# within groups. The package is able to calculate OFL, ABC represented #
# as a fraction of the OFL F, and F rebuild represented as a fixed #
# reduction in F during the specified rebuild period if needed. #
# #
##---------------------------------------------------------------------##
# #
# Author: Nathan Vaughan #
# Last update date: 10/15/21 #
# Contact: nathan.vaughan@noaa.gov #
# #
##---------------------------------------------------------------------##
#
# Disclaimer
#
# "The United States Department of Commerce (DOC) GitHub project code
# is provided on an "as is" basis and the user assumes responsibility
# for its use. DOC has relinquished control of the information and no
# longer has responsibility to protect the integrity, confidentiality,
# or availability of the information. Any claims against the Department
# of Commerce stemming from the use of its GitHub project will be
# governed by all applicable Federal law. Any reference to specific
# commercial products, processes, or services by service mark, trademark,
# manufacturer, or otherwise, does not constitute or imply their endorsement,
# recommendation or favoring by the Department of Commerce. The Department
# of Commerce seal and logo, or the seal and logo of a DOC bureau, shall
# not be used in any manner to imply endorsement of any commercial
# product or activity by DOC or the United States Government."
#
#
## #
##---------------------------------------------------------------------##
##
# This is now a generalized function to run projections that should work for most species.
# The function is now designed to mostly read out settings from the forecast file the
# same way you would generally set things up for a base SS projection.
# The only additional inputs needed are a proportion for F.ABC relative to F.OFL if
# ABC projections are desired and a rebuild target year if rebuilding projections are desired.
#
run.projections<-function(assessment_dir, #Here you set the location of a previously fit SS3.3 stock assessment to perform projections
ABC_Fraction = NULL, #Set the ABC target as a fraction of the OFL target if NULL will not fit ABC projections
Rebuild_yr = NULL, #Set the rebuild target year if NULL will not fit rebuild projections
Calc_F0 = FALSE, #Should an F=0 projection be performed
Const_Catch = NULL, #Constant catch target in mt. If constant catch is chosen no other simulations will run (i.e. benchmark, OFL, etc)
F_max = FALSE, #If true and forecast method is Fmsy will replace Fmsy with Fmax search (maximum yield per recruit)
Depletion.Threshold = 0.0001, # These are all just thresholds for when
Annual.F.Threshold = 0.0001, # targets are acceptably achieved these default to a .01% change
Allocation.Threshold = 0.0001, # increase them if run is too slow or reduce to improve fit if run is fast.
Step.Threshold = 0.0001, #
Benchmark_complete = FALSE, #Set to true if you already have a fit Benchmark run but want to add or adjust an ABC or Rebuild run
Make_plots = FALSE, #Should plots be created (this is useful for diagnostics but can cause annoying errors if plot window is small)
Calc_Hessian = FALSE, #Should the hessian inversion be completed for runs once converged. TODO: NOT YET IMPLEMENTED!!!
Do_Pstar = FALSE, #If TRUE then ABC_Fraction above will instead be the P* probability of overfishing limit for ABC calculation. TODO: NOT YET IMPLEMENTED!!!
Years_report = 20, #How many years of projection to include in stored OFL and ABC reporting. (All forecast years data will still be available in report file)
Years_projection = 100, #How many years of projection to run (need enough to reach equilibrium) 100 is safe but may not be sufficient for some long lived species.
run_in_MSE = FALSE,
starting_Forecatch = NULL,
MSY_step = 0.1,
SS_exe = NULL
)
{
projection_results <- list()
#SSMSE::report_message("Running the allocation forecasting function.")
#Removed these as inputs as they are not needed yet, could add back to input options later
oldwd<-getwd()
library(r4ss)
#Set large max print to avoid issues with writing out a large forecast file.
options(max.print = 1000000)
setwd(paste0(assessment_dir))
assessment_dir <- getwd()
#Read in all the model files and results
start <- SS_readstarter()
dat <- SS_readdat(file = start$datfile, version = 3.3)
ctl <- SS_readctl(file = start$ctlfile, version = 3.3, use_datlist = TRUE, datlist = dat)
results <- SS_output(dir = getwd(), covar = FALSE)
forecast <- SS_readforecast()
if(!is.null(SS_exe)){
}else if(file.exists("ss.exe")){
SS_exe <- "ss"
} else if(file.exists("ss3.exe")){
SS_exe <- "ss3"
} else if(file.exists("ss_opt.exe")){
SS_exe <- "ss_opt"
} else if(file.exists("ss3_opt.exe")){
SS_exe <- "ss3_opt"
} else if(file.exists("ss3_win.exe")){
SS_exe <- "ss3_win"
}else{
stop("Error: Couldn't find an expected SS executable name")
}
if(file.exists("ss.par")){
par_name <- "ss.par"
}else if(file.exists("ss3.par")){
par_name <- "ss3.par"
}else{
stop("Error: No par file found with name ss.par or ss3.par")
}
parlist <- SS_readpar_3.30(parfile = par_name, datsource = dat, ctlsource = ctl)
if(!is.null(Const_Catch)){
Const_Catch <- sort(Const_Catch)
}
#First set up a working director for running projections in (to avoid overwriting the base files with a failed model run)
#then copy all of the assessment files to this working folder (ignore any output directories that have been previously created)
if(Benchmark_complete == FALSE){
if(dir.exists(file.path(getwd(),"Working_dir"))){
unlink(file.path(getwd(),"Working_dir"), recursive = TRUE)
}
dir.create(file.path(getwd(),"Working_dir"))
temp.files <- list.files(path=assessment_dir)
folders <- c(which(temp.files=="Benchmark_target"), which(temp.files=="OFL_target"), which(temp.files=="ABC_target"), which(temp.files=="Rebuild_target"), which(temp.files=="F0_target"), which(temp.files=="Working_dir"))
if(length(folders)>0){
temp.files <- temp.files[-folders]
}
file.copy(from = file.path(getwd(),temp.files), to = file.path(getwd(),"Working_dir",temp.files))
}else{
temp.files <- list.files(path=file.path(getwd(),"Working_dir"))
folders <- c(which(temp.files=="Benchmark_target"), which(temp.files=="OFL_target"), which(temp.files=="ABC_target"), which(temp.files=="Rebuild_target"), which(temp.files=="F0_target"), which(temp.files=="Working_dir"))
if(length(folders)>0){
temp.files <- temp.files[-folders]
}
unlink(file.path(getwd(),"Working_dir/",temp.files))
temp.files <- list.files(path=file.path(getwd(),"Benchmark_target"))
file.copy(from = file.path(getwd(),"Benchmark_target",temp.files), to = file.path(getwd(),"Working_dir",temp.files))
}
#Set the new working directory
setwd(file.path(getwd(),"Working_dir"))
#Modify assessment files to produce expected timeseries length and outputs
#need enough projection years to allow equilibrium to be achieved
forecast[["Nforecastyrs"]] <- Years_projection
#If fitting the Benchmark/OFL values then save the specified recruitment source for catches
#and set to 0 (S/R curve) in order to first calculate benchmarks
catch_rec <- forecast$fcast_rec_option
if(Benchmark_complete==FALSE){
forecast$fcast_rec_option <- 0
}
#Need to set recdevs and implementation error for all projection years
#so that reading from par file is possible
expected_forecast_rec_length <- length((min(dat[["endyr"]],ctl[["MainRdevYrLast"]])+1):(dat[["endyr"]]+forecast[["Nforecastyrs"]]))
if(!is.null(parlist$recdev_forecast)){
if(length(parlist$recdev_forecast[,1])!=expected_forecast_rec_length){
temp_recs<-parlist$recdev_forecast[,2]
parlist$recdev_forecast <- matrix(NA, nrow = expected_forecast_rec_length, ncol = 2)
parlist$recdev_forecast[,1] <- (min(dat[["endyr"]],ctl[["MainRdevYrLast"]])+1):(dat[["endyr"]]+forecast[["Nforecastyrs"]])
parlist$recdev_forecast[,2] <- rep(0,expected_forecast_rec_length)
parlist$recdev_forecast[1:length(temp_recs),2] <- temp_recs
colnames(parlist$recdev_forecast) <- c("year","recdev")
}
}else{
parlist$recdev_forecast <- matrix(NA, nrow = expected_forecast_rec_length, ncol = 2)
parlist$recdev_forecast[,1] <- (min(dat[["endyr"]],ctl[["MainRdevYrLast"]])+1):(dat[["endyr"]]+forecast[["Nforecastyrs"]])
parlist$recdev_forecast[,2] <- rep(0,expected_forecast_rec_length)
colnames(parlist$recdev_forecast) <- c("year","recdev")
}
# if(!is.null(parlist$Fcast_impl_error)){
parlist$Fcast_impl_error <- matrix(NA, nrow = forecast[["Nforecastyrs"]], ncol = 2)
parlist$Fcast_impl_error[,1] <- (dat[["endyr"]]+1):(dat[["endyr"]]+forecast[["Nforecastyrs"]])
parlist$Fcast_impl_error[,2] <- rep(0,forecast[["Nforecastyrs"]])
colnames(parlist$Fcast_impl_error) <- c("year","impl_error")
if(forecast[["stddev_of_log_catch_ratio"]]==0){
forecast[["stddev_of_log_catch_ratio"]]<-0.001
}
#Adjust the starter file to read from par file, perform no fitting (This should already have been done),
#and set the depletion value to be relative to unexploited biomass and have no scaling
#(so that correct depletion target can be found).
start$init_values_src <- 1
start$last_estimation_phase <- 0
start$depl_basis <- 1
start$depl_denom_frac <- 1
start$SPR_basis <- 4
start$F_report_units <- 1
start$F_report_basis <- 0
#Get the timeseries of historic/projected catches and F
TimeFit <- results$timeseries
#Identify the column numbers for Catch, F, SSB, Recruits, etc
Catch_cols <- grep("retain(B)", names(TimeFit), fixed = TRUE)
Dead_cols <- grep("dead(B)", names(TimeFit), fixed = TRUE)
CatchN_cols <- grep("retain(N)", names(TimeFit), fixed = TRUE)
DeadN_cols <- grep("dead(N)", names(TimeFit), fixed = TRUE)
F_cols <- grep("F", names(TimeFit), fixed = TRUE)
if(length(F_cols)==0){
F_cols <- grep("Hrate", names(TimeFit), fixed = TRUE)
}
TimeFit2 <- aggregate(TimeFit[,sort(c(2,4,7,Catch_cols,Dead_cols,CatchN_cols,DeadN_cols,F_cols))],by=list(TimeFit$Yr,TimeFit$Seas),FUN=sum,na.rm=TRUE)[,-c(3,4,5)]
names(TimeFit2)[c(1,2)] <- c("Yr", "Seas")
Catch_cols2 <- grep("retain(B)", names(TimeFit2), fixed = TRUE)
Dead_cols2 <- grep("dead(B)", names(TimeFit2), fixed = TRUE)
CatchN_cols2 <- grep("retain(N)", names(TimeFit2), fixed = TRUE)
DeadN_cols2 <- grep("dead(N)", names(TimeFit2), fixed = TRUE)
F_cols2 <- grep("F", names(TimeFit2), fixed = TRUE)
if(length(F_cols2)==0){
F_cols2 <- grep("Hrate", names(TimeFit2), fixed = TRUE)
}
TimeFit3 <- aggregate(TimeFit[,sort(c(2,7,8,Catch_cols,Dead_cols,CatchN_cols,DeadN_cols,F_cols))],by=list(TimeFit$Yr),FUN=sum,na.rm=TRUE)[,-2]
names(TimeFit3)[c(1)] <- c("Yr")
Virgin_bio <- TimeFit3$SpawnBio[1]
Catch_cols3 <- grep("retain(B)", names(TimeFit3), fixed = TRUE)
Dead_cols3 <- grep("dead(B)", names(TimeFit3), fixed = TRUE)
CatchN_cols3 <- grep("retain(N)", names(TimeFit3), fixed = TRUE)
DeadN_cols3 <- grep("dead(N)", names(TimeFit3), fixed = TRUE)
F_cols3 <- grep("F", names(TimeFit3), fixed = TRUE)
if(length(F_cols3)==0){
F_cols3 <- grep("Hrate", names(TimeFit3), fixed = TRUE)
}
achieved.report <- TimeFit2[0,1:8]
colnames(achieved.report)<-c("Year","Seas","Fleet","retain(B)","dead(B)","retain(N)","dead(N)","F")
for(i in 1:length(F_cols2)){
temp.data <- TimeFit2[,1:8]
temp.data[,3] <- i
temp.data[,4] <- TimeFit2[,Catch_cols2[i]]
temp.data[,5] <- TimeFit2[,Dead_cols2[i]]
temp.data[,6] <- TimeFit2[,CatchN_cols2[i]]
temp.data[,7] <- TimeFit2[,DeadN_cols2[i]]
temp.data[,8] <- TimeFit2[,F_cols2[i]]
colnames(temp.data)<-c("Year","Seas","Fleet","retain(B)","dead(B)","retain(N)","dead(N)","F")
achieved.report <- rbind(achieved.report,temp.data)
}
achieved.report<-achieved.report[order(achieved.report$Year,achieved.report$Seas,achieved.report$Fleet),]
#Set all future projections to fish at constant apical F that matches recent years
#get the years of timeseries F's based on the forecast year range
if(is.data.frame(forecast[["Fcast_years"]])){
min_fcast_yr <- forecast[["Fcast_years"]][forecast[["Fcast_years"]][,'MG_type']==11,'st_year']
if(min_fcast_yr==-999){
min_fcast_yr <- dat[["styr"]]
}else if(min_fcast_yr <= 0){
min_fcast_yr <- dat[["endyr"]] + min_fcast_yr
}
max_fcast_yr <- forecast[["Fcast_years"]][forecast[["Fcast_years"]][,'MG_type']==11,'end_year']
if(max_fcast_yr <= 0){
max_fcast_yr <- dat[["endyr"]] + max_fcast_yr
}
}else{
if(forecast[["Fcast_years"]][3]==-999){
min_fcast_yr <- dat[["styr"]]
}else if(forecast[["Fcast_years"]][3]>0){
min_fcast_yr <- forecast[["Fcast_years"]][3]
}else{
min_fcast_yr <- dat[["endyr"]]+forecast[["Fcast_years"]][3]
}
if(forecast[["Fcast_years"]][4]>0){
max_fcast_yr <- forecast[["Fcast_years"]][4]
}else{
max_fcast_yr <- dat[["endyr"]]+forecast[["Fcast_years"]][4]
}
}
TargetYears <- TimeFit2[TimeFit2$Yr>=min_fcast_yr & TimeFit2$Yr<=max_fcast_yr,]
TargetYears <- TargetYears[,c(2,F_cols2)]
seasons <- unique(TargetYears[,1])
F_by_Fleet_seas <- as.data.frame(matrix(apply(TargetYears[TargetYears[,1]==seasons[1],,drop=FALSE], 2, mean),nrow=1,ncol=(length(F_cols)+1)))
if(length(seasons)>1){
for(i in seasons[-1]){
F_by_Fleet_seas <- rbind(F_by_Fleet_seas,apply(TargetYears[TargetYears[,1]==i,,drop=FALSE], 2, mean))
}
}
Forecast_target <- forecast[["Forecast"]]
if(!is.element(Forecast_target,c(1,2,3))){
stop("forecast should be set to either 1, 2, or 3 so we know what the target is")
}
if(is.null(starting_Forecatch)){
#Build a projection forcast matrix of F values by fleet/season/year which will adjusted to achieve target stock status, F, and allocations.
forecast_F<-matrix(1,nrow=forecast[["Nforecastyrs"]]*length(seasons)*length(F_cols),ncol=5)
forecast_F[,1]<-sort(rep((dat[["endyr"]]+1):(dat[["endyr"]]+forecast[["Nforecastyrs"]]),length(seasons)*length(F_cols)))
forecast_F[,2]<-rep(sort(rep(seasons,length(F_cols))),forecast[["Nforecastyrs"]])
forecast_F[,3]<-rep(sort(which(dat$fleetinfo$type!=3)),forecast[["Nforecastyrs"]]*(length(seasons)))
for(i in seasons){
forecast_F[forecast_F[,2]==i,4]<-unlist(rep(F_by_Fleet_seas[F_by_Fleet_seas[,1]==i,-1],forecast[["Nforecastyrs"]]))
forecast_F[forecast_F[,2]==i,5]<-rep(99,length(F_cols)*forecast[["Nforecastyrs"]])
}
forecast_F<-as.data.frame(forecast_F)
colnames(forecast_F)<-c("Year","Seas","Fleet","Catch or F","Basis")
forecast_F[,"Catch or F"] <- forecast_F[,"Catch or F"] + 0.00000001
}else{
if(dim(starting_Forecatch)[1]!=forecast[["Nforecastyrs"]]*length(seasons)*length(F_cols)){
stop("Error: You input a starting forecatch matrix but it is not the correct length n_years*n_fleets*n_seasons.")
}
if(dim(starting_Forecatch)[2]!=5){
stop("Error: You input a starting forecatch matrix but it does not have 5 columns Year, Season, Fleet, Catch, Basis.")
}
if(length(dim(starting_Forecatch))!=2){
stop("Error: You input a starting forecatch but it is not a matrix")
}
forecast_F <- starting_Forecatch
colnames(forecast_F)<-c("Year","Seas","Fleet","Catch or F","Basis")
}
adjusted_F_OFL<-1:(forecast[["Nforecastyrs"]]*length(seasons)*length(F_cols))
#Extract fixed forecast values from the forecast file these will be fixed at these values for the projections
#This is used to implement recent catches or fixed harvest from an independent fleet such as shrimp bycatch.
if(!is.null(forecast[["ForeCatch"]])){
Fixed_catch_basis <- forecast[["InputBasis"]]
Fixed_catch_target <- forecast[["ForeCatch"]]
fixed_ref <- seq_along(Fixed_catch_target[,1])
if(length(names(Fixed_catch_target))==4){
new_names <- c(names(Fixed_catch_target),"Basis")
Fixed_catch_target <- cbind(Fixed_catch_target,rep(Fixed_catch_basis,length(Fixed_catch_target[,1])))
names(Fixed_catch_target) <- new_names
}
for(i in seq_along(Fixed_catch_target[,1])){
fixed_ref[i]<-which(forecast_F[,1]==Fixed_catch_target[i,1] &
forecast_F[,2]==Fixed_catch_target[i,2] &
forecast_F[,3]==Fixed_catch_target[i,3])
}
#Replace the temporary average F values with specified fixed inputs
forecast_F[fixed_ref,c(4,5)]<-Fixed_catch_target[,c(4,5)]
adjusted_F_OFL<-adjusted_F_OFL[-fixed_ref]
if(length(adjusted_F_OFL)==0){stop("all F's are fixed nothing to estimate")}
}else{
fixed_ref<-NULL
}
if(!is.null(Rebuild_yr)){
#This reference identifies inputs subject to a rebuilding period F
rebuild_ref <- which(forecast_F[,1]<=Rebuild_yr)
if(length(rebuild_ref)>0){
adjusted_OFL_F_Rebuild<-adjusted_F_OFL[adjusted_F_OFL>max(rebuild_ref)]
adjusted_Rebuild_F_Rebuild<-rebuild_ref
if(!is.null(fixed_ref)){
adjusted_Rebuild_F_Rebuild<-adjusted_Rebuild_F_Rebuild[-fixed_ref]
}
}
}else{
adjusted_OFL_F_Rebuild <- adjusted_F_OFL
adjusted_Rebuild_F_Rebuild <- NULL
rebuild_ref <- NULL
}
#Here all input values are assigned to an allocation group if needed and
#relative landings targets are identified
n_groups <- forecast[["N_allocation_groups"]]
groups <- rep(0,length(F_cols))
fleets_by_group <- list()
Allocations <- forecast_F[,c(1,2,3,4,5,5)]
Allocations[,c(4)] <- 0
Allocations[,c(5,6)] <- 1
names(Allocations) <- c("Year","Seas","Fleet","Group","Target","Achieved")
if(n_groups>0){
for(i in seq_along(forecast[["fleet_assignment_to_allocation_group"]][,"Fleet"])){
groups[forecast[["fleet_assignment_to_allocation_group"]][i,"Fleet"]] <- forecast[["fleet_assignment_to_allocation_group"]][i,"Group"]
Allocations[Allocations[,"Fleet"]==forecast[["fleet_assignment_to_allocation_group"]][i,"Fleet"],4] <- forecast[["fleet_assignment_to_allocation_group"]][i,"Group"]
}
alloc <- forecast[["allocation_among_groups"]][order(forecast[["allocation_among_groups"]][,"Year"]),]
for(i in seq_along(alloc[,1])){
for(j in seq_along(alloc[i,-1])){
Allocations[Allocations[,1]>=alloc[,"Year"] & Allocations[,4]==j,5] <- alloc[i,(j+1)]/sum(alloc[i,-1])
}
}
for(i in 1:n_groups){
fleets_by_group[[i]]<-which(is.element(which(dat$fleetinfo$type!=3),which(groups==i)))
}
}
forecast[["Forecast"]] <- 4
forecast[["InputBasis"]] <- -1
forecast[["ForeCatch"]] <- forecast_F
forecast[["FirstYear_for_caps_and_allocations"]] <- (dat[["endyr"]]+forecast[["Nforecastyrs"]]+1)
keepFitting <- TRUE
loop <- 0
subloop <- 0
F_maxed <- 100000
F_adjust1 <- F_adjust2 <- 1
F_adjust3 <- rep(1,forecast[["Nforecastyrs"]]*length(seasons)*length(F_cols))
search_step <- MSY_step
Fmult1 <- Fmult2 <- Fmult3 <- Fmult4 <- rep(1.01,forecast[["Nforecastyrs"]]*length(seasons)*length(F_cols))
Fmult2a <- Fmult2b <- 1
First_run<-TRUE
if(!is.null(Const_Catch)){
forecast$fcast_rec_option <- catch_rec
SS_writepar_3.30(parlist = parlist,outfile=par_name,overwrite = TRUE)
SS_writeforecast(mylist=forecast,overwrite = TRUE)
SS_writestarter(mylist=start,overwrite = TRUE)
if(run_in_MSE==TRUE){
SSMSE:::run_EM(EM_dir = getwd(), verbose = TRUE, check_converged = TRUE)
}else{
shell(paste("cd /d ",getwd()," && ",SS_exe," -nohess",sep=""))
}
#Begin the search in the Benchmark phase
fitting_Benchmark <- FALSE
fitting_OFL <- FALSE
fitting_ABC <- FALSE
fitting_Rebuild <- FALSE
fitting_F0 <- FALSE
fitting_Fixed_Catch <- TRUE
CC_loop <- 1
Catch_Target <- rep(Const_Catch[CC_loop],forecast[["Nforecastyrs"]])
Catch_trunc <- 0
method <- "fixed_catch"
}else if(Benchmark_complete == FALSE){
#Save all the modified files and then perform a base run of SS so that output is specified correctly with
#a forecast[["Nforecastyrs"]] year projection series.
SS_writepar_3.30(parlist = parlist, outfile = par_name, overwrite = TRUE)
SS_writeforecast(mylist=forecast,overwrite = TRUE)
SS_writestarter(mylist=start,overwrite = TRUE)
if(run_in_MSE==TRUE){
SSMSE:::run_EM(EM_dir = getwd(), verbose = TRUE, check_converged = TRUE)
}else{
shell(paste("cd /d ",getwd()," && ",SS_exe," -nohess",sep=""))
}
#Begin the search in the Benchmark phase
fitting_Benchmark <- TRUE
fitting_OFL <- FALSE
fitting_ABC <- FALSE
fitting_Rebuild <- FALSE
fitting_F0 <- FALSE
fitting_Fixed_Catch <- FALSE
MSY.Fit <- data.frame(catch=c(0),Ave.F=c(0),depletion=c(0),target.depletion=c(0))
method <- "Benchmark"
}else{
#Save all the modified files and then set search to begin in OFL phase
start <- SS_readstarter()
dat <- SS_readdat(file = start$datfile, version = 3.3)
ctl <- SS_readctl(file = start$ctlfile, version = 3.3, use_datlist = TRUE, datlist = dat)
results <- SS_output(dir = getwd(), covar = FALSE)
forecast <- SS_readforecast()
parlist <- SS_readpar_3.30(parfile = par_name, datsource = dat, ctlsource = ctl)
forecast$fcast_rec_option <- catch_rec
SS_writeforecast(mylist=forecast,overwrite = TRUE)
fitting_Benchmark <- FALSE
fitting_OFL <- TRUE
fitting_ABC <- FALSE
fitting_Rebuild <- FALSE
fitting_F0 <- FALSE
fitting_Fixed_Catch <- FALSE
method <- "OFL"
}
#Set up plot window for production of search diagnostic plots depending on target specifications
#These plots were largely for diagnostic testing during code development but can allow you to see what
#is going wrong if a future bug does occur.
if(Make_plots==TRUE){
if(Forecast_target==2 & fitting_Benchmark==TRUE){
par(mfrow=c(5,2))
}else{
par(mfrow=c(4,2))
}
}
#Now start a loop of projecting and modifying fixed F's until the desired
#landings projections are achieved
while(keepFitting){
#Read in the SS results for landings and stock status to determine if desired
#targets have been achieved
resultsFit <- SS_output(dir=getwd(),covar=FALSE)
TimeFit <- resultsFit[["timeseries"]]
TimeFit <- TimeFit[TimeFit[,"Yr"]>dat[["endyr"]],]
SPRfit <- resultsFit[["sprseries"]]
SPRfit <- SPRfit[SPRfit[,"Yr"]>dat[["endyr"]],]
loop <- loop + 1
if(Make_plots==TRUE){
par(mar=c(4,3,3,2))
plot(SPRfit[SPRfit[,"Yr"]>=dat[["endyr"]],"F_report"],xlab="year",ylab="F",main = paste0(method," loop = ",loop))
plot(SPRfit[SPRfit[,"Yr"]>=dat[["endyr"]],"Deplete"],xlab="year",ylab="Depletion",main = paste0(method," loop = ",loop))
}
#Identify the column numbers for Catch, F, SSB, Recruits, etc
Catch_cols <- grep("retain(B)", names(TimeFit), fixed = TRUE)
Dead_cols <- grep("dead(B)", names(TimeFit), fixed = TRUE)
CatchN_cols <- grep("retain(N)", names(TimeFit), fixed = TRUE)
DeadN_cols <- grep("dead(N)", names(TimeFit), fixed = TRUE)
F_cols <- grep("F", names(TimeFit), fixed = TRUE)
if(length(F_cols)==0){
F_cols <- grep("Hrate", names(TimeFit), fixed = TRUE)
}
TimeFit2 <- aggregate(TimeFit[,sort(c(2,4,7,Catch_cols,Dead_cols,CatchN_cols,DeadN_cols,F_cols))],by=list(TimeFit$Yr,TimeFit$Seas),FUN=sum,na.rm=TRUE)[,-c(3,4,5)]
names(TimeFit2)[c(1,2)] <- c("Yr", "Seas")
Catch_cols2 <- grep("retain(B)", names(TimeFit2), fixed = TRUE)
Dead_cols2 <- grep("dead(B)", names(TimeFit2), fixed = TRUE)
CatchN_cols2 <- grep("retain(N)", names(TimeFit2), fixed = TRUE)
DeadN_cols2 <- grep("dead(N)", names(TimeFit2), fixed = TRUE)
F_cols2 <- grep("F", names(TimeFit2), fixed = TRUE)
if(length(F_cols2)==0){
F_cols2 <- grep("Hrate", names(TimeFit2), fixed = TRUE)
}
TimeFit3 <- aggregate(TimeFit[,sort(c(2,7,8,Catch_cols,Dead_cols,CatchN_cols,DeadN_cols,F_cols))],by=list(TimeFit$Yr),FUN=sum,na.rm=TRUE)[,-2]
names(TimeFit3)[c(1)] <- c("Yr")
Catch_cols3 <- grep("retain(B)", names(TimeFit3), fixed = TRUE)
Dead_cols3 <- grep("dead(B)", names(TimeFit3), fixed = TRUE)
CatchN_cols3 <- grep("retain(N)", names(TimeFit3), fixed = TRUE)
DeadN_cols3 <- grep("dead(N)", names(TimeFit3), fixed = TRUE)
F_cols3 <- grep("F", names(TimeFit3), fixed = TRUE)
if(length(F_cols3)==0){
F_cols3 <- grep("Hrate", names(TimeFit3), fixed = TRUE)
}
achieved.report <- TimeFit2[0,1:8]
colnames(achieved.report)<-c("Year","Seas","Fleet","retain(B)","dead(B)","retain(N)","dead(N)","F")
for(i in 1:length(F_cols2)){
temp.data <- TimeFit2[,1:8]
temp.data[,3] <- i
temp.data[,4] <- TimeFit2[,Catch_cols2[i]]
temp.data[,5] <- TimeFit2[,Dead_cols2[i]]
temp.data[,6] <- TimeFit2[,CatchN_cols2[i]]
temp.data[,7] <- TimeFit2[,DeadN_cols2[i]]
temp.data[,8] <- TimeFit2[,F_cols2[i]]
colnames(temp.data)<-c("Year","Seas","Fleet","retain(B)","dead(B)","retain(N)","dead(N)","F")
achieved.report <- rbind(achieved.report,temp.data)
}
achieved.report<-achieved.report[order(achieved.report$Year,achieved.report$Seas,achieved.report$Fleet),]
if(fitting_Rebuild==TRUE){
terminal_year <- min(length(SPRfit$Yr[SPRfit$Yr<=Rebuild_yr])+5, Years_projection) #min to ensure report years beyond projection length not requested
}else{
terminal_year <- min(Years_report, Years_projection) #min to ensure report years beyond projection length not requested
}
Achieved.Catch <- apply(TimeFit3[,Catch_cols3,drop=FALSE],1,sum)[1:terminal_year]
Achieved.Catch.All <- apply(TimeFit3[,Catch_cols3,drop=FALSE],1,sum)
Achieved.SSBratio <- TimeFit3$SpawnBio[1:terminal_year]/Virgin_bio
Achieved.SPR <- TimeFit3$SpawnBio[1:terminal_year]/TimeFit3$Recruit_0[1:terminal_year]
Achieved.SSB <- TimeFit3$SpawnBio[1:terminal_year]
Achieved.Rec <- TimeFit3$Recruit_0[1:terminal_year]
Achieved.F <- SPRfit$F_report[1:terminal_year]
if(is.null(Achieved.F)){
Achieved.F <- SPRfit$F_std[1:terminal_year]
}
#If reading in results of a previous OFL run then set the F_OFL and F.ABC values before begining ABC/Rebuild loops
if(Benchmark_complete==TRUE & First_run==TRUE){
F_report<-SPRfit$F_report
if(is.null(F_report)){
F_report<-SPRfit$F_std
}
FScale<-median(F_report[(length(F_report)-0.5*Years_projection):length(F_report)])
F_OFL<-FScale
if(!is.null(ABC_Fraction)){
F.ABC<-ABC_Fraction*FScale
}else{
F.ABC<-FScale
}
First_run<-FALSE
Depletion<-TimeFit3$SpawnBio/Virgin_bio
Target.Depletion <- median(Depletion[(length(Depletion)-29):length(Depletion)])
Target.Rebuild <- median(Depletion[(length(Depletion)-29):length(Depletion)])
Achieved.Catch.equil <- sum(TimeFit3[(length(TimeFit3[,1])-9):length(TimeFit3[,1]),Catch_cols3])/10
if(n_groups>1){
projection_results[["Group_Catch_Benchmark"]]<-list()
for(i in 1:n_groups){
Achieved.Catch.group.equil <- sum(TimeFit3[(length(TimeFit3[,1])-9):length(TimeFit3[,1]),Catch_cols3[fleets_by_group[[i]]]])/10
projection_results[["Group_Catch_Equil_Benchmark"]][[i]]<-Achieved.Catch.group.equil
Achieved.Catch.group <- apply(TimeFit3[1:terminal_year,Catch_cols3[fleets_by_group[[i]]],drop=FALSE],1,sum)
projection_results[["Group_Catch_Benchmark"]][[i]]<-Achieved.Catch.group
}
}
Achieved.SSBratio.equil <- median(TimeFit3$SpawnBio[(length(TimeFit3$SpawnBio)-9):length(TimeFit3$SpawnBio)])/Virgin_bio
Achieved.SPR.equil <- median(TimeFit3$SpawnBio[(length(TimeFit3$SpawnBio)-9):length(TimeFit3$SpawnBio)]/TimeFit3$Recruit_0[(length(TimeFit3$SpawnBio)-9):length(TimeFit3$SpawnBio)]) #median(SPRfit$SPR[(length(SPRfit$SPR)-9):length(SPRfit$SPR)])
Achieved.SSB.equil <- median(TimeFit3$SpawnBio[(length(TimeFit3$SpawnBio)-9):length(TimeFit3$SpawnBio)])
Achieved.Rec.equil <- median(TimeFit3$Recruit_0[(length(TimeFit3$Recruit_0)-9):length(TimeFit3$Recruit_0)])
projection_results[["Catch_equil_Benchmark"]] <- Achieved.Catch.equil
projection_results[["F_equil_Benchmark"]] <- F_OFL
projection_results[["Depletion_equil_Benchmark"]] <- Achieved.SSBratio.equil
projection_results[["SSB_equil_Benchmark"]] <- Achieved.SSB.equil
projection_results[["SPR_equil_Benchmark"]] <- Achieved.SPR.equil
projection_results[["Recruitment_equil_Benchmark"]] <- Achieved.Rec.equil
projection_results[["Forecatch_Benchmark"]] <- achieved.report
projection_results[["Catch_Benchmark"]] <- Achieved.Catch
projection_results[["F_Benchmark"]] <- Achieved.F
projection_results[["Depletion_Benchmark"]] <- Achieved.SSBratio
projection_results[["SSB_Benchmark"]] <- Achieved.SSB
projection_results[["SPR_Benchmark"]] <- Achieved.SPR
projection_results[["Recruitment_Benchmark"]] <- Achieved.Rec
}
if(is.na(max(abs(achieved.report[,'F']-forecast_F[,"Catch or F"])[adjusted_F_OFL]))){
if(fitting_Fixed_Catch==TRUE){
if(Catch_trunc >= (forecast$Nforecastyrs - 20)){
Catch_trunc <- Catch_trunc + 1
}else{
Catch_trunc <- Catch_trunc + 5
}
Catch_Target[(forecast$Nforecastyrs-c((Catch_trunc-1):0))] <- 0
forecast_F[(length(forecast_F[,1])-c((Catch_trunc*length(seasons)*length(F_cols)-1):0)),4] <- 0
}
forecast_F[,4] <- forecast_F[,4]*0.5
loop <- loop - 1
}else{
if(max(abs(achieved.report[,'F']-forecast_F[,"Catch or F"])[adjusted_F_OFL])>0.1){
if(fitting_Fixed_Catch==TRUE){
if(Catch_trunc >= (forecast$Nforecastyrs - 20)){
Catch_trunc <- Catch_trunc + 1
}else{
Catch_trunc <- Catch_trunc + 5
}
Catch_Target[(forecast$Nforecastyrs-c((Catch_trunc-1):0))] <- 0
forecast_F[(length(forecast_F[,1])-c((Catch_trunc*length(seasons)*length(F_cols)-1):0)),4] <- 0
}
F_maxed <- max(achieved.report[,'F'])
forecast_F[,4] <- achieved.report[,'F']
loop <- loop - 1
}else {
if(fitting_Benchmark==TRUE){
#Calculate the average F at equilibrium that all F's will be scaled to in order
#to achieve equal F in every year. As depletion approaches the target value this
#F will approach F(OFL).
F_report<-SPRfit$F_report
if(is.null(F_report)){
F_report<-SPRfit$F_std
}
FScale<-median(F_report[(length(F_report)-0.5*Years_projection):length(F_report)])
F_OFL<-FScale
if(!is.null(ABC_Fraction)){
F.ABC<-ABC_Fraction*FScale
}else{
F.ABC<-FScale
}
Achieved.Catch.equil <- sum(TimeFit3[(length(TimeFit3[,1])-9):length(TimeFit3[,1]),Catch_cols3])/10
Achieved.SSBratio.equil <- median(TimeFit3$SpawnBio[(length(TimeFit3$SpawnBio)-9):length(TimeFit3$SpawnBio)])/Virgin_bio
Achieved.SPR.equil <- median(TimeFit3$SpawnBio[(length(TimeFit3$SpawnBio)-9):length(TimeFit3$SpawnBio)]/TimeFit3$Recruit_0[(length(TimeFit3$SpawnBio)-9):length(TimeFit3$SpawnBio)]) #median(SPRfit$SPR[(length(SPRfit$SPR)-9):length(SPRfit$SPR)])
Achieved.SSB.equil <- median(TimeFit3$SpawnBio[(length(TimeFit3$SpawnBio)-9):length(TimeFit3$SpawnBio)])
Achieved.Rec.equil <- median(TimeFit3$Recruit_0[(length(TimeFit3$Recruit_0)-9):length(TimeFit3$Recruit_0)])
if(n_groups>1){
projection_results[["Group_Catch_Benchmark"]]<-list()
projection_results[["Group_Catch_Equil_Benchmark"]]<-list()
for(i in 1:n_groups){
Achieved.Catch.group.equil <- sum(TimeFit3[(length(TimeFit3[,1])-9):length(TimeFit3[,1]),Catch_cols3[fleets_by_group[[i]]]])/10
projection_results[["Group_Catch_Equil_Benchmark"]][[i]]<-Achieved.Catch.group.equil
Achieved.Catch.group <- apply(TimeFit3[1:terminal_year,Catch_cols3[fleets_by_group[[i]]],drop=FALSE],1,sum)
projection_results[["Group_Catch_Benchmark"]][[i]]<-Achieved.Catch.group
}
}
projection_results[["Catch_equil_Benchmark"]] <- Achieved.Catch.equil
projection_results[["F_equil_Benchmark"]] <- F_OFL
projection_results[["Depletion_equil_Benchmark"]] <- Achieved.SSBratio.equil
projection_results[["SSB_equil_Benchmark"]] <- Achieved.SSB.equil
projection_results[["SPR_equil_Benchmark"]] <- Achieved.SPR.equil
projection_results[["Recruitment_equil_Benchmark"]] <- Achieved.Rec.equil
projection_results[["Forecatch_Benchmark"]] <- achieved.report
projection_results[["Catch_Benchmark"]] <- Achieved.Catch
projection_results[["F_Benchmark"]] <- Achieved.F
projection_results[["Depletion_Benchmark"]] <- Achieved.SSBratio
projection_results[["SSB_Benchmark"]] <- Achieved.SSB
projection_results[["SPR_Benchmark"]] <- Achieved.SPR
projection_results[["Recruitment_Benchmark"]] <- Achieved.Rec
#Calculate depletion target adjustment scale depending on the specified target (SPR ratio, SSB ratio, or true MSY)
if(Forecast_target==1){
search_step<-0.00001
Target.Depletion <- forecast[["SPRtarget"]]
Depletion<-SPRfit$SPR
Achieved.Depletion <- median(Depletion[(length(Depletion)-29):length(Depletion)])
Achieved.Depletion <- min(Achieved.Depletion,max(Target.Depletion,0.9))
DepletionScale <- (1-Target.Depletion)/(1-Achieved.Depletion)
if(FScale==0){
if(DepletionScale<=1.0001){
DepletionScale<-1
}else{
FScale<-0.0001
F_OFL<-FScale
if(!is.null(ABC_Fraction)){
F.ABC<-ABC_Fraction*FScale
}else{
F.ABC<-FScale
}
}
}else{
DepletionScale <- (-log(1-((1-exp(-FScale))*DepletionScale))/FScale)
}
Depletion_R<-TimeFit3$SpawnBio/Virgin_bio
Target.Rebuild <- median(Depletion_R[(length(Depletion_R)-9):length(Depletion_R)])
}else if(Forecast_target==2){
Depletion <- TimeFit3$SpawnBio/Virgin_bio
Achieved.Depletion <- median(Depletion[(length(Depletion)-29):length(Depletion)])
Achieved.Depletion <- min(Achieved.Depletion,.9)
if(First_run == TRUE){
Target.Depletion <- forecast[["Btarget"]]
First_run <- FALSE
}
Target.Rebuild <- Target.Depletion
Achieved.SSB <- Achieved.Depletion
if(max(abs(1-Fmult3))>Allocation.Threshold |
max(abs(1-Fmult2))>Annual.F.Threshold |
max(abs(1-Fmult1))>Depletion.Threshold){
loop<-loop-1
subloop<-subloop+1
if(F_max==TRUE){
Achieved.Catch <- sum(TimeFit3[(length(TimeFit3[,1])-9):length(TimeFit3[,1]),Catch_cols3])/
sum(TimeFit3[(length(TimeFit3[,1])-9):length(TimeFit3[,1]),"Recruit_0"])
}else{
Achieved.Catch <- sum(TimeFit3[(length(TimeFit3[,1])-9):length(TimeFit3[,1]),Catch_cols3])/10
}
MSY.Fit[1,] <- c(Achieved.Catch,FScale,Achieved.Depletion,Target.Depletion)
}else{
subloop<-0
if(F_max==TRUE){
Achieved.Catch <- sum(TimeFit3[(length(TimeFit3[,1])-9):length(TimeFit3[,1]),Catch_cols3])/
sum(TimeFit3[(length(TimeFit3[,1])-9):length(TimeFit3[,1]),"Recruit_0"])
}else{
Achieved.Catch <- sum(TimeFit3[(length(TimeFit3[,1])-9):length(TimeFit3[,1]),Catch_cols3])/10
}
MSY.Fit <- rbind(MSY.Fit[1,],MSY.Fit)
MSY.Fit[1,] <- c(Achieved.Catch,FScale,Achieved.Depletion,Target.Depletion)
if(loop>1){
if(Achieved.Catch<Last_Achieved_Catch){
search_step <- -0.5*search_step
}
Target.Depletion <- Target.Depletion+search_step
min_diff <- which(abs(MSY.Fit[,4]-Target.Depletion)<0.001)
if(length(min_diff)>0){
Old.Catch <- MSY.Fit[min_diff[1],1]
if(Old.Catch<Achieved.Catch){
search_step <- -0.5*search_step
}
Target.Depletion <- Target.Depletion+search_step
Achieved.Catch <- Old.Catch
}
}else{
steps <- seq(0.1,0.9,0.1)
New.Target.Depletion <- steps[which(abs(steps-Target.Depletion)==min(abs(steps-Target.Depletion)))[1]]
if(New.Target.Depletion<Target.Depletion){
search_step <- -1*search_step
}
Target.Depletion <- New.Target.Depletion
}
Last_Achieved_Catch <- Achieved.Catch
}
DepletionScale <- (1-Target.Depletion)/(1-Achieved.Depletion)
if(FScale==0){
if(DepletionScale<=1.0001){
DepletionScale<-1
}else{
FScale<-0.0001
F_OFL<-FScale
if(!is.null(ABC_Fraction)){
F.ABC<-ABC_Fraction*FScale
}else{
F.ABC<-FScale
}
}
}
if(Make_plots==TRUE){
par(mar=c(4,3,3,2))
if(F_max==TRUE){
plot(x=TimeFit3[,"Yr"],y=apply(TimeFit3[,Catch_cols3,drop=FALSE],1,sum)/TimeFit3[,"Recruit_0"],
xlab="year",ylab="Total Yield Per Recruit",main = paste0(method," loop = ",loop,".",subloop))
plot(x=MSY.Fit[,"depletion"],y=MSY.Fit[,"catch"],xlim=c(0.9*min(MSY.Fit[,3:4]),1.1*max(MSY.Fit[,3:4])),
xlab="Esimated depletion",ylab="Total Yield Per Recruit",main = paste0(method," loop = ",loop,".",subloop))
lines(x=c(MSY.Fit[1,c(4,4)]),y=c(0,2*max(MSY.Fit[,"catch"])),col="dark red")
points(x=MSY.Fit[1,3],y=MSY.Fit[1,1],pch=16,col="dark blue")
}else{
plot(x=TimeFit3[,"Yr"],y=apply(TimeFit3[,Catch_cols3,drop=FALSE],1,sum),
xlab="year",ylab="Total Yield",main = paste0(method," loop = ",loop,".",subloop))
plot(x=MSY.Fit[,"depletion"],y=MSY.Fit[,"catch"],xlim=c(0.9*min(MSY.Fit[,3:4]),1.1*max(MSY.Fit[,3:4])),
xlab="Esimated depletion",ylab="Total Yield",main = paste0(method," loop = ",loop,".",subloop))
lines(x=c(MSY.Fit[1,c(4,4)]),y=c(0,2*max(MSY.Fit[,"catch"])),col="dark red")
points(x=MSY.Fit[1,3],y=MSY.Fit[1,1],pch=16,col="dark blue")
}
}
}else if(Forecast_target==3){
search_step<-0.00001
Target.Depletion <- forecast[["Btarget"]]
Target.Rebuild <- forecast[["Btarget"]]
Depletion<-TimeFit3$SpawnBio/Virgin_bio
Achieved.Depletion <- median(Depletion[(length(Depletion)-29):length(Depletion)])
Achieved.Depletion <- min(Achieved.Depletion,max(0.9,Target.Depletion))
DepletionScale <- (1-Target.Depletion)/(1-Achieved.Depletion)
if(FScale==0){
if(DepletionScale<=1.0001){
DepletionScale<-1
}else{
FScale<-0.0001
F_OFL<-FScale
if(!is.null(ABC_Fraction)){
F.ABC<-ABC_Fraction*FScale
}else{
F.ABC<-FScale
}
}
}else{
DepletionScale <- (-log(1-((1-exp(-FScale))*DepletionScale))/FScale)
}
}
}else if(fitting_OFL==TRUE){
search_step<-0.00001 #Set search step to small value so it doesn't trigger continued loops this value is only needed during the Benchmark MSY search
DepletionScale<-1 #Set depletion scale to 1 so it doesn't trigger continued loops now that Benchmark search is complete
FScale<-F_OFL #Set the F target to F.OFL for rescaling annual F values
if(n_groups>1){
projection_results[["Group_Catch_OFL"]]<-list()
for(i in 1:n_groups){
Achieved.Catch.group <- apply(TimeFit3[1:terminal_year,Catch_cols3[fleets_by_group[[i]]],drop=FALSE],1,sum)
projection_results[["Group_Catch_OFL"]][[i]]<-Achieved.Catch.group
}
}
projection_results[["Catch_OFL"]] <- Achieved.Catch
projection_results[["F_OFL"]] <- Achieved.F
projection_results[["Depletion_OFL"]] <- Achieved.SSBratio
projection_results[["SSB_OFL"]] <- Achieved.SSB
projection_results[["SPR_OFL"]] <- Achieved.SPR
projection_results[["Recruitment_OFL"]] <- Achieved.Rec
projection_results[["Forecatch_OFL"]] <- achieved.report
}else if(fitting_ABC==TRUE){
search_step<-0.00001 #Set search step to small value so it doesn't trigger continued loops this value is only needed during the Benchmark MSY search
DepletionScale<-1 #Set depletion scale to 1 so it doesn't trigger continued loops now that Benchmark search is complete
FScale<-F.ABC #Set the F target to F.ABC for rescaling annual F values
if(n_groups>1){
projection_results[["Group_Catch_ABC"]]<-list()
for(i in 1:n_groups){
Achieved.Catch.group <- apply(TimeFit3[1:terminal_year,Catch_cols3[fleets_by_group[[i]]],drop=FALSE],1,sum)
projection_results[["Group_Catch_ABC"]][[i]]<-Achieved.Catch.group
}
}
projection_results[["Catch_ABC"]] <- Achieved.Catch
projection_results[["F_ABC"]] <- Achieved.F
projection_results[["Depletion_ABC"]] <- Achieved.SSBratio
projection_results[["SSB_ABC"]] <- Achieved.SSB
projection_results[["SPR_ABC"]] <- Achieved.SPR
projection_results[["Recruitment_ABC"]] <- Achieved.Rec
projection_results[["Forecatch_ABC"]] <- achieved.report
}else if(fitting_F0==TRUE){
search_step<-0.00001 #Set search step to small value so it doesn't trigger continued loops this value is only needed during the Benchmark MSY search
DepletionScale<-1 #Set depletion scale to 1 so it doesn't trigger continued loops now that Benchmark search is complete
FScale<-0 #Set the F target to 0 for rescaling annual F values
if(n_groups>1){
projection_results[["Group_Catch_F0"]]<-list()
for(i in 1:n_groups){
Achieved.Catch.group <- apply(TimeFit3[1:terminal_year,Catch_cols3[fleets_by_group[[i]]],drop=FALSE],1,sum)
projection_results[["Group_Catch_F0"]][[i]]<-Achieved.Catch.group
}
}
projection_results[["Catch_F0"]] <- Achieved.Catch
projection_results[["F_F0"]] <- Achieved.F
projection_results[["Depletion_F0"]] <- Achieved.SSBratio
projection_results[["SSB_F0"]] <- Achieved.SSB
projection_results[["SPR_F0"]] <- Achieved.SPR
projection_results[["Recruitment_F0"]] <- Achieved.Rec
projection_results[["Forecatch_F0"]] <- achieved.report
}else if(fitting_Rebuild==TRUE){
search_step<-0.00001 #Set search step to small value so it doesn't trigger continued loops this value is only needed during the Benchmark MSY search
DepletionScale<-1 #Set depletion scale to 1 so it doesn't trigger continued loops now that Benchmark search is complete
FScale<-F_OFL #Set the F target to F_OFL for rescaling annual F values in years after the rebuild period.
F_report<-SPRfit$F_report
if(is.null(F_report)){
F_report<-SPRfit$F_std
}
F_Rebuild_Scale<-F_report[SPRfit$Yr==Rebuild_yr]
Depletion<-TimeFit3$SpawnBio/Virgin_bio
Achieved.Rebuild <- mean(Depletion[SPRfit$Yr==Rebuild_yr])
Rebuild.Scale <- (1-Target.Rebuild)/(1-Achieved.Rebuild)
Rebuild.Ratio <- Rebuild.Scale
Rebuild.Scale <- min(-log(1-((1-exp(-F_Rebuild_Scale))*Rebuild.Scale)),FScale)
if(Rebuild.Scale < 0.00001 & Rebuild.Ratio < 1){
Rebuild.Scale <- 0
}
if(n_groups>1){
projection_results[["Group_Catch_Rebuild"]]<-list()
for(i in 1:n_groups){
Achieved.Catch.group <- apply(TimeFit3[1:terminal_year,Catch_cols3[fleets_by_group[[i]]],drop=FALSE],1,sum)
projection_results[["Group_Catch_Rebuild"]][[i]]<-Achieved.Catch.group
}
}
projection_results[["Catch_Rebuild"]] <- Achieved.Catch
projection_results[["F_Rebuild"]] <- Achieved.F
projection_results[["Depletion_Rebuild"]] <- Achieved.SSBratio
projection_results[["SSB_Rebuild"]] <- Achieved.SSB
projection_results[["SPR_Rebuild"]] <- Achieved.SPR
projection_results[["Recruitment_Rebuild"]] <- Achieved.Rec
projection_results[["Forecatch_Rebuild"]] <- achieved.report
}else if (fitting_Fixed_Catch==TRUE){
search_step<-0.00001 #Set search step to small value so it doesn't trigger continued loops this value is only needed during the Benchmark MSY search
DepletionScale<-1 #Set depletion scale to 1 so it doesn't trigger continued loops now that Benchmark search is complete
FScale<-0 #Set the F target to F_OFL for rescaling annual F values in years after the rebuild period.
Fmult4 <- rep(Catch_Target/Achieved.Catch.All,each=(length(seasons)*length(F_cols)))
Fmult4 <- ifelse(forecast_F[,4]>=1.5,ifelse(Fmult4>1,1,Fmult4),Fmult4)
Fmult4[is.na(Fmult4)] <- 1
projection_results[[paste0("Catch_FixedCatch_",CC_loop)]] <- Achieved.Catch
projection_results[[paste0("F_FixedCatch_",CC_loop)]] <- Achieved.F
projection_results[[paste0("Depletion_FixedCatch_",CC_loop)]] <- Achieved.SSBratio
projection_results[[paste0("SSB_FixedCatch_",CC_loop)]] <- Achieved.SSB
projection_results[[paste0("SPR_FixedCatch_",CC_loop)]] <- Achieved.SPR
projection_results[[paste0("Recruitment_FixedCatch_",CC_loop)]] <- Achieved.Rec
projection_results[[paste0("Forecatch_FixedCatch_",CC_loop)]] <- achieved.report
}
#Fmult2 calculations define the multiplier for adjusting annual F values
#Zero catch years are identified first to prevent divide by zero errors in the scaling and
#to tell the search algorithm that the target has been achieved
if(is.null(SPRfit$F_report)){
zero_catch <- which(SPRfit$F_std[sort(rep(seq_along(SPRfit$F_std),length(seasons)*length(F_cols)))]==0)
}else{
zero_catch <- which(SPRfit$F_report[sort(rep(seq_along(SPRfit$F_report),length(seasons)*length(F_cols)))]==0)
}
if(fitting_Fixed_Catch==FALSE){
if(length(zero_catch)>0){
if(FScale==0){
Fmult2[zero_catch] <- 1
Fmult2[-zero_catch] <- 0
}else{
Fmult2[zero_catch] <- 2
if(is.null(SPRfit$F_report)){
temp_F <- SPRfit$F_std[sort(rep(seq_along(SPRfit$F_std),length(seasons)*length(F_cols)))][-zero_catch]
}else{
temp_F <- SPRfit$F_report[sort(rep(seq_along(SPRfit$F_report),length(seasons)*length(F_cols)))][-zero_catch]
}
temp_F[temp_F>1.5] <- 1.5
temp_F[temp_F<(min(0.001,FScale))] <- min(0.001,FScale)
Fmult2[-zero_catch] <- FScale/temp_F
}
}else if(FScale==0){
Fmult2[] <- 0
}else{
if(is.null(SPRfit$F_report)){
temp_F <- SPRfit$F_std[sort(rep(seq_along(SPRfit$F_std),length(seasons)*length(F_cols)))]
}else{
temp_F <- SPRfit$F_report[sort(rep(seq_along(SPRfit$F_report),length(seasons)*length(F_cols)))]