def test_unsupported_operations(self): """Assert unsupported operations raise an error.""" cvar = CVaRMeasurement(Z) attrs = [ 'to_matrix', 'to_matrix_op', 'to_density_matrix', 'to_circuit_op', 'sample' ] for attr in attrs: with self.subTest(attr): with self.assertRaises(NotImplementedError): _ = getattr(cvar, attr)() with self.subTest('adjoint'): with self.assertRaises(AquaError): cvar.adjoint()
def test_cvar_simple_with_coeff(self): """Test a simple case with a non-unity coefficient""" theta = 2.2 qc = QuantumCircuit(1) qc.ry(theta, 0) statefn = StateFn(qc) alpha = 0.2 cvar = ((-1 * CVaRMeasurement(Z, alpha)) @ statefn).eval() ref = self.expected_cvar(statefn.to_matrix(), Z, alpha) self.assertAlmostEqual(cvar, -1 * ref)
def test_cvar_simple(self): """Test a simple case with a single Pauli.""" theta = 1.2 qc = QuantumCircuit(1) qc.ry(theta, 0) statefn = StateFn(qc) for alpha in [0.2, 0.4, 1]: with self.subTest(alpha=alpha): cvar = (CVaRMeasurement(Z, alpha) @ statefn).eval() ref = self.expected_cvar(statefn.to_matrix(), Z, alpha) self.assertAlmostEqual(cvar, ref)
def invalid_input(self): """Test invalid input raises an error.""" op = Z with self.subTest('alpha < 0'): with self.assertRaises(ValueError): _ = CVaRMeasurement(op, alpha=-0.2) with self.subTest('alpha > 1'): with self.assertRaises(ValueError): _ = CVaRMeasurement(op, alpha=12.3) with self.subTest('Single pauli operator not diagonal'): op = Y with self.assertRaises(AquaError): _ = CVaRMeasurement(op) with self.subTest('Summed pauli operator not diagonal'): op = X ^ Z + Z ^ I with self.assertRaises(AquaError): _ = CVaRMeasurement(op) with self.subTest('List operator not diagonal'): op = ListOp([X ^ Z, Z ^ I]) with self.assertRaises(AquaError): _ = CVaRMeasurement(op) with self.subTest('Matrix operator not diagonal'): op = MatrixOp([[1, 1], [0, 1]]) with self.assertRaises(AquaError): _ = CVaRMeasurement(op)
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_add(self): """Test addition.""" theta = 2.2 qc = QuantumCircuit(1) qc.ry(theta, 0) statefn = StateFn(qc) alpha = 0.2 cvar = -1 * CVaRMeasurement(Z, alpha) ref = self.expected_cvar(statefn.to_matrix(), Z, alpha) other = ~StateFn(I) # test add in both directions res1 = ((cvar + other) @ statefn).eval() res2 = ((other + other) @ statefn).eval() self.assertAlmostEqual(res1, 1 - ref) self.assertAlmostEqual(res2, 1 - ref)