Skip to content

Commit

Permalink
Merge branch 'lazy-load-aer' of github.com:mtreinish/qiskit-core into…
Browse files Browse the repository at this point in the history
… lazy-load-aer
  • Loading branch information
mtreinish committed Jan 13, 2021
2 parents ea8cc7d + 1ed63e8 commit ce34092
Show file tree
Hide file tree
Showing 20 changed files with 204 additions and 149 deletions.
4 changes: 4 additions & 0 deletions qiskit/circuit/parametervector.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ def params(self):
"""Returns the list of parameters in the ParameterVector."""
return self._params

def index(self, value):
"""Returns first index of value."""
return self._params.index(value)

def __getitem__(self, key):
if isinstance(key, slice):
start, stop, step = key.indices(self._size)
Expand Down
19 changes: 9 additions & 10 deletions qiskit/opflow/gradients/circuit_gradients/lin_comb.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,13 @@ class LinComb(CircuitGradient):
see e.g. https://arxiv.org/pdf/1811.11184.pdf
"""

# pylint: disable=signature-differs
def convert(self,
operator: OperatorBase,
params: Optional[Union[ParameterExpression, ParameterVector,
List[ParameterExpression],
Tuple[ParameterExpression, ParameterExpression],
List[Tuple[ParameterExpression, ParameterExpression]]]]
= None,
params: Union[ParameterExpression, ParameterVector,
List[ParameterExpression],
Tuple[ParameterExpression, ParameterExpression],
List[Tuple[ParameterExpression, ParameterExpression]]]
) -> OperatorBase:
""" Convert the given operator into an operator object that represents the gradient w.r.t.
params
Expand All @@ -83,11 +83,10 @@ def convert(self,
# pylint: disable=too-many-return-statements
def _prepare_operator(self,
operator: OperatorBase,
params: Optional[Union[ParameterExpression, ParameterVector,
List[ParameterExpression],
Tuple[ParameterExpression, ParameterExpression],
List[Tuple[ParameterExpression,
ParameterExpression]]]] = None
params: Union[ParameterExpression, ParameterVector,
List[ParameterExpression],
Tuple[ParameterExpression, ParameterExpression],
List[Tuple[ParameterExpression, ParameterExpression]]]
) -> OperatorBase:
""" Traverse through the given operator to get back the adapted operator representing the
gradient
Expand Down
15 changes: 6 additions & 9 deletions qiskit/opflow/gradients/circuit_gradients/param_shift.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from collections.abc import Iterable
from copy import deepcopy
from functools import partial
from typing import List, Union, Optional, Tuple, Dict
from typing import List, Union, Tuple, Dict

import numpy as np
from qiskit import transpile, QuantumCircuit
Expand Down Expand Up @@ -78,14 +78,13 @@ def epsilon(self) -> float:
"""
return self._epsilon

# pylint: disable=arguments-differ
# pylint: disable=signature-differs
def convert(self,
operator: OperatorBase,
params: Optional[Union[ParameterExpression, ParameterVector,
List[ParameterExpression],
Tuple[ParameterExpression, ParameterExpression],
List[Tuple[ParameterExpression,
ParameterExpression]]]] = None) -> OperatorBase:
params: Union[ParameterExpression, ParameterVector, List[ParameterExpression],
Tuple[ParameterExpression, ParameterExpression],
List[Tuple[ParameterExpression, ParameterExpression]]]
) -> OperatorBase:
"""
Args:
operator: The operator corresponding to our quantum state we are taking the
Expand Down Expand Up @@ -152,8 +151,6 @@ def _parameter_shift(self,
# By this point, it's only one parameter
param = params

if not isinstance(param, ParameterExpression):
raise ValueError
if isinstance(operator, ListOp) and not isinstance(operator, ComposedOp):
return_op = operator.traverse(partial(self._parameter_shift, params=param))

Expand Down
5 changes: 2 additions & 3 deletions qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
""" CircuitQFI Class """

from abc import abstractmethod
from typing import List, Optional, Union
from typing import List, Union

from qiskit.circuit import ParameterExpression, ParameterVector
from ...converters.converter_base import ConverterBase
Expand All @@ -39,8 +39,7 @@ class CircuitQFI(ConverterBase):
@abstractmethod
def convert(self,
operator: OperatorBase,
params: Optional[Union[ParameterExpression, ParameterVector,
List[ParameterExpression]]] = None,
params: Union[ParameterExpression, ParameterVector, List[ParameterExpression]]
) -> OperatorBase:
r"""
Args:
Expand Down
8 changes: 4 additions & 4 deletions qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"""The module for Quantum the Fisher Information."""

from copy import deepcopy
from typing import List, Union, Optional, Tuple
from typing import List, Union, Tuple

import numpy as np
from qiskit.circuit import Gate, Qubit
Expand Down Expand Up @@ -41,8 +41,7 @@ class LinCombFull(CircuitQFI):

def convert(self,
operator: CircuitStateFn,
params: Optional[Union[ParameterExpression, ParameterVector,
List[ParameterExpression]]] = None,
params: Union[ParameterExpression, ParameterVector, List[ParameterExpression]]
) -> ListOp:
r"""
Args:
Expand Down Expand Up @@ -70,8 +69,9 @@ def convert(self,
'LinCombFull is only compatible with states that are given as CircuitStateFn')

# If a single parameter is given wrap it into a list.
if not isinstance(params, (list, np.ndarray)):
if isinstance(params, ParameterExpression):
params = [params]

state_qc = operator.primitive

# First, the operators are computed which can compensate for a potential phase-mismatch
Expand Down
14 changes: 9 additions & 5 deletions qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

"""The module for Quantum the Fisher Information."""

from typing import List, Union, Optional
from typing import List, Union

import numpy as np
from scipy.linalg import block_diag
Expand All @@ -39,8 +39,7 @@ class OverlapBlockDiag(CircuitQFI):

def convert(self,
operator: Union[CircuitOp, CircuitStateFn],
params: Optional[Union[ParameterExpression, ParameterVector,
List[ParameterExpression]]] = None
params: Union[ParameterExpression, ParameterVector, List[ParameterExpression]]
) -> ListOp:
r"""
Args:
Expand All @@ -61,8 +60,9 @@ def convert(self,

def _block_diag_approx(self,
operator: Union[CircuitOp, CircuitStateFn],
params: Optional[Union[ParameterExpression, ParameterVector,
List[ParameterExpression]]] = None
params: Union[ParameterExpression,
ParameterVector,
List[ParameterExpression]]
) -> ListOp:
r"""
Args:
Expand All @@ -81,6 +81,10 @@ def _block_diag_approx(self,
"""

# If a single parameter is given wrap it into a list.
if isinstance(params, ParameterExpression):
params = [params]

circuit = operator.primitive
# Partition the circuit into layers, and build the circuits to prepare $\psi_i$
layers = _partition_circuit(circuit)
Expand Down
14 changes: 8 additions & 6 deletions qiskit/opflow/gradients/circuit_qfis/overlap_diag.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,12 @@

"""The module for Quantum the Fisher Information."""
import copy
from typing import List, Union, Optional
from typing import List, Union

import numpy as np
from qiskit.circuit import ParameterVector, ParameterExpression
from qiskit.circuit.library import RZGate, RXGate, RYGate
from qiskit.converters import dag_to_circuit, circuit_to_dag
from ...operator_base import OperatorBase
from ...list_ops.list_op import ListOp
from ...primitive_ops.circuit_op import CircuitOp
from ...expectations.pauli_expectation import PauliExpectation
Expand All @@ -39,8 +38,7 @@ class OverlapDiag(CircuitQFI):

def convert(self,
operator: Union[CircuitOp, CircuitStateFn],
params: Optional[Union[ParameterExpression, ParameterVector,
List[ParameterExpression]]] = None
params: Union[ParameterExpression, ParameterVector, List[ParameterExpression]]
) -> ListOp:
r"""
Args:
Expand All @@ -66,8 +64,8 @@ def convert(self,
# This should be fixed.
def _diagonal_approx(self,
operator: Union[CircuitOp, CircuitStateFn],
params: Union[ParameterExpression, ParameterVector, List] = None
) -> OperatorBase:
params: Union[ParameterExpression, ParameterVector, List]
) -> ListOp:
"""
Args:
operator: The operator corresponding to the quantum state |ψ(ω)〉for which we compute
Expand All @@ -88,6 +86,10 @@ def _diagonal_approx(self,
if not isinstance(operator, CircuitStateFn):
raise NotImplementedError('operator must be a CircuitStateFn')

# If a single parameter is given wrap it into a list.
if isinstance(params, ParameterExpression):
params = [params]

circuit = operator.primitive

# Partition the circuit into layers, and build the circuits to prepare $\psi_i$
Expand Down
11 changes: 4 additions & 7 deletions qiskit/opflow/gradients/gradient.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

"""The base interface for Aqua's gradient."""
"""The base interface for Opflow's gradient."""

from typing import Union, List, Optional
from typing import Union, List

import numpy as np
from qiskit.exceptions import MissingOptionalLibraryError
Expand All @@ -38,10 +38,10 @@
class Gradient(GradientBase):
"""Convert an operator expression to the first-order gradient."""

# pylint: disable=signature-differs
def convert(self,
operator: OperatorBase,
params: Optional[Union[ParameterVector, ParameterExpression,
List[ParameterExpression]]] = None
params: Union[ParameterVector, ParameterExpression, List[ParameterExpression]]
) -> OperatorBase:
r"""
Args:
Expand All @@ -55,9 +55,6 @@ def convert(self,
ValueError: If ``params`` contains a parameter not present in ``operator``.
"""

if params is None:
raise ValueError("No parameters were provided to differentiate")

if isinstance(params, (ParameterVector, list)):
param_grads = [self.convert(operator, param) for param in params]
absent_params = [params[i]
Expand Down
20 changes: 7 additions & 13 deletions qiskit/opflow/gradients/hessian.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

"""The module to compute Hessians."""

from typing import Optional, Union, List, Tuple
from typing import Union, List, Tuple

import numpy as np
from qiskit.exceptions import MissingOptionalLibraryError
Expand Down Expand Up @@ -40,11 +40,12 @@
class Hessian(HessianBase):
"""Compute the Hessian of an expected value."""

# pylint: disable=signature-differs
def convert(self,
operator: OperatorBase,
params: Optional[Union[Tuple[ParameterExpression, ParameterExpression],
List[Tuple[ParameterExpression, ParameterExpression]],
List[ParameterExpression], ParameterVector]] = None
params: Union[Tuple[ParameterExpression, ParameterExpression],
List[Tuple[ParameterExpression, ParameterExpression]],
List[ParameterExpression], ParameterVector]
) -> OperatorBase:
"""
Args:
Expand All @@ -56,14 +57,8 @@ def convert(self,
Returns:
OperatorBase: An operator whose evaluation yields the Hessian
Raises:
ValueError: If `params` is not set.
"""
# if input is a tuple instead of a list, wrap it into a list
if params is None:
raise ValueError("No parameters were provided to differentiate")

if isinstance(params, (ParameterVector, list)):
# Case: a list of parameters were given, compute the Hessian for all param pairs
if all(isinstance(param, ParameterExpression) for param in params):
Expand All @@ -81,9 +76,8 @@ def convert(self,
# pylint: disable=too-many-return-statements
def get_hessian(self,
operator: OperatorBase,
params: Optional[Union[Tuple[ParameterExpression, ParameterExpression],
List[Tuple[ParameterExpression, ParameterExpression]]]]
= None
params: Union[Tuple[ParameterExpression, ParameterExpression],
List[Tuple[ParameterExpression, ParameterExpression]]]
) -> OperatorBase:
"""Get the Hessian for the given operator w.r.t. the given parameters
Expand Down
5 changes: 2 additions & 3 deletions qiskit/opflow/gradients/natural_gradient.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,10 @@ def __init__(self,
self._regularization = regularization
self._epsilon = kwargs.get('epsilon', 1e-6)

# pylint: disable=arguments-differ
# pylint: disable=signature-differs
def convert(self,
operator: OperatorBase,
params: Optional[Union[ParameterVector, ParameterExpression,
List[ParameterExpression]]] = None
params: Union[ParameterVector, ParameterExpression, List[ParameterExpression]]
) -> OperatorBase:
r"""
Args:
Expand Down
6 changes: 3 additions & 3 deletions qiskit/opflow/gradients/qfi.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

"""The module for Quantum the Fisher Information."""

from typing import List, Union, Optional
from typing import List, Union

from qiskit.circuit import (ParameterExpression, ParameterVector)
from ..list_ops.list_op import ListOp
Expand All @@ -33,10 +33,10 @@ class QFI(QFIBase):
"""

# pylint: disable=signature-differs
def convert(self,
operator: CircuitStateFn,
params: Optional[Union[ParameterExpression, ParameterVector,
List[ParameterExpression]]] = None
params: Union[ParameterExpression, ParameterVector, List[ParameterExpression]]
) -> ListOp:
r"""
Args:
Expand Down
Loading

0 comments on commit ce34092

Please sign in to comment.