-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqasm_parser.py
More file actions
233 lines (217 loc) · 8.96 KB
/
Copy pathqasm_parser.py
File metadata and controls
233 lines (217 loc) · 8.96 KB
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
from qiskit import *
from qiskit.quantum_info import Statevector, DensityMatrix, partial_trace, random_statevector
from qiskit.quantum_info.operators import Operator
from qiskit.circuit.library import XGate, SGate, SdgGate, CPhaseGate
from qiskit.extensions import UnitaryGate
import time
import random
import numpy as np
import warnings
import builtins as __builtin__
import sys
warnings.filterwarnings("ignore", category=DeprecationWarning)
warnings.filterwarnings("ignore", category=FutureWarning)
random.seed(0)
# XGate().control(num_ctrl_qubits=3,ctrl_state='000')
#font: Lucida Console
def print(*args, **kwargs): # overwrite print Boolean matrices
new_args = []
for item in args:
if type(item) == np.ndarray and item.dtype == np.dtype('bool'):
new_args.append(item.astype(int))
else:
new_args.append(item)
new_args = tuple(new_args)
return __builtin__.print(*new_args, **kwargs)
def show_m(m, thres=0.005):
data = ''
for i in range(len(m)):
for j in range(len(m[i])):
if abs(m[i,j].real) > thres:
real = '%.4f' % m[i,j].real
else:
real = '0'
mid = ' + '
if abs(m[i,j].imag) > thres:
imag = '%.4f' % abs(m[i,j].imag)
if m[i,j].imag<0:
mid = ' - '
else:
imag = '0'
data += real.rjust(7) + mid + imag.ljust(8) + ' '
data += '\n'
print(data)
def importQasm(filename):
# record operations
operations = []
qregs = []
cregs = []
with open(filename) as file:
data = file.read().replace(",", " ").replace("->", " -> ").strip('\n').split('\n')
for line in data:
if '//' in line:
line = line[:line.index('//')]
line = line.strip('; ')
if line == '':
continue
line = line.split()
if '(' in line[0]:
for i in range(len(line)):
if ')' in line[i]:
break
tmp = []
tmp.append(' '.join(line[:i+1]))
for item in line[i+1:]:
tmp.append(item)
line = tmp
if line[0] in ['OPENQASM', 'include']:
continue
elif line[0] == 'qreg':
name = line[1][:line[1].index('[')]
number = int(line[1][line[1].index('[')+1:line[1].index(']')])
qregs.append((name, number))
elif line[0] == 'creg':
name = line[1][:line[1].index('[')]
number = int(line[1][line[1].index('[')+1:line[1].index(']')])
cregs.append((name, number))
elif line[0] == 'measure':
if '[' not in line[1]:
assert('[' not in line[3])
qubits = []
qreg = line[1]
qubits.append((qreg,))
assert(line[2]=='->')
clbits = []
creg = line[3]
clbits.append((creg,))
operations.append( (line[0], qubits, clbits) )
else:
qubits = []
item = line[1]
qreg = item[:item.index('[')]
number = int(item[ item.index('[')+1 : item.index(']') ])
qubits.append((qreg, number))
assert(line[2]=='->')
clbits = []
item = line[3]
creg = item[:item.index('[')]
number = int(item[ item.index('[')+1 : item.index(']') ])
clbits.append((creg, number))
operations.append( (line[0], qubits, clbits) )
else:
qubits = []
for item in line[1:]:
qreg = item[:item.index('[')]
number = int(item[ item.index('[')+1 : item.index(']') ])
qubits.append((qreg,number))
operations.append( (line[0], qubits) )
# create circuit
qregs_map = dict()
cregs_map = dict()
for (name, number) in qregs:
qregs_map[name] = QuantumRegister(number)
for (name, number) in cregs:
cregs_map[name] = ClassicalRegister(number)
qc = QuantumCircuit(*(list(qregs_map.values()) + list(cregs_map.values())))
def getQ(qubit):
return qregs_map[qubit[0]][qubit[1]]
def getAngle(string):
return eval(string.replace('pi', str(np.pi)))
single_qubit_mapping = {'h': qc.h, 's': qc.s, 't': qc.t,'x': qc.x, 'y': qc.y, 'z': qc.z, 'sdg': qc.sdg, 'tdg': qc.tdg, 'sx': qc.sx, 'reset': qc.reset }
two_qubit_mapping = {'cx': qc.cx, 'cz': qc.cz, 'swap': qc.swap}
for op in operations:
gate = op[0]
if gate == 'measure':
assert(len(op[1])==1)
assert(len(op[2])==1)
if len(op[1][0])==1:
assert(len(op[2])==1)
qname = op[1][0][0]
cname = op[2][0][0]
assert(qregs_map[qname].size==cregs_map[cname].size)
for i in range(qregs_map[qname].size):
qc.measure(qregs_map[qname][i], cregs_map[cname][i])
else:
(qname, qnum) = op[1][0]
(cname, cnum) = op[2][0]
qc.measure(qregs_map[qname][qnum], cregs_map[cname][cnum])
else:
qubits = list(map(getQ, op[1]))
if gate in single_qubit_mapping:
assert(len(qubits)==1)
single_qubit_mapping[gate](qubits[0])
elif gate in two_qubit_mapping:
assert(len(qubits)==2)
two_qubit_mapping[gate](qubits[0], qubits[1])
elif gate.startswith('rx('):
assert(len(qubits)==1)
angle = getAngle(gate.strip('rx()'))
qc.rx(angle, qubits[0])
elif gate.startswith('ry('):
assert(len(qubits)==1)
angle = getAngle(gate.strip('ry()'))
qc.ry(angle, qubits[0])
elif gate.startswith('rz('):
assert(len(qubits)==1)
angle = getAngle(gate.strip('rz()'))
qc.rz(angle, qubits[0])
elif gate.startswith('p('):
assert(len(qubits)==1)
angle = getAngle(gate.strip('p()'))
qc.p(angle, qubits[0])
elif gate.startswith('u('):
assert(len(qubits)==1)
angles = list(map(getAngle, gate.strip('u()').split() ))
assert(len(angles)==3)
qc.u(angles[0], angles[1], angles[2], qubits[0])
elif gate.startswith('u2('):
assert(len(qubits)==1)
angles = list(map(getAngle, gate.replace('u2(','').split() ))
assert(len(angles)==2)
qc.u2(angles[0], angles[1], qubits[0])
elif gate.startswith('rzz('):
assert(len(qubits)==2)
angle = getAngle(gate.strip('rz()'))
qc.rzz(angle, qubits[0], qubits[1])
elif gate.startswith('cp('):
assert(len(qubits)==2)
angle = getAngle(gate.strip('cp()'))
qc.cp(angle, qubits[0], qubits[1])
elif gate.startswith('cz('):
assert(len(qubits)==2)
angle = getAngle(gate.strip('cz()'))
qc.cz(angle, qubits[0], qubits[1])
elif gate=='mcx' or gate=='mcx_gray':
assert(len(qubits)>1)
qc.mcx( qubits[:-1], qubits[-1] )
elif gate=='ccx':
assert(len(qubits)==3)
qc.ccx( qubits[0], qubits[1], qubits[2] )
elif gate=='cswap':
assert(len(qubits)==3)
qc.cswap(qubits[0], qubits[1], qubits[2])
else:
print(gate)
assert(False)
return qc
def exportQasm(qc, filename):
with open(filename, 'w') as file:
file.write("OPENQASM 2.0;\n")
file.write('include "qelib1.inc";\n')
for item in qc.qregs:
file.write("qreg %s[%d];\n" % (item.name, item.size))
if qc.cregs:
assert(len(qc.cregs) == 1)
file.write("creg c[%d];\n" % qc.cregs[0].size)
for gate in qc.data:
op = gate[0]
qubits = gate[1]
if op.name == 'measure':
clbits = gate[2]
assert(len(qubits) == len(clbits) == 1)
file.write("measure %s[%d] -> c[%d];\n" % (qubits[0].register.name, qubits[0].index, clbits[0].index))
else:
if op.params:
file.write("%s(%s) %s;\n" % ( op.name, ', '.join(map(str, op.params)), ', '.join(map(lambda q:'%s[%d]'%(q.register.name, q.index), qubits)) ))
else:
file.write("%s %s;\n" % ( op.name, ', '.join(map(lambda q:'%s[%d]'%(q.register.name, q.index), qubits)) ))