本文整理汇总了Python中gurobipy.Model.getVarByName方法的典型用法代码示例。如果您正苦于以下问题:Python Model.getVarByName方法的具体用法?Python Model.getVarByName怎么用?Python Model.getVarByName使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类gurobipy.Model
的用法示例。
在下文中一共展示了Model.getVarByName方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: find_feasible_start
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import getVarByName [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
示例2: GurobiSolver
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import getVarByName [as 别名]
class GurobiSolver(Solver):
""" Implements the solver interface using gurobipy. """
def __init__(self):
Solver.__init__(self)
self.problem = GurobiModel()
def __getstate__(self):
tmp_file = tempfile.mktemp(suffix=".lp")
self.problem.update()
self.problem.write(tmp_file)
cplex_form = open(tmp_file).read()
repr_dict = {'var_ids': self.var_ids, 'constr_ids': self.constr_ids, 'cplex_form': cplex_form}
return repr_dict
def __setstate__(self, repr_dict):
tmp_file = tempfile.mktemp(suffix=".lp")
open(tmp_file, 'w').write(repr_dict['cplex_form'])
self.problem = read(tmp_file)
self.var_ids = repr_dict['var_ids']
self.constr_ids = repr_dict['constr_ids']
def add_variable(self, var_id, lb=None, ub=None, vartype=VarType.CONTINUOUS, persistent=True, update_problem=True):
""" Add a variable to the current problem.
Arguments:
var_id : str -- variable identifier
lb : float -- lower bound
ub : float -- upper bound
vartype : VarType -- variable type (default: CONTINUOUS)
persistent : bool -- if the variable should be reused for multiple calls (default: true)
update_problem : bool -- update problem immediately (default: True)
"""
lb = lb if lb is not None else -GRB.INFINITY
ub = ub if ub is not None else GRB.INFINITY
map_types = {VarType.BINARY: GRB.BINARY,
VarType.INTEGER: GRB.INTEGER,
VarType.CONTINUOUS: GRB.CONTINUOUS}
if var_id in self.var_ids:
var = self.problem.getVarByName(var_id)
var.setAttr('lb', lb)
var.setAttr('ub', ub)
var.setAttr('vtype', map_types[vartype])
else:
self.problem.addVar(name=var_id, lb=lb, ub=ub, vtype=map_types[vartype])
self.var_ids.append(var_id)
if not persistent:
self.temp_vars.add(var_id)
if update_problem:
self.problem.update()
def add_constraint(self, constr_id, lhs, sense='=', rhs=0, persistent=True, update_problem=True):
""" Add a variable to the current problem.
Arguments:
constr_id : str -- constraint identifier
lhs : list [of (str, float)] -- variables and respective coefficients
sense : {'<', '=', '>'} -- default '='
rhs : float -- right-hand side of equation (default: 0)
persistent : bool -- if the variable should be reused for multiple calls (default: True)
update_problem : bool -- update problem immediately (default: True)
"""
grb_sense = {'=': GRB.EQUAL,
'<': GRB.LESS_EQUAL,
'>': GRB.GREATER_EQUAL}
if constr_id in self.constr_ids:
constr = self.problem.getConstrByName(constr_id)
self.problem.remove(constr)
expr = quicksum([coeff * self.problem.getVarByName(r_id) for r_id, coeff in lhs if coeff])
self.problem.addConstr(expr, grb_sense[sense], rhs, constr_id)
self.constr_ids.append(constr_id)
if not persistent:
self.temp_constrs.add(constr_id)
if update_problem:
self.problem.update()
def remove_variable(self, var_id):
""" Remove a variable from the current problem.
Arguments:
var_id : str -- variable identifier
"""
if var_id in self.var_ids:
self.problem.remove(self.problem.getVarByName(var_id))
self.var_ids.remove(var_id)
def remove_constraint(self, constr_id):
""" Remove a constraint from the current problem.
#.........这里部分代码省略.........
示例3: SQModel
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import getVarByName [as 别名]
class SQModel(object):
'''
classdocs
'''
# Private model object
__model = []
# Private model variables
__z0 = {}
__z = {}
__q = {}
# Private model parameters
__BackupCapacity = {}
__bBackupLink = {}
__links = []
__nodes = []
__capacity = []
__epsilon = 1
__impSample = {}
__N = 1
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)
#.........这里部分代码省略.........
示例4: _objective_function_for_delta_weight
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import getVarByName [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())
#.........这里部分代码省略.........
示例5: _objective_function_for_delta_weight
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import getVarByName [as 别名]
def _objective_function_for_delta_weight(D, delta_weight):
m = Model("model_for_supplier_assignment")
x = {}
q = {}
for (r, s, p) in D.supplier_project_shipping:
# i resource, j supplier, k project
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 sorted([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
# constraint 20(3)
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:
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))
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
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
expr = LinExpr()
for (i, j, k) in q:
expr = expr + D.c[i, j, k] * q[i, j, k]
m.addConstr(expr, GRB.LESS_EQUAL, D.B, name="constraint_7")
# constraint 8
for j in range(D.project_n):
p = D.project_list[j]
project_resources = sorted([r for (r, p_) in D.resource_project_demand.keys() if p_ == p])
for r in project_resources:
suppliers = D.resource_supplier_list[r]
# print(list(D.supplier_project_shipping.keys())[:10])
# print(D.supplier_project_shipping['NK0g77', 'S1671', 'P1'])
# print(list(x.keys())[:10])
# print(x['NK0g77', 'S1671', 'P1'])
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):
for r in sorted([r for (r, p_) in D.resource_project_demand.keys() if p_ == p]):
expr.add(delta_weight[_delta_project_idx[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()
print(m.Status)
X_ = {}
for (i, j, k) in D.supplier_project_shipping:
v = m.getVarByName("x_%s_%s_%s" % (i, j, k))
print(v)
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
return -_objective_function_for_tardiness(X_, AT_, D),
示例6: gurobi_solve_qp
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import getVarByName [as 别名]
def gurobi_solve_qp(P, q, G=None, h=None, A=None, b=None, initvals=None):
"""
Solve a Quadratic Program defined as:
minimize
(1/2) * x.T * P * x + q.T * x
subject to
G * x <= h
A * x == b
using Gurobi <http://www.gurobi.com/>.
Parameters
----------
P : array, shape=(n, n)
Primal quadratic cost matrix.
q : array, shape=(n,)
Primal quadratic cost vector.
G : array, shape=(m, n)
Linear inequality constraint matrix.
h : array, shape=(m,)
Linear inequality constraint vector.
A : array, shape=(meq, n), optional
Linear equality constraint matrix.
b : array, shape=(meq,), optional
Linear equality constraint vector.
initvals : array, shape=(n,), optional
Warm-start guess vector (not used).
Returns
-------
x : array, shape=(n,)
Solution to the QP, if found, otherwise ``None``.
"""
if initvals is not None:
print("Gurobi: note that warm-start values are ignored by wrapper")
n = P.shape[1]
model = Model()
x = {
i: model.addVar(
vtype=GRB.CONTINUOUS,
name='x_%d' % i,
lb=-GRB.INFINITY,
ub=+GRB.INFINITY)
for i in xrange(n)
}
model.update() # integrate new variables
# minimize
# 1/2 x.T * P * x + q * x
obj = QuadExpr()
rows, cols = P.nonzero()
for i, j in zip(rows, cols):
obj += 0.5 * x[i] * P[i, j] * x[j]
for i in xrange(n):
obj += q[i] * x[i]
model.setObjective(obj, GRB.MINIMIZE)
# subject to
# G * x <= h
if G is not None:
G_nonzero_rows = get_nonzero_rows(G)
for i, row in G_nonzero_rows.iteritems():
model.addConstr(quicksum(G[i, j] * x[j] for j in row) <= h[i])
# subject to
# A * x == b
if A is not None:
A_nonzero_rows = get_nonzero_rows(A)
for i, row in A_nonzero_rows.iteritems():
model.addConstr(quicksum(A[i, j] * x[j] for j in row) == b[i])
model.optimize()
a = empty(n)
for i in xrange(n):
a[i] = model.getVarByName('x_%d' % i).x
return a
示例7: schedule_rooms_in_period_raumsperren
# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import getVarByName [as 别名]
def schedule_rooms_in_period_raumsperren(exams_to_schedule, period, data, verbose = False):
#print period
'''
schedule_rooms needs to be called for every single period
schedule_rooms tries to schedule a given set of exams which are written in the same period on the rooms avialable for the given period
'''
# TODO: Initialise using meaningful values
# ...
#verbose = True
n = len(exams_to_schedule)
r = data['r']
c = data['c']
T = data['T']
s = data['s']
z = {}
exam_rooms_index = data['exam_rooms_index']
model = Model("RoomPlanner")
# z[i,k] = if exam i is written in room k
for i in exams_to_schedule:
for k in exam_rooms_index[i]:
if period == -1 or T[k][period] == 1:
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:
model.addConstr( quicksum([ z[i, k] * c[k] for k in range(r) if period == -1 or T[k][period] == 1 ]) >= s[i], "c1")
# c2: only one exam per room
for k in range(r):
if period == -1 or T[k][period] == 1:
model.addConstr( quicksum([ z[i, k] for i in exams_to_schedule ]) <= 1, "c2")
# objective: minimize number of used rooms
obj1 = quicksum([ z[i,k] for i in exams_to_schedule for k in exam_rooms_index[i] if T[k][period] == 1 ])
model.setObjective( obj1, GRB.MINIMIZE)
if not verbose:
model.params.OutputFlag = 0
model.optimize()
# return best room schedule
try:
z=defaultdict(int)
for i in exams_to_schedule:
for k in exam_rooms_index[i]:
if period == -1 or T[k][period] == 1:
v = model.getVarByName("z_%s_%s" % (i,k))
z[i,k] = v.x
return z
except GurobiError:
return None