6-Growth_Calibration.Rmd 14.2 KB
Newer Older
Poulet Camille's avatar
Poulet Camille committed
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
---
title: "Growth Calibration"
author: "Camille POULET"
date: "23/02/2021"
output: word_document
---

```{r setup, include=FALSE}

knitr::opts_chunk$set(echo = FALSE, include = TRUE, 
                      warning = FALSE,
                      fig.cap = TRUE)

rm(list = ls())
```

```{r library, include=FALSE}
library(dplyr)
library(tidyr)
library(ggplot2)
library(readr)
library(XML)
library(forcats)
library(knitr)
library(officedown)
library(flextable)
library(stringr)
library(tictoc)
29
library(tibble)
Poulet Camille's avatar
Poulet Camille committed
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

```

```{r GR3D functions and data, include=FALSE, echo = FALSE}

source("../GR3D_Rdescription/GR3Dfunction.R")
source("../GR3D_Rdescription/GR3D_NEA_env_data.R")
source("../GR3D_Rdescription/GR3D_NEA_XML_parameters.R")

#source_rmd <- function(rmd_file){
#knitr::knit(rmd_file, output = tempfile())
#}

#source_rmd("NEAgrowth.Rmd")

#source(knitr::purl("NEAgrowth.Rmd", quiet=TRUE))

```

```{r Build the connections file with temperature experienced by fish according to their offshore basins, echo = FALSE, warning=FALSE}

#Overview of connections existing between summering and wintering offshore basins
connections %>% 
  distinct(wintering_offshore_basin_name,summering_offshore_basin_name) 

#Compute an average temperature experienced by juveniles during their life at sea according to connections files i.e. wintering and summering areas.

connections_trans <- connections %>% 
  dplyr::select(-c(wintering_offshore_basin_id,
                   summering_offshore_basin_id)) %>% 
  pivot_longer(cols = c("wintering_offshore_basin_name",
                        "summering_offshore_basin_name"),
               names_to = "offshore_basin_type", 
               values_to = "offshore_basin_name") %>% 
  select(inshore_basin_name, offshore_basin_name, offshore_basin_type) %>% 
  inner_join(tempInOffshore, by = c("offshore_basin_name" = "basin_name")) %>% 
  filter(between(year,  1981, 2010)) %>% 
  mutate(offshore_basin_type = as.factor(offshore_basin_type)) %>% 
  mutate(offshore_basin_type = fct_recode(offshore_basin_type, 
                                          "summering" = "summering_offshore_basin_name",
                                          "wintering" = "wintering_offshore_basin_name"))  %>% 
  pivot_longer(cols = contains('temperature'),  names_to = "season", values_to = "temperature") %>% 
  mutate(season = str_remove(season, "_sea_surface_temperature")) 

##Select the temperature experienced by fish during the corresponding season 
#in winter
wint<-connections_trans %>% 
  filter(season %in% c("winter","spring"), offshore_basin_type == "wintering") %>% 
  select(inshore_basin_name,offshore_basin_name,year,season,temperature) 

#in summer
sum<-connections_trans %>% 
  filter(season %in% c("summer","fall"), offshore_basin_type == "summering") %>% 
  select(inshore_basin_name,offshore_basin_name,year,season,temperature)

#Combine the two files to build a summary dataframe
tempEffectInOffshore <- bind_rows(wint,sum) %>% 
87
88
89
90
91
  ungroup() %>% 
  arrange(inshore_basin_name, year,season) %>%
  group_by(inshore_basin_name,offshore_basin_name,season) %>% 
  summarise(Tmean = mean(temperature))
#mutate(temperatureEffect = temperatureEffect(Tmean, growPar$tempMinGrow, growPar$tempOptGrow, growPar$tempMaxGrow))
Poulet Camille's avatar
Poulet Camille committed
92
93
94
95
96
97

#delete intermediate files 

remove(sum,wint)


98
99
100
101
102

```

```{r Build the temperature expericenced by fish during their residency in river and inshore basins, echo = FALSE, warning=FALSE}

Poulet Camille's avatar
Poulet Camille committed
103
104
105
#TODO
#Contruire un tableau, du même style que celui-ci avec les temperatures du natal basins

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
#season = c("spring","summer","fall","winter")
#zone = c("river_tempertaure","inshore_temperature") 

tempEfffectInRiver <- tempInriver  %>% 
  pivot_longer(cols = contains('temperature'),  names_to = "season", values_to = "river_temperature") %>% 
  mutate(season = str_remove(season, "_river_temperature")) %>% 
  inner_join(tempInInshore %>% 
               pivot_longer(cols = contains('temperature'),  names_to = "season", values_to = "inshore_temperature") %>% 
               mutate(season = str_remove(season, "_inshore_temperature")),
             by = c("basin_id", "basin_name", "year","season")) %>% 
  filter(between(year,  1981, 2010)) %>% 
  pivot_longer(c("river_temperature", "inshore_temperature"), names_to = "zone", values_to = "temperature") 

#Optimzation
tempRiver <- tempEfffectInRiver %>% 
filter(season %in% c("spring","summer") & zone == "river_temperature")

tempInshore <- tempEfffectInRiver %>% 
filter(season %in% c("fall","winter") & zone == "inshore_temperature")


tempEffectInFreshWat <- bind_rows(tempRiver,tempInshore) %>% 
  arrange(basin_name,year,season) %>% 
  select(basin_name,year, season, temperature) %>% 
  group_by(basin_name,season) %>% 
  summarize(Tmean_RIB = mean(temperature)) 

# tempEfffectInRiver %>% 
#   {bind_rows(
#     filter(season == "summer" & zone == "river_temperature"),
#     filter(season == "fall" & zone == "inshore_temperature"))
#     }
 
Poulet Camille's avatar
Poulet Camille committed
139
140
```

141

Poulet Camille's avatar
Poulet Camille committed
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
The growth parameters used in GR3D give the following curves when random and temperature effects are not considered.

```{r, include = TRUE, fig.cap = "Growth curve without temperature effect"}

dfGrowth <- data.frame(age = seq(0,19.75,.25), season = c("spring","summer","fall","winter"), basin_name = 'reference') %>% 
  mutate(gender = 'male',
         L = vonBertalanffyGrowth(age, growPar$lengthAtHatching, growPar$linfVonBertForMale, growPar$kOptForMale)) %>% 
  bind_rows(select(.data = ., age, season, basin_name) %>%  
              mutate(gender = 'female',
                     L = vonBertalanffyGrowth(age, growPar$lengthAtHatching, growPar$linfVonBertForFemale, growPar$kOptForFemale)))

dfGrowth %>% filter(basin_name == 'reference') %>% 
  ggplot(aes(x = age)) + 
  geom_line(aes(y = L, linetype = gender, color = basin_name)) +
  labs( x = 'Age (year)', y = 'Fork length (cm)') 


```

To optimize the growth parameters included in GR3D for the Amercian shad, we used values gave by Stich et al, 2020. 

```{r Growth from Stich et al, 2020, echo = FALSE, warning=FALSE}

#function to compute L0 based on growth paramters from Stich et al. 
#K, Linf and t0 were provided for the three metapopulations.
#Linf is in millimeters.

vonBertalanffyLengthAtHatch = function(Linf, K, t0){
  
  L0 = Linf * (1-exp(t0*K))
  
  return(L0)
}

#vonBertalanffyTry(454,0.49,-0.21)

#parameters from Stich
Stich2020_sel <- read_csv("../NEA_calibration_offline/Stich_Table 9.csv") %>% 
  filter(parameter == "K" | parameter == "Linf"|parameter == "t0") %>% 
  dplyr::rename("catchment"="cachtment") %>% 
  select(parameter,catchment,mean) %>% 
  pivot_wider(names_from = parameter, values_from = mean) %>% 
  mutate(L0_theo = vonBertalanffyLengthAtHatch(Linf,K,t0)) %>% 
  mutate_at(vars(c(Linf,L0_theo)), funs(./10)) #from mm to cm

#create a data frame and compute L at age with values from Stich

growthInOffshore <- expand_grid(basin_name = nea_riverBasinFeatures$basin_name , age = seq(0,9.75,.25)) %>%
  mutate(season = case_when (
    (age - floor(age)) == 0.00 ~ 'spring',
    (age - floor(age)) == 0.25 ~ 'summer',
    (age - floor(age)) == 0.50 ~ 'fall',
    (age - floor(age)) == 0.75 ~ 'winter'
  )) %>% inner_join(nea_riverBasinFeatures %>% select(basin_name, lat_outlet), by ='basin_name') %>%
  select(basin_name, lat_outlet, age, season)%>% 
  mutate(metapop = case_when
         (lat_outlet < 33.8 ~ "semelparous",
           lat_outlet >=33.8 & lat_outlet <= 41.28793 ~ "southern iteroparous",
           lat_outlet > 41.28793 ~ "northern iteroparous")) %>% 
  inner_join(Stich2020_sel, by = c("metapop" = "catchment")) %>% 
  group_by(basin_name,metapop) %>% 
  mutate(LStich = vonBertalanffyGrowth(age, L0_theo, Linf, K)) %>% 
  ungroup()
205
206
207
208
209
210
211
212
213
214
215
216
217

growthInOffshore <-growthInOffshore %>% 
  inner_join(tempEffectInOffshore, by = c("basin_name" ="inshore_basin_name",
                                          "season")) %>% 
  right_join(tempEffectInFreshWat, by = c("basin_name","season"))

growthInOffshore<-growthInOffshore %>% 
  mutate(temperature = ifelse (season == "spring" & age == 0, Tmean_RIB,
                               ifelse(season == "summer" & age == 0.25, Tmean_RIB,
         ifelse(season == "fall" & age == 0.50, Tmean_RIB, Tmean)))) %>% 
  arrange(basin_name,age,season) %>% 
  select(basin_name,offshore_basin_name,metapop,age, season,temperature,LStich)

Poulet Camille's avatar
Poulet Camille committed
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
#group_by(metapop,age,season) %>% 
#summarize(LStich = unique(LStich))

```

```{r Growth in GR3D with temperature effect, echo = FALSE, warning=FALSE}

#define parameters for both sex based on value from the XML file 

growParModifed <- growPar %>% 
  transmute(tempMinGrow,tempMaxGrow,tempOptGrow, sigmaDeltaLVonBert,lengthAtHatching,
            kOpt = mean(c(kOptForFemale,kOptForMale)),
            Linf = mean(c(linfVonBertForFemale,linfVonBertForMale))) 

#merge the temperature effect to compute the relative VBGF 
#growthInOffshore<-growthInOffshore %>% 
234
235
#inner_join(tempEffectInOffshore %>% 
#select(inshore_basin_name,season,temperatureEffect), by =c("basin_name" ="inshore_basin_name", "season" ="season")) %>% 
Poulet Camille's avatar
Poulet Camille committed
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
#select(basin_name,lat_outlet, metapop,age,season,LStich, temperatureEffect)

```

```{r growth optimisation, echo = FALSE, warning=FALSE}
#vector on paramters to get optimized 
#par[1] = Tmin
#par[2] = Topt
#par [3] = Tmax
#par[4] = L0
#par[5] = Linf
#par[6] = k

vecPar = growParModifed %>% 
  select(tempMinGrow,tempOptGrow,tempMaxGrow,lengthAtHatching,Linf, kOpt) %>% 
  pivot_longer(tempMinGrow:kOpt, names_to = "parameter",values_to = "value") 

vecPar = as.vector(vecPar$value)

255
256
#Return data
computeGrowOpt = function(par,data){
Poulet Camille's avatar
Poulet Camille committed
257
258
259
260
261
262
  data <- data %>% arrange(age, basin_name) %>% 
    mutate(L = if_else(age == 0, par[4], 0))
  ages <- data %>% select(age) %>% distinct() %>% arrange(age) %>% unlist(use.names = FALSE)   
  
  
  data <- data %>% 
263
264
265
266
267
268
269
    arrange(basin_name,age, season) %>% 
    group_by(basin_name,age,season) %>% 
    mutate(temperatureEffect = temperatureEffect(temperature, 
                                                 Tmin = par[1],
                                                 Topt = par[2],
                                                 Tmax = par[3])) %>% 
    ungroup()
Poulet Camille's avatar
Poulet Camille committed
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
  
  for (i in 2:length(ages)) {
    previousAge  = ages[i - 1]
    currentAge = ages[i]
    tempEffect = data %>% filter(age == currentAge) %>% select(temperatureEffect) %>% unlist(use.names = FALSE)
    previousL <- data  %>% filter(age == previousAge) %>% select(L) %>% unlist(use.names = FALSE)
    
    currentL <- vonBertalanffyWithNextIncrement(L = previousL, 
                                                L0 = par[4], 
                                                Linf = par[5], 
                                                K = par[6],
                                                timeStepDuration = currentAge - previousAge, 
                                                sigma = 0, 
                                                tempEffect = tempEffect)
    data = data %>% mutate(L =replace(L, age == ages[i], currentL)) 
    
  }
  
288
289
290
291
292
293
294
295
296
297
298
  
  return(data)
}

#computeGrowOpt(vecPar,growthInOffshore)

#Function to be optimized 
computeSSE = function(par,data){
  
    data = computeGrowOpt(par,data)
    
Poulet Camille's avatar
Poulet Camille committed
299
  SSE = data %>% 
300
301
302
303
304
305
    group_by(metapop) %>% 
    mutate(W = 1/n()) %>% 
    ungroup() %>% 
    transmute(squareError = W * ((L - LStich)^2)) %>% 
    summarise(sumSquare = sum(squareError)) %>% 
    unlist()
Poulet Camille's avatar
Poulet Camille committed
306
307
308
309
310
  #ungroup() %>% 
  #select(sumSquare) 
  #summarize(sum = sum(sumSquare))
  
  #return(SSE = as.vector(SSE$sum))
311
  return(SSE)
Poulet Camille's avatar
Poulet Camille committed
312
313
}

314
315
#computeSSE (vecPar, growthInOffshore)

Poulet Camille's avatar
Poulet Camille committed
316
317
318

tic()
growth_optimal <- optim(c(Tmin = vecPar[1],
319
320
321
322
323
324
                          Topt = vecPar[2],
                          Tmax = vecPar[3],
                          L0 = vecPar[4],
                          Linf = vecPar[5],
                          K = vecPar[6]),
                        computeSSE, 
Poulet Camille's avatar
Poulet Camille committed
325
326
327
328
329
330
331
                        data = growthInOffshore,
                        lower = c(0,0,0,0,0,0),
                        method = "L-BFGS-B",
                        control = list(trace = TRUE, parscale = c(1,1,1,0.1,1,0.01)))

toc()

332
#Optimized parameters 
Poulet Camille's avatar
Poulet Camille committed
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
growParOptim <- data.frame(value = growth_optimal$par) %>% 
  rownames_to_column("parameter")

#Rdata
save(growth_optimal, file = "growth_optimal.RData")

#csv
write_csv(growParOptim, "growParOptim.csv")

```

```{r draw growth curves}

load("growth_optimal.RData")

348
growthCurves = computeGrowOpt(growth_optimal$par, growthInOffshore)
349
save(growthCurves, file = "growthCurves.RData")
Poulet Camille's avatar
Poulet Camille committed
350
351
352
353
354
355
356

#growth curve according to metapopulations 
growthCurves %>% 
  ggplot(aes(x = age)) + 
  geom_line(aes(y = L, col = metapop), linetype = "dashed") +
  geom_line(aes(y = LStich, col = metapop))+
  labs( x = 'Age (year)', y = 'Fork length (cm)', color = "Metapopulation (Stich)") +
357
358
359
  #scale_x_continuous(limits = c(0, 10)) +
  geom_hline(yintercept = 45, color = "pink", linetype =1)+ #female
  geom_hline(yintercept = 40, color = "lightblue", linetype = 1)+
360
361
  geom_vline(aes(age), xintercept = 8, linetype = 1)+
  facet_wrap(.~ metapop, ncol =1)
Poulet Camille's avatar
Poulet Camille committed
362
363
364
365
366

#temperature effect 
temp <- seq(0,45,0.1)

growthCurves %>% 
367
  ggplot(aes(x = temperature)) + 
Poulet Camille's avatar
Poulet Camille committed
368
369
370
371
372
373
374
375
376
377
  geom_line(aes(y = temperatureEffect)) +
  geom_jitter(aes(y = temperatureEffect, col = metapop))


#long fromat for growParOptim
growParOptim <-growParOptim %>% 
  pivot_wider(names_from = parameter, values_from = value)

df <- data.frame(temperature = temp,
                 temperatureEffect = temperatureEffect(temp,
378
379
380
                                                       growParOptim$Tmin,
                                                       growParOptim$Topt,
                                                       growParOptim$Tmax))
Poulet Camille's avatar
Poulet Camille committed
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

df %>% 
  ggplot(aes(x = temperature)) + 
  geom_line(aes(y = temperatureEffect)) +
  geom_point(aes(y = temperatureEffect), col = 'red', alpha = 0.4)

```


```{r growth try, echo = FALSE, warning=FALSE}

#k depending on water temperature in ofsshore basins 
kTempEffect = function(kopt, temp, Tmin, Topt, Tmax){
  
  kTemp <- kopt * temperatureEffect(temp, 
                                    Tmin, 
                                    Topt, 
                                    Tmax)
  
  return(kTemp)}

#Generic function
vonBertalanffyGrowthWithTempEffect = function(temp, age, L0, Linf, Kopt, Tmin, Topt, Tmax){
  
  
  koptTemp = kTempEffect(Kopt, temp, Tmin, Topt, Tmax)
  
  t0 = log(1 - L0 / Linf) / koptTemp
  
  return(Linf * (1 - exp(-koptTemp * (age - t0))))
}

```