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 common gate families as part of adopting gatesets across Cirq. #4517

Merged
merged 5 commits into from
Sep 23, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
3 changes: 3 additions & 0 deletions cirq-core/cirq/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,8 @@
from cirq.ops import (
amplitude_damp,
AmplitudeDampingChannel,
AnyIntegerPowerGateFamily,
AnyUnitaryGateFamily,
ArithmeticOperation,
asymmetric_depolarize,
AsymmetricDepolarizingChannel,
Expand Down Expand Up @@ -245,6 +247,7 @@
OP_TREE,
Operation,
ParallelGate,
ParallelGateFamily,
parallel_gate_op,
ParallelGateOperation,
Pauli,
Expand Down
6 changes: 6 additions & 0 deletions cirq-core/cirq/ops/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,12 @@
ZPowGate,
)

from cirq.ops.common_gate_families import (
AnyUnitaryGateFamily,
AnyIntegerPowerGateFamily,
ParallelGateFamily,
)

from cirq.ops.controlled_gate import (
ControlledGate,
)
Expand Down
108 changes: 108 additions & 0 deletions cirq-core/cirq/ops/common_gate_families.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# 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.

"""Common Gate Families used in cirq-core"""

from typing import cast, Optional, Type, Union

from cirq.ops import gateset, raw_types, parallel_gate, eigen_gate
from cirq import protocols


class AnyUnitaryGateFamily(gateset.GateFamily):
tanujkhattar marked this conversation as resolved.
Show resolved Hide resolved
def __init__(self, num_qubits: Optional[int] = None) -> None:
self._num_qubits = num_qubits
if num_qubits:
name = f'{num_qubits}-Qubit UnitaryGateFamily'
description = f'Accepts any {num_qubits}-qubit unitary gate.'
else:
name = 'Any-Qubit UnitaryGateFamily'
description = 'Accepts any unitary gate.'
tanujkhattar marked this conversation as resolved.
Show resolved Hide resolved
super().__init__(raw_types.Gate, name=name, description=description)

def _predicate(self, g: raw_types.Gate) -> bool:
return (
self._num_qubits is None or protocols.num_qubits(g) == self._num_qubits
) and protocols.has_unitary(g)

def __repr__(self) -> str:
return f'cirq.AnyUnitaryGateFamily(num_qubits = {self._num_qubits})'


class AnyIntegerPowerGateFamily(gateset.GateFamily):
tanujkhattar marked this conversation as resolved.
Show resolved Hide resolved
def __init__(self, gate: Type[eigen_gate.EigenGate]) -> None:
if not (isinstance(gate, type) and issubclass(gate, eigen_gate.EigenGate)):
raise ValueError(f'{gate} must be a subclass of `cirq.EigenGate`.')
super().__init__(
gate,
name=f'AnyIntegerPowerGateFamily: {gate}',
description=f'Accepts any instance `g` of `{gate}` s.t. `g.exponent` is an integer.',
)
tanujkhattar marked this conversation as resolved.
Show resolved Hide resolved

def _predicate(self, g: raw_types.Gate) -> bool:
if protocols.is_parameterized(g) or not super()._predicate(g):
return False
exp = cast(eigen_gate.EigenGate, g).exponent # for mypy
return int(exp) == exp

def __repr__(self) -> str:
return f'cirq.AnyIntegerPowerGateFamily({self._gate_str()})'


class ParallelGateFamily(gateset.GateFamily):
tanujkhattar marked this conversation as resolved.
Show resolved Hide resolved
def __init__(
self,
gate: Union[Type[raw_types.Gate], raw_types.Gate],
*,
name: Optional[str] = None,
description: Optional[str] = None,
max_parallel_allowed=None,
) -> None:
if isinstance(gate, parallel_gate.ParallelGate):
gate = cast(parallel_gate.ParallelGate, gate).sub_gate
self._max_parallel_allowed = max_parallel_allowed
super().__init__(gate, name=name, description=description)

def _max_parallel_str(self):
return self._max_parallel_allowed if self._max_parallel_allowed is not None else 'INF'

def _default_name(self) -> str:
return f'{self._max_parallel_str()} Parallel ' + super()._default_name()

def _default_description(self) -> str:
check_type = r'g == {}' if isinstance(self.gate, raw_types.Gate) else r'isinstance(g, {})'
return (
f'Accepts\n'
f'1. `cirq.Gate` instances `g` s.t. `{check_type.format(self._gate_str())}` OR\n'
f'2. `cirq.ParallelGate` instance `g` s.t. `g.sub_gate` satisfies 1. and '
f'`cirq.num_qubits(g) <= {self._max_parallel_str()}` OR\n'
f'3. `cirq.Operation` instance `op` s.t. `op.gate` satisfies 1. or 2.'
)

def _predicate(self, gate: raw_types.Gate) -> bool:
if (
self._max_parallel_allowed is not None
and protocols.num_qubits(gate) > self._max_parallel_allowed
):
return False
gate = gate.sub_gate if isinstance(gate, parallel_gate.ParallelGate) else gate
return super()._predicate(gate)

def __repr__(self) -> str:
return (
f'cirq.ParallelGateFamily(gate={self._gate_str(repr)},'
f'name="{self.name}", '
f'description=r\'\'\'' + self.description + '\'\'\','
f'max_parallel_allowed="{self._max_parallel_allowed}")'
)
64 changes: 64 additions & 0 deletions cirq-core/cirq/ops/common_gate_families_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# 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.

import pytest
import sympy
import cirq


def test_any_unitary_gate_family():
for gate in [cirq.X, cirq.MatrixGate(cirq.testing.random_unitary(8)), cirq.CNOT ** 0.2]:
q = cirq.LineQubit.range(cirq.num_qubits(gate))
for num_qubits in [None, cirq.num_qubits(gate)]:
gate_family = cirq.AnyUnitaryGateFamily(num_qubits)
cirq.testing.assert_equivalent_repr(gate_family)
assert gate in gate_family
assert gate(*q) in gate_family
if num_qubits:
assert f'{num_qubits}' in gate_family.name
assert f'{num_qubits}' in gate_family.description
else:
assert f'Any-Qubit' in gate_family.name
assert f'any unitary' in gate_family.description

tanujkhattar marked this conversation as resolved.
Show resolved Hide resolved
assert cirq.MeasurementGate(num_qubits=2) not in cirq.AnyUnitaryGateFamily()


def test_any_integer_power_gate_family():
with pytest.raises(ValueError, match='subclass of `cirq.EigenGate`'):
cirq.AnyIntegerPowerGateFamily(gate=cirq.FSimGate)
gate_family = cirq.AnyIntegerPowerGateFamily(cirq.CXPowGate)
cirq.testing.assert_equivalent_repr(gate_family)
assert cirq.CX in gate_family
assert cirq.CX ** 2 in gate_family
assert cirq.CX ** 1.5 not in gate_family
assert cirq.CX ** sympy.Symbol('theta') not in gate_family
assert 'CXPowGate' in gate_family.name
assert '`g.exponent` is an integer' in gate_family.description
tanujkhattar marked this conversation as resolved.
Show resolved Hide resolved


@pytest.mark.parametrize('gate', [cirq.X, cirq.ParallelGate(cirq.X, 2), cirq.XPowGate])
@pytest.mark.parametrize('name,description', [(None, None), ("Custom Name", "Custom Description")])
def test_parallel_gate_family(gate, name, description):
gate_family = cirq.ParallelGateFamily(
gate, name=name, description=description, max_parallel_allowed=3
)
cirq.testing.assert_equivalent_repr(gate_family)
for gate_to_test in [cirq.X, cirq.ParallelGate(cirq.X, 2)]:
assert gate_to_test in gate_family
assert gate_to_test(*cirq.LineQubit.range(cirq.num_qubits(gate_to_test))) in gate_family
assert cirq.ParallelGate(cirq.X, 4) not in gate_family
str_to_search = 'Custom' if name else 'Parallel'
assert str_to_search in gate_family.name
assert str_to_search in gate_family.description
3 changes: 3 additions & 0 deletions cirq-core/cirq/protocols/json_test_data/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
resolver_cache=_class_resolver_dictionary(),
not_yet_serializable=[
'Alignment',
'AnyIntegerPowerGateFamily',
'AnyUnitaryGateFamily',
'AxisAngleDecomposition',
'CircuitDag',
'CircuitDiagramInfo',
Expand All @@ -48,6 +50,7 @@
'ListSweep',
'DiagonalGate',
'NeutralAtomDevice',
'ParallelGateFamily',
'PauliInteractionGate',
'PauliStringPhasor',
'PauliSum',
Expand Down