def test_qaoa(self, w, p, m, solutions): self.log.debug('Testing {}-step QAOA with MaxCut on graph\n{}'.format( p, w)) np.random.seed(0) backend = BasicAer.get_backend('statevector_simulator') optimizer = COBYLA() qubitOp, offset = max_cut.get_max_cut_qubitops(w) qaoa = QAOA(qubitOp, optimizer, p, operator_mode='matrix', mixer=m) quantum_instance = QuantumInstance(backend) result = qaoa.run(quantum_instance) x = max_cut.sample_most_likely(result['eigvecs'][0]) graph_solution = max_cut.get_graph_solution(x) self.log.debug('energy: {}'.format(result['energy'])) self.log.debug('time: {}'.format(result['eval_time'])) self.log.debug('maxcut objective: {}'.format(result['energy'] + offset)) self.log.debug('solution: {}'.format(graph_solution)) self.log.debug('solution objective: {}'.format( max_cut.max_cut_value(x, w))) self.assertIn(''.join([str(int(i)) for i in graph_solution]), solutions) if quantum_instance.has_circuit_caching: self.assertLess(quantum_instance._circuit_cache.misses, 3)
def decode_result(result, offset=0): x = max_cut.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('max-cut objective:', result['energy'] + offset) print('solution:', max_cut.get_graph_solution(x)) print('solution objective:', max_cut.max_cut_value(x, w)) return " "
def test_qaoa(self, w, prob, m, solutions): """ QAOA test """ seed = 0 aqua_globals.random_seed = seed os.environ.pop('QISKIT_AQUA_CIRCUIT_CACHE', None) self.log.debug('Testing %s-step QAOA with MaxCut on graph\n%s', prob, w) backend = BasicAer.get_backend('statevector_simulator') optimizer = COBYLA() qubit_op, offset = max_cut.get_qubit_op(w) qaoa = QAOA(qubit_op, optimizer, prob, mixer=m) # TODO: cache fails for QAOA since we construct the evolution circuit via instruction quantum_instance = QuantumInstance(backend, circuit_caching=False, seed_simulator=seed, seed_transpiler=seed) result = qaoa.run(quantum_instance) x = sample_most_likely(result['eigvecs'][0]) graph_solution = max_cut.get_graph_solution(x) self.log.debug('energy: %s', result['energy']) self.log.debug('time: %s', result['eval_time']) self.log.debug('maxcut objective: %s', result['energy'] + offset) self.log.debug('solution: %s', graph_solution) self.log.debug('solution objective: %s', max_cut.max_cut_value(x, w)) self.assertIn(''.join([str(int(i)) for i in graph_solution]), solutions) if quantum_instance.has_circuit_caching: self.assertLess(quantum_instance._circuit_cache.misses, 3)
def test_qaoa(self, w, prob, m, solutions): """ QAOA test """ seed = 0 aqua_globals.random_seed = seed self.log.debug('Testing %s-step QAOA with MaxCut on graph\n%s', prob, w) backend = BasicAer.get_backend('statevector_simulator') optimizer = COBYLA() qubit_op, offset = max_cut.get_qubit_op(w) qaoa = QAOA(qubit_op, optimizer, prob, mixer=m) quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed) result = qaoa.run(quantum_instance) x = sample_most_likely(result['eigvecs'][0]) graph_solution = max_cut.get_graph_solution(x) self.log.debug('energy: %s', result['energy']) self.log.debug('time: %s', result['eval_time']) self.log.debug('maxcut objective: %s', result['energy'] + offset) self.log.debug('solution: %s', graph_solution) self.log.debug('solution objective: %s', max_cut.max_cut_value(x, w)) self.assertIn(''.join([str(int(i)) for i in graph_solution]), solutions)
def test_qaoa(self, w, p, m, solutions): os.environ.pop('QISKIT_AQUA_CIRCUIT_CACHE', None) self.log.debug('Testing {}-step QAOA with MaxCut on graph\n{}'.format( p, w)) np.random.seed(0) backend = BasicAer.get_backend('statevector_simulator') optimizer = COBYLA() qubit_op, offset = max_cut.get_max_cut_qubitops(w) qaoa = QAOA(qubit_op, optimizer, p, mixer=m) # TODO: cache fails for QAOA since we construct the evolution circuit via instruction quantum_instance = QuantumInstance(backend, circuit_caching=False) result = qaoa.run(quantum_instance) x = max_cut.sample_most_likely(result['eigvecs'][0]) graph_solution = max_cut.get_graph_solution(x) self.log.debug('energy: {}'.format(result['energy'])) self.log.debug('time: {}'.format(result['eval_time'])) self.log.debug('maxcut objective: {}'.format(result['energy'] + offset)) self.log.debug('solution: {}'.format(graph_solution)) self.log.debug('solution objective: {}'.format( max_cut.max_cut_value(x, w))) self.assertIn(''.join([str(int(i)) for i in graph_solution]), solutions) if quantum_instance.has_circuit_caching: self.assertLess(quantum_instance._circuit_cache.misses, 3)
def test_cplex_ising_direct(self): try: algo = CPLEX_Ising(self.algo_input.qubit_op, display=0) result = algo.run() self.assertEqual(result['energy'], -20.5) x_dict = result['x_sol'] x = np.array([x_dict[i] for i in sorted(x_dict.keys())]) np.testing.assert_array_equal(max_cut.get_graph_solution(x), [1, 0, 1, 1]) self.assertEqual(max_cut.max_cut_value(x, self.w), 24) except AquaError as e: self.skipTest(str(e))
def test_cplex_ising_via_run_algorithm(self): try: params = { 'problem': { 'name': 'ising' }, 'algorithm': { 'name': 'CPLEX.Ising', 'display': 0 } } result = run_algorithm(params, self.algo_input) self.assertEqual(result['energy'], -20.5) x_dict = result['x_sol'] x = np.array([x_dict[i] for i in sorted(x_dict.keys())]) np.testing.assert_array_equal(max_cut.get_graph_solution(x), [1, 0, 1, 1]) self.assertEqual(max_cut.max_cut_value(x, self.w), 24) except AquaError as e: self.skipTest(str(e))
pauli_list.append([value, Pauli(zp, xp)]) return WeightedPauliOperator(paulis=pauli_list), constant isingdict ={(0,1):0.5,(1,2):0.5,(2,3):0.5,(3,4):0.5,():-2.0} qubitOp, shift = get_ising_qubitops(isingdict,5) provider = OpenSuperQ_Provider() backend = provider.get_backend('OSQ_ETH7_rev1') optimizer = POWELL() qaoa = QAOA(qubitOp, optimizer, p=1, operator_mode='paulis',initial_point=[0.0, 0.0]) quantum_instance = QuantumInstance(backend) circ = qaoa.construct_circuit(parameter=[2.0, 1.0],circuit_name_prefix='Hello',statevector_mode=True) latex = circ[0].draw(output='latex_source') result = qaoa.run(quantum_instance) print('shift: ', shift) print('name: ', result.keys()) print([str(key) + " " + str(value) for key, value in result.items()]) plot_histogram(result['eigvecs'], figsize = (18,5)) x = max_cut.sample_most_likely(result['eigvecs'][0]) graph_solution = max_cut.get_graph_solution(x) #qaoa._circuit.draw(output='mpl') print('Hello')
algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'matrix' } optimizer_cfg = { 'name': 'SPSA', 'max_trials': 300 } var_form_cfg = { 'name': 'RY', 'depth': 5, 'entanglement': 'linear' } params = { 'problem': {'name': 'ising', 'random_seed': seed}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg, 'backend': {provider': 'qiskit.BasicAer', 'name': 'statevector_simulator'} } result = run_algorithm(params, algo_input) """ x = max_cut.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('solution:', max_cut.get_graph_solution(x))
def qiskit_maxcut(): n = 4 # Number of nodes in graph G = nx.Graph() G.add_nodes_from(np.arange(0, n, 1)) elist = [(0, 1, 1.0), (0, 2, 1.0), (0, 3, 1.0), (1, 2, 1.0), (2, 3, 1.0)] # tuple is (i,j,weight) where (i,j) is the edge G.add_weighted_edges_from(elist) colors = ['r' for node in G.nodes()] pos = nx.spring_layout(G) default_axes = plt.axes(frameon=True) nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, ax=default_axes, pos=pos) w = np.zeros([n, n]) for i in range(n): for j in range(n): temp = G.get_edge_data(i, j, default=0) if temp != 0: w[i, j] = temp['weight'] # print(w) # weight matrix. i.e. distances. 0 indicates no path. ##### # Brute force solution # best_cost_brute = 0 # for b in range(2 ** n): # x = [int(t) for t in reversed(list(bin(b)[2:].zfill(n)))] # cost = 0 # for i in range(n): # for j in range(n): # cost = cost + w[i, j] * x[i] * (1 - x[j]) # if best_cost_brute < cost: # best_cost_brute = cost # xbest_brute = x # print('case = ' + str(x) + ' cost = ' + str(cost)) # # colors = ['r' if xbest_brute[i] == 0 else 'b' for i in range(n)] # nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, pos=pos) # print('\nBest solution = ' + str(xbest_brute) + ' cost = ' + str(best_cost_brute)) # End brute force solution ##### ##### # Eigensolver solution # qubitOp, offset = max_cut.get_max_cut_qubitops(w) # algo_input = EnergyInput(qubitOp) # # # Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector # ee = ExactEigensolver(qubitOp, k=1) # result = ee.run() # # """ # algorithm_cfg = { # 'name': 'ExactEigensolver', # } # # params = { # 'problem': {'name': 'ising'}, # 'algorithm': algorithm_cfg # } # result = run_algorithm(params,algo_input) # """ # x = max_cut.sample_most_likely(result['eigvecs'][0]) # print('energy:', result['energy']) # print('maxcut objective:', result['energy'] + offset) # print('solution:', max_cut.get_graph_solution(x)) # print('solution objective:', max_cut.max_cut_value(x, w)) # # colors = ['r' if max_cut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n)] # nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, pos=pos) # End eigensolver solution ##### # run quantum algorithm with shots qubitOp, offset = max_cut.get_max_cut_qubitops(w) algo_input = EnergyInput(qubitOp) seed = 10598 spsa = SPSA(max_trials=300) ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear') vqe = VQE(qubitOp, ry, spsa, 'grouped_paulis') backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend=backend, shots=1024, seed=seed) result = vqe.run(quantum_instance) """declarative approach, update the param from the previous cell. params['algorithm']['operator_mode'] = 'grouped_paulis' params['backend']['name'] = 'qasm_simulator' params['backend']['shots'] = 1024 result = run_algorithm(params, algo_input) """ x = max_cut.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('time:', result['eval_time']) print('maxcut objective:', result['energy'] + offset) print('solution:', max_cut.get_graph_solution(x)) print('solution objective:', max_cut.max_cut_value(x, w)) plot_histogram(result['eigvecs'][0]) colors = [ 'r' if max_cut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n) ] nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, pos=pos)
seed_simulator=seed, seed_transpiler=seed) result = vqe.run(quantum_instance) """declarative approach, update the param from the previous cell. params['backend']['provider'] = 'qiskit.BasicAer' params['backend']['name'] = 'qasm_simulator' params['backend']['shots'] = 1024 result = run_algorithm(params, algo_input) """ x = max_cut.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('time:', result['eval_time']) print('max-cut objective:', result['energy'] + offset) print('solution:', max_cut.get_graph_solution(x)) print('solution objective:', max_cut.max_cut_value(x, w)) plot_histogram(result['eigvecs'][0]) colors = [ 'r' if max_cut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n) ] pos = nx.spring_layout(G) nx.draw(G, pos, with_labels=True, node_color=colors, edge_color='gray', width=7, node_size=500, font_size=8,
def optimize_f(precision, coefs_param, beta): coefs = coefs_param.copy() coefs.append(0) coefs_restr = (1, 1, 1) lista_vars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] mdl = Model() variables = [] for num_var in range(len(coefs)): tmp = { i: mdl.binary_var(name=(lista_vars[num_var] + '_{0}').format(i)) for i in range(precision) } variables.append(tmp) # x = {i: mdl.binary_var(name='x_{0}'.format(i)) for i in range(precision)} # y = {i: mdl.binary_var(name='y_{0}'.format(i)) for i in range(precision)} # z = {i: mdl.binary_var(name='z_{0}'.format(i)) for i in range(precision)} #print(variables) # Object function # my_func = mdl.sum(coefs[0]*(2**i)*x[i]+coefs[1]*(2**i)*y[i]+(2**i)*coefs[2]*z[i] for i in range(precision)) # my_func = mdl.sum(coefs[j]*(2**i)*vars[j][i] for j in range(len(coefs)) for i in range(precision)) my_func = mdl.sum(coefs[j] * (2**i) * variables[j][i] for j in range(len(coefs)) for i in range(precision)) # (x[i] for i in range(precision)), (y[i] for i in range(precision)), (z[i] for i in range(precision) # tmp = {0:{'var':x,'coef':coefs_restr[0]}, # 1:{'var':y,'coef':coefs_restr[1]}, # 2:{'var':z,'coef':coefs_restr[2]}} mdl.maximize(my_func) inverted_beta = dameInversoBinario(beta, precision, len(coefs)) # mdl.add_constraint(mdl.sum( tmp[v]['var'][i]*(2**i)*tmp[v]['coef'] for v in range(len(coefs)) for i in range(precision)) == beta) # mdl.add_constraint(mdl.sum( x[0] + x[1]*(2) + x[2]*(4) + y[0] + y[1]*(2) + y[2]*(4) + z[0] + z[1]*(2) + z[2]*(4) ) == inverted_beta) # mdl.add_constraint(mdl.sum( variables[0][0] + variables[0][1]*(2) + variables[0][2]*(4) + variables[1][0] + variables[1][1] # *(2) + variables[1][2]*(4) + variables[2][0] + variables[2][1]*(2) + variables[2][2]*(4) ) == inverted_beta) mdl.add_constraint( mdl.sum(variables[v][i] * 2**i for v in range(len(coefs)) for i in range(precision)) == inverted_beta) # mdl.add_constraint(mdl.sum( -x[0] - x[1]*(2) - x[2]*(4) - y[0] - y[1]*(2) - y[2]*(4) - z[0] - z[1]*(2) - z[2]*(4) ) == 6) # mdl.add_constraint(mdl.sum( -1*tmp[v]['var'][i]*(2**i)*tmp[v]['coef'] for v in range(len(coefs)) for i in range(precision)) == -beta) qubitOp_docplex, offset_docplex = docplex.get_qubitops(mdl) #print(qubitOp_docplex) # algo_input = EnergyInput(qubitOp_docplex) # print(algo_input.) # ee = VQE(qubitOp_docplex) # ee.run() ee = ExactEigensolver(qubitOp_docplex, k=1) result_ee = ee.run() x_ee = max_cut.sample_most_likely(result_ee['eigvecs'][0]) print('solution:', max_cut.get_graph_solution(x_ee)) solucion_ee = max_cut.get_graph_solution(x_ee) return (solucion_ee, None) """ algorithm_cfg = { 'name': 'ExactEigensolver', } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params,algo_input) """ # x = max_cut.sample_most_likely(result['eigvecs'][0]) # print('energy:', result['energy']) # print('max-cut objective:', result['energy'] + offset_docplex) # print('solution:', max_cut.get_graph_solution(x)) # print('solution objective:', max_cut.max_cut_value(x, w)) seed = 10598 # change optimizer(spsa), change ry (riyc) spsa = SPSA(max_trials=300) ry = RY(qubitOp_docplex.num_qubits, depth=6, entanglement='linear') vqe = VQE(qubitOp_docplex, ry, spsa, 'matrix') backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, seed=seed, seed_transpiler=seed) result = vqe.run(quantum_instance) x = max_cut.sample_most_likely(result['eigvecs'][0]) print('solution:', max_cut.get_graph_solution(x)) return (solucion_ee, max_cut.get_graph_solution(x))