Type: Package
Title: Disciplined Convex Optimization
Version: 1.8.1
URL: https://cvxr.rbind.io, https://www.cvxgrp.org/CVXR/
BugReports: https://github.com/cvxgrp/CVXR/issues
Description: An object-oriented modeling language for disciplined convex programming (DCP) as described in Fu, Narasimhan, and Boyd (2020, <doi:10.18637/jss.v094.i14>). It allows the user to formulate convex optimization problems in a natural way following mathematical convention and DCP rules. The system analyzes the problem, verifies its convexity, converts it into a canonical form, and hands it off to an appropriate solver to obtain the solution. This version uses the S7 object system for improved performance and maintainability.
Depends: R (≥ 4.3.0)
Imports: S7 (≥ 0.2), methods, Matrix (≥ 1.7), Rcpp (≥ 1.1), clarabel (≥ 0.11), cli (≥ 3.6), gmp (≥ 0.7), highs (≥ 1.12), osqp (≥ 1.0), scs (≥ 3.2), slam (≥ 0.1)
Suggests: jsonlite (≥ 1.9), knitr, rmarkdown, testthat (≥ 3.3), rlang
Enhances: Rmosek, gurobi (≥ 13.0), Rglpk (≥ 0.6), ECOSolveR (≥ 0.6), Rcplex (≥ 0.3), cccp (≥ 0.3), piqp (≥ 0.6)
Additional_repositories: https://bnaras.r-universe.dev
LinkingTo: Rcpp, RcppEigen
License: Apache License 2.0 | file LICENSE
LazyData: true
Encoding: UTF-8
RoxygenNote: 7.3.3
VignetteBuilder: knitr
Config/testthat/edition: 3
NeedsCompilation: yes
Packaged: 2026-03-06 05:53:49 UTC; naras
Author: Anqi Fu [aut, cre], Balasubramanian Narasimhan [aut], Steven Diamond [aut], John Miller [aut], Stephen Boyd [ctb]
Maintainer: Anqi Fu <anqif@alumni.stanford.edu>
Repository: CRAN
Date/Publication: 2026-03-06 07:50:12 UTC

CVXR: Disciplined Convex Optimization

Description

logo

An object-oriented modeling language for disciplined convex programming (DCP) as described in Fu, Narasimhan, and Boyd (2020, doi:10.18637/jss.v094.i14). It allows the user to formulate convex optimization problems in a natural way following mathematical convention and DCP rules. The system analyzes the problem, verifies its convexity, converts it into a canonical form, and hands it off to an appropriate solver to obtain the solution. This version uses the S7 object system for improved performance and maintainability.

Author(s)

Maintainer: Anqi Fu anqif@alumni.stanford.edu

Authors:

Other contributors:

See Also

Useful links:


Positive Semidefinite Constraint Operator

Description

Creates a PSD constraint: e1 - e2 is positive semidefinite. This is the R equivalent of Python's A >> B.

Usage

e1 %>>% e2

Arguments

e1, e2

CVXR expressions or numeric matrices.

Value

A PSD constraint object.

See Also

PSD()

Examples

## Not run: 
X <- Variable(3, 3, symmetric = TRUE)
constr <- X %>>% diag(3)  # X - I is PSD

## End(Not run)

Negative Semidefinite Constraint Operator

Description

Creates an NSD constraint: e2 - e1 is positive semidefinite, i.e., e1 is NSD relative to e2. This is the R equivalent of Python's A << B.

Usage

e1 %<<% e2

Arguments

e1, e2

CVXR expressions or numeric matrices.

Value

A PSD constraint object.

See Also

PSD()

Examples

## Not run: 
X <- Variable(3, 3, symmetric = TRUE)
constr <- X %<<% diag(3)  # I - X is PSD (X is NSD relative to I)

## End(Not run)

Logical AND

Description

Returns 1 if and only if all arguments equal 1, and 0 otherwise. For two operands, can also be written with the & operator: x & y.

Usage

And(..., id = NULL)

Arguments

...

Two or more boolean Variables or logic expressions.

id

Optional integer ID (internal use).

Value

An And expression.

See Also

Not(), Or(), Xor(), implies(), iff()

Examples

## Not run: 
x <- Variable(boolean = TRUE)
y <- Variable(boolean = TRUE)
both <- x & y            # operator syntax
both <- And(x, y)        # functional syntax
all3 <- And(x, y, z)     # n-ary

## End(Not run)

Create a Constant Expression

Description

Wraps a numeric value as a CVXR constant for use in optimization expressions. Constants are typically created implicitly when combining numeric values with CVXR expressions via arithmetic operators.

Usage

Constant(value, name = NULL)

Arguments

value

A numeric scalar, vector, matrix, or sparse matrix.

name

Optional character string name.

Value

A Constant object (inherits from Leaf and Expression).

Examples

c1 <- Constant(5)
c2 <- Constant(matrix(1:6, 2, 3))


DCP Error condition

Description

Creates a custom R condition of class "DCPError" for disciplined convex programming violations.

Usage

DCPError(message, call = sys.call(-1L))

Arguments

message

Character error message

call

The call to include in the condition (default: caller's call)

Value

A condition object of class c("DCPError", "error", "condition")


Extract Diagonal from a Matrix

Description

Extracts the k-th diagonal of a square matrix as a column vector.

Usage

DiagMat(x, k = 0L, id = NULL)

Arguments

x

A CVXR expression (square matrix).

k

Integer diagonal offset. k = 0 (default) is the main diagonal, k > 0 is above, k < 0 is below.

id

Optional integer ID.

Value

A DiagMat expression of shape c(n - abs(k), 1).

See Also

DiagVec


Vector to Diagonal Matrix

Description

Constructs a diagonal matrix from a column vector. If k != 0, the vector is placed on the k-th super- or sub-diagonal.

Usage

DiagVec(x, k = 0L, id = NULL)

Arguments

x

A CVXR expression (column vector).

k

Integer diagonal offset. k = 0 (default) is the main diagonal, k > 0 is above, k < 0 is below.

id

Optional integer ID.

Value

A DiagVec expression of shape c(n + abs(k), n + abs(k)).

See Also

DiagMat


Create an Equality Constraint

Description

Constrains two expressions to be equal elementwise: lhs = rhs. Typically created via the == operator on CVXR expressions.

Usage

Equality(lhs, rhs, constr_id = NULL)

Arguments

lhs

A CVXR expression (left-hand side).

rhs

A CVXR expression (right-hand side).

constr_id

Optional integer constraint ID.

Value

An Equality constraint object.

See Also

Zero, Inequality


Create an Exponential Cone Constraint

Description

Constrains (x, y, z) to lie in the exponential cone:

K = \{(x,y,z) \mid y \exp(x/y) \le z,\; y > 0\}

Usage

ExpCone(x_expr, y_expr, z_expr, constr_id = NULL)

Arguments

x_expr

A CVXR expression.

y_expr

A CVXR expression.

z_expr

A CVXR expression.

constr_id

Optional integer constraint ID.

Details

All three arguments must be affine, real, and have the same shape.

Value

An ExpCone constraint object.


FiniteSet Constraint

Description

Constrain each entry of an Expression to take a value in a given finite set of real numbers.

Usage

FiniteSet(expre, vec, ineq_form = FALSE, constr_id = NULL)

Arguments

expre

An affine Expression.

vec

A numeric vector (or set) of allowed values.

ineq_form

Logical; controls MIP canonicalization strategy. If FALSE (default), uses equality formulation (one-hot binary). If TRUE, uses inequality formulation (sorted differences + ordering).

constr_id

Optional integer constraint ID (internal use).

Value

A FiniteSet constraint.


Create an Inequality Constraint

Description

Constrains the left-hand side to be less than or equal to the right-hand side elementwise: lhs \le rhs. Typically created via the <= operator on CVXR expressions.

Usage

Inequality(lhs, rhs, constr_id = NULL)

Arguments

lhs

A CVXR expression (left-hand side).

rhs

A CVXR expression (right-hand side).

constr_id

Optional integer constraint ID.

Value

An Inequality constraint object.

See Also

Equality, NonPos, NonNeg


Create a Maximization Objective

Description

Specifies that the objective expression should be maximized. The expression must be concave and scalar for a DCP-compliant problem.

Usage

Maximize(expr)

Arguments

expr

A CVXR expression or numeric value to maximize.

Value

A Maximize object.

See Also

Minimize, Problem

Examples

x <- Variable()
obj <- Maximize(-x^2 + 1)


Create a Minimization Objective

Description

Specifies that the objective expression should be minimized. The expression must be convex and scalar for a DCP-compliant problem.

Usage

Minimize(expr)

Arguments

expr

A CVXR expression or numeric value to minimize.

Value

A Minimize object.

See Also

Maximize, Problem

Examples

x <- Variable()
obj <- Minimize(x^2 + 1)


Create a Non-Negative Constraint

Description

Constrains an expression to be non-negative elementwise: x \ge 0.

Usage

NonNeg(expr, constr_id = NULL)

Arguments

expr

A CVXR expression.

constr_id

Optional integer constraint ID.

Value

A NonNeg constraint object.

See Also

NonPos, Inequality


Create a Non-Positive Constraint

Description

Constrains an expression to be non-positive elementwise: x \le 0.

Usage

NonPos(expr, constr_id = NULL)

Arguments

expr

A CVXR expression.

constr_id

Optional integer constraint ID.

Value

A NonPos constraint object.

See Also

NonNeg, Inequality


Logical NOT

Description

Returns 1 - x, flipping 0 to 1 and 1 to 0. Can also be written with the ! operator: !x.

Usage

Not(x, id = NULL)

Arguments

x

A boolean Variable or logic expression.

id

Optional integer ID (internal use).

Value

A Not expression.

See Also

And(), Or(), Xor(), implies(), iff()

Examples

## Not run: 
x <- Variable(boolean = TRUE)
not_x <- !x          # operator syntax
not_x <- Not(x)      # functional syntax

## End(Not run)

Logical OR

Description

Returns 1 if and only if at least one argument equals 1, and 0 otherwise. For two operands, can also be written with the | operator: x | y.

Usage

Or(..., id = NULL)

Arguments

...

Two or more boolean Variables or logic expressions.

id

Optional integer ID (internal use).

Value

An Or expression.

See Also

Not(), And(), Xor(), implies(), iff()

Examples

## Not run: 
x <- Variable(boolean = TRUE)
y <- Variable(boolean = TRUE)
either <- x | y          # operator syntax
either <- Or(x, y)       # functional syntax
any3 <- Or(x, y, z)      # n-ary

## End(Not run)

Create a Positive Semidefinite Constraint

Description

Constrains a square matrix expression to be positive semidefinite (PSD): X \succeq 0. The expression must be square.

Usage

PSD(expr, constr_id = NULL)

Arguments

expr

A CVXR expression representing a square matrix.

constr_id

Optional integer constraint ID.

Value

A PSD constraint object.


Create a Parameter

Description

Constructs a parameter whose numeric value can be changed without re-canonicalizing the problem. Parameters are treated as constants for DCP purposes but their value can be updated between solves.

Usage

Parameter(
  shape = c(1L, 1L),
  name = NULL,
  value = NULL,
  id = NULL,
  latex_name = NULL,
  ...
)

Arguments

shape

Integer vector of length 1 or 2 giving the parameter dimensions. A scalar n is interpreted as c(n, 1). Defaults to c(1, 1) (scalar).

name

Optional character string name. If NULL, an automatic name "param<id>" is generated.

value

Optional initial numeric value.

id

Optional integer ID.

latex_name

Optional character string giving a custom LaTeX name for use in visualizations. For example, "\\gamma". If NULL (default), visualizations auto-generate a LaTeX name.

...

Additional attributes: nonneg, nonpos, etc.

Value

A Parameter object (inherits from Leaf and Expression).

Examples

p <- Parameter()
value(p) <- 5
p_vec <- Parameter(3, nonneg = TRUE)
gamma <- Parameter(1, name = "gamma", latex_name = "\\gamma")


Create a 3D Power Cone Constraint

Description

Constrains (x, y, z) to lie in the 3D power cone:

x^\alpha \cdot y^{1-\alpha} \ge |z|, \quad x \ge 0, \; y \ge 0

Usage

PowCone3D(x_expr, y_expr, z_expr, alpha, constr_id = NULL)

Arguments

x_expr

A CVXR expression.

y_expr

A CVXR expression.

z_expr

A CVXR expression.

alpha

A CVXR expression or numeric value in (0, 1).

constr_id

Optional integer constraint ID.

Value

A PowCone3D constraint object.

See Also

PowConeND


Create an N-Dimensional Power Cone Constraint

Description

Constrains (W, z) to lie in the N-dimensional power cone:

\prod W_i^{\alpha_i} \ge |z|, \quad W \ge 0

where \alpha_i > 0 and \sum \alpha_i = 1.

Usage

PowConeND(W, z, alpha, axis = 2L, constr_id = NULL)

Arguments

W

A CVXR expression (vector or matrix).

z

A CVXR expression (scalar or vector).

alpha

A CVXR expression with positive entries summing to 1 along the specified axis.

axis

Integer, 2 (default, column-wise) or 1 (row-wise).

constr_id

Optional integer constraint ID.

Value

A PowConeND constraint object.

Known limitations

The R clarabel solver does not currently support the PowConeND cone specification. Problems involving PowConeND (e.g., exact geometric mean with more than 2 arguments) should use SCS or MOSEK as the solver, or use approximation-based atoms (e.g., geo_mean(x, approx = TRUE)).

See Also

PowCone3D


Create an Optimization Problem

Description

Constructs a convex optimization problem from an objective and a list of constraints. Use psolve to solve the problem.

Usage

Problem(objective, constraints = list())

Arguments

objective

A Minimize or Maximize object.

constraints

A list of Constraint objects (e.g., created by ==, <=, >= operators on expressions). Defaults to an empty list (unconstrained).

Value

A Problem object.

Known limitations

Examples

x <- Variable(2)
prob <- Problem(Minimize(sum_entries(x)), list(x >= 1))


Create a Second-Order Cone Constraint

Description

Constrains \|X_i\|_2 \le t_i for each column or row i, where t is a vector and X is a matrix.

Usage

SOC(t, X, axis = 2L, constr_id = NULL)

Arguments

t

A CVXR expression (scalar or vector) representing the upper bound.

X

A CVXR expression (vector or matrix) whose columns/rows are bounded.

axis

Integer, 2 (default, column-wise) or 1 (row-wise). Determines whether columns (2) or rows (1) of X define the individual cones.

constr_id

Optional integer constraint ID.

Value

An SOC constraint object.


Solver Error condition

Description

Creates a custom R condition of class "SolverError" for solver failures.

Usage

SolverError(message, call = sys.call(-1L))

Arguments

message

Character error message

call

The call to include in the condition (default: caller's call)

Value

A condition object of class c("SolverError", "error", "condition")


Create an Optimization Variable

Description

Constructs a variable to be used in a CVXR optimization problem. Variables are decision variables that the solver optimizes over.

Usage

Variable(shape = c(1L, 1L), name = NULL, var_id = NULL, latex_name = NULL, ...)

Arguments

shape

Integer vector of length 1 or 2 giving the variable dimensions. A scalar n is interpreted as c(n, 1). Defaults to c(1, 1) (scalar).

name

Optional character string name for the variable. If NULL, an automatic name "var<id>" is generated.

var_id

Optional integer ID. If NULL, a unique ID is generated.

latex_name

Optional character string giving a custom LaTeX name for use in visualizations. For example, "\\mathbf{x}". If NULL (default), visualizations auto-generate a LaTeX name.

...

Additional attributes: nonneg, nonpos, PSD, NSD, symmetric, boolean, integer, etc.

Value

A Variable object (inherits from Leaf and Expression).

Examples

x <- Variable(3)        # 3x1 column vector
X <- Variable(c(2, 3))  # 2x3 matrix
y <- Variable(2, nonneg = TRUE)  # non-negative variable
z <- Variable(3, name = "z", latex_name = "\\mathbf{z}")  # custom LaTeX


Logical XOR

Description

For two arguments: result is 1 iff exactly one is 1. For n arguments: result is 1 iff an odd number are 1 (parity).

Usage

Xor(..., id = NULL)

Arguments

...

Two or more boolean Variables or logic expressions.

id

Optional integer ID (internal use).

Details

Note: R's ^ operator is used for power(), so Xor is functional syntax only.

Value

A Xor expression.

See Also

Not(), And(), Or(), implies(), iff()

Examples

## Not run: 
x <- Variable(boolean = TRUE)
y <- Variable(boolean = TRUE)
exclusive <- Xor(x, y)

## End(Not run)

Create a Zero Constraint

Description

Constrains an expression to equal zero elementwise: x = 0.

Usage

Zero(expr, constr_id = NULL)

Arguments

expr

A CVXR expression.

constr_id

Optional integer constraint ID.

Value

A Zero constraint object.

See Also

Equality, NonPos, NonNeg


Convert a value to a CVXR Expression

Description

Wraps numeric vectors, matrices, and Matrix package objects as CVXR Constant objects. Values that are already CVXR expressions are returned unchanged.

Usage

as_cvxr_expr(x)

Arguments

x

A numeric vector, matrix, Matrix::Matrix object, Matrix::sparseVector object, or CVXR expression.

Value

A CVXR expression (either the input unchanged or wrapped in Constant).

Matrix package interoperability

Objects from the Matrix package (dgCMatrix, dgeMatrix, ddiMatrix, sparseVector, etc.) are S4 classes. Because S4 dispatch preempts S7/S3 dispatch, raw Matrix objects cannot be used directly with CVXR operators (+, -, *, /, %*%, >=, ==, etc.).

Use as_cvxr_expr() to wrap a Matrix object as a CVXR Constant before combining it with CVXR variables or expressions. This preserves sparsity (unlike as.matrix(), which densifies).

Base R matrix and numeric objects work natively with CVXR operators — no wrapping is needed.

Examples

x <- Variable(3)

## Sparse Matrix needs as_cvxr_expr() for CVXR operator dispatch:
A <- Matrix::sparseMatrix(i = 1:3, j = 1:3, x = 1.0)
expr <- as_cvxr_expr(A) %*% x

## All operators work with wrapped Matrix objects:
y <- Variable(c(3, 3))
expr2 <- as_cvxr_expr(A) + y
constr <- as_cvxr_expr(A) >= y

## Base R matrix works natively (no wrapping needed):
D <- matrix(1:9, 3, 3)
expr3 <- D %*% x

Get Atom-Specific Domain Constraints

Description

Get Atom-Specific Domain Constraints

Usage

atom_domain(x, ...)

Arguments

x

An atom object.

...

Not used.

Value

List of Constraint objects.


Get the Atoms in an Expression

Description

Get the Atoms in an Expression

Usage

atoms(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

List of atom objects.


List available solvers

Description

Returns the names of installed solvers that are not currently excluded. Use exclude_solvers() to temporarily disable solvers.

Usage

available_solvers()

exclude_solvers(solvers)

include_solvers(solvers)

set_excluded_solvers(solvers)

Arguments

solvers

A character vector of solver names.

Value

A character vector of solver names.

The current exclusion list (character vector), invisibly.

Functions

See Also

installed_solvers(), exclude_solvers(), include_solvers(), set_excluded_solvers()


Construct a Block Matrix

Description

Takes a list of lists. Each internal list is stacked horizontally. The internal lists are stacked vertically.

Usage

bmat(block_lists)

Arguments

block_lists

A list of lists of Expression objects (or numerics). Each inner list forms one block row.

Value

An Expression representing the block matrix.


Broadcast two expressions for binary operations

Description

Broadcast two expressions for binary operations

Usage

broadcast_args(lh_expr, rh_expr)

Arguments

lh_expr

Left-hand expression

rh_expr

Right-hand expression

Value

List of two expressions with compatible shapes


Get the Canonical Form

Description

Get the Canonical Form

Usage

canonical_form(x, ...)

Arguments

x

A canonicalizable object.

...

Not used.

Value

List with (expression, constraints).


Canonicalize an Expression

Description

Canonicalize an Expression

Usage

canonicalize(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

List with canonicalized expression and constraints.


Global Monthly and Annual Temperature Anomalies (degrees C), 1850-2015 (Relative to the 1961-1990 Mean) (May 2016)

Description

Global Monthly and Annual Temperature Anomalies (degrees C), 1850-2015 (Relative to the 1961-1990 Mean) (May 2016)

Usage

cdiac

Format

A data frame with 166 rows and 14 variables:

year

Year

jan

Anomaly for month of January

feb

Anomaly for month of February

mar

Anomaly for month of March

apr

Anomaly for month of April

may

Anomaly for month of May

jun

Anomaly for month of June

jul

Anomaly for month of July

aug

Anomaly for month of August

sep

Anomaly for month of September

oct

Anomaly for month of October

nov

Anomaly for month of November

dec

Anomaly for month of December

annual

Annual anomaly for the year

Source

https://ess-dive.lbl.gov/

References

https://ess-dive.lbl.gov/


Elementwise Ceiling

Description

Returns the ceiling (smallest integer >= x) of each element. This atom is quasiconvex and quasiconcave but NOT convex or concave, so it can only be used in DQCP problems (solved with qcp = TRUE).

Usage

ceil_expr(x)

Arguments

x

A CVXR expression.

Value

A Ceil expression.

See Also

floor_expr


Condition number of a PSD matrix

Description

Computes the condition number lambda_max(A) / lambda_min(A) for a positive semidefinite matrix A. This is a quasiconvex atom.

Usage

condition_number(A)

Arguments

A

A square matrix expression (must be PSD)

Value

An expression representing the condition number of A


Get the Sizes of Individual Cones

Description

Get the Sizes of Individual Cones

Usage

cone_sizes(x, ...)

Arguments

x

A cone constraint object.

...

Not used.

Value

Integer vector of cone sizes.


Elementwise Complex Conjugate

Description

Returns the complex conjugate of an expression. For real expressions this is a no-op. R's native Conj() dispatches here for CVXR expressions via the Complex S3 group handler.

Usage

conj_expr(expr)

Arguments

expr

A CVXR Expression.

Value

A Conj_ atom.


Get the Constants in an Expression

Description

Get the Constants in an Expression

Usage

constants(x, ...)

Arguments

x

An expression or problem object.

...

Not used.

Value

List of Constant objects.


Get the Total Size of a Constraint

Description

Get the Total Size of a Constraint

Usage

constr_size(x, ...)

Arguments

x

A constraint object.

...

Not used.

Value

Integer.


Get Problem Constraints (read-only)

Description

Returns a copy of the problem's constraint list.

Usage

constraints(x)

Arguments

x

A Problem object.

Details

Problem objects are immutable: constraints cannot be modified after construction. To change constraints, create a new Problem(). This matches CVXPY's design where problems are immutable except through Parameter value changes.

Value

A list of constraint objects.

See Also

Problem(), objective()

Examples

x <- Variable(2)
prob <- Problem(Minimize(sum_entries(x)), list(x >= 1))
length(constraints(prob))  # 1


1D discrete convolution

Description

1D discrete convolution

Usage

conv(a, b)

Arguments

a

An Expression (vector, one must be constant)

b

An Expression (vector)

Value

A Convolve atom


Cumulative maximum along an axis

Description

Cumulative maximum along an axis

Usage

cummax_expr(x, axis = 2L)

Arguments

x

An Expression

axis

1 (across rows) or 2 (down columns, default)

Value

A Cummax atom


Cumulative sum along an axis

Description

Cumulative sum along an axis

Usage

cumsum_axis(x, axis = NULL)

Arguments

x

An Expression

axis

NULL (all), 1 (across rows), or 2 (down columns)

Value

A Cumsum atom


Get Expression Curvature

Description

Returns the DCP curvature of an expression as a string.

Usage

curvature(x)

Arguments

x

A CVXR expression.

Value

Character: "CONSTANT", "AFFINE", "CONVEX", "CONCAVE", or "UNKNOWN".

See Also

is_convex(), is_concave(), is_affine(), is_constant()


Conditional Value at Risk (CVaR)

Description

CVaR at confidence level beta: average of the (1-beta) largest values.

Usage

cvar(x, beta)

Arguments

x

An Expression (vector)

beta

Confidence level in [0, 1)

Value

An Expression representing the CVaR


Compute kth Order Differences of an Expression

Description

Takes in an expression and returns an expression with the kth order differences along the given axis. The output shape is the same as the input except the size along the specified axis is reduced by k.

Usage

cvxr_diff(x, k = 1L, axis = 2L)

Arguments

x

An Expression or numeric value.

k

Integer. The number of times values are differenced. Default is 1. (Mapped from R's lag argument in diff.default; use differences for repeated differencing which maps to k here.)

axis

Integer. The axis along which the difference is taken. 2 = along rows/down columns (default), 1 = along columns/across rows.

Value

An Expression representing the kth order differences.


Mean of an expression

Description

Computes the arithmetic mean of an expression along an axis.

Usage

cvxr_mean(x, axis = NULL, keepdims = FALSE)

Arguments

x

An Expression or numeric value.

axis

NULL (all), 1 (row-wise), or 2 (column-wise).

keepdims

Logical; keep reduced dimension?

Value

An Expression representing the mean.


Compute a norm of an expression

Description

Compute a norm of an expression

Usage

cvxr_norm(x, p = 2, axis = NULL, keepdims = FALSE, max_denom = 1024L)

Arguments

x

An Expression

p

Norm type: 1, 2, Inf, or "fro" (Frobenius)

axis

NULL (all), 0 (columns), or 1 (rows)

keepdims

Logical

max_denom

Integer max denominator

Value

A norm atom


Outer product of two vectors

Description

Computes the outer product x %*% t(y). Both inputs must be vectors.

Usage

cvxr_outer(x, y)

Arguments

x

An Expression or numeric value (vector).

y

An Expression or numeric value (vector).

Value

An Expression of shape (length(x), length(y)).


Promote a scalar expression to the given shape

Description

Promote a scalar expression to the given shape

Usage

cvxr_promote(expr, shape)

Arguments

expr

An expression

shape

Target shape

Value

The expression (unchanged if already the right shape) or a Promote atom


Standard deviation of an expression

Description

Computes the standard deviation of an expression.

Usage

cvxr_std(x, axis = NULL, keepdims = FALSE, ddof = 0)

std(x, axis = NULL, keepdims = FALSE, ddof = 0)

Arguments

x

An Expression or numeric value.

axis

NULL (all), 1 (row-wise), or 2 (column-wise).

keepdims

Logical; keep reduced dimension?

ddof

Degrees of freedom correction (default 0, population std).

Value

An Expression representing the standard deviation.


Variance of an expression

Description

Computes the variance. Only supports full reduction (axis = NULL).

Usage

cvxr_var(x, axis = NULL, keepdims = FALSE, ddof = 0)

Arguments

x

An Expression or numeric value.

axis

NULL only (axis reduction not yet supported).

keepdims

Logical; keep reduced dimension?

ddof

Degrees of freedom correction (default 0, population variance).

Value

An Expression representing the variance.


The difference x - y with domain x > y > 0

Description

Equivalent to x * one_minus_pos(y / x).

Usage

diff_pos(x, y)

Arguments

x

An Expression (positive)

y

An Expression (positive, elementwise less than x)

Value

A product expression


Distance ratio

Description

Computes norm(x - a)_2 / norm(x - b)_2, where a and b are constants. This is a quasiconvex atom.

Usage

dist_ratio(x, a, b)

Arguments

x

A vector expression

a

A numeric constant vector

b

A numeric constant vector

Value

An expression representing the distance ratio


Get the Domain Constraints of an Expression

Description

Get the Domain Constraints of an Expression

Usage

domain(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

List of constraints defining the domain.


Weighted sorted dot product

Description

Computes ⁠<sort(vec(X)), sort(vec(W))>⁠ where X is an expression and W is a constant. A generalization of sum_largest and sum_smallest.

Usage

dotsort(X, W)

Arguments

X

An Expression or numeric value.

W

A constant numeric vector or matrix.

Value

A scalar convex Expression.


Check if DPP Scope is Active

Description

Check if DPP Scope is Active

Usage

dpp_scope_active()

Value

Logical; TRUE if a with_dpp_scope block is active.


Direct Standardization: Population

Description

Randomly generated data for direct standardization example. Sex was drawn from a Bernoulli distribution, and age was drawn from a uniform distribution on 10,\ldots,60. The response was drawn from a normal distribution with a mean that depends on sex and age, and a variance of 1.

Usage

dspop

Format

A data frame with 1000 rows and 3 variables:

y

Response variable

sex

Sex of individual, coded male (0) and female (1)

age

Age of individual

See Also

dssamp


Direct Standardization: Sample

Description

A sample of dspop for direct standardization example. The sample is skewed such that young males are overrepresented in comparison to the population.

Usage

dssamp

Format

A data frame with 100 rows and 3 variables:

y

Response variable

sex

Sex of individual, coded male (0) and female (1)

age

Age of individual

See Also

dspop


Get the Dual Cone Constraint

Description

Get the Dual Cone Constraint

Usage

dual_cone(x, ...)

Arguments

x

A cone constraint object.

...

Optional arguments.

Value

A cone constraint representing the dual cone.


Get the Dual Residual

Description

Get the Dual Residual

Usage

dual_residual(x, ...)

Arguments

x

A cone constraint object.

...

Not used.

Value

Numeric residual.


Get the Dual Value of a Constraint

Description

Returns the dual variable value(s) associated with a constraint after solving. Returns NULL before the problem is solved.

Usage

dual_value(x)

Arguments

x

A Constraint object.

Value

A numeric matrix (single dual variable) or a list of numeric matrices (multiple dual variables), or NULL.


Create an entropy atom -x * log(x)

Description

Create an entropy atom -x * log(x)

Usage

entr(x)

Arguments

x

An Expression

Value

An Entr atom


Conjugate-Transpose of an Expression

Description

Equivalent to CVXPY's .H property. For real expressions, returns t(x). For complex expressions, returns Conj(t(x)).

Usage

expr_H(x)

Arguments

x

A CVXR Expression.

Value

The conjugate-transpose expression.


Shallow Copy of an Expression Tree Node

Description

Shallow Copy of an Expression Tree Node

Usage

expr_copy(x, args = NULL, id_objects = NULL)

Arguments

x

A canonicalizable object.

args

Optional replacement args.

id_objects

Optional identity map for deduplication.

Value

A copy of the object.


Get the Name of an Expression

Description

Get the Name of an Expression

Usage

expr_name(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Character string.


Get the DCP Sign of an Expression

Description

Returns the sign of an expression under DCP analysis. Use this instead of sign(), which conflicts with the base R function.

Usage

expr_sign(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Character string: "POSITIVE", "NEGATIVE", "ZERO", or "UNKNOWN".


Unity resolvent (I - X) inverse for positive square matrix X

Description

Log-log convex atom for DGP. Solve with psolve(problem, gp = TRUE).

Usage

eye_minus_inv(X)

Arguments

X

An Expression (positive square matrix with spectral radius < 1)

Value

An EyeMinusInv atom

Examples

X <- Variable(c(2, 2), pos = TRUE)
prob <- Problem(Minimize(sum(eye_minus_inv(X))), list(X <= 0.4))
## Not run: psolve(prob, gp = TRUE, solver = "SCS")

Elementwise Floor

Description

Returns the floor (largest integer <= x) of each element. This atom is quasiconvex and quasiconcave but NOT convex or concave, so it can only be used in DQCP problems (solved with qcp = TRUE).

Usage

floor_expr(x)

Arguments

x

A CVXR expression.

Value

A Floor expression.

See Also

ceil_expr


Maximum generalized eigenvalue

Description

Computes the maximum generalized eigenvalue lambda_max(A, B). Requires A symmetric and B positive semidefinite. This is a quasiconvex atom.

Usage

gen_lambda_max(A, B)

Arguments

A

A square symmetric matrix expression

B

A square PSD matrix expression of the same dimension as A

Value

An expression representing the maximum generalized eigenvalue


(Weighted) geometric mean of a vector

Description

(Weighted) geometric mean of a vector

Usage

geo_mean(x, p = NULL, max_denom = 1024L, approx = TRUE)

Arguments

x

An Expression (vector)

p

Numeric weight vector (default: uniform)

max_denom

Maximum denominator for rational approximation

approx

If TRUE (default), use SOC approximation. If FALSE, use exact power cone.

Value

A GeoMean or GeoMeanApprox atom


Get Atom-Specific Data

Description

Get Atom-Specific Data

Usage

get_data(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

List of data.


Get Problem Data for a Solver (deprecated)

Description

[Deprecated]

Usage

get_problem_data(x, solver = NULL, ...)

Arguments

x

A Problem object.

solver

Character string naming solver, or NULL for automatic selection.

...

Additional arguments.

Details

Use problem_data instead.

Value

A list with components data, chain, and inverse_data.

See Also

problem_data


Geometric matrix multiplication A diamond X

Description

Computes the geometric matrix product where (A diamond X)_ij = prod_k X_kj^A_ik. Log-log affine atom for DGP. Solve with psolve(problem, gp = TRUE).

Usage

gmatmul(A, X)

Arguments

A

A constant matrix

X

An Expression (positive matrix)

Value

A Gmatmul atom

Examples

x <- Variable(2, pos = TRUE)
A <- matrix(c(1, 0, 0, 1), 2, 2)
prob <- Problem(Minimize(sum(gmatmul(A, x))), list(x >= 0.5))
## Not run: psolve(prob, gp = TRUE)

Get the Gradient of an Expression

Description

Get the Gradient of an Expression

Usage

grad(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Gradient information.


Get the Graph Implementation of an Atom

Description

Get the Graph Implementation of an Atom

Usage

graph_implementation(x, arg_objs, shape, data = NULL, ...)

Arguments

x

An atom object.

arg_objs

List of canonicalized argument LinOps.

shape

Integer vector: target shape.

data

Optional atom-specific data.

...

Additional arguments.

Value

List with (expression, constraints).


Harmonic mean: n / sum(1/x_i)

Description

Harmonic mean: n / sum(1/x_i)

Usage

harmonic_mean(x)

Arguments

x

An Expression (must be positive for DCP)

Value

An Expression representing the harmonic mean


Check if Expression Has a Quadratic Term

Description

Check if Expression Has a Quadratic Term

Usage

has_quadratic_term(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Horizontal concatenation of expressions

Description

Horizontal concatenation of expressions

Usage

hstack(...)

Arguments

...

Expressions (same number of rows)

Value

An HStack atom


Create a Huber loss atom

Description

Create a Huber loss atom

Usage

huber(x, M = 1)

Arguments

x

An Expression

M

Numeric threshold (default 1)

Value

A Huber atom


Get Expression ID

Description

Returns the unique integer identifier for a CVXR object.

Usage

id(x)

Arguments

x

A CVXR expression, variable, parameter, or constraint.

Value

An integer.


Logical Biconditional

Description

Logical biconditional: x <=> y. Returns 1 if and only if x and y have the same value. Equivalent to Not(Xor(x, y)).

Usage

iff(x, y)

Arguments

x, y

Boolean Variables or logic expressions.

Value

A Not expression wrapping Xor.

See Also

implies(), Not(), And(), Or(), Xor()

Examples

## Not run: 
x <- Variable(boolean = TRUE)
y <- Variable(boolean = TRUE)
expr <- iff(x, y)

## End(Not run)

Extract Imaginary Part of Expression

Description

Returns the imaginary part of a complex expression. R's native Im() dispatches here for CVXR expressions via the Complex S3 group handler.

Usage

imag_expr(expr)

Arguments

expr

A CVXR Expression.

Value

An Imag_ atom.


Logical Implication

Description

Logical implication: x => y. Returns 1 unless x = 1 and y = 0. Equivalent to Or(Not(x), y).

Usage

implies(x, y)

Arguments

x, y

Boolean Variables or logic expressions.

Value

An Or expression representing !x | y.

See Also

iff(), Not(), And(), Or(), Xor()

Examples

## Not run: 
x <- Variable(boolean = TRUE)
y <- Variable(boolean = TRUE)
expr <- implies(x, y)

## End(Not run)

Indicator function for constraints

Description

Creates an expression that equals 0 if all constraints are satisfied and +Inf otherwise. Use this to embed constraints into the objective.

Usage

indicator(constraints, err_tol = 0.001)

Arguments

constraints

A list of constraint objects

err_tol

Numeric tolerance for checking constraint satisfaction (default 1e-3)

Value

An Indicator expression


List installed solvers

Description

Returns the names of solvers whose R packages are available.

Usage

installed_solvers()

Value

A character vector of solver names.


Convert a value to a numeric matrix or sparse matrix

Description

Normalizes R values so the rest of CVXR can assume a consistent type. Scalars -> 1x1 matrix, vectors -> column matrix, logical -> numeric. Sparse matrices are kept sparse.

Usage

intf_convert(val)

Arguments

val

A numeric scalar, vector, matrix, or Matrix object

Value

A matrix or dgCMatrix


Check if a matrix is symmetric (and Hermitian for real case)

Description

Check if a matrix is symmetric (and Hermitian for real case)

Usage

intf_is_hermitian(val)

Arguments

val

A numeric matrix or sparse matrix

Value

List with is_symmetric (logical) and is_hermitian (logical)


Check if a symmetric matrix is PSD within tolerance

Description

Check if a symmetric matrix is PSD within tolerance

Usage

intf_is_psd(val, tol = EIGVAL_TOL)

Arguments

val

A symmetric numeric matrix

tol

Eigenvalue tolerance

Value

Logical


Check if a matrix is skew-symmetric (A + A^T == 0)

Description

Check if a matrix is skew-symmetric (A + A^T == 0)

Usage

intf_is_skew_symmetric(val)

Arguments

val

A numeric matrix or sparse matrix

Value

Logical scalar


Check if a value is a sparse matrix

Description

Check if a value is a sparse matrix

Usage

intf_is_sparse(val)

Arguments

val

A value

Value

Logical


Get the shape of a value as an integer vector c(nrow, ncol)

Description

Get the shape of a value as an integer vector c(nrow, ncol)

Usage

intf_shape(val)

Arguments

val

A numeric scalar, vector, matrix, or Matrix object

Value

Integer vector of length 2


Determine the sign of a numeric value

Description

Determine the sign of a numeric value

Usage

intf_sign(val)

Arguments

val

A numeric matrix or sparse matrix

Value

List with is_nonneg (logical) and is_nonpos (logical)


Inverse position: x^{-1} (for x > 0)

Description

Inverse position: x^{-1} (for x > 0)

Usage

inv_pos(x)

Arguments

x

An Expression

Value

A Power atom with p=-1


Reciprocal of product of entries

Description

Computes the reciprocal of the product of entries. Equivalent to geo_mean(x)^(-n) where n is the number of entries.

Usage

inv_prod(x, approx = TRUE)

Arguments

x

An Expression or numeric value (must have positive entries).

approx

Logical; if TRUE (default), use SOC approximation.

Value

A convex Expression representing the reciprocal product.


Check if an Expression is Affine

Description

Check if an Expression is Affine

Usage

is_affine(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Check if Atom is Concave

Description

Check if Atom is Concave

Usage

is_atom_concave(x, ...)

Arguments

x

An atom object.

...

Not used.

Value

Logical scalar.


Check if Atom is Convex

Description

Check if Atom is Convex

Usage

is_atom_convex(x, ...)

Arguments

x

An atom object.

...

Not used.

Value

Logical scalar.


Check if Atom is Log-Log Concave

Description

Check if Atom is Log-Log Concave

Usage

is_atom_log_log_concave(x, ...)

Arguments

x

An atom object.

...

Not used.

Value

Logical scalar.


Check if Atom is Log-Log Convex

Description

Check if Atom is Log-Log Convex

Usage

is_atom_log_log_convex(x, ...)

Arguments

x

An atom object.

...

Not used.

Value

Logical scalar.


Check if Atom is Quasiconcave

Description

Check if Atom is Quasiconcave

Usage

is_atom_quasiconcave(x, ...)

Arguments

x

An atom object.

...

Not used.

Value

Logical scalar.


Check if Atom is Quasiconvex

Description

Check if Atom is Quasiconvex

Usage

is_atom_quasiconvex(x, ...)

Arguments

x

An atom object.

...

Not used.

Value

Logical scalar.


Check if Expression is Complex

Description

Check if Expression is Complex

Usage

is_complex(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Check if an Expression is Concave

Description

Check if an Expression is Concave

Usage

is_concave(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Check if an Expression is Constant

Description

Check if an Expression is Constant

Usage

is_constant(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Check if an Expression is Convex

Description

Check if an Expression is Convex

Usage

is_convex(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Check if an Expression is DCP-Compliant

Description

Tests whether an expression follows the Disciplined Convex Programming (DCP) rules.

Usage

is_dcp(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Check if Atom is Decreasing in an Argument

Description

Check if Atom is Decreasing in an Argument

Usage

is_decr(x, idx, ...)

Arguments

x

An atom object.

idx

Integer: argument index (1-based, R convention).

...

Additional arguments.

Value

Logical scalar.


Check if a Constraint is DGP-Compliant

Description

Check if a Constraint is DGP-Compliant

Usage

is_dgp(x, ...)

Arguments

x

A constraint object.

...

Not used.

Value

Logical scalar.


Check DPP Compliance

Description

Determines whether an expression or problem satisfies the rules of Disciplined Parameterized Programming (DPP). A DPP-compliant problem enables caching the compilation across parameter value changes.

Usage

is_dpp(x, ...)

Arguments

x

An expression, constraint, or problem object.

...

Not used.

Value

Logical scalar.


Check if Expression is DQCP-Compliant

Description

Tests whether an expression follows the Disciplined Quasiconvex Programming (DQCP) rules.

Usage

is_dqcp(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Check if Expression is Hermitian

Description

Check if Expression is Hermitian

Usage

is_hermitian(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Check if Expression is Imaginary

Description

Check if Expression is Imaginary

Usage

is_imag(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Check if Atom is Increasing in an Argument

Description

Check if Atom is Increasing in an Argument

Usage

is_incr(x, idx, ...)

Arguments

x

An atom object.

idx

Integer: argument index (1-based, R convention).

...

Additional arguments.

Value

Logical scalar.


Check if Expression is Log-Log Affine

Description

Check if Expression is Log-Log Affine

Usage

is_log_log_affine(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Check if Expression is Log-Log Concave

Description

Check if Expression is Log-Log Concave

Usage

is_log_log_concave(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Check if Expression is Log-Log Convex

Description

Check if Expression is Log-Log Convex

Usage

is_log_log_convex(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Check if a Problem is a Linear Program

Description

Check if a Problem is a Linear Program

Usage

is_lp(x, ...)

Arguments

x

A Problem object.

...

Not used.

Value

Logical scalar.


Is the Expression a Matrix?

Description

Returns TRUE if the expression has both dimensions greater than 1.

Usage

is_matrix(x)

Arguments

x

A CVXR expression.

Value

Logical.

See Also

size(), is_scalar(), is_vector()


Check if a Problem is Mixed-Integer

Description

Returns TRUE if any variable in the problem has a boolean or integer attribute.

Usage

is_mixed_integer(problem)

Arguments

problem

A Problem object.

Value

Logical scalar.


Check if Expression is Non-Negative

Description

Check if Expression is Non-Negative

Usage

is_nonneg(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Check if Expression is Non-Positive

Description

Check if Expression is Non-Positive

Usage

is_nonpos(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Check if Expression is Negative Semidefinite

Description

Check if Expression is Negative Semidefinite

Usage

is_nsd(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Check if Expression is Parameter-Affine

Description

Returns TRUE if the expression is affine in parameters and contains no decision variables.

Usage

is_param_affine(expr)

Arguments

expr

A CVXR expression.

Value

Logical scalar.


Check if Expression is Parameter-Free

Description

Returns TRUE if the expression contains no parameters.

Usage

is_param_free(expr)

Arguments

expr

A CVXR expression.

Value

Logical scalar.


Check if Expression is Strictly Positive

Description

Check if Expression is Strictly Positive

Usage

is_pos(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Check if Expression is Positive Semidefinite

Description

Check if Expression is Positive Semidefinite

Usage

is_psd(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Check if Expression is Piecewise Linear

Description

Check if Expression is Piecewise Linear

Is the Expression Piecewise Linear?

Usage

is_pwl(x, ...)

Arguments

x

A CVXR expression.

...

Not used.

Value

Logical scalar.

Logical.


Check if a Problem is a Quadratic Program

Description

Check if a Problem is a Quadratic Program

Usage

is_qp(x, ...)

Arguments

x

A Problem object.

...

Not used.

Value

Logical scalar.


Check if Expression is Quadratic or Piecewise Affine

Description

Check if Expression is Quadratic or Piecewise Affine

Usage

is_qpwa(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Check if an Expression is Quadratic

Description

Check if an Expression is Quadratic

Usage

is_quadratic(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Check if Expression is Quasiconcave

Description

Check if Expression is Quasiconcave

Usage

is_quasiconcave(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Check if Expression is Quasiconvex

Description

Check if Expression is Quasiconvex

Usage

is_quasiconvex(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Check if Expression is Quasilinear

Description

Check if Expression is Quasilinear

Usage

is_quasilinear(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Check if Expression is Real

Description

Check if Expression is Real

Usage

is_real(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Is the Expression a Scalar?

Description

Is the Expression a Scalar?

Usage

is_scalar(x)

Arguments

x

A CVXR expression.

Value

Logical.

See Also

size(), is_vector(), is_matrix()


Check if Expression is Skew-Symmetric

Description

Tests whether X + t(X) == 0 (real matrices only). CVXPY SOURCE: expression.py line 470-473

Usage

is_skew_symmetric(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Check if Expression is Symmetric

Description

Check if Expression is Symmetric

Usage

is_symmetric(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


Is the Expression a Vector?

Description

Returns TRUE if the expression has at most one dimension greater than 1.

Usage

is_vector(x)

Arguments

x

A CVXR expression.

Value

Logical.

See Also

size(), is_scalar(), is_matrix()


Check if Expression is Zero

Description

Check if Expression is Zero

Usage

is_zero(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

Logical scalar.


KL Divergence: x*log(x/y) - x + y

Description

KL Divergence: x*log(x/y) - x + y

Usage

kl_div(x, y)

Arguments

x

An Expression

y

An Expression

Value

A KlDiv atom


Kronecker product of two expressions

Description

Kronecker product of two expressions

Usage

kron(a, b)

Arguments

a

An Expression (one must be constant)

b

An Expression

Value

A Kron atom


Maximum eigenvalue

Description

Maximum eigenvalue

Usage

lambda_max(A)

Arguments

A

A square matrix expression

Value

An expression representing the maximum eigenvalue of A


Minimum eigenvalue

Description

Minimum eigenvalue

Usage

lambda_min(A)

Arguments

A

A square matrix expression

Value

An expression representing the minimum eigenvalue of A


Sum of largest k eigenvalues

Description

Sum of largest k eigenvalues

Usage

lambda_sum_largest(A, k)

Arguments

A

A square matrix expression

k

Number of largest eigenvalues to sum (positive integer)

Value

An expression representing the sum of the k largest eigenvalues


Sum of smallest k eigenvalues

Description

Sum of smallest k eigenvalues

Usage

lambda_sum_smallest(A, k)

Arguments

A

A square matrix expression

k

Number of smallest eigenvalues to sum (positive integer)

Value

An expression representing the sum of the k smallest eigenvalues


Length of a Vector (Last Nonzero Index)

Description

Returns the index of the last nonzero element of a vector (1-based). This atom is quasiconvex but NOT convex, so it can only be used in DQCP problems (solved with qcp = TRUE).

Usage

length_expr(x)

Arguments

x

A CVXR vector expression.

Value

A Length expression (scalar).

See Also

ceil_expr, floor_expr


Append a child LinOp to the args list

Description

Append a child LinOp to the args list

Usage

linop_args_push_back(ptr, child_ptr)

Arguments

ptr

External pointer to the parent LinOp.

child_ptr

External pointer to the child LinOp.


Create a new C++ LinOp external pointer

Description

Create a new C++ LinOp external pointer

Usage

linop_new()

Value

An external pointer to a C++ LinOp object.


Set the data dimensionality on a LinOp

Description

Set the data dimensionality on a LinOp

Usage

linop_set_data_ndim(ptr, value)

Arguments

ptr

External pointer to a LinOp.

value

Integer dimensionality (0 = scalar, 2 = matrix).


Set dense data on a LinOp

Description

Set dense data on a LinOp

Usage

linop_set_dense_data(ptr, value)

Arguments

ptr

External pointer to a LinOp.

value

Dense matrix data.


Set a LinOp data sub-tree on a LinOp

Description

Set a LinOp data sub-tree on a LinOp

Usage

linop_set_linop_data(ptr, data_ptr)

Arguments

ptr

External pointer to the LinOp.

data_ptr

External pointer to the data LinOp sub-tree.


Set sparse data on a LinOp

Description

Set sparse data on a LinOp

Usage

linop_set_sparse_data(ptr, value)

Arguments

ptr

External pointer to a LinOp.

value

Sparse matrix data (dgCMatrix or similar).


Set the type of a LinOp

Description

Set the type of a LinOp

Usage

linop_set_type(ptr, type)

Arguments

ptr

External pointer to a LinOp.

type

Character string – one of .LINOP_TYPES.


Push a dimension to the LinOp size vector

Description

Push a dimension to the LinOp size vector

Usage

linop_size_push_back(ptr, value)

Arguments

ptr

External pointer to a LinOp.

value

Integer dimension value.


Push a slice (index vector) to a LinOp

Description

Push a slice (index vector) to a LinOp

Usage

linop_slice_push_back(ptr, int_vector)

Arguments

ptr

External pointer to a LinOp.

int_vector

Integer vector of indices (0-based for C++).


Log(1 + x) – elementwise

Description

Log(1 + x) – elementwise

Usage

log1p_atom(x)

log1p_expr(x)

Arguments

x

An Expression

Value

A Log1p atom


Log-determinant

Description

Computes log(det(A)) for PSD matrix A.

Usage

log_det(A)

Arguments

A

A square PSD matrix expression

Value

An expression representing log(det(A))


Elementwise log of the standard normal CDF

Description

Quadratic approximation of log(pnorm(x)) with modest accuracy over the range -4 to 4.

Usage

log_normcdf(x)

Arguments

x

An Expression or numeric value.

Value

A concave Expression representing log(Phi(x)).


Log-sum-exp: log(sum(exp(x)))

Description

Log-sum-exp: log(sum(exp(x)))

Usage

log_sum_exp(x, axis = NULL, keepdims = FALSE)

Arguments

x

An Expression

axis

NULL (all), 1 (row-wise), or 2 (column-wise)

keepdims

Logical: keep reduced dimensions?

Value

A LogSumExp atom


Elementwise log of the gamma function

Description

Piecewise linear approximation of log(gamma(x)). Has modest accuracy over the full range, approaching perfect accuracy as x goes to infinity.

Usage

loggamma(x)

Arguments

x

An Expression or numeric value (must be positive for DCP).

Value

A convex Expression representing log(gamma(x)).


Logistic function: log(1 + exp(x)) – elementwise

Description

Logistic function: log(1 + exp(x)) – elementwise

Usage

logistic(x)

Arguments

x

An Expression

Value

A Logistic atom


Make a CSC sparse diagonal matrix

Description

Make a CSC sparse diagonal matrix

Usage

make_sparse_diagonal_matrix(size, diagonal = NULL)

Arguments

size

number of rows or columns

diagonal

if specified, the diagonal values, in which case size is ignored

Value

a compressed sparse column diagonal matrix


Standard R Functions for CVXR Expressions

Description

CVXR registers methods so that standard R functions create the appropriate atoms when applied to Expression objects.

For CVXR expressions, computes the matrix/vector norm atom. For other inputs, falls through to norm.

For CVXR expressions, computes the standard deviation atom (ddof=0 by default, matching CVXPY/numpy convention). For numeric inputs, falls through to sd.

For CVXR expressions, computes the variance atom (ddof=0 by default). For numeric inputs, falls through to var.

For CVXR expressions, computes the outer product of two vectors. For other inputs, falls through to outer.

Usage

norm(x, type = "2", ...)

sd(x, ...)

var(x, ...)

outer(X, Y, ...)

Arguments

x

An Expression or numeric.

type

Norm type: "1", "2" (default), "I"/"i" (infinity), "F"/"f" (Frobenius).

...

For non-Expression inputs: passed to outer.

X

An Expression or numeric.

Y

An Expression or numeric.

Value

An Expression or numeric value.

An Expression or numeric value.

An Expression or numeric value.

An Expression or matrix.

Math group (elementwise, via S3 group generic)

abs(x)

Absolute value (convex, nonneg)

exp(x)

Exponential (convex, positive)

log(x)

Natural logarithm (concave, domain x >= 0)

sqrt(x)

Square root via power(x, 0.5) (concave)

log1p(x)

log(1+x) compound expression (concave)

log2(x), log10(x)

Base-2/10 logarithm

cumsum(x)

Cumulative sum (affine)

cummax(x)

Cumulative max (convex)

cumprod(x)

Cumulative product

ceiling(x), floor(x)

Round up/down (MIP)

Summary group (via S3 group generic)

sum(x)

Sum all entries (affine)

max(x)

Maximum entry (convex)

min(x)

Minimum entry (concave)

S3 generic methods

mean(x)

Arithmetic mean; pass axis/keepdims via ...

diff(x)

First-order differences; also cvxr_diff

Masking wrappers

These mask the base/stats versions and dispatch on argument type:

norm(x)

2-norm; use type for "1", "I" (infinity), "F" (Frobenius)

sd(x)

Standard deviation (ddof=0 for expressions)

var(x)

Variance (ddof=0 for expressions)

outer(X, Y)

Outer product of two vector expressions

Advanced usage

For axis-aware reductions, keepdims, or other options not available through the standard interface, use the explicit functions: cvxr_norm, cvxr_mean, cvxr_diff, cvxr_std, cvxr_var, cvxr_outer.

See Also

power, sum_entries, max_entries, min_entries

cvxr_norm for the full-featured version with axis and keepdims arguments

cvxr_std for the full-featured version

cvxr_var for the full-featured version

cvxr_outer for the CVXR-specific version


Matrix fractional function

Description

Computes \mathrm{trace}(X^T P^{-1} X). If P is a constant matrix, uses a QuadForm shortcut for efficiency.

Usage

matrix_frac(X, P)

Arguments

X

A matrix expression (n by m)

P

A square matrix expression (n by n), must be PSD

Value

An expression representing \mathrm{trace}(X^T P^{-1} X)


Trace of a square matrix expression

Description

Trace of a square matrix expression

Usage

matrix_trace(x)

Arguments

x

An Expression (square matrix)

Value

A Trace atom (scalar)


Elementwise maximum of expressions

Description

Elementwise maximum of expressions

Usage

max_elemwise(...)

Arguments

...

Expressions (at least 2)

Value

A Maximum atom


Maximum entry of an expression

Description

Maximum entry of an expression

Usage

max_entries(x, axis = NULL, keepdims = FALSE)

Arguments

x

An Expression

axis

NULL (all), 1 (row-wise), or 2 (column-wise)

keepdims

Logical

Value

A MaxEntries atom


Elementwise minimum of expressions

Description

Elementwise minimum of expressions

Usage

min_elemwise(...)

Arguments

...

Expressions (at least 2)

Value

A Minimum atom


Minimum entry of an expression

Description

Minimum entry of an expression

Usage

min_entries(x, axis = NULL, keepdims = FALSE)

Arguments

x

An Expression

axis

NULL (all), 1 (row-wise), or 2 (column-wise)

keepdims

Logical

Value

A MinEntries atom


Mixed norm (L_{p,q} norm): column-wise p-norm, then q-norm

Description

Mixed norm (L_{p,q} norm): column-wise p-norm, then q-norm

Usage

mixed_norm(X, p = 2, q = 1)

Arguments

X

An Expression (matrix)

p

Inner norm parameter (default 2)

q

Outer norm parameter (default 1)

Value

An Expression representing the mixed norm


Sign of a product of two expressions

Description

Determines whether the product of two expressions is nonnegative, nonpositive, or unknown, using the sign multiplication table.

Usage

mul_sign(lh_expr, rh_expr)

Arguments

lh_expr

An Expression object (left-hand operand)

rh_expr

An Expression object (right-hand operand)

Value

Named logical vector c(is_nonneg, is_nonpos)


Elementwise multiplication (deprecated)

Description

[Deprecated]

Usage

multiply(x, y)

Arguments

x, y

Expressions or numeric values.

Details

Use the * operator instead: x * y.

Value

An Expression representing the elementwise product.


Get Expression Name

Description

Returns a human-readable string representation of a CVXR expression, variable, or constraint.

Usage

name(x)

Arguments

x

A CVXR expression, variable, parameter, constant, or constraint.

Value

A character string.

Examples

x <- Variable(2, name = "x")
name(x)  # "x"
name(x + 1)  # "x + 1"


Negative part: -min(x, 0)

Description

Negative part: -min(x, 0)

Usage

neg(x)

Arguments

x

An Expression

Value

A negated Minimum atom


L1 norm of an expression

Description

L1 norm of an expression

Usage

norm1(x, axis = NULL, keepdims = FALSE)

Arguments

x

An Expression

axis

NULL (all), 1 (row-wise), or 2 (column-wise)

keepdims

Logical: keep reduced dimensions?

Value

A Norm1 atom


Euclidean norm (deprecated alias)

Description

[Deprecated]

Usage

norm2(x)

Arguments

x

An Expression.

Details

Use p_norm(x, 2) instead.

Value

An Expression representing the L2 norm.

See Also

p_norm()


L-infinity norm of an expression

Description

L-infinity norm of an expression

Usage

norm_inf(x, axis = NULL, keepdims = FALSE)

Arguments

x

An Expression

axis

NULL (all), 1 (row-wise), or 2 (column-wise)

keepdims

Logical: keep reduced dimensions?

Value

A NormInf atom


Nuclear norm (sum of singular values)

Description

Nuclear norm (sum of singular values)

Usage

norm_nuc(A)

Arguments

A

A matrix expression

Value

An expression representing the nuclear norm of A


Get the Number of Cones in a Constraint

Description

Get the Number of Cones in a Constraint

Usage

num_cones(x, ...)

Arguments

x

A cone constraint object.

...

Not used.

Value

Integer.


Compute the Numeric Value of an Atom

Description

Compute the Numeric Value of an Atom

Usage

numeric_value(x, values, ...)

Arguments

x

An atom object.

values

List of numeric values of the atom's arguments.

...

Additional arguments.

Value

Numeric value.


Get Problem Objective (read-only)

Description

Returns the problem's objective.

Usage

objective(x)

Arguments

x

A Problem object.

Details

Problem objects are immutable: the objective cannot be modified after construction. To change the objective, create a new Problem().

Value

A Minimize or Maximize object.

See Also

Problem(), constraints()

Examples

x <- Variable(2)
prob <- Problem(Minimize(sum_entries(x)), list(x >= 1))
objective(prob)


The difference 1 - x with domain (0, 1)

Description

Log-log concave atom for DGP. Solve with psolve(problem, gp = TRUE).

Usage

one_minus_pos(x)

Arguments

x

An Expression (elementwise in (0, 1))

Value

A OneMInusPos atom

Examples

x <- Variable(pos = TRUE)
prob <- Problem(Maximize(one_minus_pos(x)), list(x >= 0.1, x <= 0.5))
## Not run: psolve(prob, gp = TRUE)

General p-norm of an expression

Description

General p-norm of an expression

Usage

p_norm(
  x,
  p = 2,
  axis = NULL,
  keepdims = FALSE,
  max_denom = 1024L,
  approx = TRUE
)

Arguments

x

An Expression

p

Numeric exponent (default 2)

axis

NULL (all), 1 (row-wise), or 2 (column-wise)

keepdims

Logical

max_denom

Integer max denominator for rational approx

approx

If TRUE (default), use SOC approximation. If FALSE, use exact power cone.

Value

A Pnorm, PnormApprox, Norm1, or NormInf atom


Get the Parameters in an Expression

Description

Get the Parameters in an Expression

Usage

parameters(x, ...)

Arguments

x

An expression or problem object.

...

Not used.

Value

List of Parameter objects.


Partial trace of a tensor product expression

Description

Assumes expr is a 2D square matrix representing a Kronecker product of length(dims) subsystems. Returns the partial trace over the subsystem at index axis (1-indexed).

Usage

partial_trace(expr, dims, axis = 1L)

Arguments

expr

An Expression (2D square matrix)

dims

Integer vector of subsystem dimensions

axis

Integer (1-indexed) subsystem to trace out

Value

An Expression representing the partial trace


Partial transpose of a tensor product expression

Description

Assumes expr is a 2D square matrix representing a Kronecker product of length(dims) subsystems. Returns the partial transpose with the transpose applied to the subsystem at index axis (1-indexed).

Usage

partial_transpose(expr, dims, axis = 1L)

Arguments

expr

An Expression (2D square matrix)

dims

Integer vector of subsystem dimensions

axis

Integer (1-indexed) subsystem to transpose

Value

An Expression representing the partial transpose


Perspective Transform

Description

Creates the perspective transform of a scalar convex or concave expression. Given a scalar expression f(x) and a nonneg variable s, the perspective is s * f(x/s).

Usage

perspective(f, s, f_recession = NULL)

Arguments

f

A scalar convex or concave Expression.

s

A nonneg Variable (scalar).

f_recession

Optional recession function for handling s = 0.

Value

A Perspective expression.


Perron-Frobenius eigenvalue of a positive matrix

Description

Log-log convex atom for DGP. Solve with psolve(problem, gp = TRUE).

Usage

pf_eigenvalue(X)

Arguments

X

An Expression (positive square matrix)

Value

A PfEigenvalue atom (scalar)

Examples

X <- Variable(c(2, 2), pos = TRUE)
prob <- Problem(Minimize(pf_eigenvalue(X)),
                list(X[1,1] >= 0.1, X[2,2] >= 0.1))
## Not run: psolve(prob, gp = TRUE)

Positive part: max(x, 0)

Description

Positive part: max(x, 0)

Usage

pos(x)

Arguments

x

An Expression

Value

A Maximum atom


Create a Power atom

Description

Create a Power atom

Usage

power(x, p, max_denom = 1024L, approx = TRUE)

Arguments

x

An Expression

p

Numeric exponent

max_denom

Maximum denominator for rational approximation

approx

If TRUE (default), use SOC approximation. If FALSE, use exact power cone.

Value

A Power or PowerApprox atom

Note

sqrt(x) on a CVXR expression dispatches to Power(x, 0.5) via the Math group generic. See math_atoms for all standard R function dispatch.


Get Problem Data for a Solver

Description

Returns the problem data that would be passed to a specific solver, along with the reduction chain and inverse data for solution retrieval.

Usage

problem_data(x, solver = NULL, ...)

Arguments

x

A Problem object.

solver

Character string naming solver, or NULL for automatic selection.

...

Additional arguments.

Value

A list with components data, chain, and inverse_data.


Get the Raw Solution Object (deprecated)

Description

[Deprecated]

Usage

problem_solution(x)

Arguments

x

A Problem object.

Details

Use solution instead.

Value

A Solution object, or NULL if the problem has not been solved.

See Also

solution


Get the Solution Status of a Problem (deprecated)

Description

[Deprecated]

Usage

problem_status(x)

Arguments

x

A Problem object.

Details

Use status instead.

Value

Character string, or NULL if the problem has not been solved.

See Also

status


Unpack Solver Results into a Problem

Description

Inverts the reduction chain and unpacks the raw solver solution into the original problem's variables and constraints. This is step 3 of the decomposed solve pipeline:

  1. problem_data() – compile the problem

  2. solve_via_data(chain, data) – call the solver

  3. problem_unpack_results() – invert and unpack

Usage

problem_unpack_results(problem, solution, chain, inverse_data)

Arguments

problem

A Problem object.

solution

The raw solver result from solve_via_data().

chain

The SolvingChain from problem_data().

inverse_data

The inverse data list from problem_data().

Details

After calling this function, variable values are available via value() and constraint duals via dual_value().

Value

The problem object (invisibly), with solution unpacked.

See Also

problem_data, solve_via_data


Product of entries along an axis

Description

Used in DGP (geometric programming) context. Solve with psolve(problem, gp = TRUE).

Usage

prod_entries(x, axis = NULL, keepdims = FALSE)

Arguments

x

An Expression

axis

NULL (all), 1 (row-wise), or 2 (column-wise)

keepdims

Whether to keep reduced dimensions

Value

A Prod atom

Examples

x <- Variable(3, pos = TRUE)
prob <- Problem(Minimize(prod_entries(x)), list(x >= 2))
## Not run: psolve(prob, gp = TRUE)

Project a Value onto the Domain of a Leaf

Description

Project a Value onto the Domain of a Leaf

Usage

project(x, val, ...)

Arguments

x

A leaf expression object.

val

The value to project.

...

Additional arguments.

Value

The projected value.


Solve a Convex Optimization Problem

Description

Solves the problem and returns the optimal objective value. After solving, variable values can be retrieved with value, constraint dual values with dual_value, and solver information with solver_stats.

Usage

psolve(
  problem,
  solver = NULL,
  gp = FALSE,
  qcp = FALSE,
  verbose = FALSE,
  warm_start = FALSE,
  feastol = NULL,
  reltol = NULL,
  abstol = NULL,
  num_iter = NULL,
  ...
)

Arguments

problem

A Problem object.

solver

Character string naming the solver to use (e.g., "CLARABEL", "SCS", "OSQP", "HIGHS"), or NULL for automatic selection.

gp

Logical; if TRUE, solve as a geometric program (DGP).

qcp

Logical; if TRUE, solve as a quasiconvex program (DQCP) via bisection. Only needed for non-DCP DQCP problems.

verbose

Logical; if TRUE, print solver output.

warm_start

Logical; if TRUE, use the current variable values as a warm-start point for the solver.

feastol

Numeric or NULL; feasibility tolerance. Mapped to the solver-specific parameter name (e.g., tol_feas for Clarabel, eps_prim_inf for OSQP). If NULL (default), the solver's own default is used.

reltol

Numeric or NULL; relative tolerance. Mapped to the solver-specific parameter name (e.g., tol_gap_rel for Clarabel, eps_rel for OSQP/SCS). If NULL (default), the solver's own default is used.

abstol

Numeric or NULL; absolute tolerance. Mapped to the solver-specific parameter name (e.g., tol_gap_abs for Clarabel, eps_abs for OSQP/SCS). If NULL (default), the solver's own default is used.

num_iter

Integer or NULL; maximum number of solver iterations. Mapped to the solver-specific parameter name (e.g., max_iter for Clarabel/OSQP, max_iters for SCS). If NULL (default), the solver's own default is used.

...

Additional solver-specific options passed directly to the solver. If a solver-native parameter name conflicts with a standard parameter (e.g., both feastol = 1e-3 and tol_feas = 1e-6 are given), the solver-native name in ... takes priority. For DQCP problems (qcp = TRUE), additional arguments include low, high, eps, max_iters, and max_iters_interval_search.

Value

The optimal objective value (numeric scalar), or Inf / -Inf for infeasible / unbounded problems.

See Also

Problem, status, solver_stats, solver_default_param

Examples

x <- Variable()
prob <- Problem(Minimize(x), list(x >= 5))
result <- psolve(prob, solver = "CLARABEL")


Peak-to-peak (range): max(x) - min(x)

Description

Computes the range of values along an axis: max(x) - min(x). The result is always nonnegative.

Usage

ptp(x, axis = NULL, keepdims = FALSE)

Arguments

x

An Expression or numeric value.

axis

NULL (all), 0 (columns), or 1 (rows).

keepdims

Logical; keep reduced dimension?

Value

An Expression representing max(x) - min(x).


Quadratic form x^T P x

Description

When x is constant, returns t(Conj(x)) %*% P %*% x (affine in P). When P is constant, returns a QuadForm atom (quadratic in x). At least one of x or P must be constant.

Usage

quad_form(x, P, assume_PSD = FALSE)

Arguments

x

An Expression (vector)

P

An Expression (square matrix, symmetric/Hermitian)

assume_PSD

If TRUE, assume P is PSD without checking (only when P is constant).

Value

A QuadForm atom or an affine Expression


Sum of squares divided by a scalar

Description

Sum of squares divided by a scalar

Usage

quad_over_lin(x, y, axis = NULL, keepdims = FALSE)

Arguments

x

An Expression

y

An Expression (scalar, positive)

axis

NULL (all), 1 (row-wise), or 2 (column-wise)

keepdims

Logical: keep reduced dimensions?

Value

A QuadOverLin atom


Extract Real Part of Expression

Description

Returns the real part of a complex expression. R's native Re() dispatches here for CVXR expressions via the Complex S3 group handler.

Usage

real_expr(expr)

Arguments

expr

A CVXR Expression.

Value

A Real_ atom.


Check if a Reduction Accepts a Problem

Description

Check if a Reduction Accepts a Problem

Usage

reduction_accepts(x, problem, ...)

Arguments

x

A Reduction object.

problem

A Problem object.

...

Additional arguments.

Value

Logical scalar.


Apply a Reduction to a Problem

Description

Apply a Reduction to a Problem

Usage

reduction_apply(x, problem, ...)

Arguments

x

A Reduction object.

problem

A Problem object.

...

Additional arguments.

Value

List with (new_problem, inverse_data).


Invert a Solution through a Reduction

Description

Invert a Solution through a Reduction

Usage

reduction_invert(x, solution, inverse_data, ...)

Arguments

x

A Reduction object.

solution

A solution object.

inverse_data

Inverse data from apply.

...

Additional arguments.

Value

A solution to the original problem.


Relative Entropy: x*log(x/y)

Description

Relative Entropy: x*log(x/y)

Usage

rel_entr(x, y)

Arguments

x

An Expression

y

An Expression

Value

A RelEntr atom


Reshape an expression to a new shape

Description

Reshape an expression to a new shape

Usage

reshape_expr(x, dim, order = "F")

Arguments

x

An Expression or numeric value.

dim

Integer vector of length 2: the target shape c(nrow, ncol). A single integer is treated as c(dim, 1). Use -1 to infer a dimension.

order

Character: "F" (column-major, default) or "C" (row-major).

Value

A Reshape expression.


Get the Residual of a Constraint

Description

Returns the residual of a constraint, measuring how much the constraint is violated or satisfied.

Usage

residual(x, ...)

Arguments

x

A constraint object.

...

Not used.

Value

Numeric array, or NULL if expression has no value.


Resolvent inverse(sI - X)

Description

Equivalent to (1/s) * eye_minus_inv(X / s).

Usage

resolvent(X, s)

Arguments

X

An Expression (positive square matrix)

s

A positive scalar

Value

An expression for the resolvent


Save Dual Variable Values from Solver Output

Description

Save Dual Variable Values from Solver Output

Usage

save_dual_value(x, val)

Arguments

x

A constraint object.

val

The dual value from the solver.

Value

Invisible constraint (side effect: sets dual variable values).


Scalar product (alias for vdot)

Description

Scalar product (alias for vdot)

Usage

scalar_product(x, y)

Arguments

x

An Expression or numeric value.

y

An Expression or numeric value.

Value

A scalar Expression representing sum(x * y).


Scalene penalty: alpha * pos(x) + beta * neg(x)

Description

Scalene penalty: alpha * pos(x) + beta * neg(x)

Usage

scalene(x, alpha, beta)

Arguments

x

An Expression

alpha

Coefficient for the positive part

beta

Coefficient for the negative part

Value

An Expression representing the scalene penalty


Set a Label on a Constraint

Description

Attaches a human-readable label to a constraint for use in visualizations and pretty-printing. Labels are visualization-only and never affect the solver pipeline.

Usage

set_label(constraint, label)

Arguments

constraint

A Constraint object.

label

A character string label.

Details

Because R uses copy-on-modify semantics, you must either assign the result back or use set_label fluently when building constraint lists.

Value

The modified constraint (invisibly).

Examples

## Not run: 
x <- Variable(3, name = "x")

# Assign back
con <- (x >= 0)
con <- set_label(con, "non-negativity")

# Fluent use in constraint lists
constraints <- list(
  set_label(x >= 1, "lower bound"),
  set_label(sum_entries(x) <= 10, "budget")
)

## End(Not run)


Infer Shape from Arguments

Description

Infer Shape from Arguments

Usage

shape_from_args(x, ...)

Arguments

x

An atom object.

...

Not used.

Value

Integer vector of shape dimensions.


Maximum singular value

Description

Maximum singular value

Usage

sigma_max(A)

Arguments

A

A matrix expression

Value

An expression representing the maximum singular value of A


Infer Sign from Arguments

Description

Infer Sign from Arguments

Usage

sign_from_args(x, ...)

Arguments

x

An atom object.

...

Not used.

Value

Character string: sign constant.


Get Expression Size

Description

Returns the total number of elements in the expression.

Usage

size(x)

Arguments

x

A CVXR expression.

Value

An integer (product of shape dimensions).

See Also

is_scalar(), is_vector(), is_matrix()


Smith Form Annotation for an Expression Node

Description

Returns LaTeX-math annotation data for visualizing the canonicalization pipeline. Each atom class can override this to provide a custom LaTeX name, definition, and conic form. The default stub auto-generates from class metadata.

Usage

smith_annotation(expr, aux_var = "t", child_vars = character(0), ...)

Arguments

expr

An Expression, Atom, or Leaf.

aux_var

Character: the auxiliary variable name assigned to this node (e.g., "t_3").

child_vars

Character vector: auxiliary variable names of the children.

...

Reserved for future use.

Value

A list with components: latex_name, latex_definition, conic, doc_topic, developer.


Get the Raw Solution Object

Description

Returns the raw Solution object from the most recent solve, containing primal and dual variable values, status, and solver attributes.

Usage

solution(x)

Arguments

x

A Problem object.

Value

A Solution object, or NULL if the problem has not been solved.


Solve via Raw Data

Description

Calls the solver on pre-compiled problem data (step 2 of the decomposed solve pipeline). Dispatches on x: when x is a SolvingChain, delegates to the terminal solver with proper cache management.

Usage

solve_via_data(
  x,
  data,
  warm_start = FALSE,
  verbose = FALSE,
  solver_opts = list(),
  ...
)

Arguments

x

A SolvingChain (preferred) or Solver object.

data

Named list of solver data from problem_data().

warm_start

Logical; use warm-start if supported.

verbose

Logical; print solver output.

solver_opts

Named list of solver-specific options.

...

Additional arguments (e.g., problem for SolvingChain dispatch, solver_cache for Solver dispatch).

Value

Solver-specific result (a named list).

See Also

problem_data, problem_unpack_results


Solver Name Constants

Description

Character string constants identifying the available solvers.

Usage

SCS_SOLVER

OSQP_SOLVER

CLARABEL_SOLVER

HIGHS_SOLVER

MOSEK_SOLVER

GUROBI_SOLVER

GLPK_SOLVER

GLPK_MI_SOLVER

ECOS_SOLVER

ECOS_BB_SOLVER

CPLEX_SOLVER

CVXOPT_SOLVER

PIQP_SOLVER

Format

An object of class character of length 1.

An object of class character of length 1.

An object of class character of length 1.

An object of class character of length 1.

An object of class character of length 1.

An object of class character of length 1.

An object of class character of length 1.

An object of class character of length 1.

An object of class character of length 1.

An object of class character of length 1.

An object of class character of length 1.

An object of class character of length 1.

An object of class character of length 1.

Value

A character string.


Standard Solver Parameter Mappings

Description

Returns a named list mapping standard CVXR parameter names (reltol, abstol, feastol, num_iter) to solver-specific parameter names and their default values. Used internally by psolve to translate standard parameters into solver-native names.

Usage

solver_default_param()

Value

A named list keyed by solver name (e.g. "CLARABEL", "OSQP"). Each element is a list of standard parameter mappings, where each mapping has name (solver-native parameter name) and value (default value).

See Also

psolve


Get Solver Name

Description

Get Solver Name

Usage

solver_name(x, ...)

Arguments

x

A Solver object.

...

Not used.

Value

Character string with solver name.


Get Solver Statistics

Description

Returns solver statistics from the most recent solve, including solve time, setup time, and iteration count.

Usage

solver_stats(x)

Arguments

x

A Problem object.

Value

A SolverStats object, or NULL if the problem has not been solved.


Square of an expression: x^2

Description

Square of an expression: x^2

Usage

square(x)

Arguments

x

An Expression

Value

A Power atom with p=2


Get the Solution Status of a Problem

Description

Returns the status string from the most recent solve, such as "optimal", "infeasible", or "unbounded".

Usage

status(x)

Arguments

x

A Problem object.

Value

Character string, or NULL if the problem has not been solved.

See Also

OPTIMAL, INFEASIBLE, UNBOUNDED


Solution Status Constants

Description

Character string constants representing the possible solution statuses returned by problem_status.

Usage

OPTIMAL

INFEASIBLE

UNBOUNDED

SOLVER_ERROR

OPTIMAL_INACCURATE

INFEASIBLE_INACCURATE

UNBOUNDED_INACCURATE

USER_LIMIT

INFEASIBLE_OR_UNBOUNDED

Format

An object of class character of length 1.

An object of class character of length 1.

An object of class character of length 1.

An object of class character of length 1.

An object of class character of length 1.

An object of class character of length 1.

An object of class character of length 1.

An object of class character of length 1.

An object of class character of length 1.

Value

A character string.

See Also

status, psolve


Sum the entries of an expression

Description

Sum the entries of an expression

Usage

sum_entries(x, axis = NULL, keepdims = FALSE)

Arguments

x

An Expression or numeric value.

axis

NULL (sum all), 1 (row-wise, like apply(X,1,sum)), or 2 (column-wise, like apply(X,2,sum)).

keepdims

Logical: if TRUE, keep the reduced dimension as size 1.

Value

A SumEntries expression.


Sum of k largest entries

Description

Sum of k largest entries

Usage

sum_largest(x, k)

Arguments

x

An Expression

k

Number of largest entries to sum

Value

A SumLargest atom


Sign of a sum of expressions

Description

Determines whether the sum of a list of expressions is nonnegative, nonpositive, or unknown.

Usage

sum_signs(exprs)

Arguments

exprs

List of Expression objects

Value

Named logical vector c(is_nonneg, is_nonpos)


Sum of k smallest entries

Description

Sum of k smallest entries

Usage

sum_smallest(x, k)

Arguments

x

An Expression

k

Number of smallest entries to sum

Value

An Expression equal to -SumLargest(-x, k)


Sum of squares (= quad_over_lin(x, 1))

Description

Sum of squares (= quad_over_lin(x, 1))

Usage

sum_squares(x, axis = NULL, keepdims = FALSE)

Arguments

x

An Expression

axis

NULL (all), 1 (row-wise), or 2 (column-wise)

keepdims

Logical: keep reduced dimensions?

Value

A QuadOverLin atom


Convert CVXR Object to LaTeX

Description

Renders a CVXR Problem, Expression, or Constraint as a LaTeX string. Problem-level output uses the optidef package (mini*/maxi* environments) and atom macros from dcp.sty (shipped as system.file("sty", "dcp.sty", package = "CVXR")).

Usage

to_latex(x, ...)

Arguments

x

A Problem, Expression, Constraint, or Objective.

...

Reserved for future options.

Value

A character string containing LaTeX code.

Examples

x <- Variable(3, name = "x")
cat(to_latex(p_norm(x, 2)))
# \cvxnorm{x}_2


Total variation of a vector or matrix

Description

Computes total variation using L1 norm of discrete gradients for vectors and L2 norm of discrete gradients for matrices.

Usage

total_variation(value, ...)

Arguments

value

An Expression or numeric constant (vector or matrix)

...

Additional matrix expressions extending the third dimension

Value

An Expression representing the total variation


Trace of matrix inverse

Description

Computes \mathrm{tr}(X^{-1}) for PSD matrix X.

Usage

tr_inv(X)

Arguments

X

A square PSD matrix expression

Value

An expression representing \mathrm{tr}(X^{-1})


Deep Copy of an Expression Tree

Description

Deep Copy of an Expression Tree

Usage

tree_copy(x, id_objects = NULL)

Arguments

x

A canonicalizable object.

id_objects

Optional identity map for deduplication.

Value

A deep copy of the entire expression tree.


Total variation (deprecated alias)

Description

[Deprecated]

Usage

tv(...)

Arguments

...

Arguments passed to total_variation().

Details

Use total_variation() instead.

See Also

total_variation()


Unpack Results (backward-compatible alias)

Description

[Deprecated]

Usage

unpack_results(problem, solution, chain, inverse_data)

Arguments

problem

A Problem object.

solution

The raw solver result from solve_via_data().

chain

The SolvingChain from problem_data().

inverse_data

The inverse data list from problem_data().

Details

Use problem_unpack_results() instead. This alias exists for backward compatibility with older CVXR examples.

Value

The problem object (invisibly), with solution unpacked.

See Also

problem_unpack_results()


Update Parameters for DPP Fast Path

Description

Update Parameters for DPP Fast Path

Usage

update_parameters(x, problem, ...)

Arguments

x

A Reduction object.

problem

A Problem object.

...

Additional arguments.

Value

NULL (called for side effects).


Extract strict upper triangle of a square matrix

Description

Extract strict upper triangle of a square matrix

Usage

upper_tri(x)

Arguments

x

An Expression (square matrix)

Value

An UpperTri atom (column vector)


Validate Arguments to an Atom

Description

Validate Arguments to an Atom

Usage

validate_arguments(x, ...)

Arguments

x

An atom object.

...

Not used.

Value

Invisible NULL (or error if invalid).


Get the Numeric Value of an Expression

Description

Returns the numeric value of a CVXR expression, variable, or constant. For variables, the value is set after solving a problem.

Usage

value(x, ...)

Arguments

x

An expression object.

...

Not used.

Value

A numeric matrix, or NULL if no value has been set.


Set the Value of a Leaf Expression

Description

Assigns a numeric value to a Variable or Parameter.

Usage

value(x) <- value

Arguments

x

A leaf expression object.

value

The value to assign.

Value

The modified object (invisibly).


Get the Variables in an Expression

Description

Get the Variables in an Expression

Usage

variables(x, ...)

Arguments

x

An expression or problem object.

...

Not used.

Value

List of Variable objects.


Vector dot product (inner product)

Description

Computes the inner product: sum of element-wise products after flattening. Returns a scalar expression.

Usage

vdot(x, y)

Arguments

x

An Expression or numeric value.

y

An Expression or numeric value.

Value

A scalar Expression representing sum(x * y).


Vectorize an expression (column vector)

Description

Reshapes an expression into a column vector of shape (n*m, 1).

Usage

vec(x)

Arguments

x

An Expression or numeric value.

Value

A Reshape atom (column vector).


Reshape a vector into an upper triangular matrix

Description

Inverts upper_tri. Takes a flat vector and returns an upper triangular matrix (row-major order, matching CVXPY convention).

Usage

vec_to_upper_tri(expr, strict = FALSE)

Arguments

expr

An Expression (vector).

strict

Logical. If TRUE, returns a strictly upper triangular matrix (diagonal is zero). If FALSE, includes the diagonal. Default is FALSE.

Value

An Expression representing the upper triangular matrix.


Get the Violation of a Constraint

Description

Returns the scalar violation (distance to feasibility) of a constraint.

Usage

violation(x, ...)

Arguments

x

A constraint object.

...

Not used.

Value

Numeric scalar.


Visualize the Canonicalization Pipeline of a CVXR Problem

Description

Displays the Smith form decomposition of a convex optimization problem, showing each stage of the DCP canonicalization pipeline: expression tree, Smith form, relaxed Smith form, conic form, and (optionally) standard cone form and solver data.

Usage

visualize(
  problem,
  output = c("text", "json", "html", "latex", "tikz"),
  solver = NULL,
  digits = 4L,
  file = NULL,
  open = interactive(),
  doc_base = "https://cvxr.rbind.io/reference/"
)

Arguments

problem

A Problem object.

output

Character: output format.

"text"

Console display (default).

"json"

JSON data model (for interop with HTML/Python).

"html"

Interactive D3+KaTeX HTML (Phase 2).

"latex"

LaTeX align* environments (Phase 3).

"tikz"

TikZ forest tree diagrams (Phase 3).

solver

Solver specification for matrix stuffing stages (4-5). NULL (default) shows only Stages 0-3 with zero overhead. TRUE uses the default solver (same as psolve()). A character string (e.g., "Clarabel") uses that specific solver.

digits

Integer: significant digits for displaying scalar constants. Integer-valued constants (0, 1, -3) always display without decimals regardless of this setting. Defaults to 4.

file

Character: path for HTML output file. If NULL (default), a temporary file is used.

open

Logical: whether to open the HTML file in a browser. Defaults to TRUE in interactive sessions.

doc_base

Character: base URL for atom documentation links. Defaults to the CVXR pkgdown site.

Value

For "text": invisible model list. For "json": a JSON string (or list if jsonlite not available). For "html": the file path (invisibly). For other formats: the rendered output (Phase 2+).

Examples

## Not run: 
x <- Variable(3, name = "x")
prob <- Problem(Minimize(p_norm(x, 2)), list(x >= 1))
visualize(prob)                          # Stages 0-3 only
visualize(prob, solver = TRUE)           # Stages 0-5, default solver
visualize(prob, solver = "Clarabel")     # Stages 0-5, specific solver
visualize(prob, output = "html", solver = TRUE)

## End(Not run)


Vertical concatenation of expressions

Description

Vertical concatenation of expressions

Usage

vstack(...)

Arguments

...

Expressions (same number of columns)

Value

A VStack atom


Execute Expression Within DPP Scope

Description

Within this scope, Parameter objects are treated as affine (not constant) for curvature analysis. This is used internally by is_dpp() to check DPP compliance.

Usage

with_dpp_scope(expr)

Arguments

expr

An R expression to evaluate within the DPP scope.

Value

The result of evaluating expr.


x * exp(x) – elementwise

Description

x * exp(x) – elementwise

Usage

xexp(x)

Arguments

x

An Expression

Value

An Xexp atom