本文整理汇总了Python中gurobipy.Model.setParam方法的典型用法代码示例。如果您正苦于以下问题:Python Model.setParam方法的具体用法?Python Model.setParam怎么用?Python Model.setParam使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类gurobipy.Model
的用法示例。
在下文中一共展示了Model.setParam方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _initialize_model
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setParam [as 别名]
def _initialize_model(self):
problem = Model()
problem.setParam('OutputFlag', False)
# edges from source to reviewers, capacity controls maximum reviewer load
self._source_vars = problem.addVars(self.numrev, vtype=GRB.CONTINUOUS, lb=0.0,
ub=self.ability, name='reviewers')
# edges from papers to sink, capacity controls a number of reviewers per paper
self._sink_vars = problem.addVars(self.numpapers, vtype=GRB.CONTINUOUS, lb=0.0,
ub=self.demand, name='papers')
# edges between reviewers and papers. Initially capacities are set to 0 (no edge is added in the network)
self._mix_vars = problem.addVars(self.numrev, self.numpapers, vtype=GRB.CONTINUOUS,
lb=0.0, ub=0.0, name='assignment')
problem.update()
# flow balance equations for reviewers' nodes
self._balance_reviewers = problem.addConstrs((self._source_vars[i] == self._mix_vars.sum(i, '*')
for i in range(self.numrev)))
# flow balance equations for papers' nodes
self._balance_papers = problem.addConstrs((self._sink_vars[i] == self._mix_vars.sum('*', i)
for i in range(self.numpapers)))
problem.update()
self._problem = problem
示例2: ilp
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setParam [as 别名]
def ilp(costMatrix):
#Invalid_Connections : -1
if costMatrix.shape==(0,0):
return []
dist_mat=numpy.copy(costMatrix)
dist_mat[costMatrix==-1]=10e10
size_x = dist_mat.shape[0]
size_y = dist_mat.shape[1]
size_min = int(numpy.amin([size_x,size_y]))
from gurobipy import Model, quicksum, GRB
m=Model("mip1")
COS,VAR={},{}
for i in range(size_x):
x_cos, x_var = [],[]
for j in range(size_y):
COS[i,j]=dist_mat[i,j]
VAR[i,j]=m.addVar(vtype='B',name="["+str(i)+","+str(j)+"]")
m.update()
# Set objective
m.setObjective( quicksum(\
COS[x,y]*VAR[x,y]
for x in range(size_x) \
for y in range(size_y) \
),GRB.MINIMIZE)
# Constrains HORIZONTAL
for i in range(size_x):
m.addConstr( quicksum\
(VAR[i,y] for y in range(size_y)) <= 1)
# Constrains VERTICAL
for i in range(size_y):
m.addConstr( quicksum\
(VAR[x,i] for x in range(size_x)) <= 1)
m.addConstr(quicksum(\
VAR[x,y] for x in range(size_x) for y in range(size_y)) == int(size_min))
m.setParam("OutputFlag",False)
m.optimize()
res=numpy.zeros(dist_mat.shape,dtype=bool)
for i in range(size_x):
for j in range(size_y):
res[i,j]=VAR[i,j].x
binMatrix = numpy.zeros( costMatrix.shape,dtype=bool )
binMatrix[res==1]=1
binMatrix[costMatrix==-1]=0
return binMatrix
示例3: def_PL
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setParam [as 别名]
def def_PL(self):
"""
Definie le PL, variables/contraintes/objectifs
"""
model = Model("MR")
self.set_vars(model)
self.set_constraints(model)
self.set_objectif(model)
model.setParam("OutputFlag", False)
return model
示例4: solve
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setParam [as 别名]
def solve(budget, buses, lines, u, c, b, S, D):
m = Model('inhibit')
w, v, y = {}, {}, {}
for i in buses:
w[i] = m.addVar(vtype=GRB.BINARY, name="w_%s" % i)
for i, j in lines:
v[i, j] = m.addVar(vtype=GRB.BINARY, name='v_%s_%s' % (i, j))
y[i, j] = m.addVar(vtype=GRB.BINARY, name='y_%s_%s' % (i, j))
m.update()
for i, j in lines:
m.addConstr(w[i]-w[j] <= v[i, j] + y[i, j], 'balance1_%s_%s' % (i, j))
m.addConstr(w[j]-w[i] <= v[i, j] + y[i, j], 'balance2_%s_%s' % (i, j))
m.addConstr(quicksum(c[i, j]*y[i, j] for i, j in lines) <= budget, 'budget')
m.setObjective(quicksum(u[i, j]*v[i, j] for i, j in lines) +
quicksum(b[i]*(1-w[i]) for i in S) -
quicksum(b[i]*w[i] for i in D))
m.setParam('OutputFlag', 0)
m.optimize()
m.write('gurobi.lp')
return w, v, y, m
示例5: Model
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setParam [as 别名]
#!/usr/bin/env python
# This is the GAP per Wolsey, pg 182, using Lagrangian Relaxation
from gurobipy import GRB, Model
model = Model('GAP per Wolsey with Lagrangian Relaxation')
model.modelSense = GRB.MAXIMIZE
model.setParam('OutputFlag', False) # turns off solver chatter
b = [15, 15, 15]
c = [
[ 6, 10, 1],
[12, 12, 5],
[15, 4, 3],
[10, 3, 9],
[ 8, 9, 5]
]
a = [
[ 5, 7, 2],
[14, 8, 7],
[10, 6, 12],
[ 8, 4, 15],
[ 6, 12, 5]
]
# x[i][j] = 1 if i is assigned to j
x = []
for i in range(len(c)):
x_i = []
for j in c[i]:
示例6: run_algorithm
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setParam [as 别名]
def run_algorithm(self):
old_M = self.M
old_items = [i.copy() for i in self.items]
map_name_to_old_item = dict()
for i in old_items:
map_name_to_old_item[i.name] = i
self.scale_items_by_cost()
from gurobipy import Model, GRB
model = Model("NP-Hard")
print("Setting Model Parameters")
# set timeout
model.setParam('TimeLimit', 1600)
model.setParam('MIPFocus', 3)
model.setParam('PrePasses', 1)
model.setParam('Heuristics', 0.01)
model.setParam('Method', 0)
map_name_to_item = dict()
map_name_to_cost = dict()
map_name_to_weight = dict()
map_name_to_profit = dict()
map_class_to_name = dict()
item_names = list()
print("Preprocessing data for model...")
for item in self.items:
item_names.append(item.name)
map_name_to_item[item.name] = item
map_name_to_cost[item.name] = item.cost
map_name_to_weight[item.name] = item.weight
map_name_to_profit[item.name] = item.profit
if item.classNumber not in map_class_to_name:
map_class_to_name[item.classNumber] = list()
map_class_to_name[item.classNumber].append(item.name)
class_numbers = list(map_class_to_name.keys())
print("Setting model variables...")
# binary variables =1, if use>0
items = model.addVars(item_names, vtype=GRB.BINARY, name="items")
classes = model.addVars(class_numbers, vtype=GRB.BINARY, name="class numbers")
print("Setting model objective...")
# maximize profit
objective = items.prod(map_name_to_profit)
model.setObjective(objective, GRB.MAXIMIZE)
# constraints
print("Setting model constraints")
model.addConstr(items.prod(map_name_to_weight) <= self.P,"weight capacity")
model.addConstr(items.prod(map_name_to_cost) <= self.M,"cost capacity")
# if any item from a class is chosen, that class variable has to be a binary of 1
for num in class_numbers:
model.addGenConstrOr(classes[num], [items[x] for x in map_class_to_name[num]] ,name="class count")
for c in self.raw_constraints:
count = model.addVar()
for n in c:
if n in classes:
count += classes[n]
model.addConstr(count <= 1, name="constraint")
print("Start optimizing...")
model.optimize()
print("Done! ")
# Status checking
status = model.Status
if status == GRB.Status.INF_OR_UNBD or \
status == GRB.Status.INFEASIBLE or \
status == GRB.Status.UNBOUNDED:
print('The model cannot be solved because it is infeasible or unbounded')
if status != GRB.Status.OPTIMAL:
print('Optimization was stopped with status ' + str(status))
Problem = True
try:
model.write("mps_model/" + self.filename + ".sol")
except Exception as e:
pass
print("Generating solution file...")
# Display solution
solution_names = list()
for i, v in enumerate(items):
try:
if items[v].X > 0.9:
solution_names.append(item_names[i])
except Exception as e:
pass
self.M = old_M
self.items = old_items
#.........这里部分代码省略.........
示例7: gurobi
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setParam [as 别名]
def gurobi(wanted_parts, available_parts, stores, shipping_cost=10.0):
from gurobipy import Model, GRB, LinExpr
kf1 = lambda x: (x['item_id'], x['wanted_color_id'])
kf2 = lambda x: (x['ItemID'], x['ColorID'])
available_by_store = utils.groupby(available_parts, lambda x: x['store_id'])
store_by_id = dict( (s['store_id'], s) for s in stores )
m = Model()
store_variables = {} # store id to variable indicating store is used
quantity_variables = [] # list of all lot variables + metadata
# for every store
for (store_id, inventory) in available_by_store.iteritems():
# a variable for if anything was bought from this store. if 1, then pay
# shipping cost and all store inventory is available; if 0, then don't pay
# for shipping and every lot in it has 0 quantity available
store_variables[store_id] = m.addVar(0.0, 1.0, shipping_cost, GRB.BINARY,
"use-store=%s" % (store_id,))
for lot in inventory:
store_id = lot['store_id']
quantity = lot['quantity_available']
unit_cost= lot['cost_per_unit']
item_id = lot['item_id']
color_id = lot['color_id']
# a variable for how much to buy of this lot
v = m.addVar(0.0, quantity, unit_cost, GRB.CONTINUOUS,
"quantity-store=%s-item=%s-color=%s" % (store_id, item_id, color_id))
# keep a list of all lots
quantity_variables.append({
'store_id': store_id,
'item_id': lot['item_id'],
'wanted_color_id': lot['wanted_color_id'],
'color_id': lot['color_id'],
'variable': v,
'quantity_available': quantity,
'cost_per_unit': unit_cost
})
# actually put the variables into the model
m.update()
# for every lot in every store
for lot in quantity_variables:
use_store = store_variables[lot['store_id']]
quantity = lot['quantity_available']
unit_cost = lot['cost_per_unit']
v = lot['variable']
# a constraint for how much can be bought
m.addConstr(LinExpr([1.0, -1 * quantity], [v, use_store]),
GRB.LESS_EQUAL, 0.0,
"maxquantity-store=%s-item=%s-color-%d" % (lot['store_id'], lot['item_id'], lot['color_id']))
# for every wanted lot
variables_by_id = utils.groupby(quantity_variables, kf1)
for lot in wanted_parts:
# a constraint saying amount bought >= wanted amount
variables = map(lambda x: x['variable'], variables_by_id[kf2(lot)])
constants = len(variables) * [1.0]
m.addConstr(LinExpr(constants, variables),
GRB.GREATER_EQUAL, lot['Qty'],
"wantedamount-item=%s-color=%s" % (lot['ItemID'], lot['ColorID']))
# for every store
variables_by_store = utils.groupby(quantity_variables, lambda x: x['store_id'])
for (store_id, variables) in variables_by_store.iteritems():
use_store = store_variables[store_id]
minimum_purchase = store_by_id[store_id]['minimum_buy']
# a constraint saying "if I purchased from this store, I bought the minimum amount or more"
constants = [v['cost_per_unit'] for v in variables] + [-1 * minimum_purchase]
variables = [v['variable'] for v in variables] + [use_store]
m.addConstr(LinExpr(constants, variables),
GRB.GREATER_EQUAL, 0.0,
"minbuy-store=%d" % (store_id,))
# minimize sum of costs of items bought + shipping costs
m.setParam(GRB.param.MIPGap, 0.01) # stop when duality gap <= 1%
m.optimize()
# get results
if m.ObjVal < float('inf'):
result = []
for lot in quantity_variables:
# get variable out
v = lot['variable']
del lot['variable']
# lot variables are continuous, so they might not actually be integral.
# If they're not, check that they're "almost" integral, so we can just
# round. Otherwise, print this warning. According to theory the optimal
# solution is for all continuous variables to be integral.
if v.X != int(v.X) and abs(v.X - round(v.X)) > 1e-3:
#.........这里部分代码省略.........
示例8: _optimize_gurobi
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setParam [as 别名]
#.........这里部分代码省略.........
#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':
#Try to find a solution using a different method
lp.setParam("MarkowitzTol", 1e-2)
for lp_method in the_methods:
lp.setParam("Method", lp_method)
lp.optimize()
if status_dict[lp.status] == 'optimal':
break
else:
lp.setParam("TimeLimit", 0.6)
lp.optimize()
lp.setParam("TimeLimit", "default")
if lp.status in status_dict:
status = status_dict[lp.status]
示例9: exact_time_schedule
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setParam [as 别名]
#.........这里部分代码省略.........
h = data['h']
conflicts = data['conflicts']
locking_times = data['locking_times']
T = data['T']
model = Model("ExaminationScheduling")
print("Building variables...")
# y[i,l] = 1 if exam i is at time l
y = {}
for i in range(n):
for l in range(p):
y[i, l] = model.addVar(vtype=GRB.BINARY, name="y_%s_%s" % (i,l))
# help variable z[i,j] and delta[i,j] for exam i and exam j
# we are only interested in those exams i and j which have a conflict!
z = {}
delta = {}
for i in range(n):
for j in conflicts[i]:
z[i, j] = model.addVar(vtype=GRB.INTEGER, name="z_%s_%s" % (i,j))
delta[i, j] = model.addVar(vtype=GRB.BINARY, name="delta_%s_%s" % (i,j))
w = {}
for i in range(n):
w[i] = model.addVar(vtype=GRB.INTEGER, name="w_%s" % (i))
# integrate new variables
model.update()
# adding constraints as found in MidTerm.pdf
print("Building constraints...")
print("c1: each exam at exactly one time")
for i in range(n):
model.addConstr( quicksum([ y[i, l] for l in range(p) ]) == 1 , "c2")
print("c2: avoid conflicts")
for i in range(n):
for l in range(p):
# careful!! Big M changed!
model.addConstr(quicksum([ y[j,l] for j in conflicts[i] ]) <= (1 - y[i, l]) * sum(conflicts[i]), "c3")
print("c3: Building %d clique constraints" %n_cliques)
if n_cliques > 0:
G = nx.Graph()
for i in range(n):
G.add_node(i)
for i in range(n):
for j in conflicts[i]:
G.add_edge(i,j)
cliques = nx.find_cliques(G) # generator
for counter, clique in itertools.izip(range(n_cliques), cliques):
for l in range(l):
model.addConstr( quicksum([ y[i, l] for i in clique ]) <= 1, "c_lique_%s_%s_%s" % (counter,clique,l))
#print "c_lique_%s_%s_%s" % (counter,clique,l)
print("c4: resolving the absolute value")
for i in range(n):
for j in conflicts[i]:
model.addConstr( z[i, j] <= quicksum([ h[l]*(y[i,l] - y[j,l]) for l in range(p) ]) + delta[i,j] * (2*h[len(h)-1]), "c7a")
model.addConstr( z[i, j] <= -quicksum([ h[l]*(y[i,l]-y[j,l]) for l in range(p) ]) + (1-delta[i,j]) * (2*h[len(h)-1]), "c7b")
model.addConstr( z[i, j] >= quicksum([ h[l]*(y[i,l] - y[j,l]) for l in range(p) ]) , "c7c")
model.addConstr( z[i, j] >= -quicksum([ h[l]*(y[i,l] - y[j,l]) for l in range(p) ]) , "c7d")
model.addConstr( w[i] <= z[i,j], "c7e")
print("c5: coloring")
color_exams = swap_color_dictionary(exam_colors)
for color in color_exams:
for l in range(p):
for i in color_exams[color]:
for j in range(n):
if i == j:
continue
if j in color_exams[color]:
model.addConstr( y[i,l] == y[j,l], "c5a")
else:
model.addConstr( y[i,l] != y[j,l], "c5b")
print("All constrained built - OK")
# objective: minimize number of used rooms
print("Building Objective...")
obj1 = quicksum([ w[i] for i in range(n)])
model.setObjective( obj1, GRB.MAXIMIZE)
# Set Parameters
#print("Setting Parameters...")
model.setParam(GRB.Param.Threads, 1)
# max presolve agressivity
#model.params.presolve = 2
# Choosing root method 3= concurrent = run barrier and dual simplex in parallel
#model.params.method = 1
# return
return(model)
示例10: _sensitivity_analysis_for_tardiness
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setParam [as 别名]
def _sensitivity_analysis_for_tardiness(z, CT, D):
m = Model("model_for_sensitivity_analysis_for_tardiness")
m.setParam('OutputFlag', False)
# m.params.IntFeasTol = 1e-7
DT = {}
TD = {}
for j in range(D.project_n):
## Project Tadeness,construction completion time
DT[j] = m.addVar(obj=0, vtype=GRB.CONTINUOUS, name="DT_%d" % j)
TD[j] = m.addVar(obj=0, vtype=GRB.CONTINUOUS, name="TD_%d" % j)
DT[-1] = m.addVar(obj=0, vtype=GRB.CONTINUOUS, name="DT_-1")
m.update();
#### Add Constraint ####
## Constrain 2: project complete data>due data ##
# equation 17
for j in range(D.project_n):
m.addConstr(DT[j] - TD[j], GRB.LESS_EQUAL, D.DD[j], name="constraint_2_project_%d" % j)
## Constraint 13
# equation 12
for j in range(D.project_n):
m.addConstr(DT[j], GRB.GREATER_EQUAL, CT[j] + D.review_duration[j],
name="constraint_13_project_%d" % j)
## Constraint 14
# equation 13
for i in range(-1, D.project_n):
for j in range(D.project_n):
if i != j:
m.addConstr(DT[j], GRB.GREATER_EQUAL, DT[i] - D.M * (1 - z[i, j]) + D.review_duration[j],
name="constraint_14_project_%d_project_%d" % (i, j))
m.update()
# Set optimization objective - minimize sum of
expr = LinExpr()
for j in range(D.project_n):
expr.add(D.w[j] * TD[j])
m.setObjective(expr, GRB.MINIMIZE)
m.update()
# m.params.presolve = 1
m.update()
m.optimize()
# _logger.info("mm binding info:")
sj = {}
for c in m.getConstrs():
if c.ConstrName.startswith('constraint_13'):
j = int(c.ConstrName.split('_')[-1])
# if c.Pi != 0:
# sj[j] = 1
# _logger.info('%s binding Pi:%.4g' % (c.ConstrName, c.Pi))
# pass
# else:
# sj[j] = 0
# _logger.info('%s not binding Pi:%.4g' % (c.ConstrName, c.Pi))
# pass
sj[j] = c.Pi
return sj
示例11: _sensitivity_for_constraints
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setParam [as 别名]
def _sensitivity_for_constraints(AT, j, project, y_, project_activity, M):
global _round, _pa_dataset
m = Model("SingleProject_%d_for_sensitivity" % j)
m.setParam('OutputFlag', False)
# m.params.IntFeasTol = 1e-7
## Project complete data,Project Tadeness,construction completion time
CT = m.addVar(obj=0, vtype=GRB.CONTINUOUS, name="CT_%d" % j)
## Activity start time
ST = {}
project_activities = project_activity[project]
for row in project_activities.nodes():
ST[row] = m.addVar(obj=0, vtype=GRB.CONTINUOUS, name="ST_%d_%s" % (j, row))
## Review sequence z_ij
## move to annealing objective function
m.update()
## Constrain 8: activity starting constrain
# equation 20
for a in project_activities.nodes():
for r in project_activities.node[a]['resources']:
m.addConstr(ST[a], GRB.GREATER_EQUAL, AT[j, r],
name="constraint_8_project_%d_activity_%s_resource_%s" % (j, a, r))
## Constrain 9 activity sequence constrain
# equation 21
for row1, row2 in project_activities.edges():
m.addConstr(ST[row1] + project_activities.node[row1]['duration'], GRB.LESS_EQUAL,
ST[row2], name="constraint_9_project_%d_activity_%s_activity_%s" % (j, row1, row2))
## Constrain 10,11
for row1 in project_activities.nodes():
for row2 in project_activities.nodes():
if row1 != row2 and len(list(
set(project_activities.node[row1]['rk_resources']).intersection(
project_activities.node[row2]['rk_resources']))) > 0:
# equation 22
m.addConstr(ST[row1] + project_activities.node[row1]['duration'] - M * (
1 - _get_y_for_activities(y_, row1, row2)), GRB.LESS_EQUAL, ST[row2],
name="constraint_10_project_%d_activity_%s_activity_%s" % (j, row1, row2))
# equation 23
m.addConstr(
ST[row2] + project_activities.node[row2]['duration'] - M * _get_y_for_activities(y_, row1, row2),
GRB.LESS_EQUAL, ST[row1],
name="constraint_11_project_%d_activity_%s_activity_%s" % (j, row1, row2))
# m.addConstr(y[j,row1,row2]+y[j,row2,row1],GRB.LESS_EQUAL,1)
## Constrain 12
# equation 24
for row in project_activities.nodes():
m.addConstr(CT, GRB.GREATER_EQUAL, ST[row] + project_activities.node[row]['duration'],
name="constraint_12_project_%d_activity_%s" % (j, row))
m.update()
# Set optimization objective - minimize completion time
expr = LinExpr()
expr.add(CT)
m.setObjective(expr, GRB.MINIMIZE)
m.update()
##########################################
# m.params.presolve = 1
m.update()
m.setParam(GRB.Param.Method, 0)
m.update()
# Solve
# m.params.presolve=0
m.optimize()
_skja = {}
for c in m.getConstrs():
if c.ConstrName.startswith('constraint_8_project'):
splits = c.ConstrName.split('_')
r = splits[7]
if r not in _skja:
_skja[r] = []
_skja[r].append(c.Pi)
# if c.Pi != 0:
# logging.debug('project %d binding resource:%s Pi:%.4g' % (j, splits[-1], c.Pi))
# else:
# logging.debug('project %d not binding resource:%s Pi:%.4g' % (j, splits[-1], c.Pi))
_pa_dataset.loc[_pa_dataset.shape[0]] = [_round, j, r, splits[5], c.Pi]
_skj = {}
for r in _skja:
_skj[j, r] = max(_skja[r])
_pa_max_dataset.loc[_pa_max_dataset.shape[0]] = [_round, j, r, max(_skja[r])]
return _skj
示例12: _objective_function_for_delta_weight
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setParam [as 别名]
def _objective_function_for_delta_weight(D, delta_weight, d1, d2):
global _time_limit_per_model, _round, _pr_dataset, _tardiness_objective_dataset
m = Model("model_for_supplier_assignment")
m.setParam('OutputFlag', False)
m.params.timelimit = _time_limit_per_model
# m.params.IntFeasTol = 1e-7
x = {}
q = {}
for (r, s, p) in D.supplier_project_shipping:
x[r, s, p] = m.addVar(vtype=GRB.BINARY, name="x_%s_%s_%s" % (r, s, p))
q[r, s, p] = m.addVar(vtype=GRB.CONTINUOUS, name="q_%s_%s_%s" % (r, s, p))
AT = {}
for j in range(D.project_n):
for k in [r for r, p in D.resource_project_demand if p == D.project_list[j]]:
AT[j, k] = m.addVar(vtype=GRB.CONTINUOUS, name="AT_%s_%s" % (j, k))
m.update()
## define constraints
# equation 2
for (r, s) in D.resource_supplier_capacity:
m.addConstr(quicksum(q[r, s, D.project_list[j]] for j in range(D.project_n)), GRB.LESS_EQUAL,
D.resource_supplier_capacity[r, s],
name="constraint_3_resource_%s_supplier_%s" % (r, s))
# constraint 21(4) 23(6)
for (r, p) in D.resource_project_demand:
# equation 5
m.addConstr(quicksum(x[r, i, p] for i in D.resource_supplier_list[r]), GRB.EQUAL, 1,
name="constraint_6_resource_%s_project_%s" % (r, p))
# equation 3
m.addConstr(quicksum(q[r, i, p] for i in D.resource_supplier_list[r]), GRB.GREATER_EQUAL,
D.resource_project_demand[r, p], name="constraint_4_resource_%s_project_%s" % (r, p))
# constraint 22(5)
for (i, j, k) in q:
# i resource, j supplier, k project
# equation 4
m.addConstr(q[i, j, k], GRB.LESS_EQUAL, D.M * x[i, j, k],
name="constraint_5_resource_%s_supplier_%s_project_%s" % (i, j, k))
# constraint 7
shipping_cost_expr = LinExpr()
for (i, j, k) in q:
shipping_cost_expr.addTerms(D.c[i, j, k], q[i, j, k])
# equation 6
m.addConstr(shipping_cost_expr, GRB.LESS_EQUAL, D.B, name="constraint_7")
# constraint 8
# equation 26
for j in range(D.project_n):
p = D.project_list[j]
project_resources = [r for (r, p_) in D.resource_project_demand.keys() if p_ == p]
for r in project_resources:
suppliers = D.resource_supplier_list[r]
m.addConstr(
quicksum(
x[r, s, p] * (D.resource_supplier_release_time[r, s] + D.supplier_project_shipping[r, s, p]) for
s in
suppliers), GRB.LESS_EQUAL, AT[j, r],
name="constraint_8_project_%d_resource_%s_deliver" % (j, r))
m.update()
expr = LinExpr()
for j in range(D.project_n):
p = D.project_list[j]
for r in [r for (r, p_) in D.resource_project_demand.keys() if p_ == p]:
expr.add(delta_weight[j, r] * AT[j, r])
m.setObjective(expr, GRB.MINIMIZE)
m.update()
##########################################
# m.params.presolve = 1
m.update()
# Solve
# m.params.presolve=0
m.optimize()
_exit_if_infeasible(m)
m.write(join(_result_output_path, "round_%d_supplier_assign.lp" % _round))
m.write(join(_result_output_path, "round_%d_supplier_assign.sol" % _round))
with open(join(log_output_path, 'shipping_cost.txt'), 'a') as fout:
fout.write('shipping cost: %f\n' % shipping_cost_expr.getValue())
_logger.info('shipping cost: %f' % shipping_cost_expr.getValue())
print('status', m.status)
# m.write(join(_output_path, 'delta_weight.sol'))
# m.write(join(_output_path, 'delta_weight.lp'))
X_ = {}
for (i, j, k) in D.supplier_project_shipping:
v = m.getVarByName("x_%s_%s_%s" % (i, j, k))
if v.X == 1:
X_[i, j, k] = 1
AT_ = {}
for j, r in AT:
val = AT[j, r].X
if val > 0:
AT_[j, r] = val
tardiness_obj_val, skj, sj = _objective_function_for_tardiness(X_, AT_, D)
new_delta_weight = {}
# delta_weight_keys = list(delta_weight.keys())
#.........这里部分代码省略.........
示例13: optmize_single_project
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setParam [as 别名]
def optmize_single_project(AT, j, project_list, project_activity, M):
m = Model("SingleProject_%d" % j)
m.setParam(GRB.Param.Method, 0)
m.update()
#### Create variables ####
project = project_list[j]
## Project complete data,Project Tadeness,construction completion time
CT = m.addVar(obj=0, vtype=GRB.CONTINUOUS, name="(CT%d)" % j)
## Activity start time
ST = {}
project_activities = project_activity[project]
# print(project_activities.nodes())
for row in project_activities.nodes():
ST[row] = m.addVar(obj=0, vtype=GRB.CONTINUOUS, name="(ST%d,%s)" % (j, row))
## Review sequence z_ij
## move to annealing objective function
# y
y = {}
for activity_i in project_activities.nodes():
for activity_j in project_activities.nodes():
# print(project_activities.node[activity_i])
# print(dir(project_activities.node[activity_i]))
if activity_i != activity_j and len(list(
set(project_activities.node[activity_i]['rk_resources']).intersection(
project_activities.node[activity_j]['rk_resources']))) > 0:
y[activity_i, activity_j] = m.addVar(obj=0, vtype=GRB.BINARY,
name="(y%d,%s,%s)" % (j, activity_i, activity_j))
m.update()
#### Create constrains ####
## Constrain 2: project complete data>due data
## move to annealing objective function
## Constrain 3: supplier capacity limit
## move to annealing neighbor & random generator
## Constrain 4,6: project demand require; each project receive from one supplier for each resource
## move to annealing neighbor & random generator
## constrain 5: shipping constrain
## move to annealing neighbor & random generator
## Constrain 7:budget limit
## move to annealing constraint valid
## Constrain 8: activity starting constrain
for a in project_activities.nodes():
for r in project_activities.node[a]['resources']:
m.addConstr(AT[j, r], GRB.LESS_EQUAL, ST[a],
name="constraint_8_project_%d_activity_%s_resource_%s" % (j, a, r))
## Constrain 9 activity sequence constrain
for row1, row2 in project_activities.edges():
m.addConstr(ST[row1] + project_activities.node[row1]['duration'], GRB.LESS_EQUAL,
ST[row2], name="constraint_9_project_%d_activity_%s_activity_%s" % (j, row1, row2))
## Constrain 10,11
for row1 in project_activities.nodes():
for row2 in project_activities.nodes():
if row1 != row2 and len(list(
set(project_activities.node[row1]['rk_resources']).intersection(
project_activities.node[row2]['rk_resources']))) > 0:
m.addConstr(ST[row1] + project_activities.node[row1]['duration'] - M * (
1 - y[row1, row2]), GRB.LESS_EQUAL, ST[row2],
name="constraint_10_project_%d_activity_%s_activity_%s" % (j, row1, row2))
m.addConstr(
ST[row2] + project_activities.node[row2]['duration'] - M * (y[row1, row2]),
GRB.LESS_EQUAL, ST[row1],
name="constraint_11_project_%d_activity_%s_activity_%s" % (j, row1, row2))
# m.addConstr(y[j,row1,row2]+y[j,row2,row1],GRB.LESS_EQUAL,1)
## Constrain 12
for row in project_activities.nodes():
m.addConstr(CT, GRB.GREATER_EQUAL, ST[row] + project_activities.node[row]['duration'],
name="constraint_12_project_%d_activity_%s" % (j, row))
## Constrain 13
## move to anealing objective function
## Constrain 14
## move to anealing objective function
## Constrain 15
## move to anealing objective function
## Constrain 16
## move to anealing objective function
## Constrain 17
## move to anealing objective function
m.update()
# Set optimization objective - minimize completion time
expr = LinExpr()
#.........这里部分代码省略.........