当前位置:编程学习 > 网站相关 >>

使用Python语言替代AMPL建模流程说明

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

Python代码
  1. # Import PuLP modeler functions   
  2. from pulp import *   
  3.   
  4. # A new LP problem   
  5. prob = LpProblem("test1", LpMinimize)   
  6.   
  7. # Variables   
  8. # 0 <= x <= 4   
  9. x = LpVariable("x", 0, 4)   
  10. # -1 <= y <= 1   
  11. y = LpVariable("y", -1, 1)   
  12. # 0 <= z   
  13. z = LpVariable("z", 0)   
  14. # Use None for  /- Infinity, i.e. z <= 0 -> LpVariable("z", None, 0)   
  15.   
  16. # Objective   
  17. prob  = x   4*y   9*z, "obj"  
  18. # (the name at the end is facultative)   
  19.   
  20. # Constraints   
  21. prob  = x y <= 5, "c1"  
  22. prob  = x z >= 10, "c2"  
  23. prob  = -y z == 7, "c3"  
  24. # (the names at the end are facultative)   
  25.   
  26. # Write the problem as an LP file   
  27. prob.writeLP("test1.lp")   
  28.   
  29. # Solve the problem using the default solver   
  30. prob.solve()   
  31. # Use prob.solve(GLPK()) instead to choose GLPK as the solver   
  32. # Use GLPK(msg = 0) to suppress GLPK messages   
  33. # If GLPK is not in your path and you lack the pulpGLPK module,   
  34. # replace GLPK() with GLPK("/path/")   
  35. # Where /path/ is the path to glpsol (excluding glpsol itself).   
  36. # If you want to use CPLEX, use CPLEX() instead of GLPK().   
  37. # If you want to use XPRESS, use XPRESS() instead of GLPK().   
  38. # If you want to use COIN, use COIN() instead of GLPK(). In this last case,   
  39. # two paths may be provided (one to clp, one to cbc).   
  40.   
  41. # Print the status of the solved LP   
  42. print "Status:", LpStatus[prob.status]   
  43.   
  44. # Print the value of the variables at the optimum   
  45. for v in prob.variables():   
  46.     print v.name, "=", v.varValue   
  47.   
  48. # Print the value of the objective   
  49. print "objective=", value(prob.objective) 
补充:Web开发 , Python ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,