示例#1
0
    def test_torch(self, tol):
        """Test that the covariance matrix computes the correct
        result, and is differentiable, using the Torch interface"""
        dev = qml.device("default.qubit", wires=3)

        @qml.qnode(dev, interface="torch")
        def circuit(weights):
            """Returns the shared probability distribution of ansatz
            in the joint basis for obs_list"""
            self.ansatz(weights, wires=dev.wires)

            for o in self.obs_list:
                o.diagonalizing_gates()

            return qml.probs(wires=[0, 1, 2])

        weights = np.array([0.1, 0.2, 0.3])
        weights_t = torch.tensor(weights, requires_grad=True)
        probs = circuit(weights_t)
        res = fn.cov_matrix(probs, self.obs_list)
        expected = self.expected_cov(weights)
        assert np.allclose(res.detach().numpy(), expected, atol=tol, rtol=0)

        loss = res[0, 1]
        loss.backward()
        res = weights_t.grad
        expected = self.expected_grad(weights)
        assert np.allclose(res.detach().numpy(), expected, atol=tol, rtol=0)
示例#2
0
    def test_tf(self, tol):
        """Test that the covariance matrix computes the correct
        result, and is differentiable, using the TF interface"""
        dev = qml.device("default.qubit", wires=3)

        @qml.qnode(dev, interface="tf")
        def circuit(weights):
            """Returns the shared probability distribution of ansatz
            in the joint basis for obs_list"""
            self.ansatz(weights, wires=dev.wires)

            for o in self.obs_list:
                o.diagonalizing_gates()

            return qml.probs(wires=[0, 1, 2])

        weights = np.array([0.1, 0.2, 0.3])
        weights_t = tf.Variable(weights)

        with tf.GradientTape() as tape:
            probs = circuit(weights_t)
            cov = fn.cov_matrix(probs, self.obs_list)
            loss = cov[0, 1]

        expected = self.expected_cov(weights)
        assert np.allclose(cov, expected, atol=tol, rtol=0)

        grad = tape.gradient(loss, weights_t)
        expected = self.expected_grad(weights)
        assert np.allclose(grad, expected, atol=tol, rtol=0)
示例#3
0
 def cov(weights):
     probs = circuit(weights)
     return fn.cov_matrix(probs, self.obs_list)
示例#4
0
 def cov(weights):
     probs = circuit(weights)
     return fn.cov_matrix(probs, obs_list, wires=dev.wires)