-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathpauli_string.py
1533 lines (1255 loc) · 55.9 KB
/
pauli_string.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
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 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.
import cmath
import math
import numbers
from typing import (
Any,
cast,
Dict,
ItemsView,
Iterable,
Iterator,
KeysView,
List,
Mapping,
Optional,
overload,
Sequence,
SupportsComplex,
Tuple,
TYPE_CHECKING,
TypeVar,
Union,
ValuesView,
AbstractSet,
Callable,
Generic,
)
import numpy as np
from cirq import value, protocols, linalg, qis
from cirq._doc import document
from cirq.ops import (
clifford_gate,
common_gates,
gate_operation,
global_phase_op,
identity,
op_tree,
pauli_gates,
pauli_interaction_gate,
raw_types,
)
from cirq.type_workarounds import NotImplementedType
if TYPE_CHECKING:
import cirq
TDefault = TypeVar('TDefault')
TKey = TypeVar('TKey', bound=raw_types.Qid)
TKeyNew = TypeVar('TKeyNew', bound=raw_types.Qid)
TKeyOther = TypeVar('TKeyOther', bound=raw_types.Qid)
# A value that can be unambiguously converted into a `cirq.PauliString`.
PAULI_STRING_LIKE = Union[
complex,
'cirq.OP_TREE',
Mapping[TKey, 'cirq.PAULI_GATE_LIKE'],
Iterable, # of PAULI_STRING_LIKE, but mypy doesn't do recursive types yet.
]
document(
PAULI_STRING_LIKE, # type: ignore
"""A `cirq.PauliString` or a value that can easily be converted into one.
Complex numbers turn into the coefficient of an empty Pauli string.
Dictionaries from qubit to Pauli operation are wrapped into a Pauli string.
Each Pauli operation can be specified as a cirq object (e.g. `cirq.X`) or as
a string (e.g. `"X"`) or as an integer where 0=I, 1=X, 2=Y, 3=Z.
Collections of Pauli operations are recursively multiplied into a single
Pauli string.
""",
)
PAULI_GATE_LIKE = Union[
'cirq.Pauli',
'cirq.IdentityGate',
str,
int,
]
document(
PAULI_GATE_LIKE, # type: ignore
"""An object that can be interpreted as a Pauli gate.
Allowed values are:
1. Cirq gates: `cirq.I`, `cirq.X`, `cirq.Y`, `cirq.Z`.
2. Strings: "I", "X", "Y", "Z". Equivalently "i", "x", "y", "z".
3. Integers from 0 to 3, with the convention 0=I, 1=X, 2=Y, 3=Z.
""",
)
@value.value_equality(approximate=True, manual_cls=True)
class PauliString(raw_types.Operation, Generic[TKey]):
def __init__(
self,
*contents: 'cirq.PAULI_STRING_LIKE',
qubit_pauli_map: Optional[Dict[TKey, 'cirq.Pauli']] = None,
coefficient: Union[int, float, complex] = 1,
):
"""Initializes a new PauliString.
Args:
*contents: A value or values to convert into a pauli string. This
can be a number, a pauli operation, a dictionary from qubit to
pauli/identity gates, or collections thereof. If a list of
values is given, they are each individually converted and then
multiplied from left to right in order.
qubit_pauli_map: Initial dictionary mapping qubits to pauli
operations. Defaults to the empty dictionary. Note that, unlike
dictionaries passed to contents, this dictionary must not
contain any identity gate values. Further note that this
argument specifies values that are logically *before* factors
specified in `contents`; `contents` are *right* multiplied onto
the values in this dictionary.
coefficient: Initial scalar coefficient. Defaults to 1.
Examples:
>>> a, b, c = cirq.LineQubit.range(3)
>>> print(cirq.PauliString([cirq.X(a), cirq.X(a)]))
I
>>> print(cirq.PauliString(-1, cirq.X(a), cirq.Y(b), cirq.Z(c)))
-X(0)*Y(1)*Z(2)
>>> print(cirq.PauliString({a: cirq.X}, [-2, 3, cirq.Y(a)]))
-6j*Z(0)
>>> print(cirq.PauliString({a: cirq.I, b: cirq.X}))
X(1)
>>> print(cirq.PauliString({a: cirq.Y},
... qubit_pauli_map={a: cirq.X}))
1j*Z(0)
"""
if qubit_pauli_map is not None:
for v in qubit_pauli_map.values():
if not isinstance(v, pauli_gates.Pauli):
raise TypeError(f'{v} is not a Pauli')
self._qubit_pauli_map: Dict[TKey, 'cirq.Pauli'] = qubit_pauli_map or {}
self._coefficient = complex(coefficient)
if contents:
m = self.mutable_copy().inplace_left_multiply_by(contents).frozen()
self._qubit_pauli_map = m._qubit_pauli_map
self._coefficient = m._coefficient
@property
def coefficient(self) -> complex:
return self._coefficient
def _value_equality_values_(self):
if len(self._qubit_pauli_map) == 1 and self.coefficient == 1:
q, p = list(self._qubit_pauli_map.items())[0]
return gate_operation.GateOperation(p, [q])._value_equality_values_()
return (frozenset(self._qubit_pauli_map.items()), self._coefficient)
def _json_dict_(self) -> Dict[str, Any]:
return {
'cirq_type': self.__class__.__name__,
# JSON requires mappings to have string keys.
'qubit_pauli_map': list(self._qubit_pauli_map.items()),
'coefficient': self.coefficient,
}
@classmethod
def _from_json_dict_(cls, qubit_pauli_map, coefficient, **kwargs):
return cls(qubit_pauli_map=dict(qubit_pauli_map), coefficient=coefficient)
def _value_equality_values_cls_(self):
if len(self._qubit_pauli_map) == 1 and self.coefficient == 1:
return gate_operation.GateOperation
return PauliString
def equal_up_to_coefficient(self, other: 'cirq.PauliString') -> bool:
return self._qubit_pauli_map == other._qubit_pauli_map
def __getitem__(self, key: TKey) -> pauli_gates.Pauli:
return self._qubit_pauli_map[key]
# pylint: disable=function-redefined
@overload
def get(self, key: Any, default: None = None) -> pauli_gates.Pauli:
pass
@overload
def get(self, key: Any, default: TDefault) -> Union[pauli_gates.Pauli, TDefault]:
pass
def get(self, key: Any, default=None):
return self._qubit_pauli_map.get(key, default)
@overload
def __mul__( # type: ignore
self, other: 'cirq.PauliString[TKeyOther]'
) -> 'cirq.PauliString[Union[TKey, TKeyOther]]':
pass
@overload
def __mul__(
self, other: Mapping[TKeyOther, 'cirq.PAULI_GATE_LIKE']
) -> 'cirq.PauliString[Union[TKey, TKeyOther]]':
pass
@overload
def __mul__(
self, other: Iterable['cirq.PAULI_STRING_LIKE']
) -> 'cirq.PauliString[Union[TKey, cirq.Qid]]':
pass
@overload
def __mul__(self, other: 'cirq.Operation') -> 'cirq.PauliString[Union[TKey, cirq.Qid]]':
pass
@overload
def __mul__(
self, other: Union[complex, int, float, numbers.Number]
) -> 'cirq.PauliString[TKey]':
pass
def __mul__(self, other):
known = False
if isinstance(other, raw_types.Operation) and isinstance(other.gate, identity.IdentityGate):
known = True
elif isinstance(other, (PauliString, numbers.Number)):
known = True
if known:
return PauliString(
cast(PAULI_STRING_LIKE, other),
qubit_pauli_map=self._qubit_pauli_map,
coefficient=self.coefficient,
)
return NotImplemented
# pylint: enable=function-redefined
@property
def gate(self) -> 'cirq.DensePauliString':
order: List[Optional[pauli_gates.Pauli]] = [
None,
pauli_gates.X,
pauli_gates.Y,
pauli_gates.Z,
]
from cirq.ops.dense_pauli_string import DensePauliString
return DensePauliString(
coefficient=self.coefficient, pauli_mask=[order.index(self[q]) for q in self.qubits]
)
def __rmul__(self, other) -> 'PauliString':
if isinstance(other, numbers.Number):
return PauliString(
qubit_pauli_map=self._qubit_pauli_map,
coefficient=self._coefficient * complex(cast(SupportsComplex, other)),
)
if isinstance(other, raw_types.Operation) and isinstance(other.gate, identity.IdentityGate):
return self
# Note: PauliString case handled by __mul__.
return NotImplemented
def __truediv__(self, other):
if isinstance(other, numbers.Number):
return PauliString(
qubit_pauli_map=self._qubit_pauli_map,
coefficient=self._coefficient / complex(cast(SupportsComplex, other)),
)
return NotImplemented
def __add__(self, other):
from cirq.ops.linear_combinations import PauliSum
return PauliSum.from_pauli_strings(self).__add__(other)
def __radd__(self, other):
return self.__add__(other)
def __sub__(self, other):
from cirq.ops.linear_combinations import PauliSum
return PauliSum.from_pauli_strings(self).__sub__(other)
def __rsub__(self, other):
return -self.__sub__(other)
def __contains__(self, key: TKey) -> bool:
return key in self._qubit_pauli_map
def _decompose_(self):
if not self._has_unitary_():
return None
return [
*(
[]
if self.coefficient == 1
else [global_phase_op.GlobalPhaseOperation(self.coefficient)]
),
*[self[q].on(q) for q in self.qubits],
]
def keys(self) -> KeysView[TKey]:
return self._qubit_pauli_map.keys()
@property
def qubits(self) -> Tuple[TKey, ...]:
return tuple(sorted(self.keys()))
def _circuit_diagram_info_(self, args: 'cirq.CircuitDiagramInfoArgs') -> List[str]:
if not len(self._qubit_pauli_map):
return NotImplemented
qs = args.known_qubits or list(self.keys())
symbols = list(str(self.get(q)) for q in qs)
if self.coefficient == 1:
prefix = '+'
elif self.coefficient == -1:
prefix = '-'
elif self.coefficient == 1j:
prefix = 'i'
elif self.coefficient == -1j:
prefix = '-i'
else:
prefix = f'({args.format_complex(self.coefficient)})*'
symbols[0] = f'PauliString({prefix}{symbols[0]})'
return symbols
def with_qubits(self, *new_qubits: 'cirq.Qid') -> 'PauliString':
return PauliString(
qubit_pauli_map=dict(zip(new_qubits, (self[q] for q in self.qubits))),
coefficient=self._coefficient,
)
def with_coefficient(self, new_coefficient: Union[int, float, complex]) -> 'PauliString':
return PauliString(qubit_pauli_map=dict(self._qubit_pauli_map), coefficient=new_coefficient)
def values(self) -> ValuesView[pauli_gates.Pauli]:
return self._qubit_pauli_map.values()
def items(self) -> ItemsView[TKey, pauli_gates.Pauli]:
return self._qubit_pauli_map.items()
def frozen(self) -> 'cirq.PauliString':
"""Returns a cirq.PauliString with the same contents."""
return self
def mutable_copy(self) -> 'cirq.MutablePauliString':
"""Returns a new cirq.MutablePauliString with the same contents."""
return MutablePauliString(
coefficient=self.coefficient,
pauli_int_dict={
q: PAULI_GATE_LIKE_TO_INDEX_MAP[p] for q, p in self._qubit_pauli_map.items()
},
)
def __iter__(self) -> Iterator[TKey]:
return iter(self._qubit_pauli_map.keys())
def __bool__(self):
return bool(self._qubit_pauli_map)
def __len__(self) -> int:
return len(self._qubit_pauli_map)
def _repr_pretty_(self, p: Any, cycle: bool) -> None:
"""Print ASCII diagram in Jupyter."""
if cycle:
# There should never be a cycle. This is just in case.
p.text('cirq.PauliString(...)')
else:
p.text(str(self))
def __repr__(self) -> str:
ordered_qubits = sorted(self.qubits)
prefix = ''
factors = []
if self._coefficient == -1:
prefix = '-'
elif self._coefficient != 1:
factors.append(repr(self._coefficient))
if not ordered_qubits:
factors.append('cirq.PauliString()')
for q in ordered_qubits:
factors.append(repr(cast(raw_types.Gate, self[q]).on(q)))
fused = prefix + '*'.join(factors)
if len(factors) > 1:
return f'({fused})'
return fused
def __str__(self) -> str:
ordered_qubits = sorted(self.qubits)
prefix = ''
factors = []
if self._coefficient == -1:
prefix = '-'
elif self._coefficient != 1:
factors.append(repr(self._coefficient))
if not ordered_qubits:
factors.append('I')
for q in ordered_qubits:
factors.append(str(cast(raw_types.Gate, self[q]).on(q)))
return prefix + '*'.join(factors)
def matrix(self, qubits: Optional[Iterable[TKey]] = None) -> np.ndarray:
"""Returns the matrix of self in computational basis of qubits.
Args:
qubits: Ordered collection of qubits that determine the subspace
in which the matrix representation of the Pauli string is to
be computed. Qubits absent from self.qubits are acted on by
the identity. Defaults to self.qubits.
"""
qubits = self.qubits if qubits is None else qubits
factors = [self.get(q, default=identity.I) for q in qubits]
return linalg.kron(self.coefficient, *[protocols.unitary(f) for f in factors])
def _has_unitary_(self) -> bool:
return abs(1 - abs(self.coefficient)) < 1e-6
def _unitary_(self) -> Optional[np.ndarray]:
if not self._has_unitary_():
return None
return self.matrix()
def _apply_unitary_(self, args: 'protocols.ApplyUnitaryArgs'):
if not self._has_unitary_():
return None
if self.coefficient != 1:
args.target_tensor *= self.coefficient
return protocols.apply_unitaries([self[q].on(q) for q in self.qubits], self.qubits, args)
def expectation_from_state_vector(
self,
state_vector: np.ndarray,
qubit_map: Mapping[TKey, int],
*,
atol: float = 1e-7,
check_preconditions: bool = True,
) -> float:
r"""Evaluate the expectation of this PauliString given a state vector.
Compute the expectation value of this PauliString with respect to a
state vector. By convention expectation values are defined for Hermitian
operators, and so this method will fail if this PauliString is
non-Hermitian.
`state` must be an array representation of a state vector and have
shape `(2 ** n, )` or `(2, 2, ..., 2)` (n entries) where `state` is
expressed over n qubits.
`qubit_map` must assign an integer index to each qubit in this
PauliString that determines which bit position of a computational basis
state that qubit corresponds to. For example if `state` represents
$|0\rangle |+\rangle$ and `q0, q1 = cirq.LineQubit.range(2)` then:
cirq.X(q0).expectation(state, qubit_map={q0: 0, q1: 1}) = 0
cirq.X(q0).expectation(state, qubit_map={q0: 1, q1: 0}) = 1
Args:
state_vector: An array representing a valid state vector.
qubit_map: A map from all qubits used in this PauliString to the
indices of the qubits that `state_vector` is defined over.
atol: Absolute numerical tolerance.
check_preconditions: Whether to check that `state_vector` represents
a valid state vector.
Returns:
The expectation value of the input state.
Raises:
NotImplementedError if this PauliString is non-Hermitian.
"""
if abs(self.coefficient.imag) > 0.0001:
raise NotImplementedError(
'Cannot compute expectation value of a non-Hermitian '
f'PauliString <{self}>. Coefficient must be real.'
)
# FIXME: Avoid enforce specific complex type. This is necessary to
# prevent an `apply_unitary` bug (Issue #2041).
if state_vector.dtype.kind != 'c':
raise TypeError("Input state dtype must be np.complex64 or np.complex128")
size = state_vector.size
num_qubits = size.bit_length() - 1
if len(state_vector.shape) != 1 and state_vector.shape != (2,) * num_qubits:
raise ValueError(
"Input array does not represent a state vector "
"with shape `(2 ** n,)` or `(2, ..., 2)`."
)
_validate_qubit_mapping(qubit_map, self.qubits, num_qubits)
if check_preconditions:
qis.validate_normalized_state_vector(
state_vector=state_vector,
qid_shape=(2,) * num_qubits,
dtype=state_vector.dtype,
atol=atol,
)
return self._expectation_from_state_vector_no_validation(state_vector, qubit_map)
def _expectation_from_state_vector_no_validation(
self, state_vector: np.ndarray, qubit_map: Mapping[TKey, int]
) -> float:
"""Evaluate the expectation of this PauliString given a state vector.
This method does not provide input validation. See
`PauliString.expectation_from_state_vector` for function description.
Args:
state_vector: An array representing a valid state vector.
qubit_map: A map from all qubits used in this PauliString to the
indices of the qubits that `state` is defined over.
Returns:
The expectation value of the input state.
"""
if len(state_vector.shape) == 1:
num_qubits = state_vector.shape[0].bit_length() - 1
state_vector = np.reshape(state_vector, (2,) * num_qubits)
ket = np.copy(state_vector)
for qubit, pauli in self.items():
buffer = np.empty(ket.shape, dtype=state_vector.dtype)
args = protocols.ApplyUnitaryArgs(
target_tensor=ket, available_buffer=buffer, axes=(qubit_map[qubit],)
)
ket = protocols.apply_unitary(pauli, args)
return self.coefficient * (
np.tensordot(state_vector.conj(), ket, axes=len(ket.shape)).item()
)
def expectation_from_density_matrix(
self,
state: np.ndarray,
qubit_map: Mapping[TKey, int],
*,
atol: float = 1e-7,
check_preconditions: bool = True,
) -> float:
r"""Evaluate the expectation of this PauliString given a density matrix.
Compute the expectation value of this PauliString with respect to an
array representing a density matrix. By convention expectation values
are defined for Hermitian operators, and so this method will fail if
this PauliString is non-Hermitian.
`state` must be an array representation of a density matrix and have
shape `(2 ** n, 2 ** n)` or `(2, 2, ..., 2)` (2*n entries), where
`state` is expressed over n qubits.
`qubit_map` must assign an integer index to each qubit in this
PauliString that determines which bit position of a computational basis
state that qubit corresponds to. For example if `state` represents
$|0\rangle |+\rangle$ and `q0, q1 = cirq.LineQubit.range(2)` then:
cirq.X(q0).expectation(state, qubit_map={q0: 0, q1: 1}) = 0
cirq.X(q0).expectation(state, qubit_map={q0: 1, q1: 0}) = 1
Args:
state: An array representing a valid density matrix.
qubit_map: A map from all qubits used in this PauliString to the
indices of the qubits that `state` is defined over.
atol: Absolute numerical tolerance.
check_preconditions: Whether to check that `state` represents a
valid density matrix.
Returns:
The expectation value of the input state.
Raises:
NotImplementedError if this PauliString is non-Hermitian.
"""
if abs(self.coefficient.imag) > 0.0001:
raise NotImplementedError(
'Cannot compute expectation value of a non-Hermitian '
f'PauliString <{self}>. Coefficient must be real.'
)
# FIXME: Avoid enforcing specific complex type. This is necessary to
# prevent an `apply_unitary` bug (Issue #2041).
if state.dtype.kind != 'c':
raise TypeError("Input state dtype must be np.complex64 or np.complex128")
size = state.size
num_qubits = int(np.sqrt(size)).bit_length() - 1
dim = 1 << num_qubits
if state.shape != (dim, dim) and state.shape != (2, 2) * num_qubits:
raise ValueError(
"Input array does not represent a density matrix "
"with shape `(2 ** n, 2 ** n)` or `(2, ..., 2)`."
)
_validate_qubit_mapping(qubit_map, self.qubits, num_qubits)
if check_preconditions:
# Do not enforce reshaping if the state all axes are dimension 2.
_ = qis.to_valid_density_matrix(
density_matrix_rep=state.reshape(dim, dim),
num_qubits=num_qubits,
dtype=state.dtype,
atol=atol,
)
return self._expectation_from_density_matrix_no_validation(state, qubit_map)
def _expectation_from_density_matrix_no_validation(
self, state: np.ndarray, qubit_map: Mapping[TKey, int]
) -> float:
"""Evaluate the expectation of this PauliString given a density matrix.
This method does not provide input validation. See
`PauliString.expectation_from_density_matrix` for function description.
Args:
state: An array representing a valid density matrix.
qubit_map: A map from all qubits used in this PauliString to the
indices of the qubits that `state` is defined over.
Returns:
The expectation value of the input state.
"""
result = np.copy(state)
if len(state.shape) == 2:
num_qubits = state.shape[0].bit_length() - 1
result = np.reshape(result, (2,) * num_qubits * 2)
for qubit, pauli in self.items():
buffer = np.empty(result.shape, dtype=state.dtype)
args = protocols.ApplyUnitaryArgs(
target_tensor=result, available_buffer=buffer, axes=(qubit_map[qubit],)
)
result = protocols.apply_unitary(pauli, args)
while any(result.shape):
result = np.trace(result, axis1=0, axis2=len(result.shape) // 2)
return result * self.coefficient
def zip_items(
self, other: 'cirq.PauliString[TKey]'
) -> Iterator[Tuple[TKey, Tuple[pauli_gates.Pauli, pauli_gates.Pauli]]]:
for qubit, pauli0 in self.items():
if qubit in other:
yield qubit, (pauli0, other[qubit])
def zip_paulis(
self, other: 'cirq.PauliString'
) -> Iterator[Tuple[pauli_gates.Pauli, pauli_gates.Pauli]]:
return (paulis for qubit, paulis in self.zip_items(other))
def _commutes_(
self, other: Any, *, atol: Union[int, float] = 1e-8
) -> Union[bool, NotImplementedType, None]:
if not isinstance(other, PauliString):
return NotImplemented
return sum(not protocols.commutes(p0, p1) for p0, p1 in self.zip_paulis(other)) % 2 == 0
def __neg__(self) -> 'PauliString':
return PauliString(qubit_pauli_map=self._qubit_pauli_map, coefficient=-self._coefficient)
def __pos__(self) -> 'PauliString':
return self
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
"""Override behavior of numpy's exp method."""
if ufunc == np.exp and len(inputs) == 1 and inputs[0] is self:
return math.e ** self
return NotImplemented
def __pow__(self, power):
if power == 1:
return self
if power == -1:
return PauliString(
qubit_pauli_map=self._qubit_pauli_map, coefficient=self.coefficient ** -1
)
if isinstance(power, (int, float)):
r, i = cmath.polar(self.coefficient)
if abs(r - 1) > 0.0001:
# Raising non-unitary PauliStrings to a power is not supported.
return NotImplemented
if len(self) == 1:
q, p = next(iter(self.items()))
gates = {
pauli_gates.X: common_gates.XPowGate,
pauli_gates.Y: common_gates.YPowGate,
pauli_gates.Z: common_gates.ZPowGate,
}
return gates[p](exponent=power).on(q)
global_half_turns = power * (i / math.pi)
# HACK: Avoid circular dependency.
from cirq.ops import pauli_string_phasor
return pauli_string_phasor.PauliStringPhasor(
PauliString(qubit_pauli_map=self._qubit_pauli_map),
exponent_neg=global_half_turns + power,
exponent_pos=global_half_turns,
)
return NotImplemented
def __rpow__(self, base):
if isinstance(base, (int, float)) and base > 0:
if abs(self.coefficient.real) > 0.0001:
raise NotImplementedError(
'Exponentiated to a non-Hermitian PauliString '
f'<{base}**{self}>. Coefficient must be imaginary.'
)
half_turns = 2 * math.log(base) * (-self.coefficient.imag / math.pi)
if len(self) == 1:
q, p = next(iter(self.items()))
gates = {
pauli_gates.X: common_gates.XPowGate,
pauli_gates.Y: common_gates.YPowGate,
pauli_gates.Z: common_gates.ZPowGate,
}
return gates[p](exponent=half_turns, global_shift=-0.5).on(q)
# HACK: Avoid circular dependency.
from cirq.ops import pauli_string_phasor
return pauli_string_phasor.PauliStringPhasor(
PauliString(qubit_pauli_map=self._qubit_pauli_map),
exponent_neg=+half_turns / 2,
exponent_pos=-half_turns / 2,
)
return NotImplemented
def map_qubits(self, qubit_map: Dict[TKey, TKeyNew]) -> 'cirq.PauliString[TKeyNew]':
new_qubit_pauli_map = {qubit_map[qubit]: pauli for qubit, pauli in self.items()}
return PauliString(qubit_pauli_map=new_qubit_pauli_map, coefficient=self._coefficient)
def to_z_basis_ops(self) -> Iterator[raw_types.Operation]:
"""Returns operations to convert the qubits to the computational basis."""
for qubit, pauli in self.items():
yield clifford_gate.SingleQubitCliffordGate.from_single_map(
{pauli: (pauli_gates.Z, False)}
)(qubit)
def dense(self, qubits: Sequence[TKey]) -> 'cirq.DensePauliString':
"""Returns a `cirq.DensePauliString` version of this Pauli string.
This method satisfies the invariant `P.dense(qubits).on(*qubits) == P`.
Args:
qubits: The implicit sequence of qubits used by the dense pauli
string. Specifically, if the returned dense Pauli string was
applied to these qubits (via its `on` method) then the result
would be a Pauli string equivalent to the receiving Pauli
string.
Returns:
A `cirq.DensePauliString` instance `D` such that `D.on(*qubits)`
equals the receiving `cirq.PauliString` instance `P`.
"""
from cirq.ops.dense_pauli_string import DensePauliString
if not self.keys() <= set(qubits):
raise ValueError('not self.keys() <= set(qubits)')
# pylint: disable=too-many-function-args
pauli_mask = [self.get(q, identity.I) for q in qubits]
# pylint: enable=too-many-function-args
return DensePauliString(pauli_mask, coefficient=self.coefficient)
def conjugated_by(self, clifford: 'cirq.OP_TREE') -> 'PauliString':
r"""Returns the Pauli string conjugated by a clifford operation.
The product-of-Paulis $P$ conjugated by the Clifford operation $C$ is
$$
C^\dagger P C
$$
For example, conjugating a +Y operation by an S operation results in a
+X operation (as opposed to a -X operation).
In a circuit diagram where `P` is a pauli string observable immediately
after a Clifford operation `C`, the pauli string `P.conjugated_by(C)` is
the equivalent pauli string observable just before `C`.
--------------------------C---P---
= ---C---P------------------------
= ---C---P---------C^-1---C-------
= ---C---P---C^-1---------C-------
= --(C^-1 · P · C)--------C-------
= ---P.conjugated_by(C)---C-------
Analogously, a Pauli product P can be moved from before a Clifford C in
a circuit diagram to after the Clifford C by conjugating P by the
inverse of C:
---P---C---------------------------
= -----C---P.conjugated_by(C^-1)---
Args:
clifford: The Clifford operation to conjugate by. This can be an
individual operation, or a tree of operations.
Note that the composite Clifford operation defined by a sequence
of operations is equivalent to a circuit containing those
operations in the given order. Somewhat counter-intuitively,
this means that the operations in the sequence are conjugated
onto the Pauli string in reverse order. For example,
`P.conjugated_by([C1, C2])` is equivalent to
`P.conjugated_by(C2).conjugated_by(C1)`.
Examples:
>>> a, b = cirq.LineQubit.range(2)
>>> print(cirq.X(a).conjugated_by(cirq.CZ(a, b)))
X(0)*Z(1)
>>> print(cirq.X(a).conjugated_by(cirq.S(a)))
-Y(0)
>>> print(cirq.X(a).conjugated_by([cirq.H(a), cirq.CNOT(a, b)]))
Z(0)*X(1)
Returns:
The Pauli string conjugated by the given Clifford operation.
"""
pauli_map = dict(self._qubit_pauli_map)
should_negate = False
for op in list(op_tree.flatten_to_ops(clifford))[::-1]:
if pauli_map.keys().isdisjoint(set(op.qubits)):
continue
for clifford_op in _decompose_into_cliffords(op)[::-1]:
if pauli_map.keys().isdisjoint(set(clifford_op.qubits)):
continue
should_negate ^= PauliString._pass_operation_over(pauli_map, clifford_op, False)
coef = -self._coefficient if should_negate else self.coefficient
return PauliString(qubit_pauli_map=pauli_map, coefficient=coef)
def after(self, ops: 'cirq.OP_TREE') -> 'cirq.PauliString':
r"""Determines the equivalent pauli string after some operations.
If the PauliString is $P$ and the Clifford operation is $C$, then the
result is $C P C^\dagger$.
Args:
ops: A stabilizer operation or nested collection of stabilizer
operations.
Returns:
The result of propagating this pauli string from before to after the
given operations.
"""
return self.conjugated_by(protocols.inverse(ops))
def before(self, ops: 'cirq.OP_TREE') -> 'cirq.PauliString':
r"""Determines the equivalent pauli string before some operations.
If the PauliString is $P$ and the Clifford operation is $C$, then the
result is $C^\dagger P C$.
Args:
ops: A stabilizer operation or nested collection of stabilizer
operations.
Returns:
The result of propagating this pauli string from after to before the
given operations.
"""
return self.conjugated_by(ops)
def pass_operations_over(
self, ops: Iterable['cirq.Operation'], after_to_before: bool = False
) -> 'PauliString':
"""Determines how the Pauli string changes when conjugated by Cliffords.
The output and input pauli strings are related by a circuit equivalence.
In particular, this circuit:
───ops───INPUT_PAULI_STRING───
will be equivalent to this circuit:
───OUTPUT_PAULI_STRING───ops───
up to global phase (assuming `after_to_before` is not set).
If ops together have matrix C, the Pauli string has matrix P, and the
output Pauli string has matrix P', then P' == C^-1 P C up to
global phase.
Setting `after_to_before` inverts the relationship, so that the output
is the input and the input is the output. Equivalently, it inverts C.
Args:
ops: The operations to move over the string.
after_to_before: Determines whether the operations start after the
pauli string, instead of before (and so are moving in the
opposite direction).
"""
pauli_map = dict(self._qubit_pauli_map)
should_negate = False
for op in ops:
if pauli_map.keys().isdisjoint(set(op.qubits)):
continue
decomposed = _decompose_into_cliffords(op)
if not after_to_before:
decomposed = decomposed[::-1]
for clifford_op in decomposed:
if pauli_map.keys().isdisjoint(set(clifford_op.qubits)):
continue
should_negate ^= PauliString._pass_operation_over(
pauli_map, clifford_op, after_to_before
)
coef = -self._coefficient if should_negate else self.coefficient
return PauliString(qubit_pauli_map=pauli_map, coefficient=coef)
@staticmethod
def _pass_operation_over(
pauli_map: Dict[TKey, pauli_gates.Pauli],
op: 'cirq.Operation',
after_to_before: bool = False,
) -> bool:
if isinstance(op, gate_operation.GateOperation):
gate = op.gate
if isinstance(gate, clifford_gate.SingleQubitCliffordGate):
return PauliString._pass_single_clifford_gate_over(
pauli_map, gate, cast(TKey, op.qubits[0]), after_to_before=after_to_before
)
if isinstance(gate, pauli_interaction_gate.PauliInteractionGate):
return PauliString._pass_pauli_interaction_gate_over(
pauli_map,
gate,
cast(TKey, op.qubits[0]),
cast(TKey, op.qubits[1]),
after_to_before=after_to_before,
)
raise NotImplementedError(f'Unsupported operation: {op!r}')
@staticmethod
def _pass_single_clifford_gate_over(
pauli_map: Dict[TKey, pauli_gates.Pauli],
gate: clifford_gate.SingleQubitCliffordGate,
qubit: TKey,
after_to_before: bool = False,
) -> bool:
if qubit not in pauli_map:
return False
if not after_to_before:
gate **= -1
pauli, inv = gate.transform(pauli_map[qubit])
pauli_map[qubit] = pauli
return inv
@staticmethod
def _pass_pauli_interaction_gate_over(
pauli_map: Dict[TKey, pauli_gates.Pauli],
gate: pauli_interaction_gate.PauliInteractionGate,
qubit0: TKey,
qubit1: TKey,
after_to_before: bool = False,
) -> bool:
def merge_and_kickback(
qubit: TKey,
pauli_left: Optional[pauli_gates.Pauli],
pauli_right: Optional[pauli_gates.Pauli],
inv: bool,
) -> int:
assert pauli_left is not None or pauli_right is not None
if pauli_left is None or pauli_right is None:
pauli_map[qubit] = cast(pauli_gates.Pauli, pauli_left or pauli_right)
return 0
if pauli_left == pauli_right:
del pauli_map[qubit]
return 0