使用背景
- 使用 continuous_var_list() 定义决策变量 x
- 使用 continuous_var_matrix() 定义决策变量 y
- x 和 y 之间的相互制约、相互限制的约束条件添加。
使用方法
#导入包
import cplex
import docplex
from docplex.mp.model import Model
from typing import List
# 输入数据
qB=[20,15,13,10,4]
cB=[2,5,7,10,11]
qQ=[2,10,15,10]
cQ=[20,18,15,13]
# 定义优化模型
mdl = Model()
## 定义决策变量
### continuous_var_list 定义一维决策变量
index1: List[int]=[i for i in range(len(qQ))]
x = mdl.continuous_var_list(index1, name='X')
### continuous_var_matrix 定义一维决策变量
index2=[i for i in range(len(qB))]
y = mdl.continuous_var_matrix(index2, index1, name='Y')
# 定义约束条件
cst = []
cst += [x[j] >= 0 for j in index1] + [x[j] <= qQ[j] for j in index1] + [mdl.sum(x[j] for j in index1) <= sum(qB)]
cst += [y[i,j] >= 0 for i in index2 for j in index1] + [mdl.sum(y[i,j] for i in index2) == x[j] for j in index1] + [mdl.sum(y[i,j] for j in index1) <= qB[i] for i in index2]
for c in cst:
mdl.add_constraint(c)
# 定义优化函数
obj = mdl.sum(y[i,j]*(pow((cQ[j]-cB[i]),3)) for i in index2 for j in index1)
# 最大化 目标函数 ,并求解
mdl.maximize(obj)
#求解模型并显示
solution = mdl.solve()
print(solution)
运行结果: