当前位置:   article > 正文

Python调用Gurobi基本操作_gurobi python

gurobi python

接上篇学会了如何用python调用gurobipy之后,这篇总结一些学到的基本操作。

tuplelist、tupledict、multidict、创建list、

1.tuplelist方法:

tuplelist是Python list的扩展对象,使用tuplelist()不能忘记from gurobipy import *,tuplelist增加了快速筛选select功能,比传统的if...else...筛选速度快。

  1. from gurobipy import *
  2. import time
  3. T1 = time.time()
  4. Cities=[("A","B"),("A","C"),("B","C"),("B","D"),("C","D")]
  5. Routes=tuplelist(Cities)
  6. print(Routes.select("A","*"))
  7. T2 =time.time()
  8. print('程序运行时间:%s毫秒' % ((T2 - T1)*1000))

tuplelist运行结果:

  1. C:\Users\xzr\.conda\envs\py310gurobi\python.exe F:\PycharmProjects\workspace\untitled\jizulunban\caogao.py
  2. <gurobi.tuplelist (2 tuples, 2 values each):
  3. ( A , B )
  4. ( A , C )
  5. >
  6. 程序运行时间:1.9958019256591797毫秒
  7. 进程已结束,退出代码0

for...else...方法:

  1. from gurobipy import *
  2. import time
  3. T1 = time.time()
  4. Cities=[("A","B"),("A","C"),("B","C"),("B","D"),("C","D")]
  5. Result=[]
  6. for i,j in Cities:
  7. if i=="A":
  8. Result.append((i,j))
  9. print(Result)
  10. T2 =time.time()
  11. print('程序运行时间:%s毫秒' % ((T2 - T1)*1000))

for...else...运行结果:

  1. C:\Users\xzr\.conda\envs\py310gurobi\python.exe F:\PycharmProjects\workspace\untitled\jizulunban\caogao.py
  2. [('A', 'B'), ('A', 'C')]
  3. 程序运行时间:0.0毫秒
  4. 进程已结束,退出代码0

尴尬了,竟然是for...else...的运行速度更快,原因是数据量太少了体现不出效果。

2.tupledict方法:

tupledict是Python Dictionary的扩展对象,键值是tuple(元组),可以使用select、sum、prob函数。用于变量和约束。后面有详细介绍。

3.multidict方法:

multidict()创建tuplelist和tupledict的便捷方法。代码示例:

  1. from gurobipy import *
  2. import time
  3. # T1 = time.time()
  4. cities,supply,demand = multidict({
  5. "A":[100,20],
  6. "B":[150,50],
  7. "C":[20,300],
  8. "D":[10,200]})
  9. print(cities)
  10. print(supply)
  11. print(demand)
  12. # T2 =time.time()

运行结果:

  1. C:\Users\xzr\.conda\envs\py310gurobi\python.exe F:\PycharmProjects\workspace\untitled\jizulunban\caogao.py
  2. ['A', 'B', 'C', 'D']
  3. {'A': 100, 'B': 150, 'C': 20, 'D': 10}
  4. {'A': 20, 'B': 50, 'C': 300, 'D': 200}
  5. 进程已结束,退出代码0

运行结果第一行是list,第二三行是dictionary。

4.创建list:

python有多种创建list的方法:

  1. a=[]
  2. a.append("A")
b=[i**2 for i in range(6)] #[0,1,4,9,16,25]
c=[(i,j)for j in range(4) for i in range(j)] #[(0,1),(0,2),(1,2),(0,3),(1,3),(2,3)]
d=[i for i in range(10) if i not in b]  #[2,3,5,6,7,8]
  1. Pairs=[]
  2. for j in range(4):
  3. for i in range(j):
  4. Pairs.append((i,j))

对于求和,Python的Generator(生成器):

SumSquares=sum(i**2 for i in range(6)) #55

Gurobi中采用quicksum,效率更高:

obj=quicksum(cost[i,j]*x[i,j] for i,j in arcs)

5.tupledict建模示例

tupledict(Gurobi变量一般都是tupledict类型)有sum函数

  1. from gurobipy import *
  2. import time
  3. # T1 = time.time()
  4. m=Model()
  5. x=m.addVars(3,4,vtype=GRB.BINARY,name="x")
  6. m.addConstrs((x.sum(i,"*")<=1 for i in range(3)),name="con")
  7. m.update()
  8. m.write("test.lp")
  9. # T2 =time.time()
  10. # print('程序运行时间:%s毫秒' % ((T2 - T1)*1000))

运行后,打开“test.lp”文件查看写入的模型

  1. \ LP format - for model browsing. Use MPS format to capture full model detail.
  2. Minimize
  3. Subject To
  4. con[0]: x[0,0] + x[0,1] + x[0,2] + x[0,3] <= 1
  5. con[1]: x[1,0] + x[1,1] + x[1,2] + x[1,3] <= 1
  6. con[2]: x[2,0] + x[2,1] + x[2,2] + x[2,3] <= 1
  7. Bounds
  8. Binaries
  9. x[0,0] x[0,1] x[0,2] x[0,3] x[1,0] x[1,1] x[1,2] x[1,3] x[2,0] x[2,1]
  10. x[2,2] x[2,3]
  11. End

太妙了太妙了

tupledict(Gurobi变量一般都是tupledict类型)还有prob函数,用于变量和系数相乘后累加

以下表达式等效

obj=quicksum(cost[i,j]*x[i,j] for i,j in arcs)
obj=x.prod(cost)

建模建议,尽量采用稀疏方式,采用tuplelists筛选和指定合适的下标组合关系,基于这些组合关系建立变量和数据字典,利用tuplelist.select()以及tupledict.select(),tupledict.sum(),tupledict.prob()来对下标进行组合处理。

 

  

 

 

 

 Gurobi建模举例1

 ​​​​​​​

  1. from gurobipy import *
  2. # T1 = time.time()
  3. try:
  4. #Create a new model
  5. m=Model("mip1")
  6. #Create variables
  7. x=m.addVar(vtype=GRB.BINARY,name="x")
  8. y=m.addVar(vtype=GRB.BINARY,name="y")
  9. z=m.addVar(vtype=GRB.BINARY,name="z")
  10. #Set objective
  11. m.setObjective(x+y+2*z,GRB.MAXIMIZE)
  12. #Add constraint:x+2y+3z<=4
  13. m.addConstr(x+2*y+3*z<=4,"c0")
  14. #Add constraint:x+y>=1
  15. m.addConstr(x+y>=1,"c1")
  16. m.optimize()
  17. for v in m.getVars(): #getVars获取所有变量
  18. print("%s %g" % (v.varName,v.x)) #(v.varName,v.x)是(变量名字,优化结果)
  19. print("Obj: %g" % m.objVal)
  20. except GurobiError as e:
  21. print("Error code" + str(e.errno)+":"+str(e))
  22. except AttributeError:
  23. print("Encountered an attribute error")
  24. # T2 =time.time()
  25. # print('程序运行时间:%s毫秒' % ((T2 - T1)*1000))

 运行结果

  1. C:\Users\xzr\.conda\envs\py310gurobi\python.exe F:\PycharmProjects\workspace\untitled\jizulunban\caogao.py
  2. Gurobi Optimizer version 10.0.0 build v10.0.0rc2 (win64)
  3. CPU model: Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz, instruction set [SSE2|AVX|AVX2]
  4. Thread count: 2 physical cores, 4 logical processors, using up to 4 threads
  5. Optimize a model with 2 rows, 3 columns and 5 nonzeros
  6. Model fingerprint: 0x98886187
  7. Variable types: 0 continuous, 3 integer (3 binary)
  8. Coefficient statistics:
  9. Matrix range [1e+00, 3e+00]
  10. Objective range [1e+00, 2e+00]
  11. Bounds range [1e+00, 1e+00]
  12. RHS range [1e+00, 4e+00]
  13. Found heuristic solution: objective 2.0000000
  14. Presolve removed 2 rows and 3 columns
  15. Presolve time: 0.02s
  16. Presolve: All rows and columns removed
  17. Explored 0 nodes (0 simplex iterations) in 0.03 seconds (0.00 work units)
  18. Thread count was 1 (of 4 available processors)
  19. Solution count 2: 3 2
  20. Optimal solution found (tolerance 1.00e-04)
  21. Best objective 3.000000000000e+00, best bound 3.000000000000e+00, gap 0.0000%
  22. x 1
  23. y 0
  24. z 1
  25. Obj: 3
  26. 进程已结束,退出代码0

Gurobi建模举例2

 

 

  1. from gurobipy import *
  2. categories,minNutrition,maxNutrition=multidict({
  3. "calories":[1800,2200],
  4. "protein":[91,GRB.INFINITY],
  5. "fat":[0,65],
  6. "sodium":[0,1779]
  7. })
  8. foods,cost=multidict({
  9. "hamburger":2.49,
  10. "chicken":2.89,
  11. "hot dog":1.50,
  12. "fries":1.89,
  13. "macaroni":2.09,
  14. "pizza":1.99,
  15. "salad":2.49,
  16. "milk":0.89,
  17. "ice cream":1.59
  18. })
  19. #Nutrition values for the foods
  20. nutritionValues={
  21. ("hamburger","calories"):410,
  22. ("hamburger","protein"):24,
  23. ("hamburger","fat"):26,
  24. ("hamburger","sodium"):730,
  25. ("chicken","calories"):420,
  26. ("chicken", "protein"):32,
  27. ("chicken", "fat"):10,
  28. ("chicken", "sodium"):1190,
  29. ("hot dog","calories"):560,
  30. ("hot dog", "protein"):20,
  31. ("hot dog", "fat"):32,
  32. ("hot dog", "sodium"):1800,
  33. ("fries","calories"):380,
  34. ("fries", "protein"):4,
  35. ("fries", "fat"):19,
  36. ("fries", "sodium"):720,
  37. ("macaroni", "calories"): 320,
  38. ("macaroni", "protein"): 12,
  39. ("macaroni", "fat"): 10,
  40. ("macaroni", "sodium"): 930,
  41. ("pizza", "calories"): 320,
  42. ("pizza", "protein"): 15,
  43. ("pizza", "fat"): 12,
  44. ("pizza", "sodium"): 820,
  45. ("salad", "calories"): 320,
  46. ("salad", "protein"): 31,
  47. ("salad", "fat"): 12,
  48. ("salad", "sodium"): 1230,
  49. ("milk", "calories"): 100,
  50. ("milk", "protein"): 8,
  51. ("milk", "fat"): 2.5,
  52. ("milk", "sodium"): 125,
  53. ("ice cream", "calories"): 330,
  54. ("ice cream", "protein"): 8,
  55. ("ice cream", "fat"): 10,
  56. ("ice cream", "sodium"): 180
  57. }
  58. #Model
  59. m=Model("diet")
  60. #Create decision variables for the foods to buy
  61. buy=m.addVars(foods,name="buy")
  62. #也可以是:
  63. # buy=[]
  64. # for f in foods:
  65. # buy[f]=m.addVar(name=f)
  66. #目标函数是最小化cost
  67. m.setObjective(buy.prod(cost),GRB.MINIMIZE)
  68. #如果使用循环结构,应该是:
  69. # m.setObjective(sum(buy[f]*cost[f] for f in foods),GRB.MINIMIZE)
  70. #Nutrition constraints
  71. m.addConstrs(
  72. (quicksum(nutritionValues[f,c]*buy[f] for f in foods)
  73. == [minNutrition[c],maxNutrition[c]]
  74. for c in categories),"_")
  75. #如果使用循环结构,应该是:
  76. # for c in categories:
  77. # m.addRange(
  78. # sum(nutritionValues[f,c] * buy[f] for f in foods),minNutrition[c],maxNutrition[c],c)
  79. # )
  80. def printSolution():
  81. if m.status == GRB.Status.OPTIMAL:
  82. print("\nCost:%g" % m.objval)
  83. print("\nBuy:")
  84. buyx=m.getAttr("x",buy)
  85. for f in foods:
  86. if buy[f].x>0.0001:
  87. print("%s %g" % (f,buyx[f]))
  88. else:
  89. print("No solution")
  90. #solve
  91. m.optimize()
  92. printSolution()
  93. # T1 = time.time()
  94. # T2 =time.time()
  95. # print('程序运行时间:%s毫秒' % ((T2 - T1)*1000))

 运行结果

  1. C:\Users\xzr\.conda\envs\py310gurobi\python.exe F:\PycharmProjects\workspace\untitled\jizulunban\caogao.py
  2. Gurobi Optimizer version 10.0.0 build v10.0.0rc2 (win64)
  3. CPU model: Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz, instruction set [SSE2|AVX|AVX2]
  4. Thread count: 2 physical cores, 4 logical processors, using up to 4 threads
  5. Optimize a model with 4 rows, 12 columns and 39 nonzeros
  6. Model fingerprint: 0xed649f3c
  7. Coefficient statistics:
  8. Matrix range [1e+00, 2e+03]
  9. Objective range [9e-01, 3e+00]
  10. Bounds range [7e+01, 2e+03]
  11. RHS range [7e+01, 2e+03]
  12. Presolve removed 0 rows and 2 columns
  13. Presolve time: 0.01s
  14. Presolved: 4 rows, 10 columns, 37 nonzeros
  15. Iteration Objective Primal Inf. Dual Inf. Time
  16. 0 0.0000000e+00 1.472500e+02 0.000000e+00 0s
  17. 4 1.1828861e+01 0.000000e+00 0.000000e+00 0s
  18. Solved in 4 iterations and 0.03 seconds (0.00 work units)
  19. Optimal objective 1.182886111e+01

 

 —————————————————————————————————————————

注意:

若出现众多warning,删去warning给的路径下的带“~”的文件

若出现ERROR: Could not find a version that satisfies the requirement time (from versions: none),是找不到适应现有python版本的包

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/645057
推荐阅读
相关标签
  

闽ICP备14008679号