Skip to content
This repository has been archived by the owner on Dec 7, 2021. It is now read-only.

Commit

Permalink
Merge branch 'master' into initial-state
Browse files Browse the repository at this point in the history
  • Loading branch information
Cryoris committed Oct 26, 2020
2 parents e8fff1b + 739e330 commit b94f78e
Show file tree
Hide file tree
Showing 21 changed files with 295 additions and 83 deletions.
3 changes: 2 additions & 1 deletion qiskit/aqua/algorithms/classifiers/qsvm/_qsvm_binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,10 @@ def train(self, data, labels):
"""
scaling = 1.0 if self._qalgo.quantum_instance.is_statevector else None
kernel_matrix = self._qalgo.construct_kernel_matrix(data)
lambda2 = self._qalgo.lambda2
labels = labels * 2 - 1 # map label from 0 --> -1 and 1 --> 1
labels = labels.astype(np.float)
[alpha, b, support] = optimize_svm(kernel_matrix, labels, scaling=scaling)
[alpha, b, support] = optimize_svm(kernel_matrix, labels, scaling=scaling, lambda2=lambda2)
support_index = np.where(support)
alphas = alpha[support_index]
svms = data[support_index]
Expand Down
3 changes: 3 additions & 0 deletions qiskit/aqua/algorithms/classifiers/qsvm/qsvm.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ def __init__(self, feature_map: Union[QuantumCircuit, FeatureMap],
test_dataset: Optional[Dict[str, np.ndarray]] = None,
datapoints: Optional[np.ndarray] = None,
multiclass_extension: Optional[MulticlassExtension] = None,
lambda2: float = 0.001,
quantum_instance: Optional[
Union[QuantumInstance, BaseBackend, Backend]] = None) -> None:
"""
Expand All @@ -90,6 +91,7 @@ def __init__(self, feature_map: Union[QuantumCircuit, FeatureMap],
datapoints: Prediction dataset.
multiclass_extension: If number of classes is greater than 2 then a multiclass scheme
must be supplied, in the form of a multiclass extension.
lambda2: L2 norm regularization factor
quantum_instance: Quantum Instance or Backend
Raises:
Expand Down Expand Up @@ -118,6 +120,7 @@ def __init__(self, feature_map: Union[QuantumCircuit, FeatureMap],
self.setup_training_data(training_dataset)
self.setup_test_data(test_dataset)
self.setup_datapoint(datapoints)
self.lambda2 = lambda2

self.feature_map = feature_map
self.num_qubits = self.feature_map.num_qubits
Expand Down
6 changes: 2 additions & 4 deletions qiskit/aqua/algorithms/minimum_eigen_solvers/qaoa/var_form.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import numpy as np

from qiskit import QuantumCircuit
from qiskit.aqua.operators import (OperatorBase, X, I, H, Zero, CircuitStateFn,
from qiskit.aqua.operators import (OperatorBase, X, I, H, CircuitStateFn,
EvolutionFactory, LegacyBaseOperator)
from qiskit.aqua.components.variational_forms import VariationalForm
from qiskit.aqua.components.initial_states import InitialState
Expand Down Expand Up @@ -81,15 +81,13 @@ def construct_circuit(self, parameters, q=None):
self.num_parameters, len(parameters)
))

circuit = (H ^ self._num_qubits)
# initialize circuit, possibly based on given register/initial state
if isinstance(self._initial_state, QuantumCircuit):
init_state = CircuitStateFn(self._initial_state)
elif self._initial_state is not None:
init_state = CircuitStateFn(self._initial_state.construct_circuit('circuit'))
else:
init_state = Zero
circuit = circuit.compose(init_state)
circuit = (H ^ self._num_qubits)

for idx in range(self._p):
circuit = (self._cost_operator * parameters[idx]).exp_i().compose(circuit)
Expand Down
4 changes: 2 additions & 2 deletions qiskit/aqua/algorithms/quantum_algorithm.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ def run(self,
AquaError: If a quantum instance or backend has not been provided
"""
if quantum_instance is None and self.quantum_instance is None:
raise AquaError("Quantum device or backend "
"is needed since you are running quantum algorithm.")
raise AquaError("A QuantumInstance or Backend "
"must be supplied to run the quantum algorithm.")
if isinstance(quantum_instance, (BaseBackend, Backend)):
self.set_backend(quantum_instance, **kwargs)
else:
Expand Down
14 changes: 11 additions & 3 deletions qiskit/aqua/operators/list_ops/list_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -504,16 +504,24 @@ def to_legacy_op(self, massive: bool = False) -> LegacyBaseOperator:

# Array operations:

def __getitem__(self, offset: int) -> OperatorBase:
def __getitem__(self, offset: Union[int, slice]) -> OperatorBase:
""" Allows array-indexing style access to the Operators in ``oplist``.
Args:
offset: The index of ``oplist`` desired.
Returns:
The ``OperatorBase`` at index ``offset`` of ``oplist``.
The ``OperatorBase`` at index ``offset`` of ``oplist``,
or another ListOp with the same properties as this one if offset is a slice.
"""
return self.oplist[offset]
if isinstance(offset, slice):
return ListOp(self._oplist[offset],
self._combo_fn,
self._coeff,
self._abelian,
self._grad_combo_fn)
else:
return self.oplist[offset]

def __iter__(self) -> Iterator:
""" Returns an iterator over the operators in ``oplist``.
Expand Down
5 changes: 2 additions & 3 deletions qiskit/aqua/operators/primitive_ops/circuit_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,8 @@ class CircuitOp(PrimitiveOp):
"""

def __init__(self,
primitive: Union[Instruction, QuantumCircuit] = None,
coeff: Optional[Union[int, float, complex,
ParameterExpression]] = 1.0) -> None:
primitive: Union[Instruction, QuantumCircuit],
coeff: Union[int, float, complex, ParameterExpression] = 1.0) -> None:
"""
Args:
primitive: The QuantumCircuit which defines the
Expand Down
14 changes: 8 additions & 6 deletions qiskit/aqua/operators/primitive_ops/matrix_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

""" MatrixOp Class """

from typing import Union, Optional, Set, Dict, List, cast
from typing import Union, Optional, Set, Dict, List, cast, get_type_hints
import logging
import numpy as np
from scipy.sparse import spmatrix
Expand Down Expand Up @@ -40,8 +40,8 @@ class MatrixOp(PrimitiveOp):
"""

def __init__(self,
primitive: Union[list, np.ndarray, spmatrix, Operator] = None,
coeff: Optional[Union[int, float, complex, ParameterExpression]] = 1.0) -> None:
primitive: Union[list, np.ndarray, spmatrix, Operator],
coeff: Union[int, float, complex, ParameterExpression] = 1.0) -> None:
"""
Args:
primitive: The matrix-like object which defines the behavior of the underlying function.
Expand All @@ -51,16 +51,18 @@ def __init__(self,
TypeError: invalid parameters.
ValueError: invalid parameters.
"""
primitive_orig = primitive
if isinstance(primitive, spmatrix):
primitive = primitive.toarray()

if isinstance(primitive, (list, np.ndarray)):
primitive = Operator(primitive)

if not isinstance(primitive, Operator):
raise TypeError(
'MatrixOp can only be instantiated with MatrixOperator, '
'not {}'.format(type(primitive)))
type_hints = get_type_hints(MatrixOp.__init__).get('primitive')
valid_cls = [cls.__name__ for cls in type_hints.__args__]
raise TypeError(f"MatrixOp can only be instantiated with {valid_cls}, "
f"not '{primitive_orig.__class__.__name__}'")

if not primitive.input_dims() == primitive.output_dims():
raise ValueError('Cannot handle non-square matrices yet.')
Expand Down
2 changes: 1 addition & 1 deletion qiskit/aqua/operators/primitive_ops/pauli_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class PauliOp(PrimitiveOp):
"""

def __init__(self,
primitive: Union[Pauli] = None,
primitive: Union[Pauli],
coeff: Union[int, float, complex, ParameterExpression] = 1.0) -> None:
"""
Args:
Expand Down
12 changes: 7 additions & 5 deletions qiskit/aqua/operators/primitive_ops/primitive_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,9 @@ class PrimitiveOp(OperatorBase):
@staticmethod
# pylint: disable=unused-argument
def __new__(cls,
primitive: Union[Instruction, QuantumCircuit, List,
np.ndarray, spmatrix, MatrixOperator, Pauli] = None,
primitive:
Optional[Union[Instruction, QuantumCircuit, List,
np.ndarray, spmatrix, MatrixOperator, Pauli]] = None,
coeff: Union[int, float, complex, ParameterExpression] = 1.0) -> 'PrimitiveOp':
""" A factory method to produce the correct type of PrimitiveOp subclass
based on the primitive passed in. Primitive and coeff arguments are passed into
Expand Down Expand Up @@ -85,9 +86,10 @@ def __new__(cls,
'factory constructor'.format(type(primitive)))

def __init__(self,
primitive: Union[Instruction, QuantumCircuit, List,
np.ndarray, spmatrix, MatrixOperator, Pauli] = None,
coeff: Optional[Union[int, float, complex, ParameterExpression]] = 1.0) -> None:
primitive:
Optional[Union[Instruction, QuantumCircuit, List,
np.ndarray, spmatrix, MatrixOperator, Pauli]] = None,
coeff: Union[int, float, complex, ParameterExpression] = 1.0) -> None:
"""
Args:
primitive: The operator primitive being wrapped.
Expand Down
Loading

0 comments on commit b94f78e

Please sign in to comment.