-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathOur_Qiskit_Functions.py
1678 lines (1466 loc) · 47.6 KB
/
Our_Qiskit_Functions.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
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, transpile
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
#from qiskit.extensions.simulator import snapshot
#from qiskit.tools.visualization import circuit_drawer
import numpy as np
import math as m
import scipy as sci
import random
import time
import matplotlib
import matplotlib.pyplot as plt
import ipywidgets as wd
S_simulator = Aer.backends(name='statevector_simulator')[0]
M_simulator = Aer.backends(name='qasm_simulator')[0]
def execute(circuit, backend, **kwargs):
s = 1024
if 'shots' in kwargs:
s = int( kwargs['shots'] )
new_circuit = transpile(circuit, backend)
return backend.run(new_circuit, shots = s)
#Displaying Results
def Wavefunction( obj , *args, **kwargs):
#Displays the wavefunction of the quantum system
if(type(obj) == QuantumCircuit ):
statevec = execute( obj, S_simulator, shots=1 ).result().get_statevector()
if(type(obj) == np.ndarray):
statevec = obj
sys = False
NL = False
dec = 5
if 'precision' in kwargs:
dec = int( kwargs['precision'] )
if 'column' in kwargs:
NL = kwargs['column']
if 'systems' in kwargs:
systems = kwargs['systems']
sys = True
last_sys = int(len(systems)-1)
show_systems = []
for s_chk in range(len(systems)):
if( type(systems[s_chk]) != int ):
raise Exception('systems must be an array of all integers')
if 'show_systems' in kwargs:
show_systems = kwargs['show_systems']
if( len(systems)!= len(show_systems) ):
raise Exception('systems and show_systems need to be arrays of equal length')
for ls in range(len(show_systems)):
if((show_systems[ls] != True) and (show_systems[ls] != False)):
raise Exception('show_systems must be an array of Truth Values')
if(show_systems[ls] == True):
last_sys = int(ls)
else:
for ss in range(len(systems)):
show_systems.append(True)
wavefunction = ''
qubits = int(m.log(len(statevec),2))
for i in range(int(len(statevec))):
#print(wavefunction)
value = round(statevec[i].real, dec) + round(statevec[i].imag, dec) * 1j
if( (value.real != 0) or (value.imag != 0)):
state = list(Binary(int(i),int(2**qubits)))
state.reverse()
state_str = ''
#print(state)
if( sys == True ): #Systems and SharSystems
k = 0
for s in range(len(systems)):
if(show_systems[s] == True):
if(int(s) != last_sys):
state.insert(int(k + systems[s]), '>|' )
k = int(k + systems[s] + 1)
else:
k = int(k + systems[s])
else:
for s2 in range(systems[s]):
del state[int(k)]
for j in range(len(state)):
if(type(state[j])!= str):
state_str = state_str + str(int(state[j]))
else:
state_str = state_str + state[j]
#print(state_str)
#print(value)
if( (value.real != 0) and (value.imag != 0) ):
if( value.imag > 0):
wavefunction = wavefunction + str(value.real) + '+' + str(value.imag) + 'j |' + state_str + '> '
else:
wavefunction = wavefunction + str(value.real) + '' + str(value.imag) + 'j |' + state_str + '> '
if( (value.real !=0 ) and (value.imag ==0) ):
wavefunction = wavefunction + str(value.real) + ' |' + state_str + '> '
if( (value.real == 0) and (value.imag != 0) ):
wavefunction = wavefunction + str(value.imag) + 'j |' + state_str + '> '
if(NL):
wavefunction = wavefunction + '\n'
#print(NL)
print(wavefunction)
return wavefunction
def Measurement(quantumcircuit, *args, **kwargs):
#Displays the measurement results of a quantum circuit
p_M = True
S = 1
ret = False
NL = False
if 'shots' in kwargs:
S = int(kwargs['shots'])
if 'return_M' in kwargs:
ret = kwargs['return_M']
if 'print_M' in kwargs:
p_M = kwargs['print_M']
if 'column' in kwargs:
NL = kwargs['column']
M1 = execute(quantumcircuit, M_simulator, shots=S).result().get_counts(quantumcircuit)
M2 = {}
k1 = list(M1.keys())
v1 = list(M1.values())
for k in range(len(k1)):
key_list = list(k1[k])
new_key = ''
for j in range(len(key_list)):
new_key = new_key+key_list[len(key_list)-(j+1)]
M2[new_key] = v1[k]
if(p_M):
k2 = list(M2.keys())
v2 = list(M2.values())
measurements = ''
for i in range(len(k2)):
m_str = str(v2[i])+'|'
for j in range(len(k2[i])):
if(k2[i][j] == '0'):
m_str = m_str + '0'
if(k2[i][j] == '1'):
m_str = m_str + '1'
if( k2[i][j] == ' ' ):
m_str = m_str +'>|'
m_str = m_str + '> '
if(NL):
m_str = m_str + '\n'
measurements = measurements + m_str
print(measurements)
if(ret):
return M2
def Most_Probable(M,N):
'''
Input: M (Dictionary) N (integer)
Returns the N most probable states accoding to the measurement counts stored in M
'''
count = []
state = []
if( len(M) < N ):
N = len(M)
for k in range(N):
count.append(0)
state.append(0)
for m in range(len(M)):
new = True
for n in range(N):
if( (list(M.values())[m] > count[n]) and new ):
for i in range( N-(n+1)):
count[-int(1+i)] = count[-int(1+i+1)]
state[-int(1+i)] = state[-int(1+i+1)]
count[int(n)] = list(M.values())[m]
state[int(n)] = list(M.keys())[m]
new = False
return count,state
#Math Operations
def Oplus(bit1,bit2):
'''Adds too bits of O's and 1's (modulo 2)'''
bit = np.zeros(len(bit1))
for i in range( len(bit) ):
if( (bit1[i]+bit2[i])%2 == 0 ):
bit[i] = 0
else:
bit[i] = 1
return bit
def Binary(number,total):
#Converts a number to binary, right to left LSB 152 153 o
qubits = int(m.log(total,2))
N = number
b_num = np.zeros(qubits)
for i in range(qubits):
if( N/((2)**(qubits-i-1)) >= 1 ):
b_num[i] = 1
N = N - 2 ** (qubits-i-1)
B = []
for j in range(len(b_num)):
B.append(int(b_num[j]))
return B
def BinaryL(number,total):
B = Binary(number, total)
B.reverse()
return B
def From_Binary(s):
num = 0
for i in range(len(s)):
num = num + int(s[-(i+1)]) * 2**i
return num
def From_BinaryLSB(S, LSB):
num = 0
for i in range(len(S)):
if(LSB=='R'):
num = num + int(S[-(i+1)]) * 2**i
elif(LSB=='L'):
num = num + int(S[i]) * 2**i
return num
def B2D(in_bi):
len_in = len(in_bi)
in_bi = in_bi[::-1]
dec = 0
for i in range(0,len_in):
if in_bi[i] != '0':
dec += 2**i
return dec
# Custom Gates
def X_Transformation(qc, qreg, state):
#Tranforms the state of the system, applying X gates according to as in the vector 'state'
for j in range(len(state)):
if( int(state[j]) == 0 ):
qc.x( qreg[int(j)] )
def n_NOT(qc, control, target, anc):
#performs an n-NOT gate
n = len(control)
instructions = []
active_ancilla = []
q_unused = []
q = 0
a = 0
while(n > 0):
if(n >= 2):
instructions.append( [control[q], control[q+1], anc[a]] )
active_ancilla.append(a)
a += 1
q += 2
n -= 2
if(n == 1):
q_unused.append(q)
n -= 1
while (len(q_unused) != 0):
if(len(active_ancilla)!=1):
instructions.append( [control[q], anc[active_ancilla[0]], anc[a]] )
del active_ancilla[0]
del q_unused[0]
active_ancilla.append(a)
a += 1
else:
instructions.append( [control[q], anc[active_ancilla[0]], target] )
del active_ancilla[0]
del q_unused[0]
while(len(active_ancilla) != 0):
if( len(active_ancilla) > 2 ):
instructions.append( [anc[active_ancilla[0]], anc[active_ancilla[1]], anc[a]] )
active_ancilla.append(a)
del active_ancilla[0]
del active_ancilla[0]
a += 1
elif( len(active_ancilla) == 2):
instructions.append([anc[active_ancilla[0]], anc[active_ancilla[1]], target])
del active_ancilla[0]
del active_ancilla[0]
elif( len(active_ancilla) == 1):
instructions.append([anc[active_ancilla[0]], target])
del active_ancilla[0]
for i in range( len(instructions) ):
if len(instructions[i]) == 2:
qc.cx( instructions[i][0], instructions[i][1])
else:
qc.ccx( instructions[i][0], instructions[i][1], instructions[i][2] )
del instructions[-1]
for i in range( len(instructions) ):
qc.ccx( instructions[0-(i+1)][0], instructions[0-(i+1)][1], instructions[0-(i+1)][2] )
def Control_Instruction( qc, vec ):
#Ammends the proper quantum circuit instruction based on the input 'vec'
#Used for the function 'n_Control_U
if( vec[0] == 'X' ):
qc.cx( vec[1], vec[2] )
elif( vec[0] == 'Z' ):
qc.cz( vec[1], vec[2] )
elif( vec[0] == 'CPHASE' ):
qc.cu1( vec[2], vec[1], vec[3] )
elif( vec[0] == 'SWAP' ):
qc.cswap( vec[1], vec[2], vec[3] )
def sinmons_solver(E,N):
'''Returns an array of s_prime candidates
'''
s_primes = []
for s in np.ararge(1,2**N):
sp = Binary( int(s), 2**N )
candidate = True
for e in range( len(E) ):
value = 0
for i in range( N ):
value = value + sp[i]*E[e][i]
if(value%2==1):
candidate=False
if(candidate):
s_primes.append(sp)
return s_primes
def Grover_Oracle(mark, qc, q, an1, an2):
'''
picks out the marked state and applies a negative phase
'''
qc.h( an1[0] )
X_Transformation(qc, q, mark)
if( len(mark) > 2 ):
n_NOT( qc, q, an1[0], an2 )
elif( len(mark) == 2 ):
qc.ccx( q[0], q[1], an1[0] )
X_Transformation(qc, q, mark)
qc.h( an1[0] )
def Grover_Diffusion(mark, qc, q, an1, an2):
'''
ammends the instructions for a Grover Diffusion Operation to the Quantum Circuit
'''
zeros_state = []
for i in range( len(mark) ):
zeros_state.append( 0 )
qc.h( q[int(i)] )
Grover_Oracle(zeros_state, qc, q, an1, an2)
for j in range( len(mark) ):
qc.h( q[int(j)] )
def Grover(Q, marked):
'''
Amends all the instructions for a Grover Search
'''
q = QuantumRegister(Q,name='q')
an1 = QuantumRegister(1,name='anc')
an2 = QuantumRegister(Q-2,name='nanc')
c = ClassicalRegister(Q,name='c')
qc = QuantumCircuit(q,an1,an2,c,name='qc')
for j in range(Q):
qc.h( q[int(j)] )
qc.x( an1[0] )
iterations = round( m.pi/4 * 2**(Q/2.0) )
for i in range( iterations ):
Grover_Oracle(marked, qc, q, an1, an2)
Grover_Diffusion(marked, qc, q, an1, an2)
return qc, q, an1, an2, c
def Multi_Grover(q, a1, a2, qc, marked, iters):
'''
Input: q (QuantumRegister) a1 (QuantumRegister) a2 (QuantumRegister) qc (QuantumCircuit)
marked (array) iters (integer)
Appends all of the gate operations for a multi-marked state Grover Search
'''
Q = int(len(marked))
for i in np.arange( iters ):
for j in np.arange(len(marked)):
M = list(marked[j])
for k in np.arange(len(M)):
if(M[k]=='1'):
M[k] = 1
else:
M[k] = 0
Grover_Oracle(M, qc, q, a1, a2)
Grover_Diffusion(M, qc, q, a1, a2)
return qc, q, a1, a2
def n_Control_U(qc, control, anc, gates):
#Performs a list of single control gates, as an n-control operation
instructions = []
active_ancilla = []
q_unused = []
n = len(control)
q = 0
a = 0
while(n > 0):
if(n >= 2) :
instructions.append([control[q], control[q+1], anc[a]])
active_ancilla.append(a)
a += 1
q += 2
n -= 2
if(n == 1):
q_unused.append( q )
n -= 1
while( len(q_unused) != 0 ) :
if(len(active_ancilla)>1):
instructions.append( [control[q] , anc[active_ancilla[0]], anc[a]])
del active_ancilla[0]
del q_unused[0]
active_ancilla.append(a)
a += 1
else:
instructions.append( [control[q] , anc[active_ancilla[0]], anc[a]])
del active_ancilla[0]
del q_unused[0]
c_a = anc[a]
while( len(active_ancilla) != 0 ) :
if( len(active_ancilla) > 2 ) :
instructions.append([anc[active_ancilla[0]], anc[active_ancilla[1]], anc[a]])
active_ancilla.append(a)
del active_ancilla[0]
del active_ancilla[0]
a += 1
elif( len(active_ancilla)==2):
instructions.append([anc[active_ancilla[0]], anc[active_ancilla[1]], anc[a]])
del active_ancilla[0]
del active_ancilla[0]
c_a = anc[a]
elif( len(active_ancilla)==1):
c_a = anc[active_ancilla[0]]
del active_ancilla[0]
for i in range( len(instructions) ) :
qc.ccx(instructions[i][0], instructions[i][1], instructions[i][2])
for j in range(len(gates)):
control_vec = [gates[j][0], c_a]
for k in range( 1, len(gates[j])):
control_vec.append( gates[j][k] )
Control_Instruction( qc, control_vec )
for i in range( len(instructions) ) :
qc.ccx(instructions[0-(i+1)][0],instructions[0-(i+1)][1], instructions[0-(i+1)][2])
def Control_Instructions(qc, vec):
if (vec[0] == 'X'):
qc.cx(vec[1], vec[2])
elif (vec[0] == 'Z'):
qc.cz(vec[1], vec[2])
def Blackbox_g_D(qc, qreg):
f_type=['f(0,1) -> (0,1)', 'f(0,1) -> (1,0)', 'f(0,1) -> 0', 'f(0,1) -> 1']
r = int(m.floor(4*np.random.rand()))
if (r == 0):
qc.cx(qreg[0],qreg[1])
if (r == 1):
qc.x(qreg[0])
qc.cx(qreg[0],qreg[1])
qc.x(qreg[0])
if (r == 2):
qc.id(qreg[0])
qc.id(qreg[1])
if (r == 3):
qc.x(qreg[1])
return f_type[r]
def Deutsch(qc,qreg):
qc.h(qreg[0])
qc.h(qreg[1])
f = Blackbox_g_D(qc, qreg)
qc.h(qreg[0])
qc.h(qreg[1])
return f
def Blackbox_g_DJ(Q, qc, qreg, an1):
f_type=['constant','balanced']
f=[]
r=int(m.floor(2**Q*np.random.rand()))
if r==0:
f.append(f_type[0])
elif r == 1:
qc.x(qreg[Q-1])
f.append(f_type[0])
else:
control = []
for i in range(Q):
control.append(qreg[i])
an2 = QuantumRegister(int(Q-2), name='nn_anc')
qc.add_register(an2)
f.append(f_type[1])
S=[]
for s in range(2**Q):
S.append(s)
for k in range(2**(Q-1)):
S_num = S[int(m.floor(len(S)*np.random.rand()))]
state = Binary(S_num,2**Q)
S.remove(S_num)
f_string = '|'
for j in range(len(state)):
f_string += str(int(state[j]))
if (state[j] == 0):
qc.x(qreg[j])
f.append(f_string + '>')
n_NOT(qc, control, an1[0], an2)
for j in range(len(state)):
if (state[j] == 0):
qc.x(qreg[j])
return f
def Deutsch_Josza(Q,qc,qreg,an1):
for i in range(Q):
qc.h(qreg[i])
qc.h(an1[0])
f = Blackbox_g_DJ(Q, qc, qreg, an1)
for i in range(Q):
qc.h(qreg[i])
qc.h(an1[0])
return f
def Blackbox_g_BV(Q,qc,qreg,an1):
a = Binary(int(m.floor(2**Q*np.random.rand())),2**Q)
control=[]
for i in range(Q):
control.append(qreg[i])
an2 = QuantumRegister(Q-2,name='nn_anc')
qc.add_register(an2)
for s in range(2**Q):
state = Binary(s,2**Q)
dp = np.vdot(a, state)
if (dp % 2 == 1):
for j in range(len(state)):
if int(state[j]) == 0:
qc.x(qreg[j])
n_NOT(qc, control, an1[0], an2)
for j in range(len(state)):
if int(state[j]) == 0:
qc.x(qreg[j])
return a
def Bernstein_Vazirani(Q,qc,qreg,an1):
for i in range(Q):
qc.h(qreg[i])
qc.h(an1[0])
a = Blackbox_g_BV(Q,qc,qreg,an1)
for i in range(Q):
qc.h(qreg[i])
qc.h(an1[0])
return a
def Blackbox_g_S(Q, qc, q, anc1):
anc2 = QuantumRegister(Q-1,name='nU_anc')
qc.add_register(anc2)
s = np.zeros(Q)
for i in range(Q):
s[i] = int(m.floor(2*np.random.rand()))
outputs=[]
for o in range(2**Q):
outputs.append(o)
f = np.zeros(2**Q)
for j in range(2**Q):
out = outputs[int(m.floor(len(outputs)*np.random.rand()))]
f[j] = out
f[int(From_Binary(Oplus(Binary(j, 2**Q),s)))] = out
outputs.remove(out)
output_states=[]
for k in range(2**Q):
output_states.append(Binary(f[k],2**Q))
for a in range(2**Q):
c_ops=[]
for b in range(Q):
if output_states[a][b] == 1:
c_ops.append(['X', anc1[b]])
X_Transformation(qc, q, Binary(a, 2**Q))
n_Control_U(qc, q, anc2, c_ops)
# instead of n_Control_U it would work witn n_NOT as well, but the overhead would be much higher:
#for b in range(Q):
# if output_states[a][b] == 1:
# n_NOT(qc, q, anc1[b], anc2)
X_Transformation(qc, q, Binary(a, 2**Q))
return qc, s, f
def Simons_Quantum(Q, qc, q, c, anc1):
for i in range(Q):
qc.h(q[i])
qc,s,f = Blackbox_g_S(Q,qc,q, anc1)
for i in range(Q):
qc.h(q[i])
qc.measure(q,c)
return qc, s
def Simons_Solver(E,N):
s_primes = []
for s in range(1, 2**N):
sp = Binary(s, 2**N)
candidate = True
for e in range(len(E)):
value = 0
for i in range(N):
value += sp[i] * E[e][i]
if value%2 == 1:
candidate = False
if candidate:
s_primes.append(sp)
return s_primes
def Simons_Classical(Q, qc):
run_quantum = True
Equations = []
Results = []
quantum_runs = 0
while(run_quantum):
quantum_runs += 1
M = Measurement(qc, shots = 20, return_M = True, print_M = False)
new_result = True
for r in range(len(Results)):
if list(M.keys())[0] == Results[r]:
new_result = False
break
if new_result:
Results.append(list(M.keys())[0])
eq = []
for e in range(Q):
eq.append(int(list(M.keys())[0][e]))
Equations.append(eq)
s_primes = Simons_Solver(Equations, Q)
if len(s_primes) == 1:
run_quantum = False
return s_primes, Results, quantum_runs
def DFT(x, **kwargs):
p = -1.0
if 'inverse' in kwargs:
P = kwargs['inverse']
if P == True:
p = 1.0
L = len(x)
X = []
for i in range(L):
value = 0
for j in range(L):
value += x[j] * np.exp(p * 2 * m.pi * 1.0j * i * j / L)
X.append(value)
for k in range(len(X)):
re = round(X[k].real,5)
im = round(X[k].imag,5)
if abs(im) == 0 and abs(re) != 0:
X[k] = re
elif abs(re) == 0 and abs(im) != 0:
X[k] = im * 1.0j
elif abs(re) == 0 and abs(im) == 0:
X[k] = 0
else:
X[k] = re + im * 1.0j
return X
def QFT(qc, q, qubits, **kwargs):
R_phis = [0]
for i in range(2, qubits+1):
R_phis.append( 2/(2**i) * m.pi )
for j in range(qubits):
qc.h( q[j] )
for k in range(qubits-j-1):
qc.cp( R_phis[k+1], q[j+k+1], q[j] )
if 'swap' in kwargs:
if(kwargs['swap'] == True):
for s in range(m.floor(qubits/2.0)):
qc.swap( q[s],q[qubits-1-s] )
def QFT_dgr(qc, q, qubits, **kwargs):
if 'swap' in kwargs:
if(kwargs['swap'] == True):
for s in range(m.floor(qubits/2.0)):
qc.swap( q[s],q[qubits-1-s] )
R_phis = [0]
for i in range(2,qubits+1):
R_phis.append( -2/(2**i) * m.pi )
for j in range(qubits):
for k in range(j):
qc.cp(R_phis[j-k], q[qubits-k-1], q[qubits-j-1] )
qc.h( q[qubits-j-1] )
def Quantum_Adder(qc, Qa, Qb, A, B):
Q = len(B)
for n in range(Q):
if( A[n] == 1 ):
qc.x( Qa[n+1] )
if( B[n] == 1 ):
qc.x( Qb[n] )
QFT(qc,Qa,Q+1)
p = 1
for j in range( Q ):
qc.cp( m.pi/(2**p), Qb[j], Qa[0] )
p = p + 1
for i in range(1,Q+1):
p = 0
for jj in np.arange( i-1, Q ):
qc.cp( m.pi/(2**p), Qb[jj], Qa[i] )
p = p + 1
QFT_dgr(qc,Qa,Q+1)
def QPE_phi(MP):
ms = [[],[]]
for i in range(2):
for j in range(len(MP[1][i])):
ms[i].append(int(MP[1][i][j]))
n = int(len(ms[0]))
MS1 = From_Binary(ms[0])
MS2 = From_Binary(ms[1])
estimatedProb = MP[0][0]
aproxPhi = 0
aproxProb = 1
for k in np.arange(1,5000):
phi = k/5000
prob = 1/(2**(2*n)) * abs((-1 + np.exp(2.0j*m.pi*phi) )/(-1 + np.exp(2.0j*m.pi*phi/(2**n))))**2
if abs(prob - estimatedProb) < abs(aproxProb - estimatedProb):
aproxProb = prob
aproxPhi = phi
if( (MS1 < MS2) and ( (MS1!=0) and (MS2!=(2**n-1)) ) ):
theta = (MS1+aproxPhi)/(2**n)
elif( (MS1 > MS2) and (MS1!=0) ):
theta = (MS1-aproxPhi)/(2**n)
else:
theta = 1+(MS1-aproxPhi)/(2**n)
return aproxPhi,theta
def C_Oracle(qc, c, q, a1, a2, state):
#qc.barrier()
N = len(q)
for i in np.arange(N):
if( state[i]==0 ):
qc.cx( c, q[int(i)] )
#---------------------------------
qc.ccx( q[0], q[1], a1[0] )
for j1 in np.arange(N-2):
qc.ccx( q[int(2+j1)], a1[int(j1)], a1[int(1+j1)] )
qc.ccx( c, a1[N-2], a2[0] )
for j2 in np.arange(N-2):
qc.ccx( q[int(N-1-j2)], a1[int(N-3-j2)], a1[int(N-2-j2)] )
qc.ccx( q[0], q[1], a1[0] )
#---------------------------------
for i2 in np.arange(N):
if( state[i2]==0 ):
qc.cx( c, q[int(i2)] )
#qc.barrier()
def C_Diffusion(qc, c, q, a1, a2, ref):
#qc.barrier()
Q = len(q)
N = 2**( Q )
for j in np.arange(Q):
qc.ch( c, q[int(j)] )
if( ref ):
for k in np.arange(1,N):
C_Oracle(qc,c,q,a1,a2,Binary(int(k),N))
else:
C_Oracle(qc,c,q,a1,a2,Binary(0,N))
for j2 in np.arange(Q):
qc.ch( c, q[int(j2)] )
#qc.barrier()
def C_Grover(qc, c, q, a1, a2, marked, **kwargs):
#qc.barrier()
Reflection=False
if 'proper' in kwargs:
Reflection = kwargs['proper']
M = []
for m1 in np.arange( len(marked) ):
M.append( list(marked[m1]) )
for m2 in np.arange( len(M[m1]) ):
M[m1][m2] = int( M[m1][m2] )
for i in np.arange(len(M)):
C_Oracle( qc,c,q,a1,a2,M[i] )
C_Diffusion( qc,c,q,a1,a2,Reflection )
#qc.barrier()
def GCD(a, b):
gcd = 0
if(a > b):
num1 = a
num2 = b
elif(b > a):
num1 = b
num2 = a
elif(a == b):
gcd = a
while( gcd == 0 ):
i = 1
while( num1 >= num2*i ):
i = i + 1
if( num1 == num2*(i-1) ):
gcd = num2
else:
r = num1 - num2*(i-1)
num1 = num2
num2 = r
return gcd
def Euclids_Alg(a, b):
if(a>=b):
num1 = a
num2 = b
else:
num1 = b
num2 = a
r_new = int( num1%num2 )
r_old = int( num2 )
while(r_new!=0):
r_old = r_new
r_new = int( num1%num2 )
num1 = num2
num2 = r_new
gcd = r_old
return gcd
def Modulo_f(Q, a, N):
mods = []
num = a%N
for i in np.arange(1,2**Q):
mods.append(num)
num = (num*a)%N
return mods
def Mod_Op(Q, qc, q1, q2, anc, a, N):
#mods = Modulo_f(Q,a,N)
num = a%N
for j in np.arange( 2**Q ):
q1_state = BinaryL( j, 2**Q )
#q2_state = BinaryL( mods[j-1], 2**Q )
q2_state = BinaryL(num, 2**Q )
num = (num*a)%N
X_Transformation(qc,q1,q1_state)
gates = []
for k in np.arange(Q):
if(q2_state[k]==1):
gates.append(['X',q2[int(k)]])
n_Control_U(qc, q1, anc, gates)
X_Transformation(qc,q1,q1_state)
def ConFrac(N, **kwargs):
imax = 20
r_a = False
if 'a_max' in kwargs:
imax = kwargs['a_max']
if 'return_a' in kwargs:
r_a = kwargs['return_a']
a = []
a.append( m.floor(N) )
b = N - a[0]
i = 1
while( (round(b,10) != 0) and (i < imax) ):
n = 1.0/b
a.append( m.floor(n) )
b = n - a[-1]
i = i + 1
#------------------------------
a_copy = []
for ia in np.arange(len(a)):
a_copy.append(a[ia])
for j in np.arange( len(a)-1 ):
if( j == 0 ):
p = a[-1] * a[-2] + 1
q = a[-1]
del a[-1]
del a[-1]
else:
p_new = a[-1] * p + q
q_new = p
p = p_new
q = q_new
del a[-1]
if(r_a == True):
return q,p,a_copy
return q,p
def r_Finder(a, N):
value1 = a**1 % N
r = 1
value2 = 0
while value1 != value2 or r > 1000:
value2 = a**(int(1+r)) % N
if( value1 != value2 ):
r = r + 1
return r
def Primality(N):
is_prime = True
if( (N==1) or (N==2) or (N==3) ):
is_prime = True
elif( (N%2==0) or (N%3==0) ):
is_prime = False
elif( is_prime==True ):
p = 5
while( (p**2 <= N) and (is_prime==True) ):
if( (N%p==0) or (N%(p+2)==0) ):
is_prime = False
p = p + 6
return is_prime
def Mod_r_Check(a, N, r):
v1 = a**(int(2)) % N
v2 = a**(int(2+r)) % N
if( (v1 == v2) and (r<N) and (r!=0) ):
return True
return False
def Evaluate_S(S, L, a, N):
Pairs = [[S,L]]
for s in np.arange(3):
S_new = int( S - 1 + s)
for l in np.arange(3):
L_new = int( L - 1 + l)
if( ((S_new!=S) or (L_new!=L)) and (S_new!=L_new) ):
Pairs.append( [S_new,L_new] )
#--------------------------- Try 9 combinations of S and L, plus or minus 1 from S & L
period = 0
r_attempts = []
found_r = False
while( (found_r==False) and (len(Pairs)!=0) ):
order = 1