R/024_expressions_variable.R

#####
## DO NOT EDIT THIS FILE!! EDIT THE SOURCE INSTEAD: rsrc_tree/expressions/variable.R
#####

## CVXPY SOURCE: expressions/variable.py
## Variable -- an optimization variable

#' Create an Optimization Variable
#'
#' Constructs a variable to be used in a CVXR optimization problem. Variables
#' are decision variables that the solver optimizes over.
#'
#' @param shape Integer vector of length 1 or 2 giving the variable dimensions.
#'   A scalar \code{n} is interpreted as \code{c(n, 1)}.
#'   Defaults to \code{c(1, 1)} (scalar).
#' @param name Optional character string name for the variable. If \code{NULL},
#'   an automatic name \code{"var<id>"} is generated.
#' @param var_id Optional integer ID. If \code{NULL}, a unique ID is generated.
#' @param latex_name Optional character string giving a custom LaTeX name for
#'   use in visualizations. For example, \code{"\\\\mathbf{x}"}.
#'   If \code{NULL} (default), visualizations auto-generate a LaTeX name.
#' @param ... Additional attributes: \code{nonneg}, \code{nonpos}, \code{PSD},
#'   \code{NSD}, \code{symmetric}, \code{boolean}, \code{integer}, etc.
#' @returns A \code{Variable} object (inherits from \code{Leaf} and
#'   \code{Expression}).
#'
#' @examples
#' x <- Variable(3)        # 3x1 column vector
#' X <- Variable(c(2, 3))  # 2x3 matrix
#' y <- Variable(2, nonneg = TRUE)  # non-negative variable
#' z <- Variable(3, name = "z", latex_name = "\\mathbf{z}")  # custom LaTeX
#'
#' @export
Variable <- new_class("Variable", parent = Leaf, package = "CVXR",
  properties = list(
    .name = new_property(class = class_character),
    .latex_name = new_property(class = class_character)
  ),
  constructor = function(shape = c(1L, 1L), name = NULL, var_id = NULL,
                         latex_name = NULL, ...) {
    ## Normalize scalar shape: Variable(3) -> c(3, 1)
    if (is.numeric(shape) && length(shape) == 1L) {
      shape <- c(as.integer(shape), 1L)
    }
    shape <- validate_shape(shape)

    id <- if (!is.null(var_id)) as.integer(var_id) else next_expr_id()

    ## Auto-name deferred: compute lazily in expr_name() to avoid paste0 overhead
    ## for intermediate variables created during canonicalization.
    ## CVXPY SOURCE: variable.py lines 40-45
    if (is.null(name)) {
      nm <- ""
    } else if (!is.character(name)) {
      cli_abort("Variable name {.val {as.character(name)}} must be a string.")
    } else {
      nm <- name
    }

    ## LaTeX name for visualizations (visualization-only, never touches solver)
    lnm <- if (is.null(latex_name)) "" else as.character(latex_name)

    ## Build leaf attributes from ...
    attrs <- do.call(.build_leaf_attrs, c(list(shape = shape), list(...)))

    obj <- new_object(S7_object(),
      id = as.integer(id),
      .cache = new.env(parent = emptyenv()),
      shape = shape,
      .value = NULL,
      attributes = attrs,
      args = list(),
      .name = nm,
      .latex_name = lnm
    )

    obj
  }
)

# -- expr_name ---------------------------------------------------------

method(expr_name, Variable) <- function(x) {
  nm <- x@.name
  if (nchar(nm) == 0L) {
    nm <- x@.cache$.auto_name
    if (is.null(nm)) {
      nm <- paste0(VAR_PREFIX, x@id)
      x@.cache$.auto_name <- nm
    }
  }
  nm
}

# -- is_constant: Variables are NOT constant ---------------------------
## CVXPY SOURCE: variable.py line 57-58

method(is_constant, Variable) <- function(x) FALSE

# -- variables: returns self -------------------------------------------
## CVXPY SOURCE: variable.py line 69-71

method(variables, Variable) <- function(x) list(x)

# -- grad: identity sparse matrix -------------------------------------
## CVXPY SOURCE: variable.py line 61-67

method(grad, Variable) <- function(x) {
  sz <- expr_size(x)
  id_mat <- make_sparse_diagonal_matrix(sz)
  result <- list()
  result[[as.character(x@id)]] <- id_mat
  result
}

# -- canonicalize: create_var LinOp ------------------------------------
## CVXPY SOURCE: variable.py line 73-76

method(canonicalize, Variable) <- function(x) {
  obj <- create_var(x@shape, x@id)
  list(obj, list())
}

# -- print -------------------------------------------------------------

method(print, Variable) <- function(x, ...) {
  cat(sprintf("Variable((%s), %s)\n",
              paste(x@shape, collapse = ", "),
              expr_name(x)))
  invisible(x)
}

Try the CVXR package in your browser

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

CVXR documentation built on March 6, 2026, 9:10 a.m.