()
git_Python-Gurobi学习资料
Get constraints in matrix format from gurobipy
Sensitivity Analysis with Gurobi
1.安装
- 注册
选择academic - license
有命令行,在terminal下直接运行,运行后自动下载证书 - APP
用canda自动安装,pip总安装失败
2. Start
- 看官方document,有相关例子,具体放在Mendelay里(2个)
import gurobipy as bi
m=bi.Model('model name')
#添加变量
m.addVars(变量下标1,变量下标2,...,lb=,ub=,vtype=bi.GRB.CONTINUS,'name')
# or
for i in 下标1:
for j in 下标2:
for ...:
m.addVar()
#更新环境
m.update()
#添加约束,基本将变量表述出来就行
m.addConstrs(fucntion for variable in ...)
#or
m.addConstr()
#添加目标值
m.setObjective(objective function,bi.GRB.MINIMIZE)
#优化
m.optimize()
在表达可能涉及到
bi.quicksum()
tuplelist.select(j,'*')
3. Model infeasible
infeasible analysis1
infeasible analysis - officail
document里有写:workforce1,2,3。
自己在建模过程中出现这个问题是因为出现conflict constraints.(因此,在添加约束和变量的时候最好定义好name,否则conflict cosntraints 会以‘R1’..,出现)
在查找conflict cosntraints的时候,应先用IIS判别模型是否infeasible
两种方式处理conflict constraints
- Remove
removed=[]
while True:
m.computeIIS()
print('\nthe following constraint cannot be satisfies:')
for c in m.getConstrs():
print('%s' % c.constrName)
removed.append(str(c.constrName))
m.remove(c)
break
print ''
m.optimize()
status=m.status
if status ==bi.GRB.Status.UNBOUNDED:
print 'unbounded'
exit(0)
if status==bi.GRB.Status.OPTIMAL:
break
if status==bi.GRB.Status.INF_OR_UNBD and status!=bi.GRB.Status.INFEASIBLE:
print ('was stopped with %d'% status)
exit(0)
print ('\nthe constraint removed:')
print removed
-
Relax
-
解决
查找冲突变量按定义顺序查找
st1
st2
st3
...
若st1与后面的任意变量冲突,输出st1。总之,显示最前的变量。
5. 输出模型结果
if m.status == bi.GRB.Status.OPTIMAL:
solution_cache = m.getAttr('x', x)
solution_deliver = m.getAttr('x', q)
#print solution_cache
#print solution_deliver
for h in range(num_file):
for i in range(num_sbs):
print('\nOptimal file %d for node %d:' % (h, i))
for j, k in bi.tuplelist(depth_first_search(i, num_sbs, edgeWeight)):
if solution_cache[i, h] > 0.0:
print ('%d cache %d: %f' % (i, h, solution_cache[i, h]))
if solution_deliver[h, i, j, k] > 0.0:
print('%d -> %d: %f' % (j, k, solution_deliver[h, i, j, k]))
if solution_cache[k, h] > 0.0:
print ('%d cache %d: %f' % (i, h, solution_cache[i, h]))
else:
print m.printStats()
主要为m.getAttr(变量)
网友评论