-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
pauli_list.py
1184 lines (955 loc) · 42.4 KB
/
pauli_list.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
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2022
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Optimized list of Pauli operators
"""
from collections import defaultdict
import numpy as np
import rustworkx as rx
from qiskit.exceptions import QiskitError
from qiskit.quantum_info.operators.custom_iterator import CustomIterator
from qiskit.quantum_info.operators.mixins import GroupMixin, LinearMixin
from qiskit.quantum_info.operators.symplectic.base_pauli import BasePauli
from qiskit.quantum_info.operators.symplectic.pauli import Pauli
from qiskit.quantum_info.operators.symplectic.pauli_table import PauliTable
from qiskit.quantum_info.operators.symplectic.stabilizer_table import StabilizerTable
class PauliList(BasePauli, LinearMixin, GroupMixin):
r"""List of N-qubit Pauli operators.
This class is an efficient representation of a list of
:class:`Pauli` operators. It supports 1D numpy array indexing
returning a :class:`Pauli` for integer indexes or a
:class:`PauliList` for slice or list indices.
**Initialization**
A PauliList object can be initialized in several ways.
``PauliList(list[str])``
where strings are same representation with :class:`~qiskit.quantum_info.Pauli`.
``PauliList(Pauli) and PauliList(list[Pauli])``
where Pauli is :class:`~qiskit.quantum_info.Pauli`.
``PauliList.from_symplectic(z, x, phase)``
where ``z`` and ``x`` are 2 dimensional boolean ``numpy.ndarrays`` and ``phase`` is
an integer in ``[0, 1, 2, 3]``.
For example,
.. code-block::
import numpy as np
from qiskit.quantum_info import Pauli, PauliList
# 1. init from list[str]
pauli_list = PauliList(["II", "+ZI", "-iYY"])
print("1. ", pauli_list)
pauli1 = Pauli("iXI")
pauli2 = Pauli("iZZ")
# 2. init from Pauli
print("2. ", PauliList(pauli1))
# 3. init from list[Pauli]
print("3. ", PauliList([pauli1, pauli2]))
# 4. init from np.ndarray
z = np.array([[True, True], [False, False]])
x = np.array([[False, True], [True, False]])
phase = np.array([0, 1])
pauli_list = PauliList.from_symplectic(z, x, phase)
print("4. ", pauli_list)
.. parsed-literal::
1. ['II', 'ZI', '-iYY']
2. ['iXI']
3. ['iXI', 'iZZ']
4. ['YZ', '-iIX']
**Data Access**
The individual Paulis can be accessed and updated using the ``[]``
operator which accepts integer, lists, or slices for selecting subsets
of PauliList. If integer is given, it returns Pauli not PauliList.
.. code-block::
pauli_list = PauliList(["XX", "ZZ", "IZ"])
print("Integer: ", repr(pauli_list[1]))
print("List: ", repr(pauli_list[[0, 2]]))
print("Slice: ", repr(pauli_list[0:2]))
.. parsed-literal::
Integer: Pauli('ZZ')
List: PauliList(['XX', 'IZ'])
Slice: PauliList(['XX', 'ZZ'])
**Iteration**
Rows in the Pauli table can be iterated over like a list. Iteration can
also be done using the label or matrix representation of each row using the
:meth:`label_iter` and :meth:`matrix_iter` methods.
"""
# Set the max number of qubits * paulis before string truncation
__truncate__ = 2000
def __init__(self, data):
"""Initialize the PauliList.
Args:
data (Pauli or list): input data for Paulis. If input is a list each item in the list
must be a Pauli object or Pauli str.
Raises:
QiskitError: if input array is invalid shape.
Additional Information:
The input array is not copied so multiple Pauli tables
can share the same underlying array.
"""
if isinstance(data, BasePauli):
base_z, base_x, base_phase = data._z, data._x, data._phase
elif isinstance(data, StabilizerTable):
# Conversion from legacy StabilizerTable
base_z, base_x, base_phase = self._from_array(data.Z, data.X, 2 * data.phase)
elif isinstance(data, PauliTable):
# Conversion from legacy PauliTable
base_z, base_x, base_phase = self._from_array(data.Z, data.X)
else:
# Conversion as iterable of Paulis
base_z, base_x, base_phase = self._from_paulis(data)
# Initialize BasePauli
super().__init__(base_z, base_x, base_phase)
# ---------------------------------------------------------------------
# Representation conversions
# ---------------------------------------------------------------------
@property
def settings(self):
"""Return settings."""
return {"data": self.to_labels()}
def __array__(self, dtype=None):
"""Convert to numpy array"""
# pylint: disable=unused-argument
shape = (len(self),) + 2 * (2**self.num_qubits,)
ret = np.zeros(shape, dtype=complex)
for i, mat in enumerate(self.matrix_iter()):
ret[i] = mat
return ret
@staticmethod
def _from_paulis(data):
"""Construct a PauliList from a list of Pauli data.
Args:
data (iterable): list of Pauli data.
Returns:
PauliList: the constructed PauliList.
Raises:
QiskitError: If the input list is empty or contains invalid
Pauli strings.
"""
if not isinstance(data, (list, tuple, set, np.ndarray)):
data = [data]
num_paulis = len(data)
if num_paulis == 0:
raise QiskitError("Input Pauli list is empty.")
paulis = []
for i in data:
if not isinstance(i, Pauli):
paulis.append(Pauli(i))
else:
paulis.append(i)
num_qubits = paulis[0].num_qubits
base_z = np.zeros((num_paulis, num_qubits), dtype=bool)
base_x = np.zeros((num_paulis, num_qubits), dtype=bool)
base_phase = np.zeros(num_paulis, dtype=int)
for i, pauli in enumerate(paulis):
base_z[i] = pauli._z
base_x[i] = pauli._x
base_phase[i] = pauli._phase
return base_z, base_x, base_phase
def __repr__(self):
"""Display representation."""
return self._truncated_str(True)
def __str__(self):
"""Print representation."""
return self._truncated_str(False)
def _truncated_str(self, show_class):
stop = self._num_paulis
if self.__truncate__ and self.num_qubits > 0:
max_paulis = self.__truncate__ // self.num_qubits
if self._num_paulis > max_paulis:
stop = max_paulis
labels = [str(self[i]) for i in range(stop)]
prefix = "PauliList(" if show_class else ""
tail = ")" if show_class else ""
if stop != self._num_paulis:
suffix = ", ...]" + tail
else:
suffix = "]" + tail
list_str = np.array2string(
np.array(labels), threshold=stop + 1, separator=", ", prefix=prefix, suffix=suffix
)
return prefix + list_str[:-1] + suffix
def __eq__(self, other):
"""Entrywise comparison of Pauli equality."""
if not isinstance(other, PauliList):
other = PauliList(other)
if not isinstance(other, BasePauli):
return False
return self._eq(other)
def equiv(self, other):
"""Entrywise comparison of Pauli equivalence up to global phase.
Args:
other (PauliList or Pauli): a comparison object.
Returns:
np.ndarray: An array of True or False for entrywise equivalence
of the current table.
"""
if not isinstance(other, PauliList):
other = PauliList(other)
return np.all(self.z == other.z, axis=1) & np.all(self.x == other.x, axis=1)
# ---------------------------------------------------------------------
# Direct array access
# ---------------------------------------------------------------------
@property
def phase(self):
"""Return the phase exponent of the PauliList."""
# Convert internal ZX-phase convention to group phase convention
return np.mod(self._phase - self._count_y(dtype=self._phase.dtype), 4)
@phase.setter
def phase(self, value):
# Convert group phase convetion to internal ZX-phase convention
self._phase[:] = np.mod(value + self._count_y(dtype=self._phase.dtype), 4)
@property
def x(self):
"""The x array for the symplectic representation."""
return self._x
@x.setter
def x(self, val):
self._x[:] = val
@property
def z(self):
"""The z array for the symplectic representation."""
return self._z
@z.setter
def z(self, val):
self._z[:] = val
# ---------------------------------------------------------------------
# Size Properties
# ---------------------------------------------------------------------
@property
def shape(self):
"""The full shape of the :meth:`array`"""
return self._num_paulis, self.num_qubits
@property
def size(self):
"""The number of Pauli rows in the table."""
return self._num_paulis
def __len__(self):
"""Return the number of Pauli rows in the table."""
return self._num_paulis
# ---------------------------------------------------------------------
# Pauli Array methods
# ---------------------------------------------------------------------
def __getitem__(self, index):
"""Return a view of the PauliList."""
# Returns a view of specified rows of the PauliList
# This supports all slicing operations the underlying array supports.
if isinstance(index, tuple):
if len(index) == 1:
index = index[0]
elif len(index) > 2:
raise IndexError(f"Invalid PauliList index {index}")
# Row-only indexing
if isinstance(index, (int, np.integer)):
# Single Pauli
return Pauli(
BasePauli(
self._z[np.newaxis, index],
self._x[np.newaxis, index],
self._phase[np.newaxis, index],
)
)
elif isinstance(index, (slice, list, np.ndarray)):
# Sub-Table view
return PauliList(BasePauli(self._z[index], self._x[index], self._phase[index]))
# Row and Qubit indexing
return PauliList((self._z[index], self._x[index], 0))
def __setitem__(self, index, value):
"""Update PauliList."""
if isinstance(index, tuple):
if len(index) == 1:
index = index[0]
elif len(index) > 2:
raise IndexError(f"Invalid PauliList index {index}")
# Modify specified rows of the PauliList
if not isinstance(value, PauliList):
value = PauliList(value)
self._z[index] = value._z
self._x[index] = value._x
if not isinstance(index, tuple):
# Row-only indexing
self._phase[index] = value._phase
else:
# Row and Qubit indexing
self._phase[index[0]] += value._phase
self._phase %= 4
def delete(self, ind, qubit=False):
"""Return a copy with Pauli rows deleted from table.
When deleting qubits the qubit index is the same as the
column index of the underlying :attr:`X` and :attr:`Z` arrays.
Args:
ind (int or list): index(es) to delete.
qubit (bool): if True delete qubit columns, otherwise delete
Pauli rows (Default: False).
Returns:
PauliList: the resulting table with the entries removed.
Raises:
QiskitError: if ind is out of bounds for the array size or
number of qubits.
"""
if isinstance(ind, int):
ind = [ind]
# Row deletion
if not qubit:
if max(ind) >= len(self):
raise QiskitError(
"Indices {} are not all less than the size"
" of the PauliList ({})".format(ind, len(self))
)
z = np.delete(self._z, ind, axis=0)
x = np.delete(self._x, ind, axis=0)
phase = np.delete(self._phase, ind)
return PauliList(BasePauli(z, x, phase))
# Column (qubit) deletion
if max(ind) >= self.num_qubits:
raise QiskitError(
"Indices {} are not all less than the number of"
" qubits in the PauliList ({})".format(ind, self.num_qubits)
)
z = np.delete(self._z, ind, axis=1)
x = np.delete(self._x, ind, axis=1)
# Use self.phase, not self._phase as deleting qubits can change the
# ZX phase convention
return PauliList.from_symplectic(z, x, self.phase)
def insert(self, ind, value, qubit=False):
"""Insert Pauli's into the table.
When inserting qubits the qubit index is the same as the
column index of the underlying :attr:`X` and :attr:`Z` arrays.
Args:
ind (int): index to insert at.
value (PauliList): values to insert.
qubit (bool): if True delete qubit columns, otherwise delete
Pauli rows (Default: False).
Returns:
PauliList: the resulting table with the entries inserted.
Raises:
QiskitError: if the insertion index is invalid.
"""
if not isinstance(ind, int):
raise QiskitError("Insert index must be an integer.")
if not isinstance(value, PauliList):
value = PauliList(value)
# Row insertion
size = self._num_paulis
if not qubit:
if ind > size:
raise QiskitError(
"Index {} is larger than the number of rows in the"
" PauliList ({}).".format(ind, size)
)
base_z = np.insert(self._z, ind, value._z, axis=0)
base_x = np.insert(self._x, ind, value._x, axis=0)
base_phase = np.insert(self._phase, ind, value._phase)
return PauliList(BasePauli(base_z, base_x, base_phase))
# Column insertion
if ind > self.num_qubits:
raise QiskitError(
"Index {} is greater than number of qubits"
" in the PauliList ({})".format(ind, self.num_qubits)
)
if len(value) == 1:
# Pad blocks to correct size
value_x = np.vstack(size * [value.x])
value_z = np.vstack(size * [value.z])
value_phase = np.vstack(size * [value.phase])
elif len(value) == size:
# Blocks are already correct size
value_x = value.x
value_z = value.z
value_phase = value.phase
else:
# Blocks are incorrect size
raise QiskitError(
"Input PauliList must have a single row, or"
" the same number of rows as the Pauli Table"
" ({}).".format(size)
)
# Build new array by blocks
z = np.hstack([self.z[:, :ind], value_z, self.z[:, ind:]])
x = np.hstack([self.x[:, :ind], value_x, self.x[:, ind:]])
phase = self.phase + value_phase
return PauliList.from_symplectic(z, x, phase)
def argsort(self, weight=False, phase=False):
"""Return indices for sorting the rows of the table.
The default sort method is lexicographic sorting by qubit number.
By using the `weight` kwarg the output can additionally be sorted
by the number of non-identity terms in the Pauli, where the set of
all Pauli's of a given weight are still ordered lexicographically.
Args:
weight (bool): Optionally sort by weight if True (Default: False).
phase (bool): Optionally sort by phase before weight or order
(Default: False).
Returns:
array: the indices for sorting the table.
"""
# Get order of each Pauli using
# I => 0, X => 1, Y => 2, Z => 3
x = self.x
z = self.z
order = 1 * (x & ~z) + 2 * (x & z) + 3 * (~x & z)
phases = self.phase
# Optionally get the weight of Pauli
# This is the number of non identity terms
if weight:
weights = np.sum(x | z, axis=1)
# To preserve ordering between successive sorts we
# are use the 'stable' sort method
indices = np.arange(self._num_paulis)
# Initial sort by phases
sort_inds = phases.argsort(kind="stable")
indices = indices[sort_inds]
order = order[sort_inds]
if phase:
phases = phases[sort_inds]
if weight:
weights = weights[sort_inds]
# Sort by order
for i in range(self.num_qubits):
sort_inds = order[:, i].argsort(kind="stable")
order = order[sort_inds]
indices = indices[sort_inds]
if weight:
weights = weights[sort_inds]
if phase:
phases = phases[sort_inds]
# If using weights we implement a sort by total number
# of non-identity Paulis
if weight:
sort_inds = weights.argsort(kind="stable")
indices = indices[sort_inds]
phases = phases[sort_inds]
# If sorting by phase we perform a final sort by the phase value
# of each pauli
if phase:
indices = indices[phases.argsort(kind="stable")]
return indices
def sort(self, weight=False, phase=False):
"""Sort the rows of the table.
The default sort method is lexicographic sorting by qubit number.
By using the `weight` kwarg the output can additionally be sorted
by the number of non-identity terms in the Pauli, where the set of
all Pauli's of a given weight are still ordered lexicographically.
**Example**
Consider sorting all a random ordering of all 2-qubit Paulis
.. code-block::
from numpy.random import shuffle
from qiskit.quantum_info.operators import PauliList
# 2-qubit labels
labels = ['II', 'IX', 'IY', 'IZ', 'XI', 'XX', 'XY', 'XZ',
'YI', 'YX', 'YY', 'YZ', 'ZI', 'ZX', 'ZY', 'ZZ']
# Shuffle Labels
shuffle(labels)
pt = PauliList(labels)
print('Initial Ordering')
print(pt)
# Lexicographic Ordering
srt = pt.sort()
print('Lexicographically sorted')
print(srt)
# Weight Ordering
srt = pt.sort(weight=True)
print('Weight sorted')
print(srt)
.. parsed-literal::
Initial Ordering
['YX', 'ZZ', 'XZ', 'YI', 'YZ', 'II', 'XX', 'XI', 'XY', 'YY', 'IX', 'IZ',
'ZY', 'ZI', 'ZX', 'IY']
Lexicographically sorted
['II', 'IX', 'IY', 'IZ', 'XI', 'XX', 'XY', 'XZ', 'YI', 'YX', 'YY', 'YZ',
'ZI', 'ZX', 'ZY', 'ZZ']
Weight sorted
['II', 'IX', 'IY', 'IZ', 'XI', 'YI', 'ZI', 'XX', 'XY', 'XZ', 'YX', 'YY',
'YZ', 'ZX', 'ZY', 'ZZ']
Args:
weight (bool): optionally sort by weight if True (Default: False).
phase (bool): Optionally sort by phase before weight or order
(Default: False).
Returns:
PauliList: a sorted copy of the original table.
"""
return self[self.argsort(weight=weight, phase=phase)]
def unique(self, return_index=False, return_counts=False):
"""Return unique Paulis from the table.
**Example**
.. code-block::
from qiskit.quantum_info.operators import PauliList
pt = PauliList(['X', 'Y', '-X', 'I', 'I', 'Z', 'X', 'iZ'])
unique = pt.unique()
print(unique)
.. parsed-literal::
['X', 'Y', '-X', 'I', 'Z', 'iZ']
Args:
return_index (bool): If True, also return the indices that
result in the unique array.
(Default: False)
return_counts (bool): If True, also return the number of times
each unique item appears in the table.
Returns:
PauliList: unique
the table of the unique rows.
unique_indices: np.ndarray, optional
The indices of the first occurrences of the unique values in
the original array. Only provided if ``return_index`` is True.
unique_counts: np.array, optional
The number of times each of the unique values comes up in the
original array. Only provided if ``return_counts`` is True.
"""
# Check if we need to stack the phase array
if np.any(self._phase != self._phase[0]):
# Create a single array of Pauli's and phases for calling np.unique on
# so that we treat different phased Pauli's as unique
array = np.hstack([self._z, self._x, self.phase.reshape((self.phase.shape[0], 1))])
else:
# All Pauli's have the same phase so we only need to sort the array
array = np.hstack([self._z, self._x])
# Get indexes of unique entries
if return_counts:
_, index, counts = np.unique(array, return_index=True, return_counts=True, axis=0)
else:
_, index = np.unique(array, return_index=True, axis=0)
# Sort the index so we return unique rows in the original array order
sort_inds = index.argsort()
index = index[sort_inds]
unique = PauliList(BasePauli(self._z[index], self._x[index], self._phase[index]))
# Concatinate return tuples
ret = (unique,)
if return_index:
ret += (index,)
if return_counts:
ret += (counts[sort_inds],)
if len(ret) == 1:
return ret[0]
return ret
# ---------------------------------------------------------------------
# BaseOperator methods
# ---------------------------------------------------------------------
def tensor(self, other):
"""Return the tensor product with each Pauli in the list.
Args:
other (PauliList): another PauliList.
Returns:
PauliList: the list of tensor product Paulis.
Raises:
QiskitError: if other cannot be converted to a PauliList, does
not have either 1 or the same number of Paulis as
the current list.
"""
if not isinstance(other, PauliList):
other = PauliList(other)
return PauliList(super().tensor(other))
def expand(self, other):
"""Return the expand product of each Pauli in the list.
Args:
other (PauliList): another PauliList.
Returns:
PauliList: the list of tensor product Paulis.
Raises:
QiskitError: if other cannot be converted to a PauliList, does
not have either 1 or the same number of Paulis as
the current list.
"""
if not isinstance(other, PauliList):
other = PauliList(other)
if len(other) not in [1, len(self)]:
raise QiskitError(
"Incompatible PauliLists. Other list must "
"have either 1 or the same number of Paulis."
)
return PauliList(super().expand(other))
def compose(self, other, qargs=None, front=False, inplace=False):
"""Return the composition self∘other for each Pauli in the list.
Args:
other (PauliList): another PauliList.
qargs (None or list): qubits to apply dot product on (Default: None).
front (bool): If True use `dot` composition method [default: False].
inplace (bool): If True update in-place (default: False).
Returns:
PauliList: the list of composed Paulis.
Raises:
QiskitError: if other cannot be converted to a PauliList, does
not have either 1 or the same number of Paulis as
the current list, or has the wrong number of qubits
for the specified qargs.
"""
if qargs is None:
qargs = getattr(other, "qargs", None)
if not isinstance(other, PauliList):
other = PauliList(other)
if len(other) not in [1, len(self)]:
raise QiskitError(
"Incompatible PauliLists. Other list must "
"have either 1 or the same number of Paulis."
)
return PauliList(super().compose(other, qargs=qargs, front=front, inplace=inplace))
# pylint: disable=arguments-differ
def dot(self, other, qargs=None, inplace=False):
"""Return the composition other∘self for each Pauli in the list.
Args:
other (PauliList): another PauliList.
qargs (None or list): qubits to apply dot product on (Default: None).
inplace (bool): If True update in-place (default: False).
Returns:
PauliList: the list of composed Paulis.
Raises:
QiskitError: if other cannot be converted to a PauliList, does
not have either 1 or the same number of Paulis as
the current list, or has the wrong number of qubits
for the specified qargs.
"""
return self.compose(other, qargs=qargs, front=True, inplace=inplace)
def _add(self, other, qargs=None):
"""Append two PauliLists.
If ``qargs`` are specified the other operator will be added
assuming it is identity on all other subsystems.
Args:
other (PauliList): another table.
qargs (None or list): optional subsystems to add on
(Default: None)
Returns:
PauliList: the concatenated list self + other.
"""
if qargs is None:
qargs = getattr(other, "qargs", None)
if not isinstance(other, PauliList):
other = PauliList(other)
self._op_shape._validate_add(other._op_shape, qargs)
base_phase = np.hstack((self._phase, other._phase))
if qargs is None or (sorted(qargs) == qargs and len(qargs) == self.num_qubits):
base_z = np.vstack([self._z, other._z])
base_x = np.vstack([self._x, other._x])
else:
# Pad other with identity and then add
padded = BasePauli(
np.zeros((other.size, self.num_qubits), dtype=bool),
np.zeros((other.size, self.num_qubits), dtype=bool),
np.zeros(other.size, dtype=int),
)
padded = padded.compose(other, qargs=qargs, inplace=True)
base_z = np.vstack([self._z, padded._z])
base_x = np.vstack([self._x, padded._x])
return PauliList(BasePauli(base_z, base_x, base_phase))
def _multiply(self, other):
"""Multiply each Pauli in the list by a phase.
Args:
other (complex or array): a complex number in [1, -1j, -1, 1j]
Returns:
PauliList: the list of Paulis other * self.
Raises:
QiskitError: if the phase is not in the set [1, -1j, -1, 1j].
"""
return PauliList(super()._multiply(other))
def conjugate(self):
"""Return the conjugate of each Pauli in the list."""
return PauliList(super().conjugate())
def transpose(self):
"""Return the transpose of each Pauli in the list."""
return PauliList(super().transpose())
def adjoint(self):
"""Return the adjoint of each Pauli in the list."""
return PauliList(super().adjoint())
def inverse(self):
"""Return the inverse of each Pauli in the list."""
return PauliList(super().adjoint())
# ---------------------------------------------------------------------
# Utility methods
# ---------------------------------------------------------------------
def commutes(self, other, qargs=None):
"""Return True for each Pauli that commutes with other.
Args:
other (PauliList): another PauliList operator.
qargs (list): qubits to apply dot product on (default: None).
Returns:
bool: True if Pauli's commute, False if they anti-commute.
"""
if qargs is None:
qargs = getattr(other, "qargs", None)
if not isinstance(other, BasePauli):
other = PauliList(other)
return super().commutes(other, qargs=qargs)
def anticommutes(self, other, qargs=None):
"""Return True if other Pauli that anticommutes with other.
Args:
other (PauliList): another PauliList operator.
qargs (list): qubits to apply dot product on (default: None).
Returns:
bool: True if Pauli's anticommute, False if they commute.
"""
return np.logical_not(self.commutes(other, qargs=qargs))
def commutes_with_all(self, other):
"""Return indexes of rows that commute other.
If other is a multi-row Pauli list the returned vector indexes rows
of the current PauliList that commute with *all* Pauli's in other.
If no rows satisfy the condition the returned array will be empty.
Args:
other (PauliList): a single Pauli or multi-row PauliList.
Returns:
array: index array of the commuting rows.
"""
return self._commutes_with_all(other)
def anticommutes_with_all(self, other):
"""Return indexes of rows that commute other.
If other is a multi-row Pauli list the returned vector indexes rows
of the current PauliList that anti-commute with *all* Pauli's in other.
If no rows satisfy the condition the returned array will be empty.
Args:
other (PauliList): a single Pauli or multi-row PauliList.
Returns:
array: index array of the anti-commuting rows.
"""
return self._commutes_with_all(other, anti=True)
def _commutes_with_all(self, other, anti=False):
"""Return row indexes that commute with all rows in another PauliList.
Args:
other (PauliList): a PauliList.
anti (bool): if True return rows that anti-commute, otherwise
return rows that commute (Default: False).
Returns:
array: index array of commuting or anti-commuting row.
"""
if not isinstance(other, PauliList):
other = PauliList(other)
comms = self.commutes(other[0])
(inds,) = np.where(comms == int(not anti))
for pauli in other[1:]:
comms = self[inds].commutes(pauli)
(new_inds,) = np.where(comms == int(not anti))
if new_inds.size == 0:
# No commuting rows
return new_inds
inds = inds[new_inds]
return inds
def evolve(self, other, qargs=None, frame="h"):
r"""Evolve the Pauli by a Clifford.
This returns the Pauli :math:`P^\prime = C.P.C^\dagger`.
By choosing the parameter frame='s', this function returns the Schrödinger evolution of the Pauli
:math:`P^\prime = C.P.C^\dagger`. This option yields a faster calculation.
Args:
other (Pauli or Clifford or QuantumCircuit): The Clifford operator to evolve by.
qargs (list): a list of qubits to apply the Clifford to.
frame (string): 'h' for Heisenberg or 's' for Schrödinger framework.
Returns:
Pauli: the Pauli :math:`C.P.C^\dagger`.
Raises:
QiskitError: if the Clifford number of qubits and qargs don't match.
"""
from qiskit.circuit import Instruction, QuantumCircuit
from qiskit.quantum_info.operators.symplectic.clifford import Clifford
if qargs is None:
qargs = getattr(other, "qargs", None)
if not isinstance(other, (BasePauli, Instruction, QuantumCircuit, Clifford)):
# Convert to a PauliList
other = PauliList(other)
return PauliList(super().evolve(other, qargs=qargs, frame=frame))
def to_labels(self, array=False):
r"""Convert a PauliList to a list Pauli string labels.
For large PauliLists converting using the ``array=True``
kwarg will be more efficient since it allocates memory for
the full Numpy array of labels in advance.
.. list-table:: Pauli Representations
:header-rows: 1
* - Label
- Symplectic
- Matrix
* - ``"I"``
- :math:`[0, 0]`
- :math:`\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}`
* - ``"X"``
- :math:`[1, 0]`
- :math:`\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}`
* - ``"Y"``
- :math:`[1, 1]`
- :math:`\begin{bmatrix} 0 & -i \\ i & 0 \end{bmatrix}`
* - ``"Z"``
- :math:`[0, 1]`
- :math:`\begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}`
Args:
array (bool): return a Numpy array if True, otherwise
return a list (Default: False).
Returns:
list or array: The rows of the PauliList in label form.
"""
if (self.phase == 1).any():
prefix_len = 2
elif (self.phase > 0).any():
prefix_len = 1
else:
prefix_len = 0
str_len = self.num_qubits + prefix_len
ret = np.zeros(self.size, dtype=f"<U{str_len}")
iterator = self.label_iter()
for i in range(self.size):
ret[i] = next(iterator)
if array:
return ret
return ret.tolist()
def to_matrix(self, sparse=False, array=False):
r"""Convert to a list or array of Pauli matrices.
For large PauliLists converting using the ``array=True``
kwarg will be more efficient since it allocates memory a full
rank-3 Numpy array of matrices in advance.
.. list-table:: Pauli Representations
:header-rows: 1
* - Label
- Symplectic
- Matrix
* - ``"I"``
- :math:`[0, 0]`
- :math:`\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}`
* - ``"X"``
- :math:`[1, 0]`
- :math:`\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}`
* - ``"Y"``
- :math:`[1, 1]`
- :math:`\begin{bmatrix} 0 & -i \\ i & 0 \end{bmatrix}`
* - ``"Z"``