本文整理汇总了Python中pyscipopt.Model.hideOutput方法的典型用法代码示例。如果您正苦于以下问题:Python Model.hideOutput方法的具体用法?Python Model.hideOutput怎么用?Python Model.hideOutput使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyscipopt.Model
的用法示例。
在下文中一共展示了Model.hideOutput方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_event
# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import hideOutput [as 别名]
def test_event():
# create solver instance
s = Model()
s.hideOutput()
s.setPresolve(SCIP_PARAMSETTING.OFF)
eventhdlr = MyEvent()
s.includeEventhdlr(eventhdlr, "TestFirstLPevent", "python event handler to catch FIRSTLPEVENT")
# add some variables
x = s.addVar("x", obj=1.0)
y = s.addVar("y", obj=2.0)
# add some constraint
s.addCons(x + 2*y >= 5)
# solve problem
s.optimize()
# print solution
assert round(s.getVal(x)) == 5.0
assert round(s.getVal(y)) == 0.0
del s
assert 'eventinit' in calls
assert 'eventexit' in calls
assert 'eventexec' in calls
assert len(calls) == 3
示例2: _init
# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import hideOutput [as 别名]
def _init():
model = Model()
model.hideOutput()
x = model.addVar("x","B")
y = model.addVar("y","B")
z = model.addVar("z","B")
return model, x, y, z
示例3: test_instance
# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import hideOutput [as 别名]
def test_instance(instance):
s = Model()
s.hideOutput()
s.readProblem(instance)
s.optimize()
name = os.path.split(instance)[1]
if name.rsplit('.',1)[1].lower() == 'gz':
name = name.rsplit('.',2)[0]
else:
name = name.rsplit('.',1)[0]
# we do not need the solution status
primalbound = s.getObjVal()
dualbound = s.getDualbound()
# get solution data from solu file
primalsolu = primalsolutions.get(name, None)
dualsolu = dualsolutions.get(name, None)
if s.getObjectiveSense() == 'minimize':
assert relGE(primalbound, dualsolu)
assert relLE(dualbound, primalsolu)
else:
if( primalsolu == infinity ): primalsolu = -infinity
if( dualsolu == infinity ): dualsolu = -infinity
assert relLE(primalbound, dualsolu)
assert relGE(dualbound, primalsolu)
示例4: pricerredcost
# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import hideOutput [as 别名]
def pricerredcost(self):
# Retreiving the dual solutions
dualSolutions = []
for i, c in enumerate(self.data['cons']):
dualSolutions.append(self.model.getDualsolLinear(c))
# Building a MIP to solve the subproblem
subMIP = Model("CuttingStock-Sub")
# Turning off presolve
subMIP.setPresolve(SCIP_PARAMSETTING.OFF)
# Setting the verbosity level to 0
subMIP.hideOutput()
cutWidthVars = []
varNames = []
varBaseName = "CutWidth"
# Variables for the subMIP
for i in range(len(dualSolutions)):
varNames.append(varBaseName + "_" + str(i))
cutWidthVars.append(subMIP.addVar(varNames[i], vtype = "I", obj = -1.0 * dualSolutions[i]))
# Adding the knapsack constraint
knapsackCoeffs = {cutWidthVars[i] : self.data['widths'][i] for i in range(len(self.data['widths']))}
knapsackCons = subMIP.addCons(knapsackCoeffs, lhs = None, rhs = self.data['rollLength'])
# Solving the subMIP to generate the most negative reduced cost pattern
subMIP.optimize()
objval = 1 + subMIP.getObjVal()
# Adding the column to the master problem
if objval < -1e-08:
currentNumVar = len(self.data['var'])
# Creating new var; must set pricedVar to True
newVar = self.model.addVar("NewPattern_" + str(currentNumVar), vtype = "C", obj = 1.0, pricedVar = True)
# Adding the new variable to the constraints of the master problem
newPattern = []
for i, c in enumerate(self.data['cons']):
coeff = round(subMIP.getVal(cutWidthVars[i]))
self.model.addConsCoeff(c, newVar, coeff)
newPattern.append(coeff)
# Storing the new variable in the pricer data.
self.data['patterns'].append(newPattern)
self.data['var'].append(newVar)
# Freeing the subMIP
subMIP.free()
return {'result':SCIP_RESULT.SUCCESS}
示例5: test_knapsack
# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import hideOutput [as 别名]
def test_knapsack():
# create solver instance
s = Model("Knapsack")
s.hideOutput()
# setting the objective sense to maximise
s.setMaximize()
# item weights
weights = [4, 2, 6, 3, 7, 5]
# item costs
costs = [7, 2, 5, 4, 3, 4]
assert len(weights) == len(costs)
# knapsack size
knapsackSize = 15
# adding the knapsack variables
knapsackVars = []
varNames = []
varBaseName = "Item"
for i in range(len(weights)):
varNames.append(varBaseName + "_" + str(i))
knapsackVars.append(s.addVar(varNames[i], vtype='I', obj=costs[i], ub=1.0))
# adding a linear constraint for the knapsack constraint
coeffs = {knapsackVars[i]: weights[i] for i in range(len(weights))}
s.addCons(coeffs, lhs=None, rhs=knapsackSize)
# solve problem
s.optimize()
s.printStatistics()
# retrieving the best solution
solution = s.getBestSol()
# print solution
varSolutions = []
for i in range(len(weights)):
solValue = round(s.getVal(knapsackVars[i], solution))
varSolutions.append(solValue)
if solValue > 0:
print (varNames[i], "Times Selected:", solValue)
print ("\tIncluded Weight:", weights[i]*solValue, "\tItem Cost:", costs[i]*solValue)
s.releaseVar(knapsackVars[i])
includedWeight = sum([weights[i]*varSolutions[i] for i in range(len(weights))])
assert includedWeight > 0 and includedWeight <= knapsackSize
示例6: setModel
# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import hideOutput [as 别名]
def setModel(vtype="B", name=None, imax=2):
"""initialize model and its variables.
imax (int): number of operators"""
if name is None:
name = "model"
m = Model(name)
m.hideOutput()
i = 0
r = m.addVar("r", vtype)
while i < imax:
m.addVar("v%s" % i, vtype)
i += 1
return m
示例7: test_relax
# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import hideOutput [as 别名]
def test_relax():
m = Model()
m.hideOutput()
#include relaxator
m.includeRelax(SoncRelax(),'testrelaxator','Test that relaxator gets included')
#add Variables
x0 = m.addVar(vtype = "C", name = "x0")
x1 = m.addVar(vtype = "C", name = "x1")
x2 = m.addVar(vtype = "C", name = "x2")
#addCons
m.addCons(x0 >= 2)
m.addCons(x0**2 <= x1)
m.addCons(x1 * x2 >= x0)
m.setObjective(x1 + x0)
m.optimize()
print(m.getVal(x0))
assert 'relaxexec' in calls
assert len(calls) == 1
示例8: parity
# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import hideOutput [as 别名]
def parity(number):
try:
assert number == int(round(number))
m = Model()
m.hideOutput()
### variables are non-negative by default since 0 is the default lb.
### To allow for negative values, give None as lower bound
### (None means -infinity as lower bound and +infinity as upper bound)
x = m.addVar("x", vtype="I", lb=None, ub=None) #ub=None is default
n = m.addVar("n", vtype="I", lb=None)
s = m.addVar("s", vtype="B")
### CAVEAT: if number is negative, x's lb must be None
### if x is set by default as non-negative and number is negative:
### there is no feasible solution (trivial) but the program
### does not highlight which constraints conflict.
m.addCons(x==number)
m.addCons(s == x-2*n)
m.setObjective(s)
m.optimize()
assert m.getStatus() == "optimal"
if verbose:
for v in m.getVars():
print("%s %d" % (v,m.getVal(v)))
print("%d%%2 == %d?" % (m.getVal(x), m.getVal(s)))
print(m.getVal(s) == m.getVal(x)%2)
xval = m.getVal(x)
sval = m.getVal(s)
sstr = sdic[sval]
print("%d is %s" % (xval, sstr))
except (AssertionError, TypeError):
print("%s is neither even nor odd!" % number.__repr__())
示例9: solve_tsp
# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import hideOutput [as 别名]
def solve_tsp(V,c):
"""solve_tsp -- solve the traveling salesman problem
- start with assignment model
- add cuts until there are no sub-cycles
Parameters:
- V: set/list of nodes in the graph
- c[i,j]: cost for traversing edge (i,j)
Returns the optimum objective value and the list of edges used.
"""
def addcut(cut_edges):
G = networkx.Graph()
G.add_edges_from(cut_edges)
Components = list(networkx.connected_components(G))
if len(Components) == 1:
return False
model.freeTransform()
for S in Components:
model.addCons(quicksum(x[i,j] for i in S for j in S if j>i) <= len(S)-1)
print("cut: len(%s) <= %s" % (S,len(S)-1))
return True
def addcut2(cut_edges):
G = networkx.Graph()
G.add_edges_from(cut_edges)
Components = list(networkx.connected_components(G))
if len(Components) == 1:
return False
model.freeTransform()
for S in Components:
T = set(V) - set(S)
print("S:",S)
print("T:",T)
model.addCons(quicksum(x[i,j] for i in S for j in T if j>i) +
quicksum(x[i,j] for i in T for j in S if j>i) >= 2)
print("cut: %s >= 2" % "+".join([("x[%s,%s]" % (i,j)) for i in S for j in T if j>i]))
return True
# main part of the solution process:
model = Model("tsp")
model.hideOutput() # silent/verbose mode
x = {}
for i in V:
for j in V:
if j > i:
x[i,j] = model.addVar(ub=1, name="x(%s,%s)"%(i,j))
for i in V:
model.addCons(quicksum(x[j,i] for j in V if j < i) + \
quicksum(x[i,j] for j in V if j > i) == 2, "Degree(%s)"%i)
model.setObjective(quicksum(c[i,j]*x[i,j] for i in V for j in V if j > i), "minimize")
EPS = 1.e-6
isMIP = False
while True:
model.optimize()
edges = []
for (i,j) in x:
if model.getVal(x[i,j]) > EPS:
edges.append( (i,j) )
if addcut(edges) == False:
if isMIP: # integer variables, components connected: solution found
break
model.freeTransform()
for (i,j) in x: # all components connected, switch to integer model
model.chgVarType(x[i,j], "B")
isMIP = True
return model.getObjVal(),edges
示例10: Copyright
# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import hideOutput [as 别名]
"""
On a beach there are octopuses, turtles and cranes.
The total number of legs of all animals is 80, while the number of heads is 32.
What are the minimum numbers of turtles and octopuses, respectively?
Copyright (c) by Joao Pedro PEDROSO and Mikio KUBO, 2012
"""
from pyscipopt import Model
model = Model("puzzle")
x = model.addVar(vtype="I", name="octopusses")
y = model.addVar(vtype="I", name="turtles")
z = model.addVar(vtype="I", name="cranes")
# Set up constraint for number of heads
model.addCons(x + y + z == 32, name="Heads")
# Set up constraint for number of legs
model.addCons(8*x + 4*y + 2*z == 80, name="Legs")
# Set objective function
model.setObjective(x + y, "minimize")
model.hideOutput()
model.optimize()
#solution = model.getBestSol()
print("Optimal value:", model.getObjVal())
print((x.name, y.name, z.name), " = ", (model.getVal(x), model.getVal(y), model.getVal(z)))
示例11: parity
# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import hideOutput [as 别名]
def parity(number):
"""
Prints if a value is even/odd/neither per each value in a example list
This example is made for newcomers and motivated by:
- modulus is unsupported for pyscipopt.scip.Variable and int
- variables are non-integer by default
Based on this: #172#issuecomment-394644046
Args:
number: value which parity is checked
Returns:
sval: 1 if number is odd, 0 if number is even, -1 if neither
"""
sval = -1
if verbose:
print(80*"*")
try:
assert number == int(round(number))
m = Model()
m.hideOutput()
# x and n are integer, s is binary
# Irrespective to their type, variables are non-negative by default
# since 0 is the default lb. To allow for negative values, give None
# as lower bound.
# (None means -infinity as lower bound and +infinity as upper bound)
x = m.addVar("x", vtype="I", lb=None, ub=None) #ub=None is default
n = m.addVar("n", vtype="I", lb=None)
s = m.addVar("s", vtype="B")
# CAVEAT: if number is negative, x's lower bound must be None
# if x is set by default as non-negative and number is negative:
# there is no feasible solution (trivial) but the program
# does not highlight which constraints conflict.
m.addCons(x==number)
# minimize the difference between the number and twice a natural number
m.addCons(s == x-2*n)
m.setObjective(s)
m.optimize()
assert m.getStatus() == "optimal"
boolmod = m.getVal(s) == m.getVal(x)%2
if verbose:
for v in m.getVars():
print("%*s: %d" % (fmtlen, v,m.getVal(v)))
print("%*d%%2 == %d?" % (fmtlen, m.getVal(x), m.getVal(s)))
print("%*s" % (fmtlen, boolmod))
xval = m.getVal(x)
sval = m.getVal(s)
sstr = sdic[sval]
print("%*d is %s" % (fmtlen, xval, sstr))
except (AssertionError, TypeError):
print("%*s is neither even nor odd!" % (fmtlen, number.__repr__()))
finally:
if verbose:
print(80*"*")
print("")
return sval
示例12: solveCuttingStock
# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import hideOutput [as 别名]
def solveCuttingStock(w,q,B):
"""solveCuttingStock: use column generation (Gilmore-Gomory approach).
Parameters:
- w: list of item's widths
- q: number of items of a width
- B: bin/roll capacity
Returns a solution: list of lists, each of which with the cuts of a roll.
"""
t = [] # patterns
m = len(w)
# Generate initial patterns with one size for each item width
for (i,width) in enumerate(w):
pat = [0]*m # vector of number of orders to be packed into one roll (bin)
pat[i] = int(B/width)
t.append(pat)
# if LOG:
# print "sizes of orders=",w
# print "quantities of orders=",q
# print "roll size=",B
# print "initial patterns",t
K = len(t)
master = Model("master LP") # master LP problem
x = {}
for k in range(K):
x[k] = master.addVar(vtype="I", name="x(%s)"%k)
orders = {}
for i in range(m):
orders[i] = master.addCons(
quicksum(t[k][i]*x[k] for k in range(K) if t[k][i] > 0) >= q[i], "Order(%s)"%i)
master.setObjective(quicksum(x[k] for k in range(K)), "minimize")
# master.Params.OutputFlag = 0 # silent mode
# iter = 0
while True:
# print "current patterns:"
# for ti in t:
# print ti
# print
# iter += 1
relax = master.relax()
relax.optimize()
pi = [relax.getDualsolLinear(c) for c in relax.getConss()] # keep dual variables
knapsack = Model("KP") # knapsack sub-problem
knapsack.setMaximize # maximize
y = {}
for i in range(m):
y[i] = knapsack.addVar(lb=0, ub=q[i], vtype="I", name="y(%s)"%i)
knapsack.addCons(quicksum(w[i]*y[i] for i in range(m)) <= B, "Width")
knapsack.setObjective(quicksum(pi[i]*y[i] for i in range(m)), "maximize")
knapsack.hideOutput() # silent mode
knapsack.optimize()
# if LOG:
# print "objective of knapsack problem:", knapsack.ObjVal
if knapsack.getObjVal() < 1+EPS: # break if no more columns
break
pat = [int(y[i].X+0.5) for i in y] # new pattern
t.append(pat)
# if LOG:
# print "shadow prices and new pattern:"
# for (i,d) in enumerate(pi):
# print "\t%5s%12s%7s" % (i,d,pat[i])
# print
# add new column to the master problem
col = Column()
for i in range(m):
if t[K][i] > 0:
col.addTerms(t[K][i], orders[i])
x[K] = master.addVar(obj=1, vtype="I", name="x(%s)"%K, column=col)
# master.write("MP" + str(iter) + ".lp")
K += 1
# Finally, solve the IP
# if LOG:
# master.Params.OutputFlag = 1 # verbose mode
master.optimize()
# if LOG:
# print
# print "final solution (integer master problem): objective =", master.ObjVal
# print "patterns:"
# for k in x:
# if x[k].X > EPS:
#.........这里部分代码省略.........
示例13: range
# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import hideOutput [as 别名]
for j in range(9):
m.addCons(quicksum(x[i,j,k] for k in range(9)) == 1)
# set up row and column constraints
for ind in range(9):
for k in range(9):
m.addCons(quicksum(x[ind,j,k] for j in range(9)) == 1)
m.addCons(quicksum(x[i,ind,k] for i in range(9)) == 1)
# set up square constraints
for row in range(3):
for col in range(3):
for k in range(9):
m.addCons(quicksum(x[i+3*row, j+3*col, k] for i in range(3) for j in range(3)) == 1)
m.hideOutput()
m.optimize()
if m.getStatus() != 'optimal':
print('Sudoku is not feasible!')
else:
print('\nSudoku solution:\n')
sol = {}
for i in range(9):
out = ''
for j in range(9):
for k in range(9):
if m.getVal(x[i,j,k]) == 1:
sol[i,j] = k+1
out += str(sol[i,j]) + ' '
print(out)
示例14: solve_vrp
# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import hideOutput [as 别名]
def solve_vrp(V,c,m,q,Q):
"""solve_vrp -- solve the vehicle routing problem.
- start with assignment model (depot has a special status)
- add cuts until all components of the graph are connected
Parameters:
- V: set/list of nodes in the graph
- c[i,j]: cost for traversing edge (i,j)
- m: number of vehicles available
- q[i]: demand for customer i
- Q: vehicle capacity
Returns the optimum objective value and the list of edges used.
"""
def addcut(cut_edges):
"""addcut: add constraint to eliminate infeasible solutions
Parameters:
- cut_edges: list of edges in the current solution, except connections to depot
Returns True if a cut was added, False otherwise
"""
G = networkx.Graph()
G.add_edges_from(cut_edges)
Components = networkx.connected_components(G)
cut = False
for S in Components:
S_card = len(S)
q_sum = sum(q[i] for i in S)
NS = int(math.ceil(float(q_sum)/Q))
S_edges = [(i,j) for i in S for j in S if i<j and (i,j) in cut_edges]
if S_card >= 3 and (len(S_edges) >= S_card or NS > 1):
add = model.addCons(quicksum(x[i,j] for i in S for j in S if j > i) <= S_card-NS)
cut = True
return cut
model = Model("vrp")
x = {}
for i in V:
for j in V:
if j > i and i == V[0]: # depot
x[i,j] = model.addVar(ub=2, vtype="I", name="x(%s,%s)"%(i,j))
elif j > i:
x[i,j] = model.addVar(ub=1, vtype="I", name="x(%s,%s)"%(i,j))
model.addCons(quicksum(x[V[0],j] for j in V[1:]) == 2*m, "DegreeDepot")
for i in V[1:]:
model.addCons(quicksum(x[j,i] for j in V if j < i) +
quicksum(x[i,j] for j in V if j > i) == 2, "Degree(%s)"%i)
model.setObjective(quicksum(c[i,j]*x[i,j] for i in V for j in V if j>i), "minimize")
model.hideOutput()
EPS = 1.e-6
while True:
model.optimize()
edges = []
for (i,j) in x:
if model.getVal(x[i,j]) > EPS:
if i != V[0] and j != V[0]:
edges.append((i,j))
if addcut(edges) == False:
break
return model.getObjVal(),edges
示例15: getColumnFromMIP
# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import hideOutput [as 别名]
def getColumnFromMIP(self, timeLimit):
def getPatternFromSolution(subMIP):
edges = []
for x in subMIP.getVars():
if "x" in x.name:
if subMIP.getVal(x) > 0.99:
i, j = x.name.split("_")[1:]
edges.append((int(i), int(j)))
return edges
# Storing the values of the dual solutions:
dualSols = {}
for c in self.cons:
i = int(c.name.split("_")[-1].strip())
dualSols[i] = self.model.getDualsolLinear(c)
# Model for the sub-problem:
subMIP = Model("VRP-Sub")
subMIP.setPresolve(SCIP_PARAMSETTING.OFF)
subMIP.setMinimize
subMIP.setRealParam("limits/time", timeLimit)
# Binary variables x_ij indicating whether the vehicle
# traverses edge (i, j)
x = {}
for i in self.data.nodes:
for j in self.data.nodes:
if i != j:
x[i, j] = subMIP.addVar(vtype="B", obj=self.data.costs[i, j] - (dualSols[i] if i in self.clientNodes else 0), name="x_%d_%d" % (i, j))
# Non negative variables u_i indicating the demand served up to node i:
u = {}
for i in self.data.nodes:
u[i] = subMIP.addVar(vtype="C", lb=0, ub=self.data.cap, obj=0.0, name="u_%d" % i)
for j in self.clientNodes:
subMIP.addCons(quicksum(x[i, j] for i in self.data.nodes if i != j) <= 1)
for h in self.clientNodes:
subMIP.addCons(quicksum(x[i, h] for i in self.data.nodes if i != h) ==
quicksum(x[h, i] for i in self.data.nodes if i != h))
for i in self.data.nodes:
for j in self.clientNodes:
if i != j:
subMIP.addCons(u[j] >= u[i] + self.data.demands[j]*x[i, j] - self.data.cap*(1 - x[i, j]))
subMIP.addCons(quicksum(x[self.data.depot, j] for j in self.clientNodes) <= 1)
subMIP.hideOutput()
subMIP.optimize()
mipSol = subMIP.getBestSol()
obj = subMIP.getSolObjVal(mipSol)
pattern = getPatternFromSolution(subMIP)
return obj, pattern