Skip to content

Commit

Permalink
Allow measure_single_paulistring to have negative coefficient (#6143)
Browse files Browse the repository at this point in the history
* updating tests

* formatted

* added test

* fixed type error

* Update cirq-core/cirq/ops/measure_util_test.py

Co-authored-by: Tanuj Khattar <tanujkhattar@google.com>

---------

Co-authored-by: Tanuj Khattar <tanujkhattar@google.com>
  • Loading branch information
skushnir123 and tanujkhattar committed Jun 13, 2023
1 parent 9a1609c commit 26af12e
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
12 changes: 8 additions & 4 deletions cirq-core/cirq/ops/measure_util.py
Expand Up @@ -46,18 +46,22 @@ def measure_single_paulistring(
Raises:
ValueError: if the observable is not an instance of PauliString or if the coefficient
is not +1.
is not +1 or -1.
"""
if not isinstance(pauli_observable, pauli_string.PauliString):
raise ValueError(
f'Pauli observable {pauli_observable} should be an instance of cirq.PauliString.'
)
if pauli_observable.coefficient != 1:
raise ValueError(f"Pauli observable {pauli_observable} must have a coefficient of +1.")
if abs(pauli_observable.coefficient) != 1:
raise ValueError(
f"Pauli observable {pauli_observable} must have a coefficient of +1 or -1."
)

if key is None:
key = _default_measurement_key(pauli_observable)
return PauliMeasurementGate(pauli_observable.values(), key).on(*pauli_observable.keys())
return PauliMeasurementGate(pauli_observable.dense(list(pauli_observable.keys())), key).on(
*pauli_observable.keys()
)


def measure_paulistring_terms(
Expand Down
10 changes: 8 additions & 2 deletions cirq-core/cirq/ops/measure_util_test.py
Expand Up @@ -95,6 +95,12 @@ def test_measure_single_paulistring():
ps.values(), key='a'
).on(*ps.keys())

# Test with negative coefficient
ps_neg = -cirq.Y(cirq.LineQubit(0)) * cirq.Y(cirq.LineQubit(1))
assert cirq.measure_single_paulistring(ps_neg, key='1').gate == cirq.PauliMeasurementGate(
cirq.DensePauliString('YY', coefficient=-1), key='1'
)

# Empty application
with pytest.raises(ValueError, match='should be an instance of cirq.PauliString'):
_ = cirq.measure_single_paulistring(cirq.I(q[0]) * cirq.I(q[1]))
Expand All @@ -103,9 +109,9 @@ def test_measure_single_paulistring():
with pytest.raises(ValueError, match='should be an instance of cirq.PauliString'):
_ = cirq.measure_single_paulistring(q)

# Coefficient != +1
# Coefficient != +1 or -1
with pytest.raises(ValueError, match='must have a coefficient'):
_ = cirq.measure_single_paulistring(-ps)
_ = cirq.measure_single_paulistring(-2 * ps)


def test_measure_paulistring_terms():
Expand Down

0 comments on commit 26af12e

Please sign in to comment.