Example #1
0
def configure_cbc():
    global _cbc_compiled_with_asl
    global _cbc_version
    global _cbc_old_version
    if _cbc_compiled_with_asl is not None:
        return
    # manually look for the cbc executable to prevent the
    # CBC.execute() from logging an error when CBC is missing
    executable = Executable("cbc")
    if not executable:
        return
    cbc_exec = executable.path()
    results = subprocess.run([cbc_exec, "-stop"],
                             timeout=1,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT,
                             universal_newlines=True)
    _cbc_version = _extract_version(results.stdout)
    results = subprocess.run([cbc_exec, "dummy", "-AMPL", "-stop"],
                             timeout=1,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT,
                             universal_newlines=True)
    _cbc_compiled_with_asl = not ('No match for AMPL' in results.stdout)
    if _cbc_version is not None:
        _cbc_old_version = _cbc_version < (2, 7, 0, 0)
Example #2
0
 def test_mod_lp2(self):
     #""" Convert from MOD+DAT to LP """
     try:
         ans = convert_problem(
             (join(currdir, "test5.mod"), join(currdir, "test5.dat")), None,
             [ProblemFormat.cpxlp])
     except ApplicationError:
         err = sys.exc_info()[1]
         if Executable("glpsol").available():
             self.fail("Unexpected ApplicationError - glpsol is "
                       "enabled but not available: '%s'" % str(err))
         return
     except ConverterError:
         err = sys.exc_info()[1]
         if Executable("glpsol").available():
             self.fail("Unexpected ConverterError - glpsol is "
                       "enabled but not available: '%s'" % str(err))
         return
     self.assertTrue(ans[0][0].endswith("glpsol.lp"))
     with open(ans[0][0],
               'r') as f1, open(join(currdir, "test3_convert.lp"),
                                'r') as f2:
         for line1, line2 in zip_longest(f1, f2):
             if 'Problem' in line1:
                 continue
             self.assertEqual(line1, line2)
Example #3
0
 def _default_executable(self):
     executable = Executable("PICO_deprecated_not_supported")
     if not executable:
         logger.warning("Could not locate the 'PICO' executable, "
                        "which is required for solver %s" % self.name)
         self.enable = False
         return None
     return executable.path()
Example #4
0
 def _default_executable(self):
     executable = Executable("cbc")
     if not executable:
         logger.warning("Could not locate the 'cbc' executable, which is "
                        "required for solver %s" % self.name)
         self.enable = False
         return None
     return executable.path()
Example #5
0
 def _default_executable(self):
     executable = Executable("pathampl")
     if not executable:  #pragma:nocover
         logger.warning("Could not locate the 'pathampl' executable, "
                        "which is required for solver %s" % self.name)
         self.enable = False
         return None
     return executable.path()
Example #6
0
 def _default_executable(self):
     executable = Executable("optimizer")
     if not executable:
         logger.warning("Could not locate the 'optimizer' executable, "
                        "which is required for solver %s" % self.name)
         self.enable = False
         return None
     return executable.path()
Example #7
0
File: GLPK.py Project: Pyomo/pyomo
 def _default_executable(self):
     executable = Executable('glpsol')
     if not executable:
         msg = ("Could not locate the 'glpsol' executable, which is "
                "required for solver '%s'")
         logger.warning(msg % self.name)
         self.enable = False
         return None
     return executable.path()
Example #8
0
 def _default_executable(self):
     executable = Executable('glpsol')
     if not executable:
         msg = ("Could not locate the 'glpsol' executable, which is "
                "required for solver '%s'")
         logger.warning(msg % self.name)
         self.enable = False
         return None
     return executable.path()
Example #9
0
def configure_glpk():
    global _glpk_version
    if _glpk_version is not None:
        return
    _glpk_version = _extract_version("")
    if not Executable("glpsol"):
        return
    errcode, results = pyutilib.subprocess.run(
        [Executable('glpsol').path(), "--version"], timelimit=2)
    if errcode == 0:
        _glpk_version = _extract_version(results)
Example #10
0
 def _default_executable(self):
     if sys.platform == 'win32':
         executable = Executable("gurobi.bat")
     else:
         executable = Executable("gurobi.sh")
     if not executable:
         logger.warning("Could not locate the 'gurobi' executable, "
                        "which is required for solver %s" % self.name)
         self.enable = False
         return None
     return executable.path()
Example #11
0
 def test_error9(self):
     #""" The Opt configuration has not been initialized """
     cmd = Executable("pico_convert").disable()
     try:
         ans = convert_problem((join(currdir, "test4.nl"), ), None,
                               [ProblemFormat.cpxlp])
         self.fail(
             "This test didn't fail, but pico_convert should not be defined."
         )
     except ConverterError:
         pass
     cmd = Executable("pico_convert").rehash()
Example #12
0
def configure_glpk():
    global _glpk_version
    if _glpk_version is not None:
        return
    _glpk_version = _extract_version("")
    if not Executable("glpsol"):
        return
    result = subprocess.run([Executable('glpsol').path(), "--version"],
                            stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                            timeout=1, universal_newlines=True)
    if not result.returncode:
        _glpk_version = _extract_version(result.stdout)
Example #13
0
 def _default_executable(self):
     """In addition to looking for the petsc executable, optionally check for
     a WSL batch file on Windows. Users could potentially also compile a
     cygwin exectable on Windows, so WSL isn't the only option, but it is the
     easiest for Windows."""
     executable = False
     if not self._wsl or self._wsl is None:
         executable = Executable("petsc")
     if sys.platform.startswith("win32") and (not executable):
         # On Windows, if wsl was requested or a normal petsc solver
         # executable was not found, look for a batch file to run it with WSL
         executable = Executable("petsc_wsl.bat")
     if not executable:
         raise RuntimeError("No PETSc executable found.")
     return executable.path()
Example #14
0
def configure_cbc():
    global _cbc_compiled_with_asl
    global _cbc_version
    global _cbc_old_version
    if _cbc_compiled_with_asl is not None:
        return
    # manually look for the cbc executable to prevent the
    # CBC.execute() from logging an error when CBC is missing
    executable = Executable("cbc")
    if not executable:
        return
    cbc_exec = executable.path()
    results = run([cbc_exec, "-stop"], timelimit=1)
    _cbc_version = _extract_version(results[1])
    results = run([cbc_exec, "dummy", "-AMPL", "-stop"], timelimit=1)
    _cbc_compiled_with_asl = not ('No match for AMPL' in results[1])
    if _cbc_version is not None:
        _cbc_old_version = _cbc_version < (2, 7, 0, 0)
Example #15
0
 def test_mod_nl1(self):
     #""" Convert from MOD to NL """
     try:
         ans = convert_problem((join(currdir, "test3.mod"), ), None,
                               [ProblemFormat.nl])
     except ApplicationError:
         err = sys.exc_info()[1]
         if Executable("ampl").available():
             self.fail("Unexpected ApplicationError - ampl is "
                       "enabled but not available: '%s'" % str(err))
         return
     except ConverterError:
         err = sys.exc_info()[1]
         if Executable("ampl").available():
             self.fail("Unexpected ConverterError - ampl is "
                       "enabled but not available: '%s'" % str(err))
         return
     self.assertTrue(ans[0][0].endswith('.nl'))
Example #16
0
 def test_nl_lp1(self):
     #""" Convert from NL to LP """
     try:
         ans = convert_problem((currdir + "test4.nl", ), None,
                               [ProblemFormat.cpxlp])
     except ApplicationError:
         err = sys.exc_info()[1]
         if Executable("pico_convert").available():
             self.fail("Unexpected ApplicationError - pico_convert is "
                       "enabled but not available: '%s'" % str(err))
         return
     except ConverterError:
         err = sys.exc_info()[1]
         if Executable("pico_convert").available():
             self.fail("Unexpected ConverterError - pico_convert is "
                       "enabled but not available: '%s'" % str(err))
         return
     self.assertEqual(ans[0][0][-15:], "pico_convert.lp")
     self.assertFileEqualsBaseline(ans[0][0], currdir + "test1_convert.lp")
Example #17
0
 def _default_executable(self):
     #
     # We register the ASL executables dynamically, since _any_ ASL solver could be
     # executed by this solver.
     #
     if self.options.solver is None:
         logger.warning("No solver option specified for ASL solver interface")
         return None
     if not self.options.solver:
         logger.warning(
             "No solver option specified for ASL solver interface")
         return None
     executable = Executable(self.options.solver)
     if not executable:
         logger.warning(
             "Could not locate the '%s' executable, which is required "
             "for solver %s" % (self.options.solver, self.name))
         self.enable = False
         return None
     return executable.path()
Example #18
0
 def test_mod_lp1(self):
     #""" Convert from MOD to LP """
     try:
         ans = convert_problem((currdir + "test3.mod", ), None,
                               [ProblemFormat.cpxlp])
     except ApplicationError:
         err = sys.exc_info()[1]
         if Executable("glpsol").available():
             self.fail("Unexpected ApplicationError - glpsol is "
                       "enabled but not available: '%s'" % str(err))
         return
     except ConverterError:
         err = sys.exc_info()[1]
         if Executable("glpsol").available():
             self.fail("Unexpected ConverterError - glpsol is "
                       "enabled but not available: '%s'" % str(err))
         return
     self.assertTrue(ans[0][0].endswith("glpsol.lp"))
     self.assertFileEqualsBaseline(ans[0][0],
                                   currdir + "test2_convert.lp",
                                   filter=filter)
Example #19
0
 def test_nl_lp1(self):
     #""" Convert from NL to LP """
     try:
         ans = convert_problem((join(currdir, "test4.nl"), ), None,
                               [ProblemFormat.cpxlp])
     except ApplicationError:
         err = sys.exc_info()[1]
         if Executable("pico_convert").available():
             self.fail("Unexpected ApplicationError - pico_convert is "
                       "enabled but not available: '%s'" % str(err))
         return
     except ConverterError:
         err = sys.exc_info()[1]
         if Executable("pico_convert").available():
             self.fail("Unexpected ConverterError - pico_convert is "
                       "enabled but not available: '%s'" % str(err))
         return
     self.assertEqual(ans[0][0][-15:], "pico_convert.lp")
     _out, _log = ans[0][0], join(currdir, "test1_convert.lp")
     self.assertTrue(cmp(_out, _log),
                     msg="Files %s and %s differ" % (_out, _log))
Example #20
0
 def test_error8(self):
     #""" Error when source file cannot be found """
     try:
         ans = convert_problem((join(currdir, "unknown.nl"), ), None,
                               [ProblemFormat.cpxlp])
         self.fail("Expected ConverterError exception")
     except ApplicationError:
         err = sys.exc_info()[1]
         if not Executable("pico_convert"):
             self.fail("Expected ApplicationError because pico_convert "
                       "is not available: '%s'" % str(err))
         return
     except ConverterError:
         pass
Example #21
0
 def test_mock_lp2(self):
     #""" Convert from NL to LP """
     arg = MockArg2()
     try:
         ans = convert_problem((arg, ), None, [ProblemFormat.cpxlp])
     except ConverterError:
         err = sys.exc_info()[1]
         if not Executable("pico_convert"):
             return
         else:
             self.fail("Expected ApplicationError because pico_convert "
                       "is not available: '%s'" % str(err))
     self.assertEqual(ans[0][0][-15:], "pico_convert.lp")
     os.remove(ans[0][0])
Example #22
0
 def Xtest_mock_mps1(self):
     #""" Convert from Pyomo to MPS """
     arg = MockArg4()
     try:
         ans = convert_problem((arg, ProblemFormat.mps, arg), None,
                               [ProblemFormat.mps])
     except ConverterError:
         err = sys.exc_info()[1]
         if not Executable("pico_convert"):
             return
         else:
             self.fail("Expected ApplicationError because pico_convert "
                       "is not available: '%s'" % str(err))
     self.assertEqual(ans[0][0][-16:], "pico_convert.mps")
     os.remove(ans[0][0])
Example #23
0
 def test_pyomo_mps1(self):
     #""" Convert from Pyomo to MPS with file"""
     try:
         ans = convert_problem((
             join(currdir, 'model.py'),
             ProblemFormat.mps,
         ), None, [ProblemFormat.mps])
     except ConverterError:
         err = sys.exc_info()[1]
         if not Executable("pico_convert"):
             return
         else:
             self.fail("Expected ApplicationError because pico_convert "
                       "is not available: '%s'" % str(err))
     self.assertEqual(ans[0][0][-16:], "pico_convert.mps")
     os.remove(ans[0][0])
Example #24
0
 def test_error11(self):
     #""" Cannot convert MOD that contains data """
     try:
         ans = convert_problem(
             (join(currdir, "test3.mod"), join(currdir, "test5.dat")), None,
             [ProblemFormat.cpxlp])
         self.fail(
             "Expected ConverterError exception because we provided a MOD file with a 'data;' declaration"
         )
     except ApplicationError:
         err = sys.exc_info()[1]
         if Executable("glpsol"):
             self.fail("Expected ApplicationError because glpsol "
                       "is not available: '%s'" % str(err))
         return
     except ConverterError:
         pass
Example #25
0
class Test(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        import pyomo.environ

    def setUp(self):
        TempfileManager.push()

    def tearDown(self):
        TempfileManager.pop(remove=deleteFiles or self.currentTestPassed())

    def test_nl_nl1(self):
        #""" Convert from NL to NL """
        ans = convert_problem(("test4.nl", ), None, [ProblemFormat.nl])
        self.assertEqual(ans[0], ("test4.nl", ))

    def test_nl_nl2(self):
        #""" Convert from NL to NL """
        ans = convert_problem(("test4.nl", "tmp.nl"), None, [ProblemFormat.nl])
        self.assertEqual(ans[0], ("test4.nl", "tmp.nl"))

    @unittest.skipUnless(
        Executable("pico_convert").available(), 'pico_convert required')
    def test_nl_lp1(self):
        #""" Convert from NL to LP """
        ans = convert_problem((join(currdir, "test4.nl"), ), None,
                              [ProblemFormat.cpxlp])
        self.assertEqual(ans[0][0][-15:], "pico_convert.lp")
        _out, _log = ans[0][0], join(currdir, "test1_convert.lp")
        self.assertTrue(cmp(_out, _log),
                        msg="Files %s and %s differ" % (_out, _log))

    @unittest.skipUnless(Executable("glpsol").available(), 'glpsol required')
    def test_mod_lp1(self):
        #""" Convert from MOD to LP """
        ans = convert_problem((join(currdir, "test3.mod"), ), None,
                              [ProblemFormat.cpxlp])
        self.assertTrue(ans[0][0].endswith("glpsol.lp"))
        with open(ans[0][0],
                  'r') as f1, open(join(currdir, "test2_convert.lp"),
                                   'r') as f2:
            for line1, line2 in zip_longest(f1, f2):
                if 'Problem' in line1:
                    continue
                self.assertEqual(line1, line2)

    @unittest.skipUnless(Executable("glpsol").available(), 'glpsol required')
    def test_mod_lp2(self):
        #""" Convert from MOD+DAT to LP """
        ans = convert_problem(
            (join(currdir, "test5.mod"), join(currdir, "test5.dat")), None,
            [ProblemFormat.cpxlp])
        self.assertTrue(ans[0][0].endswith("glpsol.lp"))
        with open(ans[0][0],
                  'r') as f1, open(join(currdir, "test3_convert.lp"),
                                   'r') as f2:
            for line1, line2 in zip_longest(f1, f2):
                if 'Problem' in line1:
                    continue
                self.assertEqual(line1, line2)

    @unittest.skipUnless(Executable("ampl").available(), 'ampl required')
    def test_mod_nl1(self):
        #""" Convert from MOD to NL """
        ans = convert_problem((join(currdir, "test3.mod"), ), None,
                              [ProblemFormat.nl])
        self.assertTrue(ans[0][0].endswith('.nl'))
        #self.assertFileEqualsBinaryFile(ans[0][0], join(currdir, "test_mod_nl1.nl")

    @unittest.skipUnless(Executable("ampl").available(), 'ampl required')
    def test_mod_nl2(self):
        #""" Convert from MOD+DAT to NL """
        ans = convert_problem(
            (join(currdir, "test5.mod"), join(currdir, "test5.dat")), None,
            [ProblemFormat.nl])
        self.assertTrue(ans[0][0].endswith('.nl'))
        #self.assertTrue(cmp(ans[0][0], join(currdir, "test_mod_nl2.nl")

    def test_mock_lp1(self):
        #""" Convert from Pyomo to LP """
        arg = MockArg()
        ans = convert_problem((arg, ProblemFormat.cpxlp, arg), None,
                              [ProblemFormat.cpxlp])
        self.assertNotEqual(re.match(".*tmp.*pyomo.lp$", ans[0][0]), None)

    def test_pyomo_lp1(self):
        #""" Convert from Pyomo to LP with file"""
        ans = convert_problem((
            join(currdir, 'model.py'),
            ProblemFormat.cpxlp,
        ), None, [ProblemFormat.cpxlp])
        self.assertNotEqual(re.match(".*tmp.*pyomo.lp$", ans[0][0]), None)

    def test_mock_lp2(self):
        #""" Convert from NL to LP """
        arg = MockArg2()
        try:
            ans = convert_problem((arg, ), None, [ProblemFormat.cpxlp])
        except ConverterError:
            err = sys.exc_info()[1]
            if not Executable("pico_convert"):
                return
            else:
                self.fail("Expected ApplicationError because pico_convert "
                          "is not available: '%s'" % str(err))
        self.assertEqual(ans[0][0][-15:], "pico_convert.lp")
        os.remove(ans[0][0])

    # Note sure what to do with this test now that we
    # have a native MPS converter
    def Xtest_mock_mps1(self):
        #""" Convert from Pyomo to MPS """
        arg = MockArg4()
        try:
            ans = convert_problem((arg, ProblemFormat.mps, arg), None,
                                  [ProblemFormat.mps])
        except ConverterError:
            err = sys.exc_info()[1]
            if not Executable("pico_convert"):
                return
            else:
                self.fail("Expected ApplicationError because pico_convert "
                          "is not available: '%s'" % str(err))
        self.assertEqual(ans[0][0][-16:], "pico_convert.mps")
        os.remove(ans[0][0])

    def test_pyomo_mps1(self):
        #""" Convert from Pyomo to MPS with file"""
        try:
            ans = convert_problem((
                join(currdir, 'model.py'),
                ProblemFormat.mps,
            ), None, [ProblemFormat.mps])
        except ConverterError:
            err = sys.exc_info()[1]
            if not Executable("pico_convert"):
                return
            else:
                self.fail("Expected ApplicationError because pico_convert "
                          "is not available: '%s'" % str(err))
        self.assertEqual(ans[0][0][-16:], "pico_convert.mps")
        os.remove(ans[0][0])

    def test_mock_nl1(self):
        #""" Convert from Pyomo to NL """
        arg = MockArg4()
        ans = convert_problem((arg, ProblemFormat.nl, arg), None,
                              [ProblemFormat.nl])
        self.assertNotEqual(re.match(".*tmp.*pyomo.nl$", ans[0][0]), None)
        os.remove(ans[0][0])

    def test_pyomo_nl1(self):
        #""" Convert from Pyomo to NL with file"""
        ans = convert_problem((
            join(currdir, 'model.py'),
            ProblemFormat.nl,
        ), None, [ProblemFormat.nl])
        self.assertNotEqual(re.match(".*tmp.*pyomo.nl$", ans[0][0]), None)
        os.remove(ans[0][0])

    def test_error1(self):
        #""" No valid problem types """
        try:
            convert_problem(("test4.nl", "tmp.nl"), ProblemFormat.nl, [])
            self.fail("Expected ConverterError exception")
        except ConverterError:
            err = sys.exc_info()[1]
            pass

    def test_error2(self):
        #""" Target problem type is not valid """
        try:
            convert_problem(("test4.nl", "tmp.nl"), ProblemFormat.nl,
                            [ProblemFormat.mps])
            self.fail("Expected ConverterError exception")
        except ConverterError:
            pass

    def test_error3(self):
        #""" Empty argument list """
        try:
            convert_problem((), None, [ProblemFormat.mps])
            self.fail("Expected ConverterError exception")
        except ConverterError:
            pass

    def test_error4(self):
        #""" Unknown source type """
        try:
            convert_problem(("prob.foo", ), None, [ProblemFormat.mps])
            self.fail("Expected ConverterError exception")
        except ConverterError:
            pass

    def test_error5(self):
        #""" Unknown source type """
        try:
            convert_problem(("prob.lp", ), ProblemFormat.nl,
                            [ProblemFormat.nl])
            self.fail("Expected ConverterError exception")
        except ConverterError:
            pass

    def test_error6(self):
        #""" Cannot use pico_convert with more than one file """
        try:
            ans = convert_problem((join(currdir, "test4.nl"), "foo"), None,
                                  [ProblemFormat.cpxlp])
            self.fail("Expected ConverterError exception")
        except ConverterError:
            pass

    def test_error8(self):
        #""" Error when source file cannot be found """
        try:
            ans = convert_problem((join(currdir, "unknown.nl"), ), None,
                                  [ProblemFormat.cpxlp])
            self.fail("Expected ConverterError exception")
        except ApplicationError:
            err = sys.exc_info()[1]
            if not Executable("pico_convert"):
                self.fail("Expected ApplicationError because pico_convert "
                          "is not available: '%s'" % str(err))
            return
        except ConverterError:
            pass

    def test_error9(self):
        #""" The Opt configuration has not been initialized """
        cmd = Executable("pico_convert").disable()
        try:
            ans = convert_problem((join(currdir, "test4.nl"), ), None,
                                  [ProblemFormat.cpxlp])
            self.fail(
                "This test didn't fail, but pico_convert should not be defined."
            )
        except ConverterError:
            pass
        cmd = Executable("pico_convert").rehash()

    def test_error10(self):
        #""" GLPSOL can only convert file data """
        try:
            arg = MockArg3()
            ans = convert_problem((arg, ProblemFormat.cpxlp, arg), None,
                                  [ProblemFormat.cpxlp])
            self.fail(
                "This test didn't fail, but glpsol cannot handle objects.")
        except ConverterError:
            pass

    def test_error11(self):
        #""" Cannot convert MOD that contains data """
        try:
            ans = convert_problem(
                (join(currdir, "test3.mod"), join(currdir, "test5.dat")), None,
                [ProblemFormat.cpxlp])
            self.fail(
                "Expected ConverterError exception because we provided a MOD file with a 'data;' declaration"
            )
        except ApplicationError:
            err = sys.exc_info()[1]
            if Executable("glpsol"):
                self.fail("Expected ApplicationError because glpsol "
                          "is not available: '%s'" % str(err))
            return
        except ConverterError:
            pass