Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add atol parameter to SparsePauliOp.equiv #8281

Merged
merged 3 commits into from
Jul 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

from collections import defaultdict
from numbers import Number
from typing import Dict
from typing import Dict, Optional

import numpy as np
import retworkx as rx
Expand Down Expand Up @@ -139,18 +139,21 @@ def __eq__(self, other):
and self.paulis == other.paulis
)

def equiv(self, other):
def equiv(self, other, atol: Optional[float] = None):
"""Check if two SparsePauliOp operators are equivalent.

Args:
other (SparsePauliOp): an operator object.
atol: Absolute numerical tolerance for checking equivalence.

Returns:
bool: True if the operator is equivalent to ``self``.
"""
if not super().__eq__(other):
return False
return np.allclose((self - other).simplify().coeffs, [0])
if atol is None:
atol = self.atol
return np.allclose((self - other).simplify().coeffs, 0.0, atol=atol)

@property
def settings(self) -> Dict:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
features:
- |
Adds `atol` parameter to :meth:`.SparsePauliOp.equiv`.
Original file line number Diff line number Diff line change
Expand Up @@ -592,6 +592,13 @@ def test_equiv(self, num_qubits):
if not spp_op2.equiv(zero):
self.assertFalse(spp_op2.equiv(spp_op2 + spp_op2))

def test_equiv_atol(self):
"""Test equiv method with atol."""
op1 = SparsePauliOp.from_list([("X", 1), ("Y", 2)])
op2 = op1 + 1e-7 * SparsePauliOp.from_list([("I", 1)])
self.assertFalse(op1.equiv(op2))
self.assertTrue(op1.equiv(op2, atol=1e-7))

def test_eq_equiv(self):
"""Test __eq__ and equiv methods with some specific cases."""
with self.subTest("shuffled"):
Expand Down