本文整理汇总了Python中gurobipy.Model.optimize方法的典型用法代码示例。如果您正苦于以下问题:Python Model.optimize方法的具体用法?Python Model.optimize怎么用?Python Model.optimize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类gurobipy.Model
的用法示例。
在下文中一共展示了Model.optimize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: solve_lp_knapsack_gurobi
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import optimize [as 别名]
def solve_lp_knapsack_gurobi(scores, costs, budget):
from gurobipy import Model, LinExpr, GRB
n = len(scores)
# Create a new model.
m = Model("lp_knapsack")
# Create variables.
for i in range(n):
m.addVar(lb=0.0, ub=1.0)
m.update()
vars = m.getVars()
# Set objective.
obj = LinExpr()
for i in range(n):
obj += scores[i] * vars[i]
m.setObjective(obj, GRB.MAXIMIZE)
# Add constraint.
expr = LinExpr()
for i in range(n):
expr += costs[i] * vars[i]
m.addConstr(expr, GRB.LESS_EQUAL, budget)
# Optimize.
m.optimize()
assert m.status == GRB.OPTIMAL
x = np.zeros(n)
for i in range(n):
x[i] = vars[i].x
return x
示例2: ilp
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import optimize [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: check_feasability_ILP
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import optimize [as 别名]
def check_feasability_ILP(exams_to_schedule, period, data, verbose=False):
# More precise but by far to slow compared to heuristic
r = data['r']
T = data['T']
s = data['s']
z = {}
model = Model("RoomFeasability")
# z[i,k] = if exam i is written in room k
for k in range(r):
# print k, period
if T[k][period] == 1:
for i in exams_to_schedule:
z[i, k] = model.addVar(vtype=GRB.BINARY, name="z_%s_%s" % (i, k))
model.update()
# Building constraints...
# c1: seats for all students
for i in exams_to_schedule:
expr = LinExpr()
for k in range(r):
if T[k][period] == 1:
expr.addTerms(1, z[i, k])
model.addConstr(expr >= s[i], "c1")
# c2: only one exam per room
for k in range(r):
if T[k][period] == 1:
expr = LinExpr()
for i in exams_to_schedule:
expr.addTerms(1, z[i, k])
model.addConstr(expr <= 1, "c2")
model.setObjective(0, GRB.MINIMIZE)
if not verbose:
model.params.OutputFlag = 0
model.params.heuristics = 0
model.params.PrePasses = 1
model.optimize()
# return best room schedule
try:
return model.objval
except GurobiError:
logging.warning('check_feasability_ILP: model has no objVal')
return None
示例4: find_feasible_start
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import optimize [as 别名]
def find_feasible_start(n_colors, h, statespace, conflicts, verbose=False):
model = Model("TimeFeasibility")
p = len(h)
y = {}
# y[i,k] = if color i gets slot l
for i in range(n_colors):
for l in range(p):
y[i,l] = model.addVar(vtype=GRB.BINARY, name="y_%s_%s" % (i,l))
model.update()
# Building constraints...
# c1: all get one
for i in range(n_colors):
model.addConstr( quicksum([ y[i, l] for l in range(p) ]) == 1, "c1")
# c2: each slot needs to be used tops once
for l in range(p):
model.addConstr( quicksum([ y[i, l] for i in range(n_colors) ]) <= 1, "c2")
### c3: statespace constraints
for i in range(n_colors):
#print l, h[l], i, [s for s in statespace]
model.addConstr( quicksum([ y[i, l] for l in range(p) if h[l] not in statespace[i] ]) == 0, "c3")
# objective: minimize conflicts
#obj = quicksum([ y[i,l] * y[j,l] for l in range(p) for i in range(n_colors) for j in range(i+1, n_colors) ])
obj = quicksum([ sum(y[i,l] for i in range(n_colors)) for l in range(p) ])
#obj = 0
model.setObjective(obj, GRB.MINIMIZE)
if not verbose:
model.params.OutputFlag = 0
model.optimize()
# return best room schedule
color_schedule = []
if model.status == GRB.INFEASIBLE:
return color_schedule
for i in range(n_colors):
for l in range(p):
v = model.getVarByName("y_%s_%s" % (i,l))
if v.x == 1:
color_schedule.append(h[l])
break
return color_schedule
示例5: generateInstance
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import optimize [as 别名]
def generateInstance(self):
def euc_dist(bor, sh):
dx = bor["x_coord"] - sh["x_coord"]
dy = bor["y_coord"] - sh["y_coord"]
return math.sqrt(dx * dx + dy * dy)
model = Model('FireSolver')
# Generate variables
x = {}
for bor in self.boroughs:
# New firehouses
for fh in self.new_firehouses + self.old_firehouses:
name = "x_" + fh["loc_id"] + "_" + bor["loc_id"]
x[bor["loc_id"], fh["loc_id"]] = model.addVar(name=name, vtype ="b", obj=self.cost_coef * euc_dist(bor, fh))
# Open variables
openfh = {}
for fh in self.new_firehouses:
openfh[fh["loc_id"]] = model.addVar(name = "open_" + fh["loc_id"], vtype ="b", obj=fh["construction_cost"])
# Close variables
closefh = {}
for fh in self.old_firehouses:
closefh[fh["loc_id"]] = model.addVar(name = "close_" + fh["loc_id"], vtype ="b", obj=fh["destruction_cost"])
model.modelSense = GRB.MINIMIZE
model.update()
# Constraints: one firehouse / borough
for bor in self.boroughs:
model.addConstr(quicksum(x[key] for key in x if key[0] == bor["loc_id"]) == 1)
# capacity of firehouses
for fh in self.new_firehouses:
model.addConstr(quicksum(x[key] for key in x if key[1] == fh["loc_id"]) <= self.capacity * openfh[fh["loc_id"]])
# If it is not removed, the initial assignment needs to be respected
for fh in self.old_firehouses:
for bor in self.boroughs:
if bor["currently_protected_by"] == fh["loc_id"]:
model.addConstr(x[bor["loc_id"], fh["loc_id"]] == 1 - closefh[fh["loc_id"]])
else:
model.addConstr(x[bor["loc_id"], fh["loc_id"]] == 0)
# solve it
model.optimize()
self.model = model
示例6: _cut
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import optimize [as 别名]
def _cut(self, model, val_func, cut_func):
'''Returns true if a cut was added to the master'''
problem = self.problem
theta = self.theta
x = self.x
# Create subproblem.
sub = Model()
# y[ip,iq,s,c] = 1 if images ip & iq have a shared path through stage
# s by running command c during s, 0 otherwise
y = {}
for (ip, iq), cmds in problem.shared_cmds.items():
for s, c in product(problem.shared_stages[ip, iq], cmds):
y[ip,iq,s,c] = sub.addVar(name='y[%s,%s,%s,%s]' % (ip,iq,s,c))
sub.update()
# Find shared paths among image pairs.
constraints = defaultdict(list)
for (ip, iq), cmds in problem.shared_cmds.items():
for s in problem.shared_stages[ip,iq]:
for c in cmds:
constraints[ip,s,c].append(sub.addConstr(y[ip,iq,s,c] <= val_func(model, x[ip,s,c])))
constraints[iq,s,c].append(sub.addConstr(y[ip,iq,s,c] <= val_func(model, x[iq,s,c])))
if s > 1:
sub.addConstr(sum(y[ip,iq,s,c] for c in cmds) <= sum(y[ip,iq,s-1,c] for c in cmds))
sub.setObjective(
-sum(problem.commands[c] * y[ip,iq,s,c] for ip,iq,s,c in y),
GRB.MINIMIZE
)
sub.optimize()
# Add the dual prices for each variable
pi = defaultdict(float)
for isp, cons in constraints.iteritems():
for c in cons:
pi[isp] += c.pi
# Detect optimality
if val_func(model, theta) >= sub.objVal:
return False # no cuts to add
# Optimality cut
cut_func(model, theta >= sum(pi[isp]*x[isp] for isp in pi if pi[isp]))
return True
示例7: two_cycle
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import optimize [as 别名]
def two_cycle(A, C, gap):
"""
Solve high-vertex dense graphs by reduction to
weighted matching ILP.
"""
_ = '*'
m = Model()
m.modelsense = GRB.MAXIMIZE
m.params.mipgap = gap
m.params.timelimit = 60 * 60
n = A.shape[0]
vars = {}
edges = tuplelist()
# model as undirected graph
for i in range(n):
for j in range(i+1, n):
if A[i, j] == 1 and A[j, i] == 1:
e = (i, j)
edges.append(e)
w_i = 2 if i in C else 1
w_j = 2 if j in C else 1
w = w_i + w_j
var = m.addVar(vtype=GRB.BINARY, obj=w)
vars[e] = var
m.update()
# 2 cycle constraint <=> undirected flow <= 1
for i in range(n):
lhs = LinExpr()
lhs_vars = [vars[e] for e in chain(edges.select(i, _), edges.select(_, i))]
ones = [1.0]*len(lhs_vars)
lhs.addTerms(ones, lhs_vars)
m.addConstr(lhs <= 1)
m.optimize()
m.update()
cycles = [list(e) for e in edges if vars[e].x == 1.0]
return cycles, m.objval
示例8: build_gurobi_model
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import optimize [as 别名]
def build_gurobi_model(case):
G, B = case.G, case.B
P = real(case.demands)
Q = imag(case.demands)
branches = case.branch_list
n = len(case.demands)
vhat = case.vhat
s2 = 2**.5
gens = {bus: gen.v for bus, gen in case.gens.items()}
del gens[0]
m = GurobiModel("jabr")
u = [m.addVar(name='u_%d'%i) for i in range(n)]
R = {(i, j): m.addVar(name='R_%d_%d' % (i, j)) for i, j in branches}
I = {(i, j): m.addVar(lb=-GRB.INFINITY, name='I_%d_%d' % (i, j)) for i, j in branches}
for i, j in branches:
R[j, i] = R[i, j]
I[j, i] = I[i, j]
m.update()
m.addConstr(u[0] == vhat*vhat/s2, 'u0')
for gen, v in gens.iteritems():
m.addConstr(u[gen] == v*v/s2, 'u%d' % gen)
for i, j in branches:
m.addQConstr(2*u[i]*u[j] >= R[i,j]*R[i,j] + I[i,j]*I[i,j], 'cone_%d_%d' % (i, j))
k = lambda i: (j for j in B[i, :].nonzero()[1])
s = lambda i, j: 1 if i < j else -1
for i in range(1, n):
m.addConstr(-s2*u[i]*G[i, :].sum() + quicksum(G[i,j]*R[i,j] + B[i,j]*s(i,j)*I[i,j] for j in k(i)) == P[i],
'real_flow_%d_%d' % (i, j))
if i in gens:
continue
m.addConstr(s2*u[i]*B[i, :].sum() + quicksum(-B[i,j]*R[i,j] + G[i,j]*s(i,j)*I[i,j] for j in k(i)) == Q[i],
'reac_flow_%d_%d' % (i, j))
m.setObjective(quicksum(R[i,j] for i, j in branches), sense=GRB.MAXIMIZE)
m.params.outputFlag = 0
#m.params.barQCPConvTol = 5e-10
m.optimize()
if m.status != 2:
raise ValueError("gurobi failed to converge: %s (check log)" % m.status)
u_opt = [x.getAttr('x') for x in u]
R_opt = {(i, j): x.getAttr('x') for (i, j), x in R.items()}
I_opt = {(i, j): x.getAttr('x') for (i, j), x in I.items()}
return u_opt, R_opt, I_opt
示例9: solve
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import optimize [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
示例10: range
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import optimize [as 别名]
# Re-optimize until either we have run a certain number of iterations
# or complementary slackness conditions apply.
for k in range(1, 101):
# max sum i,j: c_ij * x_ij
model.setObjective(
sum(
# Original objective function
sum(c_ij * x_ij for c_ij, x_ij in zip(c_i, x_i))
for c_i, x_i in zip(c, x)
) + sum (
# Penalties for dualized constraints
u_j * p_j for u_j, p_j in zip(u, penalties)
)
)
model.optimize()
print 'iteration', k, 'obj =', model.objVal, \
'u =', u, 'penalties =', [p.x for p in penalties]
# Test for complementary slackness
stop = True
eps = 10e-6
for u_i, p_i in zip(u, penalties):
if abs(u_i) > eps and abs(p_i.x) > eps:
stop = False
break
if stop:
print 'primal feasible & optimal'
break
示例11: run_algorithm
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import optimize [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
#.........这里部分代码省略.........
示例12: Backup
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import optimize [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()
示例13: __optmize_single_project
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import optimize [as 别名]
def __optmize_single_project(self, x, j):
'''
Given the generated x for single project, try to optimize the tardiness of the project.
:param x: the assignment of resource supplier to project
:param j: index of project
:return:
'''
m = Model("SingleProject_%d" % j)
#### Create variables ####
project = self.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 = self.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']:
resource_delivered_days = 0
for s in self.resource_supplier_list[r]:
resource_delivered_days += x.get((r, s, project), 0) * \
(self.resource_supplier_release_time[r, s] +
self.supplier_project_shipping[
r, s, project])
m.addConstr(resource_delivered_days, 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():
# print(row1, '#', row2, '#', j)
# print(ST)
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'] - self.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'] - self.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():
# print(project_activities.node[row]['duration'])
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
#.........这里部分代码省略.........
示例14: __objective_function
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import optimize [as 别名]
def __objective_function(self, x, q):
m = Model("Overall_Model")
CT = {}
DT = {}
TD = {}
#### Add Variable ####
for j in range(self.project_n):
## solve individual model get Project complete date
CT[j] = self.__optmize_single_project(x, j)
## 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)")
## Review Sequence z_ij
z = {}
for i in range(self.project_n):
for j in range(self.project_n):
if i != j:
z[i, j] = m.addVar(obj=0, vtype=GRB.BINARY, name="(z%d,%d)" % (i, j))
for j in range(self.project_n):
z[-1, j] = m.addVar(obj=0, vtype=GRB.BINARY, name="(z%d,%d)" % (-1, j))
m.update();
#### Add Constraint ####
## Constrain 2: project complete data>due data ##
for j in range(self.project_n):
m.addConstr(DT[j] - TD[j], GRB.LESS_EQUAL, self.DD[j], name="constraint_2_project_%d" % j)
## Constraint 13
for j in range(self.project_n):
m.addConstr(DT[j], GRB.GREATER_EQUAL, CT[j] + self.review_duration[j], name="constraint_13_project_%d" % j)
## Constraint 14
for i in range(-1, self.project_n):
for j in range(self.project_n):
if i != j:
m.addConstr(DT[j], GRB.GREATER_EQUAL, DT[i] - self.M * (1 - z[i, j]) + self.review_duration[j],
name="constraint_14_project_%d_project_%d" % (i, j))
## Constrain 15
for j in range(self.project_n):
m.addConstr(quicksum(z[i, j] for i in range(-1, self.project_n) if i != j), GRB.EQUAL, 1,
name="constraint_15_project_%d" % j)
## Constrain 16
m.addConstr(quicksum(z[-1, j] for j in range(self.project_n)), GRB.EQUAL, 1, name="constraint_16")
## Constrain 17
for i in range(self.project_n):
m.addConstr(quicksum(z[i, j] for j in range(self.project_n) if j != i), GRB.LESS_EQUAL, 1,
name="constraint_17_project_%d" % i)
m.update()
# Set optimization objective - minimize sum of
expr = LinExpr()
for j in range(self.project_n):
expr.add(self.w[j] * TD[j])
m.setObjective(expr, GRB.MINIMIZE)
m.update()
m.params.presolve = 1
m.update()
m.optimize()
m.write(join(self.output_dir, "heuristic_whole.lp"))
m.write(join(self.output_dir, "heuristic_whole.sol"))
print([self.w[j] * TD[j].X for j in range(self.project_n)])
return m.objVal, argmax([self.w[j] * TD[j].X for j in range(self.project_n)])
示例15: get_mapping
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import optimize [as 别名]
def get_mapping(PG, VG):
vnodes, vhosts = multidict({n: len(VG.node[n]['host_ports']) for n in VG.nodes()})
pnodes, phosts = multidict({n: len(PG.node[n]['host_ports']) for n in PG.nodes()})
parcs, pcapacity = multidict({(m, n): PG.edge[m][n]['weight'] for (m, n) in PG.edges()})
parcs = tuplelist(parcs)
varcs, vcapacity = multidict({(m, n): VG.edge[m][n]['weight'] for (m, n) in VG.edges()})
varcs = tuplelist(varcs)
m = Model('mapping')
# Create variables
node_mapping = {}
for i in vnodes:
for j in pnodes:
node_mapping[i, j] = m.addVar(vtype=GRB.BINARY, name="x_%s_%s" % (i, j))
edge_mapping = {}
for i in vnodes:
for p in VG.neighbors(i):
for (j, q) in parcs:
edge_mapping[i, p, j, q] = m.addVar(vtype=GRB.BINARY, name="y_%s_%s_%s_%s" % (i, p, j, q))
m.update()
# Arc capacity constraints
for i in vnodes:
m.addConstr(quicksum(node_mapping[i, j] for j in pnodes) == 1, 'node_%s' % i)
for i in vnodes:
for p in VG.neighbors(i):
for (j, q) in parcs:
m.addConstr(edge_mapping[i, p, j, q] <= ( node_mapping[i, j] + node_mapping[p, q] )/2, 'edge_%s_%s_%s_%s' % (i, p, j, q))
for (j, q) in parcs:
m.addConstr(quicksum(edge_mapping[i, p, j, q] + edge_mapping[p, i, j, q]for (i, p) in varcs) <= pcapacity[j, q], 'pcap_%s_%s' % (j, q))
for (i, p) in varcs:
m.addConstr(quicksum(edge_mapping[i, p, j, q] + edge_mapping[p, i, j, q] for (j, q) in parcs) >= vcapacity[i, p], 'vcap_%s_%s' % (i, p))
for j in pnodes:
m.addConstr(quicksum(node_mapping[i, j] * vhosts[i] for i in vnodes) <= phosts[j], 'phosts_%s' % j)
for i in vnodes:
m.addConstr(quicksum(node_mapping[i, j] * phosts[j] for j in pnodes) >= vhosts[i], 'vhosts_%s' % i)
# Compute optimal solution
m.optimize()
# Print solution
if m.status == GRB.status.OPTIMAL:
mapping = {}
mapping2 = {}
portlist = {}
for n in PG:
if 'host_ports' in PG.node[n]:
portlist[n] = PG.node[n]['host_ports']
solution = m.getAttr('x', edge_mapping)
for h in solution:
if solution[h] == 1.0:
vid1, vid2, pid1, pid2 = h
vport1, vport2 = list(VG.node[vid1]['links'][vid2])[0]
if (vid1, pid1) not in mapping:
mapping[(vid1, pid1)] =[vid1, pid1]
if (pid1, vid1) not in mapping2:
mapping2[(pid1, vid1)] =[pid1, vid1]
(pport1, pport2) = PG.node[pid1]['links'][pid2].pop()
# print vid1, vid2, pid1, pid2, pport1, pport2
if pid1 != pid2:
PG.node[pid2]['links'][pid1].remove((pport2, pport1))
mapping[(vid1, pid1)].append(vport1)
mapping[(vid1, pid1)].append(pport1)
mapping2[(pid1, vid1)].append(pport1)
mapping2[(pid1, vid1)].append(vport1)
if (vid2, pid2) not in mapping:
mapping[(vid2, pid2)] =[vid2, pid2]
if (pid2, vid2) not in mapping2:
mapping2[(pid2, vid2)] =[pid2, vid2]
mapping[(vid2, pid2)].append(vport2)
mapping[(vid2, pid2)].append(pport2)
mapping2[(pid2, vid2)].append(pport2)
mapping2[(pid2, vid2)].append(vport2)
solution2 = m.getAttr('x', node_mapping)
print [h for h in solution2 if solution2[h] == 1.0]
for h in solution2:
if solution2[h] == 1.0:
vid, pid = h
if len(VG.node[vid]['host_ports']) == 0:
continue
for vport in VG.node[vid]['host_ports']:
pport = portlist[pid].pop()
mapping[(vid, pid)].append(vport)
mapping[(vid, pid)].append(pport)
mapping2[(pid, vid)].append(pport)
mapping2[(pid, vid)].append(vport)
#.........这里部分代码省略.........