コード例 #1
0
 def test_qubits_4_py_h2(self):
     self.hf = HartreeFock(4, 4, 2, 'parity', False)
     cct = self.hf.construct_circuit('vector')
     np.testing.assert_array_equal(cct, [
         0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
         0.0, 0.0, 0.0
     ])
コード例 #2
0
 def test_qubits_4_jw_h2(self):
     self.hf = HartreeFock(4, 4, [1, 1], 'jordan_wigner', False)
     cct = self.hf.construct_circuit('vector')
     np.testing.assert_array_equal(cct, [
         0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
         0.0, 0.0, 0.0
     ])
コード例 #3
0
 def test_qubits_4_bk_h2(self):
     self.hf = HartreeFock(4, 4, [1, 1], 'bravyi_kitaev', False)
     cct = self.hf.construct_circuit('vector')
     np.testing.assert_array_equal(cct, [
         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0,
         0.0, 0.0, 0.0
     ])
コード例 #4
0
 def test_qubits_6_py_lih_cct(self):
     self.hf = HartreeFock(6, 10, [1, 1], 'parity', True, [1, 2])
     cct = self.hf.construct_circuit('circuit')
     self.assertEqual(
         cct.qasm(), 'OPENQASM 2.0;\ninclude "qelib1.inc";\nqreg q[6];\n'
         'u3(3.14159265358979,0.0,3.14159265358979) q[0];\n'
         'u3(3.14159265358979,0.0,3.14159265358979) q[1];\n')
コード例 #5
0
    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)
コード例 #6
0
 def test_qubits_10_bk_lih_bitstr(self):
     """ qubits 10 bk lih bitstr test """
     hrfo = HartreeFock(10, 10, [1, 1], 'bravyi_kitaev', False)
     bitstr = hrfo.bitstr
     np.testing.assert_array_equal(bitstr,
                                   [False, False, False, False, True,
                                    False, True, False, True, True])
コード例 #7
0
    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)
コード例 #8
0
    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)
コード例 #9
0
    def test_h2_one_qubit_statevector(self):
        """Test H2 with tapering 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']

        # tapering
        z2_symmetries = Z2Symmetries.find_Z2_symmetries(qubit_op)
        # know the sector
        tapered_op = z2_symmetries.taper(qubit_op)[1]

        initial_state = HartreeFock(tapered_op.num_qubits,
                                    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_qubits=tapered_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,
                         z2_symmetries=tapered_op.z2_symmetries)
        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('statevector_simulator')
        quantum_instance = QuantumInstance(backend)
        result = eom_vqe.run(quantum_instance)
        np.testing.assert_array_almost_equal(self.reference,
                                             result['energies'],
                                             decimal=5)
コード例 #10
0
    def test_tapered_op(self):
        # set_qiskit_chemistry_logging(logging.DEBUG)
        tapered_ops = []
        for coeff in itertools.product([1, -1], repeat=len(self.sq_list)):
            tapered_op = Operator.qubit_tapering(self.qubit_op, self.cliffords,
                                                 self.sq_list, list(coeff))
            tapered_ops.append((list(coeff), tapered_op))

        smallest_idx = 0  # Prior knowledge of which tapered_op has ground state
        the_tapered_op = tapered_ops[smallest_idx][1]
        the_coeff = tapered_ops[smallest_idx][0]

        optimizer = SLSQP(maxiter=1000)

        init_state = HartreeFock(
            num_qubits=the_tapered_op.num_qubits,
            num_orbitals=self.core._molecule_info['num_orbitals'],
            qubit_mapping=self.core._qubit_mapping,
            two_qubit_reduction=self.core._two_qubit_reduction,
            num_particles=self.core._molecule_info['num_particles'],
            sq_list=self.sq_list)

        var_form = UCCSD(
            num_qubits=the_tapered_op.num_qubits,
            depth=1,
            num_orbitals=self.core._molecule_info['num_orbitals'],
            num_particles=self.core._molecule_info['num_particles'],
            active_occupied=None,
            active_unoccupied=None,
            initial_state=init_state,
            qubit_mapping=self.core._qubit_mapping,
            two_qubit_reduction=self.core._two_qubit_reduction,
            num_time_slices=1,
            cliffords=self.cliffords,
            sq_list=self.sq_list,
            tapering_values=the_coeff,
            symmetries=self.symmetries)

        algo = VQE(the_tapered_op, var_form, optimizer, 'matrix')

        backend = BasicAer.get_backend('statevector_simulator')
        quantum_instance = QuantumInstance(backend=backend)

        algo_result = algo.run(quantum_instance)

        lines, result = self.core.process_algorithm_result(algo_result)

        self.assertAlmostEqual(result['energy'],
                               self.reference_energy,
                               places=6)
コード例 #11
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
コード例 #12
0
    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)

        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=5)
コード例 #13
0
class TestInitialStateHartreeFock(QiskitChemistryTestCase):
    def test_qubits_4_jw_h2(self):
        self.hf = HartreeFock(4, 4, 2, 'jordan_wigner', False)
        cct = self.hf.construct_circuit('vector')
        np.testing.assert_array_equal(cct, [
            0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
            0.0, 0.0, 0.0
        ])

    def test_qubits_4_py_h2(self):
        self.hf = HartreeFock(4, 4, 2, 'parity', False)
        cct = self.hf.construct_circuit('vector')
        np.testing.assert_array_equal(cct, [
            0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
            0.0, 0.0, 0.0
        ])

    def test_qubits_4_bk_h2(self):
        self.hf = HartreeFock(4, 4, 2, 'bravyi_kitaev', False)
        cct = self.hf.construct_circuit('vector')
        np.testing.assert_array_equal(cct, [
            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0,
            0.0, 0.0, 0.0
        ])

    def test_qubits_2_py_h2(self):
        self.hf = HartreeFock(2, 4, 2, 'parity', True)
        cct = self.hf.construct_circuit('vector')
        np.testing.assert_array_equal(cct, [0.0, 1.0, 0.0, 0.0])

    def test_qubits_2_py_h2_cct(self):
        self.hf = HartreeFock(2, 4, 2, 'parity', True)
        cct = self.hf.construct_circuit('circuit')
        self.assertEqual(
            cct.qasm(), 'OPENQASM 2.0;\ninclude "qelib1.inc";\nqreg q[2];\n'
            'u3(3.14159265358979,0.0,3.14159265358979) q[0];\n')

    def test_qubits_6_py_lih_cct(self):
        self.hf = HartreeFock(6, 10, 2, 'parity', True, [1, 2])
        cct = self.hf.construct_circuit('circuit')
        self.assertEqual(
            cct.qasm(), 'OPENQASM 2.0;\ninclude "qelib1.inc";\nqreg q[6];\n'
            'u3(3.14159265358979,0.0,3.14159265358979) q[0];\n'
            'u3(3.14159265358979,0.0,3.14159265358979) q[1];\n')
コード例 #14
0
 def test_qubits_10_bk_lih_bitstr(self):
     self.hf = HartreeFock(10, 10, [1, 1], 'bravyi_kitaev', False)
     bitstr = self.hf.bitstr
     np.testing.assert_array_equal(
         bitstr,
         [False, False, False, False, True, False, True, False, True, True])
コード例 #15
0
    def __init__(self,
                 ansatz,
                 molecule,
                 mean_field=None,
                 backend_options=None):
        """Initialize the settings for simulation.
        If the mean field is not provided it is automatically calculated.

        Args:
            ansatz (QiskitParametricSolver.Ansatze): Ansatz for the quantum solver.
            molecule (pyscf.gto.Mole): The molecule to simulate.
            mean_field (pyscf.scf.RHF): The mean field of the molecule.
            backend_options (dict): Extra parameters that control the behaviour
                of the solver.
        """

        # Check the ansatz
        assert (isinstance(ansatz, QiskitParametricSolver.Ansatze))
        self.ansatz = ansatz

        # Calculate the mean field if the user has not already done it.
        if not mean_field:
            mean_field = scf.RHF(molecule)
            mean_field.verbose = 0
            mean_field.scf()

            if (mean_field.converged == False):
                orb_temp = mean_field.mo_coeff
                occ_temp = mean_field.mo_occ
                nr = scf.newton(mean_field)
                energy = nr.kernel(orb_temp, occ_temp)
                mean_field = nr

        # Check the convergence of the mean field
        if not mean_field.converged:
            warnings.warn(
                "QiskitParametricSolver simulating with mean field not converged.",
                RuntimeWarning)

        # Initialize molecule quantities
        # ------------------------------
        self.num_orbitals = mean_field.mo_coeff.shape[0]
        self.num_spin_orbitals = self.num_orbitals * 2
        self.num_particles = molecule.nelec[0] + molecule.nelec[1]
        self.nuclear_repulsion_energy = gto.mole.energy_nuc(molecule)

        # Build one body integrals in Qiskit format
        one_body_integrals_pyscf = mean_field.mo_coeff.T @ mean_field.get_hcore(
        ) @ mean_field.mo_coeff
        self.one_body_integrals = QMolecule.onee_to_spin(
            one_body_integrals_pyscf)

        # Build two body integrals in Qiskit format
        eri = ao2mo.incore.full(mean_field._eri,
                                mean_field.mo_coeff,
                                compact=False)
        eri2 = eri.reshape(tuple([self.num_orbitals] * 4))
        self.two_body_integrals = QMolecule.twoe_to_spin(eri2)

        # Build Hamiltonians
        # ------------------
        # Set the fermionic Hamiltonian
        self.f_hamiltonian = FermionicOperator(h1=self.one_body_integrals,
                                               h2=self.two_body_integrals)

        # Transform the fermionic Hamiltonian into qubit Hamiltonian
        self.map_type = 'jordan_wigner'
        self.qubit_hamiltonian = self.f_hamiltonian.mapping(
            map_type=self.map_type, threshold=1e-8)
        self.qubit_hamiltonian.chop(10**-10)
        self.n_qubits = self.qubit_hamiltonian.num_qubits

        # Qubits, mapping, backend
        backend_opt = ('statevector_simulator', 'matrix')
        # backend_opt = ('qasm_simulator', 'paulis')
        self.backend = Aer.get_backend(backend_opt[0])
        self.backend_opt = backend_opt

        # Set ansatz and initial parameters
        # ---------------------------------

        # Define initial state
        self.init_state = HartreeFock(self.qubit_hamiltonian.num_qubits,
                                      self.num_spin_orbitals,
                                      self.num_particles, self.map_type,
                                      False)  # No qubit reduction

        # Select ansatz, set the dimension of the amplitudes
        self.var_form = UCCSD(self.qubit_hamiltonian.num_qubits,
                              depth=1,
                              num_orbitals=self.num_spin_orbitals,
                              num_particles=self.num_particles,
                              initial_state=self.init_state,
                              qubit_mapping=self.map_type,
                              two_qubit_reduction=False,
                              num_time_slices=1)

        self.amplitude_dimension = self.var_form._num_parameters
        self.optimized_amplitudes = []
コード例 #16
0
class TestInitialStateHartreeFock(QiskitChemistryTestCase):
    def test_qubits_4_jw_h2(self):
        self.hf = HartreeFock(4, 4, [1, 1], 'jordan_wigner', False)
        cct = self.hf.construct_circuit('vector')
        np.testing.assert_array_equal(cct, [
            0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
            0.0, 0.0, 0.0
        ])

    def test_qubits_4_py_h2(self):
        self.hf = HartreeFock(4, 4, [1, 1], 'parity', False)
        cct = self.hf.construct_circuit('vector')
        np.testing.assert_array_equal(cct, [
            0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
            0.0, 0.0, 0.0
        ])

    def test_qubits_4_bk_h2(self):
        self.hf = HartreeFock(4, 4, [1, 1], 'bravyi_kitaev', False)
        cct = self.hf.construct_circuit('vector')
        np.testing.assert_array_equal(cct, [
            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0,
            0.0, 0.0, 0.0
        ])

    def test_qubits_2_py_h2(self):
        self.hf = HartreeFock(2, 4, 2, 'parity', True)
        cct = self.hf.construct_circuit('vector')
        np.testing.assert_array_equal(cct, [0.0, 1.0, 0.0, 0.0])

    def test_qubits_2_py_h2_cct(self):
        self.hf = HartreeFock(2, 4, [1, 1], 'parity', True)
        cct = self.hf.construct_circuit('circuit')
        self.assertEqual(
            cct.qasm(), 'OPENQASM 2.0;\ninclude "qelib1.inc";\nqreg q[2];\n'
            'u3(3.14159265358979,0.0,3.14159265358979) q[0];\n')

    def test_qubits_6_py_lih_cct(self):
        self.hf = HartreeFock(6, 10, [1, 1], 'parity', True, [1, 2])
        cct = self.hf.construct_circuit('circuit')
        self.assertEqual(
            cct.qasm(), 'OPENQASM 2.0;\ninclude "qelib1.inc";\nqreg q[6];\n'
            'u3(3.14159265358979,0.0,3.14159265358979) q[0];\n'
            'u3(3.14159265358979,0.0,3.14159265358979) q[1];\n')

    def test_qubits_10_bk_lih_bitstr(self):
        self.hf = HartreeFock(10, 10, [1, 1], 'bravyi_kitaev', False)
        bitstr = self.hf.bitstr
        np.testing.assert_array_equal(
            bitstr,
            [False, False, False, False, True, False, True, False, True, True])

    @parameterized.expand([[QubitMappingType.JORDAN_WIGNER],
                           [QubitMappingType.PARITY],
                           [QubitMappingType.BRAVYI_KITAEV]])
    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)
コード例 #17
0
result_ee = exact_eigensolver.run()
reference_energy = result_ee['energy']
print('The exact ground state energy is: {} eV'.format(result_ee['energy'] *
                                                       27.21138506))

num_particles = molecule.num_alpha + molecule.num_beta
two_qubit_reduction = (qubit_mapping == 'parity')
num_orbitals = qubit_op.num_qubits + (2 if two_qubit_reduction else 0)

print('Number of qubits: ', qubit_op.num_qubits)

num_time_slices = 50
n_ancillae = 8
print('Number of ancillae:', n_ancillae)

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='trotter',
          expansion_order=2,
          shallow_circuit_concat=True)

# backend
#backend = Aer.get_backend('qasm_simulator')

# IBM Q
コード例 #18
0
 def test_qubits_2_py_h2_cct(self):
     """ qubits 2 py h2 cct test """
     hrfo = HartreeFock(2, 4, [1, 1], 'parity', True)
     cct = hrfo.construct_circuit('circuit')
     self.assertEqual(cct.qasm(), 'OPENQASM 2.0;\ninclude "qelib1.inc";\nqreg q[2];\n'
                                  'u3(3.14159265358979,0.0,3.14159265358979) q[0];\n')
コード例 #19
0
 def test_qubits_2_py_h2(self):
     """ qubits 2 py h2 test """
     hrfo = HartreeFock(2, 4, 2, 'parity', True)
     cct = hrfo.construct_circuit('vector')
     np.testing.assert_array_equal(cct, [0.0, 1.0, 0.0, 0.0])
コード例 #20
0
 def test_qubits_4_py_h2(self):
     """ qubits 4 py h2 test """
     hrfo = HartreeFock(4, 4, [1, 1], 'parity', False)
     cct = hrfo.construct_circuit('vector')
     np.testing.assert_array_equal(cct, [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0,
                                         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
コード例 #21
0
ファイル: tmp.py プロジェクト: paulineollitrault/COBRA
def run_ucc_r12(opt):
    """
    Parameters
    ----------
    * opt dictionary with user and default options/thresholds
    Returns
    -------
    * UCC-R12 ground state energy
        
    """

    import itertools
    import logging
    import numpy as np
    import time
    from datetime import datetime

    import qiskit    
    from qiskit                            import BasicAer,Aer    
    from qiskit.aqua                       import set_qiskit_aqua_logging, QuantumInstance
    from qiskit.aqua.operators             import Z2Symmetries, WeightedPauliOperator
    from qiskit.aqua.algorithms.adaptive   import VQE
    from qiskit.aqua.algorithms.classical  import ExactEigensolver
    from qiskit.aqua.components.optimizers import L_BFGS_B,CG,SPSA,SLSQP, COBYLA

    from qiskit.chemistry.drivers                                      import PySCFDriver, UnitsType, HFMethodType
    from qiskit.chemistry.core                                         import TransformationType, QubitMappingType
    from qiskit.chemistry.aqua_extensions.components.initial_states    import HartreeFock
    from qiskit.chemistry                                              import set_qiskit_chemistry_logging

    # ----- local functions ----- #
    import sys
    sys.path.append('/Users/mario/Documents/GitHub/R12-F12/project_ec/ucc_ec/')
    from qmolecule_ec   import QMolecule_ec,build_parameter_list
    from hamiltonian_ec import Hamiltonian
    from uccsd_ec       import UCCSD

    from davidson import davidson

    #import logging
    #set_qiskit_chemistry_logging(logging.DEBUG)

    logfile = open(opt["logfile"],'w')
    dateTimeObj = datetime.now()
    logfile.write("date and time "+str(dateTimeObj)+"\n")
    logfile.write("\n\n")

    import subprocess
    label = subprocess.check_output(['git','log','-1','--format="%H"']).strip()
    logfile.write("git commit "+str(label)+"\n")
    logfile.write("\n\n")

    qiskit_dict = qiskit.__qiskit_version__
    logfile.write("qiskit version \n")
    for k in qiskit_dict:
    	logfile.write(k+" : "+qiskit_dict[k]+"\n")
    logfile.write("\n\n")

    logfile.write("local run options \n")
    for k in opt:
    	logfile.write(k+" : "+str(opt[k])+"\n")
    logfile.write("\n\n")

    import time
    t0 = time.time()

    if(opt["input_file"] is None):
     # ----- normal molecular calc ----- #
     if(opt["calc_type"].lower() == "rhf"):  hf=HFMethodType.RHF
     if(opt["calc_type"].lower() == "rohf"): hf=HFMethodType.ROHF
     if(opt["calc_type"].lower() == "uhf"):  hf=HFMethodType.UHF
     driver      = PySCFDriver(atom=opt["geometry"],unit=UnitsType.ANGSTROM,charge=opt["charge"],spin=opt["spin"],basis=opt["basis"],hf_method=hf)
     molecule    = driver.run()
     molecule_ec = QMolecule_ec(molecule=molecule,filename=None,logfile=logfile)
    else:
     # ----- custom matrix elements ----- #
     molecule_ec = QMolecule_ec(molecule=None,filename=opt["input_file"],calc=opt["calc_type"],nfreeze=opt["nfreeze"],logfile=logfile)

    molecule_ec.mo_eri_ints_ec = (molecule_ec.mo_eri_ints_ec).transpose((0,1,3,2))

    t1 = time.time()
    logfile.write("classical ES and setup: %f [s] \n" % (t1-t0))
    logfile.write("\n\n")

    core        = Hamiltonian(qubit_mapping=QubitMappingType.PARITY,two_qubit_reduction=True,freeze_core=False)
    qubit_op, _ = core.run(molecule_ec)

    t2 = time.time()
    logfile.write("second-quantized Hamiltonian setup : %f [s] \n" % (t2-t1))
    logfile.write("\n\n")

    logfile.write("Original number of qubits %d \n" % (qubit_op.num_qubits))
    z2_symmetries = Z2Symmetries.find_Z2_symmetries(qubit_op)

    nsym = len(z2_symmetries.sq_paulis)
    the_tapered_op = qubit_op
    sqlist = None
    z2syms = None

    if(nsym>0):

       logfile.write('\nZ2 symmetries found: \n')
       for symm in z2_symmetries.symmetries:
           logfile.write(symm.to_label())
       logfile.write('\nsingle-qubit operators found: \n')
       for sq in z2_symmetries.sq_paulis:
           logfile.write(sq.to_label())
       logfile.write('\nCliffords found: \n')
       for clifford in z2_symmetries.cliffords:
           logfile.write(clifford.print_details())
       logfile.write('\nsingle-qubit list: {} \n'.format(z2_symmetries.sq_list))
       
       tapered_ops = z2_symmetries.taper(qubit_op)
       for tapered_op in tapered_ops:
           logfile.write("Number of qubits of tapered qubit operator: %d \n" % (tapered_op.num_qubits))
       
       t3 = time.time()
       logfile.write("detection of symmetries: %f [s] \n" % (t3-t2))
     
       smallest_eig_value = 99999999999999
       smallest_idx = -1
      
       for idx in range(len(tapered_ops)):
           td0 = time.time()
           from utils import retrieve_SCF_energy
           print("In sector ",idx,len(tapered_ops))
           curr_value = retrieve_SCF_energy(tapered_ops[idx].copy(),core,opt) #,parm_list)
           curr_value = np.abs(curr_value-molecule_ec.hf_energy)
           print("Deviation ",curr_value)
           if curr_value < smallest_eig_value:
              smallest_eig_value = curr_value
              smallest_idx = idx
              if(curr_value<1e-6): break
           td1 = time.time()
           val = curr_value
           logfile.write("Lowest-energy computational basis state of the {}-th tapered operator is %s %f \n" % (str(idx),val))
           logfile.write("HF search time %f: \n" % (td1-td0))
     
       the_tapered_op = tapered_ops[smallest_idx]
       the_coeff = tapered_ops[smallest_idx].z2_symmetries.tapering_values
       logfile.write("{}-th tapered operator, with corresponding symmetry sector of {}".format(smallest_idx, the_coeff))
       logfile.write("\nNumber of qubits in the {}-th tapered operator {}\n\n".format(smallest_idx,the_tapered_op.num_qubits))

       sqlist = the_tapered_op.z2_symmetries.sq_list
       z2syms = the_tapered_op.z2_symmetries

    # ========
    # setup initial state
    # ========

    init_state = HartreeFock(num_qubits=the_tapered_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'],sq_list=sqlist)

    # ---- initial parameter guess 
    init_parm = None
    if(opt["start_pt"].lower()=="file"):
       init_parm = np.loadtxt('vqe.parameters')
    if(opt["var_form"].lower()=="uccsd" and opt["start_pt"].lower()=="ccsd"):
       parm_list    = build_parameter_list(molecule_ec)

    logfile.write("Initial parameters = %d\n" % len(parm_list))
    for mu,p in enumerate(parm_list):
        logfile.write('%d %f\n' % (mu,p))

    if(opt["var_form"].lower()=="uccsd"):
        var_form = UCCSD(num_qubits=the_tapered_op.num_qubits,depth=opt["UCCSD_depth"],
                   num_orbitals=core._molecule_info['num_orbitals'],
                   num_particles=core._molecule_info['num_particles'],
                   active_occupied=opt["UCCSD_active_occupied"], active_unoccupied=opt["UCCSD_active_unoccupied"], initial_state=init_state,
                   qubit_mapping=core._qubit_mapping, two_qubit_reduction=core._two_qubit_reduction,
                   num_time_slices=opt["UCCSD_num_time_slices"],z2_symmetries=z2syms,init_parm=parm_list)

        if(opt["var_form"].lower()=="uccsd" and opt["start_pt"].lower()=="ccsd"):
           nparm,ndepth = len(var_form._mask),var_form._depth
           init_parm    = np.zeros(nparm*ndepth)
           for idp in range(ndepth):
            for ims in range(nparm):
             init_parm[ims+idp*nparm] = parm_list[var_form._mask[ims]]

        logfile.write("Selected parameters = %d\n" % nparm)
        for mu,p in enumerate(var_form._mask):
            logfile.write('%d %f\n' % (p,parm_list[p]))

    elif(opt["var_form"].lower()=="ry"):
        var_form = RY(the_tapered_op.num_qubits,depth=opt["R_depth"],
                   entanglement=opt["R_entanglement"],initial_state=HF_state)
    elif(opt["var_form"].lower()=="ryrz"):
        var_form = RYRZ(the_tapered_op.num_qubits,depth=opt["R_depth"],
                   entanglement=opt["R_entanglement"],initial_state=HF_state)
    elif(opt["var_form"].lower()=="swaprz"):
        var_form = SwapRZ(the_tapered_op.num_qubits,depth=opt["R_depth"],
                   entanglement=opt["R_entanglement"],initial_state=HF_state)
    else:
        print("invalid variational form")
        assert(False)

    # setup optimizer
    if(  opt["optimizer"].lower()=="bfgs"):  optimizer = L_BFGS_B(maxiter=opt["max_eval"])
    elif(opt["optimizer"].lower()=="cg"):    optimizer = CG(maxiter=opt["max_eval"])
    elif(opt["optimizer"].lower()=="slsqp"): optimizer = SLSQP(maxiter=opt["max_eval"])
    elif(opt["optimizer"].lower()=="spsa"):  optimizer = SPSA()
    elif(opt["optimizer"].lower()=="cobyla"): optimizer = COBYLA(maxiter=opt["max_eval"])
    else:                                    print("not coded yet"); assert(False) 

    # set vqe
    if(opt["var_form"].lower()=="uccsd"): algo = VQE(the_tapered_op,var_form,optimizer,initial_point=init_parm)
    else:                                 algo = VQE(the_tapered_op,var_form,optimizer)
    # setup backend
    backend = Aer.get_backend('statevector_simulator')
    quantum_instance = QuantumInstance(backend=backend)

    t0 = time.time()

    algo_result = algo.run(quantum_instance)

    t1 = time.time()

    logfile.write("\nVQE time [s] %f \n\n" % (t1-t0))

    result = core.process_algorithm_result(algo_result)
    for line in result[0]:
        logfile.write(line+"\n")
    
    logfile.write("\nThe parameters for UCCSD are:\n")
    for i,(tc,tq) in enumerate(zip(init_parm,algo_result['opt_params'])):
     logfile.write("%d %f %f \n" % (i,tc,tq))

    if(opt["print_parameters"]):
       par_file = open('vqe.parameters','w')
       for p in algo_result['opt_params']:
        par_file.write("%f \n" % p)
       par_file.close()

    #td0 = time.time()
    #ee = davidson(the_tapered_op,'fci')
    #td1 = time.time()
    #logfile.write("\n\nExact diagonalization, energy: %f \n" % (ee+molecule_ec.nuclear_repulsion_energy+molecule_ec.energy_offset_ec))

    #logfile.write("Davidson FCI time: %f [s] \n" % (td1-td0))
    
    print('============================================================================')
    print('                                      DONE!')
    print('============================================================================')
    

    return 0
コード例 #22
0
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'],
                         num_particles=operator.molecule_info['num_particles'],
                         initial_state=initial_state,
                         qubit_mapping=operator._qubit_mapping,
                         two_qubit_reduction=operator._two_qubit_reduction)

        algo = VQE(qubit_op, var_form, optimizer)
        result = algo.run(
            QuantumInstance(BasicAer.get_backend('statevector_simulator')))
コード例 #23
0
    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)

# setup HartreeFock state
HF_state = HartreeFock(qubitOp.num_qubits, num_spin_orbitals, num_particles,
                       map_type, qubit_reduction)

# setup UCCSD variational form
var_form = UCCSD(qubitOp.num_qubits,
                 depth=1,
                 num_orbitals=num_spin_orbitals,
                 num_particles=num_particles,
                 active_occupied=[0],
                 active_unoccupied=[0, 1],
                 initial_state=HF_state,
                 qubit_mapping=map_type,
                 two_qubit_reduction=qubit_reduction,
                 num_time_slices=1)

circuit = var_form.construct_circuit(parameters, use_basis_gates=False)
コード例 #24
0
    def test_iqpe(self, distance):
        """ iqpe test """
        self.log.debug(
            'Testing End-to-End with IQPE 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
        num_iterations = 6
        state_in = HartreeFock(qubit_op.num_qubits, num_orbitals,
                               num_particles, qubit_mapping,
                               two_qubit_reduction)
        iqpe = IQPE(qubit_op,
                    state_in,
                    num_time_slices,
                    num_iterations,
                    expansion_mode='suzuki',
                    expansion_order=2,
                    shallow_circuit_concat=True)
        backend = qiskit.BasicAer.get_backend('qasm_simulator')
        quantum_instance = QuantumInstance(backend, shots=100)

        result = iqpe.run(quantum_instance)

        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=num_iterations + 3,
                fractional_part_only=True))

        np.testing.assert_approx_equal(result['energy'],
                                       reference_energy,
                                       significant=2)
コード例 #25
0
    shift = energy_shift + repulsion_energy
    return qubitOp, num_particles, num_spin_orbitals, shift


backend = BasicAer.get_backend("statevector_simulator")
distances = np.arange(0.5)
exact_energies = []
vqe_energies = []
optimizer = SLSQP(maxiter=5)
for dist in distances:
    qubitOp, num_particles, num_spin_orbitals, shift = get_qubit_op(dist)
    result = ExactEigensolver(qubitOp).run()
    exact_energies.append(result['energy'] + shift)
    initial_state = HartreeFock(
        qubitOp.num_qubits,
        num_spin_orbitals,
        num_particles,
        'parity'
    )
    var_form = UCCSD(
        qubitOp.num_qubits,
        depth=1,
        num_orbitals=num_spin_orbitals,
        num_particles=num_particles,
        initial_state=initial_state,
        qubit_mapping='parity'
    )
    vqe = VQE(qubitOp, var_form, optimizer, 'matrix')
    results = vqe.run(backend)['energy'] + shift
    vqe_energies.append(results)
    print("Interatomic Distance:", np.round(dist, 2), "VQE Result:", results, "Exact Energy:", exact_energies[-1])
コード例 #26
0
ファイル: qEOM.py プロジェクト: paulineollitrault/COBRA
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
var_form = UCCSD(hamiltonian.num_qubits,
                 depth,
                 num_orbitals,
                 num_particles,
                 initial_state=init_state,
                 qubit_mapping=qubit_mapping,
                 two_qubit_reduction=two_qubit_reduction)

optimizer = COBYLA(maxiter=5000)

algo = VQE(hamiltonian, var_form, optimizer)