forked from decodoku/A_Game_to_Benchmark_Quantum_Computers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
QuantumAwesomeness.py
1231 lines (942 loc) · 46.8 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
# tools from quantum awesomeness directory
from devices import *# info on supported devices
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')
def importSDK ( device ):
num, area, entangleType, pairs, pos, example, sdk, runs = getLayout(device)
if sdk in ["QISKit","ManualQISKit"]:
global QuantumProgram, Qconfig
from qiskit import QuantumProgram
import Qconfig
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
def make_layout ( num_qubits ):
# from https://qiskit.slack.com/archives/C7SJ0PJ5A/p1519912149000214
# Create a mapping fixing qubit q0 to q0, q1 to q1, etc.
# Input is number of qubits for the map
layout = {}
for i in range(num_qubits):
layout[('q', i)] = ('q', i)
return layout
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* - 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 (needed by both QISKit and ProjectQ).
# * *c* - Register of classical bits (needed by QISKit only).
# * *engine* - Class required to create programs in QISKit, ProjectQ and Forest.
# * *script* - The quantum program, needed by QISKit and Forest.
num, area, entangleType, pairs, pos, example, sdk, runs = getLayout(device)
importSDK ( device )
if sdk in ["QISKit","ManualQISKit"]:
engine = QuantumProgram()
engine.set_api(Qconfig.APItoken, Qconfig.config["url"]) # set the APIToken and API url
q = engine.create_quantum_register("q", num)
c = engine.create_classical_register("c", num)
script = engine.create_circuit("script", [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)
return q, c, engine, script
def implementGate (device, gate, qubit, script, frac = 0 ):
# *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.
# * *qubit* - Qubit, list of two qubits or qubit register on which the gate is applied.
# * *script* -
# * *frac* -
#
# 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 classes 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")
def resultsLoad ( fileType, move, shots, sim, device ) :
filename = 'move='+move+'_shots=' + str(shots) + '_sim=' + str(sim) + '.txt'
saveFile = open('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.
#
# Process:
# * Implements all unitary quantum operations used in the program.
#
# Output:
# * None are returned, but modifications are made to the classes that contain the quantum program.
num, area, entangleType, pairs, pos, example, sdk, runs = getLayout(device)
if sdk=="QISKit":
# pick the right backend
if sim:
backend = 'local_qasm_simulator'
else:
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
print("Now sending job")
executedJob = engine.execute(["script"], backend=backend, shots=shots, max_credits = 5, wait=30, timeout=3600,initial_layout=make_layout(num))
# get ran
#print("Qasm that was executed")
#print(executedJob.get_ran_qasm("script"))
# get results
resultsVeryRaw = executedJob.get_counts("script")
if ('status' not in resultsVeryRaw.keys()): # see if it actually is data, and wai for 5 mins if not
noResults = False
else:
print(resultsVeryRaw)
print("This is not data, so we'll wait and try again")
time.sleep(300)
except:
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("\nYou'll now be given the QASM representation of the circuit. Find a way to run it, and then copy the results in the input box...\n")
input("The results you provide should be in the form of a dictionary, with bit strings as keys and the fraction of times these occurred as a result as values...")
input("Well, actually you should find some way to do this programatically. The function 'getResults' is what you need to look at. But copy and paste will do for now....\n")
resultsRaw = eval(input(qasm+"\n"))
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 10 mins if it fails
resultsVeryRaw = engine.run_and_measure(script, qubits_active, trials=shots)
noResults = False
except:
print("Job failed. We'll wait and try again.")
time.sleep(1800)
# 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
return resultsRaw
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* -
# * *shots* -
# * *sim* -
# * *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:
# * Sets up and runs a quantum circuit consisting of all gates thus far.
#
# 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*.
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 )
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
oneProb = [0]*num
for bitString in strings:
for v in range(num):
if (bitString[v]=="1"):
oneProb[v] += results[bitString]
sameProb = {p: 0 for p in pairs}
for bitString in strings:
for p in pairs:
if bitString[pairs[p][0]]==bitString[pairs[p][1]]:
sameProb[p] += results[bitString]
implementGate ( device, "finish", q, script )
return oneProb, sameProb, results
def calculateEntanglement( oneProb ):
# was once the mixedness
# E = 1-2*abs( 0.5-oneProb )
#but now based on frac
E = ( 2 * calculateFrac( oneProb ) )
return min( E, 1)
def calculateFrac ( oneProb ):
# Prob(1) = sin(frac*pi/2)^2
# therefore frac = asin(sqrt(oneProb)) *2 /pi
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*.
# * *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 ):
H = 0
for prob in probs:
if prob>0:
H -= prob * math.log(prob,2)
return H
def calculateExpect ( p0, p1, ps ):
return [ 1-2*p0, 1-2*p1, 2*ps-1 ]
def calculateMutual ( oneProb, sameProb, pairs ):
I = {}
for p in sameProb.keys():
p0 = oneProb[pairs[p][0]]
p1 = oneProb[pairs[p][1]]
expect = calculateExpect( p0, p1, 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 ):
# ### *printPuzzle*
#
# 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*.
#
# 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.
#
# 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":
# 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 = min(1, 2*calculateFrac( oneProb[node] ) ) # colour is determine by the guessed frac
E = calculateEntanglement( oneProb[node] ) # colour is determined by entanglement
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
plt.figure(2,figsize=(2*area[0],1.25*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):
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
#
# Process:
# * A graph is created using the pairs as edges, and is assigned random weights.
# These max weight matched to find a disjoint set of pairs.
#
# 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, dataNeeded=True, clean=False, game=-1):
# Input:
# * *device* - String specifying the device on which the game is played.
# Details about the device will be obtained using getLayout.
# * *move* -
# * *shots* -
# * *sim* -
#
# Process:
# * Run the game!
#
# Output:
# * *score* - score reached by the player at game over
# * *gates*
# * *conjugates*
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 sim==False:
cleaner = resultsLoad( 'cleaner', 'C', shots, sim, device )[0]
samples = len(oneProbSamples) # find out how many samples there are
if maxScore==0: # if a maxScore is not given, use the value from the first sample
maxScore = len( oneProbSamples[ 0 ] )
# choose a game randomly, if a specific one was not requested
if game==-1:
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, weight={} )
# 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 0.05*pi \leq frac*pi \leq pi/2 rotation
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, weight=I )
rawOneProb = copy.deepcopy( oneProb )
if sim==False:
#oneProb = CleanData(cleaner[score-1],rawOneProb,sameProb,pairs)
oneProb = CleanData([0.55,0.45,0]*num,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, weight={} )
# if choices are via MWPM, we do this
if (move=="B"):
guessedPairs = getDisjointPairs( pairs, oneProb=oneProb, weight={} )
# 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 sim==False:
printM("\nRaw puzzle",move)
printPuzzle( device, rawOneProb, move )
printM("\nCleaned puzzle", move)
printPuzzle( device, displayedOneProb, move )
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
#resultsDicts.append( results )
# see whether the game over condition is satisfied
gameOn = (score<maxScore) and restart==False
# given the chosen pairs, the gates are now deduced from oneProb
guessedGates = {}
for p in guessedPairs:
if (move=="C" and sim==False):
guessedFrac = gates[ 2*(score-1) ][p] + 0.1/math.sqrt(shots)
else:
guessedOneProb = 0
for j in range(2):
guessedOneProb += oneProb[ pairs[p][j] ] / 2
guessedFrac = calculateFrac( guessedOneProb )
# since the player wishes to apply the inverse gate, the opposite frac is stored
guessedGates[p] = -guessedFrac
# now we can add to the list of all gates
gates.append(guessedGates)
# finally randomly generate X or Z rotation for each active qubit to conjugate this round with
newconjugates = []
for n in range(num):
newconjugates.append( [ numpy.random.choice(['X','Y']) , random.random() ] )
conjugates.append(newconjugates)
if move=='M':
clear_output()
if sim==False:
printM("\nRaw puzzle",move)
if move=="M":
printPuzzle( device, rawOneProb, move )
printM("\nCleaned puzzle", move )
if move=="M":
printPuzzle( device, oneProb, move )
printM("", move)
printM("Round "+str(score)+" complete", move)
printM("", move)
printM("Pairs you guessed for this round", move)
printM(sorted(guessedPairs), move)
printM("Pairs our bot would have guessed", move)
printM(sorted(getDisjointPairs( pairs, oneProb=oneProb, weight={} )), move )
printM("Correct pairs for this round", move)
printM(sorted(matchingPairs), move)
correctGuesses = list( set(guessedPairs).intersection( set(matchingPairs) ) )
printM("\nYou guessed "+str(len(correctGuesses))+" out of "+str(len(matchingPairs))+" pairs correctly!", move)
printM("", move)
printM("", move)
if move=="M" and restart==False:
input(">Press Enter for the next round...\n")
if move=="M" and restart==False:
input("> There is no more data on this game :( Press Enter to restart...\n")
return gates, conjugates, oneProbs, sameProbs, resultsDicts
def MakeGraph(X,Y,y,axisLabel,labels=[],verbose=False,log=False):
plt.rcParams.update({'font.size': 30})
# convert the variances of varY into widths of error bars
for j in range(len(y)):
for k in range(len(y[j])):
y[j][k] = math.sqrt(y[j][k]/2)
plt.figure(figsize=(20,10))
# add in the series
for j in range(len(Y)):
if labels==[]:
plt.errorbar(X, Y[j], marker = "x", markersize=20, yerr = y[j], linewidth=5)
else:
plt.errorbar(X, Y[j], label=labels[j], marker = "x", markersize=20, yerr = y[j], linewidth=5)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
# label the axes
plt.xlabel(axisLabel[0])
plt.ylabel(axisLabel[1])
# make sure X axis is fully labelled
plt.xticks(X)
# logarithms if required
if log==True:
plt.yscale('log')
# make the graph
plt.show()
plt.rcParams.update(plt.rcParamsDefault)
# if verbose, print the numbers to screen
if verbose==True:
print("\nX values")
print(X)
for j in range(len(Y)):
print("\nY values for series "+str(j))
print(Y[j])
print("\nError bars")
print(y[j])
print("")
def GetData ( device, move, shots, sim, samples, maxScore ):
for sample in range(samples):
print("move="+move+", shots="+str(shots)+", sample=" + str(sample+1) )
gates, conjugates, oneProbs, sameProbs, resultsDicts = runGame( device, move, shots, sim, maxScore )
# make a directory for this device if it doesn't already exist
if not os.path.exists('results_' + device):
os.makedirs('results_' + device)
filename = 'move=' + move + '_shots=' + str(shots) + '_sim=' + str(sim) + '.txt'
saveFile = open('results_' + device + '/oneProbs_'+filename, 'a')
saveFile.write( str(oneProbs)+'\n' )
saveFile.close()
saveFile = open('results_' + device + '/sameProbs_'+filename, 'a')
saveFile.write( str(sameProbs)+'\n' )
saveFile.close()
saveFile = open('results_' + device + '/gates_'+filename, 'a')
saveFile.write( str(gates)+'\n' )
saveFile.close()
saveFile = open('results_' + device + '/conjugates_'+filename, 'a')
saveFile.write( str(conjugates)+'\n' )
saveFile.close()
if sim==False:
saveFile = open('results_' + device + '/results_'+filename, 'a')
saveFile.write( str(resultsDicts)+'\n' )
saveFile.close()
def CalculateQuality ( x, oneProbSamples, sameProbSamples, gateSamples, pairs, score, type='both') :
# see what fraction of the matchings we have corrent
fractionCorrect = 0
fracDifference = 0
for oneProbs, sameProbs, gates in zip(oneProbSamples, sameProbSamples, gateSamples):
oneProb = oneProbs[score-1]
sameProb = sameProbs[score-1]
if x!=[]:
rawOneProb = copy.deepcopy(oneProb)
oneProb = CleanData ( x, rawOneProb, sameProb, pairs )
gate = gates[ 2*(score-1) ]
matchingPairs = list(gate.keys())
guessedPairs = getDisjointPairs( pairs, oneProb=oneProb, weight={} )
correctGuesses = list( set(guessedPairs).intersection( set(matchingPairs) ) )
fractionCorrect += len(correctGuesses) / len(matchingPairs)
for p in gate.keys():
guessedOneProb = 0
for j in range(2):
guessedOneProb += oneProb[ pairs[p][j] ] / 2
fracDifference += (calculateFrac(guessedOneProb)-gate[p])**2 / len(oneProb)
fractionCorrect = fractionCorrect / len( oneProbSamples )
fracDifference = math.sqrt( fracDifference / len( oneProbSamples ) )
return fractionCorrect, fracDifference
def CleanData ( x, rawOneProb, sameProb, pairs ):
I = calculateMutual ( rawOneProb, sameProb, pairs )
matches = {}
for n in range(len(rawOneProb)):
maxI = 0
for p in pairs:
for j in range(2):
if n==pairs[p][j]:
if I[p]>maxI:
maxI = I[p]
matches[n] = pairs[p][(j+1)%2]
oneProb = []
for n in range(len(rawOneProb)):
if n in matches.keys():
match = matches[n]
else:
match = n
newOneProb = x[3*n] * rawOneProb[n] + x[3*n+1] * rawOneProb[match] + x[3*n+2]
newOneProb = min(1,newOneProb)
newOneProb = max(0,newOneProb)
oneProb.append( newOneProb )
return oneProb
def Metropolis ( x, oneProbSamples, sameProbSamples, gateSamples, num, pairs, score, steps_per_num=500, delta=0.01 ):
best_x = copy.deepcopy(x)
bestFractionCorrect , bestFracDifference = CalculateQuality ( x, oneProbSamples, sameProbSamples, gateSamples, pairs, score )
bestDiff = 0
if True:
x = copy.deepcopy(best_x)
fractionCorrect = bestFractionCorrect
fracDifference = bestFracDifference
steps = steps_per_num * num
for step in range(steps):
n = random.randint(0,3*num-1)
random_delta = random.uniform(+delta,-delta)
x[n] += random_delta
proposedFractionCorrect , proposedFracDifference = CalculateQuality ( x, oneProbSamples, sameProbSamples, gateSamples, pairs, score )
diff = fracDifference - proposedFracDifference
accept = (proposedFractionCorrect>fractionCorrect)
accept = accept or (proposedFractionCorrect==fractionCorrect) and ( proposedFracDifference < bestFracDifference )
if accept:
fractionCorrect = proposedFractionCorrect