Calc_DilRes <- function(as=3, bs=1, cs=-4, ds=10, at=3, bt=1,  dt=10,r=0.0001,ct=cs-r,
                        sd_fac=0.1, gt=1, gs=1, log_conc,
                        heteroNoise=FALSE, noDilSeries, noDils) {
  yAxfac <- (ds-as)
  log_dose <- log_conc
  isRef <- rep(c(1,0),1,each=length(log_conc)*noDilSeries)
  isSample <- rep(c(0,1),1,each=length(log_conc)*noDilSeries)
  browser()  
  av <- as*isRef + at*isSample + (ds*isRef + dt*isSample - as*isRef - at*isSample)/
    (1+isRef*exp(bs*(cs - log_dose)) + isSample*exp(bt*(ct-log_dose)))
  if (heteroNoise) {
    # heterosc noise
    ro_jit <- matrix(unlist(map(av, function(x) x+rnorm(1,0,x*sd_fac/100))), nrow=noDils, ncol=noDilSeries*2)
  } else {
    # homosc noise
    ro_jit <- matrix(unlist(map(av, function(x) x+rnorm(1,0,sd_fac*yAxfac/100))), nrow=noDils, ncol=noDilSeries*2)
  }
  ro_jit <- abs(ro_jit)
  
  ro_jit2 <- cbind(ro_jit, log_dose)
  if (noDilSeries==3) {
    colnames(ro_jit2) <- c("R_dil1","R_dil2","R_dil3","T_dil1","T_dil2","T_dil3", "log_dose")
  } else {
    colnames(ro_jit2) <- c("R_dil1","R_dil2","T_dil1","T_dil2", "log_dose")
  }
  return(ro_jit2)
}

library(openxlsx)
Conc <- 9*1/(3^(1:11))
Conc_ <- c(9, Conc)

ro_new <- list()
ro_new[[1]] <- Calc_DilRes(as=1000, bs=-2, cs=-4, ds=10000, at=1000, bt=-2,  dt=10000, log_conc = log(Conc_),
                      sd_fac=3.3,
                      # auslenkU=outlierU,
                      # auslenkM=outlierM,
                      # auslenkL=outlierL,
                      heteroNoise = F, noDilSeries = 2, noDils = 12)
ro_new[[2]] <- Calc_DilRes(as=1000, bs=-2, cs=-4, ds=10000, at=1000, bt=-2, dt=10000, log_conc = log(Conc_),
                      sd_fac=3.3,r=0.1,
                      # auslenkU=outlierU,
                      # auslenkM=outlierM,
                      # auslenkL=outlierL,
                      heteroNoise = F, noDilSeries = 2, noDils = 12)
ro_new[[3]] <- Calc_DilRes(as=1000, bs=-2, cs=-4, ds=10000, at=1000, bt=-2, dt=10000, log_conc = log(Conc_),
                      sd_fac=3.2, r=-0.3,
                      # auslenkU=outlierU,
                      # auslenkM=outlierM,
                      # auslenkL=outlierL,
                      heteroNoise = F, noDilSeries = 2, noDils = 12)

write.xlsx(ro_new, "~/plateflow/wizard/Tests3Plates.xlsx")

