l = cplex.SparsePair(ind = ['x'], val = [1.0])
q = cplex.SparseTriple(ind1 = ['x'], ind2 = ['y'], val = [1.0])
c.quadratic_constraints.add(name = "my_quad",
lin_expr = l,
quad_expr = q,
rhs = 1.0,
sense = "G")
这里一定要注意:SparsePair 和 SparseTriple 的入参顺序不能调换,必须参数 ind 在前,系数值 val 在后。否则会报错:
TypeError: non-float value in input sequence
cpx.set_results_stream(None)
cpx.set_log_stream(None)
cpx.parameters.preprocessing.reduce.set(0)
cpx.parameters.lpmethod.set(cpx.parameters.lpmethod.values.primal)
cpx.objective.set_sense(cpx.objective.sense.maximize)
# 添加变量
cpx.variables.add(obj=[0.0],lb=[0.0],ub=[cplex.infinity],names=['X1'])
cpx.variables.add(obj=[0.0],lb=[0.0],ub=[cplex.infinity],names=['X2'])
cpx.variables.add(obj=[0.0],lb=[0.0],ub=[cplex.infinity],names=['X3'])
cpx.variables.add(obj=[0.0],lb=[0.0],ub=[cplex.infinity],names=['X4'])
cpx.variables.add(obj=[0.0],lb=[0.0],ub=[cplex.infinity],names=['X5'])
# 设置线性变量
cpx.objective.set_linear([(0,21),(2,22)])
cpx.objective.set_linear([(1,23),(3,24),(4,25)])
cpx.objective.set_linear([(2,11)])
print(cpx.objective.get_linear())
运行结果如下:
[21.0, 23.0, 11.0, 24.0, 25.0]
备注:在 set_linear 之前必须添加变量,否则会报错
cplex.exceptions.errors.CplexSolverError: CPLEX Error 1201: Column index 0 out of range.
| | | | |
|---|
| objective | set_linear | | | |
| linear_constraints | add | | | |
| solution | get_status() | | | |
| solution | get_values(*) | | | |
| solution | status | unbounded | | |
| solution | advanced | get_ray() | | |
| SparsePair | | | | |
| parameters | preprocessing | reduce.set(0) | | |
| parameters | lpmethod | set(*) | | |
| parameters | lpmethod | values | primal | 单纯形法 |
Python 用户的 CPLEX
python教程
模块 cplex 中的主类是类 Cplex。 它将优化问题的数学方程与用户所指定的有关 CPLEX 应如何对问题求解的信息封装在一起。 类 Cplex 提供了方法以修改问题、对问题求解以及查询问题本身及其解法。 类 Cplex 的方法分组为相关功能的类别。 例如,用于添加、修改和查询与变量相关的数据的方法包含在类 Cplex 的成员 variables 中。
可以在 CPLEX 的各组件中对标准方程中的此线性规划模型求解。
要求解的问题是:
最大化
0≤x1≤40,x2≥0,x3≥0
以下是使用 CPLEX 对示例求解的 Python 应用程序:
execfile("cplexpypath.py")
import cplex
from cplex.exceptions import CplexError
import sys
# data common to all populateby functions
my_obj = [1.0, 2.0, 3.0]
my_ub = [40.0, cplex.infinity, cplex.infinity]
my_colnames = ["x1", "x2", "x3"]
my_rhs = [20.0, 30.0]
my_rownames = ["c1", "c2"]
my_sense = "LL"
def populatebyrow(prob):
prob.objective.set_sense(prob.objective.sense.maximize)
# since lower bounds are all 0.0 (the default), lb is omitted here
prob.variables.add(obj = my_obj, ub = my_ub, names = my_colnames)
# can query variables like the following bounds and names:
# lbs is a list of all the lower bounds
lbs = prob.variables.get_lower_bounds()
# ub1 is just the first lower bound
ub1 = prob.variables.get_upper_bounds(0)
# names is ["x1", "x3"]
names = prob.variables.get_names([0, 2])
rows = [[[0,"x2","x3"],[-1.0, 1.0,1.0]],
[["x1",1,2],[ 1.0,-3.0,1.0]]]
prob.linear_constraints.add(lin_expr = rows, senses = my_sense,
rhs = my_rhs, names = my_rownames)
# because there are two arguments, they are taken to specify a range
# thus, cols is the entire constraint matrix as a list of column vectors
cols = prob.variables.get_cols("x1", "x3")
def populatebycolumn(prob):
prob.objective.set_sense(prob.objective.sense.maximize)
prob.linear_constraints.add(rhs = my_rhs, senses = my_sense,
names = my_rownames)
c = [[[0,1],[-1.0, 1.0]],
[["c1",1],[ 1.0,-3.0]],
[[0,"c2"],[ 1.0, 1.0]]]
prob.variables.add(obj = my_obj, ub = my_ub, names = my_colnames,
columns = c)
def populatebynonzero(prob):
prob.objective.set_sense(prob.objective.sense.maximize)
prob.linear_constraints.add(rhs = my_rhs, senses = my_sense,
names = my_rownames)
prob.variables.add(obj = my_obj, ub = my_ub, names = my_colnames)
rows = [0,0,0,1,1,1]
cols = [0,1,2,0,1,2]
vals = [-1.0,1.0,1.0,1.0,-3.0,1.0]
prob.linear_constraints.set_coefficients(zip(rows, cols, vals))
# can also change one coefficient at a time
# prob.linear_constraints.set_coefficients(1,1,-3.0)
# or pass in a list of triples
# prob.linear_constraints.set_coefficients([(0,1,1.0), (1,1,-3.0)])
def lpex1(pop_method):
my_prob = cplex.Cplex()
if pop_method == "r":
handle = populatebyrow(my_prob)
if pop_method == "c":
handle = populatebycolumn(my_prob)
if pop_method == "n":
handle = populatebynonzero(my_prob)
my_prob.solve()
except CplexError, exc:
print exc
return
numrows = my_prob.linear_constraints.get_num()
numcols = my_prob.variables.get_num()
print
# solution.get_status() returns an integer code
print "Solution status = " , my_prob.solution.get_status(), ":",
# 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()
slack = my_prob.solution.get_linear_slacks()
pi = my_prob.solution.get_dual_values()
x = my_prob.solution.get_values()
dj = my_prob.solution.get_reduced_costs()
for i in range(numrows):
print "Row %d: Slack = %10f Pi = %10f" % (i, slack[i], pi[i])
for j in range(numcols):
print "Column %d: Value = %10f Reduced cost = %10f" % (j, x[j], dj[j])
my_prob.write("lpex1.lp")
if __name__ == "__main__":
if len(sys.argv) != 2 or sys.argv[1] not in ["-r", "-c", "-n"]:
print "Usage: lpex1.py -X"
print " where X is one of the following options:"
print " r generate problem by row"
print " c generate problem by column"
print " n generate problem by nonzero"
print " Exiting..."
sys.exit(-1)
lpex1(sys.argv[1][1])
else:
prompt = """Enter the letter indicating how the problem data should be populated:
r : populate by rows
c : populate by columns
n : populate by nonzeros\n ? > """
r = 'r'
c = 'c'
n = 'n'
lpex1(input(prompt))
Python 用户的 CPLEXpython教程模块 cplex 中的主类是类 Cplex。 它将优化问题的数学方程与用户所指定的有关 CPLEX 应如何对问题求解的信息封装在一起。 类 Cplex 提供了方法以修改问题、对问题求解以及查询问题本身及其解法。 类 Cplex 的方法分组为相关功能的类别。 例如,用于添加、修改和查询与变量相关的数据的方法包含在类 Cplex 的成员 variab...
论文题目:Clustering by Passing Messages Between Data Points
Clustering by Passing Messages Between Data Points
Brendan J. Frey*, Delbert Dueck
通过在数据点之间传递消息进行聚类
Brendan J. Frey*, Delbert Dueck
Abstract
Clustering data by identifying a subset of representative e
好久不写博客了,大部分时间都用来干一些重复而繁杂的工作,好久没有认认真真学习一些东西了。
借着参加服创的机会要入手学习一些运筹学知识,就从Cplex开始吧。
首先直接用Python的cplex接口写线性规划比较简单,话不多说直接从实例看:
每一句的详解都在旁边的注释上
Cplex实例
# The MIP problem solved in this example is:
# Maximize x1 + 2 x2 + 3 x3 + x4
# Subject to
# - x1 +
线性约束:
linear−expressionsymbollinear−expression
linear_ -expression \quad symbol \quad linear_-expression
linear−expressionsymbollinear−expression
其中symbol仅能取===、≤\le≤、≥\ge≥一般形式:
minCxts.t.Ax≥Bx≥0
\min C^t _x
\\s.t. \quad Ax \ge B
\\x \ge 0
minCxts.
cplex python安装及入门1. cplex安装2. cplex学习资源3. 百度网盘资源
笔者最近学习cplex,从安装到入门走了不少弯路,现在提供一个相对全面的cplex学习博文。
1. cplex安装
可以参考这篇博文DOcplex系列(二)——怎样成功安装和调用学术版DOcplex
里面介绍了学术版cplex的安装以及在python下的调用。
学术版cplex12.8网盘资源将在文末提供
该文仅介绍了在python下的安装。因为anaconda统一管理包更方便,而pycharm直接使用这些包即
https://ibm.onthehub.com/WebStore/ProductSearchOfferingList.aspx?srch=Cplex
cplex_studio 版本下载地址,可以注册学生版or faculty版本
第一步:注册IBM id账号
第二步:下载相关系统的CPLEX(windows/linux/mac)
这里需要系统中安装有JAVA,选择 open wi
CPLEX是一个高性能的数学优化软件包,它提供了一系列强大的求解器和工具,用于解决线性规划、整数规划、混合整数规划等数学优化问题。CPLEX可以通过多种编程语言进行使用,其中包括Python。
在Python中使用CPLEX,你可以使用CPLEX Python API,它提供了与CPLEX求解器的交互接口。你可以通过安装CPLEX软件包并设置相应的环境变量后,使用CPLEX Python API来构建和求解数学优化模型。
下面是一个简单的示例代码,演示如何使用CPLEX Python API来解决一个线性规划问题:
```python
import cplex
# 创建一个新的线性规划问题
problem = cplex.Cplex()
# 添加变量
problem.variables.add(names=["x", "y", "z"])
# 设置目标函数系数
problem.objective.set_linear("x", 1.0)
problem.objective.set_linear("y", 2.0)
problem.objective.set_linear("z", 3.0)
# 添加约束条件
problem.linear_constraints.add(lin_expr=[cplex.SparsePair(ind=["x", "y", "z"], val=[1.0, 1.0, 1.0])], senses=["G"], rhs=[1.0])
problem.linear_constraints.add(lin_expr=[cplex.SparsePair(ind=["x"], val=[-1.0])], senses=["L"], rhs=[0.0])
problem.linear_constraints.add(lin_expr=[cplex.SparsePair(ind=["y"], val=[2.0])], senses=["E"], rhs=[3.0])
# 求解线性规划问题
problem.solve()
# 打印结果
print("Solution status = ", problem.solution.get_status())
print("Objective value = ", problem.solution.get_objective_value())
print("Solution = ", problem.solution.get_values())
这是一个简单的例子,你可以根据自己的需求来构建更复杂的数学优化模型。CPLEX Python API提供了丰富的方法和函数,可以帮助你构建和求解各种类型的数学优化问题。如果你想了解更多关于CPLEX Python API的信息,你可以参考CPLEX的官方文档或者其他相关资源。