diff --git a/test/python/opflow/test_gradients.py b/test/python/opflow/test_gradients.py index 374631bd65cc..48266c78dea6 100644 --- a/test/python/opflow/test_gradients.py +++ b/test/python/opflow/test_gradients.py @@ -15,7 +15,6 @@ import unittest from test.python.opflow import QiskitOpflowTestCase -import warnings from itertools import product import numpy as np from ddt import ddt, data, idata, unpack @@ -68,16 +67,18 @@ def test_gradient_p(self, method): Tr(|psi>/da = - 0.5 sin(a) """ - ham = 0.5 * X - 1 * Z a = Parameter("a") params = a q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.p(a, q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + ham = 0.5 * X - 1 * Z + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + values_dict = [{a: np.pi / 4}, {a: 0}, {a: np.pi / 2}] correct_values = [-0.5 / np.sqrt(2), 0, -0.5] @@ -103,9 +104,11 @@ def test_gradient_u(self, method): qc.h(q) qc.u(a, b, c, q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) params = [a, b, c] - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + values_dict = [{a: np.pi / 4, b: 0, c: 0}, {a: np.pi / 4, b: np.pi / 4, c: np.pi / 4}] correct_values = [[0.3536, 0, 0], [0.3232, -0.42678, -0.92678]] for i, value_dict in enumerate(values_dict): @@ -122,9 +125,11 @@ def test_gradient_u(self, method): qc.h(q) qc.u(a, a, a, q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) params = [a] - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + values_dict = [{a: np.pi / 4}, {a: np.pi / 2}] correct_values = [[-1.03033], [-1]] for i, value_dict in enumerate(values_dict): @@ -135,16 +140,18 @@ def test_gradient_u(self, method): @data("lin_comb", "param_shift") def test_gradient_efficient_su2(self, method): """Test the state gradient for EfficientSU2""" - observable = SummedOp( - [ - 0.2252 * (I ^ I), - 0.5716 * (Z ^ Z), - 0.3435 * (I ^ Z), - -0.4347 * (Z ^ I), - 0.091 * (Y ^ Y), - 0.091 * (X ^ X), - ] - ).reduce() + + with self.assertWarns(DeprecationWarning): + observable = SummedOp( + [ + 0.2252 * (I ^ I), + 0.5716 * (Z ^ Z), + 0.3435 * (I ^ Z), + -0.4347 * (Z ^ I), + 0.091 * (Y ^ Y), + 0.091 * (X ^ X), + ] + ).reduce() d = 2 ansatz = EfficientSU2(observable.num_qubits, reps=d) @@ -152,7 +159,8 @@ def test_gradient_efficient_su2(self, method): # Define a set of initial parameters parameters = ansatz.ordered_parameters - operator = ~StateFn(observable) @ StateFn(ansatz) + with self.assertWarns(DeprecationWarning): + operator = ~StateFn(observable) @ StateFn(ansatz) values_dict = [ {param: np.pi / 4 for param in parameters}, @@ -189,7 +197,9 @@ def test_gradient_efficient_su2(self, method): ], ] - state_grad = Gradient(method).convert(operator, parameters) + with self.assertWarns(DeprecationWarning): + state_grad = Gradient(method).convert(operator, parameters) + for i, value_dict in enumerate(values_dict): np.testing.assert_array_almost_equal( state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1 @@ -198,7 +208,6 @@ def test_gradient_efficient_su2(self, method): @data("lin_comb", "param_shift", "fin_diff") def test_gradient_rxx(self, method): """Test the state gradient for XX rotation""" - ham = TensoredOp([Z, X]) a = Parameter("a") q = QuantumRegister(2) @@ -206,9 +215,12 @@ def test_gradient_rxx(self, method): qc.h(q[0]) qc.rxx(a, q[0], q[1]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) params = [a] - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + ham = TensoredOp([Z, X]) + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + values_dict = [{a: np.pi / 4}, {a: np.pi / 2}] correct_values = [[-0.707], [-1.0]] for i, value_dict in enumerate(values_dict): @@ -220,15 +232,17 @@ def test_gradient_rxx(self, method): def test_gradient_ryy(self, method): """Test the state gradient for YY rotation""" alpha = Parameter("alpha") - ham = TensoredOp([Y, alpha * Y]) a = Parameter("a") q = QuantumRegister(2) qc = QuantumCircuit(q) qc.ryy(a, q[0], q[1]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = Gradient(grad_method=method).convert(operator=op, params=a) + with self.assertWarns(DeprecationWarning): + ham = TensoredOp([Y, alpha * Y]) + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = Gradient(grad_method=method).convert(operator=op, params=a) + values_dict = [{a: np.pi / 8}, {a: np.pi}] correct_values = [[0], [0]] for i, value_dict in enumerate(values_dict): @@ -240,7 +254,6 @@ def test_gradient_ryy(self, method): @data("lin_comb", "param_shift", "fin_diff") def test_gradient_rzz(self, method): """Test the state gradient for ZZ rotation""" - ham = Z ^ X a = Parameter("a") q = QuantumRegister(2) @@ -248,9 +261,12 @@ def test_gradient_rzz(self, method): qc.h(q[0]) qc.rzz(a, q[0], q[1]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) params = [a] - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + ham = Z ^ X + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + values_dict = [{a: np.pi / 4}, {a: np.pi / 2}] correct_values = [[-0.707], [-1.0]] for i, value_dict in enumerate(values_dict): @@ -261,7 +277,6 @@ def test_gradient_rzz(self, method): @data("lin_comb", "param_shift", "fin_diff") def test_gradient_rzx(self, method): """Test the state gradient for ZX rotation""" - ham = Z ^ Z a = Parameter("a") q = QuantumRegister(2) @@ -269,9 +284,12 @@ def test_gradient_rzx(self, method): qc.h(q) qc.rzx(a, q[0], q[1]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) params = [a] - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + ham = Z ^ Z + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + values_dict = [{a: np.pi / 8}, {a: np.pi / 2}] correct_values = [[0.0], [0.0]] for i, value_dict in enumerate(values_dict): @@ -289,7 +307,6 @@ def test_state_gradient1(self, method): d/db = - 1 sin(a)cos(b) """ - ham = 0.5 * X - 1 * Z a = Parameter("a") b = Parameter("b") params = [a, b] @@ -299,9 +316,12 @@ def test_state_gradient1(self, method): qc.h(q) qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + ham = 0.5 * X - 1 * Z + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + values_dict = [ {a: np.pi / 4, b: np.pi}, {params[0]: np.pi / 4, params[1]: np.pi / 4}, @@ -326,7 +346,6 @@ def test_state_gradient2(self, method): Tr(|psi>/da = - 0.5 sin(a) - 2 cos(a)sin(a) """ - ham = 0.5 * X - 1 * Z a = Parameter("a") # b = Parameter('b') params = [a] @@ -336,9 +355,12 @@ def test_state_gradient2(self, method): qc.h(q) qc.rz(a, q[0]) qc.rx(a, q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + ham = 0.5 * X - 1 * Z + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + values_dict = [{a: np.pi / 4}, {a: 0}, {a: np.pi / 2}] correct_values = [-1.353553, -0, -0.5] @@ -355,7 +377,6 @@ def test_state_gradient3(self, method): Tr(|psi>/da = - 0.5 sin(a) - 1 cos(a)sin(cos(a)+1) + 1 sin^2(a)cos(cos(a)+1) """ - ham = 0.5 * X - 1 * Z a = Parameter("a") # b = Parameter('b') params = a @@ -365,9 +386,12 @@ def test_state_gradient3(self, method): qc.h(q) qc.rz(a, q[0]) qc.rx(c, q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + ham = 0.5 * X - 1 * Z + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + values_dict = [{a: np.pi / 4}, {a: 0}, {a: np.pi / 2}] correct_values = [-1.1220, -0.9093, 0.0403] for i, value_dict in enumerate(values_dict): @@ -382,7 +406,6 @@ def test_state_gradient4(self, method): daTr(|psi>/da1 = - 1 sin(a0)cos(a1) """ - ham = 0.5 * X - 1 * Z a = ParameterVector("a", 2) params = a @@ -421,9 +446,12 @@ def test_state_gradient5(self, method): qc.h(q) qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + ham = 0.5 * X - 1 * Z + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + values_dict = [ {a: [np.pi / 4, np.pi]}, {a: [np.pi / 4, np.pi / 4]}, @@ -452,7 +480,6 @@ def test_state_hessian(self, method): d^2/db^2 = + 1 sin(a)sin(b) """ - ham = 0.5 * X - 1 * Z params = ParameterVector("a", 2) q = QuantumRegister(1) @@ -461,8 +488,10 @@ def test_state_hessian(self, method): qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_hess = Hessian(hess_method=method).convert(operator=op) + with self.assertWarns(DeprecationWarning): + ham = 0.5 * X - 1 * Z + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_hess = Hessian(hess_method=method).convert(operator=op) values_dict = [ {params[0]: np.pi / 4, params[1]: np.pi}, @@ -492,7 +521,6 @@ def test_state_hessian_custom_combo_fn(self, method): d^2/db^2 = + 1 sin(a)sin(b) """ - ham = 0.5 * X - 1 * Z a = Parameter("a") b = Parameter("b") params = [(a, a), (a, b), (b, b)] @@ -503,11 +531,13 @@ def test_state_hessian_custom_combo_fn(self, method): qc.rz(a, q[0]) qc.rx(b, q[0]) - op = ListOp( - [~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)], - combo_fn=lambda x: x[0] ** 3 + 4 * x[0], - ) - state_hess = Hessian(hess_method=method).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + ham = 0.5 * X - 1 * Z + op = ListOp( + [~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)], + combo_fn=lambda x: x[0] ** 3 + 4 * x[0], + ) + state_hess = Hessian(hess_method=method).convert(operator=op, params=params) values_dict = [ {a: np.pi / 4, b: np.pi}, @@ -546,9 +576,10 @@ def test_prob_grad(self, method): qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - op = CircuitStateFn(primitive=qc, coeff=1.0) + with self.assertWarns(DeprecationWarning): + op = CircuitStateFn(primitive=qc, coeff=1.0) + prob_grad = Gradient(grad_method=method).convert(operator=op, params=params) - prob_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [ {a: np.pi / 4, b: 0}, {params[0]: np.pi / 4, params[1]: np.pi / 4}, @@ -585,9 +616,10 @@ def test_prob_hess(self, method): qc.rz(a, q[0]) qc.rx(b, q[0]) - op = CircuitStateFn(primitive=qc, coeff=1.0) + with self.assertWarns(DeprecationWarning): + op = CircuitStateFn(primitive=qc, coeff=1.0) + prob_hess = Hessian(hess_method=method).convert(operator=op, params=params) - prob_hess = Hessian(hess_method=method).convert(operator=op, params=params) values_dict = [{a: np.pi / 4, b: 0}, {a: np.pi / 4, b: np.pi / 4}, {a: np.pi / 2, b: np.pi}] correct_values = [ [[0, 0], [1 / (2 * np.sqrt(2)), -1 / (2 * np.sqrt(2))]], @@ -611,7 +643,6 @@ def test_natural_gradient(self, method, regularization): """Test the natural gradient""" try: for params in (ParameterVector("a", 2), [Parameter("a"), Parameter("b")]): - ham = 0.5 * X - 1 * Z q = QuantumRegister(1) qc = QuantumCircuit(q) @@ -619,10 +650,13 @@ def test_natural_gradient(self, method, regularization): qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - nat_grad = NaturalGradient( - grad_method=method, regularization=regularization - ).convert(operator=op) + with self.assertWarns(DeprecationWarning): + ham = 0.5 * X - 1 * Z + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + nat_grad = NaturalGradient( + grad_method=method, regularization=regularization + ).convert(operator=op) + values_dict = [{params[0]: np.pi / 4, params[1]: np.pi / 2}] # reference values obtained by classically computing the natural gradients @@ -649,7 +683,9 @@ def test_natural_gradient2(self): @unpack def test_natural_gradient3(self, qfi_method, circuit_qfi): """Test the natural gradient 3""" - nat_grad = NaturalGradient(qfi_method=qfi_method) + with self.assertWarns(DeprecationWarning): + nat_grad = NaturalGradient(qfi_method=qfi_method) + self.assertIsInstance(nat_grad.qfi_method, circuit_qfi) @idata( @@ -665,7 +701,6 @@ def test_natural_gradient4(self, grad_method, qfi_method, regularization): # Avoid regularization = lasso intentionally because it does not converge try: - ham = 0.5 * X - 1 * Z a = Parameter("a") params = a @@ -674,10 +709,13 @@ def test_natural_gradient4(self, grad_method, qfi_method, regularization): qc.h(q) qc.rz(a, q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - nat_grad = NaturalGradient( - grad_method=grad_method, qfi_method=qfi_method, regularization=regularization - ).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + ham = 0.5 * X - 1 * Z + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + nat_grad = NaturalGradient( + grad_method=grad_method, qfi_method=qfi_method, regularization=regularization + ).convert(operator=op, params=params) + values_dict = [{a: np.pi / 4}] correct_values = [[0.0]] if regularization == "ridge" else [[-1.41421342]] for i, value_dict in enumerate(values_dict): @@ -693,16 +731,18 @@ def test_gradient_p_imag(self): = iexp(-ia)/2 <1|H(|0>+exp(ia)|1>) Im() = 0.5 cos(a). """ - ham = X a = Parameter("a") params = a q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.p(a, q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = LinComb(aux_meas_op=(-1) * Y).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + ham = X + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = LinComb(aux_meas_op=(-1) * Y).convert(operator=op, params=params) + values_dict = [{a: np.pi / 4}, {a: 0}, {a: np.pi / 2}] correct_values = [1 / np.sqrt(2), 1, 0] @@ -718,7 +758,6 @@ def test_qfi_p_imag(self): circuit = QuantumCircuit(1) circuit.ry(y, 0) circuit.rx(x, 0) - state = StateFn(circuit) dx = ( lambda x, y: (-1) @@ -745,9 +784,12 @@ def test_qfi_p_imag(self): ) ) - state_grad = LinCombFull(aux_meas_op=-1 * Y, phase_fix=False).convert( - operator=state, params=[x, y] - ) + with self.assertWarns(DeprecationWarning): + state = StateFn(circuit) + state_grad = LinCombFull(aux_meas_op=-1 * Y, phase_fix=False).convert( + operator=state, params=[x, y] + ) + values_dict = [{x: 0, y: np.pi / 4}, {x: 0, y: np.pi / 2}, {x: np.pi / 2, y: 0}] for value_dict in values_dict: @@ -799,16 +841,18 @@ def combo_fn(x): def grad_combo_fn(x): return np.array([2 * x[0], -np.sin(x[1])]) - op = ListOp( - [ - ~StateFn(X) @ CircuitStateFn(primitive=qc, coeff=1.0), - ~StateFn(Z) @ CircuitStateFn(primitive=qc, coeff=1.0), - ], - combo_fn=combo_fn, - grad_combo_fn=None if autograd else grad_combo_fn, - ) + with self.assertWarns(DeprecationWarning): + + op = ListOp( + [ + ~StateFn(X) @ CircuitStateFn(primitive=qc, coeff=1.0), + ~StateFn(Z) @ CircuitStateFn(primitive=qc, coeff=1.0), + ], + combo_fn=combo_fn, + grad_combo_fn=None if autograd else grad_combo_fn, + ) + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [ {a: np.pi / 4, b: np.pi}, {params[0]: np.pi / 4, params[1]: np.pi / 4}, @@ -839,8 +883,11 @@ def grad_combo_fn(x): return grad qc = RealAmplitudes(2, reps=1) - grad_op = ListOp([StateFn(qc.decompose())], combo_fn=combo_fn, grad_combo_fn=grad_combo_fn) - grad = Gradient(grad_method=method).convert(grad_op) + + with self.assertWarns(DeprecationWarning): + grad_op = ListOp([StateFn(qc.decompose())], combo_fn=combo_fn, grad_combo_fn=grad_combo_fn) + grad = Gradient(grad_method=method).convert(grad_op) + value_dict = dict(zip(qc.ordered_parameters, np.random.rand(len(qc.ordered_parameters)))) correct_values = [ [(-0.16666259133549044 + 0j)], @@ -871,12 +918,14 @@ def grad_combo_fn(x): try: qc = RealAmplitudes(2, reps=1) - grad_op = ListOp( - [StateFn(qc.decompose())], combo_fn=combo_fn, grad_combo_fn=grad_combo_fn - ) - grad = NaturalGradient(grad_method="lin_comb", regularization="ridge").convert( - grad_op, qc.ordered_parameters - ) + + with self.assertWarns(DeprecationWarning): + grad_op = ListOp( + [StateFn(qc.decompose())], combo_fn=combo_fn, grad_combo_fn=grad_combo_fn + ) + grad = NaturalGradient(grad_method="lin_comb", regularization="ridge").convert( + grad_op, qc.ordered_parameters + ) value_dict = dict( zip(qc.ordered_parameters, np.random.rand(len(qc.ordered_parameters))) ) @@ -904,10 +953,13 @@ def test_operator_coefficient_gradient(self, method): coeff_0 = Parameter("c_0") coeff_1 = Parameter("c_1") - ham = coeff_0 * X + coeff_1 * Z - op = StateFn(ham, is_measurement=True) @ CircuitStateFn(primitive=qc, coeff=1.0) - gradient_coeffs = [coeff_0, coeff_1] - coeff_grad = Gradient(grad_method=method).convert(op, gradient_coeffs) + + with self.assertWarns(DeprecationWarning): + ham = coeff_0 * X + coeff_1 * Z + op = StateFn(ham, is_measurement=True) @ CircuitStateFn(primitive=qc, coeff=1.0) + gradient_coeffs = [coeff_0, coeff_1] + coeff_grad = Gradient(grad_method=method).convert(op, gradient_coeffs) + values_dict = [ {coeff_0: 0.5, coeff_1: -1, a: np.pi / 4, b: np.pi}, {coeff_0: 0.5, coeff_1: -1, a: np.pi / 4, b: np.pi / 4}, @@ -941,10 +993,13 @@ def test_operator_coefficient_hessian(self, method): coeff_0 = Parameter("c_0") coeff_1 = Parameter("c_1") - ham = coeff_0 * coeff_0 * X + coeff_1 * coeff_0 * Z - op = StateFn(ham, is_measurement=True) @ CircuitStateFn(primitive=qc, coeff=1.0) - gradient_coeffs = [(coeff_0, coeff_0), (coeff_0, coeff_1), (coeff_1, coeff_1)] - coeff_grad = Hessian(hess_method=method).convert(op, gradient_coeffs) + + with self.assertWarns(DeprecationWarning): + ham = coeff_0 * coeff_0 * X + coeff_1 * coeff_0 * Z + op = StateFn(ham, is_measurement=True) @ CircuitStateFn(primitive=qc, coeff=1.0) + gradient_coeffs = [(coeff_0, coeff_0), (coeff_0, coeff_1), (coeff_1, coeff_1)] + coeff_grad = Hessian(hess_method=method).convert(op, gradient_coeffs) + values_dict = [ {coeff_0: 0.5, coeff_1: -1, a: np.pi / 4, b: np.pi}, {coeff_0: 0.5, coeff_1: -1, a: np.pi / 4, b: np.pi / 4}, @@ -967,7 +1022,6 @@ def test_circuit_sampler(self, method): d/db = - 1 sin(a)cos(b) """ - ham = 0.5 * X - 1 * Z a = Parameter("a") b = Parameter("b") params = [a, b] @@ -977,16 +1031,19 @@ def test_circuit_sampler(self, method): qc.h(q) qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - shots = 8000 - if method == "fin_diff": - np.random.seed(8) - state_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).convert( - operator=op - ) - else: - state_grad = Gradient(grad_method=method).convert(operator=op) + with self.assertWarns(DeprecationWarning): + ham = 0.5 * X - 1 * Z + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + shots = 8000 + if method == "fin_diff": + np.random.seed(8) + state_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).convert( + operator=op + ) + else: + state_grad = Gradient(grad_method=method).convert(operator=op) + values_dict = [ {a: np.pi / 4, b: np.pi}, {params[0]: np.pi / 4, params[1]: np.pi / 4}, @@ -999,19 +1056,10 @@ def test_circuit_sampler(self, method): ] backend = BasicAer.get_backend("qasm_simulator") - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance(backend=backend, shots=shots) - self.assertTrue(len(caught_warnings) > 0) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): for i, value_dict in enumerate(values_dict): sampler = CircuitSampler(backend=q_instance).convert( state_grad, params={k: [v] for k, v in value_dict.items()} @@ -1019,7 +1067,6 @@ def test_circuit_sampler(self, method): np.testing.assert_array_almost_equal( sampler.eval()[0], correct_values[i], decimal=1 ) - self.assertTrue(len(caught_warnings) > 0) @data("lin_comb", "param_shift", "fin_diff") def test_circuit_sampler2(self, method): @@ -1041,16 +1088,17 @@ def test_circuit_sampler2(self, method): qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - op = CircuitStateFn(primitive=qc, coeff=1.0) + with self.assertWarns(DeprecationWarning): + op = CircuitStateFn(primitive=qc, coeff=1.0) + shots = 8000 + if method == "fin_diff": + np.random.seed(8) + prob_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).convert( + operator=op, params=params + ) + else: + prob_grad = Gradient(grad_method=method).convert(operator=op, params=params) - shots = 8000 - if method == "fin_diff": - np.random.seed(8) - prob_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).convert( - operator=op, params=params - ) - else: - prob_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [ {a: [np.pi / 4], b: [0]}, {params[0]: [np.pi / 4], params[1]: [np.pi / 4]}, @@ -1063,25 +1111,15 @@ def test_circuit_sampler2(self, method): ] backend = BasicAer.get_backend("qasm_simulator") - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance(backend=backend, shots=shots) - self.assertTrue(len(caught_warnings) > 0) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): for i, value_dict in enumerate(values_dict): sampler = CircuitSampler(backend=q_instance).convert(prob_grad, params=value_dict) result = sampler.eval()[0] self.assertTrue(np.allclose(result[0].toarray(), correct_values[i][0], atol=0.1)) self.assertTrue(np.allclose(result[1].toarray(), correct_values[i][1], atol=0.1)) - self.assertTrue(len(caught_warnings) > 0) @idata(["statevector_simulator", "qasm_simulator"]) def test_gradient_wrapper(self, backend_type): @@ -1102,34 +1140,25 @@ def test_gradient_wrapper(self, backend_type): qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - op = CircuitStateFn(primitive=qc, coeff=1.0) + with self.assertWarns(DeprecationWarning): + op = CircuitStateFn(primitive=qc, coeff=1.0) shots = 8000 backend = BasicAer.get_backend(backend_type) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance( backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2 ) - self.assertTrue(len(caught_warnings) > 0) - if method == "fin_diff": - np.random.seed(8) - prob_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).gradient_wrapper( - operator=op, bind_params=params, backend=q_instance - ) - else: - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - prob_grad = Gradient(grad_method=method).gradient_wrapper( + with self.assertWarns(DeprecationWarning): + if method == "fin_diff": + np.random.seed(8) + prob_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).gradient_wrapper( operator=op, bind_params=params, backend=q_instance ) - self.assertTrue(len(caught_warnings) > 0) + else: + prob_grad = Gradient(grad_method=method).gradient_wrapper( + operator=op, bind_params=params, backend=q_instance + ) values = [[np.pi / 4, 0], [np.pi / 4, np.pi / 4], [np.pi / 2, np.pi]] correct_values = [ @@ -1137,11 +1166,7 @@ def test_gradient_wrapper(self, backend_type): [[1 / 4, -1 / 4], [1 / 4, -1 / 4]], [[0, 0], [-1 / 2, 1 / 2]], ] - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): for i, value in enumerate(values): result = prob_grad(value) if backend_type == "qasm_simulator": # sparse result @@ -1149,7 +1174,6 @@ def test_gradient_wrapper(self, backend_type): self.assertTrue(np.allclose(result[0], correct_values[i][0], atol=0.1)) self.assertTrue(np.allclose(result[1], correct_values[i][1], atol=0.1)) - self.assertTrue(len(caught_warnings) > 0) @data(("statevector_simulator", 1e-7), ("qasm_simulator", 2e-1)) @unpack @@ -1176,35 +1200,27 @@ def test_gradient_wrapper2(self, backend_type, atol): qc.rz(params[1], 0) qc.h(1) - obs = (Z ^ X) - (Y ^ Y) - op = StateFn(obs, is_measurement=True) @ CircuitStateFn(primitive=qc) + with self.assertWarns(DeprecationWarning): + obs = (Z ^ X) - (Y ^ Y) + op = StateFn(obs, is_measurement=True) @ CircuitStateFn(primitive=qc) shots = 8192 if backend_type == "qasm_simulator" else 1 values = [[0, np.pi / 2], [np.pi / 4, np.pi / 4], [np.pi / 3, np.pi / 9]] correct_values = [[-4.0, 0], [-2.0, -4.82842712], [-0.68404029, -7.01396121]] - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - for i, value in enumerate(values): - backend = BasicAer.get_backend(backend_type) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - q_instance = QuantumInstance( - backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2 - ) - self.assertTrue(len(caught_warnings) > 0) + + for i, value in enumerate(values): + backend = BasicAer.get_backend(backend_type) + with self.assertWarns(DeprecationWarning): + q_instance = QuantumInstance( + backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2 + ) + with self.assertWarns(DeprecationWarning): grad = NaturalGradient(grad_method=method).gradient_wrapper( operator=op, bind_params=params, backend=q_instance ) result = grad(value) - self.assertTrue(np.allclose(result, correct_values[i], atol=atol)) - self.assertTrue(len(caught_warnings) > 0) + self.assertTrue(np.allclose(result, correct_values[i], atol=atol)) @slow_test def test_vqe(self): @@ -1212,19 +1228,14 @@ def test_vqe(self): method = "lin_comb" backend = "qasm_simulator" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance( BasicAer.get_backend(backend), seed_simulator=79, seed_transpiler=2 ) - self.assertTrue(len(caught_warnings) > 0) - # Define the Hamiltonian - h2_hamiltonian = ( - -1.05 * (I ^ I) + 0.39 * (I ^ Z) - 0.39 * (Z ^ I) - 0.01 * (Z ^ Z) + 0.18 * (X ^ X) - ) + # Define the Hamiltonian + h2_hamiltonian = ( + -1.05 * (I ^ I) + 0.39 * (I ^ Z) - 0.39 * (Z ^ I) - 0.01 * (Z ^ Z) + 0.18 * (X ^ X) + ) h2_energy = -1.85727503 # Define the Ansatz @@ -1241,22 +1252,17 @@ def test_vqe(self): wavefunction.rz(next(itr), 0) wavefunction.rz(next(itr), 1) - # Conjugate Gradient algorithm - optimizer = CG(maxiter=10) - - grad = Gradient(grad_method=method) + with self.assertWarns(DeprecationWarning): + # Conjugate Gradient algorithm + optimizer = CG(maxiter=10) + grad = Gradient(grad_method=method) # Gradient callable - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): vqe = VQE( ansatz=wavefunction, optimizer=optimizer, gradient=grad, quantum_instance=q_instance ) result = vqe.compute_minimum_eigenvalue(operator=h2_hamiltonian) - self.assertTrue(len(caught_warnings) > 0) np.testing.assert_almost_equal(result.optimal_value, h2_energy, decimal=0) def test_qfi_overlap_works_with_bound_parameters(self): @@ -1266,15 +1272,18 @@ def test_qfi_overlap_works_with_bound_parameters(self): circuit = QuantumCircuit(1) circuit.ry(np.pi / 4, 0) circuit.rx(x, 0) - state = StateFn(circuit) + + with self.assertWarns(DeprecationWarning): + state = StateFn(circuit) methods = ["lin_comb_full", "overlap_diag", "overlap_block_diag"] reference = 0.5 for method in methods: with self.subTest(method): - qfi = QFI(method) - value = np.real(qfi.convert(state, [x]).bind_parameters({x: 0.12}).eval()) + with self.assertWarns(DeprecationWarning): + qfi = QFI(method) + value = np.real(qfi.convert(state, [x]).bind_parameters({x: 0.12}).eval()) self.assertAlmostEqual(value[0][0], reference) @@ -1336,9 +1345,10 @@ def test_qfi_simple(self, method): qc.rz(a, 0) qc.rx(b, 0) - # convert the circuit to a QFI object - op = CircuitStateFn(qc) - qfi = QFI(qfi_method=method).convert(operator=op) + with self.assertWarns(DeprecationWarning): + # convert the circuit to a QFI object + op = CircuitStateFn(qc) + qfi = QFI(qfi_method=method).convert(operator=op) # test for different values values_dict = [{a: np.pi / 4, b: 0.1}, {a: np.pi, b: 0.1}, {a: np.pi / 2, b: 0.1}] @@ -1360,15 +1370,17 @@ def test_qfi_phase_fix(self): qc.rz(a, 0) qc.rx(b, 0) - # convert the circuit to a QFI object - op = CircuitStateFn(qc) - qfi = LinCombFull(phase_fix=False).convert(operator=op, params=[a, b]) + with self.assertWarns(DeprecationWarning): + # convert the circuit to a QFI object + op = CircuitStateFn(qc) + qfi = LinCombFull(phase_fix=False).convert(operator=op, params=[a, b]) # test for different values value_dict = {a: np.pi / 4, b: 0.1} correct_values = [[1, 0], [0, 1]] - actual = qfi.assign_parameters(value_dict).eval() + with self.assertWarns(DeprecationWarning): + actual = qfi.assign_parameters(value_dict).eval() np.testing.assert_array_almost_equal(actual, correct_values, decimal=2) def test_qfi_maxcut(self): @@ -1405,9 +1417,10 @@ def expiz(qubit0, qubit1): # reference computed via finite difference reference = np.array([[16.0, -5.551], [-5.551, 18.497]]) - # QFI from gradient framework - qfi = QFI().convert(CircuitStateFn(ansatz), params=x[:]) - actual = np.array(qfi.bind_parameters(point).eval()).real + with self.assertWarns(DeprecationWarning): + # QFI from gradient framework + qfi = QFI().convert(CircuitStateFn(ansatz), params=x[:]) + actual = np.array(qfi.bind_parameters(point).eval()).real np.testing.assert_array_almost_equal(actual, reference, decimal=3) def test_qfi_circuit_shared_params(self): @@ -1476,28 +1489,29 @@ def test_qfi_circuit_shared_params(self): circuit6.cx(1, 0) circuit6.h(1) - # compare - qfi = QFI().convert(StateFn(circuit), params=[x]) + with self.assertWarns(DeprecationWarning): + # compare + qfi = QFI().convert(StateFn(circuit), params=[x]) - circuit_sets = ( - [circuit1, circuit2, circuit3, circuit4], - [circuit5, circuit6], - [circuit5, circuit6], - ) - list_ops = ( - qfi.oplist[0].oplist[0].oplist[:-1], - qfi.oplist[0].oplist[0].oplist[-1].oplist[0].oplist, - qfi.oplist[0].oplist[0].oplist[-1].oplist[1].oplist, - ) + circuit_sets = ( + [circuit1, circuit2, circuit3, circuit4], + [circuit5, circuit6], + [circuit5, circuit6], + ) + list_ops = ( + qfi.oplist[0].oplist[0].oplist[:-1], + qfi.oplist[0].oplist[0].oplist[-1].oplist[0].oplist, + qfi.oplist[0].oplist[0].oplist[-1].oplist[1].oplist, + ) - # compose both on the same circuit such that the comparison works - base = QuantumCircuit(2) + # compose both on the same circuit such that the comparison works + base = QuantumCircuit(2) - for i, (circuit_set, list_op) in enumerate(zip(circuit_sets, list_ops)): - for j, (reference, composed_op) in enumerate(zip(circuit_set, list_op)): - with self.subTest(f"set {i} circuit {j}"): - primitive = composed_op[1].primitive - self.assertEqual(base.compose(primitive), base.compose(reference)) + for i, (circuit_set, list_op) in enumerate(zip(circuit_sets, list_ops)): + for j, (reference, composed_op) in enumerate(zip(circuit_set, list_op)): + with self.subTest(f"set {i} circuit {j}"): + primitive = composed_op[1].primitive + self.assertEqual(base.compose(primitive), base.compose(reference)) def test_overlap_qfi_bound_parameters(self): """Test the overlap QFI works on a circuit with multi-parameter bound gates.""" @@ -1506,8 +1520,10 @@ def test_overlap_qfi_bound_parameters(self): circuit.u(1, 2, 3, 0) circuit.rx(x, 0) - qfi = QFI("overlap_diag").convert(StateFn(circuit), [x]) - value = qfi.bind_parameters({x: 1}).eval()[0][0] + with self.assertWarns(DeprecationWarning): + qfi = QFI("overlap_diag").convert(StateFn(circuit), [x]) + value = qfi.bind_parameters({x: 1}).eval()[0][0] + ref = 0.87737713 self.assertAlmostEqual(value, ref) @@ -1518,7 +1534,8 @@ def test_overlap_qfi_raises_on_multiparam(self): circuit.u(x[0], x[1], 2, 0) with self.assertRaises(NotImplementedError): - _ = QFI("overlap_diag").convert(StateFn(circuit), [x]) + with self.assertWarns(DeprecationWarning): + _ = QFI("overlap_diag").convert(StateFn(circuit), [x]) def test_overlap_qfi_raises_on_unsupported_gate(self): """Test the overlap QFI raises an appropriate error on multi-param unbound gates.""" @@ -1527,7 +1544,8 @@ def test_overlap_qfi_raises_on_unsupported_gate(self): circuit.p(x, 0) with self.assertRaises(NotImplementedError): - _ = QFI("overlap_diag").convert(StateFn(circuit), [x]) + with self.assertWarns(DeprecationWarning): + _ = QFI("overlap_diag").convert(StateFn(circuit), [x]) @data(-Y, Z - 1j * Y) def test_aux_meas_op(self, aux_meas_op): @@ -1535,7 +1553,6 @@ def test_aux_meas_op(self, aux_meas_op): Gradient. """ - a = Parameter("a") b = Parameter("b") params = [a, b] @@ -1546,11 +1563,11 @@ def test_aux_meas_op(self, aux_meas_op): qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - op = CircuitStateFn(primitive=qc, coeff=1.0) + with self.assertWarns(DeprecationWarning): + op = CircuitStateFn(primitive=qc, coeff=1.0) + prob_grad = LinComb(aux_meas_op=aux_meas_op).convert(operator=op, params=params) shots = 10000 - - prob_grad = LinComb(aux_meas_op=aux_meas_op).convert(operator=op, params=params) value_dicts = [{a: [np.pi / 4], b: [0]}, {a: [np.pi / 2], b: [np.pi / 4]}] if aux_meas_op == -Y: correct_values = [ @@ -1566,33 +1583,22 @@ def test_aux_meas_op(self, aux_meas_op): ], ] - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - for backend_type in ["qasm_simulator", "statevector_simulator"]: - - for j, value_dict in enumerate(value_dicts): - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - q_instance = QuantumInstance( - backend=BasicAer.get_backend(backend_type), shots=shots - ) - self.assertTrue(len(caught_warnings) > 0) + for backend_type in ["qasm_simulator", "statevector_simulator"]: + for j, value_dict in enumerate(value_dicts): + with self.assertWarns(DeprecationWarning): + q_instance = QuantumInstance( + backend=BasicAer.get_backend(backend_type), shots=shots + ) + with self.assertWarns(DeprecationWarning): result = ( CircuitSampler(backend=q_instance) .convert(prob_grad, params=value_dict) .eval()[0] ) - if backend_type == "qasm_simulator": # sparse result - result = [result[0].toarray()[0], result[1].toarray()[0]] - for i, item in enumerate(result): - np.testing.assert_array_almost_equal(item, correct_values[j][i], decimal=1) - self.assertTrue(len(caught_warnings) > 0) + if backend_type == "qasm_simulator": # sparse result + result = [result[0].toarray()[0], result[1].toarray()[0]] + for i, item in enumerate(result): + np.testing.assert_array_almost_equal(item, correct_values[j][i], decimal=1) def test_unsupported_aux_meas_op(self): """Test error for unsupported auxiliary measurement operator in LinComb Gradient. @@ -1613,25 +1619,20 @@ def test_unsupported_aux_meas_op(self): qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - op = CircuitStateFn(primitive=qc, coeff=1.0) + with self.assertWarns(DeprecationWarning): + op = CircuitStateFn(primitive=qc, coeff=1.0) shots = 8000 aux_meas_op = X + with self.assertWarns(DeprecationWarning): + with self.assertRaises(ValueError): + prob_grad = LinComb(aux_meas_op=aux_meas_op).convert(operator=op, params=params) + value_dict = {a: [np.pi / 4], b: [0]} - with self.assertRaises(ValueError): - prob_grad = LinComb(aux_meas_op=aux_meas_op).convert(operator=op, params=params) - value_dict = {a: [np.pi / 4], b: [0]} - - backend = BasicAer.get_backend("qasm_simulator") - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + backend = BasicAer.get_backend("qasm_simulator") q_instance = QuantumInstance(backend=backend, shots=shots) - self.assertTrue(len(caught_warnings) > 0) - CircuitSampler(backend=q_instance).convert(prob_grad, params=value_dict).eval() + CircuitSampler(backend=q_instance).convert(prob_grad, params=value_dict).eval() def test_nat_grad_error(self): """Test the NaturalGradient throws an Error. @@ -1655,41 +1656,25 @@ def test_nat_grad_error(self): qc.rz(params[1], 0) qc.h(1) - obs = (Z ^ X) - (Y ^ Y) - op = StateFn(obs, is_measurement=True) @ CircuitStateFn(primitive=qc) + with self.assertWarns(DeprecationWarning): + obs = (Z ^ X) - (Y ^ Y) + op = StateFn(obs, is_measurement=True) @ CircuitStateFn(primitive=qc) backend_type = "qasm_simulator" shots = 1 value = [0, np.pi / 2] backend = BasicAer.get_backend(backend_type) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance( backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2 ) - self.assertTrue(len(caught_warnings) > 0) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): grad = NaturalGradient(grad_method=method).gradient_wrapper( operator=op, bind_params=params, backend=q_instance ) - self.assertTrue(len(caught_warnings) > 0) - - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) with self.assertRaises(ValueError): grad(value) - self.assertTrue(len(caught_warnings) > 0) if __name__ == "__main__":