-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathz_basis.py
More file actions
531 lines (387 loc) · 15.1 KB
/
z_basis.py
File metadata and controls
531 lines (387 loc) · 15.1 KB
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
# Copyright 2023 Google LLC
#
# 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 functools import cached_property
from typing import cast, Dict, Iterable, List, Optional, Sequence, Tuple, TYPE_CHECKING, Union
import attrs
import numpy as np
import sympy
from attrs import frozen
from numpy.typing import NDArray
from qualtran import (
AddControlledT,
Bloq,
bloq_example,
BloqBuilder,
BloqDocSpec,
CompositeBloq,
ConnectionT,
CtrlSpec,
DecomposeTypeError,
QAny,
QBit,
QDType,
Register,
Side,
Signature,
Soquet,
SoquetT,
)
from qualtran.bloqs.bookkeeping import ArbitraryClifford
from qualtran.drawing import Circle, directional_text_box, Text, TextBox, WireSymbol
from qualtran.symbolics import SymbolicInt
if TYPE_CHECKING:
import cirq
import pyzx as zx
import quimb.tensor as qtn
from qualtran.cirq_interop import CirqQuregT
from qualtran.pyzx_interop import ZXAncillaManager
from qualtran.resource_counting import BloqCountDictT, SympySymbolAllocator
_ZERO = np.array([1, 0], dtype=np.complex128)
_ONE = np.array([0, 1], dtype=np.complex128)
_PAULIZ = np.array([[1, 0], [0, -1]], dtype=np.complex128)
@frozen
class _ZVector(Bloq):
"""The |0> or |1> state or effect.
Please use the explicitly named subclasses instead of the boolean arguments.
Args:
bit: False chooses |0>, True chooses |1>
state: True means this is a state with right registers; False means this is an
effect with left registers.
n: bitsize of the vector.
"""
bit: bool
state: bool = True
n: int = 1
def __attrs_post_init__(self):
if self.n != 1:
raise NotImplementedError("Come back later.")
@cached_property
def signature(self) -> 'Signature':
return Signature([Register('q', QBit(), side=Side.RIGHT if self.state else Side.LEFT)])
def decompose_bloq(self) -> CompositeBloq:
raise DecomposeTypeError(f"{self} is atomic")
def my_tensors(
self, incoming: Dict[str, 'ConnectionT'], outgoing: Dict[str, 'ConnectionT']
) -> List['qtn.Tensor']:
import quimb.tensor as qtn
side = outgoing if self.state else incoming
return [
qtn.Tensor(data=_ONE if self.bit else _ZERO, inds=[(side['q'], 0)], tags=[str(self)])
]
def on_classical_vals(self, *, q: Optional[int] = None) -> Dict[str, int]:
"""Return or consume 1 or 0 depending on `self.state` and `self.bit`.
If `self.state`, we return a bit in the `q` register. Otherwise,
we assert that the inputted `q` register is the correct bit.
"""
bit_int = 1 if self.bit else 0 # guard against bad `self.bit` types.
if self.state:
assert q is None
return {'q': bit_int}
assert q == bit_int, q
return {}
def as_cirq_op(
self, qubit_manager: 'cirq.QubitManager', **cirq_quregs: 'CirqQuregT' # type: ignore[type-var]
) -> Tuple[Union['cirq.Operation', None], Dict[str, 'CirqQuregT']]: # type: ignore[type-var]
if not self.state:
raise ValueError(f"There is no Cirq equivalent for {self}")
import cirq
(q,) = qubit_manager.qalloc(self.n)
if self.bit:
op = cirq.X(q)
else:
op = None
return op, {'q': np.array([q])}
def __str__(self) -> str:
s = '1' if self.bit else '0'
return f'|{s}>' if self.state else f'<{s}|'
def wire_symbol(
self, reg: Optional['Register'], idx: Tuple[int, ...] = tuple()
) -> 'WireSymbol':
if reg is None:
return Text('')
s = '1' if self.bit else '0'
return directional_text_box(s, side=reg.side)
def as_zx_gates(
self, ancilla_manager: 'ZXAncillaManager', /, **qubits: NDArray[np.integer]
) -> tuple[list['zx.circuit.Gate'], dict[str, NDArray[np.integer]]]:
import pyzx as zx
if self.state:
qubit = ancilla_manager.allocate()
gates = [zx.circuit.gates.InitAncilla(qubit), zx.circuit.gates.HAD(qubit)]
if self.bit:
gates = gates + [zx.circuit.gates.NOT(qubit)]
return gates, {'q': np.array([qubit])}
else:
(qubit,) = qubits.pop('q')
gates = [zx.circuit.gates.HAD(qubit), zx.circuit.gates.PostSelect(qubit)]
if self.bit:
gates = [zx.circuit.gates.NOT(qubit)] + gates
return gates, {}
def _hide_base_fields(cls, fields):
# for use in attrs `field_transformer`.
return [
field.evolve(repr=False) if field.name in ['bit', 'state'] else field for field in fields
]
@frozen(init=False, field_transformer=_hide_base_fields)
class ZeroState(_ZVector):
"""The state |0>"""
def __init__(self, n: int = 1):
self.__attrs_init__(bit=False, state=True, n=n)
def adjoint(self) -> 'Bloq':
return ZeroEffect()
@bloq_example
def _zero_state() -> ZeroState:
zero_state = ZeroState()
return zero_state
_ZERO_STATE_DOC = BloqDocSpec(bloq_cls=ZeroState, examples=[_zero_state])
@frozen(init=False, field_transformer=_hide_base_fields)
class ZeroEffect(_ZVector):
"""The effect <0|"""
def __init__(self, n: int = 1):
self.__attrs_init__(bit=False, state=False, n=n)
def adjoint(self) -> 'Bloq':
return ZeroState()
@bloq_example
def _zero_effect() -> ZeroEffect:
zero_effect = ZeroEffect()
return zero_effect
_ZERO_EFFECT_DOC = BloqDocSpec(bloq_cls=ZeroEffect, examples=[_zero_effect])
@frozen(init=False, field_transformer=_hide_base_fields)
class OneState(_ZVector):
"""The state |1>"""
def __init__(self, n: int = 1):
self.__attrs_init__(bit=True, state=True, n=n)
def adjoint(self) -> 'Bloq':
return OneEffect()
@bloq_example
def _one_state() -> OneState:
one_state = OneState()
return one_state
_ONE_STATE_DOC = BloqDocSpec(bloq_cls=OneState, examples=[_one_state])
@frozen(init=False, field_transformer=_hide_base_fields)
class OneEffect(_ZVector):
"""The effect <1|"""
def __init__(self, n: int = 1):
self.__attrs_init__(bit=True, state=False, n=n)
def adjoint(self) -> 'Bloq':
return OneState()
@bloq_example
def _one_effect() -> OneEffect:
one_effect = OneEffect()
return one_effect
_ONE_EFFECT_DOC = BloqDocSpec(bloq_cls=OneEffect, examples=[_one_effect])
@frozen
class ZGate(Bloq):
"""The Z gate.
This causes a phase flip: Z|+> = |-> and vice-versa.
"""
@cached_property
def signature(self) -> 'Signature':
return Signature.build(q=1)
def adjoint(self) -> 'Bloq':
return self
def decompose_bloq(self) -> 'CompositeBloq':
raise DecomposeTypeError(f"{self} is atomic")
def my_tensors(
self, incoming: Dict[str, 'ConnectionT'], outgoing: Dict[str, 'ConnectionT']
) -> List['qtn.Tensor']:
import quimb.tensor as qtn
return [
qtn.Tensor(
data=_PAULIZ, inds=[(outgoing['q'], 0), (incoming['q'], 0)], tags=[str(self)]
)
]
def get_ctrl_system(self, ctrl_spec: 'CtrlSpec') -> Tuple['Bloq', 'AddControlledT']:
if ctrl_spec != CtrlSpec():
# Delegate to the general superclass behavior
return super().get_ctrl_system(ctrl_spec=ctrl_spec)
bloq = CZ()
def add_controlled(
bb: 'BloqBuilder', ctrl_soqs: Sequence['SoquetT'], in_soqs: Dict[str, 'SoquetT']
) -> Tuple[Iterable['SoquetT'], Iterable['SoquetT']]:
(ctrl_soq,) = ctrl_soqs
ctrl_soq, q2 = bb.add(bloq, q1=ctrl_soq, q2=in_soqs['q'])
return (ctrl_soq,), (q2,)
return bloq, add_controlled
def as_cirq_op(
self, qubit_manager: 'cirq.QubitManager', q: 'CirqQuregT'
) -> Tuple['cirq.Operation', Dict[str, 'CirqQuregT']]:
import cirq
(q,) = q
return cirq.Z(q), {'q': np.asarray([q])}
def wire_symbol(
self, reg: Optional['Register'], idx: Tuple[int, ...] = tuple()
) -> 'WireSymbol':
if reg is None:
return Text('')
return TextBox('Z')
def as_zx_gates(
self, ancilla_manager, /, q: NDArray[np.integer]
) -> tuple[list['zx.circuit.Gate'], dict[str, NDArray[np.integer]]]:
import pyzx as zx
(qubit,) = q
return [zx.circuit.Z(qubit)], {'q': q}
@bloq_example
def _zgate() -> ZGate:
zgate = ZGate()
return zgate
_Z_GATE_DOC = BloqDocSpec(bloq_cls=ZGate, examples=[_zgate], call_graph_example=None)
@frozen
class CZ(Bloq):
"""Two-qubit controlled-Z gate.
Registers:
ctrl: One-bit control register.
target: One-bit target register.
"""
@cached_property
def signature(self) -> 'Signature':
return Signature.build(q1=1, q2=1)
def decompose_bloq(self) -> 'CompositeBloq':
raise DecomposeTypeError(f"{self} is atomic")
def adjoint(self) -> 'Bloq':
return self
def my_tensors(
self, incoming: Dict[str, 'ConnectionT'], outgoing: Dict[str, 'ConnectionT']
) -> List['qtn.Tensor']:
import quimb.tensor as qtn
unitary = np.diag(np.array([1, 1, 1, -1], dtype=np.complex128)).reshape((2, 2, 2, 2))
inds = [(outgoing['q1'], 0), (outgoing['q2'], 0), (incoming['q1'], 0), (incoming['q2'], 0)]
return [qtn.Tensor(data=unitary, inds=inds, tags=[str(self)])]
def as_cirq_op(
self, qubit_manager: 'cirq.QubitManager', q1: 'CirqQuregT', q2: 'CirqQuregT'
) -> Tuple['cirq.Operation', Dict[str, 'CirqQuregT']]:
import cirq
(q1,) = q1
(q2,) = q2
return cirq.CZ(q1, q2), {'q1': np.array([q1]), 'q2': np.array([q2])}
def wire_symbol(self, reg: Optional[Register], idx: Tuple[int, ...] = tuple()) -> 'WireSymbol':
if reg is None:
return Text('')
if reg.name == 'q1' or reg.name == 'q2':
return Circle()
raise ValueError(f'Unknown wire symbol register name: {reg.name}')
def get_ctrl_system(self, ctrl_spec: 'CtrlSpec') -> Tuple['Bloq', 'AddControlledT']:
from qualtran.bloqs.mcmt.specialized_ctrl import get_ctrl_system_1bit_cv_from_bloqs
return get_ctrl_system_1bit_cv_from_bloqs(
self, ctrl_spec, current_ctrl_bit=1, bloq_with_ctrl=self, ctrl_reg_name='q1'
)
@bloq_example
def _cz() -> CZ:
cz = CZ()
return cz
_CZ_DOC = BloqDocSpec(bloq_cls=CZ, examples=[_cz], call_graph_example=None)
@frozen
class _IntVector(Bloq):
"""Represent a classical non-negative integer vector (state or effect).
Args:
val: the classical value
bitsize: The bitsize of the register
state: True if this is a state; an effect otherwise.
Registers:
val: The register of size `bitsize` which initializes the value `val`.
"""
val: Union[int, sympy.Expr] = attrs.field()
bitsize: Union[int, sympy.Expr]
state: bool
@val.validator
def check(self, attribute, val):
if isinstance(val, sympy.Expr) or isinstance(self.bitsize, sympy.Expr):
return
if val < 0:
raise ValueError("`val` must be positive")
if val >= 2**self.bitsize:
raise ValueError(f"`val` is too big for bitsize {self.bitsize}")
@cached_property
def dtype(self) -> QDType:
if self.bitsize == 1:
return QBit()
return QAny(self.bitsize)
@cached_property
def signature(self) -> Signature:
side = Side.RIGHT if self.state else Side.LEFT
return Signature([Register('val', self.dtype, side=side)])
@staticmethod
def _build_composite_state(bb: 'BloqBuilder', bits: NDArray[np.uint8]) -> Dict[str, 'SoquetT']:
states = [ZeroState(), OneState()]
xs = []
for bit in bits:
x = bb.add(states[bit])
xs.append(x)
xs = np.array(xs)
return {'val': bb.join(xs)}
@staticmethod
def _build_composite_effect(
bb: 'BloqBuilder', val: 'Soquet', bits: NDArray[np.uint8]
) -> Dict[str, 'SoquetT']:
xs = bb.split(val)
effects = [ZeroEffect(), OneEffect()]
for i, bit in enumerate(bits):
bb.add(effects[bit], q=xs[i])
return {}
def build_composite_bloq(self, bb: 'BloqBuilder', **val: 'SoquetT') -> Dict[str, 'SoquetT']:
if isinstance(self.bitsize, sympy.Expr):
raise DecomposeTypeError(f'Symbolic bitsize {self.bitsize} not supported')
bits = np.asarray(self.dtype.to_bits(self.val))
if self.state:
assert not val
return self._build_composite_state(bb, bits)
else:
return self._build_composite_effect(bb, cast(Soquet, val['val']), bits)
def on_classical_vals(self, *, val: Optional[int] = None) -> Dict[str, Union[int, sympy.Expr]]:
if self.state:
assert val is None
return {'val': self.val}
assert val == self.val, val
return {}
def build_call_graph(self, ssa: 'SympySymbolAllocator') -> 'BloqCountDictT':
return {ArbitraryClifford(self.bitsize): 1}
def __str__(self) -> str:
s = f'{self.val}'
return f'|{s}>' if self.state else f'<{s}|'
def wire_symbol(self, reg: Optional[Register], idx: Tuple[int, ...] = tuple()) -> 'WireSymbol':
if reg is None:
return Text('')
return directional_text_box(text=f'{self.val}', side=reg.side)
@frozen(init=False, field_transformer=_hide_base_fields)
class IntState(_IntVector):
"""The state |val> for non-negative integer val
Args:
val: the classical value
bitsize: The bitsize of the register
Registers:
val: The register of size `bitsize` which initializes the value `val`.
"""
def __init__(self, val: SymbolicInt, bitsize: SymbolicInt):
self.__attrs_init__(val=val, bitsize=bitsize, state=True)
@bloq_example
def _int_state() -> IntState:
int_state = IntState(55, bitsize=8)
return int_state
_INT_STATE_DOC = BloqDocSpec(bloq_cls=IntState, examples=[_int_state])
@frozen(init=False, field_transformer=_hide_base_fields)
class IntEffect(_IntVector):
"""The effect <val| for non-negative integer val
Args:
val: the classical value
bitsize: The bitsize of the register
Registers:
val: The register of size `bitsize` which de-allocates the value `val`.
"""
def __init__(self, val: SymbolicInt, bitsize: SymbolicInt):
self.__attrs_init__(val=val, bitsize=bitsize, state=False)
@bloq_example
def _int_effect() -> IntEffect:
int_effect = IntEffect(55, bitsize=8)
return int_effect
_INT_EFFECT_DOC = BloqDocSpec(bloq_cls=IntEffect, examples=[_int_effect])