• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

qiskit-community / qiskit-optimization / 12290037198

12 Dec 2024 04:49AM CUT coverage: 92.865%. Remained the same
12290037198

Pull #649

github

web-flow
Merge 607f773b2 into 53184abdc
Pull Request #649: Pin numpy<2.2.0

4451 of 4793 relevant lines covered (92.86%)

0.93 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

84.38
/qiskit_optimization/algorithms/gurobi_optimizer.py
1
# This code is part of a Qiskit project.
2
#
3
# (C) Copyright IBM 2020, 2023.
4
#
5
# This code is licensed under the Apache License, Version 2.0. You may
6
# obtain a copy of this license in the LICENSE.txt file in the root directory
7
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
8
#
9
# Any modifications or derivative works of this code must retain this
10
# copyright notice, and modified files need to carry a notice indicating
11
# that they have been altered from the originals.
12

13
"""The Gurobi optimizer wrapped to be used within Qiskit optimization module."""
14

15
import qiskit_optimization.optionals as _optionals
1✔
16
from ..exceptions import QiskitOptimizationError
1✔
17
from ..problems.quadratic_program import QuadraticProgram
1✔
18
from ..translators.gurobipy import to_gurobipy
1✔
19
from .optimization_algorithm import OptimizationAlgorithm, OptimizationResult
1✔
20

21

22
@_optionals.HAS_GUROBIPY.require_in_instance
1✔
23
class GurobiOptimizer(OptimizationAlgorithm):
1✔
24
    """The Gurobi optimizer wrapped as an Qiskit :class:`OptimizationAlgorithm`.
25

26
    This class provides a wrapper for ``gurobipy``
27
    to be used within the optimization module.
28

29
    Examples:
30
        >>> from qiskit_optimization.problems import QuadraticProgram
31
        >>> from qiskit_optimization.algorithms import GurobiOptimizer
32
        >>> problem = QuadraticProgram()
33
        >>> # specify problem here, if gurobi is installed
34
        >>> optimizer = GurobiOptimizer() if GurobiOptimizer.is_gurobi_installed() else None
35
        >>> # Suppress gurobipy print info to stdout
36
        >>> import sys
37
        >>> class DevNull:
38
        ...     def noop(*args, **kwargs): pass
39
        ...     close = write = flush = writelines = noop
40
        >>> sys.stdout = DevNull()
41
        >>> result = optimizer.solve(problem)
42
    """
43

44
    def __init__(self, disp: bool = False) -> None:
1✔
45
        """Initializes the GurobiOptimizer.
46

47
        Args:
48
            disp: Whether to print Gurobi output or not.
49
        """
50
        self._disp = disp
1✔
51

52
    @staticmethod
1✔
53
    def is_gurobi_installed():
1✔
54
        """Returns True if gurobi is installed"""
55
        return _optionals.HAS_GUROBIPY
×
56

57
    @property
1✔
58
    def disp(self) -> bool:
1✔
59
        """Returns the display setting.
60

61
        Returns:
62
            Whether to print Gurobi information or not.
63
        """
64
        return self._disp
1✔
65

66
    @disp.setter
1✔
67
    def disp(self, disp: bool):
1✔
68
        """Set the display setting.
69
        Args:
70
            disp: The display setting.
71
        """
72
        self._disp = disp
×
73

74
    # pylint:disable=unused-argument
75
    def get_compatibility_msg(self, problem: QuadraticProgram) -> str:
1✔
76
        """Checks whether a given problem can be solved with this optimizer.
77

78
        Returns ``''`` since Gurobi accepts all problems that can be modeled using the
79
        ``QuadraticProgram``. Gurobi will also solve non-convex problems.
80

81
        Args:
82
            problem: The optimization problem to check compatibility.
83

84
        Returns:
85
            An empty string.
86
        """
87
        return ""
×
88

89
    def solve(self, problem: QuadraticProgram) -> OptimizationResult:
1✔
90
        """Tries to solves the given problem using the optimizer.
91

92
        Runs the optimizer to try to solve the optimization problem. If problem is not convex,
93
        this optimizer may raise an exception due to incompatibility, depending on the settings.
94

95
        Args:
96
            problem: The problem to be solved.
97

98
        Returns:
99
            The result of the optimizer applied to the problem.
100

101
        Raises:
102
            QiskitOptimizationError: If the problem is incompatible with the optimizer.
103
        """
104
        # pylint: disable=import-error
105
        import gurobipy as gp
1✔
106

107
        # convert to Gurobi problem
108
        model = to_gurobipy(problem)
1✔
109

110
        # set display setting
111
        if not self.disp:
1✔
112
            model.Params.OutputFlag = 0
1✔
113

114
        # enable non-convex
115
        model.Params.NonConvex = 2
1✔
116

117
        # solve problem
118
        try:
1✔
119
            model.optimize()
1✔
120
        except gp.GurobiError as ex:
×
121
            raise QiskitOptimizationError(str(ex)) from ex
×
122

123
        # create results
124
        result = OptimizationResult(
1✔
125
            x=model.X,
126
            fval=model.ObjVal,
127
            variables=problem.variables,
128
            status=self._get_feasibility_status(problem, model.X),
129
            raw_results=model,
130
        )
131

132
        # return solution
133
        return result
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc