-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathpaulimer.pyi
More file actions
1798 lines (1475 loc) · 59.6 KB
/
Copy pathpaulimer.pyi
File metadata and controls
1798 lines (1475 loc) · 59.6 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
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
from enum import IntEnum
from typing import (
Literal,
final,
Optional,
Any,
Iterable,
Protocol,
Sequence,
overload,
)
from binar import BitMatrix, BitVector
PauliCharacter = Literal["I", "X", "Y", "Z"]
XOrZ = Literal["X", "Z"]
Exponent = int
__all__ = [
"CliffordUnitary",
"DensePauli",
"FaultySimulation",
"FramePropagator",
"OutcomeCompleteSimulation",
"OutcomeCondition",
"OutcomeFreeSimulation",
"OutcomeSpecificSimulation",
"PauliDistribution",
"PauliFault",
"PauliGroup",
"SparsePauli",
"UnitaryOpcode",
"centralizer_of",
"encoding_clifford_of",
"is_diagonal_resource_encoder",
"split_phased_css",
"split_qubit_cliffords_and_css",
"symplectic_form_of",
"unitary_from_diagonal_resource_state",
]
@final
class UnitaryOpcode(IntEnum):
"""Enum of standard Clifford gates and operations.
Opcodes represent common single and two-qubit Clifford gates used in
quantum circuits. Use with CliffordUnitary.from_name() or simulation
methods like apply_unitary().
Examples:
>>> UnitaryOpcode.Hadamard
>>> UnitaryOpcode.ControlledX # CNOT gate
"""
I = 0
X = 1
Y = 2
Z = 3
SqrtX = 4
SqrtXInv = 5
SqrtY = 6
SqrtYInv = 7
SqrtZ = 8
SqrtZInv = 9
Hadamard = 10
Swap = 11
ControlledX = 12
ControlledZ = 13
PrepareBell = 14
def __str__(self) -> str: ...
def __repr__(self) -> str: ...
@staticmethod
def from_string(s: str) -> "UnitaryOpcode": ...
@final
class DensePauli:
"""Dense representation of a Pauli operator on a fixed number of qubits.
Stores a Pauli operator as a dense string of characters (e.g., "IXYZ") with
an associated phase. Efficient for dense operators or when qubit count is fixed.
Phase convention: Pauli operators are represented as exp(iπ*exponent/4) * P
where P is a tensor product of X, Y, Z operators.
Examples:
>>> p = DensePauli("XYZ")
>>> p.weight
3
>>> p * DensePauli("YXI")
DensePauli("ZZZ")
"""
def __new__(cls, characters: str = "") -> "DensePauli":
"""Create a DensePauli from a character string.
Args:
characters: String of Pauli characters (I, X, Y, Z), optionally
prefixed with phase (1, i, -1, -i).
Examples:
>>> DensePauli("XYZ")
>>> DensePauli("iXYZ") # Phase i
>>> DensePauli("-XYZ") # Phase -1
"""
...
@staticmethod
def identity(size: int) -> "DensePauli":
"""Create the identity operator on `size` qubits."""
...
@staticmethod
def x(qubit_id: int, qubit_count: int) -> "DensePauli":
"""Create an X operator at position `qubit_id` on `qubit_count` qubits."""
...
@staticmethod
def y(qubit_id: int, qubit_count: int) -> "DensePauli":
"""Create a Y operator at position `qubit_id` on `qubit_count` qubits."""
...
@staticmethod
def z(qubit_id: int, qubit_count: int) -> "DensePauli":
"""Create a Z operator at position `qubit_id` on `qubit_count` qubits."""
...
@staticmethod
def from_sparse(pauli: "SparsePauli", qubit_count: int) -> "DensePauli":
"""Convert a SparsePauli to DensePauli on `qubit_count` qubits."""
...
@property
def exponent(self) -> Exponent:
"""The value of `exponent`, when `self` is written in the form e**(iπ * exponent / 4) XᵃZᵇ."""
...
@property
def phase(self) -> complex:
"""The complex phase of `self` when written in tensor product form e**(iπθ) P₁⊗P₂..., i.e., one of {1, i, -1, -i}."""
...
@property
def characters(self) -> str:
"""String representation without phase (e.g., \"IXYZ\")."""
...
@property
def support(self) -> list[int]:
"""Indices of non-identity Pauli operators."""
...
@property
def weight(self) -> int:
"""Number of non-identity Pauli operators."""
...
@property
def size(self) -> int:
"""Total number of qubits."""
...
def commutes_with(self, others: "DensePauli" | Iterable["DensePauli"]) -> bool:
"""Check if this operator commutes with another or collection of operators.
Args:
others: Single DensePauli or iterable of DensePauli operators.
Returns:
True if all operators commute with self.
"""
...
def indexed_anti_commutators_of(self, others: Iterable["DensePauli"]) -> list[int]:
"""Return the indices of operators in ``others`` that anticommute with this operator.
Args:
others: An iterable of Pauli operators to test against.
Returns:
A list of integer indices into ``others`` for operators that
anticommute with this operator.
"""
...
def indexed_commutators_of(self, others: Iterable["DensePauli"]) -> list[int]:
"""Return the indices of operators in ``others`` that commute with this operator.
Args:
others: An iterable of Pauli operators to test against.
Returns:
A list of integer indices into ``others`` for operators that
commute with this operator.
"""
...
def copy(self) -> "DensePauli": ...
def __eq__(self, other: object, /) -> bool: ...
def __ne__(self, other: object, /) -> bool: ...
def __mul__(self, other: "DensePauli", /) -> "DensePauli": ...
def __imul__(self, other: "DensePauli", /) -> "DensePauli": ...
def __add__(self, other: "DensePauli", /) -> "DensePauli": ...
def __abs__(self) -> "DensePauli": ...
def __neg__(self) -> "DensePauli": ...
def __getitem__(self, index: int, /) -> PauliCharacter: ...
def __str__(self) -> str: ...
def __repr__(self) -> str: ...
def __format__(self, format_spec: str, /) -> str: ...
def __getstate__(self) -> tuple: ...
def __setstate__(self, state: tuple) -> None: ...
@final
class SparsePauli:
"""Sparse representation of a Pauli operator.
Stores only the non-identity Pauli operators with their qubit indices.
Efficient for operators with small weight, especially in large systems.
Phase convention: Same as DensePauli - exp(iπ*exponent/4) * P.
Examples:
>>> p = SparsePauli("X2 Z5") # X on qubit 2, Z on qubit 5
>>> p.support
[2, 5]
>>> SparsePauli({2: "X", 5: "Z"}) # Dict constructor
"""
def __new__(
cls,
characters: str | dict[int, PauliCharacter] | None = None,
exponent: Exponent = 0,
) -> "SparsePauli":
"""Create a SparsePauli from a string or dict.
Args:
characters: String like \"X2 Z5\" or dict like {0: \"X\", 3: \"Z\"}, or None for identity.
exponent: Phase exponent (0, 1, 2, 3 for phases 1, i, -1, -i).
Examples:
>>> SparsePauli("X0 Z5")
>>> SparsePauli({2: "X", 5: "Z"})
>>> SparsePauli() # identity
"""
...
@staticmethod
def identity() -> "SparsePauli":
"""Create the identity operator."""
...
@staticmethod
def from_string(characters: str) -> "SparsePauli":
"""Create from a string like \"X0 Z5\"."""
...
@staticmethod
def x(qubit_id: int) -> "SparsePauli":
"""Create an X operator at the given qubit index."""
...
@staticmethod
def y(qubit_id: int) -> "SparsePauli":
"""Create a Y operator at the given qubit index."""
...
@staticmethod
def z(qubit_id: int) -> "SparsePauli":
"""Create a Z operator at the given qubit index."""
...
@staticmethod
def from_dense(dense_pauli: DensePauli) -> "SparsePauli":
"""Convert a DensePauli to SparsePauli (drops trailing identities)."""
...
@property
def exponent(self) -> Exponent:
"""Phase exponent where phase = exp(iπ*exponent/4)."""
...
@property
def phase(self) -> complex:
"""Complex phase (one of 1, i, -1, -i)."""
...
@property
def support(self) -> list[int]:
"""List of qubit indices with non-identity operators."""
...
@property
def characters(self) -> str:
"""String representation without phase."""
...
@property
def weight(self) -> int:
"""Number of non-identity operators."""
...
def commutes_with(self, others: "SparsePauli" | Iterable["SparsePauli"]) -> bool:
"""Check if this operator commutes with another or collection of operators."""
...
def indexed_anti_commutators_of(self, others: Iterable["SparsePauli"]) -> list[int]:
"""Return the indices of operators in ``others`` that anticommute with this operator.
Args:
others: An iterable of Pauli operators to test against.
Returns:
A list of integer indices into ``others`` for operators that
anticommute with this operator.
"""
...
def indexed_commutators_of(self, others: Iterable["SparsePauli"]) -> list[int]:
"""Return the indices of operators in ``others`` that commute with this operator.
Args:
others: An iterable of Pauli operators to test against.
Returns:
A list of integer indices into ``others`` for operators that
commute with this operator.
"""
...
def copy(self) -> "SparsePauli": ...
def __eq__(self, other: object, /) -> bool: ...
def __ne__(self, other: object, /) -> bool: ...
def __hash__(self) -> int: ...
def __mul__(self, other: "SparsePauli", /) -> "SparsePauli": ...
def __imul__(self, other: "SparsePauli", /) -> "SparsePauli": ...
def __abs__(self) -> "SparsePauli": ...
def __neg__(self) -> "SparsePauli": ...
def __getitem__(self, index: int, /) -> PauliCharacter: ...
def __str__(self) -> str: ...
def __repr__(self) -> str: ...
def __format__(self, format_spec: str, /) -> str: ...
def __getstate__(self) -> tuple: ...
def __setstate__(self, state: tuple) -> None: ...
@final
class PauliGroup:
"""Group of Pauli operators generated by a set of generators.
Represents a subgroup of the Pauli group, useful for stabilizer codes,
normalizer computations, and group-theoretic analysis.
Examples:
>>> g1 = SparsePauli("X_0 X_1")
>>> g2 = SparsePauli("Z_0 Z_1")
>>> group = PauliGroup([g1, g2])
>>> SparsePauli("X_0 X_1") in group
True
"""
def __new__(
cls,
generators: Iterable[SparsePauli],
all_commute: Optional[bool] = None,
) -> "PauliGroup":
"""Create a Pauli group from generators.
Args:
generators: Iterable of SparsePauli generators.
all_commute: Hint whether all generators commute (optional optimization).
"""
...
def factorization_of(self, element: SparsePauli) -> Optional[list[SparsePauli]]: ...
def factorizations_of(
self, elements: Iterable[SparsePauli]
) -> list[Optional[list[SparsePauli]]]: ...
def indexed_factorization_of(
self, element: SparsePauli
) -> Optional[tuple[list[int], Exponent]]: ...
def indexed_factorizations_of(
self, elements: Iterable[SparsePauli]
) -> list[Optional[tuple[list[int], Exponent]]]: ...
def __contains__(self, element: SparsePauli, /) -> bool: ...
def __eq__(self, other: Any, /) -> bool: ...
def __str__(self) -> str: ...
def __repr__(self) -> str: ...
def __le__(self, other: "PauliGroup", /) -> bool: ...
def __lt__(self, other: "PauliGroup", /) -> bool: ...
def __or__(self, other: "PauliGroup", /) -> "PauliGroup": ...
def __and__(self, other: "PauliGroup", /) -> "PauliGroup": ...
def __truediv__(self, other: "PauliGroup", /) -> "PauliGroup": ...
def __mod__(self, other: "PauliGroup", /) -> "PauliGroup":
"""Compute coset representatives of this group modulo another group.
Returns a group representing distinct cosets of `other` within `self`.
This operation reduces generators by eliminating components expressible
using elements from `other`. The `other` group does not need to be a
subgroup of `self`.
Args:
other: The group to compute coset representatives modulo.
Returns:
A new PauliGroup representing coset representatives.
Example:
>>> group = PauliGroup([SparsePauli("XX"), SparsePauli("ZZ")])
>>> divisor = PauliGroup([SparsePauli("ZZ")])
>>> remainder = group % divisor
>>> remainder.log2_size
1
"""
...
def __getstate__(self) -> tuple: ...
def __setstate__(self, state: tuple) -> None: ...
@property
def generators(self) -> list[SparsePauli]:
"""The set of generators."""
...
@property
def standard_generators(self) -> list[SparsePauli]:
"""Standard form generators (reduced form)."""
...
@property
def elements(self) -> Iterable[SparsePauli]:
"""Iterator over all group elements (may be large!)."""
...
@property
def phases(self) -> list[Exponent]:
"""Pure phases contained in the group."""
...
@property
def binary_rank(self) -> int:
"""Rank of the group's binary representation."""
...
@property
def support(self) -> list[int]:
"""Qubit indices touched by any generator."""
...
@property
def log2_size(self) -> int:
"""Log base 2 of the group size (number of independent generators)."""
...
@property
def is_abelian(self) -> bool:
"""True if all generators commute."""
...
@property
def is_stabilizer_group(self) -> bool:
"""True if this is a valid stabilizer group (abelian, no -I)."""
...
def centralizer_of(
group: PauliGroup, supported_by: Optional[Iterable[int]] = None
) -> PauliGroup:
"""Compute the centralizer of a Pauli group.
Args:
group: PauliGroup to centralize.
supported_by: Optional restriction to specific qubits.
Returns:
PauliGroup of operators that commute with all elements of group.
"""
...
def symplectic_form_of(generators: Iterable[SparsePauli]) -> Iterable[SparsePauli]:
"""Compute symplectic form of a set of Pauli operators.
Returns:
Canonicalized generators in symplectic form.
"""
...
@final
class CliffordUnitary:
"""Clifford unitary operator on qubits.
Represents a unitary in the Clifford group, stored as mappings of
Pauli operators (by conjugation). Efficient for stabilizer simulation
and circuit synthesis.
Examples:
>>> h = CliffordUnitary.from_name("Hadamard", [0], 1)
>>> h.image_x(0)
DensePauli("Z")
>>> cnot = CliffordUnitary.from_name("ControlledX", [0, 1], 2)
"""
@staticmethod
def from_string(characters: str) -> "CliffordUnitary":
"""Create from string representation.
For example, creates one qubit Hadamard from string \"X_0:Z_0, Z_0:X_0\".
"""
...
@staticmethod
def from_preimages(preimages: Sequence[DensePauli]) -> "CliffordUnitary":
"""Create from preimages of the X and Z generators.
Args:
preimages: Sequence of Pauli operators [X_0', ..., X_{n-1}', Z_0', ..., Z_{n-1}'].
"""
...
@staticmethod
def from_images(images: Sequence[DensePauli]) -> "CliffordUnitary":
"""Create from images of the X and Z generators.
Args:
images: Sequence of Pauli operators [X_0, ..., X_{n-1}, Z_0, ..., Z_{n-1}].
"""
...
@staticmethod
def from_name(
unitary_op: str, qubits: Sequence[int], qubit_count: int
) -> "CliffordUnitary":
"""Create a named gate.
Args:
unitary_op: Gate name (e.g., \"Hadamard\", \"ControlledX\", \"SqrtZ\").
qubits: Qubit indices.
qubit_count: Total number of qubits.
"""
...
@staticmethod
def identity(num_qubits: int) -> "CliffordUnitary":
"""Create the identity on `num_qubits` qubits."""
...
@staticmethod
def zero(num_qubits: int) -> "CliffordUnitary":
"""Create a zero Clifford on `num_qubits` qubits."""
...
@staticmethod
def group_encoding_clifford_of(
generators: Sequence[SparsePauli], qubit_count: int
) -> "CliffordUnitary":
"""Construct encoding Clifford from stabilizer generators.
Args:
generators: Stabilizer generators.
qubit_count: Total number of qubits.
Returns:
Clifford unitary that maps logical Paulis to given generators.
"""
...
@property
def is_css(self) -> bool:
"""True if this is a CSS (Calderbank-Shor-Steane) code unitary."""
...
@property
def qubit_count(self) -> int:
"""Number of qubits."""
...
@property
def is_valid(self) -> bool:
"""True if the internal representation is valid."""
...
@property
def is_identity(self) -> bool:
"""True if this is the identity operator."""
...
@property
def symplectic_matrix(self) -> BitMatrix:
"""Get the symplectic matrix representation."""
...
def qubits(self) -> slice:
"""Return a slice representing the qubit indices."""
...
def preimage_of(self, pauli: DensePauli | SparsePauli) -> DensePauli:
"""Compute U^† P U for a Pauli operator P."""
...
def preimage_x(self, qubit_index: int) -> DensePauli:
"""Preimage of X_i."""
...
def preimage_z(self, qubit_index: int) -> DensePauli:
"""Preimage of Z_i."""
...
def image_of(self, pauli: DensePauli | SparsePauli) -> DensePauli:
"""Compute U P U^† for a Pauli operator P."""
...
def image_x(self, qubit_index: int) -> DensePauli:
"""Image of X_i."""
...
def image_z(self, qubit_index: int) -> DensePauli:
"""Image of Z_i."""
...
def tensor(self, rhs: "CliffordUnitary") -> "CliffordUnitary":
"""Tensor product with another Clifford unitary."""
...
def inverse(self) -> "CliffordUnitary":
"""Compute the inverse."""
...
def is_diagonal(self, axis: XOrZ) -> bool:
"""Check if diagonal in the given axis basis."""
...
def is_diagonal_resource_encoder(self, axis: XOrZ) -> bool:
"""Check if this Clifford encodes a diagonal resource state."""
...
def unitary_from_diagonal_resource_state(
self, axis: XOrZ
) -> "CliffordUnitary" | None:
"""Extract unitary from a diagonal resource state encoder."""
...
def split_qubit_cliffords_and_css(
self,
) -> tuple["CliffordUnitary", "CliffordUnitary"] | None:
"""Split into single-qubit Cliffords and CSS components."""
...
def split_phased_css(
self,
) -> tuple["CliffordUnitary", "CliffordUnitary"] | None:
"""Split into phased CSS components."""
...
def __mul__(self, other: "CliffordUnitary", /) -> "CliffordUnitary": ...
def left_mul(self, unitary_op: UnitaryOpcode, support: Sequence[int]) -> None: ...
def left_mul_clifford(
self, clifford: "CliffordUnitary", support: Sequence[int]
) -> None: ...
def left_mul_permutation(
self, permutation: Sequence[int], support: Sequence[int]
) -> None: ...
def left_mul_pauli(self, pauli: DensePauli | SparsePauli) -> None: ...
def left_mul_pauli_exp(self, pauli: DensePauli | SparsePauli) -> None: ...
def left_mul_controlled_pauli(
self, control: DensePauli | SparsePauli, target: DensePauli | SparsePauli
) -> None: ...
def __pow__(self, exponent: int, mod: None = None, /) -> "CliffordUnitary": ...
def __eq__(self, other: object, /) -> bool: ...
def __ne__(self, other: object, /) -> bool: ...
def __str__(self) -> str: ...
def __repr__(self) -> str: ...
def __format__(self, format_spec: str, /) -> str: ...
def __getstate__(self) -> tuple: ...
def __setstate__(self, state: tuple) -> None: ...
def is_diagonal_resource_encoder(
clifford: CliffordUnitary, axis: XOrZ
) -> bool:
"""Check if a Clifford encodes a diagonal resource state."""
...
def unitary_from_diagonal_resource_state(
clifford: CliffordUnitary, axis: XOrZ
) -> "CliffordUnitary" | None:
"""Extract unitary from a diagonal resource state encoder."""
...
def split_qubit_cliffords_and_css(
clifford: CliffordUnitary,
) -> tuple["CliffordUnitary", "CliffordUnitary"] | None:
"""Split into single-qubit Cliffords and CSS components."""
...
def split_phased_css(
clifford: CliffordUnitary,
) -> tuple["CliffordUnitary", "CliffordUnitary"] | None:
"""Split into phased CSS components."""
...
def encoding_clifford_of(
generators: Sequence[SparsePauli | DensePauli], qubit_count: int
) -> "CliffordUnitary":
"""Construct encoding Clifford from stabilizer generators.
Args:
generators: Stabilizer generators.
qubit_count: Total number of qubits.
Returns:
Clifford unitary that maps logical Paulis to given generators.
"""
...
class StabilizerSimulation(Protocol):
"""Protocol for stabilizer simulation.
Defines the common interface implemented by OutcomeCompleteSimulation,
OutcomeFreeSimulation, OutcomeSpecificSimulation, and FaultySimulation.
"""
@property
def qubit_count(self) -> int:
"""Maximum number of qubits in the simulation."""
...
@property
def qubit_capacity(self) -> int:
"""The number of qubits allowed before reallocation is necessary."""
...
@property
def outcome_count(self) -> int:
"""Number of measurement outcomes recorded."""
...
@property
def outcome_capacity(self) -> int:
"""The number of measurement outcomes allowed before reallocation is necessary."""
...
@property
def random_outcome_count(self) -> int:
"""Number of random outcome bits."""
...
@property
def random_outcome_capacity(self) -> int:
"""The number of random outcome bits allowed before reallocation is necessary."""
...
@property
def random_bit_count(self) -> int:
"""Number of random bits involved in the simulation, including both random outcomes
and caller supplied random bits."""
...
def apply_unitary(self, unitary_op: UnitaryOpcode, support: Sequence[int]) -> None:
"""Apply a Clifford unitary to specified qubits.
Args:
unitary_op: Gate opcode (e.g., UnitaryOpcode.Hadamard, UnitaryOpcode.ControlledX).
support: Qubit indices where the gate acts.
"""
...
def apply_pauli_exp(self, observable: SparsePauli) -> None:
"""Apply exp(iπ/4 * P) for a Pauli observable P.
Args:
observable: Pauli operator to exponentiate.
"""
...
def apply_pauli(
self, observable: SparsePauli, controlled_by: SparsePauli | None = None
) -> None:
"""Apply a Pauli operator, optionally controlled by another Pauli.
Args:
observable: Pauli operator to apply.
controlled_by: Optional control Pauli (gate applies when control eigenvalue is +1).
"""
...
def apply_conditional_pauli(
self,
observable: SparsePauli,
outcomes: Sequence[int],
parity: bool = True,
) -> None:
"""Apply a Pauli conditioned on measurement outcome parity.
Args:
observable: Pauli operator to apply.
outcomes: Measurement outcome indices to check.
parity: If True, apply when XOR of outcomes is 1; if False, when 0.
"""
...
def apply_permutation(
self, permutation: Sequence[int], supported_by: Sequence[int] | None = None
) -> None:
"""Apply a qubit permutation.
Args:
permutation: Mapping where qubit i goes to position permutation[i].
supported_by: Qubit indices to permute (None means all qubits).
"""
...
def apply_clifford(
self, clifford: CliffordUnitary, supported_by: Sequence[int] | None = None
) -> None:
"""Apply an arbitrary Clifford unitary.
Args:
clifford: Clifford unitary to apply.
supported_by: Qubit indices where the Clifford acts (None infers from clifford.qubit_count).
"""
...
def measure(self, observable: SparsePauli, hint: SparsePauli | None = None) -> int:
"""Measure a Pauli observable, recording the outcome.
Args:
observable: Pauli observable to measure.
hint: Optional anticommuting Pauli to guide simulation (performance optimization).
Returns:
The index of the recorded measurement outcome.
"""
...
def allocate_random_bit(self) -> int:
"""Allocate a random outcome bit, returns its index."""
...
def reserve_qubits(self, new_qubit_capacity: int) -> None:
"""Pre-allocate capacity for qubits to avoid reallocation."""
...
def reserve_outcomes(
self, new_outcome_capacity: int, new_random_outcome_capacity: int
) -> None:
"""Pre-allocate capacity for measurement outcomes."""
...
def is_stabilizer(
self,
observable: SparsePauli,
ignore_sign: bool = False,
sign_parity: Sequence[int] = ..., # type: ignore[assignment]
) -> bool:
"""Check if an observable is in the stabilizer group of current state.
Args:
observable: Pauli to check.
ignore_sign: If True, check if ±observable is a stabilizer.
sign_parity: Outcome indices affecting the sign.
Returns:
True if observable stabilizes the state.
"""
...
@final
class OutcomeCompleteSimulation:
"""Asymptotically efficient stabilizer simulation tracking all measurement outcomes.
Instead of running separate simulations for each possible measurement outcome,
this simulator tracks all 2^n_random outcome branches simultaneously, where n_random
is the number of random measurements. This provides an asymptotic improvement over
outcome-specific simulation for many use cases.
Use Cases:
- **Exhaustive enumeration**: Compute quantities over all possible outcomes
- **Exact probability distributions**: Calculate measurement statistics without sampling
- **Circuit verification**: Analyze complete behavior across all measurement branches
- **Outcome codes**: Study encoding/decoding that depends on measurement outcomes
Performance:
- Complexity: O(n_gates × n_qubits²) worst-case, like other simulators
- Key advantage: Simulate once, then sample any number of shots efficiently
- Compared to OutcomeSpecific: Saves a factor of n_random when collecting many samples
- Space: O(n_qubits² + n_random²) for sign and outcome matrices
The simulation cost is linear in n_random, not exponential. The 2^n_random outcomes
are represented compactly and can be sampled efficiently.
Examples:
>>> sim = OutcomeCompleteSimulation(3)
>>> sim.apply_unitary(UnitaryOpcode.Hadamard, [0])
>>> sim.apply_unitary(UnitaryOpcode.ControlledX, [0, 1])
>>> sim.measure(SparsePauli("Z_0"))
>>> # All 2^n_random branches tracked without separate simulation runs
>>> num_branches = 1 << sim.random_outcome_count
"""
def __new__(cls, qubit_count: int = 0) -> "OutcomeCompleteSimulation":
"""Create a simulation with the specified number of qubits."""
...
@property
def qubit_count(self) -> int: ...
@property
def qubit_capacity(self) -> int: ...
@property
def outcome_count(self) -> int: ...
@property
def outcome_capacity(self) -> int: ...
@property
def random_outcome_count(self) -> int: ...
@property
def random_outcome_capacity(self) -> int: ...
@property
def random_bit_count(self) -> int: ...
def apply_unitary(
self, unitary_op: UnitaryOpcode, support: Sequence[int]
) -> None: ...
def apply_pauli_exp(self, observable: SparsePauli) -> None: ...
def apply_pauli(
self, observable: SparsePauli, controlled_by: SparsePauli | None = None
) -> None: ...
def apply_conditional_pauli(
self,
observable: SparsePauli,
outcomes: Sequence[int],
parity: bool = True,
) -> None: ...
def apply_permutation(
self, permutation: Sequence[int], supported_by: Sequence[int] | None = None
) -> None: ...
def apply_clifford(
self, clifford: CliffordUnitary, supported_by: Sequence[int] | None = None
) -> None: ...
def measure(
self, observable: SparsePauli, hint: SparsePauli | None = None
) -> int: ...
def allocate_random_bit(self) -> int: ...
def reserve_qubits(self, new_qubit_capacity: int) -> None: ...
def reserve_outcomes(
self, new_outcome_capacity: int, new_random_outcome_capacity: int
) -> None: ...
def is_stabilizer(
self,
observable: SparsePauli,
ignore_sign: bool = False,
sign_parity: Sequence[int] = ..., # type: ignore[assignment]
) -> bool:
"""Check if an observable is a stabilizer of the current state.
Args:
observable: Pauli to check.
ignore_sign: If True, check if ±observable is a stabilizer.
sign_parity: Outcome indices affecting the sign (for outcome-dependent stabilizers).
Returns:
True if observable stabilizes the state.
"""
...
@staticmethod
def with_capacity(
num_qubits: int, num_outcomes: int, num_random_outcomes: int
) -> "OutcomeCompleteSimulation":
"""Create simulation with pre-allocated capacity.
Args:
num_qubits: Initial qubit capacity.
num_outcomes: Initial outcome capacity.
num_random_outcomes: Initial random outcome capacity.
Returns:
New simulation with reserved capacity to avoid reallocations.
"""
...
@property
def random_outcome_indicator(self) -> BitVector:
"""Indicator of which outcomes are random (vs deterministic)."""
...
@property
def clifford(self) -> CliffordUnitary:
"""Clifford unitary encoding the current stabilizer state."""
...
@property
def sign_matrix(self) -> BitMatrix:
"""Sign matrix A encoding how Pauli signs depend on random outcomes.
The sign of stabilizer generator Z_i is determined by the sign parity:
sign_parity_i = A[i, :] · r
where r is the vector of random bit assignments (0 or 1 for each random outcome),
and · denotes the dot product over GF(2) (XOR). If sign_parity_i = 1, the
stabilizer has a minus sign; if 0, it's positive.
Shape: (qubit_count, random_outcome_count)
"""
...
@property
def outcome_matrix(self) -> BitMatrix:
"""Outcome matrix M encoding all 2^k measurement branches.