R/062_atoms_elementwise_abs.R

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

## CVXPY SOURCE: atoms/elementwise/abs.py
## Abs -- elementwise absolute value |x|


Abs <- new_class("Abs", parent = Elementwise, package = "CVXR",
  constructor = function(x, id = NULL) {
    if (FALSE) new_object(S7_object())  ## S7 static-check guard
    if (is.null(id)) id <- next_expr_id()
    x <- as_expr(x)
    shape <- .shape(x)
    obj <- .fast_new(Abs, S7_object(),
      id    = as.integer(id),
      .cache = new.env(parent = emptyenv()),
      args  = list(x),
      shape = shape
    )
    validate_arguments(obj)
    obj
  }
)

# -- validate: allow complex (CVXPY _allow_complex = True) ------
method(validate_arguments, Abs) <- function(x) {
  ## Abs allows complex arguments; override Elementwise's complex rejection
  invisible(NULL)
}

# -- bounds: |[lb, ub]| (#3080) -----------------------------------
## CVXPY SOURCE: elementwise/abs.py:56-59.
method(bounds_from_args, Abs) <- function(x) {
  b <- get_bounds(.args(x)[[1L]])
  abs_bounds(b[[1L]], b[[2L]])
}

# -- sign: always nonneg ------------------------------------------
method(sign_from_args, Abs) <- function(x) {
  list(is_nonneg = TRUE, is_nonpos = FALSE)
}

# -- curvature: convex --------------------------------------------
method(is_atom_convex, Abs) <- function(x) TRUE
method(is_atom_concave, Abs) <- function(x) FALSE

# -- monotonicity -------------------------------------------------
method(is_incr, Abs) <- function(x, idx, ...) is_nonneg(.args(x)[[idx]])
method(is_decr, Abs) <- function(x, idx, ...) is_nonpos(.args(x)[[idx]])

# -- PWL ----------------------------------------------------------
method(is_pwl, Abs) <- function(x) {
  is_pwl(.args(x)[[1L]])
}

# -- numeric ------------------------------------------------------
method(numeric_value, Abs) <- function(x, values, ...) {
  abs(values[[1L]])
}

# -- graph_implementation: stub (uses SOCP in CVXPY) --------------
method(graph_implementation, Abs) <- function(x, arg_objs, shape, data = NULL, ...) {
  ## Full graph implementation requires SOCP constraints
  ## For now, stub
  cli_abort("graph_implementation for {.cls Abs} not yet implemented.")
}

# -- .grad: per-atom subgradient ----------------------------------
## CVXPY SOURCE: atoms/elementwise/abs.py:68-85 (abs._grad).
## Diagonal of +1 where x > 0, -1 where x < 0, 0 elsewhere
## (subgradient choice 0 at x = 0 is the canonical CVXPY pick).
method(.grad, Abs) <- function(x, values, ...) {
  rows <- as.integer(prod(.arg_shape(x)))
  cols <- as.integer(prod(.shape(x)))
  v <- values[[1L]]
  D <- (v > 0) - (v < 0)         # +1 / -1 / 0 elementwise
  list(.elemwise_grad_to_diag(D, rows, cols))
}

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.