本文整理汇总了Python中gurobipy.Model.reset方法的典型用法代码示例。如果您正苦于以下问题:Python Model.reset方法的具体用法?Python Model.reset怎么用?Python Model.reset使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类gurobipy.Model
的用法示例。
在下文中一共展示了Model.reset方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: BFPBackupNetwork_Continuous
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import reset [as 别名]
#.........这里部分代码省略.........
if TimeLimit != None:
self.model.params.timeLimit = TimeLimit
# Compute optimal solution
self.model.optimize()
# Print solution
if self.model.status == GRB.Status.OPTIMAL:
if LogLevel == 1:
for v in self.model.getVars():
print("%s %g" % (v.varName, v.x))
self.BackupCapacitySolution = self.model.getAttr("x", self.BackupCapacity)
self.BackupRoutesSolution = self.model.getAttr("x", self.bBackupLink)
self.BackupLinksSolution = {}
self.HatBackupCapacity = {}
for link in self.BackupCapacitySolution:
if self.BackupCapacitySolution[link] < 1 and self.BackupCapacitySolution[link] > 0.001:
self.HatBackupCapacity[link] = math.ceil(self.BackupCapacitySolution[link])
else:
self.HatBackupCapacity[link] = math.floor(self.BackupCapacitySolution[link])
if self.HatBackupCapacity[link] > 0:
if len(self.BackupLinksSolution) == 0:
self.BackupLinksSolution = [link]
else:
self.BackupLinksSolution = self.BackupLinksSolution + [link]
else:
print("Optimal value not found!\n")
self.BackupCapacitySolution = []
self.BackupRoutesSolution = {}
self.BackupLinksSolution = {}
return self.BackupCapacitySolution, self.BackupRoutesSolution, self.BackupLinksSolution, self.HatBackupCapacity
def SaveBakupNetwork(self, file_name):
"""Save the optimal backup network to the file ``file_name``."""
data = {
"links": [i for i in self.BackupCapacitySolution],
"capacities": [self.BackupCapacitySolution[i] for i in self.BackupCapacitySolution],
"routes": [i for i in self.BackupRoutesSolution],
"status": [self.BackupRoutesSolution[i] for i in self.BackupRoutesSolution],
}
f = open(file_name, "w")
json.dump(data, f)
f.close()
def LoadBackupNetwork(self, file_name):
"""Load a backup network from the file ``file_name``.
Returns the backup network solution saved in the file.
"""
f = open(file_name, "r")
data = json.load(f)
f.close()
self.BackupCapacitySolution = {}
self.BackupRoutesSolution = {}
self.BackupLinksSolution = {}
links = [i for i in data["links"]]
capacities = [i for i in data["capacities"]]
routes = [i for i in data["routes"]]
status = [i for i in data["status"]]
IndexAux = 0
for i, j in links:
self.BackupCapacitySolution[i, j] = capacities[IndexAux]
IndexAux = IndexAux + 1
self.HatBackupCapacity = {}
for link in self.BackupCapacitySolution:
if self.BackupCapacitySolution[link] < 1 and self.BackupCapacitySolution[link] > 0.001:
self.HatBackupCapacity[link] = math.ceil(self.BackupCapacitySolution[link])
else:
self.HatBackupCapacity[link] = math.floor(self.BackupCapacitySolution[link])
if self.HatBackupCapacity[link] > 0:
if len(self.BackupLinksSolution) == 0:
self.BackupLinksSolution = [link]
else:
self.BackupLinksSolution = self.BackupLinksSolution + [link]
IndexAux = 0
for i, j, s, d in routes:
self.BackupRoutesSolution[i, j, s, d] = status[IndexAux]
IndexAux = IndexAux + 1
return self.BackupCapacitySolution, self.BackupRoutesSolution, self.BackupLinksSolution, self.HatBackupCapacity
def ResetModel(self):
"""
Reset model solution.
"""
self.BackupCapacity = {}
self.bBackupLink = {}
self.z0 = {}
self.z = {}
if self.model:
self.model.reset()
示例2: Backup
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import reset [as 别名]
#.........这里部分代码省略.........
self.__model = Model('Backup')
# Auxiliary variables for SOCP reformulation
U = {}
R = {}
# Create variables
for i,j in self.__links:
self.__BackupCapacity[i,j] = self.__model.addVar(lb=0, obj=1, name='Backup_Capacity[%s,%s]' % (i, j))
self.__model.update()
for i,j in self.__links:
for s,d in self.__links:
self.__bBackupLink[i,j,s,d] = self.__model.addVar(vtype=GRB.BINARY,obj=1,name='Backup_Link[%s,%s,%s,%s]' % (i, j, s, d))
self.__model.update()
for i,j in self.__links:
U[i,j] = self.__model.addVar(obj=1,name='U[%s,%s]' % (i, j))
self.__model.update()
for i,j in self.__links:
for s,d in self.__links:
R[i,j,s,d] = self.__model.addVar(obj=1,name='R[%s,%s,%s,%s]' % (i,j,s,d))
self.__model.update()
self.__model.modelSense = GRB.MINIMIZE
#m.setObjective(quicksum([fixedCosts[p]*open[p] for p in plants]))
self.__model.setObjective(quicksum(self.__BackupCapacity[i,j] for i,j in self.__links))
self.__model.update()
#------------------------------------------------------------------------#
# Constraints definition #
# #
# #
#------------------------------------------------------------------------#
# Link capacity constraints
for i,j in self.__links:
self.__model.addConstr(self.__BackupCapacity[i,j] >= quicksum(self.__mean[s,d]*self.__bBackupLink[i,j,s,d] for (s,d) in self.__links) + U[i,j]*self.__invstd,'[CONST]Link_Cap_%s_%s' % (i, j))
self.__model.update()
# SCOP Reformulation Constraints
for i,j in self.__links:
self.__model.addConstr(quicksum(R[i,j,s,d]*R[i,j,s,d] for (s,d) in self.__links) <= U[i,j]*U[i,j],'[CONST]SCOP1[%s][%s]' % (i, j))
self.__model.update()
# SCOP Reformulation Constraints
for i,j in self.__links:
for s,d in self.__links:
self.__model.addConstr(self.__std[s,d]*self.__bBackupLink[i,j,s,d] == R[i,j,s,d],'[CONST]SCOP2[%s][%s][%s][%s]' % (i, j,s,d))
self.__model.update()
for i in self.__nodes:
for s,d in self.__links:
# Flow conservation constraints
if i == s:
self.__model.addConstr(quicksum(self.__bBackupLink[i,j,s,d] for i,j in self.__links.select(i,'*')) -
quicksum(self.__bBackupLink[j,i,s,d] for j,i in self.__links.select('*',i)) == 1,'Flow1[%s,%s,%s,%s]' % (i,j,s, d))
# Flow conservation constraints
elif i == d:
self.__model.addConstr(quicksum(self.__bBackupLink[i,j,s,d] for i,j in self.__links.select(i,'*')) -
quicksum(self.__bBackupLink[j,i,s,d] for j,i in self.__links.select('*',i)) == -1,'Flow2[%s,%s,%s,%s]' % (i,j,s, d))
# Flow conservation constraints
else:
self.__model.addConstr(quicksum(self.__bBackupLink[i,j,s,d] for i,j in self.__links.select(i,'*')) -
quicksum(self.__bBackupLink[j,i,s,d] for j,i in self.__links.select('*',i)) == 0,'Flow3[%s,%s,%s,%s]' % (i,j,s, d))
self.__model.update()
def optimize(self,MipGap, TimeLimit):
self.__model.write('backup.lp')
if MipGap != None:
self.__model.params.timeLimit = TimeLimit
if TimeLimit != None:
self.__model.params.MIPGap = MipGap
# Compute optimal solution
self.__model.optimize()
# Print solution
if self.__model.status == GRB.Status.OPTIMAL:
solution = self.__model.getAttr('x', self.__BackupCapacity)
for i,j in self.__links:
if solution[i,j] > 0:
print('%s -> %s: %g' % (i, j, solution[i,j]))
else:
print('Optimal value not found!\n')
solution = []
return solution;
def reset(self):
'''
Reset model solution
'''
self.__model.reset()
示例3: SQModel
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import reset [as 别名]
#.........这里部分代码省略.........
def __init__(self,imp_samp,nodes,links,capacity,epsilon,N,backup_link,link_capacity):
'''
Constructor
'''
self.__links = links
self.__nodes = nodes
self.__capacity = capacity
self.__epsilon = epsilon
self.__N = N
self.__loadModel(imp_samp,backup_link,link_capacity)
def __loadModel(self,imp_samp, backup_link,link_capacity):
# Create optimization model
self.__model = Model('Backup')
for i,j in self.__links:
for k in range(self.__N):
self.__z[k,i,j] = self.__model.addVar(lb=0,name='z[%s][%s][%s]' % (k,i,j))
self.__model.update()
for i,j in self.__links:
self.__z0[i,j] = self.__model.addVar(lb=-GRB.INFINITY,name='z0[%s][%s]' %(i,j))
self.__model.update()
for i,j in self.__links:
self.__q[i,j] = self.__model.addVar(lb=-GRB.INFINITY,name='q[%s][%s]' %(i,j))
self.__model.update()
self.__model.modelSense = GRB.MINIMIZE
self.__model.setObjective(quicksum(self.__q[i,j] for i,j in self.__links))
self.__model.update()
#------------------------------------------------------------------------#
# Constraints definition #
# #
# #
#------------------------------------------------------------------------#
# Buffer probability I
for i,j in self.__links:
self.__model.addConstr(self.__z0[i,j] + 1/(self.__N*self.__epsilon)*quicksum(self.__z[k,i,j]*imp_samp[k] for (k) in range(self.__N)) <= self.__q[i,j],'[CONST]Buffer_Prob_I[%s][%s]'%(i,j))
self.__model.update()
# Link capacity constraints
for i,j in self.__links:
for k in range(self.__N):
self.__model.addConstr((quicksum(backup_link[i,j,s,d]*self.__capacity[k,s,d] for s,d in self.__links) - link_capacity[i,j] - self.__z0[i,j]) <= self.__z[k,i,j],'[CONST]Buffer_Prob_II[%s][%s][%s]' % (k,i,j))
self.__model.update()
# Link capacity constraints
for i,j in self.__links:
for k in range(self.__N):
self.__model.addConstr(self.__z[k,i,j] >= 0,'[CONST]Buffer_Prob_III[%s][%s][%s]' % (k,i,j))
self.__model.update()
def optimize(self,MipGap, TimeLimit, LogLevel = None):
self.__model.write('quantile.lp')
if MipGap != None:
self.__model.params.MIPGap = MipGap
if TimeLimit != None:
self.__model.params.timeLimit = TimeLimit
# Compute optimal solution
self.__model.optimize()
# Print solution
if self.__model.status == GRB.Status.OPTIMAL:
#SuperQuantileSolution = self.__model.getAttr('x', self.__z0)
SuperQuantileSolution = {}
OptimalZnot = {}
for i,j in self.__links:
name='q[%s][%s]'%(i,j)
v = self.__model.getVarByName(name)
SuperQuantileSolution[i,j]=v.x
name='z0[%s][%s]'%(i,j)
v = self.__model.getVarByName(name)
OptimalZnot[i,j]=v.x
if LogLevel == 1:
for v in self.__model.getVars():
print('%s %g' % (v.varName, v.x))
else:
print('Optimal value not found!\n')
SuperQuantileSolution = {}
OptimalZnot={}
return SuperQuantileSolution, OptimalZnot
def reset(self):
'''
Reset model solution
'''
self.__model.reset()
示例4: _optimize_gurobi
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import reset [as 别名]
#.........这里部分代码省略.........
#Set objective to quadratic program
if quadratic_component is not None:
if not hasattr(quadratic_component, 'todok'):
raise Exception('quadratic component must be a scipy.sparse type array')
quadratic_objective = QuadExpr()
for (index_0, index_1), the_value in quadratic_component.todok().items():
quadratic_objective.addTerms(the_value,
variable_list[index_0],
variable_list[index_1])
lp.setObjective(quadratic_objective, sense=objective_sense)
#Constraints are based on mass balance
#Construct the lin expression lists and then add
#TODO: Speed this up as it takes about .18 seconds
#HERE
for the_metabolite in cobra_model.metabolites:
constraint_coefficients = []
constraint_variables = []
for the_reaction in the_metabolite._reaction:
constraint_coefficients.append(the_reaction._metabolites[the_metabolite])
constraint_variables.append(reaction_to_variable[the_reaction])
#Add the metabolite to the problem
lp.addConstr(LinExpr(constraint_coefficients, constraint_variables),
sense_dict[the_metabolite._constraint_sense.upper()],
the_metabolite._bound,
the_metabolite.id)
else:
#When reusing the basis only assume that the objective coefficients or bounds can change
if copy_problem:
lp = the_problem.copy()
else:
lp = the_problem
if not reuse_basis:
lp.reset()
for the_variable, the_reaction in zip(lp.getVars(),
cobra_model.reactions):
the_variable.lb = float(the_reaction.lower_bound)
the_variable.ub = float(the_reaction.upper_bound)
the_variable.obj = float(objective_sense*the_reaction.objective_coefficient)
if the_problem == 'setup':
return lp
if print_solver_time:
start_time = time()
lp.update()
lp.setParam("FeasibilityTol", tolerance_feasibility)
lp.setParam("OptimalityTol", tolerance_optimality)
if tolerance_barrier:
lp.setParam("BarConvTol", tolerance_barrier)
if quad_precision:
lp.setParam("Quad", 1)
lp.setParam("Method", lp_method)
#Different methods to try if lp_method fails
the_methods = [0, 2, 1]
if lp_method in the_methods:
the_methods.remove(lp_method)
if not isinstance(the_problem, Model):
lp.optimize()
if lp.status in status_dict:
status = status_dict[lp.status]
else:
status = 'failed'
if status != 'optimal':
示例5: PathBackup
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import reset [as 别名]
#.........这里部分代码省略.........
def __loadModel(self):
# Create optimization model
self.__model = Model('PathBackup')
# Auxiliary variables for SOCP reformulation
U = {}
R = {}
# Create variables
for i,j in self.__links:
self.__BackupCapacity[i,j] = self.__model.addVar(lb=0, obj=1, name='Backup_Capacity[%s,%s]' % (i, j))
self.__model.update()
for p in self.__paths:
#LP Relaxation
#self.__bPath[self.__paths.index(p)] = self.__model.addVar(lb=0,obj=1,name='Backup_Path[%s]' % (self.__paths.index(p)))
self.__bPath[self.__paths.index(p)] = self.__model.addVar(vtype=GRB.BINARY,obj=1,name='Backup_Path[%s]' % (self.__paths.index(p)))
self.__model.update()
for i,j in self.__links:
U[i,j] = self.__model.addVar(obj=1,name='U[%s,%s]' % (i, j))
self.__model.update()
for i,j in self.__links:
for s,d in self.__links:
R[i,j,s,d] = self.__model.addVar(obj=1,name='R[%s,%s,%s,%s]' % (i,j,s,d))
self.__model.update()
self.__model.modelSense = GRB.MINIMIZE
self.__model.setObjective(quicksum(self.__BackupCapacity[i,j] for i,j in self.__links))
self.__model.update()
#------------------------------------------------------------------------#
# Constraints definition #
# #
# #
#------------------------------------------------------------------------#
# Link capacity constraints
for i,j in self.__links:
self.__model.addConstr(self.__BackupCapacity[i,j] >= quicksum(self.__mean[s,d]*quicksum(self.__bPath[self.__paths.index(p)] for p in self.__Pij[i,j,s,d]) for s,d in self.__links) + U[i,j]*self.__invstd,'[CONST]Link_Cap[%s][%s]' % (i, j))
self.__model.update()
# SCOP Reformulation Constraints
for i,j in self.__links:
self.__model.addConstr(quicksum(R[i,j,s,d]*R[i,j,s,d] for s,d in self.__links) <= U[i,j]*U[i,j],'[CONST]SCOP1[%s][%s]' % (i, j))
self.__model.update()
# SCOP Reformulation Constraints
for i,j in self.__links:
for s,d in self.__links:
self.__model.addConstr(self.__std[s,d]*quicksum(self.__bPath[self.__paths.index(p)] for p in self.__Pij[i,j,s,d]) == R[i,j,s,d],'[CONST]SCOP2[%s][%s][%s][%s]' % (i,j,s,d))
self.__model.update()
# Unique path
for s,d in self.__links:
self.__model.addConstr(quicksum(self.__bPath[self.__paths.index(p)] for p in self.__Psd[s,d]) == 1,'UniquePath[%s,%s]' % (s, d))
self.__model.update()
def optimize(self,MipGap,TimeLimit):
self.__model.write('pathbackup.lp')
if TimeLimit != None:
self.__model.params.timeLimit = TimeLimit
if MipGap != None:
self.__model.params.MIPGap=MipGap
# Compute optimal solution
self.__model.optimize()
# Print solution
if self.__model.status == GRB.Status.OPTIMAL:
solution = self.__model.getAttr('x', self.__bPath)
for p in self.__paths:
if solution[self.__paths.index(p)] > 0.001:
print('Path[%s] = %s = %s' % (self.__paths.index(p),p,solution[self.__paths.index(p)]))
solution = self.__model.getAttr('x', self.__BackupCapacity)
for i,j in self.__links:
if solution[i,j] > 0:
print('%s -> %s: %g' % (i, j, solution[i,j]))
else:
print('Optimal value not found!\n')
solution = self.__model.getAttr('x', self.__BackupCapacity)
for i,j in self.__links:
if solution[i,j] > 0:
print('%s -> %s: %g' % (i, j, solution[i,j]))
#solution = []
return solution;
def reset(self):
'''
Reset model solution
'''
self.__model.reset()