Skip to content

Commit

Permalink
Created ControlValues for controlled gates/operations, fix for #4512
Browse files Browse the repository at this point in the history
created control_values.py which contains the ControlValues class.\nFreeVars and ConstrainedVars classes are provided for ease of use.\nwhile the basic idea of ControlValues integrating it inside the code base was challening\nthe old way of using control_values assumed it's a tuple of tuples of ints and was used as thus (comparasion, hashing, slicing, fomatting, conditioning, and loops), the ControlValues class had to provide these functionalities\nthe trickiest part to get right was the support for formatting!\nI'll create a follow up PR for unit tests for control_values.py
  • Loading branch information
NoureldinYosri committed Dec 1, 2021
1 parent 7259925 commit 194915a
Show file tree
Hide file tree
Showing 3 changed files with 282 additions and 44 deletions.
229 changes: 229 additions & 0 deletions cirq-core/cirq/ops/control_values.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,229 @@
# Copyright 2018 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.
from typing import Collection, Optional, Sequence, Union, Tuple, List, Type, cast, Any

import copy
import itertools

import cirq


def flatten(sequence):
def _flatten_aux(sequence):
if isinstance(sequence, int):
yield sequence
else:
for item in sequence:
yield from _flatten_aux(item)

return tuple(_flatten_aux(sequence))


class ControlValues:
def __init__(
self, control_values: Sequence[Union[int, Collection[int], Type['ControlValues']]]
):
if len(control_values) == 0:
self.nxt = None
self.vals = None
self.num_variables = 0
self.itr = None
return
self.itr = None
self.nxt = None
self.vals = control_values[0]
self.num_variables = 0

if len(control_values) > 1:
self.nxt = ControlValues(control_values[1:])


if isinstance(control_values[0], ControlValues):
aux = control_values[0].copy().And(self.nxt)
self.vals, self.num_variables, self.nxt = aux.vals, aux.num_variables, aux.nxt
self.vals = cast(Tuple[Tuple[int, ...], ...], self.vals)
return

if isinstance(self.vals, int):
val = cast(int, ControlValues[0])
self.vals = ((val,),)

self.vals = cast(Tuple[Any], self.vals)

if isinstance(self.vals[0], int):
self.vals = tuple((val,) if isinstance(val, int) else tuple(val) for val in self.vals)
self.vals = cast(Tuple[Tuple[int, ...], ...], self.vals)
self.num_variables = len(self.vals[0])

def And(self, other): # pylint: disable=invalid-name
# Cartesian product of all combinations in self x other
if other is None:
return
if not isinstance(other, ControlValues):
raise ValueError
other = other.copy()
cur = self
while cur.nxt:
cur = cur.nxt
cur.nxt = other

def __call__(self):
return self.__iter__()

def __iter__(self):
nxt = self.nxt if self.nxt else lambda: [()]
if self.num_variables:
self.itr = itertools.product(self.vals, nxt())
else:
self.itr = itertools.product(*())
return self.itr

def __next__(self):
for val in self.itr:
yield val

def copy(self):
new_copy = ControlValues(
[
copy.deepcopy(self.vals),
]
)
new_copy.nxt = None
if self.nxt:
new_copy.nxt = self.nxt.copy()
return new_copy

def __len__(self):
cur = self
num_variables = 0
while cur is not None:
num_variables += cur.num_variables
cur = cur.nxt
return num_variables

def __getitem__(self, key):
if isinstance(key, slice):
if key != slice(None, -1, None):
raise TypeError('Unsupported slicing')
return self.copy().pop()
key = int(key)
num_variables = len(self)
if not 0 <= key < num_variables:
key = key % num_variables
if key < 0:
key += num_variables
cur = self
while cur.num_variables <= key:
key -= cur.num_variables
cur = cur.nxt
return cur

def __eq__(self, other):
if other is None:
return False
if not isinstance(other, ControlValues):
return self == ControlValues(other)
self_values = set(flatten(A) for A in self)
other_values = set(flatten(B) for B in other)
return self_values == other_values

def identifier(self, companions: Sequence[Union[int, 'cirq.Qid']]):
companions = tuple(companions)
controls = []
cur = self
while cur is not None:
controls.append((cur.vals, companions[: cur.num_variables]))
companions = companions[cur.num_variables :]
cur = cur.nxt
return tuple(controls)

def check_dimentionality(
self,
qid_shape: Optional[Union[Tuple[int, ...], List[int]]] = None,
controls: Optional[Union[Tuple['cirq.Qid', ...], List['cirq.Qid']]] = None,
offset=0,
):
if self.num_variables == 0:
return
if qid_shape is None and controls is None:
raise ValueError('At least one of qid_shape or controls has to be not given.')
if qid_shape is None or len(qid_shape) == 0:
qid_shape = [q.dimension for q in controls[: self.num_variables]]
if self.vals is None:
raise ValueError('vals can\'t be None.')
if not isinstance(self.vals, tuple):
raise TypeError('self.vals has to be a tuple.')
for product in self.vals:
product = flatten(product)
for i in range(self.num_variables):
if not 0 <= product[i] < qid_shape[i]:
message = (
'Control values <{!r}> outside of range ' 'for control qubit number <{!r}>.'
).format(product[i], i + offset)
if controls is not None:
message = (
'Control values <{product[i]!r}> outside of range'
' for qubit <{controls[i]!r}>.'
)
raise ValueError(message)

if self.nxt is not None:
self.nxt.check_dimentionality(
qid_shape=qid_shape[self.num_variables :],
controls=controls[self.num_variables :] if controls else None,
offset=offset + self.num_variables,
)

def are_same_value(self, value: int = 1):
if self.vals is None:
raise ValueError('vals can\'t be None.')
if not isinstance(self.vals, tuple):
raise TypeError('self.vals has to be a tuple.')
for product in self.vals:
product = flatten(product)
if not all(v == value for v in product):
return False
if self.nxt is not None:
return self.nxt.are_same_value(value)
return True

def arrangements(self):
_arrangements = []
cur = self
while cur is not None:
if cur.num_variables == 1:
_arrangements.append(flatten(cur.vals))
else:
_arrangements.append(flatten(product) for product in cur.vals)
cur = cur.nxt
return _arrangements

def pop(self):
if self.nxt is None:
return None
cur = self
while cur.nxt.nxt is not None:
cur = cur.nxt
cur.nxt = None
return self


class FreeVars(ControlValues):
pass


class ConstrainedVars(ControlValues):
def __init__(self, control_values):
sum_of_product = (tuple(zip(*control_values)),)
super().__init__(sum_of_product)
46 changes: 24 additions & 22 deletions cirq-core/cirq/ops/controlled_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import AbstractSet, Any, cast, Collection, Dict, Optional, Sequence, Tuple, Union
from typing import AbstractSet, Any, Collection, Dict, Optional, Sequence, Tuple, Union

import numpy as np

import cirq
from cirq import protocols, value
from cirq.ops import raw_types, controlled_operation as cop
from cirq.ops import raw_types, controlled_operation as cop, control_values as cv
from cirq.type_workarounds import NotImplementedType


Expand All @@ -33,7 +33,9 @@ def __init__(
self,
sub_gate: 'cirq.Gate',
num_controls: int = None,
control_values: Optional[Sequence[Union[int, Collection[int]]]] = None,
control_values: Optional[
Union[cv.ControlValues, Sequence[Union[int, Collection[int]]]]
] = None,
control_qid_shape: Optional[Sequence[int]] = None,
) -> None:
"""Initializes the controlled gate. If no arguments are specified for
Expand Down Expand Up @@ -76,22 +78,22 @@ def __init__(
self.control_qid_shape = tuple(control_qid_shape)

# Convert to sorted tuples
self.control_values = cast(
Tuple[Tuple[int, ...], ...],
tuple((val,) if isinstance(val, int) else tuple(sorted(val)) for val in control_values),
)
# Verify control values not out of bounds
for i, (val, dimension) in enumerate(zip(self.control_values, self.control_qid_shape)):
if not all(0 <= v < dimension for v in val):
raise ValueError(
'Control values <{!r}> outside of range for control qubit '
'number <{!r}>.'.format(val, i)
if not isinstance(control_values, cv.ControlValues):
self.control_values = cv.ControlValues(
tuple(
(val,) if isinstance(val, int) else tuple(sorted(val)) for val in control_values
)
)
else:
self.control_values = control_values

# Verify control values not out of bounds
self.control_values.check_dimentionality(self.control_qid_shape)

# Flatten nested ControlledGates.
if isinstance(sub_gate, ControlledGate):
self.sub_gate = sub_gate.sub_gate # type: ignore
self.control_values += sub_gate.control_values
self.control_values.And(sub_gate.control_values)
self.control_qid_shape += sub_gate.control_qid_shape
else:
self.sub_gate = sub_gate
Expand Down Expand Up @@ -131,7 +133,7 @@ def _value_equality_values_(self):
return (
self.sub_gate,
self.num_controls(),
frozenset(zip(self.control_values, self.control_qid_shape)),
frozenset(self.control_values.identifier(self.control_qid_shape)),
)

def _apply_unitary_(self, args: 'protocols.ApplyUnitaryArgs') -> np.ndarray:
Expand Down Expand Up @@ -223,14 +225,14 @@ def get_symbol(vals):

return protocols.CircuitDiagramInfo(
wire_symbols=(
*(get_symbol(vals) for vals in self.control_values),
*(get_symbol(vals) for vals in self.control_values.arrangements()),
*sub_info.wire_symbols,
),
exponent=sub_info.exponent,
)

def __str__(self) -> str:
if set(self.control_values) == {(1,)}:
if self.control_values.are_same_value(1):

def get_prefix(control_vals):
return 'C'
Expand All @@ -241,26 +243,26 @@ def get_prefix(control_vals):
control_vals_str = ''.join(map(str, sorted(control_vals)))
return f'C{control_vals_str}'

return ''.join(map(get_prefix, self.control_values)) + str(self.sub_gate)
return ''.join(map(get_prefix, self.control_values.arrangements())) + str(self.sub_gate)

def __repr__(self) -> str:
if self.num_controls() == 1 and self.control_values == ((1,),):
if self.num_controls() == 1 and self.control_values.are_same_value(1):
return f'cirq.ControlledGate(sub_gate={self.sub_gate!r})'

if all(vals == (1,) for vals in self.control_values) and set(self.control_qid_shape) == {2}:
if self.control_values.are_same_value(1) and set(self.control_qid_shape) == {2}:
return (
f'cirq.ControlledGate(sub_gate={self.sub_gate!r}, '
f'num_controls={self.num_controls()!r})'
)
return (
f'cirq.ControlledGate(sub_gate={self.sub_gate!r}, '
f'control_values={self.control_values!r},'
f'control_values={self.control_values.arrangements()!r},'
f'control_qid_shape={self.control_qid_shape!r})'
)

def _json_dict_(self) -> Dict[str, Any]:
return {
'control_values': self.control_values,
'control_values': self.control_values.arrangements(),
'control_qid_shape': self.control_qid_shape,
'sub_gate': self.sub_gate,
}
Loading

0 comments on commit 194915a

Please sign in to comment.