Пример #1
0
 def test_get_primal(self):
     self.assertEqual(self.var.primal, None)
     model = Model(problem=gurobipy.read(TESTMODELPATH))
     model.optimize()
     for i, j in zip([var.primal for var in model.variables], [
             0.8739215069684306, -16.023526143167608,
             16.023526143167604, -14.71613956874283, 14.71613956874283,
             4.959984944574658, 4.959984944574657, 4.959984944574658,
             3.1162689467973905e-29, 2.926716099010601e-29, 0.0, 0.0,
             -6.112235045340358e-30, -5.6659435396316186e-30, 0.0,
             -4.922925402711085e-29, 0.0, 9.282532599166613, 0.0,
             6.00724957535033, 6.007249575350331, 6.00724957535033,
             -5.064375661482091, 1.7581774441067828, 0.0,
             7.477381962160285, 0.0, 0.22346172933182767,
             45.514009774517454, 8.39, 0.0, 6.007249575350331, 0.0,
             -4.541857463865631, 0.0, 5.064375661482091, 0.0, 0.0,
             2.504309470368734, 0.0, 0.0, -22.809833310204958,
             22.809833310204958, 7.477381962160285, 7.477381962160285,
             1.1814980932459636, 1.496983757261567, -0.0, 0.0,
             4.860861146496815, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
             5.064375661482091, 0.0, 5.064375661482091, 0.0, 0.0,
             1.496983757261567, 10.000000000000002, -10.0, 0.0, 0.0,
             0.0, 0.0, 0.0, -29.175827135565804, 43.598985311997524,
             29.175827135565804, 0.0, 0.0, 0.0, -1.2332237321082153e-29,
             3.2148950476847613, 38.53460965051542, 5.064375661482091,
             0.0, -1.2812714099825612e-29, -1.1331887079263237e-29,
             17.530865429786694, 0.0, 0.0, 0.0, 4.765319193197458,
             -4.765319193197457, 21.79949265599876, -21.79949265599876,
             -3.2148950476847613, 0.0, -2.281503094067127,
             2.6784818505075303, 0.0
     ]):
         self.assertAlmostEqual(i, j)
Пример #2
0
 def test_gurobi_create_empty_model(self):
     model = Model()
     self.assertEqual(model.problem.getAttr('NumVars'), 0)
     self.assertEqual(model.problem.getAttr('NumConstrs'), 0)
     self.assertEqual(model.name, None)
     self.assertEqual(model.problem.getAttr('ModelName'), '')
     model = Model(name="empty_problem")
     self.assertEqual(model.problem.getAttr('ModelName'), 'empty_problem')
        def test_netlib(netlib_tar_path=os.path.join(os.path.dirname(__file__), 'data/netlib_lp_problems.tar.gz')):
            """
            Test netlib with glpk interface
            """
            tar = tarfile.open(netlib_tar_path)
            model_paths_in_tar = glob.fnmatch.filter(tar.getnames(), '*.SIF')

            for model_path_in_tar in model_paths_in_tar:
                print(model_path_in_tar)
                netlib_id = os.path.basename(model_path_in_tar).replace('.SIF', '')
                # TODO: get the following problems to work
                # E226 seems to be a MPS related problem, see http://lists.gnu.org/archive/html/bug-glpk/2003-01/msg00003.html
                if netlib_id in ('AGG', 'E226', 'SCSD6', 'BLEND', 'DFL001', 'FORPLAN', 'GFRD-PNC', 'SIERRA'):
                    # def test_skip(netlib_id):
                    # raise SkipTest('Skipping netlib problem %s ...' % netlib_id)
                    # test_skip(netlib_id)
                    # class TestWeirdNetlibProblems(unittest.TestCase):

                    # @unittest.skip('Skipping netlib problem')
                    # def test_fail():
                    # pass
                    continue
                # TODO: For now, test only models that are covered by the final netlib results
                else:
                    if netlib_id not in THE_FINAL_NETLIB_RESULTS.keys():
                        continue
                    fhandle = tar.extractfile(model_path_in_tar)
                    problem = read_netlib_sif_gurobi(fhandle)
                    model = Model(problem=problem)
                    model.configuration.presolve = True
                    model.configuration.verbosity = 3
                    func = partial(check_dimensions, problem, model)
                    func.description = "test_netlib_check_dimensions_%s (%s)" % (
                        netlib_id, os.path.basename(str(__file__)))
                    yield func

                    model.optimize()
                    if model.status == 'optimal':
                        model_objval = model.objective.value
                    else:
                        raise Exception('No optimal solution found for netlib model %s' % netlib_id)

                    func = partial(check_objval, problem, model_objval)
                    func.description = "test_netlib_check_objective_value_%s (%s)" % (
                        netlib_id, os.path.basename(str(__file__)))
                    yield func

                    func = partial(check_objval_against_the_final_netlib_results, netlib_id, model_objval)
                    func.description = "test_netlib_check_objective_value__against_the_final_netlib_results_%s (%s)" % (
                        netlib_id, os.path.basename(str(__file__)))
                    yield func
Пример #4
0
        def test_qp_convex(self):
            model = Model(problem=gurobipy.read(CONVEX_QP_PATH))
            self.assertEqual(len(model.variables), 651)
            self.assertEqual(len(model.constraints), 501)
            for constraint in model.constraints:
                self.assertTrue(
                    constraint.is_Linear,
                    "%s should be linear" % (str(constraint.expression)))
                self.assertFalse(
                    constraint.is_Quadratic, "%s should not be quadratic" %
                    (str(constraint.expression)))

            self.assertTrue(model.objective.is_Quadratic,
                            "objective should be quadratic")
            self.assertFalse(model.objective.is_Linear,
                             "objective should not be linear")

            model.optimize()
            self.assertAlmostEqual(model.objective.value, 32.2291282)
Пример #5
0
 def test_changing_variable_names_is_reflected_in_the_solver(self):
     model = Model(problem=gurobipy.read(TESTMODELPATH))
     for i, variable in enumerate(model.variables):
         print(variable._internal_variable is not None)
         print(variable.problem.name)
         variable.name = "var" + str(i)
         print(variable.problem.name)
         print(variable.name)
         print(variable._internal_variable is not None)
         self.assertEqual(variable.name, "var" + str(i))
         self.assertEqual(variable._internal_variable.getAttr('VarName'), "var" + str(i))
Пример #6
0
    class ObjectiveTestCase(abstract_test_cases.AbstractObjectiveTestCase):
        interface = gurobi_interface

        def setUp(self):
            problem = gurobipy.read(TESTMODELPATH)
            self.model = Model(problem=problem)
            self.obj = self.model.objective

        def test_change_direction(self):
            self.obj.direction = "min"
            self.assertEqual(self.obj.direction, "min")
            self.assertEqual(self.model.problem.getAttr('ModelSense'), gurobipy.GRB.MAXIMIZE)
            self.model.update()
            self.assertEqual(self.model.problem.getAttr('ModelSense'), gurobipy.GRB.MINIMIZE)

            self.obj.direction = "max"
            self.assertEqual(self.obj.direction, "max")
            self.assertEqual(self.model.problem.getAttr('ModelSense'), gurobipy.GRB.MINIMIZE)
            self.model.update()
            self.assertEqual(self.model.problem.getAttr('ModelSense'), gurobipy.GRB.MAXIMIZE)
Пример #7
0
    def load_problem(mps_file):
        prob_tmp_file = tempfile.mktemp(suffix='.mps')
        with open(prob_tmp_file, 'wb') as tmp_handle:
            f = gzip.open(mps_file, 'rb')
            tmp_handle.write(f.read())
            f.close()

        problem = gurobipy.read(prob_tmp_file)
        model = Model(problem=problem)
        model.configuration.presolve = True
        model.configuration.verbosity = 3
        model.configuration.timeout = 60 * 9
        return problem, model
Пример #8
0
        def test_qp_non_convex(self):
            model = Model(problem=gurobipy.read(NONCONVEX_QP_PATH))
            self.assertEqual(len(model.variables), 31)
            self.assertEqual(len(model.constraints), 1)
            for constraint in model.constraints:
                self.assertTrue(
                    constraint.is_Linear,
                    "%s should be linear" % (str(constraint.expression)))
                self.assertFalse(
                    constraint.is_Quadratic, "%s should not be quadratic" %
                    (str(constraint.expression)))

            self.assertTrue(model.objective.is_Quadratic,
                            "objective should be quadratic")
            self.assertFalse(model.objective.is_Linear,
                             "objective should not be linear")

            self.assertRaises(GurobiError, model.optimize)
Пример #9
0
 def setUp(self):
     problem = gurobipy.read(TESTMODELPATH)
     self.model = Model(problem=problem)
     self.obj = self.model.objective
Пример #10
0
        def test_netlib(netlib_tar_path=os.path.join(os.path.dirname(__file__), 'data/netlib_lp_problems.tar.gz')):
            """
            Test netlib with glpk interface
            """
            tar = tarfile.open(netlib_tar_path)
            model_paths_in_tar = glob.fnmatch.filter(tar.getnames(), '*.SIF')

            for model_path_in_tar in model_paths_in_tar:
                print(model_path_in_tar)
                netlib_id = os.path.basename(model_path_in_tar).replace('.SIF', '')
                # TODO: get the following problems to work
                # E226 seems to be a MPS related problem, see http://lists.gnu.org/archive/html/bug-glpk/2003-01/msg00003.html
                if netlib_id in ('AGG', 'E226', 'SCSD6', 'BLEND', 'DFL001', 'FORPLAN', 'GFRD-PNC', 'SIERRA'):
                    # def test_skip(netlib_id):
                    # raise SkipTest('Skipping netlib problem %s ...' % netlib_id)
                    # test_skip(netlib_id)
                    # class TestWeirdNetlibProblems(unittest.TestCase):

                    # @unittest.skip('Skipping netlib problem')
                    # def test_fail():
                    # pass
                    continue
                # TODO: For now, test only models that are covered by the final netlib results
                else:
                    if netlib_id not in THE_FINAL_NETLIB_RESULTS.keys():
                        continue
                    fhandle = tar.extractfile(model_path_in_tar)
                    problem = read_netlib_sif_gurobi(fhandle)
                    model = Model(problem=problem)
                    model.configuration.presolve = True
                    model.configuration.verbosity = 3
                    func = partial(check_dimensions, problem, model)
                    func.description = "test_netlib_check_dimensions_%s (%s)" % (
                        netlib_id, os.path.basename(str(__file__)))
                    yield func

                    model.optimize()
                    if model.status == 'optimal':
                        model_objval = model.objective.value
                    else:
                        raise Exception('No optimal solution found for netlib model %s' % netlib_id)

                    func = partial(check_objval, problem, model_objval)
                    func.description = "test_netlib_check_objective_value_%s (%s)" % (
                        netlib_id, os.path.basename(str(__file__)))
                    yield func

                    func = partial(check_objval_against_the_final_netlib_results, netlib_id, model_objval)
                    func.description = "test_netlib_check_objective_value__against_the_final_netlib_results_%s (%s)" % (
                        netlib_id, os.path.basename(str(__file__)))
                    yield func

                    if os.getenv('CI', 'false') != 'true':
                        # check that a cloned model also gives the correct result
                        model = Model.clone(model, use_json=False, use_lp=False)
                        model.optimize()
                        if model.status == 'optimal':
                            model_objval = model.objective.value
                        else:
                            raise Exception('No optimal solution found for netlib model %s' % netlib_id)

                        func = partial(check_objval_against_the_final_netlib_results, netlib_id, model_objval)
                        func.description = "test_netlib_check_objective_value__against_the_final_netlib_results_after_cloning_%s (%s)" % (
                            netlib_id, os.path.basename(str(__file__)))
                        yield func
Пример #11
0
 def setUp(self):
     self.model = Model()
     self.x1 = Variable("x1", lb=0)
     self.x2 = Variable("x2", lb=0)
     self.c1 = Constraint(self.x1 + self.x2, lb=1)
     self.model.add([self.x1, self.x2, self.c1])
Пример #12
0
    class QuadraticProgrammingTestCase(
            abstract_test_cases.AbstractQuadraticProgrammingTestCase):
        def setUp(self):
            self.model = Model()
            self.x1 = Variable("x1", lb=0)
            self.x2 = Variable("x2", lb=0)
            self.c1 = Constraint(self.x1 + self.x2, lb=1)
            self.model.add([self.x1, self.x2, self.c1])

        def test_convex_obj(self):
            model = self.model
            obj = Objective(self.x1**2 + self.x2**2, direction="min")
            model.objective = obj
            model.optimize()
            self.assertAlmostEqual(model.objective.value, 0.5)
            self.assertAlmostEqual(self.x1.primal, 0.5)
            self.assertAlmostEqual(self.x2.primal, 0.5)

            obj_2 = Objective(self.x1, direction="min")
            model.objective = obj_2
            model.optimize()
            self.assertAlmostEqual(model.objective.value, 0.0)
            self.assertAlmostEqual(self.x1.primal, 0.0)
            self.assertGreaterEqual(self.x2.primal, 1.0)

        # According to documentation and mailing lists Gurobi cannot solve non-convex QP
        # However version 7.0 solves this fine. Skipping for now
        @unittest.skip("Can gurobi solve non-convex QP?")
        def test_non_convex_obj(self):
            model = self.model
            obj = Objective(self.x1 * self.x2, direction="min")
            model.objective = obj
            self.assertRaises(GurobiError, model.optimize)

            obj_2 = Objective(self.x1, direction="min")
            model.objective = obj_2
            model.optimize()
            self.assertAlmostEqual(model.objective.value, 0.0)
            self.assertAlmostEqual(self.x1.primal, 0.0)
            self.assertGreaterEqual(self.x2.primal, 1.0)

        def test_qp_convex(self):
            model = Model(problem=gurobipy.read(CONVEX_QP_PATH))
            self.assertEqual(len(model.variables), 651)
            self.assertEqual(len(model.constraints), 501)
            for constraint in model.constraints:
                self.assertTrue(
                    constraint.is_Linear,
                    "%s should be linear" % (str(constraint.expression)))
                self.assertFalse(
                    constraint.is_Quadratic, "%s should not be quadratic" %
                    (str(constraint.expression)))

            self.assertTrue(model.objective.is_Quadratic,
                            "objective should be quadratic")
            self.assertFalse(model.objective.is_Linear,
                             "objective should not be linear")

            model.optimize()
            self.assertAlmostEqual(model.objective.value, 32.2291282)

        @unittest.skip("Takes a very long time")
        def test_qp_non_convex(self):
            model = Model(problem=gurobipy.read(NONCONVEX_QP_PATH))
            self.assertEqual(len(model.variables), 31)
            self.assertEqual(len(model.constraints), 1)
            for constraint in model.constraints:
                self.assertTrue(
                    constraint.is_Linear,
                    "%s should be linear" % (str(constraint.expression)))
                self.assertFalse(
                    constraint.is_Quadratic, "%s should not be quadratic" %
                    (str(constraint.expression)))

            self.assertTrue(model.objective.is_Quadratic,
                            "objective should be quadratic")
            self.assertFalse(model.objective.is_Linear,
                             "objective should not be linear")

            self.assertRaises(GurobiError, model.optimize)

        def test_quadratic_objective_expression(self):
            objective = Objective(self.x1**2 + self.x2**2, direction="min")
            self.model.objective = objective
            self.assertEqual((self.model.objective.expression -
                              (self.x1**2 + self.x2**2)).simplify(), 0)