## ----knitr_setup, include = FALSE, echo=FALSE---------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

## ----load_packages, message=FALSE, warning=FALSE------------------------------
library(aquacultuR)
library(magrittr)
library(dplyr)
library(tidyr)
library(lubridate)

## ----options------------------------------------------------------------------
oldopts <- options()
options(digits = 3)

## ----samplings_data-----------------------------------------------------------
head(samplings)

## -----------------------------------------------------------------------------
head(water_params)

## ----prepare_growth_data------------------------------------------------------
df <- samplings %>%
  mutate(timepoint = case_when(
    date == ymd("2023-03-16") ~ "beginning",
    date == ymd("2023-04-14") ~ "end",
    .default = NA
  )) %>%
  group_by(tank, timepoint, sample_type) %>%
  summarise(mean_weight = mean(fish_weight),
            sd_weight = sd(fish_weight)) %>% 
  print()

## ----growth_wide--------------------------------------------------------------
df <- df %>%
  select(-sample_type, -starts_with("sd")) %>%
  pivot_wider(
    names_from = timepoint,
    values_from = c(mean_weight),
    names_vary = "slowest"
  ) %>%
  mutate(duration = as.numeric(max(samplings$date) - min(samplings$date))) %>% 
  print()

## ----calculate_growth_metrics-------------------------------------------------
df %>%
  group_by(tank) %>%
  mutate(
    absolute_growth = ag(ibw = beginning, fbw = end),
    relative_growth = rg(ibw = beginning, fbw = end),
    absolute_growth_rate = agr(ibw = beginning, fbw = end, duration),
    specific_growth_rate = sgr(ibw = beginning, fbw = end, duration)
  )

## -----------------------------------------------------------------------------
df %>%
  group_by(tank) %>%
  mutate(
    geometric_bodyweight = gbw(ibw = beginning, fbw = end),
    relative_growth_rate_geom = rgr(
      ibw = beginning,
      fbw = end,
      duration,
      mean_fun = "geometric"
    ),
    relative_growth_rate_arith = rgr(
      ibw = beginning,
      fbw = end,
      duration,
      mean_fun = "arithmetic"
    )
  )

## ----calculate_tgc------------------------------------------------------------
# 1. calculate mean temperature 
# 2. join into growth data
# 3. calculate TGC
water_params %>%
  group_by(tank) %>%
  summarise(temp = mean(temp)) %>%
  right_join(df, join_by(tank)) %>%
  mutate(
    thermal_growth_coefficient = tgc(
    ibw = beginning,
    fbw = end,
    duration = duration,
    temp = temp
  ))

## ----show_session_info--------------------------------------------------------
sessionInfo()

## ----reset_options------------------------------------------------------------
options(oldopts)

