Exemplo n.º 1
0
def main():
    """Solve 'wolseyR2network.mod' and 'wolseyR1gamma.mod'."""
    from pympl import PyMPL, Tools, glpkutils
    os.chdir(os.path.dirname(__file__) or os.curdir)

    a, a0 = [65, 64, 41, 22, 13, 12, 8, 2], 80
    aS = abs(2 * a0 + 1 - sum(a))
    if a0 < (sum(a) - 1) // 2:
        a0 += aS
    a.append(aS)

    print("self-dual:", a, a0)

    m = len(a)
    W = [a0] + [1] * len(a)
    w = [[a[i]] + [1 if j == i else 0 for j in range(m)] for i in range(m)]
    labels = [i + 1 for i in range(m)]
    bounds = [1 if w[i] <= W else 0 for i in range(m)]

    # wolseyR2network:

    print("-" * 10)
    print("Primal:")

    mod_in = "wolseyR2network.mod"
    mod_out = "tmp/wolseyR2network.out.mod"
    parser = PyMPL(locals_=locals(), globals_=globals())
    parser.parse(mod_in, mod_out)
    lp_out = "tmp/wolseyR2network.lp"
    glpkutils.mod2lp(mod_out, lp_out, verbose=False)
    out, varvalues = Tools.script("glpk_wrapper.sh", lp_out, verbose=False)
    print("")
    print("varvalues:",
          [(k, v)
           for k, v in sorted(varvalues.items()) if not k.startswith("_")])
    print("")

    # check the solution objective value:
    assert abs(varvalues["Z0"] - 9) < 1e-5

    # wolseyR1gamma:

    print("-" * 10)
    print("wolseyR1gamma:")

    mod_in = "wolseyR1gamma.mod"
    mod_out = "tmp/wolseyR1gamma.out.mod"
    parser = PyMPL(locals_=locals(), globals_=globals())
    parser.parse(mod_in, mod_out)
    lp_out = "tmp/wolseyR1gamma.mod.lp"
    glpkutils.mod2lp(mod_out, lp_out, verbose=False)
    out, varvalues = Tools.script("glpk_wrapper.sh", lp_out, verbose=False)
    print("")
    print("varvalues:",
          [(k, v)
           for k, v in sorted(varvalues.items()) if not k.startswith("_")])
    print("")

    # check the solution objective value:
    assert abs(varvalues['theta(T)'] - 9) < 1e-5
Exemplo n.º 2
0
def main():
    """Solve 'tsp_gurobi.mod' using a cut generator."""
    from pympl import PyMPL, Tools, glpkutils
    from gurobipy import GRB, LinExpr, read
    os.chdir(os.path.dirname(__file__) or os.curdir)

    mod_in = "tsp_gurobi.mod"
    mod_out = "tmp/tsp_gurobi.out.mod"
    graph_size = "large"
    parser = PyMPL(locals_=locals(), globals_=globals())
    parser.parse(mod_in, mod_out)

    lp_out = "tmp/tsp_gurobi.lp"
    glpkutils.mod2lp(mod_out, lp_out, verbose=True)

    m = read(lp_out)
    m.params.LazyConstraints = 1
    m.params.MIPGap = 0
    m.params.MIPGapAbs = 1-1e-5

    def sep_callback(model, where):
        """Gurobi callback function."""
        if where == GRB.callback.MIPNODE:
            model._cnt += 1
            if model._cnt - model._lastrun < 10:
                return
            model._lastrun = model._cnt

            # check if the submodel was used
            assert "ATSP_MTZ" in parser.submodels()

            # calls the separate method to compute valid inequalities
            cuts = parser["ATSP_MTZ"].separate(
                lambda name: model.cbGetNodeRel(model.getVarByName(name))
            )

            # add the cuts to the model
            if len(cuts) > 0:
                print("add {0} {1}".format(
                    len(cuts), "cuts" if len(cuts) > 1 else "cut"
                ))
            for cut in cuts:
                lincomb, sign, rhs = cut
                expr = LinExpr([
                    (coef, model.getVarByName(var))
                    for var, coef in lincomb
                ])
                if sign[0] == ">":
                    model.cbLazy(expr >= rhs)
                elif sign[0] == "<":
                    model.cbLazy(expr <= rhs)
                else:
                    model.cbLazy(expr == rhs)

    m._cnt = 0
    m._lastrun = float("-inf")
    m.optimize(sep_callback)

    print("Objective:", m.ObjVal)
Exemplo n.º 3
0
def test_eval():
    """Test ${expression}$ calls."""
    parser = PyMPL()
    parser.input = """
    s.t. con1: x + y <= ${abs((2**7)//5-135)}$ * z;
    var x1, >= ${2+6}$, <= ${10*5}$;
    """
    parser.parse(comment_cmds=False)
    assert "s.t. con1: x + y <= 110 * z;" in parser.output
    assert "var x1, >= 8, <= 50;" in parser.output
Exemplo n.º 4
0
def test_stmt():
    """Test $STMT{stmt} calls."""
    parser = PyMPL()
    parser.input = """
    $STMT{"s.t. con1: x + y <= {0} * z;".format(abs((2**7)//5-135))};
    $EXEC{stmt = "s.t. {0}: x >= 10;".format("test")};
    $STMT{stmt};
    """
    parser.parse(comment_cmds=False)
    assert "s.t. con1: x + y <= 110 * z;" in parser.output
    assert "s.t. test: x >= 10;" in parser.output
Exemplo n.º 5
0
def parse(mod_in, prob, relax, xform, test_seed):
    """Parse LS-LIB test files."""
    from pympl import PyMPL, glpkutils
    os.chdir(os.path.dirname(__file__) or os.curdir)

    mod_out = "tmp/lstlib_test.out.mod"
    TEST_PROB = prob  # pass the problem name to the model
    parser = PyMPL(locals_=locals(), globals_=globals())
    parser.parse(mod_in, mod_out)

    lp_out = "tmp/lslib_test.out.lp"
    glpkutils.mod2lp(mod_out, lp_out, verbose=False)
    return lp_out
Exemplo n.º 6
0
def test_set():
    """Test $SET[name]{values} calls."""
    parser = PyMPL()
    parser.input = """
    $SET[A]{range(5)};
    $SET[B]{zip(range(5),range(5))};
    $SET[^C]{range(5)};
    """
    parser.parse(comment_cmds=False)
    assert "set A := {0,1,2,3,4};" in parser.output
    assert "set B := {(0,0),(1,1),(2,2),(3,3),(4,4)};" in parser.output
    assert "set C := {0,1,2,3,4};" not in parser.output
    assert "set ^C := {0,1,2,3,4};" not in parser.output
Exemplo n.º 7
0
def main():
    """Solve 'sos2.mod'."""
    from pympl import PyMPL, Tools, glpkutils
    os.chdir(os.path.dirname(__file__) or os.curdir)

    mod_in = "sos2.mod"
    mod_out = "tmp/sos2.out.mod"
    parser = PyMPL(locals_=locals(), globals_=globals())
    parser.parse(mod_in, mod_out)

    lp_out = "tmp/sos2.lp"
    glpkutils.mod2lp(mod_out, lp_out, verbose=True)
    out, varvalues = Tools.script("glpk_wrapper.sh", lp_out, verbose=True)

    print("varvalues:",
          [(k, v)
           for k, v in sorted(varvalues.items()) if not k.startswith("_")])
Exemplo n.º 8
0
def main():
    """Solve 'twostage.mod'."""
    from pympl import PyMPL, Tools, glpkutils
    os.chdir(os.path.dirname(__file__) or os.curdir)

    mod_in = "twostage.mod"
    mod_out = "tmp/twostage.out.mod"
    parser = PyMPL(locals_=locals(), globals_=globals())
    parser.parse(mod_in, mod_out)

    lp_out = "tmp/twostage.lp"
    glpkutils.mod2lp(mod_out, lp_out, verbose=True)

    out, varvalues = Tools.script("glpk_wrapper.sh", lp_out, verbose=True)

    print("")
    print("varvalues:",
          [(k, v)
           for k, v in sorted(varvalues.items()) if not k.startswith("_")])
    print("")
    assert varvalues["Z"] == 11  # check the solution objective value

    exctacted_solution = parser["VBP_FLOW"].extract(
        lambda name: varvalues.get(name, 0), verbose=True)

    solution = {}
    for zvar, value, sol in exctacted_solution:
        solution[zvar] = []
        for r, pattern in sol:
            solution[zvar] += [pattern] * r
        assert value == len(solution[zvar])

    def pop_pattern(zvar):
        pattern = []
        for it in solution[zvar].pop():
            if it not in solution:
                pattern.append(it)
            else:
                pattern.append((it, pop_pattern(it)))
        return pattern

    print("\n\nSolution:")
    for i in range(varvalues["Z"]):
        pattern = pop_pattern("Z")
        print("Sheet {}: {}".format(i + 1, pattern))
Exemplo n.º 9
0
def test_comments():
    """Test valid comments."""
    parser = PyMPL()
    parser.input = """
    /* ... $SET[A]{range(5)}; ... */
    # $PARAM[VALUE]{10};
    # ... $PARAM[VALUE2]{10}; ...
    param a := "\\"/*";
    $PARAM[Y]{10};
    param b := "*/";
    """
    parser.parse(comment_cmds=True)
    assert "set A := {0,1,2,3,4};" not in parser.output
    assert "param VALUE := 10;" not in parser.output
    assert "param VALUE2 := 10;" not in parser.output
    assert "param Y := 10;" in parser.output
    assert "# $PARAM[VALUE]{10};" in parser.output
    assert "/*EVALUATED:PARAM[Y]{10}*/" in parser.output
Exemplo n.º 10
0
def test_glpkutils():
    """Test glpkutils."""
    from pympl import Tools, glpkutils
    os.chdir(os.path.dirname(__file__) or os.curdir)

    mod_in, mod_out = "pwl.mod", "tmp/pwl.out.mod"
    lp_out, mps_out = "tmp/pwl.lp", "tmp/pwl.mps"

    parser = PyMPL(locals_=locals(), globals_=globals())
    parser.parse(mod_in, mod_out)

    glpkutils.mod2lp(mod_out, lp_out, verbose=True)
    glpkutils.mod2mps(mod_out, mps_out, verbose=True)

    Tools.clear()
    Tools.set_verbose(False)
    out, varvalues = Tools.script("glpk_wrapper.sh", lp_out, verbose=True)
    out, varvalues = Tools.script("glpk_wrapper.sh", mps_out, verbose=True)
Exemplo n.º 11
0
def equivknapsack(a, a0, bounds=None):
    """Compute a minimal equivalent knapsack inequalitie."""
    from pympl import PyMPL, Tools, glpkutils
    os.chdir(os.path.dirname(__file__) or os.curdir)

    if bounds is None:
        bounds = [a0] * len(a)
    for i in range(len(a)):
        bounds[i] = min(bounds[i], a0 // a[i] if a[i] != 0 else 0)

    sum_a = sum(x * y for x, y in zip(a, bounds))
    aS = abs(2 * a0 + 1 - sum_a)
    if a0 < (sum_a - 1) // 2:
        a0 += aS
        fix_as = 1
    else:
        fix_as = 0
        if aS > a0:
            return [0] * len(a), 0, bounds
    a = list(a) + [aS]
    bounds = bounds + [1]

    mod_in = "equivknapsack.mod"
    mod_out = "tmp/equivknapsack.out.mod"
    parser = PyMPL(locals_=locals())
    parser.parse(mod_in, mod_out)

    lp_out = "tmp/equivknapsack.lp"
    glpkutils.mod2lp(mod_out, lp_out, verbose=True)
    # exit_code = os.system("glpsol --math {0}".format(mod_out))
    # assert exit_code == 0
    out, varvalues = Tools.script("glpk_wrapper.sh", lp_out, verbose=True)

    b = [varvalues.get("pi({0})".format(i + 1), 0) for i in range(len(a))]
    b0 = varvalues.get("pi(0)", 0)

    if fix_as == 1:
        b0 -= b[-1]
        b = b[:-1]
    else:
        b = b[:-1]

    return tuple(b), b0, tuple(bounds)
Exemplo n.º 12
0
def test_var():
    """Test $VAR[name]{typ, lb, ub} calls."""
    parser = PyMPL()
    parser.input = """
    $VAR[x]{"integer", 0, 10};
    $VAR[y]{"binary"};
    $VAR[z]{ub=abs((2**7)//5-135)};
    $VAR[^z]{"integer", 0, 10};
    $VAR[xs{I}]{"integer", index_set=range(3)};
    $EXEC{VAR['y']("binary")};
    """
    parser.parse(comment_cmds=False)
    assert "var x, integer, >= 0, <= 10;" in parser.output
    assert "var y, binary;" in parser.output
    assert "var z, <= 110;" in parser.output
    assert "var ^z, integer, >= 0, <= 10;" not in parser.output
    assert "var y, binary;" in parser.output
    assert "var xs{I}, integer;" in parser.output
    assert "set I := {0,1,2};" in parser.output
Exemplo n.º 13
0
def test_param():
    """Test $PARAM[name]{value} calls."""
    parser = PyMPL()
    parser.input = """
    $PARAM[NAME]{"name"};
    $PARAM[VALUE]{10};
    $PARAM[D{I}]{{'a': 1}};
    $PARAM[L0]{[1,2,3], i0=0};
    $PARAM[L1]{[1,2,3], i0=1};
    $PARAM[^NAME2]{"something"};
    """
    parser.parse(comment_cmds=False)
    assert "param NAME := 'name';" in parser.output
    assert "param VALUE := 10;" in parser.output
    assert "param D := ['a']1;" in parser.output
    assert "set I := {'a'};" in parser.output
    assert "param L0 := [0]1[1]2[2]3;" in parser.output
    assert "param L1 := [1]1[2]2[3]3;" in parser.output
    assert "param NAME2 := 'something';" not in parser.output
    assert "param ^NAME2 := 'something';" not in parser.output
Exemplo n.º 14
0
def main():
    """Parses 'instance_mvp.mod'"""
    from pympl import PyMPL, Tools, glpkutils
    os.chdir(os.path.dirname(__file__) or os.curdir)

    mod_in = "instance_mvp.mod"
    mod_out = "tmp/instance_mvp.out.mod"
    parser = PyMPL(locals_=locals(), globals_=globals())
    parser.parse(mod_in, mod_out)

    lp_out = "tmp/instance_mvp.lp"
    glpkutils.mod2lp(mod_out, lp_out, True)
    out, varvalues = Tools.script("glpk_wrapper.sh", lp_out, verbose=True)
    sol = parser["MVP_FLOW"].extract(lambda varname: varvalues.get(varname, 0),
                                     verbose=True)

    print("")
    print("sol:", sol)
    print("varvalues:", [(k, v) for k, v in sorted(varvalues.items())])
    print("")
    assert varvalues["cost"] == 8  # check the solution objective value
Exemplo n.º 15
0
def main():
    """Solve 'ppbymip_ps.mod'."""
    from pympl import PyMPL, Tools, glpkutils
    os.chdir(os.path.dirname(__file__) or os.curdir)

    mod_in = "ppbymip_ps.mod"
    mod_out = "tmp/ps.out.mod"
    parser = PyMPL(locals_=locals(), globals_=globals())
    parser.parse(mod_in, mod_out)

    lp_out = "tmp/ps.lp"
    glpkutils.mod2lp(mod_out, lp_out, verbose=True)
    out, varvalues = Tools.script(
        "gurobi_wrapper.sh",
        lp_out,
        options="Threads=1 Presolve=0 Heuristics=0.25 MIPGap=0",
        verbose=True)

    print("varvalues:",
          [(k, v)
           for k, v in sorted(varvalues.items()) if not k.startswith("_")])
Exemplo n.º 16
0
def test_con():
    """Test $CON[name]{lincomb, sign, rhs} calls."""
    parser = PyMPL()
    parser.input = """
    $VAR[x1]{}; $VAR[x2]{}; $VAR[x3]{};
    $CON[con1]{[("x1",5),("x2",15),("x3",10)],">=",20};
    $CON[con2]{[("x1",5),("x2",15),-20],">=",("x3",-10)};
    $CON[con3]{[("x1",5)],">=",[("x2",-15),("x3",-10),20]};
    $CON[con4]{-20,">=",[("x1",-5),("x2",-15),("x3",-10)]};
    $CON[con5]{-20,">=",[(-5, "x1"),("x2",-15),(-10, "x3")]};
    $CON[con6]{[-20, "x1"],">=",[(-4, "x1"),("x2",-15),(-10, "x3")]};
    $CON[con7]{"x1",">=",[(-4, "x1"),20,("x2",-15),(-10, "x3")]};
    $CON[^xyz]{[("x1",5),("x2",15),("x3",10)],">=",20};
    """
    parser.parse(comment_cmds=False)
    assert "s.t. con1: +5*x1 +15*x2 +10*x3 >= 20;" in parser.output
    assert "s.t. con2: +5*x1 +15*x2 +10*x3 >= 20;" in parser.output
    assert "s.t. con3: +5*x1 +15*x2 +10*x3 >= 20;" in parser.output
    assert "s.t. con4: +5*x1 +15*x2 +10*x3 >= 20;" in parser.output
    assert "s.t. con5: +5*x1 +15*x2 +10*x3 >= 20;" in parser.output
    assert "s.t. con6: +5*x1 +15*x2 +10*x3 >= 20;" in parser.output
    assert "s.t. con7: +5*x1 +15*x2 +10*x3 >= 20;" in parser.output
    assert "s.t. xyz: +5*x1 +15*x2 +10*x3 >= 20;" not in parser.output
Exemplo n.º 17
0
def equivknapsack01(a, a0):
    """Compute a minimal equivalent 0-1 knapsack inequalitie."""
    from pympl import PyMPL, Tools, glpkutils
    os.chdir(os.path.dirname(__file__) or os.curdir)

    aS = abs(2 * a0 + 1 - sum(a))
    if a0 < (sum(a) - 1) // 2:
        a0 += aS
        fix_as = 1
    else:
        fix_as = 0
        if aS > a0:
            return [0] * len(a), 0
    a = list(a) + [aS]

    mod_in = "equivknapsack01.mod"
    mod_out = "tmp/equivknapsack01.out.mod"

    parser = PyMPL(locals_=locals(), globals_=globals())
    parser.parse(mod_in, mod_out)

    lp_out = "tmp/equivknapsack01.lp"
    glpkutils.mod2lp(mod_out, lp_out, verbose=True)
    # exit_code = os.system("glpsol --math {0}".format(mod_out))
    # assert exit_code == 0
    out, varvalues = Tools.script("glpk_wrapper.sh", lp_out, verbose=False)

    b = [varvalues.get("pi({0})".format(i + 1), 0) for i in range(len(a))]
    b0 = varvalues.get("pi(0)", 0)

    if fix_as == 1:
        b0 -= b[-1]
        b = b[:-1]
    else:
        b = b[:-1]

    return tuple(b), b0
Exemplo n.º 18
0
def main():
    """Solve 'vpsolver_vbp_flow.mod' and 'vpsolver_vbp_graph.mod'."""
    from pympl import PyMPL, Tools, glpkutils
    os.chdir(os.path.dirname(__file__) or os.curdir)

    for model in ["vpsolver_vbp_graph", "vpsolver_vbp_flow"]:
        mod_in = "{}.mod".format(model)
        mod_out = "tmp/{}.out.mod".format(model)
        parser = PyMPL()
        parser.parse(mod_in, mod_out)

        lp_out = "tmp/{}.lp".format(model)
        glpkutils.mod2lp(mod_out, lp_out, verbose=True)
        out, varvalues = Tools.script("glpk_wrapper.sh", lp_out, verbose=True)
        sol = parser["MVP_FLOW"].extract(
            lambda varname: varvalues.get(varname, 0), verbose=True)

        print("")
        print("sol:", sol)
        print("varvalues:",
              [(k, v)
               for k, v in sorted(varvalues.items()) if not k.startswith("_")])
        print("")
        assert varvalues["Z"] == 33  # check the solution objective value
Exemplo n.º 19
0
def test_exceptions():
    """Test if exceptions are being thrown correctly."""
    parser = PyMPL()
    parser.input = """$EXEC{print(1/0)};"""
    with pytest.raises(ZeroDivisionError):
        parser.parse(comment_cmds=False)
    parser.input = """$SET[X]{0};"""
    with pytest.raises(TypeError):
        parser.parse(comment_cmds=False)
    parser.input = """$VBP_FLOW[Z]{100, [10, 10]};"""
    with pytest.raises(TypeError):
        parser.parse(comment_cmds=False)
    parser.input = """$VBP_FLOW[Z]{100, 10};"""
    with pytest.raises(TypeError):
        parser.parse(comment_cmds=False)
    parser.input = """$SET[X]{};"""
    with pytest.raises(TypeError):
        parser.parse(comment_cmds=False)
    parser.input = """$SET[X]{[1,2,3]};$SET[X]{[1,2]};"""
    with pytest.raises(AssertionError):
        parser.parse(comment_cmds=False)
    parser.input = """$SET[2X]{[1,2,3]};"""
    with pytest.raises(AssertionError):
        parser.parse(comment_cmds=False)
Exemplo n.º 20
0
from pympl import PyMPL

print("/*")
pympl = PyMPL(locals_=locals(), globals_=globals())
pympl.parse("model.mod")
print("*/")

print(pympl.output)
Exemplo n.º 21
0
def test_empty():
    """Test empty files."""
    parser = PyMPL()
    parser.input = ""
    parser.parse(comment_cmds=False)
    assert parser.output == ""