0
# Problem Formulation
1
2
Classes for defining and solving optimization problems in CVXPY. These classes coordinate the objective function, constraints, and solver interface to enable problem solving.
3
4
## Capabilities
5
6
### Problem Class
7
8
The main class that represents an optimization problem, combining an objective with constraints and providing the interface for solving.
9
10
```python { .api }
11
class Problem:
12
"""
13
An optimization problem.
14
15
Parameters:
16
- objective: Minimize or Maximize object representing the objective function
17
- constraints: list of Constraint objects (optional)
18
"""
19
def __init__(self, objective, constraints=None): ...
20
21
def solve(self, solver=None, verbose=False, gp=False, qcp=False,
22
requires_grad=False, enforce_dpp=False, ignore_dcp=False,
23
canon_backend=None, **kwargs):
24
"""
25
Solve the optimization problem.
26
27
Parameters:
28
- solver: str, name of solver to use (auto-selected if None)
29
- verbose: bool, whether to print solver output
30
- gp: bool, whether to parse as geometric program
31
- qcp: bool, whether to parse as quadratically constrained program
32
- requires_grad: bool, whether to compute gradients
33
- enforce_dpp: bool, whether to enforce disciplined parametrized programming
34
- ignore_dcp: bool, whether to ignore disciplined convex programming rules
35
- canon_backend: str, canonicalization backend to use
36
- **kwargs: additional solver-specific options
37
38
Returns:
39
- float: optimal objective value
40
"""
41
...
42
43
def is_dcp(self, dpp=False):
44
"""Check if problem follows disciplined convex programming rules."""
45
...
46
47
def is_dgp(self, dpp=False):
48
"""Check if problem follows disciplined geometric programming rules."""
49
...
50
51
def is_dqcp(self):
52
"""Check if problem is disciplined quasiconvex."""
53
...
54
55
@property
56
def objective(self):
57
"""The problem's objective."""
58
...
59
60
@property
61
def constraints(self):
62
"""List of the problem's constraints."""
63
...
64
65
@property
66
def status(self):
67
"""Status of the problem after solving."""
68
...
69
70
@property
71
def value(self):
72
"""Optimal objective value (None if not solved)."""
73
...
74
75
@property
76
def variables(self):
77
"""Variables in the problem."""
78
...
79
80
@property
81
def parameters(self):
82
"""Parameters in the problem."""
83
...
84
85
@property
86
def constants(self):
87
"""Constants in the problem."""
88
...
89
90
def get_problem_data(self, solver):
91
"""Get problem data in solver's format."""
92
...
93
```
94
95
Usage examples:
96
97
```python
98
import cvxpy as cp
99
import numpy as np
100
101
# Simple quadratic program
102
x = cp.Variable(2)
103
objective = cp.Minimize(cp.sum_squares(x))
104
constraints = [x >= 0, cp.sum(x) == 1]
105
problem = cp.Problem(objective, constraints)
106
107
# Solve the problem
108
problem.solve()
109
print(f"Status: {problem.status}")
110
print(f"Optimal value: {problem.value}")
111
print(f"Optimal x: {x.value}")
112
113
# Portfolio optimization example
114
n = 5
115
mu = np.random.randn(n) # expected returns
116
Sigma = np.random.randn(n, n)
117
Sigma = Sigma.T @ Sigma # covariance matrix
118
119
w = cp.Variable(n) # portfolio weights
120
risk = cp.quad_form(w, Sigma)
121
ret = mu.T @ w
122
123
# Minimize risk for target return
124
target_return = 0.1
125
objective = cp.Minimize(risk)
126
constraints = [cp.sum(w) == 1, w >= 0, ret >= target_return]
127
portfolio_problem = cp.Problem(objective, constraints)
128
portfolio_problem.solve()
129
130
print(f"Optimal portfolio: {w.value}")
131
print(f"Portfolio risk: {risk.value}")
132
print(f"Portfolio return: {ret.value}")
133
134
# Check problem properties
135
print(f"Is DCP: {portfolio_problem.is_dcp()}")
136
print(f"Variables: {[var.name() for var in portfolio_problem.variables()]}")
137
```
138
139
### Objective Functions
140
141
Base class and specific implementations for optimization objectives.
142
143
```python { .api }
144
class Objective:
145
"""
146
Base class for optimization objectives.
147
148
Parameters:
149
- expr: Expression to optimize
150
"""
151
def __init__(self, expr): ...
152
153
@property
154
def value(self):
155
"""Value of the objective expression."""
156
...
157
158
@property
159
def expr(self):
160
"""The objective expression."""
161
...
162
163
def is_dcp(self, dpp=False):
164
"""Check if objective follows DCP rules."""
165
...
166
```
167
168
### Minimize
169
170
Creates a minimization objective for optimization problems.
171
172
```python { .api }
173
class Minimize(Objective):
174
"""
175
Minimization objective.
176
177
Parameters:
178
- expr: Expression to minimize
179
"""
180
def __init__(self, expr): ...
181
```
182
183
Usage examples:
184
185
```python
186
import cvxpy as cp
187
188
x = cp.Variable()
189
190
# Minimize a quadratic function
191
obj1 = cp.Minimize(x**2 + 2*x + 1)
192
193
# Minimize L1 norm (for sparse solutions)
194
x_vec = cp.Variable(10)
195
obj2 = cp.Minimize(cp.norm(x_vec, 1))
196
197
# Minimize sum of squares (least squares)
198
A = cp.Parameter((5, 10))
199
b = cp.Parameter(5)
200
obj3 = cp.Minimize(cp.sum_squares(A @ x_vec - b))
201
202
# Minimize maximum element (infinity norm)
203
obj4 = cp.Minimize(cp.norm(x_vec, "inf"))
204
```
205
206
### Maximize
207
208
Creates a maximization objective for optimization problems.
209
210
```python { .api }
211
class Maximize(Objective):
212
"""
213
Maximization objective.
214
215
Parameters:
216
- expr: Expression to maximize
217
"""
218
def __init__(self, expr): ...
219
```
220
221
Usage examples:
222
223
```python
224
import cvxpy as cp
225
import numpy as np
226
227
# Maximize utility function
228
x = cp.Variable(3, nonneg=True)
229
utility = cp.log(x[0]) + cp.log(x[1]) + cp.log(x[2])
230
obj1 = cp.Maximize(utility)
231
232
# Maximize minimum element (max-min fairness)
233
obj2 = cp.Maximize(cp.minimum(x[0], cp.minimum(x[1], x[2])))
234
235
# Maximize expected return (portfolio optimization)
236
mu = np.array([0.1, 0.2, 0.15])
237
w = cp.Variable(3, nonneg=True)
238
expected_return = mu.T @ w
239
obj3 = cp.Maximize(expected_return)
240
241
# Create and solve maximization problem
242
constraints = [cp.sum(w) == 1] # weights sum to 1
243
problem = cp.Problem(obj3, constraints)
244
problem.solve()
245
print(f"Optimal weights: {w.value}")
246
print(f"Maximum return: {expected_return.value}")
247
```
248
249
### Advanced Problem Solving
250
251
```python
252
import cvxpy as cp
253
254
# Solve with specific solver
255
x = cp.Variable()
256
problem = cp.Problem(cp.Minimize(x**2), [x >= 1])
257
258
# Try different solvers
259
problem.solve(solver=cp.OSQP)
260
print(f"OSQP solution: {x.value}")
261
262
problem.solve(solver=cp.SCS)
263
print(f"SCS solution: {x.value}")
264
265
# Solver-specific options
266
problem.solve(solver=cp.OSQP, eps_abs=1e-8, eps_rel=1e-8, max_iter=10000)
267
268
# Get problem statistics
269
print(f"Solve time: {problem.solver_stats.solve_time}")
270
print(f"Setup time: {problem.solver_stats.setup_time}")
271
print(f"Iterations: {problem.solver_stats.num_iters}")
272
273
# Warm start (reuse previous solution)
274
problem.solve(warm_start=True)
275
276
# Check if problem is DCP compliant
277
if not problem.is_dcp():
278
print("Problem is not DCP compliant")
279
# Can try to solve anyway
280
problem.solve(ignore_dcp=True)
281
```