R/141_reductions_dcp2cone_canonicalizers_cumsum_canon.R

Defines functions cumsum_canon

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

## CVXPY SOURCE: reductions/eliminate_pwl/canonicalizers/cumsum_canon.py
## cumsum(X) -> Y where Y[first] == X[first], X[rest] == Y[rest] - Y[prev]


cumsum_canon <- function(expr, args, solver_context = NULL) {
  X <- args[[1L]]
  axis <- expr@axis
  shape <- expr@shape

  ## Handle axis=NULL: flatten in C-order, then treat as 1D with axis=2
  if (is.null(axis)) {
    X <- Reshape(X, c(expr_size(X), 1L), order = "C")
    shape <- c(expr_size(X), 1L)
    axis <- 2L
  }

  ## If only one element along this axis, cumsum is identity
  if (shape[3L - axis] == 1L) {
    return(list(X, list()))
  }

  Y <- Variable(shape = shape)

  ## Build index slices for the axis
  n <- shape[3L - axis]
  if (axis == 2L) {
    ## axis=0: slice along rows
    ## Y[1, ] == X[1, ]
    ## X[2:n, ] == Y[2:n, ] - Y[1:(n-1), ]
    constr <- list(
      X[2L:n, ] == Y[2L:n, ] - Y[1L:(n - 1L), ],
      Y[1L, ] == X[1L, ]
    )
  } else {
    ## axis=1: slice along columns
    ## Y[, 1] == X[, 1]
    ## X[, 2:n] == Y[, 2:n] - Y[, 1:(n-1)]
    constr <- list(
      X[, 2L:n] == Y[, 2L:n] - Y[, 1L:(n - 1L)],
      Y[, 1L] == X[, 1L]
    )
  }

  list(Y, constr)
}

method(dcp_canonicalize, Cumsum) <- cumsum_canon
method(has_dcp_canon, Cumsum) <- function(expr) TRUE

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.