示例#1
0

class InitDeviceTests(BaseTest):
    """Tests for device loader in __init__.py"""
    def test_no_device(self):
        """Test exception raised for a device that doesn't exist"""
        self.logTestName()

        with self.assertRaisesRegex(qml.DeviceError, 'Device does not exist'):
            qml.device('None', wires=0)

    @patch.object(qml, 'version', return_value='0.0.1')
    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)


if __name__ == '__main__':
    print('Testing PennyLane version ' + qml.version() + ', Device class.')
    # run the tests in this file
    suite = unittest.TestSuite()
    for t in (DeviceTest, InitDeviceTests):
        ttt = unittest.TestLoader().loadTestsFromTestCase(t)
        suite.addTests(ttt)

    unittest.TextTestRunner().run(suite)
示例#2
0
            num_params = 1
            par_domain = 'N'
            grad_method = None

        with self.assertRaisesRegex(ValueError, "Must specify the wires"):
            DummyOp(0.54, 0, do_queue=False)

    def test_observable_return_type_none(self):
        """Check that the return_type of an observable is initially None"""
        self.logTestName()

        class DummyObserv(qml.operation.Observable):
            r"""Dummy custom observable"""
            num_wires = 1
            num_params = 1
            par_domain = 'N'
            grad_method = None

        self.assertEqual(
            DummyObserv(0, wires=[1], do_queue=False).return_type, None)


if __name__ == '__main__':
    print('Testing PennyLane version ' + qml.version() + ', Operation class.')
    # run the tests in this file
    suite = unittest.TestSuite()
    for t in (BasicTest, DeveloperTests):
        ttt = unittest.TestLoader().loadTestsFromTestCase(t)
        suite.addTests(ttt)
    unittest.TextTestRunner().run(suite)
示例#3
0
        @qml.qnode(dev)
        def circuit(x, target_observable=None):
            qml.RX(x[0], wires=0)
            qml.RY(x[1], wires=0)
            qml.RZ(x[2], wires=0)
            qml.CNOT(wires=[0, 1])
            return qml.expval(qml.Hermitian(target_observable, wires=[0, 1]))

        target_state = 1 / np.sqrt(2) * np.array([1, 0, 0, 1])
        target_herm_op = np.outer(target_state.conj(), target_state)
        weights = np.array([0.5, 0.1, 0.2])
        expval = circuit(weights, target_observable=target_herm_op)
        self.assertAlmostEqual(expval, 0.590556, delta=self.tol)


if __name__ == "__main__":
    print("Testing PennyLane version " + qml.version() +
          ", default.qubit plugin.")
    # run the tests in this file
    suite = unittest.TestSuite()
    for t in (
            TestAuxillaryFunctions,
            TestStateFunctions,
            TestDefaultQubitDevice,
            TestDefaultQubitIntegration,
    ):
        ttt = unittest.TestLoader().loadTestsFromTestCase(t)
        suite.addTests(ttt)
    unittest.TextTestRunner().run(suite)
示例#4
0
    def test_not_natural_param(self):
        """Test that an exception is raised if a natural number is expected but not passed"""
        self.logTestName()

        class DummyOp(oo.Operation):
            r"""Dummy custom operation"""
            num_wires = 1
            num_params = 1
            par_domain = 'N'
            grad_method = None

        with self.assertRaisesRegex(TypeError,
                                    "Natural number parameter expected, got"):
            op = DummyOp(0.5, wires=[0], do_queue=False)

        with self.assertRaisesRegex(TypeError,
                                    "Natural number parameter expected, got"):
            op = DummyOp(-2, wires=[0], do_queue=False)


if __name__ == '__main__':
    print('Testing PennyLane version ' + pennylane.version() +
          ', Operation class.')
    # run the tests in this file
    suite = unittest.TestSuite()
    for t in (BasicTest, DeveloperTests):
        ttt = unittest.TestLoader().loadTestsFromTestCase(t)
        suite.addTests(ttt)
    unittest.TextTestRunner().run(suite)
示例#5
0
                    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, 0.763][:op.num_params]

            self.assertAllEqual(circuit(*p), reference(*p))


if __name__ == '__main__':
    print('Testing PennyLane version ' + qml.version() + ', default.gaussian plugin.')
    # run the tests in this file
    suite = unittest.TestSuite()
    for t in (TestAuxillaryFunctions,
              TestGates,
              TestStates,
              TestDefaultGaussianDevice,
              TestDefaultGaussianIntegration):
        ttt = unittest.TestLoader().loadTestsFromTestCase(t)
        suite.addTests(ttt)
    unittest.TextTestRunner().run(suite)
                    if (operation, observable) not in outputs:
                        outputs[(operation, observable)] = {}

                    outputs[(operation,
                             observable)][str(type(dev).__name__) + "(shots=" +
                                          str(dev.shots) + ")"] = output

        #if we could run the circuit on more than one device assert that both should have given the same output
        for (key, val) in outputs.items():
            if len(val) >= 2:
                self.assertAllElementsAlmostEqual(
                    val.values(),
                    delta=self.tol,
                    msg="Outputs " + str(list(val.values())) +
                    " of devices [" + ', '.join(list(val.keys())) +
                    "] do not agree for a circuit consisting of a " +
                    str(key[0]) + " Operation followed by a " + str(key[1]) +
                    " Expectation.")


if __name__ == '__main__':
    log.info('Testing PennyLane ProjectQ Plugin version ' + qml.version() +
             ', Device class.')
    # run the tests in this file
    suite = unittest.TestSuite()
    for t in (CompareWithDefaultQubitTest, ):
        ttt = unittest.TestLoader().loadTestsFromTestCase(t)
        suite.addTests(ttt)

    unittest.TextTestRunner().run(suite)
示例#7
0
        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]]]))
        self.assertAllAlmostEqual(circuit_output,
                                  expected_output,
                                  delta=self.tol)

        # 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
        self.assertAllAlmostEqual(circuit_jacobian,
                                  expected_jacobian,
                                  delta=self.tol)


if __name__ == '__main__':
    print('Testing PennyLane version ' + qml.version() + ', QNode class.')
    # run the tests in this file
    suite = unittest.TestSuite()
    for t in (BasicTest, GradientTest):
        ttt = unittest.TestLoader().loadTestsFromTestCase(t)
        suite.addTests(ttt)

    unittest.TextTestRunner().run(suite)
                def circuit():
                    qml.BasisState(bits_to_flip, wires=list(range(self.num_subsystems-1)))
                    return qml.expval.PauliZ(0), qml.expval.PauliZ(1), qml.expval.PauliZ(2), qml.expval.PauliZ(3)

                self.assertAllAlmostEqual([1]*(self.num_subsystems-1)-2*bits_to_flip, np.array(circuit()[:-1]), delta=self.tol)

    def test_disallow_basis_state_after_other_operation(self):
        if self.devices is None:
            return
        self.logTestName()

        for device in self.devices:
            @qml.qnode(device)
            def circuit():
                qml.PauliX(wires=[0])
                qml.BasisState(np.array([0, 1, 0, 1]), wires=list(range(self.num_subsystems)))
                return qml.expval.PauliZ(0)

            self.assertRaises(pennylane._device.DeviceError, circuit)


if __name__ == '__main__':
    print('Testing PennyLane qiskit Plugin version ' + qml.version() + ', BasisState operation.')
    # run the tests in this file
    suite = unittest.TestSuite()
    for t in (BasisStateTest, ):
        ttt = unittest.TestLoader().loadTestsFromTestCase(t)
        suite.addTests(ttt)

    unittest.TextTestRunner().run(suite)
示例#9
0
                grad_true = grad_true0 + grad_true1 # product rule

                self.assertAlmostEqual(grad_eval, grad_true, delta=self.tol)

    def test_gradient_exception_on_sample(self):
        """Tests that the proper exception is raised if differentiation of sampling is attempted."""
        self.logTestName()

        @qml.qnode(self.qubit_dev2)
        def circuit(x):
            qml.RX(x, wires=[0])
            return qml.sample(qml.PauliZ(0), 1), qml.sample(qml.PauliX(1), 1)

        with self.assertRaisesRegex(
            qml.QuantumFunctionError,
            "Circuits that include sampling can not be differentiated."
        ):
            grad_fn = autograd.jacobian(circuit)
            grad_fn(1.0)


if __name__ == '__main__':
    print('Testing PennyLane version ' + qml.version() + ', automatic gradients.')
    # run the tests in this file
    suite = unittest.TestSuite()
    for t in (CVGradientTest, QubitGradientTest):
        ttt = unittest.TestLoader().loadTestsFromTestCase(t)
        suite.addTests(ttt)

    unittest.TextTestRunner().run(suite)
示例#10
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)

        dcircuit = qml.grad(circuit, [0, 1])
        autograd_grad = dcircuit(phi, theta)

        dcircuit = tfe.gradients_function(circuit_tfe)
        tfe_grad = dcircuit(phi_t, theta_t)

        self.assertAllAlmostEqual(autograd_grad[0], tfe_grad[0], delta=self.tol)
        self.assertAllAlmostEqual(autograd_grad[1], tfe_grad[1], delta=self.tol)


if __name__ == '__main__':
    print('Testing PennyLane version ' + qml.version() + ', QNode TFE interface.')
    # run the tests in this file
    suite = unittest.TestSuite()
    for t in (TFEQNodeTests, IntegrationTests):
        ttt = unittest.TestLoader().loadTestsFromTestCase(t)
        suite.addTests(ttt)

    unittest.TextTestRunner().run(suite)
示例#11
0
        dev = qml.device("default.qubit", wires=2)

        @qml.qnode(dev)
        def circuit(x, target_observable=None):
            qml.RX(x[0], wires=0)
            qml.RY(x[1], wires=0)
            qml.RZ(x[2], wires=0)
            qml.CNOT(wires=[0, 1])
            return qml.expval(qml.Hermitian(target_observable, wires=[0, 1]))

        target_state = 1 / np.sqrt(2) * np.array([1, 0, 0, 1])
        target_herm_op = np.outer(target_state.conj(), target_state)
        weights = np.array([0.5, 0.1, 0.2])
        expval = circuit(weights, target_observable=target_herm_op)
        self.assertAlmostEqual(expval, 0.590556, delta=self.tol)


if __name__ == "__main__":
    print("Testing PennyLane version " + qml.version() + ", default.qubit plugin.")
    # run the tests in this file
    suite = unittest.TestSuite()
    for t in (
        TestAuxillaryFunctions,
        TestStateFunctions,
        TestDefaultQubitDevice,
        TestDefaultQubitIntegration,
    ):
        ttt = unittest.TestLoader().loadTestsFromTestCase(t)
        suite.addTests(ttt)
    unittest.TextTestRunner().run(suite)
            shots = 5
            dev1 = ProjectQIBMBackend(wires=self.num_subsystems, shots=shots, use_hardware=False, user="******", password='******')
            self.assertEqual(shots, dev1.shots)

            dev2 = ProjectQIBMBackend(wires=self.num_subsystems, num_runs=shots, use_hardware=False, user="******", password='******')
            self.assertEqual(shots, dev2.shots)

            dev2 = ProjectQIBMBackend(wires=self.num_subsystems, shots=shots+2, num_runs=shots, use_hardware=False, user="******", password='******')
            self.assertEqual(shots, dev2.shots)

    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.")

if __name__ == '__main__':
    print('Testing PennyLane ProjectQ Plugin version ' + qml.version() + ', device initialization.')
    # run the tests in this file
    suite = unittest.TestSuite()
    for t in (DeviceInitialization, ):
        ttt = unittest.TestLoader().loadTestsFromTestCase(t)
        suite.addTests(ttt)

    unittest.TextTestRunner().run(suite)
示例#13
0
                    x_onestep_target = x_vec - adapted_stepsize * firstmoment / (
                        np.sqrt(secondmoment) + 1e-8)
                    self.assertAllAlmostEqual(x_onestep,
                                              x_onestep_target,
                                              delta=self.tol)

                    x_twosteps = self.adam_opt.step(f, x_onestep)
                    adapted_stepsize = stepsize * np.sqrt(1 - delta**2) / (
                        1 - gamma**2)
                    firstmoment = (gamma * gradf(x_vec) +
                                   (1 - gamma) * gradf(x_onestep))
                    secondmoment = (
                        delta * gradf(x_vec) * gradf(x_vec) +
                        (1 - delta) * gradf(x_onestep) * gradf(x_onestep))
                    x_twosteps_target = x_onestep - adapted_stepsize * firstmoment / (
                        np.sqrt(secondmoment) + 1e-8)
                    self.assertAllAlmostEqual(x_twosteps,
                                              x_twosteps_target,
                                              delta=self.tol)


if __name__ == '__main__':
    print('Testing PennyLane version ' + qml.version() + ', basic optimizers.')
    # run the tests in this file
    suite = unittest.TestSuite()
    for t in (BasicTest, ):
        ttt = unittest.TestLoader().loadTestsFromTestCase(t)
        suite.addTests(ttt)

    unittest.TextTestRunner().run(suite)
                            outputs[(operation, observable)] = {}

                        outputs[(operation, observable)][type(dev)] = output

                    except IgnoreOperationException as e:
                        log.info(e)

        #if we could run the circuit on more than one device assert that both should have given the same output
        for (key, val) in outputs.items():
            if len(val) >= 2:
                self.assertAllElementsAlmostEqual(
                    val.values(),
                    delta=self.tol,
                    msg="Outputs " + str(list(val.values())) + " of devices " +
                    str(list(val.keys())) +
                    " do not agree for a circuit consisting of a " +
                    str(key[0]) + " Operation followed by a " + str(key[0]) +
                    " Expectation.")


if __name__ == '__main__':
    log.info('Testing PennyLane qiskit Plugin version ' + qml.version() +
             ', Device class.')
    # run the tests in this file
    suite = unittest.TestSuite()
    for t in (CompareWithDefaultQubitTest, ):
        ttt = unittest.TestLoader().loadTestsFromTestCase(t)
        suite.addTests(ttt)

    unittest.TextTestRunner().run(suite)
    """

    def test_projectq_import(self):
        """Check that from projectq.ops import MatrixGate can raise an exception without problems, this ensures backward compatibility with older versions of ProjectQ
        """
        del sys.modules["pennylane_pq.pqops"]
        import projectq.ops
        if 'MatrixGate' in projectq.ops.__dict__:
            del projectq.ops.__dict__['MatrixGate']
        import pennylane_pq.pqops

        del sys.modules["pennylane_pq.pqops"]
        import projectq.ops
        if 'MatrixGate' not in projectq.ops.__dict__:
            projectq.ops.__dict__['MatrixGate'] = projectq.ops.__dict__['BasicGate']
        import pennylane_pq.pqops

        # restore
        del sys.modules["projectq.ops"]
        import pennylane_pq.pqops

if __name__ == '__main__':
    print('Testing PennyLane ProjectQ Plugin version ' + qml.version() + ', import test.')
    # run the tests in this file
    suite = unittest.TestSuite()
    for t in (ProjectQImportTest, ):
        ttt = unittest.TestLoader().loadTestsFromTestCase(t)
        suite.addTests(ttt)

    unittest.TextTestRunner().run(suite)
示例#16
0
        dev._eng.backend.get_probabilities = MagicMock()
        dev._eng.backend.get_probabilities.return_value = {'00': 1.0}

        self.assertRaises(DeviceError,
                          dev.expval,
                          'PauliX',
                          wires=[0],
                          par=list())
        self.assertRaises(DeviceError,
                          dev.expval,
                          'PauliY',
                          wires=[0],
                          par=list())
        self.assertRaises(DeviceError,
                          dev.expval,
                          'Hadamard',
                          wires=[0],
                          par=list())


if __name__ == '__main__':
    print('Testing PennyLane ProjectQ Plugin version ' + qml.version() +
          ', device expval and pre_expval.')
    # run the tests in this file
    suite = unittest.TestSuite()
    for t in (ExpvalAndPreExpvalMock, Expval):
        ttt = unittest.TestLoader().loadTestsFromTestCase(t)
        suite.addTests(ttt)

    unittest.TextTestRunner().run(suite)
示例#17
0
                    wires=[0, 1])  #this expectation will never be supported
                return qml.expval.Homodyne(0.7, 0)

            self.assertRaises(pennylane._device.DeviceError, circuit)

    def test_unsupported_expectation(self):
        if self.devices is None:
            return
        self.logTestName()

        for device in self.devices:

            @qml.qnode(device)
            def circuit():
                return qml.expval.Homodyne(
                    0.7, 0)  #this expectation will never be supported

            self.assertRaises(pennylane._device.DeviceError, circuit)


if __name__ == '__main__':
    print('Testing PennyLane qiskit Plugin version ' + qml.version() +
          ', unsupported operations.')
    # run the tests in this file
    suite = unittest.TestSuite()
    for t in (UnsupportedOperationTest, ):
        ttt = unittest.TestLoader().loadTestsFromTestCase(t)
        suite.addTests(ttt)

    unittest.TextTestRunner().run(suite)
        for reused_p in thetas:
            reused_p = reused_p**3 / 19
            for other_p in thetas:
                other_p = other_p**2 / 11

                # autograd gradient
                grad = autograd.grad(f)
                grad_eval = grad(reused_p, other_p)

                # manual gradient
                grad_true0 = (expZ(Rx(reused_p) @ Rz(other_p) @ Ry(reused_p + np.pi / 2) @ Rx(extra_param) @ zero_state) \
                             -expZ(Rx(reused_p) @ Rz(other_p) @ Ry(reused_p - np.pi / 2) @ Rx(extra_param) @ zero_state)) / 2
                grad_true1 = (expZ(Rx(reused_p + np.pi / 2) @ Rz(other_p) @ Ry(reused_p) @ Rx(extra_param) @ zero_state) \
                             -expZ(Rx(reused_p - np.pi / 2) @ Rz(other_p) @ Ry(reused_p) @ Rx(extra_param) @ zero_state)) / 2
                grad_true = grad_true0 + grad_true1  # product rule

                self.assertAlmostEqual(grad_eval, grad_true, delta=self.tol)


if __name__ == '__main__':
    print('Testing PennyLane version ' + qml.version() +
          ', automatic gradients.')
    # run the tests in this file
    suite = unittest.TestSuite()
    for t in (CVGradientTest, QubitGradientTest):
        ttt = unittest.TestLoader().loadTestsFromTestCase(t)
        suite.addTests(ttt)

    unittest.TextTestRunner().run(suite)
示例#19
0
        # test false if no config is loaded
        config = Configuration('noconfig')
        self.assertFalse(config)

        # test true if config is loaded
        config = Configuration(filename)
        self.assertTrue(config)


class PennyLaneInitTests(BaseTest):
    """Tests to ensure that the code in PennyLane/__init__.py
    correctly knows how to load and use configuration data"""

    def test_device_load(self):
        """Test loading a device with a configuration."""
        self.logTestName()

        config = Configuration(name=filename)
        dev = qml.device('default.gaussian', wires=2, config=config)

        self.assertTrue(dev.hbar, 1)

if __name__ == '__main__':
    print('Testing PennyLane version ' + pennylane.version() + ', Configuration class.')
    # run the tests in this file
    suite = unittest.TestSuite()
    for t in (BasicTest, PennyLaneInitTests):
        ttt = unittest.TestLoader().loadTestsFromTestCase(t)
        suite.addTests(ttt)
    unittest.TextTestRunner().run(suite)