def test_freezing_core(self): driver = PySCFDriver(atom='H .0 .0 -1.160518; Li .0 .0 0.386839', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() fer_op = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) fer_op, energy_shift = fer_op.fermion_mode_freezing([0, 6]) gt = -7.8187092970493755 diff = abs(energy_shift - gt) self.assertLess(diff, 1e-6) driver = PySCFDriver(atom='H .0 .0 .0; Na .0 .0 1.888', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() fer_op = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) fer_op, energy_shift = fer_op.fermion_mode_freezing( [0, 1, 2, 3, 4, 10, 11, 12, 13, 14]) gt = -162.58414559586748 diff = abs(energy_shift - gt) self.assertLess(diff, 1e-6)
def setUp(self): super().setUp() try: driver = PySCFDriver(molecule=TestDriver.MOLECULE) except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to be installed') self.qmolecule = driver.run()
def test_qpe(self, distance): self.algorithm = 'QPE' self.log.debug('Testing End-to-End with QPE on H2 with inter-atomic distance {}.'.format(distance)) try: driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 {}'.format(distance), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to be installed') self.molecule = driver.run() qubit_mapping = 'parity' fer_op = FermionicOperator( h1=self.molecule.one_body_integrals, h2=self.molecule.two_body_integrals) self.qubit_op = fer_op.mapping(map_type=qubit_mapping, threshold=1e-10).two_qubit_reduced_operator(2) exact_eigensolver = ExactEigensolver(self.qubit_op, k=1) results = exact_eigensolver.run() self.reference_energy = results['energy'] self.log.debug( 'The exact ground state energy is: {}'.format(results['energy'])) num_particles = self.molecule.num_alpha + self.molecule.num_beta two_qubit_reduction = True num_orbitals = self.qubit_op.num_qubits + \ (2 if two_qubit_reduction else 0) num_time_slices = 50 n_ancillae = 9 state_in = HartreeFock(self.qubit_op.num_qubits, num_orbitals, num_particles, qubit_mapping, two_qubit_reduction) iqft = Standard(n_ancillae) qpe = QPE(self.qubit_op, state_in, iqft, num_time_slices, n_ancillae, expansion_mode='suzuki', expansion_order=2, shallow_circuit_concat=True) backend = qiskit.Aer.get_backend('qasm_simulator') run_config = RunConfig(shots=100, max_credits=10, memory=False) quantum_instance = QuantumInstance(backend, run_config, pass_manager=PassManager()) result = qpe.run(quantum_instance) self.log.debug('eigvals: {}'.format(result['eigvals'])) self.log.debug('top result str label: {}'.format(result['top_measurement_label'])) self.log.debug('top result in decimal: {}'.format(result['top_measurement_decimal'])) self.log.debug('stretch: {}'.format(result['stretch'])) self.log.debug('translation: {}'.format(result['translation'])) self.log.debug('final energy from QPE: {}'.format(result['energy'])) self.log.debug('reference energy: {}'.format(self.reference_energy)) self.log.debug('ref energy (transformed): {}'.format( (self.reference_energy + result['translation']) * result['stretch'])) self.log.debug('ref binary str label: {}'.format(decimal_to_binary((self.reference_energy + result['translation']) * result['stretch'], max_num_digits=n_ancillae + 3, fractional_part_only=True))) np.testing.assert_approx_equal( result['energy'], self.reference_energy, significant=2)
def get_qubit_op(target_molecule): geometry, multiplicity, charge = generate_molecule_dict() driver = PySCFDriver(atom=geometry_convert(target_molecule), unit=UnitsType.ANGSTROM, charge=charge[target_molecule], spin=0, basis='sto3g') molecule = driver.run() repulsion_energy = molecule.nuclear_repulsion_energy num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 one_RDM = make_one_rdm(target_molecule) w = calculate_noons(one_RDM) freeze_list, remove_list = generate_freeze_remove_list(w) remove_list = [x % molecule.num_orbitals for x in remove_list] freeze_list = [x % molecule.num_orbitals for x in freeze_list] remove_list = [x - len(freeze_list) for x in remove_list] remove_list += [ x + molecule.num_orbitals - len(freeze_list) for x in remove_list ] freeze_list += [x + molecule.num_orbitals for x in freeze_list] ferOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list) num_spin_orbitals -= len(freeze_list) num_particles -= len(freeze_list) ferOp = ferOp.fermion_mode_elimination(remove_list) num_spin_orbitals -= len(remove_list) qubitOp = ferOp.mapping(map_type='bravyi_kitaev', threshold=0.00000001) qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) shift = energy_shift + repulsion_energy return qubitOp, num_particles, num_spin_orbitals, shift
def get_H2_data(dist): """ Use the qiskit chemistry package to get the qubit Hamiltonian for LiH Parameters ---------- dist : float The nuclear separations Returns ------- qubitOp : qiskit.aqua.operators.WeightedPauliOperator Qiskit representation of the qubit Hamiltonian shift : float The ground state of the qubit Hamiltonian needs to be corrected by this amount of energy to give the real physical energy. This includes the replusive energy between the nuclei and the energy shift of the frozen orbitals. """ driver = PySCFDriver(atom="H .0 .0 .0; H .0 .0 " + str(dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g', ) molecule = driver.run() repulsion_energy = molecule.nuclear_repulsion_energy num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 ferOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) qubitOp = ferOp.mapping(map_type='parity', threshold=1E-8) qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp,num_particles) shift = repulsion_energy return qubitOp, shift
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) qubit_op = op_converter.to_matrix_operator(qubit_op) 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.evaluate_with_statevector( qc)[0].real + core._nuclear_repulsion_energy self.assertAlmostEqual(qmolecule.hf_energy, hf_energy, places=8)
def test_bksf_mapping(self): """Test bksf mapping. The spectrum of bksf mapping should be half of jordan wigner mapping. """ driver = PySCFDriver(atom='H .0 .0 0.7414; H .0 .0 .0', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() fer_op = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) jw_op = fer_op.mapping('jordan_wigner') bksf_op = fer_op.mapping('bksf') jw_op.to_matrix() bksf_op.to_matrix() jw_eigs = np.linalg.eigvals(jw_op.matrix.toarray()) bksf_eigs = np.linalg.eigvals(bksf_op.matrix.toarray()) jw_eigs = np.sort(np.around(jw_eigs.real, 6)) bksf_eigs = np.sort(np.around(bksf_eigs.real, 6)) overlapped_spectrum = np.sum(np.isin(jw_eigs, bksf_eigs)) self.assertEqual(overlapped_spectrum, jw_eigs.size // 2)
def setUp(self): super().setUp() self.core_energy = 0.7199 self.num_orbitals = 2 self.num_electrons = 2 self.spin_number = 0 self.wf_symmetry = 1 self.orb_symmetries = [1, 1] self.mo_onee = [[1.2563, 0.0], [0.0, 0.4719]] self.mo_eri = [0.6757, 0.0, 0.1809, 0.6646, 0.0, 0.6986] try: driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 0.735', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') qmolecule = driver.run() dump = tempfile.NamedTemporaryFile() FCIDumpDriver.dump(qmolecule, dump.name) # pylint: disable=import-outside-toplevel from pyscf.tools import fcidump as pyscf_fcidump self.dumped = pyscf_fcidump.read(dump.name) dump.close() except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to be installed.') except ImportError: self.skipTest('PYSCF driver does not appear to be installed.')
def lih(dist=1.5): mol = PySCFDriver(atom= 'H 0.0 0.0 0.0;'\ 'Li 0.0 0.0 {}'.format(dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto-3g') mol = mol.run() freeze_list = [0] remove_list = [-3, -2] repulsion_energy = mol.nuclear_repulsion_energy num_particles = mol.num_alpha + mol.num_beta num_spin_orbitals = mol.num_orbitals * 2 remove_list = [x % mol.num_orbitals for x in remove_list] freeze_list = [x % mol.num_orbitals for x in freeze_list] remove_list = [x - len(freeze_list) for x in remove_list] remove_list += [ x + mol.num_orbitals - len(freeze_list) for x in remove_list ] freeze_list += [x + mol.num_orbitals for x in freeze_list] ferOp = FermionicOperator(h1=mol.one_body_integrals, h2=mol.two_body_integrals) ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list) num_spin_orbitals -= len(freeze_list) num_particles -= len(freeze_list) ferOp = ferOp.fermion_mode_elimination(remove_list) num_spin_orbitals -= len(remove_list) qubitOp = ferOp.mapping(map_type='parity', threshold=0.00000001) qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) shift = energy_shift + repulsion_energy cHam = op_converter.to_matrix_operator(qubitOp) cHam = cHam.dense_matrix + shift * numpy.identity(16) return cHam
def get_qubit_op(dist): #atom="Li .0 .0 .0; H .0 .0 " + str(dist) #atom="Be .0 .0 .0; H .0 .0 -" + str(dist) + "; H .0 .0 " + str(dist) driver = PySCFDriver("Li .0 .0 .0; H .0 .0 " + str(dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() freeze_list = [0] remove_list = [-3, -2] repulsion_energy = molecule.nuclear_repulsion_energy num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 remove_list = [x % molecule.num_orbitals for x in remove_list] freeze_list = [x % molecule.num_orbitals for x in freeze_list] remove_list = [x - len(freeze_list) for x in remove_list] remove_list += [ x + molecule.num_orbitals - len(freeze_list) for x in remove_list ] freeze_list += [x + molecule.num_orbitals for x in freeze_list] ferOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list) num_spin_orbitals -= len(freeze_list) num_particles -= len(freeze_list) ferOp = ferOp.fermion_mode_elimination(remove_list) num_spin_orbitals -= len(remove_list) qubitOp = ferOp.mapping(map_type='parity', threshold=0.00000001) qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) shift = energy_shift + repulsion_energy return qubitOp, num_particles, num_spin_orbitals, shift
def test_particle_hole(self, atom, charge=0, spin=0, basis='sto3g', hf_method=HFMethodType.RHF): """ particle hole test """ try: driver = PySCFDriver(atom=atom, unit=UnitsType.ANGSTROM, charge=charge, spin=spin, basis=basis, hf_method=hf_method) except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to be installed') config = '{}, charge={}, spin={}, basis={}, {}'.format(atom, charge, spin, basis, hf_method.value) molecule = driver.run() fer_op = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) ph_fer_op, ph_shift = fer_op.particle_hole_transformation([molecule.num_alpha, molecule.num_beta]) # ph_shift should be the electronic part of the hartree fock energy self.assertAlmostEqual(-ph_shift, molecule.hf_energy-molecule.nuclear_repulsion_energy, msg=config) # Energy in original fer_op should same as ph transformed one added with ph_shift jw_op = fer_op.mapping('jordan_wigner') result = ExactEigensolver(jw_op).run() ph_jw_op = ph_fer_op.mapping('jordan_wigner') ph_result = ExactEigensolver(ph_jw_op).run() self.assertAlmostEqual(result['energy'], ph_result['energy']-ph_shift, msg=config)
def setUp(self): """Setup.""" super().setUp() try: 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() warnings.filterwarnings('ignore', category=DeprecationWarning) core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=False, orbital_reduction=[]) warnings.filterwarnings('always', category=DeprecationWarning) 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() # np.random.seed(50) self.seed = 50 aqua_globals.random_seed = self.seed try: driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 0.735', unit=UnitsType.ANGSTROM, basis='sto3g') except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to be installed') return molecule = driver.run() self.num_particles = molecule.num_alpha + molecule.num_beta self.num_spin_orbitals = molecule.num_orbitals * 2 fer_op = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) map_type = 'PARITY' qubit_op = fer_op.mapping(map_type) self.qubit_op = Z2Symmetries.two_qubit_reduction( to_weighted_pauli_operator(qubit_op), self.num_particles) self.num_qubits = self.qubit_op.num_qubits self.init_state = HartreeFock(self.num_spin_orbitals, self.num_particles) self.var_form_base = None
def test_qpe(self, distance): """ qpe test """ self.log.debug('Testing End-to-End with QPE on ' 'H2 with inter-atomic distance %s.', distance) try: driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 {}'.format(distance), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to be installed') molecule = driver.run() qubit_mapping = 'parity' fer_op = FermionicOperator( h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) qubit_op = fer_op.mapping(map_type=qubit_mapping, threshold=1e-10) qubit_op = Z2Symmetries.two_qubit_reduction(qubit_op, 2) exact_eigensolver = ExactEigensolver(qubit_op, k=1) results = exact_eigensolver.run() reference_energy = results['energy'] self.log.debug('The exact ground state energy is: %s', results['energy']) num_particles = molecule.num_alpha + molecule.num_beta two_qubit_reduction = True num_orbitals = qubit_op.num_qubits + \ (2 if two_qubit_reduction else 0) num_time_slices = 1 n_ancillae = 6 state_in = HartreeFock(qubit_op.num_qubits, num_orbitals, num_particles, qubit_mapping, two_qubit_reduction) iqft = Standard(n_ancillae) qpe = QPE(qubit_op, state_in, iqft, num_time_slices, n_ancillae, expansion_mode='suzuki', expansion_order=2, shallow_circuit_concat=True) backend = qiskit.BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=100) result = qpe.run(quantum_instance) self.log.debug('eigvals: %s', result['eigvals']) self.log.debug('top result str label: %s', result['top_measurement_label']) self.log.debug('top result in decimal: %s', result['top_measurement_decimal']) self.log.debug('stretch: %s', result['stretch']) self.log.debug('translation: %s', result['translation']) self.log.debug('final energy from QPE: %s', result['energy']) self.log.debug('reference energy: %s', reference_energy) self.log.debug('ref energy (transformed): %s', (reference_energy + result['translation']) * result['stretch']) self.log.debug('ref binary str label: %s', decimal_to_binary( (reference_energy + result['translation']) * result['stretch'], max_num_digits=n_ancillae + 3, fractional_part_only=True)) np.testing.assert_approx_equal(result['energy'], reference_energy, significant=2)
def createPlot(exactGroundStateEnergy=-1.14, numberOfIterations=1000, bondLength=0.735, initialParameters=None, numberOfParameters=16, shotsPerPoint=1000, registerSize=12, map_type='jordan_wigner'): if initialParameters is None: initialParameters = np.random.rand(numberOfParameters) global qubitOp global qr_size global shots global values global plottingTime plottingTime = True shots = shotsPerPoint qr_size = registerSize optimizer = COBYLA(maxiter=numberOfIterations) iterations = [] values = [] for i in range(numberOfIterations): iterations.append(i + 1) #Build molecule with PySCF driver = PySCFDriver(atom="H .0 .0 .0; H .0 .0 " + str(bondLength), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() repulsion_energy = molecule.nuclear_repulsion_energy num_spin_orbitals = molecule.num_orbitals * 2 num_particles = molecule.num_alpha + molecule.num_beta #Map fermionic operator to qubit operator and start optimization ferOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) qubitOp = ferOp.mapping(map_type=map_type, threshold=0.00000001) sol_opt = optimizer.optimize(numberOfParameters, energy_opt, gradient_function=None, variable_bounds=None, initial_point=initialParameters) #Adjust values to obtain Energy Error for i in range(len(values)): values[i] = values[i] + repulsion_energy - exactGroundStateEnergy #Saving and Plotting Data filename = 'Energy Error - Iterations' with open(filename, 'wb') as f: pickle.dump([iterations, values], f) plt.plot(iterations, values) plt.ylabel('Energy Error') plt.xlabel('Iterations') plt.show()
def setUp(self): try: driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 0.735', 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()
def test_h4(self): """ Test for H4 chain """ atom = 'H 0 0 0; H 0 0 1; H 0 0 2; H 0 0 3' driver = PySCFDriver(atom=atom, unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() self.assertAlmostEqual(molecule.hf_energy, -2.09854593699776, places=5)
def test_readme_sample(self): """ readme sample test """ # pylint: disable=import-outside-toplevel # --- Exact copy of sample code ---------------------------------------- from qiskit.chemistry import FermionicOperator from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.aqua.operators import Z2Symmetries # Use PySCF, a classical computational chemistry software # package, to compute the one-body and two-body integrals in # molecular-orbital basis, necessary to form the Fermionic operator driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 0.735', unit=UnitsType.ANGSTROM, basis='sto3g') molecule = driver.run() num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 # Build the qubit operator, which is the input to the VQE algorithm in Aqua ferm_op = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) 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 # setup a classical optimizer for VQE from qiskit.aqua.components.optimizers import L_BFGS_B optimizer = L_BFGS_B() # setup the initial state for the variational form from qiskit.chemistry.components.initial_states import HartreeFock init_state = HartreeFock(num_qubits, num_spin_orbitals, num_particles) # setup the variational form for VQE from qiskit.aqua.components.variational_forms import RYRZ var_form = RYRZ(num_qubits, initial_state=init_state) # setup and run VQE from qiskit.aqua.algorithms import VQE algorithm = VQE(qubit_op, var_form, optimizer) # set the backend for the quantum computation from qiskit import Aer backend = Aer.get_backend('statevector_simulator') result = algorithm.run(backend) print(result['energy']) # ---------------------------------------------------------------------- self.assertAlmostEqual(result['energy'], -1.8572750301938803, places=6)
def test_h3(self): """ Test for H3 chain, see also issue 1148 """ atom = 'H 0 0 0; H 0 0 1; H 0 0 2' driver = PySCFDriver(atom=atom, unit=UnitsType.ANGSTROM, charge=0, spin=1, basis='sto3g') molecule = driver.run() self.assertAlmostEqual(molecule.hf_energy, -1.523996200246108, places=5)
def test_zmatrix(self): """ Check z-matrix input """ atom = 'H; H 1 1.0' driver = PySCFDriver(atom=atom, unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() self.assertAlmostEqual(molecule.hf_energy, -1.0661086493179366, places=5)
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.mp2info = MP2Info(self.qmolecule)
def test_list_atom(self): """ Check input with list of strings """ atom = ['H 0 0 0', 'H 0 0 1'] driver = PySCFDriver(atom=atom, unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() self.assertAlmostEqual(molecule.hf_energy, -1.0661086493179366, places=5)
def setUp(self): try: driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0 1.595', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to be installed') molecule = driver.run() self.fer_op = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals)
def get_LiH_qubit_op(dist): """ Use the qiskit chemistry package to get the qubit Hamiltonian for LiH Parameters ---------- dist : float The nuclear separations Returns ------- qubitOp : qiskit.aqua.operators.WeightedPauliOperator Qiskit representation of the qubit Hamiltonian shift : float The ground state of the qubit Hamiltonian needs to be corrected by this amount of energy to give the real physical energy. This includes the replusive energy between the nuclei and the energy shift of the frozen orbitals. """ driver = PySCFDriver( atom="Li .0 .0 .0; H .0 .0 " + str(dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g', ) molecule = driver.run() freeze_list = [0] remove_list = [-3, -2] repulsion_energy = molecule.nuclear_repulsion_energy num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 remove_list = [x % molecule.num_orbitals for x in remove_list] freeze_list = [x % molecule.num_orbitals for x in freeze_list] remove_list = [x - len(freeze_list) for x in remove_list] remove_list += [ x + molecule.num_orbitals - len(freeze_list) for x in remove_list ] freeze_list += [x + molecule.num_orbitals for x in freeze_list] ferOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list) num_spin_orbitals -= len(freeze_list) num_particles -= len(freeze_list) ferOp = ferOp.fermion_mode_elimination(remove_list) num_spin_orbitals -= len(remove_list) qubitOp = ferOp.mapping(map_type='parity', threshold=1E-8) #qubitOp = qubitOp.two_qubit_reduced_operator(num_particles) qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) shift = repulsion_energy + energy_shift return qubitOp, shift
def test_logging_emit(self): """ logging emit test """ with self.assertLogs(QiskitLogDomains.DOMAIN_CHEMISTRY.value, level='INFO') as log: try: driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 0.735', unit=UnitsType.ANGSTROM, basis='sto3g') except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to be installed') return _ = driver.run() self.assertIn('PySCF', log.output[0])
def get_uccsd_circuit(molecule, theta_vector=None, use_basis_gates=False): """Produce the full UCCSD circuit. Args: molecule :: string - must be a key of MOLECULE_TO_INFO theta_vector :: array - arguments for the vqe ansatz. If None, will generate random angles. use_basis_gates :: bool - Mike and Ike gates if False, Basis gates if True. Returns: circuit :: qiskit.QuantumCircuit - the UCCSD circuit parameterized by theta_vector, unoptimized """ molecule_info = MOLECULE_TO_INFO[molecule] driver = PySCFDriver(atom=molecule_info.atomic_string, basis='sto3g') qmolecule = driver.run() hamiltonian = Hamiltonian( qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=True, orbital_reduction=molecule_info.orbital_reduction) energy_input = hamiltonian.run(qmolecule) qubit_op = energy_input.qubit_op num_spin_orbitals = hamiltonian.molecule_info['num_orbitals'] num_particles = hamiltonian.molecule_info['num_particles'] map_type = hamiltonian._qubit_mapping qubit_reduction = hamiltonian.molecule_info['two_qubit_reduction'] HF_state = HartreeFock(qubit_op.num_qubits, num_spin_orbitals, num_particles, map_type, qubit_reduction) var_form = UCCSD(qubit_op.num_qubits, depth=1, num_orbitals=num_spin_orbitals, num_particles=num_particles, active_occupied=molecule_info.active_occupied, active_unoccupied=molecule_info.active_unoccupied, initial_state=HF_state, qubit_mapping=map_type, two_qubit_reduction=qubit_reduction, num_time_slices=1) if theta_vector is None: theta_vector = [ np.random.rand() * 2 * np.pi for _ in range(var_form._num_parameters) ] circuit = var_form.construct_circuit(theta_vector, use_basis_gates=use_basis_gates) return circuit
def get_qubit_op(dist): driver = PySCFDriver(atom="H .0 .0 .0; H .0 .0 " + str(dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() nuc_energy = molecule.nuclear_repulsion_energy num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 ferOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) qubitOp = ferOp.mapping(map_type='parity', threshold=0.00000001) qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) return qubitOp, num_particles, num_spin_orbitals, nuc_energy
def JW_H(systemData={'driver_string': 'Li 0.0 0.0 0.0; H 0.0 0.0 1.548', 'basis': 'sto3g'}): driver = PySCFDriver( atom=systemData["atomstring"], basis=systemData["basis"] ) mol = driver.run() OB = mol.one_body_integrals TB = mol.two_body_integrals FerOp = FermionicOperator(OB, TB) mapping = FerOp.mapping('jordan_wigner') weights = [w[0] for w in mapping.paulis] operators = [w[1].to_label() for w in mapping.paulis] return nk.operator.PauliStrings(operators, weights)
def test_mp2_h2(self): """ Just one double excitation expected - see issue 1151 """ driver = PySCFDriver(atom="H 0 0 0; H 0 0 0.7", unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() mp2info = MP2Info(molecule) terms = mp2info.mp2_terms() self.assertEqual(1, len(terms.keys())) np.testing.assert_array_almost_equal( [-0.06834019757197064, -0.012232934733533095], terms['0_1_2_3'], decimal=6)
def createPlot1(bondLengthMin=0.5, bondLengthMax=1.5, numberOfPoints=10, initialParameters=None, numberOfParameters=16, shotsPerPoint=1000, registerSize=12, map_type='jordan_wigner'): if initialParameters is None: initialParameters = np.random.rand(numberOfParameters) global qubitOp global qr_size global shots shots = shotsPerPoint qr_size = registerSize optimizer = COBYLA(maxiter=20) bondLengths = [] values = [] delta = (bondLengthMax - bondLengthMin) / numberOfPoints for i in range(numberOfPoints): bondLengths.append(bondLengthMin + i * delta) for bondLength in bondLengths: driver = PySCFDriver(atom="H .0 .0 .0; H .0 .0 " + str(bondLength), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() repulsion_energy = molecule.nuclear_repulsion_energy num_spin_orbitals = molecule.num_orbitals * 2 num_particles = molecule.num_alpha + molecule.num_beta ferOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) qubitOp = ferOp.mapping(map_type=map_type, threshold=0.00000001) sol_opt = optimizer.optimize(numberOfParameters, energy_opt, gradient_function=None, variable_bounds=None, initial_point=initialParameters) values.append(sol_opt[1] + repulsion_energy) filename = 'Energy - BondLengths' with open(filename, 'wb') as f: pickle.dump([bondLengths, values], f) plt.plot(bondLengths, values) plt.ylabel('Ground State Energy') plt.xlabel('Bond Length') plt.show()