
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning=FALSE, message=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(SUBSET != ""){
  calData <- eval(call("subset", x =  CalibrationData,
                       subset = parse(text = 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)
names(ab) <- NULL
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_string(x = tmp[2], y = tmp[1])) +
            geom_point() + geom_smooth(method = "lm") +
            annotate("text",  x=-Inf, y = Inf,
            label = substitute(paste(R^2, " = ", R2, ", adj. ", R^2, " = ", adj.R2),
                              list(R2 = signif(summary(fit)$r.squared,3),
                              adj.R2 = 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()
```

