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
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
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
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 )
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)
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
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
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
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
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
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("_")])
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("_")])
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)
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))
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)
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
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
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)
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))
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
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("_")])
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
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
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("_") ])
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
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
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
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
def solve_worker(app_name, method, form, args, output=sys.stdout): """Worker for solving the problem in a separate process.""" VPSolver.PLIST = [] def signal_handler(sig, frame): """Signal handler for cleaner exit.""" for p in VPSolver.PLIST: try: os.killpg(p.pid, signal.SIGTERM) except Exception as e: pass sys.exit(0) signal.signal(signal.SIGTERM, signal_handler) sys.stdout = output sys.stderr = output input_ = form["input"].strip("\n") if DEBUG: print("Input:\n{0}\n\nOutput:".format(input_)) output.flush() if app_name == "vbp": tmpfile = VPSolver.new_tmp_file(ext=".vbp") with open(tmpfile, "w") as f: f.write(input_) instance = VBP.from_file(tmpfile, verbose=False) afg = AFG(instance, verbose=True) lp_model = LP(afg, verbose=False) out, sol = VPSolver.script( form["script"], lp_model, afg, verbose=True ) elif app_name == "pympl": tmpfile = VPSolver.new_tmp_file(ext=".mod") parser = PyMPL() parser.input = input_ parser.parse() parser.write(tmpfile) VPSolver.run( "glpsol --math {0}".format(tmpfile), grepv="Generating", verbose=True ) print("EOF\n") output.flush()
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)
from pympl import PyMPL print("/*") pympl = PyMPL(locals_=locals(), globals_=globals()) pympl.parse("model.mod") print("*/") print(pympl.output)
def test_empty(): """Test empty files.""" parser = PyMPL() parser.input = "" parser.parse(comment_cmds=False) assert parser.output == ""
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