CVXPY

🔬 线性规划

We consider thefollowing problem

\[ \begin{align*} & \underset{x}{\min}~-3x_1-2x_2 \\ & {\rm s.t.}~3x_1 + 4x_2 \le 7 \\ & \quad~~2x_1 + x_2 \le 3 \\ & \quad~~-3x_1 + 2x_2 = 2 \\ & \quad~~0 \le x_1,x_2 \le 10 \\ \end{align*} \]


import numpy as np
import cvxpy as cp
import time
# Seed for reproducibility
np.random.seed(1)
# Define parameters
c = np.array([-3, -2])
A_ub = np.array([[3, 4], [2, 1]])
b_ub = np.array([7, 3])

# Equality constraint
Aeq = np.array([[-3, 2]])
beq = np.array([2])

# Bounds for variables
lb = np.array([0, 0])
ub = np.array([10, 10])

# Define the problem
n = 2
x = cp.Variable(n)
prob = cp.Problem(cp.Minimize(c @ x),
                  [A_ub @ x <= b_ub,
                   Aeq @ x == beq,
                   x >= lb,
                   x <= ub])

# Solve the problem
result = prob.solve()

# Print results
print("Optimal value:", result)
print("Optimal point:", x.value)

Optimal value: -4.0000000001132126
Optimal point: [0.33333333 1.5 ]


🔬 二次规划

We consider the following problem

\[ \min f(x) = \frac{1}{2}x_1^2 + x_2^2 -x_1x_2 -2x_1 -6x_2 = \frac{1}{2}x^{T}Hx + c^Tx \]

The constraint condition is

\[ \begin{cases} x_1 + x_2 \le 2\\ -x_1 + 2x_2 \le 2 \\ 2x_1 + x_2 \le 3 \\ x_1 \ge 0,x_2 \ge 0. \end{cases} \]

Where

\[ H = \begin{bmatrix} 1 & -1 \\ -1 & 2 \end{bmatrix}, c = \begin{bmatrix} -2 \\ -6 \end{bmatrix}, x = \begin{bmatrix} x_1 \\ x_2 \end{bmatrix} \]


H = np.array([[1, -1], [-1, 2]])
c = np.array([-2, -6])
A = np.array([[1, 1], [-1, 2], [2, 1]])
b = np.array([2, 2, 3])
lb = np.array([0, 0])

start_time = time.time()
# Define and solve the CVXPY problem
x = cp.Variable(2)
prob = cp.Problem(cp.Minimize((1/2) * cp.quad_form(x, H) + c @ x),
                  [A @ x <= b,
                   x >= lb])  
result = prob.solve()
end_time = time.time()

# Print the results
print("Optimal value:", result)
print("Optimal point:", x.value)
print("Time:",end_time-start_time)

Optimal value: -8.222222222222223
Optimal point: [0.66666667 1.33333333]
Time: 0.007505178451538086

posted @ 2024-11-20 19:57  MathClown  阅读(1)  评论(0编辑  收藏  举报