Пример #1
0
    def test_args(self):
        """Test that the plugin requires correct arguments"""
        self.logTestName()

        with self.assertRaisesRegex(
                TypeError, "missing 1 required positional argument: 'wires'"):
            qml.device("default.qubit")
Пример #2
0
    def test_outdated_API(self, n):
        """Test exception raised if plugin that targets an old API is loaded"""
        self.logTestName()

        with self.assertRaisesRegex(qml.DeviceError,
                                    'plugin requires PennyLane versions'):
            qml.device('default.qubit', wires=0)
Пример #3
0
 def test_initiatlization_via_pennylane(self):
     for short_name in [
             'qiskit.aer', 'qiskit.legacy', 'qiskit.basicaer', 'qiskit.ibm'
     ]:
         try:
             qml.device(short_name, wires=2, ibmqx_token=IBMQX_TOKEN)
         except DeviceError:
             raise Exception(
                 "This test is expected to fail until pennylane-qiskit is installed."
             )
Пример #4
0
 def test_aer_device(self):
     if self.args.provider in ['aer', 'all']:
         import qiskit
         try:
             for backend in qiskit.Aer.backends():
                 qml.device('qiskit.aer', wires=1, backend=backend)
         except DeviceError:
             raise Exception(
                 "This test is expected to fail until pennylane-qiskit is installed."
             )
    def test_unsupported_observables(self):
        """Test error is raised with unsupported observables"""
        self.logTestName()
        dev = qml.device('default.gaussian', wires=2)

        obs = set(dev._expectation_map.keys())
        all_obs = {
            m[0]
            for m in inspect.getmembers(qml.expval, inspect.isclass)
        }

        for g in all_obs - obs:
            op = getattr(qml.expval, g)

            if op.num_wires == 0:
                wires = [0]
            else:
                wires = list(range(op.num_wires))

            @qml.qnode(dev)
            def circuit(*x):
                """Test quantum function"""
                x = prep_par(x, op)
                return op(*x, wires=wires)

            with self.assertRaisesRegex(
                    qml.DeviceError,
                    "Expectation {} not supported on device default.gaussian".
                    format(g)):
                x = np.random.random([op.num_params])
                circuit(*x)
Пример #6
0
    def test_simple_circuits(self):

        default_qubit = qml.device('default.qubit', wires=4)

        for dev in self.devices:
            gates = [
                qml.PauliX(wires=0),
                qml.PauliY(wires=1),
                qml.PauliZ(wires=2),
                qml.S(wires=3),
                qml.T(wires=0),
                qml.RX(2.3, wires=1),
                qml.RY(1.3, wires=2),
                qml.RZ(3.3, wires=3),
                qml.Hadamard(wires=0),
                qml.Rot(0.1, 0.2, 0.3, wires=1),
                qml.CRot(0.1, 0.2, 0.3, wires=[2, 3]),
                qml.Toffoli(wires=[0, 1, 2]),
                qml.SWAP(wires=[1, 2]),
                qml.CSWAP(wires=[1, 2, 3]),
                qml.U1(1.0, wires=0),
                qml.U2(1.0, 2.0, wires=2),
                qml.U3(1.0, 2.0, 3.0, wires=3),
                qml.CRX(0.1, wires=[1, 2]),
                qml.CRY(0.2, wires=[2, 3]),
                qml.CRZ(0.3, wires=[3, 1]),
                qml.CZ(wires=[2, 3]),
                qml.QubitUnitary(np.array([[1, 0], [0, 1]]), wires=2),
            ]

            layers = 3
            np.random.seed(1967)
            gates_per_layers = [
                np.random.permutation(gates).numpy() for _ in range(layers)
            ]

            for obs in {
                    qml.PauliX(wires=0),
                    qml.PauliY(wires=0),
                    qml.PauliZ(wires=0),
                    qml.Identity(wires=0),
                    qml.Hadamard(wires=0)
            }:
                if obs.name in dev.observables:

                    def circuit():
                        """4-qubit circuit with layers of randomly selected gates and random connections for
                        multi-qubit gates."""
                        qml.BasisState(np.array([1, 0, 0, 0]),
                                       wires=[0, 1, 2, 3])
                        for gates in gates_per_layers:
                            for gate in gates:
                                if gate.name in dev.operations:
                                    qml.apply(gate)
                        return qml.expval(obs)

                    qnode_default = qml.QNode(circuit, default_qubit)
                    qnode = qml.QNode(circuit, dev)

                    assert np.allclose(qnode(), qnode_default(), atol=1e-3)
Пример #7
0
    def test_execution(self):
        """Tests the StronglyEntanglingCircuit for various parameters."""
        np.random.seed(0)
        outcomes = []

        for num_wires in range(2, 4):
            for num_layers in range(1, 3):

                dev = qml.device('default.qubit', wires=num_wires)
                weights = np.random.randn(num_layers, num_wires, 3)

                @qml.qnode(dev)
                def circuit(weights, x=None):
                    qml.BasisState(x, wires=range(num_wires))
                    qml.template.StronglyEntanglingCircuit(
                        weights, True, wires=range(num_wires))
                    return qml.expval.PauliZ(0)

                outcomes.append(
                    circuit(weights,
                            x=np.array(np.random.randint(0, 1, num_wires))))

        res = np.array(outcomes)
        expected = np.array([-0.29242496, 0.22129055, 0.07540091, -0.77626557])
        self.assertAllAlmostEqual(res, expected, delta=self.tol)
Пример #8
0
    def test_exceptions(self):
        """test that exceptions are correctly raised"""
        dev = qml.device('default.gaussian', wires=1)
        varphi = [0.42342]

        @qml.qnode(dev)
        def circuit(varphi, mesh):
            qml.template.Interferometer(theta=None,
                                        phi=None,
                                        varphi=varphi,
                                        mesh=mesh,
                                        wires=0)
            return qml.expval.MeanPhoton(0)

        with self.assertRaisesRegex(
                QuantumFunctionError, "The mesh parameter influences the "
                "circuit architecture and can not be passed as a QNode parameter."
        ):
            circuit(varphi, 'rectangular')

        @qml.qnode(dev)
        def circuit(varphi, bs):
            qml.template.Interferometer(theta=None,
                                        phi=None,
                                        varphi=varphi,
                                        beamsplitter=bs,
                                        wires=0)
            return qml.expval.MeanPhoton(0)

        with self.assertRaisesRegex(
                QuantumFunctionError,
                "The beamsplitter parameter influences the "
                "circuit architecture and can not be passed as a QNode parameter."
        ):
            circuit(varphi, 'clements')
Пример #9
0
    def test_four_mode_triangular(self):
        """Test that a 4 mode interferometer using triangular mesh gives the correct gates"""
        N = 4
        wires = range(N)
        dev = qml.device('default.gaussian', wires=N)

        theta = [0.321, 0.4523, 0.21321, 0.123, 0.5234, 1.23]
        phi = [0.234, 0.324, 0.234, 1.453, 1.42341, -0.534]
        varphi = [0.42342, 0.234, 0.4523]

        def circuit_tria(varphi):
            qml.template.Interferometer(theta,
                                        phi,
                                        varphi,
                                        mesh='triangular',
                                        wires=wires)
            return [qml.expval.MeanPhoton(w) for w in wires]

        qnode = qml.QNode(circuit_tria, dev)
        self.assertAllAlmostEqual(qnode(varphi), [0] * N, delta=self.tol)

        queue = qnode.queue
        self.assertEqual(len(queue), 9)

        expected_bs_wires = [[2, 3], [1, 2], [0, 1], [2, 3], [1, 2], [2, 3]]

        for idx, op in enumerate(qnode.queue[:6]):
            self.assertTrue(isinstance(op, qml.Beamsplitter))
            self.assertAllEqual(op.parameters, [theta[idx], phi[idx]])
            self.assertAllEqual(op.wires, expected_bs_wires[idx])

        for idx, op in enumerate(qnode.queue[6:]):
            self.assertTrue(isinstance(op, qml.Rotation))
            self.assertAllEqual(op.parameters, [varphi[idx]])
            self.assertAllEqual(op.wires, [idx])
Пример #10
0
    def test_two_mode_rect_overparameterised(self):
        """Test that a two mode interferometer using the rectangular mesh
        correctly gives a beamsplitter+2 rotation gates when requested"""
        N = 2
        wires = range(N)
        dev = qml.device('default.gaussian', wires=N)

        theta = [0.321]
        phi = [0.234]
        varphi = [0.42342, 0.543]

        def circuit(varphi):
            qml.template.Interferometer(theta, phi, varphi, wires=wires)
            return [qml.expval.MeanPhoton(w) for w in wires]

        qnode = qml.QNode(circuit, dev)
        self.assertAllAlmostEqual(qnode(varphi), [0, 0], delta=self.tol)

        queue = qnode.queue
        self.assertEqual(len(queue), 3)

        self.assertTrue(isinstance(qnode.queue[0], qml.Beamsplitter))
        self.assertAllEqual(qnode.queue[0].parameters, theta + phi)

        self.assertTrue(isinstance(qnode.queue[1], qml.Rotation))
        self.assertAllEqual(qnode.queue[1].parameters, [varphi[0]])

        self.assertTrue(isinstance(qnode.queue[2], qml.Rotation))
        self.assertAllEqual(qnode.queue[2].parameters, [varphi[1]])
Пример #11
0
 def test_ibm_device(self):
     if self.args.provider in ['ibm', 'all']:
         import qiskit
         qiskit.IBMQ.enable_account(token=IBMQX_TOKEN)
         backends = qiskit.IBMQ.backends()
         qiskit.IBMQ.disable_accounts()
         try:
             for backend in backends:
                 qml.device('qiskit.ibm',
                            wires=1,
                            ibmqx_token=IBMQX_TOKEN,
                            backend=backend)
         except DeviceError:
             raise Exception(
                 "This test is expected to fail until pennylane-qiskit is installed."
             )
Пример #12
0
    def test_unsupported_observables(self):
        """Test error is raised with unsupported observables"""
        self.logTestName()
        dev = qml.device("default.qubit", wires=2)

        obs = set(dev._observable_map.keys())
        all_obs = set(qml.ops.__all_obs__)

        for g in all_obs - obs:
            op = getattr(qml.ops, g)

            if op.num_wires == 0:
                wires = [0]
            else:
                wires = list(range(op.num_wires))

            @qml.qnode(dev)
            def circuit(*x):
                """Test quantum function"""
                x = prep_par(x, op)
                return qml.expval(op(*x, wires=wires))

            with self.assertRaisesRegex(
                    qml.DeviceError,
                    "Observable {} not supported on device default.qubit".
                    format(g),
            ):
                x = np.random.random([op.num_params])
                circuit(*x)
Пример #13
0
    def setUp(self):
        self.default_devices = ['default.qubit', 'default.gaussian']

        self.dev = {}

        for device_name in self.default_devices:
            self.dev[device_name] = qml.device(device_name, wires=2)
Пример #14
0
    def test_unsupported_gates(self):
        """Test error is raised with unsupported gates"""
        self.logTestName()
        dev = qml.device("default.qubit", wires=2)

        gates = set(dev._operation_map.keys())
        all_gates = set(qml.ops.__all_ops__)

        for g in all_gates - gates:
            op = getattr(qml.ops, g)

            if op.num_wires == 0:
                wires = [0]
            else:
                wires = list(range(op.num_wires))

            @qml.qnode(dev)
            def circuit(*x):
                """Test quantum function"""
                x = prep_par(x, op)
                op(*x, wires=wires)

                if issubclass(op, qml.operation.CV):
                    return qml.expval(qml.X(0))

                return qml.expval(qml.PauliZ(0))

            with self.assertRaisesRegex(
                    qml.DeviceError,
                    "Gate {} not supported on device default.qubit".format(g),
            ):
                x = np.random.random([op.num_params])
                circuit(*x)
Пример #15
0
    def test_first_order_cv(self, tol):
        """Test variance of a first order CV expectation value"""
        dev = qml.device('default.gaussian', wires=1)

        @qml.qnode(dev)
        def circuit(r, phi):
            qml.Squeezing(r, 0, wires=0)
            qml.Rotation(phi, wires=0)
            return qml.var(qml.X(0))

        r = 0.543
        phi = -0.654

        var = circuit(r, phi)
        expected = np.exp(2 * r) * np.sin(phi)**2 + np.exp(
            -2 * r) * np.cos(phi)**2
        assert np.allclose(var, expected, atol=tol, rtol=0)

        # circuit jacobians
        gradA = circuit.jacobian([r, phi], method='A')
        gradF = circuit.jacobian([r, phi], method='F')
        expected = np.array([
            2 * np.exp(2 * r) * np.sin(phi)**2 -
            2 * np.exp(-2 * r) * np.cos(phi)**2,
            2 * np.sinh(2 * r) * np.sin(2 * phi)
        ])
        assert np.allclose(gradA, expected, atol=tol, rtol=0)
        assert np.allclose(gradF, expected, atol=tol, rtol=0)
Пример #16
0
    def test_qnode_evaluation_agrees(self):
        "Tests that simple example is consistent."
        self.logTestName()

        dev = qml.device('default.qubit', wires=2)

        @qml.qnode(dev, interface='autograd')
        def circuit(phi, theta):
            qml.RX(phi[0], wires=0)
            qml.RY(phi[1], wires=1)
            qml.CNOT(wires=[0, 1])
            qml.PhaseShift(theta[0], wires=0)
            return qml.expval(qml.PauliZ(0))

        @qml.qnode(dev, interface='tfe')
        def circuit_tfe(phi, theta):
            qml.RX(phi[0], wires=0)
            qml.RY(phi[1], wires=1)
            qml.CNOT(wires=[0, 1])
            qml.PhaseShift(theta[0], wires=0)
            return qml.expval(qml.PauliZ(0))

        phi = [0.5, 0.1]
        theta = [0.2]

        phi_t = tfe.Variable(phi)
        theta_t = tfe.Variable(theta)

        autograd_eval = circuit(phi, theta)
        tfe_eval = circuit_tfe(phi_t, theta_t)
        self.assertAllAlmostEqual(autograd_eval, tfe_eval.numpy(), delta=self.tol)
Пример #17
0
    def test_keywordarg_not_differentiated(self, tol):
        """Tests that qnodes do not differentiate w.r.t. keyword arguments."""
        a, b = 0.5, 0.54

        def circuit1(weights, x=0.3):
            qml.QubitStateVector(np.array([1, 0, 1, 1]) / np.sqrt(3),
                                 wires=[0, 1])
            qml.Rot(weights[0], weights[1], x, wires=0)
            qml.CNOT(wires=[0, 1])
            return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliY(1))

        dev = qml.device('default.qubit', wires=2)
        circuit1 = qml.QNode(circuit1, dev)

        def circuit2(weights):
            qml.QubitStateVector(np.array([1, 0, 1, 1]) / np.sqrt(3),
                                 wires=[0, 1])
            qml.Rot(weights[0], weights[1], 0.3, wires=0)
            qml.CNOT(wires=[0, 1])
            return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliY(1))

        circuit2 = qml.QNode(circuit2, dev)

        res1 = circuit1.jacobian([np.array([a, b])])
        res2 = circuit2.jacobian([np.array([a, b])])

        assert np.allclose(res1, res2, atol=tol, rtol=0)
Пример #18
0
    def test_differentiate_second_third_positional(self, tol):
        """Tests that the second and third positional arguments are differentiated."""
        def circuit4(a, b, c):
            qml.RX(b, wires=0)
            qml.RX(c, wires=1)
            return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1))

        dev = qml.device('default.qubit', wires=2)
        circuit4 = qml.QNode(circuit4, dev)

        a = 0.7418
        b = -5.
        c = np.pi / 7
        circuit_output = circuit4(a, b, c)
        expected_output = np.array([[np.cos(b), np.cos(c)]])
        assert np.allclose(circuit_output, expected_output, atol=tol, rtol=0)

        # circuit jacobians
        circuit_jacobian = circuit4.jacobian([a, b, c])
        expected_jacobian = np.array([[0., -np.sin(b), 0.],
                                      [0., 0., -np.sin(c)]])
        assert np.allclose(circuit_jacobian,
                           expected_jacobian,
                           atol=tol,
                           rtol=0)
Пример #19
0
    def test_multiple_expectation_jacobian_positional(self, tol):
        """Tests that qnodes using positional arguments return
        correct gradients for multiple expectation values."""
        a, b, c = 0.5, 0.54, 0.3

        def circuit(x, y, z):
            qml.QubitStateVector(np.array([1, 0, 1, 1]) / np.sqrt(3),
                                 wires=[0, 1])
            qml.Rot(x, y, z, wires=0)
            qml.CNOT(wires=[0, 1])
            return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliY(1))

        dev = qml.device('default.qubit', wires=2)
        circuit = qml.QNode(circuit, dev)

        # compare our manual Jacobian computation to theoretical result
        # Note: circuit.jacobian actually returns a full jacobian in this case
        res = circuit.jacobian(np.array([a, b, c]))
        assert np.allclose(self.expected_jacobian(a, b, c),
                           res,
                           atol=tol,
                           rtol=0)

        # compare our manual Jacobian computation to autograd
        # not sure if this is the intended usage of jacobian
        jac0 = qml.jacobian(circuit, 0)
        jac1 = qml.jacobian(circuit, 1)
        jac2 = qml.jacobian(circuit, 2)
        res = np.stack([jac0(a, b, c), jac1(a, b, c), jac2(a, b, c)]).T

        assert np.allclose(self.expected_jacobian(a, b, c),
                           res,
                           atol=tol,
                           rtol=0)
Пример #20
0
    def test_multiple_expectation_jacobian_array(self, tol):
        """Tests that qnodes using an array argument return correct gradients
        for multiple expectation values."""
        a, b, c = 0.5, 0.54, 0.3

        def circuit(weights):
            qml.QubitStateVector(np.array([1, 0, 1, 1]) / np.sqrt(3),
                                 wires=[0, 1])
            qml.Rot(weights[0], weights[1], weights[2], wires=0)
            qml.CNOT(wires=[0, 1])
            return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliY(1))

        dev = qml.device('default.qubit', wires=2)
        circuit = qml.QNode(circuit, dev)

        res = circuit.jacobian([np.array([a, b, c])])
        assert np.allclose(self.expected_jacobian(a, b, c),
                           res,
                           atol=tol,
                           rtol=0)

        jac = qml.jacobian(circuit, 0)
        res = jac(np.array([a, b, c]))
        assert np.allclose(self.expected_jacobian(a, b, c),
                           res,
                           atol=tol,
                           rtol=0)
Пример #21
0
    def test_multidim_array(self, s, tol):
        """Tests that arguments which are multidimensional arrays are
        properly evaluated and differentiated in QNodes."""

        multidim_array = np.reshape(b, s)

        def circuit(w):
            qml.RX(w[np.unravel_index(0, s)], wires=0)  # b[0]
            qml.RX(w[np.unravel_index(1, s)], wires=1)  # b[1]
            qml.RX(w[np.unravel_index(2, s)], wires=2)  # ...
            qml.RX(w[np.unravel_index(3, s)], wires=3)
            qml.RX(w[np.unravel_index(4, s)], wires=4)
            qml.RX(w[np.unravel_index(5, s)], wires=5)
            qml.RX(w[np.unravel_index(6, s)], wires=6)
            qml.RX(w[np.unravel_index(7, s)], wires=7)
            return tuple(qml.expval(qml.PauliZ(idx)) for idx in range(len(b)))

        dev = qml.device('default.qubit', wires=8)
        circuit = qml.QNode(circuit, dev)

        # circuit evaluations
        circuit_output = circuit(multidim_array)
        expected_output = np.cos(b)
        assert np.allclose(circuit_output, expected_output, atol=tol, rtol=0)

        # circuit jacobians
        circuit_jacobian = circuit.jacobian([multidim_array])
        expected_jacobian = -np.diag(np.sin(b))
        assert np.allclose(circuit_jacobian,
                           expected_jacobian,
                           atol=tol,
                           rtol=0)
Пример #22
0
    def test_caching(self):
        """Test that the circuit structure does not change on
        subsequent evalutions with caching turned on
        """
        dev = qml.device('default.qubit', wires=2)

        def circuit(x, c=None):
            qml.RX(x, wires=0)

            for i in range(c.val):
                qml.RX(x, wires=i)

            return qml.expval(qml.PauliZ(0))

        circuit = qml.QNode(circuit, dev, cache=True)

        # first evaluation
        circuit(0, c=0)
        # check structure
        assert len(circuit.queue) == 1

        # second evaluation
        circuit(0, c=1)
        # check structure
        assert len(circuit.queue) == 1
Пример #23
0
    def test_obs_queue(self):
        """Check that peaking at the obs queue works correctly"""
        self.logTestName()

        # queue some gates
        queue = []
        queue.append(qml.RX(0.543, wires=[0], do_queue=False))
        queue.append(qml.CNOT(wires=[0, 1], do_queue=False))

        dev = qml.device('default.qubit', wires=2)

        # outside of an execution context, error will be raised
        with self.assertRaisesRegex(
                ValueError,
                "Cannot access the observable value queue outside of the execution context!"
        ):
            dev.obs_queue

        # inside of the execute method, it works
        with self.assertLogs(level='INFO') as l:
            dev.execute(queue, [qml.expval(qml.PauliX(0, do_queue=False))])
            self.assertEqual(len(l.output), 1)
            self.assertEqual(len(l.records), 1)
            self.assertIn('INFO:root:[<pennylane.ops.qubit.PauliX object',
                          l.output[0])
Пример #24
0
    def test_differentiate_positional_multidim(self, tol):
        """Tests that all positional arguments are differentiated
        when they are multidimensional."""
        def circuit(a, b):
            qml.RX(a[0], wires=0)
            qml.RX(a[1], wires=1)
            qml.RX(b[2, 1], wires=2)
            return qml.expval(qml.PauliZ(0)), qml.expval(
                qml.PauliZ(1)), qml.expval(qml.PauliZ(2))

        dev = qml.device('default.qubit', wires=3)
        circuit = qml.QNode(circuit, dev)

        a = np.array([-np.sqrt(2), -0.54])
        b = np.array([np.pi / 7] * 6).reshape([3, 2])
        circuit_output = circuit(a, b)
        expected_output = np.cos(np.array([[a[0], a[1], b[-1, 0]]]))
        assert np.allclose(circuit_output, expected_output, atol=tol, rtol=0)

        # circuit jacobians
        circuit_jacobian = circuit.jacobian([a, b])
        expected_jacobian = np.array([
            [-np.sin(a[0])] + [0.] * 7,  # expval 0
            [0., -np.sin(a[1])] + [0.] * 6,  # expval 1
            [0.] * 2 + [0.] * 5 + [-np.sin(b[2, 1])]
        ])  # expval 2
        assert np.allclose(circuit_jacobian,
                           expected_jacobian,
                           atol=tol,
                           rtol=0)
Пример #25
0
    def test_supported_gates(self):
        """Test that all supported gates work correctly"""
        self.logTestName()
        a = 0.312

        dev = qml.device('default.gaussian', wires=2)

        for g, qop in dev._operation_map.items():
            log.debug('\tTesting gate %s...', g)
            self.assertTrue(dev.supported(g))
            dev.reset()

            op = getattr(qml.ops, g)
            if op.num_wires == 0:
                wires = list(range(2))
            else:
                wires = list(range(op.num_wires))

            @qml.qnode(dev)
            def circuit(*x):
                """Reference quantum function"""
                qml.Displacement(a, 0, wires=[0])
                op(*x, wires=wires)
                return qml.expval.X(0)

            # compare to reference result
            def reference(*x):
                """reference circuit"""
                if g == 'GaussianState':
                    return x[0][0]

                if g == 'Displacement':
                    alpha = x[0] * np.exp(1j * x[1])
                    return (alpha + a).real * np.sqrt(2 * hbar)

                if 'State' in g:
                    mu, _ = qop(*x, hbar=hbar)
                    return mu[0]

                S = qop(*x)

                # calculate the expected output
                if op.num_wires == 1:
                    S = block_diag(S,
                                   np.identity(2))[:,
                                                   [0, 2, 1, 3]][[0, 2, 1, 3]]

                return (S @ np.array([a.real, a.imag, 0, 0]) *
                        np.sqrt(2 * hbar))[0]

            if g == 'GaussianState':
                p = [
                    np.array([0.432, 0.123, 0.342, 0.123]),
                    np.diag([0.5234] * 4)
                ]
            else:
                p = [0.432423, -0.12312, 0.324][:op.num_params]

            self.assertAllEqual(circuit(*p), reference(*p))
Пример #26
0
    def test_load_default_qubit_device(self):
        """Test that the default plugin loads correctly"""
        self.logTestName()

        dev = qml.device("default.qubit", wires=2)
        self.assertEqual(dev.num_wires, 2)
        self.assertEqual(dev.shots, 0)
        self.assertEqual(dev.short_name, "default.qubit")
Пример #27
0
    def test_load_default_gaussian_device(self):
        """Test that the default plugin loads correctly"""
        self.logTestName()

        dev = qml.device('default.gaussian', wires=2, hbar=2)
        self.assertEqual(dev.num_wires, 2)
        self.assertEqual(dev.shots, 0)
        self.assertEqual(dev.hbar, 2)
        self.assertEqual(dev.short_name, 'default.gaussian')
Пример #28
0
    def test_qnode_cv_gradient_methods(self):
        """Tests the gradient computation methods on CV circuits."""
        # we can only use the 'A' method on parameters which only affect gaussian operations
        # that are not succeeded by nongaussian operations

        par = [0.4, -2.3]
        dev = qml.device('default.qubit', wires=2)

        def check_methods(qf, d):
            q = qml.QNode(qf, dev)
            # NOTE: the default plugin is a discrete (qubit) simulator, it cannot
            # execute CV gates, but the QNode can be constructed
            q.construct(par)
            assert q.grad_method_for_par == d

        def qf(x, y):
            qml.Displacement(x, 0, wires=[0])
            qml.CubicPhase(0.2, wires=[0])
            qml.Squeezing(0.3, y, wires=[1])
            qml.Rotation(1.3, wires=[1])
            # nongaussian succeeding x but not y
            # TODO when QNode uses a DAG to describe the circuit, uncomment this line
            #qml.Kerr(0.4, [0])
            return qml.expval(qml.X(0)), qml.expval(qml.X(1))

        check_methods(qf, {0: 'F', 1: 'A'})

        def qf(x, y):
            qml.Displacement(x, 0, wires=[0])
            qml.CubicPhase(0.2, wires=[0])  # nongaussian succeeding x
            qml.Squeezing(0.3, x,
                          wires=[1])  # x affects gates on both wires, y unused
            qml.Rotation(1.3, wires=[1])
            return qml.expval(qml.X(0)), qml.expval(qml.X(1))

        check_methods(qf, {0: 'F'})

        def qf(x, y):
            qml.Displacement(x, 0, wires=[0])
            qml.Displacement(1.2, y, wires=[0])
            qml.Beamsplitter(0.2, 1.7, wires=[0, 1])
            qml.Rotation(1.9, wires=[0])
            qml.Kerr(0.3, wires=[
                1
            ])  # nongaussian succeeding both x and y due to the beamsplitter
            return qml.expval(qml.X(0)), qml.expval(qml.X(1))

        check_methods(qf, {0: 'F', 1: 'F'})

        def qf(x, y):
            qml.Kerr(y, wires=[1])
            qml.Displacement(x, 0, wires=[0])
            qml.Beamsplitter(0.2, 1.7, wires=[0, 1])
            return qml.expval(qml.X(0)), qml.expval(qml.X(1))

        check_methods(qf, {0: 'A', 1: 'F'})
 def test_initiatlization_via_pennylane(self):
     for short_name in [
             'projectq.simulator',
             'projectq.classical',
             'projectq.ibm'
     ]:
         try:
             dev = dev = qml.device(short_name, wires=2, user='******', password='******', verbose=True)
         except DeviceError:
             raise Exception("This test is expected to fail until pennylane-pq is installed.")
Пример #30
0
    def test_error_analytic_second_order_cv(self):
        """Test exception raised if attempting to use a second
        order observable to compute the variance derivative analytically"""
        dev = qml.device('default.gaussian', wires=1)

        @qml.qnode(dev)
        def circuit(a):
            qml.Displacement(a, 0, wires=0)
            return qml.var(qml.NumberOperator(0))

        with pytest.raises(ValueError, match=r"cannot be used with the parameter\(s\) \{0\}"):
            circuit.jacobian([1.], method='A')