def test_qaoa_qc_mixer_many_parameters(self): """ QAOA test with a mixer as a parameterized circuit with the num of parameters > 1. """ seed = 0 aqua_globals.random_seed = seed optimizer = COBYLA() qubit_op, _ = max_cut.get_operator(W1) qubit_op = qubit_op.to_opflow() num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) for i in range(num_qubits): theta = Parameter('θ' + str(i)) mixer.rx(theta, range(num_qubits)) qaoa = QAOA(qubit_op, optimizer=optimizer, p=2, mixer=mixer) backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed) result = qaoa.run(quantum_instance) x = sample_most_likely(result.eigenstate) print(x) graph_solution = max_cut.get_graph_solution(x) self.assertIn(''.join([str(int(i)) for i in graph_solution]), S1)
def test_tsp(self): """ TSP test """ algo = NumPyMinimumEigensolver(self.qubit_op) result = algo.run() x = sample_most_likely(result.eigenstate) order = tsp.get_tsp_solution(x) np.testing.assert_array_equal(order, [1, 2, 0])
def test_qaoa_qc_mixer(self, w, prob, solutions, convert_to_matrix_op): """ QAOA test with a mixer as a parameterized circuit""" seed = 0 aqua_globals.random_seed = seed self.log.debug( 'Testing %s-step QAOA with MaxCut on graph with ' 'a mixer as a parameterized circuit\n%s', prob, w) backend = BasicAer.get_backend('statevector_simulator') optimizer = COBYLA() qubit_op, _ = max_cut.get_operator(w) qubit_op = qubit_op.to_opflow() if convert_to_matrix_op: qubit_op = qubit_op.to_matrix_op() num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) theta = Parameter('θ') mixer.rx(theta, range(num_qubits)) qaoa = QAOA(qubit_op, optimizer, prob, mixer=mixer) 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.assertIn(''.join([str(int(i)) for i in graph_solution]), solutions)
def test_qaoa_initial_point(self, w, solutions, init_pt): """ Check first parameter value used is initial point as expected """ optimizer = COBYLA() qubit_op, _ = max_cut.get_operator(w) first_pt = [] def cb_callback(eval_count, parameters, mean, std): nonlocal first_pt if eval_count == 1: first_pt = list(parameters) quantum_instance = QuantumInstance( BasicAer.get_backend('statevector_simulator')) qaoa = QAOA(qubit_op, optimizer, initial_point=init_pt, callback=cb_callback, quantum_instance=quantum_instance) result = qaoa.compute_minimum_eigenvalue() x = sample_most_likely(result.eigenstate) graph_solution = max_cut.get_graph_solution(x) if init_pt is None: # If None the preferred initial point of QAOA variational form init_pt = [0.0, 0.0] # i.e. 0,0 should come through as the first point with self.subTest('Initial Point'): self.assertListEqual(init_pt, first_pt) with self.subTest('Solution'): self.assertIn(''.join([str(int(i)) for i in graph_solution]), solutions)
def test_set_packing_vqe(self): """ set packing vqe test """ try: # pylint: disable=import-outside-toplevel from qiskit import Aer except Exception as ex: # pylint: disable=broad-except self.skipTest( "Aer doesn't appear to be installed. Error: '{}'".format( str(ex))) return aqua_globals.random_seed = 50 result = VQE(self.qubit_op, RY(self.qubit_op.num_qubits, depth=5, entanglement='linear'), SPSA(max_trials=200), max_evals_grouped=2).run( QuantumInstance( Aer.get_backend('qasm_simulator'), seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed)) x = sample_most_likely(result['eigvecs'][0]) ising_sol = set_packing.get_solution(x) oracle = self._brute_force() self.assertEqual(np.count_nonzero(ising_sol), oracle)
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 test_set_packing_vqe(self): """ set packing vqe test """ try: # pylint: disable=import-outside-toplevel from qiskit import Aer except Exception as ex: # pylint: disable=broad-except self.skipTest( "Aer doesn't appear to be installed. Error: '{}'".format( str(ex))) return wavefunction = TwoLocal(rotation_blocks='ry', entanglement_blocks='cz', reps=3, entanglement='linear') result = VQE(self.qubit_op, wavefunction, SPSA(maxiter=200), max_evals_grouped=2).run( QuantumInstance( Aer.get_backend('qasm_simulator'), seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed)) x = sample_most_likely(result.eigenstate) ising_sol = set_packing.get_solution(x) oracle = self._brute_force() self.assertEqual(np.count_nonzero(ising_sol), oracle)
def test_partition(self): """ Partition test """ algo = NumPyMinimumEigensolver(self.qubit_op, aux_operators=[]) result = algo.run() x = sample_most_likely(result.eigenstate) if x[0] != 0: x = np.logical_not(x) * 1 np.testing.assert_array_equal(x, [0, 1, 0])
def test_vertex_cover(self): """ Vertex Cover test """ algo = NumPyMinimumEigensolver(self.qubit_op, aux_operators=[]) result = algo.run() x = sample_most_likely(result.eigenstate) sol = vertex_cover.get_graph_solution(x) np.testing.assert_array_equal(sol, [0, 0, 1]) oracle = self._brute_force() self.assertEqual(np.count_nonzero(sol), oracle)
def test_portfolio(self): """ portfolio test """ algo = NumPyMinimumEigensolver(self.qubit_op) result = algo.run() selection = sample_most_likely(result.eigenstate) value = portfolio.portfolio_value(selection, self.muu, self.sigma, self.risk, self.budget, self.penalty) np.testing.assert_array_equal(selection, [0, 1, 1, 0]) self.assertAlmostEqual(value, -0.00679917)
def test_set_packing(self): """ set packing test """ algo = NumPyMinimumEigensolver(self.qubit_op, aux_operators=[]) result = algo.run() x = sample_most_likely(result.eigenstate) ising_sol = set_packing.get_solution(x) np.testing.assert_array_equal(ising_sol, [0, 1, 1]) oracle = self._brute_force() self.assertEqual(np.count_nonzero(ising_sol), oracle)
def test_tsp(self): """ TSP test """ algo = NumPyMinimumEigensolver(self.qubit_op) result = algo.run() x = sample_most_likely(result.eigenstate) # print(self.qubit_op.to_opflow().eval(result.eigenstate).adjoint().eval(result.eigenstate)) order = tsp.get_tsp_solution(x) np.testing.assert_equal(tsp.tsp_value(order, self.ins.w), tsp.tsp_value([1, 2, 0], self.ins.w))
def test_stable_set(self): """ Stable set test """ algo = NumPyMinimumEigensolver(self.qubit_op, aux_operators=[]) result = algo.run() x = sample_most_likely(result.eigenstate) self.assertAlmostEqual(result.eigenvalue.real, -29.5) self.assertAlmostEqual(result.eigenvalue.real + self.offset, -25.0) ising_sol = stable_set.get_graph_solution(x) np.testing.assert_array_equal(ising_sol, [0, 0, 1, 1, 1]) self.assertEqual(stable_set.stable_set_value(x, self.w), (3.0, False))
def test_graph_partition(self): """ Graph Partition test """ algo = NumPyMinimumEigensolver(self.qubit_op, aux_operators=[]) result = algo.run() x = sample_most_likely(result.eigenstate) # check against the oracle ising_sol = graph_partition.get_graph_solution(x) np.testing.assert_array_equal(ising_sol, [0, 1, 0, 1]) oracle = self._brute_force() self.assertEqual(graph_partition.objective_value(x, self.w), oracle)
def test_clique(self): """ Clique test """ algo = NumPyMinimumEigensolver(self.qubit_op, aux_operators=[]) result = algo.run() x = sample_most_likely(result.eigenstate) ising_sol = clique.get_graph_solution(x) np.testing.assert_array_equal(ising_sol, [1, 1, 1, 1, 1]) oracle = self._brute_force() self.assertEqual(clique.satisfy_or_not(ising_sol, self.w, self.k), oracle)
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_exact_cover(self): """ Exact Cover test """ algo = NumPyMinimumEigensolver(self.qubit_op, aux_operators=[]) result = algo.run() x = sample_most_likely(result.eigenstate) ising_sol = exact_cover.get_solution(x) np.testing.assert_array_equal(ising_sol, [0, 1, 1, 0]) oracle = self._brute_force() self.assertEqual( exact_cover.check_solution_satisfiability(ising_sol, self.list_of_subsets), oracle)
def _run_knapsack(values, weights, max_weight): qubit_op, _ = knapsack.get_operator(values, weights, max_weight) algo = NumPyMinimumEigensolver(qubit_op) result = algo.run() x = sample_most_likely(result.eigenstate) solution = knapsack.get_solution(x, values) value, weight = knapsack.knapsack_value_weight(solution, values, weights) return solution, value, weight
def test_partition_vqe(self): """ Partition VQE test """ aqua_globals.random_seed = 100 result = VQE(self.qubit_op, RY(self.qubit_op.num_qubits, depth=5, entanglement='linear'), SPSA(max_trials=200), max_evals_grouped=2).run( QuantumInstance(BasicAer.get_backend('qasm_simulator'), seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed)) x = sample_most_likely(result['eigvecs'][0]) self.assertNotEqual(x[0], x[1]) self.assertNotEqual(x[2], x[1]) # hardcoded oracle
def test_stable_set_vqe(self): """ VQE Stable set test """ result = VQE(self.qubit_op, EfficientSU2( reps=3, entanglement='linear'), L_BFGS_B(maxfun=6000)).run( QuantumInstance(BasicAer.get_backend('statevector_simulator'), seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed)) x = sample_most_likely(result.eigenstate) self.assertAlmostEqual(result.eigenvalue, -39.5) self.assertAlmostEqual(result.eigenvalue + self.offset, -38.0) ising_sol = stable_set.get_graph_solution(x) np.testing.assert_array_equal(ising_sol, [1, 1, 0, 1, 1]) self.assertEqual(stable_set.stable_set_value(x, self.w), (4.0, False))
def test_change_operator_size(self): """ QAOA change operator size test """ aqua_globals.random_seed = 0 qubit_op, _ = max_cut.get_operator( np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]])) qaoa = QAOA(qubit_op.to_opflow(), COBYLA(), 1) quantum_instance = QuantumInstance( BasicAer.get_backend('statevector_simulator'), seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed) result = qaoa.run(quantum_instance) x = sample_most_likely(result.eigenstate) graph_solution = max_cut.get_graph_solution(x) with self.subTest(msg='QAOA 4x4'): self.assertIn(''.join([str(int(i)) for i in graph_solution]), {'0101', '1010'}) try: qubit_op, _ = max_cut.get_operator( np.array([ [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], ])) qaoa.operator = qubit_op.to_opflow() except Exception as ex: # pylint: disable=broad-except self.fail("Failed to change operator. Error: '{}'".format(str(ex))) return result = qaoa.run() x = sample_most_likely(result.eigenstate) graph_solution = max_cut.get_graph_solution(x) with self.subTest(msg='QAOA 6x6'): self.assertIn(''.join([str(int(i)) for i in graph_solution]), {'010101', '101010'})
def test_stable_set_vqe(self): """ VQE Stable set test """ result = VQE(self.qubit_op, RYRZ(self.qubit_op.num_qubits, depth=3, entanglement='linear'), L_BFGS_B(maxfun=6000)).run( QuantumInstance(BasicAer.get_backend('statevector_simulator'), seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed)) x = sample_most_likely(result['eigvecs'][0]) self.assertAlmostEqual(result['energy'], -29.5) self.assertAlmostEqual(result['energy'] + self.offset, -25.0) ising_sol = stable_set.get_graph_solution(x) np.testing.assert_array_equal(ising_sol, [0, 0, 1, 1, 1]) self.assertEqual(stable_set.stable_set_value(x, self.w), (3.0, False))
def test_portfolio_qaoa(self): """ portfolio test with QAOA """ qaoa = QAOA(self.qubit_op, COBYLA(maxiter=500), initial_point=[0., 0.]) backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend=backend, seed_simulator=self.seed, seed_transpiler=self.seed) result = qaoa.run(quantum_instance) selection = sample_most_likely(result.eigenstate) value = portfolio.portfolio_value(selection, self.muu, self.sigma, self.risk, self.budget, self.penalty) np.testing.assert_array_equal(selection, [0, 1, 1, 0]) self.assertAlmostEqual(value, -0.00679917)
def test_vertex_cover_vqe(self): """ Vertex Cover VQE test """ aqua_globals.random_seed = self.seed result = VQE(self.qubit_op, EfficientSU2(reps=3), SPSA(max_trials=200), max_evals_grouped=2).run( QuantumInstance( BasicAer.get_backend('qasm_simulator'), seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed)) x = sample_most_likely(result.eigenstate) sol = vertex_cover.get_graph_solution(x) oracle = self._brute_force() self.assertEqual(np.count_nonzero(sol), oracle)
def test_clique_vqe(self): """ VQE Clique test """ aqua_globals.random_seed = 10598 result = VQE(self.qubit_op, RealAmplitudes(reps=5, entanglement='linear'), COBYLA(), max_evals_grouped=2).run( QuantumInstance( BasicAer.get_backend('statevector_simulator'), seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed)) x = sample_most_likely(result.eigenstate) ising_sol = clique.get_graph_solution(x) np.testing.assert_array_equal(ising_sol, [1, 1, 1, 1, 1]) oracle = self._brute_force() self.assertEqual(clique.satisfy_or_not(ising_sol, self.w, self.k), oracle)
def test_exact_cover_vqe(self): """ Exact Cover VQE test """ aqua_globals.random_seed = 10598 result = VQE(self.qubit_op, RYRZ(self.qubit_op.num_qubits, depth=5), COBYLA(), max_evals_grouped=2).run( QuantumInstance( BasicAer.get_backend('statevector_simulator'), seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed)) x = sample_most_likely(result.eigenstate) ising_sol = exact_cover.get_solution(x) oracle = self._brute_force() self.assertEqual( exact_cover.check_solution_satisfiability(ising_sol, self.list_of_subsets), oracle)
def calculate(self, G, cost_matrix, starting_node = 0): # Create nodes array for the TSP solver in Qiskit coords = [] for node in G.nodes: coords.append(G.nodes[node]['pos']) tsp_instance = tsp.TspData(name = "TSP", dim = len(G.nodes), coord = coords, w = cost_matrix) qubitOp, offset = tsp.get_operator(tsp_instance) print("Qubits needed: ", qubitOp.num_qubits) #print(qubitOp.print_details()) #backend = Aer.get_backend('statevector_simulator') backend = Aer.get_backend('qasm_simulator') # Use real backend #IBMQ.load_account() #provider = IBMQ.get_provider('ibm-q') #from qiskit.providers.ibmq import least_busy #backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits > qubitOp.num_qubits and not x.configuration().simulator )) #print(backend.name()) quantum_instance = QuantumInstance(backend) optimizer = SPSA(maxiter=400) #optimizer = COBYLA(maxiter=200, rhobeg=0.3, tol=0.1, disp=True) ry = TwoLocal(qubitOp.num_qubits, 'ry', 'cz', reps=4, entanglement='full') ra = RealAmplitudes(qubitOp.num_qubits, reps=2) vqe = VQE(operator=qubitOp, var_form=ry, optimizer=optimizer, quantum_instance=quantum_instance) result = vqe.run(quantum_instance) x = sample_most_likely(result.eigenstate) if(tsp.tsp_feasible(x)): z = tsp.get_tsp_solution(x) print('solution:', z) return z else: print('no solution:', x) return []
def test_graph_partition_vqe(self): """ Graph Partition VQE test """ aqua_globals.random_seed = 10213 wavefunction = RealAmplitudes(self.qubit_op.num_qubits, insert_barriers=True, reps=5, entanglement='linear') result = VQE(self.qubit_op, wavefunction, SPSA(maxiter=300), max_evals_grouped=2).run( QuantumInstance(BasicAer.get_backend('statevector_simulator'), seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed)) x = sample_most_likely(result.eigenstate) # check against the oracle ising_sol = graph_partition.get_graph_solution(x) self.assertEqual(graph_partition.objective_value(np.array([0, 1, 0, 1]), self.w), graph_partition.objective_value(ising_sol, self.w)) oracle = self._brute_force() self.assertEqual(graph_partition.objective_value(x, self.w), oracle)
def test_graph_partition_vqe(self): """ Graph Partition VQE test """ aqua_globals.random_seed = 10598 result = VQE(self.qubit_op, RY(self.qubit_op.num_qubits, depth=5, entanglement='linear'), SPSA(max_trials=300), max_evals_grouped=2).run( QuantumInstance( BasicAer.get_backend('statevector_simulator'), seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed)) x = sample_most_likely(result['eigvecs'][0]) # check against the oracle ising_sol = graph_partition.get_graph_solution(x) np.testing.assert_array_equal(ising_sol, [0, 1, 0, 1]) oracle = self._brute_force() self.assertEqual(graph_partition.objective_value(x, self.w), oracle)
def calculate(self, G, cost_matrix, starting_node = 0): # Create nodes array for the TSP solver in Qiskit G.nodes[0]['pos'] coords = [] for node in G.nodes: coords.append(G.nodes[0]['pos']) tsp_instance = tsp.TspData(name = "TSP", dim = len(G.nodes), coord = coords, w = cost_matrix) qubitOp, offset = tsp.get_operator(tsp_instance) ee = NumPyEigensolver(qubitOp, k=1) result = ee.run() x = sample_most_likely(result['eigenstates'][0]) return tsp.get_tsp_solution(x)