def test_default(self): """ Default execution """ solver = VQEUCCFactory( QuantumInstance(BasicAer.get_backend('statevector_simulator'))) calc = AdaptVQE(self.qubit_converter, solver) res = calc.solve(self.problem) self.assertAlmostEqual(res.electronic_energies[0], self.expected, places=6)
def tearDown(self): # Reset the default providers, as in practice they acts as a singleton # due to importing the wrapper from qiskit. from qiskit.providers.ibmq import IBMQ IBMQ._providers.clear() IBMQ._credentials = None from qiskit.providers.basicaer import BasicAer BasicAer._backends = BasicAer._verify_backends()
def test_gradient(self, grad_method): """test for different gradient methods""" solver = VQEUCCFactory(quantum_instance=QuantumInstance( BasicAer.get_backend("statevector_simulator"))) grad = Gradient(grad_method, epsilon=1.0) calc = AdaptVQE(self.qubit_converter, solver, gradient=grad) res = calc.solve(self.problem) self.assertAlmostEqual(res.electronic_energies[0], self.expected, places=6)
def test_natural_gradients_invalid(self): """test that an exception is thrown when an invalid gradient method is used""" solver = VQEUCCFactory(quantum_instance=QuantumInstance( BasicAer.get_backend("statevector_simulator"))) grad = NaturalGradient(grad_method="fin_diff", qfi_method="lin_comb_full", regularization="ridge") calc = AdaptVQE(self.qubit_converter, solver, gradient=grad) with self.assertRaises(QiskitNatureError): _ = calc.solve(self.problem)
def test_delta_and_gradient(self): """test for when delta and gradient both are set""" solver = VQEUCCFactory(quantum_instance=QuantumInstance( BasicAer.get_backend("statevector_simulator"))) delta1 = 0.01 grad = Gradient(grad_method="fin_diff", epsilon=1.0) with self.assertRaises(TypeError): _ = AdaptVQE(self.qubit_converter, solver, delta=delta1, gradient=grad)
def tearDownClass(cls) -> None: # Reset the default providers, as in practice they acts as a singleton # due to importing the wrapper from qiskit. from qiskit.providers.ibmq import IBMQ try: IBMQ.disable_account() except IBMQAccountCredentialsNotFound: pass from qiskit.providers.basicaer import BasicAer BasicAer._backends = BasicAer._verify_backends()
def tearDown(self): # Reset the default providers, as in practice they acts as a singleton # due to importing the wrapper from qiskit. try: from qiskit.providers.ibmq import IBMQ IBMQ._accounts.clear() except ImportError: pass from qiskit.providers.basicaer import BasicAer BasicAer._backends = BasicAer._verify_backends()
def test_delta(self): """test for when delta is set instead of gradient""" solver = VQEUCCFactory(quantum_instance=QuantumInstance( BasicAer.get_backend("statevector_simulator"))) delta1 = 0.01 with warnings.catch_warnings(record=True): warnings.simplefilter("always") calc = AdaptVQE(self.qubit_converter, solver, delta=delta1) res = calc.solve(self.problem) self.assertAlmostEqual(res.electronic_energies[0], self.expected, places=6)
def test_aux_ops_reusability(self): """ Test that the auxiliary operators can be reused """ # Regression test against #1475 solver = VQEUCCSDFactory(QuantumInstance(BasicAer.get_backend('statevector_simulator'))) calc = AdaptVQE(self.transformation, solver) modes = 4 h_1 = np.eye(modes, dtype=complex) h_2 = np.zeros((modes, modes, modes, modes)) aux_ops = [FermionicOperator(h_1, h_2)] aux_ops_copy = copy.deepcopy(aux_ops) _ = calc.solve(self.driver, aux_ops) assert all([a == b for a, b in zip(aux_ops, aux_ops_copy)])
def tearDown(self): super().tearDown() if self.__teardown_called: raise ValueError( "In File: %s\n" "TestCase.tearDown was already called. Do not explicitly call " "tearDown from your tests. In your own tearDown, use super to " "call the base tearDown." % (sys.modules[self.__class__.__module__].__file__, )) self.__teardown_called = True # Reset the default providers, as in practice they acts as a singleton # due to importing the instances from the top-level qiskit namespace. from qiskit.providers.basicaer import BasicAer BasicAer._backends = BasicAer._verify_backends()
def test_aux_ops_reusability(self): """Test that the auxiliary operators can be reused""" # Regression test against #1475 solver = VQEUCCFactory(QuantumInstance(BasicAer.get_backend("statevector_simulator"))) calc = AdaptVQE(self.qubit_converter, solver) modes = 4 h_1 = np.eye(modes, dtype=complex) h_2 = np.zeros((modes, modes, modes, modes)) aux_ops = [build_ferm_op_from_ints(h_1, h_2)] aux_ops_copy = copy.deepcopy(aux_ops) _ = calc.solve(self.problem) assert all( frozenset(a.to_list()) == frozenset(b.to_list()) for a, b in zip(aux_ops, aux_ops_copy) )
def test_LiH(self): """Lih test""" driver = PySCFDriver( atom="Li .0 .0 .0; H .0 .0 1.6", unit=UnitsType.ANGSTROM, basis="sto3g", ) transformer = ActiveSpaceTransformer(num_electrons=2, num_molecular_orbitals=3) problem = ElectronicStructureProblem(driver, [transformer]) solver = VQEUCCFactory(quantum_instance=QuantumInstance( BasicAer.get_backend("statevector_simulator"))) calc = AdaptVQE(self.qubit_converter, solver) res = calc.solve(problem) self.assertAlmostEqual(res.electronic_energies[0], -8.855126478, places=6)
def test_entanglement(self): """ Test entanglement circuits of Ignis verification - GHZ, MQC, parity oscillations """ num_qubits = 5 # number of qubits sim = BasicAer.get_backend('qasm_simulator') # test simple GHZc circ = linear.get_ghz_simple(num_qubits, measure=True) counts = execute(circ, sim, shots=1024).result().get_counts(circ) self.assertTrue( counts.get('00000', 0) + counts.get('11111', 0) == 1024) # test MQC circ, delta = linear.get_ghz_mqc_para(num_qubits) theta_range = np.linspace(0, 2 * np.pi, 16) circuits = [ circ.bind_parameters({delta: theta_val}) for theta_val in theta_range ] for circ in circuits: counts = execute(circ, sim, shots=1024).result().get_counts(circ) self.assertTrue( (counts.get('00000', 0) == 1024) or (counts.get('00000', 0) + counts.get('00001', 0)) == 1024) # test parity oscillations circ, params = linear.get_ghz_po_para(num_qubits) theta_range = np.linspace(0, 2 * np.pi, 16) circuits = [ circ.bind_parameters({ params[0]: theta_val, params[1]: -theta_val }) for theta_val in theta_range ] for circ in circuits: counts = execute(circ, sim, shots=1024).result().get_counts(circ) even_counts = sum(key.count('1') % 2 == 0 for key in counts.keys()) odd_counts = sum(key.count('1') % 2 == 1 for key in counts.keys()) self.assertTrue(even_counts in (0, 16)) self.assertTrue(odd_counts in (0, 16))
def test_custom_excitation_pool(self): """ Test custom excitation pool """ class CustomFactory(VQEUCCSDFactory): """A custom MES factory.""" def get_solver(self, transformation): solver = super().get_solver(transformation) # Here, we can create essentially any custom excitation pool. # For testing purposes only, we simply select some hopping operator already # available in the variational form object. # pylint: disable=no-member custom_excitation_pool = [solver.var_form._hopping_ops[2]] solver.var_form.excitation_pool = custom_excitation_pool return solver solver = CustomFactory( QuantumInstance(BasicAer.get_backend('statevector_simulator'))) calc = AdaptVQE(self.transformation, solver) res = calc.solve(self.driver) self.assertAlmostEqual(res.electronic_energy, self.expected, places=6)
def test_custom_excitation_pool(self): """Test custom excitation pool""" class CustomFactory(VQEUCCFactory): """A custom MES factory.""" def get_solver(self, problem, qubit_converter): solver = super().get_solver(problem, qubit_converter) # Here, we can create essentially any custom excitation pool. # For testing purposes only, we simply select some hopping operator already # available in the ansatz object. custom_excitation_pool = [solver.ansatz.operators[2]] solver.ansatz.operators = custom_excitation_pool return solver solver = CustomFactory(quantum_instance=QuantumInstance( BasicAer.get_backend("statevector_simulator"))) calc = AdaptVQE(self.qubit_converter, solver) res = calc.solve(self.problem) self.assertAlmostEqual(res.electronic_energies[0], self.expected, places=6)
def test_aux_ops_reusability(self): """Test that the auxiliary operators can be reused""" # Regression test against #1475 solver = VQEUCCFactory( QuantumInstance(BasicAer.get_backend("statevector_simulator"))) calc = AdaptVQE(self.qubit_converter, solver) modes = 4 h_1 = np.eye(modes, dtype=complex) h_2 = np.zeros((modes, modes, modes, modes)) aux_ops = ElectronicEnergy([ OneBodyElectronicIntegrals(ElectronicBasis.MO, (h_1, None)), TwoBodyElectronicIntegrals(ElectronicBasis.MO, (h_2, None, None, None)), ]).second_q_ops() aux_ops_copy = copy.deepcopy(aux_ops) _ = calc.solve(self.problem) assert all( frozenset(a.to_list()) == frozenset(b.to_list()) for a, b in zip(aux_ops, aux_ops_copy))
def optmization_levels(self): backend = BasicAer.get_backend('qasm_simulator') circuit = self.circuit seed_simulator = self.seed_simulator seed_transpiler = seed_simulator counts_0 = execute( deepcopy(circuit), backend, optimization_level=0, seed_simulator=seed_simulator, seed_transpiler=seed_transpiler).result().get_counts() counts_1 = execute( deepcopy(circuit), backend, optimization_level=1, seed_simulator=seed_simulator, seed_transpiler=seed_transpiler, ).result().get_counts() counts_2 = execute( deepcopy(circuit), backend, optimization_level=2, seed_simulator=seed_simulator, seed_transpiler=seed_transpiler, ).result().get_counts() if self.random_bool: counts_3 = execute( deepcopy(circuit), backend, optimization_level=3, seed_simulator=seed_simulator, seed_transpiler=seed_transpiler, ).result().get_counts() else: counts_3 = deepcopy(counts_2) self.assertEqualCounts(counts_0, counts_1, counts_2, counts_3)
def run(self, qobj): """Main job in simulator""" if HAS_AER: if qobj.type == 'PULSE': from qiskit.providers.aer.pulse import PulseSystemModel system_model = PulseSystemModel.from_backend(self) sim = Aer.get_backend('pulse_simulator') job = sim.run(qobj, system_model) else: sim = Aer.get_backend('qasm_simulator') from qiskit.providers.aer.noise import NoiseModel noise_model = NoiseModel.from_backend(self) job = sim.run(qobj, noise_model=noise_model) else: if qobj.type == 'PULSE': raise QiskitError("Unable to run pulse schedules without " "qiskit-aer installed") warnings.warn("Aer not found using BasicAer and no noise", RuntimeWarning) sim = BasicAer.get_backend('qasm_simulator') job = sim.run(qobj) return job
def test_custom_minimum_eigensolver(self): """Test custom MES""" class CustomFactory(VQEUCCFactory): """A custom MES Factory""" def get_solver(self, problem, qubit_converter): particle_number = cast( ParticleNumber, problem.grouped_property_transformed.get_property( ParticleNumber), ) num_spin_orbitals = particle_number.num_spin_orbitals num_particles = (particle_number.num_alpha, particle_number.num_beta) initial_state = HartreeFock(num_spin_orbitals, num_particles, qubit_converter) ansatz = UCC( qubit_converter=qubit_converter, num_particles=num_particles, num_spin_orbitals=num_spin_orbitals, excitations="d", initial_state=initial_state, ) vqe = VQE( ansatz=ansatz, quantum_instance=self.minimum_eigensolver.quantum_instance, optimizer=L_BFGS_B(), ) return vqe solver = CustomFactory(quantum_instance=QuantumInstance( BasicAer.get_backend("statevector_simulator"))) calc = AdaptVQE(self.qubit_converter, solver) res = calc.solve(self.problem) self.assertAlmostEqual(res.electronic_energies[0], self.expected, places=6)
def test_custom_minimum_eigensolver(self): """ Test custom MES """ # Note: the VQEUCCSDFactory actually allows to specify an optimizer through its constructor. # Thus, this example is quite far fetched but for a proof-of-principle test it still works. class CustomFactory(VQEUCCSDFactory): """A custom MESFactory""" def get_solver(self, transformation): num_orbitals = transformation.molecule_info['num_orbitals'] num_particles = transformation.molecule_info['num_particles'] qubit_mapping = transformation.qubit_mapping two_qubit_reduction = transformation.molecule_info[ 'two_qubit_reduction'] z2_symmetries = transformation.molecule_info['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, quantum_instance=self._quantum_instance, optimizer=L_BFGS_B()) return vqe solver = CustomFactory( QuantumInstance(BasicAer.get_backend('statevector_simulator'))) calc = AdaptVQE(self.transformation, solver) res = calc.solve(self.driver) self.assertAlmostEqual(res.electronic_energies[0], self.expected, places=6)
def tearDown(self): # Reset the default providers, as in practice they acts as a singleton # due to importing the instances from the top-level qiskit namespace. from qiskit.providers.basicaer import BasicAer BasicAer._backends = BasicAer._verify_backends()