R/033_atoms_elementwise_elementwise.R

Defines functions .elemwise_promote

#####
## DO NOT EDIT THIS FILE!! EDIT THE SOURCE INSTEAD: rsrc_tree/atoms/elementwise/elementwise.R
#####

## CVXPY SOURCE: atoms/elementwise/elementwise.py
## Elementwise -- abstract base class for elementwise atoms
##
## Elementwise atoms operate on each element independently and produce
## output with the same shape as the broadcasted arguments.


Elementwise <- new_class("Elementwise", parent = Atom, package = "CVXR",
  constructor = function(args, id = NULL) {
    if (is.null(id)) id <- next_expr_id()
    args <- lapply(args, as_expr)
    if (length(args) == 0L) {
      cli_abort("No arguments given to {.cls Elementwise}.")
    }
    ## shape_from_args: elementwise uses sum_shapes (broadcasting)
    shape <- sum_shapes(lapply(args, function(a) a@shape))
    obj <- new_object(S7_object(),
      id    = as.integer(id),
      .cache = new.env(parent = emptyenv()),
      args  = args,
      shape = shape
    )
    validate_arguments(obj)
    obj
  }
)

# -- shape_from_args: broadcasting ---------------------------------
## CVXPY SOURCE: elementwise.py lines 30-33
method(shape_from_args, Elementwise) <- function(x) {
  sum_shapes(lapply(x@args, function(a) a@shape))
}

# -- validate_arguments: check broadcastable shapes ----------------
## CVXPY SOURCE: elementwise.py lines 35-41
method(validate_arguments, Elementwise) <- function(x) {
  ## Verify shapes are broadcastable (sum_shapes will abort on mismatch)
  sum_shapes(lapply(x@args, function(a) a@shape))
  ## Call Atom's validate_arguments (rejects complex arguments)
  ## NOTE: Can't use NextMethod() with S7 generics -- call Atom's method directly
  if (.any_args(x, is_complex)) {
    cli_abort("Arguments to {.cls {class(x)[[1L]]}} cannot be complex.")
  }
  invisible(NULL)
}

# -- is_symmetric --------------------------------------------------
## CVXPY SOURCE: elementwise.py lines 43-47
method(is_symmetric, Elementwise) <- function(x) {
  symm_args <- .all_args(x, is_symmetric)
  x@shape[1L] == x@shape[2L] && symm_args
}

# -- Helper: promote LinOp if needed ------------------------------
## CVXPY SOURCE: elementwise.py lines 63-82
## Used by graph_implementation in subclasses
.elemwise_promote <- function(arg, shape) {
  if (!identical(arg$shape, as.integer(shape))) {
    promote_linop(arg, shape)
  } else {
    arg
  }
}

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.