`
hankgong
  • 浏览: 196302 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

PULP:用Python替代AMPL建模语言

阅读更多

数学建模简单的说就是求最大化最小化问题,现在大学都有数学建模比赛,另外做科研的时候其实也经常用到。一般要么是用Lingo,要么是用matlab,其实AMPL是比较通用的描述及数学建模的语言,不过比较贵,记得我以前发神经买过一年的license花了我快2000块钱。

 

现在cplex或者ampl都有破解版的可以下到,不过毕竟不知道什么时候就不能用了,其实也有免费的软件可以用,glpk就可以解LP或者MIP的问题,而且还自带一个简单的模型描述语言,不过有时候要描述复杂一点的场景就有点不行了。

 

PULP是用python写的建模描述语言,自带的例子里面就带有column generation的例子,显然是比glpk自带的那个强不少,下面就用一个例子来说明一个简单建模的流程吧。

 

# Import PuLP modeler functions
from pulp import *

# A new LP problem
prob = LpProblem("test1", LpMinimize)

# Variables
# 0 <= x <= 4
x = LpVariable("x", 0, 4)
# -1 <= y <= 1
y = LpVariable("y", -1, 1)
# 0 <= z
z = LpVariable("z", 0)
# Use None for +/- Infinity, i.e. z <= 0 -> LpVariable("z", None, 0)

# Objective
prob += x + 4*y + 9*z, "obj"
# (the name at the end is facultative)

# Constraints
prob += x+y <= 5, "c1"
prob += x+z >= 10, "c2"
prob += -y+z == 7, "c3"
# (the names at the end are facultative)

# Write the problem as an LP file
prob.writeLP("test1.lp")

# Solve the problem using the default solver
prob.solve()
# Use prob.solve(GLPK()) instead to choose GLPK as the solver
# Use GLPK(msg = 0) to suppress GLPK messages
# If GLPK is not in your path and you lack the pulpGLPK module,
# replace GLPK() with GLPK("/path/")
# Where /path/ is the path to glpsol (excluding glpsol itself).
# If you want to use CPLEX, use CPLEX() instead of GLPK().
# If you want to use XPRESS, use XPRESS() instead of GLPK().
# If you want to use COIN, use COIN() instead of GLPK(). In this last case,
# two paths may be provided (one to clp, one to cbc).

# Print the status of the solved LP
print "Status:", LpStatus[prob.status]

# Print the value of the variables at the optimum
for v in prob.variables():
	print v.name, "=", v.varValue

# Print the value of the objective
print "objective=", value(prob.objective)

 

分享到:
评论
2 楼 hankgong 2010-06-23  
我个人是不喜欢matlab,也几乎从来没有用过matlab,虽然matlab有着无数我永远都用不到的库函数。

庞然大物不说,matlab的语法也很过时了。matlab用来描述建模的问题好像不太方便,要变成矩阵的样子。不过现在在也有matlab中可以描述问题的库了,stanford有个cvx可以解LP和一般的凸优化。
1 楼 passionke 2010-06-23  
不错  呵呵 python可以考虑哦
我暑假要参加数学建模了
但是matlab还是有优势些罢 

相关推荐

Global site tag (gtag.js) - Google Analytics