-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathQuantumAwesomeness.py
1541 lines (1219 loc) · 64.3 KB
/
QuantumAwesomeness.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
# first, some tools we'll need from this directory
from devices import * # info on supported devices
from devicePrep import *
try:
import mwmatching as mw # perfect matching
except:
pass
# other tools
import random, numpy, math, time, copy, os
from IPython.display import clear_output
import networkx as nx
import matplotlib.pyplot as plt
from itertools import product
import warnings
warnings.filterwarnings('ignore')
path = os.path.dirname(os.path.abspath(__file__))
def importSDK ( device ):
# *This function contains SDK specific code.*
#
# Input:
# * *device* - String specifying the device on which the game is played.
# Details about the device will be obtained using getLayout.
# Process:
# * The SDK associated with this device is imported.
#
# Output:
# * Nothing returned, but global variables required by the SDKs are defined
num, area, entangleType, pairs, pos, example, sdk, runs = getLayout(device)
if sdk in ["QISKit","ManualQISKit"]:
global ClassicalRegister, QuantumRegister, QuantumCircuit, execute, register, available_backends, get_backend
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit, execute
from qiskit import register, available_backends, get_backend
try:
import Qconfig
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']}
register(qx_config['APItoken'], qx_config['url'])
except:
pass
elif sdk=="ProjectQ":
global projectq, H, Measure, CNOT, C, Z, Rx, Ry
import projectq
from projectq.ops import H, Measure, CNOT, C, Z, Rx, Ry
elif sdk=="Forest":
global Program, api, I, H, CNOT, CZ, RX, RY
from pyquil.quil import Program
import pyquil.api as api
from pyquil.gates import I, H, CNOT, CZ, RX, RY
elif sdk=="Cirq":
global GridQubit, CNOT, CZ, X, Y, Circuit, H, measure, google
from cirq import GridQubit, CNOT, CZ, X, Y, Circuit, H, measure, google
def initializeQuantumProgram ( device, sim ):
# *This function contains SDK specific code.*
#
# Input:
# * *device* - String specifying the device on which the game is played.
# Details about the device will be obtained using getLayout.
# * *sim* - Boolean denoting whether this is a simulated run
# Process:
# * Initializes everything required by the SDK for the quantum program. The details depend on which SDK is used.
#
# Output:
# * *q* - Register of qubits (used by QISKit, ProjectQ and Circ).
# * *c* - Register of classical bits (used by QISKit).
# * *engine* - Class required to create programs (used by ProjectQ and Forest).
# * *script* - The quantum program (used by QISKit, Forest and Circ).
num, area, entangleType, pairs, pos, example, sdk, runs = getLayout(device)
importSDK ( device )
if sdk in ["QISKit","ManualQISKit"]:
engine = None
q = QuantumRegister(num)
c = ClassicalRegister(num)
script = QuantumCircuit(q, c)
elif sdk=="ProjectQ":
engine = projectq.MainEngine()
q = engine.allocate_qureg( num )
c = None
script = None
elif sdk=="Forest":
if sim:
engine = api.QVMConnection(use_queue=True)
else:
engine = api.QPUConnection(device)
script = Program()
q = range(num)
c = range(num)
elif sdk=="Cirq":
q = []
for qubit in range(num):
q.append( GridQubit( pos[qubit][0], pos[qubit][1] ) )
c = None
engine = None
script = Circuit.from_ops()
return q, c, engine, script
def implementGate (device, gate, qubit, script, frac = None ):
# *This function contains SDK specific code.*
#
# Input:
# * *device* - String specifying the device on which the game is played.
# Details about the device will be obtained using getLayout.
# * *gate* - String that specifies gate type. Should be 'X', 'Y' or 'XX' rotation, or 'finish'.
# * *qubit* - Qubit, list of two qubits or qubit register on which the gate is applied.
# * *script* - Used to store the quantum program in some SDKs
# * *frac=0* - Fraction of pi for which an X rotation is applied. Not required for gate of type 'finish'.
#
# Process:
# * For gates of type 'X', 'Y' and 'XX', the gate $U = \exp(-i \,\times\, gate \,\times\, frac )$ is implemented on the qubit or pair of qubits in *qubit*.
# * *gate='Finish'* implements the measurement command on the qubit register required for ProjectQ to not complain.
#
# Output:
# * None are returned, but modifications are made to the objects that contain the quantum program.
num, area, entangleType, pairs, pos, example, sdk, runs = getLayout(device)
if sdk in ["QISKit","ManualQISKit"]:
if gate=='X':
script.u3(frac * math.pi, -math.pi/2, math.pi/2, qubit )
elif gate=='Y': # a Y axis rotation
script.u3(frac * math.pi, 0,0, qubit )
elif gate=='XX':
if entangleType=='CX':
script.cx( qubit[0], qubit[1] )
script.u3(frac * math.pi, -math.pi/2, math.pi/2, qubit[0] )
script.cx( qubit[0], qubit[1] )
elif entangleType=='CZ':
script.h( qubit[1] )
script.cz( qubit[0], qubit[1] )
script.u3(frac * math.pi, -math.pi/2, math.pi/2, qubit[0] )
script.cz( qubit[0], qubit[1] )
script.h( qubit[1] )
else:
print("Support for this is yet to be added")
elif sdk=="ProjectQ":
if gate=='X':
Rx( frac * math.pi ) | qubit
elif gate=='Y': # a Y axis rotation
Ry( frac * math.pi ) | qubit
elif gate=='XX':
if entangleType=='CX':
CNOT | ( qubit[0], qubit[1] )
Rx( frac * math.pi ) | qubit[0]
CNOT | ( qubit[0], qubit[1] )
elif entangleType=='CZ':
H | qubit[1]
C(Z) | ( qubit[0], qubit[1] )
Rx( frac * math.pi ) | qubit[0]
C(Z) | ( qubit[0], qubit[1] )
H | qubit[1]
else:
print("Support for this is yet to be added")
elif gate=='finish':
Measure | qubit
elif sdk=="Forest":
if gate=='X':
if qubit in pos.keys(): # only if qubit is active
script.inst( RX ( frac * math.pi, qubit ) )
elif gate=='Y': # a Y axis rotation
if qubit in pos.keys(): # only if qubit is active
script.inst( RY ( frac * math.pi, qubit ) )
elif gate=='XX':
if entangleType=='CX':
script.inst( CNOT( qubit[0], qubit[1] ) )
script.inst( RX ( frac * math.pi, qubit[0] ) )
script.inst( CNOT( qubit[0], qubit[1] ) )
elif entangleType=='CZ':
script.inst( H ( qubit[1] ) )
script.inst( CZ( qubit[0], qubit[1] ) )
script.inst( RX ( frac * math.pi, qubit[0] ) )
script.inst( CZ( qubit[0], qubit[1] ) )
script.inst( H ( qubit[1] ) )
elif entangleType=='none':
script.inst( RX ( frac * math.pi, qubit[0] ) )
script.inst( RX ( frac * math.pi, qubit[1] ) )
else:
print("Support for this is yet to be added")
elif sdk=="Cirq":
if gate=='X':
if qubit in pos.keys(): # only if qubit is active
script.append( X(qubit)**frac )
elif gate=='Y': # a Y axis rotation
if qubit in pos.keys(): # only if qubit is active
script.append( Y(qubit)**frac )
elif gate=='XX':
if entangleType=='CX':
script.append( CNOT(qubit[0],qubit[1]) )
script.append( X(qubit[0])**frac )
script.append( CNOT(qubit[0],qubit[1]) )
elif entangleType=='CZ':
script.append( H(qubit[1]) )
script.append( CZ(qubit[0],qubit[1]) )
script.append( X(qubit[0])**frac )
script.append( CZ(qubit[0],qubit[1]) )
script.append( H(qubit[1]) )
else:
print("Support for this is yet to be added")
def resultsLoad ( fileType, move, shots, sim, device ) :
# Input:
# * *fileType* - String describing type of file to load.
# * *move* - String describing the way moves were chosen for the results to be loaded.
# * *shots* - Number of shots used in the results to be loaded.
# * *sim* - Boolean denoting whether a simulator was used for the results to be loaded.
# * *device* - String specifying the device on which the game is played.
#
# Process:
# * A filename is created using the details given in the input. This file, which will contain and array of arrays, is then loaded, evalulated and stored as an which will contain and array of arrays.
# If the file doesn't exist, the process will fail and throw and exception. This is a fatal error, so no exception handling is used.
#
# Output:
# * *samples* - Array of arrays of whatever it was the file contained.
filename = 'move='+move+'_shots=' + str(shots) + '_sim=' + str(sim) + '.txt'
saveFile = open(path+'/results/' + device + '/'+fileType+'_'+filename)
sampleStrings = saveFile.readlines()
saveFile.close()
samples = []
for sampleString in sampleStrings:
samples.append( eval( sampleString ) )
return samples
def getResults ( device, sim, shots, q, c, engine, script ):
# *This function contains SDK specific code.*
#
# Input:
# * *device* - String specifying the device on which the game is played.
# Details about the device will be obtained using getLayout.
# * *q* - Register of qubits (used in some SDKs).
# * *c* - Register of classical bits (used in some SDKs).
# * *engine* - Class required to create programs (used in some SDKs).
# * *script* - The quantum program (used in some SDKs).
#
# Process:
# * This function sends the quantum program to the desired backend to be run, and obtains results.
#
# Output:
# * *resultsRaw* - A dictionary whose keys are the bit strings obtained as results, and the values are the fraction of shots for which they occurred.
num, area, entangleType, pairs, pos, example, sdk, runs = getLayout(device)
if sdk=="QISKit":
# pick the right backend
if sim:
backend = get_backend('local_qasm_simulator')
else:
backend = get_backend(device)
# add measurement for all qubits
for n in range(num):
script.measure( q[n], c[n] )
# execute job
noResults = True
while noResults:
try: # try to run, and wait if it fails
if not sim:
print('Status of device:',backend.status)
job = execute(script, backend, shots=shots, skip_translation=True)
resultsVeryRaw = job.result().get_counts()
noResults = False
except Exception as e:
print(e)
print("Job failed. We'll wait and try again")
time.sleep(600)
# invert order of the bit string and turn into probs
resultsRaw = {}
for string in resultsVeryRaw.keys():
invertedString = string[::-1]
resultsRaw[ invertedString ] = resultsVeryRaw[string]/shots
elif sdk=="ManualQISKit":
# add measurement for all qubits
for n in range(num):
script.measure( q[n], c[n] )
qasm = engine.get_qasm("script")
input("\nHere is a QASM representation of the circuit you need to run\n"+qasm)
input_data = input("Whatever you enter into the box below will go into the results file.\nObviously, it is best if you put the results. But you can also put a job ID that can be replaced with the results later.\n")
try: # if the input successfully evaluates, we treat it as data
resultsRaw = eval(input_data)
except: # otherwise we treat it as a job ID
resultsRaw = input_data
elif sdk=="ProjectQ":
engine.flush()
# list of bit strings
strings = [''.join(x) for x in product('01', repeat=num)]
# get prob for each bit string to make resultsRaw
resultsRaw = {}
for string in strings:
resultsRaw[ string ] = engine.backend.get_probability( string, q )
elif sdk=="Forest":
# get list of active (and therefore plotted) qubits
qubits_active = list(pos.keys())
# execute job
noResults = True
while noResults:
try: # try to run, and wait for 5 mins if it fails
resultsVeryRaw = engine.run_and_measure(script, qubits_active, trials=shots)
noResults = False
except Exception as e:
#print(e)
print("\nJob failed. We'll wait and try again.\n")
time.sleep(300)
# convert them the correct form
resultsRaw = {}
for sample in resultsVeryRaw:
bitString = ""
disabled_so_far = 0
for qubit in range(num):
if qubit in qubits_active:
bitString += str(sample[qubit-disabled_so_far])
else:
bitString += "0" # fake result for dead qubit
disabled_so_far += 1
if bitString not in resultsRaw.keys():
resultsRaw[bitString] = 0
resultsRaw[bitString] += 1/shots
elif sdk=="Cirq":
# add measurement for all qubits
for qubit in range(num):
script.append( measure(q[qubit],key=qubit) )
if sim:
backend = google.XmonSimulator()
elif device=='Foxtail':
backend = google.Foxtail
elif device=='Bristlecone':
backend = google.Bristlecone
resultsExtremelyRaw = backend.run(script, repetitions=shots)
resultsVeryRaw = []
for qubit in range(num):
resultsVeryRaw.append( resultsExtremelyRaw.measurements[qubit][:, 0] )
resultsRaw = {}
for shot in range(shots):
bitString = ""
for qubit in range(num):
if resultsVeryRaw[qubit][shot]:
bitString += '1'
else:
bitString += '0'
if bitString not in resultsRaw.keys():
resultsRaw[bitString] = 0
resultsRaw[bitString] += 1/shots
return resultsRaw
def processResults ( resultsRaw, num, pairs, sim, shots ):
# Input:
# * *resultsRaw* - String specifying the device on which the game is played. Details about the device will be obtained using getLayout.
# * *num* - The number of qubits in the device.
# * *pairs* - A dictionary of pairs of qubits for which an entagling gate is possible. The key is a string which serves as the name of the pair. The value is a two element list with the qubit numbers of the two qubits in the pair. For controlled-NOTs, the control qubit is listed first.
# * *sim* - Boolean denoting whether a simulator was used.
# * *shots* - Number of shots used for statistics.
#
# Process:
# * This function sends the quantum program to the desired backend to be run, and obtains results.
#
# Output:
# * *oneProb* - A list with an entry for each qubit. Each entry is the fraction of samples for which the measurement of that qubit returns *1*.
# * *sameProb* - A dictionary with pair names as keys, and probability that the two qubits each pair give the same results as values.
# * *results* - If results are not from a simulator, this is just resultsRaw. If they are, it is assumed that the simulated effectively gave results with no statistical noise, so a sampling process is used to simulate the effect of the required number of shots.
oneProb = [0]*num
sameProb = {p: 0 for p in pairs}
if type(resultsRaw) is dict: # try to process only if it is a dict (and so not if a job id)
strings = list(resultsRaw.keys())
if sim==True:
# sample from this prob dist shots times to get results
results = {}
for string in strings:
results[string] = 0
for shot in range(shots):
j = numpy.random.choice( len(strings), p=list(resultsRaw.values()) )
results[strings[j]] += 1/shots
else:
results = resultsRaw
# determine the fraction of results that came out as 1 (instead of 0) for each qubit
for bitString in strings:
for v in range(num):
if (bitString[v]=="1"):
oneProb[v] += results[bitString]
for bitString in strings:
for p in pairs:
if bitString[pairs[p][0]]==bitString[pairs[p][1]]:
sameProb[p] += results[bitString]
else:
results = resultsRaw
return oneProb, sameProb, results
def printM ( string, move ):
# If *move=M*, this is just *print()*. Otherwise it does nothing.
if move=="M":
print(string)
def entangle( device, move, shots, sim, gates, conjugates ):
# Input:
# * *device* - String specifying the device on which the game is played.
# Details about the device will be obtained using getLayout.
# * *move* - String describing the way moves were chosen when creating the circuit.
# * *shots* - Number of shots to be taken.
# * *sim* - Boolean denoting whether a simulator will be used.
# * *gates* - Entangling gates applied so far. Each round of the game corresponds to two 'slices'. *gates* is a list with a dictionary for each slice. The dictionary has pairs of qubits as keys and fractions of pi defining a corresponding entangling gate as values.
# * *conjugates* - List of single qubit gates to conjugate entangling gates of previous rounds. Each is specified by a two element list. First is a string specifying the rotation axis ('X' or 'Y'), and the second specifies the fraction of pi for the rotation.
#
# Process:
# * Quantum circuit is created and run given the details (device, gates, etc) provided by the input. The results are then processed to give the final output.
#
# Output:
# * *oneProb*, *sameProb* and *results* - See processResults() for explanation.
num, area, entangleType, pairs, pos, example, sdk, runs = getLayout(device)
q, c, engine, script = initializeQuantumProgram(device,sim)
# apply all gates
# gates has two entries for each round, except for the current round which has only one
rounds = int( (len(gates)+1)/2 )
# loop over past rounds and apply the required gates
for r in range(rounds-1):
# do the first part of conjugation (the inverse)
for n in range(num):
implementGate ( device, conjugates[r][n][0], q[n], script, frac=-conjugates[r][n][1] )
# get the sets of gates that create and (attempt to) remove the puzzle for this round
gates_create = gates[2*r]
gates_remove = gates[2*r+1]
# determine which pairs are for both, and which are unique
pairs_both = list( set(gates_create.keys()) & set(gates_remove.keys()) )
pairs_create = list( set(gates_create.keys()) - set(gates_remove.keys()) )
pairs_remove = list( set(gates_remove.keys()) - set(gates_create.keys()) )
# then do the exp[ i XX * frac ] gates accordingly
for p in pairs_both:
#print([r,p,gates_create[p]+gates_remove[p]] )
implementGate ( device, "XX", [ q[pairs[p][0]], q[pairs[p][1]] ], script, frac=(gates_create[p]+gates_remove[p]) )
for p in pairs_create:
#print([r,p,gates_create[p]] )
implementGate ( device, "XX", [ q[pairs[p][0]], q[pairs[p][1]] ], script, frac=(gates_create[p]) )
for p in pairs_remove:
#print([r,p,gates_remove[p]] )
implementGate ( device, "XX", [ q[pairs[p][0]], q[pairs[p][1]] ], script, frac=(gates_remove[p]) )
# do the second part of conjugation
for n in range(num):
implementGate ( device, conjugates[r][n][0], q[n], script, frac=conjugates[r][n][1] )
# then the same for the current round (only needs the exp[ i XX * (frac - frac_inverse) ] )
r = rounds-1
for p in gates[2*r].keys():
implementGate ( device, "XX", [ q[ pairs[p][0] ], q[ pairs[p][1] ] ], script, frac=gates[2*r][p] )
resultsRaw = getResults( device, sim, shots, q, c, engine, script )
oneProb, sameProb, results = processResults ( resultsRaw, num, pairs, sim, shots )
implementGate ( device, "finish", q, script )
return oneProb, sameProb, results
def calculateEntanglement( oneProb ):
# Input:
# * *oneProb* - Float representing the fraction of samples for which the measurement of a qubit returns *1*.
#
# Process:
# * Calculates the number that will be shown to the player, based on oneProb. This should be zero when oneProb is zero, 1 when oneProb is 0.5, and monotonic.
# This is done by first calculating the frac that would result in such a oneProb (oneProb=0 ==> frac=0, oneProb=0.5 ==> frac=1/2, oneProb=1 ==> frac=1), and then doubling it. Since the result can exceed 1 in general (though only due to spurious effects that result in oneprob>0.5), it is capped by 1 before being returned.
# This quantity is called the 'entanglement' because early versions used the mixedness
# E = 1-2*abs( 0.5-oneProb )
# which is a measure of how entangled a qubit is with the rest of the universe. The frac based measure is now used instead such that the resulting values have a more uniform spread.
#
# Output:
# * *E* - As described above.
E = ( 2 * calculateFrac( oneProb ) )
return min( E, 1)
def calculateFrac ( oneProb ):
# Input:
# * *oneProb* - Float representing the fraction of samples for which the measurement of a qubit returns *1*.
#
# Process:
# * Calculates the fraction of pi for an X rotation which would result in the given value of oneProb.
# Prob(1) = sin(frac*pi/2)^2
# therefore frac = asin(sqrt(oneProb)) *2 /pi
#
# Output:
# * *frac* - As described above.
oneProb = max(0,oneProb)
oneProb = min(1,oneProb)
frac = math.asin(math.sqrt( oneProb )) * 2 / math.pi
return frac
def calculateFuzz ( oneProb, pairs, matchingPairs ):
# Input:
# * *oneProb* - A list with an entry for each qubit. Each entry is the fraction of samples for which the measurement of that qubit returns *1*.
# * *pairs* - A dictionary of pairs of qubits for which an entagling gate is possible. The key is a string which serves as the name of the pair. The value is a two element list with the qubit numbers of the two qubits in the pair. For controlled-NOTs, the control qubit is listed first.
# * *matchingPairs* - The pairing of qubits in the current round.
#
# Process:
# * The two qubits of the same pair should have the same oneProb value. If they don't, it is because of fuzz.
# The fuzz is therefore quantified by the average difference between these values.
#
# Output:
# * *fuzzAv* - As described above.
fuzzAv = 0
for p in matchingPairs:
fuzzAv += abs( oneProb[pairs[p][0]] - oneProb[pairs[p][1]] )/len(matchingPairs)
return fuzzAv
def calculateEntropy ( probs ):
# Input:
# * *probs* - Array of probabilities. They are assumed to sum to 1, but this is not checked.
#
# Process:
# * The Shannon entropy, H, of the probability distribution is calculated
#
# Output:
# * *H* - As described above.
H = 0
for prob in probs:
if prob>0:
H -= prob * math.log(prob,2)
return H
def calculateExpect ( probs ):
# Input:
# * *probs* - Array of probabilities.
#
# Process:
# * For each probability, the expectation value is calculated. The probabilities are takem to be the probability of a value -1 value, with 1-p representing the probability of +1.
#
# Output:
# * *expect* - Corresponding array of expectation values.
expect = []
for p in probs:
expect.append( 1-2*p)
return expect
def calculateMutual ( oneProb, sameProb, pairs ):
# Input:
# * *oneProb* - A list with an entry for each qubit. Each entry is the fraction of samples for which the measurement of that qubit returns *1*.
# * *sameProb* - A dictionary with pair names as keys, and probability that the two qubits each pair give the same results as values.
# * *pairs* - A dictionary of pairs of qubits for which an entagling gate is possible. The key is a string which serves as the name of the pair. The value is a two element list with the qubit numbers of the two qubits in the pair. For controlled-NOTs, the control qubit is listed first.
#
# Process:
# * For each pair, the (classical) mutual information for the measurement results of the two qubits is calculated. This is done using oneProbs and sameProbs, which is a bit of a pain. But this information is sufficient to calculate the probability for the results '00', '01', '10' and '11' for the two qubits of each pair, which the probability distrubution required to calculate the mutual information.
#
# Output:
# * *I* - Dictionary with pair names as keys and corresponding values of the mutual information as values.
I = {}
for p in sameProb.keys():
p0 = oneProb[pairs[p][0]]
p1 = oneProb[pairs[p][1]]
expect = calculateExpect( [ p0, p1, 1-sameProb[p] ] )
prob = [0]*4
prob[0] = ( 1 + expect[0] + expect[1] + expect[2] )/4
prob[1] = ( 1 - expect[0] + expect[1] - expect[2] )/4
prob[2] = ( 1 + expect[0] - expect[1] - expect[2] )/4
prob[3] = ( 1 - expect[0] - expect[1] + expect[2] )/4
I[p] = calculateEntropy( [ 1-p0, p0 ] ) + calculateEntropy( [ 1-p1, p1 ] ) - calculateEntropy( prob )
if I[p]>1e-3:
I[p] = I[p] / min( calculateEntropy( [ 1-p0, p0 ] ) , calculateEntropy( [ 1-p1, p1 ] ) )
return I
def printPuzzle ( device, oneProb, move, ascii=False ):
# Input:
# * *device* - String specifying the device on which the game is played.
# Details about the device will be obtained using getLayout.
# * *oneProb* - A list with an entry for each qubit. Each entry is the fraction of samples for which the measurement of that qubit returns 1.
# * *move* - String describing the way moves are chosen.
# * *ascii* - Boolean to convey whether the image should be purely ascii.
#
# Process:
# * The contents of *oneProb* contains some basic clues about the circuit that has been performed. It is the player's job to use those clues to guess the circuit. This means we have to print *oneProb* to screen. In order to make the game a pleasant experience and help build intuition about the device, this is done visually. The networkx package is used to visualize the layout of the qubits, and the oneProb information is conveyed using colour. This is done only when a player is manually playing, and so when move='M'.
# * An altenative visualization has been partially implemented. This would use only ascii.
#
# Output:
# * None returned, but the above described image is printed to screen.
num, area, entangleType, pairs, pos, example, sdk, runs = getLayout(device)
if move=="M":
if ascii:
def change_char (string, char, pos):
return string[:pos] + char + string[(pos+len(char)):]
lines = 5
length = 10
def get_x (X):
return int( length * X )
def get_y (Y):
return H-1 - int( lines * Y )
W = length*(area[0]-1)+1
H = lines*(area[1]-1)+1
plot = [ "░"*(W+4) for _ in range(H) ]
for pair in pairs:
x = get_x( (pos[pairs[pair][0]][0]+pos[pairs[pair][1]][0])/2 )
y = get_y( (pos[pairs[pair][0]][1]+pos[pairs[pair][1]][1])/2 )
plot[y] = change_char(plot[y],pair,x)
xx = [0]*2
yy = [0]*2
for j in range(2):
xx[j] = get_x( pos[pairs[pair][j]][0] )
yy[j] = get_y( pos[pairs[pair][j]][1] )
for p in range(length):
x = int( xx[0] + (p/length)*(xx[1]-xx[0]) )
y = int( yy[0] + (p/length)*(yy[1]-yy[0]) )
plot[y] = change_char(plot[y]," ",x)
for qubit in pos:
x = get_x( pos[qubit][0] )
y = get_y( pos[qubit][1] )
num = "("+str(int(100*oneProb[qubit])) +")"
plot[y] = change_char(plot[y],num,x)
print("░"*(W+8))
for line in plot:
print("░░░░"+line)
print("░"*(W+8))
else:
# create a graph with qubits as vertices and possible entangling gates as edges
G=nx.Graph()
for p in pairs:
if p[0:4]!='fake':
G.add_edge(pairs[p][0],pairs[p][1])
for p in pairs:
if p[0:4]!='fake':
G.add_edge(pairs[p][0],p)
G.add_edge(pairs[p][1],p)
pos[p] = [(pos[pairs[p][0]][dim] + pos[pairs[p][1]][dim])/2 for dim in range(2)]
# colour and label the edges with the oneProb data
colors = []
sizes = []
labels = {}
for node in G:
if type(node)!=str:
if (oneProb[node]>1): # if oneProb is out of bounds (due to this node having already been selected) make it grey
colors.append( (0.5,0.5,0.5) )
else: # otherwise it is on the spectrum between red and blue
E = calculateEntanglement( oneProb[node] )
colors.append( (1-E,0,E) )
sizes.append( 3000 )
if oneProb[node]>1:
labels[node] = ""
elif oneProb[node]==0.5:
labels[node] = "99"
else:
labels[node] = "%.0f" % ( 100 * ( E ) )
else:
colors.append( "black" )
sizes.append( 1000 )
labels[node] = node
# show it
if area[0]>2*area[1]:
ratio = 0.65
else:
ratio = 1
plt.figure(2,figsize=(2*area[0],2*ratio*area[1]))
nx.draw(G, pos, node_color = colors, node_size = sizes, labels = labels, with_labels = True,
font_color ='w', font_size = 22.5)
plt.show()
def calculateFracDifference (frac1, frac2):
# Input:
# * *frac1*, *frac2* - Two values of frac
#
# Process:
# * Determine the minimum difference between the two, accounting for the fact that frac=0 and frac=2 are equivalent. Note that his means that the
#
# Output:
# * *matchingPairs* - A list of the names of a random set of disjoint pairs included in the matching.
delta = max(frac1,frac2) - min(frac1,frac2)
delta = min( delta, 1-delta )
return delta
def getDisjointPairs ( pairs, oneProb, weight ):
# Input:
# * *pairs* - A dictionary with names of pairs as keys and lists of the two qubits of each pair as values
# * *oneProb* - A list with an entry for each qubit. Each entry is the fraction of samples for which the measurement of that qubit returns 1.
# * *weight* - dictionary with pair names as keys and a weight assigned to each pair as the corresponding values.
#
# Process:
# * A minimum weight perfect matching of the qubits is performed, using the possible pairing and weights provided. If weights are not given, but oneProbs are, the weights are calculated from the oneProbs. If oneProbs aren't given either, the weights are chosen randomly to generate a random pairing.
#
# Output:
# * *matchingPairs* - A list of the names of a random set of disjoint pairs included in the matching.
if not weight:
for p in pairs.keys():
if oneProb:
weight[p] = -calculateFracDifference( calculateFrac( oneProb[ pairs[p][0] ] ) , calculateFrac( oneProb[ pairs[p][1] ] ) )
else:
weight[p] = random.randint(0,100)
edges = []
for p in pairs.keys():
edges.append( ( pairs[p][0], pairs[p][1], weight[p] ) )
# match[j] = k means that edge j and k are matched
match = mw.maxWeightMatching(edges, maxcardinality=True)
# get a list of the pair names for each pair in the matching (not including fakes)
matchingPairs = []
for v in range(len(match)):
for p in pairs.keys():
if pairs[p]==[v,match[v]] and p[0:4]!='fake' :
matchingPairs.append(p)
return matchingPairs
def runGame ( device, move, shots, sim, maxScore=None, dataNeeded=True, cleanup=False, game=None, ascii=False):
# Input:
# * *device* - String specifying the device on which the game is played.
# Details about the device will be obtained using getLayout.
# * *move* - String describing the way moves are chosen.
# * *shots* - Number of shots to be used for statistics.
# * *sim* - Boolean for whether the simulator is to be used.
# * *maxScore* - maximum number of rounds to run the game for
# * *dataNeeded* - Boolean determining whether game need to obtain new data, or will run on old data
# * *cleanup* - Boolean determining whether error mitigation post-processing is used
# * *game* - Integer identifiying a specific game to play from a file (can only be True if dataNeeded=True)
# * *ascii* - Boolean to convey whether the image presented to the player should be purely ascii.
#
# Process:
# * Runs the game! Done either by loading up saved data, or running a new instance.
#
# Output:
# * *gates* - Entangling gates applied so far. Each round of the game corresponds to two 'slices'. *gates* is a list with a dictionary for each slice. The dictionary has pairs of qubits as keys and fractions of pi defining a corresponding entangling gate as values.
# * *conjugates* - List of single qubit gates to conjugate entangling gates of previous rounds. Each is specified by a two element list. First is a string specifying the rotation axis ('X' or 'Y'), and the second specifies the fraction of pi for the rotation.
# * *oneProbs*: Array of oneProb arrays (see processResults() for explanation of these), with an element for each round of the game.
# * *sameProbs*: Array of sameProb arrays (see processResults() for explanation of these), with an element for each round of the game.
# * *resultsDicts*: Array of results arrays (see processResults() for explanation of these), with an element for each round of the game.
num, area, entangleType, pairs, pos, example, sdk, runs = getLayout(device)
gates = []
conjugates = []
oneProbs = []
sameProbs = []
resultsDicts = []
# if we are running off data, load up oneProbs for a move='C' run and see what the right answers are
if dataNeeded==False:
oneProbSamples = resultsLoad ( 'oneProbs', 'C', shots, sim, device )
sameProbSamples = resultsLoad ( 'sameProbs', 'C', shots, sim, device )
gateSamples = resultsLoad ( 'gates', 'C', shots, sim, device )
if maxScore is None: # if a maxScore is not given, use the value from the first sample
maxScore = len( oneProbSamples[ 0 ] )
if cleanup:
cleaner = getCleaningProfile ( device, move, shots, sim, num, maxScore, gritty=True )
samples = len(oneProbSamples) # find out how many samples there are
# choose a game randomly if a specific one was not requested
if game is None:
game = random.randint( 0, samples-1 )
# get the data for this game
oneProbs = oneProbSamples[ game ]
sameProbs = sameProbSamples[ game ]
originalOneProbs = copy.deepcopy( oneProbs )
gates = gateSamples[ game ]
gameOn = True
restart = False
score = 0
while gameOn:
score += 1
# Step 1: get a new puzzle
if dataNeeded:
# if running anew, we generate a new set of gates
# gates applied are of the form
# CNOT | (j,k)
# Rx(frac*pi) | j
# CNOT | (j,k)
# and so are specified by a pair p=[j,k] and a random fraction frac
# first we generate a random set of edges
matchingPairs = getDisjointPairs( pairs, [], {} )
# then we add gates these to the list of gates
appliedGates = {}
for p in matchingPairs:
frac = ( 0.1+0.9*random.random() ) / 2 # this will correspond to a e^(i theta \sigma_x) rotation with pi/20 \leq frac * pi/2 \leq pi/4
appliedGates[p] = frac
gates.append(appliedGates)
# all gates so far are then run
oneProb, sameProb, results = entangle( device, move, shots, sim, gates, conjugates)
else:
oneProb = oneProbs[score-1]
sameProb = sameProbs[score-1]
matchingPairs = list(gates[ 2*(score-1) ].keys())
I = calculateMutual ( oneProb, sameProb, pairs )
correlatedPairs = getDisjointPairs( pairs, [], I )
rawOneProb = copy.deepcopy( oneProb )
if cleanup:
oneProb = CleanData(cleaner[score-1],rawOneProb,sameProb,pairs)
results = []
# Step 2: Get player to guess pairs
displayedOneProb = copy.copy( oneProb )
guessedPairs = []
# if choices are all correct, we just give the player the right answer
if (move=="C"):
guessedPairs = matchingPairs
# if choices are random, we generate a set of random pairs
if (move=="R"):
guessedPairs = getDisjointPairs( pairs, [], {} )
# if choices are via MWPM, we do this
if (move=="B"):
guessedPairs = getDisjointPairs( pairs, oneProb, {} )
# if choices are manual, let's get choosing
if (move=="M"):
# get the player choosing until the choosing is done
unpaired = num
restart = False
while (unpaired>1):
clear_output()
print("")
print("Round "+str(score))
if cleanup:
printM("\nRaw puzzle",move)
printPuzzle( device, rawOneProb, move, ascii=ascii)
printM("\nCleaned puzzle", move)
printPuzzle( device, displayedOneProb, move, ascii=ascii)
pairGuess = input("\nChoose a pair (or type 'done' to skip to the next round, or 'restart' for a new game)\n")
if num<=26 : # if there are few enough qubits, we don't need to be case sensitive
pairGuess = str.upper(pairGuess)
if (pairGuess in pairs.keys()) and (pairGuess not in guessedPairs) :
guessedPairs.append(pairGuess)
# set them both to grey on screen (set the corresponding oneProb value to >1)
for j in [0,1]:
displayedOneProb[ pairs[pairGuess][j] ] = 2
printM("\n\n\n", move)
# check if all active (and therefore displayed) vertices have been covered
unpaired = 0
for n in pos.keys():
unpaired += ( displayedOneProb[n] <= 1 )
elif (str.upper(pairGuess)=="DONE") : # player has decided to stop pairing
unpaired = 0
elif (str.upper(pairGuess)=="RESTART") : # player has decided to stop the game
unpaired = 0
restart = True
else:
printM("That isn't a valid pair. Try again.\n(Note that input can be case sensitive)", move)
# store the oneProb and sameProb
oneProbs.append( oneProb )
sameProbs.append( sameProb )
# store the raw data (if it is not too big
if len(str(results)) < 10000:
resultsDicts.append( results )
# see whether the game over condition is satisfied
gameOn = (score<maxScore) and restart==False