R/011_utilities_grad.R

Defines functions .error_grad .constant_grad

Documented in .constant_grad .error_grad

#####
## DO NOT EDIT THIS FILE!! EDIT THE SOURCE INSTEAD: rsrc_tree/utilities/grad.R
#####

## CVXPY SOURCE: utilities/grad.py
## Gradient utility functions used by the chain-rule walker.

#' Gradient of a Constant Expression
#'
#' Returns a Variable -> Jacobian list for an expression that is constant in
#' all of its variables. Each Jacobian is the appropriate-shape zero
#' (a scalar `0` for scalar/scalar; a sparse zero matrix otherwise).
#'
#' Mirrors `cvxpy/utilities/grad.py:constant_grad`.
#'
#' @param expr An expression.
#' @returns A list keyed by variable id (as character), each entry the zero
#'   Jacobian.
#' @keywords internal
.constant_grad <- function(expr) {
  vars <- variables(expr)
  expr_sz <- expr_size(expr)
  result <- list()
  for (v in vars) {
    var_sz <- expr_size(v)
    key <- as.character(.id(v))
    if (var_sz == 1L && expr_sz == 1L) {
      result[[key]] <- 0
    } else {
      result[[key]] <- Matrix::sparseMatrix(
        i = integer(0), j = integer(0),
        x = numeric(0),
        dims = c(var_sz, expr_sz),
        repr = "C"
      )
    }
  }
  result
}

#' Error Gradient (None for every variable)
#'
#' Returns a list keyed by variable id with every entry NULL. Used by the
#' chain-rule walker to propagate "could not compute" up the DAG when any
#' argument value is missing.
#'
#' Mirrors `cvxpy/utilities/grad.py:error_grad`.
#'
#' @param expr An expression.
#' @returns A list keyed by variable id (as character), each entry NULL.
#' @keywords internal
.error_grad <- function(expr) {
  vars <- variables(expr)
  result <- list()
  for (v in vars) {
    ## Use single-bracket assignment so NULL is *stored*, not removed
    ## (R's `result[[key]] <- NULL` is the wrong idiom — it deletes the entry).
    result[as.character(v@id)] <- list(NULL)
  }
  result
}

Try the CVXR package in your browser

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

CVXR documentation built on Aug. 24, 2026, 9:10 a.m.