Problems

The Problem class is the entry point to specifying and solving optimization problems. Each cvxpy.problems.problem.Problem instance encapsulates an optimization problem, i.e., an objective and a set of constraints, and the solve() method either solves the problem encoded by the instance, returning the optimal value and setting variables values to optimal points, or reports that the problem was in fact infeasible or unbounded. You can construct a problem, solve it, and inspect both its value and the values of its variables like so:

problem = Problem(Minimize(expression), constraints)
problem.solve()
if problem.status not in ["infeasible", "unbounded"]:
    # Otherwise, problem.value is inf or -inf, respectively.
    print("Optimal value: %s" % problem.value)
for variable in problem.variables():
    print("Variable %s: value %s" % (variable.name(), variable.value))

Problems are immutable, except through the specification of Parameter values. This means that you cannot modify a problem’s objective or constraints after you have created it. If you find yourself wanting to add a constraint to an existing problem, you should instead create a new problem using, for example, the following idiom:

problem = Problem(Minimize(expression), constraints)
problem = Problem(problem.objective, problem.constraints + new_constraints)

Most users need not know anything about the Problem class except how to instantiate it, how to solve problem instances (solve()), and how to query the solver results (status and value).

Information about the size of a problem instance and statistics about the most recent solve invocation are captured by the SizeMetrics and SolverStats classes, respectively, and can be accessed via the size_metrics() and solver_stats() properties of the Problem class.

Minimize

class cvxpy.problems.objective.Minimize(expr)[source]

Bases: cvxpy.problems.objective.Objective

An optimization objective for minimization.

Parameters

expr (Expression) – The expression to minimize. Must be a scalar.

Raises

ValueError – If expr is not a scalar.

is_dcp()[source]

The objective must be convex.

is_dgp()[source]

The objective must be log-log convex.

Maximize

class cvxpy.problems.objective.Maximize(expr)[source]

Bases: cvxpy.problems.objective.Objective

An optimization objective for maximization.

Parameters

expr (Expression) – The expression to maximize. Must be a scalar.

Raises

ValueError – If expr is not a scalar.

is_dcp()[source]

The objective must be concave.

is_dgp()[source]

The objective must be log-log concave.

SizeMetrics

class cvxpy.problems.problem.SizeMetrics(problem)[source]

Bases: object

Reports various metrics regarding the problem.

num_scalar_variables

The number of scalar variables in the problem.

Type

integer

num_scalar_data

The number of scalar constants and parameters in the problem. The number of constants used across all matrices, vectors, in the problem. Some constants are not apparent when the problem is constructed: for example, The sum_squares expression is a wrapper for a quad_over_lin expression with a constant 1 in the denominator.

Type

integer

num_scalar_eq_constr

The number of scalar equality constraints in the problem.

Type

integer

num_scalar_leq_constr

The number of scalar inequality constraints in the problem.

Type

integer

max_data_dimension

The longest dimension of any data block constraint or parameter.

Type

integer

max_big_small_squared

The maximum value of (big)(small)^2 over all data blocks of the problem, where (big) is the larger dimension and (small) is the smaller dimension for each data block.

Type

integer

SolverStats

class cvxpy.problems.problem.SolverStats(results_dict, solver_name)[source]

Bases: object

Reports some of the miscellaneous information that is returned by the solver after solving but that is not captured directly by the Problem instance.

solve_time

The time (in seconds) it took for the solver to solve the problem.

Type

double

setup_time

The time (in seconds) it took for the solver to setup the problem.

Type

double

num_iters

The number of iterations the solver had to go through to find a solution.

Type

int

Problem

class cvxpy.problems.problem.Problem(objective, constraints=None)[source]

Bases: cvxpy.utilities.canonical.Canonical

A convex optimization problem.

Problems are immutable, save for modification through the specification of Parameter

Parameters
  • objective (Minimize or Maximize) – The problem’s objective.

  • constraints (list) – The constraints on the problem variables.

atoms()[source]

Accessor method for atoms.

Returns

A list of the atom types in the problem; note that this list contains classes, not instances.

Return type

list of Atom

backward()[source]

Compute the gradient of a solution with respect to parameters.

This method differentiates through the solution map of the problem, to obtain the gradient of a solution with respect to the parameters. In other words, it calculates the sensitivities of the parameters with respect to perturbations in the optimal variable values.

.backward() populates the .gradient attribute of each parameter as a side-effect. It can only be called after calling .solve() with requires_grad=True.

Below is a simple example:

import cvxpy as cp
import numpy as np

p = cp.Parameter()
x = cp.Variable()
quadratic = cp.square(x - 2 * p)
problem = cp.Problem(cp.Minimize(quadratic), [x >= 0])
p.value = 3.0
problem.solve(requires_grad=True, eps=1e-10)
# .backward() populates the .gradient attribute of the parameters
problem.backward()
# Because x* = 2 * p, dx*/dp = 2
np.testing.assert_allclose(p.gradient, 2.0)

In the above example, the gradient could easily be computed by hand; however, .backward() can be used to differentiate through any DCP program (that is also DPP-compliant).

This method uses the chain rule to evaluate the gradients of a scalar-valued function of the variables with respect to the parameters. For example, let x be a variable and p a parameter; x and p might be scalars, vectors, or matrices. Let f be a scalar-valued function, with z = f(x). Then this method computes dz/dp = (dz/dx) (dx/p). dz/dx is chosen to be the all ones vector by default, corresponding to choosing f to be the sum function. You can specify a custom value for dz/dx by setting the .gradient attribute on your variables. For example,

import cvxpy as cp
import numpy as np


b = cp.Parameter()
x = cp.Variable()
quadratic = cp.square(x - 2 * b)
problem = cp.Problem(cp.Minimize(quadratic), [x >= 0])
b.value = 3.
problem.solve(requires_grad=True, eps=1e-10)
x.gradient = 4.
problem.backward()
# dz/dp = dz/dx dx/dp = 4. * 2. == 8.
np.testing.assert_allclose(b.gradient, 8.)

The .gradient attribute on a variable can also be interpreted as a perturbation to its optimal value.

Raises
  • ValueError – if solve was not called with requires_grad=True

  • SolverError – if the problem is infeasible or unbounded

constants()[source]

Accessor method for parameters.

Returns

A list of the constants in the problem.

Return type

list of Constant

property constraints

A shallow copy of the problem’s constraints.

Note that constraints cannot be reassigned, appended to, or otherwise modified after creation, except through parameters.

derivative()[source]

Apply the derivative of the solution map to perturbations in the parameters

This method applies the derivative of the solution map to perturbations in the parameters, to obtain perturbations in the optimal values of the variables. In other words, it tells you how the optimal values of the variables would be changed.

You can specify perturbations in a parameter by setting its .delta attribute (if unspecified, the perturbation defaults to 0). This method populates the .delta attribute of the variables as a side-effect.

This method can only be called after calling .solve() with requires_grad=True.

Below is a simple example:

import cvxpy as cp
import numpy as np

p = cp.Parameter()
x = cp.Variable()
quadratic = cp.square(x - 2 * p)
problem = cp.Problem(cp.Minimize(quadratic), [x >= 0])
p.value = 3.0
problem.solve(requires_grad=True, eps=1e-10)
# .derivative() populates the .gradient attribute of the parameters
problem.backward()
p.delta = 1e-3
# Because x* = 2 * p, dx*/dp = 2, so (dx*/dp)(p.delta) == 2e-3
np.testing.assert_allclose(p.gradient, 2e-3)
Raises
  • ValueError – if solve was not called with requires_grad=True

  • SolverError – if the problem is infeasible or unbounded

get_problem_data(solver, gp=False)[source]

Returns the problem data used in the call to the solver.

When a problem is solved, CVXPY creates a chain of reductions enclosed in a SolvingChain, and compiles it to some low-level representation that is compatible with the targeted solver. This method returns that low-level representation.

For some solving chains, this low-level representation is a dictionary that contains exactly those arguments that were supplied to the solver; however, for other solving chains, the data is an intermediate representation that is compiled even further by the solver interfaces.

A solution to the equivalent low-level problem can be obtained via the data by invoking the solve_via_data method of the returned solving chain, a thin wrapper around the code external to CVXPY that further processes and solves the problem. Invoke the unpack_results method to recover a solution to the original problem.

For example:

objective = ...
constraints = ...
problem = cp.Problem(objective, constraints)
data, chain, inverse_data = problem.get_problem_data(cp.SCS)
# calls SCS using `data`
soln = chain.solve_via_data(problem, data)
# unpacks the solution returned by SCS into `problem`
problem.unpack_results(soln, chain, inverse_data)

Alternatively, the data dictionary returned by this method contains enough information to bypass CVXPY and call the solver directly.

For example:

problem = cp.Problem(objective, constraints)
data, _, _ = problem.get_problem_data(cp.SCS)

import scs
probdata = {
  'A': data['A'],
  'b': data['b'],
  'c': data['c'],
}
cone_dims = data['dims']
cones = {
    "f": cone_dims.zero,
    "l": cone_dims.nonpos,
    "q": cone_dims.soc,
    "ep": cone_dims.exp,
    "s": cone_dims.psd,
}
soln = scs.solve(data, cones)

The structure of the data dict that CVXPY returns depends on the solver. For details, consult the solver interfaces in cvxpy/reductions/solvers.

Parameters
  • solver (str) – The solver the problem data is for.

  • gp (bool, optional) – If True, then parses the problem as a disciplined geometric program instead of a disciplined convex program.

Returns

  • dict or object – lowest level representation of problem

  • SolvingChain – The solving chain that created the data.

  • list – The inverse data generated by the chain.

is_dcp()[source]

Does the problem satisfy DCP rules?

is_dgp()[source]

Does the problem satisfy DGP rules?

is_dpp()[source]

Does the problem satisfy DPP rules?

is_dqcp()[source]

Does the problem satisfy the DQCP rules?

is_qp()[source]

Is problem a quadratic program?

property objective

The problem’s objective.

Note that the objective cannot be reassigned after creation, and modifying the objective after creation will result in undefined behavior.

Type

Minimize or Maximize

parameters()[source]

Accessor method for parameters.

Returns

A list of the parameters in the problem.

Return type

list of Parameter

classmethod register_solve(name, func)[source]

Adds a solve method to the Problem class.

Parameters
  • name (str) – The keyword for the method.

  • func (function) – The function that executes the solve method. This function must take as its first argument the problem instance to solve.

property size_metrics

Information about the problem’s size.

Type

SizeMetrics

solve(*args, **kwargs)[source]

Solves the problem using the specified method.

Populates the status and value attributes on the problem object as a side-effect.

Parameters
  • solver (str, optional) – The solver to use. For example, ‘ECOS’, ‘SCS’, or ‘OSQP’.

  • verbose (bool, optional) – Overrides the default of hiding solver output.

  • gp (bool, optional) – If True, parses the problem as a disciplined geometric program instead of a disciplined convex program.

  • qcp (bool, optional) – If True, parses the problem as a disciplined quasiconvex program instead of a disciplined convex program.

  • requires_grad (bool, optional) – Makes it possible to compute gradients with respect to parameters by calling .backward() after solving, or to compute perturbations to the variables by calling .derivative(). When True, the solver must be SCS, and gp, qcp must be false; a DPPError is thrown when problem is not DPP.

  • solver_specific_opts (dict, optional) – A dict of options that will be passed to the specific solver. In general, these options will override any default settings imposed by cvxpy.

  • method (function, optional) – A custom solve method to use.

Returns

The optimal value for the problem, or a string indicating why the problem could not be solved.

Return type

float

Raises
  • cvxpy.error.DCPError – Raised if the problem is not DCP and gp is False.

  • cvxpy.error.DGPError – Raised if the problem is not DGP and gp is True.

  • cvxpy.error.SolverError – Raised if no suitable solver exists among the installed solvers, or if an unanticipated error is encountered.

property solver_stats

Information returned by the solver.

Type

SolverStats

property status

The status from the last time the problem was solved; one of optimal, infeasible, or unbounded (with or without suffix inaccurate).

Type

str

unpack_results(solution, chain, inverse_data)[source]

Updates the problem state given the solver results.

Updates problem.status, problem.value and value of primal and dual variables.

Parameters
  • solution (object) – The solution returned by applying the chain to the problem and invoking the solver on the resulting data.

  • chain (SolvingChain) – A solving chain that was used to solve the problem.

  • inverse_data (list) – The inverse data returned by applying the chain to the problem.

Raises

cvxpy.error.SolverError – If the solver failed

property value

The value from the last time the problem was solved (or None if not solved).

Type

float

variables()[source]

Accessor method for variables.

Returns

A list of the variables in the problem.

Return type

list of Variable