Пример #1
0
 def test_help_solvers(self):
     with capture_output() as OUT:
         help_solvers()
     OUT = OUT.getvalue()
     self.assertTrue(re.search('Pyomo Solvers and Solver Managers', OUT))
     self.assertTrue(re.search('Serial Solver', OUT))
     # Test known solvers and metasolver flags
     # ASL is a metasolver
     self.assertTrue(re.search(r'\n   \*asl ', OUT))
     # MindtPY is bundled with Pyomo so should always be available
     self.assertTrue(re.search(r'\n   \+mindtpy ', OUT))
     for solver in ('ipopt', 'cbc', 'glpk'):
         s = SolverFactory(solver)
         if s.available():
             self.assertTrue(
                 re.search(r"\n   \+%s " % solver, OUT),
                 "'   +%s' not found in help --solvers" % solver)
         else:
             self.assertTrue(
                 re.search(r"\n    %s " % solver, OUT),
                 "'    %s' not found in help --solvers" % solver)
     for solver in ('baron', ):
         s = SolverFactory(solver)
         if s.license_is_valid():
             self.assertTrue(
                 re.search(r"\n   \+%s " % solver, OUT),
                 "'   +%s' not found in help --solvers" % solver)
         elif s.available():
             self.assertTrue(
                 re.search(r"\n   \-%s " % solver, OUT),
                 "'   -%s' not found in help --solvers" % solver)
         else:
             self.assertTrue(
                 re.search(r"\n    %s " % solver, OUT),
                 "'    %s' not found in help --solvers" % solver)
Пример #2
0
    def select_tear_mip(self, G, solver, solver_io=None, solver_options={}):
        """
        This finds optimal sets of tear edges based on two criteria.
        The primary objective is to minimize the maximum number of
        times any cycle is broken. The seconday criteria is to
        minimize the number of tears.

        This function creates a MIP problem in Pyomo with a doubly
        weighted objective and solves it with the solver arguments.
        """
        model, bin_list = self.select_tear_mip_model(G)

        from pyomo.environ import SolverFactory
        opt = SolverFactory(solver, solver_io=solver_io)
        if not opt.available(exception_flag=False):
            raise ValueError(
                "Solver '%s' (solver_io=%r) is not available, please pass a "
                "different solver" % (solver, solver_io))
        opt.solve(model, **solver_options)

        # collect final list by adding every edge with a "True" binary var
        tset = []
        for i in range(len(bin_list)):
            if bin_list[i].value == 1:
                tset.append(i)

        return tset
Пример #3
0
    def select_tear_mip(self, G, solver, solver_io=None, solver_options={}):
        """
        This finds optimal sets of tear edges based on two criteria.
        The primary objective is to minimize the maximum number of
        times any cycle is broken. The seconday criteria is to
        minimize the number of tears.

        This function creates a MIP problem in Pyomo with a doubly
        weighted objective and solves it with the solver arguments.
        """
        model, bin_list = self.select_tear_mip_model(G)

        from pyomo.environ import SolverFactory
        opt = SolverFactory(solver, solver_io=solver_io)
        if not opt.available(exception_flag=False):
            raise ValueError("Solver '%s' (solver_io=%r) is not available, please pass a "
                             "different solver" % (solver, solver_io))
        opt.solve(model, **solver_options)

        # collect final list by adding every edge with a "True" binary var
        tset = []
        for i in range(len(bin_list)):
            if bin_list[i].value == 1:
                tset.append(i)

        return tset
 def has_cplex_lp():
     from pyomo.environ import SolverFactory
     try:
         cplex = SolverFactory('cplex',keepFiles=True)
         available = (not cplex.executable() is None) and cplex.available(False)
         return available
     except pyutilib.common.ApplicationError:
         return False
Пример #5
0
    def __init__(self, k_aug=None, dot_sens=None):
        # The user may want to use their own k_aug/dot_sens solver
        # objects, i.e. with custom options or executable.
        if k_aug is None:
            k_aug = SolverFactory("k_aug")

            # TODO: Remove this if/when we support RH mode.
            k_aug.options["dsdp_mode"] = ""
        if dot_sens is None:
            dot_sens = SolverFactory("dot_sens")

            # TODO: Remove this if/when we support RH mode.
            dot_sens.options["dsdp_mode"] = ""

        if k_aug.available():
            self._k_aug = k_aug
        else:
            raise RuntimeError("k_aug is not available.")
        if dot_sens.available():
            self._dot_sens = dot_sens
        else:
            raise RuntimeError("dot_sens is not available")

        self.data = {fname: None for fname in known_files}
Пример #6
0
 def test_help_solvers(self):
     with capture_output() as OUT:
         help_solvers()
     OUT = OUT.getvalue()
     self.assertTrue(re.search('Pyomo Solvers and Solver Managers', OUT))
     self.assertTrue(re.search('Serial Solver', OUT))
     # Test known solvers and metasolver flags
     # ASL is a metasolver
     self.assertTrue(re.search('asl +\+', OUT))
     # PS is bundles with Pyomo so should always be available
     self.assertTrue(re.search('ps +\*', OUT))
     for solver in ('ipopt','baron','cbc','glpk'):
         s = SolverFactory(solver)
         if s.available():
             self.assertTrue(re.search("%s +\* [a-zA-Z]" % solver, OUT))
         else:
             self.assertTrue(re.search("%s +[a-zA-Z]" % solver, OUT))
Пример #7
0
 def test_help_solvers(self):
     with capture_output() as OUT:
         help_solvers()
     OUT = OUT.getvalue()
     self.assertTrue(re.search('Pyomo Solvers and Solver Managers', OUT))
     self.assertTrue(re.search('Serial Solver', OUT))
     # Test known solvers and metasolver flags
     # ASL is a metasolver
     self.assertTrue(re.search('asl +\+', OUT))
     # PS is bundles with Pyomo so should always be available
     self.assertTrue(re.search('ps +\*', OUT))
     for solver in ('ipopt','baron','cbc','glpk'):
         s = SolverFactory(solver)
         if s.available():
             self.assertTrue(re.search("%s +\* [a-zA-Z]" % solver, OUT))
         else:
             self.assertTrue(re.search("%s +[a-zA-Z]" % solver, OUT))
Пример #8
0
def pyomo_multi_stage(data, prob=None):
    """
    Perform multi-stage optimization with PySP.

    Required:
        prob:       Problem instance
    """
    #
    # Error Checking
    #
    solvername = get_solvername(prob)
    prob_name = prob.getProblemOption('name',0)
    con_name = prob.getProblemOption('constraint', prob_name)
    if len(con_name) > 1:
        raise RuntimeError, "We don't know how to handle side-constraints within PySP"
    else:
        con_name = con_name[0]
    aggr_name = prob.getProblemOption('aggregate', prob_name)
    goal_name = prob.getConstraintOption('goal', con_name)
    if lower(goal_name) != 'ns':
        cost_name = prob.getCostOption('cost file', goal_name)
        if not cost_name is None:
            raise RuntimeError, "Cannot use a cost constraint goal with the %s solver" % solvername
    if aggr_name is not None:
        raise RuntimeError, "Cannot use a aggregation with the %s solver" % solvername
    #
    # Create the Pyomo data files
    #
    create_multistage_data(prob, data)
    #
    # Setup the PySP command-line
    #
    solvername = get_solvername(prob)
    #
    seed = prob.getSolverOption('seed')
    if solvername == 'ef':
        cmd = ['runef']
        cmd.append('--output-solver-log')
    elif solvername == 'ph':
        cmd = ['runph']
        cmd.append('-r')
        cmd.append('1.0')
    cmd.append('--solver')
    #
    # TODO: add an 'ef' solver option that specifies a sub-solver name
    #
    opt = SolverFactory('pico')
    if opt.available(False) and (not opt.executable() is None):
        cmd.append('pico')
    else:
        opt = SolverFactory('cbc')
        if opt.available(False) and (not opt.executable() is None):
            cmd.append('cbc')
        else:
            opt = SolverFactory('glpk')
            if opt.available(False) and (not opt.executable() is None):
                cmd.append('glpk')
    #
    cmd.append('-m')
    cmd.append('%s/multistage' % modeldir)
    cmd.append('-i')
    cmd.append('%s' % data.datadir)
    if not seed is None:
        cmd.append('--scenario-tree-seed')
        cmd.append(str(seed))
    cmd.append('--solution-writer=pywst.sp.pyspsolutionwriter')
    cmd.append('--traceback')
    if solvername == 'ef':
        cmd.append('--solve')
    else:
        cmd.append('--linearize-nonbinary-penalty-terms=5')
    data.command_line = ' '.join(cmd)
    #
    # Run the solver
    #
    print "Running command ..."
    print ' '.join(cmd)
    rc, output = pyutilib.subprocess.run(cmd, tee=True)
    if rc != 0:
        print "ERROR executing the '%s' command" % solvername
        print output
        raise RuntimeError, "Bad return code for multi-stage solver: %d\n%s" % (rc, output)
    #
    # Read the JSON file
    #
    INPUT = open(solvername+'.json','r')
    results = json.load(INPUT)
    INPUT.close()
    stage2 = {}
    soln = []
    for i in results:
        for j in results[i]:
            for k in results[i][j]:
                for l in results[i][j][k]:
                    #print i,j,k,l
                    val = results[i][j][k][l]
                    if i == 'FirstStage' and j == 'RootNode' and k == 'Stage1Sensors' and val == 1.0:
                        soln.append( eval(l) )
                    elif i == 'SecondStage':
                        if not j in stage2:
                            stage2[ j ] = []
                        if k == 'Stage2Sensors' and val == 1.0:
                            loc = eval(l)
                            if not loc in soln:
                                stage2[ j ].append( loc )
    data.solutions = [soln]
    data.stage2_solutions = stage2
    #
    # Remove the data directory
    #
    if not prob.getConfigureOption('keepfiles'):
        shutil.rmtree(data.datadir)
Пример #9
0
#  ___________________________________________________________________________
#
#  Pyomo: Python Optimization Modeling Objects
#  Copyright 2017 National Technology and Engineering Solutions of Sandia, LLC
#  Under the terms of Contract DE-NA0003525 with National Technology and
#  Engineering Solutions of Sandia, LLC, the U.S. Government retains certain
#  rights in this software.
#  This software is distributed under the 3-clause BSD License.
#  ___________________________________________________________________________

from pyomo.environ import SolverFactory, ConcreteModel, Var, Constraint, Objective, Integers, Boolean
import pyutilib.th as unittest
from pyomo.common.tee import capture_output

opt_cbc = SolverFactory('cbc')
cbc_available = opt_cbc.available(exception_flag=False)


class CBCTests(unittest.TestCase):
    @unittest.skipIf(not cbc_available, "The CBC solver is not available")
    def test_warm_start(self):

        m = ConcreteModel()
        m.x = Var()
        m.z = Var(domain=Integers)
        m.w = Var(domain=Boolean)
        m.c = Constraint(expr=m.x + m.z + m.w >= 0)
        m.o = Objective(expr=m.x + m.z + m.w)

        # Set some initial values for warm start.
        m.x.set_value(10)
Пример #10
0
def get_solver_availability():
    logging.disable(logging.WARNING)
    available = {}
    try:
        opt = SolverFactory('pico')
        available['pico'] = opt.available(False) and (
            not opt.executable() is None)
        del opt
    except pyutilib.common.ApplicationError:
        available['pico'] = False
    try:
        opt = SolverFactory('cplex')
        available['cplex'] = opt.available(False) and (
            not opt.executable() is None)
        del opt
    except pyutilib.common.ApplicationError:
        available['cplex'] = False
    try:
        opt = SolverFactory('cplex_direct')
        available['cplex_direct'] = opt.available(False) and (
            not opt.executable() is None)
        del opt
    except pyutilib.common.ApplicationError:
        available['cplex_direct'] = False
    try:
        opt = SolverFactory('gurobi')
        available['gurobi'] = opt.available(False) and (
            not opt.executable() is None)
        del opt
    except pyutilib.common.ApplicationError:
        available['gurobi'] = False
    try:
        opt = SolverFactory('gurobi_direct')
        available['gurobi_direct'] = opt.available(False) and (
            not opt.executable() is None)
        del opt
    except pyutilib.common.ApplicationError:
        available['gurobi_direct'] = False
    try:
        opt = SolverFactory('glpk')
        available['glpk'] = opt.available(False) and (
            not opt.executable() is None)
        del opt
    except pyutilib.common.ApplicationError:
        available['glpk'] = False
    try:
        opt = SolverFactory('cbc')
        available['cbc'] = opt.available(False) and (
            not opt.executable() is None)
        del opt
    except pyutilib.common.ApplicationError:
        available['cbc'] = False
    try:
        opt = SolverFactory('xpress')
        available['xpress'] = opt.available(False) and (
            not opt.executable() is None)
        del opt
    except pyutilib.common.ApplicationError:
        available['xpress'] = False
    logging.disable(logging.NOTSET)
    return available