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

Allow measure_single_paulistring to have negative coefficient #6143

Merged
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 8 additions & 4 deletions cirq-core/cirq/ops/measure_util.py
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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') == cirq.PauliMeasurementGate(
ps_neg.dense(ps_neg.keys()), key='1'
).on(*ps_neg.keys())
skushnir123 marked this conversation as resolved.
Show resolved Hide resolved

# 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