Gurobi
- 简介:
Gurobi是一种优化器,用于解决各种数学规划问题。它是一种商业软件,由美国Gurobi公司开发。Gurobi可以解决线性问题、二次型目标问题和混合整数线性和二次型问题。它是一款功能强大的优化器,具有突出的性价比,可以为客户在开发和实施中极大降低成本。
<1> cplex使用方法
- 安装包
在python工作的虚拟环境中进行安装包
方式1:
pip install cplex
方式2:
在pycharm中的包市场里进行下载
2.写程序然后运行
# -*- coding: utf-8 -*-
# The MIP problem solved in this example is:
#
# Maximize x1 + 2 x2 + 3 x3 + x4
# Subject to
# - x1 + x2 + x3 + 10 x4 <= 20
# x1 - 3 x2 + x3 <= 30
# x2 - 3.5x4 = 0
# Bounds
# 0 <= x1 <= 40
# 0 <= x2
# 0 <= x3
# 2 <= x4 <= 3
# Integers
# x4
import cplex
from cplex.exceptions import CplexError
# data common to all populateby functions
my_obj = [1.0, 2.0, 3.0, 1.0]
my_ub = [40.0, cplex.infinity, cplex.infinity, 3.0]
my_lb = [0.0, 0.0, 0.0, 2.0]
my_ctype = "CCCI"
my_colnames = ["x1", "x2", "x3", "x4"]
my_rhs = [20.0, 30.0, 0.0]
my_rownames = ["r1", "r2", "r3"]
my_sense = "LLE"
def populatebyrow(prob):
prob.objective.set_sense(prob.objective.sense.maximize)
prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype,
names=my_colnames)
rows = [[["x1", "x2", "x3", "x4"], [-1.0, 1.0, 1.0, 10.0]],
[["x1", "x2", "x3"], [1.0, -3.0, 1.0]],
[["x2", "x4"], [1.0, -3.5]]]
prob.linear_constraints.add(lin_expr=rows, senses=my_sense,
rhs=my_rhs, names=my_rownames)
try:
my_prob = cplex.Cplex()
handle = populatebyrow(my_prob)
my_prob.solve()
except CplexError as exc:
print(exc)
print()
# solution.get_status() returns an integer code
print("Solution status = ", my_prob.solution.get_status(), ":", end=' ')
# the following line prints the corresponding string
print(my_prob.solution.status[my_prob.solution.get_status()])
print("Solution value = ", my_prob.solution.get_objective_value())
numcols = my_prob.variables.get_num()
numrows = my_prob.linear_constraints.get_num()
slack = my_prob.solution.get_linear_slacks()
x = my_prob.solution.get_values()
print('x: ')
print(x)
输出结果为
<2> Matlab调用cplex使用方法
需要用到 Yalmip程序包以及Cplex程序包
2.1 将这两种程序包中放入到matlab的搜索路径中。
2.2 验证程序
代码:
%==========================================================================
%函数:Demo.m
%功能:本程序仅作为MATLAB配置CPLEX测试使用
%修改时间:2020-03-24
%作者:Chale Young
%==========================================================================
function [x,y]=Demo
%% 定义变量
cons=[];
%% 决策变量
x=sdpvar(1,3);
%% 目标函数
y=2*x(1)+3*x(2)+x(3);
%% 约束条件
cons=[cons,x(1)+4*x(2)+2*x(3)>=8];
cons=[cons,3*x(1)+2*x(2)>=6];
cons=[cons,x(1)>=0];
cons=[cons,x(2)>=0];
cons=[cons,x(3)>=0];
%% 求解
options=sdpsettings('solver','cplex');
optimize(cons,y);
%% 结果
x=double(x);
y=double(y);
end
输出结果: