Skip to content
Snippets Groups Projects
test_solvers.py 23.5 KiB
Newer Older
  • Learn to ignore specific revisions
  • Pedro L. Magalhães's avatar
    Pedro L. Magalhães committed
    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
    # imports
    
    from src.topupopt.solvers.interface import SolverInterface
    
    from pyomo.opt.results.solver import TerminationCondition
    
    import pyomo.environ as pyo
    from pyomo.common.errors import ApplicationError
    
    import random
    
    # *****************************************************************************
    # *****************************************************************************
    
    
    class TestSolvers:
        # *************************************************************************
        # *************************************************************************
    
        def test_solver_factory_arguments(self):
            # test a collection of problems using different solvers
    
            problem = self.problem_milp_feasible()
    
            # solver settings
    
            solver_timelimit = 10
    
            solver_abs_mip_gap = 0.001
    
            solver_rel_mip_gap = 0.01
    
            solver_options = {
                "time_limit": solver_timelimit,
                "relative_mip_gap": solver_rel_mip_gap,
                "absolute_mip_gap": solver_abs_mip_gap,
                # special option
                "tee": True,
            }
    
            solver_name = "scip"
    
            results, solver_interface = self.optimise(solver_name, solver_options, problem)
    
        # *************************************************************************
        # *************************************************************************
    
        def test_problems(self):
            # test a collection of problems using different solvers
    
            # solver = "scip"
            # # scip_exec_path = '/usr/bin/scip'
            # # solver_options = {'executable': scip_exec_path}
            # solver_options = {}
            
            # solver = 'cplex'
            # # cplex_exec_path = '/home/pmlpm/Software/CPLEX/cplex/bin/x86-64_linux/cplex'
            # cplex_exec_path = '/home/pmlpm/CPLEX/cplex/bin/x86-64_linux/cplex'
            # #solver_options = {}
            # solver_options = {'executable':cplex_exec_path}
    
            list_solvers = [
                "fake_solver",
                "cbc",
                "glpk",
                "scip",
                'cplex'
            ]
    
            list_solver_options = [
                None,  # fake
                None,  # cbc
                {"tee": False},  # glpk
                None,  # scip {'executable': scip_exec_path},  
                None, # cplex
                # {'executable': cplex_exec_path},
            ]
    
            # list of problems
    
            list_concrete_models = [
                self.problem_qp_optimal(),
                self.problem_qp_infeasible(),
                self.problem_lp_unbounded(),
                self.problem_lp_infeasible(),
                self.problem_lp_optimal(),
                self.problem_milp_unbounded(),
                self.problem_milp_infeasible(),
                self.problem_milp_optimal(),
                self.problem_milp_feasible(),
                self.problem_milp_feasible(15, 64),
                self.problem_milp_feasible(10, 46),
            ]
    
            # list of problem types
    
            list_problem_types = [
                SolverInterface.PROBLEM_QP,
                SolverInterface.PROBLEM_QP,
                SolverInterface.PROBLEM_LP,
                SolverInterface.PROBLEM_LP,
                SolverInterface.PROBLEM_LP,
                SolverInterface.PROBLEM_MILP,
                SolverInterface.PROBLEM_MILP,
                SolverInterface.PROBLEM_MILP,
                SolverInterface.PROBLEM_MILP,
                SolverInterface.PROBLEM_MILP,
                "unknown_problem_type",
            ]
    
            # expected
    
            list_problem_termination_conditions = [
                TerminationCondition.optimal,
                TerminationCondition.infeasible,
                TerminationCondition.unbounded,
                TerminationCondition.infeasible,
                TerminationCondition.optimal,
                TerminationCondition.unbounded,
                TerminationCondition.infeasible,
                TerminationCondition.optimal,
                None,  # if we don't know what to expect,
                None,  # if we don't know what to expect,
                None,  # if we don't know what to expect
            ]
    
            list_problem_optimisation_sucess = [
                True,
                True,
                False,
                False,
                True,
                False,
                False,
                True,
                True,
                True,
                True,
            ]
    
            # list of solvers
    
            list_solvers = ["fake_solver", "cbc", "glpk", "scip", "cplex"]
    
            # solver settings
    
            solver_timelimit = 10
    
            solver_abs_mip_gap = 0.001
    
            solver_rel_mip_gap = 0.01
    
            for solver_name, solver_options in zip(list_solvers, list_solver_options):
                if type(solver_options) == dict:
                    solver_options.update(
                        {
                            "time_limit": solver_timelimit,
                            "relative_mip_gap": solver_rel_mip_gap,
                            "absolute_mip_gap": solver_abs_mip_gap,
                        }
                    )
    
                else:
                    solver_options = {
                        "time_limit": solver_timelimit,
                        "relative_mip_gap": solver_rel_mip_gap,
                        "absolute_mip_gap": solver_abs_mip_gap,
                    }
    
                for problem_index, problem in enumerate(list_concrete_models):
                    try:
                        # check problem and solver compatibility
    
                        problem_type = list_problem_types[problem_index]
    
                        if (
                            SolverInterface.problem_and_solver_are_compatible(
                                solver_name, problem_type
                            )
                            == False
                        ):
                            continue
    
                        # optimise
    
                        results, solver_interface = self.optimise(
                            solver_name, solver_options, problem, print_solver_output=False
                        )
    
                    except SolverInterface.UnknownSolverError:
                        continue
    
                    except SolverInterface.UnknownProblemTypeError:
                        continue
    
                    # *************************************************************
                    # *************************************************************
    
                    # termination condition
    
                    exp_term_cond = list_problem_termination_conditions[problem_index]
    
                    term_cond = results.solver.termination_condition
    
                    if (
                        exp_term_cond == None
                        or (
                            solver_name == "glpk"
                            and exp_term_cond == TerminationCondition.unbounded
                        )
                        or (
                            solver_name == "cplex"
                            and exp_term_cond == TerminationCondition.unbounded
                        )
                        or (
                            solver_name == "cplex"
                            and exp_term_cond == TerminationCondition.optimal
                        )
                        or (
                            solver_name == "cplex"
                            and exp_term_cond == TerminationCondition.infeasible
                        )
                    ):
                        # exceptions in need of correction
    
                        pass
    
                    else:
                        # print(solver_name)
                        # print(results)
                        assert exp_term_cond == term_cond
    
                    # *************************************************************
                    # *************************************************************
    
                    # solver status
    
                    if (
                        (
                            solver_name == "glpk"
                            and term_cond == TerminationCondition.infeasible
                        )
                        or (
                            solver_name == "cplex"
                            and term_cond == TerminationCondition.unknown
                        )
                        or (
                            solver_name == "cplex"
                            and exp_term_cond == TerminationCondition.unbounded
                        )
                        or (
                            solver_name == "cplex"
                            and exp_term_cond == TerminationCondition.infeasible
                        )
                    ):
                        pass
    
                    else:
                        # check if the solver status matches the one one would expect
                        # if the termination condition was correct
    
                        assert (
                            TerminationCondition.to_solver_status(term_cond)
                            == results.solver.status
                        )
    
                        # if valid, it means the results object is coherent
    
                    # *************************************************************
                    # *************************************************************
    
                    if (
                        exp_term_cond == None
                        or (
                            solver_name == "glpk"
                            and exp_term_cond == TerminationCondition.unbounded
                        )
                        or (
                            solver_name == "glpk"
                            and exp_term_cond == TerminationCondition.infeasible
                        )
                        or (
                            solver_name == "cplex"
                            and exp_term_cond == TerminationCondition.unknown
                        )
                        or (
                            solver_name == "cplex"
                            and exp_term_cond == TerminationCondition.unbounded
                        )
                        or (
                            solver_name == "cplex"
                            and exp_term_cond == TerminationCondition.infeasible
                        )
                    ):
                        pass
    
                    else:
                        # check if the solver status matches the one one would expect
                        # if the termination condition predicted was obtained
    
                        assert (
                            TerminationCondition.to_solver_status(exp_term_cond)
                            == results.solver.status
                        )
    
                        # if valid, the solver status is correct despite other issues
    
                    # *************************************************************
                    # *************************************************************
    
                    # make sure the optimisation went as expected
    
                    exp_optim_result = list_problem_optimisation_sucess[problem_index]
    
                    if (
                        TerminationCondition.to_solver_status(
                            results.solver.termination_condition
                        )
                        != results.solver.status
                    ):
                        # this can be removed once the aforementioned issues have
                        # been fixed (e.g. for the cplex and glpk solvers)
    
                        pass
    
                    else:
                        optim_result = solver_interface.was_optimisation_sucessful(
                            results, problem_type
                        )
    
                    # *************************************************************
                    # *************************************************************
    
                    if (
                        TerminationCondition.to_solver_status(
                            results.solver.termination_condition
                        )
                        != results.solver.status
                        or exp_term_cond == TerminationCondition.unbounded
                    ):
                        # this can be removed once the aforementioned issues have
                        # been fixed (e.g. for the cplex and glpk solvers)
    
                        pass
    
                    else:
                        assert optim_result == exp_optim_result
    
                    # *************************************************************
                    # *************************************************************
    
                    # test additional scenarios
    
                    if optim_result == False:
                        continue
    
                    # force unknown solver status error
    
                    results.solver.status = "false_solver_status"
    
                    try:
                        _ = solver_interface.was_optimisation_sucessful(
                            results, problem_type
                        )
    
                    except solver_interface.UnknownSolverStatusError:
                        assert True
    
                    # force unknown termination condition error
    
                    results.solver.termination_condition = "false_termin_condition"
    
                    try:
                        _ = solver_interface.was_optimisation_sucessful(
                            results, problem_type
                        )
    
                    except solver_interface.UnknownTerminationConditionError:
                        assert True
    
                    # force an InconsistentSolverStatusError
    
                    results.solver.termination_condition = TerminationCondition.optimal
    
                    results.solver.status = TerminationCondition.to_solver_status(
                        results.solver.termination_condition
                    )
    
                    results.solver.termination_condition = TerminationCondition.unknown
    
                    try:
                        _ = solver_interface.was_optimisation_sucessful(
                            results, problem_type
                        )
    
                    except solver_interface.InconsistentSolverStatusError:
                        assert True
    
                    # force an InconsistentProblemTypeAndSolverError
    
                    if problem_type == SolverInterface.PROBLEM_LP and solver_name == "glpk":
                        problem_type = SolverInterface.PROBLEM_QP
    
                        try:
                            _ = solver_interface.was_optimisation_sucessful(
                                results, problem_type
                            )
    
                        except solver_interface.InconsistentProblemTypeAndSolverError:
                            assert True
    
            # *********************************************************************
            # *********************************************************************
    
        # *************************************************************************
        # *************************************************************************
    
        # carry out optimisations
    
        def optimise(
            self,
            solver_name: str,
            solver_options: dict,
            # solver_interface: SolverInterface,
            problem: pyo.ConcreteModel,
            print_solver_output: bool = True,
        ):
            # configure common solver interface
            solver_interface = SolverInterface(solver_name=solver_name, **solver_options)
    
            # get the solver handler
            solver_handler = solver_interface.get_solver_handler(**solver_options)
    
            # solve
            if "tee" not in solver_options:
                results = solver_handler.solve(problem, tee=print_solver_output)
            else:
                results = solver_handler.solve(problem)
    
            # return
            return results, solver_interface
    
        # *************************************************************************
        # *************************************************************************
    
        def problem_qp_optimal(self):
            model = pyo.ConcreteModel("qp_optimal")
    
            model.x = pyo.Var(within=pyo.NonNegativeReals)
            model.y = pyo.Var(within=pyo.NonNegativeReals)
    
            def constraint_rule(model):
                return model.x + model.y >= 10
    
            model.constraint = pyo.Constraint(rule=constraint_rule)
    
            def objective_rule(model):
                return (
                    model.x
                    + model.y
                    + 0.5
                    * (model.x * model.x + 4 * model.x * model.y + 7 * model.y * model.y)
                )
    
            model.objective = pyo.Objective(rule=objective_rule, sense=pyo.minimize)
    
            return model
    
        # *************************************************************************
        # *************************************************************************
    
        def problem_qp_infeasible(self):
            model = pyo.ConcreteModel("qp_infeasible")
    
            # model.x = pyo.Var(within=pyo.NonNegativeReals, bounds=(0,5))
            # model.y = pyo.Var(within=pyo.NonNegativeReals, bounds=(0,4))
    
            model.x = pyo.Var(bounds=(0, 5))
            model.y = pyo.Var(bounds=(0, 4))
    
            def constraint_rule(model):
                return model.x + model.y >= 10
    
            model.constraint = pyo.Constraint(rule=constraint_rule)
    
            def objective_rule(model):
                return (
                    model.x
                    + model.y
                    + 0.5
                    * (model.x * model.x + 4 * model.x * model.y + 7 * model.y * model.y)
                )
    
            model.objective = pyo.Objective(rule=objective_rule, sense=pyo.minimize)
    
            return model
    
        # *************************************************************************
        # *************************************************************************
    
        def problem_lp_optimal(self):
            model = pyo.ConcreteModel("lp_optimal")
    
            model.x = pyo.Var([1, 2], domain=pyo.NonNegativeReals)
    
            model.OBJ = pyo.Objective(expr=2 * model.x[1] + 3 * model.x[2])
    
            model.Constraint1 = pyo.Constraint(expr=3 * model.x[1] + 4 * model.x[2] >= 1)
    
            return model
    
        # *************************************************************************
        # *************************************************************************
    
        def problem_lp_infeasible(self):
            model = pyo.ConcreteModel("lp_infeasible")
    
            model.x = pyo.Var([1, 2], domain=pyo.NonNegativeReals)
    
            model.OBJ = pyo.Objective(expr=2 * model.x[1] + 3 * model.x[2])
    
            model.Constraint1 = pyo.Constraint(expr=3 * model.x[1] + 4 * model.x[2] <= -1)
    
            return model
    
        # *************************************************************************
        # *************************************************************************
    
        def problem_lp_unbounded(self):
            model = pyo.ConcreteModel("lp_unbounded")
    
            model.x = pyo.Var([1, 2], domain=pyo.NonNegativeReals)
    
            model.OBJ = pyo.Objective(
                expr=2 * model.x[1] + 3 * model.x[2], sense=pyo.maximize
            )
    
            model.Constraint1 = pyo.Constraint(expr=3 * model.x[1] + 4 * model.x[2] >= 1)
    
            return model
    
        # *************************************************************************
        # *************************************************************************
    
        def problem_milp_optimal(self):
            model = pyo.ConcreteModel("milp_optimal")
    
            model.x = pyo.Var([1, 2], domain=pyo.Binary)
    
            model.OBJ = pyo.Objective(expr=2.15 * model.x[1] + 3.8 * model.x[2])
    
            model.Constraint1 = pyo.Constraint(expr=3 * model.x[1] + 4 * model.x[2] >= 1)
    
            return model
    
        # *************************************************************************
        # *************************************************************************
    
        def problem_milp_infeasible(self):
            model = pyo.ConcreteModel("milp_infeasible")
    
            model.x = pyo.Var([1, 2], domain=pyo.Binary)
    
            model.OBJ = pyo.Objective(expr=2 * model.x[1] + 3 * model.x[2])
    
            model.Constraint1 = pyo.Constraint(expr=3 * model.x[1] + 4 * model.x[2] <= -1)
    
            return model
    
        # *************************************************************************
        # *************************************************************************
    
        def problem_milp_unbounded(self):
            model = pyo.ConcreteModel("milp_unbounded")
    
            model.x = pyo.Var([1, 2], domain=pyo.NonNegativeReals)
    
            model.y = pyo.Var(domain=pyo.Binary)
    
            model.OBJ = pyo.Objective(
                expr=2 * model.x[1] + 3 * model.x[2] + model.y, sense=pyo.maximize
            )
    
            model.Constraint1 = pyo.Constraint(expr=3 * model.x[1] + 4 * model.x[2] >= 1)
    
            return model
    
        # *************************************************************************
        # *************************************************************************
    
        def problem_milp_feasible(self, number_binary_variables=25, seed_number=None):
            if seed_number != None:
                random.seed(seed_number)
    
            model = pyo.ConcreteModel("milp_feasible")
    
            # a knapsack-type problem
    
            model.Y = pyo.RangeSet(number_binary_variables)
    
            model.y = pyo.Var(model.Y, domain=pyo.Binary)
    
            model.OBJ = pyo.Objective(
                expr=sum(model.y[j] * random.random() for j in model.Y), sense=pyo.maximize
            )
    
            model.Constraint1 = pyo.Constraint(
                expr=sum(model.y[j] * random.random() for j in model.Y)
                <= round(number_binary_variables / 5)
            )
    
            def rule_c1(m, i):
                return (
                    sum(
                        model.y[j] * (random.random() - 0.5)
                        for j in model.Y
                        if j != i
                        if random.randint(0, 1)
                    )
                    <= round(number_binary_variables / 5) * model.y[i]
                )
    
            model.constr_c1 = pyo.Constraint(model.Y, rule=rule_c1)
    
            return model
    
        # *************************************************************************
        # *************************************************************************
    
        def test_inexistent_solver(self):
            fake_solver = "fake_solver"
            good_solver = "glpk"
            # solver_options: dict = None
    
            # try using a fake solver and a problem incompatible with another solver
    
            # list of problems: one compatible, one incompatible
    
            list_problems = [
                self.problem_milp_feasible(20, seed_number=50),
                self.problem_lp_optimal(),
                self.problem_qp_optimal(),
                self.problem_qp_optimal(),
            ]
    
            # problem types
    
            list_problem_types = [
                SolverInterface.PROBLEM_LP,
                SolverInterface.PROBLEM_LP,
                SolverInterface.PROBLEM_QP,
                "fake_problem_type",
            ]
    
            # list of solvers: one fake, one real
    
            list_solvers = [fake_solver, good_solver]
    
            # solver settings
    
            solver_timelimit = 30
    
            solver_abs_mip_gap = 0
    
            solver_rel_mip_gap = 0.01
    
            solver_options = {
                "time_limit": solver_timelimit,
                "relative_mip_gap": solver_rel_mip_gap,
                "absolute_mip_gap": solver_abs_mip_gap,
            }
    
            # *********************************************************************
            # *********************************************************************
    
            for solver_name in list_solvers:
                for index, problem in enumerate(list_problems):
                    # optimise
    
                    try:
                        # test problem-solver compatibility
    
                        problem_type = list_problem_types[index]
    
                        if (
                            SolverInterface.problem_and_solver_are_compatible(
                                solver_name, problem_type
                            )
                            == False
                        ):
                            continue
    
                    except SolverInterface.UnknownSolverError:
                        assert True
    
                    except SolverInterface.UnknownProblemTypeError:
                        assert True
    
                    # test the solver interface
    
                    try:
                        # configure common solver interface
    
                        _ = SolverInterface(solver_name=solver_name, **solver_options)
    
                    except SolverInterface.UnknownSolverError:
                        assert True
    
        # **************************************************************************
        # **************************************************************************
    
    
    # ******************************************************************************
    # ******************************************************************************