-
Notifications
You must be signed in to change notification settings - Fork 1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Created ControlValues for controlled gates/operations, fix for #4512
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
1 parent
7259925
commit 194915a
Showing
3 changed files
with
282 additions
and
44 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.