def test_qaoa(self, w, prob, m, solutions, convert_to_matrix_op): """ 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_operator(w) qubit_op = qubit_op.to_opflow() if convert_to_matrix_op: qubit_op = qubit_op.to_matrix_op() 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.eigenstate) graph_solution = max_cut.get_graph_solution(x) self.log.debug('energy: %s', result.eigenvalue.real) self.log.debug('time: %s', result.optimizer_time) self.log.debug('maxcut objective: %s', result.eigenvalue.real + 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 run_simulation(self, backend): seed = int(os.environ.get("SEED", "40598")) n = int(os.environ.get("N", "4")) # # Random 3-regular graph with 12 nodes # graph = nx.random_regular_graph(3, n, seed=seed) for e in graph.edges(): graph[e[0]][e[1]]["weight"] = 1.0 # Compute the weight matrix from the graph w = np.zeros([n, n]) for i in range(n): for j in range(n): temp = graph.get_edge_data(i, j, default=0) if temp != 0: w[i, j] = temp["weight"] # Create an Ising Hamiltonian with docplex. mdl = Model(name="max_cut") mdl.node_vars = mdl.binary_var_list(list(range(n)), name="node") maxcut_func = mdl.sum(w[i, j] * mdl.node_vars[i] * (1 - mdl.node_vars[j]) for i in range(n) for j in range(n)) mdl.maximize(maxcut_func) qubit_op, offset = docplex.get_operator(mdl) aqua_globals.random_seed = seed # Run quantum algorithm QAOA on qasm simulator spsa = SPSA(max_trials=250) qaoa = QAOA(qubit_op, spsa, p=5, max_evals_grouped=4) quantum_instance = QuantumInstance( backend, shots=1024, seed_simulator=seed, seed_transpiler=seed, optimization_level=0, ) result = qaoa.run(quantum_instance) x = sample_most_likely(result["eigvecs"][0]) result["solution"] = max_cut.get_graph_solution(x) result["solution_objective"] = max_cut.max_cut_value(x, w) result["maxcut_objective"] = result["energy"] + offset """ 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)) """ return result
def test_cplex_ising(self): """ cplex ising test """ try: algo = ClassicalCPLEX(self.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 NameError as ex: self.skipTest(str(ex))
def test_readme_sample(self): """ readme sample test """ # pylint: disable=import-outside-toplevel,redefined-builtin def print(*args): """ overloads print to log values """ if args: self.log.debug(args[0], *args[1:]) # --- Exact copy of sample code ---------------------------------------- import networkx as nx import numpy as np from docplex.mp.model import Model from qiskit import BasicAer from qiskit.aqua import aqua_globals, QuantumInstance from qiskit.aqua.algorithms import QAOA from qiskit.aqua.components.optimizers import SPSA from qiskit.optimization.applications.ising import docplex, max_cut from qiskit.optimization.applications.ising.common import sample_most_likely # Generate a graph of 4 nodes n = 4 graph = nx.Graph() graph.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)] graph.add_weighted_edges_from(elist) # Compute the weight matrix from the graph w = np.zeros([n, n]) for i in range(n): for j in range(n): temp = graph.get_edge_data(i, j, default=0) if temp != 0: w[i, j] = temp['weight'] # Create an Ising Hamiltonian with docplex. mdl = Model(name='max_cut') mdl.node_vars = mdl.binary_var_list(list(range(n)), name='node') maxcut_func = mdl.sum(w[i, j] * mdl.node_vars[i] * (1 - mdl.node_vars[j]) for i in range(n) for j in range(n)) mdl.maximize(maxcut_func) qubit_op, offset = docplex.get_operator(mdl) # Run quantum algorithm QAOA on qasm simulator seed = 40598 aqua_globals.random_seed = seed spsa = SPSA(max_trials=250) qaoa = QAOA(qubit_op, spsa, p=5) backend = BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=seed, seed_transpiler=seed) result = qaoa.run(quantum_instance) x = sample_most_likely(result.eigenstate) print('energy:', result.eigenvalue.real) print('time:', result.optimizer_time) print('max-cut objective:', result.eigenvalue.real + offset) print('solution:', max_cut.get_graph_solution(x)) print('solution objective:', max_cut.max_cut_value(x, w)) # ---------------------------------------------------------------------- self.assertListEqual( max_cut.get_graph_solution(x).tolist(), [1, 0, 1, 0]) self.assertAlmostEqual(max_cut.max_cut_value(x, w), 4.0)
pos = nx.spring_layout(G) w = my_graphs.adjacency_matrix(G) print("\nAdjacency matrix\n", w, "\n") # setting p p = 1 # ... QAOA ... # Create an Ising Hamiltonian with docplex. mdl = Model(name='max_cut') mdl.node_vars = mdl.binary_var_list(list(range(n)), name='node') maxcut_func = mdl.sum(w[i, j] * mdl.node_vars[i] * (1 - mdl.node_vars[j]) for i in range(n) for j in range(n)) mdl.maximize(maxcut_func) qubit_op, offset = docplex.get_operator(mdl) # Run quantum algorithm QAOA on qasm simulator optimizer = NELDER_MEAD() qaoa = QAOA(qubit_op, optimizer, p=p) backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1000) result = qaoa.run(quantum_instance) x = sample_most_likely(result.eigenstate) print('energy:', result.eigenvalue.real) print('time:', result.optimizer_time, 's') print('max-cut objective:', result.eigenvalue.real + offset) print('solution:', max_cut.get_graph_solution(x)) print('solution objective:', max_cut.max_cut_value(x, w)) print('angles:', result.optimal_point)
def run_experiment( G, p, optimizer, backend, n_shots=100, #important for running time, max is 8192 print_result=False, skip_qobj_validation=False, noise_model=None, coupling_map=None, basis_gates=None, ): '''Runs (Qiskit) QAOA experiment with the given parameters Inputs - G, graph - p, number of angles - optimizer, classical optimizer - backend - number of shots (n_shots) - Note, this parameter is important for running time but also affects accuracy if too low - ... Returns a dictionary with the following keys - energy - time (in seconds) - iterations - max-cut objective - solution - solution objective - eigenstate distribution - angles ''' n = len(G) # number of nodes w = adjacency_matrix(G) # calculating adjacency matrix from graph # ... QAOA ... # Create an Ising Hamiltonian with docplex. mdl = Model(name='max_cut') mdl.node_vars = mdl.binary_var_list(list(range(n)), name='node') maxcut_func = mdl.sum(w[i, j] * mdl.node_vars[i] * (1 - mdl.node_vars[j]) for i in range(n) for j in range(n)) mdl.maximize(maxcut_func) qubit_op, offset = docplex.get_operator(mdl) # Construct a circuit from the model qaoa = QAOA(qubit_op, optimizer, p=p) quantum_instance = QuantumInstance( backend, shots=n_shots, skip_qobj_validation=skip_qobj_validation, coupling_map=coupling_map, basis_gates=basis_gates, noise_model=noise_model) # Run quantum algorithm QAOA on the backend result = qaoa.run(quantum_instance) x = sample_most_likely(result.eigenstate) # Results energy = result.eigenvalue.real time = result.optimizer_time iterations = result.optimizer_evals objective = result.eigenvalue.real + offset # why offset? solution = max_cut.get_graph_solution(x) solution_objective = max_cut.max_cut_value(x, w) distribution = result.eigenstate angles = result.optimal_point if print_result: print('energy:', energy) print('time:', time, 's') print('max-cut objective:', objective) print('solution:', solution) print('solution objective:', solution_objective) print('angles:', angles) return { 'energy': energy, 'time': time, 'iterations': iterations, 'max-cut objective': objective, 'solution': solution, 'solution objective': solution_objective, 'distribution': distribution, 'angles': angles, 'n_shots': n_shots }