def test_application(self): """Test an end-to-end application.""" bounds = np.array([0., 7.]) num_qubits = 3 # the distribution circuit is a normal distribution plus a QGAN-trained ansatz circuit dist = NormalDistribution(num_qubits, mu=1, sigma=1, bounds=bounds) ansatz = TwoLocal(num_qubits, 'ry', 'cz', reps=1, entanglement='circular') trained_params = [0.29399714, 0.38853322, 0.9557694, 0.07245791, 6.02626428, 0.13537225] ansatz.assign_parameters(trained_params, inplace=True) dist.compose(ansatz, inplace=True) # create the European call expected value strike_price = 2 rescaling_factor = 0.25 european_call = EuropeanCallExpectedValue(num_qubits, strike_price, rescaling_factor, bounds) # create the state preparation circuit state_preparation = european_call.compose(dist, front=True) iae = IterativeAmplitudeEstimation(0.01, 0.05, state_preparation=state_preparation, objective_qubits=[num_qubits], post_processing=european_call.post_processing) backend = QuantumInstance(Aer.get_backend('qasm_simulator'), seed_simulator=125, seed_transpiler=80) result = iae.run(backend) self.assertAlmostEqual(result.estimation, 1.0364776997977694)
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.z(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))
def test_application(self): """Test an end-to-end application.""" num_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 mu = ((r - 0.5 * vol ** 2) * t_m + np.log(s_p)) sigma = vol * np.sqrt(t_m) mean = np.exp(mu + sigma ** 2 / 2) variance = (np.exp(sigma ** 2) - 1) * np.exp(2 * mu + 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 bounds = (low, high) # construct circuit factory for uncertainty model uncertainty_model = LogNormalDistribution(num_qubits, mu=mu, sigma=sigma ** 2, bounds=bounds) # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 1.896 # create amplitude function european_call_delta = EuropeanCallDelta(num_qubits, strike_price, bounds) # create state preparation state_preparation = european_call_delta.compose(uncertainty_model, front=True) # run amplitude estimation iae = IterativeAmplitudeEstimation(0.01, 0.05, state_preparation=state_preparation, objective_qubits=[num_qubits]) backend = QuantumInstance(Aer.get_backend('qasm_simulator'), seed_simulator=125, seed_transpiler=80) result = iae.run(backend) self.assertAlmostEqual(result.estimation, 0.8088790606143996)
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 = 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)
def test_application(self): """Test an end-to-end application.""" a_n = np.eye(2) b = np.zeros(2) num_qubits = [2, 2] # specify the lower and upper bounds for the different dimension bounds = [(0, 0.12), (0, 0.24)] mu = [0.12, 0.24] sigma = 0.01 * np.eye(2) # construct corresponding distribution dist = NormalDistribution(num_qubits, mu, sigma, bounds=bounds) # specify cash flow c_f = [1.0, 2.0] # specify approximation factor rescaling_factor = 0.125 # get fixed income circuit appfactory fixed_income = FixedIncomeExpectedValue(num_qubits, a_n, b, c_f, rescaling_factor, bounds) # build state preparation operator state_preparation = fixed_income.compose(dist, front=True) # run simulation iae = IterativeAmplitudeEstimation( epsilon=0.01, alpha=0.05, state_preparation=state_preparation, post_processing=fixed_income.post_processing) backend = QuantumInstance(Aer.get_backend('qasm_simulator'), seed_simulator=2, seed_transpiler=2) result = iae.run(backend) # compare to precomputed solution self.assertAlmostEqual(result.estimation, 2.3389012822103044)
def test_iqae_confidence_intervals(self): """End-to-end test for the IQAE confidence interval.""" n = 3 qae = IterativeAmplitudeEstimation(0.1, 0.01, state_preparation=SineIntegral(n)) expected_confint = [0.19840508760087738, 0.35110155403424115] # statevector simulator result = qae.run(self._statevector) self.assertGreater(self._statevector.time_taken, 0.) self._statevector.reset_execution_results() 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 np.testing.assert_almost_equal(confint, expected_confint, decimal=7) self.assertTrue(confint[0] <= result.estimation <= confint[1])
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): warnings.filterwarnings('ignore', category=DeprecationWarning) 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) warnings.filterwarnings('always', category=DeprecationWarning) 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)
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'] np.testing.assert_almost_equal(confint, expected_confint, decimal=7) self.assertTrue(confint[0] <= result['estimation'] <= confint[1])
def mc_var_circuit(): mu = [1, 0.9] sigma = [[1, -0.2], [-0.2, 1]] num_qubits = [3, 2] bounds = [(-1, 1), (-1, 1)] cdfs, pdfs = prepare_marginals() circuit = GaussianCopula(num_qubits, mu=mu, sigma=sigma, bounds=bounds, cdfs=cdfs, pdfs=pdfs) state_preparation = get_cdf_circuit(x_eval) ae_var = IterativeAmplitudeEstimation(state_preparation=state_preparation, epsilon=epsilon, alpha=alpha, objective_qubits=[len(qr_state)]) result_var = ae_var.run(quantum_instance=Aer.get_backend(simulator), shots=100)
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)
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
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))
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
num_sum_qubits, slope=slopes, offset=offsets, # max value that can be reached by the qubit register (will not always be reached) domain=(0, 2**num_sum_qubits-1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints ) qr_sum = QuantumRegister(5, "sum") state_preparation = QuantumCircuit(qr_sum) # to complete # set target precision and confidence level epsilon = 0.01 alpha = 0.05 # construct amplitude estimation ae_cdf = IterativeAmplitudeEstimation(state_preparation=state_preparation, epsilon=epsilon, alpha=alpha, objective_qubits=[len(qr_sum)]) result_cdf = ae_cdf.run(quantum_instance=Aer.get_backend('qasm_simulator'), shots=100) # print results exact_value = 1 # to calculate conf_int = np.array(result_cdf['confidence_interval']) print('Exact value: \t%.4f' % exact_value) print('Estimated value:\t%.4f' % result_cdf['estimation']) print('Confidence interval: \t[%.4f, %.4f]' % tuple(conf_int)) def transform_from_
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))