R/196_reductions_dgp2dcp_canonicalizers_add_canon.R

Defines functions .dgp_add_canon

#####
## DO NOT EDIT THIS FILE!! EDIT THE SOURCE INSTEAD: rsrc_tree/reductions/dgp2dcp/canonicalizers/add_canon.R
#####

## CVXPY SOURCE: reductions/dgp2dcp/canonicalizers/add_canon.py
## DGP canonicalizer for AddExpression: log_sum_exp of log-space args

.dgp_add_canon <- function(expr, args) {
  ## Scalar case: log_sum_exp(hstack(args))
  if (expr_is_scalar(expr)) {
    return(list(log_sum_exp(do.call(hstack, args)), list()))
  }

  ## Promote scalar summands to expr shape
  summands <- lapply(args, function(s) {
    if (expr_is_scalar(s)) cvxr_promote(s, expr@shape) else s
  })

  rows <- list()
  if (length(expr@shape) == 1L || expr@shape[2L] == 1L) {
    ## Vector case: iterate over rows
    for (i in seq_len(expr@shape[1L])) {
      elems <- lapply(summands, function(s) s[i])
      row_elem <- log_sum_exp(do.call(hstack, elems))
      rows <- c(rows, list(list(row_elem)))
    }
  } else {
    ## Matrix case: iterate over rows and columns
    for (i in seq_len(expr@shape[1L])) {
      row <- list()
      for (j in seq_len(expr@shape[2L])) {
        elems <- lapply(summands, function(s) s[i, j])
        row <- c(row, list(log_sum_exp(do.call(hstack, elems))))
      }
      rows <- c(rows, list(row))
    }
  }
  result <- bmat(rows)
  if (!identical(result@shape, expr@shape)) {
    result <- reshape_expr(result, expr@shape)
  }
  list(result, list())
}

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.