コード例 #1
0
ファイル: test_unittests.py プロジェクト: fdabrandao/pympl
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
コード例 #2
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
コード例 #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
ファイル: wolsey.py プロジェクト: fdabrandao/pympl
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 '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
コード例 #6
0
ファイル: vpsolver_vbp.py プロジェクト: fdabrandao/pympl
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
ファイル: instance.py プロジェクト: ethankent/vpsolver
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
コード例 #8
0
ファイル: twostage.py プロジェクト: CHEN-JIANGHANG/vpsolver
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
    )
コード例 #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
ファイル: test_lslib.py プロジェクト: fdabrandao/pympl
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 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)
コード例 #12
0
ファイル: test_unittests.py プロジェクト: fdabrandao/pympl
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)
コード例 #13
0
ファイル: vpsolver.py プロジェクト: syberi/vpsolver
 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)
コード例 #14
0
ファイル: vpsolver.py プロジェクト: fdabrandao/vpsolver
 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
     )
コード例 #15
0
ファイル: test_lslib.py プロジェクト: fdabrandao/pympl
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
コード例 #16
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
コード例 #17
0
ファイル: pwl.py プロジェクト: fdabrandao/pympl
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("_")])
コード例 #18
0
ファイル: sos2.py プロジェクト: yuegchen/pympl
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("_")])
コード例 #19
0
ファイル: twostage.py プロジェクト: yuegchen/pympl
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))
コード例 #20
0
ファイル: equivknapsack.py プロジェクト: fdabrandao/pympl
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)
コード例 #21
0
ファイル: twostage.py プロジェクト: fdabrandao/pympl
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))
コード例 #22
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)
コード例 #23
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
コード例 #24
0
ファイル: ppbymip_ps.py プロジェクト: yuegchen/pympl
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("_")])
コード例 #25
0
ファイル: ppbymip_mp.py プロジェクト: fdabrandao/pympl
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("_")
    ])
コード例 #26
0
ファイル: equivknapsack01.py プロジェクト: fdabrandao/pympl
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
ファイル: equivknapsack01.py プロジェクト: yuegchen/pympl
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
コード例 #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
ファイル: wolsey.py プロジェクト: ethankent/vpsolver
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