-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
335 lines (284 loc) · 11.8 KB
/
utils.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
#ExactCover
from collections import defaultdict
import numpy as np
from qat.core import Observable, Term
#QAOA
from pprint import pprint
import random
import json
import scipy
import matplotlib.pyplot as plt
from math import ceil
from p_tqdm import p_map
from scipy.stats import pearsonr
from qat.vsolve.ansatz import AnsatzFactory
from qat.qpus import get_default_qpu
from qat.plugins import ScipyMinimizePlugin
from multiprocessing import Pool
#Graph
import ipycytoscape
import ipywidgets as widgets
import networkx as nx
class Algorithm:
def __init__(self, threads = 1, num_prop = 100, p = 1, beta_corr_thr = 0.9, gamma_corr_thr = 0.9, beta_bound=np.pi * 1, gamma_bound=np.pi * 2):
self.beta_bound = beta_bound
self.gamma_bound = gamma_bound
self.solutions = []
self.progress_p = 0
self.progress_i = 0
self.p_range = [0, 0]
self.best_iter_solution = -1
self.iter_loop = 0
self.jobs_solution = -1
self.best_tape_graph = []
self.not_enough_calculation = 0
self.pool_size = threads
self.iter_init = num_prop
self.p = p
self.beta_corr_thr = beta_corr_thr
self.gamma_corr_thr = gamma_corr_thr
def match_params_to_job(self, x, job, p):
params = []
for var in job.get_variables():
idx = int(var.split('_')[-1].replace('{', '').replace('}', ''))
if 'beta' in var:
params.append(x[idx])
elif 'gamma' in var:
params.append(x[p + idx])
return params
def find_par(self, hamiltonian, i, p):
x = None
np.random.seed(random.randint(0, 2 ** 23 - 1))
x = np.random.rand(2 * p)
x[:p] = x[:p] * self.beta_bound
x[p:] = x[p:] * self.gamma_bound
circuit = AnsatzFactory.qaoa_circuit(hamiltonian, p)
job = circuit.to_job(observable=hamiltonian)
qpu = get_default_qpu()
init_params = self.match_params_to_job(x, job, p)
lb = np.zeros(len(x))
ub = np.ones(len(x))
ub[:p] *= self.beta_bound
ub[p:] *= self.gamma_bound
constraint = scipy.optimize.LinearConstraint(np.eye(len(x)), lb, ub)
stack = ScipyMinimizePlugin(method="COBYLA", tol=0.001, x0=init_params, constraints=constraint, options={'maxiter': 100000}) | qpu
result = stack.submit(job)
optimal_job = circuit.to_job()
optimal_job = optimal_job(
**{var: val for var, val in zip(job.get_variables(), json.loads(result.meta_data['parameters']))})
result_optimal = qpu.submit(optimal_job)
counts = {x.state.bitstring: x.probability for x in result_optimal}
energy, energies = self.compute_energy(counts)
var_map_dict = eval(result.meta_data['parameter_map'])
items = [[x[0].split('_'), x[1]] for x in list(var_map_dict.items())]
sorted_params = sorted(items, key=lambda i: [i[0][0], int(
i[0][1].replace('{', '').replace('}', ''))])
params = [x[1] for x in sorted_params]
print("", end="")
return (energy, params, counts, energies)
def range_energies(self, x, interval_count):
przedzial = ceil(len(x) / interval_count)
# print(przedzial)
interval = []
for i in range(ceil(len(x) / przedzial)):
if ((i + 1) * przedzial + 1 <= len(x)):
interval.append(sorted(list(set([x[i * przedzial], x[(i + 1) * przedzial]]))))
else:
if (x[i * przedzial] != x[-1]):
interval.append(sorted(list(set([x[i * przedzial], x[-1]]))))
else:
if (interval[-1][-1] != x[-1]):
interval.append([x[-1], '∞'])
if (interval[-1][-1] != '∞'):
interval.append([interval[-1][-1], '∞'])
return interval
def range_probability(self, y, interval_count):
przedzial = ceil(len(y) / interval_count)
interval = []
for i in range(ceil(len(y) / przedzial)):
if ((i + 1) * przedzial <= len(y)):
interval.append(self.sum_it(y[i * przedzial:(i + 1) * przedzial]))
else:
interval.append(self.sum_it(y[i * przedzial:]))
return interval
def sum_it(self, lista):
return round(sum(lista), 3)
def check_number_of_output_jobs(self, output):
output_no_blanks_sum = 0
for job in output:
if job[0][0]=="_":
continue
output_no_blanks_sum += 1
jobs_sum = 0
for x in self.jobs:
if isinstance(self.jobs[x], list):
jobs_sum += len(self.jobs[x])
if output_no_blanks_sum == jobs_sum:
return True
return False
def solve(self):
p = self.p
iter_loop = self.iter_init
hamiltonian = self.make_hamiltonian()
with Pool(p) as pool:
self.iter_loop = iter_loop
tape = pool.map(find_run, [[hamiltonian, i, p, self] for i in
range(iter_loop)])
best_tape = tape
if p > 1:
correlations = [(pearsonr(np.arange(1, p + 1), x[1][:p])[0],
pearsonr(np.arange(1, p + 1), x[1][p:])[0]) for x in tape]
best_tape = []
for t, c in zip(tape, correlations):
if c[0] > self.beta_corr_thr and c[1] > \
self.gamma_corr_thr:
best_tape.append(t)
best_tape = best_tape[:ceil(self.iter_init*0.3)]
try:
self.solutions.append((p, best_tape[0][2], best_tape[0][0]))
except:
print("Nothing good enought to add, probably not enought iteretion")
best_solution = ""
self.progress_p = -1
try:
best_solution = max(
self.solutions[-1][1], key=self.solutions[-1][1].get)
except:
pass
# print("\n")
# print("graph_data:", self.best_tape_graph, '\n')
# print("Najlepsze rozwiazanie to:", ''.join('1' if x == '0' else '0' for x in best_solution))
return (''.join('1' if x == '0' else '0' for x in best_solution))
# return 0
class EXACTCOVER(Algorithm):
def __init__(self, routes, threads = 1, num_prop = 100, p = 1, beta_corr_thr = 0.9, gamma_corr_thr = 0.9, beta_bound=np.pi * 1, gamma_bound=np.pi * 2):
Algorithm.__init__(self, threads, num_prop, p, beta_corr_thr, gamma_corr_thr, beta_bound, gamma_bound)
self.routes = routes
self.Jrr_dict = -1
self.hr_dict = -1
def Jrr(self, route1, route2):
s = len(set(route1).intersection(set(route2)))
return s / 2
def hr(self, route1, routes):
i_sum = 0
for r in routes:
i_sum += len(set(r).intersection(set(route1)))
s = i_sum - len(route1) * 2
return s / 2
def calculate_jrr_hr(self):
Jrr_dict = dict()
indices = np.triu_indices(len(self.routes), 1)
for i1, i2 in zip(indices[0], indices[1]):
Jrr_dict[(i1, i2)] = self.Jrr(self.routes[i1], self.routes[i2])
hr_dict = dict()
for i in range(len(self.routes)):
hr_dict[i] = self.hr(self.routes[i], self.routes)
return Jrr_dict, hr_dict
def make_hamiltonian(self):
line_obs = Observable(len(self.routes))
self.Jrr_dict, self.hr_dict = self.calculate_jrr_hr()
for i in self.Jrr_dict:
line_obs.add_term(Term(self.Jrr_dict[i], "ZZ", [i[0], i[1]]))
for i in self.hr_dict:
line_obs.add_term(Term(self.hr_dict[i], "Z", [i]))
return line_obs
def obj(self, x):
spin = list(map(lambda x: 2*x - 1, list(map(int, x))))
s1 = 0
indices = np.triu_indices(len(x), 1)
for i1, i2 in zip(indices[0], indices[1]):
partial = spin[i1] * spin[i2] * self.Jrr_dict[(i1, i2)]
s1 += partial
s2 = 0
for i in range(len(self.routes)):
s2 += self.hr_dict[i] * spin[i]
return s1 + s2
def compute_energy(self, counts):
energy = 0
energies = defaultdict(int)
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = self.obj(meas)
energies[obj_for_meas] += meas_count
energy += obj_for_meas * meas_count
total_counts += meas_count
return energy / total_counts, energies
class CustomNode(ipycytoscape.Node):
def __init__(self, name, classes='', label=''):
super().__init__()
self.data['id'] = name
self.classes = classes
self.data['label'] = label
class GRAPH():
def __init__(self, routes = [], result = ''):
self.routes = routes
self.result = result
def print_graph(self):
nodes = []
sender_labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
for sender_index, _ in enumerate(self.routes):
nodes.append(CustomNode(sender_labels[sender_index], label=sender_labels[sender_index], classes='class' + str(sender_index)))
nodes.append(CustomNode('ghost', classes='class-ghost'))
for i in range(7):
nodes.append(CustomNode(str(i), label=str(i+1), classes='class' + str(6+i)))
G = nx.Graph()
for sender_node in nodes:
G.add_node(sender_node)
for sender_index, sender in enumerate(self.routes):
is_in_result = 'False'
if self.result[sender_index] == '1':
is_in_result = 'True'
for receiver_id in list(sender):
G.add_edge(nodes[sender_index], nodes[6 + receiver_id], active=is_in_result)
styles = [
{
'selector': 'node',
'css': {
'background-color': 'white'
},
'style': {
'label': 'data(label)'
}
},
{
'selector': 'node.class-ghost',
'css': {
'background-color': 'white'
}
},
{
"selector": "edge.directed",
"style": {
"curve-style": "bezier",
"target-arrow-shape": "triangle",
"target-arrow-color": "#999",
},
},
{
"selector": "edge[active = 'True']",
"style": {
"line-color": "#106BEF",
"curve-style": "bezier",
"target-arrow-shape": "triangle",
"target-arrow-color": "#106BEF",
},
}]
additional_styles = []
for index, node in enumerate(self.result):
if node == '0':
continue
additional_styles.append({
'selector': 'node.class' + str(index),
'css': {
'background-color': '#106BEF',
'label': 'data(label)'
}
})
custom_inherited = ipycytoscape.CytoscapeWidget()
custom_inherited.graph.add_graph_from_networkx(G, directed=True)
custom_inherited.set_layout(name='grid', nodeSpacing=10, edgeLengthVal=10)
custom_inherited.set_style(styles + additional_styles)
return custom_inherited
def find_run(args):
hamiltonian, i, p, executing_class = args
return (executing_class.find_par(hamiltonian, i, p))