Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
7d9c2fa
Adding gurobipy as a solver
RichardOberdieck Feb 24, 2021
3155b70
Adding gurobi and gurobipy to .pylintdict
RichardOberdieck Feb 24, 2021
e9e80fc
Fixing some unit tests
RichardOberdieck Mar 5, 2021
77dfa98
Final changes to get tests to run
RichardOberdieck Mar 12, 2021
92d41a2
Changing .pylintrc to ignore gurobi member messages
RichardOberdieck Mar 12, 2021
4aeb295
Delete max_cut.py
RichardOberdieck Mar 16, 2021
56e7698
Merge branch 'master' into master
manoelmarques Mar 16, 2021
5a8a848
Merge branch 'master' into master
manoelmarques Mar 18, 2021
2fddf40
Merge branch 'master' into master
manoelmarques Mar 18, 2021
8c3b97c
Install gurobipy in CI, remove it from setup.py
manoelmarques Mar 19, 2021
7fcd591
fix docs
manoelmarques Mar 19, 2021
19b9e19
CI test without gurobipy
manoelmarques Mar 19, 2021
552fdac
Merge branch 'master' into master
manoelmarques Mar 20, 2021
0c7f0e5
Add GurobiModel to typehints
manoelmarques Mar 21, 2021
91cb275
fix lint
manoelmarques Mar 21, 2021
7b5f20d
Merge branch 'master' into master
manoelmarques Mar 23, 2021
57b1d52
remove gurobipy from requirements.txt
manoelmarques Mar 24, 2021
a3a28b3
Merge branch 'master' into master
manoelmarques Mar 24, 2021
60912c5
Merge branch 'master' into master
manoelmarques Mar 25, 2021
8a31fdd
Merge branch 'master' into master
manoelmarques Mar 25, 2021
45205d6
merge master and fix conflicts
manoelmarques Mar 31, 2021
b3d1df2
Merge branch 'master' into master
manoelmarques Apr 1, 2021
0c44388
Merge branch 'master' into master
manoelmarques Apr 1, 2021
d296242
Merge branch 'master' into master
manoelmarques Apr 2, 2021
11af069
Merge branch 'master' into master
manoelmarques Apr 4, 2021
559885b
Merge branch 'master' into master
manoelmarques Apr 12, 2021
a1220b7
Merge branch 'master' into master
manoelmarques Apr 15, 2021
40c4494
Merge branch 'main' into master
manoelmarques Apr 21, 2021
a7b7673
Merge branch 'main' into master
manoelmarques Apr 24, 2021
0d6fcd9
Merge branch 'main' into master
manoelmarques Apr 25, 2021
5b94fe2
Install gurobipy from public pypi
manoelmarques Apr 25, 2021
bc083e8
Merge main, fix conflicts
manoelmarques Apr 26, 2021
e3a5398
Use requires_extra_library decorator in unit test
manoelmarques Apr 26, 2021
77dc2c3
Merge main, fix conflicts
manoelmarques Apr 27, 2021
c591cb9
(wip) translator
t-imamichi Apr 30, 2021
8704f5b
(wip) translator
t-imamichi Apr 30, 2021
0b1c888
fix lint except cyclic import
t-imamichi Apr 30, 2021
5e69721
add an empty gurobi class in case not installed
t-imamichi Apr 30, 2021
97cc43d
fix lint
t-imamichi Apr 30, 2021
d2cb055
fix doctest
t-imamichi Apr 30, 2021
fb3b8d1
revert pylintrc
t-imamichi Apr 30, 2021
27e2713
Revert "revert pylintrc"
t-imamichi Apr 30, 2021
6ce27e1
apply black
t-imamichi May 6, 2021
ccb912f
Merge branch 'main' into translator
t-imamichi May 6, 2021
d05cecb
black -l 100
t-imamichi May 7, 2021
cc89df9
Merge branch 'main' into translator
t-imamichi May 7, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -147,11 +147,11 @@ jobs:
with:
name: optimization${{ matrix.python-version }}
path: ./o${{ matrix.python-version }}/*
- name: Optimization Unit Tests without cplex/cvxpy/matplotlib under Python ${{ matrix.python-version }}
- name: Optimization Unit Tests without cplex/cvxpy/matplotlib/gurobipy under Python ${{ matrix.python-version }}
env:
PYTHONWARNINGS: default
run: |
pip uninstall -y cplex cvxpy matplotlib
pip uninstall -y cplex cvxpy matplotlib gurobipy
if [ "${{ github.event_name }}" == "schedule" ] || [ "${{ contains(github.event.pull_request.labels.*.name, 'run_slow') }}" == "true" ]; then
export QISKIT_TESTS="run_slow"
fi
Expand Down
5 changes: 5 additions & 0 deletions .pylintdict
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ getter
goemans
grover
gset
gurobi
gurobipy
hamiltonian
hamiltonians
hardcoded
Expand Down Expand Up @@ -79,6 +81,7 @@ minimumeigenoptimizationresult
networkx
ndarray
ndarrays
noop
nosignatures
np
num
Expand Down Expand Up @@ -129,6 +132,7 @@ stdout
str
subgraph
submodules
sys
th
toctree
todo
Expand All @@ -139,6 +143,7 @@ upperbound
variational
vartype
vqe
writelines
xixj
xs
xuxv
Expand Down
2 changes: 1 addition & 1 deletion .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ ignored-classes=optparse.Values,thread._local,_thread._local,QuantumCircuit
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=
generated-members=gurobipy.*,gp.*

# List of decorators that produce context managers, such as
# contextlib.contextmanager. Add to this list to register other decorators that
Expand Down
3 changes: 3 additions & 0 deletions qiskit_optimization/algorithms/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
GoemansWilliamsonOptimizationResult
GroverOptimizationResult
GroverOptimizer
GurobiOptimizer
IntermediateResult
MeanAggregator
MinimumEigenOptimizationResult
Expand Down Expand Up @@ -75,6 +76,7 @@
GoemansWilliamsonOptimizationResult,
)
from .grover_optimizer import GroverOptimizer, GroverOptimizationResult
from .gurobi_optimizer import GurobiOptimizer
from .minimum_eigen_optimizer import (
MinimumEigenOptimizer,
MinimumEigenOptimizationResult,
Expand Down Expand Up @@ -111,6 +113,7 @@
"GoemansWilliamsonOptimizationResult",
"GroverOptimizer",
"GroverOptimizationResult",
"GurobiOptimizer",
"MeanAggregator",
"MinimumEigenOptimizer",
"MinimumEigenOptimizationResult",
Expand Down
152 changes: 152 additions & 0 deletions qiskit_optimization/algorithms/gurobi_optimizer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

"""The Gurobi optimizer wrapped to be used within Qiskit's optimization module."""

import logging

from qiskit.exceptions import MissingOptionalLibraryError
from .optimization_algorithm import OptimizationAlgorithm, OptimizationResult
from ..exceptions import QiskitOptimizationError
from ..problems.quadratic_program import QuadraticProgram
from ..translators.gurobipy import GurobipyTranslator

logger = logging.getLogger(__name__)

try:
import gurobipy as gp

_HAS_GUROBI = True
except ImportError:
_HAS_GUROBI = False


class GurobiOptimizer(OptimizationAlgorithm):
"""The Gurobi optimizer wrapped as an Qiskit :class:`OptimizationAlgorithm`.

This class provides a wrapper for ``gurobipy`` (https://pypi.gurobi.com)
to be used within the optimization module.

Examples:
>>> from qiskit_optimization.problems import QuadraticProgram
>>> from qiskit_optimization.algorithms import GurobiOptimizer
>>> problem = QuadraticProgram()
>>> # specify problem here, if gurobi is installed
>>> optimizer = GurobiOptimizer() if GurobiOptimizer.is_gurobi_installed() else None
>>> # Suppress gurobipy print info to stdout
>>> import sys
>>> class DevNull:
... def noop(*args, **kwargs): pass
... close = write = flush = writelines = noop
>>> sys.stdout = DevNull()
>>> result = optimizer.solve(problem) if GurobiOptimizer.is_gurobi_installed() else None
"""

def __init__(self, disp: bool = False) -> None:
"""Initializes the GurobiOptimizer.

Args:
disp: Whether to print Gurobi output or not.

Raises:
MissingOptionalLibraryError: Gurobi is not installed.
"""
if not _HAS_GUROBI:
raise MissingOptionalLibraryError(
libname="GUROBI",
name="GurobiOptimizer",
pip_install="pip install -i https://pypi.gurobi.com gurobipy",
)

self._disp = disp

@staticmethod
def is_gurobi_installed():
"""Returns True if gurobi is installed"""
return _HAS_GUROBI

@property
def disp(self) -> bool:
"""Returns the display setting.

Returns:
Whether to print Gurobi information or not.
"""
return self._disp

@disp.setter
def disp(self, disp: bool):
"""Set the display setting.
Args:
disp: The display setting.
"""
self._disp = disp

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

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

Args:
problem: The optimization problem to check compatibility.

Returns:
An empty string.
"""
return ""

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

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

Args:
problem: The problem to be solved.

Returns:
The result of the optimizer applied to the problem.

Raises:
QiskitOptimizationError: If the problem is incompatible with the optimizer.
"""

# convert to Gurobi problem
model = problem.to_model(translator=GurobipyTranslator())

# Enable non-convex
model.Params.NonConvex = 2

# set display setting

if not self.disp:
model.Params.OutputFlag = 0

# solve problem
try:
model.optimize()
except gp.GurobiError as ex:
raise QiskitOptimizationError(str(ex)) from ex

# create results
result = OptimizationResult(
x=model.X,
fval=model.ObjVal,
variables=problem.variables,
status=self._get_feasibility_status(problem, model.X),
raw_results=model,
)

# return solution
return result
Loading