Example #1
0
class TestFixedIncomeAssets(QiskitFinanceTestCase):
    """ Test Fixed Income Assets """
    def setUp(self):
        super().setUp()

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

    @parameterized.expand([
        ['statevector', AmplitudeEstimation(5),
         {'estimation': 2.4600, 'mle': 2.3402315559106843}],
        ['qasm', AmplitudeEstimation(5),
         {'estimation': 2.4600, 'mle': 2.3632087675061726}],
        ['statevector', MaximumLikelihoodAmplitudeEstimation(5),
         {'estimation': 2.340361798381051}],
        ['qasm', MaximumLikelihoodAmplitudeEstimation(5),
         {'estimation': 2.317921060790118}]
    ])
    def test_expected_value(self, simulator, a_e, expect):
        """ expected value test """
        # can be used in case a principal component analysis
        # has been done to derive the uncertainty model, ignored in this example.
        a_n = np.eye(2)
        b = np.zeros(2)

        # specify the number of qubits that are used to represent
        # the different dimensions of the uncertainty model
        num_qubits = [2, 2]

        # specify the lower and upper bounds for the different dimension
        low = [0, 0]
        high = [0.12, 0.24]
        m_u = [0.12, 0.24]
        sigma = 0.01 * np.eye(2)

        # construct corresponding distribution
        mund = MultivariateNormalDistribution(num_qubits, low, high, m_u, sigma)

        # specify cash flow
        c_f = [1.0, 2.0]

        # specify approximation factor
        c_approx = 0.125

        # get fixed income circuit appfactory
        fixed_income = FixedIncomeExpectedValue(mund, a_n, b, c_f, c_approx)
        a_e.a_factory = fixed_income

        # run simulation
        result = a_e.run(self._qasm if simulator == 'qasm' else self._statevector)

        # compare to precomputed solution
        for key, value in expect.items():
            self.assertAlmostEqual(result[key], value, places=4,
                                   msg="estimate `{}` failed".format(key))
    def test_mlae_circuits(self, efficient_circuit):
        """ Test the circuits constructed for MLAE """
        prob = 0.5

        for k in range(1, 7):
            warnings.filterwarnings('ignore', category=DeprecationWarning)
            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)

            warnings.filterwarnings('always', category=DeprecationWarning)
            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)
    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))
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 = BernoulliStateIn(0)
        self.q_bernoulli = BernoulliGrover(0)
        self.i_bernoulli = [0]

        num_qubits = 5
        self.a_integral = SineIntegral(num_qubits)
        oracle = QuantumCircuit(num_qubits + 1)
        oracle.x(num_qubits)
        oracle.z(num_qubits)
        oracle.x(num_qubits)

        self.q_integral = GroverOperator(oracle, self.a_integral)
        self.i_integral = [num_qubits]

    @data(
        AmplitudeEstimation(2),
        IterativeAmplitudeEstimation(0.1, 0.001),
        MaximumLikelihoodAmplitudeEstimation(3),
    )
    def test_operators(self, qae):
        """ Test if A/Q operator + i_objective set correctly """
        self.assertIsNone(qae.state_preparation)
        self.assertIsNone(qae.grover_operator)
        self.assertIsNone(qae.objective_qubits)
        self.assertIsNone(qae._state_preparation)
        self.assertIsNone(qae._grover_operator)
        self.assertIsNone(qae._objective_qubits)

        qae.state_preparation = self.a_bernoulli
        self.assertIsNotNone(qae.state_preparation)
        self.assertIsNotNone(qae.grover_operator)
        self.assertIsNotNone(qae.objective_qubits)
        self.assertIsNotNone(qae._state_preparation)
        self.assertIsNone(qae._grover_operator)
        self.assertIsNone(qae._objective_qubits)

        qae.grover_operator = self.q_bernoulli
        self.assertIsNotNone(qae.state_preparation)
        self.assertIsNotNone(qae.grover_operator)
        self.assertIsNotNone(qae.objective_qubits)
        self.assertIsNotNone(qae._state_preparation)
        self.assertIsNotNone(qae._grover_operator)
        self.assertIsNone(qae._objective_qubits)

        qae.objective_qubits = self.i_bernoulli
        self.assertIsNotNone(qae.state_preparation)
        self.assertIsNotNone(qae.grover_operator)
        self.assertIsNotNone(qae.objective_qubits)
        self.assertIsNotNone(qae._state_preparation)
        self.assertIsNotNone(qae._grover_operator)
        self.assertIsNotNone(qae._objective_qubits)
Example #5
0
class TestBernoulli(QiskitAquaTestCase):
    """ Test Bernoulli """
    def setUp(self):
        super().setUp()

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

        def qasm(shots=100):
            return QuantumInstance(backend=BasicAer.get_backend('qasm_simulator'), shots=shots,
                                   circuit_caching=False, 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}]
    ])
    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}]
    ])
    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 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
        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
        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
        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)
            self.assertEqual(confint, expected_confint)
            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
        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)
        self.q_intergal = QFactory(self.a_integral, num_qubits)
        self.i_intergal = 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 """
        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)

    @idata([
        [AmplitudeEstimation(2)],
        [IterativeAmplitudeEstimation(0.1, 0.001)],
        [MaximumLikelihoodAmplitudeEstimation(3)],
    ])
    @unpack
    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
        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_intergal)

        # 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)
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.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):
        """ statevector test """
        # 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))

    @idata([[True], [False]])
    @unpack
    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)

    @idata([[True], [False]])
    @unpack
    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)

    @idata([[True], [False]])
    @unpack
    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)
Example #9
0
class TestEuropeanCallOption(QiskitFinanceTestCase):
    """ Test European Call Option """
    def setUp(self):
        super().setUp()

        # number of qubits to represent the uncertainty
        num_uncertainty_qubits = 3

        # parameters for considered random distribution
        s_p = 2.0  # initial spot price
        vol = 0.4  # volatility of 40%
        r = 0.05  # annual interest rate of 4%
        t_m = 40 / 365  # 40 days to maturity

        # resulting parameters for log-normal distribution
        m_u = ((r - 0.5 * vol**2) * t_m + np.log(s_p))
        sigma = vol * np.sqrt(t_m)
        mean = np.exp(m_u + sigma**2 / 2)
        variance = (np.exp(sigma**2) - 1) * np.exp(2 * m_u + sigma**2)
        stddev = np.sqrt(variance)

        # lowest and highest value considered for the spot price;
        # in between, an equidistant discretization is considered.
        low = np.maximum(0, mean - 3 * stddev)
        high = mean + 3 * stddev

        # construct circuit factory for uncertainty model
        uncertainty_model = LogNormalDistribution(num_uncertainty_qubits,
                                                  mu=m_u,
                                                  sigma=sigma,
                                                  low=low,
                                                  high=high)

        # set the strike price (should be within the low and the high value of the uncertainty)
        strike_price = 1.896

        # set the approximation scaling for the payoff function
        c_approx = 0.1

        # setup piecewise linear objective function
        breakpoints = [uncertainty_model.low, strike_price]
        slopes = [0, 1]
        offsets = [0, 0]
        f_min = 0
        f_max = uncertainty_model.high - strike_price
        european_call_objective = PwlObjective(
            uncertainty_model.num_target_qubits, uncertainty_model.low,
            uncertainty_model.high, breakpoints, slopes, offsets, f_min, f_max,
            c_approx)

        # construct circuit factory for payoff function
        self.european_call = UnivariateProblem(uncertainty_model,
                                               european_call_objective)

        # construct circuit factory for payoff function
        self.european_call_delta = EuropeanCallDelta(
            uncertainty_model,
            strike_price=strike_price,
        )

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

    @parameterized.expand([
        [
            'statevector',
            AmplitudeEstimation(3), {
                'estimation': 0.45868536404797905,
                'mle': 0.1633160
            }
        ],
        [
            'qasm',
            AmplitudeEstimation(4), {
                'estimation': 0.45868536404797905,
                'mle': 0.23479973342434832
            }
        ],
        [
            'statevector',
            MaximumLikelihoodAmplitudeEstimation(5), {
                'estimation': 0.16330976193204114
            }
        ],
        [
            'qasm',
            MaximumLikelihoodAmplitudeEstimation(3), {
                'estimation': 0.1027255930905642
            }
        ],
    ])
    def test_expected_value(self, simulator, a_e, expect):
        """ expected value test """
        # set A factory for amplitude estimation
        a_e.a_factory = self.european_call

        # run simulation
        result = a_e.run(self._qasm if simulator ==
                         'qasm' else self._statevector)

        # compare to precomputed solution
        for key, value in expect.items():
            self.assertAlmostEqual(result[key],
                                   value,
                                   places=4,
                                   msg="estimate `{}` failed".format(key))

    @parameterized.expand([
        [
            'statevector',
            AmplitudeEstimation(3), {
                'estimation': 0.8535534,
                'mle': 0.8097974047170567
            }
        ],
        [
            'qasm',
            AmplitudeEstimation(4), {
                'estimation': 0.8535534,
                'mle': 0.8143597808556013
            }
        ],
        [
            'statevector',
            MaximumLikelihoodAmplitudeEstimation(5), {
                'estimation': 0.8097582003326866
            }
        ],
        [
            'qasm',
            MaximumLikelihoodAmplitudeEstimation(6), {
                'estimation': 0.8096123776923358
            }
        ],
    ])
    def test_delta(self, simulator, a_e, expect):
        """ delta test """
        # set A factory for amplitude estimation
        a_e.a_factory = self.european_call_delta

        # run simulation
        result = a_e.run(self._qasm if simulator ==
                         'qasm' else self._statevector)

        # compare to precomputed solution
        for key, value in expect.items():
            self.assertAlmostEqual(result[key],
                                   value,
                                   places=4,
                                   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()

        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)
        self.assertGreater(self._statevector.time_taken, 0.)
        self._statevector.reset_execution_results()
        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))