R/utils.R

Defines functions download_file download_data col_medians segment_columns names_to_wavelength parse_wavelength with_seed apply_preprocess preprocess check_count check_number check_numeric_vector check_flag as_tbl as_response_matrix as_numeric_matrix

# Internal helpers shared across the package. Not exported.

# Converts a matrix, data frame or tibble to a numeric matrix, keeping column
# names. Fails with an informative message for non-numeric input.
as_numeric_matrix <- function(x, arg = "x") {
  if (is.data.frame(x)) {
    if (!all(vapply(x, is.numeric, logical(1)))) {
      stop("'", arg, "' must contain only numeric columns.", call. = FALSE)
    }
    x <- as.matrix(x)
  } else if (is.numeric(x) && (is.vector(x) || (is.array(x) && length(dim(x)) == 1))) {
    # plain vectors and 1-d arrays (e.g. the result of tapply())
    x <- matrix(as.vector(x), ncol = 1)
  }
  if (!is.matrix(x) || !is.numeric(x)) {
    stop("'", arg, "' must be a numeric matrix or data frame.", call. = FALSE)
  }
  storage.mode(x) <- "double"
  x
}

# Converts a response vector, matrix or data frame to a numeric matrix.
as_response_matrix <- function(y, n, arg = "y") {
  y <- as_numeric_matrix(y, arg)
  if (nrow(y) != n) {
    stop("'x' and '", arg, "' must have the same number of rows (observations).", call. = FALSE)
  }
  y
}

# Converts a matrix to a tibble, keeping column names or creating V1, V2, ...
# names silently when there are none.
as_tbl <- function(m, names = colnames(m)) {
  m <- as.matrix(m)
  if (is.null(names) || length(names) != ncol(m)) {
    names <- paste0("V", seq_len(ncol(m)))
  }
  colnames(m) <- names
  tibble::as_tibble(m, .name_repair = "minimal")
}

check_flag <- function(x, arg) {
  if (!is.logical(x) || length(x) != 1 || is.na(x)) {
    stop("'", arg, "' must be a single logical value (TRUE or FALSE).", call. = FALSE)
  }
  invisible(x)
}

# For the functions of a single variable: stops unless `x` is a numeric vector
# or a 1-d array (such as the result of tapply()). A matrix is not pooled into
# one result; the message shows how to get one result per column.
check_numeric_vector <- function(x, fn) {
  if (!is.numeric(x) || length(dim(x)) > 1) {
    stop("The input 'x' must be a numeric vector; for the columns of a data frame or matrix, ",
         "use sapply(x, ", fn, ") or apply(x, 2, ", fn, ").", call. = FALSE)
  }
  invisible(x)
}

check_number <- function(x, arg, lower = -Inf, upper = Inf, lower_open = FALSE, upper_open = FALSE) {
  ok <- is.numeric(x) && length(x) == 1 && !is.na(x) &&
    (if (lower_open) x > lower else x >= lower) &&
    (if (upper_open) x < upper else x <= upper)
  if (!ok) {
    stop("'", arg, "' must be a single numeric value in ",
         if (lower_open) "(" else "[", lower, ", ", upper, if (upper_open) ")" else "]",
         ".", call. = FALSE)
  }
  invisible(x)
}

check_count <- function(x, arg, lower = 1) {
  if (!is.numeric(x) || length(x) != 1 || is.na(x) || x %% 1 != 0 || x < lower) {
    stop("'", arg, "' must be a single integer >= ", lower, ".", call. = FALSE)
  }
  invisible(as.integer(x))
}

# Centers and/or scales the columns of a matrix, returning the parameters so
# they can be applied to new data.
preprocess <- function(x, center = TRUE, scale = FALSE) {
  mu <- if (center) colMeans(x) else rep(0, ncol(x))
  sdev <- if (scale) apply(x, 2, stats::sd) else rep(1, ncol(x))
  sdev[!is.finite(sdev) | sdev == 0] <- 1
  xs <- sweep(sweep(x, 2, mu, "-"), 2, sdev, "/")
  list(x = xs, center = mu, scale = sdev)
}

apply_preprocess <- function(x, pp) {
  sweep(sweep(x, 2, pp$center, "-"), 2, pp$scale, "/")
}

# Runs `expr` with a fixed RNG seed and restores the caller's RNG state.
with_seed <- function(seed, expr) {
  env <- globalenv()
  old <- if (exists(".Random.seed", envir = env, inherits = FALSE)) get(".Random.seed", envir = env) else NULL
  on.exit({
    if (is.null(old)) {
      if (exists(".Random.seed", envir = env, inherits = FALSE)) rm(".Random.seed", envir = env)
    } else {
      assign(".Random.seed", old, envir = env)
    }
  })
  set.seed(seed)
  expr
}

# Parses wavelength column names ("200.5", "X200.5", "wl_200.5") to numbers.
parse_wavelength <- function(nms) {
  num <- suppressWarnings(as.numeric(nms))
  bad <- is.na(num)
  if (any(bad)) {
    num[bad] <- suppressWarnings(as.numeric(sub("^[^0-9+-.]*", "", nms[bad])))
  }
  num
}

# Wavelengths from variable names, or NULL when the names are not all
# wavelengths or are default names (V1, V2, ...).
names_to_wavelength <- function(nms) {
  if (length(nms) == 0 || identical(nms, paste0("V", seq_along(nms)))) return(NULL)
  wl <- parse_wavelength(nms)
  if (anyNA(wl)) NULL else wl
}

# Column indices of the detector segments of a spectral axis (see
# wavelength_segments()): one segment of all `n` columns when `segments` is
# FALSE or the names `nms` are not all wavelengths.
segment_columns <- function(nms, segments, n = length(nms)) {
  idx <- seq_len(n)
  if (segments && !is.null(nms) && n > 2) {
    wl <- parse_wavelength(nms)
    if (!anyNA(wl)) return(unname(split(idx, wavelength_segments(wl))))
  }
  list(idx)
}

# Column medians, in C++ (as apply(x, 2, stats::median, na.rm = na.rm), with
# the column names).
col_medians <- function(x, na.rm = FALSE) {
  if (!is.matrix(x)) x <- as.matrix(x)
  storage.mode(x) <- "double"
  stats::setNames(col_medians_cpp(x, na.rm), colnames(x))
}

# Downloads 'url' to 'file' from an online database (NIST ASD, STARK-B). A
# busy server (HTTP 5xx, such as 504 Gateway Timeout) is tried again after
# 'wait' seconds, up to 'attempts' times. The error gives the HTTP status,
# which download.file() reports after a less telling warning ("downloaded
# length 0 != reported length ..."). 'timeout' replaces the option `timeout`
# for the download, so that a server that does not answer is given up on
# after that time.
download_data <- function(url, file, database, label, timeout, attempts = 3, wait = 5) {
  old <- options(timeout = timeout)
  on.exit(options(old), add = TRUE)
  for (i in seq_len(attempts)) {
    problems <- character()
    withCallingHandlers(
      tryCatch(download_file(url, file), error = function(e) {
        problems <<- c(problems, conditionMessage(e))
      }),
      warning = function(w) {
        problems <<- c(problems, conditionMessage(w))
        invokeRestart("muffleWarning")
      }
    )
    if (length(problems) == 0 && file.exists(file) && file.size(file) > 0) {
      return(invisible(file))
    }
    http <- regmatches(problems, regexpr("HTTP status was '[^']*'", problems))
    reason <- if (length(http) > 0) {
      sub("HTTP status was '([^']*)'", "HTTP status \\1", http[1])
    } else if (length(problems) > 0) {
      problems[1]
    } else {
      "empty response"
    }
    if (!startsWith(reason, "HTTP status 5") || i == attempts) {
      break
    }
    Sys.sleep(wait)
  }
  stop("Could not download ", database, " data for ", label, " (", reason, "). ",
       "Check the internet connection, or try again later.", call. = FALSE)
}

download_file <- function(url, file) {
  utils::download.file(url, file, quiet = TRUE, mode = "wb")
}

Try the specProc package in your browser

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

specProc documentation built on Nov. 20, 2026, 5:11 p.m.