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 control_keys protocol #4490

Closed
wants to merge 19 commits into from
2 changes: 2 additions & 0 deletions cirq-core/cirq/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,7 @@
CircuitDiagramInfo,
CircuitDiagramInfoArgs,
commutes,
control_key_names,
decompose,
decompose_once,
decompose_once_with_qubits,
Expand Down Expand Up @@ -548,6 +549,7 @@
SupportsChannel,
SupportsCircuitDiagramInfo,
SupportsCommutes,
SupportsControlKey,
SupportsDecompose,
SupportsDecomposeWithQubits,
SupportsEqualUpToGlobalPhase,
Expand Down
10 changes: 6 additions & 4 deletions cirq-core/cirq/circuits/circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -1862,9 +1862,14 @@ def transform_qubits(
def _prev_moment_available(self, op: 'cirq.Operation', end_moment_index: int) -> Optional[int]:
last_available = end_moment_index
k = end_moment_index
op_control_keys = protocols.control_key_names(op)
op_qubits = op.qubits
while k > 0:
k -= 1
if not self._can_commute_past(k, op):
moment = self._moments[k]
if moment.operates_on(op_qubits) or bool(
set(op_control_keys) & protocols.measurement_key_names(moment)
):
return last_available
if self._can_add_op_at(k, op):
last_available = k
Expand Down Expand Up @@ -1918,9 +1923,6 @@ def _can_add_op_at(self, moment_index: int, operation: 'cirq.Operation') -> bool
return True
return self._device.can_add_operation_into_moment(operation, self._moments[moment_index])

def _can_commute_past(self, moment_index: int, operation: 'cirq.Operation') -> bool:
return not self._moments[moment_index].operates_on(operation.qubits)

def insert(
self,
index: int,
Expand Down
29 changes: 29 additions & 0 deletions cirq-core/cirq/circuits/circuit_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,35 @@ def test_append_single():
assert c == cirq.Circuit([cirq.Moment([cirq.X(a)])])


def test_append_control_key():
q = cirq.LineQubit(0)

class ControlOp(cirq.Operation):
def __init__(self, keys):
self._keys = keys

def with_qubits(self, *new_qids):
pass # coverage: ignore

@property
def qubits(self):
return [] # coverage: ignore

def _control_key_names_(self):
return self._keys

c = cirq.Circuit()
c.append(cirq.measure(q, key='a'))
c.append(ControlOp(['a']))
assert len(c) == 2

c = cirq.Circuit()
c.append(cirq.measure(q, key='a'))
c.append(ControlOp(['b']))
c.append(ControlOp(['b']))
assert len(c) == 1


def test_append_multiple():
a = cirq.NamedQubit('a')
b = cirq.NamedQubit('b')
Expand Down
4 changes: 4 additions & 0 deletions cirq-core/cirq/protocols/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@
definitely_commutes,
SupportsCommutes,
)
from cirq.protocols.control_key_protocol import (
control_key_names,
SupportsControlKey,
)
from cirq.protocols.circuit_diagram_info_protocol import (
circuit_diagram_info,
CircuitDiagramInfo,
Expand Down
58 changes: 58 additions & 0 deletions cirq-core/cirq/protocols/control_key_protocol.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Copyright 2021 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Protocol for object that have control keys."""

from typing import AbstractSet, Any, Iterable

from typing_extensions import Protocol

from cirq._doc import doc_private
from cirq.protocols.decompose_protocol import _try_decompose_into_operations_and_qubits


class SupportsControlKey(Protocol):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clean up docstrings in this file - it looks like there was a copy & replace from measurement keys, but the meaning doesn't line up.

"""An object that is a control and has a control key or keys.

Control keys are used in referencing the results of a measurement.

Users are free to implement either `_control_key_names_` returning an
iterable of strings.
"""

@doc_private
def _control_key_names_(self) -> Iterable[str]:
"""Return the keys for controls performed by the receiving object.

When a control occurs, either on hardware, or in a simulation,
these are the key values under which the results of the controls
will be stored.
"""


def control_key_names(val: Any) -> AbstractSet[str]:
"""Gets the control keys of controls within the given value.

Args:
val: The value which has the control key.

Returns:
The control keys of the value. If the value has no control,
the result is the empty tuple.
"""
getter = getattr(val, '_control_key_names_', None)
result = NotImplemented if getter is None else getter()
if result is not NotImplemented and result is not None:
return set(result)

return set()
1 change: 1 addition & 0 deletions cirq-core/cirq/protocols/json_test_data/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@
'SupportsCircuitDiagramInfo',
'SupportsCommutes',
'SupportsConsistentApplyUnitary',
'SupportsControlKey',
'SupportsDecompose',
'SupportsDecomposeWithQubits',
'SupportsEqualUpToGlobalPhase',
Expand Down