From ee814f96a788b64cbf82b9e23588ef3ad0eea725 Mon Sep 17 00:00:00 2001 From: "Christopher J. Wood" Date: Fri, 20 Nov 2020 14:42:24 -0500 Subject: [PATCH] Fix bug when multiplying SparsePauliOp by np.int64 (#5417) * Fix bug when multiplying SparsePauliOp by np.int64 Fix is to add dispatch mechanism for numpy ufuncs to BaseOperator which maps `np.multiply` to the `BaseOperator._multiply` method. * Change __array_ufunc__ to using __array_priority__ * Update releasenotes/notes/fix-op-ufunc-multiple-d1c59b236024f483.yaml Co-authored-by: Matthew Treinish (cherry picked from commit d26f273d17ef2ce2a18be5d5eb51b86a684f6921) --- qiskit/quantum_info/operators/base_operator.py | 3 +++ .../notes/fix-op-ufunc-multiple-d1c59b236024f483.yaml | 6 ++++++ .../operators/symplectic/test_sparse_pauli_op.py | 2 +- 3 files changed, 10 insertions(+), 1 deletion(-) create mode 100644 releasenotes/notes/fix-op-ufunc-multiple-d1c59b236024f483.yaml diff --git a/qiskit/quantum_info/operators/base_operator.py b/qiskit/quantum_info/operators/base_operator.py index cf478e3723f3..8fbae2ffe5af 100644 --- a/qiskit/quantum_info/operators/base_operator.py +++ b/qiskit/quantum_info/operators/base_operator.py @@ -85,6 +85,9 @@ def __init__(self, input_dims, output_dims): self._num_qubits = None # number of qubit subsystems if N-qubit operator self._set_dims(input_dims, output_dims) + # Set higher priority than Numpy array and matrix classes + __array_priority__ = 20 + def __call__(self, qargs): """Return a clone with qargs set""" if isinstance(qargs, int): diff --git a/releasenotes/notes/fix-op-ufunc-multiple-d1c59b236024f483.yaml b/releasenotes/notes/fix-op-ufunc-multiple-d1c59b236024f483.yaml new file mode 100644 index 000000000000..63b6f53a21e7 --- /dev/null +++ b/releasenotes/notes/fix-op-ufunc-multiple-d1c59b236024f483.yaml @@ -0,0 +1,6 @@ +--- +fixes: + - | + Fixes bug in :class:`~qiskit.quantum_info.SparsePauliOp` where multiplying + by a certain non Python builtin Numpy scalar types returned incorrect values. + Fixes `#5408 `__ diff --git a/test/python/quantum_info/operators/symplectic/test_sparse_pauli_op.py b/test/python/quantum_info/operators/symplectic/test_sparse_pauli_op.py index b8f5d28400ea..bf33c710c7e5 100644 --- a/test/python/quantum_info/operators/symplectic/test_sparse_pauli_op.py +++ b/test/python/quantum_info/operators/symplectic/test_sparse_pauli_op.py @@ -328,7 +328,7 @@ def test_sub_qargs(self, num_qubits): value = (spp_op1 - spp_op2(qargs)).to_operator() self.assertEqual(value, target) - @combine(num_qubits=[1, 2, 3], value=[0, 1, 1j, -3+4.4j]) + @combine(num_qubits=[1, 2, 3], value=[0, 1, 1j, -3+4.4j, np.int64(2)]) def test_mul(self, num_qubits, value): """Test * method for {num_qubits} qubits and value {value}.""" spp_op = random_unitary(2 ** num_qubits, seed=self.RNG)