コード例 #1
0
    def _build_operator(
            self, func_dict: Dict[Union[int, Tuple[int, int]],
                                  int]) -> QuantumCircuit:
        """Creates a circuit for the state preparation operator.

        Args:
            func_dict: Representation of the QUBO problem. The keys should be subscripts of the
                coefficients (e.g. x_1 -> 1), with the constant (if present) being represented with
                a key of -1 (i.e. d[-1] = constant). Quadratic coefficients should use a tuple for
                the key, with the corresponding subscripts inside (e.g. 2*x_1*x_2 -> d[(1,2)]=2).

        Returns:
            Circuit object describing the state preparation operator.
        """

        # Build initial circuit.
        key_val = QuantumRegister(self._num_key + self._num_value, "key_value")
        circuit = QuantumCircuit(key_val)
        if self._measurement:
            measure = ClassicalRegister(self._num_key + self._num_value)
            circuit.add_register(measure)
        circuit.h(key_val)

        # Linear Coefficients.
        for i in range(self._num_value):
            if func_dict.get(-1, 0) != 0:
                circuit.u1(
                    1 / 2**self._num_value * 2 * np.pi * 2**i * func_dict[-1],
                    key_val[self._num_key + i])
            for j in range(self._num_key):
                if func_dict.get(j, 0) != 0:
                    circuit.cu1(
                        1 / 2**self._num_value * 2 * np.pi * 2**i *
                        func_dict[j], key_val[j], key_val[self._num_key + i])

        # Quadratic Coefficients.
        for i in range(self._num_value):
            for k, v in func_dict.items():
                if isinstance(k, tuple):
                    circuit.mcu1(1 / 2**self._num_value * 2 * np.pi * 2**i * v,
                                 [key_val[k[0]], key_val[k[1]]],
                                 key_val[self._num_key + i])

        # Add IQFT.
        iqft = IQFT(self._num_value)
        value = [
            key_val[v]
            for v in range(self._num_key, self._num_key + self._num_value)
        ]
        iqft.construct_circuit(qubits=value, circuit=circuit)

        return circuit
コード例 #2
0
    def test_qae_circuit(self, efficient_circuit):
        """Test circuits resulting from canonical amplitude estimation.

        Build the circuit manually and from the algorithm and compare the resulting unitaries.
        """
        prob = 0.5

        for m in range(2, 7):
            qae = AmplitudeEstimation(m, a_factory=BernoulliAFactory(prob))
            angle = 2 * np.arcsin(np.sqrt(prob))

            # manually set up the inefficient AE circuit
            q_ancilla = QuantumRegister(m, 'a')
            q_objective = QuantumRegister(1, 'q')
            circuit = QuantumCircuit(q_ancilla, q_objective)

            # initial Hadamard gates
            for i in range(m):
                circuit.h(q_ancilla[i])

            # A operator
            circuit.ry(angle, q_objective)

            if efficient_circuit:
                qae.q_factory = BernoulliQFactory(qae.a_factory)
                for power in range(m):
                    circuit.cry(2 * 2**power * angle, q_ancilla[power],
                                q_objective[0])

            else:
                q_factory = QFactory(qae.a_factory, i_objective=0)
                for power in range(m):
                    for _ in range(2**power):
                        q_factory.build_controlled(circuit, q_objective,
                                                   q_ancilla[power])

            # fourier transform
            iqft = Standard(m)
            circuit = iqft.construct_circuit(qubits=q_ancilla,
                                             circuit=circuit,
                                             do_swaps=False)
            expected_unitary = self._unitary.execute(circuit).get_unitary()

            actual_circuit = qae.construct_circuit(measurement=False)
            actual_unitary = self._unitary.execute(
                actual_circuit).get_unitary()

            diff = np.sum(np.abs(actual_unitary - expected_unitary))
            self.assertAlmostEqual(diff, 0)
コード例 #3
0
ファイル: ae.py プロジェクト: sorin-bolos/qiskit-aqua
    def __init__(self,
                 num_eval_qubits: int,
                 a_factory: Optional[CircuitFactory] = None,
                 q_factory: Optional[CircuitFactory] = None,
                 i_objective: Optional[int] = None,
                 iqft: Optional[IQFT] = None) -> None:
        r"""
        Args:
            num_eval_qubits: Number of evaluation qubits, has a min. value of 1.
            a_factory: The CircuitFactory subclass object representing the problem unitary.
            q_factory: The CircuitFactory subclass object representing an amplitude estimation
                sample (based on a_factory).
            i_objective: The index of the objective qubit, i.e. the qubit marking 'good' solutions
                with the state \|1> and 'bad' solutions with the state \|0>.
            iqft: The Inverse Quantum Fourier Transform component, defaults to using a standard IQFT
                when None
        """
        validate_min('num_eval_qubits', num_eval_qubits, 1)
        super().__init__(a_factory, q_factory, i_objective)

        # get parameters
        self._m = num_eval_qubits
        self._M = 2**num_eval_qubits

        if iqft is None:
            iqft = Standard(self._m)

        self._iqft = iqft
        self._circuit = None
        self._ret = {}
コード例 #4
0
    def __init__(self, num_eval_qubits: int,
                 a_factory: Optional[CircuitFactory] = None,
                 i_objective: Optional[int] = None,
                 q_factory: Optional[CircuitFactory] = None,
                 iqft: Optional[IQFT] = None) -> None:
        """

        Args:
            num_eval_qubits: number of evaluation qubits, has a min. value of 1.
            a_factory: the CircuitFactory subclass object representing
                                        the problem unitary
            i_objective: i objective
            q_factory: the CircuitFactory subclass object representing an
                                        amplitude estimation sample (based on a_factory)
            iqft: the Inverse Quantum Fourier Transform component,
                         defaults to using a standard iqft when None
        """
        validate_min('num_eval_qubits', num_eval_qubits, 1)
        super().__init__(a_factory, q_factory, i_objective)

        # get parameters
        self._m = num_eval_qubits
        self._M = 2 ** num_eval_qubits

        if iqft is None:
            iqft = Standard(self._m)

        self._iqft = iqft
        self._circuit = None
        self._ret = {}
コード例 #5
0
ファイル: test_qpe.py プロジェクト: wifineural/qiskit-aqua
    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)
コード例 #6
0
    def __init__(self,
                 num_eval_qubits,
                 a_factory=None,
                 i_objective=None,
                 q_factory=None,
                 iqft=None):
        """

        Args:
            num_eval_qubits (int): number of evaluation qubits
            a_factory (CircuitFactory): the CircuitFactory subclass object representing
                                        the problem unitary
            i_objective (int): i objective
            q_factory (CircuitFactory): the CircuitFactory subclass object representing an
                                        amplitude estimation sample (based on a_factory)
            iqft (IQFT): the Inverse Quantum Fourier Transform component,
                         defaults to using a standard iqft when None
        """
        validate(locals(), self._INPUT_SCHEMA)
        super().__init__(a_factory, q_factory, i_objective)

        # get parameters
        self._m = num_eval_qubits
        self._M = 2**num_eval_qubits

        if iqft is None:
            iqft = Standard(self._m)

        self._iqft = iqft
        self._circuit = None
        self._ret = {}
コード例 #7
0
 def execute_qpe_circuit(self,
                         num_ancillae: int = 1,
                         backend: BaseBackend = None,
                         shots: int = 1024,
                         print_eig: bool = False) -> Result:
     """Runs the QPE algorithm by constructing the circuit explicitly.
     
     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.
         shots (int, optional): Indicate how many shots to take. Defaults to 1024.
         print_eig (bool, optional): whether or not print the eigenvalue. Defaults to False.
     
     Returns:
         Result: returns a Qiskit.result object. Use get_counts() to get a dictionary for the qubits' probabilities.
     """
     if backend is None:  # Default backend to Aer.get_backend('qasm_simulator').
         backend = Aer.get_backend('qasm_simulator')
     # QPE Circuit
     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 = execute(qpe.construct_circuit(measurement=True),
                       backend=backend).result()
     if print_eig: print(results.get_counts())
     return results
コード例 #8
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)
コード例 #9
0
ファイル: ae.py プロジェクト: lchmo444/qiskit-aqua
    def __init__(self, num_eval_qubits, a_factory, q_factory=None, iqft=None):
        """
        Constructor.

        Args:
            num_eval_qubits (int): number of evaluation qubits
            a_factory (CircuitFactory): the CircuitFactory subclass object representing the problem unitary
            q_factory (CircuitFactory): the CircuitFactory subclass object representing an amplitude estimation sample (based on a_factory)
            iqft (IQFT): the Inverse Quantum Fourier Transform pluggable component, defaults to using a standard iqft when None
        """
        self.validate(locals())
        super().__init__()

        # get/construct A/Q operator
        self.a_factory = a_factory
        if q_factory is None:
            self.q_factory = QFactory(a_factory)
        else:
            self.q_factory = q_factory

        # get parameters
        self._m = num_eval_qubits
        self._M = 2**num_eval_qubits

        # determine number of ancillas
        self._num_ancillas = self.q_factory.required_ancillas_controlled()
        self._num_qubits = self.a_factory.num_target_qubits + self._m + self._num_ancillas

        if iqft is None:
            iqft = Standard(self._m)

        self._iqft = iqft
        self._circuit = None
        self._ret = {}
コード例 #10
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
コード例 #11
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)
コード例 #12
0
ファイル: test_qpe.py プロジェクト: ystallonne/qiskit-aqua
    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.")
コード例 #13
0
ファイル: test_qpe.py プロジェクト: tachyoniks/qiskit-aqua
    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)
コード例 #14
0
    def test_deprecated_qft(self):
        """Test running QAE on the deprecated QFT."""
        prob = 0.2
        a_factory = BernoulliAFactory(prob)
        q_factory = BernoulliQFactory(a_factory)

        warnings.filterwarnings('ignore', category=DeprecationWarning)
        iqft = Standard(2)
        qae = AmplitudeEstimation(2,
                                  a_factory=a_factory,
                                  q_factory=q_factory,
                                  iqft=iqft)

        result = qae.run(self._statevector)
        warnings.filterwarnings('always', category=DeprecationWarning)

        expected = {'estimation': 0.5, 'mle': 0.2}
        for key, value in expected.items():
            self.assertAlmostEqual(value,
                                   result[key],
                                   places=3,
                                   msg="estimate `{}` failed".format(key))
コード例 #15
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()) 
コード例 #16
0
ファイル: test_qpe.py プロジェクト: alfrisch/qiskit-aqua
    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)
コード例 #17
0
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
from qiskit import IBMQ