def test_learning_rate_perturbation_as_iterators(self): """Test the learning rate and perturbation can be callables returning iterators.""" def get_learning_rate(): def learning_rate(): x = 0.99 while True: x *= x yield x return learning_rate def get_perturbation(): def perturbation(): x = 0.99 while True: x *= x yield max(x, 0.01) return perturbation def objective(x): return (np.linalg.norm(x) - 2)**2 spsa = SPSA(learning_rate=get_learning_rate(), perturbation=get_perturbation()) result, _, _ = spsa.optimize(1, objective, initial_point=np.array([0.5, 0.5])) self.assertAlmostEqual(np.linalg.norm(result), 2, places=2)
def test_callback(self): """Test using the callback.""" def objective(x): return (np.linalg.norm(x) - 2)**2 history = { "nfevs": [], "points": [], "fvals": [], "updates": [], "accepted": [] } def callback(nfev, point, fval, update, accepted): history["nfevs"].append(nfev) history["points"].append(point) history["fvals"].append(fval) history["updates"].append(update) history["accepted"].append(accepted) maxiter = 10 spsa = SPSA(maxiter=maxiter, learning_rate=0.01, perturbation=0.01, callback=callback) _ = spsa.optimize(1, objective, initial_point=np.array([0.5, 0.5])) expected_types = [int, np.ndarray, float, float, bool] for i, (key, values) in enumerate(history.items()): self.assertTrue( all(isinstance(value, expected_types[i]) for value in values)) self.assertEqual(len(history[key]), maxiter)
def test_pauli_two_design(self): """Test SPSA on the Pauli two-design example.""" circuit = PauliTwoDesign(3, reps=3, seed=2) parameters = list(circuit.parameters) obs = Z ^ Z ^ I expr = ~StateFn(obs) @ StateFn(circuit) initial_point = np.array([ 0.1822308, -0.27254251, 0.83684425, 0.86153976, -0.7111668, 0.82766631, 0.97867993, 0.46136964, 2.27079901, 0.13382699, 0.29589915, 0.64883193 ]) def objective(x): return expr.bind_parameters(dict(zip(parameters, x))).eval().real spsa = SPSA(maxiter=100, blocking=True, allowed_increase=0, learning_rate=0.1, perturbation=0.1) result = spsa.optimize(circuit.num_parameters, objective, initial_point=initial_point) self.assertLess(result[1], -0.95) # final loss self.assertEqual(result[2], 301) # function evaluations
def test_recalibrate_at_optimize(self): """Test SPSA calibrates anew upon each optimization run, if no autocalibration is set.""" def objective(x): return -(x**2) spsa = SPSA(maxiter=1) _ = spsa.optimize(1, objective, initial_point=np.array([0.5])) self.assertIsNone(spsa.learning_rate) self.assertIsNone(spsa.perturbation)
def test_learning_rate_perturbation_as_arrays(self): """Test the learning rate and perturbation can be arrays.""" learning_rate = np.linspace(1, 0, num=100, endpoint=False)**2 perturbation = 0.01 * np.ones(100) def objective(x): return (np.linalg.norm(x) - 2)**2 spsa = SPSA(learning_rate=learning_rate, perturbation=perturbation) result = spsa.minimize(objective, x0=np.array([0.5, 0.5])) self.assertAlmostEqual(np.linalg.norm(result.x), 2, places=2)
def test_samples_vqe(self, simulator): """Test samples for VQE""" # test minimize algorithm_globals.random_seed = 1 quantum_instance = self.sv_simulator if simulator == "sv" else self.qasm_simulator opt_sol = -2 success = OptimizationResultStatus.SUCCESS optimizer = SPSA(maxiter=100) ry_ansatz = TwoLocal(5, "ry", "cz", reps=3, entanglement="full") vqe_mes = VQE(ry_ansatz, optimizer=optimizer, quantum_instance=quantum_instance) vqe = MinimumEigenOptimizer(vqe_mes) results = vqe.solve(self.op_ordering) self.assertEqual(results.fval, opt_sol) np.testing.assert_array_almost_equal(results.x, [0, 1]) self.assertEqual(results.status, success) results.raw_samples.sort(key=lambda x: x.probability, reverse=True) np.testing.assert_array_almost_equal(results.x, results.raw_samples[0].x) self.assertAlmostEqual(sum(s.probability for s in results.samples), 1, delta=1e-5) self.assertAlmostEqual(sum(s.probability for s in results.raw_samples), 1, delta=1e-5) self.assertAlmostEqual(min(s.fval for s in results.samples), -2) self.assertAlmostEqual(min(s.fval for s in results.samples if s.status == success), opt_sol) self.assertAlmostEqual(min(s.fval for s in results.raw_samples), opt_sol) for sample in results.raw_samples: self.assertEqual(sample.status, success) np.testing.assert_array_almost_equal(results.samples[0].x, [0, 1]) self.assertAlmostEqual(results.samples[0].fval, opt_sol) self.assertEqual(results.samples[0].status, success) np.testing.assert_array_almost_equal(results.raw_samples[0].x, [0, 1]) self.assertAlmostEqual(results.raw_samples[0].fval, opt_sol) self.assertEqual(results.raw_samples[0].status, success)
def __init__( self, method: str, optimizer_kwargs: Optional[Dict] = None, recorder: RecorderFactory = _recorder, ): """ Args: method: specifies optimizer to be used. Currently supports "ADAM", "AMSGRAD" and "SPSA". optimizer_kwargs: dictionary with additional optimizer_kwargs for the optimizer. recorder: recorder object which defines how to store the optimization history. """ super().__init__(recorder=recorder) self.method = method if optimizer_kwargs is None: self.optimizer_kwargs = {} else: self.optimizer_kwargs = optimizer_kwargs if self.method == "SPSA": self.optimizer = SPSA(**self.optimizer_kwargs) elif self.method == "ADAM" or self.method == "AMSGRAD": if self.method == "AMSGRAD": self.optimizer_kwargs["amsgrad"] = True self.optimizer = ADAM(**self.optimizer_kwargs)
def get_standard_program(self, use_deprecated=False): """Get a standard VQEClient and operator to find the ground state of.""" circuit = RealAmplitudes(3) operator = Z ^ I ^ Z initial_point = np.random.random(circuit.num_parameters) backend = QasmSimulatorPy() if use_deprecated: vqe_cls = VQEProgram provider = FakeRuntimeProvider(use_deprecated=True) warnings.filterwarnings("ignore", category=DeprecationWarning) else: provider = FakeRuntimeProvider(use_deprecated=False) vqe_cls = VQEClient vqe = vqe_cls( ansatz=circuit, optimizer=SPSA(), initial_point=initial_point, backend=backend, provider=provider, ) if use_deprecated: warnings.filterwarnings("always", category=DeprecationWarning) return vqe, operator
def __init__( self, quantum_kernel: QuantumKernel, loss: Optional[Union[str, KernelLoss]] = None, optimizer: Optional[Optimizer] = None, initial_point: Optional[Sequence[float]] = None, ): """ Args: quantum_kernel: QuantumKernel to be trained loss (str or KernelLoss): Loss functions available via string: {'svc_loss': SVCLoss()}. If a string is passed as the loss function, then the underlying KernelLoss object will exhibit default behavior. optimizer: An instance of ``Optimizer`` to be used in training. Since no analytical gradient is defined for kernel loss functions, gradient-based optimizers are not recommended for training kernels. initial_point: Initial point from which the optimizer will begin. Raises: ValueError: unknown loss function """ # Class fields self._quantum_kernel = quantum_kernel self._initial_point = initial_point self._optimizer = optimizer or SPSA() # Loss setter self._set_loss(loss)
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') q_i = QuantumInstance(Aer.get_backend('qasm_simulator'), seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed) result = VQE(wavefunction, SPSA(maxiter=200), max_evals_grouped=2, quantum_instance=q_i).compute_minimum_eigenvalue( operator=self.qubit_op) 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_aux_operator_std_dev(self): """Test actuall standard deviation of aux operators in non-zero case.""" wavefunction = self.ry_wavefunction vqe = VQE( ansatz=wavefunction, optimizer=SPSA(maxiter=300, last_avg=5), quantum_instance=self.qasm_simulator, ) # Go again with two auxiliary operators aux_op1 = PauliSumOp.from_list([("II", 2.0)]) aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) aux_ops = [aux_op1, aux_op2, None, 0] result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) self.assertAlmostEqual(result.eigenvalue.real, -1.8691994, places=6) self.assertEqual(len(result.aux_operator_eigenvalues), 4) # expectation values self.assertAlmostEqual(result.aux_operator_eigenvalues[0][0], 2, places=6) self.assertAlmostEqual(result.aux_operator_eigenvalues[1][0], 0.0019531, places=6) self.assertEqual(result.aux_operator_eigenvalues[2][0], 0.0) self.assertEqual(result.aux_operator_eigenvalues[3][0], 0.0) # standard deviations self.assertAlmostEqual(result.aux_operator_eigenvalues[0][1], 0.0) self.assertAlmostEqual(result.aux_operator_eigenvalues[1][1], 0.0214711) self.assertAlmostEqual(result.aux_operator_eigenvalues[2][1], 0.0) self.assertAlmostEqual(result.aux_operator_eigenvalues[3][1], 0.0)
def test_uccsd_hf_aer_qasm(self): """ uccsd hf test with Aer qasm_simulator. """ try: # pylint: disable=import-outside-toplevel from qiskit import Aer backend = Aer.get_backend('qasm_simulator') except ImportError as ex: # pylint: disable=broad-except self.skipTest( "Aer doesn't appear to be installed. Error: '{}'".format( str(ex))) return ansatz = self._prepare_uccsd_hf(self.qubit_converter) optimizer = SPSA(maxiter=200, last_avg=5) solver = VQE(ansatz=ansatz, optimizer=optimizer, expectation=PauliExpectation(), quantum_instance=QuantumInstance( backend=backend, seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed)) gsc = GroundStateEigensolver(self.qubit_converter, solver) result = gsc.solve(self.electronic_structure_problem) self.assertAlmostEqual(result.total_energies[0], -1.138, places=2)
def test_with_aer_qasm(self): """Test VQE with Aer's qasm_simulator.""" 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 backend = Aer.get_backend('qasm_simulator') optimizer = SPSA(maxiter=200, last_avg=5) wavefunction = self.ry_wavefunction vqe = VQE(self.h2_op, wavefunction, optimizer, expectation=PauliExpectation()) quantum_instance = QuantumInstance( backend, seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed) result = vqe.run(quantum_instance) self.assertAlmostEqual(result.eigenvalue.real, -1.86305, places=2)
def test_spsa_custom_iterators(self): """Test serialization works with custom iterators for learning rate and perturbation.""" rate = 0.99 def powerlaw(): n = 0 while True: yield rate**n n += 1 def steps(): n = 1 divide_after = 20 epsilon = 0.5 while True: yield epsilon n += 1 if n % divide_after == 0: epsilon /= 2 learning_rate = powerlaw() expected_learning_rate = np.array( [next(learning_rate) for _ in range(200)]) perturbation = steps() expected_perturbation = np.array( [next(perturbation) for _ in range(200)]) spsa = SPSA(maxiter=200, learning_rate=powerlaw, perturbation=steps) settings = spsa.settings self.assertTrue( np.allclose(settings["learning_rate"], expected_learning_rate)) self.assertTrue( np.allclose(settings["perturbation"], expected_perturbation))
def test_with_two_qubit_reduction(self): """Test the VQE using TwoQubitReduction.""" qubit_op = PauliSumOp.from_list([ ("IIII", -0.8105479805373266), ("IIIZ", 0.17218393261915552), ("IIZZ", -0.22575349222402472), ("IZZI", 0.1721839326191556), ("ZZII", -0.22575349222402466), ("IIZI", 0.1209126326177663), ("IZZZ", 0.16892753870087912), ("IXZX", -0.045232799946057854), ("ZXIX", 0.045232799946057854), ("IXIX", 0.045232799946057854), ("ZXZX", -0.045232799946057854), ("ZZIZ", 0.16614543256382414), ("IZIZ", 0.16614543256382414), ("ZZZZ", 0.17464343068300453), ("ZIZI", 0.1209126326177663), ]) tapered_qubit_op = TwoQubitReduction(num_particles=2).convert(qubit_op) for simulator in [self.qasm_simulator, self.statevector_simulator]: with self.subTest(f"Test for {simulator}."): vqe = VQE( self.ry_wavefunction, SPSA(maxiter=300, last_avg=5), quantum_instance=simulator, ) result = vqe.compute_minimum_eigenvalue(tapered_qubit_op) energy = -1.868 if simulator == self.qasm_simulator else self.h2_energy self.assertAlmostEqual(result.eigenvalue.real, energy, places=2)
def test_with_aer_qasm(self): """Test VQE with Aer's qasm_simulator.""" try: from qiskit.providers.aer import Aer except Exception as ex: # pylint: disable=broad-except self.skipTest( "Aer doesn't appear to be installed. Error: '{}'".format( str(ex))) return backend = Aer.get_backend('qasm_simulator') optimizer = SPSA(maxiter=200, last_avg=5) wavefunction = self.ry_wavefunction quantum_instance = QuantumInstance( backend, seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed) vqe = VQE(ansatz=wavefunction, optimizer=optimizer, expectation=PauliExpectation(), quantum_instance=quantum_instance) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, -1.86305, places=2)
def test_uccsd_hf_aer_qasm_snapshot(self): """uccsd hf test with Aer qasm simulator snapshot.""" try: # pylint: disable=import-outside-toplevel from qiskit import Aer backend = Aer.get_backend("aer_simulator") except ImportError as ex: # pylint: disable=broad-except self.skipTest(f"Aer doesn't appear to be installed. Error: '{str(ex)}'") return ansatz = self._prepare_uccsd_hf(self.qubit_converter) optimizer = SPSA(maxiter=200, last_avg=5) solver = VQE( ansatz=ansatz, optimizer=optimizer, expectation=AerPauliExpectation(), quantum_instance=QuantumInstance(backend=backend), ) gsc = GroundStateEigensolver(self.qubit_converter, solver) result = gsc.solve(self.electronic_structure_problem) self.assertAlmostEqual(result.total_energies[0], self.reference_energy, places=3)
def setUp(self): super().setUp() self.seed = 50 algorithm_globals.random_seed = self.seed self.training_data = { 'A': np.asarray([[2.95309709, 2.51327412], [3.14159265, 4.08407045]]), 'B': np.asarray([[4.08407045, 2.26194671], [4.46106157, 2.38761042]]) } self.testing_data = { 'A': np.asarray([[3.83274304, 2.45044227]]), 'B': np.asarray([[3.89557489, 0.31415927]]) } self.ref_opt_params = np.array([ 0.47352206, -3.75934473, 1.72605939, -4.17669389, 1.28937435, -0.05841719, -0.29853266, -2.04139334, 1.00271775, -1.48133882, -1.18769138, 1.17885493, 7.58873883, -5.27078091, 2.5306601, -4.67393152 ]) self.ref_opt_params = np.array([ 4.40301812e-01, 2.10844304, -2.10118578, -5.25903194, 2.07617769, -9.25865371, -5.33834788, 8.59005180, 3.39886480, 6.33839643, 1.24425033, -1.39701513e+01, -7.16008545e-03, 3.36206032, 4.38001391, -3.47098082 ]) self.ref_train_loss = 0.5869304 self.ref_prediction_a_probs = [[0.8984375, 0.1015625]] self.ref_prediction_a_label = [0] self.ryrz_wavefunction = TwoLocal(2, ['ry', 'rz'], 'cz', reps=3, insert_barriers=True) self.data_preparation = ZZFeatureMap(2, reps=2) self.statevector_simulator = QuantumInstance( BasicAer.get_backend('statevector_simulator'), shots=1, seed_simulator=self.seed, seed_transpiler=self.seed) self.qasm_simulator = QuantumInstance( BasicAer.get_backend('qasm_simulator'), shots=1024, seed_simulator=self.seed, seed_transpiler=self.seed) self.spsa = SPSA(maxiter=10, save_steps=1, c0=4.0, c1=0.1, c2=0.602, c3=0.101, c4=0.0, skip_calibration=True)
class TestVQEClient(QiskitNatureTestCase): """Test the VQE program.""" def get_standard_program(self, use_deprecated=False): """Get a standard VQEClient and operator to find the ground state of.""" circuit = RealAmplitudes(3) operator = Z ^ I ^ Z initial_point = np.random.random(circuit.num_parameters) backend = QasmSimulatorPy() if use_deprecated: vqe_cls = VQEProgram provider = FakeRuntimeProvider(use_deprecated=True) warnings.filterwarnings("ignore", category=DeprecationWarning) else: provider = FakeRuntimeProvider(use_deprecated=False) vqe_cls = VQEClient vqe = vqe_cls( ansatz=circuit, optimizer=SPSA(), initial_point=initial_point, backend=backend, provider=provider, ) if use_deprecated: warnings.filterwarnings("always", category=DeprecationWarning) return vqe, operator @data({"name": "SPSA", "maxiter": 100}, SPSA(maxiter=100)) def test_standard_case(self, optimizer): """Test a standard use case.""" for use_deprecated in [False, True]: vqe, operator = self.get_standard_program( use_deprecated=use_deprecated) vqe.optimizer = optimizer result = vqe.compute_minimum_eigenvalue(operator) self.assertIsInstance(result, VQEResult) self.assertIsInstance( result, VQEProgramResult if use_deprecated else VQERuntimeResult) def test_supports_aux_ops(self): """Test the VQEClient says it supports aux operators.""" for use_deprecated in [False, True]: vqe, _ = self.get_standard_program(use_deprecated=use_deprecated) self.assertTrue(vqe.supports_aux_operators) def test_return_groundstate(self): """Test the VQEClient yields a ground state solver that returns the ground state.""" for use_deprecated in [False, True]: vqe, _ = self.get_standard_program(use_deprecated=use_deprecated) qubit_converter = QubitConverter(JordanWignerMapper()) gss = GroundStateEigensolver(qubit_converter, vqe) self.assertTrue(gss.returns_groundstate)
def __init__( self, ansatz: QuantumCircuit, optimizer: Optional[Union[Optimizer, Dict[str, Any]]] = None, initial_point: Optional[np.ndarray] = None, provider: Optional[Provider] = None, backend: Optional[Backend] = None, shots: int = 1024, measurement_error_mitigation: bool = False, callback: Optional[Callable[[int, np.ndarray, float, float], None]] = None, store_intermediate: bool = False, ) -> None: """ Args: ansatz: A parameterized circuit used as Ansatz for the wave function. optimizer: An optimizer or dictionary specifying a classical optimizer. If a dictionary, only SPSA and QN-SPSA are supported. The dictionary must contain a key ``name`` for the name of the optimizer and may contain additional keys for the settings. E.g. ``{'name': 'SPSA', 'maxiter': 100}``. Per default, SPSA is used. backend: The backend to run the circuits on. initial_point: An optional initial point (i.e. initial parameter values) for the optimizer. If ``None`` a random vector is used. provider: Provider that supports the runtime feature. shots: The number of shots to be used measurement_error_mitigation: Whether or not to use measurement error mitigation. callback: a callback that can access the intermediate data during the optimization. Four parameter values are passed to the callback as follows during each evaluation by the optimizer for its current set of parameters as it works towards the minimum. These are: the evaluation count, the optimizer parameters for the ansatz, the evaluated mean and the evaluated standard deviation. store_intermediate: Whether or not to store intermediate values of the optimization steps. Per default False. """ if optimizer is None: optimizer = SPSA(maxiter=300) # define program name self._program_id = "vqe" # store settings self._provider = None self._ansatz = ansatz self._optimizer = None self._backend = backend self._initial_point = initial_point self._shots = shots self._measurement_error_mitigation = measurement_error_mitigation self._callback = callback self._store_intermediate = store_intermediate # use setter to check for valid inputs if provider is not None: self.provider = provider self.optimizer = optimizer
def test_feature_map_without_parameters_warns(self): """Test that specifying a feature map with 0 parameters raises a warning.""" algorithm_globals.random_seed = self.seed var_form = QuantumCircuit(1) var_form.ry(Parameter('a'), 0) feature_map = QuantumCircuit(1) optimizer = SPSA() with self.assertWarns(UserWarning): _ = VQC(optimizer, feature_map, var_form, self.training_data, self.testing_data)
def test_basic_aer_qasm(self): """Test the VQE on BasicAer's QASM simulator.""" optimizer = SPSA(maxiter=300, last_avg=5) wavefunction = self.ry_wavefunction vqe = VQE(self.h2_op, wavefunction, optimizer, max_evals_grouped=1) # TODO benchmark this later. result = vqe.run(self.qasm_simulator) self.assertAlmostEqual(result.eigenvalue.real, -1.86823, places=2)
def test_same_parameter_names_raises(self): """Test that the varform and feature map can have parameters with the same name.""" algorithm_globals.random_seed = self.seed var_form = QuantumCircuit(1) var_form.ry(Parameter('a'), 0) feature_map = QuantumCircuit(1) feature_map.rz(Parameter('a'), 0) optimizer = SPSA() vqc = VQC(optimizer, feature_map, var_form, self.training_data, self.testing_data) with self.assertRaises(QiskitMachineLearningError): _ = vqc.run(BasicAer.get_backend('statevector_simulator'))
def test_basic_aer_qasm(self): """Test the VQE on BasicAer's QASM simulator.""" optimizer = SPSA(maxiter=300, last_avg=5) wavefunction = self.ry_wavefunction vqe = VQE(var_form=wavefunction, optimizer=optimizer, max_evals_grouped=1, quantum_instance=self.qasm_simulator) # TODO benchmark this later. result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, -1.86823, places=2)
def test_partition_vqe(self): """ Partition VQE test """ algorithm_globals.random_seed = 100 q_i = QuantumInstance(BasicAer.get_backend('qasm_simulator'), seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed) result = VQE(RealAmplitudes(reps=5, entanglement='linear'), SPSA(maxiter=200), max_evals_grouped=2, quantum_instance=q_i).compute_minimum_eigenvalue(operator=self.qubit_op) x = sample_most_likely(result.eigenstate) self.assertNotEqual(x[0], x[1]) self.assertNotEqual(x[2], x[1]) # hardcoded oracle
def test_construct_eigenstate_from_optpoint(self): """Test constructing the eigenstate from the optimal point, if the default ansatz is used.""" # use Hamiltonian yielding more than 11 parameters in the default ansatz hamiltonian = Z ^ Z ^ Z optimizer = SPSA(maxiter=1, learning_rate=0.01, perturbation=0.01) quantum_instance = QuantumInstance( backend=BasicAer.get_backend("statevector_simulator"), basis_gates=["u3", "cx"]) vqe = VQE(optimizer=optimizer, quantum_instance=quantum_instance) result = vqe.compute_minimum_eigenvalue(hamiltonian) optimal_circuit = vqe.ansatz.bind_parameters(result.optimal_point) self.assertTrue(Statevector(result.eigenstate).equiv(optimal_circuit))
def _sample_code(self): 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 qiskit_optimization import QuadraticProgram from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit import BasicAer from qiskit.algorithms import QAOA from qiskit.algorithms.optimizers import SPSA # 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 = nx.adjacency_matrix(graph) # Formulate the problem as quadratic program problem = QuadraticProgram() _ = [problem.binary_var('x{}'.format(i)) for i in range(n)] # create n binary variables linear = w.dot(np.ones(n)) quadratic = -w problem.maximize(linear=linear, quadratic=quadratic) # Fix node 0 to be 1 to break the symmetry of the max-cut solution problem.linear_constraint([1, 0, 0, 0], '==', 1) # Run quantum algorithm QAOA on qasm simulator spsa = SPSA(maxiter=250) backend = BasicAer.get_backend('qasm_simulator') qaoa = QAOA(optimizer=spsa, p=5, quantum_instance=backend) algorithm = MinimumEigenOptimizer(qaoa) result = algorithm.solve(problem) print(result) # prints solution, x=[1, 0, 1, 0], the cost, fval=4 # ---------------------------------------------------------------------- return result
def test_termination_checker(self): """Test the termination_callback""" def objective(x): return np.linalg.norm(x) + np.random.rand(1) class TerminationChecker: """Example termination checker""" def __init__(self): self.values = [] def __call__(self, nfev, point, fvalue, stepsize, accepted) -> bool: self.values.append(fvalue) if len(self.values) > 10: return True return False maxiter = 400 spsa = SPSA(maxiter=maxiter, termination_checker=TerminationChecker()) result = spsa.minimize(objective, x0=[0.5, 0.5]) self.assertLess(result.nit, maxiter)
def test_zero_parameters(self): """Test passing an ansatz with zero parameters raises an error.""" problem = EvolutionProblem(self.hamiltonian, time=0.02) pvqd = PVQD( QuantumCircuit(2), np.array([]), optimizer=SPSA(maxiter=10, learning_rate=0.1, perturbation=0.01), quantum_instance=self.sv_backend, expectation=self.expectation, ) with self.assertRaises(QiskitError): _ = pvqd.evolve(problem)
def test_uccsd_hf_qasm(self): """ uccsd hf test with qasm_simulator. """ backend = BasicAer.get_backend('qasm_simulator') optimizer = SPSA(maxiter=200, last_avg=5) solver = VQE(var_form=self.var_form, optimizer=optimizer, expectation=PauliExpectation(), quantum_instance=QuantumInstance( backend=backend, seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed)) gsc = GroundStateEigensolver(self.fermionic_transformation, solver) result = gsc.solve(self.driver) self.assertAlmostEqual(result.total_energies[0], -1.138, places=2)