Пример #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
Пример #2
0
def test_model():
    """Test model."""
    from pympl import Model, Tools, glpkutils
    os.chdir(os.path.dirname(__file__) or os.curdir)
    model = Model()
    values = [15, 10, 9, 5]
    weights = [1, 5, 3, 4]
    xvars = []
    for i in range(len(values)):
        var = model.add_var(lb=0, ub=1, vtype="I")
        xvars.append(var)
    profit = model.add_var(lb=0, vtype="C")
    model.add_con([(x, w) for x, w in zip(xvars, weights)], "<=", 8)
    model.add_con(profit, "=", [(x, v) for x, v in zip(xvars, values)])
    model.set_obj("max", profit)
    lp_out = "tmp/model.lp"
    mps_out = "tmp/model.mps"
    mod_out = "tmp/model.mod"
    model.write(lp_out)
    model.write(mps_out)
    model.write(mod_out)
    out, varvalues = Tools.script("glpk_wrapper.sh", lp_out, verbose=True)
    assert varvalues[profit] == 29
    out, varvalues = Tools.script(
        "glpk_wrapper.sh", mps_out, options="--max", verbose=True
    )
    assert varvalues[profit] == 29
    glpkutils.mod2lp(mod_out, lp_out, verbose=True)
    out, varvalues = Tools.script("glpk_wrapper.sh", lp_out, verbose=True)
    assert varvalues[profit] == 29
Пример #3
0
def test_model():
    """Test model."""
    from pympl import Model, Tools, glpkutils
    os.chdir(os.path.dirname(__file__) or os.curdir)
    model = Model()
    values = [15, 10, 9, 5]
    weights = [1, 5, 3, 4]
    xvars = []
    for i in range(len(values)):
        var = model.add_var(lb=0, ub=1, vtype="I")
        xvars.append(var)
    profit = model.add_var(lb=0, vtype="C")
    model.add_con([(x, w) for x, w in zip(xvars, weights)], "<=", 8)
    model.add_con(profit, "=", [(x, v) for x, v in zip(xvars, values)])
    model.set_obj("max", profit)
    lp_out = "tmp/model.lp"
    mps_out = "tmp/model.mps"
    mod_out = "tmp/model.mod"
    model.write(lp_out)
    model.write(mps_out)
    model.write(mod_out)
    out, varvalues = Tools.script("glpk_wrapper.sh", lp_out, verbose=True)
    assert varvalues[profit] == 29
    out, varvalues = Tools.script("glpk_wrapper.sh",
                                  mps_out,
                                  options="--max",
                                  verbose=True)
    assert varvalues[profit] == 29
    glpkutils.mod2lp(mod_out, lp_out, verbose=True)
    out, varvalues = Tools.script("glpk_wrapper.sh", lp_out, verbose=True)
    assert varvalues[profit] == 29
Пример #4
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
Пример #5
0
def main():
    """Parses '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, 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"] == 15  # check the solution objective value

    parser["VBP_FLOW"].extract(
        lambda name: varvalues.get(name, 0),
        verbose=True
    )
Пример #6
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
Пример #7
0
def main():
    """Parses 'instance_vbp.mod'"""
    from pympl import PyMPL, Tools, glpkutils
    os.chdir(os.path.dirname(__file__) or os.curdir)

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

    lp_out = "tmp/instance_vbp.lp"
    glpkutils.mod2lp(mod_out, lp_out, True)
    out, varvalues = Tools.script(
        "glpk_wrapper.sh", lp_out, verbose=True
    )
    sol = parser["VBP_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["Z"] == 33  # check the solution objective value
Пример #8
0
def main():
    """Parses 'instance.mod'"""

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

    lp_out = "tmp/instance.lp"
    glpkutils.mod2lp(mod_out, lp_out, True)
    out, varvalues = Tools.script(
        "glpk_wrapper.sh", lp_out, verbose=True
    )
    sol = parser["VBP_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["Z"] == 33  # check the solution objective value

    exit_code = os.system("glpsol --math {0}".format(mod_out))
    assert exit_code == 0
Пример #9
0
def solve_glpk(model):
    """Solve a lot-sizing model using GLPK."""
    from pympl import Tools
    out, varvalues = Tools.script("glpk_wrapper.sh", model, verbose=False)
    try:
        return varvalues["cost"]
    except:
        return inf
Пример #10
0
def solve_glpk(model):
    """Solve a lot-sizing model using GLPK."""
    from pympl import Tools
    out, varvalues = Tools.script("glpk_wrapper.sh", model, verbose=False)
    try:
        return varvalues["cost"]
    except:
        return inf
Пример #11
0
 def script_wsol(script_name, model, options=None, verbose=None):
     """Call a solver script and return the solution."""
     from pympl import Tools
     if verbose is None:
         verbose = VPSolver.VERBOSE
     if isinstance(model, (LP, MPS)):
         model = model.filename
     return Tools.script(script_name=script_name,
                         model=model,
                         options=options,
                         verbose=verbose)
Пример #12
0
 def script_wsol(script_name, model, options=None, verbose=None):
     """Call a solver script and return the solution."""
     from pympl import Tools
     if verbose is None:
         verbose = VPSolver.VERBOSE
     if isinstance(model, (LP, MPS)):
         model = model.filename
     return Tools.script(
         script_name=script_name, model=model, options=options,
         verbose=verbose
     )
Пример #13
0
def solve_gurobi(model):
    """Solve a lot-sizing model using Gurobi."""
    from pympl import Tools
    out, varvalues = Tools.script(
         "gurobi_wrapper.sh", model,
         options="Threads=1 Presolve=0 Heuristics=0.25 MIPGap=0",
         verbose=False
    )
    try:
        return varvalues["cost"]
    except:
        return inf
Пример #14
0
def solve_gurobi(model):
    """Solve a lot-sizing model using Gurobi."""
    from pympl import Tools
    out, varvalues = Tools.script(
         "gurobi_wrapper.sh", model,
         options="Threads=1 Presolve=0 Heuristics=0.25 MIPGap=0",
         verbose=False
    )
    try:
        return varvalues["cost"]
    except:
        return inf
Пример #15
0
def main():
    """Solve 'pwl.mod'."""
    from pympl import PyMPL, Tools, glpkutils

    os.chdir(os.path.dirname(__file__) or os.curdir)

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

    lp_out = "tmp/pwl.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("_")])
Пример #16
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("_")])
Пример #17
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))
Пример #18
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)
Пример #19
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)
Пример #20
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))
Пример #21
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
Пример #22
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("_")])
Пример #23
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
Пример #24
0
def main():
    """Solve 'ppbymip_mp.mod'."""
    from pympl import PyMPL, Tools, glpkutils
    os.chdir(os.path.dirname(__file__) or os.curdir)

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

    lp_out = "tmp/mp.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("_")
    ])
Пример #25
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)
Пример #26
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
Пример #27
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)
Пример #28
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
Пример #29
0
def main():
    """Parses 'graph.mod'"""

    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())])
    print("")

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

    exit_code = os.system("glpsol --math {0}".format(mod_out))
    assert exit_code == 0

    # wolseyR1gamma:

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

    mod_in = "wolseyR1gamma.mod"
    mod_out = "tmp/wolseyR1gamma.mod.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())])
    print("")

    # Check the solution objective value:
    assert abs(varvalues['theta(T)'] - 9) < 1e-5

    exit_code = os.system("glpsol --math {0}".format(mod_out))
    assert exit_code == 0