예제 #1
0
def get_solvers(solvers_tried: [str] = None):
    if not solvers_tried:
        solvers_tried = ["gurobi", "cplex", "glpk"]

    available_solvers = check_available_solvers(*solvers_tried)

    if len(available_solvers) == 0:
        raise EnvironmentError("No solvers available")

    return available_solvers
예제 #2
0
class TestAMPLExternalFunction(unittest.TestCase):
    def test_getname(self):
        m = ConcreteModel()
        m.f = ExternalFunction(library="junk.so", function="junk")
        self.assertIsInstance(m.f, AMPLExternalFunction)
        self.assertEqual(m.f.name, "f")
        self.assertEqual(m.f.local_name, "f")
        self.assertEqual(m.f.getname(), "f")
        self.assertEqual(m.f.getname(True), "f")

        M = ConcreteModel()
        M.m = m
        self.assertEqual(M.m.f.name, "m.f")
        self.assertEqual(M.m.f.local_name, "f")
        self.assertEqual(M.m.f.getname(), "f")
        self.assertEqual(M.m.f.getname(True), "m.f")

    def getGSL(self):
        # Find the GSL DLL
        DLL = None
        for path in [os.getcwd()] + os.environ['PATH'].split(os.pathsep):
            test = os.path.join(path, 'amplgsl.dll')
            if os.path.isfile(test):
                DLL = test
                break
        print("GSL found here: %s" % DLL)
        return DLL

    def test_eval_gsl_function(self):
        DLL = self.getGSL()
        if not DLL:
            self.skipTest("Could not find the amplgsl.dll library in the PATH")
        model = ConcreteModel()
        model.z_func = ExternalFunction(library=DLL, function="gsl_sf_gamma")
        model.x = Var(initialize=3, bounds=(1e-5, None))
        model.o = Objective(expr=model.z_func(model.x))
        self.assertAlmostEqual(value(model.o), 2.0, 7)

    @unittest.skipIf(not check_available_solvers('ipopt'),
                     "The 'ipopt' solver is not available")
    def test_solve_gsl_function(self):
        DLL = self.getGSL()
        if not DLL:
            self.skipTest("Could not find the amplgsl.dll library in the PATH")
        model = ConcreteModel()
        model.z_func = ExternalFunction(library=DLL, function="gsl_sf_gamma")
        model.x = Var(initialize=3, bounds=(1e-5, None))
        model.o = Objective(expr=model.z_func(model.x))
        opt = SolverFactory('ipopt')
        res = opt.solve(model, tee=True)
        self.assertAlmostEqual(value(model.o), 0.885603194411, 7)
예제 #3
0
class TestAMPLExternalFunction(unittest.TestCase):
    def test_getname(self):
        m = ConcreteModel()
        m.f = ExternalFunction(library="junk.so", function="junk")
        self.assertIsInstance(m.f, AMPLExternalFunction)
        self.assertEqual(m.f.name, "f")
        self.assertEqual(m.f.local_name, "f")
        self.assertEqual(m.f.getname(), "f")
        self.assertEqual(m.f.getname(True), "f")

        M = ConcreteModel()
        M.m = m
        self.assertEqual(M.m.f.name, "m.f")
        self.assertEqual(M.m.f.local_name, "f")
        self.assertEqual(M.m.f.getname(), "f")
        self.assertEqual(M.m.f.getname(True), "m.f")

    def test_eval_gsl_function(self):
        DLL = find_GSL()
        if not DLL:
            self.skipTest("Could not find the amplgsl.dll library")
        model = ConcreteModel()
        model.z_func = ExternalFunction(library=DLL, function="gsl_sf_gamma")
        model.x = Var(initialize=3, bounds=(1e-5, None))
        model.o = Objective(expr=model.z_func(model.x))
        self.assertAlmostEqual(value(model.o), 2.0, 7)

    @unittest.skipIf(not check_available_solvers('ipopt'),
                     "The 'ipopt' solver is not available")
    def test_solve_gsl_function(self):
        DLL = find_GSL()
        if not DLL:
            self.skipTest("Could not find the amplgsl.dll library")
        model = ConcreteModel()
        model.z_func = ExternalFunction(library=DLL, function="gsl_sf_gamma")
        model.x = Var(initialize=3, bounds=(1e-5, None))
        model.o = Objective(expr=model.z_func(model.x))
        opt = SolverFactory('ipopt')
        res = opt.solve(model, tee=True)
        self.assertAlmostEqual(value(model.o), 0.885603194411, 7)
예제 #4
0
currdir = dirname(abspath(__file__)) + os.sep

from six import StringIO
from pyomo.common.log import LoggingIntercept

import pyutilib.th as unittest
import random

from pyomo.opt import check_available_solvers
from pyomo.environ import (ConcreteModel, Set, Objective, Constraint, Var,
                           Block, Param, NonNegativeReals,
                           TransformationFactory, ComponentUID, inequality)

import pyomo.core.expr.current as EXPR

solvers = check_available_solvers('glpk')


class TestAddSlacks(unittest.TestCase):
    def setUp(self):
        # set seed so we can test name collisions predictably
        random.seed(666)

    @staticmethod
    def makeModel():
        model = ConcreteModel()
        model.x = Var(within=NonNegativeReals)
        model.y = Var(within=NonNegativeReals)
        model.rule1 = Constraint(expr=model.x <= 5)
        model.rule2 = Constraint(expr=inequality(1, model.y, 3))
        model.rule3 = Constraint(expr=model.x >= 0.1)
예제 #5
0
#  ___________________________________________________________________________

import pyomo.common.unittest as unittest

from pyomo.opt import (
    TerminationCondition,
    SolutionStatus,
    check_available_solvers,
)
import pyomo.environ as pyo
import pyomo.kernel as pmo
import sys

diff_tol = 1e-3

mosek_available = check_available_solvers('mosek_direct')


@unittest.skipIf(not mosek_available,
                 "MOSEK's python bindings are not available")
class MOSEKDirectTests(unittest.TestCase):
    def setUp(self):
        self.stderr = sys.stderr
        sys.stderr = None

    def tearDown(self):
        sys.stderr = self.stderr

    def test_interface_call(self):

        interface_instance = type(pyo.SolverFactory('mosek_direct'))
예제 #6
0
파일: test_misc.py 프로젝트: qtothec/pyomo
 def setUpClass(cls):
     global solvers
     import pyomo.environ
     solvers = check_available_solvers('glpk', 'cplex')
예제 #7
0
    # overview_ch'
    'test_overview_ch_wl_excel': ['pandas', 'xlrd'],
    'test_overview_ch_wl_mutable_excel': ['pandas', 'xlrd'],

    # scripts_ch'
    'test_scripts_ch_warehouse_cuts': ['matplotlib'],

    # performance_ch'
    'test_performance_ch_wl': ['numpy', 'matplotlib'],
}

#
# Initialize the availability data
#
solvers_used = set(sum(list(solver_dependencies.values()), []))
available_solvers = check_available_solvers(*solvers_used)
solver_available = {
    solver_: solver_ in available_solvers
    for solver_ in solvers_used
}

package_available = {}
package_modules = {}
packages_used = set(sum(list(package_dependencies.values()), []))
for package_ in packages_used:
    pack, pack_avail = attempt_import(package_)
    package_available[package_] = pack_avail
    package_modules[package_] = pack


def check_skip(name):
예제 #8
0
class TestAMPLExternalFunction(unittest.TestCase):
    def assertListsAlmostEqual(self, first, second, places=7, msg=None):
        self.assertEqual(len(first), len(second))
        msg = "lists %s and %s differ at item " % (first, second)
        for i, a in enumerate(first):
            self.assertAlmostEqual(a, second[i], places, msg + str(i))

    def test_getname(self):
        m = ConcreteModel()
        m.f = ExternalFunction(library="junk.so", function="junk")
        self.assertIsInstance(m.f, AMPLExternalFunction)
        self.assertEqual(m.f.name, "f")
        self.assertEqual(m.f.local_name, "f")
        self.assertEqual(m.f.getname(), "f")
        self.assertEqual(m.f.getname(True), "f")

        M = ConcreteModel()
        M.m = m
        self.assertEqual(M.m.f.name, "m.f")
        self.assertEqual(M.m.f.local_name, "f")
        self.assertEqual(M.m.f.getname(), "f")
        self.assertEqual(M.m.f.getname(True), "m.f")

    @unittest.skipIf(sys.platform.lower().startswith('win'),
                     "Cannot (easily) unload a DLL in Windows, so "
                     "cannot clean up the 'temporary' DLL")
    def test_load_local_asl_library(self):
        DLL = find_GSL()
        if not DLL:
            self.skipTest("Could not find the amplgsl.dll library")

        LIB = 'test_pyomo_external_gsl.dll'

        model = ConcreteModel()
        model.gamma = ExternalFunction(library=LIB, function="gsl_sf_gamma")
        model.x = Var(initialize=3, bounds=(1e-5, None))
        model.o = Objective(expr=model.gamma(model.x))

        with TempfileManager.new_context() as tempfile:
            dname = tempfile.mkdtemp()
            shutil.copyfile(DLL, os.path.join(dname, LIB))
            # Without changing directories, the load should fail
            with self.assertRaises(OSError):
                value(model.o)
            # Changing directories should pick up the library
            try:
                orig_dir = os.getcwd()
                os.chdir(dname)
                self.assertAlmostEqual(value(model.o), 2.0, 7)
            finally:
                os.chdir(orig_dir)

    def test_unknown_library(self):
        m = ConcreteModel()
        with LoggingIntercept() as LOG:
            m.ef = ExternalFunction(
                library='unknown_pyomo_external_testing_function',
                function='f')
        self.assertEqual(
            LOG.getvalue(),
            'Defining AMPL external function, but cannot locate '
            'specified library "unknown_pyomo_external_testing_function"\n')

    def test_eval_gsl_function(self):
        DLL = find_GSL()
        if not DLL:
            self.skipTest("Could not find the amplgsl.dll library")
        model = ConcreteModel()
        model.gamma = ExternalFunction(library=DLL, function="gsl_sf_gamma")
        model.bessel = ExternalFunction(library=DLL,
                                        function="gsl_sf_bessel_Jnu")
        model.x = Var(initialize=3, bounds=(1e-5, None))
        model.o = Objective(expr=model.gamma(model.x))
        self.assertAlmostEqual(value(model.o), 2.0, 7)

        f = model.bessel.evaluate((
            0.5,
            2.0,
        ))
        self.assertAlmostEqual(f, 0.5130161365618272, 7)

    def test_eval_gsl_error(self):
        DLL = find_GSL()
        if not DLL:
            self.skipTest("Could not find the amplgsl.dll library")
        model = ConcreteModel()
        model.bogus = ExternalFunction(library=DLL, function="bogus_function")
        with self.assertRaisesRegex(
                RuntimeError, "Error: external function 'bogus_function' was "
                "not registered within external library(?s:.*)gsl_sf_gamma"):
            f = model.bogus.evaluate((1, ))

    def test_eval_fgh_gsl_function(self):
        DLL = find_GSL()
        if not DLL:
            self.skipTest("Could not find the amplgsl.dll library")
        model = ConcreteModel()
        model.gamma = ExternalFunction(library=DLL, function="gsl_sf_gamma")
        model.beta = ExternalFunction(library=DLL, function="gsl_sf_beta")
        model.bessel = ExternalFunction(library=DLL,
                                        function="gsl_sf_bessel_Jnu")

        f, g, h = model.gamma.evaluate_fgh((2.0, ))
        self.assertAlmostEqual(f, 1.0, 7)
        self.assertListsAlmostEqual(g, [0.422784335098467], 7)
        self.assertListsAlmostEqual(h, [0.8236806608528794], 7)

        f, g, h = model.beta.evaluate_fgh((
            2.5,
            2.0,
        ), fixed=[1, 1])
        self.assertAlmostEqual(f, 0.11428571428571432, 7)
        self.assertListsAlmostEqual(g, [0.0, 0.0], 7)
        self.assertListsAlmostEqual(h, [0.0, 0.0, 0.0], 7)

        f, g, h = model.beta.evaluate_fgh((
            2.5,
            2.0,
        ), fixed=[0, 1])
        self.assertAlmostEqual(f, 0.11428571428571432, 7)
        self.assertListsAlmostEqual(g, [-0.07836734693877555, 0.0], 7)
        self.assertListsAlmostEqual(h, [0.08135276967930034, 0.0, 0.0], 7)

        f, g, h = model.beta.evaluate_fgh((
            2.5,
            2.0,
        ))
        self.assertAlmostEqual(f, 0.11428571428571432, 7)
        self.assertListsAlmostEqual(
            g, [-0.07836734693877555, -0.11040989614412142], 7)
        self.assertListsAlmostEqual(
            h, [0.08135276967930034, 0.0472839170086535, 0.15194654464270113],
            7)

        f, g, h = model.beta.evaluate_fgh((
            2.5,
            2.0,
        ), fgh=1)
        self.assertAlmostEqual(f, 0.11428571428571432, 7)
        self.assertListsAlmostEqual(
            g, [-0.07836734693877555, -0.11040989614412142], 7)
        self.assertIsNone(h)

        f, g, h = model.beta.evaluate_fgh((
            2.5,
            2.0,
        ), fgh=0)
        self.assertAlmostEqual(f, 0.11428571428571432, 7)
        self.assertIsNone(g)
        self.assertIsNone(h)

        f, g, h = model.bessel.evaluate_fgh((
            2.5,
            2.0,
        ), fixed=[1, 0])
        self.assertAlmostEqual(f, 0.223924531469, 7)
        self.assertListsAlmostEqual(g, [0.0, 0.21138811435101745], 7)
        self.assertListsAlmostEqual(h, [0.0, 0.0, 0.02026349177575621], 7)

        # Note: Not all AMPL-GSL functions honor the fixed flag
        # (notably, gamma and bessel do not as of 12/2021).  We will
        # test that our interface corrects that

        f, g, h = model.gamma.evaluate_fgh((2.0, ), fixed=[1])
        self.assertAlmostEqual(f, 1.0, 7)
        self.assertListsAlmostEqual(g, [0.0], 7)
        self.assertListsAlmostEqual(h, [0.0], 7)

        f, g, h = model.bessel.evaluate_fgh((
            2.5,
            2.0,
        ), fixed=[1, 1])
        self.assertAlmostEqual(f, 0.223924531469, 7)
        self.assertListsAlmostEqual(g, [0.0, 0.0], 7)
        self.assertListsAlmostEqual(h, [0.0, 0.0, 0.0], 7)

    @unittest.skipIf(not check_available_solvers('ipopt'),
                     "The 'ipopt' solver is not available")
    def test_solve_gsl_function(self):
        DLL = find_GSL()
        if not DLL:
            self.skipTest("Could not find the amplgsl.dll library")
        model = ConcreteModel()
        model.z_func = ExternalFunction(library=DLL, function="gsl_sf_gamma")
        model.x = Var(initialize=3, bounds=(1e-5, None))
        model.o = Objective(expr=model.z_func(model.x))
        opt = SolverFactory('ipopt')
        res = opt.solve(model, tee=True)
        self.assertAlmostEqual(value(model.o), 0.885603194411, 7)

    @unittest.skipIf(not check_available_solvers('ipopt'),
                     "The 'ipopt' solver is not available")
    def test_solve_gsl_function_const_arg(self):
        DLL = find_GSL()
        if not DLL:
            self.skipTest("Could not find the amplgsl.dll library")
        model = ConcreteModel()
        model.z_func = ExternalFunction(library=DLL, function="gsl_sf_beta")
        model.x = Var(initialize=1, bounds=(0.1, None))
        model.o = Objective(expr=-model.z_func(1, model.x))
        opt = SolverFactory('ipopt')
        res = opt.solve(model, tee=True)
        self.assertAlmostEqual(value(model.x), 0.1, 5)

    @unittest.skipIf(not check_available_solvers('ipopt'),
                     "The 'ipopt' solver is not available")
    def test_clone_gsl_function(self):
        DLL = find_GSL()
        if not DLL:
            self.skipTest("Could not find the amplgsl.dll library")
        m = ConcreteModel()
        m.z_func = ExternalFunction(library=DLL, function="gsl_sf_gamma")
        self.assertIsInstance(m.z_func, AMPLExternalFunction)
        m.x = Var(initialize=3, bounds=(1e-5, None))
        m.o = Objective(expr=m.z_func(m.x))

        opt = SolverFactory('ipopt')

        # Test a simple clone...
        model2 = m.clone()
        res = opt.solve(model2, tee=True)
        self.assertAlmostEqual(value(model2.o), 0.885603194411, 7)

        # Trigger the library to be loaded.  This tests that the CDLL
        # objects that are created when the SO/DLL are loaded do not
        # interfere with cloning the model.
        self.assertAlmostEqual(value(m.o), 2)
        model3 = m.clone()
        res = opt.solve(model3, tee=True)
        self.assertAlmostEqual(value(model3.o), 0.885603194411, 7)

    def test_pprint(self):
        m = ConcreteModel()
        m.f = ExternalFunction(library="junk.so", function="junk")

        out = StringIO()
        m.pprint(ostream=out)
        self.assertEqual(
            out.getvalue().strip(), """
1 ExternalFunction Declarations
    f : function=junk, library=junk.so, units=None, arg_units=None

1 Declarations: f
        """.strip())

        if not pint_available:
            return
        m.g = ExternalFunction(library="junk.so",
                               function="junk",
                               units=units.kg,
                               arg_units=[units.m, units.s])
        out = StringIO()
        m.pprint(ostream=out)
        self.assertEqual(
            out.getvalue().strip(), """
2 ExternalFunction Declarations
    f : function=junk, library=junk.so, units=None, arg_units=None
    g : function=junk, library=junk.so, units=kg, arg_units=['m', 's']

2 Declarations: f g
        """.strip())
예제 #9
0
import pyutilib.th as unittest
import pyomo.environ as pe
import romodel.examples as ex
from pyomo.opt import check_available_solvers

solvers = check_available_solvers('gurobi_direct', 'ipopt')


class TestE2E(unittest.TestCase):
    @unittest.skipIf('gurobi_direct' not in solvers,
                     'gurobi_direct not available')
    def test_knapsack_reformulation(self):
        m = ex.Knapsack()
        solver = pe.SolverFactory('romodel.reformulation')
        solver.options['solver'] = 'gurobi_direct'
        solver.options['NonConvex'] = 2
        solver.options['TimeLimit'] = 60
        solver.solve(m, tee=False)
        m = ex.Knapsack()
        m.w.uncset = m.P
        solver.solve(m, tee=False)

    @unittest.skipIf('gurobi_direct' not in solvers,
                     'gurobi_direct not available')
    def test_knapsack_cuts(self):
        m = ex.Knapsack()
        solver = pe.SolverFactory('romodel.cuts')
        solver.options['solver'] = 'gurobi_direct'
        solver.options['TimeLimit'] = 60
        solver.solve(m, tee=False)
예제 #10
0
class TestAMPLExternalFunction(unittest.TestCase):
    def assertListsAlmostEqual(self, first, second, places=7, msg=None):
        self.assertEqual(len(first), len(second))
        msg = "lists %s and %s differ at item " % (
            first, second)
        for i,a in enumerate(first):
            self.assertAlmostEqual(a, second[i], places, msg + str(i))

    def test_getname(self):
        m = ConcreteModel()
        m.f = ExternalFunction(library="junk.so", function="junk")
        self.assertIsInstance(m.f, AMPLExternalFunction)
        self.assertEqual(m.f.name, "f")
        self.assertEqual(m.f.local_name, "f")
        self.assertEqual(m.f.getname(), "f")
        self.assertEqual(m.f.getname(True), "f")

        M = ConcreteModel()
        M.m = m
        self.assertEqual(M.m.f.name, "m.f")
        self.assertEqual(M.m.f.local_name, "f")
        self.assertEqual(M.m.f.getname(), "f")
        self.assertEqual(M.m.f.getname(True), "m.f")

    def test_eval_gsl_function(self):
        DLL = find_GSL()
        if not DLL:
            self.skipTest("Could not find the amplgsl.dll library")
        model = ConcreteModel()
        model.gamma = ExternalFunction(
            library=DLL, function="gsl_sf_gamma")
        model.bessel = ExternalFunction(
            library=DLL, function="gsl_sf_bessel_Jnu")
        model.x = Var(initialize=3, bounds=(1e-5,None))
        model.o = Objective(expr=model.gamma(model.x))
        self.assertAlmostEqual(value(model.o), 2.0, 7)

        f = model.bessel.evaluate((0.5, 2.0,))
        self.assertAlmostEqual(f, 0.5130161365618272, 7)

    def test_eval_fgh_gsl_function(self):
        DLL = find_GSL()
        if not DLL:
            self.skipTest("Could not find the amplgsl.dll library")
        model = ConcreteModel()
        model.gamma = ExternalFunction(
            library=DLL, function="gsl_sf_gamma")
        model.bessel = ExternalFunction(
            library=DLL, function="gsl_sf_bessel_Jnu")
        f,g,h = model.gamma.evaluate_fgh((2.0,))
        self.assertAlmostEqual(f, 1.0, 7)
        self.assertListsAlmostEqual(g, [0.422784335098467], 7)
        self.assertListsAlmostEqual(h, [0.8236806608528794], 7)

        f,g,h = model.bessel.evaluate_fgh((2.5, 2.0,), fixed=[1,0])
        self.assertAlmostEqual(f, 0.223924531469, 7)
        self.assertListsAlmostEqual(g, [0.0, 0.21138811435101745], 7)
        self.assertListsAlmostEqual(h, [0.0, 0.0, 0.02026349177575621], 7)

    @unittest.skipIf(not check_available_solvers('ipopt'),
                     "The 'ipopt' solver is not available")
    def test_solve_gsl_function(self):
        DLL = find_GSL()
        if not DLL:
            self.skipTest("Could not find the amplgsl.dll library")
        model = ConcreteModel()
        model.z_func = ExternalFunction(library=DLL, function="gsl_sf_gamma")
        model.x = Var(initialize=3, bounds=(1e-5,None))
        model.o = Objective(expr=model.z_func(model.x))
        opt = SolverFactory('ipopt')
        res = opt.solve(model, tee=True)
        self.assertAlmostEqual(value(model.o), 0.885603194411, 7)

    @unittest.skipIf(not check_available_solvers('ipopt'),
                     "The 'ipopt' solver is not available")
    def test_clone_gsl_function(self):
        DLL = find_GSL()
        if not DLL:
            self.skipTest("Could not find the amplgsl.dll library")
        m = ConcreteModel()
        m.z_func = ExternalFunction(library=DLL, function="gsl_sf_gamma")
        self.assertIsInstance(m.z_func, AMPLExternalFunction)
        m.x = Var(initialize=3, bounds=(1e-5,None))
        m.o = Objective(expr=m.z_func(m.x))

        opt = SolverFactory('ipopt')

        # Test a simple clone...
        model2 = m.clone()
        res = opt.solve(model2, tee=True)
        self.assertAlmostEqual(value(model2.o), 0.885603194411, 7)

        # Trigger the library to be loaded.  This tests that the CDLL
        # objects that are created when the SO/DLL are loaded do not
        # interfere with cloning the model.
        self.assertAlmostEqual(value(m.o), 2)
        model3 = m.clone()
        res = opt.solve(model3, tee=True)
        self.assertAlmostEqual(value(model3.o), 0.885603194411, 7)

    def test_pprint(self):
        m = ConcreteModel()
        m.f = ExternalFunction(library="junk.so", function="junk")

        out = StringIO()
        m.pprint(ostream=out)
        self.assertEqual(out.getvalue().strip(), """
1 ExternalFunction Declarations
    f : function=junk, library=junk.so, units=None, arg_units=None

1 Declarations: f
        """.strip())

        if not pint_available:
            return
        m.g = ExternalFunction(library="junk.so", function="junk",
                               units=units.kg, arg_units=[units.m, units.s])
        out = StringIO()
        m.pprint(ostream=out)
        self.assertEqual(out.getvalue().strip(), """
2 ExternalFunction Declarations
    f : function=junk, library=junk.so, units=None, arg_units=None
    g : function=junk, library=junk.so, units=kg, arg_units=['m', 's']

2 Declarations: f g
        """.strip())
예제 #11
0
"""Tests explicit bound to variable bound transformation module."""
import pyutilib.th as unittest
from pyomo.contrib.gdp_bounds.info import (disjunctive_lb, disjunctive_ub)
from pyomo.environ import (ConcreteModel, Constraint, Objective,
                           TransformationFactory, Var)
from pyomo.gdp import Disjunct, Disjunction
from pyomo.opt import check_available_solvers

solvers = check_available_solvers('cbc')


class TestGDPBounds(unittest.TestCase):
    """Tests disjunctive variable bounds implementation."""

    # @unittest.skipIf('cbc' not in solvers, "CBC solver not available")
    def test_compute_bounds_obbt(self):
        """Test computation of disjunctive bounds."""
        m = ConcreteModel()
        m.x = Var(bounds=(0, 8))
        m.d1 = Disjunct()
        m.d1.c = Constraint(expr=m.x >= 2)
        m.d2 = Disjunct()
        m.d2.c = Constraint(expr=m.x <= 4)
        m.disj = Disjunction(expr=[m.d1, m.d2])
        m.obj = Objective(expr=m.x)
        TransformationFactory('contrib.compute_disj_var_bounds').apply_to(
            m, solver='gams')
        self.assertEqual(m.d1._disj_var_bounds[m.x], (2, 8))
        self.assertEqual(m.d2._disj_var_bounds[m.x], (0, 4))
        self.assertEqual(disjunctive_lb(m.x, m.d1), 2)
        self.assertEqual(disjunctive_ub(m.x, m.d1), 8)
예제 #12
0
class TestPyomoInterfaceInitialization(unittest.TestCase):
    def setUp(self):
        m = ConcreteModel()
        m.z = Var(range(3), domain=Reals)
        for i in range(3):
            m.z[i] = 2.0
        m.x = Var(range(2))
        for i in range(2):
            m.x[i] = 2.0
        m.obj = Objective(expr=(m.z[0] - 1.0)**2 + (m.z[0] - m.z[1])**2 +
                          (m.z[2] - 1.0)**2 + (m.x[0] - 1.0)**4 +
                          (m.x[1] - 1.0)**6)
        m.c2 = Constraint(expr=m.z[2]**4 * m.z[1]**2 + m.z[1] == 8 + sqrt(2.0))
        self.m = m

    def test_1(self):
        '''
        The simplest case that the black box has only two inputs and there is only one black block involved
        '''
        def blackbox(a, b):
            return sin(a - b)

        m = self.m
        bb = ExternalFunction(blackbox)
        m.eflist = [bb]
        m.c1 = Constraint(expr=m.x[0] * m.z[0]**2 + bb(m.x[0], m.x[1]) == 2 *
                          sqrt(2.0))
        pI = PyomoInterface(m, [bb], ConfigBlock())
        self.assertEqual(pI.lx, 2)
        self.assertEqual(pI.ly, 1)
        self.assertEqual(pI.lz, 3)
        self.assertEqual(len(list(identify_variables(m.c1.body))), 3)
        self.assertEqual(len(list(identify_variables(m.c2.body))), 2)

    def test_2(self):
        '''
        The simplest case that the black box has only one inputs and there is only a formula
        '''
        def blackbox(a):
            return sin(a)

        m = self.m
        bb = ExternalFunction(blackbox)
        m.eflist = [bb]
        m.c1 = Constraint(expr=m.x[0] * m.z[0]**2 + bb(m.x[0] - m.x[1]) == 2 *
                          sqrt(2.0))
        pI = PyomoInterface(m, [bb], ConfigBlock())
        self.assertEqual(pI.lx, 1)
        self.assertEqual(pI.ly, 1)
        self.assertEqual(pI.lz, 5)
        self.assertEqual(len(list(identify_variables(m.c1.body))), 3)
        self.assertEqual(len(list(identify_variables(m.c2.body))), 2)
        self.assertEqual(len(m.tR.conset), 1)
        self.assertEqual(len(list(identify_variables(m.tR.conset[1].body))), 3)

    def test_3(self):
        '''
        The simplest case that the black box has only two inputs and there is only one black block involved
        '''
        def blackbox(a, b):
            return sin(a - b)

        m = self.m
        bb = ExternalFunction(blackbox)
        m.eflist = [bb]
        m.c1 = Constraint(expr=m.x[0] * m.z[0]**2 + bb(m.x[0], m.x[1]) == 2 *
                          sqrt(2.0))
        m.c3 = Constraint(expr=m.x[0] * m.z[0]**2 + bb(m.x[0], m.z[1]) == 2 *
                          sqrt(2.0))
        pI = PyomoInterface(m, [bb], ConfigBlock())
        self.assertEqual(pI.lx, 3)
        self.assertEqual(pI.ly, 2)
        self.assertEqual(pI.lz, 2)
        self.assertEqual(len(list(identify_variables(m.c1.body))), 3)
        self.assertEqual(len(list(identify_variables(m.c2.body))), 2)
        self.assertEqual(len(list(identify_variables(m.c3.body))), 3)

    def test_4(self):
        '''
        The simplest case that the black box has only two inputs and there is only one black block involved
        '''
        def blackbox(a, b):
            return sin(a - b)

        m = self.m
        bb = ExternalFunction(blackbox)
        m.eflist = [bb]
        m.c1 = Constraint(expr=m.x[0] * m.z[0]**2 + bb(m.x[0], m.x[1]) == 2 *
                          sqrt(2.0))
        m.c3 = Constraint(expr=m.x[0] * m.z[0]**2 + bb(m.x[0], m.z[1]) == 2 *
                          sqrt(2.0))
        pI = PyomoInterface(m, [bb], ConfigBlock())
        self.assertEqual(pI.lx, 3)
        self.assertEqual(pI.ly, 2)
        self.assertEqual(pI.lz, 2)
        self.assertEqual(len(list(identify_variables(m.c1.body))), 3)
        self.assertEqual(len(list(identify_variables(m.c2.body))), 2)
        self.assertEqual(len(list(identify_variables(m.c3.body))), 3)

    @unittest.skipIf(not check_available_solvers('ipopt'),
                     "The 'ipopt' solver is not available")
    @unittest.skipIf(not check_available_solvers('gjh'),
                     "The 'gjh' solver is not available")
    def test_execute_TRF(self):
        m = ConcreteModel()
        m.z = Var(range(3), domain=Reals, initialize=2.)
        m.x = Var(range(2), initialize=2.)
        m.x[1] = 1.0

        def blackbox(a, b):
            return sin(a - b)

        bb = ExternalFunction(blackbox)

        m.obj = Objective(
            expr=(m.z[0]-1.0)**2 + (m.z[0]-m.z[1])**2 + (m.z[2]-1.0)**2 \
            + (m.x[0]-1.0)**4 + (m.x[1]-1.0)**6 # + m.bb(m.x[0],m.x[1])
        )
        m.c1 = Constraint(expr=m.x[0] * m.z[0]**2 + bb(m.x[0], m.x[1]) == 2 *
                          sqrt(2.0))
        m.c2 = Constraint(expr=m.z[2]**4 * m.z[1]**2 + m.z[1] == 8 + sqrt(2.0))

        SolverFactory('trustregion').solve(m, [bb])

        self.assertAlmostEqual(value(m.obj), 0.277044789315, places=4)
        self.assertAlmostEqual(value(m.x[0]), 1.32193855369, places=4)
        self.assertAlmostEqual(value(m.x[1]), 0.628744699822, places=4)
예제 #13
0
class TestAMPLExternalFunction(unittest.TestCase):
    def assertListsAlmostEqual(self, first, second, places=7, msg=None):
        self.assertEqual(len(first), len(second))
        msg = "lists %s and %s differ at item " % (first, second)
        for i, a in enumerate(first):
            self.assertAlmostEqual(a, second[i], places, msg + str(i))

    def test_getname(self):
        m = ConcreteModel()
        m.f = ExternalFunction(library="junk.so", function="junk")
        self.assertIsInstance(m.f, AMPLExternalFunction)
        self.assertEqual(m.f.name, "f")
        self.assertEqual(m.f.local_name, "f")
        self.assertEqual(m.f.getname(), "f")
        self.assertEqual(m.f.getname(True), "f")

        M = ConcreteModel()
        M.m = m
        self.assertEqual(M.m.f.name, "m.f")
        self.assertEqual(M.m.f.local_name, "f")
        self.assertEqual(M.m.f.getname(), "f")
        self.assertEqual(M.m.f.getname(True), "m.f")

    def test_eval_gsl_function(self):
        DLL = find_GSL()
        if not DLL:
            self.skipTest("Could not find the amplgsl.dll library")
        model = ConcreteModel()
        model.gamma = ExternalFunction(library=DLL, function="gsl_sf_gamma")
        model.bessel = ExternalFunction(library=DLL,
                                        function="gsl_sf_bessel_Jnu")
        model.x = Var(initialize=3, bounds=(1e-5, None))
        model.o = Objective(expr=model.gamma(model.x))
        self.assertAlmostEqual(value(model.o), 2.0, 7)

        f = model.bessel.evaluate((
            0.5,
            2.0,
        ))
        self.assertAlmostEqual(f, 0.5130161365618272, 7)

    def test_eval_fgh_gsl_function(self):
        DLL = find_GSL()
        if not DLL:
            self.skipTest("Could not find the amplgsl.dll library")
        model = ConcreteModel()
        model.gamma = ExternalFunction(library=DLL, function="gsl_sf_gamma")
        model.bessel = ExternalFunction(library=DLL,
                                        function="gsl_sf_bessel_Jnu")
        f, g, h = model.gamma.evaluate_fgh((2.0, ))
        self.assertAlmostEqual(f, 1.0, 7)
        self.assertListsAlmostEqual(g, [0.422784335098467], 7)
        self.assertListsAlmostEqual(h, [0.8236806608528794], 7)

        f, g, h = model.bessel.evaluate_fgh((
            2.5,
            2.0,
        ), fixed=[1, 0])
        self.assertAlmostEqual(f, 0.223924531469, 7)
        self.assertListsAlmostEqual(g, [0.0, 0.21138811435101745], 7)
        self.assertListsAlmostEqual(h, [0.0, 0.0, 0.02026349177575621], 7)

    @unittest.skipIf(not check_available_solvers('ipopt'),
                     "The 'ipopt' solver is not available")
    def test_solve_gsl_function(self):
        DLL = find_GSL()
        if not DLL:
            self.skipTest("Could not find the amplgsl.dll library")
        model = ConcreteModel()
        model.z_func = ExternalFunction(library=DLL, function="gsl_sf_gamma")
        model.x = Var(initialize=3, bounds=(1e-5, None))
        model.o = Objective(expr=model.z_func(model.x))
        opt = SolverFactory('ipopt')
        res = opt.solve(model, tee=True)
        self.assertAlmostEqual(value(model.o), 0.885603194411, 7)
예제 #14
0
"""Tests explicit bound to variable bound transformation module."""
import pyutilib.th as unittest
from pyomo.contrib.gdp_bounds.info import (
    disjunctive_lb, disjunctive_ub)
from pyomo.environ import (ConcreteModel, Constraint, Objective,
                           TransformationFactory, Var)
from pyomo.gdp import Disjunct, Disjunction
from pyomo.opt import check_available_solvers

solvers = check_available_solvers('cbc')


class TestGDPBounds(unittest.TestCase):
    """Tests disjunctive variable bounds implementation."""

    @unittest.skipIf('cbc' not in solvers, "CBC solver not available")
    def test_compute_bounds_obbt(self):
        """Test computation of disjunctive bounds."""
        m = ConcreteModel()
        m.x = Var(bounds=(0, 8))
        m.d1 = Disjunct()
        m.d1.c = Constraint(expr=m.x >= 2)
        m.d2 = Disjunct()
        m.d2.c = Constraint(expr=m.x <= 4)
        m.disj = Disjunction(expr=[m.d1, m.d2])
        m.obj = Objective(expr=m.x)
        TransformationFactory('contrib.compute_disj_var_bounds').apply_to(m, solver='cbc')
        self.assertEqual(m.d1._disj_var_bounds[m.x], (2, 8))
        self.assertEqual(m.d2._disj_var_bounds[m.x], (0, 4))
        self.assertEqual(disjunctive_lb(m.x, m.d1), 2)
        self.assertEqual(disjunctive_ub(m.x, m.d1), 8)
예제 #15
0
try:
    if subprocess.call(["dot", "-?"],
                       stdout=subprocess.PIPE,
                       stderr=subprocess.STDOUT):
        have_dot = False
except:
    have_dot = False

thisdir = dirname(abspath(__file__))
baselineDir = join(thisdir, "baselines")
pysp_examples_dir = \
    join(dirname(dirname(dirname(dirname(thisdir)))),
         "examples", "pysp")
examples_dir = join(pysp_examples_dir, "scripting")

solvers = check_available_solvers('cplex', 'glpk')


@unittest.category('nightly')
class TestExamples(unittest.TestCase):
    def setUp(self):
        self._tempfiles = []

    def _run_cmd(self, cmd):
        class_name, test_name = self.id().split('.')[-2:]
        print("%s.%s: Testing command: %s" %
              (class_name, test_name, str(' '.join(cmd))))
        outname = os.path.join(thisdir, class_name + "." + test_name + ".out")
        self._tempfiles.append(outname)
        with open(outname, "w") as f:
            subprocess.check_call(cmd, stdout=f, stderr=subprocess.STDOUT)
예제 #16
0
#  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.
#  ___________________________________________________________________________

# -*- coding: UTF-8 -*-
"""Tests disjunct fixing."""
import pyomo.common.unittest as unittest
from pyomo.environ import (Block, Constraint, ConcreteModel,
                           TransformationFactory, NonNegativeReals, BooleanVar,
                           LogicalConstraint, SolverFactory, Objective, value,
                           Var, implies)
from pyomo.gdp import Disjunct, Disjunction, GDP_Error
from pyomo.opt import check_available_solvers

solvers = check_available_solvers('gurobi')


class TestFixDisjuncts(unittest.TestCase):
    """Tests fixing of disjuncts."""
    def test_fix_disjunct(self):
        """Test for deactivation of trivial constraints."""
        m = ConcreteModel()
        m.d1 = Disjunct()
        m.d2 = Disjunct()
        m.d2.c = Constraint()
        m.d = Disjunction(expr=[m.d1, m.d2])
        m.d1.indicator_var.set_value(True)
        m.d2.indicator_var.set_value(False)

        TransformationFactory('gdp.fix_disjuncts').apply_to(m)
예제 #17
0
 def setUpClass(cls):
     global solvers
     import pyomo.environ
     solvers = check_available_solvers('glpk')
예제 #18
0
have_networkx = False
try:
    import networkx
    have_networkx = True
except ImportError:
    have_networkx = False

thisdir = dirname(abspath(__file__))
baselineDir = join(thisdir, "baselines")
pysp_examples_dir = \
    join(dirname(dirname(dirname(dirname(thisdir)))),
         "examples", "pysp")
examples_dir = join(pysp_examples_dir, "scripting")

solvers = check_available_solvers('cplex', 'glpk')

@unittest.category('nightly','expensive')
class TestExamples(unittest.TestCase):

    def setUp(self):
        self._tempfiles = []

    def _run_cmd(self, cmd):
        class_name, test_name = self.id().split('.')[-2:]
        print("%s.%s: Testing command: %s" % (class_name,
                                              test_name,
                                              str(' '.join(cmd))))
        outname = os.path.join(thisdir,
                               class_name+"."+test_name+".out")
        self._tempfiles.append(outname)