def test_h2_two_qubits_statevector(self): """Test H2 with parity mapping and statevector backend.""" two_qubit_reduction = True qubit_mapping = 'parity' core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=two_qubit_reduction, freeze_core=False, orbital_reduction=[]) qubit_op, _ = core.run(self.molecule) num_orbitals = core.molecule_info['num_orbitals'] num_particles = core.molecule_info['num_particles'] initial_state = HartreeFock(qubit_op.num_qubits, num_orbitals=num_orbitals, num_particles=num_particles, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction) var_form = UCCSD(num_qubits=qubit_op.num_qubits, depth=1, num_orbitals=num_orbitals, num_particles=num_particles, initial_state=initial_state, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction) optimizer = COBYLA(maxiter=1000, tol=1e-8) eom_vqe = QEomVQE(qubit_op, var_form, optimizer, num_orbitals=num_orbitals, num_particles=num_particles, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction) backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend) result = eom_vqe.run(quantum_instance) np.testing.assert_array_almost_equal(self.reference, result['energies'], decimal=4)
def setUp(self): """Setup.""" super().setUp() try: aqua_globals.random_seed = 0 atom = 'H .0 .0 .7414; H .0 .0 .0' pyscf_driver = PySCFDriver(atom=atom, unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') self.molecule = pyscf_driver.run() core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=False, orbital_reduction=[]) qubit_op, _ = core.run(self.molecule) exact_eigensolver = NumPyEigensolver(qubit_op, k=2 ** qubit_op.num_qubits) result = exact_eigensolver.run() self.reference = result.eigenvalues.real except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to be installed')
def setUp(self): super().setUp() try: driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0 1.6', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to be installed') self.qmolecule = driver.run() self.core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=True, orbital_reduction=[]) self.qubit_op, _ = self.core.run(self.qmolecule) self.z2_symmetries = Z2Symmetries.find_Z2_symmetries(self.qubit_op) self.reference_energy = -7.882096489442
def test_h2_two_qubits(self): """Test H2 with parity mapping.""" two_qubit_reduction = True qubit_mapping = 'parity' core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=two_qubit_reduction, freeze_core=False, orbital_reduction=[]) qubit_op, _ = core.run(self.molecule) num_orbitals = core.molecule_info['num_orbitals'] num_particles = core.molecule_info['num_particles'] eom_ee = QEomEE(qubit_op, num_orbitals=num_orbitals, num_particles=num_particles, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction) result = eom_ee.run() np.testing.assert_array_almost_equal(self.reference, result['energies'])
def _run_driver(driver, transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False, freeze_core=True): qmolecule = driver.run() core = Hamiltonian(transformation=transformation, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction, freeze_core=freeze_core, orbital_reduction=[]) qubit_op, aux_ops = core.run(qmolecule) exact_eigensolver = ExactEigensolver(qubit_op, aux_operators=aux_ops, k=1) _, result = core.process_algorithm_result(exact_eigensolver.run()) return result
def setUp(self): """Setup.""" super().setUp() atom = 'H .0 .0 .7414; H .0 .0 .0' pyscf_driver = PySCFDriver(atom=atom, unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') self.molecule = pyscf_driver.run() core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=False, orbital_reduction=[]) qubit_op, _ = core.run(self.molecule) exact_eigensolver = ExactEigensolver(qubit_op, k=2**qubit_op.num_qubits) result = exact_eigensolver.run() self.reference = result['eigvals'].real
def test_auto_ph_freeze_core_parity_2(self): """ Auto symmetry reduction, with freeze core, parity and two q reduction """ warnings.filterwarnings('ignore', category=DeprecationWarning) core = Hamiltonian(transformation=TransformationType.PARTICLE_HOLE, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=True, orbital_reduction=None, z2symmetry_reduction='auto') warnings.filterwarnings('always', category=DeprecationWarning) qubit_op, aux_ops = core.run(self.qmolecule) self.assertEqual(qubit_op.num_qubits, 6) npme = NumPyMinimumEigensolver(qubit_op, aux_operators=aux_ops) warnings.filterwarnings('ignore', category=DeprecationWarning) result = core.process_algorithm_result( npme.compute_minimum_eigenvalue()) warnings.filterwarnings('always', category=DeprecationWarning) self._validate_result(result) self.assertEqual( core.molecule_info[core.INFO_Z2SYMMETRIES].tapering_values, [1, 1])
def test_h2_one_qubit(self): """Test H2 with tapering.""" two_qubit_reduction = False qubit_mapping = 'jordan_wigner' core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=two_qubit_reduction, freeze_core=False, orbital_reduction=[]) qubit_op, _ = core.run(self.molecule) num_orbitals = core.molecule_info['num_orbitals'] num_particles = core.molecule_info['num_particles'] z2_symmetries = Z2Symmetries.find_Z2_symmetries(qubit_op) tapered_op = z2_symmetries.taper(qubit_op)[5] eom_ee = QEomEE(tapered_op, num_orbitals=num_orbitals, num_particles=num_particles, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction, z2_symmetries=tapered_op.z2_symmetries, untapered_op=qubit_op) result = eom_ee.run() np.testing.assert_array_almost_equal(self.reference, result['energies'])
def test_given_symmetry(self): """ Supplied symmetry reduction """ warnings.filterwarnings('ignore', category=DeprecationWarning) core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False, freeze_core=False, orbital_reduction=None, z2symmetry_reduction=[1, 1, 1, 1]) warnings.filterwarnings('always', category=DeprecationWarning) qubit_op, aux_ops = core.run(self.qmolecule) self.assertEqual(qubit_op.num_qubits, 8) npme = NumPyMinimumEigensolver(qubit_op, aux_operators=aux_ops) warnings.filterwarnings('ignore', category=DeprecationWarning) result = core.process_algorithm_result( npme.compute_minimum_eigenvalue()) warnings.filterwarnings('always', category=DeprecationWarning) self._validate_result(result) self.assertEqual( core.molecule_info[core.INFO_Z2SYMMETRIES].tapering_values, [1, 1, 1, 1])
def _create_components_for_tests(self, path='', freeze_core=False, two_qubit_reduction=False, initial_point=None): """ Instantiate classes necessary to run the test out of HDF5 files of QMolecules.""" driver = HDF5Driver(hdf5_input=self.get_resource_path(path)) qmolecule = driver.run() core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=two_qubit_reduction, freeze_core=freeze_core, orbital_reduction=[]) algo_input = core.run(qmolecule) qubit_op = algo_input[0] init_state = HartreeFock( num_orbitals=core._molecule_info['num_orbitals'], qubit_mapping=core._qubit_mapping, two_qubit_reduction=core._two_qubit_reduction, num_particles=core._molecule_info['num_particles']) var_form = UCCSD( num_orbitals=core._molecule_info['num_orbitals'], num_particles=core._molecule_info['num_particles'], active_occupied=None, active_unoccupied=None, initial_state=init_state, qubit_mapping=core._qubit_mapping, two_qubit_reduction=core._two_qubit_reduction, num_time_slices=1, method_doubles='pucc', same_spin_doubles=False, method_singles='both', skip_commute_test=True, excitation_type='d') algo = OOVQE(operator=qubit_op, var_form=var_form, optimizer=self.optimizer, core=core, qmolecule=qmolecule, expectation=MatrixExpectation(), initial_point=initial_point) return qmolecule, core, qubit_op, var_form, algo
def test_h2_one_qubit_statevector(self): """Test H2 with tapering and statevector backend.""" two_qubit_reduction = True qubit_mapping = 'parity' warnings.filterwarnings('ignore', category=DeprecationWarning) core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=two_qubit_reduction, freeze_core=False, orbital_reduction=[]) warnings.filterwarnings('always', category=DeprecationWarning) qubit_op, _ = core.run(self.molecule) num_orbitals = core.molecule_info['num_orbitals'] num_particles = core.molecule_info['num_particles'] # tapering z2_symmetries = Z2Symmetries.find_Z2_symmetries(qubit_op) # know the sector tapered_op = z2_symmetries.taper(qubit_op)[1] initial_state = HartreeFock(num_orbitals=num_orbitals, num_particles=num_particles, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction, sq_list=tapered_op.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=tapered_op.z2_symmetries) optimizer = SPSA(maxiter=50) eom_vqe = QEomVQE(tapered_op, var_form, optimizer, num_orbitals=num_orbitals, num_particles=num_particles, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction, z2_symmetries=tapered_op.z2_symmetries, untapered_op=qubit_op) backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend) result = eom_vqe.run(quantum_instance) np.testing.assert_array_almost_equal(self.reference, result['energies'], decimal=5)
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 setUp(self): try: driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0 1.6', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to be installed') self.qmolecule = driver.run() self.core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=True, orbital_reduction=[], max_workers=4) algo_input = self.core.run(self.qmolecule) self.qubit_op = algo_input.qubit_op self.symmetries, self.sq_paulis, self.cliffords, self.sq_list = self.qubit_op.find_Z2_symmetries( ) self.reference_energy = -7.882096489442
def test_vqe_auto_symmetry_freeze_core(self): """ Auto symmetry reduction, with freeze core using VQE """ warnings.filterwarnings('ignore', category=DeprecationWarning) core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False, freeze_core=True, orbital_reduction=None, z2symmetry_reduction='auto') warnings.filterwarnings('always', category=DeprecationWarning) 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') warnings.filterwarnings('ignore', category=DeprecationWarning) result = core.process_algorithm_result( vqe.compute_minimum_eigenvalue()) warnings.filterwarnings('always', category=DeprecationWarning) self._validate_result(result) self.assertEqual( core.molecule_info[core.INFO_Z2SYMMETRIES].tapering_values, [-1, 1, 1, -1])
def test_h2_one_qubit_qasm(self): """Test H2 with tapering and qasm backend""" two_qubit_reduction = True qubit_mapping = 'parity' core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=two_qubit_reduction, freeze_core=False, orbital_reduction=[]) qubit_op, _ = core.run(self.molecule) num_orbitals = core.molecule_info['num_orbitals'] num_particles = core.molecule_info['num_particles'] # tapering z2_symmetries = Z2Symmetries.find_Z2_symmetries(qubit_op) # know the sector tapered_op = z2_symmetries.taper(qubit_op)[1] var_form = RY(tapered_op.num_qubits, depth=1) optimizer = SPSA(max_trials=50) eom_vqe = QEomVQE(tapered_op, var_form, optimizer, num_orbitals=num_orbitals, num_particles=num_particles, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction, z2_symmetries=tapered_op.z2_symmetries, untapered_op=qubit_op) backend = BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=65536) result = eom_vqe.run(quantum_instance) np.testing.assert_array_almost_equal(self.reference, result['energies'], decimal=2)
def test_hf_value(self, mapping): try: driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0 1.6', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to be installed') qmolecule = driver.run() core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=mapping, two_qubit_reduction=False, freeze_core=False, orbital_reduction=[]) qubit_op, _ = core.run(qmolecule) hf = HartreeFock(qubit_op.num_qubits, core.molecule_info['num_orbitals'], core.molecule_info['num_particles'], mapping.value, False) qc = hf.construct_circuit('vector') hf_energy = qubit_op.eval('matrix', qc, None)[0].real + core._nuclear_repulsion_energy self.assertAlmostEqual(qmolecule.hf_energy, hf_energy, places=8)
def test_h2_four_qubits(self): """Test H2 with jordan wigner.""" two_qubit_reduction = False qubit_mapping = 'jordan_wigner' warnings.filterwarnings('ignore', category=DeprecationWarning) core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=two_qubit_reduction, freeze_core=False, orbital_reduction=[]) warnings.filterwarnings('always', category=DeprecationWarning) qubit_op, _ = core.run(self.molecule) num_orbitals = core.molecule_info['num_orbitals'] num_particles = core.molecule_info['num_particles'] eom_ee = QEomEE(qubit_op, num_orbitals=num_orbitals, num_particles=num_particles, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction) result = eom_ee.run() np.testing.assert_array_almost_equal(self.reference, result['energies'])
# Build the qubit operator, which is the input to the VQE algorithm in Aqua map_type = 'PARITY' qubit_op = ferm_op.mapping(map_type) qubit_op = Z2Symmetries.two_qubit_reduction(qubit_op, num_particles) num_qubits = qubit_op.num_qubits sys.exit(0) import pdb; pdb.set_trace() core = Hamiltonian( transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=False, orbital_reduction=range(0, 183), freeze_core=True) qubit_op, aux_ops = core.run(molecule) #import pdb; pdb.set_trace() 1/0 # HAMILTONIAN REDUCTION # Specify which orbitals to freeze and remove. # For example, in ICS.xyz, # Orbitals with occupancy=2 and Mulliken orbital population near # double occupancy can be readily frozen. # Orbitals with occupancy=0 and Mulliken orbital population near
fs.nroots = 3 e, c = fs.kernel(verbose=5) for i, x in enumerate(c): print('state %d, E = %.12f 2S+1 = %.7f' % (i, e[i], fci.spin_op.spin_square0(x, norb, nelec)[1])) ''' driver = PySCFDriver(atom=geo, unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto-3g', hf_method=HFMethodType.RHF) molecule = driver.run() core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False, freeze_core=False) H_op, A_op = core.run(molecule) outf.write("HF energy %f\n" % molecule.hf_energy) outf.write("Hamiltonian\n") outf.write(H_op.print_details()) init_state = HartreeFock(num_qubits=H_op.num_qubits, num_orbitals=core._molecule_info['num_orbitals'], qubit_mapping=core._qubit_mapping, two_qubit_reduction=core._two_qubit_reduction, num_particles=core._molecule_info['num_particles']) outf.write("State\n") outf.write(str(init_state.construct_circuit().draw()) + "\n")
class TestSymmetries(QiskitChemistryTestCase): """Test for symmetry processing.""" def setUp(self): super().setUp() try: driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0 1.6', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to be installed') self.qmolecule = driver.run() self.core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=True, orbital_reduction=[]) self.qubit_op, _ = self.core.run(self.qmolecule) self.z2_symmetries = Z2Symmetries.find_Z2_symmetries(self.qubit_op) self.reference_energy = -7.882096489442 def test_symmetries(self): """ symmetries test """ labels = [symm.to_label() for symm in self.z2_symmetries.symmetries] self.assertSequenceEqual(labels, ['ZIZIZIZI', 'ZZIIZZII']) def test_sq_paulis(self): """ sq paulis test """ labels = [sq.to_label() for sq in self.z2_symmetries.sq_paulis] self.assertSequenceEqual(labels, ['IIIIIIXI', 'IIIIIXII']) def test_cliffords(self): """ clifford test """ self.assertEqual(2, len(self.z2_symmetries.cliffords)) def test_sq_list(self): """ sq list test """ self.assertSequenceEqual(self.z2_symmetries.sq_list, [1, 2]) 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)
## CHECK vars(qmolecule) # ----- changing matrix elements ----- # overwrite_molecule('h.csv', qmolecule) # In[5]: # In[6]: # In[7]: hamiltonian = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=False) energy_shift = hamiltonian._energy_shift repulsion = qmolecule.nuclear_repulsion_energy num_AS_spin_orbitals = norb + norb num_AS_particles = na + nb classical_info = cqr(energy_shift, repulsion, num_AS_spin_orbitals, num_AS_particles) vars(hamiltonian) # In[8]: ## CREATE WeightedPauliOperater (qubit_op) ## CAUTION: Take a long time qubit_op, aux_ops = hamiltonian.run(qmolecule=qmolecule)
] qubit_mappings = { 'JW': QubitMappingType.JORDAN_WIGNER, 'P': QubitMappingType.PARITY, 'BK': QubitMappingType.BRAVYI_KITAEV } for basis in bases: for mol_name, molecule_str in molecules.items(): driver = PySCFDriver(molecule_str, basis=basis) mol = driver.run() for qm_name, qubit_mapping in qubit_mappings.items(): for freeze_core in [True, False]: core = Hamiltonian(qubit_mapping=qubit_mapping, two_qubit_reduction=False, freeze_core=freeze_core) qubitOp, _ = core.run(mol) n_qubits = qubitOp.num_qubits n_orbitals = core._molecule_info['num_orbitals'] n_electrons = core._molecule_info['num_particles'] # n_qubits = mol.one_body_integrals.shape[0] # n_qubits = mol.num_orbitals # n_electrons = mol.num_alpha + mol.num_beta - mol.molecular_charge # n_orbitals = mol.num_orbitals # ferOp = FermionicOperator(h1=mol.one_body_integrals, h2=mol.two_body_integrals) # if freeze_core and mol.core_orbitals: # core = mol.core_orbitals # freeze_alphas = [i for i in core if i < mol.num_alpha] # freeze_betas = [i + n_orbitals for i in core if i < mol.num_beta] # freeze_list = np.append(np.array(freeze_alphas), np.array(freeze_betas))
unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto-6g', hf_method=HFMethodType.RHF, symgroup='C2v', outfile=outfile) molecule = driver.run() # qubit representation of the Hamiltonian (possibly in an active space of chosen orbitals) orb_red = [0, 1, 2, 3, 4] # simple frozen core orb_red = [0, 1, 2, 3, 4, 8] # simple frozen core and out-of-plane orbital reduction core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=False, orbital_reduction=orb_red) H_op, A_op = core.run(molecule) # tapering off symmetries to reduce the number of qubits z2syms, sqlist = None, None H_op, A_op, z2syms, sqlist = taper(molecule, core, H_op, A_op, outfile) # hartree-fock and VQE-qUCCSD init_state = HartreeFock(num_orbitals=core._molecule_info['num_orbitals'], qubit_mapping=core._qubit_mapping, two_qubit_reduction=core._two_qubit_reduction, num_particles=core._molecule_info['num_particles'], sq_list=sqlist) circuit = init_state.construct_circuit()
charge=0, spin=0, basis='sto-6g', hf_method=HFMethodType.ROHF) molecule = driver.run() print('Overwriting PySCFDriver...') overwrite_molecule(filename + '_' + basis + '_' + procedure + '.h.csv', molecule) # Initialize the Hamiltonian and resctrict the simulation to a small subspace orb_red = [0, 1, 2, 6, 7] core = Hamiltonian(qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=False, orbital_reduction=orb_red) qubit_op, aux_ops = core.run(molecule) # we decide to measure also N, S^2 and S_z aux_ops = aux_ops[:3] aux_ops.append(qubit_op) dE = core._energy_shift + core._ph_energy_shift + core._nuclear_repulsion_energy # 2) Construct the HF initial state init_state = HartreeFock(num_orbitals=core._molecule_info['num_orbitals'], qubit_mapping=core._qubit_mapping, two_qubit_reduction=core._two_qubit_reduction, num_particles=core._molecule_info['num_particles'])
print('Processing step __', end='') for i in range(steps + 1): print('\b\b{:2d}'.format(i), end='', flush=True) d = start + i * by / steps # Given a atomic geometry specification, obtain molecular Hamiltonian driver = PySCFDriver(atom=atoms.format(d / 2), unit=UnitsType.ANGSTROM, basis='sto3g') molecule = driver.run() # Build the qubit operator, which is the input to the VQE algorithm in Aqua operator = Hamiltonian( transformation=TransformationType.FULL, qubit_mapping=QubitMappingType. PARITY, # Other choices: JORDAN_WIGNER, BRAVYI_KITAEV two_qubit_reduction=True, freeze_core=False, orbital_reduction=None) qubit_op, _ = operator.run(molecule) for j in range(len(algorithms)): if algorithms[j]['name'] == 'NumPyMinimumEigensolver': result = NumPyMinimumEigensolver(qubit_op).run() else: # Choice of classical optimizer optimizer = SPSA(max_trials=256) # Choice of ansatz var_form = TwoLocal(qubit_op.num_qubits, ['ry', 'rz'], 'cz',
class TestEnd2End(QiskitChemistryTestCase): """End2End VQE tests.""" def setUp(self): super().setUp() driver = HDF5Driver( hdf5_input=self.get_resource_path('test_driver_hdf5.hdf5')) self.qmolecule = driver.run() self.core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=False, orbital_reduction=[]) self.qubit_op, self.aux_ops = self.core.run(self.qmolecule) self.reference_energy = -1.857275027031588 @idata([ [ 'COBYLA_M', 'COBYLA', qiskit.BasicAer.get_backend('statevector_simulator'), 1 ], [ 'COBYLA_P', 'COBYLA', qiskit.BasicAer.get_backend('statevector_simulator'), 1 ], # ['SPSA_P', 'SPSA', qiskit.BasicAer.get_backend('qasm_simulator'), 'paulis', 1024], # ['SPSA_GP', 'SPSA', qiskit.BasicAer.get_backend('qasm_simulator'), 'grouped_paulis', 1024] ]) @unpack def test_end2end_h2(self, name, optimizer, backend, shots): """ end to end h2 """ del name # unused if optimizer == 'COBYLA': optimizer = COBYLA() optimizer.set_options(maxiter=1000) elif optimizer == 'SPSA': optimizer = SPSA(maxiter=2000) ryrz = TwoLocal(rotation_blocks=['ry', 'rz'], entanglement_blocks='cz') vqe = VQE(self.qubit_op, ryrz, optimizer, aux_operators=self.aux_ops) quantum_instance = QuantumInstance(backend, shots=shots) result = vqe.run(quantum_instance) self.assertAlmostEqual(result.eigenvalue.real, self.reference_energy, places=4) # TODO test aux_ops properly def test_deprecated_algo_result(self): """ Test processing a deprecated dictionary result from algorithm """ try: warnings.filterwarnings("ignore", category=DeprecationWarning) ryrz = TwoLocal(self.qubit_op.num_qubits, ['ry', 'rz'], 'cz', reps=3) vqe = VQE(self.qubit_op, ryrz, COBYLA(), aux_operators=self.aux_ops) quantum_instance = QuantumInstance( qiskit.BasicAer.get_backend('statevector_simulator')) result = vqe.run(quantum_instance) keys = {'energy', 'energies', 'eigvals', 'eigvecs', 'aux_ops'} dict_res = {key: result[key] for key in keys} lines, result = self.core.process_algorithm_result(dict_res) self.assertAlmostEqual(result['energy'], -1.137306, places=4) self.assertEqual(len(lines), 19) self.assertEqual( lines[8], ' Measured:: Num particles: 2.000, S: 0.000, M: 0.00000') finally: warnings.filterwarnings("always", category=DeprecationWarning)
element_1 = input() element_2 = input() molecule = element_1 + ' .0 .0 -{0}; ' + element_2 + ' .0 .0 {0}' distances = np.arange(0.1, 6.10, 0.1) variational_quantum_eigensolver_energies = [] hartree_fock_energies = [] # initial guess from Hartree-Fock for i, d in enumerate(distances): print('step ', i) # set up simulation driver = PySCFDriver(molecule.format(d / 2), basis='sto3g') qmolecule = driver.run() operator = Hamiltonian(qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=True, orbital_reduction=[-3, -2]) qubit_op, aux_ops = operator.run(qmolecule) # Variational Quantum Eigensolver (VQE) optimizer = SLSQP(maxiter=1000) 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) variational_form = UCCSD( num_orbitals=operator.molecule_info['num_orbitals'], num_particles=operator.molecule_info['num_particles'], initial_state=initial_state,
two_qubit_reduction = False qubit_mapping = 'jordan_wigner' distance = 0.75 pyscf_driver = PySCFDriver(atom='H .0 .0 {}; H .0 .0 .0'.format(distance), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = pyscf_driver.run() core = Hamiltonian(transformation=TransformationType.PH, qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=two_qubit_reduction, freeze_core=False, orbital_reduction=[]) algo_input = core.run(molecule) hamiltonian = algo_input[0] num_orbitals = core.molecule_info['num_orbitals'] num_particles = core.molecule_info['num_particles'] init_state = HartreeFock(hamiltonian.num_qubits, num_orbitals, num_particles, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction) depth = 1
class TestUCCSDHartreeFock(QiskitChemistryTestCase): """Test for these aqua extensions.""" def setUp(self): super().setUp() self.molecule = "H 0.000000 0.000000 0.735000;H 0.000000 0.000000 0.000000" self.driver = PySCFDriver(atom=self.molecule, unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='631g') self.qmolecule = self.driver.run() self.core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=True, orbital_reduction=[]) self.qubit_op, _ = self.core.run(self.qmolecule) z2_symmetries = Z2Symmetries.find_Z2_symmetries(self.qubit_op) tapered_ops = z2_symmetries.taper(self.qubit_op) smallest_eig_value = 99999999999999 smallest_idx = -1 for idx, _ in enumerate(tapered_ops): ee = ExactEigensolver(tapered_ops[idx], k=1) curr_value = ee.run()['energy'] if curr_value < smallest_eig_value: smallest_eig_value = curr_value smallest_idx = idx self.the_tapered_op = tapered_ops[smallest_idx] self.reference_energy_pUCCD = -1.1434447924298028 self.reference_energy_UCCD0 = -1.1476045878481704 self.reference_energy_UCCD0full = -1.1515491334334347 # reference energy of UCCSD/VQE with tapering everywhere self.reference_energy_UCCSD = -1.1516142309717594 # reference energy of UCCSD/VQE when no tapering on excitations is used self.reference_energy_UCCSD_no_tap_exc = -1.1516142309717594 # excitations for succ self.reference_singlet_double_excitations = [[0, 1, 4, 5], [0, 1, 4, 6], [0, 1, 4, 7], [0, 2, 4, 6], [0, 2, 4, 7], [0, 3, 4, 7]] # groups for succ_full self.reference_singlet_groups = [[[0, 1, 4, 5]], [[0, 1, 4, 6], [0, 2, 4, 5]], [[0, 1, 4, 7], [0, 3, 4, 5]], [[0, 2, 4, 6]], [[0, 2, 4, 7], [0, 3, 4, 6]], [[0, 3, 4, 7]]] pass 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_uccsd_hf_qUCCD0(self): """ singlet 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='succ', 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_UCCD0, places=6) def test_uccsd_hf_qUCCD0full(self): """ singlet full 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='succ_full', 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_UCCD0full, 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_uccsd_hf_excitations(self): """ uccsd tapering test using all double excitations """ # 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) # check singlet excitations 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='succ', excitation_type='d', skip_commute_test=True) double_excitations_singlet = var_form._double_excitations res = TestUCCSDHartreeFock.excitation_lists_comparator( double_excitations_singlet, self.reference_singlet_double_excitations) self.assertEqual(res, True) # check grouped singlet excitations 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='succ_full', excitation_type='d', skip_commute_test=True) double_excitations_singlet_grouped = var_form._double_excitations_grouped res_groups = TestUCCSDHartreeFock.group_excitation_lists_comparator( double_excitations_singlet_grouped, self.reference_singlet_groups) self.assertEqual(res_groups, True) @staticmethod def pop_el_when_matched(list1, list2): """ Compares if in list1 and list2 one of excitations is the same (regardless of permutations of its elements). When same excitation is found, it returns the 2 lists without that excitation . Args: list1 (list): list of excitations (e.g. [[0, 2, 4, 6], [0, 2, 4, 7]]) list2 (list): list of excitations Returns: list: list1 with one popped element if match was found list: list2 with one popped element if match was found """ counter = 0 for i, exc1 in enumerate(list1): for j, exc2 in enumerate(list2): for ind1 in exc1: for ind2 in exc2: if ind1 == ind2: counter += 1 if counter == len(exc1) and counter == len(exc2): list1.pop(i) list2.pop(j) break break return list1, list2 @staticmethod def excitation_lists_comparator(list1, list2): """ Compares if list1 and list2 contain same excitations (regardless of permutations of its elements). Only works provided all indices for an excitation are different. Args: list1 (list): list of excitations (e.g. [[0, 2, 4, 6], [0, 2, 4, 7]]) list2 (list): list of excitations Returns: bool: True or False, if list1 and list2 contain the same excitations """ if len(list1) != len(list2): return False number_el = len(list1) for _ in range(number_el): list1, list2 = TestUCCSDHartreeFock.pop_el_when_matched(list1, list2) return bool(len(list1) or len(list2) in [0]) @staticmethod def group_excitation_lists_comparator(glist1, glist2): """ Compares if list1 and list2 contain same excitations (regardless of permutations of its elements). Only works provided all indices for an excitation are different. Args: glist1 (list): list of excitations (e.g. [[0, 2, 4, 6], [0, 2, 4, 7]]) glist2 (list): list of excitations Returns: bool: True or False, if list1 and list2 contain the same excitations """ if len(glist1) != len(glist2): return False number_groups = len(glist1) counter = 0 for _, gr1 in enumerate(glist1): for _, gr2 in enumerate(glist2): res = TestUCCSDHartreeFock.excitation_lists_comparator(gr1, gr2) if res is True: counter += 1 return bool(counter == number_groups)
molecule = 'H .0 .0 -{0}; Li .0 .0 {0}' algorithms = ['VQE', 'ExactEigensolver'] dr = [x * 0.1 for x in range(6, 20)] dr += [x * 0.25 for x in range(8, 18)] dr += [4.0] energies = np.empty([len(algorithms), len(dr)]) hf_energies = np.empty(len(dr)) distances = np.empty(len(dr)) for i, d in enumerate(dr): for j in range(len(algorithms)): driver = PySCFDriver(molecule.format(d / 2), basis='sto3g') qmolecule = driver.run() operator = Hamiltonian(qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=True, orbital_reduction=[-3, -2]) qubit_op, aux_ops = operator.run(qmolecule) if algorithms[j] == 'ExactEigensolver': result = ExactEigensolver(qubit_op, aux_operators=aux_ops).run() optimizer = COBYLA(maxiter=1000) 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 = UCCSD(qubit_op.num_qubits, depth=1, num_orbitals=operator.molecule_info['num_orbitals'],