-
Notifications
You must be signed in to change notification settings - Fork 1
/
run_ms_hr.R
715 lines (627 loc) · 29 KB
/
run_ms_hr.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
#args <- c("use_MPI=FALSE", "n_workers=0", "n_blocks=1", "popSize=100", "maxiter=100", "run=10", "stock_id=12", "n_iter=500", "n_yrs=50", "fhist='random'", "catch_rule='hr'", "ga_search=TRUE", "idxB_lag=FALSE", "idxB_range_3=FALSE", "exp_b=FALSE", "comp_b_multiplier=FALSE", "interval=FALSE", "multiplier=FALSE", "upper_constraint=c(seq(1,5,0.01),Inf)", "lower_constraint=FALSE", "obj_SSB=TRUE", "obj_F=FALSE", "obj_C=TRUE", "obj_risk=TRUE", "obj_ICV=TRUE", "obj_ICES_PA=FALSE", "obj_ICES_PA2=FALSE", "obj_ICES_MSYPA=FALSE", "collate=TRUE", "scenario='GA'", "stat_yrs='all'", "add_suggestions=FALSE")
### ------------------------------------------------------------------------ ###
### run MSE ####
### ------------------------------------------------------------------------ ###
### ------------------------------------------------------------------------ ###
### arguments ####
### ------------------------------------------------------------------------ ###
args <- commandArgs(TRUE)
print("arguments passed on to this script:")
print(args)
### evaluate arguments, if they are passed to R:
if (length(args) > 0) {
### extract arguments
for (i in seq_along(args)) eval(parse(text = args[[i]]))
### set default arguments
### parallelization
if (!exists("use_MPI")) use_MPI <- FALSE
if (!exists("n_blocks")) n_blocks <- 1
if (!exists("n_workers")) n_workers <- 0
### split OM into blocks?
if (!exists("n_parts")) n_parts <- 1
if (!exists("part")) part <- 1
### projection details
if (!exists("n_iter")) n_iter <- 500
if (!exists("n_yrs")) n_yrs <- 50
if (!exists("fhist")) fhist <- "random"
### MP parameters
if (!exists("catch_rule")) catch_rule <- "hr"
if (!exists("hr")) hr <- "length"
if (!exists("multiplier")) multiplier <- 1
if (!exists("comp_r")) comp_r <- FALSE
if (!exists("comp_f")) comp_f <- FALSE
if (!exists("comp_b")) comp_b <- TRUE
if (!exists("exp_b")) exp_b <- 1
if (!exists("comp_b_multiplier")) comp_b_multiplier <- 1.4
if (!exists("interval")) interval <- 1
if (!exists("idxB_lag")) idxB_lag <- 1
if (!exists("idxB_range_3")) idxB_range_3 <- 1
if (!exists("upper_constraint")) upper_constraint <- Inf
if (!exists("lower_constraint")) lower_constraint <- 0
if (!exists("cap_below_b")) cap_below_b <- TRUE
if (!exists("stat_yrs")) stat_yrs <- "all"
if (!exists("scenario")) scenario <- "sensitivity"
### observation uncertainty
if (!exists("sigmaL")) sigmaL <- 0.2
if (!exists("sigmaB")) sigmaB <- 0.2
### observation uncertainty auto-correlation
if (!exists("sigmaL_rho")) sigmaL_rho <- 0
if (!exists("sigmaB_rho")) sigmaB_rho <- 0
### recruitment variability
if (!exists("sigmaR")) sigmaR <- 0.6
if (!exists("sigmaR_rho")) sigmaR_rho <- 0.0
### recruitment steepness
if (!exists("steepness")) steepness <- 0.75
### index selectivity
if (!exists("idx_sel")) idx_sel <- "tsb"
### what to save
if (!exists("check_file")) check_file <- TRUE
if (!exists("saveMP")) saveMP <- TRUE
if (!exists("stats")) stats <- TRUE
if (!exists("collate")) collate <- FALSE
### GA search
if (!exists("ga_search")) ga_search <- FALSE
if (isTRUE(ga_search)) {
if (!exists("popSize")) stop("popSize missing")
if (!exists("maxiter")) stop("maxiter missing")
if (!exists("stock_id")) stop("stock_id missing")
if (!exists("run")) run <- maxiter
if (!exists("collate")) collate <- TRUE
### objective function elements
if (!exists("obj_SSB")) obj_SSB <- TRUE
if (!exists("obj_F")) obj_F <- FALSE
if (!exists("obj_C")) obj_C <- TRUE
if (!exists("obj_risk")) obj_risk <- TRUE
if (!exists("obj_ICV")) obj_ICV <- TRUE
if (!exists("obj_ICES_PA")) obj_ICES_PA <- FALSE
if (!exists("obj_ICES_PA2")) obj_ICES_PA2 <- FALSE
if (!exists("obj_ICES_MSYPA")) obj_ICES_MSYPA <- FALSE
if (!exists("risk_threshold")) risk_threshold <- 0.05
### GA
if (!exists("add_suggestions")) add_suggestions <- FALSE
if (!exists("stat_yrs")) stat_yrs <- "all"
}
} else {
stop("no argument passed to R")
}
### ------------------------------------------------------------------------ ###
### set up environment ####
### ------------------------------------------------------------------------ ###
### load packages
### GA fork from GitHub remotes::install_github("shfischer/GA")
### use mse fork from shfischer/mse, branch mseDL2.0
### remotes::install_github("shfischer/mse", ref = "mseDL2.0)
req_pckgs <- c("mse", "tidyr", "dplyr", "doParallel", "GA", "doRNG")
for (i in req_pckgs) library(package = i, character.only = TRUE)
### load additional functions
source("funs.R")
source("funs_GA.R")
### ------------------------------------------------------------------------ ###
### setup parallel environment ####
### ------------------------------------------------------------------------ ###
### hybrid MPI
if (isTRUE(use_MPI)) {
### 1st: doMPI cluster with 1 worker per node
message("starting doMPI")
library(doMPI)
cl1 <- startMPIcluster()
message("startMPIcluster() succeeded")
print(cl1)
registerDoMPI(cl1)
cl_length_1 <- cl1$workerCount
cl_length_1
### 2nd: doParallel workers inside doMPI workers
. <- foreach(i = seq(cl_length_1)) %dopar% {
### load packages and functions into MPI workers
for (i in req_pckgs) library(package = i, character.only = TRUE,
warn.conflicts = FALSE, verbose = FALSE,
quietly = TRUE)
}
message("MPI package loading succeeded")
. <- foreach(i = seq(cl_length_1)) %dopar% {
source("funs.R", echo = FALSE)
source("funs_GA.R", echo = FALSE)
}
message("MPI script loading succeeded")
### start doParallel inside MPI processes
if (isTRUE(n_workers > 1)) {
. <- foreach(i = seq(cl_length_1)) %dopar% {
cl2 <- makeCluster(n_workers)
registerDoParallel(cl2)
cl_length_2 <- length(cl2)
### load packages and functions into parallel workers
. <- foreach(i = seq(cl_length_2)) %dopar% {
for (i in req_pckgs) library(package = i, character.only = TRUE,
warn.conflicts = FALSE, verbose = FALSE,
quietly = TRUE)
source("funs.R", echo = FALSE)
source("funs_GA.R", echo = FALSE)
}
}
}
message("setting up doParallel inside MPI succeeded")
} else {
if (isTRUE(n_workers > 1)) {
### start doParallel cluster
cl1 <- makeCluster(n_workers)
registerDoParallel(cl1)
cl_length_1 <- length(cl1)
### load packages and functions into parallel workers
. <- foreach(i = seq(cl_length_1)) %dopar% {
for (i in req_pckgs) library(package = i, character.only = TRUE,
warn.conflicts = FALSE, verbose = FALSE,
quietly = TRUE)
source("funs.R", echo = FALSE)
source("funs_GA.R", echo = FALSE)
}
} else {
cl1 <- FALSE
}
}
### ------------------------------------------------------------------------ ###
### load input ####
### ------------------------------------------------------------------------ ###
### stock list
stocks <- read.csv("input/stocks.csv", stringsAsFactors = FALSE)
stock <- stocks$stock[stock_id]
names(stock) <- stock
### path to input files
path_in <- paste0("input/", catch_rule, "/", n_iter, "_", n_yrs,
"/OM_2_mp_input/", fhist, "/")
### load stock(s)
input <- lapply(stock, function(x) {
readRDS(paste0(path_in, x, ".rds"))
})
input <- lapply(input, function(x) {
x$args$nblocks <- n_blocks
return(x)
})
### ------------------------------------------------------------------------ ###
### manual runs ####
### ------------------------------------------------------------------------ ###
if (isFALSE(ga_search)) {
### ---------------------------------------------------------------------- ###
### MP parameters ####
### ---------------------------------------------------------------------- ###
### load reference values
hr_ref <- readRDS("input/catch_rates.rds")[[stock]]
lhist <- stocks[stocks$stock == stock, ]
### HR rule parameters & uncertainty
hr_params <- data.frame(multiplier = multiplier,
comp_b = comp_b,
idxB_lag = idxB_lag,
idxB_range_3 = idxB_range_3,
interval = interval,
upper_constraint = upper_constraint,
lower_constraint = lower_constraint,
sigmaL = sigmaL,
sigmaB = sigmaB,
sigmaL_rho = sigmaL_rho,
sigmaB_rho = sigmaB_rho,
sigmaR = sigmaR,
sigmaR_rho = sigmaR_rho,
steepness = steepness,
idx_sel = idx_sel,
stringsAsFactors = FALSE)
### ---------------------------------------------------------------------- ###
### go through runs ####
### ---------------------------------------------------------------------- ###
if (isTRUE(n_workers > 1 & n_blocks == 1)) {
`%do_tmp%` <- `%dopar%`
} else {
`%do_tmp%` <- `%do%`
}
. <- foreach(hr_i = seq(nrow(hr_params))) %do_tmp% {
par_i <- hr_params[hr_i, ]
input_i <- hr_par(input = input[[1]], lhist = lhist,
hr = hr, hr_ref = hr_ref,
multiplier = par_i$multiplier,
comp_b = par_i$comp_b, idxB_lag = par_i$idxB_lag,
idxB_range_3 = par_i$idxB_range_3,
interval = par_i$interval,
upper_constraint = par_i$upper_constraint,
lower_constraint = par_i$lower_constraint,
cap_below_b = cap_below_b,
idx_sel = par_i$idx_sel)
## --------------------------------------------------------------------- ###
## observation uncertainty ####
## --------------------------------------------------------------------- ###
### change uncertainty?
sigmaB_i <- par_i$sigmaB
sigmaL_i <- par_i$sigmaL
sigmaB_rho_i <- par_i$sigmaB_rho
sigmaL_rho_i <- par_i$sigmaL_rho
if (par_i$sigmaB != 0.2 | par_i$sigmaL != 0.2 |
par_i$sigmaB_rho != 0 | par_i$sigmaL_rho != 0) {
#browser()
### create observation noise
set.seed(695)
dev_idxB <- input_i$oem@deviances$idx$idxB
dev_idxL <- input_i$oem@deviances$idx$idxL
dev_idxB[] <- rlnoise(n = dims(dev_idxB)$iter, dev_idxB %=% 0,
sd = sigmaB_i, b = sigmaB_rho_i)
dev_idxL[] <- rlnoise(n = dims(dev_idxL)$iter, dev_idxL %=% 0,
sd = sigmaL_i, b = sigmaL_rho_i)
set.seed(696)
dev_idxB[, ac(50:150)] <- rlnoise(n = dims(dev_idxB)$iter,
window(dev_idxB, end = 150) %=% 0,
sd = sigmaB_i, b = sigmaB_rho_i)
dev_idxL[, ac(50:150)] <- rlnoise(n = dims(dev_idxB)$iter,
window(dev_idxB, end = 150) %=% 0,
sd = sigmaL_i, b = sigmaL_rho_i)
### insert
input_i$oem@deviances$idx$idxB <- dev_idxB
input_i$oem@deviances$idx$idxL <- dev_idxL
### update I_trigger
I_loss_dev <- apply((input_i$oem@observations$idx$idxB *
dev_idxB)[, ac(50:100)], 6, min)
I_trigger_dev <- I_loss_dev * 1.4
input_i$ctrl$est@args$I_trigger <- c(I_trigger_dev)
input_i$I_loss$idx_dev <- I_loss_dev
}
## --------------------------------------------------------------------- ###
## recruitment variability ####
## --------------------------------------------------------------------- ###
### change variability?
sigmaR_i <- par_i$sigmaR
sigmaR_rho_i <- par_i$sigmaR_rho
if (sigmaR_i != 0.6 | sigmaR_rho_i != 0) {
#browser()
### retrieve original residuals
dev_R_original <- input_i$om@sr@residuals
### create recruitment residuals for projection period
set.seed(1)
dev_R_new <- rlnoise(dims(dev_R_original)$iter, dev_R_original %=% 0,
sd = sigmaR_i, b = sigmaR_rho_i)
### replicate residuals from GA paper
qnt_150 <- FLQuant(NA,
dimnames = list(age = "all", year = 0:150,
iter = dimnames(dev_R_original)$iter))
qnt_100 <- FLQuant(NA,
dimnames = list(age = "all", year = 1:100,
iter = dimnames(dev_R_original)$iter))
set.seed(0)
res_150 <- rlnoise(dims(dev_R_original)$iter,
qnt_150 %=% 0,
sd = sigmaR_i, b = sigmaR_rho_i)
set.seed(0)
res_100 <- rlnoise(dims(dev_R_original)$iter,
qnt_100 %=% 0,
sd = sigmaR_i, b = sigmaR_rho_i)
### insert into template
yrs_150 <- seq(from = dims(dev_R_original)$minyear,
to = ifelse(dims(dev_R_original)$maxyear >= 150,
150, dims(dev_R_original)$maxyear))
dev_R_new[, ac(yrs_150)] <- res_150[, ac(yrs_150)]
yrs_100 <- seq(from = dims(dev_R_original)$minyear,
to = 100)
dev_R_new[, ac(yrs_100)] <- res_100[, ac(yrs_100)]
### insert
input_i$om@sr@residuals[] <- dev_R_new
}
### -------------------------------------------------------------------- ###
### recruitment steepness ####
### -------------------------------------------------------------------- ###
steepness_i <- par_i$steepness
if (steepness_i != 0.75) {
### load brp
brps <- readRDS("input/brps.rds")
brp <- brps[[stock]]
### calculate new recruitment model parameters with new steepness
alpha <- (4*steepness_i*c(refpts(brp)["virgin", "rec"])) /
(5*steepness_i - 1)
beta <- (c(refpts(brp)["virgin", "ssb"]) * (1 - steepness_i)) /
(5*steepness_i - 1)
### insert values
params(input_i$om@sr)[] <- c(alpha, beta)
}
### -------------------------------------------------------------------- ###
### update target harvest rate ####
### -------------------------------------------------------------------- ###
### run again in case residuals were changed
input_i <- hr_par(input = input_i, lhist = lhist,
hr = hr, hr_ref = hr_ref,
multiplier = par_i$multiplier,
comp_b = par_i$comp_b, idxB_lag = par_i$idxB_lag,
idxB_range_3 = par_i$idxB_range_3,
interval = par_i$interval,
upper_constraint = par_i$upper_constraint,
lower_constraint = par_i$lower_constraint,
cap_below_b = cap_below_b,
idx_sel = par_i$idx_sel)
### -------------------------------------------------------------------- ###
### paths ####
### -------------------------------------------------------------------- ###
### generate file name
file_pars <- c(hr, par_i$multiplier, par_i$comp_b, par_i$idxB_lag,
par_i$idxB_range_3, par_i$interval,
par_i$upper_constraint, par_i$lower_constraint,
par_i$sigmaL, par_i$sigmaB,
par_i$sigmaL_rho, par_i$sigmaB_rho,
par_i$sigmaR, par_i$sigmaR_rho, par_i$steepness,
ifelse(identical(par_i$idx_sel, "tsb"), NA, par_i$idx_sel))
file_pars <- file_pars[!is.na(file_pars)]
file_out <- paste0(file_pars, collapse = "_")
path_out <- paste0("output/hr/", n_iter, "_", n_yrs, "/", scenario, "/",
fhist, "/", paste0(stock, collapse = "_"), "/")
dir.create(path_out, recursive = TRUE)
### skip if run already exists
if (file.exists(paste0(path_out, "stats_", file_out, ".rds"))) return(NULL)
### -------------------------------------------------------------------- ###
### run ####
### -------------------------------------------------------------------- ###
res <- do.call(mp, input_i)
### -------------------------------------------------------------------- ###
### save ####
### -------------------------------------------------------------------- ###
if (isTRUE(saveMP))
saveRDS(object = res, file = paste0(path_out, "mp_", file_out, ".rds"))
### -------------------------------------------------------------------- ###
### stats ####
### -------------------------------------------------------------------- ###
if (isTRUE(stats)) {
res_stats <- mp_stats(input = list(input_i), res_mp = list(res),
collapse_correction = TRUE,
stat_yrs = stat_yrs)
res_stats <- cbind(stock = stock, par_i, t(res_stats))
saveRDS(object = res_stats,
file = paste0(path_out, "stats_", file_out, ".rds"))
}
}
### ---------------------------------------------------------------------- ###
### collate stats ####
### ---------------------------------------------------------------------- ###
if (isTRUE(stats) & isTRUE(collate) & isTRUE(nrow(hr_params) > 1)) {
files <- paste0("stats_", hr, "_",
sapply(seq(nrow(hr_params)),
function(x) paste0(hr_params[x,], collapse = "_")),
".rds")
files <- paste0("output/hr/", n_iter, "_", n_yrs, "/", scenario, "/",
fhist, "/", paste0(stock, collapse = "_"), "/",
files)
stats_all <- lapply(files, readRDS)
stats_all <- do.call(rbind, stats_all)
saveRDS(stats_all, file = paste0(
"output/hr/", n_iter, "_", n_yrs, "/", scenario, "/", fhist, "/",
paste0(stock, collapse = "_"), "/",
"collated_stats_", hr, "_",
paste0(apply(hr_params, 2, function(x) {
ifelse(isTRUE(length(unique(x)) > 1), paste0(range(x), collapse = "-"),
x[1])
}), collapse = "_"), ".rds"))
}
### ------------------------------------------------------------------------ ###
### GA search ####
### ------------------------------------------------------------------------ ###
} else {
### ---------------------------------------------------------------------- ###
### prepare OM ####
### ---------------------------------------------------------------------- ###
hr_refs <- readRDS("input/catch_rates.rds")[stock]
lhist <- split(stocks[stocks$stock == stock, ], seq_along(stock))
### HR rule parameters & uncertainty
hr_params <- data.frame(multiplier = multiplier,
comp_b = comp_b,
exp_b = exp_b,
comp_b_multiplier = comp_b_multiplier,
idxB_lag = idxB_lag,
idxB_range_3 = idxB_range_3,
interval = interval,
upper_constraint = upper_constraint,
lower_constraint = lower_constraint,
sigmaL = sigmaL,
sigmaB = sigmaB,
sigmaL_rho = sigmaL_rho,
sigmaB_rho = sigmaB_rho,
sigmaR = sigmaR,
sigmaR_rho = sigmaR_rho)
par_i <- hr_params[1, ]
input <- lapply(seq_along(input), function(x) {
hr_par(input = input[[x]], lhist = lhist[[x]],
hr = hr, hr_ref = hr_ref,
multiplier = par_i$multiplier,
comp_b = par_i$comp_b, idxB_lag = par_i$idxB_lag,
idxB_range_3 = par_i$idxB_range_3,
interval = par_i$interval,
upper_constraint = par_i$upper_constraint,
lower_constraint = par_i$lower_constraint,
cap_below_b = cap_below_b)
})
names(input) <- stock
### ------------------------------------------------------------------------ ###
### GA set-up ####
### ------------------------------------------------------------------------ ###
### GA arguments
ga_names <- c("idxB_lag", "idxB_range_3", "exp_b", "comp_b_multiplier",
"interval", "multiplier",
"upper_constraint", "lower_constraint")
ga_default <- c(1, 1, 1, 1.4, 1, 1, Inf, 0)
ga_lower <- c(0, 1, 0, 0, 1, 0, 1, 0)
ga_upper <- c(1, 5, 2, 2, 5, 2, 5, 1)
ga_suggestions <- rbind(#c(1, 1, 1, 1.4, 1, 1, Inf, 0), ### default
#c(0, 1, 1, 1.4, 1, 1, Inf, 0), ### more recent data
c(1, 1, 1, 1.4, 1, 0, Inf, 0), ### zero catch
#c(1, 1, 1, 1.4, 2, 1, Inf, 0), ### biennial
#c(0, 1, 1, 1.4, 2, 1, Inf, 0), ### biennial & more recent
#c(1, 1, 1, 0, 1, 1, Inf, 0), ### without b
#c(1, 1, 1, 1.4, 1, 1, 1.2, 0.8), ### +-20% cap
#c(1, 1, 1, 1.4, 1, 1, 1.2, 0.7), ### +20% -30% cap
expand.grid(0:1, 1, 1, c(0, 1, 1.4), 1:2, 1,
c(1.2, Inf), c(0, 0.8))
)
### turn of parameters not requested, i.e. limit to default value
pos_default <- which(sapply(mget(ga_names, ifnotfound = FALSE), isFALSE))
ga_lower[pos_default] <- ga_default[pos_default]
ga_upper[pos_default] <- ga_default[pos_default]
### fix parameters?
pos_fixed <- which(sapply(mget(ga_names, ifnotfound = FALSE), is.numeric))
par_fixed <- names(pos_fixed)
val_fixed <- as.vector(unlist(mget(ga_names, ifnotfound = FALSE)[pos_fixed]))
ga_lower[pos_fixed] <- val_fixed
ga_upper[pos_fixed] <- val_fixed
### remove not requested parameters from suggestions
ga_suggestions[, pos_default] <- rep(ga_default[pos_default],
each = nrow(ga_suggestions))
ga_suggestions[, pos_fixed] <- rep(val_fixed,
each = nrow(ga_suggestions))
ga_suggestions <- unique(ga_suggestions)
names(ga_suggestions) <- ga_names
### multiplier only: run all possible values
if (isTRUE(multiplier) &
!any(sapply(mget(setdiff(ga_names, "multiplier"), ifnotfound = FALSE),
isTRUE))) {
m_vals <- seq(from = ga_lower[6], to = ga_upper[6], by = 0.01)
ga_suggestions[1, ] <- ga_lower
ga_suggestions <- ga_suggestions[rep(1, length(m_vals)), ]
ga_suggestions$multiplier <- m_vals
### adapt GA dimensions
maxiter <- run <- 1
popSize <- length(m_vals)
run_all <- TRUE
} else {
run_all <- FALSE
}
### ---------------------------------------------------------------------- ###
### paths ####
### ---------------------------------------------------------------------- ###
### output path
### set name depending on which GA parameters are used
scn_pars <- ga_names[setdiff(seq_along(ga_names), pos_default)]
### add fixed parameters
scn_pars[which(scn_pars %in% par_fixed)] <- paste0(
scn_pars[which(scn_pars %in% par_fixed)], val_fixed)
scn_pars_c <- paste0(scn_pars, collapse = "-")
#scenario <- "trial"
path_out <- paste0("output/", catch_rule, "/", n_iter, "_", n_yrs, "/",
scenario, "/", fhist, "/",
paste0(stock, collapse = "_"), "/")
dir.create(path_out, recursive = TRUE)
### objective function elements
obj_fun <- c("SSB", "F", "C", "risk", "ICV", "ICES_PA", "ICES_PA2",
"ICES_MSYPA")
obj_fun_use <- mget(x = paste0("obj_", obj_fun),
ifnotfound = FALSE)
for (i in seq_along(obj_fun)) {
assign(x = paste0("obj_", obj_fun[i]), obj_fun_use[[i]])
}
obj_desc <- obj_fun[unlist(obj_fun_use)]
obj_desc <- paste0("obj_", paste0(obj_desc, collapse = "_"), collapse = "")
### store input data in temp file
inp_file <- tempfile()
saveRDS(object = input, file = inp_file, compress = FALSE)
rm(input)
gc()
### ------------------------------------------------------------------------ ###
### check if previous solutions can be used as suggestions ####
### ------------------------------------------------------------------------ ###
### years for summary statistics
file_ext <- ifelse(stat_yrs == "all", "_res",
paste0("_res_", stat_yrs))
### suffix if different risk limit used
file_ext <- ifelse(isTRUE(!identical(risk_threshold, 0.05) &
isTRUE(obj_ICES_MSYPA)),
paste0(file_ext, "_", risk_threshold),
file_ext)
file_ext <- paste0(file_ext, ".rds")
if (isTRUE(add_suggestions)) {
### find files
avail <- list.files(path_out, pattern = paste0("--", obj_desc, file_ext))
avail <- gsub(x = avail, pattern = paste0("--", obj_desc, file_ext),
replacement = "")
avail <- strsplit(x = avail, split = "-")
### need to have fewer parameters
avail <- avail[which(sapply(avail, length) < length(scn_pars))]
### if some parameters fixed, remove suggestions without them
if (isTRUE(length(avail) > 0)) {
avail <- avail[which(sapply(avail, function(x)
all(paste0(par_fixed, val_fixed) %in% x)))]
### skip parameters not used
if (isTRUE(length(avail) > 0)) {
avail <- avail[which(sapply(avail, function(x) all(x %in% scn_pars)))]
if (isTRUE(length(avail) > 0)) {
### load results
res_add <- lapply(avail, function(x) {
tmp <- readRDS(file =
paste0(path_out, paste0(x, collapse = "-"), "--", obj_desc,
"_res",
ifelse(identical(stat_yrs, "all"), "",
paste0("_", stat_yrs)),
".rds"))
tmp <- tmp@solution[1, ]
if (is.na(tmp[which("upper_constraint" == names(tmp))])) {
tmp[which("upper_constraint" == names(tmp))] <- Inf
}
return(tmp)
})
res_add <- do.call(rbind, res_add)
if (isTRUE(nrow(res_add) > 1)) {
res_add <- data.frame(res_add, stringsAsFactors = FALSE)
} else {
res_add <- data.frame(res_add, stringsAsFactors = FALSE)
}
cat("adding GA suggestions:\n")
print(res_add)
### add to GA suggestions
ga_suggestions <- rbind(ga_suggestions, res_add)
ga_suggestions <- unique(ga_suggestions)
}
}
}
}
### ---------------------------------------------------------------------- ###
### run MSE with GA ####
### ---------------------------------------------------------------------- ###
### set random seed for reproducibility
registerDoRNG(123)
set.seed(1)
### run GA
system.time({
res <- ga(type = "real-valued", fitness = mp_fitness, inp_file = inp_file,
obj_SSB = obj_SSB, obj_F = obj_F, obj_C = obj_C,
obj_risk = obj_risk, obj_ICV = obj_ICV, obj_ICES_PA = obj_ICES_PA,
obj_ICES_PA2 = obj_ICES_PA2, obj_ICES_MSYPA = obj_ICES_MSYPA,
stat_yrs = stat_yrs, risk_threshold = risk_threshold,
path = path_out, check_file = check_file,
catch_rule = catch_rule,
suggestions = ga_suggestions, lower = ga_lower, upper = ga_upper,
names = ga_names,
maxiter = maxiter, popSize = popSize, run = run,
monitor = TRUE, keepBest = TRUE, parallel = cl1, seed = 1)
})
### save result
saveRDS(object = res, file = paste0(path_out, scn_pars_c,
"--", obj_desc, file_ext))
### ---------------------------------------------------------------------- ###
### collate runs ####
### ---------------------------------------------------------------------- ###
if (isTRUE(collate)) {
files <- list.files(path = path_out, pattern = "[0-9]*[0-9].rds",
full.names = FALSE)
files <- files[grep(x = files, pattern = "--", invert = TRUE)]
names(files) <- sapply(files, function(x) {
sub(x = x, pattern = ".rds", replacement = "", fixed = TRUE)
})
scns <- lapply(files, function(x) {
pars <- an(strsplit(sub(x = x, pattern = ".rds", replacement = "", fixed = TRUE),
split = "_")[[1]])
names(pars) <- ga_names
### only keep scenarios where requested parameters are changed
if (!all(ga_default[pos_default] == pars[pos_default])) return(NULL)
if (!isTRUE(run_all)) {
if (!all(val_fixed == pars[pos_fixed])) return(NULL)
}
stats <- readRDS(paste0(path_out, x))
list(pars = pars, stats = stats)
})
scns[sapply(scns, is.null)] <- NULL
#scns <- scns[order(sapply(scns, "[[", "obj"), decreasing = TRUE)]
saveRDS(scns,
file = paste0(path_out, scn_pars_c, "--", obj_desc, "_runs",
ifelse(identical(stat_yrs, "last10"), "_last10", ""),
".rds"))
}
}
### ------------------------------------------------------------------------ ###
### quit ####
### ------------------------------------------------------------------------ ###
quit(save = "no")