Ejemplo n.º 1
0
    def test_dict_to_circuit_sum(self):
        """Test DictToCircuitSum converter."""
        # Test qubits < entires, so dict is converted to Initialize CircuitStateFn
        dict_state_3q = StateFn({
            "101": 0.5,
            "100": 0.1,
            "000": 0.2,
            "111": 0.5
        })
        circuit_state_3q = DictToCircuitSum().convert(dict_state_3q)
        self.assertIsInstance(circuit_state_3q, CircuitStateFn)
        np.testing.assert_array_almost_equal(dict_state_3q.to_matrix(),
                                             circuit_state_3q.to_matrix())

        # Test qubits >= entires, so dict is converted to Initialize CircuitStateFn
        dict_state_4q = dict_state_3q ^ Zero
        circuit_state_4q = DictToCircuitSum().convert(dict_state_4q)
        self.assertIsInstance(circuit_state_4q, SummedOp)
        np.testing.assert_array_almost_equal(dict_state_4q.to_matrix(),
                                             circuit_state_4q.to_matrix())

        # Test VectorStateFn conversion
        vect_state_3q = dict_state_3q.to_matrix_op()
        circuit_state_3q_vect = DictToCircuitSum().convert(vect_state_3q)
        self.assertIsInstance(circuit_state_3q_vect, CircuitStateFn)
        np.testing.assert_array_almost_equal(vect_state_3q.to_matrix(),
                                             circuit_state_3q_vect.to_matrix())
    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 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)