当前位置: 首页>>代码示例>>Python>>正文


Python Model.optimize方法代码示例

本文整理汇总了Python中pyscipopt.Model.optimize方法的典型用法代码示例。如果您正苦于以下问题:Python Model.optimize方法的具体用法?Python Model.optimize怎么用?Python Model.optimize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pyscipopt.Model的用法示例。


在下文中一共展示了Model.optimize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_circle

# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import optimize [as 别名]
def test_circle():
    points =[
            (2.802686, 1.398947),
            (4.719673, 4.792101),
            (1.407758, 7.769566),
            (2.253320, 2.373641),
            (8.583144, 9.769102),
            (3.022725, 5.470335),
            (5.791380, 1.214782),
            (8.304504, 8.196392),
            (9.812677, 5.284600),
            (9.445761, 9.541600)]

    m = Model()
    a = m.addVar('a', lb=None)
    b = m.addVar('b', ub=None)
    r = m.addVar('r')

    # minimize radius
    m.setObjective(r, 'minimize')

    for i,p in enumerate(points):
        # NOTE: SCIP will not identify this as SOC constraints!
        m.addCons( sqrt((a - p[0])**2 + (b - p[1])**2) <= r, name = 'point_%d'%i)

    m.optimize()

    bestsol = m.getBestSol()
    assert abs(m.getSolVal(bestsol, r) - 5.2543) < 1.0e-3
    assert abs(m.getSolVal(bestsol, a) - 6.1242) < 1.0e-3
    assert abs(m.getSolVal(bestsol, b) - 5.4702) < 1.0e-3
开发者ID:SCIP-Interfaces,项目名称:PySCIPOpt,代码行数:33,代码来源:test_nonlinear.py

示例2: test_lpi

# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import optimize [as 别名]
def test_lpi():
    # create LP instance
    myLP = LP()

    myLP.addRow(entries = [(0,1),(1,2)] ,lhs = 5)
    lhs, rhs = myLP.getSides()
    assert lhs[0] == 5.0
    assert rhs[0] == myLP.infinity()

    assert(myLP.ncols() == 2)
    myLP.chgObj(0, 1.0)
    myLP.chgObj(1, 2.0)

    solval = myLP.solve()
    # create solver instance

    s = Model()
    # 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()

    # check solution
    assert round(s.getVal(x)) == 5.0
    assert round(s.getVal(y)) == 0.0

    assert round(s.getObjVal() == solval)
开发者ID:fserra,项目名称:PySCIPOpt,代码行数:32,代码来源:test_lp.py

示例3: transp

# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import optimize [as 别名]
def transp(I,J,c,d,M):
    """transp -- model for solving the transportation problem
    Parameters:
        I - set of customers
        J - set of facilities
        c[i,j] - unit transportation cost on arc (i,j)
        d[i] - demand at node i
        M[j] - capacity
    Returns a model, ready to be solved.
    """

    model = Model("transportation")

    # Create variables
    x = {}

    for i in I:
        for j in J:
            x[i,j] = model.addVar(vtype="C", name="x(%s,%s)" % (i, j))

    # Demand constraints
    for i in I:
        model.addCons(quicksum(x[i,j] for j in J if (i,j) in x) == d[i], name="Demand(%s)" % i)

    # Capacity constraints
    for j in J:
        model.addCons(quicksum(x[i,j] for i in I if (i,j) in x) <= M[j], name="Capacity(%s)" % j)

    # Objective
    model.setObjective(quicksum(c[i,j]*x[i,j]  for (i,j) in x), "minimize")

    model.optimize()

    model.data = x
    return model
开发者ID:fserra,项目名称:PySCIPOpt,代码行数:37,代码来源:transp.py

示例4: test_event

# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import optimize [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
开发者ID:SCIP-Interfaces,项目名称:PySCIPOpt,代码行数:29,代码来源:test_event.py

示例5: test_instance

# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import optimize [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)
开发者ID:fserra,项目名称:PySCIPOpt,代码行数:29,代码来源:test_short.py

示例6: pricerredcost

# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import optimize [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}
开发者ID:gorhan,项目名称:LFOS,代码行数:59,代码来源:test_pricer.py

示例7: solve

# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import optimize [as 别名]
    def solve(self, integer=False):
        '''
        By default we solve a linear version of the column generation.
        If integer is True than we solve the problem of finding the best
        routes to be used without column generation.
        '''
        self.integer = integer
        if self.patterns is None:
            self.genInitialPatterns()

        # Creating master Model:
        master = Model("Master problem")

        # Creating pricer:
        if not integer:
            master.setPresolve(SCIP_PARAMSETTING.OFF)

        # Populating master model.
        # Binary variables z_r indicating whether
        # pattern r is used in the solution:
        z = {}

        for i, _ in enumerate(self.patterns):
            z[i] = master.addVar(vtype="B" if integer else "C",
                                 lb=0.0, ub=1.0, name="z_%d" % i)

        # Set objective:
        master.setObjective(quicksum(self.patCost(p)*z[i] for i, p in enumerate(self.patterns)),
                            "minimize")

        clientCons = [None]*len(self.clientNodes)
        
        for i, c in enumerate(self.clientNodes):
            cons = master.addCons(
            quicksum(self.isClientVisited(c, p)*z[i] for i, p in enumerate(self.patterns)) == 1,
                "Consumer_%d" % c,
                separate=False, modifiable=True)

            clientCons[i] = cons

        if not integer:
            pricer = VRPpricer(z, clientCons, self.data, self.patterns,
                               self.data.costs, self.isClientVisited,
                               self.patCost, self.maxPatterns)

            master.includePricer(pricer, "VRP pricer", "Identifying new routes")

            self.pricer = pricer

        if integer:
            print("Finding the best patterns among:")
            for p in self.patterns:
                print(p)

        self.master = master  # Save master model.
        
        master.optimize()
开发者ID:pedrocastellucci,项目名称:playground,代码行数:59,代码来源:vrp_scip_cg.py

示例8: test_model

# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import optimize [as 别名]
def test_model():
    # create solver instance
    s = Model()

    # add some variables
    x = s.addVar("x", vtype = 'C', obj = 1.0)
    y = s.addVar("y", vtype = 'C', obj = 2.0)

    assert x.getObj() == 1.0
    assert y.getObj() == 2.0

    s.setObjective(4.0 * y + 10.5, clear = False)
    assert x.getObj() == 1.0
    assert y.getObj() == 4.0
    assert s.getObjoffset() == 10.5

    # add some constraint
    c = s.addCons(x + 2 * y >= 1.0)
    assert c.isLinear()
    s.chgLhs(c, 5.0)
    s.chgRhs(c, 6.0)

    assert s.getLhs(c) == 5.0
    assert s.getRhs(c) == 6.0

    # solve problem
    s.optimize()

    solution = s.getBestSol()

    # print solution
    assert (s.getVal(x) == s.getSolVal(solution, x))
    assert (s.getVal(y) == s.getSolVal(solution, y))
    assert round(s.getVal(x)) == 5.0
    assert round(s.getVal(y)) == 0.0
    assert s.getSlack(c, solution) == 0.0
    assert s.getSlack(c, solution, 'lhs') == 0.0
    assert s.getSlack(c, solution, 'rhs') == 1.0
    assert s.getActivity(c, solution) == 5.0

    s.writeProblem('model')
    s.writeProblem('model.lp')

    s.freeProb()
    s = Model()
    x = s.addVar("x", vtype = 'C', obj = 1.0)
    y = s.addVar("y", vtype = 'C', obj = 2.0)
    c = s.addCons(x + 2 * y <= 1.0)
    s.setMaximize()

    s.delCons(c)

    s.optimize()

    assert s.getStatus() == 'unbounded'
开发者ID:SCIP-Interfaces,项目名称:PySCIPOpt,代码行数:57,代码来源:test_model.py

示例9: test_string_poly

# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import optimize [as 别名]
def test_string_poly():
    PI = 3.141592653589793238462643
    NWIRES = 11
    DIAMETERS = [0.207, 0.225, 0.244, 0.263, 0.283, 0.307, 0.331, 0.362, 0.394, 0.4375, 0.500]
    PRELOAD = 300.0
    MAXWORKLOAD = 1000.0
    MAXDEFLECT = 6.0
    DEFLECTPRELOAD = 1.25
    MAXFREELEN = 14.0
    MAXCOILDIAM = 3.0
    MAXSHEARSTRESS = 189000.0
    SHEARMOD = 11500000.0

    m = Model()
    coil = m.addVar('coildiam')
    wire = m.addVar('wirediam')
    defl = m.addVar('deflection', lb=DEFLECTPRELOAD / (MAXWORKLOAD - PRELOAD), ub=MAXDEFLECT / PRELOAD)
    ncoils = m.addVar('ncoils', vtype='I')
    const1 = m.addVar('const1')
    const2 = m.addVar('const2')
    volume = m.addVar('volume')

    y = [m.addVar('wire%d' % i, vtype='B') for i in range(NWIRES)]

    obj = 1.0 * volume
    m.setObjective(obj, 'minimize')

    m.addCons(PI/2*(ncoils + 2)*coil*wire**2 - volume == 0, name='voldef')

    # defconst1: coil / wire - const1 == 0.0
    m.addCons(coil - const1*wire == 0, name='defconst1')

    # defconst2: (4.0*const1 - 1.0) / (4.0*const1 - 4.0) + 0.615 / const1 - const2 == 0.0
    d1 = (4.0*const1 - 4.0)
    d2 = const1
    m.addCons((4.0*const1 - 1.0)*d2 + 0.615*d1 - const2*d1*d2 == 0, name='defconst2')

    m.addCons(8.0*MAXWORKLOAD/PI*const1*const2 - MAXSHEARSTRESS*wire**2 <= 0.0, name='shear')

    # defdefl: 8.0/shearmod * ncoils * const1^3 / wire - defl == 0.0
    m.addCons(8.0/SHEARMOD*ncoils*const1**3 - defl*wire == 0.0, name="defdefl")

    m.addCons(MAXWORKLOAD*defl + 1.05*ncoils*wire + 2.1*wire <= MAXFREELEN, name='freel')

    m.addCons(coil + wire <= MAXCOILDIAM, name='coilwidth')

    m.addCons(quicksum(c*v for (c,v) in zip(DIAMETERS, y)) - wire == 0, name='defwire')

    m.addCons(quicksum(y) == 1, name='selectwire')

    m.optimize()

    assert abs(m.getPrimalbound() - 1.6924910128) < 1.0e-5
开发者ID:SCIP-Interfaces,项目名称:PySCIPOpt,代码行数:55,代码来源:test_nonlinear.py

示例10: test_knapsack

# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import optimize [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
开发者ID:gorhan,项目名称:LFOS,代码行数:54,代码来源:test_knapsack.py

示例11: test_niceqcqp

# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import optimize [as 别名]
def test_niceqcqp():
    s = Model()

    x = s.addVar("x")
    y = s.addVar("y")
    s.addCons(x*x + y*y <= 2)
    s.setObjective(x + y, sense='maximize')

    s.optimize()

    assert round(s.getVal(x)) == 1.0
    assert round(s.getVal(y)) == 1.0

    s.free()
开发者ID:gorhan,项目名称:LFOS,代码行数:16,代码来源:test_quadcons.py

示例12: test_niceqp

# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import optimize [as 别名]
def test_niceqp():
    s = Model()

    x = s.addVar("x")
    y = s.addVar("y")
    s.addCons(x >= 2)
    s.addCons(x*x <= y)
    s.setObjective(y, sense='minimize')

    s.optimize()

    assert round(s.getVal(x)) == 2.0
    assert round(s.getVal(y)) == 4.0

    s.free()
开发者ID:gorhan,项目名称:LFOS,代码行数:17,代码来源:test_quadcons.py

示例13: test_copy

# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import optimize [as 别名]
def test_copy():
    # create solver instance
    s = Model()

    # add some variables
    x = s.addVar("x", vtype = 'C', obj = 1.0)
    y = s.addVar("y", vtype = 'C', obj = 2.0)
    s.setObjective(4.0 * y, clear = False)

    c = s.addCons(x + 2 * y >= 1.0)

    s2 = Model(sourceModel=s)

    # solve problems
    s.optimize()
    s2.optimize()

    assert s.getObjVal() == s2.getObjVal()
开发者ID:SCIP-Interfaces,项目名称:PySCIPOpt,代码行数:20,代码来源:test_copy.py

示例14: test_nicelp

# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import optimize [as 别名]
def test_nicelp():
    # create solver instance
    s = Model()

    # 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

    s.free()
开发者ID:gorhan,项目名称:LFOS,代码行数:21,代码来源:test_simplelp.py

示例15: test_heur

# 需要导入模块: from pyscipopt import Model [as 别名]
# 或者: from pyscipopt.Model import optimize [as 别名]
def test_heur():
    # create solver instance
    s = Model()
    heuristic = MyHeur()
    s.includeHeur(heuristic, "PyHeur", "custom heuristic implemented in python", "Y", timingmask=SCIP_HEURTIMING.BEFORENODE)
    s.setPresolve(SCIP_PARAMSETTING.OFF)

    # 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
开发者ID:SCIP-Interfaces,项目名称:PySCIPOpt,代码行数:22,代码来源:test_heur.py


注:本文中的pyscipopt.Model.optimize方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。