R/045_atoms_affine_trace.R

Defines functions matrix_trace

Documented in matrix_trace

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

## CVXPY SOURCE: atoms/affine/trace.py
## Trace -- sum of diagonal entries of a square matrix


Trace <- new_class("Trace", parent = AffAtom, package = "CVXR",
  constructor = function(x, id = NULL) {
    if (is.null(id)) id <- next_expr_id()
    x <- as_expr(x)
    shape <- c(1L, 1L)  # scalar

    obj <- new_object(S7_object(),
      id    = as.integer(id),
      .cache = new.env(parent = emptyenv()),
      args  = list(x),
      shape = shape
    )
    validate_arguments(obj)
    obj
  }
)

method(validate_arguments, Trace) <- function(x) {
  arg <- x@args[[1L]]
  if (arg@shape[1L] != arg@shape[2L]) {
    cli_abort("{.cls Trace} requires a square matrix, got shape ({arg@shape[1L]}, {arg@shape[2L]}).")
  }
  invisible(NULL)
}

method(shape_from_args, Trace) <- function(x) c(1L, 1L)

# -- sign: PSD/NSD propagation (CVXPY trace.py lines 54-61) ------
method(sign_from_args, Trace) <- function(x) {
  list(
    is_nonneg = is_nonneg(x@args[[1L]]) || is_psd(x@args[[1L]]),
    is_nonpos = is_nonpos(x@args[[1L]]) || is_nsd(x@args[[1L]])
  )
}

# -- log-log: convex, not concave (CVXPY trace.py lines 87-92) --
method(is_atom_log_log_convex, Trace) <- function(x) TRUE
method(is_atom_log_log_concave, Trace) <- function(x) FALSE

method(numeric_value, Trace) <- function(x, values, ...) {
  matrix(sum(diag(values[[1L]])), 1L, 1L)
}

method(graph_implementation, Trace) <- function(x, arg_objs, shape, data = NULL, ...) {
  list(trace_linop(arg_objs[[1L]]), list())
}

#' Trace of a square matrix expression
#'
#' @param x An Expression (square matrix)
#' @returns A Trace atom (scalar)
#' @export
matrix_trace <- function(x) {
  Trace(x)
}

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.