Ejemplo n.º 1
0
    def test_deprecated_qft(self):
        """Test the QPE algorithm on the deprecated QFT component."""
        qubit_op = self._dict['QUBIT_OP_SIMPLE']
        exact_eigensolver = NumPyMinimumEigensolver(qubit_op)
        results = exact_eigensolver.run()
        ref_eigenval = results.eigenvalue
        ref_eigenvec = results.eigenstate
        state_in = Custom(qubit_op.num_qubits, state_vector=ref_eigenvec)

        warnings.filterwarnings('ignore', category=DeprecationWarning)
        iqft = Standard(5)
        qpe = QPE(qubit_op,
                  state_in,
                  iqft,
                  num_time_slices=1,
                  num_ancillae=5,
                  expansion_mode='suzuki',
                  expansion_order=2,
                  shallow_circuit_concat=True)

        backend = BasicAer.get_backend('qasm_simulator')
        quantum_instance = QuantumInstance(backend,
                                           shots=100,
                                           seed_transpiler=1,
                                           seed_simulator=1)

        # run qpe
        result = qpe.run(quantum_instance)
        warnings.filterwarnings('always', category=DeprecationWarning)
        self.assertAlmostEqual(result.eigenvalue.real,
                               ref_eigenval.real,
                               delta=2e-2)
Ejemplo n.º 2
0
 def run_qpe_algo(self,
                  num_ancillae: int = 1,
                  backend: BaseBackend = None,
                  print_eig: bool = False,
                  shots: int = 1024) -> dict:
     """ Runs the QPE algorithm directly.
     
     Args:
         num_ancillae (int, optional): ancillary qubit number, the higher the more accurate, but use more computing resources. Defaults to 1.
         backend (BaseBackend, optional): Choose the backend to run this algorithm. Defaults to None.
         print_eig (bool, optional): whether or not print the eigenvalue. Defaults to False.
         shots (int, optional): Indicate how many shots to take. Defaults to 1024.
     
     Returns:
         dict: returns the results dictionary of the QPE algorithm. Use the 'energy' key to get the eigenvalue.
     """
     if backend is None:  # Default backend to Aer.get_backend('qasm_simulator').
         backend = Aer.get_backend('qasm_simulator')
     # QPE
     m, n = self.matrix.shape
     qpe = QPE(operator=MatrixOperator(matrix=self.matrix),
               state_in=Custom(m),
               iqft=Standard(num_ancillae),
               num_time_slices=50,
               num_ancillae=num_ancillae,
               expansion_mode='suzuki',
               expansion_order=2,
               shallow_circuit_concat=True)
     results = qpe.run(
         QuantumInstance(backend=backend,
                         skip_qobj_validation=False,
                         shots=shots))
     if print_eig: print("ENERGY:", results['energy'])
     return results
Ejemplo n.º 3
0
    def test_qpe(self, qubit_op, simulator, num_time_slices, n_ancillae):
        """ QPE test """
        self.log.debug('Testing QPE')
        tmp_qubit_op = qubit_op.copy()
        exact_eigensolver = ExactEigensolver(qubit_op, k=1)
        results = exact_eigensolver.run()

        ref_eigenval = results['eigvals'][0]
        ref_eigenvec = results['eigvecs'][0]
        self.log.debug('The exact eigenvalue is:       %s', ref_eigenval)
        self.log.debug('The corresponding eigenvector: %s', ref_eigenvec)

        state_in = Custom(qubit_op.num_qubits, state_vector=ref_eigenvec)
        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 = BasicAer.get_backend(simulator)
        quantum_instance = QuantumInstance(backend, shots=100)

        # run qpe
        result = qpe.run(quantum_instance)

        # report result
        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 eigenvalue from QPE:    %s', result['energy'])
        self.log.debug('reference eigenvalue:         %s', ref_eigenval)
        self.log.debug('ref eigenvalue (transformed): %s',
                       (ref_eigenval + result['translation']) *
                       result['stretch'])
        self.log.debug(
            'reference binary str label:   %s',
            decimal_to_binary((ref_eigenval.real + result['translation']) *
                              result['stretch'],
                              max_num_digits=n_ancillae + 3,
                              fractional_part_only=True))

        np.testing.assert_approx_equal(result['energy'],
                                       ref_eigenval.real,
                                       significant=2)
        self.assertEqual(tmp_qubit_op, qubit_op,
                         "Operator is modified after QPE.")
Ejemplo n.º 4
0
    def test_qpe(self, qubit_op, simulator, num_time_slices, n_ancillae):
        """Test the QPE algorithm."""
        self.log.debug('Testing QPE')
        qubit_op = self._dict[qubit_op]
        exact_eigensolver = NumPyMinimumEigensolver(qubit_op)
        results = exact_eigensolver.run()

        ref_eigenval = results.eigenvalue
        ref_eigenvec = results.eigenstate
        self.log.debug('The exact eigenvalue is:       %s', ref_eigenval)
        self.log.debug('The corresponding eigenvector: %s', ref_eigenvec)

        state_in = Custom(qubit_op.num_qubits, state_vector=ref_eigenvec)
        iqft = QFT(n_ancillae).inverse()

        qpe = QPE(qubit_op,
                  state_in,
                  iqft,
                  num_time_slices,
                  n_ancillae,
                  expansion_mode='suzuki',
                  expansion_order=2,
                  shallow_circuit_concat=True)

        backend = BasicAer.get_backend(simulator)
        quantum_instance = QuantumInstance(backend,
                                           shots=100,
                                           seed_transpiler=1,
                                           seed_simulator=1)

        # run qpe
        result = qpe.run(quantum_instance)

        # report result
        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 eigenvalue from QPE:    %s', result.eigenvalue)
        self.log.debug('reference eigenvalue:         %s', ref_eigenval)
        self.log.debug('ref eigenvalue (transformed): %s',
                       (ref_eigenval + result.translation) * result.stretch)
        self.log.debug(
            'reference binary str label:   %s',
            decimal_to_binary(
                (ref_eigenval.real + result.translation) * result.stretch,
                max_num_digits=n_ancillae + 3,
                fractional_part_only=True))

        self.assertAlmostEqual(result.eigenvalue.real,
                               ref_eigenval.real,
                               delta=2e-2)
Ejemplo n.º 5
0
    def test_qpe(self, qubit_op, simulator, num_time_slices, n_ancillae, use_circuit_library):
        """ QPE test """
        self.log.debug('Testing QPE')
        qubit_op = self._dict[qubit_op]
        exact_eigensolver = NumPyMinimumEigensolver(qubit_op)
        results = exact_eigensolver.run()

        ref_eigenval = results.eigenvalue
        ref_eigenvec = results.eigenstate
        self.log.debug('The exact eigenvalue is:       %s', ref_eigenval)
        self.log.debug('The corresponding eigenvector: %s', ref_eigenvec)

        state_in = Custom(qubit_op.num_qubits, state_vector=ref_eigenvec)
        if use_circuit_library:
            iqft = QFT(n_ancillae).inverse()
        else:
            # ignore deprecation warnings from QFTs
            warnings.filterwarnings(action="ignore", category=DeprecationWarning)
            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 = BasicAer.get_backend(simulator)
        quantum_instance = QuantumInstance(backend, shots=100)

        # run qpe
        result = qpe.run(quantum_instance)

        # report result
        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 eigenvalue from QPE:    %s', result.eigenvalue)
        self.log.debug('reference eigenvalue:         %s', ref_eigenval)
        self.log.debug('ref eigenvalue (transformed): %s',
                       (ref_eigenval + result.translation) * result.stretch)
        self.log.debug('reference binary str label:   %s', decimal_to_binary(
            (ref_eigenval.real + result.translation) * result.stretch,
            max_num_digits=n_ancillae + 3,
            fractional_part_only=True
        ))

        np.testing.assert_approx_equal(result.eigenvalue.real, ref_eigenval.real, significant=2)

        if not use_circuit_library:
            warnings.filterwarnings(action="always", category=DeprecationWarning)
Ejemplo n.º 6
0
import numpy as np
from qiskit.quantum_info import Operator
from qiskit.extensions import HamiltonianGate
from qiskit.aqua.operators.legacy import MatrixOperator
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import QPE
from qiskit import Aer
from qiskit.visualization import circuit_drawer
from qiskit.aqua.components.initial_states import Custom
A = .25 * np.array([[15, 9, 5, -3], [9, 15, 3, -5], [5, 3, 15, -9],
                    [-3, -5, -9, 15]])
t0 = 2 * np.pi
#expA = la.expm(-1.j * A * t0)
op = MatrixOperator(A)
vector = [1 / 2, 1 / 2, 1 / 2, 1 / 2]
init_state = Custom(2, state_vector=vector)
algo = QPE(operator=op, state_in=init_state)

result = algo.run(QuantumInstance(Aer.get_backend('qasm_simulator')))
print(result)
Ejemplo n.º 7
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 = NumPyMinimumEigensolver(qubit_op)
        results = exact_eigensolver.run()
        reference_energy = results.eigenvalue.real
        self.log.debug('The exact ground state energy is: %s',
                       results.eigenvalue.real)

        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(num_orbitals, num_particles, qubit_mapping,
                               two_qubit_reduction)
        iqft = QFT(n_ancillae).inverse()

        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('eigenstate:                  %s', result.eigenstate)
        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.eigenvalue.real)
        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.eigenvalue.real,
                                       reference_energy,
                                       significant=2)
Ejemplo n.º 8
0
    def test_qpe(self, qubit_op, simulator, num_time_slices, n_ancillae):
        """ QPE test """
        self.log.debug('Testing QPE')
        tmp_qubit_op = qubit_op.copy()
        exact_eigensolver = ExactEigensolver(qubit_op, k=1)
        results = exact_eigensolver.run()

        ref_eigenval = results['eigvals'][0]
        ref_eigenvec = results['eigvecs'][0]
        self.log.debug('The exact eigenvalue is:       %s', ref_eigenval)
        self.log.debug('The corresponding eigenvector: %s', ref_eigenvec)

        state_in = Custom(qubit_op.num_qubits, state_vector=ref_eigenvec)
        iqft = Standard(n_ancillae)

        qpe = QPE(qubit_op, iqft, state_in=state_in, num_time_slices=num_time_slices, num_ancillae=n_ancillae,
                  expansion_mode='suzuki', expansion_order=2,
                  shallow_circuit_concat=True)

        backend = BasicAer.get_backend(simulator)
        quantum_instance = QuantumInstance(backend, shots=100)

        # run qpe
        result = qpe.run(quantum_instance)

        # report result
        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 eigenvalue from QPE:    %s', result['energy'])
        self.log.debug('reference eigenvalue:         %s', ref_eigenval)
        self.log.debug('ref eigenvalue (transformed): %s',
                       (ref_eigenval + result['translation']) * result['stretch'])
        self.log.debug('reference binary str label:   %s', decimal_to_binary(
            (ref_eigenval.real + result['translation']) * result['stretch'],
            max_num_digits=n_ancillae + 3,
            fractional_part_only=True
        ))

        np.testing.assert_approx_equal(result['energy'], ref_eigenval.real, significant=2)
        self.assertEqual(tmp_qubit_op, qubit_op, "Operator is modified after QPE.")

        #Re-run, now with state_in_circuit_factory
        superpose_state_and_flip = FlipSuperposition(state_in)
    
        qpe = QPE(qubit_op, iqft, state_in_circuit_factory=superpose_state_and_flip, num_time_slices=num_time_slices, num_ancillae=n_ancillae, expansion_mode='suzuki', expansion_order=2, shallow_circuit_concat=True)

        backend = BasicAer.get_backend(simulator)
        quantum_instance = QuantumInstance(backend, shots=100)

        # run qpe
        result = qpe.run(quantum_instance)

        ancilla_counts = result["ancilla_counts"]
        if simulator=="qasm_simulator":
            self.assertEqual(result['top_measurement_label'], sorted([(ancilla_counts[k], k) for k in ancilla_counts])[::-1][0][-1][::-1])
        else:
            self.assertEqual(len(ancilla_counts), 1<<n_ancillae)
            
        self.assertEqual(len(result["aux_counts"]), 1<<superpose_state_and_flip.required_ancillas()) 
Ejemplo n.º 9
0
    def test_qpe(self, qubitOp, simulator):
        self.algorithm = 'QPE'
        self.log.debug('Testing QPE')

        self.qubitOp = qubitOp

        exact_eigensolver = ExactEigensolver(self.qubitOp, k=1)
        results = exact_eigensolver.run()

        w = results['eigvals']
        v = results['eigvecs']

        self.qubitOp.to_matrix()
        np.testing.assert_almost_equal(self.qubitOp._matrix @ v[0],
                                       w[0] * v[0])
        np.testing.assert_almost_equal(
            expm(-1.j * sparse.csc_matrix(self.qubitOp._matrix)) @ v[0],
            np.exp(-1.j * w[0]) * v[0])

        self.ref_eigenval = w[0]
        self.ref_eigenvec = v[0]
        self.log.debug('The exact eigenvalue is:       {}'.format(
            self.ref_eigenval))
        self.log.debug('The corresponding eigenvector: {}'.format(
            self.ref_eigenvec))

        num_time_slices = 50
        n_ancillae = 6

        state_in = Custom(self.qubitOp.num_qubits,
                          state_vector=self.ref_eigenvec)
        iqft = Standard(n_ancillae)

        qpe = QPE(self.qubitOp,
                  state_in,
                  iqft,
                  num_time_slices,
                  n_ancillae,
                  expansion_mode='suzuki',
                  expansion_order=2,
                  shallow_circuit_concat=True)

        backend = BasicAer.get_backend(simulator)
        quantum_instance = QuantumInstance(backend,
                                           shots=100,
                                           pass_manager=PassManager())

        # run qpe
        result = qpe.run(quantum_instance)
        # self.log.debug('transformed operator paulis:\n{}'.format(self.qubitOp.print_operators('paulis')))

        # report result
        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 eigenvalue from QPE:    {}'.format(
            result['energy']))
        self.log.debug('reference eigenvalue:         {}'.format(
            self.ref_eigenval))
        self.log.debug('ref eigenvalue (transformed): {}'.format(
            (self.ref_eigenval + result['translation']) * result['stretch']))
        self.log.debug('reference binary str label:   {}'.format(
            decimal_to_binary(
                (self.ref_eigenval.real + result['translation']) *
                result['stretch'],
                max_num_digits=n_ancillae + 3,
                fractional_part_only=True)))

        np.testing.assert_approx_equal(result['energy'],
                                       self.ref_eigenval.real,
                                       significant=2)
Ejemplo n.º 10
0
          shallow_circuit_concat=True)

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

# IBM Q
from qiskit import IBMQ
provider0 = IBMQ.load_account()
#large_enough_devices = IBMQ.backends(filters=lambda x: x.configuration().n_qubits > qubit_op.num_qubits and not x.configuration().simulator)
backend = provider0.get_backend('ibmq_16_melbourne')
#backend = provider0.get_backend('ibmq_qasm_simulator')
#ibmq_16_melbourne
#ibmqx2
#ibmqx4
#ibmq_qasm_simulator

print("Backend:", backend)

quantum_instance = QuantumInstance(backend,
                                   shots=1000,
                                   pass_manager=PassManager())
result_qpe = qpe.run(quantum_instance)
t_final = time.time()
print('The ground state energy as computed by QPE is: {} eV'.format(
    result_qpe['energy'] * 27.21138506))
print("...")
print('Difference: {}'.format(
    (result_qpe['energy'] - result_ee['energy']) * 27.21138506))
print(result_qpe)
print("Run time: {:.2f} seconds".format(t_final - t_initial))