-
Notifications
You must be signed in to change notification settings - Fork 1
/
GTN.py
1426 lines (1265 loc) · 59.9 KB
/
GTN.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
# %%writefile GTN.py
import numpy as np
import numpy.linalg as nla
import scipy.linalg as la
from scipy.sparse import bsr_array
from copy import copy
from itertools import permutations
class GTN:
def __init__(self,L,history=True,seed=None,op=False,random_init=False,c=[1,1,1],pbc=True,trijunction=False):
self.L=L # Complex fermion sites
self.op=op
self.trijunction=trijunction
self.random_init=random_init
self.rng=np.random.default_rng(seed)
self.C_m=self.correlation_matrix()
self.Gamma_like=np.zeros_like(self.C_m)
self.C_m_history=[self.C_m.copy()]
self.history=history
self.n_history=[]
self.i_history=[]
self.MI_history=[]
self.p_history=[]
self.c=c
self.pbc=pbc
self.full_ix=set(range(self.C_m[-1].shape[0]))
def correlation_matrix(self):
'''if `self.op` is on, the physical chain will duplicate a reference chain, where both sites (i,i+2L) are coupled, with parity +1, '''
if self.trijunction:
'''construct trijuction, the order of the three chain are arranged from outmost to innermost, namely, 0->2L-1 is Chain 0; 2L->4L-1 is Chain 1; 4L->6L-1 is Chain 2'''
if self.op:
Gamma=np.zeros((12*self.L,12*self.L))
EPR=np.fliplr(np.diag([1,-1]))
for i in range(6*self.L):
Gamma[np.ix_([i,i+6*self.L],[i,i+6*self.L])]=EPR
else:
Omega=np.array([[0,1.],[-1.,0]])
Omega_diag=np.kron(np.eye(self.L),Omega)
Gamma=np.kron(np.eye(3),Omega_diag)
else:
'''construct normal 1d chain'''
if self.op:
Gamma=np.zeros((4*self.L,4*self.L))
EPR=np.fliplr(np.diag([1,-1]))
for i in range(2*self.L):
Gamma[np.ix_([i,i+2*self.L],[i,i+2*self.L])]=EPR
else:
Omega=np.array([[0,1.],[-1.,0]])
Omega_diag=np.kron(np.eye(self.L),Omega)
self.A_D=Omega_diag
O=get_O(self.rng,2*self.L) if self.random_init else np.eye(2*self.L)
Gamma=O@[email protected]
return (Gamma-Gamma.T)/2
def set(self,ij_list,n_list):
"""ij_list: [[i,j],...]
n_list: [1,-1,...]
simply set all Gamma[i,j]=n, Gamma[j,i]=-n
"""
Gamma=self.C_m
for ij,n in zip(ij_list,n_list):
i,j=ij
Gamma[i,j]=n
Gamma[j,i]=-n
def measure(self,n,ix):
''' Majorana site index for ix,
n should be a scalar'''
Psi=self.C_m
proj=self.kraus(n)
# ix_bar=np.array([i for i in np.arange(self.L*2) if i not in ix]) if not self.op else np.array([i for i in np.arange(self.L*4) if i not in ix])
ix_bar=np.array([i for i in np.arange(self.C_m[-1].shape[0]) if i not in ix])
# Psi=P_contraction(m,proj,ix,ix_bar)
P_contraction_2(Psi,proj,ix,ix_bar,self.Gamma_like,reset_Gamma_like=False)
# assert np.abs(np.trace(Psi))<1e-5, "Not trace zero {:e}".format(np.trace(Psi))
if self.history:
self.C_m_history.append(Psi.copy())
self.n_history.append(n)
self.i_history.append(ix)
# self.MI_history.append(self.mutual_information_cross_ratio())
else:
self.C_m_history=[Psi]
self.n_history=[n]
self.i_history=[ix]
# self.MI_history=[self.mutual_information_cross_ratio()]
def projection(self,s):
'''
occupancy number: s= 0,1
(-1)^0 even parity, (-1)^1 odd parity
'''
assert (s==0 or s==1),"s={} is either 0 or 1".format(s)
blkmat=np.array([[0,-(-1)**s,0,0],
[(-1)**s,0,0,0],
[0,0,0,(-1)**s],
[0,0,-(-1)**s,0]])
return blkmat
def kraus(self,n):
c=self.c
return np.array([[0,c[0]*n[0],c[1]*n[1],c[2]*n[2]],
[-c[0]*n[0],0,-c[2]*n[2],c[1]*n[1]],
[-c[1]*n[1],c[2]*n[2],0,-c[0]*n[0]],
[-c[2]*n[2],-c[1]*n[1],c[0]*n[0],0]])
# return -np.array([[0,n[0],-n[1],n[2]],
# [-n[0],0,-n[2],-n[1]],
# [n[1],n[2],0,-n[0]],
# [-n[2],n[1],n[0],0]])
# return -np.array([[0,n[0],n[1],n[2]],
# [-n[0],0,-n[2],n[1]],
# [-n[1],n[2],0,-n[0]],
# [-n[2],-n[1],n[0],0]])
def apply_charge_transfer(self,ix):
""" Majorana site index for ix, transfer from ix[2:] to ix[:2] """
Psi=self.C_m
ix_bar=np.array(list(self.full_ix-set(ix)))
proj=op_charge_transfer()
P_contraction_2(Psi,proj,ix,ix_bar,self.Gamma_like,reset_Gamma_like=False)
if self.history:
self.C_m_history.append(Psi.copy())
self.n_history.append([])
self.i_history.append(ix)
# self.MI_history.append(self.mutual_information_cross_ratio())
else:
# self.C_m_history=[Psi]
self.n_history=[]
self.i_history=[ix]
# self.MI_history=[self.mutual_information_cross_ratio()]
def measure_single_mode_force(self,kind,ix,):
''' Majorana site index for ix'''
assert len(ix)==len(kind[0])*2, 'len of ix should be 2*len(kind[0])'
Psi=self.C_m
ix_bar=np.array(list(self.full_ix-set(ix)))
proj=op_single_mode(kind)
P_contraction_2(Psi,proj,ix,ix_bar,self.Gamma_like,reset_Gamma_like=False)
if self.history:
self.C_m_history.append(Psi.copy())
self.n_history.append(kind)
self.i_history.append(ix)
# self.MI_history.append(self.mutual_information_cross_ratio())
else:
# self.C_m_history=[Psi]
self.n_history=[kind]
self.i_history=[ix]
# self.MI_history=[self.mutual_information_cross_ratio()]
def measure_class_AIII(self,A,theta1,theta2,kind,ix,):
''' Majorana site index for ix'''
assert len(ix)==4, 'len of ix should be 4'
Psi=self.C_m
ix_bar=np.array(list(self.full_ix-set(ix)))
proj=op_class_AIII(A,theta1,theta2,kind)
P_contraction_2(Psi,proj,ix,ix_bar,self.Gamma_like,reset_Gamma_like=False)
if self.history:
self.C_m_history.append(Psi.copy())
self.n_history.append([A,theta1,theta2,kind])
self.i_history.append(ix)
# self.MI_history.append(self.mutual_information_cross_ratio())
else:
# self.C_m_history=[Psi]
self.n_history=[A,theta1,theta2,kind]
self.i_history=[ix]
# self.MI_history=[self.mutual_information_cross_ratio()]
def measure_class_AIII_unitary(self,A,theta1,theta2,kind,ix,):
''' Majorana site index for ix, allows nonlocal unitary'''
assert len(ix)==8, 'len of ix should be 8'
Psi=self.C_m
ix_bar=np.array(list(self.full_ix-set(ix)))
proj=op_class_AIII_unitary(A,theta1,theta2,kind)
P_contraction_2(Psi,proj,ix,ix_bar,self.Gamma_like,reset_Gamma_like=True)
if self.history:
self.C_m_history.append(Psi.copy())
self.n_history.append([A,theta1,theta2,kind])
self.i_history.append(ix)
# self.MI_history.append(self.mutual_information_cross_ratio())
else:
# self.C_m_history=[Psi]
self.n_history=[A,theta1,theta2,kind]
self.i_history=[ix]
# self.MI_history=[self.mutual_information_cross_ratio()]
def measure_all(self,a1,a2,b1,b2,even=True,theta_list=0,phi_list=0,Born=False):
proj_range=np.arange(self.L)*2 if even else np.arange(self.L)*2+1 # Majorana site index of left leg
if Born:
Gamma_list=self.C_m[proj_range,(proj_range+1)%(2*self.L)]
n_list=get_Born_B(a1,a2,b1,b2,Gamma_list,theta_list=theta_list,phi_list=phi_list,rng=self.rng)
else:
n_list=get_random(a1,a2,b1,b2,proj_range.shape[0],theta_list=theta_list,phi_list=phi_list,rng=self.rng)
for i,n in zip(proj_range,n_list):
self.measure([n], np.array([i,(i+1)%(2*self.L)]))
def measure_all_class_AIII(self,A_list,Born=True,class_A=False,even=True,):
proj_range=np.arange(self.L//2)*4 if even else np.arange(self.L//2)*4+2 # Majorana site index of leftmost leg
if isinstance(A_list, int) or isinstance(A_list, float):
A_list=np.array([A_list]*len(proj_range))
if self.history:
self.p_history.append(A_list)
else:
self.p_history=[A_list]
if Born:
for i, A in zip(proj_range,A_list):
legs=[i,(i+1)%(2*self.L),(i+2)%(2*self.L),(i+3)%(2*self.L)]
Gamma=self.C_m[np.ix_(legs,legs)]
kind,theta1,theta2=get_Born_class_AIII(A=A,Gamma=Gamma,rng=self.rng,class_A=class_A,)
self.measure_class_AIII(A=A,theta1=theta1,theta2=theta2,kind=kind,ix=legs)
else:
pass
def measure_projection_AIII(self,legs):
"""legs is the 2 majorana site index,perform the strong projective measurement"""
Gamma = self.C_m[np.ix_(legs,legs)]
kind,_,_=get_Born_class_AIII(A=1,Gamma=Gamma,rng=self.rng,class_A=False,)
self.measure_class_AIII(A=1,theta1=0,theta2=0,kind=kind,ix=legs)
return kind
def measure_single_mode_Born(self,legs,mode):
"""measure the single mode |pm > = 1/sqrt(2) (c_1^dag pm c_2^dag), where 1 and 2 are legs[:2] and legs[2:4]
The difference between measure_projection_AIII and this and is that the former requires to measure both mode of |+> and |-> in one step"""
Gamma = self.C_m[np.ix_(legs,legs)]
n = get_Born_single_mode(Gamma=Gamma,mode=mode,rng=self.rng)
self.measure_single_mode_force(kind=(mode,n),ix=legs)
return (mode,n)
# def measure_charge(self,legs):
# ''' legs is the majorana site index,
# for measuring charge,
# n_list[0]= -1 : empty state/even parity
# n_list[0]= 1 : occupied state/odd parity
# return number density as (1+n_list[0])/2
# '''
# # Gamma = self.C_m[[legs[0]],[legs[1]]]
# Gamma = self.C_m[np.ix_(legs,legs)]
# # n_list=get_Born_tri_op(p=1,Gamma=Gamma,rng=self.rng,alpha=1)
# n = get_Born_charge(Gamma=Gamma,rng=self.rng)
# # self.measure(n_list[0],ix=legs)
# self.measure_single_mode_force(kind = ([1],n),ix=legs)
# return n
def randomize(self,legs):
""" legs is the majorana site index,
simply randomize the parity"""
n_list=get_Born_tri_op(p=0,Gamma=np.array([0]),rng=self.rng,alpha=1)
self.measure(n_list[0],ix=legs)
return n_list[0][0]
# def state_transfer(self,ix,source=None,target=None):
# """ Majorana site index for ix"""
# Psi=self.C_m
# ix_bar=np.array(list(self.full_ix-set(ix)))
# op=op_state_transfer(source,target)
# P_contraction_2(Psi,op,ix,ix_bar,self.Gamma_like,reset_Gamma_like=True)
# if self.history:
# self.C_m_history.append(Psi.copy())
# self.n_history.append([source,target])
# self.i_history.append(ix)
# else:
# self.n_history=[source,target]
# self.i_history=[ix]
def fSWAP(self,ix,state1=None,state2=None):
""" Majorana site index for ix ,exp(i*pi*c_-^dag c_-)"""
Psi=self.C_m
ix_bar=np.array(list(self.full_ix-set(ix)))
op=op_fSWAP(state1,state2)
P_contraction_2(Psi,op,ix,ix_bar,self.Gamma_like,reset_Gamma_like=True)
if self.history:
self.C_m_history.append(Psi.copy())
self.n_history.append([state1,state2])
self.i_history.append(ix)
else:
self.n_history=[state1,state2]
self.i_history=[ix]
# def measure_feedback_AIII(self,ix,feedback=True):
# """ix is the 2 fermionic site index
# this can be used to incorporate feedback"""
# legs_t = [2*ix[0],(2*ix[0]+1)%(2*self.L),(2*ix[1])%(2*self.L),(2*ix[1]+1)%(2*self.L),]
# legs_bB = [leg+self.L for leg in legs_t[:2]]
# legs_bA = [leg+self.L for leg in legs_t[2:]]
# print(legs_bB,legs_bA)
# outcome_t=self.measure_projection_AIII(legs_t)
# if feedback:
# if outcome_t == (-1,1):
# # this is good
# pass
# elif outcome_t == (1,-1):
# # need to fix it by depleting the upper band to lower band
# self.state_transfer(legs_t,source='+t',target='-t')
# # self.fSWAP(legs_t,source='+t',target='-t')
# elif outcome_t == (1,1):
# # both occupied, just depleting the upper band
# outcome_bA=self.measure_charge(legs_bA)
# if outcome_bA ==-1:
# # A on bottom is empty
# self.state_transfer(legs_t+legs_bA,source='+t')
# elif outcome_bA==1:
# outcome_bB=self.measure_charge(legs_bB)
# if outcome_bB == -1:
# # B on bottom is empty
# self.state_transfer(legs_t+legs_bB,source='+t')
# else:
# # B on bottom is not empty, cannot depelete
# pass
# elif outcome_t == (-1,-1):
# # both top empty, just fill the lower band
# outcome_bB=self.measure_charge(legs_bB)
# if outcome_bB == 1:
# # B on bottom not empty
# self.state_transfer(legs_t+legs_bB,target='-t')
# elif outcome_bB == -1:
# # B on bottom is empty
# outcome_bA=self.measure_charge(legs_bA)
# if outcome_bA ==1:
# # A on bottom is not empty
# self.state_transfer(legs_t+legs_bA,target='-t')
# else:
# # A on bottom is empty, fix failed
# pass
def measure_feedback_AIII(self,ix,feedback=True):
"""ix is the 2 fermionic site index
this can be used to incorporate feedback"""
legs_t = [2*ix[0],(2*ix[0]+1)%(2*self.L),(2*ix[1])%(2*self.L),(2*ix[1]+1)%(2*self.L),]
legs_bB = [leg+self.L for leg in legs_t[:2]]
legs_bA = [leg+self.L for leg in legs_t[2:]]
print(legs_bB,legs_bA)
# fill lower band
mode_m,n_m=self.measure_single_mode_Born(legs_t,mode=[1,-1])
if n_m ==1:
# this is good
pass
elif n_m ==0:
_, n_bA = self.measure_single_mode_Born(legs_bA,mode=[1])
if n_bA == 1:
# A bottom occupied, fill to top layer
self.fSWAP(legs_t+legs_bA,state1 = [1,-1], state2=[1])
elif n_bA == 0:
# A bottom empty, measure B bottom
_, n_bB = self.measure_single_mode_Born(legs_bB,mode=[1])
if n_bB ==1:
# B bottom occupied, fill to top layer
self.fSWAP(legs_t+legs_bB,state1 = [1,-1], state2=[1])
elif n_bB ==0:
# B bottom also empty
pass
else:
raise ValueError('Protocol failed')
# deplete upper band
mode_p,n_p=self.measure_single_mode_Born(legs_t,mode=[1,1])
if n_p ==0:
# this is good
pass
elif n_p == 1:
_, n_bA = self.measure_single_mode_Born(legs_bA,mode=[1])
if n_bA == 0:
# A bottom empty, deplete upper band
self.fSWAP(legs_t+legs_bA,state1 = [1,1], state2=[1])
elif n_bA == 1:
# A bottom occupied, measure B bottom
_, n_bB = self.measure_single_mode_Born(legs_bB,mode=[1])
if n_bB == 0:
# B bottom empty
self.fSWAP(legs_t+legs_bB,state1 = [1,1], state2=[1])
elif n_bB ==1:
# B bottom also occupied
pass
else:
raise ValueError('Protocol failed')
def measure_all_class_AIII_r_unified(self,A_list,r_list,Born=True,class_A=False,even=True,):
"""use a unified language, where even is always iA and i+r,B, and odd is iB and i+r+1,A"""
site_A_left=np.arange(self.L//2)*4
site_B_left=np.arange(self.L//2)*4+2
if isinstance(A_list, int) or isinstance(A_list, float):
A_list=np.array([A_list]*(self.L//2))
if isinstance(r_list, int) or isinstance(r_list, float):
r_list=np.array([r_list]*(self.L//2))
if self.history:
self.p_history.append(A_list)
else:
self.p_history=[A_list]
if Born:
for idx in range(self.L//2):
r0=int(np.round(self.rng.uniform(r_list[idx]-1/2,r_list[idx]+1/2)))
if even:
legs=[site_A_left[idx],(site_A_left[idx]+1)%(2*self.L),site_B_left[(idx+r0)%(self.L//2)],(site_B_left[(idx+r0)%(self.L//2)]+1)%(2*self.L)]
else:
legs=[site_B_left[idx],(site_B_left[idx]+1)%(2*self.L),site_A_left[(idx+r0+1)%(self.L//2)],(site_A_left[(idx+r0+1)%(self.L//2)]+1)%(2*self.L)]
# legs= [site_A_left[(idx+r0+1)%(self.L//2)],(site_A_left[(idx+r0+1)%(self.L//2)]+1)%(2*self.L),site_B_left[idx],(site_B_left[idx]+1)%(2*self.L)]
Gamma=self.C_m[np.ix_(legs,legs)]
kind,theta1,theta2=get_Born_class_AIII(A=A_list[idx],Gamma=Gamma,rng=self.rng,class_A=class_A,)
self.measure_class_AIII(A=A_list[idx],theta1=theta1,theta2=theta2,kind=kind,ix=legs)
else:
pass
def measure_all_class_AIII_r_unitary(self,A_list,r_list,Born=True,class_A=False,even=True,factor=1,break_symm=False):
"""this allows non local unitary to have exp(i*theta*(c_iA^dag cjA - c_iA c_jA^dag))
factor is used to ``suppress'' the variance of random unitary"""
site_A_left=np.arange(self.L//2)*4
site_B_left=np.arange(self.L//2)*4+2
if isinstance(A_list, int) or isinstance(A_list, float):
A_list=np.array([A_list]*(self.L//2))
if isinstance(r_list, int) or isinstance(r_list, float):
r_list=np.array([r_list]*(self.L//2))
if self.history:
self.p_history.append(A_list)
else:
self.p_history=[A_list]
if Born:
for idx in range(self.L//2):
r0=int(np.round(self.rng.uniform(r_list[idx]-1/2,r_list[idx]+1/2)))
if r0==0 and even:
# complex fermion (iA, iB, )
legs=[site_A_left[idx],(site_A_left[idx]+1)%(2*self.L),site_B_left[(idx+r0)%(self.L//2)],(site_B_left[(idx+r0)%(self.L//2)]+1)%(2*self.L)]
Gamma=self.C_m[np.ix_(legs,legs)]
kind,theta1,theta2=get_Born_class_AIII(A=A_list[idx],Gamma=Gamma,rng=self.rng,class_A=class_A,)
theta1,theta2=theta1/factor,theta2/factor
self.measure_class_AIII(A=A_list[idx],theta1=theta1,theta2=theta2,kind=kind,ix=legs)
else:
if even:
# complex fermion (iA, iB, jA, jB), j=i+r
legs=[site_A_left[idx],(site_A_left[idx]+1)%(2*self.L),site_B_left[idx],(site_B_left[idx]+1)%(2*self.L),site_A_left[(idx+r0)%(self.L//2)],(site_A_left[(idx+r0)%(self.L//2)]+1)%(2*self.L),site_B_left[(idx+r0)%(self.L//2)],(site_B_left[(idx+r0)%(self.L//2)]+1)%(2*self.L)]
else:
# complex fermion (iA, iB, i+r+1A, i+r+1B) or (i+r+1B,i+r+1A, iB,iA) due to the symmetry of Kraus operator with iA<->jB, and iB<->jA
legs=[
site_A_left[(idx+r0+1)%(self.L//2)],(site_A_left[(idx+r0+1)%(self.L//2)]+1)%(2*self.L),
site_B_left[(idx+r0+1)%(self.L//2)],(site_B_left[(idx+r0+1)%(self.L//2)]+1)%(2*self.L),
site_A_left[idx],(site_A_left[idx]+1)%(2*self.L),
site_B_left[idx],(site_B_left[idx]+1)%(2*self.L),
]
if break_symm:
# here to manually break the symmetry, by effectively swapping only jB<-> iA
legs[0],legs[3]=legs[3],legs[0]
Gamma=self.C_m[np.ix_(legs,legs)]
kind,theta1,theta2=get_Born_class_AIII_unitary(A=A_list[idx],Gamma=Gamma,rng=self.rng,class_A=class_A,)
theta1,theta2=theta1/factor,theta2/factor
self.measure_class_AIII_unitary(A=A_list[idx],theta1=theta1,theta2=theta2,kind=kind,ix=legs)
else:
pass
def measure_all_sync(self,a1,a2,b1,b2,even=True,theta_list=0,phi_list=0,Born=False):
"""sync means all operators apply the layer at the same time"""
proj_range=np.arange(self.L)*2 if even else np.arange(self.L)*2+1
proj_range_1=proj_range if not self.op else proj_range+2* self.L
proj_range_2=(proj_range+1)%(2*self.L) if not self.op else (proj_range+1)%(2*self.L) + 2*self.L
if isinstance(theta_list, int) or isinstance(theta_list, float):
theta_list=[theta_list]*len(proj_range_1)
if isinstance(phi_list, int) or isinstance(phi_list, float):
phi_list=[phi_list]*len(proj_range_1)
if Born:
if self.C_m.size==0:
Gamma_list=np.array([1]*self.L)
n_list=get_Born(a1,a2,b1,b2,Gamma_list,theta_list=theta_list,phi_list=phi_list,rng=self.rng)
self.measure(n_list,np.c_[proj_range_1,proj_range_2].flatten())
else:
for i,j in zip(proj_range_1,proj_range_2):
Gamma=self.C_m[[i],[j]]
if even:
n_list=get_Born_A(a1,a2,b1,b2,Gamma,rng=self.rng)
else:
n_list=get_Born_B(a1,a2,b1,b2,Gamma,rng=self.rng)
self.measure(n_list,[i,j])
else:
n_list=get_random(a1,a2,b1,b2,proj_range.shape[0],theta_list=theta_list,phi_list=phi_list,rng=self.rng)
self.measure(n_list,np.c_[proj_range_1,proj_range_2].flatten())
def measure_all_Haar(self,sigma=0,even=True,theta_list=0,phi_list=0):
proj_range=np.arange(self.L)*2 if even else np.arange(self.L)*2+1
C_m=self.C_m
proj_range_1=proj_range
proj_range_2=(proj_range+1)%(2*self.L)
if isinstance(theta_list, int) or isinstance(theta_list, float):
theta_list=[theta_list]*len(proj_range_1)
if isinstance(phi_list, int) or isinstance(phi_list, float):
phi_list=[phi_list]*len(proj_range_1)
n_list=get_Haar(sigma,proj_range.shape[0],rng=self.rng,theta_list=theta_list,phi_list=phi_list)
for i,j, n in zip(proj_range_1,proj_range_2,n_list):
self.measure(n,[i,j])
def measure_all_tri_op(self,p_list,Born=False,even=True,alpha=1):
'''The Kraus operator is composed of only three in circuit DIII
sqrt(1-p) exp(i*phi* i* gamma_i * gamma_i+1), phi ~ U[0,2pi]; n=(0,cos(phi),sin(phi))
sqrt(p) (1+i* gamma_i * gamma_i+1)/2; n=(-1,0,0)
sqrt(p) (1-i* gamma_i * gamma_i+1)/2; n=(1,0,0)
For n_A, we literally take p, while for n_B we substitute the prob from p to 1-p
'''
proj_range=np.arange(self.L)*2 if even else np.arange(self.L)*2+1
# Why do you want to change the system sites to the later part?
# proj_range_1=proj_range if not self.op else proj_range+2* self.L
# proj_range_2=(proj_range+1)%(2*self.L) if not self.op else (proj_range+1)%(2*self.L) + 2*self.L
proj_range_1=proj_range
proj_range_2=(proj_range+1)%(2*self.L)
if isinstance(p_list, int) or isinstance(p_list, float):
p_list=np.array([p_list]*len(proj_range_1))
if self.history:
self.p_history.append(p_list)
else:
self.p_history=[p_list]
if Born:
for i,j,p in zip(proj_range_1,proj_range_2,p_list):
Gamma=self.C_m[[i],[j]]
n_list=get_Born_tri_op(p,Gamma,rng=self.rng,alpha=alpha)
if not self.pbc and not even and i==proj_range_1[-1]:
continue
self.measure(n_list[0],[i,j])
else:
n_list=get_random_tri_op(p_list,proj_range.shape[0],rng=self.rng)
for i,j,n in zip(proj_range_1,proj_range_2,n_list):
try:
self.measure(n,[i,j])
except:
n[0]=-n[0]
# This is a workaround to let it run, however, in forced measurement, the strong projection is problematic, as it can sometimes vanish the state
self.measure(n,[i,j])
def measure_all_tri_op_3(self,alpha_list,Born=False,sigma=1):
'''The Kraus operator is exp(i * alpha * gamma[0] * gamma[1]) * exp(i * alpha * gamma[1] * gamma[2])
'''
proj_range_0=np.arange(self.L*2)
# Why do you want to change the system sites to the later part?
# proj_range_1=proj_range if not self.op else proj_range+2* self.L
# proj_range_2=(proj_range+1)%(2*self.L) if not self.op else (proj_range+1)%(2*self.L) + 2*self.L
proj_range_1=(proj_range_0+1)%(2*self.L)
proj_range_2=(proj_range_0+2)%(2*self.L)
if isinstance(alpha_list, int) or isinstance(alpha_list, float):
alpha_list=np.array([alpha_list]*len(proj_range_1))
if self.history:
self.p_history.append(alpha_list)
else:
self.p_history=[alpha_list]
if Born:
for idx in range(len(proj_range_0)):
Gamma01=self.C_m[proj_range_0[idx],proj_range_1[idx]]
Gamma12=self.C_m[proj_range_1[idx],proj_range_2[idx]]
n1, n2_01 , n3_01, n2_12, n3_12 = get_Born_tri_op_3(alpha_list[idx],Gamma01, Gamma12, rng=self.rng,sigma=sigma)
self.measure([n1,n2_12, n3_12],[proj_range_1[idx],proj_range_2[idx]])
self.measure([n1,n2_01, n3_01],[proj_range_0[idx],proj_range_1[idx]])
else:
for idx in range(len(proj_range_0)):
# print(idx)
_, n2_01 , n3_01, n2_12, n3_12 = get_Born_tri_op_3(alpha_list[idx],0, 0, rng=self.rng,sigma=sigma)
self.measure([alpha_list[idx],n2_12, n3_12],[proj_range_1[idx],proj_range_2[idx]])
self.measure([alpha_list[idx],n2_01, n3_01],[proj_range_0[idx],proj_range_1[idx]])
def measure_all_tri_op_D(self,p_list,r_list,Born=True,even=True,sigma=1,eps_=1e-10):
'''The Kraus operator is composed of only three in circuit D-- with BDI as state
sqrt(1-p) exp(i*phi_1* i* gamma_{iA} * gamma_{jA})exp(i*phi_2* i* gamma_{iB} * gamma_{jB}), phi ~ U[0,2pi]; n=(0,cos(phi),sin(phi))
sqrt(p) (1+i* gamma_{iA} * gamma_{jB})/2; n=(-1,0,0)
sqrt(p) (1-i* gamma_{iA} * gamma_{jB})/2; n=(1,0,0)
For n_A, we literally take p, while for n_B we substitute the prob from p to 1-p
'''
site_A_left=np.arange(self.L)*2
site_B_left=np.arange(self.L)*2+1
if isinstance(p_list, int) or isinstance(p_list, float):
p_list=np.array([p_list]*(self.L))
if isinstance(r_list, int) or isinstance(r_list, float):
r_list=np.array([r_list]*(self.L))
if self.history:
self.p_history.append(p_list)
else:
self.p_history=[p_list]
if Born:
for idx in range(self.L):
r0=int(np.round(self.rng.uniform(r_list[idx]-1/2,r_list[idx]+1/2)))
if r0==0 and even:
# Majorana fermion (iA, iB),
# Here, choose between measurement and "trivial" unitary (i.e., identity) applied
legs_M=[site_A_left[idx],site_B_left[idx]]
Gamma=np.array([self.C_m[tuple(legs_M)]])
n_list=get_Born_tri_op(p_list[idx],Gamma,rng=self.rng,sigma=sigma)
# print(legs_M,Gamma[0],n_list)
if np.abs(n_list[0][0])>eps_:
# print(legs_M,Gamma[0],n_list)
self.measure(n_list[0],legs_M)
else:
if even:
# Majorana fermion (iA, iB, jA, jB), j=i+r
legs_U1=[site_A_left[idx],site_A_left[(idx+r0)%(self.L)]]
legs_U2=[site_B_left[idx],site_B_left[(idx+r0)%(self.L)]]
legs_M=[site_A_left[idx],site_B_left[(idx+r0)%(self.L)]]
else:
# Majorana fermion (iA, iB, i+r+1A, i+r+1B)
legs_U1=[site_A_left[idx],site_A_left[(idx+r0+1)%(self.L)]]
legs_U2=[site_B_left[idx],site_B_left[(idx+r0+1)%(self.L)]]
legs_M=[site_A_left[(idx+r0+1)%(self.L)],site_B_left[idx]]
Gamma=np.array([self.C_m[tuple(legs_M)]])
n_list=get_Born_tri_op(p_list[idx],Gamma,rng=self.rng,sigma=sigma)
if np.abs(n_list[0][0])<eps_:
# apply unitary
for legs in [legs_U1,legs_U2]:
Gamma=np.array([self.C_m[tuple(legs)]])
n_list=get_Born_tri_op(0,Gamma,rng=self.rng,sigma=sigma)
# print(legs,Gamma[0],n_list)
self.measure(n_list[0],legs)
else:
# print(legs_M,Gamma[0],n_list)
self.measure(n_list[0],legs_M)
# for idx,legs in enumerate([legs_U1,legs_U2,legs_M]):
# Gamma=np.array([self.C_m[tuple(legs_M)]])
# if idx<2:
# n_list=get_Born_tri_op(0,Gamma,rng=self.rng,sigma=1/16)
# self.measure(n_list[0],legs)
# else:
# n_list=get_Born_tri_op(p_list[idx],Gamma,rng=self.rng,sigma=1/16)
# if np.abs(n_list[0][0])>0:
# self.measure(n_list[0],legs_M)
#
def measure_list_tri_op(self,site_list,p_list,Born=True,):
'''site_list: [[i1,j1],[i2,j2],[i3,j3],...] measures [i1,j1], [i2,j2], [i3,j3] respectively
p_list: [p1,p2,p3,...] measures with prob p1,p2,p3, respectively
'''
if Born:
assert len(site_list)== len(p_list), f'site_list ({len(site_list)}) is not equal to p_list ({len(p_list)})'
for (i,j),p in zip(site_list,p_list):
Gamma=self.C_m[[i],[j]]
n_list=get_Born_tri_op(p,Gamma,rng=self.rng)
self.measure(n_list[0],[i,j])
else:
pass
def measure_list_tri_op_perfect_teleportation(self,site_list,p_list,Born=True,parity_dict=None):
'''site_list: [[i1,j1],[i2,j2],[i3,j3],...] measures [i1,j1], [i2,j2], [i3,j3] respectively
p_list: [p1,p2,p3,...] measures with prob p1,p2,p3, respectively
outcome: {(i,j): parity}
'''
if Born:
assert len(site_list)== len(p_list), f'site_list ({len(site_list)}) is not equal to p_list ({len(p_list)})'
for (i,j),p in zip(site_list,p_list):
Gamma=self.C_m[[i],[j]]
n_list=get_Born_tri_op(p,Gamma,rng=self.rng)
self.measure(n_list[0],[i,j])
if n_list[0] == [-1,0,0] or [1,0,0]:
# P_+ or P_-
other_leg=find_other_leg(parity_dict, (i,j))
if len(other_leg)==1:
self.measure([0,-1,0], [other_leg])
update_dictionary(parity_dict,(i,j),p=-n_list[0][0])
else:
# unitary
update_dictionary(parity_dict,(i,j),p=None)
else:
pass
def mutual_information_cross_ratio(self,ratio=[1,4],unitcell=1):
"""unitcell=1: shift each fermionic site
unitcell=2: shift "2-atom" unit cell
"""
x=np.array([0,self.L//ratio[1]*ratio[0],self.L//2,self.L//2+self.L//ratio[1]*ratio[0]])
# x=np.array([0,self.L//8,self.L//2,self.L//8*5])
MI=[]
subA=np.arange(x[0],x[1])
subB=np.arange(x[2],x[3])
for shift in np.arange(0,self.L//2,unitcell):
MI.append(self.mutual_information_m((subA+shift)%self.L, (subB+shift)%self.L))
return np.mean(MI)
# return MI
def tripartite_mutual_information_cross_ratio(self,ratio=[1,4],unitcell=1):
"""unitcell=1: shift each fermionic site
unitcell=2: shift "2-atom" unit cell
compute the tripartite mutual information as S(A)+S(B)+S(C)-S(AB)-S(BC)-S(AC)+S(ABC)
"""
x=np.array([0,self.L//ratio[1]*ratio[0],self.L//2,self.L//2+self.L//ratio[1]*ratio[0]])
# x=np.array([0,self.L//8,self.L//2,self.L//8*5])
MI=[]
subA=np.arange(x[0],x[1])
subB=np.arange(x[1],x[2])
subC=np.arange(x[2],x[3])
subD=np.arange(x[3],self.L)
for shift in np.arange(0,self.L//2,unitcell):
SA=self.von_Neumann_entropy_m((subA+shift)%self.L)
SB=self.von_Neumann_entropy_m((subB+shift)%self.L)
SC=self.von_Neumann_entropy_m((subC+shift)%self.L)
SAB=self.von_Neumann_entropy_m((np.concatenate([subA,subB])+shift)%self.L)
SBC=self.von_Neumann_entropy_m((np.concatenate([subB,subC])+shift)%self.L)
SAC=self.von_Neumann_entropy_m((np.concatenate([subA,subC])+shift)%self.L)
SABC=self.von_Neumann_entropy_m((subD+shift)%self.L)
MI.append(SA+SB+SC-SAB-SBC-SAC+SABC)
return np.mean(MI)
def entanglement_contour(self,subregion,fermion=False, Gamma=None):
# c_A=self.c_subregion_m(subregion)
c_A=self.c_subregion_m(subregion,Gamma)+1e-18j
C_f=(np.eye(c_A.shape[0])+1j*c_A)/2
f,_=la.funm(C_f,lambda x: -x*np.log(x),disp=False)
if fermion:
return np.diag(f).real.reshape((-1,2)).sum(axis=1)
else:
return np.diag(f).real
def mutual_information_m(self,subregion_A,subregion_B,Gamma=None):
''' Complex fermion site index'''
assert np.intersect1d(subregion_A,subregion_B).size==0 , "Subregion A and B overlap"
s_A=self.von_Neumann_entropy_m(subregion_A,Gamma)
s_B=self.von_Neumann_entropy_m(subregion_B,Gamma)
subregion_AB=np.concatenate([subregion_A,subregion_B])
s_AB=self.von_Neumann_entropy_m(subregion_AB,Gamma)
return s_A+s_B-s_AB
def conditional_mutual_information_m(self,subregion_A,subregion_B,subregion_C,Gamma=None):
"""compute the conditional mutual information I(A:B|C)=S(A|C)+S(B|C)-S(AB|C)-S(C)=S(AC)-S(C)+S(BC)-S(ABC)"""
s_AC=self.von_Neumann_entropy_m(np.concatenate([subregion_A,subregion_C]),Gamma)
s_BC=self.von_Neumann_entropy_m(np.concatenate([subregion_B,subregion_C]),Gamma)
s_ABC=self.von_Neumann_entropy_m(np.concatenate([subregion_A,subregion_B,subregion_C]),Gamma)
s_C=self.von_Neumann_entropy_m(subregion_C,Gamma)
return s_AC+s_BC-s_ABC-s_C
def von_Neumann_entropy_m(self,subregion,Gamma=None):
c_A=self.c_subregion_m(subregion,Gamma)
val=nla.eigvalsh(1j*c_A)
# self.val_sh=val
val=np.sort(val)
val=(1-val)/2+1e-18j #\lambda=(1-\xi)/2
return np.real(-np.sum(val*np.log(val))-np.sum((1-val)*np.log(1-val)))/2
def von_Neumann_entropy_m_self_average(self,Gamma=None,unitcell=1):
subregion=np.arange(0,self.L//2)
EE=[]
for shift in np.arange(0,self.L//2,unitcell):
EE.append(self.von_Neumann_entropy_m((subregion+shift)%self.L,Gamma))
return np.mean(EE)
def c_subregion_m(self,subregion,Gamma=None):
if Gamma is None:
Gamma=self.C_m
subregion=self.linearize_index(subregion,2)
return Gamma[np.ix_(subregion,subregion)]
def linearize_index(self,subregion,n,k=2,proj=False):
try:
subregion=np.array(subregion)
except:
raise ValueError("The subregion is ill-defined"+subregion)
if proj:
return np.int_(sorted(np.concatenate([n*subregion+i for i in range(0,n,k)])))
else:
return np.int_(sorted(np.concatenate([n*subregion+i for i in range(n)])))
def get_random_tri_op(p,num,rng=None):
rng=np.random.default_rng(rng)
sign=rng.random(size=num)
n1= (sign<p/2)*(-1)+(sign>1-p/2)
# n2,n3=get_inplane(n1, num,rng=rng)
n2,n3=get_inplane_norm(n1, num,rng=rng,sigma=np.pi/10)
return np.c_[n1,n2,n3]
def get_Born_tri_op(p,Gamma,rng=None,sigma=1,alpha=1):
"""sigma attenuate the variance of unitary, alpha suppress the strength of measurement"""
num=Gamma.shape[0]
rng=np.random.default_rng(rng)
sign=rng.random(size=num)
n1= (sign<p*(1+Gamma)/2)*(-1)+(sign>p*(1+Gamma)/2+1-p)
n1 = n1* alpha
n2,n3=get_inplane(n1, num,rng=rng,sigma=sigma)
return np.c_[n1,n2,n3]
def get_Born_tri_op_3(alpha,Gamma01,Gamma12,rng=None,sigma=1):
rng=np.random.default_rng(rng)
prob = 1/(2*np.cosh(2*alpha)**2) * (np.cosh(2*alpha)**2 + np.sinh(2*alpha) * np.cosh(2*alpha) * Gamma01 + np.sinh(2*alpha) * Gamma12)
print(prob)
sign = rng.random()
n1 = (sign < prob) * np.tanh(alpha) + (sign>prob) * (-np.tanh(alpha))
n2_01,n3_01=get_inplane(n1, 1,rng=rng,sigma=sigma)
n2_12,n3_12=get_inplane(n1, 1,rng=rng,sigma=sigma)
return n1, n2_01[0] , n3_01[0], n2_12[0], n3_12[0]
def get_Born_class_AIII(A,Gamma,class_A=False,rng=None):
rng=np.random.default_rng(rng)
prob={(s1,s2): Gamma[0,1]*(-s1-s2)/8*A + Gamma[0,3]*(-s1+s2)/8*A + Gamma[1,2]*(s1-s2)/8*A + Gamma[2,3]*(-s1-s2)/8*A - (-Gamma[0,1]*Gamma[2,3]+Gamma[0,2]*Gamma[1,3]-Gamma[0,3]*Gamma[1,2])*s1*s2*A**2/4+1/4 for s1 in [-1,1] for s2 in [-1,1]}
# print([f'{key}:{val:.2f}' for key,val in prob.items()])
for key,val in prob.items():
assert val>-1e-9, f'{key} < 0 = {val}, {prob}'
assert val<1+1e-9, f'{key} > 1 = {val}'
if prob[key]>1 or prob[key]<0:
prob[key]=np.clip(val,0.,1.)
if not class_A:
kind=rng.choice(list(prob.keys()),p=list(prob.values()))
else:
post_selected_outcome=[(-1,1),(1,-1)]
norm= sum(prob[i] for i in post_selected_outcome)
kind=rng.choice(post_selected_outcome,p=[prob[i]/norm for i in post_selected_outcome])
theta=rng.uniform(-np.pi,np.pi,size=2)
return tuple(kind), theta[0],theta[1]
def get_Born_single_mode(Gamma,mode,rng=None):
"""get the outcome of Born measurement for a single mode, 0 or 1, where mode is sum mode[i] c_i^dag"""
rng=np.random.default_rng(rng)
prob = get_Born(Gamma,mode)
if rng.random()< prob:
return 1
else:
return 0
def get_Born_class_AIII_unitary(A,Gamma,class_A=False,rng=None):
"""here the only difference is the inclusion of extra basis, maybe a good idea is to rederived
extend from iA, jB to iA, iB, jA, jB,
(0,1,2,3): iA, jB
is mapped to
(iA, iB, jA, jB): (0,1,2,3,4,5,6,7), """
rng=np.random.default_rng(rng)
prob={(s1,s2): Gamma[0,1]*(-s1-s2)/8*A + Gamma[0,7]*(-s1+s2)/8*A + Gamma[1,6]*(s1-s2)/8*A + Gamma[6,7]*(-s1-s2)/8*A - (-Gamma[0,1]*Gamma[6,7]+Gamma[0,6]*Gamma[1,7]-Gamma[0,7]*Gamma[1,6])*s1*s2*A**2/4+1/4 for s1 in [-1,1] for s2 in [-1,1]}
for key,val in prob.items():
assert val>-1e-9, f'{key} < 0 = {val}, {prob}'
assert val<1+1e-9, f'{key} > 1 = {val}'
if prob[key]>1 or prob[key]<0:
prob[key]=np.clip(val,0.,1.)
if not class_A:
kind=rng.choice(list(prob.keys()),p=list(prob.values()))
else:
post_selected_outcome=[(-1,1),(1,-1)]
norm= sum(prob[i] for i in post_selected_outcome)
kind=rng.choice(post_selected_outcome,p=[prob[i]/norm for i in post_selected_outcome])
theta=rng.uniform(-np.pi,np.pi,size=2)
return tuple(kind), theta[0],theta[1]
def get_random(a1,a2,b1,b2,num,rng=None,theta_list=0,phi_list=0):
'''
-b1<-a1<a2<b2
n1=True: nA=(n1,n2,n3)
n1=True: nB=(n3,n1,n2)
'''
assert -b1<=-a1<=a2<=b2, "the order of -b1<-a1<a2<b2 not satisfied"
rng=np.random.default_rng(rng)
sign=rng.random(size=num)
k=1/(b1-a1+b2-a2)
n1=np.where(sign<(b1-a1)*k,sign/k-b1,(sign-k*(b1-a1))/k+a2)
# inverse of CDF
# n1=np.where(sign<.5,sign*2*(b1-a1)-b1,(sign-1/2)*2*(b2-a2)+a2)
# use rescale
# n1=np.where(sign<0.5,rescale(sign,y0=-b1,y1=-a1,x0=0,x1=.5),rescale(sign,y0=a2,y1=b2,x0=.5,x1=1))
# complete random
# n1=np.random.uniform(b2,b1-a1+a2,num)
# n1=np.where(n1<a2,n1,n1+(a1-a2))
n2,n3=get_inplane(n1, num,rng=rng)
n=np.c_[n1,n2,n3]
return rotate(n,theta_list,phi_list)
def get_O(rng,n):
rng=np.random.default_rng(rng)
A=rng.normal(size=(n,n))
AA=(A-A.T)/2
return la.expm(AA)
def rotate(n,theta,phi):
n=np.c_[np.cos(theta)*n[:,0]-np.sin(theta)*n[:,1],np.sin(theta)*n[:,0]+np.cos(theta)*n[:,1],n[:,2]]
n=np.c_[np.cos(phi)*n[:,0]+np.sin(phi)*n[:,2],n[:,1],-np.sin(phi)*n[:,0]+np.cos(phi)*n[:,2]]
return n
def get_inplane(n1,num,rng=None,sigma=1):
r=np.sqrt(1-n1**2)
rng=np.random.default_rng(rng)
phi=rng.random(num)*2*np.pi*sigma
n2,n3=r*np.cos(phi),r*np.sin(phi)
return n2,n3
def get_inplane_norm(n1,num,rng=None,sigma=np.pi/4,mu=0):
r=np.sqrt(1-n1**2)
rng=np.random.default_rng(rng)
phi=rng.normal(loc=mu,scale=sigma,size=num)
n2,n3=r*np.cos(phi),r*np.sin(phi)
return n2,n3
def get_Born_A(a1,a2,b1,b2,Gamma,rng=None,):
'''
-b1<-a1<a2<b2
Gamma: list for all parities
n1=True: nA=(n1,n2,n3)
n1=True: nB=(n3,n1,n2)
'''
assert -b1<=-a1<=a2<=b2, "the order of -b1<-a1<a2<b2 not satisfied"
num=Gamma.shape[0]
rng=np.random.default_rng(rng)
u=rng.random(size=num)
theta1,theta2=(a2+b2)/((b1-a1)*(a1+a2+b1+b2)),(a1+b1)/((b2-a2)*(a1+a2+b1+b2))
bndy=theta1*(-a1+b1-1/2*(a1**2-b1**2)*Gamma)
coef1=-1/2*theta1*Gamma,theta1,theta1*b1+1/2*theta1*b1**2*Gamma
coef2=-1/2*theta2*Gamma,theta2,theta1*(-a1+b1-(a1**2-b1**2)*Gamma/2)+a2**2*Gamma*theta2/2-theta2*a2
n1=np.where(u<bndy,solve(coef1,u),solve(coef2,u))
n2,n3=get_inplane(n1, num,rng=rng)
n=np.c_[n1,n2,n3]
return n
# return rotate(n,theta_list,phi_list)
def get_Born_B(a1,a2,b1,b2,Gamma,rng=None):
'''
-b1<-a1<a2<b2
Gamma: list for all parities
n1=True: nA=(n1,n2,n3)
n1=True: nB=(n3,n1,n2)
'''
assert -b1<=-a1<=a2<=b2, "the order of -b1<-a1<a2<b2 not satisfied"
# num=Gamma.shape[0]
rng=np.random.default_rng(rng)
s=get_random(a1,a2,b1,b2,num=1,rng=rng)[0,0]
# w1=(a2+b2)/((b1-a1)*(a1+a2+b1+b2))
# w2=(a1+b1)/((b2-a2)*(a1+a2+b1+b2))
# bndy=w1*(b1-a1)
# u=rng.random()
# s=np.where(u<bndy,u/w1-b1,(u-w1*(b1-a1))/w2+a2)
phi=get_random_phi(s,Gamma[0],rng.random())
# return s,phi
return np.array([[np.sin(phi)*np.sqrt(1-s**2),s,np.cos(phi)*np.sqrt(1-s**2)]])
def get_random_phi(s,Gamma,u):
phi=0
while np.abs((phi-np.sqrt(1-s**2)*Gamma*(1-np.cos(phi)))/(2*np.pi)-u)>1e-8:
phi=u*2*np.pi+np.sqrt(1-s**2)*Gamma*(1-np.cos(phi))
return phi
def get_Haar(sigma,num,rng=None,theta_list=0,phi_list=0):
rng=np.random.default_rng(rng)
u=rng.random(size=num)
n1=rescale(u, 1-2*sigma, 1)
n2,n3=get_inplane(n1, num,rng=rng)
n=np.c_[n1,n2,n3]
return rotate(n,theta_list,phi_list)
def solve(coef,u):
a,b,c=coef
c=c-u
with np.errstate(invalid='ignore'):
n1=np.where(a==0,-c/b,(-b+np.sqrt(b**2-4*a*c))/(2*a) )
return n1
def rescale(x,y0,y1,x0=0,x1=1):
"""rescale a range [x0,x1] to [y0,y1] using linear map"""
return (y1-y0)/(x1-x0)*(x-x0)+y0
def cross_ratio(x,L):
if L<np.inf:
xx=lambda i,j: (np.sin(np.pi/(L)*np.abs(x[i]-x[j])))
else:
xx=lambda i,j: np.abs(x[i]-x[j])
eta=(xx(0,1)*xx(2,3))/(xx(0,2)*xx(1,3))
return eta