-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathCSSLO.py
More file actions
1338 lines (1210 loc) · 45.5 KB
/
CSSLO.py
File metadata and controls
1338 lines (1210 loc) · 45.5 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
import itertools as iter
from common import *
from NHow import *
from code_library import *
from distance import *
from XCP_algebra import *
##########################################
## CSS Codes
##########################################
def CSSCode(SX,LX=None,SZ=None,LZ=None,simplifyGens=False):
"""Create CSS code from various input types.
Keyword arguments:
SX -- X-checks
LX -- X-logicals (optional)
SZ -- Z-checks (optional)
LZ -- Z-logicals (optional)
SimplifyGens -- return generators and logical Paulis in RREF/simplified form
Default is to give values for SX and LX, then calculate SZ and LZ.
Can take either text or arrays as input.
Returns SX,LX,SZ,LZ.
"""
SX = bin2ZMat(SX)
LX = bin2ZMat(LX)
SZ = bin2ZMat(SZ)
## find n - number of qubits
n = np.max([0 if A is None else A.shape[1] for A in [SX,LX,SZ]])
SX = ZMatZeros((0,n)) if SX is None else ZMat(SX,n)
## Input is SX, SZ
if LX is None:
## SZ could be None - handle this case
SZ = ZMatZeros((0,n)) if SZ is None else ZMat(SZ,n)
## Calculate LX from SX, SZ
LX = CSSgetLX(SX,SZ)
## Input is SX, LX
elif SZ is None:
LX = ZMatZeros((0,n)) if LX is None else ZMat(LX,n)
## Calculate SZ from SX, LX
SZ = getK(np.vstack([SX,LX]),2)
## Find LZ
if LZ is None:
LZ = getK(SX,2)
## canonical form of LX - LX LZ^T = I_k
LZ,lx = LXZDiag(LZ,LX)
SZ = ZMat(SZ,n)
LZ = ZMat(LZ,n)
LX = ZMat(LX,n)
if simplifyGens:
SX = indepLZ(None,SX)
LX = indepLZ(SX, LX)
SZ = indepLZ(None,SZ)
LZ = indepLZ(SZ, LZ)
return SX,LX,SZ,LZ
def CSSgetLX(SX, SZ):
"""Get LX for CSS code with check matrices SX, SZ."""
SXLX = getK(SZ,2)
R, V = HowRes(SX,SXLX,2)
LX = getH(R,2)
return LX
def LXZCanonical(LX, LZ):
"""Modify LX, LZ such that LX LZ^T = I if possible."""
LX, LZ = LXZDiag(LX,LZ)
LZ, LX = LXZDiag(LZ,LX)
return LX, LZ
def LXZDiag(LX,LZ):
"""Convert LX to a form with minimal overlap with LZ. helper for LXZCanonical"""
r, n = LZ.shape
A = np.hstack([matMul(LX, LZ.T,2),LX])
## RREF of first r columns
A = getH(A,2,r)
## updated LX is last r columns
LX = A[:r,r:]
return LX, LZ
#####################################################
## Non-CSS codes
#####################################################
def XZ2LF(S):
'''Return canonical binary linear form of a non-CSS code
S: stabiliser generators
CE: binary linear code
D: symmetric matrix rep S and CZ operators
A: binary matrix rep CZ
'''
N=2
tB = 2
m,n = S.shape
nB = n//tB
## Form RREF and find leading indices of X-components
S,LiX = getH(S,N,nC=nB,retPivots=True)
## Move leading indices to left
r = len(LiX)
ix = np.hstack([LiX, invRange(nB,LiX)])
S = ZMatPermuteCols(S,ix,tB=tB)
## Apply Hadamard to all qubits to right of LiX
S = XZhad(S,np.arange(r,nB))
## Form RREF and find leading indices of Z-components
S,LiZ = getH(S,N,retPivots=True)
## move leading indices of Sx and Sz to left
s = len(LiZ) - len(LiX)
k = nB - r - s
ix2 = np.hstack([LiZ, invRange(nB,LiZ)])
S = ZMatPermuteCols(S,ix2,tB=tB)
## update permutation
ix = ix[ix2]
## Canonical matrices
Sx, Sz = S[:,:nB],S[:,nB:]
## find Symmetric matrix D
B = Sz[:r,:r]
C = Sx[:r,nB-k:]
A2 = Sz[:r,nB-k:]
# D = np.mod(B + C @ A2.T, 2)
D = matMul(C,A2.T,2 ) ^ B
CE = Sx[:,nB-k:]
A = Sz[:r,r:]
return CE, A, D, ixRev(ix)
def LF2XZ(CE,A,S,ix=None):
'''Generate stabiliser code from Binary Linear form:
CE: an (r+s) x s binary matrix representing a binary linear code
A: an r x (s+k) binary matrix representing CZ operators
S: an r x r symmetric binary matrix representing S and CZ operators
ix: a permutation of the qubits'''
tB = 2
## number of X-gens r, Z-gens s and logical qubits k
r,sk = np.shape(A)
rs,k = np.shape(CE)
s = rs-r
n = r + s + k
## form X-components Sx = (I | CE) - binary linear code
Sx = np.hstack([ZMatI(rs),CE])
## form symmetric binary matrix representing applictaion of CZ and S operators
D1 = np.hstack([S,A])
D2 = np.hstack([A.T,ZMatZeros((sk,sk))])
D = np.vstack([D1,D2])
## Generate Z-components Sz
Sz = matMul(Sx, D, 2)
## Apply Had to last s + k qubits (swap X and Z components)
S = np.hstack([Sx,Sz],dtype=np.int16)
S = XZhad(S,np.arange(r,n,dtype=int))
A2 = A[:,s:]
Lz = np.hstack([ZMatZeros((k,n)),A2.T,ZMatZeros((k,s)),ZMatI(k)])
E = CE[r:,:]
C = CE[:r,:]
Lx = np.hstack([ZMatZeros((k,r)),E.T,ZMatI(k),C.T,ZMatZeros((k,s+k))])
## Apply permutation of columns
if ix is not None:
return ZMatPermuteCols(S,ix,tB=tB),ZMatPermuteCols(Lx,ix,tB=tB),ZMatPermuteCols(Lz,ix,tB=tB)
else:
return S, Lx, Lz
def bin2XZ(n,k,r,x,Sdiag=True):
'''Convert binary vector x to non-CSS [[n,k]] code with r independent X stabilisers'''
Dbits = r*(r+1)//2 if Sdiag else r*(r-1)//2
Abits = r*(n-r)
Lbits = (n-k) * k
d = Dbits+Abits+Lbits
if typeName(x)[:3] == "int":
x = int2bin(x,d)
x = np.array(x,dtype=np.int16)
D = makeSymmetricMatrix(r,x[:Dbits],Sdiag)
A = np.reshape(x[Dbits:Dbits+Abits],(r,n-r))
L = np.reshape(x[-Lbits:],(n-k,k))
return LF2XZ(L,A,D)
def XZhad(E, ix):
'''Apply Hadamard to qubits according to index ix for Pauli operator list E'''
m,n = E.shape
nB = n//2
ixN = ix + nB
ix1 = np.arange(n)
ix1[ix] = ixN
ix1[ixN] = ix
return ZMatPermuteCols(E,ix1)
def makeSymmetricMatrix(r,x,Sdiag=True):
'''convert binary vector x to a symmetrix rxr matrix
if Sdiag is False, the diagonal is all zeros'''
S = ZMatZeros((r,r))
if Sdiag:
S[np.triu_indices(r, 0)] = x
else:
S[np.triu_indices(r, 1)] = x
S[np.tril_indices(r, -1)] = S.T[np.tril_indices(r, -1)]
return S
###################################################
## Supporting Methods for Logical Operator Algs ##
###################################################
def Orbit2distIter(SX,t=None,return_u=False):
'''Interator yielding binary rows of form (u SX mod 2) for wt(u) <= t.
if return_u, yield u as well as the row.'''
r, n = np.shape(SX)
if t is None:
t = r
t = min(t, r)
for k in range(t+1):
for xSupp in iter.combinations(range(r),k):
vSX = np.mod(np.sum(SX[xSupp,:],axis=0),2)
if return_u:
u = set2Bin(r,xSupp)
yield vSX, u
else:
yield vSX
def Orbit2dist(SX,t=None,return_u=False):
'''Matrix with binary rows of form (q + u SX mod 2) for wt(u) <= t.
if return_u, yield u as well as the row.'''
temp = list(Orbit2distIter(SX,t,return_u))
if return_u:
temp = list(zip(*temp))
return [ZMat(a) for a in temp]
else:
return ZMat(temp)
##################################################
## Print stabilisers and codewords
##################################################
def print_SXLX(SX,LX,SZ,LZ,compact=True):
'''Print the X-checks, X-logicals, Z-checks, Z-logicals of a CSS code.
If compact=True, print full vector representations, otherwise print support of the vectors.'''
k,n = LX.shape
supercompact = (n > 70)
opDict = {'SX':SX,'SZ':SZ,'LX':LX,'LZ':LZ}
for AName,AList in opDict.items():
print(AName)
if supercompact:
print(freqTable(np.sum(AList,axis=-1)))
else:
for x in AList:
print(x2Str(x) if compact else ZMat2str(x))
def codewords(SX,LX):
'''Return canonical codewords LI={v}, CW={sum_u (uSX + vLX)}'''
r,n = np.shape(SX)
OSX = Orbit2dist(SX)
LI, CW = [],[]
for m,v in Orbit2distIter(LX,return_u=True):
S = np.mod(m + OSX,2)
LI.append(v)
CW.append(S)
return LI, CW
def print_codewords(SX,LX):
'''Print the canonical codwords of a CSS code defined by X-checks SX and X-logicals LX'''
V, CW = codewords(SX,LX)
print('\nCodewords')
for i in range(len(V)):
print(f'{ket(V[i])} : {state2str(CW[i])}')
def state2str(S):
'''Print a state corresponding to a binary matrix S in the form sum_{x in S}|x>'''
return "+".join([ket(x) for x in S])
def ket(x):
'''Display |x> for states.'''
return f'|{ZMat2str(x)}>'
#############################################################
## Code Analysis Tools
#############################################################
def nkdReport(SX,LX,SZ,LZ):
'''Report [[n,k,dX,dZ]] for CSS code specified by SX,LX,SZ,LZ.'''
k,n = np.shape(LX)
LZ = minWeightLZ(SZ,LZ)
dZ = min(np.sum(LZ,axis=-1))
LX = minWeightLZ(SX,LX)
dX = min(np.sum(LX,axis=-1))
d = min([dX,dZ])
gamma = codeGamma(n,k,d)
return(f'n:{n} k: {k} dX: {dX} dZ:{dZ} gamma:{gamma}')
def codeGamma(n,k,d):
if d > 1:
return(np.log (n / k)/np.log(d))
return 10
def tOrthogonal(SX,target=None):
'''Return largest t for which the weight of the product of any t rows of SX is even.'''
t = 1
r, n = np.shape(SX)
target = r if target is None else target
while t + 1 <= target:
## all combinations of t+1 rows
for ix in iter.combinations(range(r),t+1):
T = np.prod(SX[ix,:],axis=0)
if np.sum(T) % 2 == 1:
return t
t += 1
return t
##########################################################
## Check for quasi-transversality
##########################################################
def QuasiTransversal(SX,LX,d):
'''Check for quasi transversality - see Pin Code paper'''
## intersections of up to d elements of SX
SXE = SXIntersections(SX,d)
## check they are even weight
for x in SXE[-1]:
if (len(x) % 2) > 0:
return False
## intersections of up to d-1 elements of LX
LXE = SXIntersections(LX,d-1)
for s in range(0,d-1):
for t in range(0,d-1-s):
for x1 in SXE[s]:
for x2 in LXE[t]:
if (len(x1.intersection(x2)) % 2) > 0:
return False
return True
def SXIntersections(SX,d):
'''make products of up to d rows of SX and return list of sets'''
r,n = np.shape(SX)
E = []
E.append([set(bin2Set(x)) for x in SX])
for c in range(d-1):
temp = set()
for i in range(len(E[0])):
for j in range(len(E[c])):
e = E[0][i].intersection(E[c][j])
if len(e) > 0 and len(e) < len(E[c][j]):
temp.add(set2tuple(e))
E.append([set(e) for e in temp])
return E
##################################################
## Action and Tests for Diagonal Logical Operators
##################################################
def isDiagLO(z,SX,K_M,N):
'''Test if z is the Z-component of a logical XP operator.
Inputs:
z: Z_N vector to test
SX: X-checks
K_M: Z_N matrix representing phase and Z-components of diagonal logical identities
N: precision of XP operators'''
for x in SX:
## componentwise product of x and z
xz = x * z
## Z and phase component of commutator
czp = np.mod(np.hstack([-2*xz,[np.sum(xz)]] ),N)
## residue of czp with respect to logical identities
c, v = HowRes(K_M, czp, N)
## if non-zero, there is an error
if np.sum(c) > 0:
print(func_name(),f'Error: x={x},z={z},c={c}')
return False
return True
def CPIsLO(qVec,SX,CPKM,V,N,CP=True):
'''Check if qVec is a logical operator by calculating the group commutator [[A, CP_V(qVec)]] for each A in SX
Inputs:
qVec: Z_2N vector of length |V| representing a product of CP operators prod_{v in V}CP_N(qVec[v],v)
SX: binary matrix representing X-checks
CPKM: Z_2N Howell form matrix representing logical identities in CP form
V: binary matrix representing vector part of CP operators
N: precision of operators
CP: if True, treat operators as CP operators, otherwise RP operators'''
## check that there is an all-zero row of V
if pIndex(V) is None:
r,n = np.shape(V)
V = np.vstack([V,ZMatZeros(n)])
qVec = np.hstack([qVec,[0]])
r,n = np.shape(CPKM)
CPKM = np.hstack([CPKM,ZMatZeros((r,1))])
for x in SX:
c = CPComm(qVec,x,V,N,CP)
c, u = HowRes(CPKM,c,2*N)
c = np.mod(c,2*N)
if np.sum(c) != 0:
print('x',x2Str(x))
print('qVec',CP2Str(qVec,V,N))
print('c',CP2Str(c,V,N))
return False
return True
def action2CP(vList,pVec,N):
'''Return controlled phase operator corresponding to phase vector pVec
pList a list of phases applied on each by an operator
return a CP operator'''
qVec = pVec.copy()
for i in range(len(qVec)):
v, p = vList[i],qVec[i]
if p > 0:
ix = uLEV(v,vList)
qVec = np.mod(qVec-p*ix,N)
qVec[i] = p
return qVec
def DiagLOActions(LZ,LX,N):
'''Return phase vector for each Z component in LZ.
Inputs:
LZ: Z_N matrix whose rows are the z-vectors
LX: binary matrix - X-logicals
N: precision of XP operators.
Output:
phase vector p for each z component in LZ such that XP(0|0|z)|v>_L = w^{p[v]}|v>_L plus list of indices v
'''
t = log2int(N)
k,n = LX.shape
vLX,vList = Orbit2dist(LX,t,True)
pVec = ZMat(np.mod([[np.dot(z,x) for x in vLX] for z in LZ],N))
return pVec,vList
def codeword_test(qVec,SX,LX,V,N):
'''Print report on action of prod_{v in V}CP_N(qVec[v],v) operator on comp basis elts in each codeword.
Inputs:
qVec: Z_2N vector of length |V| representing CP operator
SX: X-checks in binary matrix form
LX: X-logicals in binary matrix form
V: vectors for CP operator
N: precision of CP operator'''
vList, CW = codewords(SX,LX)
for i in range(len(CW)):
s = {CPACT(e,qVec,V,N) for e in CW[i]}
print(f'{ket(vList[i])}L {s}')
def action_test(qVec,LX,t,V):
'''Return action of prod_{v in V}CP_N(qVec[v],v) operator on codewords in terms of CP operators.'''
N = 1 << t
## test logical action
Em,vList = Orbit2dist(LX,t,True)
## phases are modulo 2N
pList = ZMat([CPACT(e,qVec,V,N) for e in Em])//2
act = action2CP(vList,pList, N)
return 2*act, vList
def CZLO(SX, LX):
'''Find logical operators made from T gates and CZ for triorthogonal codes'''
t = 3
# make Howell Form of SX and LX
SXH = getH(SX, 2)
LXH = getH(LX, 2)
## information set for SX,LX
li = [leadingIndex(x) for x in SXH] + [leadingIndex(x) for x in LXH]
k, n = np.shape(LXH)
N = 1 << t
## only need to consider CZ between cols in info set
V = [set2Bin(n,c) for c in iter.combinations(li,2)]
## this ordering reduces number of CZ
V = np.vstack([V,ZMatI(n)])
V = np.vstack([ZMatI(n),V])
## embedded code
SX_V = matMul(SX,V.T,2)
LX_V = matMul(LX,V.T,2)
SX_V, LX_V, SZ_V, LZ_V = CSSCode(SX_V,LX_V)
r_V,n_V = np.shape(SX_V)
## Logical identities
if t == 1:
K_M = ZMatZeros((1,n_V+1))
elif t == 2 and SZ_V is not None:
K_M = np.hstack([SZ_V,ZMatZeros((len(SZ_V),1))]) * 2
else:
K_M = LIAlgorithm(LX_V,SX_V,N//2,debug=False) * 2
## z components of generators of diagonal XP LO group
K_L = DiagLOComm(SX_V,K_M,N)
v = ZMat([1] * n + [2] * (len(V)-n))
K_L = nsIntersection([K_L,np.diag(v)],N)
## phase applied to codewords
pList, VL = DiagLOActions(K_L,LX_V,N)
## actions as CP operators
qList = ZMat([action2CP(VL,pVec,N) for pVec in pList])
A = np.hstack([qList,K_L])
A = getH(A,N)
qList, zList = A[:,:len(VL)], A[:,len(VL):]
for z,qL in zip(zList,qList):
q, Vq = CP2RP(2*z,V,t,CP=False)
if np.sum(qL) > 0:
print(CP2Str(2*qL,VL,N),"=>",CP2Str(q,Vq,N))
# codeword_test(q,SX,LX,Vq,N)
########################################################
## Logical Identity Algorithm
########################################################
def LIAlgorithm(LX,SX,N,compact=True,debug=False):
'''Run logical Identity Algorithm.
Inputs:
LX: X logicals
SX: X-checks
N: required precision
compact: print full vector form if True, else support form
debug: verbose output
Output:
KM: Z_N matrix representing phase and z components of diagonal logical identities.'''
KM = getKM(SX, LX, N)
if debug:
print(f'\nLogical Identities Precision N={N}:')
print(f'K_M = Ker_{N}(E_M):')
if compact:
print(ZMat2compStr(KM))
else:
print(ZMatPrint(KM))
return KM
def getKM(SX, LX,N):
'''Return KM - Z_N matrix representing phase and z components of diagonal logical identities.'''
t = log2int(N)
A = Orbit2dist(np.vstack([SX,LX]), t)
A = np.hstack([A,[[1]]*len(A)])
return getK(A,N)
########################################################
## Generators of Diagonal Logical XP Group via Kernel Method
########################################################
def diagLOKer(LX,SX,N,target=None):
'''Return diagonal logical operators via Kernel method.
Inputs:
LX: X logicals
SX: X-checks
N: required precision
target: if not None, search for an implementation of the target.
Output:
K_L: Z components and phase vectors of diagonal logical operators
vList: list of codewords |v>_L which are the components of the phase vectors.'''
r,n = np.shape(SX)
## t is orbit distance - if N = 2^t, use t else t is None
t = log2int(N)
## Em are orbit reps 1-1 corresp with codewords
## only need to consider wt(v) <= t
Em,vList = Orbit2dist(LX,t,True)
if target is None:
m = len(Em)
## delta: indicator vector for codeword
bList = ZMatI(m)
else:
m = 1
# indicator vector if target <= vList
bList = uLEV(target,vList)
bList = ZMat([bList]).T
Em = np.hstack([Em,bList])
## Adding SX does not change delta
SX = np.hstack([SX,ZMatZeros((r,m))])
## Apply SX up to orbit distance t
E_0 = Orbit2dist(SX,t)
E_L = np.vstack([np.mod(E_0 + e,2) for e in Em])
## calculate kernel modulo N
K_L = getK(E_L,N)
return K_L, vList
def ker_method(LX,SX,N,compact=True):
'''Run the kernel method and print results.
Inputs:
LX: X logicals
SX: X-checks
N: required precision
compact: if True, output full vector forms, otherwise support view.
'''
r,n = np.shape(SX)
KL,V = diagLOKer(LX,SX,N)
m = len(V)
print(f'\nLogical Operators Precision N={N}:')
print(f'K_L = Ker_{N}(E_L):')
if compact:
print(ZMat2compStr(KL))
else:
print(ZMatPrint(KL))
print('\nLogical Operators and Phase Vectors:')
print(f'z-component | p-vector')
LZN, pList = KL[:,:n], np.mod(- KL[:,n:],N)
KL = getH(np.hstack([pList, LZN]),N)
for pz in KL:
pvec, z = pz[:m], pz[m:]
if np.sum(pvec) > 0:
if compact:
print(z2Str(z,N),":",row2compStr(pvec))
else:
print(ZMat2str(z),":",ZMat2str(pvec))
print(f'\np-vector: p[i] represents phase of w^2p[i] on |v[i]> where v[i] is:')
for i in range(len(V)):
print(f'{i}: {ket(V[i])}')
########################################################
## Search for LO by logical action via Kernel Method
########################################################
def ker_search(target,LX,SX,t=None,debug=False):
'''Run kernel search algorithm.
Inputs:
target: string corresponding logical CP operator to search for
LX: X logicals
SX: X-checks
t: required level of Clifford hierarchy
debug: if True, verbose output.
Output:
z-component of a diagonal XP operator implementing target, or None if this is not possible.
'''
r, n = np.shape(SX)
k = len(LX)
(x,qL), VL, t2 = Str2CP(target,n=k)
if t is None:
t = t2
elif t > t2:
qL = ZMat(qL) * (1 << (t-t2))
N = 1 << t
SXLX = np.vstack([SX,LX])
EL, uvList = Orbit2dist(SXLX,t,return_u = True)
vList = uvList[:,r:]
pList = np.mod(-ZMat([[CPACT(v,qL,VL,N)] for v in vList] )//2,N)
KL = getK(np.hstack([pList, EL]),N)
## check if top lhs is 1 - in this case, the LO has been found
if KL[0,0] == 1:
z = KL[0,1:]
if debug:
pList, V = DiagLOActions([z],LX,N)
q = action2CP(V,pList[0],N)
print('operator:',z2Str(z,N))
if n < 16:
print(f'XP Form: XP_{N}(0|0|{ZMat2str(z)})')
print("action:",CP2Str(2*q,V,N))
return z
if debug:
print(func_name(),f'{target} Not found')
return None
##########################################################
## Generators of Diagonal Logical XP Group via Commutator Method
##########################################################
def CPLogicalOps(SX,LX,K_M, N):
'''Return list of z components of diagonal logical XP operators and their action in terms of CP operators.
Inputs:
LX: X logicals
SX: X-checks
K_M: phase and z components of diagonal logical XP identities
Output:
LZ: list of z components
CPList: list of q-vectors of CP operators
vList: list of vectors v for the CP operators CP_N(q[v],v)'''
LZ = DiagLOComm(SX,K_M,N)
LA, vList = DiagLOActions(LZ,LX,N)
a, b = np.shape(LA)
A = np.hstack([LA,LZ])
A = getH(A,N)
LA, LZ = A[:,:b], A[:,b:]
CPlist = ZMat([action2CP(vList,pList,N) for pList in LA])
a, b = np.shape(CPlist)
A = np.hstack([CPlist,LZ])
A = getH(A,N)
CPlist, LZ = A[:,:b], A[:,b:]
return LZ, vList, CPlist
def DiagLOComm(SX,K_M,N):
'''Return z components of generating set of logical XP operators using Commutator Method.
Inputs:
SX: X-checks
K_M: phase and z components of diagonal logical XP identities
N: required precision
Output:
LZ: list of z components of logical XP operators.'''
LZ = None
for x in SX:
Rx = commZ(x,K_M,N)
LZ = Rx if LZ is None else nsIntersection([LZ, Rx],N)
return LZ
def commZ(x,K_M,N):
'''Return generating set of Z-components for which group commutator with X-check x is a logical identity.
Inputs:
x: an X-check (binary vector of length n)
K_M: phase and z components of diagonal logical XP identities
N: required precision
'''
n = len(x)
## diag(x)
xSet = bin2Set(x)
if len(xSet) == 0:
return ZMatI(n)
## rows of Ix are indicator vectors delta(x[i]==1)
Ix = ZMat([set2Bin(n,[i]) for i in xSet],n)
## rows are of form (-2* delta(x[i]==1) | 1) because we require phase component equal to x.z
Rx = np.hstack([(N-2) * Ix,np.ones((len(Ix),1),dtype=int)])
## intersection with K_MS
Rx = nsIntersection([K_M,Rx],N)
# adjustment to ensure x.z = phase (last col)
Rxp = np.sum(Rx[:,:-1],axis=-1) - 2* Rx[:,-1]
Rx[:,xSet[-1]] += Rxp
Rx = np.mod(Rx,2*N)
## solutions z are half the values in the intersection
Rx = Rx[:,:-1]//2
if N % 2 == 0 and np.sum(x) > 1:
## adding two elements N//2 to solutions z also meets requirements
l = xSet[-1]
Ix = Ix[:-1]
Ix[:,l] = 1
Rx = np.vstack([Rx,N // 2 * Ix])
## Where x[i] == 0, value of z is unrestricted
Ix = ZMat([set2Bin(n,[i]) for i in bin2Set(1-x)],n)
return np.vstack([Rx,Ix])
def comm_method(SX, LX, SZ, t, compact=True, debug=True):
'''Run the commutator method and print results.
Inputs:
LX: X logicals
SX: X-checks
SZ: Z-checks
t: Clifford hierarchy level
compact: if True, output full vector forms, otherwise support view.
debug: if True, verbose output.
Output:
zList: list of z-components generating non-trivial diagonal XP operators
qList: list of q-vectors corresponding to logical action of each operator
V: vectors indexing qList
K_M: phase and z components of diagonal logical XP identities
'''
r,n = np.shape(SX)
N = 1 << t
## Logical identities
if t == 1:
K_M = ZMatZeros((1,n+1))
elif t == 2 and SZ is not None:
K_M = np.hstack([SZ,ZMatZeros((len(SZ),1))]) * 2
else:
K_M = LIAlgorithm(LX,SX,N//2,compact,debug=debug) * 2
## z components of generators of diagonal XP LO group
# K_L = DiagLOComm(SX,K_M,N)
K_L = DiagLOComm_new(SX,K_M,N)
## phase applied to codewords
pList, V = DiagLOActions(K_L,LX,N)
## actions as CP operators
qList = ZMat([action2CP(V,pList,N) for pList in pList])
if debug:
print('\nApplying Commutator Method:')
print('(z-component | q-vector | action)')
for z, q in zip(K_L,qList):
if np.sum(q) > 0:
if compact:
print(z2Str(z,N),"|", row2compStr(q),"|", CP2Str(2*q,V,N))
else:
print(ZMat2str(z), ZMat2str(q), CP2Str(2*q,V,N))
print(f'\nq-vector Represents CP_{N}(2q, w) where w =')
for i in range(len(V)):
print(f'{i}: {ZMat2str(V[i])}')
## Generators of logical actions
A = np.hstack([qList,K_L])
A = getH(A,N)
qList, K_L = A[:,:len(V)], A[:,len(V):]
## update K_M
ix = np.sum(qList,axis=-1) == 0
K_M = K_L[ix]
## non-trivial LO
ix = np.sum(qList,axis=-1) > 0
K_L, qList = K_L[ix], qList[ix]
if debug:
print('\nRearranging matrix to form (q, z) and calculating Howell Matrix form:')
print('(z-component | q-vector | action)')
for z, q in zip(K_L,qList):
if compact:
print(z2Str(z,N),"|", row2compStr(q),"|", CP2Str(2*q,V,N))
else:
print(ZMat2str(z), ZMat2str(q), CP2Str(2*q,V,N))
return K_L, qList, V, K_M
def DiagLOComm_new(SX,K_M,N):
'''Return z components of generating set of logical XP operators using Commutator Method.
Inputs:
SX: X-checks
K_M: phase and z components of diagonal logical XP identities
N: required precision
Output:
K_L: list of z components of logical XP operators.'''
r,n = SX.shape
## partition X-checks into non-overlapping sets
SXParts = SXPartition(SX)
# print('SX Partitions',len(SXParts))
K_L = None
for XList in SXParts:
## find qubits which are not in the support of any of the X-checks in XList
w = np.sum(XList,axis=0)
ix = [i for i in range(n) if w[i] == 0]
RX = ZMatZeros((len(ix),n))
## qubits in ix have no constraints for LZ
for i in range(len(ix)):
RX[i,ix[i]] = 1
XConstr = [RX]
## Add constraints for each x in XList
for x in XList:
XConstr.append(commZ_new(x,K_M,N))
XConstr = np.vstack(XConstr)
## Intersection with previous spans
K_L = XConstr if K_L is None else nsIntersection([K_L,XConstr],N)
return K_L
def commZ_new(x,K_M,N):
'''Return generating set of Z-components for which group commutator with X-check x is a logical identity.
Inputs:
x: an X-check (binary vector of length n)
K_M: phase and z components of diagonal logical XP identities
N: required precision
'''
n = len(x)
## get set bits
xSet = bin2Set(x)
## number of set bits
wx = len(xSet)
## rows are of form (-2 I | 1) because we require phase component equal to - x.z
RI = ZMatZeros((wx,n+1))
for i in range(len(xSet)):
RI[i,xSet[i]] = N-2
RI[i,-1] = 1
LI = nsIntersection([K_M,RI],N)
# adjustment to ensure x.z = phase (last col)
phaseAdj = np.sum(LI[:,:-1],axis=-1) - 2 * LI[:,-1]
LI[:,xSet[-1]] = np.mod(LI[:,xSet[-1]] + phaseAdj,2*N)
## adding N in pairs on support of x also a solution
RI = ZMatZeros((wx-1,n+1))
for i in range(len(xSet)-1):
RI[i,xSet[i]] = N
RI[i,xSet[-1]] = N
LI = np.vstack([LI,RI])
## solutions z are half the values in the intersection + drop phase component
return LI[:,:-1] // 2
def SXPartition(SX):
'''Partition SX into non-overlapping sets'''
## order SX via BFS search
ix = BFSOrder(SX)
SX = SX[ix]
todo = set(range(len(SX)))
temp = []
while len(todo) > 0:
ix = SXCC(SX,todo)
temp.append(SX[sorted(ix)])
todo = todo - ix
return temp
def SXCC(SX,todo):
'''Find largest set of checks which don't overlap with those in todo'''
temp = set()
while len(todo) > 0:
## add smallest index to temp
i = min(todo)
temp.add(i)
## update todo to include only X-checks with no overlap with SX[i]
todo = nonOverlapping(SX,i,todo)
return temp
def nonOverlapping(SX,i,todo):
ix = bin2Set(SX[i])
return [j for j in todo if np.sum(SX[j,ix])==0]
def edgeAdj(SX):
'''Adjacency matrix for X-checks SX
Checks are adjacent if separated by an edge'''
r = len(SX)
## Edges are overlaps of two X-checks
E = [SX[i]*SX[j] for (i,j) in iter.combinations(range(r),2)]
E = ZMat([e for e in E if np.sum(e) > 0])
## Initialise adjacency matrix
A = {i: set() for i in range(r)}
## Iterate through edges
for i in range(len(E)):
# EA = set()
ix = bin2Set(E[i])
wE = len(ix)
## overlap of each X-check with the edge
wSX = np.sum(SX[:,ix],axis=-1)
## checks are connected via the edge if they have non-zero overlap, but do not contain the edge
EA = [i for i in range(len(wSX)) if wSX[i] > 0 and wSX[i] < wE]
## all pairs of checks in EA are considered adjacent - update adjacency matrix
for (j,k) in iter.combinations(EA,2):
A[j].add(k)
A[k].add(j)
return A
def BFSOrder(SX):
'''traverse SX by overlap and record BFS ordering'''
r,n = SX.shape
## get adjacency matrix
A2 = edgeAdj(SX)
visited = set()
tovisit = set(range(r))
temp = ZMatZeros(r)
## BF search - keep track of the order in which checks are encountered
count = 0
## There may be more than one connected component
CCcount = 0
while len(tovisit) > 0:
CCcount += 1
j = min(tovisit)
tovisitloop = [j]
tovisit.remove(j)
visited.add(j)
temp[count] = j
count+=1
while len(tovisitloop) > 0:
i = tovisitloop.pop(0)
for j in A2[i]:
if j not in visited:
tovisitloop.append(j)
tovisit.remove(j)
visited.add(j)
temp[count] = j
count+=1
# print(func_name(),'SX Connected Components',CCcount)
return temp
############################################################
## Depth One Algorithm
############################################################
def depth_one_t(SX,LX,t=2,cList=None, debug=False):
'''Run depth-one algorithm - search for transversal logical operator at level t of the Clifford hierarchy
Inputs:
LX: X logicals
SX: X-checks
t: required level of Clifford hierarchy
cList: partition of qubits (optional) - improves runtime for known symmetries
debug: if true, verbose output
Output: if depth-one operator found:
cList: partition of the qubits as a list of cycles of the qubits
target: logical action as text representation of CP operator
'''
r,n = np.shape(SX)
k,n = np.shape(LX)
N = 1 << t
if cList is None:
## All binary vectors of length n weight 1-t
V = Mnt(n,t)
else:
## V based on partition supplied to algorithm
V = Mnt_partition(cList,n,t)
## move highest weight ops to left - more efficient in some cases
V = np.flip(V,axis=0)
## Construct Embedded Code
SX_V = matMul(SX, V.T, 2)
LX_V = matMul(LX, V.T, 2)
SZ_V = None
## Find diagonal logical operators at level t
K_L, qList, VL, K_M = comm_method(SX_V, LX_V, SZ_V, t, compact=False, debug=False)
## zList includes both trivial and non-trivial LO
# zList = np.vstack([K_L,K_M])
## Calculate clifford level of the logical operators
tList = [CPlevel(2*qL,VL,N) for qL in qList]
## Calculate overlap (how many times a qubit is used in more than one operator) for level t operators
ix = [i for i in range(len(tList)) if tList[i] == t]
if len(ix) == 0:
print(f'No level {t} logical operators found.')
return None
j = ix[0]
## convert to CP form
CPKM = [CP2RP(2 * q,V,t,CP=False,Vto=V)[0] for q in K_M]
CPKL = [CP2RP(2 * q,V,t,CP=False,Vto=V)[0] for q in K_L]
## get jth row - level t LO
qCP = CPKL.pop(j)
## Howell form modulo 2N
CPKL = ZMat(CPKL + CPKM)