---
output:
  pdf_document:
    extra_dependencies: ["float"]
    number_sections: true
    toc: true
    toc_depth: 3
header_includes:
  -\usepackage{fancyheadr}
  -\setlength{\headheight}{22pt}%
  -\usepackage{lastpage}
  -\pagestyle{fancy}
  -\usepackage{pdflscape}
  -\usepackage{longtable}
  -\rhead{\includegraphics[width=.15\textwidth]{`r getwd()`/logov2.png}}
params:
  FileName: NA
  author: NA
  NoP: NA
  Assay: NA
  REP: NA
  coeffs: NA
author: "Author: `r params$author`"
title: |
    | ![](logov2.png){width=1in}
    | 4PL bioassay evaluation
subtitle: |
  `r params$FileName`
  
  <left> Unique time: </left> <right> `r Sys.time()`</right>
date: "`r paste(params$NoP, params$Assay)`"

---

<!-- \fancyfoot[C]{\thepage\ of \pageref{LastPage}} -->
<!-- \newpage -->

<!-- \newpage -->

```{r setup, include=FALSE}

knitr::opts_chunk$set(echo = TRUE)

library(knitr)
library(DT)
library(kableExtra)

REP <- params$REP
author <- params$author
coeffs <- params$coeffs

all_l <- REP$all_l
#ANOVAXLS <- REP$ANOVAXLS
#XLplot4pl <- REP$XLplot4pl
DiagnTable <- REP$DiagnTable
UnRPLAausw <- REP$UnRPLAausw
UnRPLBend <- REP$UnRPLBend
PLAausw <- REP$PLAausw
PLbend <- REP$PLBend
pottab4plXL <- REP$pottab4plXL
Lim <- REP$Lim
XLdat2 <- REP$XLdat2
PureErr <- REP$PureErr
ro_newROUT <- REP$ro_newROUT
ROUTplot <- REP$ROUTplot
ANOVA_ROUT <- REP$ANOVA_ROUT

CIplot <- REP$CIplot
testsTabROUT <- REP$testsTabROUT
relpotTestPlot <- REP$relpotTestPlot

#browser()

```


# Introduction

Bioassay potency estimation uses statistical methods to quantify the strength of a biological product or drug by comparing its response to that of a reference standard. Because biological responses are inherently variable, affected by assay conditions, cell systems or organisms, and measurement noise, the 4-parametric logistic regression is used to obtain reliable potency values.  
USP<1034> recommends calculation of standard errors of ratios of the parameters using Fieller's theorem [1] or using the "delta" method (for a discussion about the "delta" method see [3]). The gradient approach using the differences on the log-scale is mathematically more stable und thus preferable compared to a ratio approach [2].

# Raw data

All data used for the 4PL evaluation is shown in table 1:

```{r alll, echo=FALSE, warning=FALSE, results='asis'}

kable(XLdat2, format = "markdown", caption= "Uploaded data (test and reference) ", digits=3)

if (!is.null(ro_newROUT)) {
  kable(ro_newROUT, format = "markdown", caption= "Data after exclusion of suspected outliers (see [6]) ", digits=3)
}

```


# Results

## Overall result

```{r Over_all, echo=FALSE, comment=NA, warning=NA, message=NA}

browser()
potFlag <- 0
if (pottab4plXL["test_result"][[1]][1]=="failed") potFlag <- 1
AnalysisFlag <- FALSE
if (potFlag==1 | sum(testsTabROUT$test_results)>0) AnalysisFlag <- TRUE

colFmt <- function() {
  
  outputFormat <- knitr::opts_knit$get("rmarkdown.pandoc.to")
 if(AnalysisFlag) {
    text <- paste("\\textcolor{red}{Analysis failed}",sep="")
  } else  {
    text <- paste("\\textcolor{black}{Analysis succeeded}",sep="")
  }  
  return(text)
}


```

`r colFmt()`


## 4pl-regression

Relative potency (absolute and relative confidence limits) are shown in Table 3. `r if(PureErr) {"Pure Error is used for calculations."}` 
`r if (!PureErr) {"RMSE of restricted model is used for confidence limit calculation."}`

```{r Pot_tab4pl, echo=FALSE, comment=NA, warning=NA, message=NA}

#browser()
if (pottab4plXL["test_result"][[1]][1]==1) { cat(paste("FAILED: relative potency CL result of restricted model outside limits: ", Lim[[9]], "to" ,Lim[[10]] ))}
if (pottab4plXL["test_result"][[1]][1]==0) { cat(paste("PASSED: relative potency CL result of restricted model within limits: ", Lim[[9]], "to" ,Lim[[10]] ))}
kable(pottab4plXL, format = "markdown", caption= "Relative potency with absolute and relative CLs ", digits=3, row.names = F) %>%
  kable_styling(latex_options = "hold_position")


```
NOTE: results of unrestricted model for Information only.


## Plot of the data and models

Plots in Figure 1 shows the restricted model.


```{r XLplot, echo=FALSE, warning=FALSE, fig.height=4, fig.width=6, fig.cap="Plot of models", fig.align='left', comment=F, message=F, results='asis', fig.pos='H'}

plot(ROUTplot)


```


## ANOVA table

The ANOVA of the unconstrained model is listed in table 4. Bates and Watts [4] proposed a test on parallelism which compares the residual sum of squares of the restricted model (ResRSSE) with the residual sum of squares of the unrestricted model (UnresRSSE). If the UnresRSSE is significantly smaller than the ResRSSE, the p-value of "Non-parallelism" is smaller than 0.05 (line 4 in table 4). This test is for information only as it may be overly sensitive in case of small overall variability of the data. 

```{r anovaxls, echo=FALSE, warning=FALSE, results='asis'}

kable(ANOVA_ROUT, format = "markdown", caption= "Analysis of variance", digits=3) %>%
  kable_styling(latex_options = "hold_position")


```

## Assay suitability tests

Table 5 lists the chosen suitability test results with confidence limits, where applicable. F-tests should be read with caution, if the overall variability is small, as the test gets overly sensitive.


```{r SST_ergebn, echo=FALSE, cache=FALSE, warning=FALSE, message=FALSE, tidy=TRUE}

kable(testsTabROUT, row.names = F, format = "markdown", caption="Assay suitability results", digits=4)


```


\footnotesize

```{r Fussnote, echo=F, comment=NA}

cat("*...The estimate for F-test on regression and on non-linearity is the p-value")
cat(  "F-test on regression passes if F-value > F-crit and thus p < 0.05")
cat(  "F-test on non-linearity passes if F-value < F-crit and thus p > 0.05")
cat(  "Test results outcome:")
cat("  0 ... test passed (for EQ tests: CL within limits);")
cat("  1 ... test failed (for EQ tests: CL not within limits);")


  
```

\normalsize


```{r AST_Ergebn, echo=FALSE, cache=FALSE, warning=FALSE, message=FALSE, tidy=TRUE}

TestsTabFlag <- FALSE
if (sum(testsTabROUT$test_results)>0) TestsTabFlag <- TRUE
colFmt2 <- function() {
  
  outputFormat <- knitr::opts_knit$get("rmarkdown.pandoc.to")
 if(TestsTabFlag) {
    text <- paste("\\textcolor{red}{Assay suitability tests failed}",sep="")
  } else  {
    text <- paste("\\textcolor{black}{Assay suitability tests succeeded}",sep="")
  }  
  return(text)
}


```


`r colFmt2()`




## Fitting results with curve points

The results of the non-linear fitting procedure for the restricted model (5 parameters) is listed in table 5:

```{r PLAausw, echo=FALSE, warning=FALSE, results='asis'}

kable(PLAausw, format = "markdown", caption= "Restricted 4PL model", digits=3, row.names = F)


```



Sebaugh et al proposed bend points for test and reference samples, that define the points with highest turning behavior. Table 6 lists these bendpoints as well as asymptote points ~ twice as far from the center as the bendpoints.

```{r PLBend, echo=FALSE, warning=FALSE, results='asis'}

kable(PLbend, format = "markdown", caption= "Bendpoints and asymptote points of restricted 4PL model", digits=3)


```

The results of the non-linear fitting procedure for the unrestricted model (8 parameters) is listed in table 7:

```{r UnRPLAausw, echo=FALSE, warning=FALSE, results='asis'}

kable(UnRPLAausw, format = "markdown", caption= "Unrestricted 4PL model", digits=3, row.names = F)

```



# Signature


\vspace{1.5cm} 
\noindent
\begin{tabular}{p{6cm}p{1cm}p{6cm}}
  \cline{1-1} \cline{3-3}
  Date & & Signature 
\end{tabular}


\newpage

# Appendix: Formulas

## 4PL regression

$$
Y = D + \frac{A-D} {1+(\frac{C} {x})^B } + \epsilon
$$

where: x ... concentration of the analyte

A: upper asymptote

B: slope

D: lower asymptote

C ... EC50


## log-logistic 4P regression

$$
Y = D + \frac{A-D} {1+e^{(B*(C - log(x))) }} + \epsilon
$$



## Intercept for slope at EC50

$$
I = A+\frac{D-A}{2}-B_{true}*EC50
$$

## Slope at EC50

$$
B_{true}=B*\frac{D-A}{4}
$$

## Confidence intervals

In general, the confidence intervals are calculated as follows:
$$
 CI = \hat\theta\pm se(\hat\theta)*q^{t_{n-p}}_{1-\frac{\alpha}{2}}
$$
…where $\hat\theta$ is a fitted parameter or a linear combination thereof, q is the 1-alpha/2 quantile of the Student’s t-distribution with n-p degrees of freedom and se is the standard error derived from any covariance matrix.

Let $\theta$ be the 4+1 parameters of the fit (a, b, d, EC50 of reference and EC50 difference). It can be shown that the least squares estimator $\hat\theta$ is normally distributed with asymptotic covariance matrix. The gradient method provides one of several ways to calculate the covariance matrix:

$$
\hat{V(\theta)}= \sigma^2(A(\hat\theta)^T*A(\hat\theta))^{-1}
$$
where A($\theta$) is the n x p matrix of the first partial derivatives for each parameter (i.e. gradient) realized at the fitted parameter estimates. The RMSE of the model or the pure error is used as estimate of $\sigma$. The square root of the diagonals of $\hat{V(\theta)}$ gives the standard errors and with that confidence intervals (CI) can be computed.

# Literature

[1] Finney, D.J.: (1978) Statistical Method in Biological Assay, London: Charles Griffin House, 3rd edition (pp. 80-82)

[2] Franz, V.H.: Ratios: A short guide to confidence limits and proper use. arXiv:0710.2024v1, 10 Oct 2007

[3] VerHoef, J.M.: Who invented the Delta Method? The American Statistician, 2012, 66:2, 124-127 DOI: 10.1080/00031305.2012.687494

[4] Bates, D.M., Watts, D.G. (1988). Comparing models. In: Nonlinear Regression Analysis and Its Applications. New York: Wiley, pp 103-108

[5] Bates, D.M., Watts, D.G. (1988) 2. In: Nonlinear Regression Analysis and Its Applications. New York: Wiley, pp 52-58

[6] Motulsky, Brown Outlier testing
