generated from SEFSC/SEFSC-Template
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAllocation_forecasting.R
More file actions
2272 lines (2080 loc) · 117 KB
/
Allocation_forecasting.R
File metadata and controls
2272 lines (2080 loc) · 117 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##---------------------------------------------------------------------##
# #
# 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: 8/1/25 #
# 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
Benchmark_recruit_setting = 0, #Forecast recruitment setting to use for benchmarks in forecast file
OFL_recruit_setting = NULL, #Forecast recruitment setting to use for OFL in forecast file if NULL uses forecast file
ABC_recruit_setting = NULL, #Forecast recruitment setting to use for OFL in forecast file if NULL uses forecast file
Rebuild_recruit_setting = NULL, #Forecast recruitment setting to use for OFL in forecast file if NULL uses forecast file
F0_recruit_setting = NULL, #Forecast recruitment setting to use for OFL in forecast file if NULL uses forecast file
Const_catch_recruit_setting = NULL, #Forecast recruitment setting to use for OFL in forecast file if NULL uses forecast file
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.
Constant_fixed_catch = NULL, #Input a data frame with column names ("Fleet","Catch or F","Basis")
Annual_fixed_catch = NULL, #Input data frame for fixed catches in format of forecatch data frame with columns c("Year","Seas","Fleet","Catch or F","Basis")
Starting_Forecatch = NULL, #Input data frame for initial F values in format of forecatch data frame with columns c("Year","Seas","Fleet","Catch or F","Basis") otherwise will default to recent mean F
Fleet_group = NULL, #Data frame with columns c("Fleet","Group")specifying fleet grouping for allocations (defaults to forecast file settings if NULL)
Group_Allocations = NULL, #Data frame specifying scenarios for allocation of catch between groups (defaults to forecast file settings if NULL)
#If not null input a dataframe with a column for each group and row for each scenario.
Run_in_MSE = FALSE,
MSY_step = 0.1,
SS_exe = NULL,
Verbose = FALSE,
Keep_Only_Final = FALSE,
Keep_files = 1, #Which run files to keep options(1:All files,2:Minimum subset for r4ss output,3:Only Report)
Messages = TRUE
)
{
projection_results <- list()
if(Messages == TRUE){
message("Starting projections calculations")
}
oldwd<-getwd()
return_warnings <- FALSE
combinded_warnings <- NULL
# library(r4ss)
# if(Run_in_MSE==TRUE){
# library(SSMSE)
# }
#Set large max print to avoid issues with writing out a large forecast file.
options(max.print = 1000000)
setwd(normalizePath(paste0(Assessment_dir)))
Assessment_dir <- normalizePath(getwd())
#Read in all the model files and results
start <- r4ss::SS_readstarter(verbose = Verbose)
dat <- r4ss::SS_readdat(file = start$datfile, version = 3.3, verbose = Verbose)
ctl <- r4ss::SS_readctl(file = start$ctlfile, version = 3.3, use_datlist = TRUE, datlist = dat, verbose = Verbose)
results <- r4ss::SS_output(dir = getwd(), covar = FALSE, verbose = Verbose, printstats= Verbose)
forecast <- r4ss::SS_readforecast(verbose = Verbose)
if(!is.null(forecast$ForeCatch)){
if(length(grep("year",colnames(forecast$ForeCatch)))==1){
forecast$ForeCatch <- forecast$ForeCatch[forecast$ForeCatch$year<=(dat$endyr+forecast$Nforecastyrs) &
forecast$ForeCatch$year>(dat$endyr),]
}else if(length(grep("Year",colnames(forecast$ForeCatch)))==1){
forecast$ForeCatch <- forecast$ForeCatch[forecast$ForeCatch$Year<=(dat$endyr+forecast$Nforecastyrs) &
forecast$ForeCatch$Year>(dat$endyr),]
}else{
stop("Error: for some reason the forecast ForeCatch dataframe doesn't
have any column named 'year' or 'Year' contact developer to update
for an apparent change in SS/r4ss formating")
}
}
os <- .Platform[["OS.type"]]
if(Run_in_MSE == TRUE){
bin <- SSMSE:::get_bin("ss")
}else{
if(!is.null(SS_exe)){
}else if(file.exists("ss")){
SS_exe <- "ss"
}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")
}
admb_options <- "-nohess"
parlist <- r4ss::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(dir.exists(file.path(getwd(),"Working_dir"))){
unlink(file.path(getwd(),"Working_dir"), recursive = TRUE)
}
if(dir.exists(file.path(getwd(),"Final"))){
unlink(file.path(getwd(),"Final"), recursive = TRUE)
}
base.files <- list.files(path=Assessment_dir)
dir.create(file.path(getwd(),"Working_dir"))
if(Keep_Only_Final==TRUE){
if(dir.exists(file.path(getwd(),"OFL_target"))){
unlink(file.path(getwd(),"OFL_target"), recursive = TRUE)
}
if(dir.exists(file.path(getwd(),"ABC_target"))){
unlink(file.path(getwd(),"ABC_target"), recursive = TRUE)
}
if(dir.exists(file.path(getwd(),"Rebuild_target"))){
unlink(file.path(getwd(),"Rebuild_target"), recursive = TRUE)
}
if(dir.exists(file.path(getwd(),"F0_target"))){
unlink(file.path(getwd(),"F0_target"), recursive = TRUE)
}
dir.create(file.path(getwd(),"Final"))
}
if(Benchmark_complete == FALSE){
if(Keep_Only_Final==TRUE){
if(dir.exists(file.path(getwd(),"Benchmark_target"))){
unlink(file.path(getwd(),"Benchmark_target"), recursive = TRUE)
}
}
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(),"Benchmark_target"))
folders <- which(grep("Allocation_run_",temp.files,fixed=TRUE))
if(length(folders)>0){
temp.files <- temp.files[-folders]
}
file.copy(from = file.path(getwd(),"Benchmark_target",temp.files), to = file.path(getwd(),"Working_dir",temp.files))
}
if(Keep_Only_Final==TRUE){
base.files <- base.files[!is.element(base.files,c("starter.ss","starter.ss_new","ss.par",
start$datfile,start$ctlfile,"Report.sso",
"forecast.ss","forecast.ss_new","Forecast-report.sso",
"data.ss_new","control.ss_new","wtatage.ss_new"))]
unlink(file.path(getwd(),base.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
input_recruit_setting <- forecast$fcast_rec_option
if(is.null(Benchmark_recruit_setting)){
Benchmark_recruit_setting <- input_recruit_setting
}
if(is.null(OFL_recruit_setting)){
OFL_recruit_setting <- input_recruit_setting
}
if(is.null(ABC_recruit_setting)){
ABC_recruit_setting <- input_recruit_setting
}
if(is.null(Rebuild_recruit_setting)){
Rebuild_recruit_setting <- input_recruit_setting
}
if(is.null(F0_recruit_setting)){
F0_recruit_setting <- input_recruit_setting
}
if(is.null(Const_catch_recruit_setting)){
Const_catch_recruit_setting <- input_recruit_setting
}
if(Benchmark_complete==FALSE){
forecast$fcast_rec_option <- Benchmark_recruit_setting
}
#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))
}
}
if(!is.null(dat$bycatch_fleet_info)){
if(length(dat$bycatch_fleet_info[,1])>0){
min_bycatch_fcast_yr <- dat$bycatch_fleet_info[,4]
min_bycatch_fcast_yr[min_bycatch_fcast_yr<=0] <- dat[["endyr"]]+min_bycatch_fcast_yr[min_bycatch_fcast_yr<=0]
max_bycatch_fcast_yr <- dat$bycatch_fleet_info[,5]
max_bycatch_fcast_yr[max_bycatch_fcast_yr<=0] <- dat[["endyr"]]+max_bycatch_fcast_yr[max_bycatch_fcast_yr<=0]
for(i in seq_along(min_bycatch_fcast_yr)){
TargetYears_bycatch <- TimeFit2[TimeFit2$Yr>=min_bycatch_fcast_yr[i] & TimeFit2$Yr<=max_bycatch_fcast_yr[i],]
TargetYears_bycatch <- TargetYears_bycatch[,c(2,F_cols2)]
seasons <- unique(TargetYears_bycatch[,1])
F_by_Fleet_seas_bycatch <- as.data.frame(matrix(apply(TargetYears_bycatch[TargetYears_bycatch[,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_bycatch <- rbind(F_by_Fleet_seas_bycatch,apply(TargetYears_bycatch[TargetYears_bycatch[,1]==i,,drop=FALSE], 2, mean))
}
}
F_by_Fleet_seas[1,(dat$bycatch_fleet_info[i,1]+1)] <- F_by_Fleet_seas_bycatch[1,(dat$bycatch_fleet_info[i,1]+1)]
}
}
}
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")
}
#Set up the forecast Forecatch dataframe to specify fixed fishing mortality rates
#for each fleet for the entire 100 year projection period.
#data frame will be build sequentially
#1) Set all F's to recent mean from the model
Forecast_catch_setup<-matrix(1,nrow=forecast[["Nforecastyrs"]]*length(seasons)*length(F_cols),ncol=7)
Forecast_catch_setup[,1]<-sort(rep((dat[["endyr"]]+1):(dat[["endyr"]]+forecast[["Nforecastyrs"]]),length(seasons)*length(F_cols)))
Forecast_catch_setup[,2]<-rep(sort(rep(seasons,length(F_cols))),forecast[["Nforecastyrs"]])
Forecast_catch_setup[,3]<-rep(sort(which(dat$fleetinfo$type!=3)),forecast[["Nforecastyrs"]]*(length(seasons)))
for(i in seasons){
Forecast_catch_setup[Forecast_catch_setup[,2]==i,4]<-unlist(rep(F_by_Fleet_seas[F_by_Fleet_seas[,1]==i,-1],forecast[["Nforecastyrs"]]))
}
Forecast_catch_setup[,5] <- 99
Forecast_catch_setup[,6] <- 0
Forecast_catch_setup[,6] <- 0
Forecast_catch_setup<-as.data.frame(Forecast_catch_setup)
colnames(Forecast_catch_setup)<-c("Year","Seas","Fleet","Catch or F","Basis","Fixed","Rebuild")
#2) Set any fleets with 0 F to a small number so they can be increased if needed
#Forecast_catch_setup[,"Catch or F"] <- ifelse(Forecast_catch_setup[,"Catch or F"]==0, 0.00000001,Forecast_catch_setup[,"Catch or F"])
#3) Incorporate fixed values from the existing forecast file
if(!is.null(forecast$ForeCatch)){
for(i in seq_along(forecast$ForeCatch[,1])){
match_row <- which(Forecast_catch_setup[,c("Year")]==forecast$ForeCatch[i,c("Year")] &
Forecast_catch_setup[,c("Seas")]==forecast$ForeCatch[i,c("Seas")] &
Forecast_catch_setup[,c("Fleet")]==forecast$ForeCatch[i,c("Fleet")])
Forecast_catch_setup[match_row,"Catch or F"] <- forecast$ForeCatch[i,"Catch or F"]
Forecast_catch_setup[match_row,"Fixed"] <- 1
if(length(forecast$ForeCatch[i,])==5){
Forecast_catch_setup[match_row,"Basis"] <- forecast$ForeCatch[i,"Basis"]
}else if(length(forecast$ForeCatch[i,])==4){
Forecast_catch_setup[match_row,"Basis"] <- forecast$InputBasis
}else{
stop("You have a Forecatch dataframe in your forecast file but it doesn't have 4 or 5 columns something is wrong")
}
}
if(!is.null(Constant_fixed_catch)){
return_warnings <- TRUE
combinded_warnings <- paste(combinded_warnings,
"You have input fixed constant catches but also have fixed values in the model forecast file. Check results to make sure all values are what you intended",
sep="\n")
}
if(!is.null(Annual_fixed_catch)){
return_warnings <- TRUE
combinded_warnings <- paste(combinded_warnings,
"You have input fixed annual catches but also have fixed values in the model forecast file. Check results to make sure all values are what you intended",
sep="\n")
}
}
#4) Fix constant F/Catch for fleets such as red tide, bycatch, or closed fleets
if(!is.null(Constant_fixed_catch)){
for(i in seq_along(Constant_fixed_catch[,1])){
if(is.null(Constant_fixed_catch[i,"Catch or F"])){
Forecast_catch_setup[Forecast_catch_setup[,"Fleet"]==Constant_fixed_catch[i,"Fleet"],"Catch or F"] <- Constant_fixed_catch[i,"Catch.or.F"]
}else{
Forecast_catch_setup[Forecast_catch_setup[,"Fleet"]==Constant_fixed_catch[i,"Fleet"],"Catch or F"] <- Constant_fixed_catch[i,"Catch or F"]
}
Forecast_catch_setup[Forecast_catch_setup[,"Fleet"]==Constant_fixed_catch[i,"Fleet"],"Basis"] <- Constant_fixed_catch[i,"Basis"]
Forecast_catch_setup[Forecast_catch_setup[,"Fleet"]==Constant_fixed_catch[i,"Fleet"],"Fixed"] <- 1
}
}
#5) Update annual fixed F for fleets usually used for interim period catches
if(!is.null(Annual_fixed_catch)){
for(i in seq_along(Annual_fixed_catch[,1])){
match_row <- which(Forecast_catch_setup[,c("Year")]==Annual_fixed_catch[i,c("Year")] &
Forecast_catch_setup[,c("Seas")]==Annual_fixed_catch[i,c("Seas")] &
Forecast_catch_setup[,c("Fleet")]==Annual_fixed_catch[i,c("Fleet")])
if(is.null(Annual_fixed_catch[i,"Catch or F"])){
Forecast_catch_setup[match_row,"Catch or F"] <- Annual_fixed_catch[i,"Catch.or.F"]
}else{
Forecast_catch_setup[match_row,"Catch or F"] <- Annual_fixed_catch[i,"Catch or F"]
}
Forecast_catch_setup[match_row,"Basis"] <- Annual_fixed_catch[i,"Basis"]
Forecast_catch_setup[match_row,"Fixed"] <- 1
}
}
#6) Create reference trackers for which years have fixed catch and which are adjusted
fixed_ref <- which(Forecast_catch_setup[,"Fixed"]==1)
adjusted_F_OFL<-which(Forecast_catch_setup[,"Fixed"]==0)
Fixed_catch_target<-Forecast_catch_setup[fixed_ref,1:5]
#7) Create forecast_F dataframe that will be used to update ForeCatch in forecast file
forecast_F <- Forecast_catch_setup[,1:5]
#6) Identify which years are subject to rebuilding plan F limits
if(!is.null(Rebuild_yr)){
#This reference identifies inputs subject to a rebuilding period F if any
rebuild_ref <- which(Forecast_catch_setup[,1]<=Rebuild_yr)
if(length(rebuild_ref)>0){
Forecast_catch_setup[rebuild_ref,"Rebuild"]<-1
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
if(is.null(Fleet_group)){
n_groups <- forecast[["N_allocation_groups"]]
}else{
n_groups <- length(unique(Fleet_group[Fleet_group[,"Group"]!=0,"Group"]))
}
groups <- rep(0,length(F_cols))
fleets_by_group <- list()
#Setup multiple allocation scenarios matrix to run allocation grid
if(!is.null(Group_Allocations)){
if(length(Group_Allocations[1,])!=n_groups){
stop("Error: You have a different number of allocations specifed than the number of groups")
}
N_allocation_scenarios <- length(Group_Allocations[,1])
Allocation_targets <- Group_Allocations
for(i in seq_along(Allocation_targets[,1])){
Allocation_targets[i,] <- Allocation_targets[i,]/sum(Allocation_targets[i,])
}
Allocation_targets <- rbind(unique(Fleet_group[Fleet_group[,"Group"]!=0,"Group"]),Group_Allocations)
}else{
N_allocation_scenarios <- 1
}
Allocation_tracker <- list()
#Loop over all allocation scenarios
for(i in 1:N_allocation_scenarios){
projection_results[[paste0("Allocation_run_",i)]] <- list()
Allocations <- forecast_F[,c(1,2,3,4,5,5,5)]
Allocations[,c(4)] <- 0
Allocations[,c(5,6)] <- 1
Allocations[,c(7)] <- 0
names(Allocations) <- c("Year","Seas","Fleet","Group","Target","Achieved","Tracked")
if(n_groups>0){
if(is.null(Fleet_group)){
for(j in seq_along(forecast[["fleet_assignment_to_allocation_group"]][,"Fleet"])){
groups[forecast[["fleet_assignment_to_allocation_group"]][j,"Fleet"]] <- forecast[["fleet_assignment_to_allocation_group"]][j,"Group"]
Allocations[Allocations[,"Fleet"]==forecast[["fleet_assignment_to_allocation_group"]][j,"Fleet"],4] <- forecast[["fleet_assignment_to_allocation_group"]][j,"Group"]
}
alloc <- forecast[["allocation_among_groups"]][order(forecast[["allocation_among_groups"]][,"Year"]),]
for(j in seq_along(alloc[,1])){
for(k in seq_along(alloc[j,-1])){
Allocations[Allocations[,1]>=alloc[,"Year"] & Allocations[,4]==k,5] <- alloc[j,(k+1)]/sum(alloc[j,-1])
Allocations[Allocations[,1]>=alloc[,"Year"] & Allocations[,4]==k,7] <- 1
}
}
}else{
for(j in seq_along(Fleet_group[,"Fleet"])){
groups[Fleet_group[j,"Fleet"]] <- Fleet_group[j,"Group"]
Allocations[Allocations[,"Fleet"]==Fleet_group[j,"Fleet"],4] <- Fleet_group[j,"Group"]
}
for(j in seq_along(Allocation_targets[1,])){
Allocations[Allocations[,"Group"]==Allocation_targets[1,j],5] <- Allocation_targets[i+1,j]
Allocations[Allocations[,"Group"]==Allocation_targets[1,j],7] <- 1
}
}
for(j in 1:n_groups){
fleets_by_group[[j]]<-which(is.element(which(dat$fleetinfo$type!=3),which(groups==j)))
}
}
Allocation_tracker[[i]] <- Allocations
}
Allocations <- Allocation_tracker[[1]]
allocation_loop <- 1
forecast[["Forecast"]] <- 4
forecast[["InputBasis"]] <- -1
forecast[["ForeCatch"]] <- forecast_F
forecast[["FirstYear_for_caps_and_allocations"]] <- (dat[["endyr"]]+forecast[["Nforecastyrs"]]+1)
forecast[["N_forecast_loops"]] <- 2
last_forecast_F <- forecast[["ForeCatch"]]
keepFitting <- TRUE
loop <- 0
subloop <- 0
Curr_max_mult <- Last_max_mult <- Min_max_mult <- F_maxed <- Last_median_mult <- Min_median_mult <- Curr_median_mult <- 100000
global_adjuster <- 1
max_F_limit <- ctl$maxF
F_adjust1 <- F_adjust1_2 <- 1
F_adjust2 <- F_adjust2_2 <- F_SS_adjust <- 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))
Fmult1_raw <- Fmult2_raw <- Fmult3_raw <- Fmult4_raw <- rep(1.01,forecast[["Nforecastyrs"]]*length(seasons)*length(F_cols))
Fmult2a <- Fmult2b <- 1
First_run<-TRUE
F_SS_adjust_year <- list(a=sort(rep(1:forecast[["Nforecastyrs"]],length(seasons)*length(F_cols))))
if(!is.null(Const_Catch)){
forecast$fcast_rec_option <- Const_catch_recruit_setting
r4ss::SS_writepar_3.30(parlist = parlist,outfile=par_name,overwrite = TRUE, verbose = Verbose)
r4ss::SS_writeforecast(mylist=forecast,overwrite = TRUE, verbose = Verbose)
r4ss::SS_writestarter(mylist=start,overwrite = TRUE, verbose = Verbose)
dir <- normalizePath(getwd())
if(Run_in_MSE==FALSE){
bin <- file.path(dir,SS_exe)
}
if (os == "unix") {
system(
paste0(
"cd ", dir, ";", paste0(bin, " "),
admb_options
),
ignore.stdout = TRUE
)
} else {
system(paste0(paste0(bin, " "), admb_options),
invisible = TRUE, ignore.stdout = TRUE,
show.output.on.console = FALSE
)
}
Sys.sleep(0.05)
#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.
r4ss::SS_writepar_3.30(parlist = parlist, outfile = par_name, overwrite = TRUE, verbose = Verbose)
r4ss::SS_writeforecast(mylist=forecast,overwrite = TRUE, verbose = Verbose)
r4ss::SS_writestarter(mylist=start,overwrite = TRUE, verbose = Verbose)
dir <- normalizePath(getwd())
if(Run_in_MSE==FALSE){
bin <- file.path(dir,SS_exe)
}
if (os == "unix") {
system(
paste0(
"cd ", dir, ";", paste0(bin, " "),
admb_options
),
ignore.stdout = TRUE
)
} else {
system(paste0(paste0(bin, " "), admb_options),
invisible = TRUE, ignore.stdout = TRUE,
show.output.on.console = FALSE
)
}
Sys.sleep(0.05)
#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 <- r4ss::SS_readstarter(verbose = Verbose)
dat <- r4ss::SS_readdat(file = start$datfile, version = 3.3, verbose = Verbose)
ctl <- r4ss::SS_readctl(file = start$ctlfile, version = 3.3, use_datlist = TRUE, datlist = dat, verbose = Verbose)
results <- r4ss::SS_output(dir = getwd(), covar = FALSE, verbose = Verbose, printstats= Verbose)
forecast <- r4ss::SS_readforecast(verbose = Verbose)
parlist <- r4ss::SS_readpar_3.30(parfile = par_name, datsource = dat, ctlsource = ctl, verbose = Verbose)
forecast$fcast_rec_option <- OFL_recruit_setting
r4ss::SS_writeforecast(mylist=forecast,overwrite = TRUE, verbose = Verbose)
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))
}
}
if(Messages == TRUE){
if(Benchmark_complete==FALSE){
message("Projections targets have been set up begining optimization of Fs for Benchmarks")
}else{
message("Projections targets have been set up begining optimization of Fs for OFL")
}
}
#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 <- r4ss::SS_output(dir=getwd(),covar=FALSE, verbose = Verbose, printstats= Verbose)
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){
try(
{
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))
}
)
}
if(is.element(loop,c(1,2,3,4,5,10,20,30,40,50,100,200,300,400,500,1000))){
if(Messages == TRUE){
message(paste0("Running optimization loop ",loop))
if(loop>50){
message("Optimization seems to be taking a while I would suggest checking the working directory report and/or forcast files to ensure this is converging")
}
if(loop==1000){
message("Something is probably wrong are you really sure this is converging?")
}
}
}
#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[[paste0("Allocation_run_",allocation_loop)]][["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[[paste0("Allocation_run_",allocation_loop)]][["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[[paste0("Allocation_run_",allocation_loop)]][["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[[paste0("Allocation_run_",allocation_loop)]][["Catch_equil_Benchmark"]] <- Achieved.Catch.equil
projection_results[[paste0("Allocation_run_",allocation_loop)]][["F_equil_Benchmark"]] <- F_OFL
projection_results[[paste0("Allocation_run_",allocation_loop)]][["Depletion_equil_Benchmark"]] <- Achieved.SSBratio.equil
projection_results[[paste0("Allocation_run_",allocation_loop)]][["SSB_equil_Benchmark"]] <- Achieved.SSB.equil
projection_results[[paste0("Allocation_run_",allocation_loop)]][["SPR_equil_Benchmark"]] <- Achieved.SPR.equil
projection_results[[paste0("Allocation_run_",allocation_loop)]][["Recruitment_equil_Benchmark"]] <- Achieved.Rec.equil
projection_results[[paste0("Allocation_run_",allocation_loop)]][["Forecatch_Benchmark"]] <- achieved.report
projection_results[[paste0("Allocation_run_",allocation_loop)]][["Catch_Benchmark"]] <- Achieved.Catch
projection_results[[paste0("Allocation_run_",allocation_loop)]][["F_Benchmark"]] <- Achieved.F
projection_results[[paste0("Allocation_run_",allocation_loop)]][["Depletion_Benchmark"]] <- Achieved.SSBratio
projection_results[[paste0("Allocation_run_",allocation_loop)]][["SSB_Benchmark"]] <- Achieved.SSB
projection_results[[paste0("Allocation_run_",allocation_loop)]][["SPR_Benchmark"]] <- Achieved.SPR
projection_results[[paste0("Allocation_run_",allocation_loop)]][["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
}
expected_annual <- 1-exp(-aggregate(forecast_F[,"Catch or F"],by=F_SS_adjust_year,FUN=sum)$x)
achieved_annual <- 1-exp(-aggregate(achieved.report[,'F'],by=F_SS_adjust_year,FUN=sum)$x)
F_SS_adjust <- rep(achieved_annual/expected_annual,each=length(seasons)*length(F_cols))
F_maxed <- max(achieved.report[,'F'])
}else{
F_SS_adjust <- rep(1,length(forecast_F[,1]))
}
{
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[[paste0("Allocation_run_",allocation_loop)]][["Group_Catch_Benchmark"]]<-list()
projection_results[[paste0("Allocation_run_",allocation_loop)]][["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[[paste0("Allocation_run_",allocation_loop)]][["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[[paste0("Allocation_run_",allocation_loop)]][["Group_Catch_Benchmark"]][[i]]<-Achieved.Catch.group
}
}
projection_results[[paste0("Allocation_run_",allocation_loop)]][["Catch_equil_Benchmark"]] <- Achieved.Catch.equil
projection_results[[paste0("Allocation_run_",allocation_loop)]][["F_equil_Benchmark"]] <- F_OFL
projection_results[[paste0("Allocation_run_",allocation_loop)]][["Depletion_equil_Benchmark"]] <- Achieved.SSBratio.equil
projection_results[[paste0("Allocation_run_",allocation_loop)]][["SSB_equil_Benchmark"]] <- Achieved.SSB.equil
projection_results[[paste0("Allocation_run_",allocation_loop)]][["SPR_equil_Benchmark"]] <- Achieved.SPR.equil
projection_results[[paste0("Allocation_run_",allocation_loop)]][["Recruitment_equil_Benchmark"]] <- Achieved.Rec.equil
projection_results[[paste0("Allocation_run_",allocation_loop)]][["Forecatch_Benchmark"]] <- achieved.report
projection_results[[paste0("Allocation_run_",allocation_loop)]][["Catch_Benchmark"]] <- Achieved.Catch
projection_results[[paste0("Allocation_run_",allocation_loop)]][["F_Benchmark"]] <- Achieved.F
projection_results[[paste0("Allocation_run_",allocation_loop)]][["Depletion_Benchmark"]] <- Achieved.SSBratio
projection_results[[paste0("Allocation_run_",allocation_loop)]][["SSB_Benchmark"]] <- Achieved.SSB
projection_results[[paste0("Allocation_run_",allocation_loop)]][["SPR_Benchmark"]] <- Achieved.SPR
projection_results[[paste0("Allocation_run_",allocation_loop)]][["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_raw))>Allocation.Threshold |
max(abs(1-Fmult2_raw))>Annual.F.Threshold |
max(abs(1-Fmult1_raw))>Depletion.Threshold){
loop<-loop-1