Skip to content

Commit 56091e4

Browse files
authored
Small fix (#25)
* removed constrained import, print * sequential mode for landscape sampling. good for running large jobs, to avoid memory overload
1 parent 6942cb0 commit 56091e4

File tree

2 files changed

+91
-35
lines changed

2 files changed

+91
-35
lines changed

examples/plotroutines.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,10 @@
55
import numpy as np
66

77
from qaoa import QAOA
8-
from qaoa.mixers.constrained_mixer import Constrained
98

109
from qaoa.util import Statistic
1110

11+
1212
def __plot_landscape(A, extent, fig):
1313
if not fig:
1414
fig = pl.figure(figsize=(6, 6), dpi=80, facecolor="w", edgecolor="k")
@@ -75,9 +75,7 @@ def plot_ApproximationRatio(
7575
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
7676

7777

78-
def plot_successprob(
79-
qaoa_instance, maxdepth, label, style="", fig=None, shots=10**4
80-
):
78+
def plot_successprob(qaoa_instance, maxdepth, label, style="", fig=None, shots=10**4):
8179
successp = []
8280
for p in range(1, qaoa_instance.current_depth + 1):
8381
ar, sp = __apprrat_successprob(qaoa_instance, p, shots=shots)
@@ -125,7 +123,7 @@ def __apprrat_successprob(qaoa_instance, depth, shots=10**4):
125123

126124

127125
def plot_angles(qaoa_instance, depth, label, style="", fig=None):
128-
angles=qaoa_instance.optimization_results[depth].get_best_angles()
126+
angles = qaoa_instance.optimization_results[depth].get_best_angles()
129127

130128
if not fig:
131129
ax = pl.figure().gca()
@@ -135,13 +133,13 @@ def plot_angles(qaoa_instance, depth, label, style="", fig=None):
135133
pl.plot(
136134
np.arange(1, depth + 1),
137135
angles[::2],
138-
"--"+style,
136+
"--" + style,
139137
label=r"$\gamma$ " + label,
140138
)
141139
pl.plot(
142140
np.arange(1, depth + 1),
143141
angles[1::2],
144-
"-"+style,
142+
"-" + style,
145143
label=r"$\beta$ " + label,
146144
)
147145
pl.xlim(1 - 0.25, depth + 0.25)

qaoa/qaoa.py

Lines changed: 86 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,7 @@ def __init__(
100100
flip=False,
101101
post=False,
102102
number_trottersteps_mixer=1,
103+
sequential=False,
103104
) -> None:
104105
"""
105106
A QAO-Ansatz consist of these parts:
@@ -146,6 +147,8 @@ def __init__(
146147
self.memory = self.memorysize > 0
147148
self.interpolate = interpolate
148149

150+
self.sequential = sequential
151+
149152
self.usebarrier = False
150153
self.isQNSPSA = False
151154

@@ -276,8 +279,7 @@ def createParameterizedCircuit(self, depth):
276279
self.parametrized_circuit_depth = depth
277280

278281
def sample_cost_landscape(
279-
self,
280-
angles={"gamma": [0, 2 * np.pi, 20], "beta": [0, 2 * np.pi, 20]},
282+
self, angles={"gamma": [0, 2 * np.pi, 20], "beta": [0, 2 * np.pi, 20]}
281283
):
282284
self.landscape_p1_angles = angles
283285
logger = LOG.bind(func=self.sample_cost_landscape.__name__)
@@ -291,32 +293,88 @@ def sample_cost_landscape(
291293
self.beta_grid = np.linspace(tmp[0], tmp[1], tmp[2])
292294

293295
if self.backend.configuration().local:
294-
print(depth, self.current_depth)
295-
self.createParameterizedCircuit(depth)
296-
gamma = [None] * angles["beta"][2] * angles["gamma"][2]
297-
beta = [None] * angles["beta"][2] * angles["gamma"][2]
298-
299-
counter = 0
300-
for b in range(angles["beta"][2]):
301-
for g in range(angles["gamma"][2]):
302-
gamma[counter] = self.gamma_grid[g]
303-
beta[counter] = self.beta_grid[b]
304-
counter += 1
305-
306-
parameters = {self.gamma_params[0]: gamma, self.beta_params[0]: beta}
307-
308-
logger.info("Executing sample_cost_landscape")
309-
logger.info(f"parameters: {len(parameters)}")
310-
job = self.backend.run(
311-
self.parameterized_circuit,
312-
shots=self.shots,
313-
parameter_binds=[parameters],
314-
optimization_level=0,
315-
memory=self.memory,
316-
)
317-
logger.info("Done execute")
318-
self.measurementStatistics(job)
319-
logger.info("Done measurement")
296+
if self.sequential:
297+
expectations = []
298+
variances = []
299+
maxcosts = []
300+
mincosts = []
301+
302+
self.createParameterizedCircuit(depth)
303+
logger.info("Executing sample_cost_landscape")
304+
for b in range(angles["beta"][2]):
305+
for g in range(angles["gamma"][2]):
306+
gamma = self.gamma_grid[g]
307+
beta = self.beta_grid[b]
308+
params = self.getParametersToBind(
309+
[gamma, beta], self.parametrized_circuit_depth, asList=True
310+
)
311+
312+
job = self.backend.run(
313+
self.parameterized_circuit,
314+
noise_model=self.noisemodel,
315+
shots=self.shots,
316+
parameter_binds=[params],
317+
optimization_level=0,
318+
memory=self.memory,
319+
)
320+
321+
jres = job.result()
322+
counts_list = jres.get_counts()
323+
324+
self.stat.reset()
325+
for string in counts_list:
326+
# qiskit binary strings use little endian encoding, but our cost function expects big endian encoding. Therefore, we reverse the order
327+
cost = self.problem.cost(string[::-1])
328+
self.stat.add_sample(
329+
cost, counts_list[string], string[::-1]
330+
)
331+
332+
expectations.append(self.stat.get_CVaR())
333+
variances.append(self.stat.get_Variance())
334+
maxcosts.append(self.stat.get_max())
335+
mincosts.append(self.stat.get_min())
336+
337+
angles = self.landscape_p1_angles
338+
self.Exp_sampled_p1 = -np.array(expectations).reshape(
339+
angles["beta"][2], angles["gamma"][2]
340+
)
341+
self.Var_sampled_p1 = np.array(variances).reshape(
342+
angles["beta"][2], angles["gamma"][2]
343+
)
344+
self.MaxCost_sampled_p1 = -np.array(maxcosts).reshape(
345+
angles["beta"][2], angles["gamma"][2]
346+
)
347+
self.MinCost_sampled_p1 = -np.array(mincosts).reshape(
348+
angles["beta"][2], angles["gamma"][2]
349+
)
350+
logger.info("Done measurement")
351+
else:
352+
self.createParameterizedCircuit(depth)
353+
gamma = [None] * angles["beta"][2] * angles["gamma"][2]
354+
beta = [None] * angles["beta"][2] * angles["gamma"][2]
355+
356+
counter = 0
357+
for b in range(angles["beta"][2]):
358+
for g in range(angles["gamma"][2]):
359+
gamma[counter] = self.gamma_grid[g]
360+
beta[counter] = self.beta_grid[b]
361+
counter += 1
362+
363+
parameters = {self.gamma_params[0]: gamma, self.beta_params[0]: beta}
364+
365+
logger.info("Executing sample_cost_landscape")
366+
logger.info(f"parameters: {len(parameters)}")
367+
job = self.backend.run(
368+
self.parameterized_circuit,
369+
noise_model=self.noisemodel,
370+
shots=self.shots,
371+
parameter_binds=[parameters],
372+
optimization_level=0,
373+
memory=self.memory,
374+
)
375+
logger.info("Done execute")
376+
self.measurementStatistics(job)
377+
logger.info("Done measurement")
320378

321379
else:
322380
raise NotImplementedError

0 commit comments

Comments
 (0)