Skip to content

Commit

Permalink
remove runtime program and quantum instance
Browse files Browse the repository at this point in the history
  • Loading branch information
t-imamichi committed Aug 30, 2023
1 parent e2855f2 commit e30955f
Show file tree
Hide file tree
Showing 19 changed files with 62 additions and 2,783 deletions.
6 changes: 0 additions & 6 deletions docs/apidocs/qiskit_optimization.runtime.rst

This file was deleted.

682 changes: 0 additions & 682 deletions docs/tutorials/12_qaoa_runtime.ipynb

This file was deleted.

7 changes: 3 additions & 4 deletions qiskit_optimization/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019, 2022.
# (C) Copyright IBM 2019, 2023.
#
# 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
Expand Down Expand Up @@ -80,14 +80,13 @@
applications
converters
problems
runtime
translators
"""

from .version import __version__
from .infinity import INFINITY # must be at the top of the file
from .exceptions import QiskitOptimizationError
from .infinity import INFINITY # must be at the top of the file
from .problems.quadratic_program import QuadraticProgram
from .version import __version__

__all__ = ["__version__", "QuadraticProgram", "QiskitOptimizationError", "INFINITY"]
119 changes: 21 additions & 98 deletions qiskit_optimization/algorithms/grover_optimizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@
from qiskit.algorithms.amplitude_amplifiers.grover import Grover
from qiskit.circuit.library import QuadraticForm
from qiskit.primitives import BaseSampler
from qiskit.providers import Backend
from qiskit.quantum_info import partial_trace
from qiskit.utils import QuantumInstance, algorithm_globals
from qiskit.utils import algorithm_globals

from qiskit_optimization.algorithms.optimization_algorithm import (
OptimizationAlgorithm,
Expand All @@ -34,12 +32,6 @@
SolutionSample,
)
from qiskit_optimization.converters import QuadraticProgramConverter, QuadraticProgramToQubo
from qiskit_optimization.deprecation import (
DeprecatedType,
deprecate_method,
deprecate_property,
warn_deprecated,
)
from qiskit_optimization.exceptions import QiskitOptimizationError
from qiskit_optimization.problems import QuadraticProgram, Variable

Expand All @@ -53,7 +45,6 @@ def __init__(
self,
num_value_qubits: int,
num_iterations: int = 3,
quantum_instance: Optional[Union[Backend, QuantumInstance]] = None,
converters: Optional[
Union[QuadraticProgramConverter, List[QuadraticProgramConverter]]
] = None,
Expand All @@ -65,7 +56,6 @@ def __init__(
num_value_qubits: The number of value qubits.
num_iterations: The number of iterations the algorithm will search with
no improvement.
quantum_instance: Instance of selected backend, defaults to Aer's statevector simulator.
converters: The converters to use for converting a problem into a different form.
By default, when None is specified, an internally created instance of
:class:`~qiskit_optimization.converters.QuadraticProgramToQubo` will be used.
Expand All @@ -82,44 +72,8 @@ def __init__(
self._n_iterations = num_iterations
self._circuit_results = {} # type: dict
self._converters = self._prepare_converters(converters, penalty)

if quantum_instance is not None and sampler is not None:
raise ValueError("Only one of quantum_instance or sampler can be passed, not both!")

if quantum_instance:
warn_deprecated(
"0.6.0",
old_type=DeprecatedType.ARGUMENT,
old_name="quantum_instance",
new_type=DeprecatedType.ARGUMENT,
new_name="sampler",
)
self._quantum_instance = quantum_instance # type: Optional[QuantumInstance]
self._sampler = sampler

@property
@deprecate_property("0.6.0")
def quantum_instance(self) -> QuantumInstance:
"""The quantum instance to run the circuits.
Returns:
The quantum instance used in the algorithm.
"""
return self._quantum_instance

@quantum_instance.setter
@deprecate_method("0.6.0")
def quantum_instance(self, quantum_instance: Union[Backend, QuantumInstance]) -> None:
"""Set the quantum instance used to run the circuits.
Args:
quantum_instance: The quantum instance to be used in the algorithm.
"""
if isinstance(quantum_instance, Backend):
self._quantum_instance = QuantumInstance(quantum_instance)
else:
self._quantum_instance = quantum_instance

def get_compatibility_msg(self, problem: QuadraticProgram) -> str:
"""Checks whether a given problem can be solved with this optimizer.
Expand Down Expand Up @@ -185,11 +139,8 @@ def solve(self, problem: QuadraticProgram) -> OptimizationResult:
AttributeError: If the quantum instance has not been set.
QiskitOptimizationError: If the problem is incompatible with the optimizer.
"""
if self._sampler is None and self._quantum_instance is None:
raise ValueError("A quantum instance or sampler must be provided.")

if self._quantum_instance is not None and self._sampler is not None:
raise ValueError("Only one of quantum_instance or sampler can be passed, not both!")
if self._sampler is None:
raise ValueError("A sampler must be provided.")

self._verify_compatibility(problem)

Expand Down Expand Up @@ -222,7 +173,7 @@ def solve(self, problem: QuadraticProgram) -> OptimizationResult:
# Initialize oracle helper object.
qr_key_value = QuantumRegister(self._num_key_qubits + self._num_value_qubits)
orig_constant = problem_.objective.constant
measurement = self._quantum_instance is None or not self._quantum_instance.is_statevector
measurement = True
oracle, is_good_state = self._get_oracle(qr_key_value)

while not optimum_found:
Expand Down Expand Up @@ -274,14 +225,9 @@ def solve(self, problem: QuadraticProgram) -> OptimizationResult:
i[-1 * n_key :]: v for i, v in self._circuit_results.items()
}
else:
if self._quantum_instance.is_statevector:
indices = list(range(n_key, len(outcome)))
rho = partial_trace(self._circuit_results, indices)
self._circuit_results = cast(Dict, np.diag(rho.data) ** 0.5)
else:
self._circuit_results = {
i[-1 * n_key :]: v for i, v in self._circuit_results.items()
}
self._circuit_results = {
i[-1 * n_key :]: v for i, v in self._circuit_results.items()
}
raw_samples = self._eigenvector_to_solutions(
self._circuit_results, problem_init
)
Expand Down Expand Up @@ -347,43 +293,20 @@ def _measure(self, circuit: QuantumCircuit) -> str:
def _get_prob_dist(self, qc: QuantumCircuit) -> Dict[str, float]:
"""Gets probabilities from a given backend."""
# Execute job and filter results.
if self._sampler is not None:
job = self._sampler.run([qc])

try:
result = job.result()
except Exception as exc:
raise QiskitOptimizationError("Sampler job failed.") from exc
quasi_dist = result.quasi_dists[0]
raw_prob_dist = {
k: v
for k, v in quasi_dist.binary_probabilities(qc.num_qubits).items()
if v >= self._MIN_PROBABILITY
}
prob_dist = {k[::-1]: v for k, v in raw_prob_dist.items()}
self._circuit_results = {i: v**0.5 for i, v in raw_prob_dist.items()}
else:
result = self._quantum_instance.execute(qc)
if self._quantum_instance.is_statevector:
state = result.get_statevector(qc)
if not isinstance(state, np.ndarray):
state = state.data
keys = [
bin(i)[2::].rjust(int(np.log2(len(state))), "0")[::-1]
for i in range(0, len(state))
]
probs = [abs(a) ** 2 for a in state]
total = math.fsum(probs)
probs = [p / total for p in probs]
prob_dist = {key: prob for key, prob in zip(keys, probs) if prob > 0}
self._circuit_results = state
else:
state = result.get_counts(qc)
shots = self._quantum_instance.run_config.shots
prob_dist = {
key[::-1]: val / shots for key, val in sorted(state.items()) if val > 0
}
self._circuit_results = {b: (v / shots) ** 0.5 for (b, v) in state.items()}
job = self._sampler.run([qc])

try:
result = job.result()
except Exception as exc:
raise QiskitOptimizationError("Sampler job failed.") from exc
quasi_dist = result.quasi_dists[0]
raw_prob_dist = {
k: v
for k, v in quasi_dist.binary_probabilities(qc.num_qubits).items()
if v >= self._MIN_PROBABILITY
}
prob_dist = {k[::-1]: v for k, v in raw_prob_dist.items()}
self._circuit_results = {i: v**0.5 for i, v in raw_prob_dist.items()}
return prob_dist

@staticmethod
Expand Down
23 changes: 4 additions & 19 deletions qiskit_optimization/algorithms/minimum_eigen_optimizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,6 @@
from typing import List, Optional, Union, cast

import numpy as np
from qiskit.algorithms.minimum_eigen_solvers import MinimumEigensolver as LegacyMinimumEigensolver
from qiskit.algorithms.minimum_eigen_solvers import (
MinimumEigensolverResult as LegacyMinimumEigensolverResult,
)
from qiskit.algorithms.minimum_eigensolvers import (
VQE,
NumPyMinimumEigensolver,
Expand All @@ -37,12 +33,8 @@
SolutionSample,
)

MinimumEigensolver = Union[
SamplingMinimumEigensolver, NumPyMinimumEigensolver, LegacyMinimumEigensolver
]
MinimumEigensolverResult = Union[
SamplingMinimumEigensolverResult, NumPyMinimumEigensolverResult, LegacyMinimumEigensolverResult
]
MinimumEigensolver = Union[SamplingMinimumEigensolver, NumPyMinimumEigensolver]
MinimumEigensolverResult = Union[SamplingMinimumEigensolverResult, NumPyMinimumEigensolverResult]


class MinimumEigenOptimizationResult(OptimizationResult):
Expand Down Expand Up @@ -159,7 +151,7 @@ def __init__(
)
if not isinstance(
min_eigen_solver,
(SamplingMinimumEigensolver, NumPyMinimumEigensolver, LegacyMinimumEigensolver),
(SamplingMinimumEigensolver, NumPyMinimumEigensolver),
):
raise TypeError(
"MinimumEigenOptimizer supports "
Expand Down Expand Up @@ -237,14 +229,7 @@ def _solve_internal(
eigen_result: Optional[MinimumEigensolverResult] = None
if operator.num_qubits > 0:
# approximate ground state of operator using min eigen solver
if isinstance(self._min_eigen_solver, LegacyMinimumEigensolver):
from qiskit.opflow import PauliSumOp

eigen_result = self._min_eigen_solver.compute_minimum_eigenvalue(
PauliSumOp(operator)
)
else:
eigen_result = self._min_eigen_solver.compute_minimum_eigenvalue(operator)
eigen_result = self._min_eigen_solver.compute_minimum_eigenvalue(operator)
# analyze results
raw_samples = None
if eigen_result.eigenstate is not None:
Expand Down
3 changes: 1 addition & 2 deletions qiskit_optimization/algorithms/warm_start_qaoa_optimizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

import numpy as np
from qiskit import QuantumCircuit
from qiskit.algorithms import QAOA as LegacyQAOA
from qiskit.algorithms.minimum_eigensolvers import QAOA
from qiskit.circuit import Parameter

Expand Down Expand Up @@ -203,7 +202,7 @@ def __init__(
self,
pre_solver: OptimizationAlgorithm,
relax_for_pre_solver: bool,
qaoa: Union[QAOA, LegacyQAOA],
qaoa: QAOA,
epsilon: float = 0.25,
num_initial_solutions: int = 1,
warm_start_factory: Optional[WarmStartQAOAFactory] = None,
Expand Down
45 changes: 0 additions & 45 deletions qiskit_optimization/runtime/__init__.py

This file was deleted.

Loading

0 comments on commit e30955f

Please sign in to comment.