16
16
17
17
import copy
18
18
import logging
19
- from typing import Optional , Dict , Union , Tuple
20
19
import math
20
+ from typing import Optional , Dict , Union , Tuple
21
21
22
22
import numpy as np
23
-
24
23
from qiskit import QuantumCircuit
25
- from qiskit .providers import BaseBackend
26
24
from qiskit .aqua import QuantumInstance , aqua_globals
27
25
from qiskit .aqua .algorithms .amplitude_amplifiers .grover import Grover
26
+ from qiskit .providers import BaseBackend
27
+
28
28
from .optimization_algorithm import OptimizationAlgorithm , OptimizationResult
29
- from ..problems .quadratic_program import QuadraticProgram
30
- from ..converters .quadratic_program_to_qubo import QuadraticProgramToQubo
31
29
from ..converters .quadratic_program_to_negative_value_oracle import \
32
30
QuadraticProgramToNegativeValueOracle
33
-
31
+ from ..converters .quadratic_program_to_qubo import QuadraticProgramToQubo
32
+ from ..problems .quadratic_program import QuadraticProgram
34
33
35
34
logger = logging .getLogger (__name__ )
36
35
@@ -133,7 +132,7 @@ def solve(self, problem: QuadraticProgram) -> OptimizationResult:
133
132
n_value = self ._num_value_qubits
134
133
135
134
# Variables for tracking the solutions encountered.
136
- num_solutions = 2 ** n_key
135
+ num_solutions = 2 ** n_key
137
136
keys_measured = []
138
137
139
138
# Variables for result object.
@@ -143,7 +142,7 @@ def solve(self, problem: QuadraticProgram) -> OptimizationResult:
143
142
144
143
# Variables for stopping if we've hit the rotation max.
145
144
rotations = 0
146
- max_rotations = int (np .ceil (100 * np .pi / 4 ))
145
+ max_rotations = int (np .ceil (100 * np .pi / 4 ))
147
146
148
147
# Initialize oracle helper object.
149
148
orig_constant = problem_ .objective .constant
@@ -164,7 +163,7 @@ def solve(self, problem: QuadraticProgram) -> OptimizationResult:
164
163
while not improvement_found :
165
164
# Determine the number of rotations.
166
165
loops_with_no_improvement += 1
167
- rotation_count = int (np .ceil (aqua_globals .random .uniform (0 , m - 1 )))
166
+ rotation_count = int (np .ceil (aqua_globals .random .uniform (0 , m - 1 )))
168
167
rotations += rotation_count
169
168
170
169
# Apply Grover's Algorithm to find values below the threshold.
@@ -196,7 +195,7 @@ def solve(self, problem: QuadraticProgram) -> OptimizationResult:
196
195
threshold = optimum_value
197
196
else :
198
197
# Using Durr and Hoyer method, increase m.
199
- m = int (np .ceil (min (m * 8 / 7 , 2 ** (n_key / 2 ))))
198
+ m = int (np .ceil (min (m * 8 / 7 , 2 ** (n_key / 2 ))))
200
199
logger .info ('No Improvement. M: %s' , m )
201
200
202
201
# Check if we've already seen this value.
@@ -225,16 +224,17 @@ def solve(self, problem: QuadraticProgram) -> OptimizationResult:
225
224
opt_x = [1 if s == '1' else 0 for s in ('{0:%sb}' % n_key ).format (optimum_key )]
226
225
227
226
# Build the results object.
228
- grover_results = GroverOptimizationResults (operation_count , n_key , n_value , func_dict )
227
+ grover_results = GroverOptimizationRawResult (operation_count , n_key , n_value , func_dict )
229
228
fval = solutions [optimum_key ]
230
229
if sense == problem_ .objective .Sense .MAXIMIZE :
231
230
fval = - fval
232
- result = OptimizationResult (x = opt_x , variables = problem .variables , fval = fval ,
233
- results = {"grover_results" : grover_results ,
234
- "qubo_converter" : copy .deepcopy (self ._qubo_converter ),
235
- "negative_value_oracle_converter" : copy .deepcopy (
236
- opt_prob_converter )
237
- })
231
+ result = OptimizationResult (x = opt_x , fval = fval , variables = problem .variables ,
232
+ raw_results = {"grover_results" : grover_results ,
233
+ "qubo_converter" : copy .deepcopy (
234
+ self ._qubo_converter ),
235
+ "negative_value_oracle_converter" : copy .deepcopy (
236
+ opt_prob_converter )
237
+ })
238
238
239
239
# cast binaries back to integers
240
240
result = self ._qubo_converter .interpret (result )
@@ -247,7 +247,7 @@ def _measure(self, circuit: QuantumCircuit) -> str:
247
247
freq = sorted (probs .items (), key = lambda x : x [1 ], reverse = True )
248
248
249
249
# Pick a random outcome.
250
- freq [len ( freq ) - 1 ] = (freq [len ( freq ) - 1 ][0 ], 1.0 - sum ([ x [1 ] for x in freq [0 :len (freq )- 1 ] ]))
250
+ freq [- 1 ] = (freq [- 1 ][0 ], 1.0 - sum (x [1 ] for x in freq [0 :len (freq ) - 1 ]))
251
251
idx = aqua_globals .random .choice (len (freq ), 1 , p = [x [1 ] for x in freq ])[0 ]
252
252
logger .info ('Frequencies: %s' , freq )
253
253
@@ -261,7 +261,7 @@ def _get_probs(self, qc: QuantumCircuit) -> Dict[str, float]:
261
261
state = np .round (result .get_statevector (qc ), 5 )
262
262
keys = [bin (i )[2 ::].rjust (int (np .log2 (len (state ))), '0' )[::- 1 ]
263
263
for i in range (0 , len (state ))]
264
- probs = [np .round (abs (a )* abs (a ), 5 ) for a in state ]
264
+ probs = [np .round (abs (a ) * abs (a ), 5 ) for a in state ]
265
265
hist = dict (zip (keys , probs ))
266
266
else :
267
267
state = result .get_counts (qc )
@@ -276,13 +276,13 @@ def _get_probs(self, qc: QuantumCircuit) -> Dict[str, float]:
276
276
@staticmethod
277
277
def _twos_complement (v : int , n_bits : int ) -> str :
278
278
"""Converts an integer into a binary string of n bits using two's complement."""
279
- assert - 2 ** n_bits <= v < 2 ** n_bits
279
+ assert - 2 ** n_bits <= v < 2 ** n_bits
280
280
281
281
if v < 0 :
282
- v += 2 ** n_bits
282
+ v += 2 ** n_bits
283
283
bin_v = bin (v )[2 :]
284
284
else :
285
- format_string = '{0:0' + str (n_bits )+ 'b}'
285
+ format_string = '{0:0' + str (n_bits ) + 'b}'
286
286
bin_v = format_string .format (v )
287
287
288
288
return bin_v
@@ -315,14 +315,14 @@ def _get_qubo_solutions(function_dict: Dict[Union[int, Tuple[int, int]], int], n
315
315
constant = 0
316
316
if - 1 in function_dict :
317
317
constant = function_dict [- 1 ]
318
- format_string = '{0:0' + str (n_key )+ 'b}'
318
+ format_string = '{0:0' + str (n_key ) + 'b}'
319
319
320
320
# Iterate through every key combination.
321
321
if print_solutions :
322
322
print ("QUBO Solutions:" )
323
323
print ("==========================" )
324
324
solutions = {}
325
- for i in range (2 ** n_key ):
325
+ for i in range (2 ** n_key ):
326
326
solution = constant
327
327
328
328
# Convert int to a list of binary variables.
@@ -355,8 +355,8 @@ def _get_qubo_solutions(function_dict: Dict[Union[int, Tuple[int, int]], int], n
355
355
return solutions
356
356
357
357
358
- class GroverOptimizationResults :
359
- """A results object for Grover Optimization methods."""
358
+ class GroverOptimizationRawResult :
359
+ """A raw result object for Grover Optimization methods."""
360
360
361
361
def __init__ (self , operation_counts : Dict [int , Dict [str , int ]],
362
362
n_input_qubits : int , n_output_qubits : int ,
0 commit comments