Skip to content

Commit

Permalink
move legacy tests to its own directory
Browse files Browse the repository at this point in the history
  • Loading branch information
AmintorDusko committed Oct 2, 2023
1 parent a3b0c34 commit dd34d3e
Show file tree
Hide file tree
Showing 20 changed files with 6,073 additions and 0 deletions.
52 changes: 52 additions & 0 deletions tests_legacy/.pylintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
[MASTER]
# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code
extension-pkg-whitelist=numpy,scipy,autograd,toml,appdir,autograd.numpy,autograd.numpy.linalg,autograd.numpy.builtins,semantic_version,torch,tensorflow,tensorflow.contrib,tensorflow.contrib.eager,LazyLoader,networkx,networkx.dag
ignore-patterns=test_legacy*

[TYPECHECK]

# List of module names for which member attributes should not be checked
# (useful for modules/projects where namespaces are manipulated during runtime
# and thus existing member attributes cannot be deduced by static analysis. It
# supports qualified module names, as well as Unix pattern matching.
ignored-modules=numpy,scipy,autograd,toml,appdir,autograd.numpy,autograd.numpy.linalg,autograd.numpy.builtins,semantic_version,torch,tensorflow,tensorflow.contrib,tensorflow.contrib.eager,LazyLoader,networkx,networkx.dag,math,pennylane.numpy

# List of classes names for which member attributes should not be checked
# (useful for classes with attributes dynamically set). This supports can work
# with qualified names.
ignored-classes=numpy,scipy,autograd,toml,appdir,autograd.numpy,autograd.numpy.linalg,autograd.numpy.builtins,semantic_version,torch,tensorflow,tensorflow.contrib,tensorflow.contrib.eager,LazyLoader,networkx,networkx.dag,math,pennylane.numpy,pennylane.numpy.random,pennylane.numpy.linalg,pennylane.numpy.builtins,pennylane.operation,rustworkx,kahypar

[MESSAGES CONTROL]

# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time.
#enable=

# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once).
# Cyclical import checks are disabled for now as they are frequently used in
# the code base, but this can be removed in the future once cycles are resolved.
disable=
line-too-long,
invalid-name,
too-many-lines,
redefined-builtin,
too-many-locals,
duplicate-code,
cyclic-import,
import-error,
bad-option-value,
import-outside-toplevel,
missing-class-docstring,
missing-function-docstring,
no-self-use

[MISCELLANEOUS]

# List of note tags to take in consideration, separated by a comma.
notes=
133 changes: 133 additions & 0 deletions tests_legacy/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# Copyright 2018-2023 Xanadu Quantum Technologies Inc.

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Pytest configuration file for PennyLane-Lightning test suite.
"""
import os

import pytest
import numpy as np

import pennylane as qml

# defaults
TOL = 1e-6
TOL_STOCHASTIC = 0.05

U = np.array(
[
[0.83645892 - 0.40533293j, -0.20215326 + 0.30850569j],
[-0.23889780 - 0.28101519j, -0.88031770 - 0.29832709j],
]
)

U2 = np.array(
[
[
-0.07843244 - 3.57825948e-01j,
0.71447295 - 5.38069384e-02j,
0.20949966 + 6.59100734e-05j,
-0.50297381 + 2.35731613e-01j,
],
[
-0.26626692 + 4.53837083e-01j,
0.27771991 - 2.40717436e-01j,
0.41228017 - 1.30198687e-01j,
0.01384490 - 6.33200028e-01j,
],
[
-0.69254712 - 2.56963068e-02j,
-0.15484858 + 6.57298384e-02j,
-0.53082141 + 7.18073414e-02j,
-0.41060450 - 1.89462315e-01j,
],
[
-0.09686189 - 3.15085273e-01j,
-0.53241387 - 1.99491763e-01j,
0.56928622 + 3.97704398e-01j,
-0.28671074 - 6.01574497e-02j,
],
]
)

THETA = np.linspace(0.11, 1, 3)
PHI = np.linspace(0.32, 1, 3)
VARPHI = np.linspace(0.02, 1, 3)


@pytest.fixture(scope="session")
def tol():
"""Numerical tolerance for equality tests."""
return float(os.environ.get("TOL", TOL))


@pytest.fixture(scope="session")
def tol_stochastic():
"""Numerical tolerance for equality tests."""
return TOL_STOCHASTIC


@pytest.fixture(scope="session", params=[2, 3])
def n_subsystems(request):
"""Number of qubits or qumodes."""
return request.param


# Looking for the device for testing.
default_device = "lightning.qubit"
supported_devices = {"lightning.kokkos", "lightning.qubit"}
supported_devices.update({sb.replace(".", "_") for sb in supported_devices})


def get_device():
"""Return the pennylane lightning device.
The device is ``lightning.qubit`` by default.
Allowed values are: "lightning.kokkos" and "lightning.qubit".
An underscore can also be used instead of a dot.
If the environment variable ``PL_DEVICE`` is defined, its value is used.
Underscores are replaced by dots upon exiting.
"""
device = None
if "PL_DEVICE" in os.environ:
device = os.environ.get("PL_DEVICE", default_device)
device = device.replace("_", ".")
if device is None:
device = default_device
if device not in supported_devices:
raise ValueError(f"Invalid backend {device}.")
return device


device_name = get_device()

if device_name not in qml.plugin_devices:
raise qml.DeviceError(
f"Device {device_name} does not exist. Make sure the required plugin is installed."
)

# Device specification
if device_name == "lightning.kokkos":
from pennylane_lightning.lightning_kokkos import LightningKokkos as LightningDevice
else:
from pennylane_lightning.lightning_qubit import LightningQubit as LightningDevice


# General qubit_device fixture, for any number of wires.
@pytest.fixture(scope="function", params=[np.complex64, np.complex128])
def qubit_device(request):
def _device(wires):
return qml.device(device_name, wires=wires, c_dtype=request.param)

return _device
100 changes: 100 additions & 0 deletions tests_legacy/lightning_qubit/test_measurements_samples_MCMC.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# Copyright 2018-2023 Xanadu Quantum Technologies Inc.

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Unit tests for MCMC sampling in lightning.qubit.
"""
import pytest
from conftest import LightningDevice # tested device

import numpy as np
import pennylane as qml

import pytest

from pennylane_lightning.lightning_qubit import LightningQubit


if not LightningQubit._CPP_BINARY_AVAILABLE:
pytest.skip("No binary module found. Skipping.", allow_module_level=True)

if LightningDevice != LightningQubit:
pytest.skip("Exclusive tests for lightning.qubit. Skipping.", allow_module_level=True)


class TestMCMCSample:
"""Tests that samples are properly calculated."""

@pytest.fixture(params=[np.complex64, np.complex128])
def dev(self, request):
return qml.device("lightning.qubit", wires=2, shots=1000, mcmc=True, c_dtype=request.param)

test_data_no_parameters = [
(100, [0], qml.PauliZ(wires=[0]), 100),
(110, [1], qml.PauliZ(wires=[1]), 110),
(120, [0, 1], qml.PauliX(0) @ qml.PauliZ(1), 120),
]

@pytest.mark.parametrize("num_shots,measured_wires,operation,shape", test_data_no_parameters)
def test_mcmc_sample_dimensions(self, dev, num_shots, measured_wires, operation, shape):
"""Tests if the samples returned by sample have
the correct dimensions
"""
dev.apply([qml.RX(1.5708, wires=[0]), qml.RX(1.5708, wires=[1])])

dev.shots = num_shots
dev._wires_measured = measured_wires
dev._samples = dev.generate_samples()
s1 = dev.sample(operation)

assert np.array_equal(s1.shape, (shape,))

@pytest.mark.parametrize("kernel", ["Local", "NonZeroRandom"])
def test_sample_values(self, tol, kernel):
"""Tests if the samples returned by sample have
the correct values
"""
dev = qml.device(
"lightning.qubit", wires=2, shots=1000, mcmc=True, kernel_name=kernel, num_burnin=100
)

dev.apply([qml.RX(1.5708, wires=[0])])
dev._wires_measured = {0}
dev._samples = dev.generate_samples()
s1 = dev.sample(qml.PauliZ(0))

# s1 should only contain 1 and -1, which is guaranteed if
# they square to 1
assert np.allclose(s1**2, 1, atol=tol, rtol=0)

@pytest.mark.parametrize("kernel", ["local", "nonZeroRandom", "Global", "global"])
def test_unsupported_sample_kernels(self, tol, kernel):
"""Tests if the samples returned by sample have
the correct values
"""
with pytest.raises(
NotImplementedError,
match=f"The {kernel} is not supported and currently only 'Local' and 'NonZeroRandom' kernels are supported.",
):
dev = qml.device(
"lightning.qubit",
wires=2,
shots=1000,
mcmc=True,
kernel_name=kernel,
num_burnin=100,
)

def test_wrong_num_burnin(self):
with pytest.raises(ValueError, match="Shots should be greater than num_burnin."):
dev = qml.device("lightning.qubit", wires=2, shots=1000, mcmc=True, num_burnin=1000)
Loading

0 comments on commit dd34d3e

Please sign in to comment.