R/bestCA.R

Defines functions ffCA tjCA nistCA dwyerCA wksCA ckrsCA CallToLabel labelToCode bestN bestCA

Documented in bestCA bestN ckrsCA dwyerCA nistCA tjCA wksCA

#' Functions in support of obtaining the best uniform CA
#' for a combination of t, k and v
#'
#' Function bestCA uses function Ns to find the best currently implemented
#' CA for the requested scenario. Function bestN just retrieves the best
#' achievable run size. The other exported functions retrieve
#' actual arrays from stored collections of arrays, either within
#' the package or on the internet.
#'
#' @rdname bestCA
#'
#' @importFrom utils download.file
#' @importFrom utils packageVersion
#' @importFrom curl has_internet
#'
#' @aliases bestCA
#' @aliases bestN
#' @aliases ckrsCA
#' @aliases wksCA
#' @aliases dwyerCA
#' @aliases nistCA
#' @aliases tjCA
#'
#' @usage bestCA(t, k, v, maxN=1000000,
#'   fixNA=TRUE, seed=NULL, exclude=NULL,
#'   noderive=FALSE,
#'   nofuse=FALSE, maxfuse=NULL,
#'   noadd1=FALSE, maxadd1=1, ...)
#' @usage bestN(t, k, v, internet=TRUE, exclude=NULL,
#'   noderive=FALSE,
#'   nofuse=FALSE, maxfuse=NULL,
#'   noadd1=FALSE, maxadd1=1, ...)
#' @usage ckrsCA(t, k, v, ...)
#' @usage wksCA(t, k, v, ...)
#' @usage dwyerCA(t, k, v, ...)
#' @usage nistCA(t, k, v, ...)
#' @usage tjCA(t, k, v, ...)
#'
#' @param t integer: the strength
#' @param k integer: the number of columns
#' @param v integer: the number of levels for each column
#' @param maxN integer: the largest number of runs N for
#'     which an array is desired; if the smallest possible N is larger,
#'     an error is thrown; default: 1000000
#'     (too large for being created in reasonable time on most computers)
#' @param fixNA logical: should flexible values be fixed?\cr
#'       If the ingoing CA has flexible values, \code{fixNA=TRUE}
#'       randomly assigns a fixed value to each flexible value.\cr
#'       Thus, a seed is needed for reproducibility.
#' @param seed \code{NULL} or an integer seed for making the
#'       fixing of NA values reproducible; a non-NULL seed is
#'       stored in the attribute \code{fixNA_seed} of the returned object.
#' @param internet logical; if FALSE, methods whose designs need an internet
#'           connection are excluded
#' @param exclude \code{NULL} or a character vector of method(s) to exclude,
#'   in support of size calculations for recursive constructions
#'   which need to calculate sizes of best ingredients
#' @param noderive logical; if \code{TRUE}, derived designs are not considered
#' @param nofuse logical; if \code{TRUE}, fused designs are not considered
#' @param maxfuse maximum number of fuse steps considered; \code{NULL} (default)
#'   uses the distance to the next larger prime power
#' @param noadd1 logical; if \code{TRUE}, designs obtained by adding columns
#'   with \code{\link{add1Column}} are not considered
#' @param maxadd1 maximum number of \code{add1Column} steps considered
#' @param ... currently not used
#' @returns \code{bestN} returns a named integer: the first method that yields the
#'        smallest implemented size.\cr
#'        The other functions return a matrix of class \code{ca},
#'        which is a uniform covering array of strength at least \code{t} with
#'        \code{k} columns at \code{v} levels.
#'
#' @section Details:
#' Function \code{bestCA} uses function \code{\link{Ns}} for locating
#' the best construction for the given scenario, and subsequently
#' implements the first such construction, where the order is that
#' returned by function \code{\link{Ns}}.
#'
#' Some constructions (\code{"DWYER"} and \code{"NIST"}) require an internet
#' connection, because the respective CAs are not part of the package.
#'
#' Some constructions provide CAs with flexible values, which are denoted
#' as NA values in package \pkg{CAs}. These need to be fixed for actual
#' experimentation, and function \code{bestCA} fixes them randomly; in such
#' cases, the returned object has an attribute \code{fixNA_seed}, which is
#' either the seed that was specified by the user or a seed that was created
#' by the function. Specifying the seed in a subsequent call to the function
#' permits to get the same CA again (provided that no new smaller CAs have
#' been implemented).
#'
#' The attributes of the returned object contain elements \code{eCAN},
#' \code{CAs-version} and \code{date}: \code{eCAN} gives the current
#' best array, which is from the most recent internet source, if available;
#' the \code{eCAN} attribute has the information appended, whether or not
#' a frozen state from the package had to be used.
#' As the best array (and the frozen state) may change,
#' the other attributes provide the context.
#'
#' @seealso [Ns()]
#' @examples
#' # example with a single best construction
#' Ns(2,12,4)
#' bestCA(2,12,4)
#' # example with three best constructions
#' Ns(4,8,2)
#' # bestCA uses the leftmost
#' bestCA(4,8,2)
#'
#' Ns(3, 1500, 2)
#' ## powerCT is best
#' attributes(bestCA(3, 1500, 2))
#' ## it is, of course, also possible to directly use the
#' ## construction functions, in this case powerCA with type="CT".
#'
#' # a case that is not implemented (would be huge)
#' Ns(6, 5000, 10)
#' try(bestCA(6, 5000, 10))
#'
#' Ns(3, 50, 2)
#' ## DWYER needs internet connection,
#' ## as earlier in list, TJ is preferred
#' D <- bestCA(3, 50, 2)
#' dim(D)
#' # coverage(D, 3)
#'
#' Ns(6, 50, 2)
#' ## WKS is the only best
#' D <- bestCA(6, 50, 2)
#' dim(D)
#'
#' ## fusing is far better than direct construction
#' \donttest{
#' ## slow, yields 8187 runs by fusing an 8191 run cphfCA
#' ## in 16 levels twice
#' Ns(3,37,14)
#' Ns_fuse(3,37,14,maxfuse=2)
#' bestN(3,37,14)
#' }
#'
#' Ns(3,9,7)
#' ## CKRS and DWYER are best
#' D <- bestCA(3, 9, 7)
#' dim(D)
#'
#' Ns(3,9,6)
#' ## CKRS is best implemented, but 18 runs worse than eCAN
#' eCAN(3,9,6)
#' ## Torres-Jimenez designs are currently (Sep 2025) unavailable
#' D <- bestCA(3, 9, 6)
#' attributes(D)
#'
#' Ns(3,9,5)
#' ## CK_NRB is the unique best
#' ks(3,185,5)
#'
#' Ns(2,26,24) ## fuseBose is best-known
#' dim(bestCA(2,26,24))
#'
#' Ns(2,26,23) ## fuseBushtCA is best implemented,
#'             ## projBoseCA is close
#' dim(D <- bestCA(2,26,23))
#' attributes(D)
#' ## eCAN from NCK post processing of projBose
#' ## (removes 7 runs)
#' eCAN(2,26,23)
#'
#' Ns(3,6,12)
#' ## the optimum Ji and Yin OA is in the package as oa1728.12.6
#'
#' \donttest{
#' ## this code needs an internet connection
#' ## and is therefore wrapped in \donttest
#' ## and in try
#'    try(dim(nistCA(3,5,4)))
#' }
#'

#' @export
bestCA <- function(t, k, v, maxN=1000000, fixNA=TRUE, seed=NULL, exclude=NULL,
                   noderive=FALSE, nofuse=FALSE, maxfuse=NULL, noadd1=FALSE, maxadd1=1, ...){
  Call <- sys.call()
  if (t==1){
    aus <- matrix(0:(v-1),v,k)
    attr(aus, "constr") <- "FullFactorial"
    return(aus)
  }
  if (k <= t){
    aus <- ffCA(k , v)
    attr(aus, "constr") <- "FullFactorial"
    return(aus)
  }
  ## return a matrix with v constant rows in case k <= t
  ## there will be an error otherwise
  internet <- curl::has_internet()
  if (!internet){
     message("there is no internet connection")
     # if (!is.null(preference)) if (preference %in% c("DWYER","NIST"))
     #   stop(paste(preference, " requires an internet connection"))
     # forbidden <- which(names(hilf) %in% c("DWYER","NIST"))
     # if (length(forbidden) > 0)
     #    hilf <- hilf[-forbidden]
     hilf <- bestN(t,k,v, internet=FALSE, exclude=exclude, noderive=noderive,
                   nofuse=nofuse, maxfuse=maxfuse, noadd1=noadd1, maxadd1=maxadd1)
  }else
     hilf <- bestN(t,k,v, exclude=exclude, noderive=noderive,
                   nofuse=nofuse, maxfuse=maxfuse, noadd1=noadd1, maxadd1=maxadd1)# Ns(t,k,v, ...)
  if (is.na(hilf))
    stop("no construction for this setting has been implemented yet")
  if (hilf > maxN)
    stop("the best construction for this setting has more than ", maxN, "runs")
  constr <- names(hilf)
  ## remove eCAN entry
  ## if it is feasible, there is another entry of the same size
  # minN <- min(hilf[-length(hilf)])
  # if (length(hilf)==0) stop("no feasible construction found")
  # constrs <- names(hilf)[which(hilf<=minN)]
  ## handling of a stated preference
  # finished <- FALSE
  # if (!is.null(preference)){
  #   if (preference %in% constrs){
  #     aus <- eval(parse(text=labelToCode(preference, t, k, v, ...)))
  #     finished <- TRUE
  #   }
  #   else{
  #   message(preference, " is not among the best constructions.")
  #   if (override & preference %in% names(hilf)){
  #     message("It is used anyway because of override=TRUE.")
  #     aus <- eval(parse(text=labelToCode(preference, t, k, v, ...)))
  #     finished <- TRUE
  #   }else{
  #   if (preference %in% names(hilf))
  #     message("It is not used, because override=FALSE.")
  #   else
  #     message("It is not even among the possible constructions.")
  #   }}}
  # if (!finished){
      aus <- eval(parse(text=labelToCode(constr, t, k, v, ...)))
  # }
  if (any(is.na(aus)) && fixNA){
    nNA <- sum(is.na(aus))
    set.seed(seed)
    aus[is.na(aus)] <- sample(0:(v-1), nNA, replace=TRUE)
    attr(aus, "fixNA_seed") <- seed
  }
  dimnames(aus) <- NULL
  if (is.null(attr(aus, "origin"))) attr(aus, "origin") <- constr
  if (is.null(attr(aus, "t"))) attr(aus, "t") <- t
  attr(aus, "constr") <- constr
  parts <- strsplit(constr, ":", fixed=TRUE)[[1]]
  if (length(parts) > 1){
    ## the last step is the outermost one; the source is what it was applied to
    last <- tail(parts, 1)
    if (last=="derive"){
      attr(aus, "ingredients") <- list(source=list(
        constr=paste(parts[-length(parts)], collapse=":"),
        t=t+1, k=k+1, v=v))
    }else{
      nrun <- sum(cumprod(rev(parts[-1])==last))
      src <- paste(parts[seq_len(length(parts)-nrun)], collapse=":")
      attr(aus, "ingredients") <- list(source=list(
        constr=src, t=t, k=k-(last=="add1")*nrun, v=v+(last=="fuse")*nrun))
    }
  }
  ## prepend the Call attribute
  attr(aus, "Call") <- c(Call, attr(aus, "Call"))
  attr(aus, "eCAN") <- c(eCAN(t,k,v,frozen=is.null(smolenBigFrame)),
                         frozen=is.null(smolenBigFrame))
  attr(aus, "date") <- Sys.Date()
  attr(aus, "CAs-version") <- packageVersion("CAs")
  if (!"ca" %in% class(aus)) class(aus) <- c("ca", class(aus))
  aus
}

#' @export
bestN <- function(t,k,v, internet=TRUE, exclude=NULL, noderive=FALSE,
                  nofuse=FALSE, maxfuse=NULL, noadd1=FALSE, maxadd1=1, ...){
  ## yields the size of the smallest implemented design,
  ## with or without internet
  ## maxfuse=NULL: fusing from up to the next larger prime power level
  stopifnot(is.numeric(t), is.numeric(k), is.numeric(v))
  stopifnot(t%%1==0, k%%1==0, v%%1==0)
  if (k <= t) return(c(FullFactorial=v^k))
  if (is.null(maxfuse))
    maxfuse <- default_maxfuse(v)
  if (!internet) exclude <- union(exclude, c("DWYER", "NIST"))
  hilf <- Ns(t,k,v, exclude=exclude, noderive=noderive, nofuse=nofuse,
             maxfuse=maxfuse, noadd1=noadd1, maxadd1=maxadd1)
  hilf <- hilf[setdiff(names(hilf), "eCAN")]
  if (length(hilf)==0) return(NA)
  aus <- min(hilf)
  names(aus) <- names(hilf)[which.min(hilf)]
  aus
}

## label of the form construction[:fuse...][:derive][:add1...] as used by Ns
## the steps are applied from left to right, i.e., fuse first, add1 last
labelToCode <- function(label, t, k, v, ...){
  ## handle derive, add1 and fuse instances first
  parts <- strsplit(label, ":", fixed=TRUE)[[1]]
  if (length(parts) > 1){
    nparts <- length(parts)
    last <- parts[nparts]
    stopifnot(last %in% c("derive", "add1", "fuse"))
    if (last=="derive"){
      ## derived from a CA with strength t+1 and k+1 columns
      source <- labelToCode(paste(parts[-nparts], collapse=":"), t+1, k+1, v, ...)
      return(paste0("derive(", source, ")[, 1:", k, ", drop=FALSE]"))
    }
    ## consecutive identical steps at the end
    nrun <- sum(cumprod(rev(parts[-1])==last))
    src <- paste(parts[seq_len(nparts-nrun)], collapse=":")
    if (last=="add1"){
      ## add1Column is applied once per add1 step
      aus <- labelToCode(src, t, k - nrun, v, ...)
      for (i in seq_len(nrun))
        aus <- paste0("add1Column(", aus, ", ", t, ", ", v, ")")
      return(aus)
    }
    ## fuse
    aus <- labelToCode(src, t, k, v + nrun, ...)
    return(paste0("fuse(", aus, ", ", v + nrun, ", ", v, ")"))
  }
  ## label must correspond to the label used in function Ns
  stopifnot(label %in% c("KSK","JE","ZeroSum","PALEY",
  "CAEX", "CYCLOTOMY", "CKRS", "RMScopiesCA",
  "miscCA", "recBoseCA_PCA", "SCA_Busht",
  "fuseBoseCA", "fuseBushtCA",
  "recBoseCA_CA", "projBoseCA", "compositCA",
  "WKS", "CS_MS",
  "CS_LCDST", "CS_CK", "powerCT", "DWYER", "NIST", "TJ", "CK_doublingCA",
  "CK_NRB","FullFactorial", "CS_CMMSSY", "ODbasedCA", "pcaCA", "dpCA",
  "scphfCA", "cphfCA"))
  if (label =="FullFactorial"){
    return(paste0("as.matrix(expand.grid(rep(list(0:(", v, "-1)),", k,")))"))
  }
  if (label =="KSK"){
    if (!v==2) stop('"KSK" requires v=2')
    aus <- paste0("KSK(", k, ")")
  }
  if (label =="JE"){
    if (!v==2) stop('"JE" requires v=2')
    aus <- paste0("JE(", t, ", ", k, ")")
  }
  if (label =="ZeroSum"){
    aus <- paste0("ZeroSum(", t, ", ", k, ", ", v, ")")
  }
  if (label=="miscCA"){
    aus <- paste0("miscCA(", t, ", ", k, ", ", v, ", ...)")
  }
  if (label=="compositCA"){
    aus <- paste0("compositCA(", t, ", ", k, ", ", v, ", ...)")
  }
  if (label =="PALEY"){
    if (!v==2) stop('"PALEY" requires v=2')
    aus <- paste0("paleyCA(", t, ", ", k, ")")
  }
  if (label =="fuseBoseCA"){
    aus <- paste0("fuseBoseCA(",k, ", ", v, ", ...)")
  }
  if (label =="SCA_Busht"){
    aus <- paste0("SCA_Busht(",v,",", t, ")[,1:",k,"]")
  }
  if (label =="fuseBushtCA"){
    aus <- paste0("fuseBushtCA(",t, ",", k, ", ", v, ", ...)")
  }
  if (label =="CAEX"){
    if (!v==3) stop('"CAEX" requires v=3')
    if (!t==2) stop('"CAEX" requires t=2')
    aus <- paste0("CAEX(", k, ")")
  }
  if (label == "ODbasedCA"){
    if (!t==3) stop('"ODbasedCA" requires t=3')
    if (!k <= v) stop('"ODbasedCA" requires k<=v')
    aus <- paste0("ODbasedCA(", t, ",", k, ",", v, ")")
  }
  if (label == "pcaCA"){
    if (!t==2) stop('"pcaCA" requires t=2')
    aus <- paste0("pcaCA(", k, ",", v, ")")
  }
  if (label == "dpCA"){
    if (!t==2) stop('"dpCA" requires t=2')
    aus <- paste0("dpCA(", k, ",", v, ")")
  }
  if (label =="TJ"){
    ## as of June 2025, the 2-level CAs of TJ
    if (!v==2) stop('"TJ" requires v=2')
    aus <- paste0("tjCA(", t, ", ", k, ", ", v, ")")
  }
  if (label =="RMScopiesCA"){
    if (!t==3) stop('"RMScopiesCA" requires t=3')
    aus <- paste0("RMScopiesCA(", k, ", ", v, ")")
  }
  if (label =="CK_doublingCA"){
    if (!t==3) stop('"CK_doublingCA" requires t=3')
    aus <- paste0("CK_doublingCA(", k, ", ", v, ")")
  }
  if (label =="CK_NRB"){
    if (!t==3) stop('"CK_NRB" requires t=3')
    if (!v %in% 3:5) stop('"CK_NRB" requires v = 3, 4, or 5')
    if (!k<=2*v) stop('"CK_NRB" requires k<=2*v')
    aus <- paste0("CK_NRB(", k, ", ", v, ")")
  }
  if (label=="CYCLOTOMY"){
    aus <- paste0("cyclotomyCA(", t, ", ", k, ", ", v, ")")
  }
  if (label=="CKRS"){
    aus <- paste0("ckrsCA(", t, ", ", k, ", ", v, ")")
  }
  if (label=="recBoseCA_PCA"){
    if (!t==2) stop('"recBoseCA_PCA" requires t=2')
    if (!v %in% primedat$q) stop("v must be prime or prime power")
    aus <- paste0("recBoseCA(", t, ", ", k, ", ", v, ", type='PCA')")
  }
  if (label=="recBoseCA_CA"){
    if (!t==2) stop('"recBoseCA_CA" requires t=2')
    if (!v %in% primedat$q) stop("v must be prime or prime power")
    aus <- paste0("recBoseCA(", t, ", ", k, ", ", v, ", type='CA')")
  }
  if (label=="projBoseCA"){
    if (!t==2) stop('"projBoseCA" requires t=2')
    aus <- paste0("projBoseCA(", k, ", ", v, ")")
  }
  if (label=="WKS"){
    if (!t==6) stop('"WKS" requires t=6')
    if (!v==2) stop('"WKS" requires v=2')
    ## the CAs are labeled by k, and there is an entry
    ## for each k between 30 and 72 (including)
    aus <- paste0('wksCA(6,', k, ',2)')
  }
  if (label=="CS_MS"){
    if (!t==2) stop('"CS_MS" requires t=2')
    aus <- paste0('CS_MS(', k, ', ', v, ')')
  }
  if (label=="CS_LCDST"){
    if (!t==2) stop('"CS_LCDST" requires t=2')
    aus <- paste0('CS_LCDST(', k, ', ', v, ')')
  }
  if (label=="CS_CMMSSY"){
    if (!t==2) stop('"CS_CMMSSY" requires t=2')
    aus <- paste0('CS_CMMSSY(', k, ', ', v, ')')
  }
  if (label=="CS_CK"){
    if (!v==2) stop('"CS_CK" requires v=2')
    aus <- paste0('CS_CK(', k, ', t=', t, ')')
  }
  if (label=="scphfCA"){
    aus <- paste0('scphfCA(', t, ', ', k, ', ', v, ')')
  }
  if (label=="cphfCA"){
    aus <- paste0('cphfCA(', t, ', ', k, ', ', v, ')')
  }
  if (label=="add1CA"){
    aus <- paste0('add1CA(', t, ', ', k, ', ', v, ')')
  }
  if (label=="powerCT"){
    aus <- paste0('powerCA(', t, ', ', k, ', ', v, ', type="CT")')
  }
  if (label=="DWYER"){
    aus <- paste0('dwyerCA(', t, ', ', k, ', ', v, ')')
  }
  if (label=="NIST"){
    aus <- paste0('nistCA(', t, ', ', k, ', ', v, ')')
  }
  aus
}

## label of the form construction[:fuse[:fuse...]|:add1[:add1...]][:derive]
## as used by Ns for fused and derived entries
CallToLabel <- function(call, ...){
  call <- try(strsplit(call, "(", fixed=TRUE)[[1]], silent = TRUE)
  if ("try-error" %in% class(call)) call <- "unknown"
  ## label must correspond to the label used in function Ns
  stopifnot(call %in% c("KSK","paleyCA",
                         "CAEX", "cyclotomyCA", "ckrsCA", "RMScopiesCA",
                         "miscCA", "recBoseCA_PCA", "SCA_Busht",
                         "fuseBoseCA", "fuseBushtCA",
                         "recBoseCA_CA", "projBoseCA", "compositCA",
                         "wksCA", "CS_MS",
                         "CS_LCDST", "CS_CK", "powerCT", "dwyerCA", "nistCA", "tjCA", "CK_doublingCA",
                         "CK_NRB","ffCA", "CS_CMMSSY", "ODbasedCA", "pcaCA",
                         "dpCA", "scphfCA", "cphfCA", "add1CA", "bestCA","unknown"))
  if (call %in% c("as.matrix", "ffCA")){
    return("FullFactorial")
  }
  if (call == "paleyCA"){
    return("PALEY")
  }
  if (call =="tjCA"){
    return("tjCA")
  }
  if (call=="cyclotomyCA"){
    return("CYCLOTOMY")
  }
  if (call=="ckrsCA"){
    return("CKRS")
  }
  if (call=="recBoseCA"){
    return("recBoseCA_CA")
  }
  if (call=="recBosePCA"){
    return("recBoseCA_PCA")
  }
  if (call=="wksCA"){
    return("WKS")
  }
  if (call=="powerCA"){
    return("powerCT")
  }
  if (call=="dwyerCA"){
    return('DWYER')
  }
  if (call=="nistCA"){
    return("NIST")
  }
  ## call and label are the same
  return(call)
}

#' @export
ckrsCA <- function(t, k, v, ...){
  Call <- sys.call()
  hilf <- CKRScat[CKRScat$t>=t & CKRScat$v==v & CKRScat$k>=k,]
  if (nrow(hilf)==0) stop("there is no suitable array in CKRS_CAs")
  N <- min(hilf$N)
  tachieved <- hilf$t
  hilf <- hilf[which.min(hilf$N),,drop=FALSE]
  N <- hilf$N
  fn <- hilf$fn
  aus <- CKRS_CAs[[fn]]
  attr(aus, "t") <- tachieved
  attr(aus, "Call") <- Call
  aus[,1:k]
}

#' @export
wksCA <- function(t, k, v, ...){
  Call <- sys.call()
  stopifnot(t==6)
  stopifnot(v==2)
  hilf <- WKScat[WKScat$k>=k,]
  if (nrow(hilf)==0) stop("there is no suitable array in WKS_CAs")
  N <- min(hilf$N)
  hilf <- hilf[which.min(hilf$N),,drop=FALSE]
  N <- hilf$N
  fn <- as.character(hilf$k)
  aus <- WKS_CAs[[fn]]
  attr(aus, "t") <- 6
  attr(aus, "Call") <- Call
  aus[,1:k]
}

#' @export
dwyerCA <- function(t, k, v, ...){
  Call <- sys.call()
  hilf <- DWYERcat[DWYERcat$t>=t & DWYERcat$v==v & DWYERcat$k>=k,]
  if (nrow(hilf)==0) stop("there is no suitable array in the Dwyer database")
  N <- min(hilf$N)
  hilf <- hilf[which.min(hilf$N),,drop=FALSE]
  N <- hilf$N  ## should not be necessary, just to be safe
  kneeded <- hilf$k
  tachieved <- hilf$t
  nam <- paste0(paste("CA", N, t, kneeded, v, sep="_"), ".txt")
  ## load from Dwyer repo
  pfadGithub <- "https://raw.githubusercontent.com/aadwyer/CA_Database/main/Repository/CA"
  pfad <- paste0(pfadGithub, "/", nam)
  aus <- readCA(pfad, ninstruct = 0, ignore.chars=c("[","]"),
                header=FALSE, sep=",",
                origin=paste0("Dwyer Github repository, ", nam, ", ",
                              hilf$Source))
  attrs <- attributes(aus)
  attrs$dimnames <- NULL
  aus <- aus[,1:k]
  attrs$dim <- dim(aus)
  N <- nrow(aus)
  neles <- lengths(lapply(1:N, function(obj) unique(aus[obj,])))
  constrows <- which(neles==1)
  if (length(constrows) > 1) aus <- aus[c(constrows, setdiff(1:N, constrows)),]
  attributes(aus) <- attrs
  attr(aus, "t") <- tachieved
  if (length(constrows) > 1) attr(aus, "nconstant") <- length(constrows)
  attr(aus, "Call") <- Call
  aus
}

#' @export
nistCA <- function(t, k, v, ...){
  Call <- sys.call()
  hilf <- NISTcat[NISTcat[,"t"]==t & NISTcat[,"v"]==v &
                    NISTcat[,"k"]==k,, drop=FALSE]
  if (nrow(hilf)==0) stop("there is no suitable array in the NIST library")
  nam <- rownames(hilf)
  pfad <- paste0("https://math.nist.gov/coveringarrays/ipof/cas/t=", t,"/v=",v,"/", nam)
  speicherpfad <- paste0(tempdir(), "/", nam)
  aus <- try(download.file(url = pfad, destfile = speicherpfad))
  if ("try-error" %in% class(aus)) message("error encountered in downloading the array")
  if (!"try-error" %in% class(aus)){
    txtpfad <- gsub(".zip","",speicherpfad, fixed=TRUE)
    utils::unzip(speicherpfad, exdir = tempdir())
    aus <- readCA(txtpfad, ninstruct=0, skiplines = 1)
  }
  attr(aus, "origin") <- "NIST covering array library"
  attr(aus, "t") <- t
  attr(aus, "Call") <- Call
  aus
}

#'@export
tjCA <- function(t, k, v=2, ...){
  Call <- sys.call()
  ## the function also implements replaceable constructions from
  ##    TJcat; this may change in the future
  ## the function should only be used if no other construction
  ##    yields an equally good (or better) size.
  if (!v==2) stop("For v=3, use CAEX. v>3 was not yet implemented.")
  hilf <- TJcat[TJcat$t>=t & TJcat$v==v & TJcat$k>=k,]
  if (nrow(hilf)==0) stop("there is no suitable array in TJ2level_CAs")
  N <- min(hilf$N)
  hilf <- hilf[which.min(hilf$N),,drop=FALSE]
  N <- hilf$N  ## should not be necessary, just to be safe
  kneeded <- hilf$k
  tachieved <- hilf$t
  nam <- hilf$nameInTJ2level_CAs
  if (!nam==""){
  aus <- TJ2level_CAs[[nam]][,1:k]
  attr(aus, "origin") <- "Torres-Jimenez repository, Feb 6 2025"
  attr(aus, "t") <- tachieved
  attr(aus, "Call") <- Call
  return(aus)
  }
  code <- hilf$code
  if (code=="") stop("this setting is not implemented in tjCA, \nuse function Ns for finding alternatives")
  aus <- eval(parse(text=code))
  attrs <- attributes(aus)
  aus <- aus[,1:k]
  attrs$dim[2] <- k
  attributes(aus) <- attrs
  attr(aus, "comment") <- c(attr(aus, "comment"), "called via tjCA")
  aus
}

ffCA <- function(k, v){
  Call <- sys.call()
  aus <- maxconstant(as.matrix(expand.grid(rep(list(0:(v-1)), k))))
  dimnames(aus) <- NULL
  attr(aus, "t") <- NA
  attr(aus, "origin") <- "Full Factorial"
  attr(aus, "nconstant") <- v
  attr(aus, "Call") <- Call
  aus
}

Try the CAs package in your browser

Any scripts or data that you put into this service are public.

CAs documentation built on Nov. 29, 2026, 1:06 a.m.