R/prtree_grid_expansion.R

Defines functions .expand_sigma_grid print.sigma_grid expand_sigma_grid

Documented in expand_sigma_grid print.sigma_grid

# Last revision: July/2026

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Generates a grid of sigmas #----
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#' @title Create a grid of sigma vectors for Probabilistic Regression Trees
#'
#' @description Creates a grid of candidate \eqn{\boldsymbol\sigma} vectors for
#'   use in [pr_tree]. The grid is generated from the feature standard
#'   deviations of `X`, or using unit scales when `X = NULL`
#'
#' @details When `X` is provided, the grid is based on the empirical standard
#'   deviations of the features. If a standard deviation for a feature cannot be
#'   computed (e.g., due to all missing values or a constant feature), it
#'   defaults to 1.0 to ensure the grid generation proceeds without errors.
#'
#' @param X A numeric vector, matrix or data frame of predictor variables. If
#'   `NULL`, the grid is generated using unit scales (all features = 1.0). In
#'   this case, `n_feat` must be provided.
#'
#' @param n_feat Optional integer. Number of features. Required when `X = NULL`.
#'   Ignored when `X` is provided.
#'
#' @param idx_train Optional integer vector. Indices of observations to use for
#'   computing feature standard deviations. If `NULL` (default), all
#'   observations in `X` are used. Ignored when `X = NULL`.
#'
#' @template template_sigma_auto
#' @template template_verbose
#' @examples
#' \donttest{
#' # With actual data, default range (0, 2]
#' X <- matrix(runif(100 * 3, 0, 10), ncol = 3)
#' grid1 <- expand_sigma_grid(X, grid_size = 8)
#'
#' # Custom range with min_mult > 0 (includes min_mult)
#' grid2 <- expand_sigma_grid(X, grid_size = 8, min_mult = 0.5, max_mult = 3)
#'
#' # Without data (unit scales)
#' grid3 <- expand_sigma_grid(n_feat = 3, grid_size = 8)
#'
#' # Only tiny sigma
#' grid4 <- expand_sigma_grid(n_feat = 3, grid_size = 0, tiny_sigma = 1e-20)
#' }
#'
#' @seealso
#' [pr_tree_control] for setting control parameters.
#'
#' [pr_tree_control_cv] for cross-validation settings.
#'
#' [pr_tree] for fitting a single tree.
#'
#' [pr_tree_cv] for cross-validation.
#'
#' @export
expand_sigma_grid <- function(X = NULL, n_feat = NULL, idx_train = NULL,
                              grid_size = 8, min_mult = 0, max_mult = 2,
                              tiny_sigma = NULL, verbose = TRUE) {
  # Validate arguments that are ALWAYS needed
  # Update in the LOCAL environment
  .validate.args(
    verbose = verbose,
    tiny_sigma = tiny_sigma,
    grid_size = grid_size, # validated agains tiny_sigma
    min_mult = min_mult, # validated against grid_size
    max_mult = max_mult
  )

  # check if X was provided
  # if X is NULL, validate n_feat (required in this case)
  x_null <- is.null(X)
  if (x_null) {
    n_feat <- .validate.arg(
      value = n_feat, name = "n_feat",
      type = "integer", length = 1, positive = TRUE, required = TRUE,
      msg = "'n_feat' must be provided when X = NULL."
    )
  } else if (grid_size > 0) {
    # final validation for the case grid_size > 0:
    #  - Required: multipliers (already validated)
    #  - Optional: X, idx_train
    X <- .check.X(X)
    n_feat <- ncol(X)
    idx_train <- .rule.idx_train(n_obs = nrow(X))$custom(x = idx_train)
  }

  # Create the grid
  sigma_grid <- .expand_sigma_grid(
    X = X, n_feat = n_feat, idx_train = idx_train,
    grid_size = grid_size, min_mult = min_mult, max_mult = max_mult,
    tiny_sigma = tiny_sigma, verbose = verbose
  )

  # Add minimal metadata
  if (!is.null(X) && !is.null(colnames(X))) {
    colnames(sigma_grid) <- colnames(X)
  } else {
    colnames(sigma_grid) <- paste0("V", 1:n_feat)
  }
  storage.mode(sigma_grid) <- "double"
  attr(sigma_grid, "has_tiny") <- !is.null(tiny_sigma)
  class(sigma_grid) <- c("sigma_grid", class(sigma_grid))

  return(sigma_grid)
}

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Print method #----
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#' @title Print method for sigma grid objects
#'
#' @description
#' Prints a summary of a sigma grid generated by [expand_sigma_grid].
#'
#' @param x An object of class `sigma_grid`, as returned by [expand_sigma_grid].
#' @param digits minimal number of significant digits.
#' @param ... Further arguments passed to or from other methods.
#'
#' @return Invisibly returns the original object.
#'
#' @export
print.sigma_grid <- function(x, digits = 4, ...) {
  # Basic matrix information
  n_rows <- nrow(x)
  n_cols <- ncol(x)
  has_tiny <- isTRUE(attr(x, "has_tiny"))

  cat("\n========================================================\n")
  cat("Sigma Grid\n")
  cat("========================================================\n")

  # Grid size
  if (has_tiny) {
    cat(sprintf(
      "Grid size: %d candidates (%d + 1 tiny)\n",
      n_rows, n_rows - 1
    ))
  } else {
    cat(sprintf("Grid size: %d candidates\n", n_rows))
  }

  cat(sprintf("Features: %d\n", n_cols))

  # First rows - with smart formatting
  cat("\nFirst ", min(5, n_rows), " rows:\n", sep = "")
  print_rows <- min(5, n_rows)

  # Create a copy for formatting
  x_print <- x[1:print_rows, , drop = FALSE]

  # Detect if there are very small values
  if (has_tiny && any(x_print[1, ] < 1e-10)) {
    # Mixed formatting: scientific for first row, fixed for the rest
    row_names <- rownames(x_print)
    if (is.null(row_names)) row_names <- 1:print_rows

    # Print header
    cat(formatC("", width = 8))
    for (j in 1:n_cols) {
      col_name <- if (!is.null(colnames(x))) colnames(x)[j] else paste0("V", j)
      cat(sprintf(" %10s", col_name))
    }
    cat("\n")

    # First row (tiny) in scientific notation
    cat(sprintf("%-8s", row_names[1]))
    for (j in 1:n_cols) {
      cat(sprintf(" %10.2e", x_print[1, j]))
    }
    cat("\n")

    # Remaining rows in fixed format
    for (i in 2:print_rows) {
      cat(sprintf("%-8s", row_names[i]))
      for (j in 1:n_cols) {
        if (abs(x_print[i, j]) < 1e-4) {
          cat(sprintf(" %10.2e", x_print[i, j]))
        } else {
          cat(sprintf(" %10.4f", x_print[i, j]))
        }
      }
      cat("\n")
    }
  } else {
    # Default formatting if no tiny values
    print(x_print, digits = digits)
  }

  if (n_rows > 5) {
    cat("... (", n_rows - 5, " more rows)\n", sep = "")
  }

  cat("========================================================\n")
  return(invisible(x))
}

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Internal. Grid creation #----
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#' @importFrom stats sd
.expand_sigma_grid <- function(X, n_feat, idx_train, grid_size,
                               min_mult, max_mult, tiny_sigma, verbose) {
  # if grid_size  = 0, no normal candidates
  if (grid_size < 1) {
    return(matrix(tiny_sigma, ncol = n_feat))
  }

  # if X is null, use multiples of 1
  # otherwise, create a grid based on sd(X)
  if (is.null(X)) {
    ss <- rep(1, n_feat)
  } else {
    # Use all observations if idx_train not provided
    if (is.null(idx_train)) idx_train <- 1:nrow(X)

    # compute the sd by column
    ss <- apply(X[idx_train, , drop = FALSE], 2, function(x) stats::sd(x, na.rm = TRUE))
    w <- is.na(ss) | ss == 0

    if (any(w)) {
      if (verbose) {
        .warning.message(paste0(
          "  Unable to compute standard deviation for feature(s):\n  ",
          paste(which(w), collapse = ", "),
          ".\n  Using 1.0 instead."
        ))
      }
      ss[w] <- 1.0
    }
  }

  # if grid_size = 1, uses the sd as estimates
  # if grid_size > 1, creates a grid with multiples of the sd
  if (grid_size < 2) {
    sigma_grid <- matrix(ss, nrow = 1)
  } else {
    if (min_mult > 0) {
      multipliers <- seq(from = min_mult, to = max_mult, length.out = grid_size)
    } else {
      multipliers <- seq(from = min_mult, to = max_mult, length.out = grid_size + 1)[-1]
    }
    sigma_grid <- outer(multipliers, ss, FUN = "*")
  }

  # If requested, add tiny row at the top (so it's the first candidate)
  if (!is.null(tiny_sigma)) {
    tiny_row <- matrix(rep(tiny_sigma, length(ss)), nrow = 1)
    sigma_grid <- rbind(tiny_row, sigma_grid)
  }
  return(sigma_grid)
}

Try the PRTree package in your browser

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

PRTree documentation built on Nov. 23, 2026, 9:08 a.m.