Exemplo n.º 1
0
class TestBernoulli(QiskitAquaTestCase):
    """ Test Bernoulli """
    def setUp(self):
        super().setUp()

        self._statevector = QuantumInstance(
            backend=BasicAer.get_backend('statevector_simulator'),
            seed_simulator=2,
            seed_transpiler=2)

        def qasm(shots=100):
            return QuantumInstance(
                backend=BasicAer.get_backend('qasm_simulator'),
                shots=shots,
                seed_simulator=2,
                seed_transpiler=2)

        self._qasm = qasm

    @parameterized.expand(
        [[0.2, AmplitudeEstimation(2), {
            'estimation': 0.5,
            'mle': 0.2
        }], [0.4,
             AmplitudeEstimation(4), {
                 'estimation': 0.30866,
                 'mle': 0.4
             }],
         [0.82,
          AmplitudeEstimation(5), {
              'estimation': 0.85355,
              'mle': 0.82
          }], [0.49,
               AmplitudeEstimation(3), {
                   'estimation': 0.5,
                   'mle': 0.49
               }],
         [0.2,
          MaximumLikelihoodAmplitudeEstimation(2), {
              'estimation': 0.2
          }],
         [0.4,
          MaximumLikelihoodAmplitudeEstimation(4), {
              'estimation': 0.4
          }],
         [0.82,
          MaximumLikelihoodAmplitudeEstimation(5), {
              'estimation': 0.82
          }],
         [0.49,
          MaximumLikelihoodAmplitudeEstimation(3), {
              'estimation': 0.49
          }],
         [0.2,
          IterativeAmplitudeEstimation(0.1, 0.1), {
              'estimation': 0.2
          }],
         [
             0.4,
             IterativeAmplitudeEstimation(0.00001, 0.01), {
                 'estimation': 0.4
             }
         ],
         [
             0.82,
             IterativeAmplitudeEstimation(0.00001, 0.05), {
                 'estimation': 0.82
             }
         ],
         [
             0.49,
             IterativeAmplitudeEstimation(0.001, 0.01), {
                 'estimation': 0.49
             }
         ]])
    def test_statevector(self, prob, a_e, expect):
        """ statevector test """
        # construct factories for A and Q
        a_e.a_factory = BernoulliAFactory(prob)
        a_e.q_factory = BernoulliQFactory(a_e.a_factory)

        result = a_e.run(self._statevector)

        for key, value in expect.items():
            self.assertAlmostEqual(value,
                                   result[key],
                                   places=3,
                                   msg="estimate `{}` failed".format(key))

    @parameterized.expand([[
        0.2, 100,
        AmplitudeEstimation(4), {
            'estimation': 0.14644,
            'mle': 0.193888
        }
    ], [0.0, 1000,
        AmplitudeEstimation(2), {
            'estimation': 0.0,
            'mle': 0.0
        }],
                           [
                               0.8, 10,
                               AmplitudeEstimation(7), {
                                   'estimation': 0.79784,
                                   'mle': 0.801612
                               }
                           ],
                           [
                               0.2, 100,
                               MaximumLikelihoodAmplitudeEstimation(4), {
                                   'estimation': 0.199606
                               }
                           ],
                           [
                               0.4, 1000,
                               MaximumLikelihoodAmplitudeEstimation(6), {
                                   'estimation': 0.399488
                               }
                           ],
                           [
                               0.8, 10,
                               MaximumLikelihoodAmplitudeEstimation(7), {
                                   'estimation': 0.800926
                               }
                           ],
                           [
                               0.2, 100,
                               IterativeAmplitudeEstimation(0.0001, 0.01), {
                                   'estimation': 0.199987
                               }
                           ],
                           [
                               0.4, 1000,
                               IterativeAmplitudeEstimation(0.001, 0.05), {
                                   'estimation': 0.400071
                               }
                           ],
                           [
                               0.8, 10,
                               IterativeAmplitudeEstimation(0.1, 0.05), {
                                   'estimation': 0.811711
                               }
                           ]])
    def test_qasm(self, prob, shots, a_e, expect):
        """ qasm test """
        # construct factories for A and Q
        a_e.a_factory = BernoulliAFactory(prob)
        a_e.q_factory = BernoulliQFactory(a_e.a_factory)

        result = a_e.run(self._qasm(shots))

        for key, value in expect.items():
            self.assertAlmostEqual(value,
                                   result[key],
                                   places=3,
                                   msg="estimate `{}` failed".format(key))
class TestBernoulli(QiskitAquaTestCase):
    """Tests based on the Bernoulli A operator.

    This class tests
        * the estimation result
        * the constructed circuits
    """

    def setUp(self):
        super().setUp()
        warnings.filterwarnings(action="ignore", category=DeprecationWarning)

        self._statevector = QuantumInstance(backend=BasicAer.get_backend('statevector_simulator'),
                                            seed_simulator=2, seed_transpiler=2)

        self._unitary = QuantumInstance(backend=BasicAer.get_backend('unitary_simulator'), shots=1,
                                        seed_simulator=42, seed_transpiler=91)

        def qasm(shots=100):
            return QuantumInstance(backend=BasicAer.get_backend('qasm_simulator'), shots=shots,
                                   seed_simulator=2, seed_transpiler=2)

        self._qasm = qasm

    def tearDown(self):
        super().tearDown()
        warnings.filterwarnings(action="always", category=DeprecationWarning)

    @idata([
        [0.2, AmplitudeEstimation(2), {'estimation': 0.5, 'mle': 0.2}],
        [0.4, AmplitudeEstimation(4), {'estimation': 0.30866, 'mle': 0.4}],
        [0.82, AmplitudeEstimation(5), {'estimation': 0.85355, 'mle': 0.82}],
        [0.49, AmplitudeEstimation(3), {'estimation': 0.5, 'mle': 0.49}],
        [0.2, MaximumLikelihoodAmplitudeEstimation(2), {'estimation': 0.2}],
        [0.4, MaximumLikelihoodAmplitudeEstimation(4), {'estimation': 0.4}],
        [0.82, MaximumLikelihoodAmplitudeEstimation(5), {'estimation': 0.82}],
        [0.49, MaximumLikelihoodAmplitudeEstimation(3), {'estimation': 0.49}],
        [0.2, IterativeAmplitudeEstimation(0.1, 0.1), {'estimation': 0.2}],
        [0.4, IterativeAmplitudeEstimation(0.00001, 0.01), {'estimation': 0.4}],
        [0.82, IterativeAmplitudeEstimation(0.00001, 0.05), {'estimation': 0.82}],
        [0.49, IterativeAmplitudeEstimation(0.001, 0.01), {'estimation': 0.49}]
    ])
    @unpack
    def test_statevector(self, prob, qae, expect):
        """Test running QAE using the statevector simulator."""
        # construct factories for A and Q
        qae.a_factory = BernoulliAFactory(prob)
        qae.q_factory = BernoulliQFactory(qae.a_factory)

        result = qae.run(self._statevector)

        for key, value in expect.items():
            self.assertAlmostEqual(value, result[key], places=3,
                                   msg="estimate `{}` failed".format(key))

    @idata([
        [0.2, 100, AmplitudeEstimation(4), {'estimation': 0.14644, 'mle': 0.193888}],
        [0.0, 1000, AmplitudeEstimation(2), {'estimation': 0.0, 'mle': 0.0}],
        [0.8, 10, AmplitudeEstimation(7), {'estimation': 0.79784, 'mle': 0.801612}],
        [0.2, 100, MaximumLikelihoodAmplitudeEstimation(4), {'estimation': 0.199606}],
        [0.4, 1000, MaximumLikelihoodAmplitudeEstimation(6), {'estimation': 0.399488}],
        # [0.8, 10, MaximumLikelihoodAmplitudeEstimation(7), {'estimation': 0.800926}],
        [0.2, 100, IterativeAmplitudeEstimation(0.0001, 0.01), {'estimation': 0.199987}],
        [0.4, 1000, IterativeAmplitudeEstimation(0.001, 0.05), {'estimation': 0.400071}],
        [0.8, 10, IterativeAmplitudeEstimation(0.1, 0.05), {'estimation': 0.811711}]
    ])
    @unpack
    def test_qasm(self, prob, shots, qae, expect):
        """ qasm test """
        # construct factories for A and Q
        qae.a_factory = BernoulliAFactory(prob)
        qae.q_factory = BernoulliQFactory(qae.a_factory)

        result = qae.run(self._qasm(shots))

        for key, value in expect.items():
            self.assertAlmostEqual(value, result[key], places=3,
                                   msg="estimate `{}` failed".format(key))

    @data(True, False)
    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 = QFT(m, do_swaps=False).inverse()
            circuit.append(iqft.to_instruction(), q_ancilla)

            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)

    @data(True, False)
    def test_iqae_circuits(self, efficient_circuit):
        """Test circuits resulting from iterative amplitude estimation.

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

        for k in range(2, 7):
            qae = IterativeAmplitudeEstimation(0.01, 0.05, a_factory=BernoulliAFactory(prob))
            angle = 2 * np.arcsin(np.sqrt(prob))

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

            # A operator
            circuit.ry(angle, q_objective)

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

            else:
                q_factory = QFactory(qae.a_factory, i_objective=0)
                for _ in range(k):
                    q_factory.build(circuit, q_objective)

            expected_unitary = self._unitary.execute(circuit).get_unitary()

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

            diff = np.sum(np.abs(actual_unitary - expected_unitary))
            self.assertAlmostEqual(diff, 0)

    @data(True, False)
    def test_mlae_circuits(self, efficient_circuit):
        """ Test the circuits constructed for MLAE """
        prob = 0.5

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

            # compute all the circuits used for MLAE
            circuits = []

            # 0th power
            q_objective = QuantumRegister(1, 'q')
            circuit = QuantumCircuit(q_objective)
            circuit.ry(angle, q_objective)
            circuits += [circuit]

            # powers of 2
            for power in range(k):
                q_objective = QuantumRegister(1, 'q')
                circuit = QuantumCircuit(q_objective)

                # A operator
                circuit.ry(angle, q_objective)

                # Q^(2^j) operator
                if efficient_circuit:
                    qae.q_factory = BernoulliQFactory(qae.a_factory)
                    circuit.ry(2 * 2 ** power * angle, q_objective[0])

                else:
                    q_factory = QFactory(qae.a_factory, i_objective=0)
                    for _ in range(2**power):
                        q_factory.build(circuit, q_objective)

            actual_circuits = qae.construct_circuits(measurement=False)

            for actual, expected in zip(actual_circuits, circuits):
                expected_unitary = self._unitary.execute(expected).get_unitary()
                actual_unitary = self._unitary.execute(actual).get_unitary()
                diff = np.sum(np.abs(actual_unitary - expected_unitary))
                self.assertAlmostEqual(diff, 0)
class TestSineIntegral(QiskitAquaTestCase):
    """Tests based on the A operator to integrate sin^2(x).

    This class tests
        * the estimation result
        * the confidence intervals
    """
    def setUp(self):
        super().setUp()
        self._statevector = QuantumInstance(
            backend=BasicAer.get_backend('statevector_simulator'),
            seed_simulator=123,
            seed_transpiler=41)

        def qasm(shots=100):
            return QuantumInstance(
                backend=BasicAer.get_backend('qasm_simulator'),
                shots=shots,
                seed_simulator=7192,
                seed_transpiler=90000)

        self._qasm = qasm

    @idata([
        [2, AmplitudeEstimation(2), {
            'estimation': 0.5,
            'mle': 0.270290
        }],
        [4,
         MaximumLikelihoodAmplitudeEstimation(4), {
             'estimation': 0.272675
         }],
        [3,
         IterativeAmplitudeEstimation(0.1, 0.1), {
             'estimation': 0.272082
         }],
    ])
    @unpack
    def test_statevector(self, n, qae, expect):
        """ Statevector end-to-end test """
        # construct factories for A and Q
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore', category=DeprecationWarning)
            qae.a_factory = SineIntegralAFactory(n)

        result = qae.run(self._statevector)

        for key, value in expect.items():
            self.assertAlmostEqual(value,
                                   result[key],
                                   places=3,
                                   msg="estimate `{}` failed".format(key))

    @idata([
        [4, 10,
         AmplitudeEstimation(2), {
             'estimation': 0.5,
             'mle': 0.333333
         }],
        [
            3, 10,
            MaximumLikelihoodAmplitudeEstimation(2), {
                'estimation': 0.256878
            }
        ],
        [
            3, 1000,
            IterativeAmplitudeEstimation(0.01, 0.01), {
                'estimation': 0.271790
            }
        ],
    ])
    @unpack
    def test_qasm(self, n, shots, qae, expect):
        """QASM simulator end-to-end test."""
        # construct factories for A and Q
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore', category=DeprecationWarning)
            qae.a_factory = SineIntegralAFactory(n)

        result = qae.run(self._qasm(shots))

        for key, value in expect.items():
            self.assertAlmostEqual(value,
                                   result[key],
                                   places=3,
                                   msg="estimate `{}` failed".format(key))

    @idata([
        [
            AmplitudeEstimation(3), 'mle', {
                'likelihood_ratio': [0.24947346406470136, 0.3003771197734433],
                'fisher': [0.24861769995820207, 0.2999286066724035],
                'observed_fisher': [0.24845622030041542, 0.30009008633019013]
            }
        ],
        [
            MaximumLikelihoodAmplitudeEstimation(3), 'estimation', {
                'likelihood_ratio': [0.25987941798909114, 0.27985361366769945],
                'fisher': [0.2584889015125656, 0.2797018754936686],
                'observed_fisher': [0.2659279996107888, 0.2722627773954454]
            }
        ],
    ])
    @unpack
    def test_confidence_intervals(self, qae, key, expect):
        """End-to-end test for all confidence intervals."""
        n = 3
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore', category=DeprecationWarning)
            qae.a_factory = SineIntegralAFactory(n)

        # statevector simulator
        result = qae.run(self._statevector)
        methods = ['lr', 'fi',
                   'oi']  # short for likelihood_ratio, fisher, observed_fisher
        alphas = [0.1, 0.00001, 0.9]  # alpha shouldn't matter in statevector
        for alpha, method in zip(alphas, methods):
            confint = qae.confidence_interval(alpha, method)
            # confidence interval based on statevector should be empty, as we are sure of the result
            self.assertAlmostEqual(confint[1] - confint[0], 0.0)
            self.assertAlmostEqual(confint[0], result[key])

        # qasm simulator
        shots = 100
        alpha = 0.01
        result = qae.run(self._qasm(shots))
        for method, expected_confint in expect.items():
            confint = qae.confidence_interval(alpha, method)
            np.testing.assert_almost_equal(confint,
                                           expected_confint,
                                           decimal=10)
            self.assertTrue(confint[0] <= result[key] <= confint[1])

    def test_iqae_confidence_intervals(self):
        """End-to-end test for the IQAE confidence interval."""
        n = 3
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore', category=DeprecationWarning)
            qae = IterativeAmplitudeEstimation(
                0.1, 0.01, a_factory=SineIntegralAFactory(n))
        expected_confint = [0.19840508760087738, 0.35110155403424115]

        # statevector simulator
        result = qae.run(self._statevector)
        confint = result['confidence_interval']
        # confidence interval based on statevector should be empty, as we are sure of the result
        self.assertAlmostEqual(confint[1] - confint[0], 0.0)
        self.assertAlmostEqual(confint[0], result['estimation'])

        # qasm simulator
        shots = 100
        result = qae.run(self._qasm(shots))
        confint = result['confidence_interval']
        self.assertEqual(confint, expected_confint)
        self.assertTrue(confint[0] <= result['estimation'] <= confint[1])
class TestProblemSetting(QiskitAquaTestCase):
    """Test the setting and getting of the A and Q operator and the objective qubit index."""
    def setUp(self):
        super().setUp()
        self.a_bernoulli = BernoulliAFactory(0)
        self.q_bernoulli = BernoulliQFactory(self.a_bernoulli)
        self.i_bernoulli = 0

        num_qubits = 5
        self.a_integral = SineIntegralAFactory(num_qubits)
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore', category=DeprecationWarning)
            self.q_integral = QFactory(self.a_integral, num_qubits)
        self.i_integral = num_qubits

    @idata([
        [AmplitudeEstimation(2)],
        [IterativeAmplitudeEstimation(0.1, 0.001)],
        [MaximumLikelihoodAmplitudeEstimation(3)],
    ])
    @unpack
    def test_operators(self, qae):
        """ Test if A/Q operator + i_objective set correctly """
        warnings.filterwarnings('ignore', category=DeprecationWarning)
        self.assertIsNone(qae.a_factory)
        self.assertIsNone(qae.q_factory)
        self.assertIsNone(qae.i_objective)
        self.assertIsNone(qae._a_factory)
        self.assertIsNone(qae._q_factory)
        self.assertIsNone(qae._i_objective)

        qae.a_factory = self.a_bernoulli
        self.assertIsNotNone(qae.a_factory)
        self.assertIsNotNone(qae.q_factory)
        self.assertIsNotNone(qae.i_objective)
        self.assertIsNotNone(qae._a_factory)
        self.assertIsNone(qae._q_factory)
        self.assertIsNone(qae._i_objective)

        qae.q_factory = self.q_bernoulli
        self.assertIsNotNone(qae.a_factory)
        self.assertIsNotNone(qae.q_factory)
        self.assertIsNotNone(qae.i_objective)
        self.assertIsNotNone(qae._a_factory)
        self.assertIsNotNone(qae._q_factory)
        self.assertIsNone(qae._i_objective)

        qae.i_objective = self.i_bernoulli
        self.assertIsNotNone(qae.a_factory)
        self.assertIsNotNone(qae.q_factory)
        self.assertIsNotNone(qae.i_objective)
        self.assertIsNotNone(qae._a_factory)
        self.assertIsNotNone(qae._q_factory)
        self.assertIsNotNone(qae._i_objective)
        warnings.filterwarnings('always', category=DeprecationWarning)

    @data(
        AmplitudeEstimation(2),
        IterativeAmplitudeEstimation(0.1, 0.001),
        MaximumLikelihoodAmplitudeEstimation(3),
    )
    def test_a_factory_update(self, qae):
        """Test if the Q factory is updated if the a_factory changes -- except set manually."""
        # Case 1: Set to BernoulliAFactory with default Q operator
        warnings.filterwarnings(action="ignore", category=DeprecationWarning)
        qae.a_factory = self.a_bernoulli
        self.assertIsInstance(qae.q_factory.a_factory, BernoulliAFactory)
        self.assertEqual(qae.i_objective, self.i_bernoulli)

        # Case 2: Change to SineIntegralAFactory with default Q operator
        qae.a_factory = self.a_integral
        self.assertIsInstance(qae.q_factory.a_factory, SineIntegralAFactory)
        self.assertEqual(qae.i_objective, self.i_integral)

        # Case 3: Set to BernoulliAFactory with special Q operator
        qae.a_factory = self.a_bernoulli
        qae.q_factory = self.q_bernoulli
        self.assertIsInstance(qae.q_factory, BernoulliQFactory)
        self.assertEqual(qae.i_objective, self.i_bernoulli)

        # Case 4: Set to SineIntegralAFactory, and do not set Q. Then the old Q operator
        # should remain
        qae.a_factory = self.a_integral
        self.assertIsInstance(qae.q_factory, BernoulliQFactory)
        self.assertEqual(qae.i_objective, self.i_bernoulli)
        warnings.filterwarnings(action="always", category=DeprecationWarning)
class TestBernoulli(QiskitAquaTestCase):
    """Tests based on the Bernoulli A operator.

    This class tests
        * the estimation result
        * the constructed circuits
    """
    def setUp(self):
        super().setUp()

        self._statevector = QuantumInstance(
            backend=BasicAer.get_backend('statevector_simulator'),
            seed_simulator=2,
            seed_transpiler=2)
        self._unitary = QuantumInstance(
            backend=BasicAer.get_backend('unitary_simulator'),
            shots=1,
            seed_simulator=42,
            seed_transpiler=91)

        def qasm(shots=100):
            return QuantumInstance(
                backend=BasicAer.get_backend('qasm_simulator'),
                shots=shots,
                seed_simulator=2,
                seed_transpiler=2)

        self._qasm = qasm

    @idata(
        [[0.2, AmplitudeEstimation(2), {
            'estimation': 0.5,
            'mle': 0.2
        }], [0.49,
             AmplitudeEstimation(3), {
                 'estimation': 0.5,
                 'mle': 0.49
             }],
         [0.2,
          MaximumLikelihoodAmplitudeEstimation(2), {
              'estimation': 0.2
          }],
         [0.49,
          MaximumLikelihoodAmplitudeEstimation(3), {
              'estimation': 0.49
          }],
         [0.2,
          IterativeAmplitudeEstimation(0.1, 0.1), {
              'estimation': 0.2
          }],
         [
             0.49,
             IterativeAmplitudeEstimation(0.001, 0.01), {
                 'estimation': 0.49
             }
         ]])
    @unpack
    def test_statevector(self, prob, qae, expect):
        """ statevector test """
        # construct factories for A and Q
        qae.state_preparation = BernoulliStateIn(prob)
        qae.grover_operator = BernoulliGrover(prob)

        result = qae.run(self._statevector)

        for key, value in expect.items():
            self.assertAlmostEqual(value,
                                   getattr(result, key),
                                   places=3,
                                   msg="estimate `{}` failed".format(key))

    @idata([[
        0.2, 100,
        AmplitudeEstimation(4), {
            'estimation': 0.14644,
            'mle': 0.193888
        }
    ], [0.0, 1000,
        AmplitudeEstimation(2), {
            'estimation': 0.0,
            'mle': 0.0
        }],
            [
                0.2, 100,
                MaximumLikelihoodAmplitudeEstimation(4), {
                    'estimation': 0.199606
                }
            ],
            [
                0.8, 10,
                IterativeAmplitudeEstimation(0.1, 0.05), {
                    'estimation': 0.811711
                }
            ]])
    @unpack
    def test_qasm(self, prob, shots, qae, expect):
        """ qasm test """
        # construct factories for A and Q
        qae.state_preparation = BernoulliStateIn(prob)
        qae.grover_operator = BernoulliGrover(prob)

        result = qae.run(self._qasm(shots))

        for key, value in expect.items():
            self.assertAlmostEqual(value,
                                   getattr(result, key),
                                   places=3,
                                   msg="estimate `{}` failed".format(key))

    @data(True, False)
    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 [2, 5]:
            qae = AmplitudeEstimation(m, BernoulliStateIn(prob))
            angle = 2 * np.arcsin(np.sqrt(prob))

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

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

            # A operator
            circuit.ry(angle, qr_objective)

            if efficient_circuit:
                qae.grover_operator = BernoulliGrover(prob)
                for power in range(m):
                    circuit.cry(2 * 2**power * angle, qr_eval[power],
                                qr_objective[0])
            else:
                oracle = QuantumCircuit(1)
                oracle.x(0)
                oracle.z(0)
                oracle.x(0)

                state_preparation = QuantumCircuit(1)
                state_preparation.ry(angle, 0)
                grover_op = GroverOperator(oracle, state_preparation)
                for power in range(m):
                    circuit.compose(grover_op.power(2**power).control(),
                                    qubits=[qr_eval[power], qr_objective[0]],
                                    inplace=True)

            # fourier transform
            iqft = QFT(m, do_swaps=False).inverse()
            circuit.append(iqft.to_instruction(), qr_eval)

            actual_circuit = qae.construct_circuit(measurement=False)

            self.assertEqual(Operator(circuit), Operator(actual_circuit))

    @data(True, False)
    def test_iqae_circuits(self, efficient_circuit):
        """Test circuits resulting from iterative amplitude estimation.

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

        for k in [2, 5]:
            qae = IterativeAmplitudeEstimation(
                0.01, 0.05, state_preparation=BernoulliStateIn(prob))
            angle = 2 * np.arcsin(np.sqrt(prob))

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

            # A operator
            circuit.ry(angle, q_objective)

            if efficient_circuit:
                qae.grover_operator = BernoulliGrover(prob)
                circuit.ry(2 * k * angle, q_objective[0])

            else:
                oracle = QuantumCircuit(1)
                oracle.x(0)
                oracle.z(0)
                oracle.x(0)
                state_preparation = QuantumCircuit(1)
                state_preparation.ry(angle, 0)
                grover_op = GroverOperator(oracle, state_preparation)
                for _ in range(k):
                    circuit.compose(grover_op, inplace=True)

            actual_circuit = qae.construct_circuit(k, measurement=False)
            self.assertEqual(Operator(circuit), Operator(actual_circuit))

    @data(True, False)
    def test_mlae_circuits(self, efficient_circuit):
        """ Test the circuits constructed for MLAE """
        prob = 0.5

        for k in [2, 5]:
            qae = MaximumLikelihoodAmplitudeEstimation(
                k, state_preparation=BernoulliStateIn(prob))
            angle = 2 * np.arcsin(np.sqrt(prob))

            # compute all the circuits used for MLAE
            circuits = []

            # 0th power
            q_objective = QuantumRegister(1, 'q')
            circuit = QuantumCircuit(q_objective)
            circuit.ry(angle, q_objective)
            circuits += [circuit]

            # powers of 2
            for power in range(k):
                q_objective = QuantumRegister(1, 'q')
                circuit = QuantumCircuit(q_objective)

                # A operator
                circuit.ry(angle, q_objective)

                # Q^(2^j) operator
                if efficient_circuit:
                    qae.grover_operator = BernoulliGrover(prob)
                    circuit.ry(2 * 2**power * angle, q_objective[0])

                else:
                    oracle = QuantumCircuit(1)
                    oracle.x(0)
                    oracle.z(0)
                    oracle.x(0)
                    state_preparation = QuantumCircuit(1)
                    state_preparation.ry(angle, 0)
                    grover_op = GroverOperator(oracle, state_preparation)
                    for _ in range(2**power):
                        circuit.compose(grover_op, inplace=True)

            actual_circuits = qae.construct_circuits(measurement=False)

            for actual, expected in zip(actual_circuits, circuits):
                self.assertEqual(Operator(actual), Operator(expected))
Exemplo n.º 6
0
plt.show()

# evaluate exact expected value (normalized to the [0, 1] interval)
exact_value = np.dot(uncertainty_model.probabilities, y)
exact_delta = sum(uncertainty_model.probabilities[np.logical_and(
    x >= strike_price_1, x <= strike_price_2)])
print('exact expected value:\t%.4f' % exact_value)
print('exact delta value:   \t%.4f' % exact_delta)

# set target precision and confidence level
epsilon = 0.01
alpha = 0.05

# construct amplitude estimation
ae = IterativeAmplitudeEstimation(epsilon=epsilon,
                                  alpha=alpha,
                                  a_factory=bull_spread)

result = ae.run(quantum_instance=Aer.get_backend('qasm_simulator'), shots=100)

conf_int = np.array(result['confidence_interval'])
print('Exact value:    \t%.4f' % exact_value)
print('Estimated value:\t%.4f' % result['estimation'])
print('Confidence interval: \t[%.4f, %.4f]' % tuple(conf_int))

###Evaluate Delta which is a little simplier than the Excpected Payoff
# setup piecewise linear objective fcuntion
breakpoints = [uncertainty_model.low, strike_price_1, strike_price_2]
slopes = [0, 0, 0]
offsets = [0, 1, 0]
f_min = 0
Exemplo n.º 7
0
plt.plot(x, y_strike, 'ro-')
plt.grid()
plt.title('Payoff Function', size=15)
plt.xlabel('Spot Price', size=15)
plt.ylabel('Payoff', size=15)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.show()


# set target precision and confidence level
epsilon = 0.01
alpha = 0.05

# construct amplitude estimation
ae = IterativeAmplitudeEstimation(epsilon=epsilon, alpha=alpha, a_factory=european_call)


result = ae.run(quantum_instance=Aer.get_backend('qasm_simulator'), shots=100)


conf_int = np.array(result['confidence_interval'])
print('Exact value:        \t%.4f' % ep_trained)
print('Estimated value:    \t%.4f' % (result['estimation']))
print('Confidence interval:\t[%.4f, %.4f]' % tuple(conf_int))


import qiskit.tools.jupyter
#%qiskit_version_table
#%qiskit_copyright