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 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): 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 test_orbital_reduction(self): """ orbital reduction test --- Remove virtual orbital just for test purposes (not sensible!) """ fermionic_transformation = FermionicTransformation( transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False, freeze_core=False, orbital_reduction=[-1]) # get dummy aux operator qmolecule = self.driver.run() fer_op = FermionicOperator(h1=qmolecule.one_body_integrals, h2=qmolecule.two_body_integrals) dummy = fer_op.total_particle_number() expected = (I ^ I) - 0.5 * (I ^ Z) - 0.5 * (Z ^ I) qubit_op, aux_ops = fermionic_transformation.transform( self.driver, [dummy]) self._validate_vars(fermionic_transformation) self._validate_info(fermionic_transformation, num_orbitals=2) self._validate_input_object(qubit_op, num_qubits=2, num_paulis=4) # the first six aux_ops are added automatically, ours is the 7th one self.assertEqual(aux_ops[6], expected)
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 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 _build_single_hopping_operator(index, num_particles, num_orbitals, qubit_mapping, two_qubit_reduction, z2_symmetries): h_1 = np.zeros((num_orbitals, num_orbitals), dtype=complex) h_2 = np.zeros((num_orbitals, num_orbitals, num_orbitals, num_orbitals), dtype=complex) if len(index) == 2: i, j = index h_1[i, j] = 4.0 elif len(index) == 4: i, j, k, m = index h_2[i, j, k, m] = 16.0 fer_op = FermionicOperator(h_1, h_2) qubit_op = fer_op.mapping(qubit_mapping) if two_qubit_reduction: qubit_op = Z2Symmetries.two_qubit_reduction(qubit_op, num_particles) commutativities = [] if not z2_symmetries.is_empty(): for symmetry in z2_symmetries.symmetries: symmetry_op = WeightedPauliOperator(paulis=[[1.0, symmetry]]) commuting = qubit_op.commute_with(symmetry_op) anticommuting = qubit_op.anticommute_with(symmetry_op) if commuting != anticommuting: # only one of them is True if commuting: commutativities.append(True) elif anticommuting: commutativities.append(False) else: raise AquaError("Symmetry {} is nor commute neither anti-commute " "to exciting operator.".format(symmetry.to_label())) return qubit_op, commutativities
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 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 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 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 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 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 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 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()
def __init__(self, n, nelec, h1, h2, algorithm='cobra'): self.n = n self.nelec = nelec self.htot = FermionicOperator(h1, h2) self.algo = algorithm self.hten = 0.5 * h2[:, :, :, :] + np.einsum( 'pr,qs->pqsr', h1, np.eye(n) / (self.nelec - 1))
def load_qubitop_for_molecule(molecule_data): atom_list = [a[0] + ' ' + " ".join([str(elem) for elem in a[1]]) for a in molecule_data['geometry']] atom = "; ".join(atom_list) #atom = 'Li .0 .0 .0; H .0 .0 3.9' basis = molecule_data['basis'] transform = molecule_data['transform'] electrons = molecule_data['electrons'] active = molecule_data['active_orbitals'] driver = PySCFDriver(atom=atom, unit=UnitsType.ANGSTROM, basis=basis, charge=0, spin=0) molecule = driver.run() num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 #print("# of electrons: {}".format(num_particles)) #print("# of spin orbitals: {}".format(num_spin_orbitals)) freeze_list = [x for x in range(int(active/2), int(num_particles/2))] remove_list = [-x for x in range(active,molecule.num_orbitals-int(num_particles/2)+int(active/2))] #print(freeze_list) #print(remove_list) if transform == 'BK': map_type = 'bravyi_kitaev' elif transform == 'JW': map_type = 'jordan_wigner' else: map_type = 'parity' 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] fermiOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) energy_shift = 0 if len(freeze_list) > 0: fermiOp, energy_shift = fermiOp.fermion_mode_freezing(freeze_list) num_spin_orbitals -= len(freeze_list) num_particles -= len(freeze_list) if len(remove_list) > 0: fermiOp = fermiOp.fermion_mode_elimination(remove_list) num_spin_orbitals -= len(remove_list) qubitOp = fermiOp.mapping(map_type=map_type, threshold=0.00000001) if len(freeze_list) > 0 or len(remove_list) >0: qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) #print(qubitOp.print_operators()) num_spin_orbitals= qubitOp.num_qubits return molecule, qubitOp, map_type, num_particles, num_spin_orbitals
def h2(dist=0.75): mol = PySCFDriver(atom= 'H 0.0 0.0 0.0;'\ 'H 0.0 0.0 {}'.format(dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto-3g') mol = mol.run() h1 = mol.one_body_integrals h2 = mol.two_body_integrals nuclear_repulsion_energy = mol.nuclear_repulsion_energy num_particles = mol.num_alpha + mol.num_beta + 0 ferOp = FermionicOperator(h1=h1, h2=h2) qubitOp = ferOp.mapping(map_type='parity', threshold=0.00000001) qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) cHam = op_converter.to_matrix_operator(qubitOp) cHam = cHam.dense_matrix + nuclear_repulsion_energy * numpy.identity(4) return cHam
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): 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 test_aux_ops_reusability(self): """ Test that the auxiliary operators can be reused """ # Regression test against #1475 solver = NumPyMinimumEigensolverFactory() calc = GroundStateEigensolver(self.transformation, solver) modes = 4 h_1 = np.eye(modes, dtype=np.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 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)])
ds=range(steps) for dist in ds: dist_step=dist dist=ds_min+dist*(ds_max-ds_min)/steps ds_build.append(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() repulsion_energy = molecule.nuclear_repulsion_energy num_spin_orbitals=molecule.num_orbitals*2 num_particles=molecule.num_alpha+molecule.num_beta map_type='jordan_wigner' ferOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) qubitOp = ferOp.mapping(map_type=map_type, threshold=0.00000001) exact_solution = ExactEigensolver(qubitOp).run()['energy'] exact_solution=exact_solution+repulsion_energy #optimizer = SLSQP(maxiter=5) optimizer = COBYLA(maxiter=opt_iter) HF_state=HartreeFock(qubitOp.num_qubits, num_spin_orbitals, num_particles, map_type) #var_form = RYRZ(qubitOp.num_qubits, depth=1, entanglement="linear") var_form = UCCSD(qubitOp.num_qubits, depth=1, num_orbitals=num_spin_orbitals, num_particles=num_particles, active_occupied=None, active_unoccupied=None, initial_state=HF_state, qubit_mapping='jordan_wigner', two_qubit_reduction=False, num_time_slices=1, shallow_circuit_concat=True, z2_symmetries=None)
def excitation_to_k_body_operator(self, mu, adjoint=False): hs = [np.zeros(tuple([self.n] * s)) for s in [2, 4, 6, 8]] idx = self.E_mu[mu] if (adjoint): hs[len(idx) // 2 - 1][tuple(idx[::-1])] = 1.0 else: hs[len(idx) // 2 - 1][tuple(idx)] = 1.0 return FermionicOperator(hs[0], hs[1])
def ten_commutator(fop_a, fop_b, fop_c=None, stat='fermi', Chem=True, threshold=1e-12): # fop_a, fop_b, fop_c - Fermionic Operators # if fop_c ==0 => return = [a,b] ([X,Y]=X*Y-Y*X) # if fop_c !=0 => return = 0.5*([[a,b],c]+[a,[b,c]]) ha_list = [] if np.all(fop_a.h1) != 0: ha_list.append(fop_a.h1) if np.all(fop_a.h2) != 0: ha_list.append(fop_a.h2) hb_list = [] if np.all(fop_b.h1) != 0: hb_list.append(fop_b.h1) if np.all(fop_b.h2) != 0: hb_list.append(fop_b.h2) hc_list = [] if fop_c is not None: if np.all(fop_c.h1) != 0: hc_list.append(fop_c.h1) if np.all(fop_c.h2) != 0: hc_list.append(fop_c.h2) ha_phys_list = [] hb_phys_list = [] hc_phys_list = [] if Chem == True: for x in ha_list: ha_phys_list.append(toPhys(x)) for x in hb_list: hb_phys_list.append(toPhys(x)) for x in hc_list: hc_phys_list.append(toPhys(x)) if len(ha_phys_list) != 0: nf = ha_phys_list[0].shape[0] else: nf = hb_phys_list[0].shape[0] if fop_c is None: #just [A,B] res = [] for x in ha_phys_list: for y in hb_phys_list: res.append(hComPhys(x, y, stat, threshold)) res = mat_list_simplify(res, nf, threshold) if len(res) == 0: #return empty fermionic operator return FermionicOperator(np.zeros((nf, nf))) else: h1out = np.zeros((nf, nf)) h2out = np.zeros((nf, nf, nf, nf)) for x in res: if len(x.shape) == 2: h1out = hSimplify(x, stat, threshold) if len(x.shape) == 4: h2out = hSimplify(x, stat, threshold) if Chem == True: return FermionicOperator(toChem(h1out), toChem(h2out)) else: return FermionicOperator(h1out, h2out) else: #([[A,B],C]+[A,[B,C]])/2 comAB = [] for x in ha_phys_list: for y in hb_phys_list: comAB.append(hComPhys(x, y, stat, threshold)) comAB = mat_list_simplify(comAB, nf, threshold) if len(comAB) == 0: comAB_C = [] else: comAB_C = [] for x in comAB: for y in hc_phys_list: comAB_C.append(hComPhys(x, y, stat, threshold)) comBC = [] for x in hb_phys_list: for y in hc_phys_list: comBC.append(hComPhys(x, y, stat, threshold)) comBC = mat_list_simplify(comBC, nf, threshold) if len(comBC) == 0: comA_BC = [] else: comA_BC = [] for x in ha_phys_list: for y in comBC: comA_BC.append(hComPhys(x, y, stat, threshold)) comABC = mat_list_simplify(comAB_C + comA_BC, nf, threshold) if len(comABC) == 0: #return empty fermionic operator return FermionicOperator(np.zeros((nf, nf))) else: h1out = np.zeros((nf, nf)) h2out = np.zeros((nf, nf, nf, nf)) for x in comABC: if len(x.shape) == 2: h1out = 0.5 * hSimplify(x, stat, threshold) if len(x.shape) == 4: h2out = 0.5 * hSimplify(x, stat, threshold) if Chem == True: return FermionicOperator(toChem(h1out), toChem(h2out)) else: return FermionicOperator(h1out, h2out)
# convert all negative idx to positive remove_list = [x % molecule.num_orbitals for x in remove_list] freeze_list = [x % molecule.num_orbitals for x in freeze_list] # update the idx in remove_list of the idx after frozen, since the idx of orbitals are changed after freezing 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] # prepare fermionic hamiltonian with orbital freezing and eliminating, and then map to qubit hamiltonian # and if PARITY mapping is selected, reduction qubits energy_shift = 0.0 qubit_reduction = True if map_type == 'parity' else False ferOp = FermionicOperator(h1=h1, h2=h2) if len(freeze_list) > 0: ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list) num_spin_orbitals -= len(freeze_list) num_particles -= len(freeze_list) if len(remove_list) > 0: ferOp = ferOp.fermion_mode_elimination(remove_list) num_spin_orbitals -= len(remove_list) qubitOp = ferOp.mapping(map_type=map_type, threshold=0.00000001) qubitOp = qubitOp.two_qubit_reduced_operator( num_particles) if qubit_reduction else qubitOp qubitOp.chop(10**-10) #print(qubitOp.print_operators()) print(qubitOp, flush=True)
def number_operator(num_qubits): h1 = np.identity(num_qubits) op = FermionicOperator(h1) num_op = op.mapping('jordan_wigner') return num_op
mol.basis = 'sto-3g' # mol.basis = {'O': 'sto-3g', 'H': 'cc-pvdz', 'H@2': '6-31G'} is_atomic = False mol.build() _q_ = qmol_func(mol, atomic=is_atomic) if is_atomic: two_body_temp = QMolecule.twoe_to_spin(_q_.mo_eri_ints) temp_int = np.einsum('ijkl->ljik', _q_.mo_eri_ints) two_body_temp = QMolecule.twoe_to_spin(temp_int) mol = gto.M(atom=atom, basis='sto-3g') O = get_ovlp(mol) X = np.kron(np.identity(2), np.linalg.inv(scipy.linalg.sqrtm(O))) fer_op = FermionicOperator(h1=_q_.one_body_integrals, h2=two_body_temp) fer_op.transform(X) else: fer_op = FermionicOperator(h1=_q_.one_body_integrals, h2=_q_.two_body_integrals) # s = np.shape(fer_op.h1) # fer_op.h1 = np.zeros(s) # print(fer_op.h1) ref_op = fer_op.mapping('jordan_wigner') print(ref_op.print_operators()) ee = ExactEigensolver(ref_op, k=1) ee_result = ee.run() temp_min_eigvals = ee_result['eigvals'] print(temp_min_eigvals)