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

Commit

Permalink
message enhancement in MatrixOp init
Browse files Browse the repository at this point in the history
  • Loading branch information
manoelmarques committed Oct 22, 2020
1 parent 2734384 commit 63941d3
Show file tree
Hide file tree
Showing 6 changed files with 45 additions and 16 deletions.
2 changes: 1 addition & 1 deletion qiskit/aqua/algorithms/quantum_algorithm.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ 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 "
raise AquaError("QuantumInstance or backend "
"is needed since you are running quantum algorithm.")
if isinstance(quantum_instance, (BaseBackend, Backend)):
self.set_backend(quantum_instance, **kwargs)
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
26 changes: 26 additions & 0 deletions test/aqua/operators/test_op_construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
CircuitStateFn, VectorStateFn, DictStateFn, OperatorStateFn, ListOp, ComposedOp, TensoredOp,
SummedOp
)
from qiskit.aqua.operators import MatrixOperator


# pylint: disable=invalid-name
Expand Down Expand Up @@ -909,6 +910,31 @@ def test_to_circuit_op(self):
sfn.to_circuit_op().eval().primitive.data, vector
)

def test_invalid_primitive(self):
"""Test invalid MatrixOp construction"""
msg = "MatrixOp can only be instantiated with " \
"['list', 'ndarray', 'spmatrix', 'Operator'], not "

with self.assertRaises(TypeError) as cm:
_ = MatrixOp('invalid')

self.assertEqual(str(cm.exception), msg + "'str'")

with self.assertRaises(TypeError) as cm:
_ = MatrixOp(MatrixOperator(np.eye(2)))

self.assertEqual(str(cm.exception), msg + "'MatrixOperator'")

with self.assertRaises(TypeError) as cm:
_ = MatrixOp(None)

self.assertEqual(str(cm.exception), msg + "'NoneType'")

with self.assertRaises(TypeError) as cm:
_ = MatrixOp(2.0)

self.assertEqual(str(cm.exception), msg + "'float'")


class TestOpMethods(QiskitAquaTestCase):
"""Basic method tests."""
Expand Down

0 comments on commit 63941d3

Please sign in to comment.