Skip to content

Commit

Permalink
black
Browse files Browse the repository at this point in the history
  • Loading branch information
austingmhuang committed Apr 25, 2024
1 parent 8bca44e commit 6eea970
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 95 deletions.
27 changes: 16 additions & 11 deletions tests/test_base_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,8 @@ def run(self, *args, **kwargs):
@property
def target(self):
return self._target



class MockedBackendLegacy(BackendV1):
def __init__(self, num_qubits=10, name="mocked_backend_legacy"):
self._configuration = Configuration(num_qubits, backend_name=name)
Expand All @@ -106,6 +107,7 @@ def run(self, *args, **kwargs):
def options(self):
return self._options


class MockSession:
def __init__(self, backend, max_time=None):
self.backend = backend
Expand Down Expand Up @@ -135,6 +137,7 @@ def options_for_testing():
options.resilience_level = 1
return options


class TestSupportForV1andV2:
"""Tests compatibility with BackendV1 and BackendV2"""

Expand All @@ -149,30 +152,32 @@ def test_v1_and_v2_mocked(self, backend):
"""Test that device initializes with no error mocked"""
dev = QiskitDevice2(wires=10, backend=backend, use_primitives=True)
assert dev._backend == backend


@pytest.mark.skip(reason="Fake backends do not have attribute _service, should address in (SC 55725)")
@pytest.mark.skip(
reason="Fake backends do not have attribute _service, should address in (SC 55725)"
)
@pytest.mark.parametrize(
"backend",
[
FakeManila(),
FakeManilaV2(),
]
"backend",
[
FakeManila(),
FakeManilaV2(),
],
)
def test_v1_and_v2_manila(self, backend):
"""Test that device initializes with no error with V1 and V2 backends by Qiskit"""
dev = QiskitDevice2(wires=5, backend=backend, use_primitives=True)

@qml.qnode(dev)
def circuit(x):
qml.RX(x, wires=[0])
qml.CNOT(wires=[0, 1])
return qml.sample(qml.PauliZ(0))
res = circuit(np.pi/2)

res = circuit(np.pi / 2)
assert isinstance(res, np.ndarray)
assert np.shape(res) == (1024,)


class TestDeviceInitialization:
def test_compile_backend_kwarg(self):
"""Test that the compile_backend is set correctly if passed, and the main
Expand Down
129 changes: 55 additions & 74 deletions tests/test_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,9 +198,7 @@ def test_longer_parameter_expression(self):
assert isinstance(recorded_op, qml.RX)
assert recorded_op.parameters == a_val * np.cos(b_val) + c_val

def test_quantum_circuit_loaded_multiple_times_with_different_arguments(
self, recorder
):
def test_quantum_circuit_loaded_multiple_times_with_different_arguments(self, recorder):
"""Tests that a loaded quantum circuit can be called multiple times with
different arguments."""

Expand Down Expand Up @@ -379,9 +377,7 @@ def test_wires_two_different_quantum_registers(self, recorder):
assert recorder.queue[0].parameters == []
assert recorder.queue[0].wires == Wires(three_wires)

def test_wires_quantum_circuit_init_with_two_different_quantum_registers(
self, recorder
):
def test_wires_quantum_circuit_init_with_two_different_quantum_registers(self, recorder):
"""Tests that the wires is correct even if the quantum circuit was initiliazed with two
separate quantum registers."""

Expand Down Expand Up @@ -428,11 +424,7 @@ class TestConverterGatesQiskitToPennyLane:

@pytest.mark.parametrize(
"qiskit_operation, pennylane_name",
[
(QuantumCircuit.crx, "CRX"),
(QuantumCircuit.crz, "CRZ"),
(QuantumCircuit.cry, "CRY"),
],
[(QuantumCircuit.crx, "CRX"), (QuantumCircuit.crz, "CRZ"), (QuantumCircuit.cry, "CRY")],
)
def test_controlled_rotations(self, qiskit_operation, pennylane_name, recorder):
"""Tests loading a circuit with two qubit controlled rotations (except
Expand All @@ -453,6 +445,32 @@ def test_controlled_rotations(self, qiskit_operation, pennylane_name, recorder):
assert recorder.queue[0].parameters == [0.5]
assert recorder.queue[0].wires == Wires([0, 1])

@pytest.mark.parametrize(
"qiskit_operation, pennylane_name",
[
(QuantumCircuit.rxx, "IsingXX"),
(QuantumCircuit.ryy, "IsingYY"),
(QuantumCircuit.rzz, "IsingZZ"),
],
)
def test_controlled_rotations(self, qiskit_operation, pennylane_name, recorder):
"""Tests loading a circuit with two qubit Ising operations."""

q2 = QuantumRegister(2)
qc = QuantumCircuit(q2)

qiskit_operation(qc, 0.5, q2[0], q2[1])

quantum_circuit = load(qc)

with recorder:
quantum_circuit()

assert len(recorder.queue) == 1
assert recorder.queue[0].name == pennylane_name
assert recorder.queue[0].parameters == [0.5]
assert recorder.queue[0].wires == Wires([0, 1])

def test_one_qubit_operations_supported_by_pennylane(self, recorder):
"""Tests loading a circuit with the one-qubit operations supported by PennyLane."""

Expand Down Expand Up @@ -764,9 +782,7 @@ def test_parameter_is_not_unbound(self):
of unbound parameters.
"""
param = Parameter("θ")
with pytest.raises(
ValueError, match=r"The parameter θ was not bound correctly\."
):
with pytest.raises(ValueError, match=r"The parameter θ was not bound correctly\."):
_check_parameter_bound(param=param, unbound_params={})


Expand Down Expand Up @@ -979,19 +995,13 @@ def test_too_many_args(self):
qc.rx(b * c[1], 1)
qc.measure_all()

with pytest.raises(
TypeError, match="Expected 3 positional arguments but 4 were given"
):
with pytest.raises(TypeError, match="Expected 3 positional arguments but 4 were given"):
load(qc)(0.2, 0.4, [0.1, 0.3], 0.5)

with pytest.raises(
TypeError, match="Expected 1 positional argument but 2 were given"
):
with pytest.raises(TypeError, match="Expected 1 positional argument but 2 were given"):
load(qc)(0.4, 0.5, a=0.2, c=[0.1, 0.3])

with pytest.raises(
TypeError, match="Expected 1 positional argument but 2 were given"
):
with pytest.raises(TypeError, match="Expected 1 positional argument but 2 were given"):
load(qc)([0.1, 0.3], 0.5, a=0.2, b=0.4)

def test_missing_argument(self):
Expand Down Expand Up @@ -1076,9 +1086,7 @@ def test_no_parameters_raises_error(self):

quantum_circuit = load(qc)

with pytest.raises(
TypeError, match="Missing required argument to define Parameter value"
):
with pytest.raises(TypeError, match="Missing required argument to define Parameter value"):
quantum_circuit()


Expand All @@ -1100,9 +1108,7 @@ class TestConverterQasm:
"measure q -> c;"
)

@pytest.mark.skipif(
sys.version_info < (3, 6), reason="tmpdir fixture requires Python >=3.6"
)
@pytest.mark.skipif(sys.version_info < (3, 6), reason="tmpdir fixture requires Python >=3.6")
# pylint:disable=unspecified-encoding
def test_qasm_from_file(self, tmpdir, recorder):
"""Tests that a QuantumCircuit object is deserialized from a qasm file."""
Expand Down Expand Up @@ -1253,12 +1259,12 @@ def circuit_native_pennylane(angle):
qml.RZ(angle, wires=0)
return qml.expval(qml.PauliZ(0))

assert circuit_loaded_qiskit_circuit(
assert circuit_loaded_qiskit_circuit(rotation_angle) == circuit_native_pennylane(
rotation_angle
) == circuit_native_pennylane(rotation_angle)
assert circuit_loaded_qiskit_circuit2(
)
assert circuit_loaded_qiskit_circuit2(rotation_angle) == circuit_native_pennylane(
rotation_angle
) == circuit_native_pennylane(rotation_angle)
)

def test_one_parameter_in_qc_one_passed_into_qnode(self, qubit_device_2_wires):
"""Tests passing a parameter by pre-defining it and then
Expand Down Expand Up @@ -1291,12 +1297,12 @@ def circuit_native_pennylane(angle):
qml.RX(rotation_angle2, wires=0)
return qml.expval(qml.PauliZ(0))

assert circuit_loaded_qiskit_circuit(
assert circuit_loaded_qiskit_circuit(rotation_angle1) == circuit_native_pennylane(
rotation_angle1
) == circuit_native_pennylane(rotation_angle1)
assert circuit_loaded_qiskit_circuit2(
)
assert circuit_loaded_qiskit_circuit2(rotation_angle1) == circuit_native_pennylane(
rotation_angle1
) == circuit_native_pennylane(rotation_angle1)
)

def test_initialize_with_qubit_state_vector(self, qubit_device_single_wire):
"""Tests the QuantumCircuit.initialize method in a QNode."""
Expand Down Expand Up @@ -1592,9 +1598,7 @@ def test_circuit_to_qiskit(self):
"""Test that a simple PennyLane circuit is converted to the expected Qiskit circuit"""

qscript = QuantumScript([qml.Hadamard(1), qml.CNOT([1, 0])])
qc = circuit_to_qiskit(
qscript, len(qscript.wires), diagonalize=False, measure=False
)
qc = circuit_to_qiskit(qscript, len(qscript.wires), diagonalize=False, measure=False)

operation_names = [instruction.operation.name for instruction in qc.data]

Expand All @@ -1605,19 +1609,15 @@ def test_circuit_to_qiskit_with_parameterized_gate(self):
angle = 1.2

qscript = QuantumScript([qml.Hadamard(1), qml.CNOT([1, 0]), qml.RX(angle, 2)])
qc = circuit_to_qiskit(
qscript, len(qscript.wires), diagonalize=False, measure=False
)
qc = circuit_to_qiskit(qscript, len(qscript.wires), diagonalize=False, measure=False)

operation_names = [instruction.operation.name for instruction in qc.data]
operation_params = [instruction.operation.params for instruction in qc.data]

assert operation_names == ["h", "cx", "rx"]
assert operation_params == [[], [], [angle]]

@pytest.mark.parametrize(
"operations", [[], [qml.PauliX(0), qml.PauliY(1)], [qml.Hadamard(0)]]
)
@pytest.mark.parametrize("operations", [[], [qml.PauliX(0), qml.PauliY(1)], [qml.Hadamard(0)]])
@pytest.mark.parametrize("register_size", [2, 5])
def test_circuit_to_qiskit_register_size(self, operations, register_size):
"""Test that the regsiter_size determines the shape of the Qiskit
Expand Down Expand Up @@ -1794,9 +1794,7 @@ class TestConverterUtilsPennyLaneToQiskit:
@pytest.mark.parametrize("wire", [0, 1, 2])
@pytest.mark.parametrize("register_size", [3, 5])
# pylint:disable=too-many-arguments
def test_mp_to_pauli(
self, measurement_type, observable, obs_string, wire, register_size
):
def test_mp_to_pauli(self, measurement_type, observable, obs_string, wire, register_size):
"""Tests that a SparsePauliOp is created from a Pauli observable, and that
it has the expected format"""

Expand Down Expand Up @@ -2016,10 +2014,7 @@ def ansatz_false():
qml.RZ(0.24, wires=0)
qml.CNOT([0, 1])
qml.Barrier([0, 1, 2])
return [
qml.expval(m)
for m in [m0, m1, qml.measure(0), qml.measure(1), qml.measure(2)]
]
return [qml.expval(m) for m in [m0, m1, qml.measure(0), qml.measure(1), qml.measure(2)]]

assert loaded_qiskit_circuit() == built_pl_circuit()
assert all(
Expand Down Expand Up @@ -2070,9 +2065,7 @@ def test_control_flow_ops_circuit_switch(self, cond_type):
qc.measure_all()

dev = qml.device("default.qubit", wires=5, seed=24)
qiskit_circuit = load(
qc, measurements=[qml.expval(qml.PauliZ(0) @ qml.PauliY(1))]
)
qiskit_circuit = load(qc, measurements=[qml.expval(qml.PauliZ(0) @ qml.PauliY(1))])

@qml.qnode(dev)
def loaded_qiskit_circuit():
Expand Down Expand Up @@ -2282,15 +2275,11 @@ def test_passing_parameters_new_interface_args(self, qubit_device_2_wires):
"""Test calling the qfunc with the new interface for setting the value
of Qiskit Parameters by passing args in order."""

qc, circuit_native_pennylane = self._get_parameter_test_circuit(
qubit_device_2_wires
)
qc, circuit_native_pennylane = self._get_parameter_test_circuit(qubit_device_2_wires)

@qml.qnode(qubit_device_2_wires)
def circuit_loaded_qiskit_circuit():
load(qc)(
0.5, 0.3, 0.4
) # a, b, c (alphabetical) rather than order used in qc
load(qc)(0.5, 0.3, 0.4) # a, b, c (alphabetical) rather than order used in qc
return qml.expval(qml.PauliZ(0))

assert circuit_loaded_qiskit_circuit() == circuit_native_pennylane()
Expand All @@ -2299,9 +2288,7 @@ def test_passing_parameters_new_interface_kwargs(self, qubit_device_2_wires):
"""Test calling the qfunc with the new interface for setting the value
of Qiskit Parameters by passing kwargs matching the parameter names"""

qc, circuit_native_pennylane = self._get_parameter_test_circuit(
qubit_device_2_wires
)
qc, circuit_native_pennylane = self._get_parameter_test_circuit(qubit_device_2_wires)

@qml.qnode(qubit_device_2_wires)
def circuit_loaded_qiskit_circuit():
Expand All @@ -2314,9 +2301,7 @@ def test_passing_parameters_new_interface_mixed(self, qubit_device_2_wires):
"""Test calling the qfunc with the new interface for setting the value
of Qiskit Parameters - by passing a combination of kwargs and args"""

qc, circuit_native_pennylane = self._get_parameter_test_circuit(
qubit_device_2_wires
)
qc, circuit_native_pennylane = self._get_parameter_test_circuit(qubit_device_2_wires)

@qml.qnode(qubit_device_2_wires)
def circuit_loaded_qiskit_circuit():
Expand All @@ -2342,9 +2327,7 @@ def circuit_loaded_qiskit_circuit():

assert circuit_loaded_qiskit_circuit() == circuit_native_pennylane()

def test_using_parameter_vector_with_positional_argument(
self, qubit_device_2_wires
):
def test_using_parameter_vector_with_positional_argument(self, qubit_device_2_wires):
"""Test that a parameterized QuanutmCircuit based on a ParameterVector can also be
converted to a PennyLane template with the expected arguments passed as a params dict"""

Expand Down Expand Up @@ -2481,9 +2464,7 @@ def test_convert_too_many_coefficients(self):
(
SparsePauliOp("XYZ"),
"ABC",
qml.prod(
qml.PauliZ(wires="A"), qml.PauliY(wires="B"), qml.PauliX(wires="C")
),
qml.prod(qml.PauliZ(wires="A"), qml.PauliY(wires="B"), qml.PauliX(wires="C")),
),
(
SparsePauliOp(["XY", "ZX"]),
Expand Down
20 changes: 10 additions & 10 deletions tests/test_qiskit_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from pennylane_qiskit import AerDevice
from pennylane_qiskit.qiskit_device import QiskitDevice
from qiskit_aer import noise
from qiskit.providers import BackendV1, BackendV2
from qiskit.providers import BackendV1, BackendV2
from qiskit_ibm_runtime.fake_provider import FakeManila, FakeManilaV2
from unittest.mock import Mock
from qiskit_ibm_runtime.options import Options
Expand Down Expand Up @@ -92,25 +92,25 @@ def test_v1_and_v2_mocked(self, backend):
"""Test that device initializes with no error mocked"""
dev = qml.device("qiskit.remote", wires=10, backend=backend, use_primitives=True)
assert dev._backend == backend

@pytest.mark.parametrize(
"backend",
[
FakeManila(),
FakeManilaV2(),
]
"backend",
[
FakeManila(),
FakeManilaV2(),
],
)
def test_v1_and_v2_manila(self, backend):
"""Test that device initializes with no error with V1 and V2 backends by Qiskit"""
dev = qml.device("qiskit.remote", wires=5, backend=backend, use_primitives=True)

@qml.qnode(dev)
def circuit(x):
qml.RX(x, wires=[0])
qml.CNOT(wires=[0, 1])
return qml.sample(qml.PauliZ(0))
res = circuit(np.pi/2)

res = circuit(np.pi / 2)
assert isinstance(res, np.ndarray)
assert np.shape(res) == (1024,)

Expand Down

0 comments on commit 6eea970

Please sign in to comment.