本文整理汇总了Python中gurobipy.Model.setObjective方法的典型用法代码示例。如果您正苦于以下问题:Python Model.setObjective方法的具体用法?Python Model.setObjective怎么用?Python Model.setObjective使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类gurobipy.Model
的用法示例。
在下文中一共展示了Model.setObjective方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: solve_lp_knapsack_gurobi
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setObjective [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: build_model
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setObjective [as 别名]
def build_model(plants, warehouses, capacity, demand, fixed_costs, trans_costs):
# decision variables
m = Model("facility")
is_open = []
for p in plants:
is_open.append(m.addVar(vtype=GRB.BINARY,
name="is_open[{}]".format(p)))
trans_qty = []
for w in warehouses:
trans_qty.append([])
for p in plants:
trans_qty[w].append(m.addVar(vtype=GRB.CONTINUOUS,
name="trans_qty[{}.{}]".format(p, w),
lb=0.0))
m.update()
# objective function
m.setObjective(quicksum(fixed_costs[p] * is_open[p]
for p in plants) +
quicksum(trans_costs[w][p] * trans_qty[w][p]
for w in warehouses
for p in plants),
GRB.MINIMIZE)
# constraints
for p in plants:
m.addConstr(quicksum(trans_qty[w][p] for w in warehouses) <= capacity[p] * is_open[p],
"Capacity({})".format(p))
for w in warehouses:
m.addConstr(quicksum(trans_qty[w][p] for p in plants) == demand[w],
"Demand({})".format(w))
m.update()
return m
示例3: ilp
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setObjective [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
示例4: check_feasability_ILP
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setObjective [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
示例5: find_feasible_start
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setObjective [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
示例6: _cut
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setObjective [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: build_gurobi_model
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setObjective [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
示例8: global_model
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setObjective [as 别名]
def global_model(N, k_choices, distance_matrix):
if k_choices >= N:
raise ValueError("k_choices must be less than N")
model = Model("distance1")
trajectories = range(N)
distance_matrix = np.array(
distance_matrix / distance_matrix.max(), dtype=np.float64)
dm = distance_matrix ** 2
y, x = {}, {}
for i in trajectories:
y[i] = model.addVar(vtype="B", obj=0, name="y[%s]" % i)
for j in range(i + 1, N):
x[i, j] = model.addVar(
vtype="B", obj=1.0, name="x[%s,%s]" % (i, j))
model.update()
model.setObjective(quicksum([x[i, j] * dm[j][i]
for i in trajectories
for j in range(i + 1, N)]))
# Add constraints to the model
model.addConstr(quicksum([y[i]
for i in trajectories]) <= k_choices, "27")
for i in trajectories:
for j in range(i + 1, N):
model.addConstr(x[i, j] <= y[i], "28-%s-%s" % (i, j))
model.addConstr(x[i, j] <= y[j], "29-%s-%s" % (i, j))
model.addConstr(y[i] + y[j] <= 1 + x[i, j],
"30-%s-%s" % (i, j))
model.addConstr(quicksum([x[i, j] for i in trajectories
for j in range(i + 1, N)])
<= nchoosek(k_choices, 2), "Cut_1")
model.update()
return model
示例9: solve
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setObjective [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: Backup
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setObjective [as 别名]
class Backup(object):
""" Class object for normal-based backup network model.
Parameters
----------
nodes: set of nodes
links: set of links
capacity: capacities per link based based on random failures
mean: mean for failure random variable
std: standard deviation for failure random variable
invstd: inverse of Phi-normal distribution for (1-epsilon)
Returns
-------
solution: set of capacity assigned per backup link.
"""
# Private model object
__model = []
# Private model variables
__BackupCapacity = {}
__bBackupLink = {}
__ValidLink = {}
# Private model parameters
__links = []
__nodes = []
__capacity = []
__mean = []
__std = []
__invstd = 1
def __init__(self,nodes,links,capacity,mean,std,invstd):
'''
Constructor
'''
self.__links = links
self.__nodes = nodes
self.__capacity = capacity
self.__mean = mean
self.__std = std
self.__invstd = invstd
self.__loadModel()
def __loadModel(self):
# Create optimization model
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:
#.........这里部分代码省略.........
示例11: run_algorithm
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setObjective [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: __objective_function
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setObjective [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)])
示例13: __optmize_single_project
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setObjective [as 别名]
#.........这里部分代码省略.........
# 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
## 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()
expr.add(CT)
m.setObjective(expr, GRB.MINIMIZE)
m.update()
##########################################
m.params.presolve = 1
m.update()
# Solve
# m.params.presolve=0
m.optimize()
m.write(join(self.output_dir, "heuristic_%d.lp" % j))
m.write(join(self.output_dir, "heuristic_%d.sol" % j))
return m.objVal
示例14: build_model
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setObjective [as 别名]
def build_model(data):
# Load Data Format
n = data['n']
r = data['r']
p = data['p']
s = data['s']
c = data['c']
h = data['h']
Q = data['Q']
T = data['T']
conflicts = data['conflicts']
locking_times = data['locking_times']
model = Model("ExaminationScheduling_v1")
# Build variables
print("Building variables...")
# x[i,k,l] = 1 if exam i is at time l in room k
x = {}
for i in range(n):
for k in range(r):
for l in range(p):
x[i,k,l] = model.addVar(vtype=GRB.BINARY, name="x_%s_%s_%s" % (i,k,l))
# 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 range(i+1,n):
if Q[i][j] == 0:
continue
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))
# integrate new variables
model.update()
# adding variables as found in MidTerm.pdf
print("Building constraints...")
print("c1: connecting variables x and y")
for i in range(n):
for l in range(p):
model.addConstr( quicksum([ x[i, k, l] for k in range(r) ]) <= r * y[i, l], "c1a")
model.addConstr( quicksum([ x[i, k, l] for k in range(r) ]) >= y[i, l], "c1b")
print("c2: 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("c3: avoid conflicts")
for i in range(n):
for l in range(p):
model.addConstr(quicksum([ Q[i][j] * y[j,l] for j in range(i+1,n) if Q[i][j] == 1 ]) <= (1 - y[i, l]) * sum(Q[i]), "c3")
print("c4: seats for all students")
for i in range(n):
model.addConstr( quicksum([ x[i, k, l] * c[k] for k in range(r) for l in range(p)]) >= s[i], "c4")
print("c5: only one exam per room per period")
for k in range(r):
for l in range(p):
model.addConstr( quicksum([ x[i, k, l] for i in range(n) ]) <= T[k][l], "c5")
print("c6: any multi room exam takes place at one moment in time")
for i in range(n):
for l in range(p):
model.addConstr(quicksum([ x[i, k, m] for k in range(r) for m in range(p) if m != l ]) <= (1 - y[i, l])*r, "c6")
print("c7: resolving the absolute value")
for i in range(n):
for j in range(i+1,n):
if Q[i][j] == 0:
continue
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")
print("OK")
# objective: minimize number of used rooms and maximize the distance of exams
print("Building Objective...")
gamma = 1
obj1 = quicksum([ x[i,k,l] * s[i] for i,k,l in itertools.product(range(n), range(r), range(p)) ])
obj2 = -quicksum([ Q[i][j] * z[i,j] for i in range(n) for j in range(i+1,n) if Q[i][j] == 1])
model.setObjective( obj1 + gamma * obj2, GRB.MINIMIZE)
print("Setting Parameters...")
# max presolve agressivity:
#.........这里部分代码省略.........
示例15: _optimize_gurobi
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import setObjective [as 别名]
#.........这里部分代码省略.........
status_dict = eval(status_dict['gurobi'])
#Update objectives if they are new.
if new_objective and new_objective != 'update problem':
update_objective(cobra_model, new_objective)
#Create a new problem
if not the_problem or the_problem in ['return', 'setup'] or \
not isinstance(the_problem, Model):
lp = Model("cobra")
lp.Params.OutputFlag = 0
lp.Params.LogFile = ''
# Create variables
#TODO: Speed this up
variable_list = [lp.addVar(lb=float(x.lower_bound),
ub=float(x.upper_bound),
obj=objective_sense*float(x.objective_coefficient),
name=x.id,
vtype=variable_kind_dict[x.variable_kind])
for x in cobra_model.reactions]
reaction_to_variable = dict(zip(cobra_model.reactions,
variable_list))
# Integrate new variables
lp.update()
#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