cvxpy 示例代码

cvxpy 优化模型示例代码

  1. 线性规划

如果线性规划的最优解存在,则最优解只能在可行域的边界上达到(特别是在可行域的顶点上达到)

import cvxpy as cp
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt

data = pd.read_csv('Pdata.csv', header=None, encoding='utf-8')
darray = data.values

c = darray[:-1, :-1]
e = darray[:-1, -1].reshape(-1, 1)
d = darray[-1, :-1].reshape(1, -1)

x = cp.Variable((6, 8))

obj = cp.Minimize(cp.sum(cp.multiply(c, x))) # c, x 同形状, 这里是矩阵的点乘

# x 的每一行求列和, 均小于e的每一行; x 的每一列求行和, 等于d的每一行, x 的每一个元素均非负

con = [cp.sum(x, axis=1, keepdims=True) <= e,
       cp.sum(x, axis=0, keepdims=True) == d,
       x >= 0]

prob = cp.Problem(obj, con)

prob.solve(solver='GLPK_MI', verbose=True)

print('最优值为: {0}\n最优解为{1}'.format(prob.value, x.value))
  1. 整数规划
import cvxpy as cp
import numpy as np
import pandas as pd

c = np.array([40, 90])
a = np.array([[9,7], [-7,-20]])
b = np.array([56, -70])

x = cp.Variable(2, integer=True) # 约束必须为整数

obj = cp.Minimize(cp.sum(cp.multiply(c, x))) # cp.multiply 为对应元素相乘, 要求c ,x同形状, 且结果与c 、x同形状

cons = [a @ x <= b, x >= 0] # @ 矩阵乘法

prob = cp.Problem(obj, cons)

prob.solve(solver='GLPK_MI', verbose=True)

print(prob.value)
print(x.value)
  1. 指派问题
import pandas as pd
import numpy as np
import cvxpy as cp
from matplotlib import pyplot as plt


data = pd.read_csv('Pdata02.csv', encoding='utf-8', header=None)

darray = data.values

x = cp.Variable((5,5), integer=True)
obj = cp.Minimize(cp.sum(cp.multiply(darray, x)))
con = [0 <= x, x <= 1, cp.sum(x, axis=0, keepdims=True) == 1, cp.sum(x, axis=1, keepdims=True) == 1]
prob = cp.Problem(obj, con)
prob.solve(solver='GLPK_MI')
print(prob.value)
print(x.value)
  1. 装箱问题 - 1988美赛B
#%%
import cvxpy as cp
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt

data = pd.read_csv('Pdata03.csv', encoding='utf-8', header=None)
darray = data.values

length = darray[0, :]
weight = darray[1, :]
number = darray[2, :]

l_2 = length.copy()
l_2[:4] = 0

L = 1020
W = 40000
S = 302.7

x = cp.Variable((7, 2), integer=True)

obj = cp.Maximize(cp.sum(cp.multiply(weight, cp.sum(x, axis=1))))

cons = []

cons.append(cp.sum(x, axis=1) <= number)
cons.append(x >= 0)
cons.append(length @ x <= L)
cons.append(weight @ x <= W)
cons.append(cp.sum(l_2 @ x) <= S)

prob = cp.Problem(obj, cons)

prob.solve(solver='GLPK_MI', verbose=True)
print(prob.value)
print(x.value)
  1. 非线性规划
import cvxpy as cp
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt

c1 = np.array([1, 1, 3, 4, 2])
c2 = np.array([-8, -2, -3, -1, -2])
a = np.array([[1,1,1,1,1], [1,2,2,1,6], [2,1,6,0,0], [0,0,1,1,5]])

b = np.array([400, 800, 200, 200])

x = cp.Variable(5, integer=True)

obj = cp.Minimize(c1*x**2+c2*x)

con = [0 <= x, x <= 99, a@x <= b]

prob = cp.Problem(obj, con)

prob.solve(solver='ECOS_BB')

print(prob.value)
print(x.value)
posted @ 2021-07-17 21:43  popozyl  阅读(1266)  评论(0编辑  收藏  举报