• 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

83.78
/qiskit_optimization/algorithms/cplex_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 CPLEX optimizer wrapped to be used within Qiskit optimization module."""
14

15
from typing import Any, Dict, Optional
1✔
16
from warnings import warn
1✔
17

18
from qiskit_optimization.problems.quadratic_program import QuadraticProgram
1✔
19
from qiskit_optimization.translators import to_docplex_mp
1✔
20
import qiskit_optimization.optionals as _optionals
1✔
21
from .optimization_algorithm import (
1✔
22
    OptimizationAlgorithm,
23
    OptimizationResult,
24
    OptimizationResultStatus,
25
)
26

27

28
@_optionals.HAS_CPLEX.require_in_instance
1✔
29
class CplexOptimizer(OptimizationAlgorithm):
1✔
30
    """The CPLEX optimizer wrapped as an Qiskit :class:`OptimizationAlgorithm`.
31

32
    This class provides a wrapper for ``cplex.Cplex`` (https://pypi.org/project/cplex/)
33
    to be used within the optimization module.
34

35
    Examples:
36
        >>> from qiskit_optimization.problems import QuadraticProgram
37
        >>> from qiskit_optimization.algorithms import CplexOptimizer
38
        >>> problem = QuadraticProgram()
39
        >>> # specify problem here, if cplex is installed
40
        >>> optimizer = CplexOptimizer() if CplexOptimizer.is_cplex_installed() else None
41
        >>> if optimizer: result = optimizer.solve(problem)
42
    """
43

44
    def __init__(
1✔
45
        self, disp: bool = False, cplex_parameters: Optional[Dict[str, Any]] = None
46
    ) -> None:
47
        """Initializes the CplexOptimizer.
48

49
        Args:
50
            disp: Whether to print CPLEX output or not.
51
            cplex_parameters: The parameters for CPLEX.
52
                See https://www.ibm.com/docs/en/icos/20.1.0?topic=cplex-parameters for details.
53
        """
54
        self._disp = disp
1✔
55
        self._cplex_parameters = cplex_parameters
1✔
56

57
    @staticmethod
1✔
58
    def is_cplex_installed():
1✔
59
        """Returns True if cplex is installed"""
60
        return _optionals.HAS_CPLEX
×
61

62
    @property
1✔
63
    def disp(self) -> bool:
1✔
64
        """Returns the display setting.
65

66
        Returns:
67
            Whether to print CPLEX information or not.
68
        """
69
        return self._disp
×
70

71
    @disp.setter
1✔
72
    def disp(self, disp: bool):
1✔
73
        """Set the display setting.
74
        Args:
75
            disp: The display setting.
76
        """
77
        self._disp = disp
×
78

79
    @property
1✔
80
    def cplex_parameters(self) -> Optional[Dict[str, Any]]:
1✔
81
        """Returns parameters for CPLEX"""
82
        return self._cplex_parameters
×
83

84
    @cplex_parameters.setter
1✔
85
    def cplex_parameters(self, parameters: Optional[Dict[str, Any]]):
1✔
86
        """Set parameters for CPLEX
87
        Args:
88
            parameters: The parameters for CPLEX
89
        """
90
        self._cplex_parameters = parameters
×
91

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

96
        Returns ``''`` since CPLEX accepts all problems that can be modeled using the
97
        ``QuadraticProgram``. CPLEX may throw an exception in case the problem is determined
98
        to be non-convex.
99

100
        Args:
101
            problem: The optimization problem to check compatibility.
102

103
        Returns:
104
            An empty string.
105
        """
106
        return ""
×
107

108
    def solve(self, problem: QuadraticProgram) -> OptimizationResult:
1✔
109
        """Tries to solves the given problem using the optimizer.
110

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

114
        Args:
115
            problem: The problem to be solved.
116

117
        Returns:
118
            The result of the optimizer applied to the problem.
119

120
        Raises:
121
            QiskitOptimizationError: If the problem is incompatible with the optimizer.
122
        """
123

124
        mod = to_docplex_mp(problem)
1✔
125
        sol = mod.solve(log_output=self._disp, cplex_parameters=self._cplex_parameters)
1✔
126
        if sol is None:
1✔
127
            # no solution is found
128
            warn("CPLEX cannot solve the model")
1✔
129
            x = [0.0] * mod.number_of_variables
1✔
130
            return OptimizationResult(
1✔
131
                x=x,
132
                fval=problem.objective.evaluate(x),
133
                variables=problem.variables,
134
                status=OptimizationResultStatus.FAILURE,
135
                raw_results=None,
136
            )
137
        else:
138
            # a solution is found
139
            x = sol.get_values(mod.iter_variables())
1✔
140
            return OptimizationResult(
1✔
141
                x=x,
142
                fval=sol.get_objective_value(),
143
                variables=problem.variables,
144
                status=self._get_feasibility_status(problem, x),
145
                raw_results=sol,
146
            )
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