#' Generate an example concentration data set for testing
#'
#' @param nsub The number of subjects to generate
#' @param ntreat The number of treatments per subject
#' @param time.points The times points to generate for each subject (a
#' vector)
#' @param nstudies The number of studies (\code{NA} gives one study
#' without a study column)
#' @param nanalytes The number of analytes to generate (\code{NA}
#' gives one analyte without an analyte column)
#' @param resid The normally distributed random error
#' @return A data frame with columns for study, treatment, subject,
#' time, analyte, and concentration.
generate.conc <- function(nsub, ntreat, time.points, nstudies=NA, nanalytes=NA, resid=0.1) {
  one.cmt.oral <- function(time, dose, v, ka, kel, f=1)
    f*dose*ka/(v*(ka-kel))*(exp(-kel*time) - exp(-ka*time))
  # one.cmt.iv <- function(time, dose, v, kel)
  #   dose/v*exp(-kel*time)
  set.seed(5)
  ret <- data.frame()
  nanalytes.include <- !is.na(nanalytes)
  if (is.na(nanalytes))
    nanalytes <- 1
  nstudies.include <- !is.na(nstudies)
  if (is.na(nstudies))
    nstudies <- 1
  for (i in seq_len(ntreat))
    for (j in seq_len(nsub))
      for (k in seq_len(nanalytes))
        for (m in seq_len(nstudies)) {
          ret <- rbind(
            ret,
            data.frame(
              study=paste("Study", m),
              treatment=paste("Trt", i),
              ID=j,
              time=time.points,
              conc=exp(
                rnorm(length(time.points), mean=0, sd=resid))*
                one.cmt.oral(time.points,
                             dose=i,
                             v=1,
                             ka=1,
                             kel=0.05),
              analyte=paste("Analyte", k),
              stringsAsFactors=FALSE
            )
          )
        }
  if (!nanalytes.include)
    ret$analyte <- NULL
  if (!nstudies.include)
    ret$study <- NULL
  ret
}

#' Generate dose information to go with concentration data.
#'
#' @param concdata Concentration-time data generated by
#' \code{\link{generate.conc}}
#' @return A data frame of dosing data
generate.dose <- function(concdata) {
  ret <-
    unique(
      concdata[
        ,
        setdiff(names(concdata), c("time", "conc", "analyte"))
        ]
    )
  ret$dose <- as.numeric(factor(ret$treatment))
  ret$time <- 0
  ret
}
