Skip to content

Commit 9d7777e

Browse files
Created ControlValues for controlled gates/operations, fix for quantumlib#4512
created control_values.py which contains the ControlValues class. FreeVars and ConstrainedVars classes are provided for ease of use. while the basic idea of ControlValues integrating it inside the code base was challening the 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 the trickiest part to get right was the support for formatting!
1 parent fe7fa12 commit 9d7777e

File tree

2 files changed

+341
-0
lines changed

2 files changed

+341
-0
lines changed

cirq-core/cirq/ops/control_values.py

Lines changed: 224 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,224 @@
1+
# Copyright 2018 The Cirq Developers
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# https://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
from typing import Collection, Optional, Sequence, Union, Tuple, List, Type, cast
15+
16+
import copy
17+
import itertools
18+
19+
import cirq # pylint: disable=unused-import
20+
21+
22+
def flatten(sequence):
23+
def _flatten_aux(sequence):
24+
if isinstance(sequence, int):
25+
yield sequence
26+
else:
27+
for item in sequence:
28+
yield from _flatten_aux(item)
29+
30+
return tuple(_flatten_aux(sequence))
31+
32+
33+
def _from_int(val: int) -> Tuple[Tuple[int, ...], ...]:
34+
return ((val,),)
35+
36+
37+
def _from_sequence_int(vals: Sequence[int]) -> Tuple[Tuple[int, ...], ...]:
38+
return tuple((val,) for val in vals)
39+
40+
41+
def _from_sequence_sequence(vals: Sequence[Sequence[int]]) -> Tuple[Tuple[int, ...], ...]:
42+
return tuple(tuple(product) for product in vals)
43+
44+
45+
class ControlValues:
46+
def __init__(
47+
self, control_values: Sequence[Union[int, Collection[int], Type['ControlValues']]]
48+
):
49+
if len(control_values) == 0:
50+
self.vals = cast(Tuple[Tuple[int, ...], ...], (()))
51+
self.num_variables = 0
52+
self.nxt = None
53+
self.itr = None
54+
return
55+
self.itr = None
56+
self.nxt = None
57+
58+
if len(control_values) > 1:
59+
self.nxt = ControlValues(control_values[1:])
60+
61+
if isinstance(control_values[0], ControlValues):
62+
aux = control_values[0].copy()
63+
aux.And(self.nxt)
64+
self.vals, self.num_variables, self.nxt = aux.vals, aux.num_variables, aux.nxt
65+
self.vals = cast(Tuple[Tuple[int, ...], ...], self.vals)
66+
return
67+
68+
val = control_values[0]
69+
if isinstance(val, int):
70+
self.vals = _from_int(val)
71+
elif isinstance(val, (list, tuple)):
72+
if isinstance(val[0], int):
73+
self.vals = _from_sequence_int(val)
74+
else:
75+
self.vals = _from_sequence_sequence(val)
76+
self.num_variables = len(self.vals[0])
77+
78+
def And(self, other: ControlValues): # pylint: disable=invalid-name
79+
# Cartesian product of all combinations in self x other
80+
if other is None:
81+
return
82+
other = other.copy()
83+
cur = self
84+
while cur.nxt is not None:
85+
cur = cur.nxt
86+
cur.nxt = other
87+
88+
def __call__(self):
89+
return self.__iter__()
90+
91+
def __iter__(self):
92+
nxt = self.nxt if self.nxt else lambda: [()]
93+
if self.num_variables:
94+
self.itr = itertools.product(self.vals, nxt())
95+
else:
96+
self.itr = itertools.product(*(), nxt())
97+
return self.itr
98+
99+
def copy(self):
100+
if self.num_variables == 0:
101+
new_copy = ControlValues([])
102+
else:
103+
new_copy = ControlValues(
104+
[
105+
copy.deepcopy(self.vals),
106+
]
107+
)
108+
new_copy.nxt = None
109+
if self.nxt:
110+
new_copy.nxt = self.nxt.copy()
111+
return new_copy
112+
113+
def __len__(self):
114+
cur = self
115+
num_variables = 0
116+
while cur is not None:
117+
num_variables += cur.num_variables
118+
cur = cur.nxt
119+
return num_variables
120+
121+
def __getitem__(self, key):
122+
if isinstance(key, slice):
123+
if key != slice(None, -1, None):
124+
raise ValueError('Unsupported slicing')
125+
return self.copy().pop()
126+
key = int(key)
127+
num_variables = len(self)
128+
if not 0 <= key < num_variables:
129+
key = key % num_variables
130+
cur = self
131+
while cur.num_variables <= key:
132+
key -= cur.num_variables
133+
cur = cur.nxt
134+
return cur
135+
136+
def __eq__(self, other):
137+
if not isinstance(other, ControlValues):
138+
return self == ControlValues(other)
139+
self_values = set(flatten(A) for A in self)
140+
other_values = set(flatten(B) for B in other)
141+
return self_values == other_values
142+
143+
def identifier(self, companions: Sequence[Union[int, 'cirq.Qid']]):
144+
companions = tuple(companions)
145+
controls = []
146+
cur = cast(Optional[ControlValues], self)
147+
while cur is not None:
148+
controls.append((cur.vals, companions[: cur.num_variables]))
149+
companions = companions[cur.num_variables :]
150+
cur = cur.nxt
151+
return tuple(controls)
152+
153+
def check_dimentionality(
154+
self,
155+
qid_shape: Optional[Union[Tuple[int, ...], List[int]]] = None,
156+
controls: Optional[Union[Tuple['cirq.Qid', ...], List['cirq.Qid']]] = None,
157+
offset=0,
158+
):
159+
if self.num_variables == 0:
160+
return
161+
if qid_shape is None and controls is None:
162+
raise ValueError('At least one of qid_shape or controls has to be not given.')
163+
if controls is not None:
164+
controls = tuple(controls)
165+
if (qid_shape is None or len(qid_shape) == 0) and controls is not None:
166+
qid_shape = tuple(q.dimension for q in controls[: self.num_variables])
167+
qid_shape = cast(Tuple[int], qid_shape)
168+
for product in self.vals:
169+
product = flatten(product)
170+
for i in range(self.num_variables):
171+
if not 0 <= product[i] < qid_shape[i]:
172+
message = (
173+
'Control values <{!r}> outside of range ' 'for control qubit number <{!r}>.'
174+
).format(product[i], i + offset)
175+
if controls is not None:
176+
message = (
177+
'Control values <{product[i]!r}> outside of range'
178+
' for qubit <{controls[i]!r}>.'
179+
)
180+
raise ValueError(message)
181+
182+
if self.nxt is not None:
183+
self.nxt.check_dimentionality(
184+
qid_shape=qid_shape[self.num_variables :],
185+
controls=controls[self.num_variables :] if controls else None,
186+
offset=offset + self.num_variables,
187+
)
188+
189+
def are_same_value(self, value: int = 1):
190+
for product in self.vals:
191+
product = flatten(product)
192+
if not all(v == value for v in product):
193+
return False
194+
if self.nxt is not None:
195+
return self.nxt.are_same_value(value)
196+
return True
197+
198+
def arrangements(self):
199+
_arrangements = []
200+
cur = self
201+
while cur is not None:
202+
if cur.num_variables == 1:
203+
_arrangements.append(flatten(cur.vals))
204+
else:
205+
_arrangements.append(tuple(flatten(product) for product in cur.vals))
206+
cur = cur.nxt
207+
return _arrangements
208+
209+
def pop(self):
210+
if self.nxt is None:
211+
return None
212+
self.nxt = self.nxt.pop()
213+
return self
214+
215+
216+
class FreeVars(ControlValues):
217+
pass
218+
219+
220+
class ConstrainedVars(ControlValues):
221+
def __init__(self, control_values):
222+
sum_of_product = (tuple(zip(*control_values)),)
223+
print(sum_of_product)
224+
super().__init__(sum_of_product)
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
# Copyright 2018 The Cirq Developers
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# https://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import pytest
16+
17+
from cirq.ops import control_values as cv
18+
19+
20+
def test_init_control_values():
21+
tests = [
22+
([], [()]),
23+
([1], [(1,)]),
24+
([[0, 1], 1], [(0, 1), (1, 1)]),
25+
([[[0, 1], [1, 0]]], [(0, 1), (1, 0)]),
26+
]
27+
for control_values, want in tests:
28+
control_vals = cv.ControlValues(control_values)
29+
got = [cv.flatten(product) for product in control_vals]
30+
assert want == sorted(got)
31+
32+
33+
def test_copy_constructor():
34+
tests = [
35+
([], [()]),
36+
([1], [(1,)]),
37+
([[0, 1], 1], [(0, 1), (1, 1)]),
38+
([[[0, 1], [1, 0]]], [(0, 1), (1, 0)]),
39+
]
40+
for control_values, want in tests:
41+
control_vals = cv.ControlValues([cv.ControlValues(control_values)])
42+
got = [cv.flatten(product) for product in control_vals]
43+
assert want == sorted(got)
44+
45+
for control_values, want in tests:
46+
values = [cv.ControlValues([cv.ControlValues([val])]) for val in control_values]
47+
control_vals = cv.ControlValues(values)
48+
got = [cv.flatten(product) for product in control_vals]
49+
assert want == sorted(got)
50+
51+
52+
def test_constrained_init():
53+
tests = [
54+
([[0, 1], [1, 0]], [(0, 1), (1, 0)]),
55+
([[0, 0], [0, 1]], [(0, 0), (0, 1)]),
56+
([[1, 0], [1, 1]], [(0, 1), (1, 1)]),
57+
]
58+
for control_values, want in tests:
59+
control_vals = cv.ConstrainedVars(control_values)
60+
got = [cv.flatten(product) for product in control_vals]
61+
assert want == sorted(got)
62+
63+
64+
def test_and():
65+
originals = [
66+
([], [()]),
67+
([1], [(1,)]),
68+
([[0, 1], 1], [(0, 1), (1, 1)]),
69+
([[[0, 1], [1, 0]]], [(0, 1), (1, 0)]),
70+
]
71+
for control_values1, products1 in originals:
72+
for control_values2, products2 in originals:
73+
control_vals1 = cv.ControlValues(control_values1)
74+
control_vals2 = cv.ControlValues(control_values2)
75+
want = sorted([v1 + v2 for v1 in products1 for v2 in products2])
76+
control_vals1.And(control_vals2)
77+
got = sorted([cv.flatten(product) for product in control_vals1])
78+
assert want == got
79+
80+
81+
def test_slicing_not_supported():
82+
control_vals = cv.ControlValues([[[0, 1], [1, 0]]])
83+
with pytest.raises(ValueError):
84+
control_vals[0:1] # pylint: disable=pointless-statement
85+
86+
87+
def test_check_dimentionality():
88+
empty_control_vals = cv.ControlValues([])
89+
empty_control_vals.check_dimentionality()
90+
91+
control_values = cv.ControlValues([[0, 1], 1])
92+
with pytest.raises(ValueError):
93+
control_values.check_dimentionality()
94+
95+
96+
def test_pop():
97+
tests = [
98+
([[0, 1], 1], [(0,), (1,)]),
99+
([[[0, 1], [1, 0]], 0, 1], [(0, 1, 0), (1, 0, 0)]),
100+
]
101+
for control_values, want in tests:
102+
control_vals = cv.ControlValues(control_values)
103+
control_vals.pop()
104+
got = [cv.flatten(product) for product in control_vals]
105+
assert want == sorted(got)
106+
107+
108+
def test_arrangements():
109+
tests = [
110+
((), [()]),
111+
([1], [(1,)]),
112+
([(0, 1), (1,)], [(0, 1), (1,)]),
113+
([((0, 1), (1, 0))], [((0, 1), (1, 0))]),
114+
]
115+
for control_values, want in tests:
116+
control_vals = cv.ControlValues(control_values)
117+
assert want == control_vals.arrangements()

0 commit comments

Comments
 (0)