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)
Ejemplo n.º 2
0
 def calc_classical_eig(self,
                        print_results: bool = False,
                        solver: str = "exact_solver") -> list:
     """ Prints Eigenvalues generated by the selected classical algorithm.
     
     Args:
         print_results (bool, optional): print the eigenvalues or not. Defaults to False.
         solver (str, optional): can be "exact_solver" or "numpy". Defaults to "exact_solver"
     """
     results = []
     print("=======TRADITIONAL=======")
     if solver == "exact_solver":
         # Classical Eigensolver in Qiskit
         eig_solver = ExactEigensolver(MatrixOperator(self.matrix), 2)
         results = eig_solver.run()['eigvals']
         print("EXACTSOLVER:", results)
     elif solver == "numpy":
         # Classical Eigenvalue Decomposition in NumPy
         results = list(np.linalg.eig(self.matrix)[0])
         print("EIGENVALUES:", results)
         # print("EIGENVECTORS:", list(list(item) for item in np.linalg.eig(matrix)[1]))
     else:
         print("No solver found. Check your solver name.")
     print("=========================")
     return results
Ejemplo n.º 3
0
    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)
Ejemplo n.º 4
0
    def _run_driver(driver, transformation=TransformationType.FULL,
                    qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False,
                    freeze_core=True):
        qmolecule = driver.run()

        core = Hamiltonian(transformation=transformation,
                           qubit_mapping=qubit_mapping,
                           two_qubit_reduction=two_qubit_reduction,
                           freeze_core=freeze_core,
                           orbital_reduction=[])

        qubit_op, aux_ops = core.run(qmolecule)

        exact_eigensolver = ExactEigensolver(qubit_op, aux_operators=aux_ops, k=1)
        _, result = core.process_algorithm_result(exact_eigensolver.run())
        return result
    algo = VQE(qubit_op,
               var_form,
               optimizer,
               callback=store_intermediate_result)
    quantum_instance = QuantumInstance(backend=backend)
    algo_result = algo.run(quantum_instance)
    converge_cnts[i] = np.asarray(counts)
    converge_vals[i] = np.asarray(values)
    param_vals[i] = np.asarray(params)
print('\rOptimization complete      ')

# In[12]:

ee = ExactEigensolver(qubit_op)
result = ee.run()
ref = result['energy']
print('Reference value: {}'.format(ref))

# In[13]:

plt.figure(figsize=(10, 5))
for i in range(len(optimizers)):
    plt.plot(converge_cnts[i],
             abs(ref - converge_vals[i]),
             label=optimizers[i].__name__)
plt.xlabel('Eval count')
plt.ylabel('Energy difference from solution reference value')
plt.title('Energy convergence for various optimizers')
plt.yscale('log')
plt.legend(loc='upper right')