```{css zoom-lib-src, echo = FALSE}
script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"
```

```{js zoom-jquery, echo = FALSE}
 $(document).ready(function() {
    $('body').prepend('<div class=\"zoomDiv\"><img src=\"\" class=\"zoomImg\"></div>');
    // onClick function for all plots (img's)
    $('img:not(.zoomImg)').click(function() {
      $('.zoomImg').attr('src', $(this).attr('src')).css({width: '100%'});
      $('.zoomDiv').css({opacity: '1', width: 'auto', border: '1px solid white', borderRadius: '5px', position: 'fixed', top: '50%', left: '50%', marginRight: '-50%', transform: 'translate(-50%, -50%)', boxShadow: '0px 0px 50px #888888', zIndex: '50', overflow: 'auto', maxHeight: '100%'});
    });
    // onClick function for zoomImg
    $('img.zoomImg').click(function() {
      $('.zoomDiv').css({opacity: '0', width: '0%'}); 
    });
  });
```

```{r setup, include=FALSE}
assessment_dir <- normalizePath(
  file.path(dirname(knitr::current_input(dir = TRUE)), "..", "..", "assessment"),
  winslash = "/"
)
knitr::opts_knit$set(root.dir = assessment_dir)
knitr::opts_chunk$set(warning=F, message=F, echo=F, results=F,fig.width=6, fig.height=5)
```

```{r}
library(jjmR)
library(tidyverse)
library(kableExtra)
library(ggthemes)
library(patchwork)
library(here)

geth <- function(mod,h=hyp) paste0(h,"_", mod)

```

# Chile's New Age Data ("Validacion")

Model      | Description
-----------|--------------
**Models 0.x**| **Data introductions**
1.01     | As 1.00 but use revised data series "antiguo" of age composition and weight at age data for both Chilean fisheries and both Chilean acoustic surveys (assessment/NewAgeData/AgeDataInAssessment.csv)
1.02     | As 1.01 but incorporate revised (validated) age data for surveys and fleets with M and maturity updated (M=0.35) (NOT RUN)
1.03     | As 1.02 but M=0.45 (NOT RUN)


```{r}
dat.acousN.nue <- read_csv(file.path("data", "SC09_AcousN_Nuevo.csv")) %>%
                      janitor::clean_names() %>%
                      mutate(numbers_at_age=as.numeric(str_remove_all(replace_na(numbers_at_age,0)," ")),
                              total_biomass=replace_na(total_biomass,0)) %>%
                      filter(age>0) %>%
                      rename(catch_no=numbers_at_age,
                              avg_wt=mean_weight,
                              catch_wt=total_biomass) %>%
                      mutate(fleet_type="survey",
                              fleet=1,
                              age=as.numeric(str_extract(age, "[0-9]+")),
                              method="validacion") %>%
                      select(-mean_length)

dat.f.new <- read_csv(file.path("data", "SC09_catchNumByFleet_newAgeMet.csv")) %>% 
                      select(-1,-`0`) %>%
                      mutate_all(replace_na,0) %>%
                      mutate(fleet=as.numeric(str_extract(fleet,"\\d"))) %>%
                      pivot_longer(-(year:fleet),names_to="age",values_to="catch_no") %>%
                      mutate(fleet_type="fishery", 
                              age=as.numeric(str_extract(age, "[0-9]+"))) %>%
                      left_join(
                        read_csv(file.path("data", "SC09_catchWtByFleet_newAgeMet.csv")) %>%
                        select(-1,-`0`)  %>%
                        mutate(fleet=as.numeric(str_extract(fleet,"\\d"))) %>%
                        pivot_longer(-(year:fleet),names_to="age",values_to="avg_wt") %>%
                        mutate(fleet_type="fishery", 
                                age=as.numeric(str_extract(age, "[0-9]+")),
                                method="validacion")
                    ) %>%
                      filter(fleet %in% 1:2) %>%

dat.chile <- read_csv(file.path("data", "NewAgeData", "All_Age_Data_Chile.csv")) %>%
              janitor::clean_names() %>%
              rename(year=ano,
                      fleet=macrozona,
                      age=grupo_edad,
                      catch_no=capt,
                      catch_wt=capt_ton,
                      method=criterio_lectura) %>%
              mutate(fleet_type=ifelse(grepl("acoustic",fleet),"survey","fishery"),
                      fleet=as.numeric(str_extract(fleet, "[0-9]+"))) %>%
              group_by(fleet,method,year,age,fleet_type) %>%
              summarise(catch_no=sum(catch_no), 
                        catch_wt=sum(catch_wt),
                        avg_wt=1e3*catch_wt/catch_no) %>%
              ungroup() %>%
              filter(age!=0) %>%
              complete(age, nesting(fleet, method, year, fleet_type)) 

mods2compare <- c("1.01","1.02","1.03")
Validacion <- compareModels(geth(mods2compare,"h1"))

dat.ass <- readJJM(geth("1.00","h1"), path = "config", input = "input")[[1]]$data

dat.ass.f <- dat.ass$Fagecomp[,,1] %>% bind_rows(dat.ass$Fagecomp[,,2])
				rownames_to_column(var="year")

```

* Updated age composition and weight at age for Chile_SC and Chile_N fleets, and also for AcousCS and AcousN surveys
* Sample sizes remained the same
* Current year is downweighted, as usual
* Natural Mortality updated to 0.35 (per the data workshop)
* Maturity at age was not provided, so the values for the FarNorth stock under the two-stock hypothesis were used.
* Population weight at age was uncertain. The validacion data were pooled across years (summed catch numbers at age multiplied by catch weight at age divided by summed catch numbers at age), and the mean weights at age were calculated in the interim.
* Code for this setup is shown in `SC09.R`.

## Data Exploration


## Single-stock hypothesis {.tabset}
### Biomass
```{r}
plot(Validacion,combine=T,what="biomass",stack=F,main="Biomass")
```

### Recruitment
```{r}
plot(Validacion,combine=T,what="recruitment",stack=F,main="Recruitment")
```

### Fishing Mortality
```{r }
plot(Validacion,combine=T,what="ftot",stack=F,main="Total Fishing Mortality")
```

## Two-stock hypothesis {.tabset}
### Biomass
```{r}
Validacion <- compareModels(geth(mods2compare,"h2"))

plot(Validacion,combine=T,what="biomass",stack=F,main="Biomass")
```

### Recruitment
```{r}
plot(Validacion,combine=T,what="recruitment",stack=F,main="Recruitment")
```

### Fishing Mortality
```{r}
plot(Validacion,combine=T,what="ftot",stack=F,main="Total Fishing Mortality")
```

# Things Missing
* Maturity-at-age estimates
* An overall population weight at age
* Some years of data seem to be missing
