def test_uccsd_hf(self): """ uccsd hf test """ driver = HDF5Driver(self.get_resource_path('test_driver_hdf5.hdf5')) qmolecule = driver.run() core = Hamiltonian(qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True) qubit_op, _ = core.run(qmolecule) optimizer = SLSQP(maxiter=100) initial_state = HartreeFock( core.molecule_info['num_orbitals'], core.molecule_info['num_particles'], qubit_mapping=core._qubit_mapping, two_qubit_reduction=core._two_qubit_reduction) var_form = UCCSD(num_orbitals=core.molecule_info['num_orbitals'], num_particles=core.molecule_info['num_particles'], initial_state=initial_state, qubit_mapping=core._qubit_mapping, two_qubit_reduction=core._two_qubit_reduction) algo = VQE(qubit_op, var_form, optimizer) result = algo.run( QuantumInstance(BasicAer.get_backend('statevector_simulator'))) result = core.process_algorithm_result(result) self.assertAlmostEqual(result.energy, self.reference_energy, places=6)
def test_vqe_auto_symmetry_freeze_core(self): """ Auto symmetry reduction, with freeze core using VQE """ core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False, freeze_core=True, orbital_reduction=None, z2symmetry_reduction='auto') qubit_op, aux_ops = core.run(self.qmolecule) self.assertEqual(qubit_op.num_qubits, 6) num_orbitals = core.molecule_info[core.INFO_NUM_ORBITALS] num_particles = core.molecule_info[core.INFO_NUM_PARTICLES] qubit_mapping = 'jordan_wigner' two_qubit_reduction = core.molecule_info[core.INFO_TWO_QUBIT_REDUCTION] z2_symmetries = core.molecule_info[core.INFO_Z2SYMMETRIES] initial_state = HartreeFock(num_orbitals, num_particles, qubit_mapping, two_qubit_reduction, z2_symmetries.sq_list) var_form = UCCSD(num_orbitals=num_orbitals, num_particles=num_particles, initial_state=initial_state, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction, z2_symmetries=z2_symmetries) vqe = VQE(qubit_op, var_form=var_form, optimizer=SLSQP(maxiter=500), aux_operators=aux_ops) vqe.quantum_instance = BasicAer.get_backend('statevector_simulator') result = core.process_algorithm_result(vqe.compute_minimum_eigenvalue()) self._validate_result(result) self.assertEqual(core.molecule_info[core.INFO_Z2SYMMETRIES].tapering_values, [-1, 1, 1, -1])
def test_uccsd_hf_qpUCCD(self): """ paired uccd test """ optimizer = SLSQP(maxiter=100) initial_state = HartreeFock(self.qubit_op.num_qubits, self.core.molecule_info['num_orbitals'], self.core.molecule_info['num_particles'], qubit_mapping=self.core._qubit_mapping, two_qubit_reduction=self.core._two_qubit_reduction) var_form = UCCSD(num_qubits=self.qubit_op.num_qubits, depth=1, num_orbitals=self.core._molecule_info['num_orbitals'], num_particles=self.core._molecule_info['num_particles'], active_occupied=None, active_unoccupied=None, initial_state=initial_state, qubit_mapping=self.core._qubit_mapping, two_qubit_reduction=self.core._two_qubit_reduction, num_time_slices=1, shallow_circuit_concat=False, method_doubles='pucc', excitation_type='d' ) algo = VQE(self.qubit_op, var_form, optimizer) result = algo.run(QuantumInstance(BasicAer.get_backend('statevector_simulator'))) _, result = self.core.process_algorithm_result(result) self.assertAlmostEqual(result['energy'], self.reference_energy_pUCCD, places=6)
def test_excitation_preserving(self): """Test the excitation preserving wavefunction on a chemistry example.""" driver = HDF5Driver(self.get_resource_path('test_driver_hdf5.hdf5')) fermionic_transformation = FermionicTransformation( qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=False) qubit_op, _ = fermionic_transformation.transform(driver) optimizer = SLSQP(maxiter=100) initial_state = HartreeFock( fermionic_transformation.molecule_info['num_orbitals'], fermionic_transformation.molecule_info['num_particles'], qubit_mapping=fermionic_transformation._qubit_mapping, two_qubit_reduction=fermionic_transformation._two_qubit_reduction) wavefunction = ExcitationPreserving(qubit_op.num_qubits, initial_state=initial_state) solver = VQE(var_form=wavefunction, optimizer=optimizer, quantum_instance=QuantumInstance( BasicAer.get_backend('statevector_simulator'), seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed)) gsc = GroundStateEigensolver(fermionic_transformation, solver) result = gsc.solve(driver) self.assertAlmostEqual(result.energy, self.reference_energy, places=4)
def test_swaprz(self, mode): """ SwapRZ variational form test """ driver = HDF5Driver(self.get_resource_path('test_driver_hdf5.hdf5')) qmolecule = driver.run() operator = Hamiltonian(qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False) qubit_op, _ = operator.run(qmolecule) optimizer = SLSQP(maxiter=100) initial_state = HartreeFock( operator.molecule_info['num_orbitals'], operator.molecule_info['num_particles'], qubit_mapping=operator._qubit_mapping, two_qubit_reduction=operator._two_qubit_reduction) if mode == 'wrapped': warnings.filterwarnings('ignore', category=DeprecationWarning) wavefunction = SwapRZ(qubit_op.num_qubits, initial_state=initial_state) else: wavefunction = ExcitationPreserving(qubit_op.num_qubits, initial_state=initial_state) algo = VQE(qubit_op, wavefunction, optimizer) if mode == 'wrapped': warnings.filterwarnings('always', category=DeprecationWarning) result = algo.run( QuantumInstance(BasicAer.get_backend('statevector_simulator'), seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed)) result = operator.process_algorithm_result(result) self.assertAlmostEqual(result.energy, self.reference_energy, places=6)
def test_tapered_op(self): """ tapered op test """ optimizer = SLSQP(maxiter=1000) init_state = HartreeFock( num_orbitals=self.fermionic_transformation.molecule_info['num_orbitals'], qubit_mapping=self.fermionic_transformation._qubit_mapping, two_qubit_reduction=self.fermionic_transformation._two_qubit_reduction, num_particles=self.fermionic_transformation.molecule_info['num_particles'], sq_list=self.z2_symmetries.sq_list) var_form = UCCSD( num_orbitals=self.fermionic_transformation.molecule_info['num_orbitals'], num_particles=self.fermionic_transformation.molecule_info['num_particles'], active_occupied=None, active_unoccupied=None, initial_state=init_state, qubit_mapping=self.fermionic_transformation._qubit_mapping, two_qubit_reduction=self.fermionic_transformation._two_qubit_reduction, num_time_slices=1, z2_symmetries=self.z2_symmetries) solver = VQE(var_form=var_form, optimizer=optimizer, quantum_instance=QuantumInstance( backend=BasicAer.get_backend('statevector_simulator'))) gsc = GroundStateEigensolver(self.fermionic_transformation, solver) result = gsc.solve(self.driver) self.assertAlmostEqual(result.total_energies[0], self.reference_energy, places=6)
def test_uccsd_hf_qpUCCD(self): """ paired uccd test """ optimizer = SLSQP(maxiter=100) initial_state = HartreeFock( self.fermionic_transformation.molecule_info['num_orbitals'], self.fermionic_transformation.molecule_info['num_particles'], qubit_mapping=self.fermionic_transformation._qubit_mapping, two_qubit_reduction=self.fermionic_transformation._two_qubit_reduction) var_form = UCCSD( num_orbitals=self.fermionic_transformation.molecule_info['num_orbitals'], num_particles=self.fermionic_transformation.molecule_info['num_particles'], active_occupied=None, active_unoccupied=None, initial_state=initial_state, qubit_mapping=self.fermionic_transformation._qubit_mapping, two_qubit_reduction=self.fermionic_transformation._two_qubit_reduction, num_time_slices=1, shallow_circuit_concat=False, method_doubles='pucc', excitation_type='d' ) solver = VQE(var_form=var_form, optimizer=optimizer, quantum_instance=QuantumInstance( backend=BasicAer.get_backend('statevector_simulator'))) gsc = GroundStateEigensolver(self.fermionic_transformation, solver) result = gsc.solve(self.driver) self.assertAlmostEqual(result.total_energies[0], self.reference_energy_pUCCD, places=6)
def __init__(self, var_form: Union[QuantumCircuit, VariationalForm], optimizer: Optimizer, cost_fn: Optional[Callable] = None, initial_point: Optional[np.ndarray] = None, quantum_instance: Optional[ Union[QuantumInstance, BaseBackend, Backend]] = None) -> None: """ Args: var_form: An optional parameterized variational form (ansatz). optimizer: A classical optimizer. cost_fn: An optional cost function for optimizer. If not supplied here must be supplied on :meth:`find_minimum`. initial_point: An optional initial point (i.e. initial parameter values) for the optimizer. quantum_instance: Quantum Instance or Backend Raises: ValueError: for invalid input """ super().__init__(quantum_instance) if optimizer is None: logger.info('No optimizer provided, setting it to SLSPQ.') optimizer = SLSQP() self._optimizer = optimizer self._cost_fn = cost_fn self._initial_point = initial_point self._var_form = var_form self._var_form_params = None if var_form is not None: self.var_form = var_form self._parameterized_circuits = None
def test_excitation_preserving(self): """Test the excitation preserving wavefunction on a chemistry example.""" driver = HDF5Driver(self.get_resource_path('test_driver_hdf5.hdf5')) qmolecule = driver.run() operator = Hamiltonian(qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False) qubit_op, _ = operator.run(qmolecule) optimizer = SLSQP(maxiter=100) initial_state = HartreeFock( operator.molecule_info['num_orbitals'], operator.molecule_info['num_particles'], qubit_mapping=operator._qubit_mapping, two_qubit_reduction=operator._two_qubit_reduction) wavefunction = ExcitationPreserving(qubit_op.num_qubits, initial_state=initial_state) algo = VQE(qubit_op, wavefunction, optimizer) result = algo.run( QuantumInstance(BasicAer.get_backend('statevector_simulator'), seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed)) result = operator.process_algorithm_result(result) self.assertAlmostEqual(result.energy, self.reference_energy, places=6)
def setUp(self): super().setUp() self.reference_energy = -1.1373060356951838 self.seed = 700 aqua_globals.random_seed = self.seed driver = HDF5Driver(self.get_resource_path('test_driver_hdf5.hdf5')) qmolecule = driver.run() core = Hamiltonian(qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True) self.qubit_op, _ = core.run(qmolecule) self.core = core self.optimizer = SLSQP(maxiter=100) initial_state = HartreeFock( core.molecule_info['num_orbitals'], core.molecule_info['num_particles'], qubit_mapping=core._qubit_mapping, two_qubit_reduction=core._two_qubit_reduction) self.var_form = UCCSD( num_orbitals=core.molecule_info['num_orbitals'], num_particles=core.molecule_info['num_particles'], initial_state=initial_state, qubit_mapping=core._qubit_mapping, two_qubit_reduction=core._two_qubit_reduction)
def test_backend_change(self, user_expectation): """Test that VQE works when backend changes.""" vqe = VQE( operator=self.h2_op, var_form=TwoLocal(rotation_blocks=['ry', 'rz'], entanglement_blocks='cz'), optimizer=SLSQP(maxiter=2), expectation=user_expectation, quantum_instance=BasicAer.get_backend('statevector_simulator')) result0 = vqe.run() if user_expectation is not None: with self.subTest('User expectation kept.'): self.assertEqual(vqe.expectation, user_expectation) else: with self.subTest('Expectation created.'): self.assertIsInstance(vqe.expectation, ExpectationBase) try: vqe.set_backend(BasicAer.get_backend('qasm_simulator')) except Exception as ex: # pylint: disable=broad-except self.fail("Failed to change backend. Error: '{}'".format(str(ex))) return result1 = vqe.run() if user_expectation is not None: with self.subTest( 'Change backend with user expectation, it is kept.'): self.assertEqual(vqe.expectation, user_expectation) else: with self.subTest( 'Change backend without user expectation, one created.'): self.assertIsInstance(vqe.expectation, ExpectationBase) with self.subTest('Check results.'): self.assertEqual(len(result0.optimal_point), len(result1.optimal_point))
def setUp(self): super().setUp() self.reference_energy = -1.1373060356951838 self.seed = 700 aqua_globals.random_seed = self.seed self.driver = HDF5Driver( self.get_resource_path('test_driver_hdf5.hdf5')) fermionic_transformation = FermionicTransformation( qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=False) self.qubit_op, _ = fermionic_transformation.transform(self.driver) self.fermionic_transformation = fermionic_transformation self.optimizer = SLSQP(maxiter=100) initial_state = HartreeFock( fermionic_transformation.molecule_info['num_orbitals'], fermionic_transformation.molecule_info['num_particles'], qubit_mapping=fermionic_transformation._qubit_mapping, two_qubit_reduction=fermionic_transformation._two_qubit_reduction) self.var_form = UCCSD( num_orbitals=fermionic_transformation. molecule_info['num_orbitals'], num_particles=fermionic_transformation. molecule_info['num_particles'], initial_state=initial_state, qubit_mapping=fermionic_transformation._qubit_mapping, two_qubit_reduction=fermionic_transformation._two_qubit_reduction)
def vqe_create_solver(num_particles, num_orbitals, qubit_mapping, two_qubit_reduction, z2_symmetries, initial_point = system.opt_amplitudes, noise = noise): initial_state = HartreeFock(num_orbitals, num_particles, qubit_mapping, two_qubit_reduction, z2_symmetries.sq_list) var_form = UCCSD(num_orbitals=num_orbitals, num_particles=num_particles, initial_state=initial_state, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction, z2_symmetries=z2_symmetries) if noise: var_form = EfficientSU2(num_qubits = no_qubits, entanglement="linear") else: var_form = UCCSD(num_orbitals=num_orbitals, num_particles=num_particles, initial_state=initial_state, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction, z2_symmetries=z2_symmetries) vqe = VQE(var_form=var_form, optimizer=SLSQP(maxiter=500), include_custom=True, initial_point = initial_point) vqe.quantum_instance = backend return vqe
def test_swaprz(self): """ SwapRZ variational form test """ driver = HDF5Driver(self.get_resource_path('test_driver_hdf5.hdf5')) qmolecule = driver.run() operator = Hamiltonian(qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False) qubit_op, _ = operator.run(qmolecule) optimizer = SLSQP(maxiter=100) initial_state = HartreeFock( qubit_op.num_qubits, operator.molecule_info['num_orbitals'], operator.molecule_info['num_particles'], qubit_mapping=operator._qubit_mapping, two_qubit_reduction=operator._two_qubit_reduction) var_form = SwapRZ(qubit_op.num_qubits, initial_state=initial_state) algo = VQE(qubit_op, var_form, optimizer) result = algo.run( QuantumInstance(BasicAer.get_backend('statevector_simulator'), seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed)) _, result = operator.process_algorithm_result(result) self.assertAlmostEqual(result['energy'], self.reference_energy, places=6)
def test_uccsd_hf_qUCCSD(self): """ uccsd tapering test using all double excitations """ # optimizer optimizer = SLSQP(maxiter=100) # initial state init_state = HartreeFock(num_qubits=self.the_tapered_op.num_qubits, num_orbitals=self.core._molecule_info['num_orbitals'], qubit_mapping=self.core._qubit_mapping, two_qubit_reduction=self.core._two_qubit_reduction, num_particles=self.core._molecule_info['num_particles'], sq_list=self.the_tapered_op.z2_symmetries.sq_list) var_form = UCCSD(num_qubits=self.the_tapered_op.num_qubits, depth=1, num_orbitals=self.core._molecule_info['num_orbitals'], num_particles=self.core._molecule_info['num_particles'], active_occupied=None, active_unoccupied=None, initial_state=init_state, qubit_mapping=self.core._qubit_mapping, two_qubit_reduction=self.core._two_qubit_reduction, num_time_slices=1, z2_symmetries=self.the_tapered_op.z2_symmetries, shallow_circuit_concat=False, method_doubles='ucc', excitation_type='sd', skip_commute_test=True) algo = VQE(self.the_tapered_op, var_form, optimizer) result = algo.run(QuantumInstance(BasicAer.get_backend('statevector_simulator'))) _, result = self.core.process_algorithm_result(result) self.assertAlmostEqual(result['energy'], self.reference_energy_UCCSD, places=6)
def test_tapered_op(self): """ tapered op test """ tapered_ops = self.z2_symmetries.taper(self.qubit_op) smallest_idx = 0 # Prior knowledge of which tapered_op has ground state the_tapered_op = tapered_ops[smallest_idx] optimizer = SLSQP(maxiter=1000) init_state = HartreeFock(num_qubits=the_tapered_op.num_qubits, num_orbitals=self.core._molecule_info['num_orbitals'], qubit_mapping=self.core._qubit_mapping, two_qubit_reduction=self.core._two_qubit_reduction, num_particles=self.core._molecule_info['num_particles'], sq_list=the_tapered_op.z2_symmetries.sq_list) var_form = UCCSD(num_qubits=the_tapered_op.num_qubits, depth=1, num_orbitals=self.core._molecule_info['num_orbitals'], num_particles=self.core._molecule_info['num_particles'], active_occupied=None, active_unoccupied=None, initial_state=init_state, qubit_mapping=self.core._qubit_mapping, two_qubit_reduction=self.core._two_qubit_reduction, num_time_slices=1, z2_symmetries=the_tapered_op.z2_symmetries) algo = VQE(the_tapered_op, var_form, optimizer) backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend=backend) algo_result = algo.run(quantum_instance) _, result = self.core.process_algorithm_result(algo_result) self.assertAlmostEqual(result['energy'], self.reference_energy, places=6)
def test_uccsd_hf_qUCCSD(self): """ uccsd tapering test using all double excitations """ fermionic_transformation = FermionicTransformation( transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=True, orbital_reduction=[], z2symmetry_reduction='auto') qubit_op, _ = fermionic_transformation.transform(self.driver) # optimizer optimizer = SLSQP(maxiter=100) # initial state init_state = HartreeFock( num_orbitals=fermionic_transformation. molecule_info['num_orbitals'], qubit_mapping=fermionic_transformation._qubit_mapping, two_qubit_reduction=fermionic_transformation._two_qubit_reduction, num_particles=fermionic_transformation. molecule_info['num_particles'], sq_list=fermionic_transformation.molecule_info['z2_symmetries']. sq_list) var_form = UCCSD( num_orbitals=fermionic_transformation. molecule_info['num_orbitals'], num_particles=fermionic_transformation. molecule_info['num_particles'], active_occupied=None, active_unoccupied=None, initial_state=init_state, qubit_mapping=fermionic_transformation._qubit_mapping, two_qubit_reduction=fermionic_transformation._two_qubit_reduction, num_time_slices=1, z2_symmetries=fermionic_transformation. molecule_info['z2_symmetries'], shallow_circuit_concat=False, method_doubles='ucc', excitation_type='sd', skip_commute_test=True) solver = VQE( var_form=var_form, optimizer=optimizer, quantum_instance=QuantumInstance( backend=BasicAer.get_backend('statevector_simulator'))) raw_result = solver.compute_minimum_eigenvalue(qubit_op, None) result = fermionic_transformation.interpret(raw_result) self.assertAlmostEqual(result.energy, self.reference_energy_UCCSD, places=6)
def test_circuit_input(self): """Test running the VQE on a plain QuantumCircuit object.""" wavefunction = QuantumCircuit(2).compose(EfficientSU2(2)) optimizer = SLSQP(maxiter=50) vqe = VQE(self.h2_op, wavefunction, optimizer=optimizer) result = vqe.run(self.statevector_simulator) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5)
def __init__(self): ### MOLECULE ### # These things need to be set before running self.molecule_string = None # You can make a pretty educated guess for these two self.spin = None self.charge = None self.qmolecule = None ### CHEMISTRY DRIVER ### #Basis has to be in a format accepted by Gaussian (sto-3g, 6-31g) self.basis = 'sto-3g' self.chem_driver = DriverType.GAUSSIAN self.hf_method = HFMethodType.UHF self.length_unit = UnitsType.ANGSTROM self.gaussian_checkfile = '' self.driver = None self.core = None ### HAMILTONIAN ### self.transformation = TransformationType.FULL self.qubit_mapping = QubitMappingType.JORDAN_WIGNER self.two_qubit_reduction = False self.freeze_core = True self.orbital_reduction = [] self.qubit_op = None self.aux_ops = None self.initial_point = None self.optimizer = SLSQP(maxiter=5000) self.ansatz = 'UCCSD' self.excitation_type = 'sd' self.num_time_slices = 1 self.shallow_circuit_concat = False self.vqe_algo = None self.var_form = None self.vqe_callback = None self.vqe_time = None ### BACKEND CONFIG ### #Choose the backend (use Aer instead of BasicAer) self.simulator = 'statevector_simulator' self.shots = 1024 self.seed_simulator = None self.seed_transpiler = None self.noise_model = None self.measurement_error_mitigation_cls = None self.backend_options = {}
def test_ibmq(self): """ IBMQ VQE Test """ from qiskit import IBMQ provider = IBMQ.load_account() backend = provider.get_backend('ibmq_qasm_simulator') ansatz = TwoLocal(rotation_blocks=['ry', 'rz'], entanglement_blocks='cz') opt = SLSQP(maxiter=1) opt.set_max_evals_grouped(100) vqe = VQE(self.h2_op, ansatz, SLSQP(maxiter=2)) result = vqe.run(backend) print(result) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy) np.testing.assert_array_almost_equal(result.eigenvalue.real, self.h2_energy, 5) self.assertEqual(len(result.optimal_point), 16) self.assertIsNotNone(result.cost_function_evals) self.assertIsNotNone(result.optimizer_time)
def getOptimiser(name="SPSA", params={}): optimiser = None if 'SPSA' in name: #max_trials (int) – Maximum number of iterations to perform. #save_steps (int) – Save intermeditate info every save_steps step. #last_avg (int) – Averged parameters over the last_avg iterations. If last_avg = 1, only the last iteration is considered. #c0 (float) – The initial a. Step size to update paramters. #c1 (float) – The initial c. The step size used to approximate gradient. #c2 (float) – The alpha in the paper, and it is used to adjust a (c0) at each iteration. #c3 (float) – The gamma in the paper, and it is used to adjust c (c1) at each iteration. #c4 (float) – The parameter used to control a as well. #skip_calibration (bool) – skip calibration and use provided c(s) as is. optimiser = SPSA( max_trials=params["max_trials"], save_steps=params["save_steps"], ) elif 'COBYLA' in name: #maxiter (int) – Maximum number of function evaluations. #disp (bool) – Set to True to print convergence messages. #rhobeg (float) – Reasonable initial changes to the variables. #tol (float) – Final accuracy in the optimization (not precisely guaranteed). This is a lower bound on the size of the trust region. optimiser = COBYLA(maxiter=params["maxiter"], disp=True) elif 'L_BFGS_B' in name: #maxfun (int) – Maximum number of function evaluations. #maxiter (int) – Maximum number of iterations. #factr (float) – The iteration stops when (f^k - f^{k+1})/max{|f^k|, |f^{k+1}|,1} <= factr * eps, where eps is the machine precision, which is automatically generated by the code. Typical values for factr are: 1e12 for low accuracy; 1e7 for moderate accuracy; 10.0 for extremely high accuracy. See Notes for relationship to ftol, which is exposed (instead of factr) by the scipy.optimize.minimize interface to L-BFGS-B. #iprint (int) – Controls the frequency of output. iprint < 0 means no output; iprint = 0 print only one line at the last iteration; 0 < iprint < 99 print also f and |proj g| every iprint iterations; iprint = 99 print details of every iteration except n-vectors; iprint = 100 print also the changes of active set and final x; iprint > 100 print details of every iteration including x and g. #epsilon (float) – Step size used when approx_grad is True, for numerically calculating the gradient optimiser = L_BFGS_B( #maxfun=params["maxfun"], maxiter=params["maxiter"]) elif 'P_BFGS' in name: optimiser = P_BFGS(maxfun=params["maxfun"]) elif 'NELDER_MEAD' in name: #maxiter (int) – Maximum allowed number of iterations. If both maxiter and maxfev are set, minimization will stop at the first reached. #maxfev (int) – Maximum allowed number of function evaluations. If both maxiter and maxfev are set, minimization will stop at the first reached. #disp (bool) – Set to True to print convergence messages. #xatol (float) – Absolute error in xopt between iterations that is acceptable for convergence. #tol (float or None) – Tolerance for termination. #adaptive (bool) – Adapt algorithm parameters to dimensionality of problem. optimiser = NELDER_MEAD(maxiter=params["maxiter"], disp=True) elif 'SLSQP' in name: #maxiter (int) – Maximum number of iterations. #disp (bool) – Set to True to print convergence messages. #ftol (float) – Precision goal for the value of f in the stopping criterion. #tol (float or None) – Tolerance for termination. #eps (float) – Step size used for numerical approximation of the Jacobian. optimiser = SLSQP(maxiter=params["maxiter"]) print("Optimising with {0} - {1}".format(name, optimiser)) return optimiser
def cb_create_solver(num_particles, num_orbitals, qubit_mapping, two_qubit_reduction, z2_symmetries): initial_state = HartreeFock(num_orbitals, num_particles, qubit_mapping, two_qubit_reduction, z2_symmetries.sq_list) var_form = UCCSD(num_orbitals=num_orbitals, num_particles=num_particles, initial_state=initial_state, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction, z2_symmetries=z2_symmetries) vqe = VQE(var_form=var_form, optimizer=SLSQP(maxiter=500)) vqe.quantum_instance = BasicAer.get_backend('statevector_simulator') return vqe
def test_tapered_op(self): # set_qiskit_chemistry_logging(logging.DEBUG) tapered_ops = [] for coeff in itertools.product([1, -1], repeat=len(self.sq_list)): tapered_op = Operator.qubit_tapering(self.qubit_op, self.cliffords, self.sq_list, list(coeff)) tapered_ops.append((list(coeff), tapered_op)) smallest_idx = 0 # Prior knowledge of which tapered_op has ground state the_tapered_op = tapered_ops[smallest_idx][1] the_coeff = tapered_ops[smallest_idx][0] optimizer = SLSQP(maxiter=1000) init_state = HartreeFock( num_qubits=the_tapered_op.num_qubits, num_orbitals=self.core._molecule_info['num_orbitals'], qubit_mapping=self.core._qubit_mapping, two_qubit_reduction=self.core._two_qubit_reduction, num_particles=self.core._molecule_info['num_particles'], sq_list=self.sq_list) var_form = UCCSD( num_qubits=the_tapered_op.num_qubits, depth=1, num_orbitals=self.core._molecule_info['num_orbitals'], num_particles=self.core._molecule_info['num_particles'], active_occupied=None, active_unoccupied=None, initial_state=init_state, qubit_mapping=self.core._qubit_mapping, two_qubit_reduction=self.core._two_qubit_reduction, num_time_slices=1, cliffords=self.cliffords, sq_list=self.sq_list, tapering_values=the_coeff, symmetries=self.symmetries) algo = VQE(the_tapered_op, var_form, optimizer, 'matrix') backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend=backend) algo_result = algo.run(quantum_instance) lines, result = self.core.process_algorithm_result(algo_result) self.assertAlmostEqual(result['energy'], self.reference_energy, places=6)
def vqe_create_solver(num_particles, num_orbitals, qubit_mapping, two_qubit_reduction, z2_symmetries): initial_state = HartreeFock(num_orbitals, num_particles, qubit_mapping, two_qubit_reduction, z2_symmetries.sq_list) var_form = UCCSD(num_orbitals=num_orbitals, num_particles=num_particles, initial_state=initial_state, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction, z2_symmetries=z2_symmetries) vqe = VQE(var_form=var_form, optimizer=SLSQP(maxiter=500), include_custom=True) vqe.quantum_instance = backend return vqe
def run(self, instance, verbose=False): for i, d in enumerate(self.distances): print("Simulation step", i, "simulating molecule: ", self.molecule.format(d)) if verbose: print("PySCFDriver") driver = PySCFDriver(self.molecule.format(d), basis="sto3g") if verbose: print("driver.run") qmolecule = driver.run() if verbose: print("Hamiltonian") operator = Hamiltonian(qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=self.two_qubit_reduction, freeze_core=self.freeze_core, orbital_reduction=self.orbital_reduction) if verbose: print("Hamiltonian.run") qubit_op, aux_ops = operator.run(qmolecule) if verbose: print("SLSQP") optimizer = SLSQP(maxiter=100) if verbose: print("HartreeFock") initial_state = HartreeFock(operator.molecule_info["num_orbitals"], operator.molecule_info["num_particles"], "parity", two_qubit_reduction=self.two_qubit_reduction) if verbose: print("UCCSD") var_form = UCCSD(num_orbitals=operator.molecule_info["num_orbitals"], num_particles=operator.molecule_info["num_particles"], initial_state=initial_state, qubit_mapping="parity", two_qubit_reduction=self.two_qubit_reduction) if verbose: print("VQE") algo = VQE(qubit_op, var_form, optimizer, aux_operators=aux_ops) if verbose: print("VQE.run") vqe_result = algo.run(instance) if verbose: print("Hamiltonian.process_algorithm_result") vqe_result_processed = operator.process_algorithm_result(vqe_result) self.vqe_energies.append(vqe_result_processed.energy) self.hf_energies.append(vqe_result_processed.hartree_fock_energy)
def test_antiferromagnetic_field_5qubits_with_vqe(seed='999999'): #Sets up a simple antiferromagnetic background field and checks if VQE can create the proper pattern num_qubits = 5 H = ham.magnetic_fields( [-1, 1, -1, 1, -1]) #With this field the ground state should be ^v^v^ ansatz = vf.sz_conserved_ansatz(num_qubits, entanglement='full', spindn_cluster='random', seed=seed) #ansatz.draw('mpl') optimizer = SLSQP(maxiter=30) vqe_h5 = VQE(H, ansatz, optimizer) backend = Aer.get_backend("statevector_simulator") vqe_h5_results = vqe_h5.run(backend) assert (np.absolute(vqe_h5_results['eigenvalue'] + 2.5) < 0.01 ) #Ground state energy should just be -5/2
def test_vqe_optimizer(self): """ Test running same VQE twice to re-use optimizer, then switch optimizer """ vqe = VQE(self.h2_op, optimizer=SLSQP(), quantum_instance=QuantumInstance( BasicAer.get_backend('statevector_simulator'))) def run_check(): result = vqe.compute_minimum_eigenvalue() self.assertAlmostEqual(result.eigenvalue.real, -1.85727503, places=5) run_check() with self.subTest('Optimizer re-use'): run_check() with self.subTest('Optimizer replace'): vqe.optimizer = L_BFGS_B() run_check()
def cb_create_solver(num_particles, num_orbitals, qubit_mapping, two_qubit_reduction, z2_symmetries): initial_state = HartreeFock(num_orbitals, num_particles, qubit_mapping, two_qubit_reduction, z2_symmetries.sq_list) var_form = UCCSD(num_orbitals=num_orbitals, num_particles=num_particles, initial_state=initial_state, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction, z2_symmetries=z2_symmetries) vqe = VQE(var_form=var_form, include_custom=True, optimizer=SLSQP(maxiter=5000), max_evals_grouped=256) vqe.quantum_instance = Aer.get_backend('qasm_simulator') vqe.quantum_instance.backend_options['backend_options'] = { 'max_parallel_experiments': threads, 'method': method } return vqe
def __init__( self, operator: Optional[Union[OperatorBase, LegacyBaseOperator]] = None, var_form: Optional[Union[QuantumCircuit, VariationalForm]] = None, optimizer: Optional[Optimizer] = None, initial_point: Optional[np.ndarray] = None, expectation: Optional[ExpectationBase] = None, include_custom: bool = False, max_evals_grouped: int = 1, aux_operators: Optional[List[Optional[Union[ OperatorBase, LegacyBaseOperator]]]] = None, callback: Optional[Callable[[int, np.ndarray, float, float], None]] = None, quantum_instance: Optional[Union[QuantumInstance, BaseBackend, Backend]] = None ) -> None: """ Args: operator: Qubit operator of the Observable var_form: A parameterized circuit used as Ansatz for the wave function. optimizer: A classical optimizer. initial_point: An optional initial point (i.e. initial parameter values) for the optimizer. If ``None`` then VQE will look to the variational form for a preferred point and if not will simply compute a random one. expectation: The Expectation converter for taking the average value of the Observable over the var_form state function. When ``None`` (the default) an :class:`~qiskit.aqua.operators.expectations.ExpectationFactory` is used to select an appropriate expectation based on the operator and backend. When using Aer qasm_simulator backend, with paulis, it is however much faster to leverage custom Aer function for the computation but, although VQE performs much faster with it, the outcome is ideal, with no shot noise, like using a state vector simulator. If you are just looking for the quickest performance when choosing Aer qasm_simulator and the lack of shot noise is not an issue then set `include_custom` parameter here to ``True`` (defaults to ``False``). include_custom: When `expectation` parameter here is None setting this to ``True`` will allow the factory to include the custom Aer pauli expectation. max_evals_grouped: Max number of evaluations performed simultaneously. Signals the given optimizer that more than one set of parameters can be supplied so that potentially the expectation values can be computed in parallel. Typically this is possible when a finite difference gradient is used by the optimizer such that multiple points to compute the gradient can be passed and if computed in parallel improve overall execution time. aux_operators: Optional list of auxiliary operators to be evaluated with the eigenstate of the minimum eigenvalue main result and their expectation values returned. For instance in chemistry these can be dipole operators, total particle count operators so we can get values for these at the ground state. 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 variational form, the evaluated mean and the evaluated standard deviation.` quantum_instance: Quantum Instance or Backend """ validate_min('max_evals_grouped', max_evals_grouped, 1) if var_form is None: var_form = RealAmplitudes() if optimizer is None: optimizer = SLSQP() # set the initial point to the preferred parameters of the variational form if initial_point is None and hasattr(var_form, 'preferred_init_points'): initial_point = var_form.preferred_init_points self._max_evals_grouped = max_evals_grouped self._circuit_sampler = None # type: Optional[CircuitSampler] self._expectation = expectation self._user_valid_expectation = self._expectation is not None self._include_custom = include_custom self._expect_op = None self._operator = None super().__init__(var_form=var_form, optimizer=optimizer, cost_fn=self._energy_evaluation, initial_point=initial_point, quantum_instance=quantum_instance) self._ret = None # type: Dict[str, Any] self._eval_time = None self._optimizer.set_max_evals_grouped(max_evals_grouped) self._callback = callback if operator is not None: self.operator = operator self.aux_operators = aux_operators self._eval_count = 0 logger.info(self.print_settings())
class TestVQE(QiskitAquaTestCase): """ Test VQE """ def setUp(self): super().setUp() self.seed = 50 aqua_globals.random_seed = self.seed self.h2_op = -1.052373245772859 * (I ^ I) \ + 0.39793742484318045 * (I ^ Z) \ - 0.39793742484318045 * (Z ^ I) \ - 0.01128010425623538 * (Z ^ Z) \ + 0.18093119978423156 * (X ^ X) self.h2_energy = -1.85727503 self.ryrz_wavefunction = TwoLocal(rotation_blocks=['ry', 'rz'], entanglement_blocks='cz') self.ry_wavefunction = TwoLocal(rotation_blocks='ry', entanglement_blocks='cz') self.qasm_simulator = QuantumInstance( BasicAer.get_backend('qasm_simulator'), shots=1024, seed_simulator=self.seed, seed_transpiler=self.seed) self.statevector_simulator = QuantumInstance( BasicAer.get_backend('statevector_simulator'), shots=1, seed_simulator=self.seed, seed_transpiler=self.seed) def test_basic_aer_statevector(self): """Test the VQE on BasicAer's statevector simulator.""" wavefunction = self.ryrz_wavefunction vqe = VQE(self.h2_op, wavefunction, L_BFGS_B()) result = vqe.run( QuantumInstance(BasicAer.get_backend('statevector_simulator'), basis_gates=['u1', 'u2', 'u3', 'cx', 'id'], coupling_map=[[0, 1]], seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed)) with self.subTest(msg='test eigenvalue'): self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy) with self.subTest(msg='test dimension of optimal point'): self.assertEqual(len(result.optimal_point), 16) with self.subTest(msg='assert cost_function_evals is set'): self.assertIsNotNone(result.cost_function_evals) with self.subTest(msg='assert optimizer_time is set'): self.assertIsNotNone(result.optimizer_time) def test_deprecated_variational_forms(self): """Test running the VQE on a deprecated VariationalForm object.""" warnings.filterwarnings('ignore', category=DeprecationWarning) wavefunction = RYRZ(2) vqe = VQE(self.h2_op, wavefunction, L_BFGS_B()) warnings.filterwarnings('always', category=DeprecationWarning) result = vqe.run(self.statevector_simulator) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy) def test_circuit_input(self): """Test running the VQE on a plain QuantumCircuit object.""" wavefunction = QuantumCircuit(2).compose(EfficientSU2(2)) optimizer = SLSQP(maxiter=50) vqe = VQE(self.h2_op, wavefunction, optimizer=optimizer) result = vqe.run(self.statevector_simulator) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) def test_legacy_operator(self): """Test the VQE accepts and converts the legacy WeightedPauliOperator.""" pauli_dict = { 'paulis': [{ "coeff": { "imag": 0.0, "real": -1.052373245772859 }, "label": "II" }, { "coeff": { "imag": 0.0, "real": 0.39793742484318045 }, "label": "IZ" }, { "coeff": { "imag": 0.0, "real": -0.39793742484318045 }, "label": "ZI" }, { "coeff": { "imag": 0.0, "real": -0.01128010425623538 }, "label": "ZZ" }, { "coeff": { "imag": 0.0, "real": 0.18093119978423156 }, "label": "XX" }] } h2_op = WeightedPauliOperator.from_dict(pauli_dict) vqe = VQE(h2_op) self.assertEqual(vqe.operator, self.h2_op) def test_missing_varform_params(self): """Test specifying a variational form with no parameters raises an error.""" circuit = QuantumCircuit(self.h2_op.num_qubits) vqe = VQE(self.h2_op, circuit) with self.assertRaises(RuntimeError): vqe.run(BasicAer.get_backend('statevector_simulator')) @data( (SLSQP(maxiter=50), 5, 4), (SPSA(max_trials=150), 3, 2), # max_evals_grouped=n or =2 if n>2 ) @unpack def test_max_evals_grouped(self, optimizer, places, max_evals_grouped): """ VQE Optimizers test """ vqe = VQE(self.h2_op, self.ryrz_wavefunction, optimizer, max_evals_grouped=max_evals_grouped, quantum_instance=self.statevector_simulator) result = vqe.run() self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=places) def test_basic_aer_qasm(self): """Test the VQE on BasicAer's QASM simulator.""" optimizer = SPSA(max_trials=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_statevector_snapshot_mode(self): """Test the VQE using Aer's statevector_simulator snapshot mode.""" 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('statevector_simulator') wavefunction = self.ry_wavefunction optimizer = L_BFGS_B() vqe = VQE(self.h2_op, wavefunction, optimizer, max_evals_grouped=1) 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, self.h2_energy, places=6) def test_qasm_snapshot_mode(self): """Test the VQE using Aer's qasm_simulator snapshot mode.""" 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 = L_BFGS_B() wavefunction = self.ry_wavefunction vqe = VQE(self.h2_op, wavefunction, optimizer, expectation=AerPauliExpectation(), max_evals_grouped=1) quantum_instance = QuantumInstance( backend, shots=1, seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed) result = vqe.run(quantum_instance) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) def test_callback(self): """Test the callback on VQE.""" history = {'eval_count': [], 'parameters': [], 'mean': [], 'std': []} def store_intermediate_result(eval_count, parameters, mean, std): history['eval_count'].append(eval_count) history['parameters'].append(parameters) history['mean'].append(mean) history['std'].append(std) optimizer = COBYLA(maxiter=3) wavefunction = self.ry_wavefunction vqe = VQE(self.h2_op, wavefunction, optimizer, callback=store_intermediate_result) vqe.run(self.qasm_simulator) self.assertTrue( all(isinstance(count, int) for count in history['eval_count'])) self.assertTrue( all(isinstance(mean, float) for mean in history['mean'])) self.assertTrue(all(isinstance(std, float) for std in history['std'])) for params in history['parameters']: self.assertTrue(all(isinstance(param, float) for param in params)) def test_reuse(self): """Test re-using a VQE algorithm instance.""" vqe = VQE() with self.subTest(msg='assert running empty raises AquaError'): with self.assertRaises(AquaError): _ = vqe.run() var_form = TwoLocal(rotation_blocks=['ry', 'rz'], entanglement_blocks='cz') vqe.var_form = var_form with self.subTest(msg='assert missing operator raises AquaError'): with self.assertRaises(AquaError): _ = vqe.run() vqe.operator = self.h2_op with self.subTest(msg='assert missing backend raises AquaError'): with self.assertRaises(AquaError): _ = vqe.run() vqe.quantum_instance = self.statevector_simulator with self.subTest(msg='assert VQE works once all info is available'): result = vqe.run() self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) operator = PrimitiveOp( np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]])) with self.subTest(msg='assert minimum eigensolver interface works'): result = vqe.compute_minimum_eigenvalue(operator) self.assertAlmostEqual(result.eigenvalue.real, -1.0, places=5) def test_vqe_optimizer(self): """ Test running same VQE twice to re-use optimizer, then switch optimizer """ vqe = VQE(self.h2_op, optimizer=SLSQP(), quantum_instance=QuantumInstance( BasicAer.get_backend('statevector_simulator'))) def run_check(): result = vqe.compute_minimum_eigenvalue() self.assertAlmostEqual(result.eigenvalue.real, -1.85727503, places=5) run_check() with self.subTest('Optimizer re-use'): run_check() with self.subTest('Optimizer replace'): vqe.optimizer = L_BFGS_B() run_check() def test_vqe_expectation_select(self): """Test expectation selection 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') with self.subTest('Defaults'): vqe = VQE(self.h2_op, quantum_instance=backend) self.assertIsInstance(vqe.expectation, PauliExpectation) with self.subTest('Include custom'): vqe = VQE(self.h2_op, include_custom=True, quantum_instance=backend) self.assertIsInstance(vqe.expectation, AerPauliExpectation) with self.subTest('Set explicitly'): vqe = VQE(self.h2_op, expectation=AerPauliExpectation(), quantum_instance=backend) self.assertIsInstance(vqe.expectation, AerPauliExpectation) @unittest.skip(reason="IBMQ testing not available in general.") def test_ibmq(self): """ IBMQ VQE Test """ from qiskit import IBMQ provider = IBMQ.load_account() backend = provider.get_backend('ibmq_qasm_simulator') ansatz = TwoLocal(rotation_blocks=['ry', 'rz'], entanglement_blocks='cz') opt = SLSQP(maxiter=1) opt.set_max_evals_grouped(100) vqe = VQE(self.h2_op, ansatz, SLSQP(maxiter=2)) result = vqe.run(backend) print(result) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy) np.testing.assert_array_almost_equal(result.eigenvalue.real, self.h2_energy, 5) self.assertEqual(len(result.optimal_point), 16) self.assertIsNotNone(result.cost_function_evals) self.assertIsNotNone(result.optimizer_time)