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 get_qubit_op(num_qubits, seed=23412341234): G = nx.Graph() # """ HAVE DATA -- VIGO n = num_qubits SEED = seed np.random.seed(SEED % (2 ** 31 - 1)) G = nx.dense_gnm_random_graph(n, n ** 2, seed=SEED) for (u, v, w) in G.edges(data=True): w['weight'] = np.random.rand() * 0.5 # 0.1 np.random.seed(int(time.time())) 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) qubitOp, offset = max_cut.get_max_cut_qubitops(w) algo_input = EnergyInput(qubitOp) pos = nx.spring_layout(G) exact = ExactEigensolver(qubitOp).run() exact_energy = exact['energy'] return qubitOp, exact_energy
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 set_adj_matrix(self, adj_matrix): maxcut_op, self.maxcut_shift = max_cut.get_max_cut_qubitops(adj_matrix) # print("maxcut_op: ", maxcut_op, ", maxcut_shift: ", maxcut_shift) # TODO: Find different approach of calculating and retrieving diagonal maxcut_op._paulis_to_matrix() self.eigenvalues = maxcut_op._dia_matrix self.calc_expectation_value() self.draw_expectation_grid()
def setUp(self): super().setUp() np.random.seed(8123179) self.w = max_cut.random_graph(4, edge_prob=0.5, weight_range=10) self.qubit_op, self.offset = max_cut.get_max_cut_qubitops(self.w) self.algo_input = EnergyInput(self.qubit_op)
# tuple is (i,j,weight) where (i,j) is the edge G.add_weighted_edges_from(elist) print(list(nx.connected_components(G))) print(list(G.edges)) square_ring = list(G.edges) print(square_ring) 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) 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, 'matrix') backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, seed=seed, seed_transpiler=seed) result = vqe.run(quantum_instance) """declarative approach algorithm_cfg = {
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)