forked from hadsed/AdiaQC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.py
475 lines (444 loc) · 19 KB
/
run.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
'''
File: run.py
Author: Hadayat Seddiqi
Date: 3.11.14
Description: Runs everything.
'''
import os, shutil, optparse
import json
import collections
import scipy as sp
from scipy import linalg as sla
from scipy import sparse as sps
import initialize
import solve
import statelabels
from solve import output
# Command line options
if __name__=="__main__":
parser = optparse.OptionParser("usage: %prog [options] arg1 arg2")
parser.add_option("-p", "--problem", dest="problem", default="",
type="string",
help="The problem that you want to run.")
parser.add_option("-r", "--relpath", dest="relpath", default="./",
type="string",
help="Relative path of run.py from current dir.")
parser.add_option("-i", "--instance", dest="instance", default=None,
type="int",
help="Instance number for large scale simulations.")
parser.add_option("-k", "--simtype", dest="simtype", default=None,
type="string",
help="Further specification of problem type, if needed.")
parser.add_option("-q", "--qubits", dest="qubits", default=None,
type="int",
help="Number of qubits, if needed for batch scripts.")
parser.add_option("-f", "--farg", dest="farg", default=None,
type="string",
help="Just another parameter, if needed.")
parser.add_option("-g", "--garg", dest="garg", default=None,
type="string",
help="Just another parameter, if needed.")
(options, args) = parser.parse_args()
problem = options.problem
relpath = options.relpath
instance = options.instance
simtype = options.simtype
qubits = options.qubits
farg = options.farg
garg = options.garg
# Clean up the problem path
problemClean = problem.replace('/', '.')
problemPath = ''
# Separate problem path and problem itself
if problemClean.endswith('.py'):
problemClean = problemClean[:-3]
while problemClean.rfind('.') > 0:
idx = problemClean.rfind('.') + 1
problemPath = problemClean[0:idx]
problemClean = problemClean[idx:]
# Now import it
try:
fparams = __import__("problems."+problemPath+problemClean,
fromlist=[problem])
except ImportError:
print ("Unable to import config file for '%s'." % problem)
raise SystemExit
# Get parameter dict from problem file
cmdargs = {'problem': problem,
'relpath': relpath,
'instance': instance,
'simtype': simtype,
'qubits': qubits,
'farg': farg,
'garg': garg}
params = fparams.parameters(cmdargs)
# Create data directory
pathpref = os.path.dirname(os.path.realpath(__file__)) + "/"
try:
os.makedirs(pathpref + params['outputdir'])
except OSError:
if not os.path.isdir(pathpref + params['outputdir']):
raise
# Get the other variables from the problem file
nQubits = params['nQubits']
T = params['T']
dt = params['dt']
errchk = params['errchk']
eps = params['eps']
isingConvert = params['isingConvert']
isingSigns = params['isingSigns']
hzscale = params['hzscale']
hzzscale = params['hzzscale']
hxscale = params['hxscale']
solveMethod = params['solveMethod']
# Output some params to a file
try:
params['outputs']
except NameError:
pass
else:
with open(pathpref + params['outputdir'] +
'/problem_outputs.dat', 'w') as handle:
json.dump(params['outputs'], handle)
# Construct output parameters dictionary
outinfo = {
'eigdat': params['eigdat'],
'eigplot': params['eigplot'],
'eignum': params['eignum'],
'fiddat': params['fiddat'],
'fidplot': params['fidplot'],
'fidnumstates': params['fidnumstates'],
'overlapdat': params['overlapdat'],
'overlapplot': params['overlapplot'],
'outdir': params['outdir'],
'probshow': params['probshow'],
'probout': params['probout'],
'mingap': params['mingap'],
'binary': params['binary'],
'progressout': params['progressout'],
'stateoverlap': params['stateoverlap']
}
# Copy the input file to the output dir
shutil.copyfile(relpath+'/problems/'+problemClean+'.py',
relpath+outinfo['outdir']+'/'+problemClean+'.out')
# Get our initial Hamiltonian coefficients
if (isingConvert):
# Get Ising coefficients
h, J, g = initialize.QUBO2Ising(params['Q'])
# Construct operators
hz, hzz, hx = initialize.IsingHamiltonian(nQubits, h, J, g)
# Free memory
del h, J, g, params['Q']
elif (params['alpha'].size == 0 and
params['beta'].size == 0 and
params['delta'].size == 0):
# Get default generated coefficients
hz, hzz, hx = initialize.HamiltonianGen(nQubits,
params['alpha'],
params['beta'],
params['delta'])
else:
alpha = beta = delta = 0
# Check if we need to generate individually
if (params['alpha'].size == 0):
alpha = sp.ones(nQubits)
else:
alpha = params['alpha']
if (params['beta'].size == 0):
beta = sp.ones((nQubits, nQubits))
else:
beta = params['beta']
if (params['delta'].size == 0):
delta = sp.ones(nQubits)
else:
delta = params['delta']
if (params['alpha'].size == 1 and params['beta'].size == 1):
hz, hzz = initialize.AlphaBetaCoeffs(nQubits, alpha, beta)
hx = initialize.DeltaCoeffs(nQubits, delta)
# Free up some memory
del params['alpha'], params['beta'], params['delta']
del alpha, beta, delta
else:
hz, hzz, hx = initialize.HamiltonianGen(nQubits, alpha, beta, delta)
del params['alpha'], params['beta'], params['delta']
del alpha, beta, delta
# Initial state
Psi0 = initialize.InitialState(-hx)
Psi = sp.empty(2**nQubits)
# Apply signs to our operators
hz *= isingSigns['hz']
hzz *= isingSigns['hzz']
hx *= isingSigns['hx']
# if outinfo['probshow']:
# print ("Initial state:")
# print (Psi0)
# Determine if we're doing multiple simulations over T
if isinstance(T, collections.Iterable):
# Keep the fidelity data somewhere
if (outinfo['fiddat'] or outinfo['fidplot']):
fidelitydata = []
# Keep the user-specified values for eigspec stuff
ueigdat = outinfo['eigdat']
ueigplot = outinfo['eigplot']
# Go through all the T's
for i in range(0, len(T)):
# If user wants eigenspectrum data/plots and is also doing multiple T's,
# make sure we output only one file since spectrum is independent of T.
if ueigdat:
if i == (len(T) - 1):
outinfo['eigdat'] = 1
else:
outinfo['eigdat'] = 0
if ueigplot:
if i == (len(T) - 1):
outinfo['eigplot'] = 1
else:
outinfo['eigplot'] = 0
# Solve the Schrodinger equation, get back the final state and mingap
if solveMethod == 'ExpPert':
Psi, mingap = solve.ExpPert(nQubits, hz, hzz, hx, Psi0,
T[i], dt[i], errchk, eps,
outinfo)
elif solveMethod == 'SuzTrot':
Psi, mingap = solve.SuzTrot(nQubits, hz, hzz, hx, Psi0,
T[i], dt[i], errchk, eps,
outinfo)
elif solveMethod == 'ForRuth':
Psi, mingap = solve.ForRuth(nQubits, hz, hzz, hx, Psi0,
T[i], dt[i], errchk, eps,
outinfo)
elif solveMethod == 'BCM':
Psi, mingap = solve.BCM(nQubits, hz, hzz, hx, Psi0,
T[i], dt[i], errchk, eps,
outinfo)
else:
print("Variable solveMethod has invalid input. See "+
"solve.py for the different solver methods available.")
sys.exit(1)
# Do fidelity stuff
if outinfo['fiddat'] or outinfo['fidplot']:
# Get the eigenpairs
Hvals, Hvecs = sp.linalg.eigh(hz + hzz)
# Sort by eigenvalues
idx = Hvals.argsort()
Hvals = Hvals[idx]
Hvecs = Hvecs[:,idx]
Hvecs = sp.transpose(Hvecs) # So we can grab them as vectors
# Construct fidelity data
if (outinfo['fiddat'] or outinfo['fidplot']):
d = solve.output.ConstructFidelityData(
Psi,
Hvecs[0:outinfo['fidnumstates']],
T[i],
outinfo['outdir'])
for j in range(0, outinfo['fidnumstates']):
fidelitydata.append(d[j])
# Record the mingap
if outinfo['mingap']:
solve.output.RecordMingap(T[i], mingap, 'mingap.dat', i,
relpath, outinfo)
# Record probabilities
if outinfo['probout']:
# Get state labelings and probabilities
bitstring = statelabels.GenerateLabels(nQubits)
density = statelabels.GetProbabilities(nQubits, Psi)
# Record the final output probabilities
solve.output.RecordProbs(bitstring, density,
'probsT'+str(T[i])+'.dat',
relpath, outinfo)
# Check if the bitstrings were recorded, if not, record them
if not os.path.isfile(relpath+outinfo['outdir']+'/statelabels.txt'):
# Build a nice string for output to file
finalstr = ''
for j in range(2**nQubits):
finalstr += bitstring[j] + '\n'
with open(relpath+outinfo['outdir']+'/statelabels.txt',
"w") as file:
file.write(finalstr)
# Incase the user wants this printed to screen
if outinfo['probshow']:
finalOutputStr = ''
# Sort by probability
bitstring, density = statelabels.SortStates(nQubits,
Psi,
bitstring,
density)
# Construct a nice-looking string
for j in range(2**nQubits):
outstr = bitstring[j] + '\t' + '%.8E' % density[j]
finalOutputStr += outstr + '\n'
# Print out the probabilities
print "\nProbability (T = "+str(T[i])+"):"
print finalOutputStr
# Sort fidelity data (so the plots come out correctly)
if (outinfo['fiddat'] or outinfo['fidplot']):
fidelitydata, fidelitydataplot = \
solve.output.SortFidelity(outinfo['fidnumstates'], fidelitydata)
# Write out fidelity data
if outinfo['fiddat']:
solve.output.RecordFidelity(fidelitydata, outinfo['outdir'],
outinfo['binary'])
# Plot fidelity(T)
if outinfo['fidplot']:
solve.output.PlotFidelity(fidelitydataplot, outinfo['outdir'],
outinfo['fidnumstates'])
# Determine if we're doing multiple simulations over Gamma
elif hzscale is not None:
# Keep the fidelity data somewhere
if (outinfo['fiddat'] or outinfo['fidplot']):
fidelitydata = []
# Go through all the Gamma's
for i in range(0, len(hzscale)):
# Solve the Schrodinger equation, get back the final state and mingap
if solveMethod == 'ExpPert':
Psi, mingap = solve.ExpPert(nQubits, hzscale[i]*hz, hzz, hx, Psi0,
T, dt, errchk, eps,
outinfo)
elif solveMethod == 'SuzTrot':
Psi, mingap = solve.SuzTrot(nQubits, hzscale[i]*hz, hzz, hx, Psi0,
T, dt, errchk, eps,
outinfo)
elif solveMethod == 'ForRuth':
Psi, mingap = solve.ForRuth(nQubits, hzscale[i]*hz, hzz, hx, Psi0,
T, dt, errchk, eps,
outinfo)
elif solveMethod == 'BCM':
Psi, mingap = solve.BCM(nQubits, hzscale[i]*hz, hzz, hx, Psi0,
T, dt, errchk, eps,
outinfo)
else:
print("Variable solveMethod has invalid input. See "+
"solve.py for the different solver methods available.")
sys.exit(1)
# Rename eigenspectrum.dat[.npy] for particular G (hzscale element)
esout_pref = outinfo['outdir']+'/'
esout = esout_pref+'eigenspectrum.dat'
esrenamed = esout_pref+'eigspecG'+str(hzscale[i])+'.dat'
if outinfo['binary']:
esout += '.npy'
esrenamed += '.npy'
os.rename(esout, esrenamed)
# Do fidelity stuff
if outinfo['fiddat'] or outinfo['fidplot']:
# Get the eigenpairs
Hvals, Hvecs = sp.linalg.eigh(hz + hzz)
# Sort by eigenvalues
idx = Hvals.argsort()
Hvals = Hvals[idx]
Hvecs = Hvecs[:,idx]
Hvecs = sp.transpose(Hvecs) # So we can grab them as vectors
# Construct fidelity data
if (outinfo['fiddat'] or outinfo['fidplot']):
d = solve.output.ConstructFidelityData(
Psi,
Hvecs[0:outinfo['fidnumstates']],
T,
outinfo['outdir'])
for j in range(0, outinfo['fidnumstates']):
fidelitydata.append(d[j])
# Record the mingap
if outinfo['mingap']:
solve.output.RecordMingap(hzscale[i], mingap, 'mingap.dat',
i, relpath, outinfo)
# Record probabilities
if outinfo['probout']:
# Get state labelings and probabilities
bitstring = statelabels.GenerateLabels(nQubits)
density = statelabels.GetProbabilities(nQubits, Psi)
# Record the final output probabilities
solve.output.RecordProbs(bitstring, density,
'probsG'+str(hzscale[i])+'.dat',
relpath, outinfo)
# Check if the bitstrings were recorded, if not, record them
if not os.path.isfile(relpath+outinfo['outdir']+'/statelabels.txt'):
# Build a nice string for output to file
finalstr = ''
for j in range(2**nQubits):
finalstr += bitstring[j] + '\n'
with open(relpath+outinfo['outdir']+'/statelabels.txt',
"w") as file:
file.write(finalstr)
# Incase the user wants this printed to screen
if outinfo['probshow']:
finalOutputStr = ''
# Sort by probability
bitstring, density = statelabels.SortStates(nQubits,
Psi,
bitstring,
density)
# Construct a nice-looking string
for j in range(2**nQubits):
outstr = bitstring[j] + '\t' + '%.8E' % density[j]
finalOutputStr += outstr + '\n'
# Print out the probabilities
print "\nProbability (T = "+str(T)+"):"
print finalOutputStr
# Sort fidelity data (so the plots come out correctly)
if (outinfo['fiddat'] or outinfo['fidplot']):
fidelitydata, fidelitydataplot = \
solve.output.SortFidelity(outinfo['fidnumstates'], fidelitydata)
# Write out fidelity data
if outinfo['fiddat']:
solve.output.RecordFidelity(fidelitydata, outinfo['outdir'],
outinfo['binary'])
# Plot fidelity(T)
if outinfo['fidplot']:
solve.output.PlotFidelity(fidelitydataplot, outinfo['outdir'],
outinfo['fidnumstates'])
else:
# Solve the Schrodinger equation, get back the final state and mingap
if solveMethod == 'ExpPert':
Psi, mingap = solve.ExpPert(nQubits, hz, hzz, hx, Psi0,
T, dt, errchk, eps,
outinfo)
elif solveMethod == 'SuzTrot':
Psi, mingap = solve.SuzTrot(nQubits, hz, hzz, hx, Psi0,
T, dt, errchk, eps,
outinfo)
elif solveMethod == 'ForRuth':
Psi, mingap = solve.ForRuth(nQubits, hz, hzz, hx, Psi0,
T, dt, errchk, eps,
outinfo)
elif solveMethod == 'BCM':
Psi, mingap = solve.BCM(nQubits, hz, hzz, hx, Psi0,
T, dt, errchk, eps,
outinfo)
else:
print("Variable solveMethod has invalid input. See "+
"solve.py for the different solver methods available.")
sys.exit(1)
# Output the minimal spectral gap
if outinfo['mingap']:
solve.output.RecordMingap(T, mingap, 'mingap.dat', None,
relpath, outinfo)
# Output the probabilities
if outinfo['probout']:
sp.set_printoptions(precision=16)
# Get state labelings, sort them in descending order
bitstring = statelabels.GenerateLabels(nQubits)
# Get probability densities
density = statelabels.GetProbabilities(nQubits, Psi)
# Output to file
solve.output.RecordProbs(bitstring, density,
'probsT'+str(T)+'.dat',
relpath, outinfo)
# Check if the bitstrings were recorded, if not, record them
if not os.path.isfile(relpath+outinfo['outdir']+'/statelabels.txt'):
# Build a nice string for output to file
finalstr = ''
for j in range(2**nQubits):
finalstr += bitstring[j] + '\n'
with open(relpath+outinfo['outdir']+'/statelabels.txt',
"w") as file:
file.write(finalstr)
# Output probabilities to screen if user wants it
if outinfo['probshow']:
finalOutputStr = ''
bitstring, density = statelabels.SortStates(nQubits,
bitstring,
density)
print ("Probability (T = "+str(T)+"):\n")
for i in range(2**nQubits):
outstr = bitstring[i] + '\t' + '%.8E' % density[i]
finalOutputStr += outstr + '\n'
print finalOutputStr