Skip to content

Commit

Permalink
Add SerializableGateSet.is_supported (#3410)
Browse files Browse the repository at this point in the history
This method checks if a given object containing operations (a circuit, moment, or other arbitrary op tree) is supported by a gateset. Note that this does not address separating the notions of belonging to a gateset from serializability, but at it provides a way to check if a circuit is supported without actually serializing, which can be expensive.
  • Loading branch information
maffoo committed Oct 14, 2020
1 parent ca307cd commit f394892
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
17 changes: 10 additions & 7 deletions cirq/google/serializable_gate_set.py
Expand Up @@ -86,15 +86,18 @@ def with_added_gates(
def supported_gate_types(self) -> Tuple:
return tuple(self.serializers.keys())

def is_supported(self, op_tree: 'cirq.OP_TREE') -> bool:
"""Whether the given object contains only supported operations."""
return all(
self.is_supported_operation(op)
for op in ops.flatten_to_ops(op_tree))

def is_supported_operation(self, op: 'cirq.Operation') -> bool:
"""Whether or not the given gate can be serialized by this gate set."""
gate = op.gate
for gate_type_mro in type(gate).mro():
if gate_type_mro in self.serializers:
for serializer in self.serializers[gate_type_mro]:
if serializer.can_serialize_operation(op):
return True
return False
return any(
serializer.can_serialize_operation(op)
for gate_type in type(op.gate).mro()
for serializer in self.serializers.get(gate_type, []))

def serialize(self,
program: 'cirq.Circuit',
Expand Down
6 changes: 6 additions & 0 deletions cirq/google/serializable_gate_set_test.py
Expand Up @@ -83,6 +83,12 @@ def test_supported_gate_types():
assert MY_GATE_SET.supported_gate_types() == (cirq.XPowGate,)


def test_is_supported():
q0, q1 = cirq.GridQubit.rect(1, 2)
assert MY_GATE_SET.is_supported(cirq.Circuit(cirq.X(q0), cirq.X(q1)))
assert not MY_GATE_SET.is_supported(cirq.Circuit(cirq.X(q0), cirq.Z(q1)))


def test_is_supported_operation():
q = cirq.GridQubit(1, 1)
assert MY_GATE_SET.is_supported_operation(cirq.XPowGate()(q))
Expand Down

0 comments on commit f394892

Please sign in to comment.