forked from quantumlib/Cirq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathact_on_args.py
358 lines (301 loc) · 12.6 KB
/
act_on_args.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# 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.
"""Objects and methods for acting efficiently on a state tensor."""
import copy
from typing import (
Any,
cast,
Dict,
Iterator,
List,
Mapping,
Optional,
Sequence,
TypeVar,
TYPE_CHECKING,
Tuple,
)
import numpy as np
from cirq import protocols, value
from cirq._compat import deprecated
from cirq.protocols.decompose_protocol import _try_decompose_into_operations_and_qubits
from cirq.sim.operation_target import OperationTarget
TSelf = TypeVar('TSelf', bound='ActOnArgs')
if TYPE_CHECKING:
import cirq
class ActOnArgs(OperationTarget[TSelf]):
"""State and context for an operation acting on a state tensor."""
def __init__(
self,
prng: Optional[np.random.RandomState] = None,
qubits: Optional[Sequence['cirq.Qid']] = None,
log_of_measurement_results: Optional[Dict[str, List[int]]] = None,
classical_data: Optional['cirq.ClassicalDataStore'] = None,
state: Optional['cirq.QuantumStateRepresentation'] = None,
):
"""Inits ActOnArgs.
Args:
prng: The pseudo random number generator to use for probabilistic
effects.
qubits: Determines the canonical ordering of the qubits. This
is often used in specifying the initial state, i.e. the
ordering of the computational basis states.
log_of_measurement_results: A mutable object that measurements are
being recorded into.
classical_data: The shared classical data container for this
simulation.
state: The underlying quantum state of the simulation.
"""
if prng is None:
prng = cast(np.random.RandomState, np.random)
if qubits is None:
qubits = ()
self._set_qubits(qubits)
self._prng = prng
self._classical_data = classical_data or value.ClassicalDataDictionaryStore(
_records={
value.MeasurementKey.parse_serialized(k): [tuple(v)]
for k, v in (log_of_measurement_results or {}).items()
}
)
self._state = state
@property
def prng(self) -> np.random.RandomState:
return self._prng
@property
def qubit_map(self) -> Mapping['cirq.Qid', int]:
return self._qubit_map
def _set_qubits(self, qubits: Sequence['cirq.Qid']):
self._qubits = tuple(qubits)
self._qubit_map = {q: i for i, q in enumerate(self.qubits)}
def measure(self, qubits: Sequence['cirq.Qid'], key: str, invert_mask: Sequence[bool]):
"""Measures the qubits and records to `log_of_measurement_results`.
Any bitmasks will be applied to the measurement record.
Args:
qubits: The qubits to measure.
key: The key the measurement result should be logged under. Note
that operations should only store results under keys they have
declared in a `_measurement_key_names_` method.
invert_mask: The invert mask for the measurement.
Raises:
ValueError: If a measurement key has already been logged to a key.
"""
bits = self._perform_measurement(qubits)
corrected = [bit ^ (bit < 2 and mask) for bit, mask in zip(bits, invert_mask)]
self._classical_data.record_measurement(
value.MeasurementKey.parse_serialized(key), corrected, qubits
)
def get_axes(self, qubits: Sequence['cirq.Qid']) -> List[int]:
return [self.qubit_map[q] for q in qubits]
def _perform_measurement(self, qubits: Sequence['cirq.Qid']) -> List[int]:
"""Delegates the call to measure the density matrix."""
if self._state is not None:
return self._state.measure(self.get_axes(qubits), self.prng)
raise NotImplementedError()
def sample(
self,
qubits: Sequence['cirq.Qid'],
repetitions: int = 1,
seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None,
) -> np.ndarray:
if self._state is not None:
return self._state.sample(self.get_axes(qubits), repetitions, seed)
raise NotImplementedError()
def copy(self: TSelf, deep_copy_buffers: bool = True) -> TSelf:
"""Creates a copy of the object.
Args:
deep_copy_buffers: If True, buffers will also be deep-copied.
Otherwise the copy will share a reference to the original object's
buffers.
Returns:
A copied instance.
"""
args = copy.copy(self)
args._classical_data = self._classical_data.copy()
if self._state is not None:
args._state = self._state.copy(deep_copy_buffers=deep_copy_buffers)
else:
self._on_copy(args, deep_copy_buffers)
return args
def _on_copy(self: TSelf, args: TSelf, deep_copy_buffers: bool = True):
"""Subclasses should implement this with any additional state copy
functionality."""
def create_merged_state(self: TSelf) -> TSelf:
"""Creates a final merged state."""
return self
def kronecker_product(self: TSelf, other: TSelf, *, inplace=False) -> TSelf:
"""Joins two state spaces together."""
args = self if inplace else copy.copy(self)
if self._state is not None and other._state is not None:
args._state = self._state.kron(other._state)
else:
self._on_kronecker_product(other, args)
args._set_qubits(self.qubits + other.qubits)
return args
def _on_kronecker_product(self: TSelf, other: TSelf, target: TSelf):
"""Subclasses should implement this with any additional state product
functionality, if supported."""
def with_qubits(self: TSelf, qubits) -> TSelf:
"""Extend current state space with added qubits.
The state of the added qubits is the default value set in the
subclasses. A new state space is created as the Kronecker product of
the original one and the added one.
Args:
qubits: The qubits to be added to the state space.
Regurns:
A new subclass object containing the extended state space.
"""
new_space = type(self)(qubits=qubits)
return self.kronecker_product(new_space)
def factor(
self: TSelf,
qubits: Sequence['cirq.Qid'],
*,
validate=True,
atol=1e-07,
inplace=False,
) -> Tuple[TSelf, TSelf]:
"""Splits two state spaces after a measurement or reset."""
extracted = copy.copy(self)
remainder = self if inplace else copy.copy(self)
if self._state is not None:
e, r = self._state.factor(self.get_axes(qubits), validate=validate, atol=atol)
extracted._state = e
remainder._state = r
else:
self._on_factor(qubits, extracted, remainder, validate, atol)
extracted._set_qubits(qubits)
remainder._set_qubits([q for q in self.qubits if q not in qubits])
return extracted, remainder
@property
def allows_factoring(self):
"""Subclasses that allow factorization should override this."""
return self._state.supports_factor if self._state is not None else False
def _on_factor(
self: TSelf,
qubits: Sequence['cirq.Qid'],
extracted: TSelf,
remainder: TSelf,
validate=True,
atol=1e-07,
):
"""Subclasses should implement this with any additional state factor
functionality, if supported."""
def transpose_to_qubit_order(
self: TSelf, qubits: Sequence['cirq.Qid'], *, inplace=False
) -> TSelf:
"""Physically reindexes the state by the new basis.
Args:
qubits: The desired qubit order.
inplace: True to perform this operation inplace.
Returns:
The state with qubit order transposed and underlying representation
updated.
Raises:
ValueError: If the provided qubits do not match the existing ones.
"""
if len(self.qubits) != len(qubits) or set(qubits) != set(self.qubits):
raise ValueError(f'Qubits do not match. Existing: {self.qubits}, provided: {qubits}')
args = self if inplace else copy.copy(self)
if self._state is not None:
args._state = self._state.reindex(self.get_axes(qubits))
else:
self._on_transpose_to_qubit_order(qubits, args)
args._set_qubits(qubits)
return args
def _on_transpose_to_qubit_order(self: TSelf, qubits: Sequence['cirq.Qid'], target: TSelf):
"""Subclasses should implement this with any additional state transpose
functionality, if supported."""
@property
def classical_data(self) -> 'cirq.ClassicalDataStoreReader':
return self._classical_data
@property # type: ignore
@deprecated(deadline='v0.16', fix='Remove this call, it always returns False.')
def ignore_measurement_results(self) -> bool:
return False
@property
def qubits(self) -> Tuple['cirq.Qid', ...]:
return self._qubits
def swap(self, q1: 'cirq.Qid', q2: 'cirq.Qid', *, inplace=False):
"""Swaps two qubits.
This only affects the index, and does not modify the underlying
state.
Args:
q1: The first qubit to swap.
q2: The second qubit to swap.
inplace: True to swap the qubits in the current object, False to
create a copy with the qubits swapped.
Returns:
The original object with the qubits swapped if inplace is
requested, or a copy of the original object with the qubits swapped
otherwise.
Raises:
ValueError: If the qubits are of different dimensionality.
"""
if q1.dimension != q2.dimension:
raise ValueError(f'Cannot swap different dimensions: q1={q1}, q2={q2}')
args = self if inplace else copy.copy(self)
i1 = self.qubits.index(q1)
i2 = self.qubits.index(q2)
qubits = list(args.qubits)
qubits[i1], qubits[i2] = qubits[i2], qubits[i1]
args._set_qubits(qubits)
return args
def rename(self, q1: 'cirq.Qid', q2: 'cirq.Qid', *, inplace=False):
"""Renames `q1` to `q2`.
Args:
q1: The qubit to rename.
q2: The new name.
inplace: True to rename the qubit in the current object, False to
create a copy with the qubit renamed.
Returns:
The original object with the qubits renamed if inplace is
requested, or a copy of the original object with the qubits renamed
otherwise.
Raises:
ValueError: If the qubits are of different dimensionality.
"""
if q1.dimension != q2.dimension:
raise ValueError(f'Cannot rename to different dimensions: q1={q1}, q2={q2}')
args = self if inplace else copy.copy(self)
i1 = self.qubits.index(q1)
qubits = list(args.qubits)
qubits[i1] = q2
args._set_qubits(qubits)
return args
def __getitem__(self: TSelf, item: Optional['cirq.Qid']) -> TSelf:
if item not in self.qubit_map:
raise IndexError(f'{item} not in {self.qubits}')
return self
def __len__(self) -> int:
return len(self.qubits)
def __iter__(self) -> Iterator[Optional['cirq.Qid']]:
return iter(self.qubits)
@property
def can_represent_mixed_states(self) -> bool:
return self._state.can_represent_mixed_states if self._state is not None else False
def strat_act_on_from_apply_decompose(
val: Any,
args: 'cirq.ActOnArgs',
qubits: Sequence['cirq.Qid'],
) -> bool:
operations, qubits1, _ = _try_decompose_into_operations_and_qubits(val)
assert len(qubits1) == len(qubits)
qubit_map = {q: qubits[i] for i, q in enumerate(qubits1)}
if operations is None:
return NotImplemented
for operation in operations:
operation = operation.with_qubits(*[qubit_map[q] for q in operation.qubits])
protocols.act_on(operation, args)
return True