-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCohoFRAMModelValidation.Rmd
5140 lines (4322 loc) · 305 KB
/
CohoFRAMModelValidation.Rmd
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
---
title: "Coho FRAM Model Validation and Mixed Stock Model Updating<br><br>"
author:
- Angelika Hagen-Breaux^[Washington Department of Fish and Wildlife, hagenafh@dfw.wa.gov]
- Carrie Cook-Tabor^[U.S. Fish and Wildlife Service, carrie_cook-tabor@fws.gov],
- Dan Auerbach^[Washington Department of Fish and Wildlife, Daniel.Auerbach@dfw.wa.gov]
date: "`r Sys.Date()`"
output:
bookdown::html_document2:
fig_caption: yes
theme: cerulean
toc: yes
toc_depth: 3
toc_float: yes
code_folding: hide
html_document:
toc: yes
toc_depth: '3'
df_print: paged
word_document: null
always_allow_html: yes
editor_options:
chunk_output_type: console
markdown:
wrap: 72
subtitle: Southern Fund Project 2019-SP-3A<br><br><br>
---
<style type="text/css">
h1.title {
text-align: center;
}
h3.subtitle {
text-align: center;
}
h4.author { /* Header 4 - and the author and data headers use this too */
text-align: center;
}
h4.date { /* Header 4 - and the author and data headers use this too */
text-align: center;
}
</style>
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, results = FALSE, warning = FALSE, message = FALSE, fig.width = 9, fig.height = 9)
library("tidyverse")
library("patchwork")
library("gt")
# install.packages("devtools")
# devtools::install_github("BSchamberger/RDCOMClient")
# devtools::install_github("FRAMverse/framr")
library(framr)
library(rstatix)
library(ggpubr)
library(broom)
library(modelr)
library(reactable)
pal = c("#465177", "#E4C22B", "#965127")
table_dir<-"C:/Data/CoTC/SouthernFund/2019/2019SouthernFundProject/DataSF19/"
mdb<-"C:/data/CoTC/PostseasonRuns/PostDB/PSC_CoTC_PostSeason_CohoFRAMDB_thru2020_021622.mdb"
d_fishmap<-read.csv(file.path(table_dir,"FishMapAug26_2022.csv"))
d_uniquefishery<-read.csv(file.path(table_dir,"MR_FishMapUnique.csv"))
d_uniquefishery2<-read.csv(file.path(table_dir,"MR_FishMapUnique2.csv"))
d_tSlu<-read.csv(file.path(table_dir,"ts_lu.csv"))
d_fishscalar<-framr::read_coho_fish_sclr(mdb,runs = 34:42) |>
select(RunYear, FisheryID, TimeStep, FisheryFlag, MarkReleaseRate)
d_exclude_fish<-read.csv(file.path(table_dir,"MR_ExcludeFish.csv"))
t_unclipped<-read.csv(file.path(table_dir,"MR_unclipped.csv"))
t_prmu<-read.csv(file.path(table_dir,"PR_MU.csv"))
d_stockmap<-read.csv(file.path(table_dir,"ER_Stock_CWT07112022.csv"))
d_ERtrollsum<-read.csv(file.path(table_dir,"ER_Ttrollsum.csv"))
d_top10<-read.csv(file.path(table_dir,"Fish43top10.csv"))
#needed to combine T/NT net pairs. Do not combine T/NT troll (different MSF regs)
Tpair<-c(80,82,87,96,101,109,111,119,121,123,130,132,137,139,141,143,145,153,155,157,159)
#load DA objects for ER_comp
list2env(readRDS("T:/DFW-Salmon Mgmt Modeling Team - General/Southern Fund Projects/Coho FRAM MSM CWT analysis/ER_comp_fram_rmis_obj.rds"), .GlobalEnv)
```
```{r d_samp}
d_samp <- read_csv(file.path(table_dir, "MR Sampling Data.csv"))
# get FishIDs for sport fisheries for later use
sampsportID <- unique(d_samp[d_samp$Gear=="Sport",3]) |>
filter(!is.na(FisheryID))
sort(sampsportID$FisheryID)
#exclude some non-FRAM areas without FishID
d_samp <- d_samp|>
filter(!is.na(FisheryID)) |>
select(RunYear = Year, FisheryID, TimeStep = TS, #Flag,
MK = `Mrkd Landed`,
UK = `UM Landed`,
MR = `Mrkd Released`,
UR = `UM Released`
) |>
mutate(
FisheryID = if_else(FisheryID %in% Tpair, FisheryID+1, FisheryID)
) |> #count(Flag)
group_by(RunYear, FisheryID, TimeStep) |> #, Flag
summarise(across(MK:UR, sum), .groups = "drop") #count(Flag)
# only calculate landed mark rate if sum of marked and unmarked >20
# calculate encounter mark rate if sum of all encounters >20
d_samp <- d_samp |>
mutate(
mr_kept = MK/(MK+UK),
mr_enc = (MK+MR)/(MK+UK+MR+UR)
) |>
dplyr::rename_at(vars(MK:mr_enc), ~paste0(.,"_samp")) |>
filter(!is.na(mr_enc_samp))|>
mutate(Source = "Sampling")
#use Encounters for MSF Sport and Landed for NS
d_samp <- left_join(
d_samp,
d_fishscalar |> select(RunYear,FisheryID,TimeStep,FisheryFlag),
by=c("RunYear","FisheryID","TimeStep"))
d_samp <- d_samp |>
mutate(Type = ifelse(FisheryFlag>2,"Encounters","Landed"))|>
mutate(
TotalLanded = MK_samp+UK_samp,
TotalEncounters = MK_samp+UK_samp+MR_samp+UR_samp,
MrkdEncounters = MK_samp + MR_samp
)|>
mutate(
Total_samp = ifelse(Type=="Encounters",TotalEncounters,TotalLanded),
Marked_samp = ifelse(Type=="Encounters",MrkdEncounters,MK_samp),
MR_sampl = ifelse(Type=="Encounters",mr_enc_samp,mr_kept_samp)
)
d_samp <- d_samp[,c(1:3,16:18,10,11,12)] |>
filter(!is.na(MR_sampl)) |>
filter(!is.na(FisheryFlag)) |>
filter(!FisheryFlag == 0) |>
filter(!FisheryFlag == 28)
#eliminate MSF troll fisheries Type= Encounters FisheryID = 34,35,38,42. Sampling for these fisheries only records landed catch
troll <- c(34,35,38,42)
d_samp <- d_samp |>
filter(!FisheryID %in% troll ) |>
filter(!Total_samp<20)
```
```{r d_rmisraw}
# data pulled from RMIS CatchSample May 17, 2022 with only a species (Coho) and years (2010 to 2020) filter
d_rmisraw<-read.csv(file.path(table_dir,"MR_RMIS2010_20CohoMrkSample.csv"))
# fisheries that remained unassigned after the first round were added to
# the fishmap file based on best fit, with some exceptions that remained unmapped
# such as 1M2, 1M3, 1M4, Oregon Net etc.
#Clean and summarize data
#maps CatchSample data to FRAM fisheries
d_rmisraw2<-d_rmisraw%>%
add_column (FisheryID = 0)
# add blanks to end of recovery location code
d_rmisraw2$catch_location_code<-paste(d_rmisraw2$catch_location_code," ")
for (i in 1:nrow(d_fishmap)) {
numchars<-d_fishmap[i,4]
gear<-d_fishmap[i,3]
FishID2<-d_fishmap[i,1]
FishName2<-d_fishmap[i,2]
locc<-substr(d_fishmap[i,5], 1, numchars)
i=i+1
#find all the records in rmis_recrel with matching fishery and location codes
# update FishID and FishName fields to FishID and FishName
# assign fishery 50-59 to escapement
if (gear == 5){
d_rmisraw2<-within(d_rmisraw2,FisheryID[floor(fishery/10) ==gear ]<-FishID2)
} else {
d_rmisraw2<-within(d_rmisraw2,FisheryID[floor(fishery/10) ==gear & substr(catch_location_code,start=1,stop=numchars) ==locc]<-FishID2)
}
}
#assign unassigned records with a freshwater sampling location to escapement
d_rmisraw2<- within(d_rmisraw2, FisheryID[FisheryID==0 & substr(catch_location_code,2,2) == "F"]<-300)
#add Treaty ocean troll designation
NT_ocean_troll<-c(35,38,42)
d_rmisraw2$FisheryID = ifelse(d_rmisraw2$fishery ==15 & d_rmisraw2$FisheryID %in% NT_ocean_troll, d_rmisraw2$FisheryID + 1,d_rmisraw2$FisheryID)
#add Fishery Name
SoFtroll<-c(18,20,22)
d_rmisraw2<-left_join(d_rmisraw2,d_uniquefishery %>% select(FisheryID,FisheryName), by = c("FisheryID"))|>
# eliminate Newport,Coos Bay, Tillamook troll, very low mark rate based on only one or two years of sampling with low sample rate
filter(!FisheryID %in% SoFtroll)
for (i in 1:nrow(d_rmisraw2)) {
if (d_rmisraw2$FisheryID[i] %in% Tpair){
d_rmisraw2$FisheryID[i]<- d_rmisraw2$FisheryID[i]+1
} else {
d_rmisraw2$FisheryID[i]<- d_rmisraw2$FisheryID[i]
}
}
d_junk<-d_rmisraw2|>
group_by(FisheryID)|>
summarize(n = n())
# eliminate records with no sampling to later compute a new sampling expansion
d_rmis_no_samp<-d_rmisraw2[,c(3,13,14,15,20,21)]|>
filter(number_sampled>0,
number_caught>0,
sample_type!=5)|>
select(-sample_type)|>
dplyr::rename("RunYear"=catch_year)|>
group_by(RunYear,FisheryID,FisheryName)|>
summarise(across(c(number_caught,number_sampled),sum))
#for use in comparing FRAM and RMIS Catches see Data Preparation
rmis_landed<-d_rmisraw2[,c(3,14,15,20,21)]|>
filter(!is.na(number_caught))|>
dplyr::rename("Total_rmis"=number_caught,
"Sampled_rmis"=number_sampled,
"RunYear"=catch_year)|>
group_by(RunYear,FisheryID,FisheryName)|>
summarise(across(c(Total_rmis,Sampled_rmis),sum),.groups="drop")
# add time steps
d_rmis3<-left_join(d_rmisraw2,d_tSlu,by=c('period_type'='PeriodType','period'='Period'))|>
#clean data
#Eliminate records where mark rate is na
filter(!is.na(mark_rate))|>
#eliminate records where number caught is na
filter(!is.na(number_caught))|>
#eliminate records where number caught is zero
filter(!number_caught==0) |>
#eliminate records where number sampled is na
filter(!is.na(number_sampled))|>
#eliminate records where number sampled is zero
filter(!number_sampled==0)|>
#calculate the number marked
mutate(number_marked = number_caught * mark_rate) |>
#eliminate records where adclip_selective_fishery = M (mixed)
filter(!adclip_selective_fishery=="M")|>
#eliminate Skagit FW sport. Only one year of sampling in the Cascade which appears to have a different mark rate (higher) than the Skagit River fishery modeled in FRAM. Eliminate Quinault net. Only one record that has a mark sample. This record has a mark rate of zero. This result is highly improbable.
filter(!FisheryID %in% c(108,63))
#sum number marked by fishery, year, and time step
d_rmis<-d_rmis3 |>
group_by(catch_year, FisheryID, TimeStep) |>
summarise(across(c(number_caught,number_marked,number_sampled), sum), .groups = "drop")|>
mutate(MR_rmis = number_marked/number_caught)|>
#eliminate records where number sampled < 20
filter(!number_sampled<20)
d_rmis<-d_rmis[,c(1:5,7)]|>
mutate(Source = "RMIS")|>
mutate(Type = "Landed")
colnames(d_rmis)[1]<- "RunYear"
colnames(d_rmis)[4]<- "Total_rmis"
colnames(d_rmis)[5]<- "Marked_rmis"
colnames(d_rmis)[2]<-"FisheryID"
```
```{r d_fram}
d_fram <- left_join(
framr::read_coho_mort(mdb, runs = 34:44) |>
select(RunYear, StockID, FisheryID, TimeStep, LandedCatch, MSFLandedCatch, MSFNonRetention) |>
mutate(RunYear = as.numeric(RunYear))
,
d_fishscalar
,
#d_fram_mort, d_fram_fs,
by = c("RunYear","FisheryID","TimeStep")
) |> #filter(FisheryID %in% 96:97) |> count(FisheryID, FisheryName)
mutate(
MarkStatus = if_else(StockID %% 2 == 0, "M", "UM"),
FisheryID = ifelse(FisheryID %in% Tpair, FisheryID+1, FisheryID),
Kept = LandedCatch + MSFLandedCatch,
Enc = LandedCatch + MSFLandedCatch + if_else(MarkReleaseRate>0,MSFNonRetention/MarkReleaseRate,0)
)
#re-flag 1s to 2s.In post-season runs fisheries should all be flagged as 2. This will avaoid potential duplicates for T/NT fishing pairs
d_fram[which(d_fram$FisheryFlag == 1),]$FisheryFlag=2
d_fram<-d_fram|>
group_by(RunYear, FisheryID,MarkStatus, TimeStep,FisheryFlag)|>
summarize(across(Kept:Enc,sum),.groups = "drop")|>
pivot_wider(names_from = MarkStatus, values_from = c(Kept,Enc))|>
mutate(
mr_kept = Kept_M/(Kept_M+Kept_UM),
mr_enc = Enc_M/(Enc_M+Enc_UM)
) |>
dplyr::rename_at(vars(Kept_M:mr_enc), ~paste0(.,"_fram"))
# for landed catch comparison with RMIS
fram_landed<-d_fram[,c(1:6)]|>
mutate(Total_fram =Kept_M_fram + Kept_UM_fram )|>
group_by(RunYear,FisheryID)|>
summarise(across(c(Kept_M_fram,Total_fram),sum),.groups="drop")
d_fram<-d_fram|>
filter(!is.na(mr_enc_fram))|>
filter(!FisheryFlag>8)|> #exclude mixed MSF/NS fisheries
mutate(Source = "FRAM")
d_fram<-d_fram[,c(1:4,7,8,10,11)]|>
mutate(Type = "Encounters",
Total = Enc_M_fram + Enc_UM_fram
)
colnames(d_fram)[5]<-"Marked"
colnames(d_fram)[7]<-"MR"
d_fram<-d_fram[,c(1:4,10,5,7:9)]
```
```{r joined_MR_objs}
#nothing in sampling dataset that isn't in fram dataset
setdiff(unique(d_samp$FisheryID), unique(d_fram$FisheryID))
#but lots of fram fisheries for which we don't have sampling obs...
sort(setdiff(unique(d_fram$FisheryID), unique(d_samp$FisheryID)))
#join to sampling if MSF, join to RMIS if non-selective
# d_samp<-d_samp|>
# group_by(RunYear,FisheryID,TimeStep,Source,Type)|>
# summarise(across(c(Total_samp,Marked_samp,MR_sampl),sum),.groups="drop")
d_fram_joined1 <- d_fram|>
filter(FisheryFlag ==8)|>
inner_join(
d_samp[,-c(8)],
by=c("RunYear","FisheryID","TimeStep")
)
colnames(d_fram_joined1)[10]<-"Total"
colnames(d_fram_joined1)[11]<-"Marked"
colnames(d_fram_joined1)[12]<-"MR"
d_fram_joined2<-d_fram|>
filter(!FisheryFlag==8)|>
inner_join(
d_rmis,
by=c("RunYear","FisheryID","TimeStep")
)
colnames(d_fram_joined2)[10]<-"Total"
colnames(d_fram_joined2)[11]<-"Marked"
colnames(d_fram_joined2)[12]<-"MR"
mr_fram_samp_rmis <-rbind(d_fram_joined1,d_fram_joined2)
colnames(mr_fram_samp_rmis)[10]<-"Tot_samp"
colnames(mr_fram_samp_rmis)[11]<-"Marked_samp"
colnames(mr_fram_samp_rmis)[12]<-"MR_samp"
mr_ts_fram_samp_rmis <-left_join(mr_fram_samp_rmis,d_uniquefishery %>% select(FisheryID,FisheryName), by = c("FisheryID"))
#sum over time steps before computing annual rates. It's okay to ignore Flags and Type (based on data QAQC). Conduct analyses on annual mark rates, because many FRAM fisheries are not reported in the time step they actually occur; i.e., PS fw fisheries are modeled in time 5 even if most catch occurs in time 4.
d_fram_yr<-d_fram|>
group_by(RunYear,FisheryID,FisheryFlag,Source,Type)|>
summarise(across(c(Total,Marked,MR),sum),.groups="drop")|>
mutate(MR=Marked/Total)|>
left_join(d_uniquefishery|>
select(FisheryID,FisheryName), by = c("FisheryID"))
d_samp_yr<-d_samp|>
filter(Type != "Landed")|>
group_by(RunYear,FisheryID,Source,Type)|>
summarise(across(c(Total_samp,Marked_samp,MR_sampl),sum),.groups="drop")|>
mutate(MR_sampl=Marked_samp/Total_samp)
#include RMIS time steps for non-selective fisheries that are modeled in a different time step in FRAM
d_rmis_yr<-d_rmis|>
left_join(d_fram|>
select(RunYear,FisheryID,TimeStep,FisheryFlag), by = c("RunYear","FisheryID","TimeStep"))|>
rowid_to_column("uid")
d_rmis_yr<-d_rmis_yr|>
nest_by(FisheryID, RunYear) |>
#same as: group_by(FisheryID, RunYear) |> nest() |> rowwise() |>
filter(
nrow(data) >= 2 &
nrow(data |> filter(is.na(FisheryFlag) & MR_rmis < 0.95) > 0) &
nrow(data |> filter(FisheryFlag == 2) > 0)
) |>
unnest(data) |> ungroup() |>
split(f = ~FisheryID + RunYear, drop = T) |>
map_df(
function(d){
ts_na = d |> filter(is.na(FisheryFlag) & MR_rmis < 0.95) |> pluck("TimeStep")
if(length(ts_na) > 1) {
map_df(
ts_na,
function(ts){
ff_pre = d |> filter(TimeStep == ts - 1) |> pluck("FisheryFlag", .default = NA)
ff_pst = d |> filter(TimeStep == ts + 1) |> pluck("FisheryFlag", .default = NA)
if(!all(is.na(c(ff_pre, ff_pst)))){
if(ff_pre == 2 | ff_pst == 2){
d |> filter(TimeStep == ts) |> select(uid) |> mutate(flag = "3")
}
}
})
} else {
ff_pre = d |> filter(TimeStep == ts_na - 1) |> pluck("FisheryFlag", .default = NA)
ff_pst = d |> filter(TimeStep == ts_na + 1) |> pluck("FisheryFlag", .default = NA)
if(!all(is.na(c(ff_pre, ff_pst)))){
if(ff_pre == 2 | ff_pst == 2){
d |> filter(TimeStep == ts_na) |> select(uid) |> mutate(flag = "3")
}
}
}
}
) %>%
left_join(d_rmis_yr, y = ., by = "uid")|>
filter(FisheryFlag==2 | flag==3)|>
#eliminate non-selective fisheries with MR >0.98% These are likely MSFs placed in the wrong time step due to RMIS management week structure
filter(MR_rmis<0.98)
# for (i in 1:nrow(d_rmis_yr)) {
# Tstep<-d_rmis_yr$TimeStep[i]
# runyr<- d_rmis_yr$RunYear[i] #d_rmis_yr[i,"RunYear"]
# fid<-d_rmis_yr$FisheryID[i]
# fflag<-d_rmis_yr$FisheryFlag[i]
# mrkrate<-d_rmis_yr$MR_rmis[i]
# if (is.na(fflag) & mrkrate<0.95) {
# other_ts <- d_rmis_yr[
# d_rmis_yr$RunYear == runyr &
# d_rmis_yr$FisheryID == fid &
# d_rmis_yr$FisheryFlag == 2 &
# (d_rmis_yr$TimeStep == Tstep + 1 | d_rmis_yr$TimeStep == Tstep - 1 ) ,]
# if(nrow(other_ts) > 0) {
# d_rmis_yr$FisheryFlag[i]<-3
# }
# }
# }
d_rmis_yr<-d_rmis_yr[,c(2:9)]|>
group_by(RunYear,FisheryID,Source,Type)|>
summarise(across(c(Total_rmis,Marked_rmis,MR_rmis),sum),.groups="drop")|>
mutate(MR_rmis=Marked_rmis/Total_rmis)
mr_yr_fram_join_samp<-d_fram_yr|>
filter(FisheryFlag ==8)|>
inner_join(
d_samp_yr,
by=c("RunYear","FisheryID")
)
mr_yr_fram_join_rmis<-d_fram_yr|>
filter(FisheryFlag !=8)|>
inner_join(
d_rmis_yr,
by=c("RunYear","FisheryID")
)|>
dplyr::rename(Total_samp = Total_rmis)|>
dplyr::rename(Marked_samp = Marked_rmis)|>
dplyr::rename(MR_sampl=MR_rmis)
mr_yr_fram_samp_rmis<-rbind(mr_yr_fram_join_samp,mr_yr_fram_join_rmis)|>
mutate(RelPctDiff = (MR_sampl-MR)/MR_sampl,
AbsPctDiff = (MR_sampl-MR))
# compare landed RMIS to landed sampling for non-selective fisheries
# mr_rmis_samp<-left_join(mr_rmis_samp,d_uniquefishery %>% select(FRAM_Fish_ID,FRAM_Fish_Name), by = c("FisheryID"="FRAM_Fish_ID"))
mr_rmis_samp<-d_samp|>
#filter(Type=="Landed")|>
inner_join(
d_rmis,
by=c("RunYear","FisheryID","TimeStep")
)|>
left_join(
d_uniquefishery,
by=c("FisheryID")
)
# #add fishery flag
# mr_rmis_samp<-left_join(mr_rmis_samp, d_fram%>% select(RunYear,FisheryID,TimeStep,FisheryFlag),
# by=c("RunYear","FisheryID","TimeStep"))
#eliminate MSF
mr_rmis_samp<- mr_rmis_samp|>
filter(FisheryFlag<=2)
mr_fram_samp_long <- left_join(mr_fram_samp_rmis,d_uniquefishery %>% select(FisheryID,FisheryName), by = c("FisheryID"))|>
select(RunYear, FisheryID, FisheryName, TimeStep, starts_with("MR")) |>
pivot_longer(names_to = "type", values_to = "val", cols = starts_with("MR"))
colnames(mr_fram_samp_long)[3]<-"FisheryName"
mr_fram_samp_long$type[mr_fram_samp_long$type!="MR_samp"]<-"MR_fram"
mr_rmis_samp_long <- mr_rmis_samp |>
select(RunYear, FisheryID, FisheryName, TimeStep, MR_sampl ,MR_rmis) |>
pivot_longer(names_to = "type", values_to = "val", cols = c("MR_sampl","MR_rmis"))
colnames(mr_rmis_samp_long)[3]<-"FisheryName"
```
\newpage
# Overview
## Acknowledgements
Financial support for this project was provided by the Southern Endowment Fund, with support from the Washington Department of Fish and Wildlife, U.S. Fish and Wildlife Service, and members of the Coho Technical Committee. <br>
The authors also wish to thank Jeremiah Shrovnal, Derek Dapp, Marlene Bellman, and Jon Carey for their help and feedback.
\newpage
## Glossary
<a id='M'></a>**Adipose Mark**<br>
A missing adipose fin on salmon as a result of clipping by a hatchery program. Commonly, a visual identifier of a hatchery fish that can be retained in a [mark selective fishery](#MSF). The use of "marked" and "clipped" is used interchangeably within the document.
<a id='BP'></a>**Base Period (BP)** <br>
A range of years from which CWT data are used to estimate exploitation rates and other parameters through a process of cohort reconstruction. Resulting base period reference parameters are used to populate the FRAM model to predict annual stock/fishery specific impacts.
<a id='BkFRAM'></a>**Backwards FRAM (BkFRAM)** <br>
A [FRAM](#FRAM) utility that reconstructs starting Cohorts by adding fisheries mortalities and escapements for the purpose of producing post-season model runs (Hagen-Breaux 2018). FRAM iteratively adjusts stock recruit scalars (a surrogate for [starting cohorts](#SC)) and runs FRAM forward until the resulting escapements match the target escapements.
<a id='CRC'></a>**Catch Record Cards (CRC)** <br>
Catch Record Cards are used to estimate the recreational catch of salmon, steelhead, sturgeon, halibut and Puget Sound Dungeness crab. The CRC system houses the recreational catch estimates.
<a id='CWT'></a>**Coded-Wire Tag (CWT)** <br>
Coded micro-wire implanted in juvenile salmon prior to release. When recovered, the binary or numeric code on the tag identifies the tag group, and thus provides information such as location and timing of release, special hatchery treatments, etc.
<a id='CoTC'></a>**Coho Technical Committee (CoTC)** <br>
Technical committee formed by the [Pacific Salmon Commission](#PSC) providing the panels with scientific data to make decisions affecting Southern Coho salmon.
<a id='ER'></a>**Exploitation Rate (ER)**<br>
The mortality (landed or total) of a stock or stock aggregate in a fishery(s) divided by the stock's abundance (fishery mortality + escapement).
<a id='ET'></a>**Extreme Terminal**<br>
Marine area directly adjacent to salmon native streams with a very high proportion of catch made up of the "local stock" due to river mouth proximity, i.e., Elliott Bay is the extreme terminal area for Green River Chinook and Coho.
<a id='FRAM'></a>**Fishery Regulation Assessment Model (FRAM)** <br>
[Fishery simulation model](https://framverse.github.io/fram_doc/index.html) used by the Pacific Salmon Commission (Coho only), Pacific Fishery Management Council, Washington Department of Fish and Wildlife, and Puget Sound Treaty Tribes to evaluate the effects of fisheries on Chinook and Coho salmon and to evaluate management objectives.
<a id='fulljoin'></a>**Full Join** <br>
A data join returning all the rows from the joined tables, whether they are matched or not.
<a id='MR'></a>**Mark Rate** <br>
The mark rate of a fishery is computed as [adipose marked](#M) landed catch or encounters divided by total landed catch or total encounters in the fishery.
<a id='MSF'></a>**Mark-Selective Fishery (MSF)** <br>
A fishery in which only marked (adipose fin clipped) fish can be legally retained.
<a id='MSM'></a>**Mixed Stock Model (MSM)** <br>
Main computer program used to build the current Coho [base period](#BP). Model inputs included [coded-wire tags](#CWT) and estimated catches and escapements of Coho coast-wide from catch years 1986-1992. Model output includes base period [exploitation rates](#ER) utilized in contemporary [FRAM](#FRAM) runs.
<a id='NOF'></a>**North of Falcon (NOF)**<br>
Co-manager, annual, pre-season Puget Sound salmon fishery planning process; referencing the region North of Cape Falcon, Oregon, which marks the southern border of active management for Washington salmon stocks.
<a id='PSC'></a>**Pacific Salmon Commission [(PSC)](https://www.psc.org/)** <br>
A commission composed of Canadian and United States representatives tasked with developing and upholding the [Pacific Salmon Treaty](#PST).
<a id='PFMC'></a>**Pacific Fishery Management Council [(PFMC)](https://www.pcouncil.org/)** <br>
The Pacific Fishery Management Council manages fisheries for approximately 119 species of salmon, groundfish, coastal pelagic species (sardines, anchovies, and mackerel), and highly migratory species (tunas, sharks, and swordfish) on the West Coast of the United States.
<a id='PST'></a>**Pacific Salmon Treaty [(PST)](https://www.psc.org/about-us/history-purpose/pacific-salmon-treaty/)** <br>
Treaty between the Governments of Canada and the United States of America concerning Pacific Salmon.
<a id='PTerm'></a>**Preterminal Fisheries**<br>
Fisheries on salmon in marine preterminal areas. Preterminal areas are distant to natal streams and consist of predominately mixed stocks.
<a id='RMIS'></a>**Regional Mark Information System (RMIS)** <br>
[RMIS](https://www.rmpc.org/) is an online data repository, storing Pacific Coast-wide anadromous salmon [adipose marking](#M) information, [coded-wire-tag](#CWT) releases and recoveries, recovery locations, and sampling information.
<a id='SOF'></a> **South of Falcon (SOF)**<br>
Referencing the region South of Cape Falcon, Oregon, which marks the southern border of active management for Washington State salmon stocks.
<a id='SC'></a> **Starting Cohort**<br>
Initial adult Coho run sizes prior to subtracting natural and fishing mortality at the beginning of the run year.
<a id='Term'></a>**Terminal Fisheries**<br>
Fisheries on adult salmon in marine terminal areas. Terminal areas are close to the natal stream and consist of predominately local stocks.
<a id='TS'></a>**Time Steps**<br>
Coho [FRAM](#FRAM) has 5 time steps.<br>
- Time 1: January – June<br>
- Time 2: July<br>
- Time 3: August<br>
- Time 4: September<br>
- Time 5: October-December
<a id='VR'></a>**Validation Runs** <br>
Post-season FRAM model runs populated with observed mortalities and escapements, reflecting the "best information". [Exploitation rates](#ER) resulting from these runs are compared to pre-season exploitation rates to assess whether management objectives were achieved.
---
```{js, echo=FALSE}
// Place footnotes after glossary section
$(document).ready(function() {
$('.footnotes ol').appendTo('#glossary');
$('.footnotes').remove();
});
```
\newpage
## List of Figures
[Figure 4.1. Exploitation Rates of Key Wild Stocks Resulting from Varying the Abundance of Test Stocks](#ERWild)<br>
[Figure 4.2. Exploitation Rate Differences Resulting from Varying the Abundances of Test Stocks from High to Low](#ERWildDiff)<br>
[Figure 5.1. Differences between Post-season Coho FRAM Modeled Mark Rates and Sampling Observations, 2010-18](#MRDiff)<br>
[Figure 5.2. 2010-18 Average Fishery mark Rates from FRAM and Sampling Observations](#AvgMR)<br>
[Figure 5.3. Wilcoxon p-values by Fishery](#Wilcox1)<br>
[Figure 5.4. 2010-18 Fishery Mark Rates from FRAM and Sampling by Year](#MRbyYr)<br>
[Figure 6.1. Recovery Counts by Time Period and Type](#RecCount)<br>
[Figure 6.2. Annual CWT Recoveries by Release Location in Fisheries and Escapement](#AnnualRecCount)<br>
[Figure 6.3.1. Skagit Pseudo ERs and Proportional Fishery Rankings](#Skagit1)<br>
[Figure 6.3.2. Tulalip Pseudo ERs and Proportional Fishery Rankings](#Tulalip1)<br>
[Figure 6.3.3. Quilcene Pseudo ERs and Proportional Fishery Rankings](#Quilcene1)<br>
[Figure 6.3.4. George Adams Pseudo ERs and Proportional Fishery Rankings](#GeorgeAdams1)<br>
[Figure 6.3.5. Nisqually Pseudo ERs and Proportional Fishery Rankings](#Nisqually1)<br>
[Figure 6.3.6. Puyallup Pseudo ERs and Proportional Fishery Rankings](#Puyallup1)<br>
[Figure 6.3.7. Green Pseudo ERs and Proportional Fishery Rankings](#Green1)<br>
[Figure 6.3.8. Quillayute Pseudo ERs and Proportional Fishery Rankings](#Quillayute1)<br>
[Figure 6.3.9. Queets Pseudo ERs and Proportional Fishery Rankings](#Queets1)<br>
[Figure 6.3.10. Quinault Pseudo ERs and Proportional Fishery Rankings](#Quinault1)<br>
[Figure 6.3.11. Chehalis Pseudo ERs and Proportional Fishery Rankings](#Chehalis1)<br>
[Figure 6.3.12. Willapa Pseudo ERs and Proportional Fishery Rankings](#Willapa1)<br>
[Figure 6.3.13. Columbia Earlies Pseudo ERs and Proportional Fishery Rankings](#ColumbiaEarlies1)<br>
[Figure 6.3.14. Columbia Lates Pseudo ERs and Proportional Fishery Rankings](#ColumbiaLates1)<br>
[Figure 6.3.15. Strait of Georgia Vancouver Island Pseudo ERs and Proportional Fishery Rankings](#SGVI1)<br>
[Figure 6.3.16. Fraser Lower Pseudo ERs and Proportional Fishery Rankings](#FraserLower1)<br>
[Figure 6.3.17. Fraser Upper Pseudo ERs and Proportional Fishery Rankings](#FraserUpper1)<br>
\newpage
## List of Tables
[Table 3.1. Unique Release Codes Mapped](#Unique)<br>
[Table 3.2. Columbia River Stock Assignments and Numbers Released](#ColRStk)<br>
[Table 3.3. Stock CWT 1998](#StkCWT)<br>
[Table 3.4. Fisheries Excluded from CWT Analysis and Main Reasons for Exclusion](#ExcludeFish)<br>
[Table 4.1. List of Response Stock Aggregates](#ResponseStk)<br>
[Table 4.2. List of Test Stock Aggregates](#TestStk)<br>
[Table 4.3. 2010-2018 Starting Cohorts of Coho Test Stocks](#StartingCohorts)<br>
[Table 4.4. List of Model Runs, Fisheries, and Time Steps with Catch Reductions to Avoid Negative Escapements](#NegEsc)<br>
[Table 4.5. Exploitation Rates of Key Wild Response Stocks Resulting from Varying Abundances of Test Stocks](#ERKey)<br>
[Table 4.6. Average Exploitation Rates Differences of Key Wild Stocks Resulting from Varying the Abundances of Test Stocks ](#ERDiff)<br>
[Table 4.7. Top 5 Fisheries Responsible for Total Mortality Differences Caused by Varying the Abundances of Test Stocks](#Top5)<br>
[Table 5.1. Sources for Mark Rate Comparisons by Fishery Type](#MRSource)<br>
[Table 5.2. Number of Fisheries Evaluated with Wilcoxon and Number of Fisheries with Significant Mark Rate Differences in Each Area](#Wilcox2)<br>
[Table 5.3. 'Good', 'Moderate', 'Poor' Agreement between FRAM and Sampling Mark Rates](#GMP)<br>
[Table 5.4. Mean Mark Rate Differences by Fishery Area](#MeanMRDiff)<br>
[Table 5.5. Comparison of FRAM and RMIS Catches by Mark Status](#MarkStatus)<br>
[Table 5.6. Comparison of FRAM and RMIS Marked Catches in the Area 4/4B Treaty Troll Fishery](#MarkedCatch)<br>
[Table 6.1. Number of CWT Recoveries for Assessed Stocks, 2010-1019](#FocalCWT)<br>
\newpage
## Executive Summary
Evaluations of Coho salmon (*Oncorhynchus kisutch*) exploitation rates ([ERs](#ER)) in fisheries along the Canadian and U.S. West Coast rely on the Fishery Regulation Assessment Model [(FRAM)](#FRAM). Coded-wire-tag [(CWT)](#CWT) recoveries from 1986-1992, also referred to as the [base-period](#BP), were used to develop the stock-fishery-time period specific exploitation rates that act as core model parameters driving FRAM calculations of the impacts associated with proposed and observed fisheries and returns.
The main goal of this project was to assess whether [FRAM](#FRAM) outputs based on decades old parameterization reflect current patterns of stock distribution within mixed stock fisheries. This objective was addressed by (1) comparison of post-season FRAM ["pseudo-ER"](#Pseudo) estimates against rates derived directly from contemporary [CWT](#CWT) recoveries, and (2) through comparison of fishery mark-rates produced by [FRAM](#FRAM) against reported values in those same fisheries. This project also aimed to use sensitivity analyses to study how changes in the abundance of [FRAM](#FRAM) stock aggregates affect the resulting modeled [exploitation rates](#ER) of key co-migrating stocks. Depending on these assessments, the final project goal was to investigate potential pathways to updating the existing base-period.
**[Exploitation Rate](#ER) Analysis**<br>
[CWT](#CWT) data queried from the Regional Mark Information System [(RMIS)](#RMIS) were used for comparison of [exploitation rates](#ER) against post-season [FRAM](#FRAM). Error checking these data and determining their mapping to FRAM stocks and fisheries formed major elements of the project. In the course of mapping RMIS recoveries to FRAM fisheries we discovered that the **Southeast Alaska sport fishery is entirely missing from FRAM**. The updated look-up tables that reference [RMIS](#RMIS) recovery locations to FRAM fisheries and [RMIS](#RMIS) release information to FRAM stocks can form a valuable starting point to any future work seeking to build on the results presented here.
Initial exploration of these data narrowed fisheries to mainly those in mixed stock areas with adequate sampling and to selection of several focal stocks with sufficient [CWT](#CWT) representation in these fisheries. Most freshwater and many [extreme terminal](#ET) fisheries were excluded due to sampling limitations and the presumption that catches consisted of predominantly local stocks. [Pseudo-exploitation rates](#Pseudo) were then calculated by dividing [FRAM](#FRAM) landed catches and [RMIS](#RMIS) [CWT](#CWT) expanded recoveries by the sum of these fisheries plus escapement. In addition, the rank abundances of fishery-specific mortality proportions were calculated to provide a complementary depiction of among-fishery patterns unaffected by issues related to monitoring and sampling escapement.
**It was initially hypothesized that values of these measures from Coho [FRAM](#FRAM) [validation runs](#VR) for the fishing years 2010-2019 would correspond poorly with those calculated directly from [RMIS](#RMIS) recoveries during the same time span. However, for the selected stocks and fisheries, [FRAM](#FRAM) output exhibited better than expected agreement in terms of the relative ranking of impacts among pre-terminal fisheries and generally modest differences in the calculated [pseduo-ERs](#Pseudo).** Most larger differences between the two datasets were plausibly explained by sampling limitations in fisheries, sampling limitations in escapement, or both. Potential errors in the post-season [FRAM](#FRAM) datasets of annual catch and escapement also likely affected individual stocks, fisheries, and years, indicating the need to **review and update these critical inputs** to Coho FRAM "validation" runs as high priority next step for model improvements.
**[Mark Rate](#MR) Analysis** <br>
External mark status information (i.e., the presence or absence of an adipose fin) is collected by professional fishery samplers and reported to [RMIS](#RMIS). For the [mark rate](#MR) analysis [adipose marked](#M) statistics from [RMIS](#RMIS)' Catch/Sample database were summarized by [FRAM](#FRAM) fishery and time period and compared to the corresponding FRAM output. [Mark rates](#MR) were calculated for each fishery as the number of marked Coho encountered and/or landed divided by all Coho encountered and/or landed. In [FRAM](#FRAM), the fishery-wide [mark rate](#MR) results from aggregation across the stocks that are modeled as caught or encountered, and divergence of this composite rate from observations may therefore indicate errors in the modeled relative abundances and/or stock composition of the fishery.
This project also compared [RMIS](#RMIS) [mark rates](#MR) to mark rates directly reported by the sampling programs. As [RMIS](#RMIS) mark rates are derived from these data, we found, perhaps unsurprisingly, that [RMIS](#RMIS) and sampling mark rates closely match. Upon examination, the small differences in mark rates were caused by slight differences in [time step](#TS) definitions.
**Agreement between [FRAM](#FRAM) [mark rates](#MR) and sampling mark rates was worse than expected in many fisheries.** In particular, fishery mark rates in [FRAM](#FRAM) were consistently higher than sampled rates in several Washington coastal and ocean fisheries, and these differences warrant [further investigation](#casestudy). We were unable to conclusively determine whether [mark rate](#MR) differences were caused by inaccurate stock distributions, incorrect abundance inputs, or other data errors. [FRAM](#FRAM) and [RMIS](#RMIS) data have various shared and distinct sources of inaccuracy. In some cases, preliminary findings suggest that missing wild escapements may be responsible for some higher than observed FRAM mark rates (see [Case Study](#casestudy)).
**Sensitivity Analysis**<br>
Stock aggregate abundances were artificially adjusted from the starting values in several [validation runs](#VR) selected to capture qualitatively distinct "good" and "bad" return years. One-at-a-time increases and decreases were evaluated for the effects on modeled [exploitation rates](#ER) of other model "response" stocks, providing an indication of the relative importance of among-stock interactions in the model.
**With the exception of the Lower Fraser aggregate, the Canadian Coho stocks included in the [Pacific Salmon Treaty](#PST) have a relatively minor effect on the [FRAM](#FRAM)-modeled [exploitation rates](#ER) of U.S. Puget Sound and Coastal stocks. However, several Puget Sound stocks can significantly affect both Canadian and other Washington stocks.** In particular, changes to the Nooksack/Samish, Hood Canal, and South Puget Sound stock aggregates were influential for other modeled stock units. While improved forecast accuracy may benefit all model stocks, investments to increase the performance of preseason projections could yield the broadest returns if they were targeted to these aggregates (Nooksack/Samish, Hood Canal, South Puget Sound, and Lower Fraser). Similarly, dedicating additional resources to refined escapement estimation for these model units may tend to have greater influence on the overall accuracy of model results.
**[Updating the Mixed Stock Model](#MSM)**<br>
The [Mixed Stock Model (MSM)](#MSM) computer program was developed to estimate stock composition in [pre-terminal](#Pterm) mixed stock fisheries using [coded-wire-tag](#CWT) recovery data. Output from the [MSM](#MSM) was combined with [terminal](#Term) fishery data before producing cohort reconstructions and calculating the [base period](#BP) [exploitation rates](#ER) that form the foundation of Coho [FRAM](#FRAM).
This project investigated steps associated with combining contemporary [CWT](#CWT) recoveries with older [base period](#BP) CWTs to update base period [exploitation rates](#ER). **We identified several potential challenges and considerations, including a lack of CWT sampling in some contemporary fisheries as well as changes to marking and tagging practices that ultimately prevented a model update. We believe that updating the MSM would require an intense, concerted effort by regional experts to address the many data shortcomings.**
To calculate [base period](#BP) [exploitation rates](#ER) for contemporary tags, modelers must develop estimates of cohort size (i.e., the ER denominator). Because cohort size combines escapement and mortality, it is not possible to accurately estimate cohort size while excluding poorly sampled fisheries. Incorrect cohort sizes influence base period exploitation rate calculations for all fishery-[time steps](#TS) in the model, and therefore, even fisheries that are sampled well will require correct cohort sizes to estimate base exploitation rates.
However, to facilitate future [base period](#BP) development and updates, the following products were developed:
- A description of challenges and potential solutions related to base period changes
- Development of [Mixed Stock Model](#MSM) documentation
- Updated instructions to map [RMIS](#RMIS) recoveries to [FRAM](#FRAM) stocks and fisheries
\newpage
# Introduction
The Coho [FRAM](#FRAM) is a forward projecting computer application that uses estimates of stock abundances and fishery mortalities scaled to a [base period](#BP) average. This model is the primary tool used to evaluate performance of fisheries regimes by the Pacific Fishery Management Council [(PFMC)](#PFMC) and the parties to the Pacific Salmon Treaty [(PST)](#PST). Improvement, validation, and updating of this model are high priority activities needed to ensure accurate estimates of fishery impacts for stocks ranging from Alaska to California. [FRAM](#FRAM) is based upon historical (catch years 1986 through 1992) coded-wire-tag [(CWT)](#CWT) data to assess stock specific [exploitation rates](#ER). Members of the Coho Technical Committee [(CoTC)](#CoTC) and Coho Workgroup have grown increasingly concerned about the ability of this 30-year-old [base period](#BP) to accurately reflect current stock distribution patterns. To re-establish confidence in the model and assure that changes in stock distribution and fishery patterns are accurately captured, contemporary assessments are needed. An updated assessment of stock migratory patterns is particularly relevant given concerns about changing environmental conditions.
Unfortunately, [CWT](#CWT) recoveries have been in steep decline for the past two decades ([see recovery patterns since 1986](#RP)), with too few recoveries to complete full-scale coast-wide cohort reconstructions. Updating stock distribution patterns, which are modeled through the use of static [base period](#BP) [exploitation rates](#ER), is extremely data intense and time consuming, with the current [base period](#BP) requiring over 10 years of development time. Rather than attempting to create a brand new [base period](#BP), a project that previously failed due to its large scope and sparsity of data, this project partitioned the tasks into four smaller, achievable sub-components.
1. A sensitivity analysis evaluating which stocks have the greatest influence on the [exploitation rates](#ER) of key stocks of concern.
2. A comparison of fishery [adipose mark](#M) rates from sampling to [FRAM](#FRAM) estimated [mark rates](#MR).
3. A comparison of contemporary [exploitation rates](#ER) to [base period](#BP) derived exploitation rates
4. Investigation of potential pathways to updating the existing base-period.<br>
**The R computer code for this project as well as supporting data files are located on [GitHub](https://github.com/PSC-CoTC/coho_CWT_analysis). Many data tables can also be downloaded directly from the tables in the [Appendix](#A).**
```{r}
# focal_cols_recs <- c("recovery_id", "tag_code", "run_year", "recovery_location_code", "recovery_location_name", "fishery", "gear", "estimated_number")
#
# rmis_recs<-purrr::map_dfr(
# list.files(dir_proj, full.names =T)
# ,
# ~readr::read_csv(.x,col_select = all_of(focal_cols_recs))
# )
# #write.csv(rmis_recs, "C:/Data/CoTC/SouthernFund/2019/ERAnalysis/rmis_recov_86_20.txt")
#
# # get unique tag codes to query RMIS releases
#
# unique.tc<- unique(rmis_recs$tag_code) #12937 unique codes
# # split into two groups, because RMIS does not accept more than 10000 records
# top<-length(unique.tc)
# unique.tc1<-unique.tc[1:6000]
# unique.tc2<-unique.tc[6001:top]
# setwd("C:/Data/CoTC/SouthernFund/2019/ERAnalysis/")
#
# write(unique.tc1, "utc1.txt")
# write(unique.tc2, "utc2.txt")
#
# focal_cols_rel <- c("tag_code_or_release_id", "brood_year", "release_location_name", "hatchery_location_name", "stock_location_name", "release_location_state", "release_location_rmis_region", "release_location_rmis_basin", "cwt_1st_mark", "cwt_1st_mark_count", "cwt_2nd_mark", "cwt_2nd_mark_count")
#
# rmis_rel<-map_df(
# c(
# "https://www.rmis.org/reports/CSV6577.txt",
# "https://www.rmis.org/reports/CSV7053.txt"
# ),
# #~read.csv(.x)
# ~readr::read_csv(.x,col_select = all_of(focal_cols_rel))
# )
#
# #add area aggregation column to releases rmis_rel$Region
# rmis_rel$Region<-rmis_rel$release_location_state
# attach(rmis_rel)
# rmis_rel$Region<-case_when(is.na(release_location_state) ~ "PS",
# release_location_state=="BC" ~ "BC",
# release_location_state=="AK" ~ "AK",
#
# release_location_rmis_region =="CECR" | release_location_rmis_region =="CRGN"|
# release_location_rmis_region =="LOCR" | release_location_rmis_region =="UPCR"~ "Col R",
#
# release_location_rmis_region =="HOOD" | release_location_rmis_region =="JUAN"|
# release_location_rmis_region =="MPS" | release_location_rmis_region =="NOWA"|
# release_location_rmis_region =="NPS" | release_location_rmis_region =="SKAG"|
# release_location_rmis_region =="SPS" ~ "PS",
#
# release_location_rmis_region =="GRAY" | release_location_rmis_region =="NWC"|
# release_location_rmis_region =="WAGN" | release_location_rmis_region =="WILP" ~ "Coastal",
#
# release_location_rmis_region =="SOOR" | release_location_rmis_region =="KLTR"|
# release_location_rmis_region =="NOCA" ~ "SONCC",
# release_location_rmis_region =="NOOR" | release_location_rmis_region =="ORGN"
# ~ "OR,CA,SNAK",
# release_location_rmis_region =="CECA" | release_location_rmis_region =="SAFA"
# ~ "OR,CA,SNAK",
# release_location_rmis_region =="SNAK" ~ "OR,CA,SNAK"
# )
#
# #write.csv(rmis_rel, "RMIS_RelforUTC.txt")
# # join release and recovery table
# rmis_recs2<-left_join(rmis_recs,rmis_rel, by = c("tag_code" = "tag_code_or_release_id"))
# # eliminate unmarked
# rmis_recs3<-rmis_recs2[,c(-18,-19)]
# rmis_recs4<-rmis_recs3[rmis_recs3$cwt_1st_mark>4999,]
# rmis_recs4<-rmis_recs4[!is.na(rmis_recs4$run_year),]
#
# # #plot by region and year
# # rmis_recs4|>
# # count(run_year, Region)|>
# # ggplot(aes(run_year, n,fill = Region)) +
# # geom_col(show.legend = F) +
# # facet_wrap(~Region, ncol=1)
# # map to fisheries
#
# fish_agg<-read.csv("fishaggmap_no_fw.txt") #freshwater not mapped in file and hence excluded"
# # loop through each row in fish_agg
# # find all the records in rmis_recs4 that have a matching location and gear code
# # assign FishID to these records
# rmis_recrel<-rmis_recs4%>%
# add_column (FishID = 0, FishName = 0)
#
#
# x<-nrow(fish_agg)
#
# for(i in 1:x) {
# # if (i > 31) {
# # browser()
# # }
# locc<-fish_agg[i,4]
# gearc<-fish_agg[i,3]
# FishID2<-fish_agg[i,1]
# FishName2<-fish_agg[i,2]
# i=i+1
# #find all the records in rmis_recrel with matching gear and location codes
# # update FishID and FishName fields to FishID and FishName
# l<-nchar(locc)
# if (gearc == 5){
# rmis_recrel<-within(rmis_recrel,FishID[floor(fishery/10) ==gearc ]<-FishID2)
# } else {
# rmis_recrel<-within(rmis_recrel,FishID[floor(fishery/10) ==gearc & substr(recovery_location_code,start=1,stop=l) ==locc]<-FishID2)
# }
# }
#
# #rm(list=ls())
# #populate FishName field through look-up in fish_agg table
# rmis_recrel$FishName <-fish_agg[match(rmis_recrel$FishID,fish_agg$Fish_ID),2]
# rmis_recrel_fish<-rmis_recrel[!rmis_recrel$FishID==18,]
# rmis_recrel_esc<<-rmis_recrel[rmis_recrel$FishID==18,]
# #recrel_test<-rmis_recrel[1:20000,c(4,6,8,19,20)]
# #write.csv(recrel_test,"RecrelTest.txt")
#
# #plot number of fishery recoveries by year for each region as stacked fishery bar graph
# #plot number of escapement recoveries by year for each region
#
# a<-rmis_recrel_fish|>
# count(run_year,Region,FishName)|>
# filter(!is.na(FishName))
# plot1<-ggplot(a,aes(run_year,n,fill = FishName)) + geom_col() +
# ggtitle("Marine Fishery CWTs by Stock Origin and Year")+
# labs(y="CWT_Fisheries")+
# facet_wrap(~Region, ncol = 1)+
# theme(legend.position="none")
#
# b<-rmis_recrel_esc|>
# count(run_year,Region)
# plot2<-ggplot(b,aes(run_year,n, fill = "darkred")) + geom_col() +
# theme(legend.position = "none")+
# ggtitle("Escapement CWTs by Stock Origin and Year")+
# labs(y="CWT_Escapement")+
# facet_wrap(~Region, ncol = 1)
# #arrange escapement and fisheries plots side-by-side
# require(gridExtra)
# plot3<-grid.arrange(plot1, plot2, ncol=2)
# ggsave("cwtsovertime.png", plot=plot3, height=7, width=10)
```
\newpage
# Data Preparation
## Assigning Coded-Wire-Tagged Groups to [FRAM](#FRAM) Model Stocks {#SM}
This section describes the steps taken to identify and map available Coho salmon [CWTs](#CWT) to the stocks in [FRAM](#FRAM). All available Coho salmon release and recovery data were downloaded from the Regional Mark Processing Center [(RMIS)](https://www.rmis.org/cgi-bin/queryfrm.mpl?Table=catch_sample&Version=4.1) in July of 2020 and uploaded into a Microsoft Access Database called 'MappingDatabase.mdb'. A total of 17,268 CWT groups were downloaded and ranged from brood year 1969 to 2019. After the raw data were loaded, the following steps were taken to create the stock assignments:
1. Mark Status was determined for each [CWT](#CWT) group released. Release and recovery data were examined to determine the intended mark status of each of the CWT release groups. For release groups identified as being marked, the estimated number of CWTs recovered from fisheries were summarized by 'recorded_mark' and compared to the mark type listed under 'cwt_1st_mark'. The CWT was flagged for further review if more than 20% of the fishery recoveries were identified as having a different mark than what was listed in the release data. Final review of all of these flagged CWTs yielded a total of 15 tag codes with the intended mark type differing from the mark type listed under 'cwt_1st_mark' (see Appendix Table [8.4](#WrongClip) for the list of these tags). A table called 'CWT_1st_mark_fixes' was created in the Access database and a query titled 'Step1- Fix CWT_1st_Mark value' was used to update the release data that was downloaded from [RMIS](#RMIS) into the database to correct the 'cwt_1st_mark'.
2. Releases were grouped and assigned to Production Regions (PRs) and Management Units (MUs). To streamline assigning release groups to PRs and MUs, a list of unique combinations of the following data was generated and saved in a table titled '[RMIS](#RMIS)_UniqueReleaseCodes' within the Access database:
- `release_location_state`
- `release_location_rmis_region`
- `release_location_rmis_basin`
- `release_location_name`
- `hatchery_location_name`
- `stock_location_name`<br>
This table, consisting of a total of 2,058 unique combinations, was then copied to a table titled 'RMIS_UniqueReleaseCodesMapped' and a column containing the assigned PR and another containing the MU were added. Production Regions and Management Units were manually assigned to each unique record. An example of a unique combination within the 'RMIS_UniqueReleaseCodesMapped' table that was mapped to a PR and an MU is below. See Appendix [Table 8.6](#StkMap) for a list of mapped [CWT](#CWT) codes and Appendix [Table 8.5](#CoPRMU) for a list of Coho Production Regions and Management Units[.]{#Unique}
```{r t41, results ='asis'}
tibble(
`release location state` = "AK",
`release location rmis region` = "ALSR",
`release location rmis basin` = "ALSRG",
`hatchery location name` = "NA",
`stock location_name` = "AKWE R",
`release_location name` = "AKWE R 182-40",
`PR` = "Northern Alaska Outside",
`MU` = "Alaska Northern Outside Hat/Wild",
) |>
gt::gt() |>
gt::tab_header(title = "Table 3.1. Unique Release Codes Mapped")
```
<br>
3. Assign MUs to the Columbia River releases. The Columbia River Production Region consists of two types of Coho Salmon: South or Early returning stocks (also known as A-Type or fall type run) and North or Late returning stocks (also known as B-Type or late-fall run). While there is a field in [RMIS](#RMIS) that provides the run type, this data was missing for many of the releases. Over 1,500 [CWT](#CWT) releases within the Columbia River Basin did not have a run type associated with them. Because of this, a summary of these tag codes was provided to Eric Kinne and Jillian Cady of WDFW to review. They provided MU assignments for the CWTs with blank MUs and confirmed all the preliminary assignments for the remaining records. This resulted in the following assignments summarized by MU, and an Access query updated all the Columbia River CWTs with these newly assigned MUs[.]{#ColRStk}
```{r t42, results ='asis'}
tibble(
`Management Unit` = c("Columbia River Early Hatchery", "Columbia River Late Hatchery", "Lower Col R Oregon Wild","Wash Early Wild","Wash Late Wild","Youngs Bay Hatchery", "Grand Total"),
`Number of CWTs Released` = c(1430,594,9,114,25,836,3008)
) |>
gt::gt() |>
gt::cols_label(.list = list(`Management Unit` = gt::md("**Management Unit**"),
`Number of CWTs Released` = gt::md("**Number of CWTs Released**")))|>
gt::tab_style(
style = gt::cell_text(weight = "bold"),
locations = gt::cells_body(columns = everything(), rows=7))|>
gt::tab_header(title = "Table 3.2. Columbia River Stock Assignments and Numbers Released")
```
<br>
4. Assigned PRs and MUs were used to map [coded wire tag](#CWT) codes to [FRAM](#FRAM) stocks through a look-up table with the following fields[:]{#StkCWT}
<br>
```{r t43, results ='asis'}
tibble(
`Run ID` = 9,
`PR Number` = 16,
`PR MU Number` = 0,
`CWT Code` = 011044,
`Number Released` = 1000,
`Release name` = "BURNT HILL CR (OPSR)",
`Hatchery name` = "ORE-PAC SALMON RANCH",
`Stock Name` = "NESTUCCA R PRIVATE",
`brood year` = 1995
) |>
gt::gt() |>
gt::tab_header(title = "Table 3.3. Stock CWT 1998")
```
<br>
The look-up file to map [RMIS](#RMIS) recoveries to [FRAM](#FRAM) stocks is included on the [GitHub site](https://github.com/PSC-CoTC/coho_CWT_analysis/blob/main/lu_cct_MSM_Stock_CWT_20220913.csv) for this project.
## Assigning Coded-Wire-Tagged Recoveries to [FRAM](#FRAM) Fisheries {#FM}
Coho [FRAM](#FRAM) contains [198 fisheries](#F) for complete West-Coast-wide Coho fishery coverage. [FRAM](#FRAM) fisheries are assigned by geographic areas and gear type. Generally, geographic fishing areas overlap with important management boundaries. Fisheries in the same geographic area are usually divided into troll, net, and sport fisheries. Frequently, treaty (first nations) and non-treaty (all citizen) fisheries are also separated into discrete fisheries. An assignment of [RMIS](#RMIS) [CWT](#CWT) recovery information to [FRAM](#FRAM) fisheries is usually possible by examining [RMIS](#RMIS)' `fishery` and `recovery_location_code` fields. [RMIS](#RMIS) `fishery` coding specifies the gear type, while the `recovery_location_code` designates a geographic area. [RMIS](#RMIS) contains 90 unique `fishery` codes and approximately 5,000 unique `recovery_location_codes`, potentially designating tens of thousands of unique fisheries. A 19-character location code strip is used by all parties to the [Pacific Salmon Treaty](#PST) to geographically identify locations (see [Lapi et al. 1989](#Lapi1)). Assignments of [RMIS](#RMIS) recoveries to [FRAM](#FRAM) fisheries are accomplished through a mix of a look-up on 'fishery' and 'recovery_location_code' fields and some coded logic. The coded logic relies on the hierarchical nature of the `recovery_location_code`, where the location code string narrows down the geographic area going from left to right in the coded sequence, e.g., the first character specifies the state or country, the second freshwater or marine, the third the management region, etc. When developing the look-up, the analyst determines the minimum number of `recovery_location_code` characters needed to make a distinct [FRAM](#FRAM) location assignment. A similar approach is taken to make [FRAM](#FRAM) gear assignments from the [RMIS](#RMIS) `fishery` field, e.g., a `fishery` code between 40 and 49 identifies a sport fishery. Recoveries with a `fishery` code between 50 and 59 are automatically assigned to escapement. Thus, the final fishery look-up table contains only 537 records. This is possible because the R code developed to map to FRAM fisheries truncates the `recovery_location_code` sequence to just the characters needed to make a unique [FRAM](#FRAM) fishery assignment, significantly reducing the number of possible permutations. The look-up file is included on the [GitHub site](https://github.com/PSC-CoTC/coho_CWT_analysis/blob/main/lu_ahb_FishMap_20220826.csv) for this project.
## Data Issues
Despite the dedication of staff involved in data collection and management across organizations, the sheer number of records involved in constructing and populating a coast-wide model of salmon harvest means that problems will arise. The following briefly describes some of the major issues related to data acquisition and preparation that were encountered during this project. Some concerns cannot be remedied (e.g., past year fisheries cannot be retrospectively sampled), but further collective review efforts may improve the quality of key [FRAM](#FRAM) datasets and thereby any inferences based on model runs. In particular, we observed a need to ensure recent time-series of post-season runs reflect current catch and escapement estimates, some of which appear to have changed since being originally compiled.
Reported catch values are essential inputs to post-season [FRAM](#FRAM) and are critical to computing [CWT](#CWT) expansions. This project was impacted by inaccurate, uncertain, and missing values in catch reporting and accounting, and by extremely low or no sampling in some fisheries. In several instances, the modeled landed catch within [FRAM](#FRAM) did not match the catch reported to [RMIS](#RMIS)' Catch/Sample data, and mismatches persisted even after fisheries mapping issues were ruled out. Further investigation showed that official catch estimates were updated in [RMIS](#RMIS) after the [CoTC](#CoTC) completes the annual [ER](#ER) analyses using [BkFRAM](#BkFRAM). Therefore, we suggest annually re-querying and updating the most current 2-3 years to populate [BkFRAM](#BkFRAM). We also suggest similar procedures for catches reported to [RMIS](#RMIS).
Just as catches, stock specific escapements are also essential inputs to post-season [FRAM](#FRAM) to reconstruct pre-fishing cohort abundances. Missing and uncertain estimates of escapements related to lack of sampling and/or reporting hindered the number of ER comparisons that were possible. Another source of escapement error originates from inputs to [BkFRAM](#BkFRAM) runs. The [BkFRAM](#BkFRAM) option to apply [mark rates](#MR) (often from pre-season forecasts) to total (marked + unmarked) escapements has the potential to create inaccuracies in stock-specific and potentially whole fishery [mark rates](#MR), such as those assessed in this project. We recommend further review of [mark rate](#MR) estimates by regional experts, with special attention to instances where post-season escapement estimates are not provided by mark status.
Accurate sampling data is critical for the integrity of the [CWT](#CWT) system, execution of mark-selective fisheries, production of [mark rate](#MR) and catch estimates, and collection of biological information. Hundreds of dedicated samplers annually collect these data, often under difficult circumstances. Several factors can lead to inaccurate results such as sampler error, equipment failure, sampling stratification that differs from fishery stratification, low sampling rates, etc. We encountered many instances where sampling was inadequate, relied on voluntary tag recoveries, or was conducted without electronic CWT detection equipment. Additionally, some fisheries, even if well sampled, exhibited highly improbable mark or tag rates.<br>
Since sampling is the backbone of collecting CWT information which flows into [exploitation rate](#ER) estimates, poor sampling can have a very detrimental effect on this type of analysis.<br>
Perhaps a feedback loop between RMIS and sampling programs could address some of these shortcomings by providing sampling supervisors with annual [RMIS](#RMIS) summary reports of sampling rates, CWT recoveries, and [mark rates](#MR).
### [RMIS Data](#RMIS)
This project relied heavily on [RMIS](#RMIS) which houses a vast amount of information associated with [CWTs](#CWT). The complexity of these data creates considerable risk of misinterpretation, and this project underscored the importance of [RMIS](#RMIS) providing explanatory materials and training sessions to reduce this risk.
[RMIS](#RMIS) release data contains information about all salmon released from hatcheries as well as wild fish that were caught and marked or tagged prior to release. The [exploitation rate](#ER) analyses were conducted solely on [adipose-fin-clipped (marked)](#M) and [coded-wire-tagged](#CWT) fish. However, some of the salmon with tag codes from marked releases were assessed to be predominantly unmarked by field samplers. Either the tag codes were assigned the wrong mark status or the adipose clip was insufficient. Other problems encountered in the release data were optional fields left blank that would have allowed us to much more easily assign [CWTs](#CWT) to [FRAM](#FRAM) stocks. For example, the optional and often blank "Run" data field was needed to easily designate a Columbia River or WA Coast Coho stock as a "Summer" or "Fall" run or "Early" versus "Late".
Every salmon recovered with a [coded-wire tag](#CWT) (and subsequently decoded and reported) is a data record in the recovery database. This database contains many fields with fairly complex flagging options. There are a number of pitfalls that can lead an uninformed user to the wrong conclusions. For the database containing recovery data in particular, user training is highly recommended. In addition to the complexity of the database, deficiencies encountered in the recovery data were often caused by sampling issues. The principal concerns with this database are problematic [CWT](#CWT) expansions (see next bullet) and/or missing recoveries. Some entities fail to report CWT recoveries to [RMIS](#RMIS), sometimes resulting in entire fisheries and escapements missing from the database. In the case of missing escapements this can leave a large amount of uncertainty when conducting cohort reconstructions or [exploitation rate](#ER) analyses. We also found many instances of errors in recovery data fields, such as the `adclip_selective_fishery` field, where mark-selective fisheries (S) were incorrectly flagged as non-selective (N).
The Catch/Sample data is vital to the recovery data as [coded-wire-tag](#CWT) sampling expansions are calculated from the data. Inaccurately or non-reported catches or escapements can have a huge impact on [CWT](#CWT) analyses. Additionally, the stratification used in [RMIS](#RMIS) can be problematic. Generally, [RMIS](#RMIS) data is stratified by management or statistical weeks and months, while fisheries are commonly scheduled on a calendar month basis. This can result in miss-alignment of strata. Moreover, un-sampled strata can lead to missing CWT expansions (see [Handling of RMIS Catch/Sample data](#Handling)), and hence missing expanded recoveries.
### [MSM](#MSM) User Guide and Code Documentation
The [Mixed Stock Model](#MSM) was rewritten in Visual Basic in 2007. Although the document ["Coho FRAM Base Development"](#Pac1) describes the project, the current [MSM](#MSM) lacks code documentation and a user guide, thus requiring a great deal of initiative by a new user to understand the code, the data requirements, and re-(run) analyses. A draft [user guide](#MSMGuide) of the [MSM](#MSM) was developed during the early stages of this project.