-
Notifications
You must be signed in to change notification settings - Fork 0
/
funs.R
744 lines (603 loc) · 22.6 KB
/
funs.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
### ------------------------------------------------------------------------ ###
### observations ####
### ------------------------------------------------------------------------ ###
obs_generic <- function(stk, observations, deviances, args, tracking,
ssb_idx = FALSE, tsb_idx = FALSE, ### use SSB idx
idx_dev = FALSE,
lngth = FALSE, ### catch length data?
lngth_dev = FALSE,
lngth_par,
PA_status = FALSE,
PA_status_dev = FALSE,
PA_Bmsy = FALSE, PA_Fmsy = FALSE,
...) {
#ay <- args$ay
### update observations
observations$stk <- stk
### use SSB as index?
if (isTRUE(ssb_idx)) {
observations$idx$idxB <- ssb(observations$stk)
### TSB?
} else if (isTRUE(tsb_idx)) {
observations$idx$idxB <- tsb(observations$stk)
### otherwise calculate biomass index
} else {
observations$idx$idxB <- quantSums([email protected] * [email protected] *
observations$idx$sel)
}
### use mean length in catch?
if (isTRUE(lngth)) {
observations$idx$idxL <- lmean(stk = stk, params = lngth_par)
}
### stock status for PA buffer?
if (isTRUE(PA_status)) {
observations$idx$PA_status[] <- ssb(observations$stk) > 0.5*PA_Bmsy &
fbar(observations$stk) < PA_Fmsy
}
### observation model
stk0 <- observations$stk
idx0 <- observations$idx
### add deviances to index?
if (isTRUE(idx_dev)) {
if (isTRUE(ssb_idx) | isTRUE(tsb_idx)) {
idx0$idxB <- observations$idx$idxB * deviances$idx$idxB
} else {
idx0$idxB <- quantSums([email protected] * [email protected] *
observations$idx$sel * deviances$idx$sel)
if (isTRUE("idxB" %in% names(deviances$idx)) &
all.equal(dim(deviances$idx$idxB), dim(idx0$idxB)))
idx0$idxB <- idx0$idxB * deviances$idx$idxB
}
}
### uncertainty for catch length
if (isTRUE(lngth) & isTRUE(lngth_dev)) {
idx0$idxL <- observations$idx$idxL * deviances$idx$idxL
}
### uncertainty for stock status for PA buffer
if (isTRUE(PA_status) & isTRUE(PA_status_dev)) {
idx0$PA_status <- ifelse(observations$idx$PA_status == TRUE,
deviances$idx$PA_status["positive", ],
deviances$idx$PA_status["negative", ])
}
return(list(stk = stk0, idx = idx0, observations = observations,
tracking = tracking))
}
### ------------------------------------------------------------------------ ###
### estimator ####
### ------------------------------------------------------------------------ ###
est_comps <- function(stk, idx, tracking, args,
comp_r = FALSE, comp_f = FALSE, comp_b = FALSE,
comp_i = FALSE, comp_c = TRUE, comp_m = FALSE,
idxB_lag = 1, idxB_range_1 = 2, idxB_range_2 = 3,
idxB_range_3 = 1,
catch_lag = 1, catch_range = 1,
Lref, I_trigger,
idxL_lag = 1, idxL_range = 1,
pa_buffer = FALSE, pa_size = 0.8, pa_duration = 3,
Bmsy = NA,
...) {
ay <- args$ay
### component r: index trend
if (isTRUE(comp_r)) {
r_res <- est_r(idx = idx$idxB, ay = ay,
idxB_lag = idxB_lag, idxB_range_1 = idxB_range_1,
idxB_range_2 = idxB_range_2)
} else {
r_res <- 1
}
tracking["comp_r", ac(ay)] <- r_res
### component f: length data
if (isTRUE(comp_f)) {
f_res <- est_f(idx = idx$idxL, ay = ay,
Lref = Lref, idxL_range = idxL_range, idxL_lag = idxL_lag)
} else {
f_res <- 1
}
tracking["comp_f", ac(ay)] <- f_res
### component b: biomass safeguard
if (isTRUE(comp_b)) {
b_res <- est_b(idx = idx$idxB, ay = ay,
I_trigger = I_trigger, idxB_lag = idxB_lag,
idxB_range_3 = idxB_range_3)
} else {
b_res <- 1
}
### PA buffer
if (isTRUE(pa_buffer)) {
b_res <- est_pa(idx = idx$PA_status, ay = ay,
tracking = tracking, idxB_lag = idxB_lag,
pa_size = pa_size, pa_duration = pa_duration)
}
tracking["comp_b", ac(ay)] <- b_res
### component i: index value
if (isTRUE(comp_i)) {
i_res <- est_i(idx = idx$idxB, ay = ay,
idxB_lag = idxB_lag, idxB_range_3 = idxB_range_3)
} else {
i_res <- 1
}
tracking["comp_i", ac(ay)] <- i_res
### current catch
if (isTRUE(comp_c)) {
c_res <- est_c(ay = ay, catch = catch(stk), catch_lag = catch_lag,
catch_range = catch_range)
} else {
c_res <- 1
}
tracking["comp_c", ac(ay)] <- c_res
### component m: multiplier
if (!isFALSE(comp_m)) {
m_res <- comp_m
### subset to iteration when simultion is split into blocks
if (isTRUE(length(comp_m) > dims(stk)$iter)) {
m_res <- comp_m[as.numeric(dimnames(stk)$iter)]
}
} else {
m_res <- 1
}
tracking["multiplier", ac(ay)] <- m_res
return(list(stk = stk, tracking = tracking))
}
### biomass index trend
est_r <- function(idx, ay,
idxB_lag, idxB_range_1, idxB_range_2,
...) {
### index ratio
yrs_a <- seq(to = c(ay - idxB_lag), length.out = idxB_range_1)
yrs_b <- seq(to = min(yrs_a) - 1, length.out = idxB_range_2)
idx_a <- yearMeans(idx[, ac(yrs_a)])
idx_b <- yearMeans(idx[, ac(yrs_b)])
idx_ratio <- c(idx_a / idx_b)
return(idx_ratio)
}
### length data
est_f <- function(idx, ay,
Lref, idxL_range, idxL_lag,
...) {
### if fewer iterations provided expand
if (isTRUE(length(Lref) < dims(idx)$iter)) {
Lref <- rep(Lref, dims(idx)$iter)
### if more iterations provided, subset
} else if (isTRUE(length(Lref) > dims(idx)$iter)) {
Lref <- Lref[an(dimnames(idx)$iter)]
}
### get mean length in catch
idx_yrs <- seq(to = ay - idxL_range, length.out = idxL_lag)
idx_mean <- yearMeans(idx[, ac(idx_yrs)])
### length relative to reference
idx_ratio <- c(idx_mean / Lref)
### avoid negative values
idx_ratio <- ifelse(idx_ratio > 0, idx_ratio, 0)
### avoid NAs, happens if catch = 0
idx_ratio <- ifelse(is.na(idx_ratio), 1, idx_ratio)
return(idx_ratio)
}
### biomass index trend
est_b <- function(idx, ay,
I_trigger, idxB_lag, idxB_range_3,
...) {
### if fewer iterations provided expand
if (isTRUE(length(I_trigger) < dims(idx)$iter)) {
I_trigger <- rep(I_trigger, dims(idx)$iter)
### if more iterations provided, subset
} else if (isTRUE(length(I_trigger) > dims(idx)$iter)) {
I_trigger <- I_trigger[an(dimnames(idx)$iter)]
}
### calculate index mean
idx_yrs <- seq(to = ay - idxB_lag, length.out = idxB_range_3)
idx_mean <- yearMeans(idx[, ac(idx_yrs)])
### ratio
idx_ratio <- c(idx_mean / I_trigger)
### b is 1 or smaller
idx_ratio <- ifelse(idx_ratio < 1, idx_ratio, 1)
return(idx_ratio)
}
### biomass index trend
est_pa <- function(idx, ay, tracking, pa_size, pa_duration, idxB_lag,
...) {
### find last year in which buffer was applied
last <- apply(tracking["comp_b",,, drop = FALSE], 6, FUN = function(x) {#browser()
### positions (years) where buffer was applied
yr <- dimnames(x)$year[which(x < 1)]
### return -Inf if buffer was never applied
ifelse(length(yr) > 0, as.numeric(yr), -Inf)
})
### find iterations to check
pos_check <- which(last <= (ay - pa_duration))
### find negative stock status (SSB<0.5Bmsy or F>Fmsy)
pos_negative <- which(idx[, ac(ay - idxB_lag)] == 0)
### apply only if buffer applications need to be checked and status is negative
pos_apply <- intersect(pos_check, pos_negative)
return(ifelse(seq(dims(last)$iter) %in% pos_apply, pa_size, 1))
}
### index value
est_i <- function(idx, ay,
idxB_lag, idxB_range_3,
...) {
### index ratio
yrs_r <- seq(to = c(ay - idxB_lag), length.out = idxB_range_3)
idx_i <- yearMeans(idx[, ac(yrs_r)])
return(idx_i)
}
### recent catch
est_c <- function(catch, ay,
catch_lag, catch_range,
...) {
catch_yrs <- seq(to = ay - catch_lag, length.out = catch_range)
catch_current <- yearMeans(catch[, ac(catch_yrs)])
return(catch_current)
}
### harvest rate index
est_hr <- function(stk, idx, tracking, args,
idxB_lag = 1, idxB_range = 1,
...) {
ay <- args$ay
### current index value
idx_yrs <- seq(to = ay - idxB_lag,
length.out = idxB_range)
idx_current <- yearMeans(idx$idxB[, ac(idx_yrs)])
tracking["I_current", ac(ay)] <- idx_current
return(list(stk = stk, tracking = tracking))
}
### ------------------------------------------------------------------------ ###
### phcr ####
### ------------------------------------------------------------------------ ###
### parametrization of HCR
phcr_comps <- function(tracking, args,
exp_r = 1, exp_f = 1, exp_b = 1,
...){
ay <- args$ay
hcrpars <- tracking[c("comp_r", "comp_f", "comp_b", "comp_i",
"comp_c", "multiplier",
"exp_r", "exp_f", "exp_b"), ac(ay)]
hcrpars["exp_r", ] <- exp_r
hcrpars["exp_f", ] <- exp_f
hcrpars["exp_b", ] <- exp_b
if (exp_r != 1) tracking["exp_r", ] <- exp_r
if (exp_f != 1) tracking["exp_f", ] <- exp_f
if (exp_b != 1) tracking["exp_b", ] <- exp_b
### return results
return(list(tracking = tracking, hcrpars = hcrpars))
}
### harvest rate: select
phcr_hr <- function(tracking, args, rate = 0.5,
...){
ay <- args$ay
hcrpars <- tracking[c("I_current", "multiplier"), ac(ay)]
hcrpars["multiplier", ] <- rate
### return results
return(list(tracking = tracking, hcrpars = hcrpars))
}
### ------------------------------------------------------------------------ ###
### hcr ####
### ------------------------------------------------------------------------ ###
### apply catch rule
hcr_comps <- function(hcrpars, args, tracking, interval = 2,
...) {
ay <- args$ay ### current year
iy <- args$iy ### first simulation year
### check if new advice requested
if ((ay - iy) %% interval == 0) {
### calculate advice
advice <- hcrpars["comp_c", ] *
(hcrpars["comp_r", ]^hcrpars["exp_r", ]) *
(hcrpars["comp_f", ]^hcrpars["exp_f", ]) *
(hcrpars["comp_b", ]^hcrpars["exp_b", ]) *
hcrpars["comp_i"] *
hcrpars["multiplier", ]
#advice <- apply(X = hcrpars, MARGIN = 6, prod, na.rm = TRUE)
} else {
### use last year's advice
advice <- tracking["metric.hcr", ac(ay - 1)]
}
ctrl <- getCtrl(values = c(advice), quantity = "catch", years = ay + 1,
it = dim(advice)[6])
return(list(ctrl = ctrl, tracking = tracking))
}
### harvest rate
hcr_hr <- function(hcrpars, args, tracking, interval = 1,
...) {
ay <- args$ay
iy <- args$iy
if ((ay - iy) %% interval == 0) {
advice <- hcrpars["I_current", ] * hcrpars["multiplier", ]
} else {
advice <- tracking["metric.hcr", ac(ay - 1)]
}
ctrl <- getCtrl(values = c(advice), quantity = "catch", years = ay + 1,
it = dim(advice)[6])
return(list(ctrl = ctrl, tracking = tracking))
}
### ------------------------------------------------------------------------ ###
### implementation ####
### ------------------------------------------------------------------------ ###
### no need to convert, already catch in tonnes
### apply TAC constraint, if required
is_comps <- function(ctrl, args, tracking, interval = 2,
upper_constraint = Inf, lower_constraint = 0,
cap_below_b = TRUE, ...) {
ay <- args$ay ### current year
iy <- args$iy ### first simulation year
advice <- ctrl@trgtArray[ac(ay + args$management_lag), "val", ]
### check if new advice requested
if ((ay - iy) %% interval == 0) {
### apply TAC constraint, if requested
if (!is.infinite(upper_constraint) | lower_constraint != 0) {
### get last advice
if (isTRUE(ay == iy)) {
### use OM value in first year of projection
adv_last <- tracking["C.om", ac(iy)]
} else {
adv_last <- tracking["metric.is", ac(ay - 1)]
}
### ratio of new advice/last advice
adv_ratio <- advice/adv_last
### upper constraint
if (!is.infinite(upper_constraint)) {
### find positions
pos_upper <- which(adv_ratio > upper_constraint)
### turn of constraint when index below Itrigger?
if (isFALSE(cap_below_b)) {
pos_upper <- setdiff(pos_upper,
which(c(tracking[, ac(ay)]["comp_b", ]) < 1))
}
### limit advice
if (length(pos_upper) > 0) {
advice[pos_upper] <- adv_last[,,,,, pos_upper] * upper_constraint
}
### lower constraint
}
if (lower_constraint != 0) {
### find positions
pos_lower <- which(adv_ratio < lower_constraint)
### turn of constraint when index below Itrigger?
if (isFALSE(cap_below_b)) {
pos_lower <- setdiff(pos_lower,
which(c(tracking[, ac(ay)]["comp_b", ]) < 1))
}
### limit advice
if (length(pos_lower) > 0) {
advice[pos_lower] <- adv_last[,,,,, pos_lower] * lower_constraint
}
}
}
### otherwise do nothing here and recycle last year's advice
} else {
advice <- tracking["metric.is", ac(ay - 1)]
}
ctrl@trgtArray[ac(ay + args$management_lag),"val",] <- advice
return(list(ctrl = ctrl, tracking = tracking))
}
### ------------------------------------------------------------------------ ###
### implementation error ####
### ------------------------------------------------------------------------ ###
iem_comps <- function(ctrl, args, tracking,
iem_dev = FALSE, use_dev, ...) {
ay <- args$ay
### only do something if requested
if (isTRUE(use_dev)) {
### get advice
advice <- ctrl@trgtArray[ac(ay + args$management_lag), "val", ]
### get deviation
dev <- c(iem_dev[, ac(ay)])
### implement deviation
advice <- advice * dev
### insert into ctrl object
ctrl@trgtArray[ac(ay + args$management_lag),"val",] <- advice
}
return(list(ctrl = ctrl, tracking = tracking))
}
### ------------------------------------------------------------------------ ###
### projection ####
### ------------------------------------------------------------------------ ###
fwd_attr <- function(stk, ctrl,
sr, ### stock recruitment model
sr.residuals, ### recruitment residuals
sr.residuals.mult = TRUE, ### are res multiplicative?
maxF = 5, ### maximum allowed Fbar
dupl_trgt = FALSE,
...) {
### avoid the issue that the catch is higher than the targeted catch
### can happen due to bug in FLash if >1 iteration provided
### sometimes, FLash struggles to get estimates and then uses F estimate from
### previous iteration
### workaround: target same value several times and force FLash to try again
if (isTRUE(dupl_trgt)) {
### duplicate target
ctrl@target <- rbind(ctrl@target, ctrl@target, ctrl@target)
### replace catch in second row with landings
ctrl@target$quantity[1] <- "landings"
ctrl@target$quantity[3] <- "catch"
### extract target values
val_temp <- ctrl@trgtArray[, "val", ]
### extend trgtArray
### extract dim and dimnames
dim_temp <- dim(ctrl@trgtArray)
dimnames_temp <- dimnames(ctrl@trgtArray)
### duplicate years
dim_temp[["year"]] <- dim_temp[["year"]] * 3
dimnames_temp$year <- rep(dimnames_temp$year, 3)
### create new empty array
trgtArray <- array(data = NA, dim = dim_temp, dimnames = dimnames_temp)
### fill with values
### first as target
trgtArray[1, "val", ] <- val_temp
### then again, but as max
trgtArray[2, "max", ] <- val_temp
### min F
trgtArray[3, "max", ] <- val_temp
### insert into ctrl object
ctrl@trgtArray <- trgtArray
}
### project forward with FLash::fwd
stk[] <- fwd(object = stk, control = ctrl, sr = sr,
sr.residuals = sr.residuals,
sr.residuals.mult = sr.residuals.mult,
maxF = maxF)
### return stock
return(list(object = stk))
}
### ------------------------------------------------------------------------ ###
### iter subset ####
### ------------------------------------------------------------------------ ###
iter_attr <- function(object, iters, subset_attributes = TRUE) {
### subset object to iter
res <- FLCore::iter(object, iters)
if (isTRUE(subset_attributes)) {
### get default attributes of object class
attr_def <- names(attributes(new(Class = class(object))))
### get additional attributes
attr_new <- setdiff(names(attributes(object)), attr_def)
### subset attributes
for (attr_i in attr_new) {
attr(res, attr_i) <- FLCore::iter(attr(res, attr_i), iters)
}
}
return(res)
}
### ------------------------------------------------------------------------ ###
### estimtate steepness based on l50/linf ratio ####
### according to Wiff et al. 2018
### ------------------------------------------------------------------------ ###
h_Wiff <- function(l50, linf) {
l50linf <- l50/linf
### linear model
lin <- 2.706 - 3.698*l50linf
### logit
h <- (0.2 + exp(lin)) / (1 + exp(lin))
return(h)
}
### ------------------------------------------------------------------------ ###
### mean length in catch ####
### ------------------------------------------------------------------------ ###
lmean <- function(stk, params) {
### calculate length from age with a & b
weights <- c(catch.wt(stk)[, 1,,,, 1])
lengths <- (weights / c(params["a"]))^(1 / c(params["b"]))
catch.n <- catch.n(stk)
dimnames(catch.n)$age <- lengths
### subset to lengths > Lc
catch.n <- catch.n[lengths > c(params["Lc"]),]
### calculate mean length
lmean <- apply(X = catch.n, MARGIN = c(2, 6), FUN = function(x) {
### calculate
res <- weighted.mean(x = an(dimnames(x)$age),
w = ifelse(is.na(x), 0, x), na.rm = TRUE)
### check if result obtained
### if all catch at all lengths = 0, return 0 as mean length
# if (is.nan(res)) {
# if (all(ifelse(is.na(x), 0, x) == 0)) {
# res[] <- 0
# }
# }
return(res)
})
return(lmean)
}
### ------------------------------------------------------------------------ ###
### length at first capture ####
### ------------------------------------------------------------------------ ###
calc_lc <- function(stk, a, b) {
### find position in age vector
Ac <- apply(catch.n(stk), MARGIN = c(2, 6), function(x) {
head(which(x >= (max(x, na.rm = TRUE)/2)), 1)
})
Ac <- an(median(Ac))
### calculate lengths
weights <- c(catch.wt(stk)[, 1,,,, 1])
lengths <- (weights / a)^(1 / b)
### length at Ac
Lc <- floor(lengths[Ac]*10)/10
return(Lc)
}
### ------------------------------------------------------------------------ ###
### inter-annual variability ####
### ------------------------------------------------------------------------ ###
#' calculate inter-annual variability of FLQuant
#'
#' This function calculates survey indices from the numbers at age of an
#' FLStock object
#'
#' @param object Object of class \linkS4class{FLQuant} with values.
#' @param period Select every n-th year, e.g. biennial (optional).
#' @param from,to Optional year range for analysis.
#' @param summary_per_iter Function for summarising per iter. Defaults to mean.
#' @param summary Function for summarising over iter. Defaults to mean.
#' @return An object of class \code{FLQuant} with inter-annual variability.
#'
#' @export
#'
setGeneric("iav", function(object, period, from, to, summary_per_iter,
summary_year, summary_all) {
standardGeneric("iav")
})
### object = FLQuant
#' @rdname iav
setMethod(f = "iav",
signature = signature(object = "FLQuant"),
definition = function(object,
period, ### periodicity, e.g. use every 2nd value
from, to,### year range
summary_per_iter, ### summarise values per iteration
summary_year,
summary_all) {
### subset years
if (!missing(from)) object <- FLCore::window(object, start = from)
if (!missing(to)) object <- FLCore::window(object, end = from)
### get years in object
yrs <- dimnames(object)$year
### select every n-th value, if requested
if (!missing(period)) {
yrs <- yrs[seq(from = 1, to = length(yrs), by = period)]
}
### reference years
yrs_ref <- yrs[-length(yrs)]
### years to compare
yrs_comp <- yrs[-1]
### calculate variation (absolute values, ignore pos/neg)
res <- abs(1 - object[, yrs_comp] / object[, yrs_ref])
### replace Inf with NA (compared to 0 catch)
res <- ifelse(is.finite(res), res, NA)
### summarise per iteration
if (!missing(summary_per_iter)) {
res <- apply(res, 6, summary_per_iter, na.rm = TRUE)
}
### summarise per year
if (!missing(summary_year)) {
res <- apply(res, 1:5, summary_year, na.rm = TRUE)
}
### summarise over everything
if (!missing(summary_all)) {
res <- summary_all(c(res), na.rm = TRUE)
}
return(res)
})
### ------------------------------------------------------------------------ ###
### "correct" collapses ####
### ------------------------------------------------------------------------ ###
collapse_correction <- function(stk, quants = c("catch", "ssb", "fbar"),
threshold = 1, yrs) {
names(quants) <- quants
qnt_list <- lapply(quants, function(x) get(x)(stk))
qnt_list <- lapply(qnt_list, function(x) x[, ac(yrs)])
n_yrs <- dim(qnt_list[[1]])[2]
n_its <- dim(qnt_list[[1]])[6]
### find collapses
cd <- sapply(seq(n_its), function(x) {
min_yr <- min(which(qnt_list$ssb[,,,,, x] < 1))
if (is.finite(min_yr)) {
all_yrs <- min_yr:n_yrs
} else {
all_yrs <- NA
}
all_yrs + (x - 1)*n_yrs
})
cd <- unlist(cd)
cd <- cd[which(!is.na(cd))]
### remove values
qnt_list <- lapply(qnt_list, function(x) {
[email protected][cd] <- 0
return(x)
})
return(qnt_list)
}