---
author: "`r paste0('Biodose Tools', ' v', utils::packageVersion(pkg = 'biodosetools'))`"
date: "`r format(Sys.time(), '%d %B, %Y %H:%M:%S')`"
output:
  pdf_document:
    number_sections: true
    extra_dependencies: ["graphicx", "newpxtext", "newpxmath"]
header-includes:
  - \usepackage{titling}
  - \usepackage{booktabs}
  - \usepackage{tabularx}
  - \usepackage{float}
  - \usepackage{colortbl}
  - \pretitle{
    \vspace{-50pt}
    \includegraphics[width=2.0625in,height=0.5in]{`r system.file("/app/reports/logo.pdf", package = "biodosetools")`}\LARGE\\
    \begin{center}}
  - \posttitle{\end{center}}

params:
  fit_results_list: NA
  aberr_module: NA
---

```{r setup, include=FALSE}
library(dplyr)
library(ggplot2)
```

```{r parsed-title, include=FALSE}
aberr_module <- params$aberr_module

parsed_title <- dplyr::case_when(
  aberr_module == "dicentrics" ~ "Dicentrics curve fitting report",
  aberr_module == "translocations" ~ "Translocation FISH curve fitting report",
  aberr_module == "micronuclei" ~ "Micronuclei curve fitting report"
)
```

---
title: `r parsed_title`
---

```{r render-table-fn, include=FALSE}
render_table <- function(x, font_size = NULL, ...) {
  knitr::kable(x, format = "latex", booktabs = TRUE, ...) %>%
    kableExtra::kable_styling(
      position = "center",
      latex_options = "HOLD_position",
      font_size = font_size
    )
}
```

```{r load-data, echo=FALSE}
# General parameters
count_data <- params$fit_results_list[["fit_raw_data"]]
fit_model_statistics <- params$fit_results_list[["fit_model_statistics"]]
fit_model_summary <- params$fit_results_list[["fit_model_summary"]]
fit_coeffs <- params$fit_results_list[["fit_coeffs"]]
fit_var_cov_mat <- params$fit_results_list[["fit_var_cov_mat"]]
fit_cor_mat <- params$fit_results_list[["fit_cor_mat"]]
fit_formula_tex <- params$fit_results_list[["fit_formula_tex"]]
gg_curve <- params$fit_results_list[["gg_curve"]]
irr_conds <- params$fit_results_list[["irr_conds"]]
# detection_lims <- params$fit_results_list[["detection_lims"]]

# Translocations
genome_factor <- params$fit_results_list[["genome_factor"]]
chromosome_table <- params$fit_results_list[["chromosome_table"]]
trans_sex <- params$fit_results_list[["trans_sex"]]
frequency_select <- params$fit_results_list[["frequency_select"]]
```


`r if (aberr_module == "translocations") {"# Chromosome data"}`

`r if (aberr_module == "translocations") {
  paste("The analysed blood sample comes from a", trans_sex, "individual.")
}
`

```{r chromosome-table, echo=FALSE}
if (aberr_module == "translocations") {
  num_cols <- as.numeric(ncol(chromosome_table))

  chromosome_table %>%
    dplyr::mutate(
      dplyr::across(
        .cols = dplyr::everything(),
        .fns = function(x) {
          x <- ifelse(is.na(x) | x == "FALSE", "", x)
          x <- ifelse(x == "TRUE", "$\\checkmark$", x)
          return(x)
        }
      )
    ) %>%
    render_table(align = "c", escape = FALSE)
}
```

`r if (aberr_module == "translocations") {
  if (num_cols == 1) {
    "where each chromosome was stained using M-FISH."
  }
}`


# Count data used

```{r count-data, echo=FALSE}
data <- count_data %>%
  biodosetools:::fix_count_data_names(type = "count", output = "kable")

if ("$u$" %in% colnames(data)) {
  
  data$`$u$` <- kableExtra::cell_spec(
    x = data$`$u$`,
    background = ifelse(
      !is.na(data$`$u$`) & data$`$u$` > 1.96, 
      "#ffc0cb", 
      "white"
    )
  )
}

data %>%
  render_table(align = "c", escape = FALSE)
```


# Results

## Fit formula

`r paste0("$$", fit_formula_tex, "$$")`

## Model

`r gsub("<=", "$\\\\leq$", fit_model_summary)`

`r if (aberr_module == "translocations") {"## Translocation frequency"}`

`r if (aberr_module == "translocations") {
  paste("The fitting was performed using the ")
}
`
`r if (aberr_module == "translocations") {
  if (frequency_select == "full_gen_freq") {
    paste("full genome translocation frequency.")
  } else if (frequency_select == "measured_freq") {
    paste("translocation frequency measured by FISH.")
  }
}
`

`r if (aberr_module == "translocations") {"## Genomic conversion factor"}`

`r if (aberr_module == "translocations") {
  paste0("The genomic conversion factor to full genome is ", as.character(round(genome_factor, 3)), ".")
}
`

## Coefficients

```{r fit-coeffs, echo=FALSE}
fit_coeffs %>%
  formatC(format = "e", digits = 3) %>%
  biodosetools:::fix_coeff_names(type = "rows", output = "kable") %>%
  render_table(align = "c", escape = FALSE)
```

## Model-level statistics

```{r fit-model-statistics, echo=FALSE}
fit_model_statistics %>%
  formatC(format = "f", digits = 3) %>%
  as.data.frame() %>%
  dplyr::mutate(df = as.integer(df)) %>%
  render_table(align = "c")
```

## Correlation matrix

```{r fit-cor-mat, echo=FALSE}
fit_cor_mat %>%
  biodosetools:::fix_coeff_names(type = "rows", output = "kable") %>%
  biodosetools:::fix_coeff_names(type = "cols", output = "kable") %>%
  formatC(format = "f", digits = 3) %>%
  render_table(align = "c", escape = FALSE)
```

## Variance-covariance matrix

```{r fit-var-cov-mat, echo=FALSE}
fit_var_cov_mat %>%
  biodosetools:::fix_coeff_names(type = "rows", output = "kable") %>%
  biodosetools:::fix_coeff_names(type = "cols", output = "kable") %>%
  formatC(format = "e", digits = 3) %>%
  render_table(align = "c", escape = FALSE)
```

## Irradiation conditions

```{r irr-conds, echo=FALSE}
data.frame(
  matrix(
    unlist(irr_conds),
    nrow = length(irr_conds),
    byrow = TRUE
  )
) %>%
  `colnames<-`(c("Characteristic", "Details")) %>%
  dplyr::mutate(
    Details = ifelse(Details == "", "Not specified", Details)
  ) %>% 
  render_table(align = "l", linesep = "\\midrule") %>%
  kableExtra::column_spec(1, width = "4.5cm") %>%
  kableExtra::column_spec(2, width = "10cm")
```

## Curve plot

```{r gg-curve, echo=FALSE, fig.width=6, fig.height=3}
gg_curve
```
