
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE, error = FALSE)
```

# Import of Data

We import the data and select the variables needed for the analysis.
```{r}
load(paste0(params$filename, "_Data.RData"))
tmp <- strsplit(params$formula, " ~ ")[[1]]

y.var <- names(unlist(sapply(colnames(CalibrationData), 
                             grep, x = tmp[1])))
x.var <- names(unlist(sapply(colnames(CalibrationData), 
                              grep, x = tmp[2])))

if (!is.null(params$subset)) {
  calData <- subset(CalibrationData, eval(parse(text = params$subset)))
} else {
  calData <- CalibrationData
}
calData <- calData[,c(y.var, x.var)]
calData
```


# Model

We will apply the following model.
```{r}
params$formula
```


# Analysis

We now fit (simple) linear model.
```{r}
fit <- lm(as.formula(params$formula), data = calData)
summary(fit)
```

We determine the inverse of the fitted model.
```{r}
ab <- coef(fit)
predFunc <- function(newdata){}
body(predFunc) <- substitute({ with(newdata, (eval(y)-a)/b) }, 
                             list(y = parse(text = tmp[1]), 
                                a = ab[[1]], 
                                b = ab[[2]]))
```

We plot the given concentrations against the fitted values.
```{r, warning=FALSE}
library(ggplot2)
modelPlot <- ggplot(calData, aes(x = .data[[params$concVar]],
                                 y = !!rlang::parse_expr(tmp[1]))) +
            geom_point() + geom_smooth(method = "lm") +
            annotate("text",  x=-Inf, y = Inf,
            label = paste0("R² = ", signif(summary(fit)$r.squared, 3),
                           ", adj. R² = ", signif(summary(fit)$adj.r.squared, 3)),
            vjust=1, hjust=0, size=5)
modelPlot
```

# Computation of LOB, LOD and LOQ

We compute limit of blank (LOB), limit of detection (LOD) and limit of 
quantification (LOQ) by inverting the regression fit. We get the LOB by inverting 
the upper bound of the one-sided 95\% confidence interval at concentration $0$. 
In case of LOD, the upper-bound of the 99.95\% confidence interval at 
concentration $0$ is inverted. LOQ is determined as $3\times\textrm{LOD}$.
```{r}
if(ab[2] > 0){
  LOB <- (confint(fit, parm = 1, level = 0.90)[2]-ab[1])/ab[2]
  LOD <- (confint(fit, parm = 1, level = 0.999)[2]-ab[1])/ab[2]
}else{
  LOB <- (confint(fit, parm = 1, level = 0.90)[1]-ab[1])/ab[2]
  LOD <- (confint(fit, parm = 1, level = 0.999)[1]-ab[1])/ab[2]
}
names(LOB) <- "LOB"
names(LOD) <- "LOD"
LOQ <- 3*LOD
names(LOQ) <- "LOQ"
LOB
LOD
LOQ
```

# Save Results

We save the results.
```{r}
save(fit, LOB, LOD, LOQ, file = paste0(params$filename, "_Results.RData"))
```

# Save Model

We save the inverse of the fitted model to be able to apply it for predicting
concentrations.
```{r}
saveRDS(object = predFunc, file = paste0(params$filename, "_Model.rds"))
```

# Software

```{r}
sessionInfo()
```

