def test_compute_variance(self): """Test if the compute_variance method works""" alphas = [0, .3, 0.5, 0.7, 1] correct_vars = [0, 0, 0, 0.8163, 1] for i, alpha in enumerate(alphas): base_expecation = PauliExpectation() cvar_expecation = CVaRExpectation(alpha=alpha, expectation=base_expecation) op = ~StateFn(Z ^ Z) @ (Plus ^ Plus) cvar_var = cvar_expecation.compute_variance(op) np.testing.assert_almost_equal(cvar_var, correct_vars[i], decimal=3)
def test_underlying_expectation(self, base_expecation): """Test the underlying expectation works correctly.""" cvar_expecation = CVaRExpectation(alpha=0.3, expectation=base_expecation) circuit = QuantumCircuit(2) circuit.z(0) circuit.cp(0.5, 0, 1) circuit.t(1) op = ~StateFn(CircuitOp(circuit)) @ (Plus ^ 2) cvar = cvar_expecation.convert(op) expected = base_expecation.convert(op) # test if the operators have been transformed in the same manner self.assertEqual(cvar.oplist[0].primitive, expected.oplist[0].primitive)
def test_construction(self): """Test the correct operator expression is constructed.""" alpha = 0.5 base_expecation = PauliExpectation() cvar_expecation = CVaRExpectation(alpha=alpha, expectation=base_expecation) with self.subTest('single operator'): op = ~StateFn(Z) @ Plus expected = CVaRMeasurement(Z, alpha) @ Plus cvar = cvar_expecation.convert(op) self.assertEqual(cvar, expected) with self.subTest('list operator'): op = ~StateFn(ListOp([Z ^ Z, I ^ Z])) @ (Plus ^ Plus) expected = ListOp([ CVaRMeasurement((Z ^ Z), alpha) @ (Plus ^ Plus), CVaRMeasurement((I ^ Z), alpha) @ (Plus ^ Plus) ]) cvar = cvar_expecation.convert(op) self.assertEqual(cvar, expected)
def test_unsupported_operations(self): """Assert unsupported operations raise an error.""" cvar = CVaRExpectation(0.2) with self.assertRaises(NotImplementedError): cvar.compute_variance(Z)
def test_unsupported_expectation(self): """Assert passing an AerPauliExpectation raises an error.""" expecation = AerPauliExpectation() with self.assertRaises(NotImplementedError): _ = CVaRExpectation(alpha=1, expectation=expecation)