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_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])
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_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 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_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 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)
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_
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 f_max = 1 c_approx = 1 # no approximation necessary bull_spread_delta_objective = PwlObjective(uncertainty_model.num_target_qubits,