1. cplex介绍

Cplex是IBM出的一款科学计算软件,从IBM官网可以下到最新版。最近惊奇的发现python竟然能直接安装使用cplex了!
安装方法如下:

pip install cplex

2. 示例代码和说明

用一个简单案例尝试一下:
maxx1+2x2+3x3+x4\max x_1+2x_2+3x_3+x_4
s.t. x1+x2+x3+10x420-x_1+x_2+x_3+10x_4\le20
x13x2+x330x_1-3x_2+x_3\le30
x23.5x4=0x_2-3.5x_4=0
x140x_1\le40
2x432\le x_4\le3x4Zx_4\in Z
x1,x2,x30x_1,x_2,x_3\ge0

import cplex
from cplex.exceptions import CplexError
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 = [[my_colnames, [-1.0, 1.0, 1.0, 10.0]],
            [my_colnames, [1.0, -3.0, 1.0, 0.0]],
            [my_colnames, [0.0, 1.0, -3.5, 0.0]]]
    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 status = ", my_prob.solution.status[my_prob.solution.get_status()])
print("Solution value  = ", my_prob.solution.get_objective_value())
x = my_prob.solution.get_values()
print('x: ',x)     

输出为:
运筹系列20:IBM的cplex算法包

代码中:
my_ctype中,C表示连续变量,I表示整数型变量
my_sense,G表示大于等于,E表示等于,L表示小于等于
不过由于只用能矩阵和向量形式表示,因此对于某些复杂的模型,写起来还是比较麻烦的。

相关文章:

  • 2022-12-23
  • 2021-05-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-16
  • 2021-05-23
  • 2021-11-12
猜你喜欢
  • 2021-11-12
  • 2021-10-30
  • 2021-11-17
  • 2021-12-24
  • 2021-12-19
  • 2021-12-28
  • 2021-05-28
相关资源
相似解决方案