-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxbm.py
292 lines (187 loc) · 6.66 KB
/
xbm.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
import re
from typing import Union
import numpy as np
import scipy
from scipy.sparse import coo_matrix
from qiskit import QuantumCircuit, QuantumRegister
def get_vec_ab(
vec_a: QuantumCircuit,
vec_b: QuantumCircuit,
ancilla: Union[QuantumRegister, None] = None,
label_a: str = 'controlled_a',
label_b: str = 'controlled_b'
) -> QuantumCircuit:
if ancilla is None:
ancilla = QuantumRegister(1, name='ancilla')
bits = []
for qreg in vec_a.qregs:
bits += qreg._bits
bits += ancilla._bits
vec_ab = QuantumCircuit(QuantumRegister(bits=bits))
vec_ab.h(ancilla)
controlled_a = vec_a.to_gate()
controlled_a.label = label_a
controlled_a = controlled_a.control()
controlled_b = vec_b.to_gate()
controlled_b.label = label_b
controlled_b = controlled_b.control()
bits_rev = ancilla._bits.copy()
for qreg in vec_a.qregs:
bits_rev += qreg._bits
vec_ab.append(controlled_a, bits_rev)
vec_ab.x(ancilla)
vec_ab.append(controlled_b, bits_rev)
return vec_ab
def get_exp_meas_circ(circ, T_rc, j0_rc, is_imag):
meas_circ = circ.copy()
meas_circ.h(j0_rc)
for k in list(T_rc):
if k != j0_rc:
meas_circ.cx(j0_rc, k)
if is_imag:
meas_circ.s(j0_rc)
return meas_circ.inverse()
def get_nb_qubits(mat):
if scipy.sparse.issparse(mat):
nb_qubits = int(np.log2(mat.get_shape()[0]))
elif type(mat) == np.ndarray:
nb_qubits = int(np.log2(mat.shape[0]))
else:
raise TypeError(type(mat))
return nb_qubits
def expand_mat(mat):
nb_qubits = get_nb_qubits(mat)
if scipy.sparse.issparse(mat):
mat = scipy.sparse.kron(np.array([[0, 2], [0, 0]]), mat)
elif type(mat) == np.ndarray:
mat = np.kron(np.array([[0, 2], [0, 0]]), mat)
else:
raise TypeError(type(mat))
return mat
def get_rows_cols(mat):
if scipy.sparse.issparse(mat):
rows, cols = mat.nonzero()
elif type(mat) == np.ndarray:
rows, cols = np.where(mat != 0.)
else:
raise TypeError(type(mat))
return rows, cols
def get_matrix_component(mat, row, col):
if (scipy.sparse.isspmatrix_coo(mat) or
scipy.sparse.isspmatrix_bsr(mat) or
scipy.sparse.isspmatrix_dia(mat)):
data = mat.getcol(col).getrow(row).data
if len(data) == 0:
A_rc = 0.
else:
A_rc = data[0]
else:
if type(mat) == np.ndarray or scipy.sparse.issparse(mat):
A_rc = mat[row, col]
else:
raise TypeError(type(mat))
return A_rc
def get_trace(mat):
if scipy.sparse.issparse(mat):
trace = mat.diagonal().sum()
elif type(mat) == np.ndarray:
trace = np.trace(mat)
else:
raise TypeError(type(mat))
return trace
def get_all_meas_circs_bits_coefs(
psi_0,
psi_1,
mat_A,
part='both',
reduce_nb_measure=True,
return_circ=True
):
nb_qubits = get_nb_qubits(mat_A)
if psi_1 is not None:
base_circ = get_vec_ab(psi_0, psi_1)
mat_A = expand_mat(mat_A)
nb_qubits += 1
else:
base_circ = psi_0
rows, cols = get_rows_cols(mat_A)
bits = []
for qreg in base_circ.qregs:
bits += qreg._bits
meas_circ = QuantumCircuit(QuantumRegister(bits=bits))
if type(mat_A) == scipy.sparse.coo.coo_matrix:
mat_A = mat_A.tolil()
dict_M = {}
dict_G = {}
for rr, cc in zip(rows, cols):
A_rc = get_matrix_component(mat_A, rr, cc)
if rr == cc:
if 0 not in dict_M.keys():
dict_M.update({0: (meas_circ.copy(), None)})
dict_G.update({0: ({rr: A_rc}, None)})
else:
bitscoef_re, _ = dict_G[0]
bitscoef_re.update({rr: A_rc})
dict_G.update({0: (bitscoef_re, None)})
else:
if rr > cc:
r = cc
c = rr
A_re = A_rc
A_im = -A_rc
else:
r = rr
c = cc
A_re = A_im = A_rc
ones = re.finditer('1', bin(r ^ c)[2:].zfill(nb_qubits)[::-1])
zeros = re.finditer('0', bin(r)[2:].zfill(nb_qubits)[::-1])
T_rc = set([m.span()[0] for m in ones])
T0_r = set([m.span()[0] for m in zeros])
j0_rc = np.array(list(T_rc & T0_r)).max()
beta_rc_pls = r
beta_rc_mns = r ^ (2**j0_rc)
if r ^ c not in dict_M.keys():
M_rc_Re = M_rc_Im = bitscoef_re = bitscoef_im = None
if part == 'real' or part == 'both':
M_rc_Re = get_exp_meas_circ(meas_circ, T_rc, j0_rc, is_imag=False)
if part == 'imag' or part == 'both':
M_rc_Im = get_exp_meas_circ(meas_circ, T_rc, j0_rc, is_imag=True)
dict_M.update({r ^ c: (M_rc_Re, M_rc_Im)})
if part == 'real' or part == 'both':
bitscoef_re = {beta_rc_pls: 0.5 * A_re, beta_rc_mns: -0.5 * A_re}
if part == 'imag' or part == 'both':
bitscoef_im = {beta_rc_pls: 0.5j * A_im, beta_rc_mns: -0.5j * A_im}
dict_G.update({r ^ c: (bitscoef_re, bitscoef_im)})
else:
bitscoef_re, bitscoef_im = dict_G[r ^ c]
if part == 'real' or part == 'both':
bitscoef_re = dict_update(bitscoef_re, beta_rc_pls, 0.5 * A_re)
bitscoef_re = dict_update(bitscoef_re, beta_rc_mns, -0.5 * A_re)
if part == 'imag' or part == 'both':
bitscoef_im = dict_update(bitscoef_im, beta_rc_pls, 0.5j * A_im)
bitscoef_im = dict_update(bitscoef_im, beta_rc_mns, -0.5j * A_im)
dict_G.update({r ^ c: (bitscoef_re, bitscoef_im)})
return dictMG2meas(base_circ, dict_M, dict_G, nb_qubits)
def dict_update(dic, k, v):
if k in dic.keys():
dic.update({k: dic[k]+v})
else:
dic.update({k: v})
return dic
def dictMG2meas(base_circ, dict_M, dict_G, nb_qubits):
keys = dict_M.keys()
meas = []
for key in keys:
M_re, M_im = dict_M[key]
bitscoef_re, bitscoef_im = dict_G[key]
if bitscoef_re is not None:
foo = []
for k, v in bitscoef_re.items():
foo += [(bin(k)[2:].zfill(nb_qubits), v)]
meas += [(base_circ.combine(M_re), foo)]
if bitscoef_im is not None:
bar = []
for k, v in bitscoef_im.items():
bar += [(bin(k)[2:].zfill(nb_qubits), v)]
meas += [(base_circ.combine(M_im), bar)]
return meas