sensitivity.py


sensitivity.py


#!/usr/bin/env python3.7 # Copyright 2021, 狗万app足彩Gurobi Optimization, LLC #一个简单的敏感性分析示例,从文件中读取一个MIP模型#并解决它。然后使用场景特征分析影响# w.r.t.,即每个二元变量的目标函数,如果它被设置为# 1-X,其中X是其在最优解决方案中的值。# #使用:# sensitivity.py  # import sys import gurobipy as gp from gurobipy import GRB #可以考虑的最大场景数max场景= 100 if len(sys.argv) < 2: print('Usage: sensitivity.py filename') sys.exit(0) # Read model model = gp. Read (sys.argv[1]) if model。IsMIP == 0: print('Model is not a MIP') sys.exit(0) #解决模型Model .optimize() if模型。地位! =伽马线暴。优化:打印('优化结束与状态%d' % model.status) sys.exit(0) #存储最优解决方案origObjVal = model。ObjVal for v in model. getvars (): v. _origx = v. x场景= 0 #计算模型中不固定的二进制变量的数量。对于每一个,我们创建一个#场景。for v in model.getVars(): if (v.b.b == 0.0 and v.b.b == 1.0 and v.b.b == 1.0 and v.b.b type in (GRB. exe);BINARY, GRB.INTEGER)):场景+= 1如果场景>= maxscenario: break #设置模型中场景的数量。numscenario = scenario scenario = 0 print('### # construct multi-scenario model with %d scenario ' % scenario) #通过迭代模型中不固定的二进制#变量来创建一个(单个)场景模型,并为每个这些变量创建一个场景#通过将变量固定为1-X,在这里,X是它的值在计算的#最优解的v在model.getVars(): if (v. lb == 0.0和v. ub == 1.0和v. vtype在(GRB。BINARY, GRB.INTEGER) and scenarios < maxScenarios): # Set ScenarioNumber parameter to select the corresponding scenario # for adjustments model.params.ScenarioNumber = scenarios # Set variable to 1-X, where X is its value in the optimal solution if v._origX < 0.5: v.ScenNLB = 1.0 else: v.ScenNUB = 0.0 scenarios += 1 else: # Add MIP start for all other variables using the optimal solution # of the base model v.Start = v._origX # Solve multi-scenario model model.optimize() # In case we solved the scenario model to optimality capture the # sensitivity information if model.status == GRB.OPTIMAL: modelSense = model.ModelSense scenarios = 0 # Capture sensitivity information from each scenario for v in model.getVars(): if (v.LB == 0.0 and v.UB == 1.0 and v.VType in (GRB.BINARY, GRB.INTEGER)): # Set scenario parameter to collect the objective value of the # corresponding scenario model.params.ScenarioNumber = scenarios # Collect objective value and bound for the scenario scenarioObjVal = model.ScenNObjVal scenarioObjBound = model.ScenNObjBound # Check if we found a feasible solution for this scenario if scenarioObjVal >= modelSense * GRB.INFINITY: # Check if the scenario is infeasible if scenarioObjBound >= modelSense * GRB.INFINITY: print('Objective sensitivity for variable %s is infeasible' % v.VarName) else: print('Objective sensitivity for variable %s is unknown (no solution available)' % v.VarName) else: # Scenario is feasible and a solution is available print('Objective sensitivity for variable %s is %g' % (v.VarName, modelSense * (scenarioObjVal - origObjVal))) scenarios += 1 if scenarios >= maxScenarios: break