repo
stringclasses 900
values | file
stringclasses 754
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Tests for uniformly controlled single-qubit unitaries.
"""
import unittest
from ddt import ddt
from test import combine # pylint: disable=wrong-import-order
import numpy as np
from scipy.linalg import block_diag
from qiskit.extensions.quantum_initializer.uc import UCGate
from qiskit import QuantumCircuit, QuantumRegister, BasicAer, execute
from qiskit.test import QiskitTestCase
from qiskit.quantum_info.random import random_unitary
from qiskit.compiler import transpile
from qiskit.quantum_info.operators.predicates import matrix_equal
from qiskit.quantum_info import Operator
_id = np.eye(2, 2)
_not = np.matrix([[0, 1], [1, 0]])
@ddt
class TestUCGate(QiskitTestCase):
"""Qiskit UCGate tests."""
@combine(
squs=[
[_not],
[_id],
[_id, _id],
[_id, 1j * _id],
[_id, _not, _id, _not],
[random_unitary(2, seed=541234).data for _ in range(2**2)],
[random_unitary(2, seed=975163).data for _ in range(2**3)],
[random_unitary(2, seed=629462).data for _ in range(2**4)],
],
up_to_diagonal=[True, False],
)
def test_ucg(self, squs, up_to_diagonal):
"""Test uniformly controlled gates."""
num_con = int(np.log2(len(squs)))
q = QuantumRegister(num_con + 1)
qc = QuantumCircuit(q)
qc.uc(squs, q[1:], q[0], up_to_diagonal=up_to_diagonal)
# Decompose the gate
qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"])
# Simulate the decomposed gate
simulator = BasicAer.get_backend("unitary_simulator")
result = execute(qc, simulator).result()
unitary = result.get_unitary(qc)
if up_to_diagonal:
ucg = UCGate(squs, up_to_diagonal=up_to_diagonal)
unitary = np.dot(np.diagflat(ucg._get_diagonal()), unitary)
unitary_desired = _get_ucg_matrix(squs)
self.assertTrue(matrix_equal(unitary_desired, unitary, ignore_phase=True))
def test_global_phase_ucg(self):
"""Test global phase of uniformly controlled gates"""
gates = [random_unitary(2).data for _ in range(2**2)]
num_con = int(np.log2(len(gates)))
q = QuantumRegister(num_con + 1)
qc = QuantumCircuit(q)
qc.uc(gates, q[1:], q[0], up_to_diagonal=False)
simulator = BasicAer.get_backend("unitary_simulator")
result = execute(qc, simulator).result()
unitary = result.get_unitary(qc)
unitary_desired = _get_ucg_matrix(gates)
self.assertTrue(np.allclose(unitary_desired, unitary))
def test_inverse_ucg(self):
"""Test inverse function of uniformly controlled gates"""
gates = [random_unitary(2, seed=42 + s).data for s in range(2**2)]
num_con = int(np.log2(len(gates)))
q = QuantumRegister(num_con + 1)
qc = QuantumCircuit(q)
qc.uc(gates, q[1:], q[0], up_to_diagonal=False)
qc.append(qc.inverse(), qc.qubits)
unitary = Operator(qc).data
unitary_desired = np.identity(2**qc.num_qubits)
self.assertTrue(np.allclose(unitary_desired, unitary))
def _get_ucg_matrix(squs):
return block_diag(*squs)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for uniformly controlled Rx,Ry and Rz gates"""
import itertools
import unittest
import numpy as np
from scipy.linalg import block_diag
from qiskit import BasicAer, QuantumCircuit, QuantumRegister, execute
from qiskit.test import QiskitTestCase
from qiskit.quantum_info.operators.predicates import matrix_equal
from qiskit.compiler import transpile
angles_list = [
[0],
[0.4],
[0, 0],
[0, 0.8],
[0, 0, 1, 1],
[0, 1, 0.5, 1],
(2 * np.pi * np.random.rand(2**3)).tolist(),
(2 * np.pi * np.random.rand(2**4)).tolist(),
(2 * np.pi * np.random.rand(2**5)).tolist(),
]
rot_axis_list = ["X", "Y", "Z"]
class TestUCRXYZ(QiskitTestCase):
"""Qiskit tests for UCRXGate, UCRYGate and UCRZGate rotations gates."""
def test_ucy(self):
"""Test the decomposition of uniformly controlled rotations."""
for angles, rot_axis in itertools.product(angles_list, rot_axis_list):
with self.subTest(angles=angles, rot_axis=rot_axis):
num_contr = int(np.log2(len(angles)))
q = QuantumRegister(num_contr + 1)
qc = QuantumCircuit(q)
if rot_axis == "X":
qc.ucrx(angles, q[1 : num_contr + 1], q[0])
elif rot_axis == "Y":
qc.ucry(angles, q[1 : num_contr + 1], q[0])
else:
qc.ucrz(angles, q[1 : num_contr + 1], q[0])
# Decompose the gate
qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"])
# Simulate the decomposed gate
simulator = BasicAer.get_backend("unitary_simulator")
result = execute(qc, simulator).result()
unitary = result.get_unitary(qc)
unitary_desired = _get_ucr_matrix(angles, rot_axis)
self.assertTrue(matrix_equal(unitary_desired, unitary, ignore_phase=True))
def _get_ucr_matrix(angles, rot_axis):
if rot_axis == "X":
gates = [
np.array(
[
[np.cos(angle / 2), -1j * np.sin(angle / 2)],
[-1j * np.sin(angle / 2), np.cos(angle / 2)],
]
)
for angle in angles
]
elif rot_axis == "Y":
gates = [
np.array(
[[np.cos(angle / 2), -np.sin(angle / 2)], [np.sin(angle / 2), np.cos(angle / 2)]]
)
for angle in angles
]
else:
gates = [
np.array([[np.exp(-1.0j * angle / 2), 0], [0, np.exp(1.0j * angle / 2)]])
for angle in angles
]
return block_diag(*gates)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""UnitaryGate tests"""
import json
import numpy
from numpy.testing import assert_allclose
import qiskit
from qiskit.extensions.unitary import UnitaryGate
from qiskit.test import QiskitTestCase
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.quantum_info.random import random_unitary
from qiskit.quantum_info.operators import Operator
from qiskit.transpiler.passes import CXCancellation
class TestUnitaryGate(QiskitTestCase):
"""Tests for the Unitary class."""
def test_set_matrix(self):
"""Test instantiation"""
try:
UnitaryGate([[0, 1], [1, 0]])
# pylint: disable=broad-except
except Exception as err:
self.fail(f"unexpected exception in init of Unitary: {err}")
def test_set_matrix_raises(self):
"""test non-unitary"""
try:
UnitaryGate([[1, 1], [1, 0]])
# pylint: disable=broad-except
except Exception:
pass
else:
self.fail("setting Unitary with non-unitary did not raise")
def test_set_init_with_unitary(self):
"""test instantiation of new unitary with another one (copy)"""
uni1 = UnitaryGate([[0, 1], [1, 0]])
uni2 = UnitaryGate(uni1)
self.assertEqual(uni1, uni2)
self.assertFalse(uni1 is uni2)
def test_conjugate(self):
"""test conjugate"""
ymat = numpy.array([[0, -1j], [1j, 0]])
uni = UnitaryGate([[0, 1j], [-1j, 0]])
self.assertTrue(numpy.array_equal(uni.conjugate().to_matrix(), ymat))
def test_adjoint(self):
"""test adjoint operation"""
uni = UnitaryGate([[0, 1j], [-1j, 0]])
self.assertTrue(numpy.array_equal(uni.adjoint().to_matrix(), uni.to_matrix()))
class TestUnitaryCircuit(QiskitTestCase):
"""Matrix gate circuit tests."""
def test_1q_unitary(self):
"""test 1 qubit unitary matrix"""
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
matrix = numpy.array([[1, 0], [0, 1]])
qc.x(qr[0])
qc.append(UnitaryGate(matrix), [qr[0]])
# test of qasm output
self.log.info(qc.qasm())
# test of text drawer
self.log.info(qc)
dag = circuit_to_dag(qc)
dag_nodes = dag.named_nodes("unitary")
self.assertTrue(len(dag_nodes) == 1)
dnode = dag_nodes[0]
self.assertIsInstance(dnode.op, UnitaryGate)
self.assertEqual(dnode.qargs, (qr[0],))
assert_allclose(dnode.op.to_matrix(), matrix)
def test_2q_unitary(self):
"""test 2 qubit unitary matrix"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
sigmax = numpy.array([[0, 1], [1, 0]])
sigmay = numpy.array([[0, -1j], [1j, 0]])
matrix = numpy.kron(sigmax, sigmay)
qc.x(qr[0])
uni2q = UnitaryGate(matrix)
qc.append(uni2q, [qr[0], qr[1]])
passman = PassManager()
passman.append(CXCancellation())
qc2 = passman.run(qc)
# test of qasm output
self.log.info(qc2.qasm())
# test of text drawer
self.log.info(qc2)
dag = circuit_to_dag(qc)
nodes = dag.two_qubit_ops()
self.assertEqual(len(nodes), 1)
dnode = nodes[0]
self.assertIsInstance(dnode.op, UnitaryGate)
self.assertEqual(dnode.qargs, (qr[0], qr[1]))
assert_allclose(dnode.op.to_matrix(), matrix)
qc3 = dag_to_circuit(dag)
self.assertEqual(qc2, qc3)
def test_3q_unitary(self):
"""test 3 qubit unitary matrix on non-consecutive bits"""
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
sigmax = numpy.array([[0, 1], [1, 0]])
sigmay = numpy.array([[0, -1j], [1j, 0]])
matrix = numpy.kron(sigmay, numpy.kron(sigmax, sigmay))
qc.x(qr[0])
uni3q = UnitaryGate(matrix)
qc.append(uni3q, [qr[0], qr[1], qr[3]])
qc.cx(qr[3], qr[2])
# test of text drawer
self.log.info(qc)
dag = circuit_to_dag(qc)
nodes = dag.multi_qubit_ops()
self.assertEqual(len(nodes), 1)
dnode = nodes[0]
self.assertIsInstance(dnode.op, UnitaryGate)
self.assertEqual(dnode.qargs, (qr[0], qr[1], qr[3]))
assert_allclose(dnode.op.to_matrix(), matrix)
def test_1q_unitary_int_qargs(self):
"""test single qubit unitary matrix with 'int' and 'list of ints' qubits argument"""
sigmax = numpy.array([[0, 1], [1, 0]])
sigmaz = numpy.array([[1, 0], [0, -1]])
# new syntax
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.unitary(sigmax, 0)
qc.unitary(sigmax, qr[1])
qc.unitary(sigmaz, [0, 1])
# expected circuit
qc_target = QuantumCircuit(qr)
qc_target.append(UnitaryGate(sigmax), [0])
qc_target.append(UnitaryGate(sigmax), [qr[1]])
qc_target.append(UnitaryGate(sigmaz), [[0, 1]])
self.assertEqual(qc, qc_target)
def test_qobj_with_unitary_matrix(self):
"""test qobj output with unitary matrix"""
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
sigmax = numpy.array([[0, 1], [1, 0]])
sigmay = numpy.array([[0, -1j], [1j, 0]])
matrix = numpy.kron(sigmay, numpy.kron(sigmax, sigmay))
qc.rx(numpy.pi / 4, qr[0])
uni = UnitaryGate(matrix)
qc.append(uni, [qr[0], qr[1], qr[3]])
qc.cx(qr[3], qr[2])
qobj = qiskit.compiler.assemble(qc)
instr = qobj.experiments[0].instructions[1]
self.assertEqual(instr.name, "unitary")
assert_allclose(numpy.array(instr.params[0]).astype(numpy.complex64), matrix)
# check conversion to dict
qobj_dict = qobj.to_dict()
class NumpyEncoder(json.JSONEncoder):
"""Class for encoding json str with complex and numpy arrays."""
def default(self, obj):
if isinstance(obj, numpy.ndarray):
return obj.tolist()
if isinstance(obj, complex):
return (obj.real, obj.imag)
return json.JSONEncoder.default(self, obj)
# check json serialization
self.assertTrue(isinstance(json.dumps(qobj_dict, cls=NumpyEncoder), str))
def test_labeled_unitary(self):
"""test qobj output with unitary matrix"""
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
sigmax = numpy.array([[0, 1], [1, 0]])
sigmay = numpy.array([[0, -1j], [1j, 0]])
matrix = numpy.kron(sigmax, sigmay)
uni = UnitaryGate(matrix, label="xy")
qc.append(uni, [qr[0], qr[1]])
qobj = qiskit.compiler.assemble(qc)
instr = qobj.experiments[0].instructions[0]
self.assertEqual(instr.name, "unitary")
self.assertEqual(instr.label, "xy")
def test_qasm_unitary_only_one_def(self):
"""test that a custom unitary can be converted to qasm and the
definition is only written once"""
qr = QuantumRegister(2, "q0")
cr = ClassicalRegister(1, "c0")
qc = QuantumCircuit(qr, cr)
matrix = numpy.array([[1, 0], [0, 1]])
unitary_gate = UnitaryGate(matrix)
qc.x(qr[0])
qc.append(unitary_gate, [qr[0]])
qc.append(unitary_gate, [qr[1]])
expected_qasm = (
"OPENQASM 2.0;\n"
'include "qelib1.inc";\n'
"gate unitary q0 { u(0,0,0) q0; }\n"
"qreg q0[2];\ncreg c0[1];\n"
"x q0[0];\n"
"unitary q0[0];\n"
"unitary q0[1];\n"
)
self.assertEqual(expected_qasm, qc.qasm())
def test_qasm_unitary_twice(self):
"""test that a custom unitary can be converted to qasm and that if
the qasm is called twice it is the same every time"""
qr = QuantumRegister(2, "q0")
cr = ClassicalRegister(1, "c0")
qc = QuantumCircuit(qr, cr)
matrix = numpy.array([[1, 0], [0, 1]])
unitary_gate = UnitaryGate(matrix)
qc.x(qr[0])
qc.append(unitary_gate, [qr[0]])
qc.append(unitary_gate, [qr[1]])
expected_qasm = (
"OPENQASM 2.0;\n"
'include "qelib1.inc";\n'
"gate unitary q0 { u(0,0,0) q0; }\n"
"qreg q0[2];\ncreg c0[1];\n"
"x q0[0];\n"
"unitary q0[0];\n"
"unitary q0[1];\n"
)
self.assertEqual(expected_qasm, qc.qasm())
self.assertEqual(expected_qasm, qc.qasm())
def test_qasm_2q_unitary(self):
"""test that a 2 qubit custom unitary can be converted to qasm"""
qr = QuantumRegister(2, "q0")
cr = ClassicalRegister(1, "c0")
qc = QuantumCircuit(qr, cr)
matrix = numpy.asarray([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]])
unitary_gate = UnitaryGate(matrix)
qc.x(qr[0])
qc.append(unitary_gate, [qr[0], qr[1]])
qc.append(unitary_gate, [qr[1], qr[0]])
expected_qasm = (
"OPENQASM 2.0;\n"
'include "qelib1.inc";\n'
"gate unitary q0,q1 { u(pi,-pi/2,pi/2) q0; u(pi,pi/2,-pi/2) q1; }\n"
"qreg q0[2];\n"
"creg c0[1];\n"
"x q0[0];\n"
"unitary q0[0],q0[1];\n"
"unitary q0[1],q0[0];\n"
)
self.assertEqual(expected_qasm, qc.qasm())
def test_qasm_unitary_noop(self):
"""Test that an identity unitary can be converted to OpenQASM 2"""
qc = QuantumCircuit(QuantumRegister(3, "q0"))
qc.unitary(numpy.eye(8), qc.qubits)
expected_qasm = (
"OPENQASM 2.0;\n"
'include "qelib1.inc";\n'
"gate unitary q0,q1,q2 { }\n"
"qreg q0[3];\n"
"unitary q0[0],q0[1],q0[2];\n"
)
self.assertEqual(expected_qasm, qc.qasm())
def test_unitary_decomposition(self):
"""Test decomposition for unitary gates over 2 qubits."""
qc = QuantumCircuit(3)
qc.unitary(random_unitary(8, seed=42), [0, 1, 2])
self.assertTrue(Operator(qc).equiv(Operator(qc.decompose())))
def test_unitary_decomposition_via_definition(self):
"""Test decomposition for 1Q unitary via definition."""
mat = numpy.array([[0, 1], [1, 0]])
self.assertTrue(numpy.allclose(Operator(UnitaryGate(mat).definition).data, mat))
def test_unitary_decomposition_via_definition_2q(self):
"""Test decomposition for 2Q unitary via definition."""
mat = numpy.array([[0, 0, 1, 0], [0, 0, 0, -1], [1, 0, 0, 0], [0, -1, 0, 0]])
self.assertTrue(numpy.allclose(Operator(UnitaryGate(mat).definition).data, mat))
def test_unitary_control(self):
"""Test parameters of controlled - unitary."""
mat = numpy.array([[0, 1], [1, 0]])
gate = UnitaryGate(mat).control()
self.assertTrue(numpy.allclose(gate.params, mat))
self.assertTrue(numpy.allclose(gate.base_gate.params, mat))
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the functional Pauli rotations."""
import unittest
from collections import defaultdict
import numpy as np
from ddt import ddt, data, unpack
from qiskit.test.base import QiskitTestCase
from qiskit import BasicAer, execute
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.library import (
LinearPauliRotations,
PolynomialPauliRotations,
PiecewiseLinearPauliRotations,
)
@ddt
class TestFunctionalPauliRotations(QiskitTestCase):
"""Test the functional Pauli rotations."""
def assertFunctionIsCorrect(self, function_circuit, reference):
"""Assert that ``function_circuit`` implements the reference function ``reference``."""
num_state_qubits = function_circuit.num_qubits - function_circuit.num_ancillas - 1
num_ancilla_qubits = function_circuit.num_ancillas
circuit = QuantumCircuit(num_state_qubits + 1 + num_ancilla_qubits)
circuit.h(list(range(num_state_qubits)))
circuit.append(function_circuit.to_instruction(), list(range(circuit.num_qubits)))
backend = BasicAer.get_backend("statevector_simulator")
statevector = execute(circuit, backend).result().get_statevector()
probabilities = defaultdict(float)
for i, statevector_amplitude in enumerate(statevector):
i = bin(i)[2:].zfill(circuit.num_qubits)[num_ancilla_qubits:]
probabilities[i] += np.real(np.abs(statevector_amplitude) ** 2)
unrolled_probabilities = []
unrolled_expectations = []
for i, probability in probabilities.items():
x, last_qubit = int(i[1:], 2), i[0]
if last_qubit == "0":
expected_amplitude = np.cos(reference(x)) / np.sqrt(2**num_state_qubits)
else:
expected_amplitude = np.sin(reference(x)) / np.sqrt(2**num_state_qubits)
unrolled_probabilities += [probability]
unrolled_expectations += [np.real(np.abs(expected_amplitude) ** 2)]
np.testing.assert_almost_equal(unrolled_probabilities, unrolled_expectations)
@data(
([1, 0.1], 3),
([0, 0.4, 2], 2),
([1, 0.5, 0.2, -0.2, 0.4, 2.5], 5),
)
@unpack
def test_polynomial_function(self, coeffs, num_state_qubits):
"""Test the polynomial rotation."""
def poly(x):
res = sum(coeff * x**i for i, coeff in enumerate(coeffs))
return res
polynome = PolynomialPauliRotations(num_state_qubits, [2 * coeff for coeff in coeffs])
self.assertFunctionIsCorrect(polynome, poly)
def test_polynomial_rotations_mutability(self):
"""Test the mutability of the linear rotations circuit."""
polynomial_rotations = PolynomialPauliRotations()
with self.subTest(msg="missing number of state qubits"):
with self.assertRaises(AttributeError): # no state qubits set
print(polynomial_rotations.draw())
with self.subTest(msg="default setup, just setting number of state qubits"):
polynomial_rotations.num_state_qubits = 2
self.assertFunctionIsCorrect(polynomial_rotations, lambda x: x / 2)
with self.subTest(msg="setting non-default values"):
polynomial_rotations.coeffs = [0, 1.2 * 2, 0.4 * 2]
self.assertFunctionIsCorrect(polynomial_rotations, lambda x: 1.2 * x + 0.4 * x**2)
with self.subTest(msg="changing of all values"):
polynomial_rotations.num_state_qubits = 4
polynomial_rotations.coeffs = [1 * 2, 0, 0, -0.5 * 2]
self.assertFunctionIsCorrect(polynomial_rotations, lambda x: 1 - 0.5 * x**3)
@data(
(2, 0.1, 0),
(4, -2, 2),
(1, 0, 0),
)
@unpack
def test_linear_function(self, num_state_qubits, slope, offset):
"""Test the linear rotation arithmetic circuit."""
def linear(x):
return offset + slope * x
linear_rotation = LinearPauliRotations(num_state_qubits, slope * 2, offset * 2)
self.assertFunctionIsCorrect(linear_rotation, linear)
def test_linear_rotations_mutability(self):
"""Test the mutability of the linear rotations circuit."""
linear_rotation = LinearPauliRotations()
with self.subTest(msg="missing number of state qubits"):
with self.assertRaises(AttributeError): # no state qubits set
print(linear_rotation.draw())
with self.subTest(msg="default setup, just setting number of state qubits"):
linear_rotation.num_state_qubits = 2
self.assertFunctionIsCorrect(linear_rotation, lambda x: x / 2)
with self.subTest(msg="setting non-default values"):
linear_rotation.slope = -2.3 * 2
linear_rotation.offset = 1 * 2
self.assertFunctionIsCorrect(linear_rotation, lambda x: 1 - 2.3 * x)
with self.subTest(msg="changing all values"):
linear_rotation.num_state_qubits = 4
linear_rotation.slope = 0.2 * 2
linear_rotation.offset = 0.1 * 2
self.assertFunctionIsCorrect(linear_rotation, lambda x: 0.1 + 0.2 * x)
@data(
(1, [0], [1], [0]),
(2, [0, 2], [-0.5, 1], [2, 1]),
(3, [0, 2, 5], [1, 0, -1], [0, 2, 2]),
(2, [1, 2], [1, -1], [2, 1]),
(3, [0, 1], [1, 0], [0, 1]),
)
@unpack
def test_piecewise_linear_function(self, num_state_qubits, breakpoints, slopes, offsets):
"""Test the piecewise linear rotations."""
def pw_linear(x):
for i, point in enumerate(reversed(breakpoints)):
if x >= point:
return offsets[-(i + 1)] + slopes[-(i + 1)] * (x - point)
return 0
pw_linear_rotations = PiecewiseLinearPauliRotations(
num_state_qubits,
breakpoints,
[2 * slope for slope in slopes],
[2 * offset for offset in offsets],
)
self.assertFunctionIsCorrect(pw_linear_rotations, pw_linear)
def test_piecewise_linear_rotations_mutability(self):
"""Test the mutability of the linear rotations circuit."""
pw_linear_rotations = PiecewiseLinearPauliRotations()
with self.subTest(msg="missing number of state qubits"):
with self.assertRaises(AttributeError): # no state qubits set
print(pw_linear_rotations.draw())
with self.subTest(msg="default setup, just setting number of state qubits"):
pw_linear_rotations.num_state_qubits = 2
self.assertFunctionIsCorrect(pw_linear_rotations, lambda x: x / 2)
with self.subTest(msg="setting non-default values"):
pw_linear_rotations.breakpoints = [0, 2]
pw_linear_rotations.slopes = [-1 * 2, 1 * 2]
pw_linear_rotations.offsets = [0, -1.2 * 2]
self.assertFunctionIsCorrect(
pw_linear_rotations, lambda x: -1.2 + (x - 2) if x >= 2 else -x
)
with self.subTest(msg="changing all values"):
pw_linear_rotations.num_state_qubits = 4
pw_linear_rotations.breakpoints = [1, 3, 6]
pw_linear_rotations.slopes = [-1 * 2, 1 * 2, -0.2 * 2]
pw_linear_rotations.offsets = [0, -1.2 * 2, 2 * 2]
def pw_linear(x):
if x >= 6:
return 2 - 0.2 * (x - 6)
if x >= 3:
return -1.2 + (x - 3)
if x >= 1:
return -(x - 1)
return 0
self.assertFunctionIsCorrect(pw_linear_rotations, pw_linear)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test library of integer comparison circuits."""
import unittest
import numpy as np
from ddt import ddt, data, unpack
from qiskit.test.base import QiskitTestCase
from qiskit import BasicAer, execute
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.library import IntegerComparator
@ddt
class TestIntegerComparator(QiskitTestCase):
"""Test the integer comparator circuit."""
def assertComparisonIsCorrect(self, comp, num_state_qubits, value, geq):
"""Assert that the comparator output is correct."""
qc = QuantumCircuit(comp.num_qubits) # initialize circuit
qc.h(list(range(num_state_qubits))) # set equal superposition state
qc.append(comp, list(range(comp.num_qubits))) # add comparator
# run simulation
backend = BasicAer.get_backend("statevector_simulator")
statevector = execute(qc, backend).result().get_statevector()
for i, amplitude in enumerate(statevector):
prob = np.abs(amplitude) ** 2
if prob > 1e-6:
# equal superposition
self.assertEqual(True, np.isclose(1.0, prob * 2.0**num_state_qubits))
b_value = f"{i:b}".rjust(qc.width(), "0")
x = int(b_value[(-num_state_qubits):], 2)
comp_result = int(b_value[-num_state_qubits - 1], 2)
if geq:
self.assertEqual(x >= value, comp_result == 1)
else:
self.assertEqual(x < value, comp_result == 1)
@data(
[1, 0, True],
[1, 1, True],
[2, -1, True],
[3, 5, True],
[3, 2, True],
[3, 2, False],
[4, 6, False],
)
@unpack
def test_fixed_value_comparator(self, num_state_qubits, value, geq):
"""Test the fixed value comparator circuit."""
# build the circuit with the comparator
comp = IntegerComparator(num_state_qubits, value, geq=geq)
self.assertComparisonIsCorrect(comp, num_state_qubits, value, geq)
def test_mutability(self):
"""Test changing the arguments of the comparator."""
comp = IntegerComparator()
with self.subTest(msg="missing num state qubits and value"):
with self.assertRaises(AttributeError):
print(comp.draw())
comp.num_state_qubits = 2
with self.subTest(msg="missing value"):
with self.assertRaises(AttributeError):
print(comp.draw())
comp.value = 0
comp.geq = True
with self.subTest(msg="updating num state qubits"):
comp.num_state_qubits = 1
self.assertComparisonIsCorrect(comp, 1, 0, True)
with self.subTest(msg="updating the value"):
comp.num_state_qubits = 3
comp.value = 2
self.assertComparisonIsCorrect(comp, 3, 2, True)
with self.subTest(msg="updating geq"):
comp.geq = False
self.assertComparisonIsCorrect(comp, 3, 2, False)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the linear amplitude function."""
import unittest
from functools import partial
from collections import defaultdict
from ddt import ddt, data, unpack
import numpy as np
from qiskit import BasicAer, execute
from qiskit.test.base import QiskitTestCase
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.library import LinearAmplitudeFunction
@ddt
class TestLinearAmplitudeFunctional(QiskitTestCase):
"""Test the functional Pauli rotations."""
def assertFunctionIsCorrect(self, function_circuit, reference):
"""Assert that ``function_circuit`` implements the reference function ``reference``."""
num_ancillas = function_circuit.num_ancillas
num_state_qubits = function_circuit.num_qubits - num_ancillas - 1
circuit = QuantumCircuit(function_circuit.num_qubits)
circuit.h(list(range(num_state_qubits)))
circuit.append(function_circuit.to_instruction(), list(range(circuit.num_qubits)))
backend = BasicAer.get_backend("statevector_simulator")
statevector = execute(circuit, backend).result().get_statevector()
probabilities = defaultdict(float)
for i, statevector_amplitude in enumerate(statevector):
i = bin(i)[2:].zfill(circuit.num_qubits)[num_ancillas:]
probabilities[i] += np.real(np.abs(statevector_amplitude) ** 2)
unrolled_probabilities = []
unrolled_expectations = []
for i, probability in probabilities.items():
x, last_qubit = int(i[1:], 2), i[0]
if last_qubit == "0":
expected_amplitude = np.cos(reference(x)) / np.sqrt(2**num_state_qubits)
else:
expected_amplitude = np.sin(reference(x)) / np.sqrt(2**num_state_qubits)
unrolled_probabilities += [probability]
unrolled_expectations += [np.real(np.abs(expected_amplitude) ** 2)]
np.testing.assert_almost_equal(unrolled_probabilities, unrolled_expectations)
def evaluate_function(
self, x_int, num_qubits, slope, offset, domain, image, rescaling_factor, breakpoints=None
):
"""A helper function to get the expected value of the linear amplitude function."""
a, b = domain
c, d = image
# map integer x to the domain of the function
x = a + (b - a) / (2**num_qubits - 1) * x_int
# apply the function
if breakpoints is None:
value = offset + slope * x
else:
value = 0
for i, point in enumerate(reversed(breakpoints)):
if x >= point:
value = offset[-(i + 1)] + slope[-(i + 1)] * (x - point)
break
# map the value to [0, 1]
normalized = (value - c) / (d - c)
# prepared value for taylor approximation
return np.pi / 4 + np.pi * rescaling_factor / 2 * (normalized - 0.5)
@data(
(2, 1, 0, (0, 3), (0, 3), 0.1, None),
(3, 1, 0, (0, 1), (0, 1), 0.01, None),
(1, [0, 0], [0, 0], (0, 2), (0, 1), 0.1, [0, 1]),
(2, [1, -1], [0, 1], (0, 2), (0, 1), 0.1, [0, 1]),
(3, [1, 0, -1, 0], [0, 0.5, -0.5, -0.5], (0, 2.5), (-0.5, 0.5), 0.1, [0, 0.5, 1, 2]),
)
@unpack
def test_polynomial_function(
self, num_state_qubits, slope, offset, domain, image, rescaling_factor, breakpoints
):
"""Test the polynomial rotation."""
reference = partial(
self.evaluate_function,
num_qubits=num_state_qubits,
slope=slope,
offset=offset,
domain=domain,
image=image,
rescaling_factor=rescaling_factor,
breakpoints=breakpoints,
)
linear_f = LinearAmplitudeFunction(
num_state_qubits, slope, offset, domain, image, rescaling_factor, breakpoints
)
self.assertFunctionIsCorrect(linear_f, reference)
def test_not_including_start_in_breakpoints(self):
"""Test not including the start of the domain works."""
num_state_qubits = 1
slope = [0, 0]
offset = [0, 0]
domain = (0, 2)
image = (0, 1)
rescaling_factor = 0.1
breakpoints = [1]
reference = partial(
self.evaluate_function,
num_qubits=num_state_qubits,
slope=slope,
offset=offset,
domain=domain,
image=image,
rescaling_factor=rescaling_factor,
breakpoints=breakpoints,
)
linear_f = LinearAmplitudeFunction(
num_state_qubits, slope, offset, domain, image, rescaling_factor, breakpoints
)
self.assertFunctionIsCorrect(linear_f, reference)
def test_invalid_inputs_raise(self):
"""Test passing invalid inputs to the LinearAmplitudeFunction raises an error."""
# default values
num_state_qubits = 1
slope = [0, 0]
offset = [0, 0]
domain = (0, 2)
image = (0, 1)
rescaling_factor = 0.1
breakpoints = [0, 1]
with self.subTest("mismatching breakpoints size"):
with self.assertRaises(ValueError):
_ = LinearAmplitudeFunction(
num_state_qubits, slope, offset, domain, image, rescaling_factor, [0]
)
with self.subTest("mismatching offsets"):
with self.assertRaises(ValueError):
_ = LinearAmplitudeFunction(
num_state_qubits, slope, [0], domain, image, rescaling_factor, breakpoints
)
with self.subTest("mismatching slopes"):
with self.assertRaises(ValueError):
_ = LinearAmplitudeFunction(
num_state_qubits, [0], offset, domain, image, rescaling_factor, breakpoints
)
with self.subTest("breakpoints outside of domain"):
with self.assertRaises(ValueError):
_ = LinearAmplitudeFunction(
num_state_qubits, slope, offset, (0, 0.2), image, rescaling_factor, breakpoints
)
with self.subTest("breakpoints not sorted"):
with self.assertRaises(ValueError):
_ = LinearAmplitudeFunction(
num_state_qubits, slope, offset, domain, image, rescaling_factor, [1, 0]
)
def test_post_processing(self):
"""Test the ``post_processing`` method."""
num_state_qubits = 2
slope = 1
offset = -2
domain = (0, 2)
image = (-2, 0)
rescaling_factor = 0.1
circuit = LinearAmplitudeFunction(
num_state_qubits, slope, offset, domain, image, rescaling_factor
)
values = [0, 0.2, 0.5, 0.9, 1]
def reference_post_processing(x):
x = 2 / np.pi / rescaling_factor * (x - 0.5) + 0.5
return image[0] + (image[1] - image[0]) * x
expected = [reference_post_processing(value) for value in values]
actual = [circuit.post_processing(value) for value in values]
self.assertListEqual(expected, actual)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test library of n-local circuits."""
import unittest
from test import combine
import numpy as np
from ddt import ddt, data, unpack
from qiskit.test.base import QiskitTestCase
from qiskit import transpile
from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector, ParameterExpression
from qiskit.circuit.library import (
NLocal,
TwoLocal,
RealAmplitudes,
ExcitationPreserving,
XGate,
CRXGate,
CCXGate,
SwapGate,
RXGate,
RYGate,
EfficientSU2,
RZGate,
RXXGate,
RYYGate,
CXGate,
)
from qiskit.circuit.random.utils import random_circuit
from qiskit.converters.circuit_to_dag import circuit_to_dag
from qiskit.quantum_info import Operator
@ddt
class TestNLocal(QiskitTestCase):
"""Test the n-local circuit class."""
def test_if_reps_is_negative(self):
"""Test to check if error is raised for negative value of reps"""
with self.assertRaises(ValueError):
_ = NLocal(reps=-1)
def test_if_reps_is_str(self):
"""Test to check if proper error is raised for str value of reps"""
with self.assertRaises(TypeError):
_ = NLocal(reps="3")
def test_if_reps_is_float(self):
"""Test to check if proper error is raised for float value of reps"""
with self.assertRaises(TypeError):
_ = NLocal(reps=5.6)
def test_if_reps_is_npint32(self):
"""Equality test for reps with int value and np.int32 value"""
self.assertEqual(NLocal(reps=3), NLocal(reps=np.int32(3)))
def test_if_reps_is_npint64(self):
"""Equality test for reps with int value and np.int64 value"""
self.assertEqual(NLocal(reps=3), NLocal(reps=np.int64(3)))
def test_reps_setter_when_negative(self):
"""Test to check if setter raises error for reps < 0"""
nlocal = NLocal(reps=1)
with self.assertRaises(ValueError):
nlocal.reps = -1
def assertCircuitEqual(self, qc1, qc2, visual=False, transpiled=True):
"""An equality test specialized to circuits."""
if transpiled:
basis_gates = ["id", "u1", "u3", "cx"]
qc1_transpiled = transpile(qc1, basis_gates=basis_gates, optimization_level=0)
qc2_transpiled = transpile(qc2, basis_gates=basis_gates, optimization_level=0)
qc1, qc2 = qc1_transpiled, qc2_transpiled
if visual:
self.assertEqual(qc1.draw(), qc2.draw())
else:
self.assertEqual(qc1, qc2)
def test_empty_nlocal(self):
"""Test the creation of an empty NLocal."""
nlocal = NLocal()
self.assertEqual(nlocal.num_qubits, 0)
self.assertEqual(nlocal.num_parameters_settable, 0)
self.assertEqual(nlocal.reps, 1)
self.assertEqual(nlocal, QuantumCircuit())
for attribute in [nlocal.rotation_blocks, nlocal.entanglement_blocks]:
self.assertEqual(len(attribute), 0)
@data(
(XGate(), [[0], [2], [1]]),
(XGate(), [[0]]),
(CRXGate(-0.2), [[2, 0], [1, 3]]),
)
@unpack
def test_add_layer_to_empty_nlocal(self, block, entangler_map):
"""Test appending gates to an empty nlocal."""
nlocal = NLocal()
nlocal.add_layer(block, entangler_map)
max_num_qubits = max(max(indices) for indices in entangler_map)
reference = QuantumCircuit(max_num_qubits + 1)
for indices in entangler_map:
reference.append(block, indices)
self.assertCircuitEqual(nlocal, reference)
@data([5, 3], [1, 5], [1, 1], [1, 2, 3, 10])
def test_append_circuit(self, num_qubits):
"""Test appending circuits to an nlocal works normally."""
# fixed depth of 3 gates per circuit
depth = 3
# keep track of a reference circuit
reference = QuantumCircuit(max(num_qubits))
# construct the NLocal from the first circuit
first_circuit = random_circuit(num_qubits[0], depth, seed=4200)
# TODO Terra bug: if this is to_gate it fails, since the QC adds an instruction not gate
nlocal = NLocal(max(num_qubits), entanglement_blocks=first_circuit.to_instruction(), reps=1)
reference.append(first_circuit, list(range(num_qubits[0])))
# append the rest
for num in num_qubits[1:]:
circuit = random_circuit(num, depth, seed=4200)
nlocal.append(circuit, list(range(num)))
reference.append(circuit, list(range(num)))
self.assertCircuitEqual(nlocal, reference)
@data([5, 3], [1, 5], [1, 1], [1, 2, 3, 10])
def test_add_nlocal(self, num_qubits):
"""Test adding an nlocal to an nlocal (using add_layer)."""
# fixed depth of 3 gates per circuit
depth = 3
# keep track of a reference circuit
reference = QuantumCircuit(max(num_qubits))
# construct the NLocal from the first circuit
first_circuit = random_circuit(num_qubits[0], depth, seed=4220)
# TODO Terra bug: if this is to_gate it fails, since the QC adds an instruction not gate
nlocal = NLocal(max(num_qubits), entanglement_blocks=first_circuit.to_instruction(), reps=1)
nlocal2 = nlocal.copy()
_ = nlocal2.data
reference.append(first_circuit, list(range(num_qubits[0])))
# append the rest
for num in num_qubits[1:]:
circuit = random_circuit(num, depth, seed=4220)
layer = NLocal(num, entanglement_blocks=circuit, reps=1)
nlocal.add_layer(layer)
nlocal2.add_layer(layer)
reference.append(circuit, list(range(num)))
self.assertCircuitEqual(nlocal, reference)
self.assertCircuitEqual(nlocal2, reference)
@unittest.skip("Feature missing")
def test_iadd_overload(self):
"""Test the overloaded + operator."""
num_qubits, depth = 2, 2
# construct two circuits for adding
first_circuit = random_circuit(num_qubits, depth, seed=4242)
circuit = random_circuit(num_qubits, depth, seed=4242)
# get a reference
reference = first_circuit + circuit
# convert the object to be appended to different types
others = [circuit, circuit.to_instruction(), circuit.to_gate(), NLocal(circuit)]
# try adding each type
for other in others:
nlocal = NLocal(num_qubits, entanglement_blocks=first_circuit, reps=1)
nlocal += other
with self.subTest(msg=f"type: {type(other)}"):
self.assertCircuitEqual(nlocal, reference)
def test_parameter_getter_from_automatic_repetition(self):
"""Test getting and setting of the nlocal parameters."""
circuit = QuantumCircuit(2)
circuit.ry(Parameter("a"), 0)
circuit.crx(Parameter("b"), 0, 1)
# repeat circuit and check that parameters are duplicated
reps = 3
nlocal = NLocal(2, entanglement_blocks=circuit, reps=reps)
self.assertTrue(nlocal.num_parameters, 6)
self.assertTrue(len(nlocal.parameters), 6)
@data(list(range(6)), ParameterVector("ΞΈ", length=6), [0, 1, Parameter("theta"), 3, 4, 5])
def test_parameter_setter_from_automatic_repetition(self, params):
"""Test getting and setting of the nlocal parameters."""
circuit = QuantumCircuit(2)
circuit.ry(Parameter("a"), 0)
circuit.crx(Parameter("b"), 0, 1)
# repeat circuit and check that parameters are duplicated
reps = 3
nlocal = NLocal(2, entanglement_blocks=circuit, reps=reps)
nlocal.assign_parameters(params, inplace=True)
param_set = {p for p in params if isinstance(p, ParameterExpression)}
with self.subTest(msg="Test the parameters of the non-transpiled circuit"):
# check the parameters of the final circuit
self.assertEqual(nlocal.parameters, param_set)
with self.subTest(msg="Test the parameters of the transpiled circuit"):
basis_gates = ["id", "u1", "u2", "u3", "cx"]
transpiled_circuit = transpile(nlocal, basis_gates=basis_gates)
self.assertEqual(transpiled_circuit.parameters, param_set)
@data(list(range(6)), ParameterVector("ΞΈ", length=6), [0, 1, Parameter("theta"), 3, 4, 5])
def test_parameters_setter(self, params):
"""Test setting the parameters via list."""
# construct circuit with some parameters
initial_params = ParameterVector("p", length=6)
circuit = QuantumCircuit(1)
for i, initial_param in enumerate(initial_params):
circuit.ry(i * initial_param, 0)
# create an NLocal from the circuit and set the new parameters
nlocal = NLocal(1, entanglement_blocks=circuit, reps=1)
nlocal.assign_parameters(params, inplace=True)
param_set = {p for p in params if isinstance(p, ParameterExpression)}
with self.subTest(msg="Test the parameters of the non-transpiled circuit"):
# check the parameters of the final circuit
self.assertEqual(nlocal.parameters, param_set)
with self.subTest(msg="Test the parameters of the transpiled circuit"):
basis_gates = ["id", "u1", "u2", "u3", "cx"]
transpiled_circuit = transpile(nlocal, basis_gates=basis_gates)
self.assertEqual(transpiled_circuit.parameters, param_set)
def test_repetetive_parameter_setting(self):
"""Test alternate setting of parameters and circuit construction."""
x = Parameter("x")
circuit = QuantumCircuit(1)
circuit.rx(x, 0)
nlocal = NLocal(1, entanglement_blocks=circuit, reps=3, insert_barriers=True)
with self.subTest(msg="immediately after initialization"):
self.assertEqual(len(nlocal.parameters), 3)
with self.subTest(msg="after circuit construction"):
self.assertEqual(len(nlocal.parameters), 3)
q = Parameter("q")
nlocal.assign_parameters([x, q, q], inplace=True)
with self.subTest(msg="setting parameter to Parameter objects"):
self.assertEqual(nlocal.parameters, set({x, q}))
nlocal.assign_parameters([0, -1], inplace=True)
with self.subTest(msg="setting parameter to numbers"):
self.assertEqual(nlocal.parameters, set())
def test_skip_unentangled_qubits(self):
"""Test skipping the unentangled qubits."""
num_qubits = 6
entanglement_1 = [[0, 1, 3], [1, 3, 5], [0, 1, 5]]
skipped_1 = [2, 4]
entanglement_2 = [entanglement_1, [[0, 1, 2], [2, 3, 5]]]
skipped_2 = [4]
for entanglement, skipped in zip([entanglement_1, entanglement_2], [skipped_1, skipped_2]):
with self.subTest(entanglement=entanglement, skipped=skipped):
nlocal = NLocal(
num_qubits,
rotation_blocks=XGate(),
entanglement_blocks=CCXGate(),
entanglement=entanglement,
reps=3,
skip_unentangled_qubits=True,
)
decomposed = nlocal.decompose()
skipped_set = {decomposed.qubits[i] for i in skipped}
dag = circuit_to_dag(decomposed)
idle = set(dag.idle_wires())
self.assertEqual(skipped_set, idle)
@data(
"linear",
"full",
"circular",
"sca",
"reverse_linear",
["linear", "full"],
["reverse_linear", "full"],
["circular", "linear", "sca"],
)
def test_entanglement_by_str(self, entanglement):
"""Test setting the entanglement of the layers by str."""
reps = 3
nlocal = NLocal(
5,
rotation_blocks=XGate(),
entanglement_blocks=CCXGate(),
entanglement=entanglement,
reps=reps,
)
def get_expected_entangler_map(rep_num, mode):
if mode == "linear":
return [(0, 1, 2), (1, 2, 3), (2, 3, 4)]
elif mode == "reverse_linear":
return [(2, 3, 4), (1, 2, 3), (0, 1, 2)]
elif mode == "full":
return [
(0, 1, 2),
(0, 1, 3),
(0, 1, 4),
(0, 2, 3),
(0, 2, 4),
(0, 3, 4),
(1, 2, 3),
(1, 2, 4),
(1, 3, 4),
(2, 3, 4),
]
else:
circular = [(3, 4, 0), (0, 1, 2), (1, 2, 3), (2, 3, 4)]
if mode == "circular":
return circular
sca = circular[-rep_num:] + circular[:-rep_num]
if rep_num % 2 == 1:
sca = [tuple(reversed(indices)) for indices in sca]
return sca
for rep_num in range(reps):
entangler_map = nlocal.get_entangler_map(rep_num, 0, 3)
if isinstance(entanglement, list):
mode = entanglement[rep_num % len(entanglement)]
else:
mode = entanglement
expected = get_expected_entangler_map(rep_num, mode)
with self.subTest(rep_num=rep_num):
# using a set here since the order does not matter
self.assertEqual(entangler_map, expected)
def test_pairwise_entanglement(self):
"""Test pairwise entanglement."""
nlocal = NLocal(
5,
rotation_blocks=XGate(),
entanglement_blocks=CXGate(),
entanglement="pairwise",
reps=1,
)
entangler_map = nlocal.get_entangler_map(0, 0, 2)
pairwise = [(0, 1), (2, 3), (1, 2), (3, 4)]
self.assertEqual(pairwise, entangler_map)
def test_pairwise_entanglement_raises(self):
"""Test choosing pairwise entanglement raises an error for too large blocks."""
nlocal = NLocal(3, XGate(), CCXGate(), entanglement="pairwise", reps=1)
# pairwise entanglement is only defined if the entangling gate has 2 qubits
with self.assertRaises(ValueError):
print(nlocal.draw())
def test_entanglement_by_list(self):
"""Test setting the entanglement by list.
This is the circuit we test (times 2, with final X layer)
βββββ ββββββββββ βββββ
q_0: |0>β€ X ββββ βββββ βββXβββββ€ X ββ€ X ββββ βββXβββββββ .. β€ X β
βββββ€ β β β βββββ€βββ¬ββ β β βββββ€
q_1: |0>β€ X ββββ βββββΌββββΌββXββ€ X ββββ βββββΌβββXββXββββ .. β€ X β
βββββ€βββ΄ββ β β β βββββ€ β β β x2 βββββ€
q_2: |0>β€ X ββ€ X ββββ ββββΌββXββ€ X ββββ βββββ ββββββXββXβ .. β€ X β
βββββ€ββββββββ΄ββ β βββββ€ βββ΄ββ β βββββ€
q_3: |0>β€ X βββββββ€ X ββXβββββ€ X βββββββ€ X ββββββββXβ .. β€ X β
βββββ βββββ βββββ βββββ βββββ
"""
circuit = QuantumCircuit(4)
for _ in range(2):
circuit.x([0, 1, 2, 3])
circuit.barrier()
circuit.ccx(0, 1, 2)
circuit.ccx(0, 2, 3)
circuit.swap(0, 3)
circuit.swap(1, 2)
circuit.barrier()
circuit.x([0, 1, 2, 3])
circuit.barrier()
circuit.ccx(2, 1, 0)
circuit.ccx(0, 2, 3)
circuit.swap(0, 1)
circuit.swap(1, 2)
circuit.swap(2, 3)
circuit.barrier()
circuit.x([0, 1, 2, 3])
layer_1_ccx = [(0, 1, 2), (0, 2, 3)]
layer_1_swap = [(0, 3), (1, 2)]
layer_1 = [layer_1_ccx, layer_1_swap]
layer_2_ccx = [(2, 1, 0), (0, 2, 3)]
layer_2_swap = [(0, 1), (1, 2), (2, 3)]
layer_2 = [layer_2_ccx, layer_2_swap]
entanglement = [layer_1, layer_2]
nlocal = NLocal(
4,
rotation_blocks=XGate(),
entanglement_blocks=[CCXGate(), SwapGate()],
reps=4,
entanglement=entanglement,
insert_barriers=True,
)
self.assertCircuitEqual(nlocal, circuit)
def test_initial_state_as_circuit_object(self):
"""Test setting `initial_state` to `QuantumCircuit` object"""
# βββββ βββββ
# q_0: βββ βββ€ X βββββββββ βββ€ X β
# βββ΄βββββββ€ββββββββ΄βββββββ€
# q_1: β€ X ββ€ H ββ€ X ββ€ X ββ€ X β
# βββββββββββββββββββββββββ
ref = QuantumCircuit(2)
ref.cx(0, 1)
ref.x(0)
ref.h(1)
ref.x(1)
ref.cx(0, 1)
ref.x(0)
ref.x(1)
qc = QuantumCircuit(2)
qc.cx(0, 1)
qc.h(1)
expected = NLocal(
num_qubits=2,
rotation_blocks=XGate(),
entanglement_blocks=CXGate(),
initial_state=qc,
reps=1,
)
self.assertCircuitEqual(ref, expected)
@ddt
class TestTwoLocal(QiskitTestCase):
"""Tests for the TwoLocal circuit."""
def assertCircuitEqual(self, qc1, qc2, visual=False, transpiled=True):
"""An equality test specialized to circuits."""
if transpiled:
basis_gates = ["id", "u1", "u3", "cx"]
qc1_transpiled = transpile(qc1, basis_gates=basis_gates, optimization_level=0)
qc2_transpiled = transpile(qc2, basis_gates=basis_gates, optimization_level=0)
qc1, qc2 = qc1_transpiled, qc2_transpiled
if visual:
self.assertEqual(qc1.draw(), qc2.draw())
else:
self.assertEqual(qc1, qc2)
def test_skip_final_rotation_layer(self):
"""Test skipping the final rotation layer works."""
two = TwoLocal(3, ["ry", "h"], ["cz", "cx"], reps=2, skip_final_rotation_layer=True)
self.assertEqual(two.num_parameters, 6) # would be 9 with a final rotation layer
@data(
(5, "rx", "cx", "full", 2, 15),
(3, "x", "z", "linear", 1, 0),
(3, "rx", "cz", "linear", 0, 3),
(3, ["rx", "ry"], ["cry", "cx"], "circular", 2, 24),
)
@unpack
def test_num_parameters(self, num_qubits, rot, ent, ent_mode, reps, expected):
"""Test the number of parameters."""
two = TwoLocal(
num_qubits,
rotation_blocks=rot,
entanglement_blocks=ent,
entanglement=ent_mode,
reps=reps,
)
with self.subTest(msg="num_parameters_settable"):
self.assertEqual(two.num_parameters_settable, expected)
with self.subTest(msg="num_parameters"):
self.assertEqual(two.num_parameters, expected)
def test_empty_two_local(self):
"""Test the setup of an empty two-local circuit."""
two = TwoLocal()
with self.subTest(msg="0 qubits"):
self.assertEqual(two.num_qubits, 0)
with self.subTest(msg="no blocks are set"):
self.assertListEqual(two.rotation_blocks, [])
self.assertListEqual(two.entanglement_blocks, [])
with self.subTest(msg="equal to empty circuit"):
self.assertEqual(two, QuantumCircuit())
@data("rx", RXGate(Parameter("p")), RXGate, "circuit")
def test_various_block_types(self, rot):
"""Test setting the rotation blocks to various type and assert the output type is RX."""
if rot == "circuit":
rot = QuantumCircuit(1)
rot.rx(Parameter("angle"), 0)
two = TwoLocal(3, rot, reps=0)
self.assertEqual(len(two.rotation_blocks), 1)
rotation = two.rotation_blocks[0]
# decompose
self.assertIsInstance(rotation.data[0].operation, RXGate)
def test_parameter_setters(self):
"""Test different possibilities to set parameters."""
two = TwoLocal(3, rotation_blocks="rx", entanglement="cz", reps=2)
params = [0, 1, 2, Parameter("x"), Parameter("y"), Parameter("z"), 6, 7, 0]
params_set = {param for param in params if isinstance(param, Parameter)}
with self.subTest(msg="dict assign and copy"):
ordered = two.ordered_parameters
bound = two.assign_parameters(dict(zip(ordered, params)), inplace=False)
self.assertEqual(bound.parameters, params_set)
self.assertEqual(two.num_parameters, 9)
with self.subTest(msg="list assign and copy"):
ordered = two.ordered_parameters
bound = two.assign_parameters(params, inplace=False)
self.assertEqual(bound.parameters, params_set)
self.assertEqual(two.num_parameters, 9)
with self.subTest(msg="list assign inplace"):
ordered = two.ordered_parameters
two.assign_parameters(params, inplace=True)
self.assertEqual(two.parameters, params_set)
self.assertEqual(two.num_parameters, 3)
self.assertEqual(two.num_parameters_settable, 9)
def test_parameters_settable_is_constant(self):
"""Test the attribute num_parameters_settable does not change on parameter change."""
two = TwoLocal(3, rotation_blocks="rx", entanglement="cz", reps=2)
ordered_params = two.ordered_parameters
x = Parameter("x")
two.assign_parameters(dict(zip(ordered_params, [x] * two.num_parameters)), inplace=True)
with self.subTest(msg="num_parameters collapsed to 1"):
self.assertEqual(two.num_parameters, 1)
with self.subTest(msg="num_parameters_settable remained constant"):
self.assertEqual(two.num_parameters_settable, len(ordered_params))
def test_compose_inplace_to_circuit(self):
"""Test adding a two-local to an existing circuit."""
two = TwoLocal(3, ["ry", "rz"], "cz", "full", reps=1, insert_barriers=True)
circuit = QuantumCircuit(3)
circuit.compose(two, inplace=True)
# ββββββββββββββββββββββββ β β ββββββββββββ ββββββββββββ
# q_0: β€ Ry(ΞΈ[0]) ββ€ Rz(ΞΈ[3]) ββββββ βββ ββββββββ€ Ry(ΞΈ[6]) βββ€ Rz(ΞΈ[9]) β
# ββββββββββββ€ββββββββββββ€ β β β β ββββββββββββ€ββ΄βββββββββββ€
# q_1: β€ Ry(ΞΈ[1]) ββ€ Rz(ΞΈ[4]) ββββββ βββΌβββ βββββ€ Ry(ΞΈ[7]) ββ€ Rz(ΞΈ[10]) β
# ββββββββββββ€ββββββββββββ€ β β β β ββββββββββββ€βββββββββββββ€
# q_2: β€ Ry(ΞΈ[2]) ββ€ Rz(ΞΈ[5]) βββββββββ βββ βββββ€ Ry(ΞΈ[8]) ββ€ Rz(ΞΈ[11]) β
# ββββββββββββββββββββββββ β β βββββββββββββββββββββββββ
reference = QuantumCircuit(3)
param_iter = iter(two.ordered_parameters)
for i in range(3):
reference.ry(next(param_iter), i)
for i in range(3):
reference.rz(next(param_iter), i)
reference.barrier()
reference.cz(0, 1)
reference.cz(0, 2)
reference.cz(1, 2)
reference.barrier()
for i in range(3):
reference.ry(next(param_iter), i)
for i in range(3):
reference.rz(next(param_iter), i)
self.assertCircuitEqual(circuit.decompose(), reference)
def test_composing_two(self):
"""Test adding two two-local circuits."""
entangler_map = [[0, 3], [0, 2]]
two = TwoLocal(4, [], "cry", entangler_map, reps=1)
circuit = two.compose(two)
reference = QuantumCircuit(4)
params = two.ordered_parameters
for _ in range(2):
reference.cry(params[0], 0, 3)
reference.cry(params[1], 0, 2)
self.assertCircuitEqual(reference, circuit)
def test_ry_blocks(self):
"""Test that the RealAmplitudes circuit is instantiated correctly."""
two = RealAmplitudes(4)
with self.subTest(msg="test rotation gate"):
self.assertEqual(len(two.rotation_blocks), 1)
self.assertIsInstance(two.rotation_blocks[0].data[0].operation, RYGate)
with self.subTest(msg="test parameter bounds"):
expected = [(-np.pi, np.pi)] * two.num_parameters
np.testing.assert_almost_equal(two.parameter_bounds, expected)
def test_ry_circuit_reverse_linear(self):
"""Test a RealAmplitudes circuit with entanglement = "reverse_linear"."""
num_qubits = 3
reps = 2
entanglement = "reverse_linear"
parameters = ParameterVector("theta", num_qubits * (reps + 1))
param_iter = iter(parameters)
expected = QuantumCircuit(3)
for _ in range(reps):
for i in range(num_qubits):
expected.ry(next(param_iter), i)
expected.cx(1, 2)
expected.cx(0, 1)
for i in range(num_qubits):
expected.ry(next(param_iter), i)
library = RealAmplitudes(
num_qubits, reps=reps, entanglement=entanglement
).assign_parameters(parameters)
self.assertCircuitEqual(library, expected)
def test_ry_circuit_full(self):
"""Test a RealAmplitudes circuit with entanglement = "full"."""
num_qubits = 3
reps = 2
entanglement = "full"
parameters = ParameterVector("theta", num_qubits * (reps + 1))
param_iter = iter(parameters)
# ββββββββββββ ββββββββββββ ββββββββββββ
# q_0: β€ Ry(ΞΈ[0]) ββββ βββββ βββ€ Ry(ΞΈ[3]) ββββββββββββββββ βββββ βββ€ Ry(ΞΈ[6]) βββββββββββββ
# ββββββββββββ€βββ΄ββ β βββββββββββββββββββββββββββ΄ββ β ββββββββββββββββββββββββ
# q_1: β€ Ry(ΞΈ[1]) ββ€ X ββββΌββββββββββ βββββ€ Ry(ΞΈ[4]) ββ€ X ββββΌββββββββββ βββββ€ Ry(ΞΈ[7]) β
# ββββββββββββ€ββββββββ΄ββ βββ΄ββ ββββββββββββ€ββββββββ΄ββ βββ΄ββ ββββββββββββ€
# q_2: β€ Ry(ΞΈ[2]) βββββββ€ X βββββββ€ X ββββ€ Ry(ΞΈ[5]) βββββββ€ X βββββββ€ X ββββ€ Ry(ΞΈ[8]) β
# ββββββββββββ βββββ βββββ ββββββββββββ βββββ βββββ ββββββββββββ
expected = QuantumCircuit(3)
for _ in range(reps):
for i in range(num_qubits):
expected.ry(next(param_iter), i)
expected.cx(0, 1)
expected.cx(0, 2)
expected.cx(1, 2)
for i in range(num_qubits):
expected.ry(next(param_iter), i)
library = RealAmplitudes(
num_qubits, reps=reps, entanglement=entanglement
).assign_parameters(parameters)
self.assertCircuitEqual(library, expected)
def test_ryrz_blocks(self):
"""Test that the EfficientSU2 circuit is instantiated correctly."""
two = EfficientSU2(3)
with self.subTest(msg="test rotation gate"):
self.assertEqual(len(two.rotation_blocks), 2)
self.assertIsInstance(two.rotation_blocks[0].data[0].operation, RYGate)
self.assertIsInstance(two.rotation_blocks[1].data[0].operation, RZGate)
with self.subTest(msg="test parameter bounds"):
expected = [(-np.pi, np.pi)] * two.num_parameters
np.testing.assert_almost_equal(two.parameter_bounds, expected)
def test_ryrz_circuit(self):
"""Test an EfficientSU2 circuit."""
num_qubits = 3
reps = 2
entanglement = "circular"
parameters = ParameterVector("theta", 2 * num_qubits * (reps + 1))
param_iter = iter(parameters)
# βββββββββββββββββββββββββββββ ββββββββββββββββββββββββ Β»
# q_0: β€ Ry(ΞΈ[0]) ββ€ Rz(ΞΈ[3]) ββ€ X ββββ βββ€ Ry(ΞΈ[6]) ββ€ Rz(ΞΈ[9]) ββββββββββββββΒ»
# ββββββββββββ€ββββββββββββ€βββ¬βββββ΄ββββββββββββββββββββββββββ€βββββββββββββΒ»
# q_1: β€ Ry(ΞΈ[1]) ββ€ Rz(ΞΈ[4]) ββββΌβββ€ X βββββββ βββββββ€ Ry(ΞΈ[7]) ββ€ Rz(ΞΈ[10]) βΒ»
# ββββββββββββ€ββββββββββββ€ β βββββ βββ΄ββ ββββββββββββ€βββββββββββββ€Β»
# q_2: β€ Ry(ΞΈ[2]) ββ€ Rz(ΞΈ[5]) ββββ βββββββββββ€ X ββββββ€ Ry(ΞΈ[8]) ββ€ Rz(ΞΈ[11]) βΒ»
# ββββββββββββββββββββββββ βββββ βββββββββββββββββββββββββΒ»
# Β« βββββ ββββββββββββββββββββββββββ
# Β«q_0: β€ X ββββ βββ€ Ry(ΞΈ[12]) ββ€ Rz(ΞΈ[15]) ββββββββββββββ
# Β« βββ¬βββββ΄ββββββββββββββββββββββββββββ€βββββββββββββ
# Β«q_1: βββΌβββ€ X ββββββββ βββββββ€ Ry(ΞΈ[13]) ββ€ Rz(ΞΈ[16]) β
# Β« β βββββ βββ΄ββ βββββββββββββ€βββββββββββββ€
# Β«q_2: βββ ββββββββββββ€ X ββββββ€ Ry(ΞΈ[14]) ββ€ Rz(ΞΈ[17]) β
# Β« βββββ ββββββββββββββββββββββββββ
expected = QuantumCircuit(3)
for _ in range(reps):
for i in range(num_qubits):
expected.ry(next(param_iter), i)
for i in range(num_qubits):
expected.rz(next(param_iter), i)
expected.cx(2, 0)
expected.cx(0, 1)
expected.cx(1, 2)
for i in range(num_qubits):
expected.ry(next(param_iter), i)
for i in range(num_qubits):
expected.rz(next(param_iter), i)
library = EfficientSU2(num_qubits, reps=reps, entanglement=entanglement).assign_parameters(
parameters
)
self.assertCircuitEqual(library, expected)
def test_swaprz_blocks(self):
"""Test that the ExcitationPreserving circuit is instantiated correctly."""
two = ExcitationPreserving(5)
with self.subTest(msg="test rotation gate"):
self.assertEqual(len(two.rotation_blocks), 1)
self.assertIsInstance(two.rotation_blocks[0].data[0].operation, RZGate)
with self.subTest(msg="test entanglement gate"):
self.assertEqual(len(two.entanglement_blocks), 1)
block = two.entanglement_blocks[0]
self.assertEqual(len(block.data), 2)
self.assertIsInstance(block.data[0].operation, RXXGate)
self.assertIsInstance(block.data[1].operation, RYYGate)
with self.subTest(msg="test parameter bounds"):
expected = [(-np.pi, np.pi)] * two.num_parameters
np.testing.assert_almost_equal(two.parameter_bounds, expected)
def test_swaprz_circuit(self):
"""Test a ExcitationPreserving circuit in iswap mode."""
num_qubits = 3
reps = 2
entanglement = "linear"
parameters = ParameterVector("theta", num_qubits * (reps + 1) + reps * (num_qubits - 1))
param_iter = iter(parameters)
# ββββββββββββββββββββββββββββββββββββββββ ββββββββββββ Β»
# q_0: β€ Rz(ΞΈ[0]) ββ€0 ββ€0 βββ€ Rz(ΞΈ[5]) ββββββββββββββββΒ»
# ββββββββββββ€β Rxx(ΞΈ[3]) ββ Ryy(ΞΈ[3]) βββ΄βββββββββββ΄βββββββββββββββΒ»
# q_1: β€ Rz(ΞΈ[1]) ββ€1 ββ€1 ββ€0 ββ€0 βΒ»
# ββββββββββββ€βββββββββββββββββββββββββββββ Rxx(ΞΈ[4]) ββ Ryy(ΞΈ[4]) βΒ»
# q_2: β€ Rz(ΞΈ[2]) ββββββββββββββββββββββββββββββ€1 ββ€1 βΒ»
# ββββββββββββ ββββββββββββββββββββββββββββΒ»
# Β« βββββββββββββββββββββββββββββββββββββββββ Β»
# Β«q_0: βββββββββββββ€0 ββ€0 ββ€ Rz(ΞΈ[10]) ββββββββββββββββΒ»
# Β« βββββββββββββ Rxx(ΞΈ[8]) ββ Ryy(ΞΈ[8]) ββββββββββββββ΄βββββββββββββββΒ»
# Β«q_1: β€ Rz(ΞΈ[6]) ββ€1 ββ€1 ββ€0 ββ€0 βΒ»
# Β« ββββββββββββ€βββββββββββββββββββββββββββββ Rxx(ΞΈ[9]) ββ Ryy(ΞΈ[9]) βΒ»
# Β«q_2: β€ Rz(ΞΈ[7]) ββββββββββββββββββββββββββββββ€1 ββ€1 βΒ»
# Β« ββββββββββββ ββββββββββββββββββββββββββββΒ»
# Β«
# Β«q_0: βββββββββββββ
# Β« βββββββββββββ
# Β«q_1: β€ Rz(ΞΈ[11]) β
# Β« βββββββββββββ€
# Β«q_2: β€ Rz(ΞΈ[12]) β
# Β« βββββββββββββ
expected = QuantumCircuit(3)
for _ in range(reps):
for i in range(num_qubits):
expected.rz(next(param_iter), i)
shared_param = next(param_iter)
expected.rxx(shared_param, 0, 1)
expected.ryy(shared_param, 0, 1)
shared_param = next(param_iter)
expected.rxx(shared_param, 1, 2)
expected.ryy(shared_param, 1, 2)
for i in range(num_qubits):
expected.rz(next(param_iter), i)
library = ExcitationPreserving(
num_qubits, reps=reps, entanglement=entanglement
).assign_parameters(parameters)
self.assertCircuitEqual(library, expected)
def test_fsim_circuit(self):
"""Test a ExcitationPreserving circuit in fsim mode."""
num_qubits = 3
reps = 2
entanglement = "linear"
# need the parameters in the entanglement blocks to be the same because the order
# can get mixed up in ExcitationPreserving (since parameters are not ordered in circuits)
parameters = [1] * (num_qubits * (reps + 1) + reps * (1 + num_qubits))
param_iter = iter(parameters)
# βββββββββββββββββββββββββββββββ βββββββββ Β»
# q_0: β€ Rz(1) ββ€0 ββ€0 βββ βββββββ€ Rz(1) ββββββββββββββββββββΒ»
# βββββββββ€β Rxx(1) ββ Ryy(1) β βP(1) ββ΄ββββββββ΄ββββββββββββ Β»
# q_1: β€ Rz(1) ββ€1 ββ€1 βββ ββββββ€0 ββ€0 βββ βββββΒ»
# βββββββββ€ββββββββββββββββββββββ β Rxx(1) ββ Ryy(1) β βP(1) Β»
# q_2: β€ Rz(1) βββββββββββββββββββββββββββββββ€1 ββ€1 βββ βββββΒ»
# βββββββββ ββββββββββββββββββββββ Β»
# Β« ββββββββββββββββββββββ βββββββββ Β»
# Β«q_0: ββββββββββ€0 ββ€0 βββ βββββββ€ Rz(1) ββββββββββββββββββββΒ»
# Β« ββββββββββ Rxx(1) ββ Ryy(1) β βP(1) ββ΄ββββββββ΄ββββββββββββ Β»
# Β«q_1: β€ Rz(1) ββ€1 ββ€1 βββ ββββββ€0 ββ€0 βββ βββββΒ»
# Β« βββββββββ€ββββββββββββββββββββββ β Rxx(1) ββ Ryy(1) β βP(1) Β»
# Β«q_2: β€ Rz(1) βββββββββββββββββββββββββββββββ€1 ββ€1 βββ βββββΒ»
# Β« βββββββββ ββββββββββββββββββββββ Β»
# Β«
# Β«q_0: βββββββββ
# Β« βββββββββ
# Β«q_1: β€ Rz(1) β
# Β« βββββββββ€
# Β«q_2: β€ Rz(1) β
# Β« βββββββββ
expected = QuantumCircuit(3)
for _ in range(reps):
for i in range(num_qubits):
expected.rz(next(param_iter), i)
shared_param = next(param_iter)
expected.rxx(shared_param, 0, 1)
expected.ryy(shared_param, 0, 1)
expected.cp(next(param_iter), 0, 1)
shared_param = next(param_iter)
expected.rxx(shared_param, 1, 2)
expected.ryy(shared_param, 1, 2)
expected.cp(next(param_iter), 1, 2)
for i in range(num_qubits):
expected.rz(next(param_iter), i)
library = ExcitationPreserving(
num_qubits, reps=reps, mode="fsim", entanglement=entanglement
).assign_parameters(parameters)
self.assertCircuitEqual(library, expected)
def test_circular_on_same_block_and_circuit_size(self):
"""Test circular entanglement works correctly if the circuit and block sizes match."""
two = TwoLocal(2, "ry", "cx", entanglement="circular", reps=1)
parameters = np.arange(two.num_parameters)
# βββββββββ βββββββββ
# q_0: β€ Ry(0) ββββ βββ€ Ry(2) β
# βββββββββ€βββ΄βββββββββββ€
# q_1: β€ Ry(1) ββ€ X ββ€ Ry(3) β
# βββββββββββββββββββββββ
ref = QuantumCircuit(2)
ref.ry(parameters[0], 0)
ref.ry(parameters[1], 1)
ref.cx(0, 1)
ref.ry(parameters[2], 0)
ref.ry(parameters[3], 1)
self.assertCircuitEqual(two.assign_parameters(parameters), ref)
def test_circuit_with_numpy_integers(self):
"""Test if TwoLocal can be made from numpy integers"""
num_qubits = 6
reps = 3
expected_np32 = [
(i, j)
for i in np.arange(num_qubits, dtype=np.int32)
for j in np.arange(num_qubits, dtype=np.int32)
if i < j
]
expected_np64 = [
(i, j)
for i in np.arange(num_qubits, dtype=np.int64)
for j in np.arange(num_qubits, dtype=np.int64)
if i < j
]
two_np32 = TwoLocal(num_qubits, "ry", "cx", entanglement=expected_np32, reps=reps)
two_np64 = TwoLocal(num_qubits, "ry", "cx", entanglement=expected_np64, reps=reps)
expected_cx = reps * num_qubits * (num_qubits - 1) / 2
self.assertEqual(two_np32.decompose().count_ops()["cx"], expected_cx)
self.assertEqual(two_np64.decompose().count_ops()["cx"], expected_cx)
@combine(num_qubits=[4, 5])
def test_full_vs_reverse_linear(self, num_qubits):
"""Test that 'full' and 'reverse_linear' provide the same unitary element."""
reps = 2
full = RealAmplitudes(num_qubits=num_qubits, entanglement="full", reps=reps)
num_params = (reps + 1) * num_qubits
np.random.seed(num_qubits)
params = np.random.rand(num_params)
reverse = RealAmplitudes(num_qubits=num_qubits, entanglement="reverse_linear", reps=reps)
full.assign_parameters(params, inplace=True)
reverse.assign_parameters(params, inplace=True)
self.assertEqual(Operator(full), Operator(reverse))
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test permutation quantum circuits, permutation gates, and quantum circuits that
contain permutation gates."""
import io
import unittest
import numpy as np
from qiskit import QuantumRegister
from qiskit.test.base import QiskitTestCase
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.exceptions import CircuitError
from qiskit.circuit.library import Permutation, PermutationGate
from qiskit.quantum_info import Operator
from qiskit.qpy import dump, load
class TestPermutationLibrary(QiskitTestCase):
"""Test library of permutation logic quantum circuits."""
def test_permutation(self):
"""Test permutation circuit."""
circuit = Permutation(num_qubits=4, pattern=[1, 0, 3, 2])
expected = QuantumCircuit(4)
expected.swap(0, 1)
expected.swap(2, 3)
expected = Operator(expected)
simulated = Operator(circuit)
self.assertTrue(expected.equiv(simulated))
def test_permutation_bad(self):
"""Test that [0,..,n-1] permutation is required (no -1 for last element)."""
self.assertRaises(CircuitError, Permutation, 4, [1, 0, -1, 2])
class TestPermutationGate(QiskitTestCase):
"""Tests for the PermutationGate class."""
def test_permutation(self):
"""Test that Operator can be constructed."""
perm = PermutationGate(pattern=[1, 0, 3, 2])
expected = QuantumCircuit(4)
expected.swap(0, 1)
expected.swap(2, 3)
expected = Operator(expected)
simulated = Operator(perm)
self.assertTrue(expected.equiv(simulated))
def test_permutation_bad(self):
"""Test that [0,..,n-1] permutation is required (no -1 for last element)."""
self.assertRaises(CircuitError, PermutationGate, [1, 0, -1, 2])
def test_permutation_array(self):
"""Test correctness of the ``__array__`` method."""
perm = PermutationGate([1, 2, 0])
# The permutation pattern means q1->q0, q2->q1, q0->q2, or equivalently
# q0'=q1, q1'=q2, q2'=q0, where the primed values are the values after the
# permutation. The following matrix is the expected unitary matrix for this.
# As an example, the second column represents the result of applying
# the permutation to |001>, i.e. to q2=0, q1=0, q0=1. We should get
# q2'=q0=1, q1'=q2=0, q0'=q1=0, that is the state |100>. This corresponds
# to the "1" in the 5 row.
expected_op = np.array(
[
[1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1],
]
)
self.assertTrue(np.array_equal(perm.__array__(dtype=int), expected_op))
def test_pattern(self):
"""Test the ``pattern`` method."""
pattern = [1, 3, 5, 0, 4, 2]
perm = PermutationGate(pattern)
self.assertTrue(np.array_equal(perm.pattern, pattern))
def test_inverse(self):
"""Test correctness of the ``inverse`` method."""
perm = PermutationGate([1, 3, 5, 0, 4, 2])
# We have the permutation 1->0, 3->1, 5->2, 0->3, 4->4, 2->5.
# The inverse permutations is 0->1, 1->3, 2->5, 3->0, 4->4, 5->2, or
# after reordering 3->0, 0->1, 5->2, 1->3, 4->4, 2->5.
inverse_perm = perm.inverse()
expected_inverse_perm = PermutationGate([3, 0, 5, 1, 4, 2])
self.assertTrue(np.array_equal(inverse_perm.pattern, expected_inverse_perm.pattern))
class TestPermutationGatesOnCircuit(QiskitTestCase):
"""Tests for quantum circuits containing permutations."""
def test_append_to_circuit(self):
"""Test method for adding Permutations to quantum circuit."""
qc = QuantumCircuit(5)
qc.append(PermutationGate([1, 2, 0]), [0, 1, 2])
qc.append(PermutationGate([2, 3, 0, 1]), [1, 2, 3, 4])
self.assertIsInstance(qc.data[0].operation, PermutationGate)
self.assertIsInstance(qc.data[1].operation, PermutationGate)
def test_inverse(self):
"""Test inverse method for circuits with permutations."""
qc = QuantumCircuit(5)
qc.append(PermutationGate([1, 2, 3, 0]), [0, 4, 2, 1])
qci = qc.inverse()
qci_pattern = qci.data[0].operation.pattern
expected_pattern = [3, 0, 1, 2]
# The inverse permutations should be defined over the same qubits but with the
# inverse permutation pattern.
self.assertTrue(np.array_equal(qci_pattern, expected_pattern))
self.assertTrue(np.array_equal(qc.data[0].qubits, qci.data[0].qubits))
def test_reverse_ops(self):
"""Test reverse_ops method for circuits with permutations."""
qc = QuantumCircuit(5)
qc.append(PermutationGate([1, 2, 3, 0]), [0, 4, 2, 1])
qcr = qc.reverse_ops()
# The reversed circuit should have the permutation gate with the same pattern and over the
# same qubits.
self.assertTrue(np.array_equal(qc.data[0].operation.pattern, qcr.data[0].operation.pattern))
self.assertTrue(np.array_equal(qc.data[0].qubits, qcr.data[0].qubits))
def test_conditional(self):
"""Test adding conditional permutations."""
qc = QuantumCircuit(5, 1)
qc.append(PermutationGate([1, 2, 0]), [2, 3, 4]).c_if(0, 1)
self.assertIsNotNone(qc.data[0].operation.condition)
def test_qasm(self):
"""Test qasm for circuits with permutations."""
qr = QuantumRegister(5, "q0")
circuit = QuantumCircuit(qr)
pattern = [2, 4, 3, 0, 1]
permutation = PermutationGate(pattern)
circuit.append(permutation, [0, 1, 2, 3, 4])
circuit.h(qr[0])
expected_qasm = (
"OPENQASM 2.0;\n"
'include "qelib1.inc";\n'
"gate permutation__2_4_3_0_1_ q0,q1,q2,q3,q4 { swap q2,q3; swap q1,q4; swap q0,q3; }\n"
"qreg q0[5];\n"
"permutation__2_4_3_0_1_ q0[0],q0[1],q0[2],q0[3],q0[4];\n"
"h q0[0];\n"
)
self.assertEqual(expected_qasm, circuit.qasm())
def test_qpy(self):
"""Test qpy for circuits with permutations."""
circuit = QuantumCircuit(6, 1)
circuit.cx(0, 1)
circuit.append(PermutationGate([1, 2, 0]), [2, 4, 5])
circuit.h(4)
print(circuit)
qpy_file = io.BytesIO()
dump(circuit, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(circuit, new_circuit)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test library of phase estimation circuits."""
import unittest
import numpy as np
from qiskit.test.base import QiskitTestCase
from qiskit import BasicAer, execute
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.library import PhaseEstimation, QFT
from qiskit.quantum_info import Statevector
class TestPhaseEstimation(QiskitTestCase):
"""Test the phase estimation circuit."""
def assertPhaseEstimationIsCorrect(
self, pec: QuantumCircuit, eigenstate: QuantumCircuit, phase_as_binary: str
):
r"""Assert that the phase estimation circuit implements the correct transformation.
Applying the phase estimation circuit on a target register which holds the eigenstate
:math:`|u\rangle` (say the last register), the final state should be
.. math::
|\phi_1\rangle \cdots |\phi_t\rangle |u\rangle
where the eigenvalue is written as :math:`e^{2\pi i \phi}` and the angle is represented
in binary fraction, i.e. :math:`\phi = 0.\phi_1 \ldots \phi_t`.
Args:
pec: The circuit implementing the phase estimation circuit.
eigenstate: The eigenstate as circuit.
phase_as_binary: The phase of the eigenvalue in a binary fraction. E.g. if the
phase is 0.25, the binary fraction is '01' as 0.01 = 0 * 0.5 + 1 * 0.25 = 0.25.
"""
# the target state
eigenstate_as_vector = Statevector.from_instruction(eigenstate).data
reference = eigenstate_as_vector
zero, one = [1, 0], [0, 1]
for qubit in phase_as_binary[::-1]:
reference = np.kron(reference, zero if qubit == "0" else one)
# the simulated state
circuit = QuantumCircuit(pec.num_qubits)
circuit.compose(
eigenstate,
list(range(pec.num_qubits - eigenstate.num_qubits, pec.num_qubits)),
inplace=True,
)
circuit.compose(pec, inplace=True)
# TODO use Statevector for simulation once Qiskit/qiskit-terra#4681 is resolved
# actual = Statevector.from_instruction(circuit).data
backend = BasicAer.get_backend("statevector_simulator")
actual = execute(circuit, backend).result().get_statevector()
np.testing.assert_almost_equal(reference, actual)
def test_phase_estimation(self):
"""Test the standard phase estimation circuit."""
with self.subTest("U=S, psi=|1>"):
unitary = QuantumCircuit(1)
unitary.s(0)
eigenstate = QuantumCircuit(1)
eigenstate.x(0)
# eigenvalue is 1j = exp(2j pi 0.25) thus phi = 0.25 = 0.010 = '010'
# using three digits as 3 evaluation qubits are used
phase_as_binary = "0100"
pec = PhaseEstimation(4, unitary)
self.assertPhaseEstimationIsCorrect(pec, eigenstate, phase_as_binary)
with self.subTest("U=SZ, psi=|11>"):
unitary = QuantumCircuit(2)
unitary.z(0)
unitary.s(1)
eigenstate = QuantumCircuit(2)
eigenstate.x([0, 1])
# eigenvalue is -1j = exp(2j pi 0.75) thus phi = 0.75 = 0.110 = '110'
# using three digits as 3 evaluation qubits are used
phase_as_binary = "110"
pec = PhaseEstimation(3, unitary)
self.assertPhaseEstimationIsCorrect(pec, eigenstate, phase_as_binary)
with self.subTest("a 3-q unitary"):
# βββββ
# q_0: β€ X ββββ βββββ βββββββ
# βββββ€ β β
# q_1: β€ X ββββ βββββ βββββββ
# βββββ€ββββββββ΄βββββββ
# q_2: β€ X ββ€ H ββ€ X ββ€ H β
# ββββββββββββββββββββ
unitary = QuantumCircuit(3)
unitary.x([0, 1, 2])
unitary.cz(0, 1)
unitary.h(2)
unitary.ccx(0, 1, 2)
unitary.h(2)
# βββββ
# q_0: β€ H ββββ βββββ ββ
# ββββββββ΄ββ β
# q_1: ββββββ€ X ββββΌββ
# ββββββββ΄ββ
# q_2: βββββββββββ€ X β
# βββββ
eigenstate = QuantumCircuit(3)
eigenstate.h(0)
eigenstate.cx(0, 1)
eigenstate.cx(0, 2)
# the unitary acts as identity on the eigenstate, thus the phase is 0
phase_as_binary = "00"
pec = PhaseEstimation(2, unitary)
self.assertPhaseEstimationIsCorrect(pec, eigenstate, phase_as_binary)
def test_phase_estimation_iqft_setting(self):
"""Test default and custom setting of the QFT circuit."""
unitary = QuantumCircuit(1)
unitary.s(0)
with self.subTest("default QFT"):
pec = PhaseEstimation(3, unitary)
expected_qft = QFT(3, inverse=True, do_swaps=False)
self.assertEqual(
pec.decompose().data[-1].operation.definition, expected_qft.decompose()
)
with self.subTest("custom QFT"):
iqft = QFT(3, approximation_degree=2).inverse()
pec = PhaseEstimation(3, unitary, iqft=iqft)
self.assertEqual(pec.decompose().data[-1].operation.definition, iqft.decompose())
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the piecewise Chebyshev approximation."""
import unittest
from collections import defaultdict
import numpy as np
from ddt import ddt, data, unpack
from qiskit.test.base import QiskitTestCase
from qiskit import BasicAer, execute
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev
@ddt
class TestPiecewiseChebyshev(QiskitTestCase):
"""Test the piecewise Chebyshev approximation."""
def assertFunctionIsCorrect(self, function_circuit, reference):
"""Assert that ``function_circuit`` implements the reference function ``reference``."""
function_circuit._build()
num_state_qubits = function_circuit.num_state_qubits
num_ancilla_qubits = function_circuit.num_ancillas
circuit = QuantumCircuit(num_state_qubits + 1 + num_ancilla_qubits)
circuit.h(list(range(num_state_qubits)))
circuit.append(function_circuit.to_instruction(), list(range(circuit.num_qubits)))
backend = BasicAer.get_backend("statevector_simulator")
statevector = execute(circuit, backend).result().get_statevector()
probabilities = defaultdict(float)
for i, statevector_amplitude in enumerate(statevector):
i = bin(i)[2:].zfill(circuit.num_qubits)[num_ancilla_qubits:]
probabilities[i] += np.real(np.abs(statevector_amplitude) ** 2)
unrolled_probabilities = []
unrolled_expectations = []
for i, probability in probabilities.items():
x, last_qubit = int(i[1:], 2), i[0]
if last_qubit == "0":
expected_amplitude = np.cos(reference(x)) / np.sqrt(2**num_state_qubits)
else:
expected_amplitude = np.sin(reference(x)) / np.sqrt(2**num_state_qubits)
unrolled_probabilities += [probability]
unrolled_expectations += [np.real(np.abs(expected_amplitude) ** 2)]
np.testing.assert_array_almost_equal(
unrolled_probabilities, unrolled_expectations, decimal=1
)
@data(
(lambda x: np.arcsin(1 / x), 2, [2, 4], 2),
(lambda x: x / 8, 1, [1, 8], 3),
(np.sqrt, 2, None, 2),
)
@unpack
def test_piecewise_chebyshev(self, f_x, degree, breakpoints, num_state_qubits):
"""Test the piecewise Chebyshev approximation."""
def pw_poly(x):
if breakpoints:
if len(breakpoints) > 1:
start = breakpoints[0]
end = breakpoints[-1]
else:
start = breakpoints[0]
end = 2**num_state_qubits
else:
start = 0
end = 2**num_state_qubits
if start <= x < end:
return f_x(x)
return np.arcsin(1)
pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits)
self.assertFunctionIsCorrect(pw_approximation, pw_poly)
def test_piecewise_chebyshev_mutability(self):
"""Test the mutability of the piecewise Chebyshev approximation."""
def pw_poly(x, f_x):
if breakpoints[0] <= x < breakpoints[-1]:
return f_x(x)
return np.arcsin(1)
def f_x_1(x):
return x / 2
pw_approximation = PiecewiseChebyshev(f_x_1)
with self.subTest(msg="missing number of state qubits"):
with self.assertRaises(AttributeError): # no state qubits set
print(pw_approximation.draw())
with self.subTest(msg="default setup, just setting number of state qubits"):
pw_approximation.num_state_qubits = 2
pw_approximation.f_x = f_x_1
# set to the default breakpoints for pw_poly
breakpoints = [0, 4]
pw_approximation.breakpoints = breakpoints
self.assertFunctionIsCorrect(pw_approximation, lambda x: pw_poly(x, f_x_1))
def f_x_2(x):
return x / 4
with self.subTest(msg="setting non-default values"):
breakpoints = [0, 2]
degree = 2
pw_approximation.breakpoints = breakpoints
pw_approximation.degree = degree
pw_approximation.f_x = f_x_2
self.assertFunctionIsCorrect(pw_approximation, lambda x: pw_poly(x, f_x_2))
def f_x_3(x):
return x**2
with self.subTest(msg="changing all values"):
pw_approximation.num_state_qubits = 4
breakpoints = [1, 3, 6]
degree = 3
pw_approximation.breakpoints = breakpoints
pw_approximation.degree = degree
pw_approximation.f_x = f_x_3
self.assertFunctionIsCorrect(pw_approximation, lambda x: pw_poly(x, f_x_3))
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
""" This file allows to test the various QFT implemented. The user must specify:
1) The number of qubits it wants the QFT to be implemented on
2) The kind of QFT want to implement, among the options:
-> Normal QFT with SWAP gates at the end
-> Normal QFT without SWAP gates at the end
-> Inverse QFT with SWAP gates at the end
-> Inverse QFT without SWAP gates at the end
The user must can also specify, in the main function, the input quantum state. By default is a maximal superposition state
This file uses as simulator the local simulator 'statevector_simulator' because this simulator saves
the quantum state at the end of the circuit, which is exactly the goal of the test file. This simulator supports sufficient
qubits to the size of the QFTs that are going to be used in Shor's Algorithm because the IBM simulator only supports up to 32 qubits
"""
""" Imports from qiskit"""
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, IBMQ, BasicAer
""" Imports to Python functions """
import time
""" Local Imports """
from qfunctions import create_QFT, create_inverse_QFT
""" Function to properly print the final state of the simulation """
""" This is only possible in this way because the program uses the statevector_simulator """
def show_good_coef(results, n):
i=0
max = pow(2,n)
if max > 100: max = 100
""" Iterate to all possible states """
while i<max:
binary = bin(i)[2:].zfill(n)
number = results.item(i)
number = round(number.real, 3) + round(number.imag, 3) * 1j
""" Print the respective component of the state if it has a non-zero coefficient """
if number!=0:
print('|{}>'.format(binary),number)
i=i+1
""" Main program """
if __name__ == '__main__':
""" Select how many qubits want to apply the QFT on """
n = int(input('\nPlease select how many qubits want to apply the QFT on: '))
""" Select the kind of QFT to apply using the variable what_to_test:
what_to_test = 0: Apply normal QFT with the SWAP gates at the end
what_to_test = 1: Apply normal QFT without the SWAP gates at the end
what_to_test = 2: Apply inverse QFT with the SWAP gates at the end
what_to_test = 3: Apply inverse QFT without the SWAP gates at the end
"""
print('\nSelect the kind of QFT to apply:')
print('Select 0 to apply normal QFT with the SWAP gates at the end')
print('Select 1 to apply normal QFT without the SWAP gates at the end')
print('Select 2 to apply inverse QFT with the SWAP gates at the end')
print('Select 3 to apply inverse QFT without the SWAP gates at the end\n')
what_to_test = int(input('Select your option: '))
if what_to_test<0 or what_to_test>3:
print('Please select one of the options')
exit()
print('\nTotal number of qubits used: {0}\n'.format(n))
print('Please check source file to change input quantum state. By default is a maximal superposition state with |+> in every qubit.\n')
ts = time.time()
""" Create quantum and classical registers """
quantum_reg = QuantumRegister(n)
classic_reg = ClassicalRegister(n)
""" Create Quantum Circuit """
circuit = QuantumCircuit(quantum_reg, classic_reg)
""" Create the input state desired
Please change this as you like, by default we put H gates in every qubit,
initializing with a maximimal superposition state
"""
#circuit.h(quantum_reg)
""" Test the right QFT according to the variable specified before"""
if what_to_test == 0:
create_QFT(circuit,quantum_reg,n,1)
elif what_to_test == 1:
create_QFT(circuit,quantum_reg,n,0)
elif what_to_test == 2:
create_inverse_QFT(circuit,quantum_reg,n,1)
elif what_to_test == 3:
create_inverse_QFT(circuit,quantum_reg,n,0)
else:
print('Noting to implement, exiting program')
exit()
""" show results of circuit creation """
create_time = round(time.time()-ts, 3)
if n < 8: print(circuit)
print(f"... circuit creation time = {create_time}")
ts = time.time()
""" Simulate the created Quantum Circuit """
simulation = execute(circuit, backend=BasicAer.get_backend('statevector_simulator'),shots=1)
""" Get the results of the simulation in proper structure """
sim_result=simulation.result()
""" Get the statevector of the final quantum state """
outputstate = sim_result.get_statevector(circuit, decimals=3)
""" show execution time """
exec_time = round(time.time()-ts, 3)
print(f"... circuit execute time = {exec_time}")
""" Print final quantum state to user """
print('The final state after applying the QFT is:\n')
show_good_coef(outputstate,n)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
StatePreparation test.
"""
import unittest
import math
import numpy as np
from ddt import ddt, data
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info import Statevector, Operator
from qiskit.test import QiskitTestCase
from qiskit.exceptions import QiskitError
from qiskit.circuit.library import StatePreparation
@ddt
class TestStatePreparation(QiskitTestCase):
"""Test initialization with StatePreparation class"""
def test_prepare_from_label(self):
"""Prepare state from label."""
desired_sv = Statevector.from_label("01+-lr")
qc = QuantumCircuit(6)
qc.prepare_state("01+-lr", range(6))
actual_sv = Statevector(qc)
self.assertTrue(desired_sv == actual_sv)
def test_prepare_from_int(self):
"""Prepare state from int."""
desired_sv = Statevector.from_label("110101")
qc = QuantumCircuit(6)
qc.prepare_state(53, range(6))
actual_sv = Statevector(qc)
self.assertTrue(desired_sv == actual_sv)
def test_prepare_from_list(self):
"""Prepare state from list."""
desired_sv = Statevector([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
qc = QuantumCircuit(2)
qc.prepare_state([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
actual_sv = Statevector(qc)
self.assertTrue(desired_sv == actual_sv)
def test_prepare_single_qubit(self):
"""Prepare state in single qubit."""
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
circuit.prepare_state([1 / math.sqrt(2), 1 / math.sqrt(2)], qreg[1])
expected = QuantumCircuit(qreg)
expected.prepare_state([1 / math.sqrt(2), 1 / math.sqrt(2)], [qreg[1]])
self.assertEqual(circuit, expected)
def test_nonzero_state_incorrect(self):
"""Test final state incorrect if initial state not zero"""
desired_sv = Statevector([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
qc = QuantumCircuit(2)
qc.x(0)
qc.prepare_state([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
actual_sv = Statevector(qc)
self.assertFalse(desired_sv == actual_sv)
@data(2, "11", [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
def test_inverse(self, state):
"""Test inverse of StatePreparation"""
qc = QuantumCircuit(2)
stateprep = StatePreparation(state)
qc.append(stateprep, [0, 1])
qc.append(stateprep.inverse(), [0, 1])
self.assertTrue(np.allclose(Operator(qc).data, np.identity(2**qc.num_qubits)))
def test_double_inverse(self):
"""Test twice inverse of StatePreparation"""
desired_sv = Statevector([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
qc = QuantumCircuit(2)
stateprep = StatePreparation([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
qc.append(stateprep.inverse().inverse(), [0, 1])
actual_sv = Statevector(qc)
self.assertTrue(desired_sv == actual_sv)
def test_incompatible_state_and_qubit_args(self):
"""Test error raised if number of qubits not compatible with state arg"""
qc = QuantumCircuit(3)
with self.assertRaises(QiskitError):
qc.prepare_state("11")
def test_incompatible_int_state_and_qubit_args(self):
"""Test error raised if number of qubits not compatible with integer state arg"""
# pylint: disable=pointless-statement
with self.assertRaises(QiskitError):
stateprep = StatePreparation(5, num_qubits=2)
stateprep.definition
def test_int_state_and_no_qubit_args(self):
"""Test automatic determination of qubit number"""
stateprep = StatePreparation(5)
self.assertEqual(stateprep.num_qubits, 3)
def test_repeats(self):
"""Test repeat function repeats correctly"""
qc = QuantumCircuit(2)
qc.append(StatePreparation("01").repeat(2), [0, 1])
self.assertEqual(qc.decompose().count_ops()["state_preparation"], 2)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test library of weighted adder circuits."""
import unittest
from collections import defaultdict
from ddt import ddt, data
import numpy as np
from qiskit.test.base import QiskitTestCase
from qiskit import BasicAer, execute
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.library import WeightedAdder
@ddt
class TestWeightedAdder(QiskitTestCase):
"""Test the weighted adder circuit."""
def assertSummationIsCorrect(self, adder):
"""Assert that ``adder`` correctly implements the summation w.r.t. its set weights."""
circuit = QuantumCircuit(adder.num_qubits)
circuit.h(list(range(adder.num_state_qubits)))
circuit.append(adder.to_instruction(), list(range(adder.num_qubits)))
backend = BasicAer.get_backend("statevector_simulator")
statevector = execute(circuit, backend).result().get_statevector()
probabilities = defaultdict(float)
for i, statevector_amplitude in enumerate(statevector):
i = bin(i)[2:].zfill(circuit.num_qubits)[adder.num_ancillas :]
probabilities[i] += np.real(np.abs(statevector_amplitude) ** 2)
expectations = defaultdict(float)
for x in range(2**adder.num_state_qubits):
bits = np.array(list(bin(x)[2:].zfill(adder.num_state_qubits)), dtype=int)
summation = bits.dot(adder.weights[::-1])
entry = bin(summation)[2:].zfill(adder.num_sum_qubits) + bin(x)[2:].zfill(
adder.num_state_qubits
)
expectations[entry] = 1 / 2**adder.num_state_qubits
for state, probability in probabilities.items():
self.assertAlmostEqual(probability, expectations[state])
@data([0], [1, 2, 1], [4], [1, 2, 1, 1, 4])
def test_summation(self, weights):
"""Test the weighted adder on some examples."""
adder = WeightedAdder(len(weights), weights)
self.assertSummationIsCorrect(adder)
def test_mutability(self):
"""Test the mutability of the weighted adder."""
adder = WeightedAdder()
with self.subTest(msg="missing number of state qubits"):
with self.assertRaises(AttributeError):
print(adder.draw())
with self.subTest(msg="default weights"):
adder.num_state_qubits = 3
default_weights = 3 * [1]
self.assertListEqual(adder.weights, default_weights)
with self.subTest(msg="specify weights"):
adder.weights = [3, 2, 1]
self.assertSummationIsCorrect(adder)
with self.subTest(msg="mismatching number of state qubits and weights"):
with self.assertRaises(ValueError):
adder.weights = [0, 1, 2, 3]
print(adder.draw())
with self.subTest(msg="change all attributes"):
adder.num_state_qubits = 4
adder.weights = [2, 0, 1, 1]
self.assertSummationIsCorrect(adder)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test boolean expression."""
import unittest
from os import path
from ddt import ddt, unpack, data
from qiskit.test.base import QiskitTestCase
from qiskit import execute, BasicAer
from qiskit.utils.optionals import HAS_TWEEDLEDUM
if HAS_TWEEDLEDUM:
from qiskit.circuit.classicalfunction.boolean_expression import BooleanExpression
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
@ddt
class TestBooleanExpression(QiskitTestCase):
"""Test boolean expression."""
@data(
("x | x", "1", True),
("x & x", "0", False),
("(x0 & x1 | ~x2) ^ x4", "0110", False),
("xx & xxx | ( ~z ^ zz)", "0111", True),
)
@unpack
def test_evaluate(self, expression, input_bitstring, expected):
"""Test simulate"""
expression = BooleanExpression(expression)
result = expression.simulate(input_bitstring)
self.assertEqual(result, expected)
@data(
("x", False),
("not x", True),
("(x0 & x1 | ~x2) ^ x4", True),
("xx & xxx | ( ~z ^ zz)", True),
)
@unpack
def test_synth(self, expression, expected):
"""Test synth"""
expression = BooleanExpression(expression)
expr_circ = expression.synth()
new_creg = expr_circ._create_creg(1, "c")
expr_circ.add_register(new_creg)
expr_circ.measure(expression.num_qubits - 1, new_creg)
[result] = (
execute(
expr_circ,
backend=BasicAer.get_backend("qasm_simulator"),
shots=1,
seed_simulator=14,
)
.result()
.get_counts()
.keys()
)
self.assertEqual(bool(int(result)), expected)
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
class TestBooleanExpressionDIMACS(QiskitTestCase):
"""Loading from a cnf file"""
def normalize_filenames(self, filename):
"""Given a filename, returns the directory in terms of __file__."""
dirname = path.dirname(__file__)
return path.join(dirname, filename)
def test_simple(self):
"""Loads simple_v3_c2.cnf and simulate"""
filename = self.normalize_filenames("dimacs/simple_v3_c2.cnf")
simple = BooleanExpression.from_dimacs_file(filename)
self.assertEqual(simple.name, "simple_v3_c2.cnf")
self.assertEqual(simple.num_qubits, 4)
self.assertTrue(simple.simulate("101"))
def test_quinn(self):
"""Loads quinn.cnf and simulate"""
filename = self.normalize_filenames("dimacs/quinn.cnf")
simple = BooleanExpression.from_dimacs_file(filename)
self.assertEqual(simple.name, "quinn.cnf")
self.assertEqual(simple.num_qubits, 16)
self.assertFalse(simple.simulate("1010101010101010"))
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests ClassicalFunction as a gate."""
import unittest
from qiskit.test import QiskitTestCase
from qiskit import QuantumCircuit
from qiskit.circuit.library.standard_gates import XGate
from qiskit.utils.optionals import HAS_TWEEDLEDUM
if HAS_TWEEDLEDUM:
from . import examples
from qiskit.circuit.classicalfunction import classical_function as compile_classical_function
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
class TestOracleDecomposition(QiskitTestCase):
"""Tests ClassicalFunction.decomposition."""
def test_grover_oracle(self):
"""grover_oracle.decomposition"""
oracle = compile_classical_function(examples.grover_oracle)
quantum_circuit = QuantumCircuit(5)
quantum_circuit.append(oracle, [2, 1, 0, 3, 4])
expected = QuantumCircuit(5)
expected.append(XGate().control(4, ctrl_state="1010"), [2, 1, 0, 3, 4])
self.assertEqual(quantum_circuit.decompose(), expected)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Randomized tests of quantum synthesis."""
import unittest
from test.python.quantum_info.test_synthesis import CheckDecompositions
from hypothesis import given, strategies, settings
import numpy as np
from qiskit import execute
from qiskit.circuit import QuantumCircuit, QuantumRegister
from qiskit.extensions import UnitaryGate
from qiskit.providers.basicaer import UnitarySimulatorPy
from qiskit.quantum_info.random import random_unitary
from qiskit.quantum_info.synthesis.two_qubit_decompose import (
two_qubit_cnot_decompose,
TwoQubitBasisDecomposer,
Ud,
)
class TestSynthesis(CheckDecompositions):
"""Test synthesis"""
seed = strategies.integers(min_value=0, max_value=2**32 - 1)
rotation = strategies.floats(min_value=-np.pi * 10, max_value=np.pi * 10)
@given(seed)
def test_1q_random(self, seed):
"""Checks one qubit decompositions"""
unitary = random_unitary(2, seed=seed)
self.check_one_qubit_euler_angles(unitary)
self.check_one_qubit_euler_angles(unitary, "U3")
self.check_one_qubit_euler_angles(unitary, "U1X")
self.check_one_qubit_euler_angles(unitary, "PSX")
self.check_one_qubit_euler_angles(unitary, "ZSX")
self.check_one_qubit_euler_angles(unitary, "ZYZ")
self.check_one_qubit_euler_angles(unitary, "ZXZ")
self.check_one_qubit_euler_angles(unitary, "XYX")
self.check_one_qubit_euler_angles(unitary, "RR")
@settings(deadline=None)
@given(seed)
def test_2q_random(self, seed):
"""Checks two qubit decompositions"""
unitary = random_unitary(4, seed=seed)
self.check_exact_decomposition(unitary.data, two_qubit_cnot_decompose)
@given(strategies.tuples(*[seed] * 5))
def test_exact_supercontrolled_decompose_random(self, seeds):
"""Exact decomposition for random supercontrolled basis and random target"""
k1 = np.kron(random_unitary(2, seed=seeds[0]).data, random_unitary(2, seed=seeds[1]).data)
k2 = np.kron(random_unitary(2, seed=seeds[2]).data, random_unitary(2, seed=seeds[3]).data)
basis_unitary = k1 @ Ud(np.pi / 4, 0, 0) @ k2
decomposer = TwoQubitBasisDecomposer(UnitaryGate(basis_unitary))
self.check_exact_decomposition(random_unitary(4, seed=seeds[4]).data, decomposer)
@given(strategies.tuples(*[rotation] * 6), seed)
def test_cx_equivalence_0cx_random(self, rnd, seed):
"""Check random circuits with 0 cx gates locally equivalent to identity."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 0)
@given(strategies.tuples(*[rotation] * 12), seed)
def test_cx_equivalence_1cx_random(self, rnd, seed):
"""Check random circuits with 1 cx gates locally equivalent to a cx."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[6], rnd[7], rnd[8], qr[0])
qc.u(rnd[9], rnd[10], rnd[11], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 1)
@given(strategies.tuples(*[rotation] * 18), seed)
def test_cx_equivalence_2cx_random(self, rnd, seed):
"""Check random circuits with 2 cx gates locally equivalent to some circuit with 2 cx."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[6], rnd[7], rnd[8], qr[0])
qc.u(rnd[9], rnd[10], rnd[11], qr[1])
qc.cx(qr[0], qr[1])
qc.u(rnd[12], rnd[13], rnd[14], qr[0])
qc.u(rnd[15], rnd[16], rnd[17], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 2)
@given(strategies.tuples(*[rotation] * 24), seed)
def test_cx_equivalence_3cx_random(self, rnd, seed):
"""Check random circuits with 3 cx gates are outside the 0, 1, and 2 qubit regions."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[6], rnd[7], rnd[8], qr[0])
qc.u(rnd[9], rnd[10], rnd[11], qr[1])
qc.cx(qr[0], qr[1])
qc.u(rnd[12], rnd[13], rnd[14], qr[0])
qc.u(rnd[15], rnd[16], rnd[17], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[18], rnd[19], rnd[20], qr[0])
qc.u(rnd[21], rnd[22], rnd[23], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 3)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests LogicNetwork.Tweedledum2Qiskit converter."""
import unittest
from qiskit.utils.optionals import HAS_TWEEDLEDUM
from qiskit.test import QiskitTestCase
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import XGate
if HAS_TWEEDLEDUM:
# pylint: disable=import-error
from qiskit.circuit.classicalfunction.utils import tweedledum2qiskit
from tweedledum.ir import Circuit
from tweedledum.operators import X
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
class TestTweedledum2Qiskit(QiskitTestCase):
"""Tests qiskit.transpiler.classicalfunction.utils.tweedledum2qiskit function."""
def test_x(self):
"""Single uncontrolled X"""
tweedledum_circuit = Circuit()
tweedledum_circuit.apply_operator(X(), [tweedledum_circuit.create_qubit()])
circuit = tweedledum2qiskit(tweedledum_circuit)
expected = QuantumCircuit(1)
expected.x(0)
self.assertEqual(circuit, expected)
def test_cx_0_1(self):
"""CX(0, 1)"""
tweedledum_circuit = Circuit()
qubits = []
qubits.append(tweedledum_circuit.create_qubit())
qubits.append(tweedledum_circuit.create_qubit())
tweedledum_circuit.apply_operator(X(), [qubits[0], qubits[1]])
circuit = tweedledum2qiskit(tweedledum_circuit)
expected = QuantumCircuit(2)
expected.append(XGate().control(1, ctrl_state="1"), [0, 1])
self.assertEqual(circuit, expected)
def test_cx_1_0(self):
"""CX(1, 0)"""
tweedledum_circuit = Circuit()
qubits = []
qubits.append(tweedledum_circuit.create_qubit())
qubits.append(tweedledum_circuit.create_qubit())
tweedledum_circuit.apply_operator(X(), [qubits[1], qubits[0]])
circuit = tweedledum2qiskit(tweedledum_circuit)
expected = QuantumCircuit(2)
expected.append(XGate().control(1, ctrl_state="1"), [1, 0])
self.assertEqual(expected, circuit)
def test_cx_qreg(self):
"""CX(0, 1) with qregs parameter"""
tweedledum_circuit = Circuit()
qubits = []
qubits.append(tweedledum_circuit.create_qubit())
qubits.append(tweedledum_circuit.create_qubit())
tweedledum_circuit.apply_operator(X(), [qubits[1], qubits[0]])
qr = QuantumRegister(2, "qr")
circuit = tweedledum2qiskit(tweedledum_circuit, qregs=[qr])
expected = QuantumCircuit(qr)
expected.append(XGate().control(1, ctrl_state="1"), [qr[1], qr[0]])
self.assertEqual(expected, circuit)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Assembler Test."""
import unittest
import io
from logging import StreamHandler, getLogger
import sys
import copy
import numpy as np
from qiskit import pulse
from qiskit.circuit import Instruction, Gate, Parameter, ParameterVector
from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.compiler.assembler import assemble
from qiskit.exceptions import QiskitError
from qiskit.pulse import Schedule, Acquire, Play
from qiskit.pulse.channels import MemorySlot, AcquireChannel, DriveChannel, MeasureChannel
from qiskit.pulse.configuration import Kernel, Discriminator
from qiskit.pulse.library import gaussian
from qiskit.qobj import QasmQobj, PulseQobj
from qiskit.qobj.utils import MeasLevel, MeasReturnType
from qiskit.pulse.macros import measure
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import (
FakeOpenPulse2Q,
FakeOpenPulse3Q,
FakeYorktown,
FakeHanoi,
)
class RxGate(Gate):
"""Used to test custom gate assembly.
Useful for testing pulse gates with parameters, as well.
Note: Parallel maps (e.g., in assemble_circuits) pickle their input,
so circuit features have to be defined top level.
"""
def __init__(self, theta):
super().__init__("rxtheta", 1, [theta])
class TestCircuitAssembler(QiskitTestCase):
"""Tests for assembling circuits to qobj."""
def setUp(self):
super().setUp()
qr = QuantumRegister(2, name="q")
cr = ClassicalRegister(2, name="c")
self.circ = QuantumCircuit(qr, cr, name="circ")
self.circ.h(qr[0])
self.circ.cx(qr[0], qr[1])
self.circ.measure(qr, cr)
self.backend = FakeYorktown()
self.backend_config = self.backend.configuration()
self.num_qubits = self.backend_config.n_qubits
# lo test values
self.default_qubit_lo_freq = [5e9 for _ in range(self.num_qubits)]
self.default_meas_lo_freq = [6.7e9 for _ in range(self.num_qubits)]
self.user_lo_config_dict = {
pulse.DriveChannel(0): 5.55e9,
pulse.MeasureChannel(0): 6.64e9,
pulse.DriveChannel(3): 4.91e9,
pulse.MeasureChannel(4): 6.1e9,
}
self.user_lo_config = pulse.LoConfig(self.user_lo_config_dict)
def test_assemble_single_circuit(self):
"""Test assembling a single circuit."""
qobj = assemble(self.circ, shots=2000, memory=True)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.shots, 2000)
self.assertEqual(qobj.config.memory, True)
self.assertEqual(len(qobj.experiments), 1)
self.assertEqual(qobj.experiments[0].instructions[1].name, "cx")
def test_assemble_multiple_circuits(self):
"""Test assembling multiple circuits, all should have the same config."""
qr0 = QuantumRegister(2, name="q0")
qc0 = ClassicalRegister(2, name="c0")
circ0 = QuantumCircuit(qr0, qc0, name="circ0")
circ0.h(qr0[0])
circ0.cx(qr0[0], qr0[1])
circ0.measure(qr0, qc0)
qr1 = QuantumRegister(3, name="q1")
qc1 = ClassicalRegister(3, name="c1")
circ1 = QuantumCircuit(qr1, qc1, name="circ0")
circ1.h(qr1[0])
circ1.cx(qr1[0], qr1[1])
circ1.cx(qr1[0], qr1[2])
circ1.measure(qr1, qc1)
qobj = assemble([circ0, circ1], shots=100, memory=False, seed_simulator=6)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.seed_simulator, 6)
self.assertEqual(len(qobj.experiments), 2)
self.assertEqual(qobj.experiments[1].config.n_qubits, 3)
self.assertEqual(len(qobj.experiments), 2)
self.assertEqual(len(qobj.experiments[1].instructions), 6)
def test_assemble_no_run_config(self):
"""Test assembling with no run_config, relying on default."""
qobj = assemble(self.circ)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.shots, 1024)
def test_shots_greater_than_max_shots(self):
"""Test assembling with shots greater than max shots"""
self.assertRaises(QiskitError, assemble, self.backend, shots=1024000)
def test_shots_not_of_type_int(self):
"""Test assembling with shots having type other than int"""
self.assertRaises(QiskitError, assemble, self.backend, shots="1024")
def test_shots_of_type_numpy_int64(self):
"""Test assembling with shots having type numpy.int64"""
qobj = assemble(self.circ, shots=np.int64(2048))
self.assertEqual(qobj.config.shots, 2048)
def test_default_shots_greater_than_max_shots(self):
"""Test assembling with default shots greater than max shots"""
self.backend_config.max_shots = 5
qobj = assemble(self.circ, self.backend)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.shots, 5)
def test_assemble_initialize(self):
"""Test assembling a circuit with an initialize."""
q = QuantumRegister(2, name="q")
circ = QuantumCircuit(q, name="circ")
circ.initialize([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)], q[:])
qobj = assemble(circ)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.experiments[0].instructions[0].name, "initialize")
np.testing.assert_almost_equal(
qobj.experiments[0].instructions[0].params, [0.7071067811865, 0, 0, 0.707106781186]
)
def test_assemble_meas_level_meas_return(self):
"""Test assembling a circuit schedule with `meas_level`."""
qobj = assemble(self.circ, meas_level=1, meas_return="single")
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.meas_level, 1)
self.assertEqual(qobj.config.meas_return, "single")
# no meas_level set
qobj = assemble(self.circ)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.meas_level, 2)
self.assertEqual(hasattr(qobj.config, "meas_return"), False)
def test_assemble_backend_rep_delays(self):
"""Check that rep_delay is properly set from backend values."""
rep_delay_range = [2.5e-3, 4.5e-3] # sec
default_rep_delay = 3.0e-3
setattr(self.backend_config, "rep_delay_range", rep_delay_range)
setattr(self.backend_config, "default_rep_delay", default_rep_delay)
# dynamic rep rates off
setattr(self.backend_config, "dynamic_reprate_enabled", False)
qobj = assemble(self.circ, self.backend)
self.assertEqual(hasattr(qobj.config, "rep_delay"), False)
# dynamic rep rates on
setattr(self.backend_config, "dynamic_reprate_enabled", True)
qobj = assemble(self.circ, self.backend)
self.assertEqual(qobj.config.rep_delay, default_rep_delay * 1e6)
def test_assemble_user_rep_time_delay(self):
"""Check that user runtime config rep_delay works."""
# set custom rep_delay in runtime config
rep_delay = 2.2e-6
rep_delay_range = [0, 3e-6] # sec
setattr(self.backend_config, "rep_delay_range", rep_delay_range)
# dynamic rep rates off (no default so shouldn't be in qobj config)
setattr(self.backend_config, "dynamic_reprate_enabled", False)
qobj = assemble(self.circ, self.backend, rep_delay=rep_delay)
self.assertEqual(hasattr(qobj.config, "rep_delay"), False)
# turn on dynamic rep rates, rep_delay should be set
setattr(self.backend_config, "dynamic_reprate_enabled", True)
qobj = assemble(self.circ, self.backend, rep_delay=rep_delay)
self.assertEqual(qobj.config.rep_delay, 2.2)
# test ``rep_delay=0``
qobj = assemble(self.circ, self.backend, rep_delay=0)
self.assertEqual(qobj.config.rep_delay, 0)
# use ``rep_delay`` outside of ``rep_delay_range```
rep_delay_large = 5.0e-6
with self.assertRaises(QiskitError):
assemble(self.circ, self.backend, rep_delay=rep_delay_large)
def test_assemble_opaque_inst(self):
"""Test opaque instruction is assembled as-is"""
opaque_inst = Instruction(name="my_inst", num_qubits=4, num_clbits=2, params=[0.5, 0.4])
q = QuantumRegister(6, name="q")
c = ClassicalRegister(4, name="c")
circ = QuantumCircuit(q, c, name="circ")
circ.append(opaque_inst, [q[0], q[2], q[5], q[3]], [c[3], c[0]])
qobj = assemble(circ)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(len(qobj.experiments[0].instructions), 1)
self.assertEqual(qobj.experiments[0].instructions[0].name, "my_inst")
self.assertEqual(qobj.experiments[0].instructions[0].qubits, [0, 2, 5, 3])
self.assertEqual(qobj.experiments[0].instructions[0].memory, [3, 0])
self.assertEqual(qobj.experiments[0].instructions[0].params, [0.5, 0.4])
def test_assemble_unroll_parametervector(self):
"""Verfiy that assemble unrolls parametervectors ref #5467"""
pv1 = ParameterVector("pv1", 3)
pv2 = ParameterVector("pv2", 3)
qc = QuantumCircuit(2, 2)
for i in range(3):
qc.rx(pv1[i], 0)
qc.ry(pv2[i], 1)
qc.barrier()
qc.measure([0, 1], [0, 1])
qc.bind_parameters({pv1: [0.1, 0.2, 0.3], pv2: [0.4, 0.5, 0.6]})
qobj = assemble(qc, parameter_binds=[{pv1: [0.1, 0.2, 0.3], pv2: [0.4, 0.5, 0.6]}])
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.experiments[0].instructions[0].params[0], 0.100000000000000)
self.assertEqual(qobj.experiments[0].instructions[1].params[0], 0.400000000000000)
self.assertEqual(qobj.experiments[0].instructions[2].params[0], 0.200000000000000)
self.assertEqual(qobj.experiments[0].instructions[3].params[0], 0.500000000000000)
self.assertEqual(qobj.experiments[0].instructions[4].params[0], 0.300000000000000)
self.assertEqual(qobj.experiments[0].instructions[5].params[0], 0.600000000000000)
def test_measure_to_registers_when_conditionals(self):
"""Verify assemble_circuits maps all measure ops on to a register slot
for a circuit containing conditionals."""
qr = QuantumRegister(2)
cr1 = ClassicalRegister(1)
cr2 = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr1, cr2)
qc.measure(qr[0], cr1) # Measure not required for a later conditional
qc.measure(qr[1], cr2[1]) # Measure required for a later conditional
qc.h(qr[1]).c_if(cr2, 3)
qobj = assemble(qc)
first_measure, second_measure = (
op for op in qobj.experiments[0].instructions if op.name == "measure"
)
self.assertTrue(hasattr(first_measure, "register"))
self.assertEqual(first_measure.register, first_measure.memory)
self.assertTrue(hasattr(second_measure, "register"))
self.assertEqual(second_measure.register, second_measure.memory)
def test_convert_to_bfunc_plus_conditional(self):
"""Verify assemble_circuits converts conditionals from QASM to Qobj."""
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0]).c_if(cr, 1)
qobj = assemble(qc)
bfunc_op, h_op = qobj.experiments[0].instructions
self.assertEqual(bfunc_op.name, "bfunc")
self.assertEqual(bfunc_op.mask, "0x1")
self.assertEqual(bfunc_op.val, "0x1")
self.assertEqual(bfunc_op.relation, "==")
self.assertTrue(hasattr(h_op, "conditional"))
self.assertEqual(bfunc_op.register, h_op.conditional)
def test_convert_to_bfunc_plus_conditional_onebit(self):
"""Verify assemble_circuits converts single bit conditionals from QASM to Qobj."""
qr = QuantumRegister(1)
cr = ClassicalRegister(3)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0]).c_if(cr[2], 1)
qobj = assemble(qc)
inst_set = qobj.experiments[0].instructions
[bfunc_op, h_op] = inst_set
self.assertEqual(len(inst_set), 2)
self.assertEqual(bfunc_op.name, "bfunc")
self.assertEqual(bfunc_op.mask, "0x4")
self.assertEqual(bfunc_op.val, "0x4")
self.assertEqual(bfunc_op.relation, "==")
self.assertTrue(hasattr(h_op, "conditional"))
self.assertEqual(bfunc_op.register, h_op.conditional)
def test_resize_value_to_register(self):
"""Verify assemble_circuits converts the value provided on the classical
creg to its mapped location on the device register."""
qr = QuantumRegister(1)
cr1 = ClassicalRegister(2)
cr2 = ClassicalRegister(2)
cr3 = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr1, cr2, cr3)
qc.h(qr[0]).c_if(cr2, 2)
qobj = assemble(qc)
bfunc_op, h_op = qobj.experiments[0].instructions
self.assertEqual(bfunc_op.name, "bfunc")
self.assertEqual(bfunc_op.mask, "0xC")
self.assertEqual(bfunc_op.val, "0x8")
self.assertEqual(bfunc_op.relation, "==")
self.assertTrue(hasattr(h_op, "conditional"))
self.assertEqual(bfunc_op.register, h_op.conditional)
def test_assemble_circuits_raises_for_bind_circuit_mismatch(self):
"""Verify assemble_circuits raises error for parameterized circuits without matching
binds."""
qr = QuantumRegister(2)
x = Parameter("x")
y = Parameter("y")
full_bound_circ = QuantumCircuit(qr)
full_param_circ = QuantumCircuit(qr)
partial_param_circ = QuantumCircuit(qr)
partial_param_circ.p(x, qr[0])
full_param_circ.p(x, qr[0])
full_param_circ.p(y, qr[1])
partial_bind_args = {"parameter_binds": [{x: 1}, {x: 0}]}
full_bind_args = {"parameter_binds": [{x: 1, y: 1}, {x: 0, y: 0}]}
inconsistent_bind_args = {"parameter_binds": [{x: 1}, {x: 0, y: 0}]}
# Raise when parameters passed for non-parametric circuit
self.assertRaises(QiskitError, assemble, full_bound_circ, **partial_bind_args)
# Raise when no parameters passed for parametric circuit
self.assertRaises(QiskitError, assemble, partial_param_circ)
self.assertRaises(QiskitError, assemble, full_param_circ)
# Raise when circuit has more parameters than run_config
self.assertRaises(QiskitError, assemble, full_param_circ, **partial_bind_args)
# Raise when not all circuits have all parameters
self.assertRaises(
QiskitError, assemble, [full_param_circ, partial_param_circ], **full_bind_args
)
# Raise when not all binds have all circuit params
self.assertRaises(QiskitError, assemble, full_param_circ, **inconsistent_bind_args)
def test_assemble_circuits_rases_for_bind_mismatch_over_expressions(self):
"""Verify assemble_circuits raises for invalid binds for circuit including
ParameterExpressions.
"""
qr = QuantumRegister(1)
x = Parameter("x")
y = Parameter("y")
expr_circ = QuantumCircuit(qr)
expr_circ.p(x + y, qr[0])
partial_bind_args = {"parameter_binds": [{x: 1}, {x: 0}]}
# Raise when no parameters passed for parametric circuit
self.assertRaises(QiskitError, assemble, expr_circ)
# Raise when circuit has more parameters than run_config
self.assertRaises(QiskitError, assemble, expr_circ, **partial_bind_args)
def test_assemble_circuits_binds_parameters(self):
"""Verify assemble_circuits applies parameter bindings and output circuits are bound."""
qr = QuantumRegister(1)
qc1 = QuantumCircuit(qr)
qc2 = QuantumCircuit(qr)
qc3 = QuantumCircuit(qr)
x = Parameter("x")
y = Parameter("y")
sum_ = x + y
product_ = x * y
qc1.u(x, y, 0, qr[0])
qc2.rz(x, qr[0])
qc2.rz(y, qr[0])
qc3.u(sum_, product_, 0, qr[0])
bind_args = {"parameter_binds": [{x: 0, y: 0}, {x: 1, y: 0}, {x: 1, y: 1}]}
qobj = assemble([qc1, qc2, qc3], **bind_args)
self.assertEqual(len(qobj.experiments), 9)
self.assertEqual(
[len(expt.instructions) for expt in qobj.experiments], [1, 1, 1, 2, 2, 2, 1, 1, 1]
)
def _qobj_inst_params(expt_no, inst_no):
expt = qobj.experiments[expt_no]
inst = expt.instructions[inst_no]
return [float(p) for p in inst.params]
self.assertEqual(_qobj_inst_params(0, 0), [0, 0, 0])
self.assertEqual(_qobj_inst_params(1, 0), [1, 0, 0])
self.assertEqual(_qobj_inst_params(2, 0), [1, 1, 0])
self.assertEqual(_qobj_inst_params(3, 0), [0])
self.assertEqual(_qobj_inst_params(3, 1), [0])
self.assertEqual(_qobj_inst_params(4, 0), [1])
self.assertEqual(_qobj_inst_params(4, 1), [0])
self.assertEqual(_qobj_inst_params(5, 0), [1])
self.assertEqual(_qobj_inst_params(5, 1), [1])
self.assertEqual(_qobj_inst_params(6, 0), [0, 0, 0])
self.assertEqual(_qobj_inst_params(7, 0), [1, 0, 0])
self.assertEqual(_qobj_inst_params(8, 0), [2, 1, 0])
def test_init_qubits_default(self):
"""Check that the init_qubits=None assemble option is passed on to the qobj."""
qobj = assemble(self.circ)
self.assertEqual(qobj.config.init_qubits, True)
def test_init_qubits_true(self):
"""Check that the init_qubits=True assemble option is passed on to the qobj."""
qobj = assemble(self.circ, init_qubits=True)
self.assertEqual(qobj.config.init_qubits, True)
def test_init_qubits_false(self):
"""Check that the init_qubits=False assemble option is passed on to the qobj."""
qobj = assemble(self.circ, init_qubits=False)
self.assertEqual(qobj.config.init_qubits, False)
def test_circuit_with_global_phase(self):
"""Test that global phase for a circuit is handled correctly."""
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.measure_all()
circ.global_phase = 0.3 * np.pi
qobj = assemble([circ, self.circ])
self.assertEqual(getattr(qobj.experiments[1].header, "global_phase"), 0)
self.assertEqual(getattr(qobj.experiments[0].header, "global_phase"), 0.3 * np.pi)
def test_circuit_global_phase_gate_definitions(self):
"""Test circuit with global phase on gate definitions."""
class TestGate(Gate):
"""dummy gate"""
def __init__(self):
super().__init__("test_gate", 1, [])
def _define(self):
circ_def = QuantumCircuit(1)
circ_def.x(0)
circ_def.global_phase = np.pi
self._definition = circ_def
gate = TestGate()
circ = QuantumCircuit(1)
circ.append(gate, [0])
qobj = assemble([circ])
self.assertEqual(getattr(qobj.experiments[0].header, "global_phase"), 0)
circ.global_phase = np.pi / 2
qobj = assemble([circ])
self.assertEqual(getattr(qobj.experiments[0].header, "global_phase"), np.pi / 2)
def test_pulse_gates_single_circ(self):
"""Test that we can add calibrations to circuits."""
theta = Parameter("theta")
circ = QuantumCircuit(2)
circ.h(0)
circ.append(RxGate(3.14), [0])
circ.append(RxGate(theta), [1])
circ = circ.assign_parameters({theta: 3.14})
with pulse.build() as custom_h_schedule:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
with pulse.build() as x180:
pulse.play(pulse.library.Gaussian(50, 0.2, 5), pulse.DriveChannel(1))
circ.add_calibration("h", [0], custom_h_schedule)
circ.add_calibration(RxGate(3.14), [0], x180)
circ.add_calibration(RxGate(3.14), [1], x180)
qobj = assemble(circ, FakeOpenPulse2Q())
# Only one circuit, so everything is stored at the job level
cals = qobj.config.calibrations
lib = qobj.config.pulse_library
self.assertFalse(hasattr(qobj.experiments[0].config, "calibrations"))
self.assertEqual([gate.name == "rxtheta" for gate in cals.gates].count(True), 2)
self.assertEqual([gate.name == "h" for gate in cals.gates].count(True), 1)
self.assertEqual(len(lib), 2)
self.assertTrue(all(len(item.samples) == 50 for item in lib))
def test_pulse_gates_with_parameteric_pulses(self):
"""Test that pulse gates are assembled efficiently for backends that enable
parametric pulses.
"""
with pulse.build() as custom_h_schedule:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
circ = QuantumCircuit(2)
circ.h(0)
circ.add_calibration("h", [0], custom_h_schedule)
backend = FakeOpenPulse2Q()
backend.configuration().parametric_pulses = ["drag"]
qobj = assemble(circ, backend)
self.assertFalse(hasattr(qobj.config, "pulse_library"))
self.assertTrue(hasattr(qobj.config, "calibrations"))
def test_pulse_gates_multiple_circuits(self):
"""Test one circuit with cals and another without."""
with pulse.build() as dummy_sched:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
circ = QuantumCircuit(2)
circ.h(0)
circ.append(RxGate(3.14), [1])
circ.add_calibration("h", [0], dummy_sched)
circ.add_calibration(RxGate(3.14), [1], dummy_sched)
circ2 = QuantumCircuit(2)
circ2.h(0)
qobj = assemble([circ, circ2], FakeOpenPulse2Q())
self.assertEqual(len(qobj.config.pulse_library), 1)
self.assertEqual(len(qobj.experiments[0].config.calibrations.gates), 2)
self.assertFalse(hasattr(qobj.config, "calibrations"))
self.assertFalse(hasattr(qobj.experiments[1].config, "calibrations"))
def test_pulse_gates_common_cals(self):
"""Test that common calibrations are added at the top level."""
with pulse.build() as dummy_sched:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
circ = QuantumCircuit(2)
circ.h(0)
circ.append(RxGate(3.14), [1])
circ.add_calibration("h", [0], dummy_sched)
circ.add_calibration(RxGate(3.14), [1], dummy_sched)
circ2 = QuantumCircuit(2)
circ2.h(0)
circ2.add_calibration(RxGate(3.14), [1], dummy_sched)
qobj = assemble([circ, circ2], FakeOpenPulse2Q())
# Identical pulses are only added once
self.assertEqual(len(qobj.config.pulse_library), 1)
# Identical calibrations are only added once
self.assertEqual(qobj.config.calibrations.gates[0].name, "rxtheta")
self.assertEqual(qobj.config.calibrations.gates[0].params, [3.14])
self.assertEqual(qobj.config.calibrations.gates[0].qubits, [1])
self.assertEqual(len(qobj.experiments[0].config.calibrations.gates), 1)
self.assertFalse(hasattr(qobj.experiments[1].config, "calibrations"))
def test_assemble_adds_circuit_metadata_to_experiment_header(self):
"""Verify that any circuit metadata is added to the exeriment header."""
circ = QuantumCircuit(2, metadata={"experiment_type": "gst", "execution_number": "1234"})
qobj = assemble(circ, shots=100, memory=False, seed_simulator=6)
self.assertEqual(
qobj.experiments[0].header.metadata,
{"experiment_type": "gst", "execution_number": "1234"},
)
def test_pulse_gates_delay_only(self):
"""Test that a single delay gate is translated to an instruction."""
circ = QuantumCircuit(2)
circ.append(Gate("test", 1, []), [0])
test_sched = pulse.Delay(64, DriveChannel(0)) + pulse.Delay(160, DriveChannel(0))
circ.add_calibration("test", [0], test_sched)
qobj = assemble(circ, FakeOpenPulse2Q())
self.assertEqual(len(qobj.config.calibrations.gates[0].instructions), 2)
self.assertEqual(
qobj.config.calibrations.gates[0].instructions[1].to_dict(),
{"name": "delay", "t0": 64, "ch": "d0", "duration": 160},
)
def test_job_qubit_meas_los_no_range(self):
"""Test that adding job qubit/meas lo freq lists are assembled into the qobj.config, w/ out
any lo range."""
qobj = assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
)
# convert to ghz
qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq]
meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq]
self.assertEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz)
self.assertEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz)
def test_job_lo_errors(self):
"""Test that job lo's are checked against the lo ranges and that errors are thrown if either
quantity has an incorrect length or type."""
qubit_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_qubit_lo_freq]
meas_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_meas_lo_freq]
# lo range not a nested list
with self.assertRaises(QiskitError):
assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=[4.995e9 for i in range(self.num_qubits)],
meas_lo_range=meas_lo_range,
)
# qubit lo range inner list not 2d
with self.assertRaises(QiskitError):
assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=qubit_lo_range,
meas_lo_range=[[6.695e9] for i in range(self.num_qubits)],
)
# meas lo range inner list not 2d
with self.assertRaises(QiskitError):
assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=qubit_lo_range,
meas_lo_range=[[6.695e9] for i in range(self.num_qubits)],
)
# qubit lo out of range
with self.assertRaises(QiskitError):
assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=[[5.005e9, 5.010e9] for i in range(self.num_qubits)],
meas_lo_range=meas_lo_range,
)
# meas lo out of range
with self.assertRaises(QiskitError):
assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=qubit_lo_range,
meas_lo_range=[[6.705e9, 6.710e9] for i in range(self.num_qubits)],
)
def test_job_qubit_meas_los_w_range(self):
"""Test that adding job qubit/meas lo freq lists are assembled into the qobj.config, w/ lo
ranges input. Verify that lo ranges do not enter into the config."""
qubit_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_qubit_lo_freq]
meas_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_meas_lo_freq]
qobj = assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=qubit_lo_range,
meas_lo_range=meas_lo_range,
)
# convert to ghz
qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq]
meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq]
self.assertEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz)
self.assertEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz)
self.assertNotIn("qubit_lo_range", qobj.config.to_dict())
self.assertNotIn("meas_lo_range", qobj.config.to_dict())
def test_assemble_single_circ_single_lo_config(self):
"""Test assembling a single circuit, with a single experiment level lo config."""
qobj = assemble(
self.circ,
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=self.user_lo_config,
)
self.assertListEqual(qobj.config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5])
self.assertListEqual(qobj.config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1])
self.assertEqual(len(qobj.experiments), 1)
def test_assemble_single_circ_single_lo_config_dict(self):
"""Test assembling a single circuit, with a single experiment level lo config supplied as
dictionary."""
qobj = assemble(
self.circ,
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=self.user_lo_config_dict,
)
self.assertListEqual(qobj.config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5])
self.assertListEqual(qobj.config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1])
self.assertEqual(len(qobj.experiments), 1)
def test_assemble_single_circ_multi_lo_config(self):
"""Test assembling a single circuit, with multiple experiment level lo configs (frequency
sweep).
"""
user_lo_config_dict2 = {
pulse.DriveChannel(1): 5.55e9,
pulse.MeasureChannel(1): 6.64e9,
pulse.DriveChannel(4): 4.91e9,
pulse.MeasureChannel(3): 6.1e9,
}
user_lo_config2 = pulse.LoConfig(user_lo_config_dict2)
qobj = assemble(
self.circ,
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, user_lo_config2],
)
qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq]
meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq]
self.assertListEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz)
self.assertListEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz)
self.assertEqual(len(qobj.experiments), 2)
# experiment 0 los
self.assertEqual(qobj.experiments[0].config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5])
self.assertEqual(qobj.experiments[0].config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1])
# experiment 1 los
self.assertEqual(qobj.experiments[1].config.qubit_lo_freq, [5, 5.55, 5, 5, 4.91])
self.assertEqual(qobj.experiments[1].config.meas_lo_freq, [6.7, 6.64, 6.7, 6.1, 6.7])
def test_assemble_multi_circ_multi_lo_config(self):
"""Test assembling circuits, with the same number of experiment level lo configs (n:n
setup)."""
user_lo_config_dict2 = {
pulse.DriveChannel(1): 5.55e9,
pulse.MeasureChannel(1): 6.64e9,
pulse.DriveChannel(4): 4.91e9,
pulse.MeasureChannel(3): 6.1e9,
}
user_lo_config2 = pulse.LoConfig(user_lo_config_dict2)
qobj = assemble(
[self.circ, self.circ],
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, user_lo_config2],
)
qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq]
meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq]
self.assertListEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz)
self.assertListEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz)
self.assertEqual(len(qobj.experiments), 2)
# experiment 0 los
self.assertEqual(qobj.experiments[0].config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5])
self.assertEqual(qobj.experiments[0].config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1])
# experiment 1 los
self.assertEqual(qobj.experiments[1].config.qubit_lo_freq, [5, 5.55, 5, 5, 4.91])
self.assertEqual(qobj.experiments[1].config.meas_lo_freq, [6.7, 6.64, 6.7, 6.1, 6.7])
def test_assemble_multi_circ_single_lo_config(self):
"""Test assembling multiple circuits, with a single experiment level lo config (should
override job level)."""
qobj = assemble(
[self.circ, self.circ],
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=self.user_lo_config,
)
self.assertListEqual(qobj.config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5])
self.assertListEqual(qobj.config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1])
self.assertEqual(len(qobj.experiments), 2)
def test_assemble_multi_circ_wrong_number_of_multi_lo_configs(self):
"""Test assembling circuits, with a different number of experiment level lo configs (n:m
setup).
"""
with self.assertRaises(QiskitError):
assemble(
[self.circ, self.circ, self.circ],
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, self.user_lo_config],
)
def test_assemble_circ_lo_config_errors(self):
"""Test that lo config errors are raised properly if experiment level los are provided and
some are missing or if default values are not provided. Also check that experiment level lo
range is validated."""
# no defaults, but have drive/meas experiment level los for each qubit (no error)
full_lo_config_dict = {
pulse.DriveChannel(0): 4.85e9,
pulse.DriveChannel(1): 4.9e9,
pulse.DriveChannel(2): 4.95e9,
pulse.DriveChannel(3): 5e9,
pulse.DriveChannel(4): 5.05e9,
pulse.MeasureChannel(0): 6.8e9,
pulse.MeasureChannel(1): 6.85e9,
pulse.MeasureChannel(2): 6.9e9,
pulse.MeasureChannel(3): 6.95e9,
pulse.MeasureChannel(4): 7e9,
}
qobj = assemble(self.circ, self.backend, schedule_los=full_lo_config_dict)
self.assertListEqual(qobj.config.qubit_lo_freq, [4.85, 4.9, 4.95, 5, 5.05])
self.assertListEqual(qobj.config.meas_lo_freq, [6.8, 6.85, 6.9, 6.95, 7])
self.assertEqual(len(qobj.experiments), 1)
# no defaults and missing experiment level drive lo raises
missing_drive_lo_config_dict = copy.deepcopy(full_lo_config_dict)
missing_drive_lo_config_dict.pop(pulse.DriveChannel(0))
with self.assertRaises(QiskitError):
qobj = assemble(self.circ, self.backend, schedule_los=missing_drive_lo_config_dict)
# no defaults and missing experiment level meas lo raises
missing_meas_lo_config_dict = copy.deepcopy(full_lo_config_dict)
missing_meas_lo_config_dict.pop(pulse.MeasureChannel(0))
with self.assertRaises(QiskitError):
qobj = assemble(self.circ, self.backend, schedule_los=missing_meas_lo_config_dict)
# verify lo ranges are checked at experiment level
lo_values = list(full_lo_config_dict.values())
qubit_lo_range = [[freq - 5e6, freq + 5e6] for freq in lo_values[:5]]
meas_lo_range = [[freq - 5e6, freq + 5e6] for freq in lo_values[5:]]
# out of range drive lo
full_lo_config_dict[pulse.DriveChannel(0)] -= 5.5e6
with self.assertRaises(QiskitError):
qobj = assemble(
self.circ,
self.backend,
qubit_lo_range=qubit_lo_range,
schedule_los=full_lo_config_dict,
)
full_lo_config_dict[pulse.DriveChannel(0)] += 5.5e6 # reset drive value
# out of range meas lo
full_lo_config_dict[pulse.MeasureChannel(0)] += 5.5e6
with self.assertRaises(QiskitError):
qobj = assemble(
self.circ,
self.backend,
meas_lo_range=meas_lo_range,
schedule_los=full_lo_config_dict,
)
class TestPulseAssembler(QiskitTestCase):
"""Tests for assembling schedules to qobj."""
def setUp(self):
super().setUp()
self.backend = FakeOpenPulse2Q()
self.backend_config = self.backend.configuration()
test_pulse = pulse.Waveform(
samples=np.array([0.02739068, 0.05, 0.05, 0.05, 0.02739068], dtype=np.complex128),
name="pulse0",
)
self.schedule = pulse.Schedule(name="fake_experiment")
self.schedule = self.schedule.insert(0, Play(test_pulse, self.backend_config.drive(0)))
for i in range(self.backend_config.n_qubits):
self.schedule = self.schedule.insert(
5, Acquire(5, self.backend_config.acquire(i), MemorySlot(i))
)
self.user_lo_config_dict = {self.backend_config.drive(0): 4.91e9}
self.user_lo_config = pulse.LoConfig(self.user_lo_config_dict)
self.default_qubit_lo_freq = [4.9e9, 5.0e9]
self.default_meas_lo_freq = [6.5e9, 6.6e9]
self.config = {"meas_level": 1, "memory_slot_size": 100, "meas_return": "avg"}
self.header = {"backend_name": "FakeOpenPulse2Q", "backend_version": "0.0.0"}
def test_assemble_adds_schedule_metadata_to_experiment_header(self):
"""Verify that any circuit metadata is added to the exeriment header."""
self.schedule.metadata = {"experiment_type": "gst", "execution_number": "1234"}
qobj = assemble(
self.schedule,
shots=100,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
)
self.assertEqual(
qobj.experiments[0].header.metadata,
{"experiment_type": "gst", "execution_number": "1234"},
)
def test_assemble_sample_pulse(self):
"""Test that the pulse lib and qobj instruction can be paired up."""
schedule = pulse.Schedule()
schedule += pulse.Play(
pulse.Waveform([0.1] * 16, name="test0"), pulse.DriveChannel(0), name="test1"
)
schedule += pulse.Play(
pulse.Waveform([0.1] * 16, name="test1"), pulse.DriveChannel(0), name="test2"
)
schedule += pulse.Play(
pulse.Waveform([0.5] * 16, name="test0"), pulse.DriveChannel(0), name="test1"
)
qobj = assemble(
schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
**self.config,
)
test_dict = qobj.to_dict()
experiment = test_dict["experiments"][0]
inst0_name = experiment["instructions"][0]["name"]
inst1_name = experiment["instructions"][1]["name"]
inst2_name = experiment["instructions"][2]["name"]
pulses = {}
for item in test_dict["config"]["pulse_library"]:
pulses[item["name"]] = item["samples"]
self.assertTrue(all(name in pulses for name in [inst0_name, inst1_name, inst2_name]))
# Their pulses are the same
self.assertEqual(inst0_name, inst1_name)
self.assertTrue(np.allclose(pulses[inst0_name], [0.1] * 16))
self.assertTrue(np.allclose(pulses[inst2_name], [0.5] * 16))
def test_assemble_single_schedule_without_lo_config(self):
"""Test assembling a single schedule, no lo config."""
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0])
self.assertEqual(len(test_dict["experiments"]), 1)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
def test_assemble_multi_schedules_without_lo_config(self):
"""Test assembling schedules, no lo config."""
qobj = assemble(
[self.schedule, self.schedule],
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0])
self.assertEqual(len(test_dict["experiments"]), 2)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
def test_assemble_single_schedule_with_lo_config(self):
"""Test assembling a single schedule, with a single lo config."""
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=self.user_lo_config,
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.91, 5.0])
self.assertEqual(len(test_dict["experiments"]), 1)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
def test_assemble_single_schedule_with_lo_config_dict(self):
"""Test assembling a single schedule, with a single lo config supplied as dictionary."""
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=self.user_lo_config_dict,
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.91, 5.0])
self.assertEqual(len(test_dict["experiments"]), 1)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
def test_assemble_single_schedule_with_multi_lo_configs(self):
"""Test assembling a single schedule, with multiple lo configs (frequency sweep)."""
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, self.user_lo_config],
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0])
self.assertEqual(len(test_dict["experiments"]), 2)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
self.assertDictEqual(test_dict["experiments"][0]["config"], {"qubit_lo_freq": [4.91, 5.0]})
def test_assemble_multi_schedules_with_multi_lo_configs(self):
"""Test assembling schedules, with the same number of lo configs (n:n setup)."""
qobj = assemble(
[self.schedule, self.schedule],
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, self.user_lo_config],
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0])
self.assertEqual(len(test_dict["experiments"]), 2)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
self.assertDictEqual(test_dict["experiments"][0]["config"], {"qubit_lo_freq": [4.91, 5.0]})
def test_assemble_multi_schedules_with_wrong_number_of_multi_lo_configs(self):
"""Test assembling schedules, with a different number of lo configs (n:m setup)."""
with self.assertRaises(QiskitError):
assemble(
[self.schedule, self.schedule, self.schedule],
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, self.user_lo_config],
**self.config,
)
def test_assemble_meas_map(self):
"""Test assembling a single schedule, no lo config."""
schedule = Schedule(name="fake_experiment")
schedule = schedule.insert(5, Acquire(5, AcquireChannel(0), MemorySlot(0)))
schedule = schedule.insert(5, Acquire(5, AcquireChannel(1), MemorySlot(1)))
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1]],
)
self.assertIsInstance(qobj, PulseQobj)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1, 2]],
)
self.assertIsInstance(qobj, PulseQobj)
def test_assemble_memory_slots(self):
"""Test assembling a schedule and inferring number of memoryslots."""
n_memoryslots = 10
# single acquisition
schedule = Acquire(
5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslots - 1)
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1]],
)
self.assertEqual(qobj.config.memory_slots, n_memoryslots)
# this should be in experimental header as well
self.assertEqual(qobj.experiments[0].header.memory_slots, n_memoryslots)
# multiple acquisition
schedule = Acquire(
5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslots - 1)
)
schedule = schedule.insert(
10,
Acquire(
5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslots - 1)
),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1]],
)
self.assertEqual(qobj.config.memory_slots, n_memoryslots)
# this should be in experimental header as well
self.assertEqual(qobj.experiments[0].header.memory_slots, n_memoryslots)
def test_assemble_memory_slots_for_schedules(self):
"""Test assembling schedules with different memory slots."""
n_memoryslots = [10, 5, 7]
schedules = []
for n_memoryslot in n_memoryslots:
schedule = Acquire(
5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslot - 1)
)
schedules.append(schedule)
qobj = assemble(
schedules,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1]],
)
self.assertEqual(qobj.config.memory_slots, max(n_memoryslots))
self.assertEqual(qobj.experiments[0].header.memory_slots, n_memoryslots[0])
self.assertEqual(qobj.experiments[1].header.memory_slots, n_memoryslots[1])
self.assertEqual(qobj.experiments[2].header.memory_slots, n_memoryslots[2])
def test_pulse_name_conflicts(self):
"""Test that pulse name conflicts can be resolved."""
name_conflict_pulse = pulse.Waveform(
samples=np.array([0.02, 0.05, 0.05, 0.05, 0.02], dtype=np.complex128), name="pulse0"
)
self.schedule = self.schedule.insert(
1, Play(name_conflict_pulse, self.backend_config.drive(1))
)
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
**self.config,
)
self.assertNotEqual(qobj.config.pulse_library[0].name, qobj.config.pulse_library[1].name)
def test_pulse_name_conflicts_in_other_schedule(self):
"""Test two pulses with the same name in different schedule can be resolved."""
backend = FakeHanoi()
defaults = backend.defaults()
schedules = []
ch_d0 = pulse.DriveChannel(0)
for amp in (0.1, 0.2):
sched = Schedule()
sched += Play(gaussian(duration=100, amp=amp, sigma=30, name="my_pulse"), ch_d0)
sched += measure(qubits=[0], backend=backend) << 100
schedules.append(sched)
qobj = assemble(
schedules, qubit_lo_freq=defaults.qubit_freq_est, meas_lo_freq=defaults.meas_freq_est
)
# two user pulses and one measurement pulse should be contained
self.assertEqual(len(qobj.config.pulse_library), 3)
def test_assemble_with_delay(self):
"""Test that delay instruction is not ignored in assembly."""
delay_schedule = pulse.Delay(10, self.backend_config.drive(0))
delay_schedule += self.schedule
delay_qobj = assemble(delay_schedule, self.backend)
self.assertEqual(delay_qobj.experiments[0].instructions[0].name, "delay")
self.assertEqual(delay_qobj.experiments[0].instructions[0].duration, 10)
self.assertEqual(delay_qobj.experiments[0].instructions[0].t0, 0)
def test_delay_removed_on_acq_ch(self):
"""Test that delay instructions on acquire channels are skipped on assembly with times
shifted properly.
"""
delay0 = pulse.Delay(5, self.backend_config.acquire(0))
delay1 = pulse.Delay(7, self.backend_config.acquire(1))
sched0 = delay0
sched0 += self.schedule # includes ``Acquire`` instr
sched0 += delay1
sched1 = self.schedule # includes ``Acquire`` instr
sched1 += delay0
sched1 += delay1
sched2 = delay0
sched2 += delay1
sched2 += self.schedule # includes ``Acquire`` instr
delay_qobj = assemble([sched0, sched1, sched2], self.backend)
# check that no delay instrs occur on acquire channels
is_acq_delay = False
for exp in delay_qobj.experiments:
for instr in exp.instructions:
if instr.name == "delay" and "a" in instr.ch:
is_acq_delay = True
self.assertFalse(is_acq_delay)
# check that acquire instr are shifted from ``t0=5`` as needed
self.assertEqual(delay_qobj.experiments[0].instructions[1].t0, 10)
self.assertEqual(delay_qobj.experiments[0].instructions[1].name, "acquire")
self.assertEqual(delay_qobj.experiments[1].instructions[1].t0, 5)
self.assertEqual(delay_qobj.experiments[1].instructions[1].name, "acquire")
self.assertEqual(delay_qobj.experiments[2].instructions[1].t0, 12)
self.assertEqual(delay_qobj.experiments[2].instructions[1].name, "acquire")
def test_assemble_schedule_enum(self):
"""Test assembling a schedule with enum input values to assemble."""
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
meas_level=MeasLevel.CLASSIFIED,
meas_return=MeasReturnType.AVERAGE,
)
test_dict = qobj.to_dict()
self.assertEqual(test_dict["config"]["meas_return"], "avg")
self.assertEqual(test_dict["config"]["meas_level"], 2)
def test_assemble_parametric(self):
"""Test that parametric pulses can be assembled properly into a PulseQobj."""
amp = [0.5, 0.6, 1, 0.2]
angle = [np.pi / 2, 0.6, 0, 0]
sched = pulse.Schedule(name="test_parametric")
sched += Play(
pulse.Gaussian(duration=25, sigma=4, amp=amp[0], angle=angle[0]), DriveChannel(0)
)
sched += Play(
pulse.Drag(duration=25, amp=amp[1], angle=angle[1], sigma=7.8, beta=4), DriveChannel(1)
)
sched += Play(pulse.Constant(duration=25, amp=amp[2], angle=angle[2]), DriveChannel(2))
sched += (
Play(
pulse.GaussianSquare(duration=150, amp=amp[3], angle=angle[3], sigma=8, width=140),
MeasureChannel(0),
)
<< sched.duration
)
backend = FakeOpenPulse3Q()
backend.configuration().parametric_pulses = [
"gaussian",
"drag",
"gaussian_square",
"constant",
]
qobj = assemble(sched, backend)
self.assertEqual(qobj.config.pulse_library, [])
qobj_insts = qobj.experiments[0].instructions
self.assertTrue(all(inst.name == "parametric_pulse" for inst in qobj_insts))
self.assertEqual(qobj_insts[0].pulse_shape, "gaussian")
self.assertEqual(qobj_insts[1].pulse_shape, "drag")
self.assertEqual(qobj_insts[2].pulse_shape, "constant")
self.assertEqual(qobj_insts[3].pulse_shape, "gaussian_square")
self.assertDictEqual(
qobj_insts[0].parameters,
{"duration": 25, "sigma": 4, "amp": amp[0] * np.exp(1j * angle[0])},
)
self.assertDictEqual(
qobj_insts[1].parameters,
{"duration": 25, "sigma": 7.8, "amp": amp[1] * np.exp(1j * angle[1]), "beta": 4},
)
self.assertDictEqual(
qobj_insts[2].parameters, {"duration": 25, "amp": amp[2] * np.exp(1j * angle[2])}
)
self.assertDictEqual(
qobj_insts[3].parameters,
{"duration": 150, "sigma": 8, "amp": amp[3] * np.exp(1j * angle[3]), "width": 140},
)
self.assertEqual(
qobj.to_dict()["experiments"][0]["instructions"][0]["parameters"]["amp"],
amp[0] * np.exp(1j * angle[0]),
)
def test_assemble_parametric_unsupported(self):
"""Test that parametric pulses are translated to Waveform if they're not supported
by the backend during assemble time.
"""
sched = pulse.Schedule(name="test_parametric_to_sample_pulse")
sched += Play(
pulse.Drag(duration=25, amp=0.5, angle=-0.3, sigma=7.8, beta=4), DriveChannel(1)
)
sched += Play(pulse.Constant(duration=25, amp=1), DriveChannel(2))
backend = FakeOpenPulse3Q()
backend.configuration().parametric_pulses = ["something_extra"]
qobj = assemble(sched, backend)
self.assertNotEqual(qobj.config.pulse_library, [])
qobj_insts = qobj.experiments[0].instructions
self.assertFalse(hasattr(qobj_insts[0], "pulse_shape"))
def test_assemble_parametric_pulse_kwarg_with_backend_setting(self):
"""Test that parametric pulses respect the kwarg over backend"""
backend = FakeHanoi()
qc = QuantumCircuit(1, 1)
qc.x(0)
qc.measure(0, 0)
with pulse.build(backend, name="x") as x_q0:
pulse.play(pulse.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0))
qc.add_calibration("x", (0,), x_q0)
qobj = assemble(qc, backend, parametric_pulses=["gaussian"])
self.assertEqual(qobj.config.parametric_pulses, ["gaussian"])
def test_assemble_parametric_pulse_kwarg_empty_list_with_backend_setting(self):
"""Test that parametric pulses respect the kwarg as empty list over backend"""
backend = FakeHanoi()
qc = QuantumCircuit(1, 1)
qc.x(0)
qc.measure(0, 0)
with pulse.build(backend, name="x") as x_q0:
pulse.play(pulse.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0))
qc.add_calibration("x", (0,), x_q0)
qobj = assemble(qc, backend, parametric_pulses=[])
self.assertEqual(qobj.config.parametric_pulses, [])
def test_init_qubits_default(self):
"""Check that the init_qubits=None assemble option is passed on to the qobj."""
qobj = assemble(self.schedule, self.backend)
self.assertEqual(qobj.config.init_qubits, True)
def test_init_qubits_true(self):
"""Check that the init_qubits=True assemble option is passed on to the qobj."""
qobj = assemble(self.schedule, self.backend, init_qubits=True)
self.assertEqual(qobj.config.init_qubits, True)
def test_init_qubits_false(self):
"""Check that the init_qubits=False assemble option is passed on to the qobj."""
qobj = assemble(self.schedule, self.backend, init_qubits=False)
self.assertEqual(qobj.config.init_qubits, False)
def test_assemble_backend_rep_times_delays(self):
"""Check that rep_time and rep_delay are properly set from backend values."""
# use first entry from allowed backend values
rep_times = [2.0, 3.0, 4.0] # sec
rep_delay_range = [2.5e-3, 4.5e-3]
default_rep_delay = 3.0e-3
self.backend_config.rep_times = rep_times
setattr(self.backend_config, "rep_delay_range", rep_delay_range)
setattr(self.backend_config, "default_rep_delay", default_rep_delay)
# dynamic rep rates off
qobj = assemble(self.schedule, self.backend)
self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6))
self.assertEqual(hasattr(qobj.config, "rep_delay"), False)
# dynamic rep rates on
setattr(self.backend_config, "dynamic_reprate_enabled", True)
# RuntimeWarning bc ``rep_time`` is specified`` when dynamic rep rates not enabled
with self.assertWarns(RuntimeWarning):
qobj = assemble(self.schedule, self.backend)
self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6))
self.assertEqual(qobj.config.rep_delay, default_rep_delay * 1e6)
def test_assemble_user_rep_time_delay(self):
"""Check that user runtime config rep_time and rep_delay work."""
# set custom rep_time and rep_delay in runtime config
rep_time = 200.0e-6
rep_delay = 2.5e-6
self.config["rep_time"] = rep_time
self.config["rep_delay"] = rep_delay
# dynamic rep rates off
# RuntimeWarning bc using ``rep_delay`` when dynamic rep rates off
with self.assertWarns(RuntimeWarning):
qobj = assemble(self.schedule, self.backend, **self.config)
self.assertEqual(qobj.config.rep_time, int(rep_time * 1e6))
self.assertEqual(hasattr(qobj.config, "rep_delay"), False)
# now remove rep_delay and enable dynamic rep rates
# RuntimeWarning bc using ``rep_time`` when dynamic rep rates are enabled
del self.config["rep_delay"]
setattr(self.backend_config, "dynamic_reprate_enabled", True)
with self.assertWarns(RuntimeWarning):
qobj = assemble(self.schedule, self.backend, **self.config)
self.assertEqual(qobj.config.rep_time, int(rep_time * 1e6))
self.assertEqual(hasattr(qobj.config, "rep_delay"), False)
# use ``default_rep_delay``
# ``rep_time`` comes from allowed backend rep_times
rep_times = [0.5, 1.0, 1.5] # sec
self.backend_config.rep_times = rep_times
setattr(self.backend_config, "rep_delay_range", [0, 3.0e-6])
setattr(self.backend_config, "default_rep_delay", 2.2e-6)
del self.config["rep_time"]
qobj = assemble(self.schedule, self.backend, **self.config)
self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6))
self.assertEqual(qobj.config.rep_delay, 2.2)
# use qobj ``default_rep_delay``
self.config["rep_delay"] = 1.5e-6
qobj = assemble(self.schedule, self.backend, **self.config)
self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6))
self.assertEqual(qobj.config.rep_delay, 1.5)
# use ``rep_delay`` outside of ``rep_delay_range
self.config["rep_delay"] = 5.0e-6
with self.assertRaises(QiskitError):
assemble(self.schedule, self.backend, **self.config)
def test_assemble_with_individual_discriminators(self):
"""Test that assembly works with individual discriminators."""
disc_one = Discriminator("disc_one", test_params=True)
disc_two = Discriminator("disc_two", test_params=False)
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0), discriminator=disc_one),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1), discriminator=disc_two),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
qobj_discriminators = qobj.experiments[0].instructions[0].discriminators
self.assertEqual(len(qobj_discriminators), 2)
self.assertEqual(qobj_discriminators[0].name, "disc_one")
self.assertEqual(qobj_discriminators[0].params["test_params"], True)
self.assertEqual(qobj_discriminators[1].name, "disc_two")
self.assertEqual(qobj_discriminators[1].params["test_params"], False)
def test_assemble_with_single_discriminators(self):
"""Test that assembly works with both a single discriminator."""
disc_one = Discriminator("disc_one", test_params=True)
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0), discriminator=disc_one),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
qobj_discriminators = qobj.experiments[0].instructions[0].discriminators
self.assertEqual(len(qobj_discriminators), 1)
self.assertEqual(qobj_discriminators[0].name, "disc_one")
self.assertEqual(qobj_discriminators[0].params["test_params"], True)
def test_assemble_with_unequal_discriminators(self):
"""Test that assembly works with incorrect number of discriminators for
number of qubits."""
disc_one = Discriminator("disc_one", test_params=True)
disc_two = Discriminator("disc_two", test_params=False)
schedule = Schedule()
schedule += Acquire(5, AcquireChannel(0), MemorySlot(0), discriminator=disc_one)
schedule += Acquire(5, AcquireChannel(1), MemorySlot(1), discriminator=disc_two)
schedule += Acquire(5, AcquireChannel(2), MemorySlot(2))
with self.assertRaises(QiskitError):
assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1, 2]],
)
def test_assemble_with_individual_kernels(self):
"""Test that assembly works with individual kernels."""
disc_one = Kernel("disc_one", test_params=True)
disc_two = Kernel("disc_two", test_params=False)
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0), kernel=disc_one),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1), kernel=disc_two),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
qobj_kernels = qobj.experiments[0].instructions[0].kernels
self.assertEqual(len(qobj_kernels), 2)
self.assertEqual(qobj_kernels[0].name, "disc_one")
self.assertEqual(qobj_kernels[0].params["test_params"], True)
self.assertEqual(qobj_kernels[1].name, "disc_two")
self.assertEqual(qobj_kernels[1].params["test_params"], False)
def test_assemble_with_single_kernels(self):
"""Test that assembly works with both a single kernel."""
disc_one = Kernel("disc_one", test_params=True)
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0), kernel=disc_one),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
qobj_kernels = qobj.experiments[0].instructions[0].kernels
self.assertEqual(len(qobj_kernels), 1)
self.assertEqual(qobj_kernels[0].name, "disc_one")
self.assertEqual(qobj_kernels[0].params["test_params"], True)
def test_assemble_with_unequal_kernels(self):
"""Test that assembly works with incorrect number of discriminators for
number of qubits."""
disc_one = Kernel("disc_one", test_params=True)
disc_two = Kernel("disc_two", test_params=False)
schedule = Schedule()
schedule += Acquire(5, AcquireChannel(0), MemorySlot(0), kernel=disc_one)
schedule += Acquire(5, AcquireChannel(1), MemorySlot(1), kernel=disc_two)
schedule += Acquire(5, AcquireChannel(2), MemorySlot(2))
with self.assertRaises(QiskitError):
assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1, 2]],
)
def test_assemble_single_instruction(self):
"""Test assembling schedules, no lo config."""
inst = pulse.Play(pulse.Constant(100, 1.0), pulse.DriveChannel(0))
self.assertIsInstance(assemble(inst, self.backend), PulseQobj)
def test_assemble_overlapping_time(self):
"""Test that assembly errors when qubits are measured in overlapping time."""
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)) << 1,
)
with self.assertRaises(QiskitError):
assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
def test_assemble_meas_map_vs_insts(self):
"""Test that assembly errors when the qubits are measured in overlapping time
and qubits are not in the first meas_map list."""
schedule = Schedule()
schedule += Acquire(5, AcquireChannel(0), MemorySlot(0))
schedule += Acquire(5, AcquireChannel(1), MemorySlot(1))
schedule += Acquire(5, AcquireChannel(2), MemorySlot(2)) << 2
schedule += Acquire(5, AcquireChannel(3), MemorySlot(3)) << 2
with self.assertRaises(QiskitError):
assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1, 2], [3]],
)
def test_assemble_non_overlapping_time_single_meas_map(self):
"""Test that assembly works when qubits are measured in non-overlapping
time within the same measurement map list."""
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)) << 5,
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
self.assertIsInstance(qobj, PulseQobj)
def test_assemble_disjoint_time(self):
"""Test that assembly works when qubits are in disjoint meas map sets."""
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)) << 1,
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 2], [1, 3]],
)
self.assertIsInstance(qobj, PulseQobj)
def test_assemble_valid_qubits(self):
"""Test that assembly works when qubits that are in the measurement map
is measured."""
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(2), MemorySlot(2)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(3), MemorySlot(3)),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1, 2], [3]],
)
self.assertIsInstance(qobj, PulseQobj)
class TestPulseAssemblerMissingKwargs(QiskitTestCase):
"""Verify that errors are raised in case backend is not provided and kwargs are missing."""
def setUp(self):
super().setUp()
self.schedule = pulse.Schedule(name="fake_experiment")
self.backend = FakeOpenPulse2Q()
self.config = self.backend.configuration()
self.defaults = self.backend.defaults()
self.qubit_lo_freq = list(self.defaults.qubit_freq_est)
self.meas_lo_freq = list(self.defaults.meas_freq_est)
self.qubit_lo_range = self.config.qubit_lo_range
self.meas_lo_range = self.config.meas_lo_range
self.schedule_los = {
pulse.DriveChannel(0): self.qubit_lo_freq[0],
pulse.DriveChannel(1): self.qubit_lo_freq[1],
pulse.MeasureChannel(0): self.meas_lo_freq[0],
pulse.MeasureChannel(1): self.meas_lo_freq[1],
}
self.meas_map = self.config.meas_map
self.memory_slots = self.config.n_qubits
# default rep_time and rep_delay
self.rep_time = self.config.rep_times[0]
self.rep_delay = None
def test_defaults(self):
"""Test defaults work."""
qobj = assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
self.assertIsInstance(qobj, PulseQobj)
def test_missing_qubit_lo_freq(self):
"""Test error raised if qubit_lo_freq missing."""
with self.assertRaises(QiskitError):
assemble(
self.schedule,
qubit_lo_freq=None,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
def test_missing_meas_lo_freq(self):
"""Test error raised if meas_lo_freq missing."""
with self.assertRaises(QiskitError):
assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=None,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
def test_missing_memory_slots(self):
"""Test error is not raised if memory_slots are missing."""
qobj = assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_map=self.meas_map,
memory_slots=None,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
self.assertIsInstance(qobj, PulseQobj)
def test_missing_rep_time_and_delay(self):
"""Test qobj is valid if rep_time and rep_delay are missing."""
qobj = assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_map=self.meas_map,
memory_slots=None,
rep_time=None,
rep_delay=None,
)
self.assertEqual(hasattr(qobj, "rep_time"), False)
self.assertEqual(hasattr(qobj, "rep_delay"), False)
def test_missing_meas_map(self):
"""Test that assembly still works if meas_map is missing."""
qobj = assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_map=None,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
self.assertIsInstance(qobj, PulseQobj)
def test_missing_lo_ranges(self):
"""Test that assembly still works if lo_ranges are missing."""
qobj = assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=None,
meas_lo_range=None,
schedule_los=self.schedule_los,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
self.assertIsInstance(qobj, PulseQobj)
def test_unsupported_meas_level(self):
"""Test that assembly raises an error if meas_level is not supported"""
backend = FakeOpenPulse2Q()
backend.configuration().meas_levels = [1, 2]
with self.assertRaises(QiskitError):
assemble(
self.schedule,
backend,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_level=0,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
def test_single_and_deprecated_acquire_styles(self):
"""Test that acquires are identically combined with Acquires that take a single channel."""
backend = FakeOpenPulse2Q()
new_style_schedule = Schedule()
acq_dur = 1200
for i in range(2):
new_style_schedule += Acquire(acq_dur, AcquireChannel(i), MemorySlot(i))
deprecated_style_schedule = Schedule()
for i in range(2):
deprecated_style_schedule += Acquire(1200, AcquireChannel(i), MemorySlot(i))
# The Qobj IDs will be different
n_qobj = assemble(new_style_schedule, backend)
n_qobj.qobj_id = None
n_qobj.experiments[0].header.name = None
d_qobj = assemble(deprecated_style_schedule, backend)
d_qobj.qobj_id = None
d_qobj.experiments[0].header.name = None
self.assertEqual(n_qobj, d_qobj)
assembled_acquire = n_qobj.experiments[0].instructions[0]
self.assertEqual(assembled_acquire.qubits, [0, 1])
self.assertEqual(assembled_acquire.memory_slot, [0, 1])
class StreamHandlerRaiseException(StreamHandler):
"""Handler class that will raise an exception on formatting errors."""
def handleError(self, record):
raise sys.exc_info()
class TestLogAssembler(QiskitTestCase):
"""Testing the log_assembly option."""
def setUp(self):
super().setUp()
logger = getLogger()
self.addCleanup(logger.setLevel, logger.level)
logger.setLevel("DEBUG")
self.output = io.StringIO()
logger.addHandler(StreamHandlerRaiseException(self.output))
self.circuit = QuantumCircuit(QuantumRegister(1))
def assertAssembleLog(self, log_msg):
"""Runs assemble and checks for logs containing specified message"""
assemble(self.circuit, shots=2000, memory=True)
self.output.seek(0)
# Filter unrelated log lines
output_lines = self.output.readlines()
assembly_log_lines = [x for x in output_lines if log_msg in x]
self.assertTrue(len(assembly_log_lines) == 1)
def test_assembly_log_time(self):
"""Check Total Assembly Time is logged"""
self.assertAssembleLog("Total Assembly Time")
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Compiler Test."""
import os
import unittest
from qiskit import BasicAer
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit import execute
from qiskit.circuit.library import U1Gate, U2Gate
from qiskit.compiler import transpile, assemble
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeRueschlikon, FakeTenerife
from qiskit.qobj import QasmQobj
class TestCompiler(QiskitTestCase):
"""Qiskit Compiler Tests."""
def setUp(self):
super().setUp()
self.seed_simulator = 42
self.backend = BasicAer.get_backend("qasm_simulator")
def test_example_multiple_compile(self):
"""Test a toy example compiling multiple circuits.
Pass if the results are correct.
"""
backend = BasicAer.get_backend("qasm_simulator")
coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]]
qr = QuantumRegister(5)
cr = ClassicalRegister(5)
bell = QuantumCircuit(qr, cr)
ghz = QuantumCircuit(qr, cr)
# Create a GHZ state
ghz.h(qr[0])
for i in range(4):
ghz.cx(qr[i], qr[i + 1])
# Insert a barrier before measurement
ghz.barrier()
# Measure all of the qubits in the standard basis
for i in range(5):
ghz.measure(qr[i], cr[i])
# Create a Bell state
bell.h(qr[0])
bell.cx(qr[0], qr[1])
bell.barrier()
bell.measure(qr[0], cr[0])
bell.measure(qr[1], cr[1])
shots = 2048
bell_backend = transpile(bell, backend=backend)
ghz_backend = transpile(ghz, backend=backend, coupling_map=coupling_map)
bell_qobj = assemble(bell_backend, shots=shots, seed_simulator=10)
ghz_qobj = assemble(ghz_backend, shots=shots, seed_simulator=10)
bell_result = backend.run(bell_qobj).result()
ghz_result = backend.run(ghz_qobj).result()
threshold = 0.05 * shots
counts_bell = bell_result.get_counts()
target_bell = {"00000": shots / 2, "00011": shots / 2}
self.assertDictAlmostEqual(counts_bell, target_bell, threshold)
counts_ghz = ghz_result.get_counts()
target_ghz = {"00000": shots / 2, "11111": shots / 2}
self.assertDictAlmostEqual(counts_ghz, target_ghz, threshold)
def test_compile_coupling_map(self):
"""Test compile_coupling_map.
If all correct should return data with the same stats. The circuit may
be different.
"""
backend = BasicAer.get_backend("qasm_simulator")
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(3, "cr")
qc = QuantumCircuit(qr, cr, name="qccccccc")
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.cx(qr[0], qr[2])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
qc.measure(qr[2], cr[2])
shots = 2048
coupling_map = [[0, 1], [1, 2]]
initial_layout = [0, 1, 2]
qc_b = transpile(
qc, backend=backend, coupling_map=coupling_map, initial_layout=initial_layout
)
qobj = assemble(qc_b, shots=shots, seed_simulator=88)
job = backend.run(qobj)
result = job.result()
qasm_to_check = qc.qasm()
self.assertEqual(len(qasm_to_check), 173)
counts = result.get_counts(qc)
target = {"000": shots / 2, "111": shots / 2}
threshold = 0.05 * shots
self.assertDictAlmostEqual(counts, target, threshold)
def test_example_swap_bits(self):
"""Test a toy example swapping a set bit around.
Uses the mapper. Pass if results are correct.
"""
backend = BasicAer.get_backend("qasm_simulator")
coupling_map = [
[0, 1],
[0, 8],
[1, 2],
[1, 9],
[2, 3],
[2, 10],
[3, 4],
[3, 11],
[4, 5],
[4, 12],
[5, 6],
[5, 13],
[6, 7],
[6, 14],
[7, 15],
[8, 9],
[9, 10],
[10, 11],
[11, 12],
[12, 13],
[13, 14],
[14, 15],
]
# βββββ β βββ
# q0_0: β€ X ββXββββββββββββββ€Mββββββββββββββββ
# βββββ β β ββ₯β βββ
# q0_1: βββββββΌβββββXββXββββββ«βββββ€Mββββββββββ
# β β β β β ββ₯β βββ
# q0_2: ββββββXββXβββΌβββΌββββββ«ββββββ«βββββ€Mββββ
# β β β β β βββ β ββ₯β
# q1_0: ββββββββββΌβββΌβββΌββββββ«ββ€Mβββ«ββββββ«ββββ
# β β β β β ββ₯β β βββ β
# q1_1: ββββββββββΌβββΌββXββββββ«βββ«βββ«ββ€Mβββ«ββββ
# β β β β β β ββ₯β β βββ
# q1_2: βββββββββXββXβββββββββ«βββ«βββ«βββ«βββ«ββ€Mβ
# β β β β β β ββ₯β
# c0: 6/ββββββββββββββββββββββ©βββ©βββ©βββ©βββ©βββ©β
# 0 3 1 4 2 5
n = 3 # make this at least 3
qr0 = QuantumRegister(n)
qr1 = QuantumRegister(n)
ans = ClassicalRegister(2 * n)
qc = QuantumCircuit(qr0, qr1, ans)
# Set the first bit of qr0
qc.x(qr0[0])
# Swap the set bit
qc.swap(qr0[0], qr0[n - 1])
qc.swap(qr0[n - 1], qr1[n - 1])
qc.swap(qr1[n - 1], qr0[1])
qc.swap(qr0[1], qr1[1])
# Insert a barrier before measurement
qc.barrier()
# Measure all of the qubits in the standard basis
for j in range(n):
qc.measure(qr0[j], ans[j])
qc.measure(qr1[j], ans[j + n])
# First version: no mapping
result = execute(
qc, backend=backend, coupling_map=None, shots=1024, seed_simulator=14
).result()
self.assertEqual(result.get_counts(qc), {"010000": 1024})
# Second version: map to coupling graph
result = execute(
qc, backend=backend, coupling_map=coupling_map, shots=1024, seed_simulator=14
).result()
self.assertEqual(result.get_counts(qc), {"010000": 1024})
def test_parallel_compile(self):
"""Trigger parallel routines in compile."""
backend = FakeRueschlikon()
qr = QuantumRegister(16)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
for k in range(1, 15):
qc.cx(qr[0], qr[k])
qc.measure(qr[5], cr[0])
qlist = [qc for k in range(10)]
qobj = assemble(transpile(qlist, backend=backend))
self.assertEqual(len(qobj.experiments), 10)
def test_no_conflict_backend_passmanager(self):
"""execute(qc, backend=..., passmanager=...)
See: https://github.com/Qiskit/qiskit-terra/issues/5037
"""
backend = BasicAer.get_backend("qasm_simulator")
qc = QuantumCircuit(2)
qc.append(U1Gate(0), [0])
qc.measure_all()
job = execute(qc, backend=backend, pass_manager=PassManager())
result = job.result().get_counts()
self.assertEqual(result, {"00": 1024})
def test_compile_single_qubit(self):
"""Compile a single-qubit circuit in a non-trivial layout"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
layout = {qr[0]: 12}
cmap = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
circuit2 = transpile(
circuit, backend=None, coupling_map=cmap, basis_gates=["u2"], initial_layout=layout
)
qobj = assemble(circuit2)
compiled_instruction = qobj.experiments[0].instructions[0]
self.assertEqual(compiled_instruction.name, "u2")
self.assertEqual(compiled_instruction.qubits, [12])
self.assertEqual(compiled_instruction.params, [0, 3.141592653589793])
def test_compile_pass_manager(self):
"""Test compile with and without an empty pass manager."""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.append(U1Gate(3.14), [qr[0]])
qc.append(U2Gate(3.14, 1.57), [qr[0]])
qc.barrier(qr)
qc.measure(qr, cr)
backend = BasicAer.get_backend("qasm_simulator")
qrtrue = assemble(transpile(qc, backend, seed_transpiler=8), seed_simulator=42)
rtrue = backend.run(qrtrue).result()
qrfalse = assemble(PassManager().run(qc), seed_simulator=42)
rfalse = backend.run(qrfalse).result()
self.assertEqual(rtrue.get_counts(), rfalse.get_counts())
def test_mapper_overoptimization(self):
"""Check mapper overoptimization.
The mapper should not change the semantics of the input.
An overoptimization introduced issue #81:
https://github.com/Qiskit/qiskit-terra/issues/81
"""
# βββββ βββ
# q0_0: β€ X ββββ ββββββββ€Mββββββββββββ
# βββββ€βββ΄βββββββββ₯β βββ
# q0_1: β€ Y ββ€ X ββ€ S βββ«ββββ βββ€Mββββ
# βββββ€ββββββββββ€ β βββ΄ββββ₯ββββ
# q0_2: β€ Z ββββ βββ€ T βββ«ββ€ X βββ«ββ€Mβ
# ββββββββ΄βββββββ€ β ββ¬ββ¬β β ββ₯β
# q0_3: ββββββ€ X ββ€ H βββ«βββ€Mββββ«βββ«β
# ββββββββββ β ββ₯β β β
# c0: 4/βββββββββββββββββ©ββββ©ββββ©βββ©β
# 0 3 1 2
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
circ = QuantumCircuit(qr, cr)
circ.x(qr[0])
circ.y(qr[1])
circ.z(qr[2])
circ.cx(qr[0], qr[1])
circ.cx(qr[2], qr[3])
circ.s(qr[1])
circ.t(qr[2])
circ.h(qr[3])
circ.cx(qr[1], qr[2])
circ.measure(qr[0], cr[0])
circ.measure(qr[1], cr[1])
circ.measure(qr[2], cr[2])
circ.measure(qr[3], cr[3])
coupling_map = [[0, 2], [1, 2], [2, 3]]
shots = 1000
result1 = execute(
circ,
backend=self.backend,
coupling_map=coupling_map,
seed_simulator=self.seed_simulator,
seed_transpiler=8,
shots=shots,
)
count1 = result1.result().get_counts()
result2 = execute(
circ,
backend=self.backend,
coupling_map=None,
seed_simulator=self.seed_simulator,
seed_transpiler=8,
shots=shots,
)
count2 = result2.result().get_counts()
self.assertDictAlmostEqual(count1, count2, shots * 0.02)
def test_grovers_circuit(self):
"""Testing a circuit originated in the Grover algorithm"""
shots = 1000
coupling_map = None
# 6-qubit grovers
#
# ββββββββββ ββββββββββ βββββ ββββββββββ β βββ
# q0_0: β€ H ββ€ X ββββ βββ€ X ββ€ X ββββ βββ€ X ββββ βββ€ X ββ€ H ββββββββββ€Mββββ
# βββββ€βββββ β ββββββββββ β βββββ€ β βββββ€βββββ€ β ββ₯ββββ
# q0_1: β€ H ββββ βββββΌββββββββββ βββββΌβββ€ X ββββ βββ€ X ββ€ H βββββββββββ«ββ€Mβ
# βββββ€ β βββ΄ββ β βββ΄βββββββ β ββββββββββ β β ββ₯β
# q0_2: β€ X ββββΌβββ€ X ββββ βββββΌβββ€ X βββββββββΌββββββββββββββββββββββ«βββ«β
# βββββ€βββ΄βββββββ β βββ΄βββββββ β β β β
# q0_3: β€ X ββ€ X βββββββββ βββ€ X ββββββββββββββΌββββββββββββββββββββββ«βββ«β
# ββββββββββ βββ΄βββββββ€βββββ βββ΄βββββββββββββββββ β β β
# q0_4: ββββββββββββββββ€ X ββ€ X ββ€ H βββββββ€ X ββ€ H ββ€ X ββ€ H ββββββ«βββ«β
# βββββββββββββββ ββββββββββββββββββββ β β β
# q0_5: ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ«βββ«β
# β β β
# c0: 2/ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ©βββ©β
# 0 1
qr = QuantumRegister(6)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr, name="grovers")
circuit.h(qr[0])
circuit.h(qr[1])
circuit.x(qr[2])
circuit.x(qr[3])
circuit.x(qr[0])
circuit.cx(qr[0], qr[2])
circuit.x(qr[0])
circuit.cx(qr[1], qr[3])
circuit.ccx(qr[2], qr[3], qr[4])
circuit.cx(qr[1], qr[3])
circuit.x(qr[0])
circuit.cx(qr[0], qr[2])
circuit.x(qr[0])
circuit.x(qr[1])
circuit.x(qr[4])
circuit.h(qr[4])
circuit.ccx(qr[0], qr[1], qr[4])
circuit.h(qr[4])
circuit.x(qr[0])
circuit.x(qr[1])
circuit.x(qr[4])
circuit.h(qr[0])
circuit.h(qr[1])
circuit.h(qr[4])
circuit.barrier(qr)
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[1])
result = execute(
circuit,
backend=self.backend,
coupling_map=coupling_map,
seed_simulator=self.seed_simulator,
shots=shots,
)
counts = result.result().get_counts()
expected_probs = {"00": 0.64, "01": 0.117, "10": 0.113, "11": 0.13}
target = {key: shots * val for key, val in expected_probs.items()}
threshold = 0.04 * shots
self.assertDictAlmostEqual(counts, target, threshold)
def test_math_domain_error(self):
"""Check for floating point errors.
The math library operates over floats and introduces floating point
errors that should be avoided.
See: https://github.com/Qiskit/qiskit-terra/issues/111
"""
# ββββββββββ βββ
# q0_0: β€ Y ββ€ X βββββββ€Mββββββββββββββββββββββ
# ββββββββ¬ββ ββ₯β βββ
# q0_1: ββββββββ βββββββββ«ββββββββββββββ βββ€Mββββ
# βββββββββββββββ β βββββββββββββ΄ββββ₯ββββ
# q0_2: β€ Z ββ€ H ββ€ Y βββ«ββ€ T ββ€ Z ββ€ X βββ«ββ€Mβ
# ββ¬ββ¬βββββββββββ β βββββββββββββββ β ββ₯β
# q0_3: ββ€Mββββββββββββββ«ββββββββββββββββββ«βββ«β
# ββ₯β β β β
# c0: 4/βββ©ββββββββββββββ©ββββββββββββββββββ©βββ©β
# 3 0 1 2
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
circ = QuantumCircuit(qr, cr)
circ.y(qr[0])
circ.z(qr[2])
circ.h(qr[2])
circ.cx(qr[1], qr[0])
circ.y(qr[2])
circ.t(qr[2])
circ.z(qr[2])
circ.cx(qr[1], qr[2])
circ.measure(qr[0], cr[0])
circ.measure(qr[1], cr[1])
circ.measure(qr[2], cr[2])
circ.measure(qr[3], cr[3])
coupling_map = [[0, 2], [1, 2], [2, 3]]
shots = 2000
job = execute(
circ,
backend=self.backend,
coupling_map=coupling_map,
seed_simulator=self.seed_simulator,
shots=shots,
)
counts = job.result().get_counts()
target = {"0001": shots / 2, "0101": shots / 2}
threshold = 0.04 * shots
self.assertDictAlmostEqual(counts, target, threshold)
def test_random_parameter_circuit(self):
"""Run a circuit with randomly generated parameters."""
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "random_n5_d5.qasm"))
coupling_map = [[0, 1], [1, 2], [2, 3], [3, 4]]
shots = 1024
qobj = execute(
circ,
backend=self.backend,
coupling_map=coupling_map,
shots=shots,
seed_simulator=self.seed_simulator,
)
counts = qobj.result().get_counts()
expected_probs = {
"00000": 0.079239867254200971,
"00001": 0.032859032998526903,
"00010": 0.10752610993531816,
"00011": 0.018818532050952699,
"00100": 0.054830807251011054,
"00101": 0.0034141983951965164,
"00110": 0.041649309748902276,
"00111": 0.039967731207338125,
"01000": 0.10516937819949743,
"01001": 0.026635620063700002,
"01010": 0.0053475143548793866,
"01011": 0.01940513314416064,
"01100": 0.0044028405481225047,
"01101": 0.057524760052126644,
"01110": 0.010795354134597078,
"01111": 0.026491296821535528,
"10000": 0.094827455395274859,
"10001": 0.0008373965072688836,
"10010": 0.029082297894094441,
"10011": 0.012386622870598416,
"10100": 0.018739140061148799,
"10101": 0.01367656456536896,
"10110": 0.039184170706009248,
"10111": 0.062339335178438288,
"11000": 0.00293674365989009,
"11001": 0.012848433960739968,
"11010": 0.018472497159499782,
"11011": 0.0088903691234912003,
"11100": 0.031305389080034329,
"11101": 0.0004788556283690458,
"11110": 0.002232419390471667,
"11111": 0.017684822659235985,
}
target = {key: shots * val for key, val in expected_probs.items()}
threshold = 0.04 * shots
self.assertDictAlmostEqual(counts, target, threshold)
def test_yzy_zyz_cases(self):
"""yzy_to_zyz works in previously failed cases.
See: https://github.com/Qiskit/qiskit-terra/issues/607
"""
backend = FakeTenerife()
qr = QuantumRegister(2)
circ1 = QuantumCircuit(qr)
circ1.cx(qr[0], qr[1])
circ1.rz(0.7, qr[1])
circ1.rx(1.570796, qr[1])
qobj1 = assemble(transpile(circ1, backend))
self.assertIsInstance(qobj1, QasmQobj)
circ2 = QuantumCircuit(qr)
circ2.y(qr[0])
circ2.h(qr[0])
circ2.s(qr[0])
circ2.h(qr[0])
qobj2 = assemble(transpile(circ2, backend))
self.assertIsInstance(qobj2, QasmQobj)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Assembler Test."""
import unittest
import numpy as np
from numpy.testing import assert_allclose
from qiskit import pulse
from qiskit.compiler.assembler import assemble
from qiskit.assembler.disassemble import disassemble
from qiskit.assembler.run_config import RunConfig
from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Gate, Instruction, Parameter
from qiskit.circuit.library import RXGate
from qiskit.pulse.transforms import target_qobj_transform
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeOpenPulse2Q
import qiskit.quantum_info as qi
def _parametric_to_waveforms(schedule):
instructions = list(schedule.instructions)
for i, time_instruction_tuple in enumerate(schedule.instructions):
time, instruction = time_instruction_tuple
if not isinstance(instruction.pulse, pulse.library.Waveform):
new_inst = pulse.Play(instruction.pulse.get_waveform(), instruction.channel)
instructions[i] = (time, new_inst)
return tuple(instructions)
class TestQuantumCircuitDisassembler(QiskitTestCase):
"""Tests for disassembling circuits to qobj."""
def test_disassemble_single_circuit(self):
"""Test disassembling a single circuit."""
qr = QuantumRegister(2, name="q")
cr = ClassicalRegister(2, name="c")
circ = QuantumCircuit(qr, cr, name="circ")
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.measure(qr, cr)
qubit_lo_freq = [5e9, 5e9]
meas_lo_freq = [6.7e9, 6.7e9]
qobj = assemble(
circ,
shots=2000,
memory=True,
qubit_lo_freq=qubit_lo_freq,
meas_lo_freq=meas_lo_freq,
)
circuits, run_config_out, headers = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 2)
self.assertEqual(run_config_out.shots, 2000)
self.assertEqual(run_config_out.memory, True)
self.assertEqual(run_config_out.qubit_lo_freq, qubit_lo_freq)
self.assertEqual(run_config_out.meas_lo_freq, meas_lo_freq)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], circ)
self.assertEqual({}, headers)
def test_disassemble_multiple_circuits(self):
"""Test disassembling multiple circuits, all should have the same config."""
qr0 = QuantumRegister(2, name="q0")
qc0 = ClassicalRegister(2, name="c0")
circ0 = QuantumCircuit(qr0, qc0, name="circ0")
circ0.h(qr0[0])
circ0.cx(qr0[0], qr0[1])
circ0.measure(qr0, qc0)
qr1 = QuantumRegister(3, name="q1")
qc1 = ClassicalRegister(3, name="c1")
circ1 = QuantumCircuit(qr1, qc1, name="circ0")
circ1.h(qr1[0])
circ1.cx(qr1[0], qr1[1])
circ1.cx(qr1[0], qr1[2])
circ1.measure(qr1, qc1)
qobj = assemble([circ0, circ1], shots=100, memory=False, seed=6)
circuits, run_config_out, headers = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 3)
self.assertEqual(run_config_out.memory_slots, 3)
self.assertEqual(run_config_out.shots, 100)
self.assertEqual(run_config_out.memory, False)
self.assertEqual(run_config_out.seed, 6)
self.assertEqual(len(circuits), 2)
for circuit in circuits:
self.assertIn(circuit, [circ0, circ1])
self.assertEqual({}, headers)
def test_disassemble_no_run_config(self):
"""Test disassembling with no run_config, relying on default."""
qr = QuantumRegister(2, name="q")
qc = ClassicalRegister(2, name="c")
circ = QuantumCircuit(qr, qc, name="circ")
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.measure(qr, qc)
qobj = assemble(circ)
circuits, run_config_out, headers = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 2)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], circ)
self.assertEqual({}, headers)
def test_disassemble_initialize(self):
"""Test disassembling a circuit with an initialize."""
q = QuantumRegister(2, name="q")
circ = QuantumCircuit(q, name="circ")
circ.initialize([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)], q[:])
qobj = assemble(circ)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 0)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], circ)
self.assertEqual({}, header)
def test_disassemble_isometry(self):
"""Test disassembling a circuit with an isometry."""
q = QuantumRegister(2, name="q")
circ = QuantumCircuit(q, name="circ")
circ.iso(qi.random_unitary(4).data, circ.qubits, [])
qobj = assemble(circ)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 0)
self.assertEqual(len(circuits), 1)
# params array
assert_allclose(circuits[0]._data[0].operation.params[0], circ._data[0].operation.params[0])
# all other data
self.assertEqual(
circuits[0]._data[0].operation.params[1:], circ._data[0].operation.params[1:]
)
self.assertEqual(circuits[0]._data[0].qubits, circ._data[0].qubits)
self.assertEqual(circuits[0]._data[0].clbits, circ._data[0].clbits)
self.assertEqual(circuits[0]._data[1:], circ._data[1:])
self.assertEqual({}, header)
def test_opaque_instruction(self):
"""Test the disassembler handles opaque instructions correctly."""
opaque_inst = Instruction(name="my_inst", num_qubits=4, num_clbits=2, params=[0.5, 0.4])
q = QuantumRegister(6, name="q")
c = ClassicalRegister(4, name="c")
circ = QuantumCircuit(q, c, name="circ")
circ.append(opaque_inst, [q[0], q[2], q[5], q[3]], [c[3], c[0]])
qobj = assemble(circ)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 6)
self.assertEqual(run_config_out.memory_slots, 4)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], circ)
self.assertEqual({}, header)
def test_circuit_with_conditionals(self):
"""Verify disassemble sets conditionals correctly."""
qr = QuantumRegister(2)
cr1 = ClassicalRegister(1)
cr2 = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr1, cr2)
qc.measure(qr[0], cr1) # Measure not required for a later conditional
qc.measure(qr[1], cr2[1]) # Measure required for a later conditional
qc.h(qr[1]).c_if(cr2, 3)
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 3)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
def test_circuit_with_simple_conditional(self):
"""Verify disassemble handles a simple conditional on the only bits."""
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0]).c_if(cr, 1)
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 1)
self.assertEqual(run_config_out.memory_slots, 1)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
def test_circuit_with_single_bit_conditions(self):
"""Verify disassemble handles a simple conditional on a single bit of a register."""
# This circuit would fail to perfectly round-trip if 'cr' below had only one bit in it.
# This is because the format of QasmQobj is insufficient to disambiguate single-bit
# conditions from conditions on registers with only one bit. Since single-bit conditions are
# mostly a hack for the QasmQobj format at all, `disassemble` always prefers to return the
# register if it can. It would also fail if registers overlap.
qr = QuantumRegister(1)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0]).c_if(cr[0], 1)
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, len(qr))
self.assertEqual(run_config_out.memory_slots, len(cr))
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
def test_circuit_with_mcx(self):
"""Verify disassemble handles mcx gate - #6271."""
qr = QuantumRegister(5)
cr = ClassicalRegister(5)
qc = QuantumCircuit(qr, cr)
qc.mcx([0, 1, 2], 4)
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 5)
self.assertEqual(run_config_out.memory_slots, 5)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
def test_multiple_conditionals_multiple_registers(self):
"""Verify disassemble handles multiple conditionals and registers."""
qr = QuantumRegister(3)
cr1 = ClassicalRegister(3)
cr2 = ClassicalRegister(5)
cr3 = ClassicalRegister(6)
cr4 = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr1, cr2, cr3, cr4)
qc.x(qr[1])
qc.h(qr)
qc.cx(qr[1], qr[0]).c_if(cr3, 14)
qc.ccx(qr[0], qr[2], qr[1]).c_if(cr4, 1)
qc.h(qr).c_if(cr1, 3)
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 3)
self.assertEqual(run_config_out.memory_slots, 15)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
def test_circuit_with_bit_conditional_1(self):
"""Verify disassemble handles conditional on a single bit."""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0]).c_if(cr[1], True)
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 2)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
def test_circuit_with_bit_conditional_2(self):
"""Verify disassemble handles multiple single bit conditionals."""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
cr1 = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr, cr1)
qc.h(qr[0]).c_if(cr1[1], False)
qc.h(qr[1]).c_if(cr[0], True)
qc.cx(qr[0], qr[1]).c_if(cr1[0], False)
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 4)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
def assertCircuitCalibrationsEqual(self, in_circuits, out_circuits):
"""Verify circuit calibrations are equivalent pre-assembly and post-disassembly"""
self.assertEqual(len(in_circuits), len(out_circuits))
for in_qc, out_qc in zip(in_circuits, out_circuits):
in_cals = in_qc.calibrations
out_cals = out_qc.calibrations
self.assertEqual(in_cals.keys(), out_cals.keys())
for gate_name in in_cals:
self.assertEqual(in_cals[gate_name].keys(), out_cals[gate_name].keys())
for gate_params, in_sched in in_cals[gate_name].items():
out_sched = out_cals[gate_name][gate_params]
self.assertEqual(*map(_parametric_to_waveforms, (in_sched, out_sched)))
def test_single_circuit_calibrations(self):
"""Test that disassembler parses single circuit QOBJ calibrations (from QOBJ-level)."""
theta = Parameter("theta")
qc = QuantumCircuit(2)
qc.h(0)
qc.rx(np.pi, 0)
qc.rx(theta, 1)
qc = qc.assign_parameters({theta: np.pi})
with pulse.build() as h_sched:
pulse.play(pulse.library.Drag(1, 0.15, 4, 2), pulse.DriveChannel(0))
with pulse.build() as x180:
pulse.play(pulse.library.Gaussian(1, 0.2, 5), pulse.DriveChannel(0))
qc.add_calibration("h", [0], h_sched)
qc.add_calibration(RXGate(np.pi), [0], x180)
qobj = assemble(qc, FakeOpenPulse2Q())
output_circuits, _, _ = disassemble(qobj)
self.assertCircuitCalibrationsEqual([qc], output_circuits)
def test_parametric_pulse_circuit_calibrations(self):
"""Test that disassembler parses parametric pulses back to pulse gates."""
with pulse.build() as h_sched:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
qc = QuantumCircuit(2)
qc.h(0)
qc.add_calibration("h", [0], h_sched)
backend = FakeOpenPulse2Q()
backend.configuration().parametric_pulses = ["drag"]
qobj = assemble(qc, backend)
output_circuits, _, _ = disassemble(qobj)
out_qc = output_circuits[0]
self.assertCircuitCalibrationsEqual([qc], output_circuits)
self.assertTrue(
all(
qc_sched.instructions == out_qc_sched.instructions
for (_, qc_gate), (_, out_qc_gate) in zip(
qc.calibrations.items(), out_qc.calibrations.items()
)
for qc_sched, out_qc_sched in zip(qc_gate.values(), out_qc_gate.values())
),
)
def test_multi_circuit_uncommon_calibrations(self):
"""Test that disassembler parses uncommon calibrations (stored at QOBJ experiment-level)."""
with pulse.build() as sched:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
qc_0 = QuantumCircuit(2)
qc_0.h(0)
qc_0.append(RXGate(np.pi), [1])
qc_0.add_calibration("h", [0], sched)
qc_0.add_calibration(RXGate(np.pi), [1], sched)
qc_1 = QuantumCircuit(2)
qc_1.h(0)
circuits = [qc_0, qc_1]
qobj = assemble(circuits, FakeOpenPulse2Q())
output_circuits, _, _ = disassemble(qobj)
self.assertCircuitCalibrationsEqual(circuits, output_circuits)
def test_multi_circuit_common_calibrations(self):
"""Test that disassembler parses common calibrations (stored at QOBJ-level)."""
with pulse.build() as sched:
pulse.play(pulse.library.Drag(1, 0.15, 4, 2), pulse.DriveChannel(0))
qc_0 = QuantumCircuit(2)
qc_0.h(0)
qc_0.append(RXGate(np.pi), [1])
qc_0.add_calibration("h", [0], sched)
qc_0.add_calibration(RXGate(np.pi), [1], sched)
qc_1 = QuantumCircuit(2)
qc_1.h(0)
qc_1.add_calibration(RXGate(np.pi), [1], sched)
circuits = [qc_0, qc_1]
qobj = assemble(circuits, FakeOpenPulse2Q())
output_circuits, _, _ = disassemble(qobj)
self.assertCircuitCalibrationsEqual(circuits, output_circuits)
def test_single_circuit_delay_calibrations(self):
"""Test that disassembler parses delay instruction back to delay gate."""
qc = QuantumCircuit(2)
qc.append(Gate("test", 1, []), [0])
test_sched = pulse.Delay(64, pulse.DriveChannel(0)) + pulse.Delay(
160, pulse.DriveChannel(0)
)
qc.add_calibration("test", [0], test_sched)
qobj = assemble(qc, FakeOpenPulse2Q())
output_circuits, _, _ = disassemble(qobj)
self.assertEqual(len(qc.calibrations), len(output_circuits[0].calibrations))
self.assertEqual(qc.calibrations.keys(), output_circuits[0].calibrations.keys())
self.assertTrue(
all(
qc_cal.keys() == out_qc_cal.keys()
for qc_cal, out_qc_cal in zip(
qc.calibrations.values(), output_circuits[0].calibrations.values()
)
)
)
self.assertEqual(
qc.calibrations["test"][((0,), ())], output_circuits[0].calibrations["test"][((0,), ())]
)
class TestPulseScheduleDisassembler(QiskitTestCase):
"""Tests for disassembling pulse schedules to qobj."""
def setUp(self):
super().setUp()
self.backend = FakeOpenPulse2Q()
self.backend_config = self.backend.configuration()
self.backend_config.parametric_pulses = ["constant", "gaussian", "gaussian_square", "drag"]
def test_disassemble_single_schedule(self):
"""Test disassembling a single schedule."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build(self.backend) as sched:
with pulse.align_right():
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.set_phase(1.0, d0)
pulse.shift_phase(3.11, d0)
pulse.set_frequency(1e9, d0)
pulse.shift_frequency(1e7, d0)
pulse.delay(20, d0)
pulse.delay(10, d1)
pulse.play(pulse.library.Constant(8, 0.1), d1)
pulse.measure_all()
qobj = assemble(sched, backend=self.backend, shots=2000)
scheds, run_config_out, _ = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.memory_slots, 2)
self.assertEqual(run_config_out.shots, 2000)
self.assertEqual(run_config_out.memory, False)
self.assertEqual(run_config_out.meas_level, 2)
self.assertEqual(run_config_out.meas_lo_freq, self.backend.defaults().meas_freq_est)
self.assertEqual(run_config_out.qubit_lo_freq, self.backend.defaults().qubit_freq_est)
self.assertEqual(run_config_out.rep_time, 99)
self.assertEqual(len(scheds), 1)
self.assertEqual(scheds[0], target_qobj_transform(sched))
def test_disassemble_multiple_schedules(self):
"""Test disassembling multiple schedules, all should have the same config."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build(self.backend) as sched0:
with pulse.align_right():
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.set_phase(1.0, d0)
pulse.shift_phase(3.11, d0)
pulse.set_frequency(1e9, d0)
pulse.shift_frequency(1e7, d0)
pulse.delay(20, d0)
pulse.delay(10, d1)
pulse.play(pulse.library.Constant(8, 0.1), d1)
pulse.measure_all()
with pulse.build(self.backend) as sched1:
with pulse.align_right():
pulse.play(pulse.library.Constant(8, 0.1), d0)
pulse.play(pulse.library.Waveform([0.0, 1.0]), d1)
pulse.set_phase(1.1, d0)
pulse.shift_phase(3.5, d0)
pulse.set_frequency(2e9, d0)
pulse.shift_frequency(3e7, d1)
pulse.delay(20, d1)
pulse.delay(10, d0)
pulse.play(pulse.library.Constant(8, 0.4), d1)
pulse.measure_all()
qobj = assemble([sched0, sched1], backend=self.backend, shots=2000)
scheds, run_config_out, _ = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.memory_slots, 2)
self.assertEqual(run_config_out.shots, 2000)
self.assertEqual(run_config_out.memory, False)
self.assertEqual(len(scheds), 2)
self.assertEqual(scheds[0], target_qobj_transform(sched0))
self.assertEqual(scheds[1], target_qobj_transform(sched1))
def test_disassemble_parametric_pulses(self):
"""Test disassembling multiple schedules all should have the same config."""
d0 = pulse.DriveChannel(0)
with pulse.build(self.backend) as sched:
with pulse.align_right():
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.play(pulse.library.Gaussian(10, 1.0, 2.0), d0)
pulse.play(pulse.library.GaussianSquare(10, 1.0, 2.0, 3), d0)
pulse.play(pulse.library.Drag(10, 1.0, 2.0, 0.1), d0)
qobj = assemble(sched, backend=self.backend, shots=2000)
scheds, _, _ = disassemble(qobj)
self.assertEqual(scheds[0], target_qobj_transform(sched))
def test_disassemble_schedule_los(self):
"""Test disassembling schedule los."""
d0 = pulse.DriveChannel(0)
m0 = pulse.MeasureChannel(0)
d1 = pulse.DriveChannel(1)
m1 = pulse.MeasureChannel(1)
sched0 = pulse.Schedule()
sched1 = pulse.Schedule()
schedule_los = [
{d0: 4.5e9, d1: 5e9, m0: 6e9, m1: 7e9},
{d0: 5e9, d1: 4.5e9, m0: 7e9, m1: 6e9},
]
qobj = assemble([sched0, sched1], backend=self.backend, schedule_los=schedule_los)
_, run_config_out, _ = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.schedule_los, schedule_los)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-function-docstring
"""Tests basic functionality of the sequence function"""
import unittest
from qiskit import QuantumCircuit, pulse
from qiskit.compiler import sequence, transpile, schedule
from qiskit.pulse.transforms import pad
from qiskit.providers.fake_provider import FakeParis
from qiskit.test import QiskitTestCase
class TestSequence(QiskitTestCase):
"""Test sequence function."""
def setUp(self):
super().setUp()
self.backend = FakeParis()
def test_sequence_empty(self):
self.assertEqual(sequence([], self.backend), [])
def test_transpile_and_sequence_agree_with_schedule(self):
qc = QuantumCircuit(2, name="bell")
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
sc = transpile(qc, self.backend, scheduling_method="alap")
actual = sequence(sc, self.backend)
expected = schedule(transpile(qc, self.backend), self.backend)
self.assertEqual(actual, pad(expected))
def test_transpile_and_sequence_agree_with_schedule_for_circuit_with_delay(self):
qc = QuantumCircuit(1, 1, name="t2")
qc.h(0)
qc.delay(500, 0, unit="ns")
qc.h(0)
qc.measure(0, 0)
sc = transpile(qc, self.backend, scheduling_method="alap")
actual = sequence(sc, self.backend)
expected = schedule(transpile(qc, self.backend), self.backend)
self.assertEqual(
actual.exclude(instruction_types=[pulse.Delay]),
expected.exclude(instruction_types=[pulse.Delay]),
)
@unittest.skip("not yet determined if delays on ancilla should be removed or not")
def test_transpile_and_sequence_agree_with_schedule_for_circuits_without_measures(self):
qc = QuantumCircuit(2, name="bell_without_measurement")
qc.h(0)
qc.cx(0, 1)
sc = transpile(qc, self.backend, scheduling_method="alap")
actual = sequence(sc, self.backend)
expected = schedule(transpile(qc, self.backend), self.backend)
self.assertEqual(actual, pad(expected))
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests basic functionality of the transpile function"""
import copy
import io
import math
import os
import sys
import unittest
from logging import StreamHandler, getLogger
from test import combine # pylint: disable=wrong-import-order
from unittest.mock import patch
import numpy as np
import rustworkx as rx
from ddt import data, ddt, unpack
from qiskit import BasicAer, ClassicalRegister, QuantumCircuit, QuantumRegister, pulse, qasm3, qpy
from qiskit.circuit import (
Clbit,
ControlFlowOp,
ForLoopOp,
Gate,
IfElseOp,
Parameter,
Qubit,
Reset,
SwitchCaseOp,
WhileLoopOp,
)
from qiskit.circuit.classical import expr
from qiskit.circuit.delay import Delay
from qiskit.circuit.library import (
CXGate,
CZGate,
HGate,
RXGate,
RYGate,
RZGate,
SXGate,
U1Gate,
U2Gate,
UGate,
XGate,
)
from qiskit.circuit.measure import Measure
from qiskit.compiler import transpile
from qiskit.converters import circuit_to_dag
from qiskit.dagcircuit import DAGOpNode, DAGOutNode
from qiskit.exceptions import QiskitError
from qiskit.providers.backend import BackendV2
from qiskit.providers.fake_provider import (
FakeBoeblingen,
FakeMelbourne,
FakeMumbaiV2,
FakeNairobiV2,
FakeRueschlikon,
FakeSherbrooke,
FakeVigo,
)
from qiskit.providers.options import Options
from qiskit.pulse import InstructionScheduleMap
from qiskit.quantum_info import Operator, random_unitary
from qiskit.test import QiskitTestCase, slow_test
from qiskit.tools import parallel
from qiskit.transpiler import CouplingMap, Layout, PassManager, TransformationPass
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.passes import BarrierBeforeFinalMeasurements, GateDirection, VF2PostLayout
from qiskit.transpiler.passmanager_config import PassManagerConfig
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager, level_0_pass_manager
from qiskit.transpiler.target import InstructionProperties, Target
class CustomCX(Gate):
"""Custom CX gate representation."""
def __init__(self):
super().__init__("custom_cx", 2, [])
def _define(self):
self._definition = QuantumCircuit(2)
self._definition.cx(0, 1)
def connected_qubits(physical: int, coupling_map: CouplingMap) -> set:
"""Get the physical qubits that have a connection to this one in the coupling map."""
for component in coupling_map.connected_components():
if physical in (qubits := set(component.graph.nodes())):
return qubits
raise ValueError(f"physical qubit {physical} is not in the coupling map")
@ddt
class TestTranspile(QiskitTestCase):
"""Test transpile function."""
def test_empty_transpilation(self):
"""Test that transpiling an empty list is a no-op. Regression test of gh-7287."""
self.assertEqual(transpile([]), [])
def test_pass_manager_none(self):
"""Test passing the default (None) pass manager to the transpiler.
It should perform the default qiskit flow:
unroll, swap_mapper, cx_direction, cx_cancellation, optimize_1q_gates
and should be equivalent to using tools.compile
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
coupling_map = [[1, 0]]
basis_gates = ["u1", "u2", "u3", "cx", "id"]
backend = BasicAer.get_backend("qasm_simulator")
circuit2 = transpile(
circuit,
backend=backend,
coupling_map=coupling_map,
basis_gates=basis_gates,
)
circuit3 = transpile(
circuit, backend=backend, coupling_map=coupling_map, basis_gates=basis_gates
)
self.assertEqual(circuit2, circuit3)
def test_transpile_basis_gates_no_backend_no_coupling_map(self):
"""Verify transpile() works with no coupling_map or backend."""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
basis_gates = ["u1", "u2", "u3", "cx", "id"]
circuit2 = transpile(circuit, basis_gates=basis_gates, optimization_level=0)
resources_after = circuit2.count_ops()
self.assertEqual({"u2": 2, "cx": 4}, resources_after)
def test_transpile_non_adjacent_layout(self):
"""Transpile pipeline can handle manual layout on non-adjacent qubits.
circuit:
.. parsed-literal::
βββββ
qr_0: β€ H ββββ ββββββββββββ -> 1
ββββββββ΄ββ
qr_1: ββββββ€ X ββββ βββββββ -> 2
ββββββββ΄ββ
qr_2: βββββββββββ€ X ββββ ββ -> 3
ββββββββ΄ββ
qr_3: ββββββββββββββββ€ X β -> 5
βββββ
device:
0 - 1 - 2 - 3 - 4 - 5 - 6
| | | | | |
13 - 12 - 11 - 10 - 9 - 8 - 7
"""
qr = QuantumRegister(4, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[2], qr[3])
coupling_map = FakeMelbourne().configuration().coupling_map
basis_gates = FakeMelbourne().configuration().basis_gates
initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]]
new_circuit = transpile(
circuit,
basis_gates=basis_gates,
coupling_map=coupling_map,
initial_layout=initial_layout,
)
qubit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qubits)}
for instruction in new_circuit.data:
if isinstance(instruction.operation, CXGate):
self.assertIn([qubit_indices[x] for x in instruction.qubits], coupling_map)
def test_transpile_qft_grid(self):
"""Transpile pipeline can handle 8-qubit QFT on 14-qubit grid."""
qr = QuantumRegister(8)
circuit = QuantumCircuit(qr)
for i, _ in enumerate(qr):
for j in range(i):
circuit.cp(math.pi / float(2 ** (i - j)), qr[i], qr[j])
circuit.h(qr[i])
coupling_map = FakeMelbourne().configuration().coupling_map
basis_gates = FakeMelbourne().configuration().basis_gates
new_circuit = transpile(circuit, basis_gates=basis_gates, coupling_map=coupling_map)
qubit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qubits)}
for instruction in new_circuit.data:
if isinstance(instruction.operation, CXGate):
self.assertIn([qubit_indices[x] for x in instruction.qubits], coupling_map)
def test_already_mapped_1(self):
"""Circuit not remapped if matches topology.
See: https://github.com/Qiskit/qiskit-terra/issues/342
"""
backend = FakeRueschlikon()
coupling_map = backend.configuration().coupling_map
basis_gates = backend.configuration().basis_gates
qr = QuantumRegister(16, "qr")
cr = ClassicalRegister(16, "cr")
qc = QuantumCircuit(qr, cr)
qc.cx(qr[3], qr[14])
qc.cx(qr[5], qr[4])
qc.h(qr[9])
qc.cx(qr[9], qr[8])
qc.x(qr[11])
qc.cx(qr[3], qr[4])
qc.cx(qr[12], qr[11])
qc.cx(qr[13], qr[4])
qc.measure(qr, cr)
new_qc = transpile(
qc,
coupling_map=coupling_map,
basis_gates=basis_gates,
initial_layout=Layout.generate_trivial_layout(qr),
)
qubit_indices = {bit: idx for idx, bit in enumerate(new_qc.qubits)}
cx_qubits = [instr.qubits for instr in new_qc.data if instr.operation.name == "cx"]
cx_qubits_physical = [
[qubit_indices[ctrl], qubit_indices[tgt]] for [ctrl, tgt] in cx_qubits
]
self.assertEqual(
sorted(cx_qubits_physical), [[3, 4], [3, 14], [5, 4], [9, 8], [12, 11], [13, 4]]
)
def test_already_mapped_via_layout(self):
"""Test that a manual layout that satisfies a coupling map does not get altered.
See: https://github.com/Qiskit/qiskit-terra/issues/2036
circuit:
.. parsed-literal::
βββββ βββββ β βββ
qn_0: β€ H ββββ βββββββββββββ βββ€ H βββββ€Mββββ -> 9
βββββ β β βββββ β ββ₯β
qn_1: ββββββββΌβββββββββββββΌββββββββββββ«ββββ -> 6
β β β β
qn_2: ββββββββΌβββββββββββββΌββββββββββββ«ββββ -> 5
β β β β
qn_3: ββββββββΌβββββββββββββΌββββββββββββ«ββββ -> 0
β β β β
qn_4: ββββββββΌβββββββββββββΌββββββββββββ«ββββ -> 1
ββββββββ΄βββββββββββββ΄βββββββ β β βββ
qn_5: β€ H ββ€ X ββ€ P(2) ββ€ X ββ€ H ββββββ«ββ€Mβ -> 4
ββββββββββββββββββββββββββββ β β ββ₯β
cn: 2/βββββββββββββββββββββββββββββββββ©βββ©β
0 1
device:
0 -- 1 -- 2 -- 3 -- 4
| |
5 -- 6 -- 7 -- 8 -- 9
| |
10 - 11 - 12 - 13 - 14
| |
15 - 16 - 17 - 18 - 19
"""
basis_gates = ["u1", "u2", "u3", "cx", "id"]
coupling_map = [
[0, 1],
[0, 5],
[1, 0],
[1, 2],
[2, 1],
[2, 3],
[3, 2],
[3, 4],
[4, 3],
[4, 9],
[5, 0],
[5, 6],
[5, 10],
[6, 5],
[6, 7],
[7, 6],
[7, 8],
[7, 12],
[8, 7],
[8, 9],
[9, 4],
[9, 8],
[9, 14],
[10, 5],
[10, 11],
[10, 15],
[11, 10],
[11, 12],
[12, 7],
[12, 11],
[12, 13],
[13, 12],
[13, 14],
[14, 9],
[14, 13],
[14, 19],
[15, 10],
[15, 16],
[16, 15],
[16, 17],
[17, 16],
[17, 18],
[18, 17],
[18, 19],
[19, 14],
[19, 18],
]
q = QuantumRegister(6, name="qn")
c = ClassicalRegister(2, name="cn")
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.h(q[5])
qc.cx(q[0], q[5])
qc.p(2, q[5])
qc.cx(q[0], q[5])
qc.h(q[0])
qc.h(q[5])
qc.barrier(q)
qc.measure(q[0], c[0])
qc.measure(q[5], c[1])
initial_layout = [
q[3],
q[4],
None,
None,
q[5],
q[2],
q[1],
None,
None,
q[0],
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
]
new_qc = transpile(
qc, coupling_map=coupling_map, basis_gates=basis_gates, initial_layout=initial_layout
)
qubit_indices = {bit: idx for idx, bit in enumerate(new_qc.qubits)}
cx_qubits = [instr.qubits for instr in new_qc.data if instr.operation.name == "cx"]
cx_qubits_physical = [
[qubit_indices[ctrl], qubit_indices[tgt]] for [ctrl, tgt] in cx_qubits
]
self.assertEqual(sorted(cx_qubits_physical), [[9, 4], [9, 4]])
def test_transpile_bell(self):
"""Test Transpile Bell.
If all correct some should exists.
"""
backend = BasicAer.get_backend("qasm_simulator")
qubit_reg = QuantumRegister(2, name="q")
clbit_reg = ClassicalRegister(2, name="c")
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
circuits = transpile(qc, backend)
self.assertIsInstance(circuits, QuantumCircuit)
def test_transpile_one(self):
"""Test transpile a single circuit.
Check that the top-level `transpile` function returns
a single circuit."""
backend = BasicAer.get_backend("qasm_simulator")
qubit_reg = QuantumRegister(2)
clbit_reg = ClassicalRegister(2)
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
circuit = transpile(qc, backend)
self.assertIsInstance(circuit, QuantumCircuit)
def test_transpile_two(self):
"""Test transpile two circuits.
Check that the transpiler returns a list of two circuits.
"""
backend = BasicAer.get_backend("qasm_simulator")
qubit_reg = QuantumRegister(2)
clbit_reg = ClassicalRegister(2)
qubit_reg2 = QuantumRegister(2)
clbit_reg2 = ClassicalRegister(2)
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
qc_extra = QuantumCircuit(qubit_reg, qubit_reg2, clbit_reg, clbit_reg2, name="extra")
qc_extra.measure(qubit_reg, clbit_reg)
circuits = transpile([qc, qc_extra], backend)
self.assertIsInstance(circuits, list)
self.assertEqual(len(circuits), 2)
for circuit in circuits:
self.assertIsInstance(circuit, QuantumCircuit)
def test_transpile_singleton(self):
"""Test transpile a single-element list with a circuit.
Check that `transpile` returns a single-element list.
See https://github.com/Qiskit/qiskit-terra/issues/5260
"""
backend = BasicAer.get_backend("qasm_simulator")
qubit_reg = QuantumRegister(2)
clbit_reg = ClassicalRegister(2)
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
circuits = transpile([qc], backend)
self.assertIsInstance(circuits, list)
self.assertEqual(len(circuits), 1)
self.assertIsInstance(circuits[0], QuantumCircuit)
def test_mapping_correction(self):
"""Test mapping works in previous failed case."""
backend = FakeRueschlikon()
qr = QuantumRegister(name="qr", size=11)
cr = ClassicalRegister(name="qc", size=11)
circuit = QuantumCircuit(qr, cr)
circuit.u(1.564784764685993, -1.2378965763410095, 2.9746763177861713, qr[3])
circuit.u(1.2269835563676523, 1.1932982847014162, -1.5597357740824318, qr[5])
circuit.cx(qr[5], qr[3])
circuit.p(0.856768317675967, qr[3])
circuit.u(-3.3911273825190915, 0.0, 0.0, qr[5])
circuit.cx(qr[3], qr[5])
circuit.u(2.159209321625547, 0.0, 0.0, qr[5])
circuit.cx(qr[5], qr[3])
circuit.u(0.30949966910232335, 1.1706201763833217, 1.738408691990081, qr[3])
circuit.u(1.9630571407274755, -0.6818742967975088, 1.8336534616728195, qr[5])
circuit.u(1.330181833806101, 0.6003162754946363, -3.181264980452862, qr[7])
circuit.u(0.4885914820775024, 3.133297443244865, -2.794457469189904, qr[8])
circuit.cx(qr[8], qr[7])
circuit.p(2.2196187596178616, qr[7])
circuit.u(-3.152367609631023, 0.0, 0.0, qr[8])
circuit.cx(qr[7], qr[8])
circuit.u(1.2646005789809263, 0.0, 0.0, qr[8])
circuit.cx(qr[8], qr[7])
circuit.u(0.7517780502091939, 1.2828514296564781, 1.6781179605443775, qr[7])
circuit.u(0.9267400575390405, 2.0526277839695153, 2.034202361069533, qr[8])
circuit.u(2.550304293455634, 3.8250017126569698, -2.1351609599720054, qr[1])
circuit.u(0.9566260876600556, -1.1147561503064538, 2.0571590492298797, qr[4])
circuit.cx(qr[4], qr[1])
circuit.p(2.1899329069137394, qr[1])
circuit.u(-1.8371715243173294, 0.0, 0.0, qr[4])
circuit.cx(qr[1], qr[4])
circuit.u(0.4717053496327104, 0.0, 0.0, qr[4])
circuit.cx(qr[4], qr[1])
circuit.u(2.3167620677708145, -1.2337330260253256, -0.5671322899563955, qr[1])
circuit.u(1.0468499525240678, 0.8680750644809365, -1.4083720073192485, qr[4])
circuit.u(2.4204244021892807, -2.211701932616922, 3.8297006565735883, qr[10])
circuit.u(0.36660280497727255, 3.273119149343493, -1.8003362351299388, qr[6])
circuit.cx(qr[6], qr[10])
circuit.p(1.067395863586385, qr[10])
circuit.u(-0.7044917541291232, 0.0, 0.0, qr[6])
circuit.cx(qr[10], qr[6])
circuit.u(2.1830003849921527, 0.0, 0.0, qr[6])
circuit.cx(qr[6], qr[10])
circuit.u(2.1538343756723917, 2.2653381826084606, -3.550087952059485, qr[10])
circuit.u(1.307627685019188, -0.44686656993522567, -2.3238098554327418, qr[6])
circuit.u(2.2046797998462906, 0.9732961754855436, 1.8527865921467421, qr[9])
circuit.u(2.1665254613904126, -1.281337664694577, -1.2424905413631209, qr[0])
circuit.cx(qr[0], qr[9])
circuit.p(2.6209599970201007, qr[9])
circuit.u(0.04680566321901303, 0.0, 0.0, qr[0])
circuit.cx(qr[9], qr[0])
circuit.u(1.7728411151289603, 0.0, 0.0, qr[0])
circuit.cx(qr[0], qr[9])
circuit.u(2.4866395967434443, 0.48684511243566697, -3.0069186877854728, qr[9])
circuit.u(1.7369112924273789, -4.239660866163805, 1.0623389015296005, qr[0])
circuit.barrier(qr)
circuit.measure(qr, cr)
circuits = transpile(circuit, backend)
self.assertIsInstance(circuits, QuantumCircuit)
def test_transpiler_layout_from_intlist(self):
"""A list of ints gives layout to correctly map circuit.
virtual physical
q1_0 - 4 ---[H]---
q2_0 - 5
q2_1 - 6 ---[H]---
q3_0 - 8
q3_1 - 9
q3_2 - 10 ---[H]---
"""
qr1 = QuantumRegister(1, "qr1")
qr2 = QuantumRegister(2, "qr2")
qr3 = QuantumRegister(3, "qr3")
qc = QuantumCircuit(qr1, qr2, qr3)
qc.h(qr1[0])
qc.h(qr2[1])
qc.h(qr3[2])
layout = [4, 5, 6, 8, 9, 10]
cmap = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
new_circ = transpile(
qc, backend=None, coupling_map=cmap, basis_gates=["u2"], initial_layout=layout
)
qubit_indices = {bit: idx for idx, bit in enumerate(new_circ.qubits)}
mapped_qubits = []
for instruction in new_circ.data:
mapped_qubits.append(qubit_indices[instruction.qubits[0]])
self.assertEqual(mapped_qubits, [4, 6, 10])
def test_mapping_multi_qreg(self):
"""Test mapping works for multiple qregs."""
backend = FakeRueschlikon()
qr = QuantumRegister(3, name="qr")
qr2 = QuantumRegister(1, name="qr2")
qr3 = QuantumRegister(4, name="qr3")
cr = ClassicalRegister(3, name="cr")
qc = QuantumCircuit(qr, qr2, qr3, cr)
qc.h(qr[0])
qc.cx(qr[0], qr2[0])
qc.cx(qr[1], qr3[2])
qc.measure(qr, cr)
circuits = transpile(qc, backend)
self.assertIsInstance(circuits, QuantumCircuit)
def test_transpile_circuits_diff_registers(self):
"""Transpile list of circuits with different qreg names."""
backend = FakeRueschlikon()
circuits = []
for _ in range(2):
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.measure(qr, cr)
circuits.append(circuit)
circuits = transpile(circuits, backend)
self.assertIsInstance(circuits[0], QuantumCircuit)
def test_wrong_initial_layout(self):
"""Test transpile with a bad initial layout."""
backend = FakeMelbourne()
qubit_reg = QuantumRegister(2, name="q")
clbit_reg = ClassicalRegister(2, name="c")
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
bad_initial_layout = [
QuantumRegister(3, "q")[0],
QuantumRegister(3, "q")[1],
QuantumRegister(3, "q")[2],
]
with self.assertRaises(TranspilerError):
transpile(qc, backend, initial_layout=bad_initial_layout)
def test_parameterized_circuit_for_simulator(self):
"""Verify that a parameterized circuit can be transpiled for a simulator backend."""
qr = QuantumRegister(2, name="qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.rz(theta, qr[0])
transpiled_qc = transpile(qc, backend=BasicAer.get_backend("qasm_simulator"))
expected_qc = QuantumCircuit(qr)
expected_qc.append(RZGate(theta), [qr[0]])
self.assertEqual(expected_qc, transpiled_qc)
def test_parameterized_circuit_for_device(self):
"""Verify that a parameterized circuit can be transpiled for a device backend."""
qr = QuantumRegister(2, name="qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.rz(theta, qr[0])
transpiled_qc = transpile(
qc, backend=FakeMelbourne(), initial_layout=Layout.generate_trivial_layout(qr)
)
qr = QuantumRegister(14, "q")
expected_qc = QuantumCircuit(qr, global_phase=-1 * theta / 2.0)
expected_qc.append(U1Gate(theta), [qr[0]])
self.assertEqual(expected_qc, transpiled_qc)
def test_parameter_expression_circuit_for_simulator(self):
"""Verify that a circuit including expressions of parameters can be
transpiled for a simulator backend."""
qr = QuantumRegister(2, name="qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
square = theta * theta
qc.rz(square, qr[0])
transpiled_qc = transpile(qc, backend=BasicAer.get_backend("qasm_simulator"))
expected_qc = QuantumCircuit(qr)
expected_qc.append(RZGate(square), [qr[0]])
self.assertEqual(expected_qc, transpiled_qc)
def test_parameter_expression_circuit_for_device(self):
"""Verify that a circuit including expressions of parameters can be
transpiled for a device backend."""
qr = QuantumRegister(2, name="qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
square = theta * theta
qc.rz(square, qr[0])
transpiled_qc = transpile(
qc, backend=FakeMelbourne(), initial_layout=Layout.generate_trivial_layout(qr)
)
qr = QuantumRegister(14, "q")
expected_qc = QuantumCircuit(qr, global_phase=-1 * square / 2.0)
expected_qc.append(U1Gate(square), [qr[0]])
self.assertEqual(expected_qc, transpiled_qc)
def test_final_measurement_barrier_for_devices(self):
"""Verify BarrierBeforeFinalMeasurements pass is called in default pipeline for devices."""
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "example.qasm"))
layout = Layout.generate_trivial_layout(*circ.qregs)
orig_pass = BarrierBeforeFinalMeasurements()
with patch.object(BarrierBeforeFinalMeasurements, "run", wraps=orig_pass.run) as mock_pass:
transpile(
circ,
coupling_map=FakeRueschlikon().configuration().coupling_map,
initial_layout=layout,
)
self.assertTrue(mock_pass.called)
def test_do_not_run_gatedirection_with_symmetric_cm(self):
"""When the coupling map is symmetric, do not run GateDirection."""
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "example.qasm"))
layout = Layout.generate_trivial_layout(*circ.qregs)
coupling_map = []
for node1, node2 in FakeRueschlikon().configuration().coupling_map:
coupling_map.append([node1, node2])
coupling_map.append([node2, node1])
orig_pass = GateDirection(CouplingMap(coupling_map))
with patch.object(GateDirection, "run", wraps=orig_pass.run) as mock_pass:
transpile(circ, coupling_map=coupling_map, initial_layout=layout)
self.assertFalse(mock_pass.called)
def test_optimize_to_nothing(self):
"""Optimize gates up to fixed point in the default pipeline
See https://github.com/Qiskit/qiskit-terra/issues/2035
"""
# βββββ βββββββββββββββ βββββ
# q0_0: β€ H ββββ βββ€ X ββ€ Y ββ€ Z ββββ βββ€ H ββββ βββββ ββ
# ββββββββ΄ββββββββββββββββββββ΄ββββββββββ΄βββββ΄ββ
# q0_1: ββββββ€ X βββββββββββββββββ€ X βββββββ€ X ββ€ X β
# βββββ βββββ ββββββββββ
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.x(qr[0])
circ.y(qr[0])
circ.z(qr[0])
circ.cx(qr[0], qr[1])
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.cx(qr[0], qr[1])
after = transpile(circ, coupling_map=[[0, 1], [1, 0]], basis_gates=["u3", "u2", "u1", "cx"])
expected = QuantumCircuit(QuantumRegister(2, "q"), global_phase=-np.pi / 2)
msg = f"after:\n{after}\nexpected:\n{expected}"
self.assertEqual(after, expected, msg=msg)
def test_pass_manager_empty(self):
"""Test passing an empty PassManager() to the transpiler.
It should perform no transformations on the circuit.
"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
resources_before = circuit.count_ops()
pass_manager = PassManager()
out_circuit = pass_manager.run(circuit)
resources_after = out_circuit.count_ops()
self.assertDictEqual(resources_before, resources_after)
def test_move_measurements(self):
"""Measurements applied AFTER swap mapping."""
backend = FakeRueschlikon()
cmap = backend.configuration().coupling_map
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "move_measurements.qasm"))
lay = [0, 1, 15, 2, 14, 3, 13, 4, 12, 5, 11, 6]
out = transpile(circ, initial_layout=lay, coupling_map=cmap, routing_method="stochastic")
out_dag = circuit_to_dag(out)
meas_nodes = out_dag.named_nodes("measure")
for meas_node in meas_nodes:
is_last_measure = all(
isinstance(after_measure, DAGOutNode)
for after_measure in out_dag.quantum_successors(meas_node)
)
self.assertTrue(is_last_measure)
@data(0, 1, 2, 3)
def test_init_resets_kept_preset_passmanagers(self, optimization_level):
"""Test initial resets kept at all preset transpilation levels"""
num_qubits = 5
qc = QuantumCircuit(num_qubits)
qc.reset(range(num_qubits))
num_resets = transpile(qc, optimization_level=optimization_level).count_ops()["reset"]
self.assertEqual(num_resets, num_qubits)
@data(0, 1, 2, 3)
def test_initialize_reset_is_not_removed(self, optimization_level):
"""The reset in front of initializer should NOT be removed at beginning"""
qr = QuantumRegister(1, "qr")
qc = QuantumCircuit(qr)
qc.initialize([1.0 / math.sqrt(2), 1.0 / math.sqrt(2)], [qr[0]])
qc.initialize([1.0 / math.sqrt(2), -1.0 / math.sqrt(2)], [qr[0]])
after = transpile(qc, basis_gates=["reset", "u3"], optimization_level=optimization_level)
self.assertEqual(after.count_ops()["reset"], 2, msg=f"{after}\n does not have 2 resets.")
def test_initialize_FakeMelbourne(self):
"""Test that the zero-state resets are remove in a device not supporting them."""
desired_vector = [1 / math.sqrt(2), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(2)]
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1], qr[2]])
out = transpile(qc, backend=FakeMelbourne())
out_dag = circuit_to_dag(out)
reset_nodes = out_dag.named_nodes("reset")
self.assertEqual(len(reset_nodes), 3)
def test_non_standard_basis(self):
"""Test a transpilation with a non-standard basis"""
qr1 = QuantumRegister(1, "q1")
qr2 = QuantumRegister(2, "q2")
qr3 = QuantumRegister(3, "q3")
qc = QuantumCircuit(qr1, qr2, qr3)
qc.h(qr1[0])
qc.h(qr2[1])
qc.h(qr3[2])
layout = [4, 5, 6, 8, 9, 10]
cmap = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
circuit = transpile(
qc, backend=None, coupling_map=cmap, basis_gates=["h"], initial_layout=layout
)
dag_circuit = circuit_to_dag(circuit)
resources_after = dag_circuit.count_ops()
self.assertEqual({"h": 3}, resources_after)
def test_hadamard_to_rot_gates(self):
"""Test a transpilation from H to Rx, Ry gates"""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.h(0)
expected = QuantumCircuit(qr, global_phase=np.pi / 2)
expected.append(RYGate(theta=np.pi / 2), [0])
expected.append(RXGate(theta=np.pi), [0])
circuit = transpile(qc, basis_gates=["rx", "ry"], optimization_level=0)
self.assertEqual(circuit, expected)
def test_basis_subset(self):
"""Test a transpilation with a basis subset of the standard basis"""
qr = QuantumRegister(1, "q1")
qc = QuantumCircuit(qr)
qc.h(qr[0])
qc.x(qr[0])
qc.t(qr[0])
layout = [4]
cmap = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
circuit = transpile(
qc, backend=None, coupling_map=cmap, basis_gates=["u3"], initial_layout=layout
)
dag_circuit = circuit_to_dag(circuit)
resources_after = dag_circuit.count_ops()
self.assertEqual({"u3": 1}, resources_after)
def test_check_circuit_width(self):
"""Verify transpilation of circuit with virtual qubits greater than
physical qubits raises error"""
cmap = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
qc = QuantumCircuit(15, 15)
with self.assertRaises(TranspilerError):
transpile(qc, coupling_map=cmap)
@data(0, 1, 2, 3)
def test_ccx_routing_method_none(self, optimization_level):
"""CCX without routing method."""
qc = QuantumCircuit(3)
qc.cx(0, 1)
qc.cx(1, 2)
out = transpile(
qc,
routing_method="none",
basis_gates=["u", "cx"],
initial_layout=[0, 1, 2],
seed_transpiler=0,
coupling_map=[[0, 1], [1, 2]],
optimization_level=optimization_level,
)
self.assertTrue(Operator(qc).equiv(out))
@data(0, 1, 2, 3)
def test_ccx_routing_method_none_failed(self, optimization_level):
"""CCX without routing method cannot be routed."""
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
with self.assertRaises(TranspilerError):
transpile(
qc,
routing_method="none",
basis_gates=["u", "cx"],
initial_layout=[0, 1, 2],
seed_transpiler=0,
coupling_map=[[0, 1], [1, 2]],
optimization_level=optimization_level,
)
@data(0, 1, 2, 3)
def test_ms_unrolls_to_cx(self, optimization_level):
"""Verify a Rx,Ry,Rxx circuit transpile to a U3,CX target."""
qc = QuantumCircuit(2)
qc.rx(math.pi / 2, 0)
qc.ry(math.pi / 4, 1)
qc.rxx(math.pi / 4, 0, 1)
out = transpile(qc, basis_gates=["u3", "cx"], optimization_level=optimization_level)
self.assertTrue(Operator(qc).equiv(out))
@data(0, 1, 2, 3)
def test_ms_can_target_ms(self, optimization_level):
"""Verify a Rx,Ry,Rxx circuit can transpile to an Rx,Ry,Rxx target."""
qc = QuantumCircuit(2)
qc.rx(math.pi / 2, 0)
qc.ry(math.pi / 4, 1)
qc.rxx(math.pi / 4, 0, 1)
out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level)
self.assertTrue(Operator(qc).equiv(out))
@data(0, 1, 2, 3)
def test_cx_can_target_ms(self, optimization_level):
"""Verify a U3,CX circuit can transpiler to a Rx,Ry,Rxx target."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.rz(math.pi / 4, [0, 1])
out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level)
self.assertTrue(Operator(qc).equiv(out))
@data(0, 1, 2, 3)
def test_measure_doesnt_unroll_ms(self, optimization_level):
"""Verify a measure doesn't cause an Rx,Ry,Rxx circuit to unroll to U3,CX."""
qc = QuantumCircuit(2, 2)
qc.rx(math.pi / 2, 0)
qc.ry(math.pi / 4, 1)
qc.rxx(math.pi / 4, 0, 1)
qc.measure([0, 1], [0, 1])
out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level)
self.assertEqual(qc, out)
@data(
["cx", "u3"],
["cz", "u3"],
["cz", "rx", "rz"],
["rxx", "rx", "ry"],
["iswap", "rx", "rz"],
)
def test_block_collection_runs_for_non_cx_bases(self, basis_gates):
"""Verify block collection is run when a single two qubit gate is in the basis."""
twoq_gate, *_ = basis_gates
qc = QuantumCircuit(2)
qc.cx(0, 1)
qc.cx(1, 0)
qc.cx(0, 1)
qc.cx(0, 1)
out = transpile(qc, basis_gates=basis_gates, optimization_level=3)
self.assertLessEqual(out.count_ops()[twoq_gate], 2)
@unpack
@data(
(["u3", "cx"], {"u3": 1, "cx": 1}),
(["rx", "rz", "iswap"], {"rx": 6, "rz": 12, "iswap": 2}),
(["rx", "ry", "rxx"], {"rx": 6, "ry": 5, "rxx": 1}),
)
def test_block_collection_reduces_1q_gate(self, basis_gates, gate_counts):
"""For synthesis to non-U3 bases, verify we minimize 1q gates."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
out = transpile(qc, basis_gates=basis_gates, optimization_level=3)
self.assertTrue(Operator(out).equiv(qc))
self.assertTrue(set(out.count_ops()).issubset(basis_gates))
for basis_gate in basis_gates:
self.assertLessEqual(out.count_ops()[basis_gate], gate_counts[basis_gate])
@combine(
optimization_level=[0, 1, 2, 3],
basis_gates=[
["u3", "cx"],
["rx", "rz", "iswap"],
["rx", "ry", "rxx"],
],
)
def test_translation_method_synthesis(self, optimization_level, basis_gates):
"""Verify translation_method='synthesis' gets to the basis."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
out = transpile(
qc,
translation_method="synthesis",
basis_gates=basis_gates,
optimization_level=optimization_level,
)
self.assertTrue(Operator(out).equiv(qc))
self.assertTrue(set(out.count_ops()).issubset(basis_gates))
def test_transpiled_custom_gates_calibration(self):
"""Test if transpiled calibrations is equal to custom gates circuit calibrations."""
custom_180 = Gate("mycustom", 1, [3.14])
custom_90 = Gate("mycustom", 1, [1.57])
circ = QuantumCircuit(2)
circ.append(custom_180, [0])
circ.append(custom_90, [1])
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
with pulse.build() as q1_y90:
pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), pulse.DriveChannel(1))
# Add calibration
circ.add_calibration(custom_180, [0], q0_x180)
circ.add_calibration(custom_90, [1], q1_y90)
backend = FakeBoeblingen()
transpiled_circuit = transpile(
circ,
backend=backend,
layout_method="trivial",
)
self.assertEqual(transpiled_circuit.calibrations, circ.calibrations)
self.assertEqual(list(transpiled_circuit.count_ops().keys()), ["mycustom"])
self.assertEqual(list(transpiled_circuit.count_ops().values()), [2])
def test_transpiled_basis_gates_calibrations(self):
"""Test if the transpiled calibrations is equal to basis gates circuit calibrations."""
circ = QuantumCircuit(2)
circ.h(0)
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
# Add calibration
circ.add_calibration("h", [0], q0_x180)
backend = FakeBoeblingen()
transpiled_circuit = transpile(
circ,
backend=backend,
)
self.assertEqual(transpiled_circuit.calibrations, circ.calibrations)
def test_transpile_calibrated_custom_gate_on_diff_qubit(self):
"""Test if the custom, non calibrated gate raises QiskitError."""
custom_180 = Gate("mycustom", 1, [3.14])
circ = QuantumCircuit(2)
circ.append(custom_180, [0])
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
# Add calibration
circ.add_calibration(custom_180, [1], q0_x180)
backend = FakeBoeblingen()
with self.assertRaises(QiskitError):
transpile(circ, backend=backend, layout_method="trivial")
def test_transpile_calibrated_nonbasis_gate_on_diff_qubit(self):
"""Test if the non-basis gates are transpiled if they are on different qubit that
is not calibrated."""
circ = QuantumCircuit(2)
circ.h(0)
circ.h(1)
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
# Add calibration
circ.add_calibration("h", [1], q0_x180)
backend = FakeBoeblingen()
transpiled_circuit = transpile(
circ,
backend=backend,
)
self.assertEqual(transpiled_circuit.calibrations, circ.calibrations)
self.assertEqual(set(transpiled_circuit.count_ops().keys()), {"u2", "h"})
def test_transpile_subset_of_calibrated_gates(self):
"""Test transpiling a circuit with both basis gate (not-calibrated) and
a calibrated gate on different qubits."""
x_180 = Gate("mycustom", 1, [3.14])
circ = QuantumCircuit(2)
circ.h(0)
circ.append(x_180, [0])
circ.h(1)
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
circ.add_calibration(x_180, [0], q0_x180)
circ.add_calibration("h", [1], q0_x180) # 'h' is calibrated on qubit 1
transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial")
self.assertEqual(set(transpiled_circ.count_ops().keys()), {"u2", "mycustom", "h"})
def test_parameterized_calibrations_transpile(self):
"""Check that gates can be matched to their calibrations before and after parameter
assignment."""
tau = Parameter("tau")
circ = QuantumCircuit(3, 3)
circ.append(Gate("rxt", 1, [2 * 3.14 * tau]), [0])
def q0_rxt(tau):
with pulse.build() as q0_rxt:
pulse.play(pulse.library.Gaussian(20, 0.4 * tau, 3.0), pulse.DriveChannel(0))
return q0_rxt
circ.add_calibration("rxt", [0], q0_rxt(tau), [2 * 3.14 * tau])
transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial")
self.assertEqual(set(transpiled_circ.count_ops().keys()), {"rxt"})
circ = circ.assign_parameters({tau: 1})
transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial")
self.assertEqual(set(transpiled_circ.count_ops().keys()), {"rxt"})
def test_inst_durations_from_calibrations(self):
"""Test that circuit calibrations can be used instead of explicitly
supplying inst_durations.
"""
qc = QuantumCircuit(2)
qc.append(Gate("custom", 1, []), [0])
with pulse.build() as cal:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
qc.add_calibration("custom", [0], cal)
out = transpile(qc, scheduling_method="alap")
self.assertEqual(out.duration, cal.duration)
@data(0, 1, 2, 3)
def test_multiqubit_gates_calibrations(self, opt_level):
"""Test multiqubit gate > 2q with calibrations works
Adapted from issue description in https://github.com/Qiskit/qiskit-terra/issues/6572
"""
circ = QuantumCircuit(5)
custom_gate = Gate("my_custom_gate", 5, [])
circ.append(custom_gate, [0, 1, 2, 3, 4])
circ.measure_all()
backend = FakeBoeblingen()
with pulse.build(backend, name="custom") as my_schedule:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(1)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(2)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(3)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(4)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(1)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(2)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(3)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(4)
)
circ.add_calibration("my_custom_gate", [0, 1, 2, 3, 4], my_schedule, [])
trans_circ = transpile(circ, backend, optimization_level=opt_level, layout_method="trivial")
self.assertEqual({"measure": 5, "my_custom_gate": 1, "barrier": 1}, trans_circ.count_ops())
@data(0, 1, 2, 3)
def test_circuit_with_delay(self, optimization_level):
"""Verify a circuit with delay can transpile to a scheduled circuit."""
qc = QuantumCircuit(2)
qc.h(0)
qc.delay(500, 1)
qc.cx(0, 1)
out = transpile(
qc,
scheduling_method="alap",
basis_gates=["h", "cx"],
instruction_durations=[("h", 0, 200), ("cx", [0, 1], 700)],
optimization_level=optimization_level,
)
self.assertEqual(out.duration, 1200)
def test_delay_converts_to_dt(self):
"""Test that a delay instruction is converted to units of dt given a backend."""
qc = QuantumCircuit(2)
qc.delay(1000, [0], unit="us")
backend = FakeRueschlikon()
backend.configuration().dt = 0.5e-6
out = transpile([qc, qc], backend)
self.assertEqual(out[0].data[0].operation.unit, "dt")
self.assertEqual(out[1].data[0].operation.unit, "dt")
out = transpile(qc, dt=1e-9)
self.assertEqual(out.data[0].operation.unit, "dt")
def test_scheduling_backend_v2(self):
"""Test that scheduling method works with Backendv2."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
backend = FakeMumbaiV2()
out = transpile([qc, qc], backend, scheduling_method="alap")
self.assertIn("delay", out[0].count_ops())
self.assertIn("delay", out[1].count_ops())
@data(1, 2, 3)
def test_no_infinite_loop(self, optimization_level):
"""Verify circuit cost always descends and optimization does not flip flop indefinitely."""
qc = QuantumCircuit(1)
qc.ry(0.2, 0)
out = transpile(
qc, basis_gates=["id", "p", "sx", "cx"], optimization_level=optimization_level
)
# Expect a -pi/2 global phase for the U3 to RZ/SX conversion, and
# a -0.5 * theta phase for RZ to P twice, once at theta, and once at 3 pi
# for the second and third RZ gates in the U3 decomposition.
expected = QuantumCircuit(
1, global_phase=-np.pi / 2 - 0.5 * (-0.2 + np.pi) - 0.5 * 3 * np.pi
)
expected.p(-np.pi, 0)
expected.sx(0)
expected.p(np.pi - 0.2, 0)
expected.sx(0)
error_message = (
f"\nOutput circuit:\n{out!s}\n{Operator(out).data}\n"
f"Expected circuit:\n{expected!s}\n{Operator(expected).data}"
)
self.assertEqual(out, expected, error_message)
@data(0, 1, 2, 3)
def test_transpile_preserves_circuit_metadata(self, optimization_level):
"""Verify that transpile preserves circuit metadata in the output."""
circuit = QuantumCircuit(2, metadata={"experiment_id": "1234", "execution_number": 4})
circuit.h(0)
circuit.cx(0, 1)
cmap = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
res = transpile(
circuit,
basis_gates=["id", "p", "sx", "cx"],
coupling_map=cmap,
optimization_level=optimization_level,
)
self.assertEqual(circuit.metadata, res.metadata)
@data(0, 1, 2, 3)
def test_transpile_optional_registers(self, optimization_level):
"""Verify transpile accepts circuits without registers end-to-end."""
qubits = [Qubit() for _ in range(3)]
clbits = [Clbit() for _ in range(3)]
qc = QuantumCircuit(qubits, clbits)
qc.h(0)
qc.cx(0, 1)
qc.cx(1, 2)
qc.measure(qubits, clbits)
out = transpile(qc, FakeBoeblingen(), optimization_level=optimization_level)
self.assertEqual(len(out.qubits), FakeBoeblingen().configuration().num_qubits)
self.assertEqual(len(out.clbits), len(clbits))
@data(0, 1, 2, 3)
def test_translate_ecr_basis(self, optimization_level):
"""Verify that rewriting in ECR basis is efficient."""
circuit = QuantumCircuit(2)
circuit.append(random_unitary(4, seed=1), [0, 1])
circuit.barrier()
circuit.cx(0, 1)
circuit.barrier()
circuit.swap(0, 1)
circuit.barrier()
circuit.iswap(0, 1)
res = transpile(circuit, basis_gates=["u", "ecr"], optimization_level=optimization_level)
self.assertEqual(res.count_ops()["ecr"], 9)
self.assertTrue(Operator(res).equiv(circuit))
def test_optimize_ecr_basis(self):
"""Test highest optimization level can optimize over ECR."""
circuit = QuantumCircuit(2)
circuit.swap(1, 0)
circuit.iswap(0, 1)
res = transpile(circuit, basis_gates=["u", "ecr"], optimization_level=3)
self.assertEqual(res.count_ops()["ecr"], 1)
self.assertTrue(Operator(res).equiv(circuit))
def test_approximation_degree_invalid(self):
"""Test invalid approximation degree raises."""
circuit = QuantumCircuit(2)
circuit.swap(0, 1)
with self.assertRaises(QiskitError):
transpile(circuit, basis_gates=["u", "cz"], approximation_degree=1.1)
def test_approximation_degree(self):
"""Test more approximation gives lower-cost circuit."""
circuit = QuantumCircuit(2)
circuit.swap(0, 1)
circuit.h(0)
circ_10 = transpile(
circuit,
basis_gates=["u", "cx"],
translation_method="synthesis",
approximation_degree=0.1,
)
circ_90 = transpile(
circuit,
basis_gates=["u", "cx"],
translation_method="synthesis",
approximation_degree=0.9,
)
self.assertLess(circ_10.depth(), circ_90.depth())
@data(0, 1, 2, 3)
def test_synthesis_translation_method_with_single_qubit_gates(self, optimization_level):
"""Test that synthesis basis translation works for solely 1q circuit"""
qc = QuantumCircuit(3)
qc.h(0)
qc.h(1)
qc.h(2)
res = transpile(
qc,
basis_gates=["id", "rz", "x", "sx", "cx"],
translation_method="synthesis",
optimization_level=optimization_level,
)
expected = QuantumCircuit(3, global_phase=3 * np.pi / 4)
expected.rz(np.pi / 2, 0)
expected.rz(np.pi / 2, 1)
expected.rz(np.pi / 2, 2)
expected.sx(0)
expected.sx(1)
expected.sx(2)
expected.rz(np.pi / 2, 0)
expected.rz(np.pi / 2, 1)
expected.rz(np.pi / 2, 2)
self.assertEqual(res, expected)
@data(0, 1, 2, 3)
def test_synthesis_translation_method_with_gates_outside_basis(self, optimization_level):
"""Test that synthesis translation works for circuits with single gates outside bassis"""
qc = QuantumCircuit(2)
qc.swap(0, 1)
res = transpile(
qc,
basis_gates=["id", "rz", "x", "sx", "cx"],
translation_method="synthesis",
optimization_level=optimization_level,
)
if optimization_level != 3:
self.assertTrue(Operator(qc).equiv(res))
self.assertNotIn("swap", res.count_ops())
else:
# Optimization level 3 eliminates the pointless swap
self.assertEqual(res, QuantumCircuit(2))
@data(0, 1, 2, 3)
def test_target_ideal_gates(self, opt_level):
"""Test that transpile() with a custom ideal sim target works."""
theta = Parameter("ΞΈ")
phi = Parameter("Ο")
lam = Parameter("Ξ»")
target = Target(num_qubits=2)
target.add_instruction(UGate(theta, phi, lam), {(0,): None, (1,): None})
target.add_instruction(CXGate(), {(0, 1): None})
target.add_instruction(Measure(), {(0,): None, (1,): None})
qubit_reg = QuantumRegister(2, name="q")
clbit_reg = ClassicalRegister(2, name="c")
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
result = transpile(qc, target=target, optimization_level=opt_level)
self.assertEqual(Operator.from_circuit(result), Operator.from_circuit(qc))
@data(0, 1, 2, 3)
def test_transpile_with_custom_control_flow_target(self, opt_level):
"""Test transpile() with a target and constrol flow ops."""
target = FakeMumbaiV2().target
target.add_instruction(ForLoopOp, name="for_loop")
target.add_instruction(WhileLoopOp, name="while_loop")
target.add_instruction(IfElseOp, name="if_else")
target.add_instruction(SwitchCaseOp, name="switch_case")
circuit = QuantumCircuit(6, 1)
circuit.h(0)
circuit.measure(0, 0)
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.append(CustomCX(), [1, 2], [])
with circuit.for_loop((1,)):
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.append(CustomCX(), [1, 2], [])
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.append(CustomCX(), [1, 2], [])
with else_:
circuit.cx(3, 4)
circuit.cz(3, 5)
circuit.append(CustomCX(), [4, 5], [])
with circuit.while_loop((circuit.clbits[0], True)):
circuit.cx(3, 4)
circuit.cz(3, 5)
circuit.append(CustomCX(), [4, 5], [])
with circuit.switch(circuit.cregs[0]) as case_:
with case_(0):
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.append(CustomCX(), [1, 2], [])
with case_(1):
circuit.cx(1, 2)
circuit.cz(1, 3)
circuit.append(CustomCX(), [2, 3], [])
transpiled = transpile(
circuit, optimization_level=opt_level, target=target, seed_transpiler=12434
)
# Tests of the complete validity of a circuit are mostly done at the indiviual pass level;
# here we're just checking that various passes do appear to have run.
self.assertIsInstance(transpiled, QuantumCircuit)
# Assert layout ran.
self.assertIsNot(getattr(transpiled, "_layout", None), None)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(target.instruction_supported(instruction.operation.name, qargs))
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
# Assert unrolling ran.
self.assertNotIsInstance(instruction.operation, CustomCX)
# Assert translation ran.
self.assertNotIsInstance(instruction.operation, CZGate)
# Assert routing ran.
_visit_block(
transpiled,
qubit_mapping={qubit: index for index, qubit in enumerate(transpiled.qubits)},
)
@data(1, 2, 3)
def test_transpile_identity_circuit_no_target(self, opt_level):
"""Test circuit equivalent to identity is optimized away for all optimization levels >0.
Reproduce taken from https://github.com/Qiskit/qiskit-terra/issues/9217
"""
qr1 = QuantumRegister(3, "state")
qr2 = QuantumRegister(2, "ancilla")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr1, qr2, cr)
qc.h(qr1[0])
qc.cx(qr1[0], qr1[1])
qc.cx(qr1[1], qr1[2])
qc.cx(qr1[1], qr1[2])
qc.cx(qr1[0], qr1[1])
qc.h(qr1[0])
empty_qc = QuantumCircuit(qr1, qr2, cr)
result = transpile(qc, optimization_level=opt_level)
self.assertEqual(empty_qc, result)
@data(0, 1, 2, 3)
def test_initial_layout_with_loose_qubits(self, opt_level):
"""Regression test of gh-10125."""
qc = QuantumCircuit([Qubit(), Qubit()])
qc.cx(0, 1)
transpiled = transpile(qc, initial_layout=[1, 0], optimization_level=opt_level)
self.assertIsNotNone(transpiled.layout)
self.assertEqual(
transpiled.layout.initial_layout, Layout({0: qc.qubits[1], 1: qc.qubits[0]})
)
@data(0, 1, 2, 3)
def test_initial_layout_with_overlapping_qubits(self, opt_level):
"""Regression test of gh-10125."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(bits=qr1[:])
qc = QuantumCircuit(qr1, qr2)
qc.cx(0, 1)
transpiled = transpile(qc, initial_layout=[1, 0], optimization_level=opt_level)
self.assertIsNotNone(transpiled.layout)
self.assertEqual(
transpiled.layout.initial_layout, Layout({0: qc.qubits[1], 1: qc.qubits[0]})
)
@combine(opt_level=[0, 1, 2, 3], basis=[["rz", "x"], ["rx", "z"], ["rz", "y"], ["ry", "x"]])
def test_paulis_to_constrained_1q_basis(self, opt_level, basis):
"""Test that Pauli-gate circuits can be transpiled to constrained 1q bases that do not
contain any root-Pauli gates."""
qc = QuantumCircuit(1)
qc.x(0)
qc.barrier()
qc.y(0)
qc.barrier()
qc.z(0)
transpiled = transpile(qc, basis_gates=basis, optimization_level=opt_level)
self.assertGreaterEqual(set(basis) | {"barrier"}, transpiled.count_ops().keys())
self.assertEqual(Operator(qc), Operator(transpiled))
@ddt
class TestPostTranspileIntegration(QiskitTestCase):
"""Test that the output of `transpile` is usable in various other integration contexts."""
def _regular_circuit(self):
a = Parameter("a")
regs = [
QuantumRegister(2, name="q0"),
QuantumRegister(3, name="q1"),
ClassicalRegister(2, name="c0"),
]
bits = [Qubit(), Qubit(), Clbit()]
base = QuantumCircuit(*regs, bits)
base.h(0)
base.measure(0, 0)
base.cx(0, 1)
base.cz(0, 2)
base.cz(0, 3)
base.cz(1, 4)
base.cx(1, 5)
base.measure(1, 1)
base.append(CustomCX(), [3, 6])
base.append(CustomCX(), [5, 4])
base.append(CustomCX(), [5, 3])
base.append(CustomCX(), [2, 4]).c_if(base.cregs[0], 3)
base.ry(a, 4)
base.measure(4, 2)
return base
def _control_flow_circuit(self):
a = Parameter("a")
regs = [
QuantumRegister(2, name="q0"),
QuantumRegister(3, name="q1"),
ClassicalRegister(2, name="c0"),
]
bits = [Qubit(), Qubit(), Clbit()]
base = QuantumCircuit(*regs, bits)
base.h(0)
base.measure(0, 0)
with base.if_test((base.cregs[0], 1)) as else_:
base.cx(0, 1)
base.cz(0, 2)
base.cz(0, 3)
with else_:
base.cz(1, 4)
with base.for_loop((1, 2)):
base.cx(1, 5)
base.measure(2, 2)
with base.while_loop((2, False)):
base.append(CustomCX(), [3, 6])
base.append(CustomCX(), [5, 4])
base.append(CustomCX(), [5, 3])
base.append(CustomCX(), [2, 4])
base.ry(a, 4)
base.measure(4, 2)
with base.switch(base.cregs[0]) as case_:
with case_(0, 1):
base.cz(3, 5)
with case_(case_.DEFAULT):
base.cz(1, 4)
base.append(CustomCX(), [2, 4])
base.append(CustomCX(), [3, 4])
return base
def _control_flow_expr_circuit(self):
a = Parameter("a")
regs = [
QuantumRegister(2, name="q0"),
QuantumRegister(3, name="q1"),
ClassicalRegister(2, name="c0"),
]
bits = [Qubit(), Qubit(), Clbit()]
base = QuantumCircuit(*regs, bits)
base.h(0)
base.measure(0, 0)
with base.if_test(expr.equal(base.cregs[0], 1)) as else_:
base.cx(0, 1)
base.cz(0, 2)
base.cz(0, 3)
with else_:
base.cz(1, 4)
with base.for_loop((1, 2)):
base.cx(1, 5)
base.measure(2, 2)
with base.while_loop(expr.logic_not(bits[2])):
base.append(CustomCX(), [3, 6])
base.append(CustomCX(), [5, 4])
base.append(CustomCX(), [5, 3])
base.append(CustomCX(), [2, 4])
base.ry(a, 4)
base.measure(4, 2)
with base.switch(expr.bit_and(base.cregs[0], 2)) as case_:
with case_(0, 1):
base.cz(3, 5)
with case_(case_.DEFAULT):
base.cz(1, 4)
base.append(CustomCX(), [2, 4])
base.append(CustomCX(), [3, 4])
return base
@data(0, 1, 2, 3)
def test_qpy_roundtrip(self, optimization_level):
"""Test that the output of a transpiled circuit can be round-tripped through QPY."""
transpiled = transpile(
self._regular_circuit(),
backend=FakeMelbourne(),
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# Round-tripping the layout is out-of-scope for QPY while it's a private attribute.
transpiled._layout = None
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_backendv2(self, optimization_level):
"""Test that the output of a transpiled circuit can be round-tripped through QPY."""
transpiled = transpile(
self._regular_circuit(),
backend=FakeMumbaiV2(),
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# Round-tripping the layout is out-of-scope for QPY while it's a private attribute.
transpiled._layout = None
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_control_flow(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow can be round-tripped
through QPY."""
if optimization_level == 3 and sys.platform == "win32":
self.skipTest(
"This test case triggers a bug in the eigensolver routine on windows. "
"See #10345 for more details."
)
backend = FakeMelbourne()
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
basis_gates=backend.configuration().basis_gates
+ ["if_else", "for_loop", "while_loop", "switch_case"],
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# Round-tripping the layout is out-of-scope for QPY while it's a private attribute.
transpiled._layout = None
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_control_flow_backendv2(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow can be round-tripped
through QPY."""
backend = FakeMumbaiV2()
backend.target.add_instruction(IfElseOp, name="if_else")
backend.target.add_instruction(ForLoopOp, name="for_loop")
backend.target.add_instruction(WhileLoopOp, name="while_loop")
backend.target.add_instruction(SwitchCaseOp, name="switch_case")
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# Round-tripping the layout is out-of-scope for QPY while it's a private attribute.
transpiled._layout = None
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_control_flow_expr(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow including `Expr` nodes can
be round-tripped through QPY."""
if optimization_level == 3 and sys.platform == "win32":
self.skipTest(
"This test case triggers a bug in the eigensolver routine on windows. "
"See #10345 for more details."
)
backend = FakeMelbourne()
transpiled = transpile(
self._control_flow_expr_circuit(),
backend=backend,
basis_gates=backend.configuration().basis_gates
+ ["if_else", "for_loop", "while_loop", "switch_case"],
optimization_level=optimization_level,
seed_transpiler=2023_07_26,
)
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_control_flow_expr_backendv2(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow including `Expr` nodes can
be round-tripped through QPY."""
backend = FakeMumbaiV2()
backend.target.add_instruction(IfElseOp, name="if_else")
backend.target.add_instruction(ForLoopOp, name="for_loop")
backend.target.add_instruction(WhileLoopOp, name="while_loop")
backend.target.add_instruction(SwitchCaseOp, name="switch_case")
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
optimization_level=optimization_level,
seed_transpiler=2023_07_26,
)
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qasm3_output(self, optimization_level):
"""Test that the output of a transpiled circuit can be dumped into OpenQASM 3."""
transpiled = transpile(
self._regular_circuit(),
backend=FakeMelbourne(),
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# TODO: There's not a huge amount we can sensibly test for the output here until we can
# round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump
# itself doesn't throw an error, though.
self.assertIsInstance(qasm3.dumps(transpiled).strip(), str)
@data(0, 1, 2, 3)
def test_qasm3_output_control_flow(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow can be dumped into
OpenQASM 3."""
backend = FakeMumbaiV2()
backend.target.add_instruction(IfElseOp, name="if_else")
backend.target.add_instruction(ForLoopOp, name="for_loop")
backend.target.add_instruction(WhileLoopOp, name="while_loop")
backend.target.add_instruction(SwitchCaseOp, name="switch_case")
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# TODO: There's not a huge amount we can sensibly test for the output here until we can
# round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump
# itself doesn't throw an error, though.
self.assertIsInstance(
qasm3.dumps(transpiled, experimental=qasm3.ExperimentalFeatures.SWITCH_CASE_V1).strip(),
str,
)
@data(0, 1, 2, 3)
def test_qasm3_output_control_flow_expr(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow and `Expr` nodes can be
dumped into OpenQASM 3."""
backend = FakeMumbaiV2()
backend.target.add_instruction(IfElseOp, name="if_else")
backend.target.add_instruction(ForLoopOp, name="for_loop")
backend.target.add_instruction(WhileLoopOp, name="while_loop")
backend.target.add_instruction(SwitchCaseOp, name="switch_case")
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
optimization_level=optimization_level,
seed_transpiler=2023_07_26,
)
# TODO: There's not a huge amount we can sensibly test for the output here until we can
# round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump
# itself doesn't throw an error, though.
self.assertIsInstance(
qasm3.dumps(transpiled, experimental=qasm3.ExperimentalFeatures.SWITCH_CASE_V1).strip(),
str,
)
@data(0, 1, 2, 3)
def test_transpile_target_no_measurement_error(self, opt_level):
"""Test that transpile with a target which contains ideal measurement works
Reproduce from https://github.com/Qiskit/qiskit-terra/issues/8969
"""
target = Target()
target.add_instruction(Measure(), {(0,): None})
qc = QuantumCircuit(1, 1)
qc.measure(0, 0)
res = transpile(qc, target=target, optimization_level=opt_level)
self.assertEqual(qc, res)
def test_transpile_final_layout_updated_with_post_layout(self):
"""Test that the final layout is correctly set when vf2postlayout runs.
Reproduce from #10457
"""
def _get_index_layout(transpiled_circuit: QuantumCircuit, num_source_qubits: int):
"""Return the index layout of a transpiled circuit"""
layout = transpiled_circuit.layout
if layout is None:
return list(range(num_source_qubits))
pos_to_virt = {v: k for k, v in layout.input_qubit_mapping.items()}
qubit_indices = []
for index in range(num_source_qubits):
qubit_idx = layout.initial_layout[pos_to_virt[index]]
if layout.final_layout is not None:
qubit_idx = layout.final_layout[transpiled_circuit.qubits[qubit_idx]]
qubit_indices.append(qubit_idx)
return qubit_indices
vf2_post_layout_called = False
def callback(**kwargs):
nonlocal vf2_post_layout_called
if isinstance(kwargs["pass_"], VF2PostLayout):
vf2_post_layout_called = True
self.assertIsNotNone(kwargs["property_set"]["post_layout"])
backend = FakeVigo()
qubits = 3
qc = QuantumCircuit(qubits)
for i in range(5):
qc.cx(i % qubits, int(i + qubits / 2) % qubits)
tqc = transpile(qc, backend=backend, seed_transpiler=4242, callback=callback)
self.assertTrue(vf2_post_layout_called)
self.assertEqual([3, 2, 1], _get_index_layout(tqc, qubits))
class StreamHandlerRaiseException(StreamHandler):
"""Handler class that will raise an exception on formatting errors."""
def handleError(self, record):
raise sys.exc_info()
class TestLogTranspile(QiskitTestCase):
"""Testing the log_transpile option."""
def setUp(self):
super().setUp()
logger = getLogger()
self.addCleanup(logger.setLevel, logger.level)
logger.setLevel("DEBUG")
self.output = io.StringIO()
logger.addHandler(StreamHandlerRaiseException(self.output))
self.circuit = QuantumCircuit(QuantumRegister(1))
def assertTranspileLog(self, log_msg):
"""Runs the transpiler and check for logs containing specified message"""
transpile(self.circuit)
self.output.seek(0)
# Filter unrelated log lines
output_lines = self.output.readlines()
transpile_log_lines = [x for x in output_lines if log_msg in x]
self.assertTrue(len(transpile_log_lines) > 0)
def test_transpile_log_time(self):
"""Check Total Transpile Time is logged"""
self.assertTranspileLog("Total Transpile Time")
class TestTranspileCustomPM(QiskitTestCase):
"""Test transpile function with custom pass manager"""
def test_custom_multiple_circuits(self):
"""Test transpiling with custom pass manager and multiple circuits.
This tests created a deadlock, so it needs to be monitored for timeout.
See: https://github.com/Qiskit/qiskit-terra/issues/3925
"""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
pm_conf = PassManagerConfig(
initial_layout=None,
basis_gates=["u1", "u2", "u3", "cx"],
coupling_map=CouplingMap([[0, 1]]),
backend_properties=None,
seed_transpiler=1,
)
passmanager = level_0_pass_manager(pm_conf)
transpiled = passmanager.run([qc, qc])
expected = QuantumCircuit(QuantumRegister(2, "q"))
expected.append(U2Gate(0, 3.141592653589793), [0])
expected.cx(0, 1)
self.assertEqual(len(transpiled), 2)
self.assertEqual(transpiled[0], expected)
self.assertEqual(transpiled[1], expected)
@ddt
class TestTranspileParallel(QiskitTestCase):
"""Test transpile() in parallel."""
def setUp(self):
super().setUp()
# Force parallel execution to True to test multiprocessing for this class
original_val = parallel.PARALLEL_DEFAULT
def restore_default():
parallel.PARALLEL_DEFAULT = original_val
self.addCleanup(restore_default)
parallel.PARALLEL_DEFAULT = True
@data(0, 1, 2, 3)
def test_parallel_multiprocessing(self, opt_level):
"""Test parallel dispatch works with multiprocessing."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
backend = FakeMumbaiV2()
pm = generate_preset_pass_manager(opt_level, backend)
res = pm.run([qc, qc])
for circ in res:
self.assertIsInstance(circ, QuantumCircuit)
@data(0, 1, 2, 3)
def test_parallel_with_target(self, opt_level):
"""Test that parallel dispatch works with a manual target."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
target = FakeMumbaiV2().target
res = transpile([qc] * 3, target=target, optimization_level=opt_level)
self.assertIsInstance(res, list)
for circ in res:
self.assertIsInstance(circ, QuantumCircuit)
@data(0, 1, 2, 3)
def test_parallel_dispatch(self, opt_level):
"""Test that transpile in parallel works for all optimization levels."""
backend = FakeRueschlikon()
qr = QuantumRegister(16)
cr = ClassicalRegister(16)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
for k in range(1, 15):
qc.cx(qr[0], qr[k])
qc.measure(qr, cr)
qlist = [qc for k in range(15)]
tqc = transpile(
qlist, backend=backend, optimization_level=opt_level, seed_transpiler=424242
)
result = backend.run(tqc, seed_simulator=4242424242, shots=1000).result()
counts = result.get_counts()
for count in counts:
self.assertTrue(math.isclose(count["0000000000000000"], 500, rel_tol=0.1))
self.assertTrue(math.isclose(count["0111111111111111"], 500, rel_tol=0.1))
def test_parallel_dispatch_lazy_cal_loading(self):
"""Test adding calibration by lazy loading in parallel environment."""
class TestAddCalibration(TransformationPass):
"""A fake pass to test lazy pulse qobj loading in parallel environment."""
def __init__(self, target):
"""Instantiate with target."""
super().__init__()
self.target = target
def run(self, dag):
"""Run test pass that adds calibration of SX gate of qubit 0."""
dag.add_calibration(
"sx",
qubits=(0,),
schedule=self.target["sx"][(0,)].calibration, # PulseQobj is parsed here
)
return dag
backend = FakeMumbaiV2()
# This target has PulseQobj entries that provides a serialized schedule data
pass_ = TestAddCalibration(backend.target)
pm = PassManager(passes=[pass_])
self.assertIsNone(backend.target["sx"][(0,)]._calibration._definition)
qc = QuantumCircuit(1)
qc.sx(0)
qc_copied = [qc for _ in range(10)]
qcs_cal_added = pm.run(qc_copied)
ref_cal = backend.target["sx"][(0,)].calibration
for qc_test in qcs_cal_added:
added_cal = qc_test.calibrations["sx"][((0,), ())]
self.assertEqual(added_cal, ref_cal)
@data(0, 1, 2, 3)
def test_backendv2_and_basis_gates(self, opt_level):
"""Test transpile() with BackendV2 and basis_gates set."""
backend = FakeNairobiV2()
qc = QuantumCircuit(5)
qc.h(0)
qc.cz(0, 1)
qc.cz(0, 2)
qc.cz(0, 3)
qc.cz(0, 4)
qc.measure_all()
tqc = transpile(
qc,
backend=backend,
basis_gates=["u", "cz"],
optimization_level=opt_level,
seed_transpiler=12345678942,
)
op_count = set(tqc.count_ops())
self.assertEqual({"u", "cz", "measure", "barrier"}, op_count)
for inst in tqc.data:
if inst.operation.name not in {"u", "cz"}:
continue
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
self.assertIn(qubits, backend.target.qargs)
@data(0, 1, 2, 3)
def test_backendv2_and_coupling_map(self, opt_level):
"""Test transpile() with custom coupling map."""
backend = FakeNairobiV2()
qc = QuantumCircuit(5)
qc.h(0)
qc.cz(0, 1)
qc.cz(0, 2)
qc.cz(0, 3)
qc.cz(0, 4)
qc.measure_all()
cmap = CouplingMap.from_line(5, bidirectional=False)
tqc = transpile(
qc,
backend=backend,
coupling_map=cmap,
optimization_level=opt_level,
seed_transpiler=12345678942,
)
op_count = set(tqc.count_ops())
self.assertTrue({"rz", "sx", "x", "cx", "measure", "barrier"}.issuperset(op_count))
for inst in tqc.data:
if len(inst.qubits) == 2:
qubit_0 = tqc.find_bit(inst.qubits[0]).index
qubit_1 = tqc.find_bit(inst.qubits[1]).index
self.assertEqual(qubit_1, qubit_0 + 1)
def test_transpile_with_multiple_coupling_maps(self):
"""Test passing a different coupling map for every circuit"""
backend = FakeNairobiV2()
qc = QuantumCircuit(3)
qc.cx(0, 2)
# Add a connection between 0 and 2 so that transpile does not change
# the gates
cmap = CouplingMap.from_line(7)
cmap.add_edge(0, 2)
with self.assertRaisesRegex(TranspilerError, "Only a single input coupling"):
# Initial layout needed to prevent transpiler from relabeling
# qubits to avoid doing the swap
transpile(
[qc] * 2,
backend,
coupling_map=[backend.coupling_map, cmap],
initial_layout=(0, 1, 2),
)
@data(0, 1, 2, 3)
def test_backend_and_custom_gate(self, opt_level):
"""Test transpile() with BackendV2, custom basis pulse gate."""
backend = FakeNairobiV2()
inst_map = InstructionScheduleMap()
inst_map.add("newgate", [0, 1], pulse.ScheduleBlock())
newgate = Gate("newgate", 2, [])
circ = QuantumCircuit(2)
circ.append(newgate, [0, 1])
tqc = transpile(
circ, backend, inst_map=inst_map, basis_gates=["newgate"], optimization_level=opt_level
)
self.assertEqual(len(tqc.data), 1)
self.assertEqual(tqc.data[0].operation, newgate)
qubits = tuple(tqc.find_bit(x).index for x in tqc.data[0].qubits)
self.assertIn(qubits, backend.target.qargs)
@ddt
class TestTranspileMultiChipTarget(QiskitTestCase):
"""Test transpile() with a disjoint coupling map."""
def setUp(self):
super().setUp()
class FakeMultiChip(BackendV2):
"""Fake multi chip backend."""
def __init__(self):
super().__init__()
graph = rx.generators.directed_heavy_hex_graph(3)
num_qubits = len(graph) * 3
rng = np.random.default_rng(seed=12345678942)
rz_props = {}
x_props = {}
sx_props = {}
measure_props = {}
delay_props = {}
self._target = Target("Fake multi-chip backend", num_qubits=num_qubits)
for i in range(num_qubits):
qarg = (i,)
rz_props[qarg] = InstructionProperties(error=0.0, duration=0.0)
x_props[qarg] = InstructionProperties(
error=rng.uniform(1e-6, 1e-4), duration=rng.uniform(1e-8, 9e-7)
)
sx_props[qarg] = InstructionProperties(
error=rng.uniform(1e-6, 1e-4), duration=rng.uniform(1e-8, 9e-7)
)
measure_props[qarg] = InstructionProperties(
error=rng.uniform(1e-3, 1e-1), duration=rng.uniform(1e-8, 9e-7)
)
delay_props[qarg] = None
self._target.add_instruction(XGate(), x_props)
self._target.add_instruction(SXGate(), sx_props)
self._target.add_instruction(RZGate(Parameter("theta")), rz_props)
self._target.add_instruction(Measure(), measure_props)
self._target.add_instruction(Delay(Parameter("t")), delay_props)
cz_props = {}
for i in range(3):
for root_edge in graph.edge_list():
offset = i * len(graph)
edge = (root_edge[0] + offset, root_edge[1] + offset)
cz_props[edge] = InstructionProperties(
error=rng.uniform(1e-5, 5e-3), duration=rng.uniform(1e-8, 9e-7)
)
self._target.add_instruction(CZGate(), cz_props)
@property
def target(self):
return self._target
@property
def max_circuits(self):
return None
@classmethod
def _default_options(cls):
return Options(shots=1024)
def run(self, circuit, **kwargs):
raise NotImplementedError
self.backend = FakeMultiChip()
@data(0, 1, 2, 3)
def test_basic_connected_circuit(self, opt_level):
"""Test basic connected circuit on disjoint backend"""
qc = QuantumCircuit(5)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.measure_all()
tqc = transpile(qc, self.backend, optimization_level=opt_level)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
@data(0, 1, 2, 3)
def test_triple_circuit(self, opt_level):
"""Test a split circuit with one circuit component per chip."""
qc = QuantumCircuit(30)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.measure_all()
if opt_level == 0:
with self.assertRaises(TranspilerError):
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42)
return
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
def test_disjoint_control_flow(self):
"""Test control flow circuit on disjoint coupling map."""
qc = QuantumCircuit(6, 1)
qc.h(0)
qc.ecr(0, 1)
qc.cx(0, 2)
qc.measure(0, 0)
with qc.if_test((qc.clbits[0], True)):
qc.reset(0)
qc.cz(1, 0)
qc.h(3)
qc.cz(3, 4)
qc.cz(3, 5)
target = self.backend.target
target.add_instruction(Reset(), {(i,): None for i in range(target.num_qubits)})
target.add_instruction(IfElseOp, name="if_else")
tqc = transpile(qc, target=target)
edges = set(target.build_coupling_map().graph.edge_list())
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(target.instruction_supported(instruction.operation.name, qargs))
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
elif len(qargs) == 2:
self.assertIn(qargs, edges)
self.assertIn(instruction.operation.name, target)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
def test_disjoint_control_flow_shared_classical(self):
"""Test circuit with classical data dependency between connected components."""
creg = ClassicalRegister(19)
qc = QuantumCircuit(25)
qc.add_register(creg)
qc.h(0)
for i in range(18):
qc.cx(0, i + 1)
for i in range(18):
qc.measure(i, creg[i])
with qc.if_test((creg, 0)):
qc.h(20)
qc.ecr(20, 21)
qc.ecr(20, 22)
qc.ecr(20, 23)
qc.ecr(20, 24)
target = self.backend.target
target.add_instruction(Reset(), {(i,): None for i in range(target.num_qubits)})
target.add_instruction(IfElseOp, name="if_else")
tqc = transpile(qc, target=target)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(target.instruction_supported(instruction.operation.name, qargs))
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
@slow_test
@data(2, 3)
def test_six_component_circuit(self, opt_level):
"""Test input circuit with more than 1 component per backend component."""
qc = QuantumCircuit(42)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.h(30)
qc.cx(30, 31)
qc.cx(30, 32)
qc.cx(30, 33)
qc.h(34)
qc.cx(34, 35)
qc.cx(34, 36)
qc.cx(34, 37)
qc.h(38)
qc.cx(38, 39)
qc.cx(39, 40)
qc.cx(39, 41)
qc.measure_all()
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
def test_six_component_circuit_level_1(self):
"""Test input circuit with more than 1 component per backend component."""
opt_level = 1
qc = QuantumCircuit(42)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.h(30)
qc.cx(30, 31)
qc.cx(30, 32)
qc.cx(30, 33)
qc.h(34)
qc.cx(34, 35)
qc.cx(34, 36)
qc.cx(34, 37)
qc.h(38)
qc.cx(38, 39)
qc.cx(39, 40)
qc.cx(39, 41)
qc.measure_all()
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
@data(0, 1, 2, 3)
def test_shared_classical_between_components_condition(self, opt_level):
"""Test a condition sharing classical bits between components."""
creg = ClassicalRegister(19)
qc = QuantumCircuit(25)
qc.add_register(creg)
qc.h(0)
for i in range(18):
qc.cx(0, i + 1)
for i in range(18):
qc.measure(i, creg[i])
qc.ecr(20, 21).c_if(creg, 0)
tqc = transpile(qc, self.backend, optimization_level=opt_level)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(
self.backend.target.instruction_supported(instruction.operation.name, qargs)
)
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
@data(0, 1, 2, 3)
def test_shared_classical_between_components_condition_large_to_small(self, opt_level):
"""Test a condition sharing classical bits between components."""
creg = ClassicalRegister(2)
qc = QuantumCircuit(25)
qc.add_register(creg)
# Component 0
qc.h(24)
qc.cx(24, 23)
qc.measure(24, creg[0])
qc.measure(23, creg[1])
# Component 1
qc.h(0).c_if(creg, 0)
for i in range(18):
qc.ecr(0, i + 1).c_if(creg, 0)
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=123456789)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(
self.backend.target.instruction_supported(instruction.operation.name, qargs)
)
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
# Check that virtual qubits that interact with each other via quantum links are placed into
# the same component of the coupling map.
initial_layout = tqc.layout.initial_layout
coupling_map = self.backend.target.build_coupling_map()
components = [
connected_qubits(initial_layout[qc.qubits[23]], coupling_map),
connected_qubits(initial_layout[qc.qubits[0]], coupling_map),
]
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in [23, 24]}, components[0])
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(19)}, components[1])
# Check clbits are in order.
# Traverse the output dag over the sole clbit, checking that the qubits of the ops
# go in order between the components. This is a sanity check to ensure that routing
# doesn't reorder a classical data dependency between components. Inside a component
# we have the dag ordering so nothing should be out of order within a component.
tqc_dag = circuit_to_dag(tqc)
qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)}
input_node = tqc_dag.input_map[tqc_dag.clbits[0]]
first_meas_node = tqc_dag._multi_graph.find_successors_by_edge(
input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
# The first node should be a measurement
self.assertIsInstance(first_meas_node.op, Measure)
# This should be in the first component
self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
while isinstance(op_node, DAGOpNode):
self.assertIn(qubit_map[op_node.qargs[0]], components[1])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
@data(1, 2, 3)
def test_shared_classical_between_components_condition_large_to_small_reverse_index(
self, opt_level
):
"""Test a condition sharing classical bits between components."""
creg = ClassicalRegister(2)
qc = QuantumCircuit(25)
qc.add_register(creg)
# Component 0
qc.h(0)
qc.cx(0, 1)
qc.measure(0, creg[0])
qc.measure(1, creg[1])
# Component 1
qc.h(24).c_if(creg, 0)
for i in range(23, 5, -1):
qc.ecr(24, i).c_if(creg, 0)
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=2023)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(
self.backend.target.instruction_supported(instruction.operation.name, qargs)
)
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
# Check that virtual qubits that interact with each other via quantum links are placed into
# the same component of the coupling map.
initial_layout = tqc.layout.initial_layout
coupling_map = self.backend.target.build_coupling_map()
components = [
connected_qubits(initial_layout[qc.qubits[0]], coupling_map),
connected_qubits(initial_layout[qc.qubits[6]], coupling_map),
]
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(2)}, components[0])
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(6, 25)}, components[1])
# Check clbits are in order.
# Traverse the output dag over the sole clbit, checking that the qubits of the ops
# go in order between the components. This is a sanity check to ensure that routing
# doesn't reorder a classical data dependency between components. Inside a component
# we have the dag ordering so nothing should be out of order within a component.
tqc_dag = circuit_to_dag(tqc)
qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)}
input_node = tqc_dag.input_map[tqc_dag.clbits[0]]
first_meas_node = tqc_dag._multi_graph.find_successors_by_edge(
input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
# The first node should be a measurement
self.assertIsInstance(first_meas_node.op, Measure)
# This shoulde be in the first ocmponent
self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
while isinstance(op_node, DAGOpNode):
self.assertIn(qubit_map[op_node.qargs[0]], components[1])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
@data(1, 2, 3)
def test_chained_data_dependency(self, opt_level):
"""Test 3 component circuit with shared clbits between each component."""
creg = ClassicalRegister(1)
qc = QuantumCircuit(30)
qc.add_register(creg)
# Component 0
qc.h(0)
for i in range(9):
qc.cx(0, i + 1)
measure_op = Measure()
qc.append(measure_op, [9], [creg[0]])
# Component 1
qc.h(10).c_if(creg, 0)
for i in range(11, 20):
qc.ecr(10, i).c_if(creg, 0)
measure_op = Measure()
qc.append(measure_op, [19], [creg[0]])
# Component 2
qc.h(20).c_if(creg, 0)
for i in range(21, 30):
qc.cz(20, i).c_if(creg, 0)
measure_op = Measure()
qc.append(measure_op, [29], [creg[0]])
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=2023)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(
self.backend.target.instruction_supported(instruction.operation.name, qargs)
)
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
# Check that virtual qubits that interact with each other via quantum links are placed into
# the same component of the coupling map.
initial_layout = tqc.layout.initial_layout
coupling_map = self.backend.target.build_coupling_map()
components = [
connected_qubits(initial_layout[qc.qubits[0]], coupling_map),
connected_qubits(initial_layout[qc.qubits[10]], coupling_map),
connected_qubits(initial_layout[qc.qubits[20]], coupling_map),
]
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(10)}, components[0])
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(10, 20)}, components[1])
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(20, 30)}, components[2])
# Check clbits are in order.
# Traverse the output dag over the sole clbit, checking that the qubits of the ops
# go in order between the components. This is a sanity check to ensure that routing
# doesn't reorder a classical data dependency between components. Inside a component
# we have the dag ordering so nothing should be out of order within a component.
tqc_dag = circuit_to_dag(tqc)
qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)}
input_node = tqc_dag.input_map[tqc_dag.clbits[0]]
first_meas_node = tqc_dag._multi_graph.find_successors_by_edge(
input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
self.assertIsInstance(first_meas_node.op, Measure)
self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
while not isinstance(op_node.op, Measure):
self.assertIn(qubit_map[op_node.qargs[0]], components[1])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
self.assertIn(qubit_map[op_node.qargs[0]], components[1])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
while not isinstance(op_node.op, Measure):
self.assertIn(qubit_map[op_node.qargs[0]], components[2])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
self.assertIn(qubit_map[op_node.qargs[0]], components[2])
@data("sabre", "stochastic", "basic", "lookahead")
def test_basic_connected_circuit_dense_layout(self, routing_method):
"""Test basic connected circuit on disjoint backend"""
qc = QuantumCircuit(5)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.measure_all()
tqc = transpile(
qc,
self.backend,
layout_method="dense",
routing_method=routing_method,
seed_transpiler=42,
)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
# Lookahead swap skipped for performance
@data("sabre", "stochastic", "basic")
def test_triple_circuit_dense_layout(self, routing_method):
"""Test a split circuit with one circuit component per chip."""
qc = QuantumCircuit(30)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.measure_all()
tqc = transpile(
qc,
self.backend,
layout_method="dense",
routing_method=routing_method,
seed_transpiler=42,
)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
@data("sabre", "stochastic", "basic", "lookahead")
def test_triple_circuit_invalid_layout(self, routing_method):
"""Test a split circuit with one circuit component per chip."""
qc = QuantumCircuit(30)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.measure_all()
with self.assertRaises(TranspilerError):
transpile(
qc,
self.backend,
layout_method="trivial",
routing_method=routing_method,
seed_transpiler=42,
)
# Lookahead swap skipped for performance reasons
@data("sabre", "stochastic", "basic")
def test_six_component_circuit_dense_layout(self, routing_method):
"""Test input circuit with more than 1 component per backend component."""
qc = QuantumCircuit(42)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.h(30)
qc.cx(30, 31)
qc.cx(30, 32)
qc.cx(30, 33)
qc.h(34)
qc.cx(34, 35)
qc.cx(34, 36)
qc.cx(34, 37)
qc.h(38)
qc.cx(38, 39)
qc.cx(39, 40)
qc.cx(39, 41)
qc.measure_all()
tqc = transpile(
qc,
self.backend,
layout_method="dense",
routing_method=routing_method,
seed_transpiler=42,
)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
@data(0, 1, 2, 3)
def test_transpile_target_with_qubits_without_ops(self, opt_level):
"""Test qubits without operations aren't ever used."""
target = Target(num_qubits=5)
target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(
CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]}
)
qc = QuantumCircuit(3)
qc.x(0)
qc.cx(0, 1)
qc.cx(0, 2)
tqc = transpile(qc, target=target, optimization_level=opt_level)
invalid_qubits = {3, 4}
self.assertEqual(tqc.num_qubits, 5)
for inst in tqc.data:
for bit in inst.qubits:
self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits)
@data(0, 1, 2, 3)
def test_transpile_target_with_qubits_without_ops_with_routing(self, opt_level):
"""Test qubits without operations aren't ever used."""
target = Target(num_qubits=5)
target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(4)})
target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(4)})
target.add_instruction(
CXGate(),
{edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0), (2, 3)]},
)
qc = QuantumCircuit(4)
qc.x(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(1, 3)
qc.cx(0, 3)
tqc = transpile(qc, target=target, optimization_level=opt_level)
invalid_qubits = {
4,
}
self.assertEqual(tqc.num_qubits, 5)
for inst in tqc.data:
for bit in inst.qubits:
self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits)
@data(0, 1, 2, 3)
def test_transpile_target_with_qubits_without_ops_circuit_too_large(self, opt_level):
"""Test qubits without operations aren't ever used and error if circuit needs them."""
target = Target(num_qubits=5)
target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(
CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]}
)
qc = QuantumCircuit(4)
qc.x(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
with self.assertRaises(TranspilerError):
transpile(qc, target=target, optimization_level=opt_level)
@data(0, 1, 2, 3)
def test_transpile_target_with_qubits_without_ops_circuit_too_large_disconnected(
self, opt_level
):
"""Test qubits without operations aren't ever used if a disconnected circuit needs them."""
target = Target(num_qubits=5)
target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(
CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]}
)
qc = QuantumCircuit(5)
qc.x(0)
qc.x(1)
qc.x(3)
qc.x(4)
with self.assertRaises(TranspilerError):
transpile(qc, target=target, optimization_level=opt_level)
@data(0, 1, 2, 3)
def test_transpile_does_not_affect_backend_coupling(self, opt_level):
"""Test that transpiliation of a circuit does not mutate the `CouplingMap` stored by a V2
backend. Regression test of gh-9997."""
if opt_level == 3:
raise unittest.SkipTest("unitary resynthesis fails due to gh-10004")
qc = QuantumCircuit(127)
for i in range(1, 127):
qc.ecr(0, i)
backend = FakeSherbrooke()
original_map = copy.deepcopy(backend.coupling_map)
transpile(qc, backend, optimization_level=opt_level)
self.assertEqual(original_map, backend.coupling_map)
@combine(
optimization_level=[0, 1, 2, 3],
scheduling_method=["asap", "alap"],
)
def test_transpile_target_with_qubits_without_delays_with_scheduling(
self, optimization_level, scheduling_method
):
"""Test qubits without operations aren't ever used."""
no_delay_qubits = [1, 3, 4]
target = Target(num_qubits=5, dt=1)
target.add_instruction(
XGate(), {(i,): InstructionProperties(duration=160) for i in range(4)}
)
target.add_instruction(
HGate(), {(i,): InstructionProperties(duration=160) for i in range(4)}
)
target.add_instruction(
CXGate(),
{
edge: InstructionProperties(duration=800)
for edge in [(0, 1), (1, 2), (2, 0), (2, 3)]
},
)
target.add_instruction(
Delay(Parameter("t")), {(i,): None for i in range(4) if i not in no_delay_qubits}
)
qc = QuantumCircuit(4)
qc.x(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(1, 3)
qc.cx(0, 3)
tqc = transpile(
qc,
target=target,
optimization_level=optimization_level,
scheduling_method=scheduling_method,
)
invalid_qubits = {
4,
}
self.assertEqual(tqc.num_qubits, 5)
for inst in tqc.data:
for bit in inst.qubits:
self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits)
if isinstance(inst.operation, Delay):
self.assertNotIn(tqc.find_bit(bit).index, no_delay_qubits)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for the converters."""
import os
import unittest
from qiskit.converters import ast_to_dag, circuit_to_dag
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import qasm
from qiskit.test import QiskitTestCase
class TestAstToDag(QiskitTestCase):
"""Test AST to DAG."""
def setUp(self):
super().setUp()
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
self.circuit = QuantumCircuit(qr, cr)
self.circuit.ccx(qr[0], qr[1], qr[2])
self.circuit.measure(qr, cr)
self.dag = circuit_to_dag(self.circuit)
def test_from_ast_to_dag(self):
"""Test Unroller.execute()"""
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
ast = qasm.Qasm(os.path.join(qasm_dir, "example.qasm")).parse()
dag_circuit = ast_to_dag(ast)
expected_result = """\
OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
qreg r[3];
creg c[3];
creg d[3];
h q[0];
h q[1];
h q[2];
cx q[0],r[0];
cx q[1],r[1];
cx q[2],r[2];
barrier q[0],q[1],q[2];
measure q[0] -> c[0];
measure q[1] -> c[1];
measure q[2] -> c[2];
measure r[0] -> d[0];
measure r[1] -> d[1];
measure r[2] -> d[2];
"""
expected_dag = circuit_to_dag(QuantumCircuit.from_qasm_str(expected_result))
self.assertEqual(dag_circuit, expected_dag)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test for the converter dag dependency to circuit and circuit to dag
dependency."""
import unittest
from qiskit.converters.dagdependency_to_circuit import dagdependency_to_circuit
from qiskit.converters.circuit_to_dagdependency import circuit_to_dagdependency
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
class TestCircuitToDagCanonical(QiskitTestCase):
"""Test QuantumCircuit to DAGDependency."""
def test_circuit_and_dag_canonical(self):
"""Check convert to dag dependency and back"""
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit_in = QuantumCircuit(qr, cr)
circuit_in.h(qr[0])
circuit_in.h(qr[1])
circuit_in.measure(qr[0], cr[0])
circuit_in.measure(qr[1], cr[1])
circuit_in.x(qr[0]).c_if(cr, 0x3)
circuit_in.measure(qr[0], cr[0])
circuit_in.measure(qr[1], cr[1])
circuit_in.measure(qr[2], cr[2])
dag_dependency = circuit_to_dagdependency(circuit_in)
circuit_out = dagdependency_to_circuit(dag_dependency)
self.assertEqual(circuit_out, circuit_in)
def test_circuit_and_dag_canonical2(self):
"""Check convert to dag dependency and back
also when the option ``create_preds_and_succs`` is False."""
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit_in = QuantumCircuit(qr, cr)
circuit_in.h(qr[0])
circuit_in.h(qr[1])
circuit_in.measure(qr[0], cr[0])
circuit_in.measure(qr[1], cr[1])
circuit_in.x(qr[0]).c_if(cr, 0x3)
circuit_in.measure(qr[0], cr[0])
circuit_in.measure(qr[1], cr[1])
circuit_in.measure(qr[2], cr[2])
dag_dependency = circuit_to_dagdependency(circuit_in, create_preds_and_succs=False)
circuit_out = dagdependency_to_circuit(dag_dependency)
self.assertEqual(circuit_out, circuit_in)
def test_calibrations(self):
"""Test that calibrations are properly copied over."""
circuit_in = QuantumCircuit(1)
circuit_in.add_calibration("h", [0], None)
self.assertEqual(len(circuit_in.calibrations), 1)
dag_dependency = circuit_to_dagdependency(circuit_in)
self.assertEqual(len(dag_dependency.calibrations), 1)
circuit_out = dagdependency_to_circuit(dag_dependency)
self.assertEqual(len(circuit_out.calibrations), 1)
def test_metadata(self):
"""Test circuit metadata is preservered through conversion."""
meta_dict = {"experiment_id": "1234", "execution_number": 4}
qr = QuantumRegister(2)
circuit_in = QuantumCircuit(qr, metadata=meta_dict)
circuit_in.h(qr[0])
circuit_in.cx(qr[0], qr[1])
circuit_in.measure_all()
dag_dependency = circuit_to_dagdependency(circuit_in)
self.assertEqual(dag_dependency.metadata, meta_dict)
circuit_out = dagdependency_to_circuit(dag_dependency)
self.assertEqual(circuit_out.metadata, meta_dict)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for the converters."""
import math
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit import Gate, Qubit
from qiskit.quantum_info import Operator
from qiskit.test import QiskitTestCase
from qiskit.exceptions import QiskitError
class TestCircuitToGate(QiskitTestCase):
"""Test QuantumCircuit to Gate"""
def test_simple_circuit(self):
"""test simple circuit"""
qr1 = QuantumRegister(4, "qr1")
qr2 = QuantumRegister(3, "qr2")
qr3 = QuantumRegister(3, "qr3")
circ = QuantumCircuit(qr1, qr2, qr3)
circ.cx(qr1[1], qr2[2])
gate = circ.to_gate()
q = QuantumRegister(10, "q")
self.assertIsInstance(gate, Gate)
self.assertEqual(gate.definition[0].qubits, (q[1], q[6]))
def test_circuit_with_registerless_bits(self):
"""Test a circuit with registerless bits can be converted to a gate."""
qr1 = QuantumRegister(2)
qubits = [Qubit(), Qubit(), Qubit()]
qr2 = QuantumRegister(3)
circ = QuantumCircuit(qr1, qubits, qr2)
circ.cx(3, 5)
gate = circ.to_gate()
self.assertIsInstance(gate, Gate)
self.assertEqual(gate.num_qubits, len(qr1) + len(qubits) + len(qr2))
gate_definition = gate.definition
cx = gate_definition.data[0]
self.assertEqual(cx.qubits, (gate_definition.qubits[3], gate_definition.qubits[5]))
self.assertEqual(cx.clbits, ())
def test_circuit_with_overlapping_registers(self):
"""Test that the conversion works when the given circuit has bits that are contained in more
than one register."""
qubits = [Qubit() for _ in [None] * 10]
qr1 = QuantumRegister(bits=qubits[:6])
qr2 = QuantumRegister(bits=qubits[4:])
circ = QuantumCircuit(qubits, qr1, qr2)
circ.cx(3, 5)
gate = circ.to_gate()
self.assertIsInstance(gate, Gate)
self.assertEqual(gate.num_qubits, len(qubits))
gate_definition = gate.definition
cx = gate_definition.data[0]
self.assertEqual(cx.qubits, (gate_definition.qubits[3], gate_definition.qubits[5]))
self.assertEqual(cx.clbits, ())
def test_raises(self):
"""test circuit which can't be converted raises"""
circ1 = QuantumCircuit(3)
circ1.x(0)
circ1.cx(0, 1)
circ1.barrier()
circ2 = QuantumCircuit(1, 1)
circ2.measure(0, 0)
circ3 = QuantumCircuit(1)
circ3.x(0)
circ3.reset(0)
with self.assertRaises(QiskitError): # TODO: accept barrier
circ1.to_gate()
with self.assertRaises(QiskitError): # measure and reset are not valid
circ2.to_gate()
def test_generated_gate_inverse(self):
"""Test inverse of generated gate works."""
qr1 = QuantumRegister(2, "qr1")
circ = QuantumCircuit(qr1)
circ.cx(qr1[1], qr1[0])
gate = circ.to_gate()
out_gate = gate.inverse()
self.assertIsInstance(out_gate, Gate)
def test_to_gate_label(self):
"""Test label setting."""
qr1 = QuantumRegister(2, "qr1")
circ = QuantumCircuit(qr1, name="a circuit name")
circ.cx(qr1[1], qr1[0])
gate = circ.to_gate(label="a label")
self.assertEqual(gate.label, "a label")
def test_zero_operands(self):
"""Test that a gate can be created, even if it has zero operands."""
base = QuantumCircuit(global_phase=math.pi)
gate = base.to_gate()
self.assertEqual(gate.num_qubits, 0)
self.assertEqual(gate.num_clbits, 0)
self.assertEqual(gate.definition, base)
compound = QuantumCircuit(1)
compound.append(gate, [], [])
np.testing.assert_allclose(-np.eye(2), Operator(compound), atol=1e-16)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for the converters."""
import math
import unittest
import numpy as np
from qiskit.converters import circuit_to_instruction
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Qubit, Clbit, Instruction
from qiskit.circuit import Parameter
from qiskit.quantum_info import Operator
from qiskit.test import QiskitTestCase
from qiskit.exceptions import QiskitError
class TestCircuitToInstruction(QiskitTestCase):
"""Test Circuit to Instruction."""
def test_flatten_circuit_registers(self):
"""Check correct flattening"""
qr1 = QuantumRegister(4, "qr1")
qr2 = QuantumRegister(3, "qr2")
qr3 = QuantumRegister(3, "qr3")
cr1 = ClassicalRegister(4, "cr1")
cr2 = ClassicalRegister(1, "cr2")
circ = QuantumCircuit(qr1, qr2, qr3, cr1, cr2)
circ.cx(qr1[1], qr2[2])
circ.measure(qr3[0], cr2[0])
inst = circuit_to_instruction(circ)
q = QuantumRegister(10, "q")
c = ClassicalRegister(5, "c")
self.assertEqual(inst.definition[0].qubits, (q[1], q[6]))
self.assertEqual(inst.definition[1].qubits, (q[7],))
self.assertEqual(inst.definition[1].clbits, (c[4],))
def test_flatten_registers_of_circuit_single_bit_cond(self):
"""Check correct mapping of registers gates conditioned on single classical bits."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(3, "qr2")
cr1 = ClassicalRegister(3, "cr1")
cr2 = ClassicalRegister(3, "cr2")
circ = QuantumCircuit(qr1, qr2, cr1, cr2)
circ.h(qr1[0]).c_if(cr1[1], True)
circ.h(qr2[1]).c_if(cr2[0], False)
circ.cx(qr1[1], qr2[2]).c_if(cr2[2], True)
circ.measure(qr2[2], cr2[0])
inst = circuit_to_instruction(circ)
q = QuantumRegister(5, "q")
c = ClassicalRegister(6, "c")
self.assertEqual(inst.definition[0].qubits, (q[0],))
self.assertEqual(inst.definition[1].qubits, (q[3],))
self.assertEqual(inst.definition[2].qubits, (q[1], q[4]))
self.assertEqual(inst.definition[0].operation.condition, (c[1], True))
self.assertEqual(inst.definition[1].operation.condition, (c[3], False))
self.assertEqual(inst.definition[2].operation.condition, (c[5], True))
def test_flatten_circuit_registerless(self):
"""Test that the conversion works when the given circuit has bits that are not contained in
any register."""
qr1 = QuantumRegister(2)
qubits = [Qubit(), Qubit(), Qubit()]
qr2 = QuantumRegister(3)
cr1 = ClassicalRegister(2)
clbits = [Clbit(), Clbit(), Clbit()]
cr2 = ClassicalRegister(3)
circ = QuantumCircuit(qr1, qubits, qr2, cr1, clbits, cr2)
circ.cx(3, 5)
circ.measure(4, 4)
inst = circuit_to_instruction(circ)
self.assertEqual(inst.num_qubits, len(qr1) + len(qubits) + len(qr2))
self.assertEqual(inst.num_clbits, len(cr1) + len(clbits) + len(cr2))
inst_definition = inst.definition
cx = inst_definition.data[0]
measure = inst_definition.data[1]
self.assertEqual(cx.qubits, (inst_definition.qubits[3], inst_definition.qubits[5]))
self.assertEqual(cx.clbits, ())
self.assertEqual(measure.qubits, (inst_definition.qubits[4],))
self.assertEqual(measure.clbits, (inst_definition.clbits[4],))
def test_flatten_circuit_overlapping_registers(self):
"""Test that the conversion works when the given circuit has bits that are contained in more
than one register."""
qubits = [Qubit() for _ in [None] * 10]
qr1 = QuantumRegister(bits=qubits[:6])
qr2 = QuantumRegister(bits=qubits[4:])
clbits = [Clbit() for _ in [None] * 10]
cr1 = ClassicalRegister(bits=clbits[:6])
cr2 = ClassicalRegister(bits=clbits[4:])
circ = QuantumCircuit(qubits, clbits, qr1, qr2, cr1, cr2)
circ.cx(3, 5)
circ.measure(4, 4)
inst = circuit_to_instruction(circ)
self.assertEqual(inst.num_qubits, len(qubits))
self.assertEqual(inst.num_clbits, len(clbits))
inst_definition = inst.definition
cx = inst_definition.data[0]
measure = inst_definition.data[1]
self.assertEqual(cx.qubits, (inst_definition.qubits[3], inst_definition.qubits[5]))
self.assertEqual(cx.clbits, ())
self.assertEqual(measure.qubits, (inst_definition.qubits[4],))
self.assertEqual(measure.clbits, (inst_definition.clbits[4],))
def test_flatten_parameters(self):
"""Verify parameters from circuit are moved to instruction.params"""
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
phi = Parameter("phi")
sum_ = theta + phi
qc.rz(theta, qr[0])
qc.rz(phi, qr[1])
qc.u(theta, phi, 0, qr[2])
qc.rz(sum_, qr[0])
inst = circuit_to_instruction(qc)
self.assertEqual(inst.params, [phi, theta])
self.assertEqual(inst.definition[0].operation.params, [theta])
self.assertEqual(inst.definition[1].operation.params, [phi])
self.assertEqual(inst.definition[2].operation.params, [theta, phi, 0])
self.assertEqual(str(inst.definition[3].operation.params[0]), "phi + theta")
def test_underspecified_parameter_map_raises(self):
"""Verify we raise if not all circuit parameters are present in parameter_map."""
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
phi = Parameter("phi")
sum_ = theta + phi
gamma = Parameter("gamma")
qc.rz(theta, qr[0])
qc.rz(phi, qr[1])
qc.u(theta, phi, 0, qr[2])
qc.rz(sum_, qr[0])
self.assertRaises(QiskitError, circuit_to_instruction, qc, {theta: gamma})
# Raise if provided more parameters than present in the circuit
delta = Parameter("delta")
self.assertRaises(
QiskitError, circuit_to_instruction, qc, {theta: gamma, phi: phi, delta: delta}
)
def test_parameter_map(self):
"""Verify alternate parameter specification"""
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
phi = Parameter("phi")
sum_ = theta + phi
gamma = Parameter("gamma")
qc.rz(theta, qr[0])
qc.rz(phi, qr[1])
qc.u(theta, phi, 0, qr[2])
qc.rz(sum_, qr[0])
inst = circuit_to_instruction(qc, {theta: gamma, phi: phi})
self.assertEqual(inst.params, [gamma, phi])
self.assertEqual(inst.definition[0].operation.params, [gamma])
self.assertEqual(inst.definition[1].operation.params, [phi])
self.assertEqual(inst.definition[2].operation.params, [gamma, phi, 0])
self.assertEqual(str(inst.definition[3].operation.params[0]), "gamma + phi")
def test_registerless_classical_bits(self):
"""Test that conditions on registerless classical bits can be handled during the conversion.
Regression test of gh-7394."""
expected = QuantumCircuit([Qubit(), Clbit()])
expected.h(0).c_if(expected.clbits[0], 0)
test = circuit_to_instruction(expected)
self.assertIsInstance(test, Instruction)
self.assertIsInstance(test.definition, QuantumCircuit)
self.assertEqual(len(test.definition.data), 1)
test_instruction = test.definition.data[0]
expected_instruction = expected.data[0]
self.assertIs(type(test_instruction.operation), type(expected_instruction.operation))
self.assertEqual(test_instruction.operation.condition, (test.definition.clbits[0], 0))
def test_zero_operands(self):
"""Test that an instruction can be created, even if it has zero operands."""
base = QuantumCircuit(global_phase=math.pi)
instruction = base.to_instruction()
self.assertEqual(instruction.num_qubits, 0)
self.assertEqual(instruction.num_clbits, 0)
self.assertEqual(instruction.definition, base)
compound = QuantumCircuit(1)
compound.append(instruction, [], [])
np.testing.assert_allclose(-np.eye(2), Operator(compound), atol=1e-16)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test for the converter dag dependency to dag circuit and
dag circuit to dag dependency."""
import unittest
from qiskit.converters.circuit_to_dag import circuit_to_dag
from qiskit.converters.dag_to_dagdependency import dag_to_dagdependency
from qiskit.converters.dagdependency_to_dag import dagdependency_to_dag
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
class TestCircuitToDagDependency(QiskitTestCase):
"""Test DAGCircuit to DAGDependency."""
def test_circuit_and_dag_dependency(self):
"""Check convert to dag dependency and back"""
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit_in = QuantumCircuit(qr, cr)
circuit_in.h(qr[0])
circuit_in.h(qr[1])
circuit_in.measure(qr[0], cr[0])
circuit_in.measure(qr[1], cr[1])
circuit_in.x(qr[0]).c_if(cr, 0x3)
circuit_in.measure(qr[0], cr[0])
circuit_in.measure(qr[1], cr[1])
circuit_in.measure(qr[2], cr[2])
dag_in = circuit_to_dag(circuit_in)
dag_dependency = dag_to_dagdependency(dag_in)
dag_out = dagdependency_to_dag(dag_dependency)
self.assertEqual(dag_out, dag_in)
def test_circuit_and_dag_dependency2(self):
"""Check convert to dag dependency and back
also when the option ``create_preds_and_succs`` is False."""
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit_in = QuantumCircuit(qr, cr)
circuit_in.h(qr[0])
circuit_in.h(qr[1])
circuit_in.measure(qr[0], cr[0])
circuit_in.measure(qr[1], cr[1])
circuit_in.x(qr[0]).c_if(cr, 0x3)
circuit_in.measure(qr[0], cr[0])
circuit_in.measure(qr[1], cr[1])
circuit_in.measure(qr[2], cr[2])
dag_in = circuit_to_dag(circuit_in)
dag_dependency = dag_to_dagdependency(dag_in, create_preds_and_succs=False)
dag_out = dagdependency_to_dag(dag_dependency)
self.assertEqual(dag_out, dag_in)
def test_metadata(self):
"""Test circuit metadata is preservered through conversion."""
meta_dict = {"experiment_id": "1234", "execution_number": 4}
qr = QuantumRegister(2)
circuit_in = QuantumCircuit(qr, metadata=meta_dict)
circuit_in.h(qr[0])
circuit_in.cx(qr[0], qr[1])
circuit_in.measure_all()
dag = circuit_to_dag(circuit_in)
self.assertEqual(dag.metadata, meta_dict)
dag_dependency = dag_to_dagdependency(dag)
self.assertEqual(dag_dependency.metadata, meta_dict)
dag_out = dagdependency_to_dag(dag_dependency)
self.assertEqual(dag_out.metadata, meta_dict)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test functionality to collect, split and consolidate blocks from DAGCircuits."""
import unittest
from qiskit import QuantumRegister, ClassicalRegister
from qiskit.converters import (
circuit_to_dag,
circuit_to_dagdependency,
circuit_to_instruction,
dag_to_circuit,
dagdependency_to_circuit,
)
from qiskit.test import QiskitTestCase
from qiskit.circuit import QuantumCircuit, Measure, Clbit
from qiskit.dagcircuit.collect_blocks import BlockCollector, BlockSplitter, BlockCollapser
class TestCollectBlocks(QiskitTestCase):
"""Tests to verify correctness of collecting, splitting, and consolidating blocks
from DAGCircuit and DAGDependency. Additional tests appear as a part of
CollectLinearFunctions and CollectCliffords passes.
"""
def test_collect_gates_from_dagcircuit_1(self):
"""Test collecting CX gates from DAGCircuits."""
qc = QuantumCircuit(5)
qc.cx(0, 1)
qc.cx(0, 2)
qc.z(0)
qc.cx(0, 3)
qc.cx(0, 4)
block_collector = BlockCollector(circuit_to_dag(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name == "cx",
split_blocks=False,
min_block_size=2,
)
# The middle z-gate leads to two blocks of size 2 each
self.assertEqual(len(blocks), 2)
self.assertEqual(len(blocks[0]), 2)
self.assertEqual(len(blocks[1]), 2)
def test_collect_gates_from_dagcircuit_2(self):
"""Test collecting both CX and Z gates from DAGCircuits."""
qc = QuantumCircuit(5)
qc.cx(0, 1)
qc.cx(0, 2)
qc.z(0)
qc.cx(0, 3)
qc.cx(0, 4)
block_collector = BlockCollector(circuit_to_dag(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "z"],
split_blocks=False,
min_block_size=1,
)
# All of the gates are part of a single block
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 5)
def test_collect_gates_from_dagcircuit_3(self):
"""Test collecting CX gates from DAGCircuits."""
qc = QuantumCircuit(5)
qc.cx(0, 1)
qc.cx(0, 2)
qc.z(0)
qc.cx(1, 3)
qc.cx(0, 3)
qc.cx(0, 4)
block_collector = BlockCollector(circuit_to_dag(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx"],
split_blocks=False,
min_block_size=1,
)
# We should end up with two CX blocks: even though there is "a path
# around z(0)", without commutativity analysis z(0) prevents from
# including all CX-gates into the same block
self.assertEqual(len(blocks), 2)
def test_collect_gates_from_dagdependency_1(self):
"""Test collecting CX gates from DAGDependency."""
qc = QuantumCircuit(5)
qc.cx(0, 1)
qc.cx(0, 2)
qc.z(0)
qc.cx(0, 3)
qc.cx(0, 4)
block_collector = BlockCollector(circuit_to_dagdependency(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name == "cx",
split_blocks=False,
min_block_size=1,
)
# The middle z-gate commutes with CX-gates, which leads to a single block of length 4
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 4)
def test_collect_gates_from_dagdependency_2(self):
"""Test collecting both CX and Z gates from DAGDependency."""
qc = QuantumCircuit(5)
qc.cx(0, 1)
qc.cx(0, 2)
qc.z(0)
qc.cx(0, 3)
qc.cx(0, 4)
block_collector = BlockCollector(circuit_to_dagdependency(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "z"],
split_blocks=False,
min_block_size=1,
)
# All the gates are part of a single block
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 5)
def test_collect_and_split_gates_from_dagcircuit(self):
"""Test collecting and splitting blocks from DAGCircuit."""
qc = QuantumCircuit(6)
qc.cx(0, 1)
qc.cx(3, 5)
qc.cx(2, 4)
qc.swap(1, 0)
qc.cz(5, 3)
block_collector = BlockCollector(circuit_to_dag(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: True,
split_blocks=False,
min_block_size=1,
)
# All the gates are part of a single block
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 5)
# Split the first block into sub-blocks over disjoint qubit sets
# We should get 3 sub-blocks
split_blocks = BlockSplitter().run(blocks[0])
self.assertEqual(len(split_blocks), 3)
def test_collect_and_split_gates_from_dagdependency(self):
"""Test collecting and splitting blocks from DAGDependecy."""
qc = QuantumCircuit(6)
qc.cx(0, 1)
qc.cx(3, 5)
qc.cx(2, 4)
qc.swap(1, 0)
qc.cz(5, 3)
block_collector = BlockCollector(circuit_to_dagdependency(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: True,
split_blocks=False,
min_block_size=1,
)
# All the gates are part of a single block
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 5)
# Split the first block into sub-blocks over disjoint qubit sets
# We should get 3 sub-blocks
split_blocks = BlockSplitter().run(blocks[0])
self.assertEqual(len(split_blocks), 3)
def test_circuit_has_measure(self):
"""Test that block collection works properly when there is a measure in the
middle of the circuit."""
qc = QuantumCircuit(2, 1)
qc.cx(1, 0)
qc.x(0)
qc.x(1)
qc.measure(0, 0)
qc.x(0)
qc.cx(1, 0)
block_collector = BlockCollector(circuit_to_dag(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["x", "cx"],
split_blocks=False,
min_block_size=1,
)
# measure prevents combining the two blocks
self.assertEqual(len(blocks), 2)
self.assertEqual(len(blocks[0]), 3)
self.assertEqual(len(blocks[1]), 2)
def test_circuit_has_measure_dagdependency(self):
"""Test that block collection works properly when there is a measure in the
middle of the circuit."""
qc = QuantumCircuit(2, 1)
qc.cx(1, 0)
qc.x(0)
qc.x(1)
qc.measure(0, 0)
qc.x(0)
qc.cx(1, 0)
block_collector = BlockCollector(circuit_to_dagdependency(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["x", "cx"],
split_blocks=False,
min_block_size=1,
)
# measure prevents combining the two blocks
self.assertEqual(len(blocks), 2)
self.assertEqual(len(blocks[0]), 3)
self.assertEqual(len(blocks[1]), 2)
def test_circuit_has_conditional_gates(self):
"""Test that block collection works properly when there the circuit
contains conditional gates."""
qc = QuantumCircuit(2, 1)
qc.x(0)
qc.x(1)
qc.cx(1, 0)
qc.x(1).c_if(0, 1)
qc.x(0)
qc.x(1)
qc.cx(0, 1)
# If the filter_function does not look at conditions, we should collect all
# gates into the block.
block_collector = BlockCollector(circuit_to_dag(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["x", "cx"],
split_blocks=False,
min_block_size=1,
)
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 7)
# If the filter_function does look at conditions, we should not collect the middle
# conditional gate (note that x(1) following the measure is collected into the first
# block).
block_collector = BlockCollector(circuit_to_dag(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["x", "cx"] and not getattr(node.op, "condition", None),
split_blocks=False,
min_block_size=1,
)
self.assertEqual(len(blocks), 2)
self.assertEqual(len(blocks[0]), 4)
self.assertEqual(len(blocks[1]), 2)
def test_circuit_has_conditional_gates_dagdependency(self):
"""Test that block collection works properly when there the circuit
contains conditional gates."""
qc = QuantumCircuit(2, 1)
qc.x(0)
qc.x(1)
qc.cx(1, 0)
qc.x(1).c_if(0, 1)
qc.x(0)
qc.x(1)
qc.cx(0, 1)
# If the filter_function does not look at conditions, we should collect all
# gates into the block.
block_collector = BlockCollector(circuit_to_dagdependency(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["x", "cx"],
split_blocks=False,
min_block_size=1,
)
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 7)
# If the filter_function does look at conditions, we should not collect the middle
# conditional gate (note that x(1) following the measure is collected into the first
# block).
block_collector = BlockCollector(circuit_to_dag(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["x", "cx"] and not getattr(node.op, "condition", None),
split_blocks=False,
min_block_size=1,
)
self.assertEqual(len(blocks), 2)
self.assertEqual(len(blocks[0]), 4)
self.assertEqual(len(blocks[1]), 2)
def test_multiple_collection_methods(self):
"""Test that block collection allows to collect blocks using several different
filter functions."""
qc = QuantumCircuit(5)
qc.cx(0, 1)
qc.cx(0, 2)
qc.swap(1, 4)
qc.swap(4, 3)
qc.z(0)
qc.z(1)
qc.z(2)
qc.z(3)
qc.z(4)
qc.swap(3, 4)
qc.cx(0, 3)
qc.cx(0, 4)
block_collector = BlockCollector(circuit_to_dag(qc))
linear_blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "swap"],
split_blocks=False,
min_block_size=1,
)
cx_blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx"],
split_blocks=False,
min_block_size=1,
)
swapz_blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["swap", "z"],
split_blocks=False,
min_block_size=1,
)
# We should end up with two linear blocks
self.assertEqual(len(linear_blocks), 2)
self.assertEqual(len(linear_blocks[0]), 4)
self.assertEqual(len(linear_blocks[1]), 3)
# We should end up with two cx blocks
self.assertEqual(len(cx_blocks), 2)
self.assertEqual(len(cx_blocks[0]), 2)
self.assertEqual(len(cx_blocks[1]), 2)
# We should end up with one swap,z blocks
self.assertEqual(len(swapz_blocks), 1)
self.assertEqual(len(swapz_blocks[0]), 8)
def test_min_block_size(self):
"""Test that the option min_block_size for collecting blocks works correctly."""
# original circuit
circuit = QuantumCircuit(2)
circuit.cx(0, 1)
circuit.h(0)
circuit.cx(0, 1)
circuit.cx(1, 0)
circuit.h(0)
circuit.cx(0, 1)
circuit.cx(1, 0)
circuit.cx(0, 1)
block_collector = BlockCollector(circuit_to_dag(circuit))
# When min_block_size = 1, we should obtain 3 linear blocks
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "swap"],
split_blocks=False,
min_block_size=1,
)
self.assertEqual(len(blocks), 3)
# When min_block_size = 2, we should obtain 2 linear blocks
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "swap"],
split_blocks=False,
min_block_size=2,
)
self.assertEqual(len(blocks), 2)
# When min_block_size = 3, we should obtain 1 linear block
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "swap"],
split_blocks=False,
min_block_size=3,
)
self.assertEqual(len(blocks), 1)
# When min_block_size = 4, we should obtain no linear blocks
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "swap"],
split_blocks=False,
min_block_size=4,
)
self.assertEqual(len(blocks), 0)
def test_split_blocks(self):
"""Test that splitting blocks of nodes into sub-blocks works correctly."""
# original circuit is linear
circuit = QuantumCircuit(5)
circuit.cx(0, 2)
circuit.cx(1, 4)
circuit.cx(2, 0)
circuit.cx(0, 3)
circuit.swap(3, 2)
circuit.swap(4, 1)
block_collector = BlockCollector(circuit_to_dag(circuit))
# If we do not split block into sub-blocks, we expect a single linear block.
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "swap"],
split_blocks=False,
min_block_size=2,
)
self.assertEqual(len(blocks), 1)
# If we do split block into sub-blocks, we expect two linear blocks:
# one over qubits {0, 2, 3}, and another over qubits {1, 4}.
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "swap"],
split_blocks=True,
min_block_size=2,
)
self.assertEqual(len(blocks), 2)
def test_do_not_split_blocks(self):
"""Test that splitting blocks of nodes into sub-blocks works correctly."""
# original circuit is linear
circuit = QuantumCircuit(5)
circuit.cx(0, 3)
circuit.cx(0, 2)
circuit.cx(1, 4)
circuit.swap(4, 2)
block_collector = BlockCollector(circuit_to_dagdependency(circuit))
# Check that we have a single linear block
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "swap"],
split_blocks=True,
min_block_size=1,
)
self.assertEqual(len(blocks), 1)
def test_collect_blocks_with_cargs(self):
"""Test collecting and collapsing blocks with classical bits appearing as cargs."""
qc = QuantumCircuit(3)
qc.h(0)
qc.h(1)
qc.h(2)
qc.measure_all()
dag = circuit_to_dag(qc)
# Collect all measure instructions
blocks = BlockCollector(dag).collect_all_matching_blocks(
lambda node: isinstance(node.op, Measure), split_blocks=False, min_block_size=1
)
# We should have a single block consisting of 3 measures
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 3)
self.assertEqual(blocks[0][0].op, Measure())
self.assertEqual(blocks[0][1].op, Measure())
self.assertEqual(blocks[0][2].op, Measure())
def _collapse_fn(circuit):
op = circuit_to_instruction(circuit)
op.name = "COLLAPSED"
return op
# Collapse block with measures into a single "COLLAPSED" block
dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn)
collapsed_qc = dag_to_circuit(dag)
self.assertEqual(len(collapsed_qc.data), 5)
self.assertEqual(collapsed_qc.data[0].operation.name, "h")
self.assertEqual(collapsed_qc.data[1].operation.name, "h")
self.assertEqual(collapsed_qc.data[2].operation.name, "h")
self.assertEqual(collapsed_qc.data[3].operation.name, "barrier")
self.assertEqual(collapsed_qc.data[4].operation.name, "COLLAPSED")
self.assertEqual(collapsed_qc.data[4].operation.definition.num_qubits, 3)
self.assertEqual(collapsed_qc.data[4].operation.definition.num_clbits, 3)
def test_collect_blocks_with_cargs_dagdependency(self):
"""Test collecting and collapsing blocks with classical bits appearing as cargs,
using DAGDependency."""
qc = QuantumCircuit(3)
qc.h(0)
qc.h(1)
qc.h(2)
qc.measure_all()
dag = circuit_to_dagdependency(qc)
# Collect all measure instructions
blocks = BlockCollector(dag).collect_all_matching_blocks(
lambda node: isinstance(node.op, Measure), split_blocks=False, min_block_size=1
)
# We should have a single block consisting of 3 measures
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 3)
self.assertEqual(blocks[0][0].op, Measure())
self.assertEqual(blocks[0][1].op, Measure())
self.assertEqual(blocks[0][2].op, Measure())
def _collapse_fn(circuit):
op = circuit_to_instruction(circuit)
op.name = "COLLAPSED"
return op
# Collapse block with measures into a single "COLLAPSED" block
dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn)
collapsed_qc = dagdependency_to_circuit(dag)
self.assertEqual(len(collapsed_qc.data), 5)
self.assertEqual(collapsed_qc.data[0].operation.name, "h")
self.assertEqual(collapsed_qc.data[1].operation.name, "h")
self.assertEqual(collapsed_qc.data[2].operation.name, "h")
self.assertEqual(collapsed_qc.data[3].operation.name, "barrier")
self.assertEqual(collapsed_qc.data[4].operation.name, "COLLAPSED")
self.assertEqual(collapsed_qc.data[4].operation.definition.num_qubits, 3)
self.assertEqual(collapsed_qc.data[4].operation.definition.num_clbits, 3)
def test_collect_blocks_with_clbits(self):
"""Test collecting and collapsing blocks with classical bits appearing under
condition."""
qc = QuantumCircuit(4, 3)
qc.cx(0, 1).c_if(0, 1)
qc.cx(2, 3)
qc.cx(1, 2)
qc.cx(0, 1)
qc.cx(2, 3).c_if(1, 0)
dag = circuit_to_dag(qc)
# Collect all cx gates (including the conditional ones)
blocks = BlockCollector(dag).collect_all_matching_blocks(
lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1
)
# We should have a single block consisting of all CX nodes
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 5)
def _collapse_fn(circuit):
op = circuit_to_instruction(circuit)
op.name = "COLLAPSED"
return op
# Collapse block with measures into a single "COLLAPSED" block
dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn)
collapsed_qc = dag_to_circuit(dag)
self.assertEqual(len(collapsed_qc.data), 1)
self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED")
self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 4)
self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 2)
def test_collect_blocks_with_clbits_dagdependency(self):
"""Test collecting and collapsing blocks with classical bits appearing
under conditions, using DAGDependency."""
qc = QuantumCircuit(4, 3)
qc.cx(0, 1).c_if(0, 1)
qc.cx(2, 3)
qc.cx(1, 2)
qc.cx(0, 1)
qc.cx(2, 3).c_if(1, 0)
dag = circuit_to_dagdependency(qc)
# Collect all cx gates (including the conditional ones)
blocks = BlockCollector(dag).collect_all_matching_blocks(
lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1
)
# We should have a single block consisting of all CX nodes
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 5)
def _collapse_fn(circuit):
op = circuit_to_instruction(circuit)
op.name = "COLLAPSED"
return op
# Collapse block with measures into a single "COLLAPSED" block
dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn)
collapsed_qc = dagdependency_to_circuit(dag)
self.assertEqual(len(collapsed_qc.data), 1)
self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED")
self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 4)
self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 2)
def test_collect_blocks_with_clbits2(self):
"""Test collecting and collapsing blocks with classical bits appearing under
condition."""
qreg = QuantumRegister(4, "qr")
creg = ClassicalRegister(3, "cr")
cbit = Clbit()
qc = QuantumCircuit(qreg, creg, [cbit])
qc.cx(0, 1).c_if(creg[1], 1)
qc.cx(2, 3).c_if(cbit, 0)
qc.cx(1, 2)
qc.cx(0, 1).c_if(creg[2], 1)
dag = circuit_to_dag(qc)
# Collect all cx gates (including the conditional ones)
blocks = BlockCollector(dag).collect_all_matching_blocks(
lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1
)
# We should have a single block consisting of all CX nodes
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 4)
def _collapse_fn(circuit):
op = circuit_to_instruction(circuit)
op.name = "COLLAPSED"
return op
# Collapse block with measures into a single "COLLAPSED" block
dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn)
collapsed_qc = dag_to_circuit(dag)
self.assertEqual(len(collapsed_qc.data), 1)
self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED")
self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 4)
self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 3)
def test_collect_blocks_with_clbits2_dagdependency(self):
"""Test collecting and collapsing blocks with classical bits appearing under
condition, using DAGDependency."""
qreg = QuantumRegister(4, "qr")
creg = ClassicalRegister(3, "cr")
cbit = Clbit()
qc = QuantumCircuit(qreg, creg, [cbit])
qc.cx(0, 1).c_if(creg[1], 1)
qc.cx(2, 3).c_if(cbit, 0)
qc.cx(1, 2)
qc.cx(0, 1).c_if(creg[2], 1)
dag = circuit_to_dag(qc)
# Collect all cx gates (including the conditional ones)
blocks = BlockCollector(dag).collect_all_matching_blocks(
lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1
)
# We should have a single block consisting of all CX nodes
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 4)
def _collapse_fn(circuit):
op = circuit_to_instruction(circuit)
op.name = "COLLAPSED"
return op
# Collapse block with measures into a single "COLLAPSED" block
dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn)
collapsed_qc = dag_to_circuit(dag)
self.assertEqual(len(collapsed_qc.data), 1)
self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED")
self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 4)
self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 3)
def test_collect_blocks_with_cregs(self):
"""Test collecting and collapsing blocks with classical registers appearing under
condition."""
qreg = QuantumRegister(4, "qr")
creg = ClassicalRegister(3, "cr")
creg2 = ClassicalRegister(2, "cr2")
qc = QuantumCircuit(qreg, creg, creg2)
qc.cx(0, 1).c_if(creg, 3)
qc.cx(1, 2)
qc.cx(0, 1).c_if(creg[2], 1)
dag = circuit_to_dag(qc)
# Collect all cx gates (including the conditional ones)
blocks = BlockCollector(dag).collect_all_matching_blocks(
lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1
)
# We should have a single block consisting of all CX nodes
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 3)
def _collapse_fn(circuit):
op = circuit_to_instruction(circuit)
op.name = "COLLAPSED"
return op
# Collapse block with measures into a single "COLLAPSED" block
dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn)
collapsed_qc = dag_to_circuit(dag)
self.assertEqual(len(collapsed_qc.data), 1)
self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED")
self.assertEqual(len(collapsed_qc.data[0].operation.definition.cregs), 1)
self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 3)
self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 3)
def test_collect_blocks_with_cregs_dagdependency(self):
"""Test collecting and collapsing blocks with classical registers appearing under
condition, using DAGDependency."""
qreg = QuantumRegister(4, "qr")
creg = ClassicalRegister(3, "cr")
creg2 = ClassicalRegister(2, "cr2")
qc = QuantumCircuit(qreg, creg, creg2)
qc.cx(0, 1).c_if(creg, 3)
qc.cx(1, 2)
qc.cx(0, 1).c_if(creg[2], 1)
dag = circuit_to_dagdependency(qc)
# Collect all cx gates (including the conditional ones)
blocks = BlockCollector(dag).collect_all_matching_blocks(
lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1
)
# We should have a single block consisting of all CX nodes
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 3)
def _collapse_fn(circuit):
op = circuit_to_instruction(circuit)
op.name = "COLLAPSED"
return op
# Collapse block with measures into a single "COLLAPSED" block
dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn)
collapsed_qc = dagdependency_to_circuit(dag)
self.assertEqual(len(collapsed_qc.data), 1)
self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED")
self.assertEqual(len(collapsed_qc.data[0].operation.definition.cregs), 1)
self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 3)
self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 3)
def test_collect_blocks_backwards_dagcircuit(self):
"""Test collecting H gates from DAGCircuit in the forward vs. the reverse
directions."""
qc = QuantumCircuit(4)
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
qc.cx(1, 2)
qc.z(0)
qc.z(1)
qc.z(2)
qc.z(3)
block_collector = BlockCollector(circuit_to_dag(qc))
# When collecting in the forward direction, there are two blocks of
# single-qubit gates: the first of size 6, and the second of size 2.
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["h", "z"],
split_blocks=False,
min_block_size=1,
collect_from_back=False,
)
self.assertEqual(len(blocks), 2)
self.assertEqual(len(blocks[0]), 6)
self.assertEqual(len(blocks[1]), 2)
# When collecting in the backward direction, there are also two blocks of
# single-qubit ates: but now the first is of size 2, and the second is of size 6.
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["h", "z"],
split_blocks=False,
min_block_size=1,
collect_from_back=True,
)
self.assertEqual(len(blocks), 2)
self.assertEqual(len(blocks[0]), 2)
self.assertEqual(len(blocks[1]), 6)
def test_collect_blocks_backwards_dagdependency(self):
"""Test collecting H gates from DAGDependency in the forward vs. the reverse
directions."""
qc = QuantumCircuit(4)
qc.z(0)
qc.z(1)
qc.z(2)
qc.z(3)
qc.cx(1, 2)
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
block_collector = BlockCollector(circuit_to_dagdependency(qc))
# When collecting in the forward direction, there are two blocks of
# single-qubit gates: the first of size 6, and the second of size 2.
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["h", "z"],
split_blocks=False,
min_block_size=1,
collect_from_back=False,
)
self.assertEqual(len(blocks), 2)
self.assertEqual(len(blocks[0]), 6)
self.assertEqual(len(blocks[1]), 2)
# When collecting in the backward direction, there are also two blocks of
# single-qubit ates: but now the first is of size 1, and the second is of size 7
# (note that z(1) and CX(1, 2) commute).
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["h", "z"],
split_blocks=False,
min_block_size=1,
collect_from_back=True,
)
self.assertEqual(len(blocks), 2)
self.assertEqual(len(blocks[0]), 1)
self.assertEqual(len(blocks[1]), 7)
def test_split_layers_dagcircuit(self):
"""Test that splitting blocks of nodes into layers works correctly."""
# original circuit is linear
circuit = QuantumCircuit(5)
circuit.cx(0, 2)
circuit.cx(1, 4)
circuit.cx(2, 0)
circuit.cx(0, 3)
circuit.swap(3, 2)
circuit.swap(4, 1)
block_collector = BlockCollector(circuit_to_dag(circuit))
# If we split the gates into depth-1 layers, we expect four linear blocks:
# CX(0, 2), CX(1, 4)
# CX(2, 0), CX(4, 1)
# CX(0, 3)
# CX(3, 2)
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "swap"],
split_blocks=False,
min_block_size=1,
split_layers=True,
)
self.assertEqual(len(blocks), 4)
self.assertEqual(len(blocks[0]), 2)
self.assertEqual(len(blocks[1]), 2)
self.assertEqual(len(blocks[2]), 1)
self.assertEqual(len(blocks[3]), 1)
def test_split_layers_dagdependency(self):
"""Test that splitting blocks of nodes into layers works correctly."""
# original circuit is linear
circuit = QuantumCircuit(5)
circuit.cx(0, 2)
circuit.cx(1, 4)
circuit.cx(2, 0)
circuit.cx(0, 3)
circuit.swap(3, 2)
circuit.swap(4, 1)
block_collector = BlockCollector(circuit_to_dagdependency(circuit))
# If we split the gates into depth-1 layers, we expect four linear blocks:
# CX(0, 2), CX(1, 4)
# CX(2, 0), CX(4, 1)
# CX(0, 3)
# CX(3, 2)
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "swap"],
split_blocks=False,
min_block_size=1,
split_layers=True,
)
self.assertEqual(len(blocks), 4)
self.assertEqual(len(blocks[0]), 2)
self.assertEqual(len(blocks[1]), 2)
self.assertEqual(len(blocks[2]), 1)
self.assertEqual(len(blocks[3]), 1)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
import os
import sys
cwd = os.getcwd()
qiskit_dir = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(cwd))))
sys.path.append(qiskit_dir)
from qiskit import IBMQ
from qiskit.tools.jupyter import *
IBMQ.load_account()
%qiskit_backend_overview
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
import os
import sys
cwd = os.getcwd()
qiskit_dir = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(cwd))))
sys.path.append(qiskit_dir)
from qiskit import BasicAer, execute
from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.compiler import transpile
from qiskit.tools.parallel import parallel_map
from qiskit.tools.monitor import job_monitor
from qiskit.tools.events import TextProgressBar
from qiskit.tools.jupyter import *
sim_backend = BasicAer.get_backend("qasm_simulator")
import time
def func(_):
time.sleep(0.1)
return 0
HTMLProgressBar()
parallel_map(func, list(range(10)));
%qiskit_progress_bar
parallel_map(func, list(range(10)));
TextProgressBar()
parallel_map(func, list(range(10)));
%qiskit_progress_bar -t text
parallel_map(func, list(range(10)));
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.cx(q[0], q[1])
qc.measure(q, c)
HTMLProgressBar()
qobj = transpile([qc] * 20, backend=sim_backend)
job_sim2 = execute([qc] * 10, backend=sim_backend)
job_monitor(job_sim2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""The Conditional Value at Risk (CVaR) measurement."""
import unittest
from test.python.opflow import QiskitOpflowTestCase
import numpy as np
from ddt import ddt, data
from qiskit import QuantumCircuit
from qiskit.utils import algorithm_globals
from qiskit.opflow import (
CVaRMeasurement,
StateFn,
Z,
I,
X,
Y,
Plus,
PauliSumOp,
PauliExpectation,
MatrixExpectation,
CVaRExpectation,
ListOp,
CircuitOp,
AerPauliExpectation,
MatrixOp,
OpflowError,
)
class TestCVaRMeasurement(QiskitOpflowTestCase):
"""Test the CVaR measurement."""
def expected_cvar(self, statevector, operator, alpha):
"""Compute the expected CVaR expected value."""
probabilities = statevector * np.conj(statevector)
# get energies
num_bits = int(np.log2(len(statevector)))
energies = []
for i, _ in enumerate(probabilities):
basis_state = np.binary_repr(i, num_bits)
energies += [operator.eval(basis_state).eval(basis_state)]
# sort ascending
i_sorted = np.argsort(energies)
energies = [energies[i] for i in i_sorted]
probabilities = [probabilities[i] for i in i_sorted]
# add up
result = 0
accumulated_probabilities = 0
for energy, probability in zip(energies, probabilities):
accumulated_probabilities += probability
if accumulated_probabilities <= alpha:
result += probability * energy
else: # final term
result += (alpha - accumulated_probabilities + probability) * energy
break
return result / alpha
def cleanup_algorithm_globals(self, massive):
"""Method used to reset the values of algorithm_globals."""
algorithm_globals.massive = massive
def test_cvar_simple(self):
"""Test a simple case with a single Pauli."""
theta = 1.2
qc = QuantumCircuit(1)
qc.ry(theta, 0)
statefn = StateFn(qc)
for alpha in [0.2, 0.4, 1]:
with self.subTest(alpha=alpha):
cvar = (CVaRMeasurement(Z, alpha) @ statefn).eval()
ref = self.expected_cvar(statefn.to_matrix(), Z, alpha)
self.assertAlmostEqual(cvar, ref)
def test_cvar_simple_with_coeff(self):
"""Test a simple case with a non-unity coefficient"""
theta = 2.2
qc = QuantumCircuit(1)
qc.ry(theta, 0)
statefn = StateFn(qc)
alpha = 0.2
cvar = ((-1 * CVaRMeasurement(Z, alpha)) @ statefn).eval()
ref = self.expected_cvar(statefn.to_matrix(), Z, alpha)
self.assertAlmostEqual(cvar, -1 * ref)
def test_add(self):
"""Test addition."""
theta = 2.2
qc = QuantumCircuit(1)
qc.ry(theta, 0)
statefn = StateFn(qc)
alpha = 0.2
cvar = -1 * CVaRMeasurement(Z, alpha)
ref = self.expected_cvar(statefn.to_matrix(), Z, alpha)
other = ~StateFn(I)
# test add in both directions
res1 = ((cvar + other) @ statefn).eval()
res2 = ((other + other) @ statefn).eval()
self.assertAlmostEqual(res1, 1 - ref)
self.assertAlmostEqual(res2, 1 - ref)
def invalid_input(self):
"""Test invalid input raises an error."""
op = Z
with self.subTest("alpha < 0"):
with self.assertRaises(ValueError):
_ = CVaRMeasurement(op, alpha=-0.2)
with self.subTest("alpha > 1"):
with self.assertRaises(ValueError):
_ = CVaRMeasurement(op, alpha=12.3)
with self.subTest("Single pauli operator not diagonal"):
op = Y
with self.assertRaises(OpflowError):
_ = CVaRMeasurement(op)
with self.subTest("Summed pauli operator not diagonal"):
op = X ^ Z + Z ^ I
with self.assertRaises(OpflowError):
_ = CVaRMeasurement(op)
with self.subTest("List operator not diagonal"):
op = ListOp([X ^ Z, Z ^ I])
with self.assertRaises(OpflowError):
_ = CVaRMeasurement(op)
with self.subTest("Matrix operator not diagonal"):
op = MatrixOp([[1, 1], [0, 1]])
with self.assertRaises(OpflowError):
_ = CVaRMeasurement(op)
def test_unsupported_operations(self):
"""Assert unsupported operations raise an error."""
cvar = CVaRMeasurement(Z)
attrs = ["to_matrix", "to_matrix_op", "to_density_matrix", "to_circuit_op", "sample"]
for attr in attrs:
with self.subTest(attr):
with self.assertRaises(NotImplementedError):
_ = getattr(cvar, attr)()
with self.subTest("adjoint"):
with self.assertRaises(OpflowError):
cvar.adjoint()
def test_cvar_on_paulisumop(self):
"""Test a large PauliSumOp is checked for diagonality efficiently.
Regression test for Qiskit/qiskit-terra#7573.
"""
op = PauliSumOp.from_list([("Z" * 30, 1)])
# assert global algorithm settings do not have massive calculations turned on
# -- which is the default, but better to be sure in the test!
# also add a cleanup so we're sure to reset to the original value after the test, even if
# the test would fail
self.addCleanup(self.cleanup_algorithm_globals, algorithm_globals.massive)
algorithm_globals.massive = False
cvar = CVaRMeasurement(op, alpha=0.1)
fake_probabilities = [0.2, 0.8]
fake_energies = [1, 2]
expectation = cvar.compute_cvar(fake_energies, fake_probabilities)
self.assertEqual(expectation, 1)
@ddt
class TestCVaRExpectation(QiskitOpflowTestCase):
"""Test the CVaR expectation object."""
def test_construction(self):
"""Test the correct operator expression is constructed."""
alpha = 0.5
base_expecation = PauliExpectation()
cvar_expecation = CVaRExpectation(alpha=alpha, expectation=base_expecation)
with self.subTest("single operator"):
op = ~StateFn(Z) @ Plus
expected = CVaRMeasurement(Z, alpha) @ Plus
cvar = cvar_expecation.convert(op)
self.assertEqual(cvar, expected)
with self.subTest("list operator"):
op = ~StateFn(ListOp([Z ^ Z, I ^ Z])) @ (Plus ^ Plus)
expected = ListOp(
[
CVaRMeasurement((Z ^ Z), alpha) @ (Plus ^ Plus),
CVaRMeasurement((I ^ Z), alpha) @ (Plus ^ Plus),
]
)
cvar = cvar_expecation.convert(op)
self.assertEqual(cvar, expected)
def test_unsupported_expectation(self):
"""Assert passing an AerPauliExpectation raises an error."""
expecation = AerPauliExpectation()
with self.assertRaises(NotImplementedError):
_ = CVaRExpectation(alpha=1, expectation=expecation)
@data(PauliExpectation(), MatrixExpectation())
def test_underlying_expectation(self, base_expecation):
"""Test the underlying expectation works correctly."""
cvar_expecation = CVaRExpectation(alpha=0.3, expectation=base_expecation)
circuit = QuantumCircuit(2)
circuit.z(0)
circuit.cp(0.5, 0, 1)
circuit.t(1)
op = ~StateFn(CircuitOp(circuit)) @ (Plus ^ 2)
cvar = cvar_expecation.convert(op)
expected = base_expecation.convert(op)
# test if the operators have been transformed in the same manner
self.assertEqual(cvar.oplist[0].primitive, expected.oplist[0].primitive)
def test_compute_variance(self):
"""Test if the compute_variance method works"""
alphas = [0, 0.3, 0.5, 0.7, 1]
correct_vars = [0, 0, 0, 0.8163, 1]
for i, alpha in enumerate(alphas):
base_expecation = PauliExpectation()
cvar_expecation = CVaRExpectation(alpha=alpha, expectation=base_expecation)
op = ~StateFn(Z ^ Z) @ (Plus ^ Plus)
cvar_var = cvar_expecation.compute_variance(op)
np.testing.assert_almost_equal(cvar_var, correct_vars[i], decimal=3)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test Evolution"""
import unittest
from test.python.opflow import QiskitOpflowTestCase
import numpy as np
import scipy.linalg
import qiskit
from qiskit.circuit import Parameter, ParameterVector
from qiskit.extensions import UnitaryGate
from qiskit.opflow import (
CX,
CircuitOp,
EvolutionFactory,
EvolvedOp,
H,
I,
ListOp,
PauliTrotterEvolution,
QDrift,
SummedOp,
Suzuki,
Trotter,
X,
Y,
Z,
Zero,
)
class TestEvolution(QiskitOpflowTestCase):
"""Evolution tests."""
def test_exp_i(self):
"""exponential of Pauli test"""
op = Z.exp_i()
gate = op.to_circuit().data[0].operation
self.assertIsInstance(gate, qiskit.circuit.library.RZGate)
self.assertEqual(gate.params[0], 2)
def test_trotter_with_identity(self):
"""trotterization of operator with identity term"""
op = (2.0 * I ^ I) + (Z ^ Y)
exact_matrix = scipy.linalg.expm(-1j * op.to_matrix())
evo = PauliTrotterEvolution(trotter_mode="suzuki", reps=2)
with self.subTest("all PauliOp terms"):
circ_op = evo.convert(EvolvedOp(op))
circuit_matrix = qiskit.quantum_info.Operator(circ_op.to_circuit()).data
np.testing.assert_array_almost_equal(exact_matrix, circuit_matrix)
with self.subTest("MatrixOp identity term"):
op = (2.0 * I ^ I).to_matrix_op() + (Z ^ Y)
circ_op = evo.convert(EvolvedOp(op))
circuit_matrix = qiskit.quantum_info.Operator(circ_op.to_circuit()).data
np.testing.assert_array_almost_equal(exact_matrix, circuit_matrix)
with self.subTest("CircuitOp identity term"):
op = (2.0 * I ^ I).to_circuit_op() + (Z ^ Y)
circ_op = evo.convert(EvolvedOp(op))
circuit_matrix = qiskit.quantum_info.Operator(circ_op.to_circuit()).data
np.testing.assert_array_almost_equal(exact_matrix, circuit_matrix)
def test_pauli_evolution(self):
"""pauli evolution test"""
op = (
(-1.052373245772859 * I ^ I)
+ (0.39793742484318045 * I ^ Z)
+ (0.18093119978423156 * X ^ X)
+ (-0.39793742484318045 * Z ^ I)
+ (-0.01128010425623538 * Z ^ Z)
)
evolution = EvolutionFactory.build(operator=op)
# wf = (Pl^Pl) + (Ze^Ze)
wf = ((np.pi / 2) * op).exp_i() @ CX @ (H ^ I) @ Zero
mean = evolution.convert(wf)
self.assertIsNotNone(mean)
def test_summedop_pauli_evolution(self):
"""SummedOp[PauliOp] evolution test"""
op = SummedOp(
[
(-1.052373245772859 * I ^ I),
(0.39793742484318045 * I ^ Z),
(0.18093119978423156 * X ^ X),
(-0.39793742484318045 * Z ^ I),
(-0.01128010425623538 * Z ^ Z),
]
)
evolution = EvolutionFactory.build(operator=op)
# wf = (Pl^Pl) + (Ze^Ze)
wf = ((np.pi / 2) * op).exp_i() @ CX @ (H ^ I) @ Zero
mean = evolution.convert(wf)
self.assertIsNotNone(mean)
def test_parameterized_evolution(self):
"""parameterized evolution test"""
thetas = ParameterVector("ΞΈ", length=7)
op = (
(thetas[0] * I ^ I)
+ (thetas[1] * I ^ Z)
+ (thetas[2] * X ^ X)
+ (thetas[3] * Z ^ I)
+ (thetas[4] * Y ^ Z)
+ (thetas[5] * Z ^ Z)
)
op = op * thetas[6]
evolution = PauliTrotterEvolution(trotter_mode="trotter", reps=1)
# wf = (Pl^Pl) + (Ze^Ze)
wf = (op).exp_i() @ CX @ (H ^ I) @ Zero
mean = evolution.convert(wf)
circuit = mean.to_circuit()
# Check that all parameters are in the circuit
for p in thetas:
self.assertIn(p, circuit.parameters)
# Check that the identity-parameters only exist as global phase
self.assertNotIn(thetas[0], circuit._parameter_table.get_keys())
def test_bind_parameters(self):
"""bind parameters test"""
thetas = ParameterVector("ΞΈ", length=6)
op = (
(thetas[1] * I ^ Z)
+ (thetas[2] * X ^ X)
+ (thetas[3] * Z ^ I)
+ (thetas[4] * Y ^ Z)
+ (thetas[5] * Z ^ Z)
)
op = thetas[0] * op
evolution = PauliTrotterEvolution(trotter_mode="trotter", reps=1)
# wf = (Pl^Pl) + (Ze^Ze)
wf = (op).exp_i() @ CX @ (H ^ I) @ Zero
wf = wf.assign_parameters({thetas: np.arange(10, 16)})
mean = evolution.convert(wf)
circuit_params = mean.to_circuit().parameters
# Check that the no parameters are in the circuit
for p in thetas[1:]:
self.assertNotIn(p, circuit_params)
def test_bind_circuit_parameters(self):
"""bind circuit parameters test"""
thetas = ParameterVector("ΞΈ", length=6)
op = (
(thetas[1] * I ^ Z)
+ (thetas[2] * X ^ X)
+ (thetas[3] * Z ^ I)
+ (thetas[4] * Y ^ Z)
+ (thetas[5] * Z ^ Z)
)
op = thetas[0] * op
evolution = PauliTrotterEvolution(trotter_mode="trotter", reps=1)
# wf = (Pl^Pl) + (Ze^Ze)
wf = (op).exp_i() @ CX @ (H ^ I) @ Zero
evo = evolution.convert(wf)
mean = evo.assign_parameters({thetas: np.arange(10, 16)})
# Check that the no parameters are in the circuit
for p in thetas[1:]:
self.assertNotIn(p, mean.to_circuit().parameters)
# Check that original circuit is unchanged
for p in thetas:
self.assertIn(p, evo.to_circuit().parameters)
# TODO test with other Op types than CircuitStateFn
def test_bind_parameter_list(self):
"""bind parameters list test"""
thetas = ParameterVector("ΞΈ", length=6)
op = (
(thetas[1] * I ^ Z)
+ (thetas[2] * X ^ X)
+ (thetas[3] * Z ^ I)
+ (thetas[4] * Y ^ Z)
+ (thetas[5] * Z ^ Z)
)
op = thetas[0] * op
evolution = PauliTrotterEvolution(trotter_mode="trotter", reps=1)
# wf = (Pl^Pl) + (Ze^Ze)
wf = (op).exp_i() @ CX @ (H ^ I) @ Zero
evo = evolution.convert(wf)
param_list = np.transpose([np.arange(10, 16), np.arange(2, 8), np.arange(30, 36)]).tolist()
means = evo.assign_parameters({thetas: param_list})
self.assertIsInstance(means, ListOp)
# Check that the no parameters are in the circuit
for p in thetas[1:]:
for circop in means.oplist:
self.assertNotIn(p, circop.to_circuit().parameters)
# Check that original circuit is unchanged
for p in thetas:
self.assertIn(p, evo.to_circuit().parameters)
def test_bind_parameters_complex(self):
"""bind parameters with a complex value test"""
th1 = Parameter("th1")
th2 = Parameter("th2")
operator = th1 * X + th2 * Y
bound_operator = operator.bind_parameters({th1: 3j, th2: 2})
expected_bound_operator = SummedOp([3j * X, (2 + 0j) * Y])
self.assertEqual(bound_operator, expected_bound_operator)
def test_qdrift(self):
"""QDrift test"""
op = (2 * Z ^ Z) + (3 * X ^ X) - (4 * Y ^ Y) + (0.5 * Z ^ I)
trotterization = QDrift().convert(op)
self.assertGreater(len(trotterization.oplist), 150)
last_coeff = None
# Check that all types are correct and all coefficients are equals
for op in trotterization.oplist:
self.assertIsInstance(op, (EvolvedOp, CircuitOp))
if isinstance(op, EvolvedOp):
if last_coeff:
self.assertEqual(op.primitive.coeff, last_coeff)
else:
last_coeff = op.primitive.coeff
def test_qdrift_summed_op(self):
"""QDrift test for SummedOp"""
op = SummedOp(
[
(2 * Z ^ Z),
(3 * X ^ X),
(-4 * Y ^ Y),
(0.5 * Z ^ I),
]
)
trotterization = QDrift().convert(op)
self.assertGreater(len(trotterization.oplist), 150)
last_coeff = None
# Check that all types are correct and all coefficients are equals
for op in trotterization.oplist:
self.assertIsInstance(op, (EvolvedOp, CircuitOp))
if isinstance(op, EvolvedOp):
if last_coeff:
self.assertEqual(op.primitive.coeff, last_coeff)
else:
last_coeff = op.primitive.coeff
def test_matrix_op_evolution(self):
"""MatrixOp evolution test"""
op = (
(-1.052373245772859 * I ^ I)
+ (0.39793742484318045 * I ^ Z)
+ (0.18093119978423156 * X ^ X)
+ (-0.39793742484318045 * Z ^ I)
+ (-0.01128010425623538 * Z ^ Z) * np.pi / 2
)
exp_mat = op.to_matrix_op().exp_i().to_matrix()
ref_mat = scipy.linalg.expm(-1j * op.to_matrix())
np.testing.assert_array_almost_equal(ref_mat, exp_mat)
def test_log_i(self):
"""MatrixOp.log_i() test"""
op = (
(-1.052373245772859 * I ^ I)
+ (0.39793742484318045 * I ^ Z)
+ (0.18093119978423156 * X ^ X)
+ (-0.39793742484318045 * Z ^ I)
+ (-0.01128010425623538 * Z ^ Z) * np.pi / 2
)
# Test with CircuitOp
log_exp_op = op.to_matrix_op().exp_i().log_i().to_pauli_op()
np.testing.assert_array_almost_equal(op.to_matrix(), log_exp_op.to_matrix())
# Test with MatrixOp
log_exp_op = op.to_matrix_op().exp_i().to_matrix_op().log_i().to_pauli_op()
np.testing.assert_array_almost_equal(op.to_matrix(), log_exp_op.to_matrix())
# Test with PauliOp
log_exp_op = op.to_matrix_op().exp_i().to_pauli_op().log_i().to_pauli_op()
np.testing.assert_array_almost_equal(op.to_matrix(), log_exp_op.to_matrix())
# Test with EvolvedOp
log_exp_op = op.exp_i().to_pauli_op().log_i().to_pauli_op()
np.testing.assert_array_almost_equal(op.to_matrix(), log_exp_op.to_matrix())
# Test with proper ListOp
op = ListOp(
[
(0.39793742484318045 * I ^ Z),
(0.18093119978423156 * X ^ X),
(-0.39793742484318045 * Z ^ I),
(-0.01128010425623538 * Z ^ Z) * np.pi / 2,
]
)
log_exp_op = op.to_matrix_op().exp_i().to_matrix_op().log_i().to_pauli_op()
np.testing.assert_array_almost_equal(op.to_matrix(), log_exp_op.to_matrix())
def test_matrix_op_parameterized_evolution(self):
"""parameterized MatrixOp evolution test"""
theta = Parameter("ΞΈ")
op = (
(-1.052373245772859 * I ^ I)
+ (0.39793742484318045 * I ^ Z)
+ (0.18093119978423156 * X ^ X)
+ (-0.39793742484318045 * Z ^ I)
+ (-0.01128010425623538 * Z ^ Z)
)
op = op * theta
wf = (op.to_matrix_op().exp_i()) @ CX @ (H ^ I) @ Zero
self.assertIn(theta, wf.to_circuit().parameters)
op = op.assign_parameters({theta: 1})
exp_mat = op.to_matrix_op().exp_i().to_matrix()
ref_mat = scipy.linalg.expm(-1j * op.to_matrix())
np.testing.assert_array_almost_equal(ref_mat, exp_mat)
wf = wf.assign_parameters({theta: 3})
self.assertNotIn(theta, wf.to_circuit().parameters)
def test_mixed_evolution(self):
"""bind parameters test"""
thetas = ParameterVector("ΞΈ", length=6)
op = (
(thetas[1] * (I ^ Z).to_matrix_op())
+ (thetas[2] * (X ^ X)).to_matrix_op()
+ (thetas[3] * Z ^ I)
+ (thetas[4] * Y ^ Z).to_circuit_op()
+ (thetas[5] * (Z ^ I).to_circuit_op())
)
op = thetas[0] * op
evolution = PauliTrotterEvolution(trotter_mode="trotter", reps=1)
# wf = (Pl^Pl) + (Ze^Ze)
wf = (op).exp_i() @ CX @ (H ^ I) @ Zero
wf = wf.assign_parameters({thetas: np.arange(10, 16)})
mean = evolution.convert(wf)
circuit_params = mean.to_circuit().parameters
# Check that the no parameters are in the circuit
for p in thetas[1:]:
self.assertNotIn(p, circuit_params)
def test_reps(self):
"""Test reps and order params in Trotterization"""
reps = 7
trotter = Trotter(reps=reps)
self.assertEqual(trotter.reps, reps)
order = 5
suzuki = Suzuki(reps=reps, order=order)
self.assertEqual(suzuki.reps, reps)
self.assertEqual(suzuki.order, order)
qdrift = QDrift(reps=reps)
self.assertEqual(qdrift.reps, reps)
def test_suzuki_directly(self):
"""Test for Suzuki converter"""
operator = X + Z
evo = Suzuki()
evolution = evo.convert(operator)
matrix = np.array(
[[0.29192658 - 0.45464871j, -0.84147098j], [-0.84147098j, 0.29192658 + 0.45464871j]]
)
np.testing.assert_array_almost_equal(evolution.to_matrix(), matrix)
def test_evolved_op_to_instruction(self):
"""Test calling `to_instruction` on a plain EvolvedOp.
Regression test of Qiskit/qiskit-terra#8025.
"""
op = EvolvedOp(0.5 * X)
circuit = op.to_instruction()
unitary = scipy.linalg.expm(-0.5j * X.to_matrix())
expected = UnitaryGate(unitary)
self.assertEqual(circuit, expected)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# =============================================================================
"""Test Quantum Gradient Framework"""
import unittest
from test.python.opflow import QiskitOpflowTestCase
from itertools import product
import numpy as np
from ddt import ddt, data, idata, unpack
from qiskit import QuantumCircuit, QuantumRegister, BasicAer
from qiskit.test import slow_test
from qiskit.utils import QuantumInstance
from qiskit.exceptions import MissingOptionalLibraryError
from qiskit.utils import algorithm_globals
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import CG
from qiskit.opflow import (
I,
X,
Y,
Z,
StateFn,
CircuitStateFn,
ListOp,
CircuitSampler,
TensoredOp,
SummedOp,
)
from qiskit.opflow.gradients import Gradient, NaturalGradient, Hessian
from qiskit.opflow.gradients.qfi import QFI
from qiskit.opflow.gradients.circuit_gradients import LinComb
from qiskit.opflow.gradients.circuit_qfis import LinCombFull, OverlapBlockDiag, OverlapDiag
from qiskit.circuit import Parameter
from qiskit.circuit import ParameterVector
from qiskit.circuit.library import RealAmplitudes, EfficientSU2
from qiskit.utils import optionals
if optionals.HAS_JAX:
import jax.numpy as jnp
@ddt
class TestGradients(QiskitOpflowTestCase):
"""Test Qiskit Gradient Framework"""
def setUp(self):
super().setUp()
algorithm_globals.random_seed = 50
@data("lin_comb", "param_shift", "fin_diff")
def test_gradient_p(self, method):
"""Test the state gradient for p
|psi> = 1/sqrt(2)[[1, exp(ia)]]
Tr(|psi><psi|Z) = 0
Tr(|psi><psi|X) = cos(a)
d<H>/da = - 0.5 sin(a)
"""
ham = 0.5 * X - 1 * Z
a = Parameter("a")
params = a
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.p(a, q[0])
op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)
state_grad = Gradient(grad_method=method).convert(operator=op, params=params)
values_dict = [{a: np.pi / 4}, {a: 0}, {a: np.pi / 2}]
correct_values = [-0.5 / np.sqrt(2), 0, -0.5]
for i, value_dict in enumerate(values_dict):
np.testing.assert_array_almost_equal(
state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1
)
@data("lin_comb", "param_shift", "fin_diff")
def test_gradient_u(self, method):
"""Test the state gradient for U
Tr(|psi><psi|Z) = - 0.5 sin(a)cos(c)
Tr(|psi><psi|X) = cos^2(a/2) cos(b+c) - sin^2(a/2) cos(b-c)
"""
ham = 0.5 * X - 1 * Z
a = Parameter("a")
b = Parameter("b")
c = Parameter("c")
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.u(a, b, c, q[0])
op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)
params = [a, b, c]
state_grad = Gradient(grad_method=method).convert(operator=op, params=params)
values_dict = [{a: np.pi / 4, b: 0, c: 0}, {a: np.pi / 4, b: np.pi / 4, c: np.pi / 4}]
correct_values = [[0.3536, 0, 0], [0.3232, -0.42678, -0.92678]]
for i, value_dict in enumerate(values_dict):
np.testing.assert_array_almost_equal(
state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1
)
# Tr(|psi><psi|Z) = - 0.5 sin(a)cos(c)
# Tr(|psi><psi|X) = cos^2(a/2) cos(b+c) - sin^2(a/2) cos(b-c)
# dTr(|psi><psi|H)/da = 0.5(cos(2a)) + 0.5()
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.u(a, a, a, q[0])
op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)
params = [a]
state_grad = Gradient(grad_method=method).convert(operator=op, params=params)
values_dict = [{a: np.pi / 4}, {a: np.pi / 2}]
correct_values = [[-1.03033], [-1]]
for i, value_dict in enumerate(values_dict):
np.testing.assert_array_almost_equal(
state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1
)
@data("lin_comb", "param_shift")
def test_gradient_efficient_su2(self, method):
"""Test the state gradient for EfficientSU2"""
observable = SummedOp(
[
0.2252 * (I ^ I),
0.5716 * (Z ^ Z),
0.3435 * (I ^ Z),
-0.4347 * (Z ^ I),
0.091 * (Y ^ Y),
0.091 * (X ^ X),
]
).reduce()
d = 2
ansatz = EfficientSU2(observable.num_qubits, reps=d)
# Define a set of initial parameters
parameters = ansatz.ordered_parameters
operator = ~StateFn(observable) @ StateFn(ansatz)
values_dict = [
{param: np.pi / 4 for param in parameters},
{param: np.pi / 2 for param in parameters},
]
correct_values = [
[
-0.38617868191914206 + 0j,
-0.014055349300198364 + 0j,
-0.06385049040183734 + 0j,
0.13620629212619334 + 0j,
-0.15180743339043595 + 0j,
-0.2378393653877069 + 0j,
0.0024060546876464237 + 0j,
0.09977051760912459 + 0j,
0.40357721595080603 + 0j,
0.010453846462186653 + 0j,
-0.04578581127401049 + 0j,
0.04578581127401063 + 0j,
],
[
0.4346999999999997 + 0j,
0.0,
0.0,
0.6625999999999991 + 0j,
0.0,
0.0,
-0.34349999999999986 + 0j,
0.0,
0.0,
0.0,
0.0,
0.0,
],
]
state_grad = Gradient(method).convert(operator, parameters)
for i, value_dict in enumerate(values_dict):
np.testing.assert_array_almost_equal(
state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1
)
@data("lin_comb", "param_shift", "fin_diff")
def test_gradient_rxx(self, method):
"""Test the state gradient for XX rotation"""
ham = TensoredOp([Z, X])
a = Parameter("a")
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.h(q[0])
qc.rxx(a, q[0], q[1])
op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)
params = [a]
state_grad = Gradient(grad_method=method).convert(operator=op, params=params)
values_dict = [{a: np.pi / 4}, {a: np.pi / 2}]
correct_values = [[-0.707], [-1.0]]
for i, value_dict in enumerate(values_dict):
np.testing.assert_array_almost_equal(
state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1
)
@data("lin_comb", "param_shift", "fin_diff")
def test_gradient_ryy(self, method):
"""Test the state gradient for YY rotation"""
alpha = Parameter("alpha")
ham = TensoredOp([Y, alpha * Y])
a = Parameter("a")
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.ryy(a, q[0], q[1])
op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)
state_grad = Gradient(grad_method=method).convert(operator=op, params=a)
values_dict = [{a: np.pi / 8}, {a: np.pi}]
correct_values = [[0], [0]]
for i, value_dict in enumerate(values_dict):
value_dict[alpha] = 1.0
np.testing.assert_array_almost_equal(
state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1
)
@data("lin_comb", "param_shift", "fin_diff")
def test_gradient_rzz(self, method):
"""Test the state gradient for ZZ rotation"""
ham = Z ^ X
a = Parameter("a")
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.h(q[0])
qc.rzz(a, q[0], q[1])
op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)
params = [a]
state_grad = Gradient(grad_method=method).convert(operator=op, params=params)
values_dict = [{a: np.pi / 4}, {a: np.pi / 2}]
correct_values = [[-0.707], [-1.0]]
for i, value_dict in enumerate(values_dict):
np.testing.assert_array_almost_equal(
state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1
)
@data("lin_comb", "param_shift", "fin_diff")
def test_gradient_rzx(self, method):
"""Test the state gradient for ZX rotation"""
ham = Z ^ Z
a = Parameter("a")
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.h(q)
qc.rzx(a, q[0], q[1])
op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)
params = [a]
state_grad = Gradient(grad_method=method).convert(operator=op, params=params)
values_dict = [{a: np.pi / 8}, {a: np.pi / 2}]
correct_values = [[0.0], [0.0]]
for i, value_dict in enumerate(values_dict):
np.testing.assert_array_almost_equal(
state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1
)
@data("lin_comb", "param_shift", "fin_diff")
def test_state_gradient1(self, method):
"""Test the state gradient
Tr(|psi><psi|Z) = sin(a)sin(b)
Tr(|psi><psi|X) = cos(a)
d<H>/da = - 0.5 sin(a) - 1 cos(a)sin(b)
d<H>/db = - 1 sin(a)cos(b)
"""
ham = 0.5 * X - 1 * Z
a = Parameter("a")
b = Parameter("b")
params = [a, b]
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(params[0], q[0])
qc.rx(params[1], q[0])
op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)
state_grad = Gradient(grad_method=method).convert(operator=op, params=params)
values_dict = [
{a: np.pi / 4, b: np.pi},
{params[0]: np.pi / 4, params[1]: np.pi / 4},
{params[0]: np.pi / 2, params[1]: np.pi / 4},
]
correct_values = [
[-0.5 / np.sqrt(2), 1 / np.sqrt(2)],
[-0.5 / np.sqrt(2) - 0.5, -1 / 2.0],
[-0.5, -1 / np.sqrt(2)],
]
for i, value_dict in enumerate(values_dict):
np.testing.assert_array_almost_equal(
state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1
)
@data("lin_comb", "param_shift", "fin_diff")
def test_state_gradient2(self, method):
"""Test the state gradient 2
Tr(|psi><psi|Z) = sin(a)sin(a)
Tr(|psi><psi|X) = cos(a)
d<H>/da = - 0.5 sin(a) - 2 cos(a)sin(a)
"""
ham = 0.5 * X - 1 * Z
a = Parameter("a")
# b = Parameter('b')
params = [a]
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(a, q[0])
qc.rx(a, q[0])
op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)
state_grad = Gradient(grad_method=method).convert(operator=op, params=params)
values_dict = [{a: np.pi / 4}, {a: 0}, {a: np.pi / 2}]
correct_values = [-1.353553, -0, -0.5]
for i, value_dict in enumerate(values_dict):
np.testing.assert_array_almost_equal(
state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1
)
@data("lin_comb", "param_shift", "fin_diff")
def test_state_gradient3(self, method):
"""Test the state gradient 3
Tr(|psi><psi|Z) = sin(a)sin(c(a)) = sin(a)sin(cos(a)+1)
Tr(|psi><psi|X) = cos(a)
d<H>/da = - 0.5 sin(a) - 1 cos(a)sin(cos(a)+1) + 1 sin^2(a)cos(cos(a)+1)
"""
ham = 0.5 * X - 1 * Z
a = Parameter("a")
# b = Parameter('b')
params = a
c = np.cos(a) + 1
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(a, q[0])
qc.rx(c, q[0])
op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)
state_grad = Gradient(grad_method=method).convert(operator=op, params=params)
values_dict = [{a: np.pi / 4}, {a: 0}, {a: np.pi / 2}]
correct_values = [-1.1220, -0.9093, 0.0403]
for i, value_dict in enumerate(values_dict):
np.testing.assert_array_almost_equal(
state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1
)
@data("lin_comb", "param_shift", "fin_diff")
def test_state_gradient4(self, method):
"""Test the state gradient 4
Tr(|psi><psi|ZX) = -cos(a)
daTr(|psi><psi|ZX) = sin(a)
"""
ham = X ^ Z
a = Parameter("a")
params = a
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.x(q[0])
qc.h(q[1])
qc.crz(a, q[0], q[1])
op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)
state_grad = Gradient(grad_method=method).convert(operator=op, params=params)
values_dict = [{a: np.pi / 4}, {a: 0}, {a: np.pi / 2}]
correct_values = [1 / np.sqrt(2), 0, 1]
for i, value_dict in enumerate(values_dict):
np.testing.assert_array_almost_equal(
state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1
)
@data("lin_comb", "param_shift", "fin_diff")
def test_state_gradient5(self, method):
"""Test the state gradient
Tr(|psi><psi|Z) = sin(a0)sin(a1)
Tr(|psi><psi|X) = cos(a0)
d<H>/da0 = - 0.5 sin(a0) - 1 cos(a0)sin(a1)
d<H>/da1 = - 1 sin(a0)cos(a1)
"""
ham = 0.5 * X - 1 * Z
a = ParameterVector("a", 2)
params = a
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(params[0], q[0])
qc.rx(params[1], q[0])
op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)
state_grad = Gradient(grad_method=method).convert(operator=op, params=params)
values_dict = [
{a: [np.pi / 4, np.pi]},
{a: [np.pi / 4, np.pi / 4]},
{a: [np.pi / 2, np.pi / 4]},
]
correct_values = [
[-0.5 / np.sqrt(2), 1 / np.sqrt(2)],
[-0.5 / np.sqrt(2) - 0.5, -1 / 2.0],
[-0.5, -1 / np.sqrt(2)],
]
for i, value_dict in enumerate(values_dict):
np.testing.assert_array_almost_equal(
state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1
)
@data("lin_comb", "param_shift", "fin_diff")
def test_state_hessian(self, method):
"""Test the state Hessian
Tr(|psi><psi|Z) = sin(a)sin(b)
Tr(|psi><psi|X) = cos(a)
d^2<H>/da^2 = - 0.5 cos(a) + 1 sin(a)sin(b)
d^2<H>/dbda = - 1 cos(a)cos(b)
d^2<H>/dbda = - 1 cos(a)cos(b)
d^2<H>/db^2 = + 1 sin(a)sin(b)
"""
ham = 0.5 * X - 1 * Z
params = ParameterVector("a", 2)
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(params[0], q[0])
qc.rx(params[1], q[0])
op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)
state_hess = Hessian(hess_method=method).convert(operator=op)
values_dict = [
{params[0]: np.pi / 4, params[1]: np.pi},
{params[0]: np.pi / 4, params[1]: np.pi / 4},
]
correct_values = [
[[-0.5 / np.sqrt(2), 1 / np.sqrt(2)], [1 / np.sqrt(2), 0]],
[[-0.5 / np.sqrt(2) + 0.5, -1 / 2.0], [-1 / 2.0, 0.5]],
]
for i, value_dict in enumerate(values_dict):
np.testing.assert_array_almost_equal(
state_hess.assign_parameters(value_dict).eval(), correct_values[i], decimal=1
)
@unittest.skipIf(not optionals.HAS_JAX, "Skipping test due to missing jax module.")
@data("lin_comb", "param_shift", "fin_diff")
def test_state_hessian_custom_combo_fn(self, method):
"""Test the state Hessian with on an operator which includes
a user-defined combo_fn.
Tr(|psi><psi|Z) = sin(a)sin(b)
Tr(|psi><psi|X) = cos(a)
d^2<H>/da^2 = - 0.5 cos(a) + 1 sin(a)sin(b)
d^2<H>/dbda = - 1 cos(a)cos(b)
d^2<H>/dbda = - 1 cos(a)cos(b)
d^2<H>/db^2 = + 1 sin(a)sin(b)
"""
ham = 0.5 * X - 1 * Z
a = Parameter("a")
b = Parameter("b")
params = [(a, a), (a, b), (b, b)]
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(a, q[0])
qc.rx(b, q[0])
op = ListOp(
[~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)],
combo_fn=lambda x: x[0] ** 3 + 4 * x[0],
)
state_hess = Hessian(hess_method=method).convert(operator=op, params=params)
values_dict = [
{a: np.pi / 4, b: np.pi},
{a: np.pi / 4, b: np.pi / 4},
{a: np.pi / 2, b: np.pi / 4},
]
correct_values = [
[-1.28163104, 2.56326208, 1.06066017],
[-0.04495626, -2.40716991, 1.8125],
[2.82842712, -1.5, 1.76776695],
]
for i, value_dict in enumerate(values_dict):
np.testing.assert_array_almost_equal(
state_hess.assign_parameters(value_dict).eval(), correct_values[i], decimal=1
)
@data("lin_comb", "param_shift", "fin_diff")
def test_prob_grad(self, method):
"""Test the probability gradient
dp0/da = cos(a)sin(b) / 2
dp1/da = - cos(a)sin(b) / 2
dp0/db = sin(a)cos(b) / 2
dp1/db = - sin(a)cos(b) / 2
"""
a = Parameter("a")
b = Parameter("b")
params = [a, b]
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(params[0], q[0])
qc.rx(params[1], q[0])
op = CircuitStateFn(primitive=qc, coeff=1.0)
prob_grad = Gradient(grad_method=method).convert(operator=op, params=params)
values_dict = [
{a: np.pi / 4, b: 0},
{params[0]: np.pi / 4, params[1]: np.pi / 4},
{params[0]: np.pi / 2, params[1]: np.pi},
]
correct_values = [
[[0, 0], [1 / (2 * np.sqrt(2)), -1 / (2 * np.sqrt(2))]],
[[1 / 4, -1 / 4], [1 / 4, -1 / 4]],
[[0, 0], [-1 / 2, 1 / 2]],
]
for i, value_dict in enumerate(values_dict):
for j, prob_grad_result in enumerate(prob_grad.assign_parameters(value_dict).eval()):
np.testing.assert_array_almost_equal(
prob_grad_result, correct_values[i][j], decimal=1
)
@data("lin_comb", "param_shift", "fin_diff")
def test_prob_hess(self, method):
"""Test the probability Hessian using linear combination of unitaries method
d^2p0/da^2 = - sin(a)sin(b) / 2
d^2p1/da^2 = sin(a)sin(b) / 2
d^2p0/dadb = cos(a)cos(b) / 2
d^2p1/dadb = - cos(a)cos(b) / 2
"""
a = Parameter("a")
b = Parameter("b")
params = [(a, a), (a, b)]
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(a, q[0])
qc.rx(b, q[0])
op = CircuitStateFn(primitive=qc, coeff=1.0)
prob_hess = Hessian(hess_method=method).convert(operator=op, params=params)
values_dict = [{a: np.pi / 4, b: 0}, {a: np.pi / 4, b: np.pi / 4}, {a: np.pi / 2, b: np.pi}]
correct_values = [
[[0, 0], [1 / (2 * np.sqrt(2)), -1 / (2 * np.sqrt(2))]],
[[-1 / 4, 1 / 4], [1 / 4, -1 / 4]],
[[0, 0], [0, 0]],
]
for i, value_dict in enumerate(values_dict):
for j, prob_hess_result in enumerate(prob_hess.assign_parameters(value_dict).eval()):
np.testing.assert_array_almost_equal(
prob_hess_result, correct_values[i][j], decimal=1
)
@idata(
product(
["lin_comb", "param_shift", "fin_diff"],
[None, "lasso", "ridge", "perturb_diag", "perturb_diag_elements"],
)
)
@unpack
def test_natural_gradient(self, method, regularization):
"""Test the natural gradient"""
try:
for params in (ParameterVector("a", 2), [Parameter("a"), Parameter("b")]):
ham = 0.5 * X - 1 * Z
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(params[0], q[0])
qc.rx(params[1], q[0])
op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)
nat_grad = NaturalGradient(
grad_method=method, regularization=regularization
).convert(operator=op)
values_dict = [{params[0]: np.pi / 4, params[1]: np.pi / 2}]
# reference values obtained by classically computing the natural gradients
correct_values = [[-3.26, 1.63]] if regularization == "ridge" else [[-4.24, 0]]
for i, value_dict in enumerate(values_dict):
np.testing.assert_array_almost_equal(
nat_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1
)
except MissingOptionalLibraryError as ex:
self.skipTest(str(ex))
def test_natural_gradient2(self):
"""Test the natural gradient 2"""
with self.assertRaises(TypeError):
_ = NaturalGradient().convert(None, None)
@idata(
zip(
["lin_comb_full", "overlap_block_diag", "overlap_diag"],
[LinCombFull, OverlapBlockDiag, OverlapDiag],
)
)
@unpack
def test_natural_gradient3(self, qfi_method, circuit_qfi):
"""Test the natural gradient 3"""
nat_grad = NaturalGradient(qfi_method=qfi_method)
self.assertIsInstance(nat_grad.qfi_method, circuit_qfi)
@idata(
product(
["lin_comb", "param_shift", "fin_diff"],
["lin_comb_full", "overlap_block_diag", "overlap_diag"],
[None, "ridge", "perturb_diag", "perturb_diag_elements"],
)
)
@unpack
def test_natural_gradient4(self, grad_method, qfi_method, regularization):
"""Test the natural gradient 4"""
# Avoid regularization = lasso intentionally because it does not converge
try:
ham = 0.5 * X - 1 * Z
a = Parameter("a")
params = a
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(a, q[0])
op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)
nat_grad = NaturalGradient(
grad_method=grad_method, qfi_method=qfi_method, regularization=regularization
).convert(operator=op, params=params)
values_dict = [{a: np.pi / 4}]
correct_values = [[0.0]] if regularization == "ridge" else [[-1.41421342]]
for i, value_dict in enumerate(values_dict):
np.testing.assert_array_almost_equal(
nat_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=3
)
except MissingOptionalLibraryError as ex:
self.skipTest(str(ex))
def test_gradient_p_imag(self):
"""Test the imaginary state gradient for p
|psi(a)> = 1/sqrt(2)[[1, exp(ia)]]
<psi(a)|X|da psi(a)> = iexp(-ia)/2 <1|H(|0>+exp(ia)|1>)
Im(<psi(a)|X|da psi(a)>) = 0.5 cos(a).
"""
ham = X
a = Parameter("a")
params = a
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.p(a, q[0])
op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)
state_grad = LinComb(aux_meas_op=(-1) * Y).convert(operator=op, params=params)
values_dict = [{a: np.pi / 4}, {a: 0}, {a: np.pi / 2}]
correct_values = [1 / np.sqrt(2), 1, 0]
for i, value_dict in enumerate(values_dict):
np.testing.assert_array_almost_equal(
state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1
)
def test_qfi_p_imag(self):
"""Test the imaginary state QFI for RXRY"""
x = Parameter("x")
y = Parameter("y")
circuit = QuantumCircuit(1)
circuit.ry(y, 0)
circuit.rx(x, 0)
state = StateFn(circuit)
dx = (
lambda x, y: (-1)
* 0.5j
* np.array(
[
[
-1j * np.sin(x / 2) * np.cos(y / 2) + np.cos(x / 2) * np.sin(y / 2),
np.cos(x / 2) * np.cos(y / 2) - 1j * np.sin(x / 2) * np.sin(y / 2),
]
]
)
)
dy = (
lambda x, y: (-1)
* 0.5j
* np.array(
[
[
-1j * np.cos(x / 2) * np.sin(y / 2) + np.sin(x / 2) * np.cos(y / 2),
1j * np.cos(x / 2) * np.cos(y / 2) - 1 * np.sin(x / 2) * np.sin(y / 2),
]
]
)
)
state_grad = LinCombFull(aux_meas_op=-1 * Y, phase_fix=False).convert(
operator=state, params=[x, y]
)
values_dict = [{x: 0, y: np.pi / 4}, {x: 0, y: np.pi / 2}, {x: np.pi / 2, y: 0}]
for value_dict in values_dict:
x_ = list(value_dict.values())[0]
y_ = list(value_dict.values())[1]
correct_values = [
[
4 * np.imag(np.dot(dx(x_, y_), np.conj(np.transpose(dx(x_, y_))))[0][0]),
4 * np.imag(np.dot(dy(x_, y_), np.conj(np.transpose(dx(x_, y_))))[0][0]),
],
[
4 * np.imag(np.dot(dy(x_, y_), np.conj(np.transpose(dx(x_, y_))))[0][0]),
4 * np.imag(np.dot(dy(x_, y_), np.conj(np.transpose(dy(x_, y_))))[0][0]),
],
]
np.testing.assert_array_almost_equal(
state_grad.assign_parameters(value_dict).eval(), correct_values, decimal=3
)
@unittest.skipIf(not optionals.HAS_JAX, "Skipping test due to missing jax module.")
@idata(product(["lin_comb", "param_shift", "fin_diff"], [True, False]))
@unpack
def test_jax_chain_rule(self, method: str, autograd: bool):
"""Test the chain rule functionality using Jax
d<H>/d<X> = 2<X>
d<H>/d<Z> = - sin(<Z>)
<Z> = Tr(|psi><psi|Z) = sin(a)sin(b)
<X> = Tr(|psi><psi|X) = cos(a)
d<H>/da = d<H>/d<X> d<X>/da + d<H>/d<Z> d<Z>/da = - 2 cos(a)sin(a)
- sin(sin(a)sin(b)) * cos(a)sin(b)
d<H>/db = d<H>/d<X> d<X>/db + d<H>/d<Z> d<Z>/db = - sin(sin(a)sin(b)) * sin(a)cos(b)
"""
a = Parameter("a")
b = Parameter("b")
params = [a, b]
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(params[0], q[0])
qc.rx(params[1], q[0])
def combo_fn(x):
return jnp.power(x[0], 2) + jnp.cos(x[1])
def grad_combo_fn(x):
return np.array([2 * x[0], -np.sin(x[1])])
op = ListOp(
[
~StateFn(X) @ CircuitStateFn(primitive=qc, coeff=1.0),
~StateFn(Z) @ CircuitStateFn(primitive=qc, coeff=1.0),
],
combo_fn=combo_fn,
grad_combo_fn=None if autograd else grad_combo_fn,
)
state_grad = Gradient(grad_method=method).convert(operator=op, params=params)
values_dict = [
{a: np.pi / 4, b: np.pi},
{params[0]: np.pi / 4, params[1]: np.pi / 4},
{params[0]: np.pi / 2, params[1]: np.pi / 4},
]
correct_values = [[-1.0, 0.0], [-1.2397, -0.2397], [0, -0.45936]]
for i, value_dict in enumerate(values_dict):
np.testing.assert_array_almost_equal(
state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1
)
@data("lin_comb", "param_shift", "fin_diff")
def test_grad_combo_fn_chain_rule(self, method):
"""Test the chain rule for a custom gradient combo function."""
np.random.seed(2)
def combo_fn(x):
amplitudes = x[0].primitive.data
pdf = np.multiply(amplitudes, np.conj(amplitudes))
return np.sum(np.log(pdf)) / (-len(amplitudes))
def grad_combo_fn(x):
amplitudes = x[0].primitive.data
pdf = np.multiply(amplitudes, np.conj(amplitudes))
grad = []
for prob in pdf:
grad += [-1 / prob]
return grad
qc = RealAmplitudes(2, reps=1)
grad_op = ListOp([StateFn(qc.decompose())], combo_fn=combo_fn, grad_combo_fn=grad_combo_fn)
grad = Gradient(grad_method=method).convert(grad_op)
value_dict = dict(zip(qc.ordered_parameters, np.random.rand(len(qc.ordered_parameters))))
correct_values = [
[(-0.16666259133549044 + 0j)],
[(-7.244949702732864 + 0j)],
[(-2.979791752749964 + 0j)],
[(-5.310186078432614 + 0j)],
]
np.testing.assert_array_almost_equal(
grad.assign_parameters(value_dict).eval(), correct_values
)
def test_grad_combo_fn_chain_rule_nat_grad(self):
"""Test the chain rule for a custom gradient combo function."""
np.random.seed(2)
def combo_fn(x):
amplitudes = x[0].primitive.data
pdf = np.multiply(amplitudes, np.conj(amplitudes))
return np.sum(np.log(pdf)) / (-len(amplitudes))
def grad_combo_fn(x):
amplitudes = x[0].primitive.data
pdf = np.multiply(amplitudes, np.conj(amplitudes))
grad = []
for prob in pdf:
grad += [-1 / prob]
return grad
try:
qc = RealAmplitudes(2, reps=1)
grad_op = ListOp(
[StateFn(qc.decompose())], combo_fn=combo_fn, grad_combo_fn=grad_combo_fn
)
grad = NaturalGradient(grad_method="lin_comb", regularization="ridge").convert(
grad_op, qc.ordered_parameters
)
value_dict = dict(
zip(qc.ordered_parameters, np.random.rand(len(qc.ordered_parameters)))
)
correct_values = [[0.20777236], [-18.92560338], [-15.89005475], [-10.44002031]]
np.testing.assert_array_almost_equal(
grad.assign_parameters(value_dict).eval(), correct_values, decimal=3
)
except MissingOptionalLibraryError as ex:
self.skipTest(str(ex))
@data("lin_comb", "param_shift", "fin_diff")
def test_operator_coefficient_gradient(self, method):
"""Test the operator coefficient gradient
Tr( | psi > < psi | Z) = sin(a)sin(b)
Tr( | psi > < psi | X) = cos(a)
"""
a = Parameter("a")
b = Parameter("b")
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(a, q[0])
qc.rx(b, q[0])
coeff_0 = Parameter("c_0")
coeff_1 = Parameter("c_1")
ham = coeff_0 * X + coeff_1 * Z
op = StateFn(ham, is_measurement=True) @ CircuitStateFn(primitive=qc, coeff=1.0)
gradient_coeffs = [coeff_0, coeff_1]
coeff_grad = Gradient(grad_method=method).convert(op, gradient_coeffs)
values_dict = [
{coeff_0: 0.5, coeff_1: -1, a: np.pi / 4, b: np.pi},
{coeff_0: 0.5, coeff_1: -1, a: np.pi / 4, b: np.pi / 4},
]
correct_values = [[1 / np.sqrt(2), 0], [1 / np.sqrt(2), 1 / 2]]
for i, value_dict in enumerate(values_dict):
np.testing.assert_array_almost_equal(
coeff_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1
)
@data("lin_comb", "param_shift", "fin_diff")
def test_operator_coefficient_hessian(self, method):
"""Test the operator coefficient hessian
<Z> = Tr( | psi > < psi | Z) = sin(a)sin(b)
<X> = Tr( | psi > < psi | X) = cos(a)
d<H>/dc_0 = 2 * c_0 * <X> + c_1 * <Z>
d<H>/dc_1 = c_0 * <Z>
d^2<H>/dc_0^2 = 2 * <X>
d^2<H>/dc_0dc_1 = <Z>
d^2<H>/dc_1dc_0 = <Z>
d^2<H>/dc_1^2 = 0
"""
a = Parameter("a")
b = Parameter("b")
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(a, q[0])
qc.rx(b, q[0])
coeff_0 = Parameter("c_0")
coeff_1 = Parameter("c_1")
ham = coeff_0 * coeff_0 * X + coeff_1 * coeff_0 * Z
op = StateFn(ham, is_measurement=True) @ CircuitStateFn(primitive=qc, coeff=1.0)
gradient_coeffs = [(coeff_0, coeff_0), (coeff_0, coeff_1), (coeff_1, coeff_1)]
coeff_grad = Hessian(hess_method=method).convert(op, gradient_coeffs)
values_dict = [
{coeff_0: 0.5, coeff_1: -1, a: np.pi / 4, b: np.pi},
{coeff_0: 0.5, coeff_1: -1, a: np.pi / 4, b: np.pi / 4},
]
correct_values = [[2 / np.sqrt(2), 0, 0], [2 / np.sqrt(2), 1 / 2, 0]]
for i, value_dict in enumerate(values_dict):
np.testing.assert_array_almost_equal(
coeff_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1
)
@data("lin_comb", "param_shift", "fin_diff")
def test_circuit_sampler(self, method):
"""Test the gradient with circuit sampler
Tr(|psi><psi|Z) = sin(a)sin(b)
Tr(|psi><psi|X) = cos(a)
d<H>/da = - 0.5 sin(a) - 1 cos(a)sin(b)
d<H>/db = - 1 sin(a)cos(b)
"""
ham = 0.5 * X - 1 * Z
a = Parameter("a")
b = Parameter("b")
params = [a, b]
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(params[0], q[0])
qc.rx(params[1], q[0])
op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)
shots = 8000
if method == "fin_diff":
np.random.seed(8)
state_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).convert(
operator=op
)
else:
state_grad = Gradient(grad_method=method).convert(operator=op)
values_dict = [
{a: np.pi / 4, b: np.pi},
{params[0]: np.pi / 4, params[1]: np.pi / 4},
{params[0]: np.pi / 2, params[1]: np.pi / 4},
]
correct_values = [
[-0.5 / np.sqrt(2), 1 / np.sqrt(2)],
[-0.5 / np.sqrt(2) - 0.5, -1 / 2.0],
[-0.5, -1 / np.sqrt(2)],
]
backend = BasicAer.get_backend("qasm_simulator")
with self.assertWarns(DeprecationWarning):
q_instance = QuantumInstance(backend=backend, shots=shots)
with self.assertWarns(DeprecationWarning):
for i, value_dict in enumerate(values_dict):
sampler = CircuitSampler(backend=q_instance).convert(
state_grad, params={k: [v] for k, v in value_dict.items()}
)
np.testing.assert_array_almost_equal(
sampler.eval()[0], correct_values[i], decimal=1
)
@data("lin_comb", "param_shift", "fin_diff")
def test_circuit_sampler2(self, method):
"""Test the probability gradient with the circuit sampler
dp0/da = cos(a)sin(b) / 2
dp1/da = - cos(a)sin(b) / 2
dp0/db = sin(a)cos(b) / 2
dp1/db = - sin(a)cos(b) / 2
"""
a = Parameter("a")
b = Parameter("b")
params = [a, b]
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(params[0], q[0])
qc.rx(params[1], q[0])
op = CircuitStateFn(primitive=qc, coeff=1.0)
shots = 8000
if method == "fin_diff":
np.random.seed(8)
prob_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).convert(
operator=op, params=params
)
else:
prob_grad = Gradient(grad_method=method).convert(operator=op, params=params)
values_dict = [
{a: [np.pi / 4], b: [0]},
{params[0]: [np.pi / 4], params[1]: [np.pi / 4]},
{params[0]: [np.pi / 2], params[1]: [np.pi]},
]
correct_values = [
[[0, 0], [1 / (2 * np.sqrt(2)), -1 / (2 * np.sqrt(2))]],
[[1 / 4, -1 / 4], [1 / 4, -1 / 4]],
[[0, 0], [-1 / 2, 1 / 2]],
]
backend = BasicAer.get_backend("qasm_simulator")
with self.assertWarns(DeprecationWarning):
q_instance = QuantumInstance(backend=backend, shots=shots)
with self.assertWarns(DeprecationWarning):
for i, value_dict in enumerate(values_dict):
sampler = CircuitSampler(backend=q_instance).convert(prob_grad, params=value_dict)
result = sampler.eval()[0]
self.assertTrue(np.allclose(result[0].toarray(), correct_values[i][0], atol=0.1))
self.assertTrue(np.allclose(result[1].toarray(), correct_values[i][1], atol=0.1))
@idata(["statevector_simulator", "qasm_simulator"])
def test_gradient_wrapper(self, backend_type):
"""Test the gradient wrapper for probability gradients
dp0/da = cos(a)sin(b) / 2
dp1/da = - cos(a)sin(b) / 2
dp0/db = sin(a)cos(b) / 2
dp1/db = - sin(a)cos(b) / 2
"""
method = "param_shift"
a = Parameter("a")
b = Parameter("b")
params = [a, b]
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(params[0], q[0])
qc.rx(params[1], q[0])
op = CircuitStateFn(primitive=qc, coeff=1.0)
shots = 8000
backend = BasicAer.get_backend(backend_type)
with self.assertWarns(DeprecationWarning):
q_instance = QuantumInstance(
backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2
)
if method == "fin_diff":
np.random.seed(8)
prob_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).gradient_wrapper(
operator=op, bind_params=params, backend=q_instance
)
else:
with self.assertWarns(DeprecationWarning):
prob_grad = Gradient(grad_method=method).gradient_wrapper(
operator=op, bind_params=params, backend=q_instance
)
values = [[np.pi / 4, 0], [np.pi / 4, np.pi / 4], [np.pi / 2, np.pi]]
correct_values = [
[[0, 0], [1 / (2 * np.sqrt(2)), -1 / (2 * np.sqrt(2))]],
[[1 / 4, -1 / 4], [1 / 4, -1 / 4]],
[[0, 0], [-1 / 2, 1 / 2]],
]
with self.assertWarns(DeprecationWarning):
for i, value in enumerate(values):
result = prob_grad(value)
if backend_type == "qasm_simulator": # sparse result
result = [result[0].toarray(), result[1].toarray()]
self.assertTrue(np.allclose(result[0], correct_values[i][0], atol=0.1))
self.assertTrue(np.allclose(result[1], correct_values[i][1], atol=0.1))
@data(("statevector_simulator", 1e-7), ("qasm_simulator", 2e-1))
@unpack
def test_gradient_wrapper2(self, backend_type, atol):
"""Test the gradient wrapper for gradients checking that statevector and qasm gives the
same results
dp0/da = cos(a)sin(b) / 2
dp1/da = - cos(a)sin(b) / 2
dp0/db = sin(a)cos(b) / 2
dp1/db = - sin(a)cos(b) / 2
"""
method = "lin_comb"
a = Parameter("a")
b = Parameter("b")
params = [a, b]
qc = QuantumCircuit(2)
qc.h(1)
qc.h(0)
qc.sdg(1)
qc.cz(0, 1)
qc.ry(params[0], 0)
qc.rz(params[1], 0)
qc.h(1)
obs = (Z ^ X) - (Y ^ Y)
op = StateFn(obs, is_measurement=True) @ CircuitStateFn(primitive=qc)
shots = 8192 if backend_type == "qasm_simulator" else 1
values = [[0, np.pi / 2], [np.pi / 4, np.pi / 4], [np.pi / 3, np.pi / 9]]
correct_values = [[-4.0, 0], [-2.0, -4.82842712], [-0.68404029, -7.01396121]]
for i, value in enumerate(values):
backend = BasicAer.get_backend(backend_type)
with self.assertWarns(DeprecationWarning):
q_instance = QuantumInstance(
backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2
)
grad = NaturalGradient(grad_method=method).gradient_wrapper(
operator=op, bind_params=params, backend=q_instance
)
result = grad(value)
self.assertTrue(np.allclose(result, correct_values[i], atol=atol))
@slow_test
def test_vqe(self):
"""Test VQE with gradients"""
method = "lin_comb"
backend = "qasm_simulator"
with self.assertWarns(DeprecationWarning):
q_instance = QuantumInstance(
BasicAer.get_backend(backend), seed_simulator=79, seed_transpiler=2
)
# Define the Hamiltonian
h2_hamiltonian = (
-1.05 * (I ^ I) + 0.39 * (I ^ Z) - 0.39 * (Z ^ I) - 0.01 * (Z ^ Z) + 0.18 * (X ^ X)
)
h2_energy = -1.85727503
# Define the Ansatz
wavefunction = QuantumCircuit(2)
params = ParameterVector("theta", length=8)
itr = iter(params)
wavefunction.ry(next(itr), 0)
wavefunction.ry(next(itr), 1)
wavefunction.rz(next(itr), 0)
wavefunction.rz(next(itr), 1)
wavefunction.cx(0, 1)
wavefunction.ry(next(itr), 0)
wavefunction.ry(next(itr), 1)
wavefunction.rz(next(itr), 0)
wavefunction.rz(next(itr), 1)
# Conjugate Gradient algorithm
optimizer = CG(maxiter=10)
grad = Gradient(grad_method=method)
# Gradient callable
with self.assertWarns(DeprecationWarning):
vqe = VQE(
ansatz=wavefunction, optimizer=optimizer, gradient=grad, quantum_instance=q_instance
)
result = vqe.compute_minimum_eigenvalue(operator=h2_hamiltonian)
np.testing.assert_almost_equal(result.optimal_value, h2_energy, decimal=0)
def test_qfi_overlap_works_with_bound_parameters(self):
"""Test all QFI methods work if the circuit contains a gate with bound parameters."""
x = Parameter("x")
circuit = QuantumCircuit(1)
circuit.ry(np.pi / 4, 0)
circuit.rx(x, 0)
state = StateFn(circuit)
methods = ["lin_comb_full", "overlap_diag", "overlap_block_diag"]
reference = 0.5
for method in methods:
with self.subTest(method):
qfi = QFI(method)
value = np.real(qfi.convert(state, [x]).bind_parameters({x: 0.12}).eval())
self.assertAlmostEqual(value[0][0], reference)
@ddt
class TestParameterGradients(QiskitOpflowTestCase):
"""Test taking the gradient of parameter expressions."""
def test_grad(self):
"""Test taking the gradient of parameter expressions."""
x, y = Parameter("x"), Parameter("y")
with self.subTest("linear"):
expr = 2 * x + y
grad = expr.gradient(x)
self.assertEqual(grad, 2)
grad = expr.gradient(y)
self.assertEqual(grad, 1)
with self.subTest("polynomial"):
expr = x * x * x - x * y + y * y
grad = expr.gradient(x)
self.assertEqual(grad, 3 * x * x - y)
grad = expr.gradient(y)
self.assertEqual(grad, -1 * x + 2 * y)
def test_converted_to_float_if_bound(self):
"""Test the gradient is a float when no free symbols are left."""
x = Parameter("x")
expr = 2 * x + 1
grad = expr.gradient(x)
self.assertIsInstance(grad, float)
def test_converted_to_complex_if_bound(self):
"""Test the gradient is a complex when no free symbols are left."""
x = Parameter("x")
x2 = 1j * x
expr = 2 * x2 + 1
grad = expr.gradient(x)
self.assertIsInstance(grad, complex)
@ddt
class TestQFI(QiskitOpflowTestCase):
"""Tests for the quantum Fisher information."""
@data("lin_comb_full", "overlap_block_diag", "overlap_diag")
def test_qfi_simple(self, method):
"""Test if the quantum fisher information calculation is correct for a simple test case.
QFI = [[1, 0], [0, 1]] - [[0, 0], [0, cos^2(a)]]
"""
# create the circuit
a, b = Parameter("a"), Parameter("b")
qc = QuantumCircuit(1)
qc.h(0)
qc.rz(a, 0)
qc.rx(b, 0)
# convert the circuit to a QFI object
op = CircuitStateFn(qc)
qfi = QFI(qfi_method=method).convert(operator=op)
# test for different values
values_dict = [{a: np.pi / 4, b: 0.1}, {a: np.pi, b: 0.1}, {a: np.pi / 2, b: 0.1}]
correct_values = [[[1, 0], [0, 0.5]], [[1, 0], [0, 0]], [[1, 0], [0, 1]]]
for i, value_dict in enumerate(values_dict):
actual = qfi.assign_parameters(value_dict).eval()
np.testing.assert_array_almost_equal(actual, correct_values[i], decimal=1)
def test_qfi_phase_fix(self):
"""Test the phase-fix argument in a QFI calculation
QFI = [[1, 0], [0, 1]].
"""
# create the circuit
a, b = Parameter("a"), Parameter("b")
qc = QuantumCircuit(1)
qc.h(0)
qc.rz(a, 0)
qc.rx(b, 0)
# convert the circuit to a QFI object
op = CircuitStateFn(qc)
qfi = LinCombFull(phase_fix=False).convert(operator=op, params=[a, b])
# test for different values
value_dict = {a: np.pi / 4, b: 0.1}
correct_values = [[1, 0], [0, 1]]
actual = qfi.assign_parameters(value_dict).eval()
np.testing.assert_array_almost_equal(actual, correct_values, decimal=2)
def test_qfi_maxcut(self):
"""Test the QFI for a simple MaxCut problem.
This is interesting because it contains the same parameters in different gates.
"""
# create maxcut circuit for the hamiltonian
# H = (I ^ I ^ Z ^ Z) + (I ^ Z ^ I ^ Z) + (Z ^ I ^ I ^ Z) + (I ^ Z ^ Z ^ I)
x = ParameterVector("x", 2)
ansatz = QuantumCircuit(4)
# initial hadamard layer
ansatz.h(ansatz.qubits)
# e^{iZZ} layers
def expiz(qubit0, qubit1):
ansatz.cx(qubit0, qubit1)
ansatz.rz(2 * x[0], qubit1)
ansatz.cx(qubit0, qubit1)
expiz(2, 1)
expiz(3, 0)
expiz(2, 0)
expiz(1, 0)
# mixer layer with RX gates
for i in range(ansatz.num_qubits):
ansatz.rx(2 * x[1], i)
point = {x[0]: 0.4, x[1]: 0.69}
# reference computed via finite difference
reference = np.array([[16.0, -5.551], [-5.551, 18.497]])
# QFI from gradient framework
qfi = QFI().convert(CircuitStateFn(ansatz), params=x[:])
actual = np.array(qfi.bind_parameters(point).eval()).real
np.testing.assert_array_almost_equal(actual, reference, decimal=3)
def test_qfi_circuit_shared_params(self):
"""Test the QFI circuits for parameters shared across some gates."""
# create the test circuit
x = Parameter("x")
circuit = QuantumCircuit(1)
circuit.rx(x, 0)
circuit.rx(x, 0)
# construct the QFI circuits used in the evaluation
circuit1 = QuantumCircuit(2)
circuit1.h(1)
circuit1.x(1)
circuit1.cx(1, 0)
circuit1.x(1)
circuit1.cx(1, 0)
# circuit1.rx(x, 0) # trimmed
# circuit1.rx(x, 0) # trimmed
circuit1.h(1)
circuit2 = QuantumCircuit(2)
circuit2.h(1)
circuit2.x(1)
circuit2.cx(1, 0)
circuit2.x(1)
circuit2.rx(x, 0)
circuit2.cx(1, 0)
# circuit2.rx(x, 0) # trimmed
circuit2.h(1)
circuit3 = QuantumCircuit(2)
circuit3.h(1)
circuit3.cx(1, 0)
circuit3.x(1)
circuit3.rx(x, 0)
circuit3.cx(1, 0)
# circuit3.rx(x, 0) # trimmed
circuit3.x(1)
circuit3.h(1)
circuit4 = QuantumCircuit(2)
circuit4.h(1)
circuit4.rx(x, 0)
circuit4.x(1)
circuit4.cx(1, 0)
circuit4.x(1)
circuit4.cx(1, 0)
# circuit4.rx(x, 0) # trimmed
circuit4.h(1)
# this naming and adding of register is required bc circuit's are only equal if the
# register have the same names
circuit5 = QuantumCircuit(2)
circuit5.h(1)
circuit5.sdg(1)
circuit5.cx(1, 0)
# circuit5.rx(x, 0) # trimmed
circuit5.h(1)
circuit6 = QuantumCircuit(2)
circuit6.h(1)
circuit6.sdg(1)
circuit6.rx(x, 0)
circuit6.cx(1, 0)
circuit6.h(1)
# compare
qfi = QFI().convert(StateFn(circuit), params=[x])
circuit_sets = (
[circuit1, circuit2, circuit3, circuit4],
[circuit5, circuit6],
[circuit5, circuit6],
)
list_ops = (
qfi.oplist[0].oplist[0].oplist[:-1],
qfi.oplist[0].oplist[0].oplist[-1].oplist[0].oplist,
qfi.oplist[0].oplist[0].oplist[-1].oplist[1].oplist,
)
# compose both on the same circuit such that the comparison works
base = QuantumCircuit(2)
for i, (circuit_set, list_op) in enumerate(zip(circuit_sets, list_ops)):
for j, (reference, composed_op) in enumerate(zip(circuit_set, list_op)):
with self.subTest(f"set {i} circuit {j}"):
primitive = composed_op[1].primitive
self.assertEqual(base.compose(primitive), base.compose(reference))
def test_overlap_qfi_bound_parameters(self):
"""Test the overlap QFI works on a circuit with multi-parameter bound gates."""
x = Parameter("x")
circuit = QuantumCircuit(1)
circuit.u(1, 2, 3, 0)
circuit.rx(x, 0)
qfi = QFI("overlap_diag").convert(StateFn(circuit), [x])
value = qfi.bind_parameters({x: 1}).eval()[0][0]
ref = 0.87737713
self.assertAlmostEqual(value, ref)
def test_overlap_qfi_raises_on_multiparam(self):
"""Test the overlap QFI raises an appropriate error on multi-param unbound gates."""
x = ParameterVector("x", 2)
circuit = QuantumCircuit(1)
circuit.u(x[0], x[1], 2, 0)
with self.assertRaises(NotImplementedError):
_ = QFI("overlap_diag").convert(StateFn(circuit), [x])
def test_overlap_qfi_raises_on_unsupported_gate(self):
"""Test the overlap QFI raises an appropriate error on multi-param unbound gates."""
x = Parameter("x")
circuit = QuantumCircuit(1)
circuit.p(x, 0)
with self.assertRaises(NotImplementedError):
_ = QFI("overlap_diag").convert(StateFn(circuit), [x])
@data(-Y, Z - 1j * Y)
def test_aux_meas_op(self, aux_meas_op):
"""Test various auxiliary measurement operators for probability gradients with LinComb
Gradient.
"""
a = Parameter("a")
b = Parameter("b")
params = [a, b]
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(params[0], q[0])
qc.rx(params[1], q[0])
op = CircuitStateFn(primitive=qc, coeff=1.0)
shots = 10000
prob_grad = LinComb(aux_meas_op=aux_meas_op).convert(operator=op, params=params)
value_dicts = [{a: [np.pi / 4], b: [0]}, {a: [np.pi / 2], b: [np.pi / 4]}]
if aux_meas_op == -Y:
correct_values = [
[[-0.5, 0.5], [-1 / (np.sqrt(2) * 2), -1 / (np.sqrt(2) * 2)]],
[[-1 / (np.sqrt(2) * 2), 1 / (np.sqrt(2) * 2)], [0, 0]],
]
else:
correct_values = [
[[-0.5j, 0.5j], [(1 - 1j) / (np.sqrt(2) * 2), (-1 - 1j) / (np.sqrt(2) * 2)]],
[
[-1j / (np.sqrt(2) * 2), 1j / (np.sqrt(2) * 2)],
[1 / (np.sqrt(2) * 2), -1 / (np.sqrt(2) * 2)],
],
]
for backend_type in ["qasm_simulator", "statevector_simulator"]:
for j, value_dict in enumerate(value_dicts):
with self.assertWarns(DeprecationWarning):
q_instance = QuantumInstance(
backend=BasicAer.get_backend(backend_type), shots=shots
)
result = (
CircuitSampler(backend=q_instance)
.convert(prob_grad, params=value_dict)
.eval()[0]
)
if backend_type == "qasm_simulator": # sparse result
result = [result[0].toarray()[0], result[1].toarray()[0]]
for i, item in enumerate(result):
np.testing.assert_array_almost_equal(item, correct_values[j][i], decimal=1)
def test_unsupported_aux_meas_op(self):
"""Test error for unsupported auxiliary measurement operator in LinComb Gradient.
dp0/da = cos(a)sin(b) / 2
dp1/da = - cos(a)sin(b) / 2
dp0/db = sin(a)cos(b) / 2
dp1/db = - sin(a)cos(b) / 2
"""
a = Parameter("a")
b = Parameter("b")
params = [a, b]
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(params[0], q[0])
qc.rx(params[1], q[0])
op = CircuitStateFn(primitive=qc, coeff=1.0)
shots = 8000
aux_meas_op = X
with self.assertRaises(ValueError):
prob_grad = LinComb(aux_meas_op=aux_meas_op).convert(operator=op, params=params)
value_dict = {a: [np.pi / 4], b: [0]}
backend = BasicAer.get_backend("qasm_simulator")
with self.assertWarns(DeprecationWarning):
q_instance = QuantumInstance(backend=backend, shots=shots)
CircuitSampler(backend=q_instance).convert(prob_grad, params=value_dict).eval()
def test_nat_grad_error(self):
"""Test the NaturalGradient throws an Error.
dp0/da = cos(a)sin(b) / 2
dp1/da = - cos(a)sin(b) / 2
dp0/db = sin(a)cos(b) / 2
dp1/db = - sin(a)cos(b) / 2
"""
method = "lin_comb"
a = Parameter("a")
b = Parameter("b")
params = [a, b]
qc = QuantumCircuit(2)
qc.h(1)
qc.h(0)
qc.sdg(1)
qc.cz(0, 1)
qc.ry(params[0], 0)
qc.rz(params[1], 0)
qc.h(1)
obs = (Z ^ X) - (Y ^ Y)
op = StateFn(obs, is_measurement=True) @ CircuitStateFn(primitive=qc)
backend_type = "qasm_simulator"
shots = 1
value = [0, np.pi / 2]
backend = BasicAer.get_backend(backend_type)
with self.assertWarns(DeprecationWarning):
q_instance = QuantumInstance(
backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2
)
with self.assertWarns(DeprecationWarning):
grad = NaturalGradient(grad_method=method).gradient_wrapper(
operator=op, bind_params=params, backend=q_instance
)
with self.assertWarns(DeprecationWarning):
with self.assertRaises(ValueError):
grad(value)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test MatrixExpectation"""
import unittest
from test.python.opflow import QiskitOpflowTestCase
import itertools
import numpy as np
from qiskit.utils import QuantumInstance
from qiskit.opflow import (
X,
Y,
Z,
I,
CX,
H,
S,
ListOp,
Zero,
One,
Plus,
Minus,
StateFn,
MatrixExpectation,
CircuitSampler,
)
from qiskit import BasicAer
class TestMatrixExpectation(QiskitOpflowTestCase):
"""Pauli Change of Basis Expectation tests."""
def setUp(self) -> None:
super().setUp()
self.seed = 97
backend = BasicAer.get_backend("statevector_simulator")
with self.assertWarns(DeprecationWarning):
q_instance = QuantumInstance(
backend, seed_simulator=self.seed, seed_transpiler=self.seed
)
self.sampler = CircuitSampler(q_instance, attach_results=True)
self.expect = MatrixExpectation()
def test_pauli_expect_pair(self):
"""pauli expect pair test"""
op = Z ^ Z
# wf = (Pl^Pl) + (Ze^Ze)
wf = CX @ (H ^ I) @ Zero
converted_meas = self.expect.convert(~StateFn(op) @ wf)
self.assertAlmostEqual(converted_meas.eval(), 0, delta=0.1)
with self.assertWarns(DeprecationWarning):
sampled = self.sampler.convert(converted_meas)
self.assertAlmostEqual(sampled.eval(), 0, delta=0.1)
def test_pauli_expect_single(self):
"""pauli expect single test"""
paulis = [Z, X, Y, I]
states = [Zero, One, Plus, Minus, S @ Plus, S @ Minus]
for pauli, state in itertools.product(paulis, states):
converted_meas = self.expect.convert(~StateFn(pauli) @ state)
matmulmean = state.adjoint().to_matrix() @ pauli.to_matrix() @ state.to_matrix()
self.assertAlmostEqual(converted_meas.eval(), matmulmean, delta=0.1)
with self.assertWarns(DeprecationWarning):
sampled = self.sampler.convert(converted_meas)
self.assertAlmostEqual(sampled.eval(), matmulmean, delta=0.1)
def test_pauli_expect_op_vector(self):
"""pauli expect op vector test"""
paulis_op = ListOp([X, Y, Z, I])
converted_meas = self.expect.convert(~StateFn(paulis_op))
with self.assertWarns(DeprecationWarning):
plus_mean = converted_meas @ Plus
np.testing.assert_array_almost_equal(plus_mean.eval(), [1, 0, 0, 1], decimal=1)
sampled_plus = self.sampler.convert(plus_mean)
np.testing.assert_array_almost_equal(sampled_plus.eval(), [1, 0, 0, 1], decimal=1)
minus_mean = converted_meas @ Minus
np.testing.assert_array_almost_equal(minus_mean.eval(), [-1, 0, 0, 1], decimal=1)
sampled_minus = self.sampler.convert(minus_mean)
np.testing.assert_array_almost_equal(sampled_minus.eval(), [-1, 0, 0, 1], decimal=1)
zero_mean = converted_meas @ Zero
np.testing.assert_array_almost_equal(zero_mean.eval(), [0, 0, 1, 1], decimal=1)
sampled_zero = self.sampler.convert(zero_mean)
np.testing.assert_array_almost_equal(sampled_zero.eval(), [0, 0, 1, 1], decimal=1)
sum_zero = (Plus + Minus) * (0.5**0.5)
sum_zero_mean = converted_meas @ sum_zero
np.testing.assert_array_almost_equal(sum_zero_mean.eval(), [0, 0, 1, 1], decimal=1)
sampled_zero = self.sampler.convert(sum_zero)
np.testing.assert_array_almost_equal(
(converted_meas @ sampled_zero).eval(), [0, 0, 1, 1], decimal=1
)
for i, op in enumerate(paulis_op.oplist):
mat_op = op.to_matrix()
np.testing.assert_array_almost_equal(
zero_mean.eval()[i],
Zero.adjoint().to_matrix() @ mat_op @ Zero.to_matrix(),
decimal=1,
)
np.testing.assert_array_almost_equal(
plus_mean.eval()[i],
Plus.adjoint().to_matrix() @ mat_op @ Plus.to_matrix(),
decimal=1,
)
np.testing.assert_array_almost_equal(
minus_mean.eval()[i],
Minus.adjoint().to_matrix() @ mat_op @ Minus.to_matrix(),
decimal=1,
)
def test_pauli_expect_state_vector(self):
"""pauli expect state vector test"""
states_op = ListOp([One, Zero, Plus, Minus])
paulis_op = X
converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op)
np.testing.assert_array_almost_equal(converted_meas.eval(), [0, 0, 1, -1], decimal=1)
with self.assertWarns(DeprecationWarning):
sampled = self.sampler.convert(converted_meas)
np.testing.assert_array_almost_equal(sampled.eval(), [0, 0, 1, -1], decimal=1)
# Small test to see if execution results are accessible
for composed_op in sampled:
self.assertIn("statevector", composed_op[1].execution_results)
def test_pauli_expect_op_vector_state_vector(self):
"""pauli expect op vector state vector test"""
paulis_op = ListOp([X, Y, Z, I])
states_op = ListOp([One, Zero, Plus, Minus])
valids = [[+0, 0, 1, -1], [+0, 0, 0, 0], [-1, 1, 0, -0], [+1, 1, 1, 1]]
converted_meas = self.expect.convert(~StateFn(paulis_op))
np.testing.assert_array_almost_equal((converted_meas @ states_op).eval(), valids, decimal=1)
with self.assertWarns(DeprecationWarning):
sampled = self.sampler.convert(states_op)
np.testing.assert_array_almost_equal((converted_meas @ sampled).eval(), valids, decimal=1)
def test_multi_representation_ops(self):
"""Test observables with mixed representations"""
mixed_ops = ListOp([X.to_matrix_op(), H, H + I, X])
converted_meas = self.expect.convert(~StateFn(mixed_ops))
plus_mean = converted_meas @ Plus
with self.assertWarns(DeprecationWarning):
sampled_plus = self.sampler.convert(plus_mean)
np.testing.assert_array_almost_equal(
sampled_plus.eval(), [1, 0.5**0.5, (1 + 0.5**0.5), 1], decimal=1
)
def test_matrix_expectation_non_hermite_op(self):
"""Test MatrixExpectation for non hermitian operator"""
exp = ~StateFn(1j * Z) @ One
self.assertEqual(self.expect.convert(exp).eval(), 1j)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test Operator construction, including OpPrimitives and singletons."""
import itertools
import unittest
from math import pi
from test.python.opflow import QiskitOpflowTestCase
import numpy as np
import scipy
from ddt import data, ddt, unpack
from scipy.sparse import csr_matrix
from scipy.stats import unitary_group
from qiskit import QiskitError, transpile
from qiskit.circuit import (
Instruction,
Parameter,
ParameterVector,
QuantumCircuit,
QuantumRegister,
)
from qiskit.circuit.library import CZGate, ZGate
from qiskit.extensions.exceptions import ExtensionError
from qiskit.opflow import (
CX,
CircuitOp,
CircuitStateFn,
ComposedOp,
DictStateFn,
EvolvedOp,
H,
I,
ListOp,
MatrixOp,
Minus,
OperatorBase,
OperatorStateFn,
OpflowError,
PauliOp,
PrimitiveOp,
SparseVectorStateFn,
StateFn,
SummedOp,
T,
TensoredOp,
VectorStateFn,
X,
Y,
Z,
Zero,
)
from qiskit.quantum_info import Operator, Pauli, Statevector
# pylint: disable=invalid-name
@ddt
class TestOpConstruction(QiskitOpflowTestCase):
"""Operator Construction tests."""
def test_pauli_primitives(self):
"""from to file test"""
newop = X ^ Y ^ Z ^ I
self.assertEqual(newop.primitive, Pauli("XYZI"))
kpower_op = (Y ^ 5) ^ (I ^ 3)
self.assertEqual(kpower_op.primitive, Pauli("YYYYYIII"))
kpower_op2 = (Y ^ I) ^ 4
self.assertEqual(kpower_op2.primitive, Pauli("YIYIYIYI"))
# Check immutability
self.assertEqual(X.primitive, Pauli("X"))
self.assertEqual(Y.primitive, Pauli("Y"))
self.assertEqual(Z.primitive, Pauli("Z"))
self.assertEqual(I.primitive, Pauli("I"))
def test_composed_eval(self):
"""Test eval of ComposedOp"""
self.assertAlmostEqual(Minus.eval("1"), -(0.5**0.5))
def test_xz_compose_phase(self):
"""Test phase composition"""
self.assertEqual((-1j * Y).eval("0").eval("0"), 0)
self.assertEqual((-1j * Y).eval("0").eval("1"), 1)
self.assertEqual((-1j * Y).eval("1").eval("0"), -1)
self.assertEqual((-1j * Y).eval("1").eval("1"), 0)
self.assertEqual((X @ Z).eval("0").eval("0"), 0)
self.assertEqual((X @ Z).eval("0").eval("1"), 1)
self.assertEqual((X @ Z).eval("1").eval("0"), -1)
self.assertEqual((X @ Z).eval("1").eval("1"), 0)
self.assertEqual((1j * Y).eval("0").eval("0"), 0)
self.assertEqual((1j * Y).eval("0").eval("1"), -1)
self.assertEqual((1j * Y).eval("1").eval("0"), 1)
self.assertEqual((1j * Y).eval("1").eval("1"), 0)
self.assertEqual((Z @ X).eval("0").eval("0"), 0)
self.assertEqual((Z @ X).eval("0").eval("1"), -1)
self.assertEqual((Z @ X).eval("1").eval("0"), 1)
self.assertEqual((Z @ X).eval("1").eval("1"), 0)
def test_evals(self):
"""evals test"""
# TODO: Think about eval names
self.assertEqual(Z.eval("0").eval("0"), 1)
self.assertEqual(Z.eval("1").eval("0"), 0)
self.assertEqual(Z.eval("0").eval("1"), 0)
self.assertEqual(Z.eval("1").eval("1"), -1)
self.assertEqual(X.eval("0").eval("0"), 0)
self.assertEqual(X.eval("1").eval("0"), 1)
self.assertEqual(X.eval("0").eval("1"), 1)
self.assertEqual(X.eval("1").eval("1"), 0)
self.assertEqual(Y.eval("0").eval("0"), 0)
self.assertEqual(Y.eval("1").eval("0"), -1j)
self.assertEqual(Y.eval("0").eval("1"), 1j)
self.assertEqual(Y.eval("1").eval("1"), 0)
with self.assertRaises(ValueError):
Y.eval("11")
with self.assertRaises(ValueError):
(X ^ Y).eval("1111")
with self.assertRaises(ValueError):
Y.eval((X ^ X).to_matrix_op())
# Check that Pauli logic eval returns same as matrix logic
self.assertEqual(PrimitiveOp(Z.to_matrix()).eval("0").eval("0"), 1)
self.assertEqual(PrimitiveOp(Z.to_matrix()).eval("1").eval("0"), 0)
self.assertEqual(PrimitiveOp(Z.to_matrix()).eval("0").eval("1"), 0)
self.assertEqual(PrimitiveOp(Z.to_matrix()).eval("1").eval("1"), -1)
self.assertEqual(PrimitiveOp(X.to_matrix()).eval("0").eval("0"), 0)
self.assertEqual(PrimitiveOp(X.to_matrix()).eval("1").eval("0"), 1)
self.assertEqual(PrimitiveOp(X.to_matrix()).eval("0").eval("1"), 1)
self.assertEqual(PrimitiveOp(X.to_matrix()).eval("1").eval("1"), 0)
self.assertEqual(PrimitiveOp(Y.to_matrix()).eval("0").eval("0"), 0)
self.assertEqual(PrimitiveOp(Y.to_matrix()).eval("1").eval("0"), -1j)
self.assertEqual(PrimitiveOp(Y.to_matrix()).eval("0").eval("1"), 1j)
self.assertEqual(PrimitiveOp(Y.to_matrix()).eval("1").eval("1"), 0)
pauli_op = Z ^ I ^ X ^ Y
mat_op = PrimitiveOp(pauli_op.to_matrix())
full_basis = list(map("".join, itertools.product("01", repeat=pauli_op.num_qubits)))
for bstr1, bstr2 in itertools.product(full_basis, full_basis):
# print('{} {} {} {}'.format(bstr1, bstr2, pauli_op.eval(bstr1, bstr2),
# mat_op.eval(bstr1, bstr2)))
np.testing.assert_array_almost_equal(
pauli_op.eval(bstr1).eval(bstr2), mat_op.eval(bstr1).eval(bstr2)
)
gnarly_op = SummedOp(
[
(H ^ I ^ Y).compose(X ^ X ^ Z).tensor(Z),
PrimitiveOp(Operator.from_label("+r0I")),
3 * (X ^ CX ^ T),
],
coeff=3 + 0.2j,
)
gnarly_mat_op = PrimitiveOp(gnarly_op.to_matrix())
full_basis = list(map("".join, itertools.product("01", repeat=gnarly_op.num_qubits)))
for bstr1, bstr2 in itertools.product(full_basis, full_basis):
np.testing.assert_array_almost_equal(
gnarly_op.eval(bstr1).eval(bstr2), gnarly_mat_op.eval(bstr1).eval(bstr2)
)
def test_circuit_construction(self):
"""circuit construction test"""
hadq2 = H ^ I
cz = hadq2.compose(CX).compose(hadq2)
qc = QuantumCircuit(2)
qc.append(cz.primitive, qargs=range(2))
ref_cz_mat = PrimitiveOp(CZGate()).to_matrix()
np.testing.assert_array_almost_equal(cz.to_matrix(), ref_cz_mat)
def test_io_consistency(self):
"""consistency test"""
new_op = X ^ Y ^ I
label = "XYI"
# label = new_op.primitive.to_label()
self.assertEqual(str(new_op.primitive), label)
np.testing.assert_array_almost_equal(
new_op.primitive.to_matrix(), Operator.from_label(label).data
)
self.assertEqual(new_op.primitive, Pauli(label))
x_mat = X.primitive.to_matrix()
y_mat = Y.primitive.to_matrix()
i_mat = np.eye(2, 2)
np.testing.assert_array_almost_equal(
new_op.primitive.to_matrix(), np.kron(np.kron(x_mat, y_mat), i_mat)
)
hi = np.kron(H.to_matrix(), I.to_matrix())
hi2 = Operator.from_label("HI").data
hi3 = (H ^ I).to_matrix()
np.testing.assert_array_almost_equal(hi, hi2)
np.testing.assert_array_almost_equal(hi2, hi3)
xy = np.kron(X.to_matrix(), Y.to_matrix())
xy2 = Operator.from_label("XY").data
xy3 = (X ^ Y).to_matrix()
np.testing.assert_array_almost_equal(xy, xy2)
np.testing.assert_array_almost_equal(xy2, xy3)
# Check if numpy array instantiation is the same as from Operator
matrix_op = Operator.from_label("+r")
np.testing.assert_array_almost_equal(
PrimitiveOp(matrix_op).to_matrix(), PrimitiveOp(matrix_op.data).to_matrix()
)
# Ditto list of lists
np.testing.assert_array_almost_equal(
PrimitiveOp(matrix_op.data.tolist()).to_matrix(),
PrimitiveOp(matrix_op.data).to_matrix(),
)
# TODO make sure this works once we resolve endianness mayhem
# qc = QuantumCircuit(3)
# qc.x(2)
# qc.y(1)
# from qiskit import BasicAer, QuantumCircuit, execute
# unitary = execute(qc, BasicAer.get_backend('unitary_simulator')).result().get_unitary()
# np.testing.assert_array_almost_equal(new_op.primitive.to_matrix(), unitary)
def test_to_matrix(self):
"""to matrix text"""
np.testing.assert_array_equal(X.to_matrix(), Operator.from_label("X").data)
np.testing.assert_array_equal(Y.to_matrix(), Operator.from_label("Y").data)
np.testing.assert_array_equal(Z.to_matrix(), Operator.from_label("Z").data)
op1 = Y + H
np.testing.assert_array_almost_equal(op1.to_matrix(), Y.to_matrix() + H.to_matrix())
op2 = op1 * 0.5
np.testing.assert_array_almost_equal(op2.to_matrix(), op1.to_matrix() * 0.5)
op3 = (4 - 0.6j) * op2
np.testing.assert_array_almost_equal(op3.to_matrix(), op2.to_matrix() * (4 - 0.6j))
op4 = op3.tensor(X)
np.testing.assert_array_almost_equal(
op4.to_matrix(), np.kron(op3.to_matrix(), X.to_matrix())
)
op5 = op4.compose(H ^ I)
np.testing.assert_array_almost_equal(
op5.to_matrix(), np.dot(op4.to_matrix(), (H ^ I).to_matrix())
)
op6 = op5 + PrimitiveOp(Operator.from_label("+r").data)
np.testing.assert_array_almost_equal(
op6.to_matrix(), op5.to_matrix() + Operator.from_label("+r").data
)
param = Parameter("Ξ±")
m = np.array([[0, -1j], [1j, 0]])
op7 = MatrixOp(m, param)
np.testing.assert_array_equal(op7.to_matrix(), m * param)
param = Parameter("Ξ²")
op8 = PauliOp(primitive=Pauli("Y"), coeff=param)
np.testing.assert_array_equal(op8.to_matrix(), m * param)
param = Parameter("Ξ³")
qc = QuantumCircuit(1)
qc.h(0)
op9 = CircuitOp(qc, coeff=param)
m = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
np.testing.assert_array_equal(op9.to_matrix(), m * param)
def test_circuit_op_to_matrix(self):
"""test CircuitOp.to_matrix"""
qc = QuantumCircuit(1)
qc.rz(1.0, 0)
qcop = CircuitOp(qc)
np.testing.assert_array_almost_equal(
qcop.to_matrix(), scipy.linalg.expm(-0.5j * Z.to_matrix())
)
def test_matrix_to_instruction(self):
"""Test MatrixOp.to_instruction yields an Instruction object."""
matop = (H ^ 3).to_matrix_op()
with self.subTest("assert to_instruction returns Instruction"):
self.assertIsInstance(matop.to_instruction(), Instruction)
matop = ((H ^ 3) + (Z ^ 3)).to_matrix_op()
with self.subTest("matrix operator is not unitary"):
with self.assertRaises(ExtensionError):
matop.to_instruction()
def test_adjoint(self):
"""adjoint test"""
gnarly_op = 3 * (H ^ I ^ Y).compose(X ^ X ^ Z).tensor(T ^ Z) + PrimitiveOp(
Operator.from_label("+r0IX").data
)
np.testing.assert_array_almost_equal(
np.conj(np.transpose(gnarly_op.to_matrix())), gnarly_op.adjoint().to_matrix()
)
def test_primitive_strings(self):
"""get primitives test"""
self.assertEqual(X.primitive_strings(), {"Pauli"})
gnarly_op = 3 * (H ^ I ^ Y).compose(X ^ X ^ Z).tensor(T ^ Z) + PrimitiveOp(
Operator.from_label("+r0IX").data
)
self.assertEqual(gnarly_op.primitive_strings(), {"QuantumCircuit", "Matrix"})
def test_to_pauli_op(self):
"""Test to_pauli_op method"""
gnarly_op = 3 * (H ^ I ^ Y).compose(X ^ X ^ Z).tensor(T ^ Z) + PrimitiveOp(
Operator.from_label("+r0IX").data
)
mat_op = gnarly_op.to_matrix_op()
pauli_op = gnarly_op.to_pauli_op()
self.assertIsInstance(pauli_op, SummedOp)
for p in pauli_op:
self.assertIsInstance(p, PauliOp)
np.testing.assert_array_almost_equal(mat_op.to_matrix(), pauli_op.to_matrix())
def test_circuit_permute(self):
r"""Test the CircuitOp's .permute method"""
perm = range(7)[::-1]
c_op = (
((CX ^ 3) ^ X)
@ (H ^ 7)
@ (X ^ Y ^ Z ^ I ^ X ^ X ^ X)
@ (Y ^ (CX ^ 3))
@ (X ^ Y ^ Z ^ I ^ X ^ X ^ X)
)
c_op_perm = c_op.permute(perm)
self.assertNotEqual(c_op, c_op_perm)
c_op_id = c_op_perm.permute(perm)
self.assertEqual(c_op, c_op_id)
def test_summed_op_reduce(self):
"""Test SummedOp"""
sum_op = (X ^ X * 2) + (Y ^ Y) # type: PauliSumOp
sum_op = sum_op.to_pauli_op() # type: SummedOp[PauliOp]
with self.subTest("SummedOp test 1"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [2, 1])
sum_op = (X ^ X * 2) + (Y ^ Y)
sum_op += Y ^ Y
sum_op = sum_op.to_pauli_op() # type: SummedOp[PauliOp]
with self.subTest("SummedOp test 2-a"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [2, 1, 1])
sum_op = sum_op.collapse_summands()
with self.subTest("SummedOp test 2-b"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [2, 2])
sum_op = (X ^ X * 2) + (Y ^ Y)
sum_op += (Y ^ Y) + (X ^ X * 2)
sum_op = sum_op.to_pauli_op() # type: SummedOp[PauliOp]
with self.subTest("SummedOp test 3-a"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY", "YY", "XX"])
self.assertListEqual([op.coeff for op in sum_op], [2, 1, 1, 2])
sum_op = sum_op.reduce().to_pauli_op()
with self.subTest("SummedOp test 3-b"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [4, 2])
sum_op = SummedOp([X ^ X * 2, Y ^ Y], 2)
with self.subTest("SummedOp test 4-a"):
self.assertEqual(sum_op.coeff, 2)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [2, 1])
sum_op = sum_op.collapse_summands()
with self.subTest("SummedOp test 4-b"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [4, 2])
sum_op = SummedOp([X ^ X * 2, Y ^ Y], 2)
sum_op += Y ^ Y
with self.subTest("SummedOp test 5-a"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [4, 2, 1])
sum_op = sum_op.collapse_summands()
with self.subTest("SummedOp test 5-b"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [4, 3])
sum_op = SummedOp([X ^ X * 2, Y ^ Y], 2)
sum_op += ((X ^ X) * 2 + (Y ^ Y)).to_pauli_op()
with self.subTest("SummedOp test 6-a"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY", "XX", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [4, 2, 2, 1])
sum_op = sum_op.collapse_summands()
with self.subTest("SummedOp test 6-b"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [6, 3])
sum_op = SummedOp([X ^ X * 2, Y ^ Y], 2)
sum_op += sum_op
with self.subTest("SummedOp test 7-a"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY", "XX", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [4, 2, 4, 2])
sum_op = sum_op.collapse_summands()
with self.subTest("SummedOp test 7-b"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [8, 4])
sum_op = SummedOp([X ^ X * 2, Y ^ Y], 2) + SummedOp([X ^ X * 2, Z ^ Z], 3)
with self.subTest("SummedOp test 8-a"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY", "XX", "ZZ"])
self.assertListEqual([op.coeff for op in sum_op], [4, 2, 6, 3])
sum_op = sum_op.collapse_summands()
with self.subTest("SummedOp test 8-b"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY", "ZZ"])
self.assertListEqual([op.coeff for op in sum_op], [10, 2, 3])
sum_op = SummedOp([])
with self.subTest("SummedOp test 9"):
self.assertEqual(sum_op.reduce(), sum_op)
sum_op = ((Z + I) ^ Z) + (Z ^ X)
with self.subTest("SummedOp test 10"):
expected = SummedOp([PauliOp(Pauli("ZZ")), PauliOp(Pauli("IZ")), PauliOp(Pauli("ZX"))])
self.assertEqual(sum_op.to_pauli_op(), expected)
def test_compose_op_of_different_dim(self):
"""
Test if smaller operator expands to correct dim when composed with bigger operator.
Test if PrimitiveOps compose methods are consistent.
"""
# PauliOps of different dim
xy_p = X ^ Y
xyz_p = X ^ Y ^ Z
pauli_op = xy_p @ xyz_p
expected_result = I ^ I ^ Z
self.assertEqual(pauli_op, expected_result)
# MatrixOps of different dim
xy_m = xy_p.to_matrix_op()
xyz_m = xyz_p.to_matrix_op()
matrix_op = xy_m @ xyz_m
self.assertEqual(matrix_op, expected_result.to_matrix_op())
# CircuitOps of different dim
xy_c = xy_p.to_circuit_op()
xyz_c = xyz_p.to_circuit_op()
circuit_op = xy_c @ xyz_c
self.assertTrue(np.array_equal(pauli_op.to_matrix(), matrix_op.to_matrix()))
self.assertTrue(np.allclose(pauli_op.to_matrix(), circuit_op.to_matrix(), rtol=1e-14))
self.assertTrue(np.allclose(matrix_op.to_matrix(), circuit_op.to_matrix(), rtol=1e-14))
def test_permute_on_primitive_op(self):
"""Test if permute methods of PrimitiveOps are consistent and work as expected."""
indices = [1, 2, 4]
# PauliOp
pauli_op = X ^ Y ^ Z
permuted_pauli_op = pauli_op.permute(indices)
expected_pauli_op = X ^ I ^ Y ^ Z ^ I
self.assertEqual(permuted_pauli_op, expected_pauli_op)
# CircuitOp
circuit_op = pauli_op.to_circuit_op()
permuted_circuit_op = circuit_op.permute(indices)
expected_circuit_op = expected_pauli_op.to_circuit_op()
self.assertEqual(
Operator(permuted_circuit_op.primitive), Operator(expected_circuit_op.primitive)
)
# MatrixOp
matrix_op = pauli_op.to_matrix_op()
permuted_matrix_op = matrix_op.permute(indices)
expected_matrix_op = expected_pauli_op.to_matrix_op()
equal = np.allclose(permuted_matrix_op.to_matrix(), expected_matrix_op.to_matrix())
self.assertTrue(equal)
def test_permute_on_list_op(self):
"""Test if ListOp permute method is consistent with PrimitiveOps permute methods."""
op1 = (X ^ Y ^ Z).to_circuit_op()
op2 = Z ^ X ^ Y
# ComposedOp
indices = [1, 2, 0]
primitive_op = op1 @ op2
primitive_op_perm = primitive_op.permute(indices) # CircuitOp.permute
composed_op = ComposedOp([op1, op2])
composed_op_perm = composed_op.permute(indices)
# reduce the ListOp to PrimitiveOp
to_primitive = composed_op_perm.oplist[0] @ composed_op_perm.oplist[1]
# compare resulting PrimitiveOps
equal = np.allclose(primitive_op_perm.to_matrix(), to_primitive.to_matrix())
self.assertTrue(equal)
# TensoredOp
indices = [3, 5, 4, 0, 2, 1]
primitive_op = op1 ^ op2
primitive_op_perm = primitive_op.permute(indices)
tensored_op = TensoredOp([op1, op2])
tensored_op_perm = tensored_op.permute(indices)
# reduce the ListOp to PrimitiveOp
composed_oplist = tensored_op_perm.oplist
to_primitive = (
composed_oplist[0]
@ (composed_oplist[1].oplist[0] ^ composed_oplist[1].oplist[1])
@ composed_oplist[2]
)
# compare resulting PrimitiveOps
equal = np.allclose(primitive_op_perm.to_matrix(), to_primitive.to_matrix())
self.assertTrue(equal)
# SummedOp
primitive_op = X ^ Y ^ Z
summed_op = SummedOp([primitive_op])
indices = [1, 2, 0]
primitive_op_perm = primitive_op.permute(indices) # PauliOp.permute
summed_op_perm = summed_op.permute(indices)
# reduce the ListOp to PrimitiveOp
to_primitive = summed_op_perm.oplist[0] @ primitive_op @ summed_op_perm.oplist[2]
# compare resulting PrimitiveOps
equal = np.allclose(primitive_op_perm.to_matrix(), to_primitive.to_matrix())
self.assertTrue(equal)
def test_expand_on_list_op(self):
"""Test if expanded ListOp has expected num_qubits."""
add_qubits = 3
# ComposedOp
composed_op = ComposedOp([(X ^ Y ^ Z), (H ^ T), (Z ^ X ^ Y ^ Z).to_matrix_op()])
expanded = composed_op._expand_dim(add_qubits)
self.assertEqual(composed_op.num_qubits + add_qubits, expanded.num_qubits)
# TensoredOp
tensored_op = TensoredOp([(X ^ Y), (Z ^ I)])
expanded = tensored_op._expand_dim(add_qubits)
self.assertEqual(tensored_op.num_qubits + add_qubits, expanded.num_qubits)
# SummedOp
summed_op = SummedOp([(X ^ Y), (Z ^ I ^ Z)])
expanded = summed_op._expand_dim(add_qubits)
self.assertEqual(summed_op.num_qubits + add_qubits, expanded.num_qubits)
def test_expand_on_state_fn(self):
"""Test if expanded StateFn has expected num_qubits."""
num_qubits = 3
add_qubits = 2
# case CircuitStateFn, with primitive QuantumCircuit
qc2 = QuantumCircuit(num_qubits)
qc2.cx(0, 1)
cfn = CircuitStateFn(qc2, is_measurement=True)
cfn_exp = cfn._expand_dim(add_qubits)
self.assertEqual(cfn_exp.num_qubits, add_qubits + num_qubits)
# case OperatorStateFn, with OperatorBase primitive, in our case CircuitStateFn
osfn = OperatorStateFn(cfn)
osfn_exp = osfn._expand_dim(add_qubits)
self.assertEqual(osfn_exp.num_qubits, add_qubits + num_qubits)
# case DictStateFn
dsfn = DictStateFn("1" * num_qubits, is_measurement=True)
self.assertEqual(dsfn.num_qubits, num_qubits)
dsfn_exp = dsfn._expand_dim(add_qubits)
self.assertEqual(dsfn_exp.num_qubits, num_qubits + add_qubits)
# case VectorStateFn
vsfn = VectorStateFn(np.ones(2**num_qubits, dtype=complex))
self.assertEqual(vsfn.num_qubits, num_qubits)
vsfn_exp = vsfn._expand_dim(add_qubits)
self.assertEqual(vsfn_exp.num_qubits, num_qubits + add_qubits)
def test_permute_on_state_fn(self):
"""Test if StateFns permute are consistent."""
num_qubits = 4
dim = 2**num_qubits
primitive_list = [1.0 / (i + 1) for i in range(dim)]
primitive_dict = {format(i, "b").zfill(num_qubits): 1.0 / (i + 1) for i in range(dim)}
dict_fn = DictStateFn(primitive=primitive_dict, is_measurement=True)
vec_fn = VectorStateFn(primitive=primitive_list, is_measurement=True)
# check if dict_fn and vec_fn are equivalent
equivalent = np.allclose(dict_fn.to_matrix(), vec_fn.to_matrix())
self.assertTrue(equivalent)
# permute
indices = [2, 3, 0, 1]
permute_dict = dict_fn.permute(indices)
permute_vect = vec_fn.permute(indices)
equivalent = np.allclose(permute_dict.to_matrix(), permute_vect.to_matrix())
self.assertTrue(equivalent)
def test_compose_consistency(self):
"""Test if PrimitiveOp @ ComposedOp is consistent with ComposedOp @ PrimitiveOp."""
# PauliOp
op1 = X ^ Y ^ Z
op2 = X ^ Y ^ Z
op3 = (X ^ Y ^ Z).to_circuit_op()
comp1 = op1 @ ComposedOp([op2, op3])
comp2 = ComposedOp([op3, op2]) @ op1
self.assertListEqual(comp1.oplist, list(reversed(comp2.oplist)))
# CircitOp
op1 = op1.to_circuit_op()
op2 = op2.to_circuit_op()
op3 = op3.to_matrix_op()
comp1 = op1 @ ComposedOp([op2, op3])
comp2 = ComposedOp([op3, op2]) @ op1
self.assertListEqual(comp1.oplist, list(reversed(comp2.oplist)))
# MatrixOp
op1 = op1.to_matrix_op()
op2 = op2.to_matrix_op()
op3 = op3.to_pauli_op()
comp1 = op1 @ ComposedOp([op2, op3])
comp2 = ComposedOp([op3, op2]) @ op1
self.assertListEqual(comp1.oplist, list(reversed(comp2.oplist)))
def test_compose_with_indices(self):
"""Test compose method using its permutation feature."""
pauli_op = X ^ Y ^ Z
circuit_op = T ^ H
matrix_op = (X ^ Y ^ H ^ T).to_matrix_op()
evolved_op = EvolvedOp(matrix_op)
# composition of PrimitiveOps
num_qubits = 4
primitive_op = pauli_op @ circuit_op @ matrix_op
composed_op = pauli_op @ circuit_op @ evolved_op
self.assertEqual(primitive_op.num_qubits, num_qubits)
self.assertEqual(composed_op.num_qubits, num_qubits)
# with permutation
num_qubits = 5
indices = [1, 4]
permuted_primitive_op = evolved_op @ circuit_op.permute(indices) @ pauli_op @ matrix_op
composed_primitive_op = (
evolved_op @ pauli_op.compose(circuit_op, permutation=indices, front=True) @ matrix_op
)
self.assertTrue(
np.allclose(permuted_primitive_op.to_matrix(), composed_primitive_op.to_matrix())
)
self.assertEqual(num_qubits, permuted_primitive_op.num_qubits)
# ListOp
num_qubits = 6
tensored_op = TensoredOp([pauli_op, circuit_op])
summed_op = pauli_op + circuit_op.permute([2, 1])
composed_op = circuit_op @ evolved_op @ matrix_op
list_op = summed_op @ composed_op.compose(
tensored_op, permutation=[1, 2, 3, 5, 4], front=True
)
self.assertEqual(num_qubits, list_op.num_qubits)
num_qubits = 4
circuit_fn = CircuitStateFn(primitive=circuit_op.primitive, is_measurement=True)
operator_fn = OperatorStateFn(primitive=circuit_op ^ circuit_op, is_measurement=True)
no_perm_op = circuit_fn @ operator_fn
self.assertEqual(no_perm_op.num_qubits, num_qubits)
indices = [0, 4]
perm_op = operator_fn.compose(circuit_fn, permutation=indices, front=True)
self.assertEqual(perm_op.num_qubits, max(indices) + 1)
# StateFn
num_qubits = 3
dim = 2**num_qubits
vec = [1.0 / (i + 1) for i in range(dim)]
dic = {format(i, "b").zfill(num_qubits): 1.0 / (i + 1) for i in range(dim)}
is_measurement = True
op_state_fn = OperatorStateFn(matrix_op, is_measurement=is_measurement) # num_qubit = 4
vec_state_fn = VectorStateFn(vec, is_measurement=is_measurement) # 3
dic_state_fn = DictStateFn(dic, is_measurement=is_measurement) # 3
circ_state_fn = CircuitStateFn(circuit_op.to_circuit(), is_measurement=is_measurement) # 2
composed_op = op_state_fn @ vec_state_fn @ dic_state_fn @ circ_state_fn
self.assertEqual(composed_op.num_qubits, op_state_fn.num_qubits)
# with permutation
perm = [2, 4, 6]
composed = (
op_state_fn
@ dic_state_fn.compose(vec_state_fn, permutation=perm, front=True)
@ circ_state_fn
)
self.assertEqual(composed.num_qubits, max(perm) + 1)
def test_summed_op_equals(self):
"""Test corner cases of SummedOp's equals function."""
with self.subTest("multiplicative factor"):
self.assertEqual(2 * X, X + X)
with self.subTest("commutative"):
self.assertEqual(X + Z, Z + X)
with self.subTest("circuit and paulis"):
z = CircuitOp(ZGate())
self.assertEqual(Z + z, z + Z)
with self.subTest("matrix op and paulis"):
z = MatrixOp([[1, 0], [0, -1]])
self.assertEqual(Z + z, z + Z)
with self.subTest("matrix multiplicative"):
z = MatrixOp([[1, 0], [0, -1]])
self.assertEqual(2 * z, z + z)
with self.subTest("parameter coefficients"):
expr = Parameter("theta")
z = MatrixOp([[1, 0], [0, -1]])
self.assertEqual(expr * z, expr * z)
with self.subTest("different coefficient types"):
expr = Parameter("theta")
z = MatrixOp([[1, 0], [0, -1]])
self.assertNotEqual(expr * z, 2 * z)
with self.subTest("additions aggregation"):
z = MatrixOp([[1, 0], [0, -1]])
a = z + z + Z
b = 2 * z + Z
c = z + Z + z
self.assertEqual(a, b)
self.assertEqual(b, c)
self.assertEqual(a, c)
def test_circuit_compose_register_independent(self):
"""Test that CircuitOp uses combines circuits independent of the register.
I.e. that is uses ``QuantumCircuit.compose`` over ``combine`` or ``extend``.
"""
op = Z ^ 2
qr = QuantumRegister(2, "my_qr")
circuit = QuantumCircuit(qr)
composed = op.compose(CircuitOp(circuit))
self.assertEqual(composed.num_qubits, 2)
def test_matrix_op_conversions(self):
"""Test to reveal QiskitError when to_instruction or to_circuit method is called on
parameterized matrix op."""
m = np.array([[0, 0, 1, 0], [0, 0, 0, -1], [1, 0, 0, 0], [0, -1, 0, 0]])
matrix_op = MatrixOp(m, Parameter("beta"))
for method in ["to_instruction", "to_circuit"]:
with self.subTest(method):
# QiskitError: multiplication of Operator with ParameterExpression isn't implemented
self.assertRaises(QiskitError, getattr(matrix_op, method))
def test_list_op_to_circuit(self):
"""Test if unitary ListOps transpile to circuit."""
# generate unitary matrices of dimension 2,4,8, seed is fixed
np.random.seed(233423)
u2 = unitary_group.rvs(2)
u4 = unitary_group.rvs(4)
u8 = unitary_group.rvs(8)
# pauli matrices as numpy.arrays
x = np.array([[0.0, 1.0], [1.0, 0.0]])
y = np.array([[0.0, -1.0j], [1.0j, 0.0]])
z = np.array([[1.0, 0.0], [0.0, -1.0]])
# create MatrixOp and CircuitOp out of matrices
op2 = MatrixOp(u2)
op4 = MatrixOp(u4)
op8 = MatrixOp(u8)
c2 = op2.to_circuit_op()
# algorithm using only matrix operations on numpy.arrays
xu4 = np.kron(x, u4)
zc2 = np.kron(z, u2)
zc2y = np.kron(zc2, y)
matrix = np.matmul(xu4, zc2y)
matrix = np.matmul(matrix, u8)
matrix = np.kron(matrix, u2)
operator = Operator(matrix)
# same algorithm as above, but using PrimitiveOps
list_op = ((X ^ op4) @ (Z ^ c2 ^ Y) @ op8) ^ op2
circuit = list_op.to_circuit()
# verify that ListOp.to_circuit() outputs correct quantum circuit
self.assertTrue(operator.equiv(circuit), "ListOp.to_circuit() outputs wrong circuit!")
def test_composed_op_to_circuit(self):
"""
Test if unitary ComposedOp transpile to circuit and represents expected operator.
Test if to_circuit on non-unitary ListOp raises exception.
"""
x = np.array([[0.0, 1.0], [1.0, 0.0]]) # Pauli X as numpy array
y = np.array([[0.0, -1.0j], [1.0j, 0.0]]) # Pauli Y as numpy array
m1 = np.array([[0, 0, 1, 0], [0, 0, 0, -1], [0, 0, 0, 0], [0, 0, 0, 0]]) # non-unitary
m2 = np.array([[0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 0], [0, -1, 0, 0]]) # non-unitary
m_op1 = MatrixOp(m1)
m_op2 = MatrixOp(m2)
pm1 = (X ^ Y) ^ m_op1 # non-unitary TensoredOp
pm2 = (X ^ Y) ^ m_op2 # non-unitary TensoredOp
self.assertRaises(ExtensionError, pm1.to_circuit)
self.assertRaises(ExtensionError, pm2.to_circuit)
summed_op = pm1 + pm2 # unitary SummedOp([TensoredOp, TensoredOp])
circuit = summed_op.to_circuit() # should transpile without any exception
# same algorithm that leads to summed_op above, but using only arrays and matrix operations
unitary = np.kron(np.kron(x, y), m1 + m2)
self.assertTrue(Operator(unitary).equiv(circuit))
def test_pauli_op_to_circuit(self):
"""Test PauliOp.to_circuit()"""
with self.subTest("single Pauli"):
pauli = PauliOp(Pauli("Y"))
expected = QuantumCircuit(1)
expected.y(0)
self.assertEqual(pauli.to_circuit(), expected)
with self.subTest("single Pauli with phase"):
pauli = PauliOp(Pauli("-iX"))
expected = QuantumCircuit(1)
expected.x(0)
expected.global_phase = -pi / 2
self.assertEqual(Operator(pauli.to_circuit()), Operator(expected))
with self.subTest("two qubit"):
pauli = PauliOp(Pauli("IX"))
expected = QuantumCircuit(2)
expected.pauli("IX", range(2))
self.assertEqual(pauli.to_circuit(), expected)
expected = QuantumCircuit(2)
expected.x(0)
self.assertEqual(pauli.to_circuit().decompose(), expected)
with self.subTest("Pauli identity"):
pauli = PauliOp(Pauli("I"))
expected = QuantumCircuit(1)
self.assertEqual(pauli.to_circuit(), expected)
with self.subTest("two qubit with phase"):
pauli = PauliOp(Pauli("iXZ"))
expected = QuantumCircuit(2)
expected.pauli("XZ", range(2))
expected.global_phase = pi / 2
self.assertEqual(pauli.to_circuit(), expected)
expected = QuantumCircuit(2)
expected.z(0)
expected.x(1)
expected.global_phase = pi / 2
self.assertEqual(pauli.to_circuit().decompose(), expected)
def test_op_to_circuit_with_parameters(self):
"""On parameterized SummedOp, to_matrix_op returns ListOp, instead of MatrixOp. To avoid
the infinite recursion, OpflowError is raised."""
m1 = np.array([[0, 0, 1, 0], [0, 0, 0, -1], [0, 0, 0, 0], [0, 0, 0, 0]]) # non-unitary
m2 = np.array([[0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 0], [0, -1, 0, 0]]) # non-unitary
op1_with_param = MatrixOp(m1, Parameter("alpha")) # non-unitary
op2_with_param = MatrixOp(m2, Parameter("beta")) # non-unitary
summed_op_with_param = op1_with_param + op2_with_param # unitary
# should raise OpflowError error
self.assertRaises(OpflowError, summed_op_with_param.to_circuit)
def test_permute_list_op_with_inconsistent_num_qubits(self):
"""Test if permute raises error if ListOp contains operators with different num_qubits."""
list_op = ListOp([X, X ^ X])
self.assertRaises(OpflowError, list_op.permute, [0, 1])
@data(Z, CircuitOp(ZGate()), MatrixOp([[1, 0], [0, -1]]))
def test_op_indent(self, op):
"""Test that indentation correctly adds INDENTATION at the beginning of each line"""
initial_str = str(op)
indented_str = op._indent(initial_str)
starts_with_indent = indented_str.startswith(op.INDENTATION)
self.assertTrue(starts_with_indent)
indented_str_content = (indented_str[len(op.INDENTATION) :]).split(f"\n{op.INDENTATION}")
self.assertListEqual(indented_str_content, initial_str.split("\n"))
def test_composed_op_immutable_under_eval(self):
"""Test ``ComposedOp.eval`` does not change the operator instance."""
op = 2 * ComposedOp([X])
_ = op.eval()
# previous bug: after op.eval(), op was 2 * ComposedOp([2 * X])
self.assertEqual(op, 2 * ComposedOp([X]))
def test_op_parameters(self):
"""Test that Parameters are stored correctly"""
phi = Parameter("Ο")
theta = ParameterVector(name="ΞΈ", length=2)
qc = QuantumCircuit(2)
qc.rz(phi, 0)
qc.rz(phi, 1)
for i in range(2):
qc.rx(theta[i], i)
qc.h(0)
qc.x(1)
l = Parameter("Ξ»")
op = PrimitiveOp(qc, coeff=l)
params = {phi, l, *theta.params}
self.assertEqual(params, op.parameters)
self.assertEqual(params, StateFn(op).parameters)
self.assertEqual(params, StateFn(qc, coeff=l).parameters)
def test_list_op_parameters(self):
"""Test that Parameters are stored correctly in a List Operator"""
lam = Parameter("Ξ»")
phi = Parameter("Ο")
omega = Parameter("Ο")
mat_op = PrimitiveOp([[0, 1], [1, 0]], coeff=omega)
qc = QuantumCircuit(1)
qc.rx(phi, 0)
qc_op = PrimitiveOp(qc)
op1 = SummedOp([mat_op, qc_op])
params = [phi, omega]
self.assertEqual(op1.parameters, set(params))
# check list nesting case
op2 = PrimitiveOp([[1, 0], [0, -1]], coeff=lam)
list_op = ListOp([op1, op2])
params.append(lam)
self.assertEqual(list_op.parameters, set(params))
@data(
VectorStateFn([1, 0]),
CircuitStateFn(QuantumCircuit(1)),
OperatorStateFn(I),
OperatorStateFn(MatrixOp([[1, 0], [0, 1]])),
OperatorStateFn(CircuitOp(QuantumCircuit(1))),
)
def test_statefn_eval(self, op):
"""Test calling eval on StateFn returns the statevector."""
expected = Statevector([1, 0])
self.assertEqual(op.eval().primitive, expected)
def test_sparse_eval(self):
"""Test calling eval on a DictStateFn returns a sparse statevector."""
op = DictStateFn({"0": 1})
expected = scipy.sparse.csr_matrix([[1, 0]])
self.assertFalse((op.eval().primitive != expected).toarray().any())
def test_sparse_to_dict(self):
"""Test converting a sparse vector state function to a dict state function."""
isqrt2 = 1 / np.sqrt(2)
sparse = scipy.sparse.csr_matrix([[0, isqrt2, 0, isqrt2]])
sparse_fn = SparseVectorStateFn(sparse)
dict_fn = DictStateFn({"01": isqrt2, "11": isqrt2})
with self.subTest("sparse to dict"):
self.assertEqual(dict_fn, sparse_fn.to_dict_fn())
with self.subTest("dict to sparse"):
self.assertEqual(dict_fn.to_spmatrix_op(), sparse_fn)
def test_to_circuit_op(self):
"""Test to_circuit_op method."""
vector = np.array([2, 2])
vsfn = VectorStateFn([1, 1], coeff=2)
dsfn = DictStateFn({"0": 1, "1": 1}, coeff=2)
for sfn in [vsfn, dsfn]:
np.testing.assert_array_almost_equal(sfn.to_circuit_op().eval().primitive.data, vector)
def test_invalid_primitive(self):
"""Test invalid MatrixOp construction"""
msg = (
"MatrixOp can only be instantiated with "
"['list', 'ndarray', 'spmatrix', 'Operator'], not "
)
with self.assertRaises(TypeError) as cm:
_ = MatrixOp("invalid")
self.assertEqual(str(cm.exception), msg + "'str'")
with self.assertRaises(TypeError) as cm:
_ = MatrixOp(None)
self.assertEqual(str(cm.exception), msg + "'NoneType'")
with self.assertRaises(TypeError) as cm:
_ = MatrixOp(2.0)
self.assertEqual(str(cm.exception), msg + "'float'")
def test_summedop_equals(self):
"""Test SummedOp.equals"""
ops = [Z, CircuitOp(ZGate()), MatrixOp([[1, 0], [0, -1]]), Zero, Minus]
sum_op = sum(ops + [ListOp(ops)])
self.assertEqual(sum_op, sum_op)
self.assertEqual(sum_op + sum_op, 2 * sum_op)
self.assertEqual(sum_op + sum_op + sum_op, 3 * sum_op)
ops2 = [Z, CircuitOp(ZGate()), MatrixOp([[1, 0], [0, 1]]), Zero, Minus]
sum_op2 = sum(ops2 + [ListOp(ops)])
self.assertNotEqual(sum_op, sum_op2)
self.assertEqual(sum_op2, sum_op2)
sum_op3 = sum(ops)
self.assertNotEqual(sum_op, sum_op3)
self.assertNotEqual(sum_op2, sum_op3)
self.assertEqual(sum_op3, sum_op3)
def test_empty_listops(self):
"""Test reduce and eval on ListOp with empty oplist."""
with self.subTest("reduce empty ComposedOp "):
self.assertEqual(ComposedOp([]).reduce(), ComposedOp([]))
with self.subTest("reduce empty TensoredOp "):
self.assertEqual(TensoredOp([]).reduce(), TensoredOp([]))
with self.subTest("eval empty ComposedOp "):
self.assertEqual(ComposedOp([]).eval(), 0.0)
with self.subTest("eval empty TensoredOp "):
self.assertEqual(TensoredOp([]).eval(), 0.0)
def test_composed_op_to_matrix_with_coeff(self):
"""Test coefficients are properly handled.
Regression test of Qiskit/qiskit-terra#9283.
"""
x = MatrixOp(X.to_matrix())
composed = 0.5 * (x @ X)
expected = 0.5 * np.eye(2)
np.testing.assert_almost_equal(composed.to_matrix(), expected)
def test_composed_op_to_matrix_with_vector(self):
"""Test a matrix-vector composed op can be cast to matrix.
Regression test of Qiskit/qiskit-terra#9283.
"""
x = MatrixOp(X.to_matrix())
composed = x @ Zero
expected = np.array([0, 1])
np.testing.assert_almost_equal(composed.to_matrix(), expected)
def test_tensored_op_to_matrix(self):
"""Test tensored operators to matrix works correctly with a global coefficient.
Regression test of Qiskit/qiskit-terra#9398.
"""
op = TensoredOp([X, I], coeff=0.5)
expected = 1 / 2 * np.kron(X.to_matrix(), I.to_matrix())
np.testing.assert_almost_equal(op.to_matrix(), expected)
class TestOpMethods(QiskitOpflowTestCase):
"""Basic method tests."""
def test_listop_num_qubits(self):
"""Test that ListOp.num_qubits checks that all operators have the same number of qubits."""
op = ListOp([X ^ Y, Y ^ Z])
with self.subTest("All operators have the same numbers of qubits"):
self.assertEqual(op.num_qubits, 2)
op = ListOp([X ^ Y, Y])
with self.subTest("Operators have different numbers of qubits"):
with self.assertRaises(ValueError):
op.num_qubits # pylint: disable=pointless-statement
with self.assertRaises(ValueError):
X @ op # pylint: disable=pointless-statement
def test_is_hermitian(self):
"""Test is_hermitian method."""
with self.subTest("I"):
self.assertTrue(I.is_hermitian())
with self.subTest("X"):
self.assertTrue(X.is_hermitian())
with self.subTest("Y"):
self.assertTrue(Y.is_hermitian())
with self.subTest("Z"):
self.assertTrue(Z.is_hermitian())
with self.subTest("XY"):
self.assertFalse((X @ Y).is_hermitian())
with self.subTest("CX"):
self.assertTrue(CX.is_hermitian())
with self.subTest("T"):
self.assertFalse(T.is_hermitian())
@ddt
class TestListOpMethods(QiskitOpflowTestCase):
"""Test ListOp accessing methods"""
@data(ListOp, SummedOp, ComposedOp, TensoredOp)
def test_indexing(self, list_op_type):
"""Test indexing and slicing"""
coeff = 3 + 0.2j
states_op = list_op_type([X, Y, Z, I], coeff=coeff)
single_op = states_op[1]
self.assertIsInstance(single_op, OperatorBase)
self.assertNotIsInstance(single_op, ListOp)
list_one_element = states_op[1:2]
self.assertIsInstance(list_one_element, list_op_type)
self.assertEqual(len(list_one_element), 1)
self.assertEqual(list_one_element[0], Y)
list_two_elements = states_op[::2]
self.assertIsInstance(list_two_elements, list_op_type)
self.assertEqual(len(list_two_elements), 2)
self.assertEqual(list_two_elements[0], X)
self.assertEqual(list_two_elements[1], Z)
self.assertEqual(list_one_element.coeff, coeff)
self.assertEqual(list_two_elements.coeff, coeff)
class TestListOpComboFn(QiskitOpflowTestCase):
"""Test combo fn is propagated."""
def setUp(self):
super().setUp()
self.combo_fn = lambda x: [x_i**2 for x_i in x]
self.listop = ListOp([X], combo_fn=self.combo_fn)
def assertComboFnPreserved(self, processed_op):
"""Assert the quadratic combo_fn is preserved."""
x = [1, 2, 3]
self.assertListEqual(processed_op.combo_fn(x), self.combo_fn(x))
def test_at_conversion(self):
"""Test after conversion the combo_fn is preserved."""
for method in ["to_matrix_op", "to_pauli_op", "to_circuit_op"]:
with self.subTest(method):
converted = getattr(self.listop, method)()
self.assertComboFnPreserved(converted)
def test_after_mul(self):
"""Test after multiplication the combo_fn is preserved."""
self.assertComboFnPreserved(2 * self.listop)
def test_at_traverse(self):
"""Test after traversing the combo_fn is preserved."""
def traverse_fn(op):
return -op
traversed = self.listop.traverse(traverse_fn)
self.assertComboFnPreserved(traversed)
def test_after_adjoint(self):
"""Test after traversing the combo_fn is preserved."""
self.assertComboFnPreserved(self.listop.adjoint())
def test_after_reduce(self):
"""Test after reducing the combo_fn is preserved."""
self.assertComboFnPreserved(self.listop.reduce())
def pauli_group_labels(nq, full_group=True):
"""Generate list of the N-qubit pauli group string labels"""
labels = ["".join(i) for i in itertools.product(("I", "X", "Y", "Z"), repeat=nq)]
if full_group:
labels = ["".join(i) for i in itertools.product(("", "-i", "-", "i"), labels)]
return labels
def operator_from_label(label):
"""Construct operator from full Pauli group label"""
return Operator(Pauli(label))
@ddt
class TestPauliOp(QiskitOpflowTestCase):
"""PauliOp tests."""
def test_construct(self):
"""constructor test"""
pauli = Pauli("XYZX")
coeff = 3.0
pauli_op = PauliOp(pauli, coeff)
self.assertIsInstance(pauli_op, PauliOp)
self.assertEqual(pauli_op.primitive, pauli)
self.assertEqual(pauli_op.coeff, coeff)
self.assertEqual(pauli_op.num_qubits, 4)
def test_add(self):
"""add test"""
pauli_sum = X + Y
summed_op = SummedOp([X, Y])
self.assertEqual(pauli_sum, summed_op)
a = Parameter("a")
b = Parameter("b")
actual = PauliOp(Pauli("X"), a) + PauliOp(Pauli("Y"), b)
expected = SummedOp([PauliOp(Pauli("X"), a), PauliOp(Pauli("Y"), b)])
self.assertEqual(actual, expected)
def test_adjoint(self):
"""adjoint test"""
pauli_op = PauliOp(Pauli("XYZX"), coeff=3)
expected = PauliOp(Pauli("XYZX"), coeff=3)
self.assertEqual(~pauli_op, expected)
pauli_op = PauliOp(Pauli("XXY"), coeff=2j)
expected = PauliOp(Pauli("XXY"), coeff=-2j)
self.assertEqual(~pauli_op, expected)
pauli_op = PauliOp(Pauli("XYZX"), coeff=2 + 3j)
expected = PauliOp(Pauli("XYZX"), coeff=2 - 3j)
self.assertEqual(~pauli_op, expected)
pauli_op = PauliOp(Pauli("iXYZX"), coeff=2 + 3j)
expected = PauliOp(Pauli("-iXYZX"), coeff=2 - 3j)
self.assertEqual(~pauli_op, expected)
@data(*itertools.product(pauli_group_labels(2, full_group=True), repeat=2))
@unpack
def test_compose(self, label1, label2):
"""compose test"""
p1 = PauliOp(Pauli(label1))
p2 = PauliOp(Pauli(label2))
value = Operator(p1 @ p2)
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1 @ op2
self.assertEqual(value, target)
def test_equals(self):
"""equality test"""
self.assertEqual(I @ X, X)
self.assertEqual(X, I @ X)
theta = Parameter("theta")
pauli_op = theta * X ^ Z
expected = PauliOp(
Pauli("XZ"),
coeff=1.0 * theta,
)
self.assertEqual(pauli_op, expected)
def test_eval(self):
"""eval test"""
target0 = (X ^ Y ^ Z).eval("000")
target1 = (X ^ Y ^ Z).eval(Zero ^ 3)
expected = DictStateFn({"110": 1j})
self.assertEqual(target0, expected)
self.assertEqual(target1, expected)
def test_exp_i(self):
"""exp_i test"""
target = (2 * X ^ Z).exp_i()
expected = EvolvedOp(PauliOp(Pauli("XZ"), coeff=2.0), coeff=1.0)
self.assertEqual(target, expected)
@data(([1, 2, 4], "XIYZI"), ([2, 1, 0], "ZYX"))
@unpack
def test_permute(self, permutation, expected_pauli):
"""Test the permute method."""
pauli_op = PauliOp(Pauli("XYZ"), coeff=1.0)
expected = PauliOp(Pauli(expected_pauli), coeff=1.0)
permuted = pauli_op.permute(permutation)
with self.subTest(msg="test permutated object"):
self.assertEqual(permuted, expected)
with self.subTest(msg="test original object is unchanged"):
original = PauliOp(Pauli("XYZ"))
self.assertEqual(pauli_op, original)
def test_primitive_strings(self):
"""primitive strings test"""
target = (2 * X ^ Z).primitive_strings()
expected = {"Pauli"}
self.assertEqual(target, expected)
def test_tensor(self):
"""tensor test"""
pauli_op = X ^ Y ^ Z
tensored_op = PauliOp(Pauli("XYZ"))
self.assertEqual(pauli_op, tensored_op)
def test_to_instruction(self):
"""to_instruction test"""
target = (X ^ Z).to_instruction()
qc = QuantumCircuit(2)
qc.u(0, 0, np.pi, 0)
qc.u(np.pi, 0, np.pi, 1)
qc_out = QuantumCircuit(2)
qc_out.append(target, qc_out.qubits)
qc_out = transpile(qc_out, basis_gates=["u"])
self.assertEqual(qc, qc_out)
def test_to_matrix(self):
"""to_matrix test"""
target = (X ^ Y).to_matrix()
expected = np.kron(np.array([[0.0, 1.0], [1.0, 0.0]]), np.array([[0.0, -1j], [1j, 0.0]]))
np.testing.assert_array_equal(target, expected)
def test_to_spmatrix(self):
"""to_spmatrix test"""
target = X ^ Y
expected = csr_matrix(
np.kron(np.array([[0.0, 1.0], [1.0, 0.0]]), np.array([[0.0, -1j], [1j, 0.0]]))
)
self.assertEqual((target.to_spmatrix() - expected).nnz, 0)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test Pauli Change of Basis Converter"""
import itertools
import unittest
from functools import reduce
from test.python.opflow import QiskitOpflowTestCase
import numpy as np
from qiskit import QuantumCircuit
from qiskit.opflow import (
ComposedOp,
I,
OperatorStateFn,
PauliSumOp,
SummedOp,
X,
Y,
Z,
)
from qiskit.opflow.converters import PauliBasisChange
from qiskit.quantum_info import Pauli, SparsePauliOp
class TestPauliCoB(QiskitOpflowTestCase):
"""Pauli Change of Basis Converter tests."""
def test_pauli_cob_singles(self):
"""from to file test"""
singles = [X, Y, Z]
dests = [None, Y]
for pauli, dest in itertools.product(singles, dests):
# print(pauli)
converter = PauliBasisChange(destination_basis=dest)
inst, dest = converter.get_cob_circuit(pauli.primitive)
cob = converter.convert(pauli)
np.testing.assert_array_almost_equal(
pauli.to_matrix(), inst.adjoint().to_matrix() @ dest.to_matrix() @ inst.to_matrix()
)
np.testing.assert_array_almost_equal(pauli.to_matrix(), cob.to_matrix())
np.testing.assert_array_almost_equal(
inst.compose(pauli).compose(inst.adjoint()).to_matrix(), dest.to_matrix()
)
def test_pauli_cob_two_qubit(self):
"""pauli cob two qubit test"""
multis = [Y ^ X, Z ^ Y, I ^ Z, Z ^ I, X ^ X, I ^ X]
for pauli, dest in itertools.product(multis, reversed(multis)):
converter = PauliBasisChange(destination_basis=dest)
inst, dest = converter.get_cob_circuit(pauli.primitive)
cob = converter.convert(pauli)
np.testing.assert_array_almost_equal(
pauli.to_matrix(), inst.adjoint().to_matrix() @ dest.to_matrix() @ inst.to_matrix()
)
np.testing.assert_array_almost_equal(pauli.to_matrix(), cob.to_matrix())
np.testing.assert_array_almost_equal(
inst.compose(pauli).compose(inst.adjoint()).to_matrix(), dest.to_matrix()
)
def test_pauli_cob_multiqubit(self):
"""pauli cob multi qubit test"""
# Helpful prints for debugging commented out below.
multis = [Y ^ X ^ I ^ I, I ^ Z ^ Y ^ X, X ^ Y ^ I ^ Z, I ^ I ^ I ^ X, X ^ X ^ X ^ X]
for pauli, dest in itertools.product(multis, reversed(multis)):
# print(pauli)
# print(dest)
converter = PauliBasisChange(destination_basis=dest)
inst, dest = converter.get_cob_circuit(pauli.primitive)
cob = converter.convert(pauli)
# print(inst)
# print(pauli.to_matrix())
# print(np.round(inst.adjoint().to_matrix() @ cob.to_matrix()))
np.testing.assert_array_almost_equal(
pauli.to_matrix(), inst.adjoint().to_matrix() @ dest.to_matrix() @ inst.to_matrix()
)
np.testing.assert_array_almost_equal(pauli.to_matrix(), cob.to_matrix())
np.testing.assert_array_almost_equal(
inst.compose(pauli).compose(inst.adjoint()).to_matrix(), dest.to_matrix()
)
def test_pauli_cob_traverse(self):
"""pauli cob traverse test"""
# Helpful prints for debugging commented out below.
multis = [(X ^ Y) + (I ^ Z) + (Z ^ Z), (Y ^ X ^ I ^ I) + (I ^ Z ^ Y ^ X)]
dests = [Y ^ Y, I ^ I ^ I ^ Z]
for paulis, dest in zip(multis, dests):
converter = PauliBasisChange(destination_basis=dest, traverse=True)
cob = converter.convert(paulis)
self.assertIsInstance(cob, SummedOp)
inst = [None] * len(paulis)
ret_dest = [None] * len(paulis)
cob_mat = [None] * len(paulis)
for i, pauli in enumerate(paulis):
inst[i], ret_dest[i] = converter.get_cob_circuit(pauli.to_pauli_op().primitive)
self.assertEqual(dest, ret_dest[i])
self.assertIsInstance(cob.oplist[i], ComposedOp)
cob_mat[i] = cob.oplist[i].to_matrix()
np.testing.assert_array_almost_equal(pauli.to_matrix(), cob_mat[i])
np.testing.assert_array_almost_equal(paulis.to_matrix(), sum(cob_mat))
def test_grouped_pauli(self):
"""grouped pauli test"""
pauli = 2 * (I ^ I) + (X ^ I) + 3 * (X ^ Y)
grouped_pauli = PauliSumOp(pauli.primitive, grouping_type="TPB")
converter = PauliBasisChange()
cob = converter.convert(grouped_pauli)
np.testing.assert_array_almost_equal(pauli.to_matrix(), cob.to_matrix())
origin_x = reduce(np.logical_or, pauli.primitive.paulis.x)
origin_z = reduce(np.logical_or, pauli.primitive.paulis.z)
origin_pauli = Pauli((origin_z, origin_x))
inst, dest = converter.get_cob_circuit(origin_pauli)
self.assertEqual(str(dest), "ZZ")
expected_inst = np.array(
[
[0.5, -0.5j, 0.5, -0.5j],
[0.5, 0.5j, 0.5, 0.5j],
[0.5, -0.5j, -0.5, 0.5j],
[0.5, 0.5j, -0.5, -0.5j],
]
)
np.testing.assert_array_almost_equal(inst.to_matrix(), expected_inst)
def test_grouped_pauli_statefn(self):
"""grouped pauli test with statefn"""
grouped_pauli = PauliSumOp(SparsePauliOp(["Y"]), grouping_type="TPB")
observable = OperatorStateFn(grouped_pauli, is_measurement=True)
converter = PauliBasisChange(replacement_fn=PauliBasisChange.measurement_replacement_fn)
cob = converter.convert(observable)
expected = PauliSumOp(SparsePauliOp(["Z"]), grouping_type="TPB")
self.assertEqual(cob[0].primitive, expected)
circuit = QuantumCircuit(1)
circuit.sdg(0)
circuit.h(0)
self.assertEqual(cob[1].primitive, circuit)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test PauliExpectation"""
import itertools
import unittest
from test.python.opflow import QiskitOpflowTestCase
import numpy as np
from qiskit import BasicAer
from qiskit.opflow import (
CX,
CircuitSampler,
H,
I,
ListOp,
Minus,
One,
PauliExpectation,
PauliSumOp,
Plus,
S,
StateFn,
X,
Y,
Z,
Zero,
)
from qiskit.utils import QuantumInstance, algorithm_globals
# pylint: disable=invalid-name
class TestPauliExpectation(QiskitOpflowTestCase):
"""Pauli Change of Basis Expectation tests."""
def setUp(self) -> None:
super().setUp()
self.seed = 97
backend = BasicAer.get_backend("qasm_simulator")
with self.assertWarns(DeprecationWarning):
q_instance = QuantumInstance(
backend, seed_simulator=self.seed, seed_transpiler=self.seed
)
self.sampler = CircuitSampler(q_instance, attach_results=True)
self.expect = PauliExpectation()
def test_pauli_expect_pair(self):
"""pauli expect pair test"""
op = Z ^ Z
# wf = (Pl^Pl) + (Ze^Ze)
wf = CX @ (H ^ I) @ Zero
converted_meas = self.expect.convert(~StateFn(op) @ wf)
self.assertAlmostEqual(converted_meas.eval(), 0, delta=0.1)
with self.assertWarns(DeprecationWarning):
sampled = self.sampler.convert(converted_meas)
self.assertAlmostEqual(sampled.eval(), 0, delta=0.1)
def test_pauli_expect_single(self):
"""pauli expect single test"""
paulis = [Z, X, Y, I]
states = [Zero, One, Plus, Minus, S @ Plus, S @ Minus]
for pauli, state in itertools.product(paulis, states):
converted_meas = self.expect.convert(~StateFn(pauli) @ state)
matmulmean = state.adjoint().to_matrix() @ pauli.to_matrix() @ state.to_matrix()
self.assertAlmostEqual(converted_meas.eval(), matmulmean, delta=0.1)
with self.assertWarns(DeprecationWarning):
sampled = self.sampler.convert(converted_meas)
self.assertAlmostEqual(sampled.eval(), matmulmean, delta=0.1)
def test_pauli_expect_op_vector(self):
"""pauli expect op vector test"""
paulis_op = ListOp([X, Y, Z, I])
converted_meas = self.expect.convert(~StateFn(paulis_op))
plus_mean = converted_meas @ Plus
np.testing.assert_array_almost_equal(plus_mean.eval(), [1, 0, 0, 1], decimal=1)
with self.assertWarns(DeprecationWarning):
sampled_plus = self.sampler.convert(plus_mean)
np.testing.assert_array_almost_equal(sampled_plus.eval(), [1, 0, 0, 1], decimal=1)
minus_mean = converted_meas @ Minus
np.testing.assert_array_almost_equal(minus_mean.eval(), [-1, 0, 0, 1], decimal=1)
sampled_minus = self.sampler.convert(minus_mean)
np.testing.assert_array_almost_equal(sampled_minus.eval(), [-1, 0, 0, 1], decimal=1)
zero_mean = converted_meas @ Zero
np.testing.assert_array_almost_equal(zero_mean.eval(), [0, 0, 1, 1], decimal=1)
sampled_zero = self.sampler.convert(zero_mean)
np.testing.assert_array_almost_equal(sampled_zero.eval(), [0, 0, 1, 1], decimal=1)
sum_zero = (Plus + Minus) * (0.5**0.5)
sum_zero_mean = converted_meas @ sum_zero
np.testing.assert_array_almost_equal(sum_zero_mean.eval(), [0, 0, 1, 1], decimal=1)
sampled_zero_mean = self.sampler.convert(sum_zero_mean)
# !!NOTE!!: Depolarizing channel (Sampling) means interference
# does not happen between circuits in sum, so expectation does
# not equal expectation for Zero!!
np.testing.assert_array_almost_equal(sampled_zero_mean.eval(), [0, 0, 0, 1], decimal=1)
for i, op in enumerate(paulis_op.oplist):
mat_op = op.to_matrix()
np.testing.assert_array_almost_equal(
zero_mean.eval()[i],
Zero.adjoint().to_matrix() @ mat_op @ Zero.to_matrix(),
decimal=1,
)
np.testing.assert_array_almost_equal(
plus_mean.eval()[i],
Plus.adjoint().to_matrix() @ mat_op @ Plus.to_matrix(),
decimal=1,
)
np.testing.assert_array_almost_equal(
minus_mean.eval()[i],
Minus.adjoint().to_matrix() @ mat_op @ Minus.to_matrix(),
decimal=1,
)
def test_pauli_expect_state_vector(self):
"""pauli expect state vector test"""
states_op = ListOp([One, Zero, Plus, Minus])
paulis_op = X
converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op)
np.testing.assert_array_almost_equal(converted_meas.eval(), [0, 0, 1, -1], decimal=1)
with self.assertWarns(DeprecationWarning):
sampled = self.sampler.convert(converted_meas)
np.testing.assert_array_almost_equal(sampled.eval(), [0, 0, 1, -1], decimal=1)
# Small test to see if execution results are accessible
for composed_op in sampled:
self.assertIn("counts", composed_op[1].execution_results)
def test_pauli_expect_op_vector_state_vector(self):
"""pauli expect op vector state vector test"""
paulis_op = ListOp([X, Y, Z, I])
states_op = ListOp([One, Zero, Plus, Minus])
valids = [[+0, 0, 1, -1], [+0, 0, 0, 0], [-1, 1, 0, -0], [+1, 1, 1, 1]]
converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op)
np.testing.assert_array_almost_equal(converted_meas.eval(), valids, decimal=1)
with self.assertWarns(DeprecationWarning):
sampled = self.sampler.convert(converted_meas)
np.testing.assert_array_almost_equal(sampled.eval(), valids, decimal=1)
def test_to_matrix_called(self):
"""test to matrix called in different situations"""
qs = 45
states_op = ListOp([Zero ^ qs, One ^ qs, (Zero ^ qs) + (One ^ qs)])
paulis_op = ListOp([Z ^ qs, (I ^ Z ^ I) ^ int(qs / 3)])
# 45 qubit calculation - throws exception if to_matrix is called
# massive is False
with self.assertRaises(ValueError):
states_op.to_matrix()
paulis_op.to_matrix()
# now set global variable or argument
try:
algorithm_globals.massive = True
with self.assertRaises(MemoryError):
states_op.to_matrix()
paulis_op.to_matrix()
algorithm_globals.massive = False
with self.assertRaises(MemoryError):
states_op.to_matrix(massive=True)
paulis_op.to_matrix(massive=True)
finally:
algorithm_globals.massive = False
def test_not_to_matrix_called(self):
"""45 qubit calculation - literally will not work if to_matrix is
somehow called (in addition to massive=False throwing an error)"""
qs = 45
states_op = ListOp([Zero ^ qs, One ^ qs, (Zero ^ qs) + (One ^ qs)])
paulis_op = ListOp([Z ^ qs, (I ^ Z ^ I) ^ int(qs / 3)])
converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op)
np.testing.assert_array_almost_equal(converted_meas.eval(), [[1, -1, 0], [1, -1, 0]])
def test_grouped_pauli_expectation(self):
"""grouped pauli expectation test"""
two_qubit_H2 = (
(-1.052373245772859 * I ^ I)
+ (0.39793742484318045 * I ^ Z)
+ (-0.39793742484318045 * Z ^ I)
+ (-0.01128010425623538 * Z ^ Z)
+ (0.18093119978423156 * X ^ X)
)
wf = CX @ (H ^ I) @ Zero
expect_op = PauliExpectation(group_paulis=False).convert(~StateFn(two_qubit_H2) @ wf)
self.sampler._extract_circuitstatefns(expect_op)
num_circuits_ungrouped = len(self.sampler._circuit_ops_cache)
self.assertEqual(num_circuits_ungrouped, 5)
expect_op_grouped = PauliExpectation(group_paulis=True).convert(~StateFn(two_qubit_H2) @ wf)
with self.assertWarns(DeprecationWarning):
q_instance = QuantumInstance(
BasicAer.get_backend("statevector_simulator"),
seed_simulator=self.seed,
seed_transpiler=self.seed,
)
sampler = CircuitSampler(q_instance)
sampler._extract_circuitstatefns(expect_op_grouped)
num_circuits_grouped = len(sampler._circuit_ops_cache)
self.assertEqual(num_circuits_grouped, 2)
@unittest.skip(reason="IBMQ testing not available in general.")
def test_ibmq_grouped_pauli_expectation(self):
"""pauli expect op vector state vector test"""
from qiskit import IBMQ
p = IBMQ.load_account()
backend = p.get_backend("ibmq_qasm_simulator")
with self.assertWarns(DeprecationWarning):
q_instance = QuantumInstance(
backend, seed_simulator=self.seed, seed_transpiler=self.seed
)
paulis_op = ListOp([X, Y, Z, I])
states_op = ListOp([One, Zero, Plus, Minus])
valids = [[+0, 0, 1, -1], [+0, 0, 0, 0], [-1, 1, 0, -0], [+1, 1, 1, 1]]
converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op)
with self.assertWarns(DeprecationWarning):
sampled = CircuitSampler(q_instance).convert(converted_meas)
np.testing.assert_array_almost_equal(sampled.eval(), valids, decimal=1)
def test_multi_representation_ops(self):
"""Test observables with mixed representations"""
mixed_ops = ListOp([X.to_matrix_op(), H, H + I, X])
converted_meas = self.expect.convert(~StateFn(mixed_ops))
plus_mean = converted_meas @ Plus
with self.assertWarns(DeprecationWarning):
sampled_plus = self.sampler.convert(plus_mean)
np.testing.assert_array_almost_equal(
sampled_plus.eval(), [1, 0.5**0.5, (1 + 0.5**0.5), 1], decimal=1
)
def test_pauli_expectation_non_hermite_op(self):
"""Test PauliExpectation for non hermitian operator"""
exp = ~StateFn(1j * Z) @ One
self.assertEqual(self.expect.convert(exp).eval(), 1j)
def test_list_pauli_sum_op(self):
"""Test PauliExpectation for List[PauliSumOp]"""
test_op = ListOp([~StateFn(PauliSumOp.from_list([("XX", 1), ("ZI", 3), ("ZZ", 5)]))])
observable = self.expect.convert(test_op)
self.assertIsInstance(observable, ListOp)
self.assertIsInstance(observable[0][0][0].primitive, PauliSumOp)
self.assertIsInstance(observable[0][1][0].primitive, PauliSumOp)
def test_expectation_with_coeff(self):
"""Test PauliExpectation with coefficients."""
with self.subTest("integer coefficients"):
exp = 3 * ~StateFn(X) @ (2 * Minus)
with self.assertWarns(DeprecationWarning):
target = self.sampler.convert(self.expect.convert(exp)).eval()
self.assertEqual(target, -12)
with self.subTest("complex coefficients"):
exp = 3j * ~StateFn(X) @ (2j * Minus)
with self.assertWarns(DeprecationWarning):
target = self.sampler.convert(self.expect.convert(exp)).eval()
self.assertEqual(target, -12j)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test PauliSumOp."""
import unittest
from itertools import product
from test.python.opflow import QiskitOpflowTestCase
from ddt import ddt, data, unpack
import numpy as np
from scipy.sparse import csr_matrix
from sympy import Symbol
from qiskit import QuantumCircuit, transpile
from qiskit.circuit import Parameter, ParameterExpression, ParameterVector
from qiskit.opflow import (
CX,
CircuitStateFn,
DictStateFn,
H,
I,
One,
OperatorStateFn,
PauliSumOp,
SummedOp,
X,
Y,
Z,
Zero,
OpflowError,
)
from qiskit.quantum_info import Pauli, PauliTable, SparsePauliOp
@ddt
class TestPauliSumOp(QiskitOpflowTestCase):
"""PauliSumOp tests."""
def test_construct(self):
"""constructor test"""
sparse_pauli = SparsePauliOp(Pauli("XYZX"), coeffs=[2.0])
coeff = 3.0
pauli_sum = PauliSumOp(sparse_pauli, coeff=coeff)
self.assertIsInstance(pauli_sum, PauliSumOp)
self.assertEqual(pauli_sum.primitive, sparse_pauli)
self.assertEqual(pauli_sum.coeff, coeff)
self.assertEqual(pauli_sum.num_qubits, 4)
def test_coeffs(self):
"""ListOp.coeffs test"""
sum1 = SummedOp(
[(0 + 1j) * X, (1 / np.sqrt(2) + 1j / np.sqrt(2)) * Z], 0.5
).collapse_summands()
self.assertAlmostEqual(sum1.coeffs[0], 0.5j)
self.assertAlmostEqual(sum1.coeffs[1], (1 + 1j) / (2 * np.sqrt(2)))
a_param = Parameter("a")
b_param = Parameter("b")
param_exp = ParameterExpression({a_param: 1, b_param: 0}, Symbol("a") ** 2 + Symbol("b"))
sum2 = SummedOp([X, (1 / np.sqrt(2) - 1j / np.sqrt(2)) * Y], param_exp).collapse_summands()
self.assertIsInstance(sum2.coeffs[0], ParameterExpression)
self.assertIsInstance(sum2.coeffs[1], ParameterExpression)
# Nested ListOp
sum_nested = SummedOp([X, sum1])
self.assertRaises(TypeError, lambda: sum_nested.coeffs)
def test_add(self):
"""add test"""
pauli_sum = 3 * X + Y
self.assertIsInstance(pauli_sum, PauliSumOp)
expected = PauliSumOp(3.0 * SparsePauliOp(Pauli("X")) + SparsePauliOp(Pauli("Y")))
self.assertEqual(pauli_sum, expected)
pauli_sum = X + Y
summed_op = SummedOp([X, Y])
self.assertEqual(pauli_sum, summed_op)
a = Parameter("a")
b = Parameter("b")
actual = a * PauliSumOp.from_list([("X", 2)]) + b * PauliSumOp.from_list([("Y", 1)])
expected = SummedOp(
[PauliSumOp.from_list([("X", 2)], a), PauliSumOp.from_list([("Y", 1)], b)]
)
self.assertEqual(actual, expected)
def test_mul(self):
"""multiplication test"""
target = 2 * (X + Z)
self.assertEqual(target.coeff, 1)
self.assertListEqual(target.primitive.to_list(), [("X", (2 + 0j)), ("Z", (2 + 0j))])
target = 0 * (X + Z)
self.assertEqual(target.coeff, 0)
self.assertListEqual(target.primitive.to_list(), [("X", (1 + 0j)), ("Z", (1 + 0j))])
beta = Parameter("Ξ²")
target = beta * (X + Z)
self.assertEqual(target.coeff, 1.0 * beta)
self.assertListEqual(target.primitive.to_list(), [("X", (1 + 0j)), ("Z", (1 + 0j))])
def test_adjoint(self):
"""adjoint test"""
pauli_sum = PauliSumOp(SparsePauliOp(Pauli("XYZX"), coeffs=[2]), coeff=3)
expected = PauliSumOp(SparsePauliOp(Pauli("XYZX")), coeff=6)
self.assertEqual(pauli_sum.adjoint(), expected)
pauli_sum = PauliSumOp(SparsePauliOp(Pauli("XYZY"), coeffs=[2]), coeff=3j)
expected = PauliSumOp(SparsePauliOp(Pauli("XYZY")), coeff=-6j)
self.assertEqual(pauli_sum.adjoint(), expected)
pauli_sum = PauliSumOp(SparsePauliOp(Pauli("X"), coeffs=[1]))
self.assertEqual(pauli_sum.adjoint(), pauli_sum)
pauli_sum = PauliSumOp(SparsePauliOp(Pauli("Y"), coeffs=[1]))
self.assertEqual(pauli_sum.adjoint(), pauli_sum)
pauli_sum = PauliSumOp(SparsePauliOp(Pauli("Z"), coeffs=[1]))
self.assertEqual(pauli_sum.adjoint(), pauli_sum)
pauli_sum = (Z ^ Z) + (Y ^ I)
self.assertEqual(pauli_sum.adjoint(), pauli_sum)
def test_equals(self):
"""equality test"""
self.assertNotEqual((X ^ X) + (Y ^ Y), X + Y)
self.assertEqual((X ^ X) + (Y ^ Y), (Y ^ Y) + (X ^ X))
self.assertEqual(0 * X + I, I)
self.assertEqual(I, 0 * X + I)
theta = ParameterVector("theta", 2)
pauli_sum0 = theta[0] * (X + Z)
pauli_sum1 = theta[1] * (X + Z)
expected = PauliSumOp(
SparsePauliOp(Pauli("X")) + SparsePauliOp(Pauli("Z")),
coeff=1.0 * theta[0],
)
self.assertEqual(pauli_sum0, expected)
self.assertNotEqual(pauli_sum1, expected)
def test_tensor(self):
"""Test for tensor operation"""
with self.subTest("Test 1"):
pauli_sum = ((I - Z) ^ (I - Z)) + ((X - Y) ^ (X + Y))
expected = (I ^ I) - (I ^ Z) - (Z ^ I) + (Z ^ Z) + (X ^ X) + (X ^ Y) - (Y ^ X) - (Y ^ Y)
self.assertEqual(pauli_sum, expected)
with self.subTest("Test 2"):
pauli_sum = (Z + I) ^ Z
expected = (Z ^ Z) + (I ^ Z)
self.assertEqual(pauli_sum, expected)
with self.subTest("Test 3"):
pauli_sum = Z ^ (Z + I)
expected = (Z ^ Z) + (Z ^ I)
self.assertEqual(pauli_sum, expected)
@data(([1, 2, 4], "XIYZI"), ([2, 1, 0], "ZYX"))
@unpack
def test_permute(self, permutation, expected_pauli):
"""Test the permute method."""
pauli_sum = PauliSumOp(SparsePauliOp.from_list([("XYZ", 1)]))
expected = PauliSumOp(SparsePauliOp.from_list([(expected_pauli, 1)]))
permuted = pauli_sum.permute(permutation)
with self.subTest(msg="test permutated object"):
self.assertEqual(permuted, expected)
with self.subTest(msg="test original object is unchanged"):
original = PauliSumOp(SparsePauliOp.from_list([("XYZ", 1)]))
self.assertEqual(pauli_sum, original)
@data([1, 2, 1], [1, 2, -1])
def test_permute_invalid(self, permutation):
"""Test the permute method raises an error on invalid permutations."""
pauli_sum = PauliSumOp(SparsePauliOp((X ^ Y ^ Z).primitive))
with self.assertRaises(OpflowError):
pauli_sum.permute(permutation)
def test_compose(self):
"""compose test"""
target = (X + Z) @ (Y + Z)
expected = 1j * Z - 1j * Y - 1j * X + I
self.assertEqual(target, expected)
observable = (X ^ X) + (Y ^ Y) + (Z ^ Z)
state = CircuitStateFn((CX @ (X ^ H @ X)).to_circuit())
self.assertAlmostEqual((~OperatorStateFn(observable) @ state).eval(), -3)
def test_to_matrix(self):
"""test for to_matrix method"""
target = (Z + Y).to_matrix()
expected = np.array([[1.0, -1j], [1j, -1]])
np.testing.assert_array_equal(target, expected)
def test_str(self):
"""str test"""
target = 3.0 * (X + 2.0 * Y - 4.0 * Z)
expected = "3.0 * X\n+ 6.0 * Y\n- 12.0 * Z"
self.assertEqual(str(target), expected)
alpha = Parameter("Ξ±")
target = alpha * (X + 2.0 * Y - 4.0 * Z)
expected = "1.0*Ξ± * (\n 1.0 * X\n + 2.0 * Y\n - 4.0 * Z\n)"
self.assertEqual(str(target), expected)
def test_eval(self):
"""eval test"""
target0 = (2 * (X ^ Y ^ Z) + 3 * (X ^ X ^ Z)).eval("000")
target1 = (2 * (X ^ Y ^ Z) + 3 * (X ^ X ^ Z)).eval(Zero ^ 3)
expected = DictStateFn({"110": (3 + 2j)})
self.assertEqual(target0, expected)
self.assertEqual(target1, expected)
phi = 0.5 * ((One + Zero) ^ 2)
zero_op = (Z + I) / 2
one_op = (I - Z) / 2
h1 = one_op ^ I
h2 = one_op ^ (one_op + zero_op)
h2a = one_op ^ one_op
h2b = one_op ^ zero_op
self.assertEqual((~OperatorStateFn(h1) @ phi).eval(), 0.5)
self.assertEqual((~OperatorStateFn(h2) @ phi).eval(), 0.5)
self.assertEqual((~OperatorStateFn(h2a) @ phi).eval(), 0.25)
self.assertEqual((~OperatorStateFn(h2b) @ phi).eval(), 0.25)
pauli_op = (Z ^ I ^ X) + (I ^ I ^ Y)
mat_op = pauli_op.to_matrix_op()
full_basis = ["".join(b) for b in product("01", repeat=pauli_op.num_qubits)]
for bstr1, bstr2 in product(full_basis, full_basis):
self.assertEqual(pauli_op.eval(bstr1).eval(bstr2), mat_op.eval(bstr1).eval(bstr2))
def test_exp_i(self):
"""exp_i test"""
# TODO: add tests when special methods are added
pass
def test_to_instruction(self):
"""test for to_instruction"""
target = ((X + Z) / np.sqrt(2)).to_instruction()
qc = QuantumCircuit(1)
qc.u(np.pi / 2, 0, np.pi, 0)
qc_out = transpile(target.definition, basis_gates=["u"])
self.assertEqual(qc_out, qc)
def test_to_pauli_op(self):
"""test to_pauli_op method"""
target = X + Y
self.assertIsInstance(target, PauliSumOp)
expected = SummedOp([X, Y])
self.assertEqual(target.to_pauli_op(), expected)
def test_getitem(self):
"""test get item method"""
target = X + Z
self.assertEqual(target[0], PauliSumOp(SparsePauliOp(X.primitive)))
self.assertEqual(target[1], PauliSumOp(SparsePauliOp(Z.primitive)))
def test_len(self):
"""test len"""
target = X + Y + Z
self.assertEqual(len(target), 3)
def test_reduce(self):
"""test reduce"""
target = X + X + Z
self.assertEqual(len(target.reduce()), 2)
def test_to_spmatrix(self):
"""test to_spmatrix"""
target = X + Y
expected = csr_matrix([[0, 1 - 1j], [1 + 1j, 0]])
self.assertEqual((target.to_spmatrix() - expected).nnz, 0)
def test_from_list(self):
"""test from_list"""
target = PauliSumOp.from_list(
[
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156),
]
)
expected = (
-1.052373245772859 * (I ^ I)
+ 0.39793742484318045 * (I ^ Z)
- 0.39793742484318045 * (Z ^ I)
- 0.01128010425623538 * (Z ^ Z)
+ 0.18093119978423156 * (X ^ X)
)
self.assertEqual(target, expected)
a = Parameter("a")
target = PauliSumOp.from_list([("X", 0.5 * a), ("Y", -0.5j * a)], dtype=object)
expected = PauliSumOp(
SparsePauliOp.from_list([("X", 0.5 * a), ("Y", -0.5j * a)], dtype=object)
)
self.assertEqual(target.primitive, expected.primitive)
def test_matrix_iter(self):
"""Test PauliSumOp dense matrix_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
coeffs = np.array([1, 2, 3, 4, 5, 6])
table = PauliTable.from_labels(labels)
coeff = 10
op = PauliSumOp(SparsePauliOp(table, coeffs), coeff)
for idx, i in enumerate(op.matrix_iter()):
self.assertTrue(np.array_equal(i, coeff * coeffs[idx] * Pauli(labels[idx]).to_matrix()))
def test_matrix_iter_sparse(self):
"""Test PauliSumOp sparse matrix_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
coeffs = np.array([1, 2, 3, 4, 5, 6])
coeff = 10
table = PauliTable.from_labels(labels)
op = PauliSumOp(SparsePauliOp(table, coeffs), coeff)
for idx, i in enumerate(op.matrix_iter(sparse=True)):
self.assertTrue(
np.array_equal(i.toarray(), coeff * coeffs[idx] * Pauli(labels[idx]).to_matrix())
)
def test_is_hermitian(self):
"""Test is_hermitian method"""
with self.subTest("True test"):
target = PauliSumOp.from_list(
[
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156),
]
)
self.assertTrue(target.is_hermitian())
with self.subTest("False test"):
target = PauliSumOp.from_list(
[
("II", -1.052373245772859),
("IZ", 0.39793742484318045j),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156),
]
)
self.assertFalse(target.is_hermitian())
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test Operator construction, including OpPrimitives and singletons."""
import unittest
from test.python.opflow import QiskitOpflowTestCase
import numpy as np
from qiskit import QuantumCircuit, BasicAer, execute
from qiskit.circuit import ParameterVector
from qiskit.quantum_info import Statevector
from qiskit.opflow import (
StateFn,
Zero,
One,
Plus,
Minus,
PrimitiveOp,
CircuitOp,
SummedOp,
H,
I,
Z,
X,
Y,
CX,
CircuitStateFn,
DictToCircuitSum,
)
class TestStateConstruction(QiskitOpflowTestCase):
"""State Construction tests."""
def test_state_singletons(self):
"""state singletons test"""
self.assertEqual(Zero.primitive, {"0": 1})
self.assertEqual(One.primitive, {"1": 1})
self.assertEqual((Zero ^ 5).primitive, {"00000": 1})
self.assertEqual((One ^ 5).primitive, {"11111": 1})
self.assertEqual(((Zero ^ One) ^ 3).primitive, {"010101": 1})
def test_zero_broadcast(self):
"""zero broadcast test"""
np.testing.assert_array_almost_equal(((H ^ 5) @ Zero).to_matrix(), (Plus ^ 5).to_matrix())
def test_state_to_matrix(self):
"""state to matrix test"""
np.testing.assert_array_equal(Zero.to_matrix(), np.array([1, 0]))
np.testing.assert_array_equal(One.to_matrix(), np.array([0, 1]))
np.testing.assert_array_almost_equal(
Plus.to_matrix(), (Zero.to_matrix() + One.to_matrix()) / (np.sqrt(2))
)
np.testing.assert_array_almost_equal(
Minus.to_matrix(), (Zero.to_matrix() - One.to_matrix()) / (np.sqrt(2))
)
# TODO Not a great test because doesn't test against validated values
# or test internal representation. Fix this.
gnarly_state = (One ^ Plus ^ Zero ^ Minus * 0.3) @ StateFn(
Statevector.from_label("r0+l")
) + (StateFn(X ^ Z ^ Y ^ I) * 0.1j)
gnarly_mat = gnarly_state.to_matrix()
gnarly_mat_separate = (One ^ Plus ^ Zero ^ Minus * 0.3).to_matrix()
gnarly_mat_separate = np.dot(
gnarly_mat_separate, StateFn(Statevector.from_label("r0+l")).to_matrix()
)
gnarly_mat_separate = gnarly_mat_separate + (StateFn(X ^ Z ^ Y ^ I) * 0.1j).to_matrix()
np.testing.assert_array_almost_equal(gnarly_mat, gnarly_mat_separate)
def test_qiskit_result_instantiation(self):
"""qiskit result instantiation test"""
qc = QuantumCircuit(3)
# REMEMBER: This is Qubit 2 in Operator land.
qc.h(0)
sv_res = execute(qc, BasicAer.get_backend("statevector_simulator")).result()
sv_vector = sv_res.get_statevector()
qc_op = PrimitiveOp(qc) @ Zero
qasm_res = execute(
qc_op.to_circuit(meas=True), BasicAer.get_backend("qasm_simulator")
).result()
np.testing.assert_array_almost_equal(
StateFn(sv_res).to_matrix(), [0.5**0.5, 0.5**0.5, 0, 0, 0, 0, 0, 0]
)
np.testing.assert_array_almost_equal(
StateFn(sv_vector).to_matrix(), [0.5**0.5, 0.5**0.5, 0, 0, 0, 0, 0, 0]
)
np.testing.assert_array_almost_equal(
StateFn(qasm_res).to_matrix(), [0.5**0.5, 0.5**0.5, 0, 0, 0, 0, 0, 0], decimal=1
)
np.testing.assert_array_almost_equal(
((I ^ I ^ H) @ Zero).to_matrix(), [0.5**0.5, 0.5**0.5, 0, 0, 0, 0, 0, 0]
)
np.testing.assert_array_almost_equal(
qc_op.to_matrix(), [0.5**0.5, 0.5**0.5, 0, 0, 0, 0, 0, 0]
)
def test_state_meas_composition(self):
"""state meas composition test"""
pass
# print((~Zero^4).eval(Zero^4))
# print((~One^4).eval(Zero^4))
# print((~One ^ 4).eval(One ^ 4))
# print(StateFn(I^Z, is_measurement=True).eval(One^2))
def test_add_direct(self):
"""add direct test"""
wf = StateFn({"101010": 0.5, "111111": 0.3}) + (Zero ^ 6)
self.assertEqual(wf.primitive, {"101010": 0.5, "111111": 0.3, "000000": 1.0})
wf = (4 * StateFn({"101010": 0.5, "111111": 0.3})) + ((3 + 0.1j) * (Zero ^ 6))
self.assertEqual(
wf.primitive, {"000000": (3 + 0.1j), "101010": (2 + 0j), "111111": (1.2 + 0j)}
)
def test_circuit_state_fn_from_dict_as_sum(self):
"""state fn circuit from dict as sum test"""
statedict = {"1010101": 0.5, "1000000": 0.1, "0000000": 0.2j, "1111111": 0.5j}
sfc_sum = CircuitStateFn.from_dict(statedict)
self.assertIsInstance(sfc_sum, SummedOp)
for sfc_op in sfc_sum.oplist:
self.assertIsInstance(sfc_op, CircuitStateFn)
samples = sfc_op.sample()
self.assertIn(list(samples.keys())[0], statedict)
self.assertEqual(sfc_op.coeff, statedict[list(samples.keys())[0]])
np.testing.assert_array_almost_equal(StateFn(statedict).to_matrix(), sfc_sum.to_matrix())
def test_circuit_state_fn_from_dict_initialize(self):
"""state fn circuit from dict initialize test"""
statedict = {"101": 0.5, "100": 0.1, "000": 0.2, "111": 0.5}
sfc = CircuitStateFn.from_dict(statedict)
self.assertIsInstance(sfc, CircuitStateFn)
samples = sfc.sample()
np.testing.assert_array_almost_equal(
StateFn(statedict).to_matrix(), np.round(sfc.to_matrix(), decimals=1)
)
for k, v in samples.items():
self.assertIn(k, statedict)
# It's ok if these are far apart because the dict is sampled.
self.assertAlmostEqual(v, np.abs(statedict[k]) ** 0.5, delta=0.5)
# Follows same code path as above, but testing to be thorough
sfc_vector = CircuitStateFn.from_vector(StateFn(statedict).to_matrix())
np.testing.assert_array_almost_equal(StateFn(statedict).to_matrix(), sfc_vector.to_matrix())
# #1276
def test_circuit_state_fn_from_complex_vector_initialize(self):
"""state fn circuit from complex vector initialize test"""
sfc = CircuitStateFn.from_vector(np.array([1j / np.sqrt(2), 0, 1j / np.sqrt(2), 0]))
self.assertIsInstance(sfc, CircuitStateFn)
def test_sampling(self):
"""state fn circuit from dict initialize test"""
statedict = {"101": 0.5 + 1.0j, "100": 0.1 + 2.0j, "000": 0.2 + 0.0j, "111": 0.5 + 1.0j}
sfc = CircuitStateFn.from_dict(statedict)
circ_samples = sfc.sample()
dict_samples = StateFn(statedict).sample()
vec_samples = StateFn(statedict).to_matrix_op().sample()
for k, v in circ_samples.items():
self.assertIn(k, dict_samples)
self.assertIn(k, vec_samples)
# It's ok if these are far apart because the dict is sampled.
self.assertAlmostEqual(v, np.abs(dict_samples[k]) ** 0.5, delta=0.5)
self.assertAlmostEqual(v, np.abs(vec_samples[k]) ** 0.5, delta=0.5)
def test_dict_to_circuit_sum(self):
"""Test DictToCircuitSum converter."""
# Test qubits < entires, so dict is converted to Initialize CircuitStateFn
dict_state_3q = StateFn({"101": 0.5, "100": 0.1, "000": 0.2, "111": 0.5})
circuit_state_3q = DictToCircuitSum().convert(dict_state_3q)
self.assertIsInstance(circuit_state_3q, CircuitStateFn)
np.testing.assert_array_almost_equal(
dict_state_3q.to_matrix(), circuit_state_3q.to_matrix()
)
# Test qubits >= entires, so dict is converted to Initialize CircuitStateFn
dict_state_4q = dict_state_3q ^ Zero
circuit_state_4q = DictToCircuitSum().convert(dict_state_4q)
self.assertIsInstance(circuit_state_4q, SummedOp)
np.testing.assert_array_almost_equal(
dict_state_4q.to_matrix(), circuit_state_4q.to_matrix()
)
# Test VectorStateFn conversion
vect_state_3q = dict_state_3q.to_matrix_op()
circuit_state_3q_vect = DictToCircuitSum().convert(vect_state_3q)
self.assertIsInstance(circuit_state_3q_vect, CircuitStateFn)
np.testing.assert_array_almost_equal(
vect_state_3q.to_matrix(), circuit_state_3q_vect.to_matrix()
)
def test_circuit_permute(self):
r"""Test the CircuitStateFn's .permute method"""
perm = range(7)[::-1]
c_op = (
((CX ^ 3) ^ X)
@ (H ^ 7)
@ (X ^ Y ^ Z ^ I ^ X ^ X ^ X)
@ (Y ^ (CX ^ 3))
@ (X ^ Y ^ Z ^ I ^ X ^ X ^ X)
) @ Zero
c_op_perm = c_op.permute(perm)
self.assertNotEqual(c_op, c_op_perm)
c_op_id = c_op_perm.permute(perm)
self.assertEqual(c_op, c_op_id)
def test_primitive_param_binding(self):
"""Test that assign_parameters binds parameters of both the underlying primitive and coeffs."""
theta = ParameterVector("theta", 2)
# only OperatorStateFn can have a primitive with a parameterized coefficient
op = StateFn(theta[0] * X) * theta[1]
bound = op.assign_parameters(dict(zip(theta, [0.2, 0.3])))
self.assertEqual(bound.coeff, 0.3)
self.assertEqual(bound.primitive.coeff, 0.2)
# #6003
def test_flatten_statefn_composed_with_composed_op(self):
"""Test that composing a StateFn with a ComposedOp constructs a single ComposedOp"""
circuit = QuantumCircuit(1)
vector = [1, 0]
ex = ~StateFn(I) @ (CircuitOp(circuit) @ StateFn(vector))
self.assertEqual(len(ex), 3)
self.assertEqual(ex.eval(), 1)
def test_tensorstate_to_matrix(self):
"""Test tensored states to matrix works correctly with a global coefficient.
Regression test of Qiskit/qiskit-terra#9398.
"""
state = 0.5 * (Plus ^ Zero)
expected = 1 / (2 * np.sqrt(2)) * np.array([1, 0, 1, 0])
np.testing.assert_almost_equal(state.to_matrix(), expected)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for BackendSampler."""
import math
import unittest
from unittest.mock import patch
from test import combine
from test.python.transpiler._dummy_passes import DummyTP
import numpy as np
from ddt import ddt
from qiskit import QuantumCircuit
from qiskit.circuit.library import RealAmplitudes
from qiskit.primitives import BackendSampler, SamplerResult
from qiskit.providers import JobStatus, JobV1
from qiskit.providers.fake_provider import FakeNairobi, FakeNairobiV2
from qiskit.providers.basicaer import QasmSimulatorPy
from qiskit.test import QiskitTestCase
from qiskit.transpiler import PassManager
from qiskit.utils import optionals
BACKENDS = [FakeNairobi(), FakeNairobiV2()]
@ddt
class TestBackendSampler(QiskitTestCase):
"""Test BackendSampler"""
def setUp(self):
super().setUp()
hadamard = QuantumCircuit(1, 1)
hadamard.h(0)
hadamard.measure(0, 0)
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
bell.measure_all()
self._circuit = [hadamard, bell]
self._target = [
{0: 0.5, 1: 0.5},
{0: 0.5, 3: 0.5, 1: 0, 2: 0},
]
self._pqc = RealAmplitudes(num_qubits=2, reps=2)
self._pqc.measure_all()
self._pqc2 = RealAmplitudes(num_qubits=2, reps=3)
self._pqc2.measure_all()
self._pqc_params = [[0.0] * 6, [1.0] * 6]
self._pqc_target = [{0: 1}, {0: 0.0148, 1: 0.3449, 2: 0.0531, 3: 0.5872}]
self._theta = [
[0, 1, 1, 2, 3, 5],
[1, 2, 3, 4, 5, 6],
[0, 1, 2, 3, 4, 5, 6, 7],
]
def _generate_circuits_target(self, indices):
if isinstance(indices, list):
circuits = [self._circuit[j] for j in indices]
target = [self._target[j] for j in indices]
else:
raise ValueError(f"invalid index {indices}")
return circuits, target
def _generate_params_target(self, indices):
if isinstance(indices, int):
params = self._pqc_params[indices]
target = self._pqc_target[indices]
elif isinstance(indices, list):
params = [self._pqc_params[j] for j in indices]
target = [self._pqc_target[j] for j in indices]
else:
raise ValueError(f"invalid index {indices}")
return params, target
def _compare_probs(self, prob, target):
if not isinstance(prob, list):
prob = [prob]
if not isinstance(target, list):
target = [target]
self.assertEqual(len(prob), len(target))
for p, targ in zip(prob, target):
for key, t_val in targ.items():
if key in p:
self.assertAlmostEqual(p[key], t_val, delta=0.1)
else:
self.assertAlmostEqual(t_val, 0, delta=0.1)
@combine(backend=BACKENDS)
def test_sampler_run(self, backend):
"""Test Sampler.run()."""
bell = self._circuit[1]
sampler = BackendSampler(backend=backend)
job = sampler.run(circuits=[bell], shots=1000)
self.assertIsInstance(job, JobV1)
result = job.result()
self.assertIsInstance(result, SamplerResult)
self.assertEqual(result.quasi_dists[0].shots, 1000)
self.assertEqual(result.quasi_dists[0].stddev_upper_bound, math.sqrt(1 / 1000))
self._compare_probs(result.quasi_dists, self._target[1])
@combine(backend=BACKENDS)
def test_sample_run_multiple_circuits(self, backend):
"""Test Sampler.run() with multiple circuits."""
# executes three Bell circuits
# Argument `parameters` is optional.
bell = self._circuit[1]
sampler = BackendSampler(backend=backend)
result = sampler.run([bell, bell, bell]).result()
# print([q.binary_probabilities() for q in result.quasi_dists])
self._compare_probs(result.quasi_dists[0], self._target[1])
self._compare_probs(result.quasi_dists[1], self._target[1])
self._compare_probs(result.quasi_dists[2], self._target[1])
@combine(backend=BACKENDS)
def test_sampler_run_with_parameterized_circuits(self, backend):
"""Test Sampler.run() with parameterized circuits."""
# parameterized circuit
pqc = self._pqc
pqc2 = self._pqc2
theta1, theta2, theta3 = self._theta
sampler = BackendSampler(backend=backend)
result = sampler.run([pqc, pqc, pqc2], [theta1, theta2, theta3]).result()
# result of pqc(theta1)
prob1 = {
"00": 0.1309248462975777,
"01": 0.3608720796028448,
"10": 0.09324865232050054,
"11": 0.41495442177907715,
}
self.assertDictAlmostEqual(result.quasi_dists[0].binary_probabilities(), prob1, delta=0.1)
# result of pqc(theta2)
prob2 = {
"00": 0.06282290651933871,
"01": 0.02877144385576705,
"10": 0.606654494132085,
"11": 0.3017511554928094,
}
self.assertDictAlmostEqual(result.quasi_dists[1].binary_probabilities(), prob2, delta=0.1)
# result of pqc2(theta3)
prob3 = {
"00": 0.1880263994380416,
"01": 0.6881971261189544,
"10": 0.09326232720582443,
"11": 0.030514147237179892,
}
self.assertDictAlmostEqual(result.quasi_dists[2].binary_probabilities(), prob3, delta=0.1)
@combine(backend=BACKENDS)
def test_run_1qubit(self, backend):
"""test for 1-qubit cases"""
qc = QuantumCircuit(1)
qc.measure_all()
qc2 = QuantumCircuit(1)
qc2.x(0)
qc2.measure_all()
sampler = BackendSampler(backend=backend)
result = sampler.run([qc, qc2]).result()
self.assertIsInstance(result, SamplerResult)
self.assertEqual(len(result.quasi_dists), 2)
self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1)
self.assertDictAlmostEqual(result.quasi_dists[1], {1: 1}, 0.1)
@combine(backend=BACKENDS)
def test_run_2qubit(self, backend):
"""test for 2-qubit cases"""
qc0 = QuantumCircuit(2)
qc0.measure_all()
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.measure_all()
qc2 = QuantumCircuit(2)
qc2.x(1)
qc2.measure_all()
qc3 = QuantumCircuit(2)
qc3.x([0, 1])
qc3.measure_all()
sampler = BackendSampler(backend=backend)
result = sampler.run([qc0, qc1, qc2, qc3]).result()
self.assertIsInstance(result, SamplerResult)
self.assertEqual(len(result.quasi_dists), 4)
self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1)
self.assertDictAlmostEqual(result.quasi_dists[1], {1: 1}, 0.1)
self.assertDictAlmostEqual(result.quasi_dists[2], {2: 1}, 0.1)
self.assertDictAlmostEqual(result.quasi_dists[3], {3: 1}, 0.1)
@combine(backend=BACKENDS)
def test_run_errors(self, backend):
"""Test for errors"""
qc1 = QuantumCircuit(1)
qc1.measure_all()
qc2 = RealAmplitudes(num_qubits=1, reps=1)
qc2.measure_all()
sampler = BackendSampler(backend=backend)
with self.assertRaises(ValueError):
sampler.run([qc1], [[1e2]]).result()
with self.assertRaises(ValueError):
sampler.run([qc2], [[]]).result()
with self.assertRaises(ValueError):
sampler.run([qc2], [[1e2]]).result()
@combine(backend=BACKENDS)
def test_run_empty_parameter(self, backend):
"""Test for empty parameter"""
n = 5
qc = QuantumCircuit(n, n - 1)
qc.measure(range(n - 1), range(n - 1))
sampler = BackendSampler(backend=backend)
with self.subTest("one circuit"):
result = sampler.run([qc], shots=1000).result()
self.assertEqual(len(result.quasi_dists), 1)
for q_d in result.quasi_dists:
quasi_dist = {k: v for k, v in q_d.items() if v != 0.0}
self.assertDictAlmostEqual(quasi_dist, {0: 1.0}, delta=0.1)
self.assertEqual(len(result.metadata), 1)
with self.subTest("two circuits"):
result = sampler.run([qc, qc], shots=1000).result()
self.assertEqual(len(result.quasi_dists), 2)
for q_d in result.quasi_dists:
quasi_dist = {k: v for k, v in q_d.items() if v != 0.0}
self.assertDictAlmostEqual(quasi_dist, {0: 1.0}, delta=0.1)
self.assertEqual(len(result.metadata), 2)
@combine(backend=BACKENDS)
def test_run_numpy_params(self, backend):
"""Test for numpy array as parameter values"""
qc = RealAmplitudes(num_qubits=2, reps=2)
qc.measure_all()
k = 5
params_array = np.random.rand(k, qc.num_parameters)
params_list = params_array.tolist()
params_list_array = list(params_array)
sampler = BackendSampler(backend=backend)
target = sampler.run([qc] * k, params_list).result()
with self.subTest("ndarrary"):
result = sampler.run([qc] * k, params_array).result()
self.assertEqual(len(result.metadata), k)
for i in range(k):
self.assertDictAlmostEqual(result.quasi_dists[i], target.quasi_dists[i], delta=0.1)
with self.subTest("list of ndarray"):
result = sampler.run([qc] * k, params_list_array).result()
self.assertEqual(len(result.metadata), k)
for i in range(k):
self.assertDictAlmostEqual(result.quasi_dists[i], target.quasi_dists[i], delta=0.1)
@combine(backend=BACKENDS)
def test_run_with_shots_option(self, backend):
"""test with shots option."""
params, target = self._generate_params_target([1])
sampler = BackendSampler(backend=backend)
result = sampler.run(
circuits=[self._pqc], parameter_values=params, shots=1024, seed=15
).result()
self._compare_probs(result.quasi_dists, target)
@combine(backend=BACKENDS)
def test_primitive_job_status_done(self, backend):
"""test primitive job's status"""
bell = self._circuit[1]
sampler = BackendSampler(backend=backend)
job = sampler.run(circuits=[bell])
_ = job.result()
self.assertEqual(job.status(), JobStatus.DONE)
def test_primitive_job_size_limit_backend_v2(self):
"""Test primitive respects backend's job size limit."""
class FakeNairobiLimitedCircuits(FakeNairobiV2):
"""FakeNairobiV2 with job size limit."""
@property
def max_circuits(self):
return 1
qc = QuantumCircuit(1)
qc.measure_all()
qc2 = QuantumCircuit(1)
qc2.x(0)
qc2.measure_all()
sampler = BackendSampler(backend=FakeNairobiLimitedCircuits())
result = sampler.run([qc, qc2]).result()
self.assertIsInstance(result, SamplerResult)
self.assertEqual(len(result.quasi_dists), 2)
self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1)
self.assertDictAlmostEqual(result.quasi_dists[1], {1: 1}, 0.1)
def test_primitive_job_size_limit_backend_v1(self):
"""Test primitive respects backend's job size limit."""
backend = FakeNairobi()
config = backend.configuration()
config.max_experiments = 1
backend._configuration = config
qc = QuantumCircuit(1)
qc.measure_all()
qc2 = QuantumCircuit(1)
qc2.x(0)
qc2.measure_all()
sampler = BackendSampler(backend=backend)
result = sampler.run([qc, qc2]).result()
self.assertIsInstance(result, SamplerResult)
self.assertEqual(len(result.quasi_dists), 2)
self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1)
self.assertDictAlmostEqual(result.quasi_dists[1], {1: 1}, 0.1)
@unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test")
def test_circuit_with_dynamic_circuit(self):
"""Test BackendSampler with QuantumCircuit with a dynamic circuit"""
from qiskit_aer import Aer
qc = QuantumCircuit(2, 1)
with qc.for_loop(range(5)):
qc.h(0)
qc.cx(0, 1)
qc.measure(0, 0)
qc.break_loop().c_if(0, True)
backend = Aer.get_backend("aer_simulator")
backend.set_options(seed_simulator=15)
sampler = BackendSampler(backend, skip_transpilation=True)
sampler.set_transpile_options(seed_transpiler=15)
result = sampler.run(qc).result()
self.assertDictAlmostEqual(result.quasi_dists[0], {0: 0.5029296875, 1: 0.4970703125})
def test_sequential_run(self):
"""Test sequential run."""
qc = QuantumCircuit(1)
qc.measure_all()
qc2 = QuantumCircuit(1)
qc2.x(0)
qc2.measure_all()
sampler = BackendSampler(backend=FakeNairobi())
result = sampler.run([qc]).result()
self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1)
result2 = sampler.run([qc2]).result()
self.assertDictAlmostEqual(result2.quasi_dists[0], {1: 1}, 0.1)
result3 = sampler.run([qc, qc2]).result()
self.assertDictAlmostEqual(result3.quasi_dists[0], {0: 1}, 0.1)
self.assertDictAlmostEqual(result3.quasi_dists[1], {1: 1}, 0.1)
def test_outcome_bitstring_size(self):
"""Test that the result bitstrings are properly padded.
E.g. measuring '0001' should not get truncated to '1'.
"""
qc = QuantumCircuit(4)
qc.x(0)
qc.measure_all()
# We need a noise-free backend here (shot noise is fine) to ensure that
# the only bit string measured is "0001". With device noise, it could happen that
# strings with a leading 1 are measured and then the truncation cannot be tested.
sampler = BackendSampler(backend=QasmSimulatorPy())
result = sampler.run(qc).result()
probs = result.quasi_dists[0].binary_probabilities()
self.assertIn("0001", probs.keys())
self.assertEqual(len(probs), 1)
def test_bound_pass_manager(self):
"""Test bound pass manager."""
with self.subTest("Test single circuit"):
dummy_pass = DummyTP()
with patch.object(DummyTP, "run", wraps=dummy_pass.run) as mock_pass:
bound_pass = PassManager(dummy_pass)
sampler = BackendSampler(backend=FakeNairobi(), bound_pass_manager=bound_pass)
_ = sampler.run(self._circuit[0]).result()
self.assertEqual(mock_pass.call_count, 1)
with self.subTest("Test circuit batch"):
dummy_pass = DummyTP()
with patch.object(DummyTP, "run", wraps=dummy_pass.run) as mock_pass:
bound_pass = PassManager(dummy_pass)
sampler = BackendSampler(backend=FakeNairobi(), bound_pass_manager=bound_pass)
_ = sampler.run([self._circuit[0], self._circuit[0]]).result()
self.assertEqual(mock_pass.call_count, 2)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for BasePrimitive."""
import json
from ddt import data, ddt, unpack
from numpy import array, float32, float64, int32, int64
from qiskit import QuantumCircuit, pulse, transpile
from qiskit.circuit.random import random_circuit
from qiskit.primitives.base.base_primitive import BasePrimitive
from qiskit.primitives.utils import _circuit_key
from qiskit.providers.fake_provider import FakeAlmaden
from qiskit.test import QiskitTestCase
@ddt
class TestCircuitValidation(QiskitTestCase):
"""Test circuits validation logic."""
@data(
(random_circuit(2, 2, seed=0), (random_circuit(2, 2, seed=0),)),
(
[random_circuit(2, 2, seed=0), random_circuit(2, 2, seed=1)],
(random_circuit(2, 2, seed=0), random_circuit(2, 2, seed=1)),
),
)
@unpack
def test_validate_circuits(self, circuits, expected):
"""Test circuits standardization."""
self.assertEqual(BasePrimitive._validate_circuits(circuits), expected)
@data(None, "ERROR", True, 0, 1.0, 1j, [0.0])
def test_type_error(self, circuits):
"""Test type error if invalid input."""
with self.assertRaises(TypeError):
BasePrimitive._validate_circuits(circuits)
@data((), [], "")
def test_value_error(self, circuits):
"""Test value error if no circuits are provided."""
with self.assertRaises(ValueError):
BasePrimitive._validate_circuits(circuits)
@ddt
class TestParameterValuesValidation(QiskitTestCase):
"""Test parameter_values validation logic."""
@data(
((), ((),)),
([], ((),)),
(0, ((0,),)),
(1.2, ((1.2,),)),
((0,), ((0,),)),
([0], ((0,),)),
([1.2], ((1.2,),)),
((0, 1), ((0, 1),)),
([0, 1], ((0, 1),)),
([0, 1.2], ((0, 1.2),)),
([0.3, 1.2], ((0.3, 1.2),)),
(((0, 1)), ((0, 1),)),
(([0, 1]), ((0, 1),)),
([(0, 1)], ((0, 1),)),
([[0, 1]], ((0, 1),)),
([[0, 1.2]], ((0, 1.2),)),
([[0.3, 1.2]], ((0.3, 1.2),)),
# Test for numpy dtypes
(int32(5), ((float(int32(5)),),)),
(int64(6), ((float(int64(6)),),)),
(float32(3.2), ((float(float32(3.2)),),)),
(float64(6.4), ((float(float64(6.4)),),)),
([int32(5), float32(3.2)], ((float(int32(5)), float(float32(3.2))),)),
)
@unpack
def test_validate_parameter_values(self, _parameter_values, expected):
"""Test parameter_values standardization."""
for parameter_values in [_parameter_values, array(_parameter_values)]: # Numpy
self.assertEqual(BasePrimitive._validate_parameter_values(parameter_values), expected)
self.assertEqual(
BasePrimitive._validate_parameter_values(None, default=parameter_values), expected
)
@data(
"ERROR",
("E", "R", "R", "O", "R"),
(["E", "R", "R"], ["O", "R"]),
1j,
(1j,),
((1j,),),
True,
False,
float("inf"),
float("-inf"),
float("nan"),
)
def test_type_error(self, parameter_values):
"""Test type error if invalid input."""
with self.assertRaises(TypeError):
BasePrimitive._validate_parameter_values(parameter_values)
def test_value_error(self):
"""Test value error if no parameter_values or default are provided."""
with self.assertRaises(ValueError):
BasePrimitive._validate_parameter_values(None)
class TestCircuitKey(QiskitTestCase):
"""Tests for _circuit_key function"""
def test_different_circuits(self):
"""Test collision of quantum circuits."""
with self.subTest("Ry circuit"):
def test_func(n):
qc = QuantumCircuit(1, 1, name="foo")
qc.ry(n, 0)
return qc
keys = [_circuit_key(test_func(i)) for i in range(5)]
self.assertEqual(len(keys), len(set(keys)))
with self.subTest("pulse circuit"):
def test_with_scheduling(n):
custom_gate = pulse.Schedule(name="custom_x_gate")
custom_gate.insert(
0, pulse.Play(pulse.Constant(160 * n, 0.1), pulse.DriveChannel(0)), inplace=True
)
qc = QuantumCircuit(1)
qc.x(0)
qc.add_calibration("x", qubits=(0,), schedule=custom_gate)
return transpile(qc, FakeAlmaden(), scheduling_method="alap")
keys = [_circuit_key(test_with_scheduling(i)) for i in range(1, 5)]
self.assertEqual(len(keys), len(set(keys)))
def test_circuit_key_controlflow(self):
"""Test for a circuit with control flow."""
qc = QuantumCircuit(2, 1)
with qc.for_loop(range(5)):
qc.h(0)
qc.cx(0, 1)
qc.measure(0, 0)
qc.break_loop().c_if(0, True)
self.assertIsInstance(hash(_circuit_key(qc)), int)
self.assertIsInstance(json.dumps(_circuit_key(qc)), str)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for Sampler."""
import unittest
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.circuit.library import RealAmplitudes
from qiskit.exceptions import QiskitError
from qiskit.extensions.unitary import UnitaryGate
from qiskit.primitives import Sampler, SamplerResult
from qiskit.providers import JobStatus, JobV1
from qiskit.test import QiskitTestCase
class TestSampler(QiskitTestCase):
"""Test Sampler"""
def setUp(self):
super().setUp()
hadamard = QuantumCircuit(1, 1, name="Hadamard")
hadamard.h(0)
hadamard.measure(0, 0)
bell = QuantumCircuit(2, name="Bell")
bell.h(0)
bell.cx(0, 1)
bell.measure_all()
self._circuit = [hadamard, bell]
self._target = [
{0: 0.5, 1: 0.5},
{0: 0.5, 3: 0.5, 1: 0, 2: 0},
]
self._pqc = RealAmplitudes(num_qubits=2, reps=2)
self._pqc.measure_all()
self._pqc2 = RealAmplitudes(num_qubits=2, reps=3)
self._pqc2.measure_all()
self._pqc_params = [[0.0] * 6, [1.0] * 6]
self._pqc_target = [{0: 1}, {0: 0.0148, 1: 0.3449, 2: 0.0531, 3: 0.5872}]
self._theta = [
[0, 1, 1, 2, 3, 5],
[1, 2, 3, 4, 5, 6],
[0, 1, 2, 3, 4, 5, 6, 7],
]
def _generate_circuits_target(self, indices):
if isinstance(indices, list):
circuits = [self._circuit[j] for j in indices]
target = [self._target[j] for j in indices]
else:
raise ValueError(f"invalid index {indices}")
return circuits, target
def _generate_params_target(self, indices):
if isinstance(indices, int):
params = self._pqc_params[indices]
target = self._pqc_target[indices]
elif isinstance(indices, list):
params = [self._pqc_params[j] for j in indices]
target = [self._pqc_target[j] for j in indices]
else:
raise ValueError(f"invalid index {indices}")
return params, target
def _compare_probs(self, prob, target):
if not isinstance(prob, list):
prob = [prob]
if not isinstance(target, list):
target = [target]
self.assertEqual(len(prob), len(target))
for p, targ in zip(prob, target):
for key, t_val in targ.items():
if key in p:
self.assertAlmostEqual(p[key], t_val, places=1)
else:
self.assertAlmostEqual(t_val, 0, places=1)
def test_sampler_run(self):
"""Test Sampler.run()."""
bell = self._circuit[1]
sampler = Sampler()
job = sampler.run(circuits=[bell])
self.assertIsInstance(job, JobV1)
result = job.result()
self.assertIsInstance(result, SamplerResult)
# print([q.binary_probabilities() for q in result.quasi_dists])
self._compare_probs(result.quasi_dists, self._target[1])
def test_sample_run_multiple_circuits(self):
"""Test Sampler.run() with multiple circuits."""
# executes three Bell circuits
# Argument `parameters` is optional.
bell = self._circuit[1]
sampler = Sampler()
result = sampler.run([bell, bell, bell]).result()
# print([q.binary_probabilities() for q in result.quasi_dists])
self._compare_probs(result.quasi_dists[0], self._target[1])
self._compare_probs(result.quasi_dists[1], self._target[1])
self._compare_probs(result.quasi_dists[2], self._target[1])
def test_sampler_run_with_parameterized_circuits(self):
"""Test Sampler.run() with parameterized circuits."""
# parameterized circuit
pqc = self._pqc
pqc2 = self._pqc2
theta1, theta2, theta3 = self._theta
sampler = Sampler()
result = sampler.run([pqc, pqc, pqc2], [theta1, theta2, theta3]).result()
# result of pqc(theta1)
prob1 = {
"00": 0.1309248462975777,
"01": 0.3608720796028448,
"10": 0.09324865232050054,
"11": 0.41495442177907715,
}
self.assertDictAlmostEqual(result.quasi_dists[0].binary_probabilities(), prob1)
# result of pqc(theta2)
prob2 = {
"00": 0.06282290651933871,
"01": 0.02877144385576705,
"10": 0.606654494132085,
"11": 0.3017511554928094,
}
self.assertDictAlmostEqual(result.quasi_dists[1].binary_probabilities(), prob2)
# result of pqc2(theta3)
prob3 = {
"00": 0.1880263994380416,
"01": 0.6881971261189544,
"10": 0.09326232720582443,
"11": 0.030514147237179892,
}
self.assertDictAlmostEqual(result.quasi_dists[2].binary_probabilities(), prob3)
def test_run_1qubit(self):
"""test for 1-qubit cases"""
qc = QuantumCircuit(1)
qc.measure_all()
qc2 = QuantumCircuit(1)
qc2.x(0)
qc2.measure_all()
sampler = Sampler()
result = sampler.run([qc, qc2]).result()
self.assertIsInstance(result, SamplerResult)
self.assertEqual(len(result.quasi_dists), 2)
for i in range(2):
keys, values = zip(*sorted(result.quasi_dists[i].items()))
self.assertTupleEqual(keys, (i,))
np.testing.assert_allclose(values, [1])
def test_run_2qubit(self):
"""test for 2-qubit cases"""
qc0 = QuantumCircuit(2)
qc0.measure_all()
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.measure_all()
qc2 = QuantumCircuit(2)
qc2.x(1)
qc2.measure_all()
qc3 = QuantumCircuit(2)
qc3.x([0, 1])
qc3.measure_all()
sampler = Sampler()
result = sampler.run([qc0, qc1, qc2, qc3]).result()
self.assertIsInstance(result, SamplerResult)
self.assertEqual(len(result.quasi_dists), 4)
for i in range(4):
keys, values = zip(*sorted(result.quasi_dists[i].items()))
self.assertTupleEqual(keys, (i,))
np.testing.assert_allclose(values, [1])
def test_run_single_circuit(self):
"""Test for single circuit case."""
sampler = Sampler()
with self.subTest("No parameter"):
circuit = self._circuit[1]
target = self._target[1]
param_vals = [None, [], [[]], np.array([]), np.array([[]])]
for val in param_vals:
with self.subTest(f"{circuit.name} w/ {val}"):
result = sampler.run(circuit, val).result()
self._compare_probs(result.quasi_dists, target)
self.assertEqual(len(result.metadata), 1)
with self.subTest("One parameter"):
circuit = QuantumCircuit(1, 1, name="X gate")
param = Parameter("x")
circuit.ry(param, 0)
circuit.measure(0, 0)
target = [{1: 1}]
param_vals = [
[np.pi],
[[np.pi]],
np.array([np.pi]),
np.array([[np.pi]]),
[np.array([np.pi])],
]
for val in param_vals:
with self.subTest(f"{circuit.name} w/ {val}"):
result = sampler.run(circuit, val).result()
self._compare_probs(result.quasi_dists, target)
self.assertEqual(len(result.metadata), 1)
with self.subTest("More than one parameter"):
circuit = self._pqc
target = [self._pqc_target[0]]
param_vals = [
self._pqc_params[0],
[self._pqc_params[0]],
np.array(self._pqc_params[0]),
np.array([self._pqc_params[0]]),
[np.array(self._pqc_params[0])],
]
for val in param_vals:
with self.subTest(f"{circuit.name} w/ {val}"):
result = sampler.run(circuit, val).result()
self._compare_probs(result.quasi_dists, target)
self.assertEqual(len(result.metadata), 1)
def test_run_reverse_meas_order(self):
"""test for sampler with reverse measurement order"""
x = Parameter("x")
y = Parameter("y")
qc = QuantumCircuit(3, 3)
qc.rx(x, 0)
qc.rx(y, 1)
qc.x(2)
qc.measure(0, 2)
qc.measure(1, 1)
qc.measure(2, 0)
sampler = Sampler()
result = sampler.run([qc] * 2, [[0, 0], [np.pi / 2, 0]]).result()
self.assertIsInstance(result, SamplerResult)
self.assertEqual(len(result.quasi_dists), 2)
# qc({x: 0, y: 0})
keys, values = zip(*sorted(result.quasi_dists[0].items()))
self.assertTupleEqual(keys, (1,))
np.testing.assert_allclose(values, [1])
# qc({x: pi/2, y: 0})
keys, values = zip(*sorted(result.quasi_dists[1].items()))
self.assertTupleEqual(keys, (1, 5))
np.testing.assert_allclose(values, [0.5, 0.5])
def test_run_errors(self):
"""Test for errors with run method"""
qc1 = QuantumCircuit(1)
qc1.measure_all()
qc2 = RealAmplitudes(num_qubits=1, reps=1)
qc2.measure_all()
qc3 = QuantumCircuit(1)
qc4 = QuantumCircuit(1, 1)
sampler = Sampler()
with self.subTest("set parameter values to a non-parameterized circuit"):
with self.assertRaises(ValueError):
_ = sampler.run([qc1], [[1e2]])
with self.subTest("missing all parameter values for a parameterized circuit"):
with self.assertRaises(ValueError):
_ = sampler.run([qc2], [[]])
with self.subTest("missing some parameter values for a parameterized circuit"):
with self.assertRaises(ValueError):
_ = sampler.run([qc2], [[1e2]])
with self.subTest("too many parameter values for a parameterized circuit"):
with self.assertRaises(ValueError):
_ = sampler.run([qc2], [[1e2]] * 100)
with self.subTest("no classical bits"):
with self.assertRaises(ValueError):
_ = sampler.run([qc3], [[]])
with self.subTest("no measurement"):
with self.assertRaises(QiskitError):
# The following raises QiskitError because this check is located in
# `Sampler._preprocess_circuit`
_ = sampler.run([qc4], [[]])
def test_run_empty_parameter(self):
"""Test for empty parameter"""
n = 5
qc = QuantumCircuit(n, n - 1)
qc.measure(range(n - 1), range(n - 1))
sampler = Sampler()
with self.subTest("one circuit"):
result = sampler.run([qc], shots=1000).result()
self.assertEqual(len(result.quasi_dists), 1)
for q_d in result.quasi_dists:
quasi_dist = {k: v for k, v in q_d.items() if v != 0.0}
self.assertDictEqual(quasi_dist, {0: 1.0})
self.assertEqual(len(result.metadata), 1)
with self.subTest("two circuits"):
result = sampler.run([qc, qc], shots=1000).result()
self.assertEqual(len(result.quasi_dists), 2)
for q_d in result.quasi_dists:
quasi_dist = {k: v for k, v in q_d.items() if v != 0.0}
self.assertDictEqual(quasi_dist, {0: 1.0})
self.assertEqual(len(result.metadata), 2)
def test_run_numpy_params(self):
"""Test for numpy array as parameter values"""
qc = RealAmplitudes(num_qubits=2, reps=2)
qc.measure_all()
k = 5
params_array = np.random.rand(k, qc.num_parameters)
params_list = params_array.tolist()
params_list_array = list(params_array)
sampler = Sampler()
target = sampler.run([qc] * k, params_list).result()
with self.subTest("ndarrary"):
result = sampler.run([qc] * k, params_array).result()
self.assertEqual(len(result.metadata), k)
for i in range(k):
self.assertDictEqual(result.quasi_dists[i], target.quasi_dists[i])
with self.subTest("list of ndarray"):
result = sampler.run([qc] * k, params_list_array).result()
self.assertEqual(len(result.metadata), k)
for i in range(k):
self.assertDictEqual(result.quasi_dists[i], target.quasi_dists[i])
def test_run_with_shots_option(self):
"""test with shots option."""
params, target = self._generate_params_target([1])
sampler = Sampler()
result = sampler.run(
circuits=[self._pqc], parameter_values=params, shots=1024, seed=15
).result()
self._compare_probs(result.quasi_dists, target)
def test_run_with_shots_option_none(self):
"""test with shots=None option. Seed is ignored then."""
sampler = Sampler()
result_42 = sampler.run(
[self._pqc], parameter_values=[[0, 1, 1, 2, 3, 5]], shots=None, seed=42
).result()
result_15 = sampler.run(
[self._pqc], parameter_values=[[0, 1, 1, 2, 3, 5]], shots=None, seed=15
).result()
self.assertDictAlmostEqual(result_42.quasi_dists, result_15.quasi_dists)
def test_run_shots_result_size(self):
"""test with shots option to validate the result size"""
n = 10
shots = 100
qc = QuantumCircuit(n)
qc.h(range(n))
qc.measure_all()
sampler = Sampler()
result = sampler.run(qc, [], shots=shots, seed=42).result()
self.assertEqual(len(result.quasi_dists), 1)
self.assertLessEqual(len(result.quasi_dists[0]), shots)
self.assertAlmostEqual(sum(result.quasi_dists[0].values()), 1.0)
def test_primitive_job_status_done(self):
"""test primitive job's status"""
bell = self._circuit[1]
sampler = Sampler()
job = sampler.run(circuits=[bell])
_ = job.result()
self.assertEqual(job.status(), JobStatus.DONE)
def test_options(self):
"""Test for options"""
with self.subTest("init"):
sampler = Sampler(options={"shots": 3000})
self.assertEqual(sampler.options.get("shots"), 3000)
with self.subTest("set_options"):
sampler.set_options(shots=1024, seed=15)
self.assertEqual(sampler.options.get("shots"), 1024)
self.assertEqual(sampler.options.get("seed"), 15)
with self.subTest("run"):
params, target = self._generate_params_target([1])
result = sampler.run([self._pqc], parameter_values=params).result()
self._compare_probs(result.quasi_dists, target)
self.assertEqual(result.quasi_dists[0].shots, 1024)
def test_circuit_with_unitary(self):
"""Test for circuit with unitary gate."""
gate = UnitaryGate(np.eye(2))
circuit = QuantumCircuit(1)
circuit.append(gate, [0])
circuit.measure_all()
sampler = Sampler()
sampler_result = sampler.run([circuit]).result()
self.assertDictAlmostEqual(sampler_result.quasi_dists[0], {0: 1, 1: 0})
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for visualization tools."""
import unittest
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Qubit, Clbit
from qiskit.visualization.circuit import _utils
from qiskit.visualization import array_to_latex
from qiskit.test import QiskitTestCase
from qiskit.utils import optionals
class TestVisualizationUtils(QiskitTestCase):
"""Tests for circuit drawer utilities."""
def setUp(self):
super().setUp()
self.qr1 = QuantumRegister(2, "qr1")
self.qr2 = QuantumRegister(2, "qr2")
self.cr1 = ClassicalRegister(2, "cr1")
self.cr2 = ClassicalRegister(2, "cr2")
self.circuit = QuantumCircuit(self.qr1, self.qr2, self.cr1, self.cr2)
self.circuit.cx(self.qr2[0], self.qr2[1])
self.circuit.measure(self.qr2[0], self.cr2[0])
self.circuit.cx(self.qr2[1], self.qr2[0])
self.circuit.measure(self.qr2[1], self.cr2[1])
self.circuit.cx(self.qr1[0], self.qr1[1])
self.circuit.measure(self.qr1[0], self.cr1[0])
self.circuit.cx(self.qr1[1], self.qr1[0])
self.circuit.measure(self.qr1[1], self.cr1[1])
def test_get_layered_instructions(self):
"""_get_layered_instructions without reverse_bits"""
(qregs, cregs, layered_ops) = _utils._get_layered_instructions(self.circuit)
exp = [
[("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())],
[("measure", (self.qr2[0],), (self.cr2[0],))],
[("measure", (self.qr1[0],), (self.cr1[0],))],
[("cx", (self.qr2[1], self.qr2[0]), ()), ("cx", (self.qr1[1], self.qr1[0]), ())],
[("measure", (self.qr2[1],), (self.cr2[1],))],
[("measure", (self.qr1[1],), (self.cr1[1],))],
]
self.assertEqual([self.qr1[0], self.qr1[1], self.qr2[0], self.qr2[1]], qregs)
self.assertEqual([self.cr1[0], self.cr1[1], self.cr2[0], self.cr2[1]], cregs)
self.assertEqual(
exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_reverse_bits(self):
"""_get_layered_instructions with reverse_bits=True"""
(qregs, cregs, layered_ops) = _utils._get_layered_instructions(
self.circuit, reverse_bits=True
)
exp = [
[("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())],
[("measure", (self.qr2[0],), (self.cr2[0],))],
[("measure", (self.qr1[0],), (self.cr1[0],)), ("cx", (self.qr2[1], self.qr2[0]), ())],
[("cx", (self.qr1[1], self.qr1[0]), ())],
[("measure", (self.qr2[1],), (self.cr2[1],))],
[("measure", (self.qr1[1],), (self.cr1[1],))],
]
self.assertEqual([self.qr2[1], self.qr2[0], self.qr1[1], self.qr1[0]], qregs)
self.assertEqual([self.cr2[1], self.cr2[0], self.cr1[1], self.cr1[0]], cregs)
self.assertEqual(
exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_remove_idle_wires(self):
"""_get_layered_instructions with idle_wires=False"""
qr1 = QuantumRegister(3, "qr1")
qr2 = QuantumRegister(3, "qr2")
cr1 = ClassicalRegister(3, "cr1")
cr2 = ClassicalRegister(3, "cr2")
circuit = QuantumCircuit(qr1, qr2, cr1, cr2)
circuit.cx(qr2[0], qr2[1])
circuit.measure(qr2[0], cr2[0])
circuit.cx(qr2[1], qr2[0])
circuit.measure(qr2[1], cr2[1])
circuit.cx(qr1[0], qr1[1])
circuit.measure(qr1[0], cr1[0])
circuit.cx(qr1[1], qr1[0])
circuit.measure(qr1[1], cr1[1])
(qregs, cregs, layered_ops) = _utils._get_layered_instructions(circuit, idle_wires=False)
exp = [
[("cx", (qr2[0], qr2[1]), ()), ("cx", (qr1[0], qr1[1]), ())],
[("measure", (qr2[0],), (cr2[0],))],
[("measure", (qr1[0],), (cr1[0],))],
[("cx", (qr2[1], qr2[0]), ()), ("cx", (qr1[1], qr1[0]), ())],
[("measure", (qr2[1],), (cr2[1],))],
[("measure", (qr1[1],), (cr1[1],))],
]
self.assertEqual([qr1[0], qr1[1], qr2[0], qr2[1]], qregs)
self.assertEqual([cr1[0], cr1[1], cr2[0], cr2[1]], cregs)
self.assertEqual(
exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_left_justification_simple(self):
"""Test _get_layered_instructions left justification simple since #2802
q_0: |0>ββββββββ ββ
βββββ β
q_1: |0>β€ H ββββΌββ
βββββ€ β
q_2: |0>β€ H ββββΌββ
ββββββββ΄ββ
q_3: |0>ββββββ€ X β
βββββ
"""
qc = QuantumCircuit(4)
qc.h(1)
qc.h(2)
qc.cx(0, 3)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left")
l_exp = [
[
("h", (Qubit(QuantumRegister(4, "q"), 1),), ()),
("h", (Qubit(QuantumRegister(4, "q"), 2),), ()),
],
[("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())],
]
self.assertEqual(
l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_right_justification_simple(self):
"""Test _get_layered_instructions right justification simple since #2802
q_0: |0>βββ βββββββ
β βββββ
q_1: |0>βββΌβββ€ H β
β βββββ€
q_2: |0>βββΌβββ€ H β
βββ΄βββββββ
q_3: |0>β€ X ββββββ
βββββ
"""
qc = QuantumCircuit(4)
qc.h(1)
qc.h(2)
qc.cx(0, 3)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right")
r_exp = [
[("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())],
[
("h", (Qubit(QuantumRegister(4, "q"), 1),), ()),
("h", (Qubit(QuantumRegister(4, "q"), 2),), ()),
],
]
self.assertEqual(
r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_left_justification_less_simple(self):
"""Test _get_layered_instructions left justification
less simple example since #2802
βββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββ
q_0: |0>β€ U2(0,pi/1) ββ€ X ββ€ U2(0,pi/1) ββββββββββββββββ€Mββ€ U2(0,pi/1) ββ€ X ββ€ U2(0,pi/1) β
ββββββββββββββ€βββ¬ββββββββββββββββ€ββββββββββββββββ₯ββββββββββββββββββ¬ββββββββββββββββ€
q_1: |0>β€ U2(0,pi/1) ββββ βββ€ U2(0,pi/1) ββ€ U2(0,pi/1) βββ«ββββββββββββββββββ βββ€ U2(0,pi/1) β
ββββββββββββββ ββββββββββββββββββββββββββββ β ββββββββββββββ
q_2: |0>βββββββββββββββββββββββββββββββββββββββββββββββββ«ββββββββββββββββββββββββββββββββββ
β
q_3: |0>βββββββββββββββββββββββββββββββββββββββββββββββββ«ββββββββββββββββββββββββββββββββββ
β
q_4: |0>βββββββββββββββββββββββββββββββββββββββββββββββββ«ββββββββββββββββββββββββββββββββββ
β
c1_0: 0 βββββββββββββββββββββββββββββββββββββββββββββββββ©ββββββββββββββββββββββββββββββββββ
"""
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[5];
creg c1[1];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
u2(0,3.14159265358979) q[1];
measure q[0] -> c1[0];
u2(0,3.14159265358979) q[0];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
"""
qc = QuantumCircuit.from_qasm_str(qasm)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left")
l_exp = [
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("u2", (Qubit(QuantumRegister(5, "q"), 1),), ())],
[
(
"measure",
(Qubit(QuantumRegister(5, "q"), 0),),
(Clbit(ClassicalRegister(1, "c1"), 0),),
)
],
[("u2", (Qubit(QuantumRegister(5, "q"), 0),), ())],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
]
self.assertEqual(
l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_right_justification_less_simple(self):
"""Test _get_layered_instructions right justification
less simple example since #2802
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
q_0: |0>β€ U2(0,pi/1) ββ€ X ββ€ U2(0,pi/1) ββ€Mββ€ U2(0,pi/1) ββ€ X ββ€ U2(0,pi/1) β
ββββββββββββββ€βββ¬ββββββββββββββββ€ββ₯βββββββββββββββ€βββ¬ββββββββββββββββ€
q_1: |0>β€ U2(0,pi/1) ββββ βββ€ U2(0,pi/1) βββ«ββ€ U2(0,pi/1) ββββ βββ€ U2(0,pi/1) β
ββββββββββββββ ββββββββββββββ β ββββββββββββββ ββββββββββββββ
q_2: |0>βββββββββββββββββββββββββββββββββββ«ββββββββββββββββββββββββββββββββββ
β
q_3: |0>βββββββββββββββββββββββββββββββββββ«ββββββββββββββββββββββββββββββββββ
β
q_4: |0>βββββββββββββββββββββββββββββββββββ«ββββββββββββββββββββββββββββββββββ
β
c1_0: 0 βββββββββββββββββββββββββββββββββββ©ββββββββββββββββββββββββββββββββββ
"""
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[5];
creg c1[1];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
u2(0,3.14159265358979) q[1];
measure q[0] -> c1[0];
u2(0,3.14159265358979) q[0];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
"""
qc = QuantumCircuit.from_qasm_str(qasm)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right")
r_exp = [
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[
(
"measure",
(Qubit(QuantumRegister(5, "q"), 0),),
(Clbit(ClassicalRegister(1, "c1"), 0),),
)
],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
]
self.assertEqual(
r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_op_with_cargs(self):
"""Test _get_layered_instructions op with cargs right of measure
ββββββββ
q_0: |0>β€ H ββ€Mββββββββββββββ
βββββββ₯ββββββββββββββ
q_1: |0>βββββββ«ββ€0 β
β β add_circ β
c_0: 0 βββββββ©ββ‘0 β
βββββββββββββ
c_1: 0 βββββββββββββββββββββ
"""
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.measure(0, 0)
qc_2 = QuantumCircuit(1, 1, name="add_circ")
qc_2.h(0).c_if(qc_2.cregs[0], 1)
qc_2.measure(0, 0)
qc.append(qc_2, [1], [0])
(_, _, layered_ops) = _utils._get_layered_instructions(qc)
expected = [
[("h", (Qubit(QuantumRegister(2, "q"), 0),), ())],
[
(
"measure",
(Qubit(QuantumRegister(2, "q"), 0),),
(Clbit(ClassicalRegister(2, "c"), 0),),
)
],
[
(
"add_circ",
(Qubit(QuantumRegister(2, "q"), 1),),
(Clbit(ClassicalRegister(2, "c"), 0),),
)
],
]
self.assertEqual(
expected, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_nomathmode(self):
"""Test generate latex label default."""
self.assertEqual("abc", _utils.generate_latex_label("abc"))
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_nomathmode_utf8char(self):
"""Test generate latex label utf8 characters."""
self.assertEqual(
"{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label("βXβY"),
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_mathmode_utf8char(self):
"""Test generate latex label mathtext with utf8."""
self.assertEqual(
"abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label("$abc_$βXβY"),
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_mathmode_underscore_outside(self):
"""Test generate latex label with underscore outside mathmode."""
self.assertEqual(
"abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label("$abc$_βXβY"),
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_escaped_dollar_signs(self):
"""Test generate latex label with escaped dollarsign."""
self.assertEqual("${\\ensuremath{\\forall}}$", _utils.generate_latex_label(r"\$β\$"))
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_escaped_dollar_sign_in_mathmode(self):
"""Test generate latex label with escaped dollar sign in mathmode."""
self.assertEqual(
"a$bc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label(r"$a$bc$_βXβY"),
)
def test_array_to_latex(self):
"""Test array_to_latex produces correct latex string"""
matrix = [
[np.sqrt(1 / 2), 1 / 16, 1 / np.sqrt(8) + 3j, -0.5 + 0.5j],
[1 / 3 - 1 / 3j, np.sqrt(1 / 2) * 1j, 34.3210, -9 / 2],
]
matrix = np.array(matrix)
exp_str = (
"\\begin{bmatrix}\\frac{\\sqrt{2}}{2}&\\frac{1}{16}&"
"\\frac{\\sqrt{2}}{4}+3i&-\\frac{1}{2}+\\frac{i}{2}\\\\"
"\\frac{1}{3}+\\frac{i}{3}&\\frac{\\sqrt{2}i}{2}&34.321&-"
"\\frac{9}{2}\\\\\\end{bmatrix}"
)
result = array_to_latex(matrix, source=True).replace(" ", "").replace("\n", "")
self.assertEqual(exp_str, result)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test of generated fake backends."""
import math
import unittest
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, schedule, transpile, assemble
from qiskit.pulse import Schedule
from qiskit.qobj import PulseQobj
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider.utils.configurable_backend import ConfigurableFakeBackend
from qiskit.providers.fake_provider import FakeAthens, FakePerth
from qiskit.utils import optionals
def get_test_circuit():
"""Generates simple circuit for tests."""
desired_vector = [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
qc = QuantumCircuit(qr, cr)
qc.initialize(desired_vector, [qr[0], qr[1]])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
return qc
class GeneratedFakeBackendsTest(QiskitTestCase):
"""Generated fake backends test."""
def setUp(self) -> None:
self.backend = ConfigurableFakeBackend("Tashkent", n_qubits=4)
@unittest.skip("Skipped until qiskit-aer#741 is fixed and released")
@unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test")
def test_transpile_schedule_and_assemble(self):
"""Test transpile, schedule and assemble on generated backend."""
qc = get_test_circuit()
circuit = transpile(qc, backend=self.backend)
self.assertTrue(isinstance(circuit, QuantumCircuit))
self.assertEqual(circuit.num_qubits, 4)
experiments = schedule(circuits=circuit, backend=self.backend)
self.assertTrue(isinstance(experiments, Schedule))
self.assertGreater(experiments.duration, 0)
qobj = assemble(experiments, backend=self.backend)
self.assertTrue(isinstance(qobj, PulseQobj))
self.assertEqual(qobj.header.backend_name, "Tashkent")
self.assertEqual(len(qobj.experiments), 1)
job = self.backend.run(qobj)
result = job.result()
self.assertTrue(result.success)
self.assertEqual(len(result.results), 1)
class FakeBackendsTest(QiskitTestCase):
"""fake backends test."""
@unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test")
def test_fake_backends_get_kwargs(self):
"""Fake backends honor kwargs passed."""
backend = FakeAthens()
qc = QuantumCircuit(2)
qc.x(range(0, 2))
qc.measure_all()
trans_qc = transpile(qc, backend)
raw_counts = backend.run(trans_qc, shots=1000).result().get_counts()
self.assertEqual(sum(raw_counts.values()), 1000)
@unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test")
def test_fake_backend_v2_noise_model_always_present(self):
"""Test that FakeBackendV2 instances always run with noise."""
backend = FakePerth()
qc = QuantumCircuit(1)
qc.x(0)
qc.measure_all()
res = backend.run(qc, shots=1000).result().get_counts()
# Assert noise was present and result wasn't ideal
self.assertNotEqual(res, {"1": 1000})
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""Test cases for the pulse schedule block."""
import re
import unittest
from typing import List, Any
from qiskit import pulse, circuit
from qiskit.pulse import transforms
from qiskit.pulse.exceptions import PulseError
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeOpenPulse2Q, FakeArmonk
from qiskit.utils import has_aer
class BaseTestBlock(QiskitTestCase):
"""ScheduleBlock tests."""
def setUp(self):
super().setUp()
self.backend = FakeOpenPulse2Q()
self.test_waveform0 = pulse.Constant(100, 0.1)
self.test_waveform1 = pulse.Constant(200, 0.1)
self.d0 = pulse.DriveChannel(0)
self.d1 = pulse.DriveChannel(1)
self.left_context = transforms.AlignLeft()
self.right_context = transforms.AlignRight()
self.sequential_context = transforms.AlignSequential()
self.equispaced_context = transforms.AlignEquispaced(duration=1000)
def _align_func(j):
return {1: 0.1, 2: 0.25, 3: 0.7, 4: 0.85}.get(j)
self.func_context = transforms.AlignFunc(duration=1000, func=_align_func)
def assertScheduleEqual(self, target, reference):
"""Check if two block are equal schedule representation."""
self.assertEqual(transforms.target_qobj_transform(target), reference)
class TestTransformation(BaseTestBlock):
"""Test conversion of ScheduleBlock to Schedule."""
def test_left_alignment(self):
"""Test left alignment context."""
block = pulse.ScheduleBlock(alignment_context=self.left_context)
block = block.append(pulse.Play(self.test_waveform0, self.d0))
block = block.append(pulse.Play(self.test_waveform1, self.d1))
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1))
self.assertScheduleEqual(block, ref_sched)
def test_right_alignment(self):
"""Test right alignment context."""
block = pulse.ScheduleBlock(alignment_context=self.right_context)
block = block.append(pulse.Play(self.test_waveform0, self.d0))
block = block.append(pulse.Play(self.test_waveform1, self.d1))
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1))
self.assertScheduleEqual(block, ref_sched)
def test_sequential_alignment(self):
"""Test sequential alignment context."""
block = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block = block.append(pulse.Play(self.test_waveform0, self.d0))
block = block.append(pulse.Play(self.test_waveform1, self.d1))
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform1, self.d1))
self.assertScheduleEqual(block, ref_sched)
def test_equispace_alignment(self):
"""Test equispace alignment context."""
block = pulse.ScheduleBlock(alignment_context=self.equispaced_context)
for _ in range(4):
block = block.append(pulse.Play(self.test_waveform0, self.d0))
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(300, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(600, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(900, pulse.Play(self.test_waveform0, self.d0))
self.assertScheduleEqual(block, ref_sched)
def test_func_alignment(self):
"""Test func alignment context."""
block = pulse.ScheduleBlock(alignment_context=self.func_context)
for _ in range(4):
block = block.append(pulse.Play(self.test_waveform0, self.d0))
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(50, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(200, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(650, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(800, pulse.Play(self.test_waveform0, self.d0))
self.assertScheduleEqual(block, ref_sched)
def test_nested_alignment(self):
"""Test nested block scheduling."""
block_sub = pulse.ScheduleBlock(alignment_context=self.right_context)
block_sub = block_sub.append(pulse.Play(self.test_waveform0, self.d0))
block_sub = block_sub.append(pulse.Play(self.test_waveform1, self.d1))
block_main = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block_main = block_main.append(block_sub)
block_main = block_main.append(pulse.Delay(10, self.d0))
block_main = block_main.append(block_sub)
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1))
ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(200, pulse.Delay(10, self.d0))
ref_sched = ref_sched.insert(210, pulse.Play(self.test_waveform1, self.d1))
ref_sched = ref_sched.insert(310, pulse.Play(self.test_waveform0, self.d0))
self.assertScheduleEqual(block_main, ref_sched)
class TestBlockOperation(BaseTestBlock):
"""Test fundamental operation on schedule block.
Because ScheduleBlock adapts to the lazy scheduling, no uniitest for
overlap constraints is necessary. Test scheme becomes simpler than the schedule.
Some tests have dependency on schedule conversion.
This operation should be tested in `test.python.pulse.test_block.TestTransformation`.
"""
def setUp(self):
super().setUp()
self.test_blocks = [
pulse.Play(self.test_waveform0, self.d0),
pulse.Play(self.test_waveform1, self.d1),
pulse.Delay(50, self.d0),
pulse.Play(self.test_waveform1, self.d0),
]
def test_append_an_instruction_to_empty_block(self):
"""Test append instructions to an empty block."""
block = pulse.ScheduleBlock()
block = block.append(pulse.Play(self.test_waveform0, self.d0))
self.assertEqual(block.blocks[0], pulse.Play(self.test_waveform0, self.d0))
def test_append_an_instruction_to_empty_block_sugar(self):
"""Test append instructions to an empty block with syntax sugar."""
block = pulse.ScheduleBlock()
block += pulse.Play(self.test_waveform0, self.d0)
self.assertEqual(block.blocks[0], pulse.Play(self.test_waveform0, self.d0))
def test_append_an_instruction_to_empty_block_inplace(self):
"""Test append instructions to an empty block with inplace."""
block = pulse.ScheduleBlock()
block.append(pulse.Play(self.test_waveform0, self.d0), inplace=True)
self.assertEqual(block.blocks[0], pulse.Play(self.test_waveform0, self.d0))
def test_append_a_block_to_empty_block(self):
"""Test append another ScheduleBlock to empty block."""
block = pulse.ScheduleBlock()
block.append(pulse.Play(self.test_waveform0, self.d0), inplace=True)
block_main = pulse.ScheduleBlock()
block_main = block_main.append(block)
self.assertEqual(block_main.blocks[0], block)
def test_append_an_instruction_to_block(self):
"""Test append instructions to a non-empty block."""
block = pulse.ScheduleBlock()
block = block.append(pulse.Delay(100, self.d0))
block = block.append(pulse.Delay(100, self.d0))
self.assertEqual(len(block.blocks), 2)
def test_append_an_instruction_to_block_inplace(self):
"""Test append instructions to a non-empty block with inplace."""
block = pulse.ScheduleBlock()
block = block.append(pulse.Delay(100, self.d0))
block.append(pulse.Delay(100, self.d0), inplace=True)
self.assertEqual(len(block.blocks), 2)
def test_duration(self):
"""Test if correct duration is returned with implicit scheduling."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
self.assertEqual(block.duration, 350)
def test_channels(self):
"""Test if all channels are returned."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
self.assertEqual(len(block.channels), 2)
def test_instructions(self):
"""Test if all instructions are returned."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
self.assertEqual(block.blocks, tuple(self.test_blocks))
def test_channel_duraction(self):
"""Test if correct durations is calculated for each channel."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
self.assertEqual(block.ch_duration(self.d0), 350)
self.assertEqual(block.ch_duration(self.d1), 200)
def test_cannot_append_schedule(self):
"""Test schedule cannot be appended. Schedule should be input as Call instruction."""
block = pulse.ScheduleBlock()
sched = pulse.Schedule()
sched += pulse.Delay(10, self.d0)
with self.assertRaises(PulseError):
block.append(sched)
def test_replace(self):
"""Test replacing specific instruction."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
replaced = pulse.Play(pulse.Constant(300, 0.1), self.d1)
target = pulse.Delay(50, self.d0)
block_replaced = block.replace(target, replaced, inplace=False)
# original schedule is not destroyed
self.assertListEqual(list(block.blocks), self.test_blocks)
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1))
ref_sched = ref_sched.insert(200, replaced)
ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform1, self.d0))
self.assertScheduleEqual(block_replaced, ref_sched)
def test_replace_inplace(self):
"""Test replacing specific instruction with inplace."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
replaced = pulse.Play(pulse.Constant(300, 0.1), self.d1)
target = pulse.Delay(50, self.d0)
block.replace(target, replaced, inplace=True)
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1))
ref_sched = ref_sched.insert(200, replaced)
ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform1, self.d0))
self.assertScheduleEqual(block, ref_sched)
def test_replace_block_by_instruction(self):
"""Test replacing block with instruction."""
sub_block1 = pulse.ScheduleBlock()
sub_block1 = sub_block1.append(pulse.Delay(50, self.d0))
sub_block1 = sub_block1.append(pulse.Play(self.test_waveform0, self.d0))
sub_block2 = pulse.ScheduleBlock()
sub_block2 = sub_block2.append(pulse.Delay(50, self.d0))
sub_block2 = sub_block2.append(pulse.Play(self.test_waveform1, self.d1))
main_block = pulse.ScheduleBlock()
main_block = main_block.append(pulse.Delay(50, self.d0))
main_block = main_block.append(pulse.Play(self.test_waveform0, self.d0))
main_block = main_block.append(sub_block1)
main_block = main_block.append(sub_block2)
main_block = main_block.append(pulse.Play(self.test_waveform0, self.d1))
replaced = main_block.replace(sub_block1, pulse.Delay(100, self.d0))
ref_blocks = [
pulse.Delay(50, self.d0),
pulse.Play(self.test_waveform0, self.d0),
pulse.Delay(100, self.d0),
sub_block2,
pulse.Play(self.test_waveform0, self.d1),
]
self.assertListEqual(list(replaced.blocks), ref_blocks)
def test_replace_instruction_by_block(self):
"""Test replacing instruction with block."""
sub_block1 = pulse.ScheduleBlock()
sub_block1 = sub_block1.append(pulse.Delay(50, self.d0))
sub_block1 = sub_block1.append(pulse.Play(self.test_waveform0, self.d0))
sub_block2 = pulse.ScheduleBlock()
sub_block2 = sub_block2.append(pulse.Delay(50, self.d0))
sub_block2 = sub_block2.append(pulse.Play(self.test_waveform1, self.d1))
main_block = pulse.ScheduleBlock()
main_block = main_block.append(pulse.Delay(50, self.d0))
main_block = main_block.append(pulse.Play(self.test_waveform0, self.d0))
main_block = main_block.append(pulse.Delay(100, self.d0))
main_block = main_block.append(sub_block2)
main_block = main_block.append(pulse.Play(self.test_waveform0, self.d1))
replaced = main_block.replace(pulse.Delay(100, self.d0), sub_block1)
ref_blocks = [
pulse.Delay(50, self.d0),
pulse.Play(self.test_waveform0, self.d0),
sub_block1,
sub_block2,
pulse.Play(self.test_waveform0, self.d1),
]
self.assertListEqual(list(replaced.blocks), ref_blocks)
def test_len(self):
"""Test __len__ method"""
block = pulse.ScheduleBlock()
self.assertEqual(len(block), 0)
for j in range(1, 10):
block = block.append(pulse.Delay(10, self.d0))
self.assertEqual(len(block), j)
def test_inherit_from(self):
"""Test creating schedule with another schedule."""
ref_metadata = {"test": "value"}
ref_name = "test"
base_sched = pulse.ScheduleBlock(name=ref_name, metadata=ref_metadata)
new_sched = pulse.ScheduleBlock.initialize_from(base_sched)
self.assertEqual(new_sched.name, ref_name)
self.assertDictEqual(new_sched.metadata, ref_metadata)
@unittest.skipUnless(has_aer(), "qiskit-aer doesn't appear to be installed.")
def test_execute_block(self):
"""Test executing a ScheduleBlock on a Pulse backend"""
with pulse.build(name="test_block") as sched_block:
pulse.play(pulse.Constant(160, 1.0), pulse.DriveChannel(0))
pulse.acquire(50, pulse.AcquireChannel(0), pulse.MemorySlot(0))
backend = FakeArmonk()
# TODO: Rewrite test to simulate with qiskit-dynamics
with self.assertWarns(DeprecationWarning):
test_result = backend.run(sched_block).result()
self.assertDictEqual(test_result.get_counts(), {"0": 1024})
class TestBlockEquality(BaseTestBlock):
"""Test equality of blocks.
Equality of instruction ordering is compared on DAG representation.
This should be tested for each transform.
"""
def test_different_channels(self):
"""Test equality is False if different channels."""
block1 = pulse.ScheduleBlock()
block1 += pulse.Delay(10, self.d0)
block2 = pulse.ScheduleBlock()
block2 += pulse.Delay(10, self.d1)
self.assertNotEqual(block1, block2)
def test_different_transform(self):
"""Test equality is False if different transforms."""
block1 = pulse.ScheduleBlock(alignment_context=self.left_context)
block1 += pulse.Delay(10, self.d0)
block2 = pulse.ScheduleBlock(alignment_context=self.right_context)
block2 += pulse.Delay(10, self.d0)
self.assertNotEqual(block1, block2)
def test_different_transform_opts(self):
"""Test equality is False if different transform options."""
context1 = transforms.AlignEquispaced(duration=100)
context2 = transforms.AlignEquispaced(duration=500)
block1 = pulse.ScheduleBlock(alignment_context=context1)
block1 += pulse.Delay(10, self.d0)
block2 = pulse.ScheduleBlock(alignment_context=context2)
block2 += pulse.Delay(10, self.d0)
self.assertNotEqual(block1, block2)
def test_instruction_out_of_order_left(self):
"""Test equality is True if two blocks have instructions in different order."""
block1 = pulse.ScheduleBlock(alignment_context=self.left_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.left_context)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertEqual(block1, block2)
def test_instruction_in_order_left(self):
"""Test equality is True if two blocks have instructions in same order."""
block1 = pulse.ScheduleBlock(alignment_context=self.left_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.left_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertEqual(block1, block2)
def test_instruction_out_of_order_right(self):
"""Test equality is True if two blocks have instructions in different order."""
block1 = pulse.ScheduleBlock(alignment_context=self.right_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.right_context)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertEqual(block1, block2)
def test_instruction_in_order_right(self):
"""Test equality is True if two blocks have instructions in same order."""
block1 = pulse.ScheduleBlock(alignment_context=self.right_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.right_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertEqual(block1, block2)
def test_instruction_out_of_order_sequential(self):
"""Test equality is False if two blocks have instructions in different order."""
block1 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertNotEqual(block1, block2)
def test_instruction_out_of_order_sequential_more(self):
"""Test equality is False if three blocks have instructions in different order.
This could detect a particular bug as discussed in this thread:
https://github.com/Qiskit/qiskit-terra/pull/8005#discussion_r966191018
"""
block1 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertNotEqual(block1, block2)
def test_instruction_in_order_sequential(self):
"""Test equality is True if two blocks have instructions in same order."""
block1 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertEqual(block1, block2)
def test_instruction_out_of_order_equispaced(self):
"""Test equality is False if two blocks have instructions in different order."""
block1 = pulse.ScheduleBlock(alignment_context=self.equispaced_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.equispaced_context)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertNotEqual(block1, block2)
def test_instruction_in_order_equispaced(self):
"""Test equality is True if two blocks have instructions in same order."""
block1 = pulse.ScheduleBlock(alignment_context=self.equispaced_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.equispaced_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertEqual(block1, block2)
def test_instruction_out_of_order_func(self):
"""Test equality is False if two blocks have instructions in different order."""
block1 = pulse.ScheduleBlock(alignment_context=self.func_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.func_context)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertNotEqual(block1, block2)
def test_instruction_in_order_func(self):
"""Test equality is True if two blocks have instructions in same order."""
block1 = pulse.ScheduleBlock(alignment_context=self.func_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.func_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertEqual(block1, block2)
def test_instrution_in_oder_but_different_node(self):
"""Test equality is False if two blocks have different instructions."""
block1 = pulse.ScheduleBlock(alignment_context=self.left_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform1, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.left_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertNotEqual(block1, block2)
def test_instruction_out_of_order_complex_equal(self):
"""Test complex schedule equality can be correctly evaluated."""
block1_a = pulse.ScheduleBlock(alignment_context=self.left_context)
block1_a += pulse.Delay(10, self.d0)
block1_a += pulse.Play(self.test_waveform1, self.d1)
block1_a += pulse.Play(self.test_waveform0, self.d0)
block1_b = pulse.ScheduleBlock(alignment_context=self.left_context)
block1_b += pulse.Play(self.test_waveform1, self.d1)
block1_b += pulse.Delay(10, self.d0)
block1_b += pulse.Play(self.test_waveform0, self.d0)
block2_a = pulse.ScheduleBlock(alignment_context=self.right_context)
block2_a += block1_a
block2_a += block1_b
block2_a += block1_a
block2_b = pulse.ScheduleBlock(alignment_context=self.right_context)
block2_b += block1_a
block2_b += block1_a
block2_b += block1_b
self.assertEqual(block2_a, block2_b)
def test_instruction_out_of_order_complex_not_equal(self):
"""Test complex schedule equality can be correctly evaluated."""
block1_a = pulse.ScheduleBlock(alignment_context=self.left_context)
block1_a += pulse.Play(self.test_waveform0, self.d0)
block1_a += pulse.Play(self.test_waveform1, self.d1)
block1_a += pulse.Delay(10, self.d0)
block1_b = pulse.ScheduleBlock(alignment_context=self.left_context)
block1_b += pulse.Play(self.test_waveform1, self.d1)
block1_b += pulse.Delay(10, self.d0)
block1_b += pulse.Play(self.test_waveform0, self.d0)
block2_a = pulse.ScheduleBlock(alignment_context=self.right_context)
block2_a += block1_a
block2_a += block1_b
block2_a += block1_a
block2_b = pulse.ScheduleBlock(alignment_context=self.right_context)
block2_b += block1_a
block2_b += block1_a
block2_b += block1_b
self.assertNotEqual(block2_a, block2_b)
class TestParametrizedBlockOperation(BaseTestBlock):
"""Test fundamental operation with parametrization."""
def setUp(self):
super().setUp()
self.amp0 = circuit.Parameter("amp0")
self.amp1 = circuit.Parameter("amp1")
self.dur0 = circuit.Parameter("dur0")
self.dur1 = circuit.Parameter("dur1")
self.test_par_waveform0 = pulse.Constant(self.dur0, self.amp0)
self.test_par_waveform1 = pulse.Constant(self.dur1, self.amp1)
def test_report_parameter_assignment(self):
"""Test duration assignment check."""
block = pulse.ScheduleBlock()
block += pulse.Play(self.test_par_waveform0, self.d0)
# check parameter evaluation mechanism
self.assertTrue(block.is_parameterized())
self.assertFalse(block.is_schedulable())
# assign duration
block = block.assign_parameters({self.dur0: 200})
self.assertTrue(block.is_parameterized())
self.assertTrue(block.is_schedulable())
def test_cannot_get_duration_if_not_assigned(self):
"""Test raise error when duration is not assigned."""
block = pulse.ScheduleBlock()
block += pulse.Play(self.test_par_waveform0, self.d0)
with self.assertRaises(PulseError):
# pylint: disable=pointless-statement
block.duration
def test_get_assigend_duration(self):
"""Test duration is correctly evaluated."""
block = pulse.ScheduleBlock()
block += pulse.Play(self.test_par_waveform0, self.d0)
block += pulse.Play(self.test_waveform0, self.d0)
block = block.assign_parameters({self.dur0: 300})
self.assertEqual(block.duration, 400)
def test_nested_parametrized_instructions(self):
"""Test parameters of nested schedule can be assigned."""
test_waveform = pulse.Constant(100, self.amp0)
param_sched = pulse.Schedule(pulse.Play(test_waveform, self.d0))
with self.assertWarns(DeprecationWarning):
call_inst = pulse.instructions.Call(param_sched)
sub_block = pulse.ScheduleBlock()
sub_block += call_inst
block = pulse.ScheduleBlock()
block += sub_block
self.assertTrue(block.is_parameterized())
# assign durations
block = block.assign_parameters({self.amp0: 0.1})
self.assertFalse(block.is_parameterized())
def test_equality_of_parametrized_channels(self):
"""Test check equality of blocks involving parametrized channels."""
par_ch = circuit.Parameter("ch")
block1 = pulse.ScheduleBlock(alignment_context=self.left_context)
block1 += pulse.Play(self.test_waveform0, pulse.DriveChannel(par_ch))
block1 += pulse.Play(self.test_par_waveform0, self.d0)
block2 = pulse.ScheduleBlock(alignment_context=self.left_context)
block2 += pulse.Play(self.test_par_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, pulse.DriveChannel(par_ch))
self.assertEqual(block1, block2)
block1_assigned = block1.assign_parameters({par_ch: 1})
block2_assigned = block2.assign_parameters({par_ch: 1})
self.assertEqual(block1_assigned, block2_assigned)
def test_replace_parametrized_instruction(self):
"""Test parametrized instruction can updated with parameter table."""
block = pulse.ScheduleBlock()
block += pulse.Play(self.test_par_waveform0, self.d0)
block += pulse.Delay(100, self.d0)
block += pulse.Play(self.test_waveform0, self.d0)
replaced = block.replace(
pulse.Play(self.test_par_waveform0, self.d0),
pulse.Play(self.test_par_waveform1, self.d0),
)
self.assertTrue(replaced.is_parameterized())
# check assign parameters
replaced_assigned = replaced.assign_parameters({self.dur1: 100, self.amp1: 0.1})
self.assertFalse(replaced_assigned.is_parameterized())
def test_parametrized_context(self):
"""Test parametrize context parameter."""
duration = circuit.Parameter("dur")
param_context = transforms.AlignEquispaced(duration=duration)
block = pulse.ScheduleBlock(alignment_context=param_context)
block += pulse.Delay(10, self.d0)
block += pulse.Delay(10, self.d0)
block += pulse.Delay(10, self.d0)
block += pulse.Delay(10, self.d0)
self.assertTrue(block.is_parameterized())
self.assertFalse(block.is_schedulable())
block.assign_parameters({duration: 100}, inplace=True)
self.assertFalse(block.is_parameterized())
self.assertTrue(block.is_schedulable())
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Delay(10, self.d0))
ref_sched = ref_sched.insert(30, pulse.Delay(10, self.d0))
ref_sched = ref_sched.insert(60, pulse.Delay(10, self.d0))
ref_sched = ref_sched.insert(90, pulse.Delay(10, self.d0))
self.assertScheduleEqual(block, ref_sched)
class TestBlockFilter(BaseTestBlock):
"""Test ScheduleBlock filtering methods."""
def test_filter_channels(self):
"""Test filtering over channels."""
with pulse.build() as blk:
pulse.play(self.test_waveform0, self.d0)
pulse.delay(10, self.d0)
pulse.play(self.test_waveform1, self.d1)
filtered_blk = self._filter_and_test_consistency(blk, channels=[self.d0])
self.assertEqual(len(filtered_blk.channels), 1)
self.assertTrue(self.d0 in filtered_blk.channels)
with pulse.build() as ref_blk:
pulse.play(self.test_waveform0, self.d0)
pulse.delay(10, self.d0)
self.assertEqual(filtered_blk, ref_blk)
filtered_blk = self._filter_and_test_consistency(blk, channels=[self.d1])
self.assertEqual(len(filtered_blk.channels), 1)
self.assertTrue(self.d1 in filtered_blk.channels)
with pulse.build() as ref_blk:
pulse.play(self.test_waveform1, self.d1)
self.assertEqual(filtered_blk, ref_blk)
filtered_blk = self._filter_and_test_consistency(blk, channels=[self.d0, self.d1])
self.assertEqual(len(filtered_blk.channels), 2)
for ch in [self.d0, self.d1]:
self.assertTrue(ch in filtered_blk.channels)
self.assertEqual(filtered_blk, blk)
def test_filter_channels_nested_block(self):
"""Test filtering over channels in a nested block."""
with pulse.build() as blk:
with pulse.align_sequential():
pulse.play(self.test_waveform0, self.d0)
pulse.delay(5, self.d0)
with pulse.build(self.backend) as cx_blk:
pulse.cx(0, 1)
pulse.call(cx_blk)
for ch in [self.d0, self.d1, pulse.ControlChannel(0)]:
filtered_blk = self._filter_and_test_consistency(blk, channels=[ch])
self.assertEqual(len(filtered_blk.channels), 1)
self.assertTrue(ch in filtered_blk.channels)
def test_filter_inst_types(self):
"""Test filtering on instruction types."""
with pulse.build() as blk:
pulse.acquire(5, pulse.AcquireChannel(0), pulse.MemorySlot(0))
with pulse.build() as blk_internal:
pulse.play(self.test_waveform1, self.d1)
pulse.call(blk_internal)
pulse.reference(name="dummy_reference")
pulse.delay(10, self.d0)
pulse.play(self.test_waveform0, self.d0)
pulse.barrier(self.d0, self.d1, pulse.AcquireChannel(0), pulse.MemorySlot(0))
pulse.set_frequency(10, self.d0)
pulse.shift_frequency(5, self.d1)
pulse.set_phase(3.14 / 4.0, self.d0)
pulse.shift_phase(-3.14 / 2.0, self.d1)
pulse.snapshot(label="dummy_snapshot")
# test filtering Acquire
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.Acquire])
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.Acquire)
self.assertEqual(len(filtered_blk.channels), 2)
# test filtering Reference
filtered_blk = self._filter_and_test_consistency(
blk, instruction_types=[pulse.instructions.Reference]
)
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.instructions.Reference)
# test filtering Delay
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.Delay])
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.Delay)
self.assertEqual(len(filtered_blk.channels), 1)
# test filtering Play
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.Play])
self.assertEqual(len(filtered_blk.blocks), 2)
self.assertIsInstance(filtered_blk.blocks[0].blocks[0], pulse.Play)
self.assertIsInstance(filtered_blk.blocks[1], pulse.Play)
self.assertEqual(len(filtered_blk.channels), 2)
# test filtering RelativeBarrier
filtered_blk = self._filter_and_test_consistency(
blk, instruction_types=[pulse.instructions.RelativeBarrier]
)
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.instructions.RelativeBarrier)
self.assertEqual(len(filtered_blk.channels), 4)
# test filtering SetFrequency
filtered_blk = self._filter_and_test_consistency(
blk, instruction_types=[pulse.SetFrequency]
)
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.SetFrequency)
self.assertEqual(len(filtered_blk.channels), 1)
# test filtering ShiftFrequency
filtered_blk = self._filter_and_test_consistency(
blk, instruction_types=[pulse.ShiftFrequency]
)
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.ShiftFrequency)
self.assertEqual(len(filtered_blk.channels), 1)
# test filtering SetPhase
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.SetPhase])
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.SetPhase)
self.assertEqual(len(filtered_blk.channels), 1)
# test filtering ShiftPhase
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.ShiftPhase])
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.ShiftPhase)
self.assertEqual(len(filtered_blk.channels), 1)
# test filtering SnapShot
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.Snapshot])
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.Snapshot)
self.assertEqual(len(filtered_blk.channels), 1)
def test_filter_functionals(self):
"""Test functional filtering."""
with pulse.build() as blk:
pulse.play(self.test_waveform0, self.d0, "play0")
pulse.delay(10, self.d0, "delay0")
with pulse.build() as blk_internal:
pulse.play(self.test_waveform1, self.d1, "play1")
pulse.call(blk_internal)
pulse.play(self.test_waveform1, self.d1)
def filter_with_inst_name(inst: pulse.Instruction) -> bool:
try:
if isinstance(inst.name, str):
match_obj = re.search(pattern="play", string=inst.name)
if match_obj is not None:
return True
except AttributeError:
pass
return False
filtered_blk = self._filter_and_test_consistency(blk, filter_with_inst_name)
self.assertEqual(len(filtered_blk.blocks), 2)
self.assertIsInstance(filtered_blk.blocks[0], pulse.Play)
self.assertIsInstance(filtered_blk.blocks[1].blocks[0], pulse.Play)
self.assertEqual(len(filtered_blk.channels), 2)
def test_filter_multiple(self):
"""Test filter composition."""
with pulse.build() as blk:
pulse.play(pulse.Constant(100, 0.1, name="play0"), self.d0)
pulse.delay(10, self.d0, "delay0")
with pulse.build(name="internal_blk") as blk_internal:
pulse.play(pulse.Constant(50, 0.1, name="play1"), self.d0)
pulse.call(blk_internal)
pulse.barrier(self.d0, self.d1)
pulse.play(pulse.Constant(100, 0.1, name="play2"), self.d1)
def filter_with_pulse_name(inst: pulse.Instruction) -> bool:
try:
if isinstance(inst.pulse.name, str):
match_obj = re.search(pattern="play", string=inst.pulse.name)
if match_obj is not None:
return True
except AttributeError:
pass
return False
filtered_blk = self._filter_and_test_consistency(
blk, filter_with_pulse_name, channels=[self.d1], instruction_types=[pulse.Play]
)
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.Play)
self.assertEqual(len(filtered_blk.channels), 1)
def _filter_and_test_consistency(
self, sched_blk: pulse.ScheduleBlock, *args: Any, **kwargs: Any
) -> pulse.ScheduleBlock:
"""
Returns sched_blk.filter(*args, **kwargs),
including a test that sched_blk.filter | sched_blk.exclude == sched_blk
in terms of instructions.
"""
filtered = sched_blk.filter(*args, **kwargs)
excluded = sched_blk.exclude(*args, **kwargs)
def list_instructions(blk: pulse.ScheduleBlock) -> List[pulse.Instruction]:
insts = []
for element in blk.blocks:
if isinstance(element, pulse.ScheduleBlock):
inner_insts = list_instructions(element)
if len(inner_insts) != 0:
insts.extend(inner_insts)
elif isinstance(element, pulse.Instruction):
insts.append(element)
return insts
sum_insts = list_instructions(filtered) + list_instructions(excluded)
ref_insts = list_instructions(sched_blk)
self.assertEqual(len(sum_insts), len(ref_insts))
self.assertTrue(all(inst in ref_insts for inst in sum_insts))
return filtered
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test pulse builder context utilities."""
from math import pi
import numpy as np
from qiskit import circuit, compiler, pulse
from qiskit.pulse import builder, exceptions, macros
from qiskit.pulse.instructions import directives
from qiskit.pulse.transforms import target_qobj_transform
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeOpenPulse2Q
from qiskit.providers.fake_provider.utils.configurable_backend import (
ConfigurableFakeBackend as ConfigurableBackend,
)
from qiskit.pulse import library, instructions
class TestBuilder(QiskitTestCase):
"""Test the pulse builder context."""
def setUp(self):
super().setUp()
self.backend = FakeOpenPulse2Q()
self.configuration = self.backend.configuration()
self.defaults = self.backend.defaults()
self.inst_map = self.defaults.instruction_schedule_map
def assertScheduleEqual(self, program, target):
"""Assert an error when two pulse programs are not equal.
.. note:: Two programs are converted into standard execution format then compared.
"""
self.assertEqual(target_qobj_transform(program), target_qobj_transform(target))
class TestBuilderBase(TestBuilder):
"""Test builder base."""
def test_schedule_supplied(self):
"""Test that schedule is used if it is supplied to the builder."""
d0 = pulse.DriveChannel(0)
with pulse.build(name="reference") as reference:
with pulse.align_sequential():
pulse.delay(10, d0)
with pulse.build(schedule=reference) as schedule:
pass
self.assertScheduleEqual(schedule, reference)
self.assertEqual(schedule.name, "reference")
def test_default_alignment_left(self):
"""Test default left alignment setting."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(0)
with pulse.build(default_alignment="left") as schedule:
pulse.delay(10, d0)
pulse.delay(20, d1)
with pulse.build(self.backend) as reference:
with pulse.align_left():
pulse.delay(10, d0)
pulse.delay(20, d1)
self.assertScheduleEqual(schedule, reference)
def test_default_alignment_right(self):
"""Test default right alignment setting."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(0)
with pulse.build(default_alignment="right") as schedule:
pulse.delay(10, d0)
pulse.delay(20, d1)
with pulse.build() as reference:
with pulse.align_right():
pulse.delay(10, d0)
pulse.delay(20, d1)
self.assertScheduleEqual(schedule, reference)
def test_default_alignment_sequential(self):
"""Test default sequential alignment setting."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(0)
with pulse.build(default_alignment="sequential") as schedule:
pulse.delay(10, d0)
pulse.delay(20, d1)
with pulse.build() as reference:
with pulse.align_sequential():
pulse.delay(10, d0)
pulse.delay(20, d1)
self.assertScheduleEqual(schedule, reference)
class TestContexts(TestBuilder):
"""Test builder contexts."""
def test_align_sequential(self):
"""Test the sequential alignment context."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as schedule:
with pulse.align_sequential():
pulse.delay(3, d0)
pulse.delay(5, d1)
pulse.delay(7, d0)
reference = pulse.Schedule()
# d0
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(8, instructions.Delay(7, d0), inplace=True)
# d1
reference.insert(3, instructions.Delay(5, d1), inplace=True)
self.assertScheduleEqual(schedule, reference)
def test_align_left(self):
"""Test the left alignment context."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
d2 = pulse.DriveChannel(2)
with pulse.build() as schedule:
with pulse.align_left():
pulse.delay(11, d2)
pulse.delay(3, d0)
with pulse.align_left():
pulse.delay(5, d1)
pulse.delay(7, d0)
reference = pulse.Schedule()
# d0
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(3, instructions.Delay(7, d0), inplace=True)
# d1
reference.insert(3, instructions.Delay(5, d1), inplace=True)
# d2
reference.insert(0, instructions.Delay(11, d2), inplace=True)
self.assertScheduleEqual(schedule, reference)
def test_align_right(self):
"""Test the right alignment context."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
d2 = pulse.DriveChannel(2)
with pulse.build() as schedule:
with pulse.align_right():
with pulse.align_right():
pulse.delay(11, d2)
pulse.delay(3, d0)
pulse.delay(13, d0)
pulse.delay(5, d1)
reference = pulse.Schedule()
# d0
reference.insert(8, instructions.Delay(3, d0), inplace=True)
reference.insert(11, instructions.Delay(13, d0), inplace=True)
# d1
reference.insert(19, instructions.Delay(5, d1), inplace=True)
# d2
reference.insert(0, instructions.Delay(11, d2), inplace=True)
self.assertScheduleEqual(schedule, reference)
def test_transpiler_settings(self):
"""Test the transpiler settings context.
Tests that two cx gates are optimized away with higher optimization level.
"""
twice_cx_qc = circuit.QuantumCircuit(2)
twice_cx_qc.cx(0, 1)
twice_cx_qc.cx(0, 1)
with pulse.build(self.backend) as schedule:
with pulse.transpiler_settings(optimization_level=0):
builder.call(twice_cx_qc)
self.assertNotEqual(len(schedule.instructions), 0)
with pulse.build(self.backend) as schedule:
with pulse.transpiler_settings(optimization_level=3):
builder.call(twice_cx_qc)
self.assertEqual(len(schedule.instructions), 0)
def test_scheduler_settings(self):
"""Test the circuit scheduler settings context."""
inst_map = pulse.InstructionScheduleMap()
d0 = pulse.DriveChannel(0)
test_x_sched = pulse.Schedule()
test_x_sched += instructions.Delay(10, d0)
inst_map.add("x", (0,), test_x_sched)
ref_sched = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
ref_sched += pulse.instructions.Call(test_x_sched)
x_qc = circuit.QuantumCircuit(2)
x_qc.x(0)
with pulse.build(backend=self.backend) as schedule:
with pulse.transpiler_settings(basis_gates=["x"]):
with pulse.circuit_scheduler_settings(inst_map=inst_map):
builder.call(x_qc)
self.assertScheduleEqual(schedule, ref_sched)
def test_phase_offset(self):
"""Test the phase offset context."""
d0 = pulse.DriveChannel(0)
with pulse.build() as schedule:
with pulse.phase_offset(3.14, d0):
pulse.delay(10, d0)
reference = pulse.Schedule()
reference += instructions.ShiftPhase(3.14, d0)
reference += instructions.Delay(10, d0)
reference += instructions.ShiftPhase(-3.14, d0)
self.assertScheduleEqual(schedule, reference)
def test_frequency_offset(self):
"""Test the frequency offset context."""
d0 = pulse.DriveChannel(0)
with pulse.build() as schedule:
with pulse.frequency_offset(1e9, d0):
pulse.delay(10, d0)
reference = pulse.Schedule()
reference += instructions.ShiftFrequency(1e9, d0)
reference += instructions.Delay(10, d0)
reference += instructions.ShiftFrequency(-1e9, d0)
self.assertScheduleEqual(schedule, reference)
def test_phase_compensated_frequency_offset(self):
"""Test that the phase offset context properly compensates for phase
accumulation."""
d0 = pulse.DriveChannel(0)
with pulse.build(self.backend) as schedule:
with pulse.frequency_offset(1e9, d0, compensate_phase=True):
pulse.delay(10, d0)
reference = pulse.Schedule()
reference += instructions.ShiftFrequency(1e9, d0)
reference += instructions.Delay(10, d0)
reference += instructions.ShiftPhase(
-2 * np.pi * ((1e9 * 10 * self.configuration.dt) % 1), d0
)
reference += instructions.ShiftFrequency(-1e9, d0)
self.assertScheduleEqual(schedule, reference)
class TestChannels(TestBuilder):
"""Test builder channels."""
def test_drive_channel(self):
"""Text context builder drive channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.drive_channel(0), pulse.DriveChannel(0))
def test_measure_channel(self):
"""Text context builder measure channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.measure_channel(0), pulse.MeasureChannel(0))
def test_acquire_channel(self):
"""Text context builder acquire channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.acquire_channel(0), pulse.AcquireChannel(0))
def test_control_channel(self):
"""Text context builder control channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.control_channels(0, 1)[0], pulse.ControlChannel(0))
class TestInstructions(TestBuilder):
"""Test builder instructions."""
def test_delay(self):
"""Test delay instruction."""
d0 = pulse.DriveChannel(0)
with pulse.build() as schedule:
pulse.delay(10, d0)
reference = pulse.Schedule()
reference += instructions.Delay(10, d0)
self.assertScheduleEqual(schedule, reference)
def test_play_parametric_pulse(self):
"""Test play instruction with parametric pulse."""
d0 = pulse.DriveChannel(0)
test_pulse = library.Constant(10, 1.0)
with pulse.build() as schedule:
pulse.play(test_pulse, d0)
reference = pulse.Schedule()
reference += instructions.Play(test_pulse, d0)
self.assertScheduleEqual(schedule, reference)
def test_play_sample_pulse(self):
"""Test play instruction with sample pulse."""
d0 = pulse.DriveChannel(0)
test_pulse = library.Waveform([0.0, 0.0])
with pulse.build() as schedule:
pulse.play(test_pulse, d0)
reference = pulse.Schedule()
reference += instructions.Play(test_pulse, d0)
self.assertScheduleEqual(schedule, reference)
def test_play_array_pulse(self):
"""Test play instruction on an array directly."""
d0 = pulse.DriveChannel(0)
test_array = np.array([0.0, 0.0], dtype=np.complex_)
with pulse.build() as schedule:
pulse.play(test_array, d0)
reference = pulse.Schedule()
test_pulse = pulse.Waveform(test_array)
reference += instructions.Play(test_pulse, d0)
self.assertScheduleEqual(schedule, reference)
def test_play_name_argument(self):
"""Test name argument for play instruction."""
d0 = pulse.DriveChannel(0)
test_pulse = library.Constant(10, 1.0)
with pulse.build() as schedule:
pulse.play(test_pulse, channel=d0, name="new_name")
self.assertEqual(schedule.instructions[0][1].name, "new_name")
def test_acquire_memory_slot(self):
"""Test acquire instruction into memory slot."""
acquire0 = pulse.AcquireChannel(0)
mem0 = pulse.MemorySlot(0)
with pulse.build() as schedule:
pulse.acquire(10, acquire0, mem0)
reference = pulse.Schedule()
reference += pulse.Acquire(10, acquire0, mem_slot=mem0)
self.assertScheduleEqual(schedule, reference)
def test_acquire_register_slot(self):
"""Test acquire instruction into register slot."""
acquire0 = pulse.AcquireChannel(0)
reg0 = pulse.RegisterSlot(0)
with pulse.build() as schedule:
pulse.acquire(10, acquire0, reg0)
reference = pulse.Schedule()
reference += pulse.Acquire(10, acquire0, reg_slot=reg0)
self.assertScheduleEqual(schedule, reference)
def test_acquire_qubit(self):
"""Test acquire instruction on qubit."""
acquire0 = pulse.AcquireChannel(0)
mem0 = pulse.MemorySlot(0)
with pulse.build() as schedule:
pulse.acquire(10, 0, mem0)
reference = pulse.Schedule()
reference += pulse.Acquire(10, acquire0, mem_slot=mem0)
self.assertScheduleEqual(schedule, reference)
def test_instruction_name_argument(self):
"""Test setting the name of an instruction."""
d0 = pulse.DriveChannel(0)
for instruction_method in [
pulse.delay,
pulse.set_frequency,
pulse.set_phase,
pulse.shift_frequency,
pulse.shift_phase,
]:
with pulse.build() as schedule:
instruction_method(0, d0, name="instruction_name")
self.assertEqual(schedule.instructions[0][1].name, "instruction_name")
def test_set_frequency(self):
"""Test set frequency instruction."""
d0 = pulse.DriveChannel(0)
with pulse.build() as schedule:
pulse.set_frequency(1e9, d0)
reference = pulse.Schedule()
reference += instructions.SetFrequency(1e9, d0)
self.assertScheduleEqual(schedule, reference)
def test_shift_frequency(self):
"""Test shift frequency instruction."""
d0 = pulse.DriveChannel(0)
with pulse.build() as schedule:
pulse.shift_frequency(0.1e9, d0)
reference = pulse.Schedule()
reference += instructions.ShiftFrequency(0.1e9, d0)
self.assertScheduleEqual(schedule, reference)
def test_set_phase(self):
"""Test set phase instruction."""
d0 = pulse.DriveChannel(0)
with pulse.build() as schedule:
pulse.set_phase(3.14, d0)
reference = pulse.Schedule()
reference += instructions.SetPhase(3.14, d0)
self.assertScheduleEqual(schedule, reference)
def test_shift_phase(self):
"""Test shift phase instruction."""
d0 = pulse.DriveChannel(0)
with pulse.build() as schedule:
pulse.shift_phase(3.14, d0)
reference = pulse.Schedule()
reference += instructions.ShiftPhase(3.14, d0)
self.assertScheduleEqual(schedule, reference)
def test_snapshot(self):
"""Test snapshot instruction."""
with pulse.build() as schedule:
pulse.snapshot("test", "state")
reference = pulse.Schedule()
reference += instructions.Snapshot("test", "state")
self.assertScheduleEqual(schedule, reference)
class TestDirectives(TestBuilder):
"""Test builder directives."""
def test_barrier_with_align_right(self):
"""Test barrier directive with right alignment context."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
d2 = pulse.DriveChannel(2)
with pulse.build() as schedule:
with pulse.align_right():
pulse.delay(3, d0)
pulse.barrier(d0, d1, d2)
pulse.delay(11, d2)
with pulse.align_right():
pulse.delay(5, d1)
pulse.delay(7, d0)
reference = pulse.Schedule()
# d0
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(7, instructions.Delay(7, d0), inplace=True)
# d1
reference.insert(9, instructions.Delay(5, d1), inplace=True)
# d2
reference.insert(3, instructions.Delay(11, d2), inplace=True)
self.assertScheduleEqual(schedule, reference)
def test_barrier_with_align_left(self):
"""Test barrier directive with left alignment context."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
d2 = pulse.DriveChannel(2)
with pulse.build() as schedule:
with pulse.align_left():
pulse.delay(3, d0)
pulse.barrier(d0, d1, d2)
pulse.delay(11, d2)
with pulse.align_left():
pulse.delay(5, d1)
pulse.delay(7, d0)
reference = pulse.Schedule()
# d0
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(3, instructions.Delay(7, d0), inplace=True)
# d1
reference.insert(3, instructions.Delay(5, d1), inplace=True)
# d2
reference.insert(3, instructions.Delay(11, d2), inplace=True)
self.assertScheduleEqual(schedule, reference)
def test_barrier_on_qubits(self):
"""Test barrier directive on qubits."""
with pulse.build(self.backend) as schedule:
pulse.barrier(0, 1)
reference = pulse.ScheduleBlock()
reference += directives.RelativeBarrier(
pulse.DriveChannel(0),
pulse.DriveChannel(1),
pulse.MeasureChannel(0),
pulse.MeasureChannel(1),
pulse.ControlChannel(0),
pulse.ControlChannel(1),
pulse.AcquireChannel(0),
pulse.AcquireChannel(1),
)
self.assertEqual(schedule, reference)
def test_trivial_barrier(self):
"""Test that trivial barrier is not added."""
with pulse.build() as schedule:
pulse.barrier(pulse.DriveChannel(0))
self.assertEqual(schedule, pulse.ScheduleBlock())
class TestUtilities(TestBuilder):
"""Test builder utilities."""
def test_active_backend(self):
"""Test getting active builder backend."""
with pulse.build(self.backend):
self.assertEqual(pulse.active_backend(), self.backend)
def test_append_schedule(self):
"""Test appending a schedule to the active builder."""
d0 = pulse.DriveChannel(0)
reference = pulse.Schedule()
reference += instructions.Delay(10, d0)
with pulse.build() as schedule:
builder.call(reference)
self.assertScheduleEqual(schedule, reference)
def test_append_instruction(self):
"""Test appending an instruction to the active builder."""
d0 = pulse.DriveChannel(0)
instruction = instructions.Delay(10, d0)
with pulse.build() as schedule:
builder.append_instruction(instruction)
self.assertScheduleEqual(schedule, (0, instruction))
def test_qubit_channels(self):
"""Test getting the qubit channels of the active builder's backend."""
with pulse.build(self.backend):
qubit_channels = pulse.qubit_channels(0)
self.assertEqual(
qubit_channels,
{
pulse.DriveChannel(0),
pulse.MeasureChannel(0),
pulse.AcquireChannel(0),
pulse.ControlChannel(0),
pulse.ControlChannel(1),
},
)
def test_active_transpiler_settings(self):
"""Test setting settings of active builder's transpiler."""
with pulse.build(self.backend):
self.assertFalse(pulse.active_transpiler_settings())
with pulse.transpiler_settings(test_setting=1):
self.assertEqual(pulse.active_transpiler_settings()["test_setting"], 1)
def test_active_circuit_scheduler_settings(self):
"""Test setting settings of active builder's circuit scheduler."""
with pulse.build(self.backend):
self.assertFalse(pulse.active_circuit_scheduler_settings())
with pulse.circuit_scheduler_settings(test_setting=1):
self.assertEqual(pulse.active_circuit_scheduler_settings()["test_setting"], 1)
def test_num_qubits(self):
"""Test builder utility to get number of qubits."""
with pulse.build(self.backend):
self.assertEqual(pulse.num_qubits(), 2)
def test_samples_to_seconds(self):
"""Test samples to time"""
config = self.backend.configuration()
config.dt = 0.1
with pulse.build(self.backend):
time = pulse.samples_to_seconds(100)
self.assertTrue(isinstance(time, float))
self.assertEqual(pulse.samples_to_seconds(100), 10)
def test_samples_to_seconds_array(self):
"""Test samples to time (array format)."""
config = self.backend.configuration()
config.dt = 0.1
with pulse.build(self.backend):
samples = np.array([100, 200, 300])
times = pulse.samples_to_seconds(samples)
self.assertTrue(np.issubdtype(times.dtype, np.floating))
np.testing.assert_allclose(times, np.array([10, 20, 30]))
def test_seconds_to_samples(self):
"""Test time to samples"""
config = self.backend.configuration()
config.dt = 0.1
with pulse.build(self.backend):
samples = pulse.seconds_to_samples(10)
self.assertTrue(isinstance(samples, int))
self.assertEqual(pulse.seconds_to_samples(10), 100)
def test_seconds_to_samples_array(self):
"""Test time to samples (array format)."""
config = self.backend.configuration()
config.dt = 0.1
with pulse.build(self.backend):
times = np.array([10, 20, 30])
samples = pulse.seconds_to_samples(times)
self.assertTrue(np.issubdtype(samples.dtype, np.integer))
np.testing.assert_allclose(pulse.seconds_to_samples(times), np.array([100, 200, 300]))
class TestMacros(TestBuilder):
"""Test builder macros."""
def test_macro(self):
"""Test builder macro decorator."""
@pulse.macro
def nested(a):
pulse.play(pulse.Gaussian(100, a, 20), pulse.drive_channel(0))
return a * 2
@pulse.macro
def test():
pulse.play(pulse.Constant(100, 1.0), pulse.drive_channel(0))
output = nested(0.5)
return output
with pulse.build(self.backend) as schedule:
output = test()
self.assertEqual(output, 0.5 * 2)
reference = pulse.Schedule()
reference += pulse.Play(pulse.Constant(100, 1.0), pulse.DriveChannel(0))
reference += pulse.Play(pulse.Gaussian(100, 0.5, 20), pulse.DriveChannel(0))
self.assertScheduleEqual(schedule, reference)
def test_measure(self):
"""Test utility function - measure."""
with pulse.build(self.backend) as schedule:
reg = pulse.measure(0)
self.assertEqual(reg, pulse.MemorySlot(0))
reference = macros.measure(
qubits=[0], inst_map=self.inst_map, meas_map=self.configuration.meas_map
)
self.assertScheduleEqual(schedule, reference)
def test_measure_multi_qubits(self):
"""Test utility function - measure with multi qubits."""
with pulse.build(self.backend) as schedule:
regs = pulse.measure([0, 1])
self.assertListEqual(regs, [pulse.MemorySlot(0), pulse.MemorySlot(1)])
reference = macros.measure(
qubits=[0, 1], inst_map=self.inst_map, meas_map=self.configuration.meas_map
)
self.assertScheduleEqual(schedule, reference)
def test_measure_all(self):
"""Test utility function - measure."""
with pulse.build(self.backend) as schedule:
regs = pulse.measure_all()
self.assertEqual(regs, [pulse.MemorySlot(0), pulse.MemorySlot(1)])
reference = macros.measure_all(self.backend)
self.assertScheduleEqual(schedule, reference)
backend_100q = ConfigurableBackend("100q", 100)
with pulse.build(backend_100q) as schedule:
regs = pulse.measure_all()
reference = backend_100q.defaults().instruction_schedule_map.get(
"measure", list(range(100))
)
self.assertScheduleEqual(schedule, reference)
def test_delay_qubit(self):
"""Test delaying on a qubit macro."""
with pulse.build(self.backend) as schedule:
pulse.delay_qubits(10, 0)
d0 = pulse.DriveChannel(0)
m0 = pulse.MeasureChannel(0)
a0 = pulse.AcquireChannel(0)
u0 = pulse.ControlChannel(0)
u1 = pulse.ControlChannel(1)
reference = pulse.Schedule()
reference += instructions.Delay(10, d0)
reference += instructions.Delay(10, m0)
reference += instructions.Delay(10, a0)
reference += instructions.Delay(10, u0)
reference += instructions.Delay(10, u1)
self.assertScheduleEqual(schedule, reference)
def test_delay_qubits(self):
"""Test delaying on multiple qubits to make sure we don't insert delays twice."""
with pulse.build(self.backend) as schedule:
pulse.delay_qubits(10, 0, 1)
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
m0 = pulse.MeasureChannel(0)
m1 = pulse.MeasureChannel(1)
a0 = pulse.AcquireChannel(0)
a1 = pulse.AcquireChannel(1)
u0 = pulse.ControlChannel(0)
u1 = pulse.ControlChannel(1)
reference = pulse.Schedule()
reference += instructions.Delay(10, d0)
reference += instructions.Delay(10, d1)
reference += instructions.Delay(10, m0)
reference += instructions.Delay(10, m1)
reference += instructions.Delay(10, a0)
reference += instructions.Delay(10, a1)
reference += instructions.Delay(10, u0)
reference += instructions.Delay(10, u1)
self.assertScheduleEqual(schedule, reference)
class TestGates(TestBuilder):
"""Test builder gates."""
def test_cx(self):
"""Test cx gate."""
with pulse.build(self.backend) as schedule:
pulse.cx(0, 1)
reference_qc = circuit.QuantumCircuit(2)
reference_qc.cx(0, 1)
reference = compiler.schedule(reference_qc, self.backend)
self.assertScheduleEqual(schedule, reference)
def test_u1(self):
"""Test u1 gate."""
with pulse.build(self.backend) as schedule:
with pulse.transpiler_settings(layout_method="trivial"):
pulse.u1(np.pi / 2, 0)
reference_qc = circuit.QuantumCircuit(1)
reference_qc.append(circuit.library.U1Gate(np.pi / 2), [0])
reference = compiler.schedule(reference_qc, self.backend)
self.assertScheduleEqual(schedule, reference)
def test_u2(self):
"""Test u2 gate."""
with pulse.build(self.backend) as schedule:
pulse.u2(np.pi / 2, 0, 0)
reference_qc = circuit.QuantumCircuit(1)
reference_qc.append(circuit.library.U2Gate(np.pi / 2, 0), [0])
reference = compiler.schedule(reference_qc, self.backend)
self.assertScheduleEqual(schedule, reference)
def test_u3(self):
"""Test u3 gate."""
with pulse.build(self.backend) as schedule:
pulse.u3(np.pi / 8, np.pi / 16, np.pi / 4, 0)
reference_qc = circuit.QuantumCircuit(1)
reference_qc.append(circuit.library.U3Gate(np.pi / 8, np.pi / 16, np.pi / 4), [0])
reference = compiler.schedule(reference_qc, self.backend)
self.assertScheduleEqual(schedule, reference)
def test_x(self):
"""Test x gate."""
with pulse.build(self.backend) as schedule:
pulse.x(0)
reference_qc = circuit.QuantumCircuit(1)
reference_qc.x(0)
reference_qc = compiler.transpile(reference_qc, self.backend)
reference = compiler.schedule(reference_qc, self.backend)
self.assertScheduleEqual(schedule, reference)
def test_lazy_evaluation_with_transpiler(self):
"""Test that the two cx gates are optimizied away by the transpiler."""
with pulse.build(self.backend) as schedule:
pulse.cx(0, 1)
pulse.cx(0, 1)
reference_qc = circuit.QuantumCircuit(2)
reference = compiler.schedule(reference_qc, self.backend)
self.assertScheduleEqual(schedule, reference)
def test_measure(self):
"""Test pulse measurement macro against circuit measurement and
ensure agreement."""
with pulse.build(self.backend) as schedule:
with pulse.align_sequential():
pulse.x(0)
pulse.measure(0)
reference_qc = circuit.QuantumCircuit(1, 1)
reference_qc.x(0)
reference_qc.measure(0, 0)
reference_qc = compiler.transpile(reference_qc, self.backend)
reference = compiler.schedule(reference_qc, self.backend)
self.assertScheduleEqual(schedule, reference)
def test_backend_require(self):
"""Test that a backend is required to use a gate."""
with self.assertRaises(exceptions.BackendNotSet):
with pulse.build():
pulse.x(0)
class TestBuilderComposition(TestBuilder):
"""Test more sophisticated composite builder examples."""
def test_complex_build(self):
"""Test a general program build with nested contexts,
circuits and macros."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
d2 = pulse.DriveChannel(2)
delay_dur = 30
short_dur = 20
long_dur = 49
with pulse.build(self.backend) as schedule:
with pulse.align_sequential():
pulse.delay(delay_dur, d0)
pulse.u2(0, pi / 2, 1)
with pulse.align_right():
pulse.play(library.Constant(short_dur, 0.1), d1)
pulse.play(library.Constant(long_dur, 0.1), d2)
pulse.u2(0, pi / 2, 1)
with pulse.align_left():
pulse.u2(0, pi / 2, 0)
pulse.u2(0, pi / 2, 1)
pulse.u2(0, pi / 2, 0)
pulse.measure(0)
# prepare and schedule circuits that will be used.
single_u2_qc = circuit.QuantumCircuit(2)
single_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [1])
single_u2_qc = compiler.transpile(single_u2_qc, self.backend)
single_u2_sched = compiler.schedule(single_u2_qc, self.backend)
# sequential context
sequential_reference = pulse.Schedule()
sequential_reference += instructions.Delay(delay_dur, d0)
sequential_reference.insert(delay_dur, single_u2_sched, inplace=True)
# align right
align_right_reference = pulse.Schedule()
align_right_reference += pulse.Play(library.Constant(long_dur, 0.1), d2)
align_right_reference.insert(
long_dur - single_u2_sched.duration, single_u2_sched, inplace=True
)
align_right_reference.insert(
long_dur - single_u2_sched.duration - short_dur,
pulse.Play(library.Constant(short_dur, 0.1), d1),
inplace=True,
)
# align left
triple_u2_qc = circuit.QuantumCircuit(2)
triple_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [0])
triple_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [1])
triple_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [0])
triple_u2_qc = compiler.transpile(triple_u2_qc, self.backend)
align_left_reference = compiler.schedule(triple_u2_qc, self.backend, method="alap")
# measurement
measure_reference = macros.measure(
qubits=[0], inst_map=self.inst_map, meas_map=self.configuration.meas_map
)
reference = pulse.Schedule()
reference += sequential_reference
# Insert so that the long pulse on d2 occurs as early as possible
# without an overval on d1.
insert_time = reference.ch_stop_time(d1) - align_right_reference.ch_start_time(d1)
reference.insert(insert_time, align_right_reference, inplace=True)
reference.insert(reference.ch_stop_time(d0, d1), align_left_reference, inplace=True)
reference += measure_reference
self.assertScheduleEqual(schedule, reference)
class TestSubroutineCall(TestBuilder):
"""Test for calling subroutine."""
def test_call(self):
"""Test calling schedule instruction."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
reference = pulse.Schedule()
reference = reference.insert(10, instructions.Delay(10, d0))
reference += instructions.Delay(20, d1)
ref_sched = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
ref_sched += pulse.instructions.Call(reference)
with pulse.build() as schedule:
with pulse.align_right():
builder.call(reference)
self.assertScheduleEqual(schedule, ref_sched)
with pulse.build() as schedule:
with pulse.align_right():
pulse.call(reference)
self.assertScheduleEqual(schedule, ref_sched)
def test_call_circuit(self):
"""Test calling circuit instruction."""
inst_map = self.inst_map
reference = inst_map.get("u1", (0,), 0.0)
ref_sched = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
ref_sched += pulse.instructions.Call(reference)
u1_qc = circuit.QuantumCircuit(2)
u1_qc.append(circuit.library.U1Gate(0.0), [0])
transpiler_settings = {"optimization_level": 0}
with pulse.build(self.backend, default_transpiler_settings=transpiler_settings) as schedule:
with pulse.align_right():
builder.call(u1_qc)
self.assertScheduleEqual(schedule, ref_sched)
def test_call_circuit_with_cregs(self):
"""Test calling of circuit wiht classical registers."""
qc = circuit.QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
with pulse.build(self.backend) as schedule:
pulse.call(qc)
reference_qc = compiler.transpile(qc, self.backend)
reference = compiler.schedule(reference_qc, self.backend)
ref_sched = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
ref_sched += pulse.instructions.Call(reference)
self.assertScheduleEqual(schedule, ref_sched)
def test_call_gate_and_circuit(self):
"""Test calling circuit with gates."""
h_control = circuit.QuantumCircuit(2)
h_control.h(0)
with pulse.build(self.backend) as schedule:
with pulse.align_sequential():
# this is circuit, a subroutine stored as Call instruction
pulse.call(h_control)
# this is instruction, not subroutine
pulse.cx(0, 1)
# this is macro, not subroutine
pulse.measure([0, 1])
# subroutine
h_reference = compiler.schedule(compiler.transpile(h_control, self.backend), self.backend)
# gate
cx_circ = circuit.QuantumCircuit(2)
cx_circ.cx(0, 1)
cx_reference = compiler.schedule(compiler.transpile(cx_circ, self.backend), self.backend)
# measurement
measure_reference = macros.measure(
qubits=[0, 1], inst_map=self.inst_map, meas_map=self.configuration.meas_map
)
reference = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
reference += pulse.instructions.Call(h_reference)
reference += cx_reference
reference += measure_reference << reference.duration
self.assertScheduleEqual(schedule, reference)
def test_subroutine_not_transpiled(self):
"""Test called circuit is frozen as a subroutine."""
subprogram = circuit.QuantumCircuit(1)
subprogram.x(0)
transpiler_settings = {"optimization_level": 2}
with pulse.build(self.backend, default_transpiler_settings=transpiler_settings) as schedule:
pulse.call(subprogram)
pulse.call(subprogram)
self.assertNotEqual(len(target_qobj_transform(schedule).instructions), 0)
def test_subroutine_not_transformed(self):
"""Test called schedule is not transformed."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
subprogram = pulse.Schedule()
subprogram.insert(0, pulse.Delay(30, d0), inplace=True)
subprogram.insert(10, pulse.Delay(10, d1), inplace=True)
with pulse.build() as target:
with pulse.align_right():
pulse.delay(10, d1)
pulse.call(subprogram)
reference = pulse.Schedule()
reference.insert(0, pulse.Delay(10, d1), inplace=True)
reference.insert(10, pulse.Delay(30, d0), inplace=True)
reference.insert(20, pulse.Delay(10, d1), inplace=True)
self.assertScheduleEqual(target, reference)
def test_deepcopying_subroutine(self):
"""Test if deepcopying the schedule can copy inline subroutine."""
from copy import deepcopy
with pulse.build() as subroutine:
pulse.delay(10, pulse.DriveChannel(0))
with pulse.build() as main_prog:
pulse.call(subroutine)
copied_prog = deepcopy(main_prog)
main_call = main_prog.instructions[0]
copy_call = copied_prog.instructions[0]
self.assertNotEqual(id(main_call), id(copy_call))
def test_call_with_parameters(self):
"""Test call subroutine with parameters."""
amp = circuit.Parameter("amp")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0))
with pulse.build() as main_prog:
pulse.call(subroutine, amp=0.1)
pulse.call(subroutine, amp=0.3)
self.assertEqual(main_prog.is_parameterized(), False)
assigned_sched = target_qobj_transform(main_prog)
play_0 = assigned_sched.instructions[0][1]
play_1 = assigned_sched.instructions[1][1]
self.assertEqual(play_0.pulse.amp, 0.1)
self.assertEqual(play_1.pulse.amp, 0.3)
def test_call_partly_with_parameters(self):
"""Test multiple calls partly with parameters then assign."""
amp = circuit.Parameter("amp")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0))
with pulse.build() as main_prog:
pulse.call(subroutine, amp=0.1)
pulse.call(subroutine)
self.assertEqual(main_prog.is_parameterized(), True)
main_prog.assign_parameters({amp: 0.5})
self.assertEqual(main_prog.is_parameterized(), False)
assigned_sched = target_qobj_transform(main_prog)
play_0 = assigned_sched.instructions[0][1]
play_1 = assigned_sched.instructions[1][1]
self.assertEqual(play_0.pulse.amp, 0.1)
self.assertEqual(play_1.pulse.amp, 0.5)
def test_call_with_not_existing_parameter(self):
"""Test call subroutine with parameter not defined."""
amp = circuit.Parameter("amp1")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0))
with self.assertRaises(exceptions.PulseError):
with pulse.build():
pulse.call(subroutine, amp=0.1)
def test_call_with_common_parameter(self):
"""Test call subroutine with parameter that is defined multiple times."""
amp = circuit.Parameter("amp")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(320, amp, 80), pulse.DriveChannel(0))
with pulse.build() as main_prog:
pulse.call(subroutine, amp=0.1)
assigned_sched = target_qobj_transform(main_prog)
play_0 = assigned_sched.instructions[0][1]
play_1 = assigned_sched.instructions[1][1]
self.assertEqual(play_0.pulse.amp, 0.1)
self.assertEqual(play_1.pulse.amp, 0.1)
def test_call_with_parameter_name_collision(self):
"""Test call subroutine with duplicated parameter names."""
amp1 = circuit.Parameter("amp")
amp2 = circuit.Parameter("amp")
sigma = circuit.Parameter("sigma")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp1, sigma), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, amp2, sigma), pulse.DriveChannel(0))
with pulse.build() as main_prog:
pulse.call(subroutine, value_dict={amp1: 0.1, amp2: 0.2}, sigma=40)
assigned_sched = target_qobj_transform(main_prog)
play_0 = assigned_sched.instructions[0][1]
play_1 = assigned_sched.instructions[1][1]
self.assertEqual(play_0.pulse.amp, 0.1)
self.assertEqual(play_0.pulse.sigma, 40)
self.assertEqual(play_1.pulse.amp, 0.2)
self.assertEqual(play_1.pulse.sigma, 40)
def test_call_subroutine_with_parametrized_duration(self):
"""Test call subroutine containing a parametrized duration."""
dur = circuit.Parameter("dur")
with pulse.build() as subroutine:
pulse.play(pulse.Constant(dur, 0.1), pulse.DriveChannel(0))
pulse.play(pulse.Constant(dur, 0.2), pulse.DriveChannel(0))
with pulse.build() as main:
pulse.call(subroutine)
self.assertEqual(len(main.blocks), 1)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test pulse builder with backendV2 context utilities."""
import numpy as np
from qiskit import circuit, pulse
from qiskit.pulse import builder, macros
from qiskit.pulse.instructions import directives
from qiskit.pulse.transforms import target_qobj_transform
from qiskit.providers.fake_provider import FakeMumbaiV2
from qiskit.pulse import instructions
from qiskit.test import QiskitTestCase
class TestBuilderV2(QiskitTestCase):
"""Test the pulse builder context with backendV2."""
def setUp(self):
super().setUp()
self.backend = FakeMumbaiV2()
def assertScheduleEqual(self, program, target):
"""Assert an error when two pulse programs are not equal.
.. note:: Two programs are converted into standard execution format then compared.
"""
self.assertEqual(target_qobj_transform(program), target_qobj_transform(target))
class TestContextsV2(TestBuilderV2):
"""Test builder contexts."""
def test_transpiler_settings(self):
"""Test the transpiler settings context.
Tests that two cx gates are optimized away with higher optimization level.
"""
twice_cx_qc = circuit.QuantumCircuit(2)
twice_cx_qc.cx(0, 1)
twice_cx_qc.cx(0, 1)
with pulse.build(self.backend) as schedule:
with pulse.transpiler_settings(optimization_level=0):
builder.call(twice_cx_qc)
self.assertNotEqual(len(schedule.instructions), 0)
with pulse.build(self.backend) as schedule:
with pulse.transpiler_settings(optimization_level=3):
builder.call(twice_cx_qc)
self.assertEqual(len(schedule.instructions), 0)
def test_scheduler_settings(self):
"""Test the circuit scheduler settings context."""
inst_map = pulse.InstructionScheduleMap()
d0 = pulse.DriveChannel(0)
test_x_sched = pulse.Schedule()
test_x_sched += instructions.Delay(10, d0)
inst_map.add("x", (0,), test_x_sched)
ref_sched = pulse.Schedule()
ref_sched += pulse.instructions.Call(test_x_sched)
x_qc = circuit.QuantumCircuit(2)
x_qc.x(0)
with pulse.build(backend=self.backend) as schedule:
with pulse.transpiler_settings(basis_gates=["x"]):
with pulse.circuit_scheduler_settings(inst_map=inst_map):
builder.call(x_qc)
self.assertScheduleEqual(schedule, ref_sched)
def test_phase_compensated_frequency_offset(self):
"""Test that the phase offset context properly compensates for phase
accumulation with backendV2."""
d0 = pulse.DriveChannel(0)
with pulse.build(self.backend) as schedule:
with pulse.frequency_offset(1e9, d0, compensate_phase=True):
pulse.delay(10, d0)
reference = pulse.Schedule()
reference += instructions.ShiftFrequency(1e9, d0)
reference += instructions.Delay(10, d0)
reference += instructions.ShiftPhase(
-2 * np.pi * ((1e9 * 10 * self.backend.target.dt) % 1), d0
)
reference += instructions.ShiftFrequency(-1e9, d0)
self.assertScheduleEqual(schedule, reference)
class TestChannelsV2(TestBuilderV2):
"""Test builder channels."""
def test_drive_channel(self):
"""Text context builder drive channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.drive_channel(0), pulse.DriveChannel(0))
def test_measure_channel(self):
"""Text context builder measure channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.measure_channel(0), pulse.MeasureChannel(0))
def test_acquire_channel(self):
"""Text context builder acquire channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.acquire_channel(0), pulse.AcquireChannel(0))
def test_control_channel(self):
"""Text context builder control channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.control_channels(0, 1)[0], pulse.ControlChannel(0))
class TestDirectivesV2(TestBuilderV2):
"""Test builder directives."""
def test_barrier_on_qubits(self):
"""Test barrier directive on qubits with backendV2.
A part of qubits map of Mumbai
0 -- 1 -- 4 --
|
|
2
"""
with pulse.build(self.backend) as schedule:
pulse.barrier(0, 1)
reference = pulse.ScheduleBlock()
reference += directives.RelativeBarrier(
pulse.DriveChannel(0),
pulse.DriveChannel(1),
pulse.MeasureChannel(0),
pulse.MeasureChannel(1),
pulse.ControlChannel(0),
pulse.ControlChannel(1),
pulse.ControlChannel(2),
pulse.ControlChannel(3),
pulse.ControlChannel(4),
pulse.ControlChannel(8),
pulse.AcquireChannel(0),
pulse.AcquireChannel(1),
)
self.assertEqual(schedule, reference)
class TestUtilitiesV2(TestBuilderV2):
"""Test builder utilities."""
def test_active_backend(self):
"""Test getting active builder backend."""
with pulse.build(self.backend):
self.assertEqual(pulse.active_backend(), self.backend)
def test_qubit_channels(self):
"""Test getting the qubit channels of the active builder's backend."""
with pulse.build(self.backend):
qubit_channels = pulse.qubit_channels(0)
self.assertEqual(
qubit_channels,
{
pulse.DriveChannel(0),
pulse.MeasureChannel(0),
pulse.AcquireChannel(0),
pulse.ControlChannel(0),
pulse.ControlChannel(1),
},
)
def test_active_transpiler_settings(self):
"""Test setting settings of active builder's transpiler."""
with pulse.build(self.backend):
self.assertFalse(pulse.active_transpiler_settings())
with pulse.transpiler_settings(test_setting=1):
self.assertEqual(pulse.active_transpiler_settings()["test_setting"], 1)
def test_active_circuit_scheduler_settings(self):
"""Test setting settings of active builder's circuit scheduler."""
with pulse.build(self.backend):
self.assertFalse(pulse.active_circuit_scheduler_settings())
with pulse.circuit_scheduler_settings(test_setting=1):
self.assertEqual(pulse.active_circuit_scheduler_settings()["test_setting"], 1)
def test_num_qubits(self):
"""Test builder utility to get number of qubits with backendV2."""
with pulse.build(self.backend):
self.assertEqual(pulse.num_qubits(), 27)
def test_samples_to_seconds(self):
"""Test samples to time with backendV2"""
target = self.backend.target
target.dt = 0.1
with pulse.build(self.backend):
time = pulse.samples_to_seconds(100)
self.assertTrue(isinstance(time, float))
self.assertEqual(pulse.samples_to_seconds(100), 10)
def test_samples_to_seconds_array(self):
"""Test samples to time (array format) with backendV2."""
target = self.backend.target
target.dt = 0.1
with pulse.build(self.backend):
samples = np.array([100, 200, 300])
times = pulse.samples_to_seconds(samples)
self.assertTrue(np.issubdtype(times.dtype, np.floating))
np.testing.assert_allclose(times, np.array([10, 20, 30]))
def test_seconds_to_samples(self):
"""Test time to samples with backendV2"""
target = self.backend.target
target.dt = 0.1
with pulse.build(self.backend):
samples = pulse.seconds_to_samples(10)
self.assertTrue(isinstance(samples, int))
self.assertEqual(pulse.seconds_to_samples(10), 100)
def test_seconds_to_samples_array(self):
"""Test time to samples (array format) with backendV2."""
target = self.backend.target
target.dt = 0.1
with pulse.build(self.backend):
times = np.array([10, 20, 30])
samples = pulse.seconds_to_samples(times)
self.assertTrue(np.issubdtype(samples.dtype, np.integer))
np.testing.assert_allclose(pulse.seconds_to_samples(times), np.array([100, 200, 300]))
class TestMacrosV2(TestBuilderV2):
"""Test builder macros with backendV2."""
def test_macro(self):
"""Test builder macro decorator."""
@pulse.macro
def nested(a):
pulse.play(pulse.Gaussian(100, a, 20), pulse.drive_channel(0))
return a * 2
@pulse.macro
def test():
pulse.play(pulse.Constant(100, 1.0), pulse.drive_channel(0))
output = nested(0.5)
return output
with pulse.build(self.backend) as schedule:
output = test()
self.assertEqual(output, 0.5 * 2)
reference = pulse.Schedule()
reference += pulse.Play(pulse.Constant(100, 1.0), pulse.DriveChannel(0))
reference += pulse.Play(pulse.Gaussian(100, 0.5, 20), pulse.DriveChannel(0))
self.assertScheduleEqual(schedule, reference)
def test_measure(self):
"""Test utility function - measure with backendV2."""
with pulse.build(self.backend) as schedule:
reg = pulse.measure(0)
self.assertEqual(reg, pulse.MemorySlot(0))
reference = macros.measure(qubits=[0], backend=self.backend, meas_map=self.backend.meas_map)
self.assertScheduleEqual(schedule, reference)
def test_measure_multi_qubits(self):
"""Test utility function - measure with multi qubits with backendV2."""
with pulse.build(self.backend) as schedule:
regs = pulse.measure([0, 1])
self.assertListEqual(regs, [pulse.MemorySlot(0), pulse.MemorySlot(1)])
reference = macros.measure(
qubits=[0, 1], backend=self.backend, meas_map=self.backend.meas_map
)
self.assertScheduleEqual(schedule, reference)
def test_measure_all(self):
"""Test utility function - measure with backendV2.."""
with pulse.build(self.backend) as schedule:
regs = pulse.measure_all()
self.assertEqual(regs, [pulse.MemorySlot(i) for i in range(self.backend.num_qubits)])
reference = macros.measure_all(self.backend)
self.assertScheduleEqual(schedule, reference)
def test_delay_qubit(self):
"""Test delaying on a qubit macro."""
with pulse.build(self.backend) as schedule:
pulse.delay_qubits(10, 0)
d0 = pulse.DriveChannel(0)
m0 = pulse.MeasureChannel(0)
a0 = pulse.AcquireChannel(0)
u0 = pulse.ControlChannel(0)
u1 = pulse.ControlChannel(1)
reference = pulse.Schedule()
reference += instructions.Delay(10, d0)
reference += instructions.Delay(10, m0)
reference += instructions.Delay(10, a0)
reference += instructions.Delay(10, u0)
reference += instructions.Delay(10, u1)
self.assertScheduleEqual(schedule, reference)
def test_delay_qubits(self):
"""Test delaying on multiple qubits with backendV2 to make sure we don't insert delays twice."""
with pulse.build(self.backend) as schedule:
pulse.delay_qubits(10, 0, 1)
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
m0 = pulse.MeasureChannel(0)
m1 = pulse.MeasureChannel(1)
a0 = pulse.AcquireChannel(0)
a1 = pulse.AcquireChannel(1)
u0 = pulse.ControlChannel(0)
u1 = pulse.ControlChannel(1)
u2 = pulse.ControlChannel(2)
u3 = pulse.ControlChannel(3)
u4 = pulse.ControlChannel(4)
u8 = pulse.ControlChannel(8)
reference = pulse.Schedule()
reference += instructions.Delay(10, d0)
reference += instructions.Delay(10, d1)
reference += instructions.Delay(10, m0)
reference += instructions.Delay(10, m1)
reference += instructions.Delay(10, a0)
reference += instructions.Delay(10, a1)
reference += instructions.Delay(10, u0)
reference += instructions.Delay(10, u1)
reference += instructions.Delay(10, u2)
reference += instructions.Delay(10, u3)
reference += instructions.Delay(10, u4)
reference += instructions.Delay(10, u8)
self.assertScheduleEqual(schedule, reference)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Unit tests for pulse instructions."""
import numpy as np
from qiskit import pulse, circuit
from qiskit.pulse import channels, configuration, instructions, library, exceptions
from qiskit.pulse.transforms import inline_subroutines, target_qobj_transform
from qiskit.test import QiskitTestCase
class TestAcquire(QiskitTestCase):
"""Acquisition tests."""
def test_can_construct_valid_acquire_command(self):
"""Test if valid acquire command can be constructed."""
kernel_opts = {"start_window": 0, "stop_window": 10}
kernel = configuration.Kernel(name="boxcar", **kernel_opts)
discriminator_opts = {
"neighborhoods": [{"qubits": 1, "channels": 1}],
"cal": "coloring",
"resample": False,
}
discriminator = configuration.Discriminator(
name="linear_discriminator", **discriminator_opts
)
acq = instructions.Acquire(
10,
channels.AcquireChannel(0),
channels.MemorySlot(0),
kernel=kernel,
discriminator=discriminator,
name="acquire",
)
self.assertEqual(acq.duration, 10)
self.assertEqual(acq.discriminator.name, "linear_discriminator")
self.assertEqual(acq.discriminator.params, discriminator_opts)
self.assertEqual(acq.kernel.name, "boxcar")
self.assertEqual(acq.kernel.params, kernel_opts)
self.assertIsInstance(acq.id, int)
self.assertEqual(acq.name, "acquire")
self.assertEqual(
acq.operands,
(
10,
channels.AcquireChannel(0),
channels.MemorySlot(0),
None,
kernel,
discriminator,
),
)
def test_instructions_hash(self):
"""Test hashing for acquire instruction."""
acq_1 = instructions.Acquire(
10,
channels.AcquireChannel(0),
channels.MemorySlot(0),
name="acquire",
)
acq_2 = instructions.Acquire(
10,
channels.AcquireChannel(0),
channels.MemorySlot(0),
name="acquire",
)
hash_1 = hash(acq_1)
hash_2 = hash(acq_2)
self.assertEqual(hash_1, hash_2)
class TestDelay(QiskitTestCase):
"""Delay tests."""
def test_delay(self):
"""Test delay."""
delay = instructions.Delay(10, channels.DriveChannel(0), name="test_name")
self.assertIsInstance(delay.id, int)
self.assertEqual(delay.name, "test_name")
self.assertEqual(delay.duration, 10)
self.assertIsInstance(delay.duration, int)
self.assertEqual(delay.operands, (10, channels.DriveChannel(0)))
self.assertEqual(delay, instructions.Delay(10, channels.DriveChannel(0)))
self.assertNotEqual(delay, instructions.Delay(11, channels.DriveChannel(1)))
self.assertEqual(repr(delay), "Delay(10, DriveChannel(0), name='test_name')")
# Test numpy int for duration
delay = instructions.Delay(np.int32(10), channels.DriveChannel(0), name="test_name2")
self.assertEqual(delay.duration, 10)
self.assertIsInstance(delay.duration, np.integer)
def test_operator_delay(self):
"""Test Operator(delay)."""
from qiskit.circuit import QuantumCircuit
from qiskit.quantum_info import Operator
circ = QuantumCircuit(1)
circ.delay(10)
op_delay = Operator(circ)
expected = QuantumCircuit(1)
expected.i(0)
op_identity = Operator(expected)
self.assertEqual(op_delay, op_identity)
class TestSetFrequency(QiskitTestCase):
"""Set frequency tests."""
def test_freq(self):
"""Test set frequency basic functionality."""
set_freq = instructions.SetFrequency(4.5e9, channels.DriveChannel(1), name="test")
self.assertIsInstance(set_freq.id, int)
self.assertEqual(set_freq.duration, 0)
self.assertEqual(set_freq.frequency, 4.5e9)
self.assertEqual(set_freq.operands, (4.5e9, channels.DriveChannel(1)))
self.assertEqual(
set_freq, instructions.SetFrequency(4.5e9, channels.DriveChannel(1), name="test")
)
self.assertNotEqual(
set_freq, instructions.SetFrequency(4.5e8, channels.DriveChannel(1), name="test")
)
self.assertEqual(repr(set_freq), "SetFrequency(4500000000.0, DriveChannel(1), name='test')")
def test_freq_non_pulse_channel(self):
"""Test set frequency constructor with illegal channel"""
with self.assertRaises(exceptions.PulseError):
instructions.SetFrequency(4.5e9, channels.RegisterSlot(1), name="test")
def test_parameter_expression(self):
"""Test getting all parameters assigned by expression."""
p1 = circuit.Parameter("P1")
p2 = circuit.Parameter("P2")
expr = p1 + p2
instr = instructions.SetFrequency(expr, channel=channels.DriveChannel(0))
self.assertSetEqual(instr.parameters, {p1, p2})
class TestShiftFrequency(QiskitTestCase):
"""Shift frequency tests."""
def test_shift_freq(self):
"""Test shift frequency basic functionality."""
shift_freq = instructions.ShiftFrequency(4.5e9, channels.DriveChannel(1), name="test")
self.assertIsInstance(shift_freq.id, int)
self.assertEqual(shift_freq.duration, 0)
self.assertEqual(shift_freq.frequency, 4.5e9)
self.assertEqual(shift_freq.operands, (4.5e9, channels.DriveChannel(1)))
self.assertEqual(
shift_freq, instructions.ShiftFrequency(4.5e9, channels.DriveChannel(1), name="test")
)
self.assertNotEqual(
shift_freq, instructions.ShiftFrequency(4.5e8, channels.DriveChannel(1), name="test")
)
self.assertEqual(
repr(shift_freq), "ShiftFrequency(4500000000.0, DriveChannel(1), name='test')"
)
def test_freq_non_pulse_channel(self):
"""Test shift frequency constructor with illegal channel"""
with self.assertRaises(exceptions.PulseError):
instructions.ShiftFrequency(4.5e9, channels.RegisterSlot(1), name="test")
def test_parameter_expression(self):
"""Test getting all parameters assigned by expression."""
p1 = circuit.Parameter("P1")
p2 = circuit.Parameter("P2")
expr = p1 + p2
instr = instructions.ShiftFrequency(expr, channel=channels.DriveChannel(0))
self.assertSetEqual(instr.parameters, {p1, p2})
class TestSetPhase(QiskitTestCase):
"""Test the instruction construction."""
def test_default(self):
"""Test basic SetPhase."""
set_phase = instructions.SetPhase(1.57, channels.DriveChannel(0))
self.assertIsInstance(set_phase.id, int)
self.assertEqual(set_phase.name, None)
self.assertEqual(set_phase.duration, 0)
self.assertEqual(set_phase.phase, 1.57)
self.assertEqual(set_phase.operands, (1.57, channels.DriveChannel(0)))
self.assertEqual(
set_phase, instructions.SetPhase(1.57, channels.DriveChannel(0), name="test")
)
self.assertNotEqual(
set_phase, instructions.SetPhase(1.57j, channels.DriveChannel(0), name="test")
)
self.assertEqual(repr(set_phase), "SetPhase(1.57, DriveChannel(0))")
def test_set_phase_non_pulse_channel(self):
"""Test shift phase constructor with illegal channel"""
with self.assertRaises(exceptions.PulseError):
instructions.SetPhase(1.57, channels.RegisterSlot(1), name="test")
def test_parameter_expression(self):
"""Test getting all parameters assigned by expression."""
p1 = circuit.Parameter("P1")
p2 = circuit.Parameter("P2")
expr = p1 + p2
instr = instructions.SetPhase(expr, channel=channels.DriveChannel(0))
self.assertSetEqual(instr.parameters, {p1, p2})
class TestShiftPhase(QiskitTestCase):
"""Test the instruction construction."""
def test_default(self):
"""Test basic ShiftPhase."""
shift_phase = instructions.ShiftPhase(1.57, channels.DriveChannel(0))
self.assertIsInstance(shift_phase.id, int)
self.assertEqual(shift_phase.name, None)
self.assertEqual(shift_phase.duration, 0)
self.assertEqual(shift_phase.phase, 1.57)
self.assertEqual(shift_phase.operands, (1.57, channels.DriveChannel(0)))
self.assertEqual(
shift_phase, instructions.ShiftPhase(1.57, channels.DriveChannel(0), name="test")
)
self.assertNotEqual(
shift_phase, instructions.ShiftPhase(1.57j, channels.DriveChannel(0), name="test")
)
self.assertEqual(repr(shift_phase), "ShiftPhase(1.57, DriveChannel(0))")
def test_shift_phase_non_pulse_channel(self):
"""Test shift phase constructor with illegal channel"""
with self.assertRaises(exceptions.PulseError):
instructions.ShiftPhase(1.57, channels.RegisterSlot(1), name="test")
def test_parameter_expression(self):
"""Test getting all parameters assigned by expression."""
p1 = circuit.Parameter("P1")
p2 = circuit.Parameter("P2")
expr = p1 + p2
instr = instructions.ShiftPhase(expr, channel=channels.DriveChannel(0))
self.assertSetEqual(instr.parameters, {p1, p2})
class TestSnapshot(QiskitTestCase):
"""Snapshot tests."""
def test_default(self):
"""Test default snapshot."""
snapshot = instructions.Snapshot(label="test_name", snapshot_type="state")
self.assertIsInstance(snapshot.id, int)
self.assertEqual(snapshot.name, "test_name")
self.assertEqual(snapshot.type, "state")
self.assertEqual(snapshot.duration, 0)
self.assertNotEqual(snapshot, instructions.Delay(10, channels.DriveChannel(0)))
self.assertEqual(repr(snapshot), "Snapshot(test_name, state, name='test_name')")
class TestPlay(QiskitTestCase):
"""Play tests."""
def setUp(self):
"""Setup play tests."""
super().setUp()
self.duration = 4
self.pulse_op = library.Waveform([1.0] * self.duration, name="test")
def test_play(self):
"""Test basic play instruction."""
play = instructions.Play(self.pulse_op, channels.DriveChannel(1))
self.assertIsInstance(play.id, int)
self.assertEqual(play.name, self.pulse_op.name)
self.assertEqual(play.duration, self.duration)
self.assertEqual(
repr(play),
"Play(Waveform(array([1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j]), name='test'),"
" DriveChannel(1), name='test')",
)
def test_play_non_pulse_ch_raises(self):
"""Test that play instruction on non-pulse channel raises a pulse error."""
with self.assertRaises(exceptions.PulseError):
instructions.Play(self.pulse_op, channels.AcquireChannel(0))
class TestDirectives(QiskitTestCase):
"""Test pulse directives."""
def test_relative_barrier(self):
"""Test the relative barrier directive."""
a0 = channels.AcquireChannel(0)
d0 = channels.DriveChannel(0)
m0 = channels.MeasureChannel(0)
u0 = channels.ControlChannel(0)
mem0 = channels.MemorySlot(0)
reg0 = channels.RegisterSlot(0)
chans = (a0, d0, m0, u0, mem0, reg0)
name = "barrier"
barrier = instructions.RelativeBarrier(*chans, name=name)
self.assertEqual(barrier.name, name)
self.assertEqual(barrier.duration, 0)
self.assertEqual(barrier.channels, chans)
self.assertEqual(barrier.operands, chans)
class TestCall(QiskitTestCase):
"""Test call instruction."""
def setUp(self):
super().setUp()
with pulse.build() as _subroutine:
pulse.delay(10, pulse.DriveChannel(0))
self.subroutine = _subroutine
self.param1 = circuit.Parameter("amp1")
self.param2 = circuit.Parameter("amp2")
with pulse.build() as _function:
pulse.play(pulse.Gaussian(160, self.param1, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, self.param2, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, self.param1, 40), pulse.DriveChannel(0))
self.function = _function
def test_call(self):
"""Test basic call instruction."""
with self.assertWarns(DeprecationWarning):
call = instructions.Call(subroutine=self.subroutine)
self.assertEqual(call.duration, 10)
self.assertEqual(call.subroutine, self.subroutine)
def test_parameterized_call(self):
"""Test call instruction with parameterized subroutine."""
with self.assertWarns(DeprecationWarning):
call = instructions.Call(subroutine=self.function)
self.assertTrue(call.is_parameterized())
self.assertEqual(len(call.parameters), 2)
def test_assign_parameters_to_call(self):
"""Test create schedule by calling subroutine and assign parameters to it."""
init_dict = {self.param1: 0.1, self.param2: 0.5}
with pulse.build() as test_sched:
pulse.call(self.function)
test_sched = test_sched.assign_parameters(value_dict=init_dict)
test_sched = inline_subroutines(test_sched)
with pulse.build() as ref_sched:
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.5, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
self.assertEqual(target_qobj_transform(test_sched), target_qobj_transform(ref_sched))
def test_call_initialize_with_parameter(self):
"""Test call instruction with parameterized subroutine with initial dict."""
init_dict = {self.param1: 0.1, self.param2: 0.5}
with self.assertWarns(DeprecationWarning):
call = instructions.Call(subroutine=self.function, value_dict=init_dict)
with pulse.build() as ref_sched:
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.5, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
self.assertEqual(
target_qobj_transform(call.assigned_subroutine()), target_qobj_transform(ref_sched)
)
def test_call_subroutine_with_different_parameters(self):
"""Test call subroutines with different parameters in the same schedule."""
init_dict1 = {self.param1: 0.1, self.param2: 0.5}
init_dict2 = {self.param1: 0.3, self.param2: 0.7}
with pulse.build() as test_sched:
pulse.call(self.function, value_dict=init_dict1)
pulse.call(self.function, value_dict=init_dict2)
with pulse.build() as ref_sched:
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.5, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.3, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.7, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.3, 40), pulse.DriveChannel(0))
self.assertEqual(target_qobj_transform(test_sched), target_qobj_transform(ref_sched))
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""Test cases for parameter manager."""
from copy import deepcopy
import numpy as np
from qiskit import pulse
from qiskit.circuit import Parameter
from qiskit.pulse.exceptions import PulseError, UnassignedDurationError
from qiskit.pulse.parameter_manager import ParameterGetter, ParameterSetter
from qiskit.pulse.transforms import AlignEquispaced, AlignLeft, inline_subroutines
from qiskit.test import QiskitTestCase
class ParameterTestBase(QiskitTestCase):
"""A base class for parameter manager unittest, providing test schedule."""
def setUp(self):
"""Just some useful, reusable Parameters, constants, schedules."""
super().setUp()
self.amp1_1 = Parameter("amp1_1")
self.amp1_2 = Parameter("amp1_2")
self.amp2 = Parameter("amp2")
self.amp3 = Parameter("amp3")
self.dur1 = Parameter("dur1")
self.dur2 = Parameter("dur2")
self.dur3 = Parameter("dur3")
self.parametric_waveform1 = pulse.Gaussian(
duration=self.dur1, amp=self.amp1_1 + self.amp1_2, sigma=self.dur1 / 4
)
self.parametric_waveform2 = pulse.Gaussian(
duration=self.dur2, amp=self.amp2, sigma=self.dur2 / 5
)
self.parametric_waveform3 = pulse.Gaussian(
duration=self.dur3, amp=self.amp3, sigma=self.dur3 / 6
)
self.ch1 = Parameter("ch1")
self.ch2 = Parameter("ch2")
self.ch3 = Parameter("ch3")
self.d1 = pulse.DriveChannel(self.ch1)
self.d2 = pulse.DriveChannel(self.ch2)
self.d3 = pulse.DriveChannel(self.ch3)
self.phi1 = Parameter("phi1")
self.phi2 = Parameter("phi2")
self.phi3 = Parameter("phi3")
self.meas_dur = Parameter("meas_dur")
self.mem1 = Parameter("s1")
self.reg1 = Parameter("m1")
self.context_dur = Parameter("context_dur")
# schedule under test
subroutine = pulse.ScheduleBlock(alignment_context=AlignLeft())
subroutine += pulse.ShiftPhase(self.phi1, self.d1)
subroutine += pulse.Play(self.parametric_waveform1, self.d1)
sched = pulse.Schedule()
sched += pulse.ShiftPhase(self.phi3, self.d3)
long_schedule = pulse.ScheduleBlock(
alignment_context=AlignEquispaced(self.context_dur), name="long_schedule"
)
long_schedule += subroutine
long_schedule += pulse.ShiftPhase(self.phi2, self.d2)
long_schedule += pulse.Play(self.parametric_waveform2, self.d2)
with self.assertWarns(DeprecationWarning):
long_schedule += pulse.Call(sched)
long_schedule += pulse.Play(self.parametric_waveform3, self.d3)
long_schedule += pulse.Acquire(
self.meas_dur,
pulse.AcquireChannel(self.ch1),
mem_slot=pulse.MemorySlot(self.mem1),
reg_slot=pulse.RegisterSlot(self.reg1),
)
self.test_sched = long_schedule
class TestParameterGetter(ParameterTestBase):
"""Test getting parameters."""
def test_get_parameter_from_channel(self):
"""Test get parameters from channel."""
test_obj = pulse.DriveChannel(self.ch1 + self.ch2)
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.ch1, self.ch2}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_pulse(self):
"""Test get parameters from pulse instruction."""
test_obj = self.parametric_waveform1
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.amp1_1, self.amp1_2, self.dur1}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_acquire(self):
"""Test get parameters from acquire instruction."""
test_obj = pulse.Acquire(16000, pulse.AcquireChannel(self.ch1), pulse.MemorySlot(self.ch1))
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.ch1}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_inst(self):
"""Test get parameters from instruction."""
test_obj = pulse.ShiftPhase(self.phi1 + self.phi2, pulse.DriveChannel(0))
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.phi1, self.phi2}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_call(self):
"""Test get parameters from instruction."""
sched = pulse.Schedule()
sched += pulse.ShiftPhase(self.phi1, self.d1)
with self.assertWarns(DeprecationWarning):
test_obj = pulse.Call(subroutine=sched)
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.phi1, self.ch1}
self.assertSetEqual(visitor.parameters, ref_params)
def test_with_function(self):
"""Test ParameterExpressions formed trivially in a function."""
def get_shift(variable):
return variable - 1
test_obj = pulse.ShiftPhase(get_shift(self.phi1), self.d1)
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.phi1, self.ch1}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_alignment_context(self):
"""Test get parameters from alignment context."""
test_obj = AlignEquispaced(duration=self.context_dur + self.dur1)
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.context_dur, self.dur1}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_complex_schedule(self):
"""Test get parameters from complicated schedule."""
test_block = deepcopy(self.test_sched)
visitor = ParameterGetter()
visitor.visit(test_block)
self.assertEqual(len(visitor.parameters), 17)
class TestParameterSetter(ParameterTestBase):
"""Test setting parameters."""
def test_set_parameter_to_channel(self):
"""Test set parameters from channel."""
test_obj = pulse.DriveChannel(self.ch1 + self.ch2)
value_dict = {self.ch1: 1, self.ch2: 2}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = pulse.DriveChannel(3)
self.assertEqual(assigned, ref_obj)
def test_set_parameter_to_pulse(self):
"""Test set parameters from pulse instruction."""
test_obj = self.parametric_waveform1
value_dict = {self.amp1_1: 0.1, self.amp1_2: 0.2, self.dur1: 160}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = pulse.Gaussian(duration=160, amp=0.3, sigma=40)
self.assertEqual(assigned, ref_obj)
def test_set_parameter_to_acquire(self):
"""Test set parameters to acquire instruction."""
test_obj = pulse.Acquire(16000, pulse.AcquireChannel(self.ch1), pulse.MemorySlot(self.ch1))
value_dict = {self.ch1: 2}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = pulse.Acquire(16000, pulse.AcquireChannel(2), pulse.MemorySlot(2))
self.assertEqual(assigned, ref_obj)
def test_set_parameter_to_inst(self):
"""Test get parameters from instruction."""
test_obj = pulse.ShiftPhase(self.phi1 + self.phi2, pulse.DriveChannel(0))
value_dict = {self.phi1: 0.123, self.phi2: 0.456}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = pulse.ShiftPhase(0.579, pulse.DriveChannel(0))
self.assertEqual(assigned, ref_obj)
def test_set_parameter_to_call(self):
"""Test get parameters from instruction."""
sched = pulse.Schedule()
sched += pulse.ShiftPhase(self.phi1, self.d1)
with self.assertWarns(DeprecationWarning):
test_obj = pulse.Call(subroutine=sched)
value_dict = {self.phi1: 1.57, self.ch1: 2}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_sched = pulse.Schedule()
ref_sched += pulse.ShiftPhase(1.57, pulse.DriveChannel(2))
with self.assertWarns(DeprecationWarning):
ref_obj = pulse.Call(subroutine=ref_sched)
self.assertEqual(assigned, ref_obj)
def test_with_function(self):
"""Test ParameterExpressions formed trivially in a function."""
def get_shift(variable):
return variable - 1
test_obj = pulse.ShiftPhase(get_shift(self.phi1), self.d1)
value_dict = {self.phi1: 2.0, self.ch1: 2}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = pulse.ShiftPhase(1.0, pulse.DriveChannel(2))
self.assertEqual(assigned, ref_obj)
def test_set_parameter_to_alignment_context(self):
"""Test get parameters from alignment context."""
test_obj = AlignEquispaced(duration=self.context_dur + self.dur1)
value_dict = {self.context_dur: 1000, self.dur1: 100}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = AlignEquispaced(duration=1100)
self.assertEqual(assigned, ref_obj)
def test_nested_assignment_partial_bind(self):
"""Test nested schedule with call instruction.
Inline the schedule and partially bind parameters."""
context = AlignEquispaced(duration=self.context_dur)
subroutine = pulse.ScheduleBlock(alignment_context=context)
subroutine += pulse.Play(self.parametric_waveform1, self.d1)
nested_block = pulse.ScheduleBlock()
with self.assertWarns(DeprecationWarning):
nested_block += pulse.Call(subroutine=subroutine)
test_obj = pulse.ScheduleBlock()
test_obj += nested_block
test_obj = inline_subroutines(test_obj)
value_dict = {self.context_dur: 1000, self.dur1: 200, self.ch1: 1}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_context = AlignEquispaced(duration=1000)
ref_subroutine = pulse.ScheduleBlock(alignment_context=ref_context)
ref_subroutine += pulse.Play(
pulse.Gaussian(200, self.amp1_1 + self.amp1_2, 50), pulse.DriveChannel(1)
)
ref_nested_block = pulse.ScheduleBlock()
ref_nested_block += ref_subroutine
ref_obj = pulse.ScheduleBlock()
ref_obj += ref_nested_block
self.assertEqual(assigned, ref_obj)
def test_complex_valued_parameter(self):
"""Test complex valued parameter can be casted to a complex value,
but raises PendingDeprecationWarning.."""
amp = Parameter("amp")
test_obj = pulse.Constant(duration=160, amp=1j * amp)
value_dict = {amp: 0.1}
visitor = ParameterSetter(param_map=value_dict)
with self.assertWarns(PendingDeprecationWarning):
assigned = visitor.visit(test_obj)
with self.assertWarns(DeprecationWarning):
ref_obj = pulse.Constant(duration=160, amp=1j * 0.1)
self.assertEqual(assigned, ref_obj)
def test_complex_value_to_parameter(self):
"""Test complex value can be assigned to parameter object,
but raises PendingDeprecationWarning."""
amp = Parameter("amp")
test_obj = pulse.Constant(duration=160, amp=amp)
value_dict = {amp: 0.1j}
visitor = ParameterSetter(param_map=value_dict)
with self.assertWarns(PendingDeprecationWarning):
assigned = visitor.visit(test_obj)
with self.assertWarns(DeprecationWarning):
ref_obj = pulse.Constant(duration=160, amp=1j * 0.1)
self.assertEqual(assigned, ref_obj)
def test_complex_parameter_expression(self):
"""Test assignment of complex-valued parameter expression to parameter,
but raises PendingDeprecationWarning."""
amp = Parameter("amp")
mag = Parameter("A")
phi = Parameter("phi")
test_obj = pulse.Constant(duration=160, amp=amp)
test_obj_copy = deepcopy(test_obj)
# generate parameter expression
value_dict = {amp: mag * np.exp(1j * phi)}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
# generate complex value
value_dict = {mag: 0.1, phi: 0.5}
visitor = ParameterSetter(param_map=value_dict)
with self.assertWarns(PendingDeprecationWarning):
assigned = visitor.visit(assigned)
# evaluated parameter expression: 0.0877582561890373 + 0.0479425538604203*I
value_dict = {amp: 0.1 * np.exp(0.5j)}
visitor = ParameterSetter(param_map=value_dict)
with self.assertWarns(PendingDeprecationWarning):
ref_obj = visitor.visit(test_obj_copy)
self.assertEqual(assigned, ref_obj)
def test_invalid_pulse_amplitude(self):
"""Test that invalid parameters are still checked upon assignment."""
amp = Parameter("amp")
test_sched = pulse.ScheduleBlock()
test_sched.append(
pulse.Play(
pulse.Constant(160, amp=2 * amp),
pulse.DriveChannel(0),
),
inplace=True,
)
with self.assertRaises(PulseError):
test_sched.assign_parameters({amp: 0.6}, inplace=False)
def test_set_parameter_to_complex_schedule(self):
"""Test get parameters from complicated schedule."""
test_block = deepcopy(self.test_sched)
value_dict = {
self.amp1_1: 0.1,
self.amp1_2: 0.2,
self.amp2: 0.3,
self.amp3: 0.4,
self.dur1: 100,
self.dur2: 125,
self.dur3: 150,
self.ch1: 0,
self.ch2: 2,
self.ch3: 4,
self.phi1: 1.0,
self.phi2: 2.0,
self.phi3: 3.0,
self.meas_dur: 300,
self.mem1: 3,
self.reg1: 0,
self.context_dur: 1000,
}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_block)
# create ref schedule
subroutine = pulse.ScheduleBlock(alignment_context=AlignLeft())
subroutine += pulse.ShiftPhase(1.0, pulse.DriveChannel(0))
subroutine += pulse.Play(pulse.Gaussian(100, 0.3, 25), pulse.DriveChannel(0))
sched = pulse.Schedule()
sched += pulse.ShiftPhase(3.0, pulse.DriveChannel(4))
ref_obj = pulse.ScheduleBlock(alignment_context=AlignEquispaced(1000), name="long_schedule")
ref_obj += subroutine
ref_obj += pulse.ShiftPhase(2.0, pulse.DriveChannel(2))
ref_obj += pulse.Play(pulse.Gaussian(125, 0.3, 25), pulse.DriveChannel(2))
with self.assertWarns(DeprecationWarning):
ref_obj += pulse.Call(sched)
ref_obj += pulse.Play(pulse.Gaussian(150, 0.4, 25), pulse.DriveChannel(4))
ref_obj += pulse.Acquire(
300, pulse.AcquireChannel(0), pulse.MemorySlot(3), pulse.RegisterSlot(0)
)
self.assertEqual(assigned, ref_obj)
class TestAssignFromProgram(QiskitTestCase):
"""Test managing parameters from programs. Parameter manager is implicitly called."""
def test_attribute_parameters(self):
"""Test the ``parameter`` attributes."""
sigma = Parameter("sigma")
amp = Parameter("amp")
waveform = pulse.library.Gaussian(duration=128, sigma=sigma, amp=amp)
block = pulse.ScheduleBlock()
block += pulse.Play(waveform, pulse.DriveChannel(10))
ref_set = {amp, sigma}
self.assertSetEqual(set(block.parameters), ref_set)
def test_parametric_pulses(self):
"""Test Parametric Pulses with parameters determined by ParameterExpressions
in the Play instruction."""
sigma = Parameter("sigma")
amp = Parameter("amp")
waveform = pulse.library.Gaussian(duration=128, sigma=sigma, amp=amp)
block = pulse.ScheduleBlock()
block += pulse.Play(waveform, pulse.DriveChannel(10))
block.assign_parameters({amp: 0.2, sigma: 4}, inplace=True)
self.assertEqual(block.blocks[0].pulse.amp, 0.2)
self.assertEqual(block.blocks[0].pulse.sigma, 4.0)
def test_parameters_from_subroutine(self):
"""Test that get parameter objects from subroutines."""
param1 = Parameter("amp")
waveform = pulse.library.Constant(duration=100, amp=param1)
program_layer0 = pulse.Schedule()
program_layer0 += pulse.Play(waveform, pulse.DriveChannel(0))
# from call instruction
program_layer1 = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
program_layer1 += pulse.instructions.Call(program_layer0)
self.assertEqual(program_layer1.get_parameters("amp")[0], param1)
# from nested call instruction
program_layer2 = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
program_layer2 += pulse.instructions.Call(program_layer1)
self.assertEqual(program_layer2.get_parameters("amp")[0], param1)
def test_assign_parameter_to_subroutine(self):
"""Test that assign parameter objects to subroutines."""
param1 = Parameter("amp")
waveform = pulse.library.Constant(duration=100, amp=param1)
program_layer0 = pulse.Schedule()
program_layer0 += pulse.Play(waveform, pulse.DriveChannel(0))
reference = program_layer0.assign_parameters({param1: 0.1}, inplace=False)
# to call instruction
program_layer1 = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
program_layer1 += pulse.instructions.Call(program_layer0)
target = program_layer1.assign_parameters({param1: 0.1}, inplace=False)
self.assertEqual(inline_subroutines(target), reference)
# to nested call instruction
program_layer2 = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
program_layer2 += pulse.instructions.Call(program_layer1)
target = program_layer2.assign_parameters({param1: 0.1}, inplace=False)
self.assertEqual(inline_subroutines(target), reference)
def test_assign_parameter_to_subroutine_parameter(self):
"""Test that assign parameter objects to parameter of subroutine."""
param1 = Parameter("amp")
waveform = pulse.library.Constant(duration=100, amp=param1)
param_sub1 = Parameter("p1")
param_sub2 = Parameter("p2")
subroutine = pulse.Schedule()
subroutine += pulse.Play(waveform, pulse.DriveChannel(0))
reference = subroutine.assign_parameters({param1: 0.6}, inplace=False)
main_prog = pulse.Schedule()
pdict = {param1: param_sub1 + param_sub2}
with self.assertWarns(DeprecationWarning):
main_prog += pulse.instructions.Call(subroutine, value_dict=pdict)
# parameter is overwritten by parameters
self.assertEqual(len(main_prog.parameters), 2)
target = main_prog.assign_parameters({param_sub1: 0.1, param_sub2: 0.5}, inplace=False)
result = inline_subroutines(target)
self.assertEqual(result, reference)
class TestScheduleTimeslots(QiskitTestCase):
"""Test for edge cases of timing overlap on parametrized channels.
Note that this test is dedicated to `Schedule` since `ScheduleBlock` implicitly
assigns instruction time t0 that doesn't overlap with existing instructions.
"""
def test_overlapping_pulses(self):
"""Test that an error is still raised when overlapping instructions are assigned."""
param_idx = Parameter("q")
schedule = pulse.Schedule()
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx))
with self.assertRaises(PulseError):
schedule |= pulse.Play(
pulse.Waveform([0.5, 0.5, 0.5, 0.5]), pulse.DriveChannel(param_idx)
)
def test_overlapping_on_assignment(self):
"""Test that assignment will catch against existing instructions."""
param_idx = Parameter("q")
schedule = pulse.Schedule()
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(1))
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx))
with self.assertRaises(PulseError):
schedule.assign_parameters({param_idx: 1})
def test_overlapping_on_expression_assigment_to_zero(self):
"""Test constant*zero expression conflict."""
param_idx = Parameter("q")
schedule = pulse.Schedule()
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx))
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(2 * param_idx))
with self.assertRaises(PulseError):
schedule.assign_parameters({param_idx: 0})
def test_merging_upon_assignment(self):
"""Test that schedule can match instructions on a channel."""
param_idx = Parameter("q")
schedule = pulse.Schedule()
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(1))
schedule = schedule.insert(
4, pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx))
)
schedule.assign_parameters({param_idx: 1})
self.assertEqual(schedule.ch_duration(pulse.DriveChannel(1)), 8)
self.assertEqual(schedule.channels, (pulse.DriveChannel(1),))
def test_overlapping_on_multiple_assignment(self):
"""Test that assigning one qubit then another raises error when overlapping."""
param_idx1 = Parameter("q1")
param_idx2 = Parameter("q2")
schedule = pulse.Schedule()
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx1))
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx2))
schedule.assign_parameters({param_idx1: 2})
with self.assertRaises(PulseError):
schedule.assign_parameters({param_idx2: 2})
def test_cannot_build_schedule_with_unassigned_duration(self):
"""Test we cannot build schedule with parameterized instructions"""
dur = Parameter("dur")
ch = pulse.DriveChannel(0)
test_play = pulse.Play(pulse.Gaussian(dur, 0.1, dur / 4), ch)
sched = pulse.Schedule()
with self.assertRaises(UnassignedDurationError):
sched.insert(0, test_play)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test schedule block subroutine reference mechanism."""
import numpy as np
from qiskit import circuit, pulse
from qiskit.pulse import builder
from qiskit.pulse.transforms import inline_subroutines
from qiskit.test import QiskitTestCase
class TestReference(QiskitTestCase):
"""Test for basic behavior of reference mechanism."""
def test_append_schedule(self):
"""Test appending schedule without calling.
Appended schedules are not subroutines.
These are directly exposed to the outer block.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.append_schedule(sched_x1)
with pulse.build() as sched_z1:
builder.append_schedule(sched_y1)
self.assertEqual(len(sched_z1.references), 0)
def test_append_schedule_parameter_scope(self):
"""Test appending schedule without calling.
Parameter in the appended schedule has the scope of outer schedule.
"""
param = circuit.Parameter("name")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.append_schedule(sched_x1)
with pulse.build() as sched_z1:
builder.append_schedule(sched_y1)
sched_param = next(iter(sched_z1.scoped_parameters()))
self.assertEqual(sched_param.name, "root::name")
# object equality
self.assertEqual(
sched_z1.search_parameters("root::name")[0],
param,
)
def test_refer_schedule(self):
"""Test refer to schedule by name.
Outer block is only aware of its inner reference.
Nested reference is not directly exposed to the most outer block.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.reference("x1", "d0")
with pulse.build() as sched_z1:
builder.reference("y1", "d0")
sched_y1.assign_references({("x1", "d0"): sched_x1})
sched_z1.assign_references({("y1", "d0"): sched_y1})
self.assertEqual(len(sched_z1.references), 1)
self.assertEqual(sched_z1.references[("y1", "d0")], sched_y1)
self.assertEqual(len(sched_y1.references), 1)
self.assertEqual(sched_y1.references[("x1", "d0")], sched_x1)
def test_refer_schedule_parameter_scope(self):
"""Test refer to schedule by name.
Parameter in the called schedule has the scope of called schedule.
"""
param = circuit.Parameter("name")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.reference("x1", "d0")
with pulse.build() as sched_z1:
builder.reference("y1", "d0")
sched_y1.assign_references({("x1", "d0"): sched_x1})
sched_z1.assign_references({("y1", "d0"): sched_y1})
sched_param = next(iter(sched_z1.scoped_parameters()))
self.assertEqual(sched_param.name, "root::y1,d0::x1,d0::name")
# object equality
self.assertEqual(
sched_z1.search_parameters("root::y1,d0::x1,d0::name")[0],
param,
)
# regex
self.assertEqual(
sched_z1.search_parameters(r"\S::x1,d0::name")[0],
param,
)
def test_call_schedule(self):
"""Test call schedule.
Outer block is only aware of its inner reference.
Nested reference is not directly exposed to the most outer block.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.call(sched_x1, name="x1")
with pulse.build() as sched_z1:
builder.call(sched_y1, name="y1")
self.assertEqual(len(sched_z1.references), 1)
self.assertEqual(sched_z1.references[("y1",)], sched_y1)
self.assertEqual(len(sched_y1.references), 1)
self.assertEqual(sched_y1.references[("x1",)], sched_x1)
def test_call_schedule_parameter_scope(self):
"""Test call schedule.
Parameter in the called schedule has the scope of called schedule.
"""
param = circuit.Parameter("name")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.call(sched_x1, name="x1")
with pulse.build() as sched_z1:
builder.call(sched_y1, name="y1")
sched_param = next(iter(sched_z1.scoped_parameters()))
self.assertEqual(sched_param.name, "root::y1::x1::name")
# object equality
self.assertEqual(
sched_z1.search_parameters("root::y1::x1::name")[0],
param,
)
# regex
self.assertEqual(
sched_z1.search_parameters(r"\S::x1::name")[0],
param,
)
def test_append_and_call_schedule(self):
"""Test call and append schedule.
Reference is copied to the outer schedule by appending.
Original reference remains unchanged.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.call(sched_x1, name="x1")
with pulse.build() as sched_z1:
builder.append_schedule(sched_y1)
self.assertEqual(len(sched_z1.references), 1)
self.assertEqual(sched_z1.references[("x1",)], sched_x1)
# blocks[0] is sched_y1 and its reference is now point to outer block reference
self.assertIs(sched_z1.blocks[0].references, sched_z1.references)
# however the original program is protected to prevent unexpected mutation
self.assertIsNot(sched_y1.references, sched_z1.references)
# appended schedule is preserved
self.assertEqual(len(sched_y1.references), 1)
self.assertEqual(sched_y1.references[("x1",)], sched_x1)
def test_calling_similar_schedule(self):
"""Test calling schedules with the same representation.
sched_x1 and sched_y1 are the different subroutines, but same representation.
Two references shoud be created.
"""
param1 = circuit.Parameter("param")
param2 = circuit.Parameter("param")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param1, name="p"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, param2, name="p"), pulse.DriveChannel(0))
with pulse.build() as sched_z1:
pulse.call(sched_x1)
pulse.call(sched_y1)
self.assertEqual(len(sched_z1.references), 2)
def test_calling_same_schedule(self):
"""Test calling same schedule twice.
Because it calls the same schedule, no duplication should occur in reference table.
"""
param = circuit.Parameter("param")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_z1:
pulse.call(sched_x1, name="same_sched")
pulse.call(sched_x1, name="same_sched")
self.assertEqual(len(sched_z1.references), 1)
def test_calling_same_schedule_with_different_assignment(self):
"""Test calling same schedule twice but with different parameters.
Same schedule is called twice but with different assignment.
Two references should be created.
"""
param = circuit.Parameter("param")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_z1:
pulse.call(sched_x1, param=0.1)
pulse.call(sched_x1, param=0.2)
self.assertEqual(len(sched_z1.references), 2)
def test_alignment_context(self):
"""Test nested alignment context.
Inline alignment is identical to append_schedule operation.
Thus scope is not newly generated.
"""
with pulse.build(name="x1") as sched_x1:
with pulse.align_right():
with pulse.align_left():
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
self.assertEqual(len(sched_x1.references), 0)
def test_appending_child_block(self):
"""Test for edge case.
User can append blocks which is an element of another schedule block.
But this is not standard use case.
In this case, references may contain subroutines which don't exist in the context.
This is because all references within the program are centrally
managed in the most outer block.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, 0.2, name="y1"), pulse.DriveChannel(0))
with pulse.build() as sched_x2:
builder.call(sched_x1, name="x1")
self.assertEqual(list(sched_x2.references.keys()), [("x1",)])
with pulse.build() as sched_y2:
builder.call(sched_y1, name="y1")
self.assertEqual(list(sched_y2.references.keys()), [("y1",)])
with pulse.build() as sched_z1:
builder.append_schedule(sched_x2)
builder.append_schedule(sched_y2)
self.assertEqual(list(sched_z1.references.keys()), [("x1",), ("y1",)])
# child block references point to its parent, i.e. sched_z1
self.assertIs(sched_z1.blocks[0].references, sched_z1._reference_manager)
self.assertIs(sched_z1.blocks[1].references, sched_z1._reference_manager)
with pulse.build() as sched_z2:
# Append child block
# The reference of this block is sched_z1.reference thus it contains both x1 and y1.
# However, y1 doesn't exist in the context, so only x1 should be added.
# Usually, user will append sched_x2 directly here, rather than sched_z1.blocks[0]
# This is why this situation is an edge case.
builder.append_schedule(sched_z1.blocks[0])
self.assertEqual(len(sched_z2.references), 1)
self.assertEqual(sched_z2.references[("x1",)], sched_x1)
def test_replacement(self):
"""Test nested alignment context.
Replacing schedule block with schedule block.
Removed block contains own reference, that should be removed with replacement.
New block also contains reference, that should be passed to the current reference.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, 0.2, name="y1"), pulse.DriveChannel(0))
with pulse.build() as sched_x2:
builder.call(sched_x1, name="x1")
with pulse.build() as sched_y2:
builder.call(sched_y1, name="y1")
with pulse.build() as sched_z1:
builder.append_schedule(sched_x2)
builder.append_schedule(sched_y2)
self.assertEqual(len(sched_z1.references), 2)
self.assertEqual(sched_z1.references[("x1",)], sched_x1)
self.assertEqual(sched_z1.references[("y1",)], sched_y1)
# Define schedule to replace
with pulse.build() as sched_r1:
pulse.play(pulse.Constant(100, 0.1, name="r1"), pulse.DriveChannel(0))
with pulse.build() as sched_r2:
pulse.call(sched_r1, name="r1")
sched_z2 = sched_z1.replace(sched_x2, sched_r2)
self.assertEqual(len(sched_z2.references), 2)
self.assertEqual(sched_z2.references[("r1",)], sched_r1)
self.assertEqual(sched_z2.references[("y1",)], sched_y1)
def test_special_parameter_name(self):
"""Testcase to guarantee usage of some special symbols in parameter name.
These symbols might be often used in user code.
No conflict should occur with the default scope delimiter.
"""
param = circuit.Parameter("my.parameter_object")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
pulse.reference("sub", "q0")
sched_y1.assign_references({("sub", "q0"): sched_x1})
ret_param = sched_y1.search_parameters(r"\Ssub,q0::my.parameter_object")[0]
self.assertEqual(param, ret_param)
def test_parameter_in_multiple_scope(self):
"""Testcase for scope-aware parameter getter.
When a single parameter object is used in multiple scopes,
the scoped_parameters method must return parameter objects associated to each scope,
while parameters property returns a single parameter object.
"""
param = circuit.Parameter("name")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, param), pulse.DriveChannel(1))
with pulse.build() as sched_z1:
pulse.call(sched_x1, name="x1")
pulse.call(sched_y1, name="y1")
self.assertEqual(len(sched_z1.parameters), 1)
self.assertEqual(len(sched_z1.scoped_parameters()), 2)
self.assertEqual(sched_z1.search_parameters("root::x1::name")[0], param)
self.assertEqual(sched_z1.search_parameters("root::y1::name")[0], param)
def test_parallel_alignment_equality(self):
"""Testcase for potential edge case.
In parallel alignment context, reference instruction is broadcasted to
all channels. When new channel is added after reference, this should be
connected with reference node.
"""
with pulse.build() as subroutine:
pulse.reference("unassigned")
with pulse.build() as sched1:
with pulse.align_left():
pulse.delay(10, pulse.DriveChannel(0))
pulse.call(subroutine) # This should be broadcasted to d1 as well
pulse.delay(10, pulse.DriveChannel(1))
with pulse.build() as sched2:
with pulse.align_left():
pulse.delay(10, pulse.DriveChannel(0))
pulse.delay(10, pulse.DriveChannel(1))
pulse.call(subroutine)
self.assertNotEqual(sched1, sched2)
def test_subroutine_conflict(self):
"""Test for edge case of appending two schedule blocks having the
references with conflicting reference key.
This operation should fail because one of references will be gone after assignment.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1), pulse.DriveChannel(0))
with pulse.build() as sched_x2:
pulse.call(sched_x1, name="conflict_name")
self.assertEqual(sched_x2.references[("conflict_name",)], sched_x1)
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, 0.2), pulse.DriveChannel(0))
with pulse.build() as sched_y2:
pulse.call(sched_y1, name="conflict_name")
self.assertEqual(sched_y2.references[("conflict_name",)], sched_y1)
with self.assertRaises(pulse.exceptions.PulseError):
with pulse.build():
builder.append_schedule(sched_x2)
builder.append_schedule(sched_y2)
def test_assign_existing_reference(self):
"""Test for explicitly assign existing reference.
This operation should fail because overriding reference is not allowed.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, 0.2), pulse.DriveChannel(0))
with pulse.build() as sched_z1:
pulse.call(sched_x1, name="conflict_name")
with self.assertRaises(pulse.exceptions.PulseError):
sched_z1.assign_references({("conflict_name",): sched_y1})
class TestSubroutineWithCXGate(QiskitTestCase):
"""Test called program scope with practical example of building fully parametrized CX gate."""
def setUp(self):
super().setUp()
# parameters of X pulse
self.xp_dur = circuit.Parameter("dur")
self.xp_amp = circuit.Parameter("amp")
self.xp_sigma = circuit.Parameter("sigma")
self.xp_beta = circuit.Parameter("beta")
# amplitude of SX pulse
self.sxp_amp = circuit.Parameter("amp")
# parameters of CR pulse
self.cr_dur = circuit.Parameter("dur")
self.cr_amp = circuit.Parameter("amp")
self.cr_sigma = circuit.Parameter("sigma")
self.cr_risefall = circuit.Parameter("risefall")
# channels
self.control_ch = circuit.Parameter("ctrl")
self.target_ch = circuit.Parameter("tgt")
self.cr_ch = circuit.Parameter("cr")
# echo pulse on control qubit
with pulse.build(name="xp") as xp_sched_q0:
pulse.play(
pulse.Drag(
duration=self.xp_dur,
amp=self.xp_amp,
sigma=self.xp_sigma,
beta=self.xp_beta,
),
channel=pulse.DriveChannel(self.control_ch),
)
self.xp_sched = xp_sched_q0
# local rotation on target qubit
with pulse.build(name="sx") as sx_sched_q1:
pulse.play(
pulse.Drag(
duration=self.xp_dur,
amp=self.sxp_amp,
sigma=self.xp_sigma,
beta=self.xp_beta,
),
channel=pulse.DriveChannel(self.target_ch),
)
self.sx_sched = sx_sched_q1
# cross resonance
with pulse.build(name="cr") as cr_sched:
pulse.play(
pulse.GaussianSquare(
duration=self.cr_dur,
amp=self.cr_amp,
sigma=self.cr_sigma,
risefall_sigma_ratio=self.cr_risefall,
),
channel=pulse.ControlChannel(self.cr_ch),
)
self.cr_sched = cr_sched
def test_lazy_ecr(self):
"""Test lazy subroutines through ECR schedule construction."""
with pulse.build(name="lazy_ecr") as sched:
with pulse.align_sequential():
pulse.reference("cr", "q0", "q1")
pulse.reference("xp", "q0")
with pulse.phase_offset(np.pi, pulse.ControlChannel(self.cr_ch)):
pulse.reference("cr", "q0", "q1")
pulse.reference("xp", "q0")
# Schedule has references
self.assertTrue(sched.is_referenced())
# Schedule is not schedulable because of unassigned references
self.assertFalse(sched.is_schedulable())
# Two references cr and xp are called
self.assertEqual(len(sched.references), 2)
# Parameters in the current scope are Parameter("cr") which is used in phase_offset
# References are not assigned yet.
params = {p.name for p in sched.parameters}
self.assertSetEqual(params, {"cr"})
# Parameter names are scoepd
scoped_params = {p.name for p in sched.scoped_parameters()}
self.assertSetEqual(scoped_params, {"root::cr"})
# Assign CR and XP schedule to the empty reference
sched.assign_references({("cr", "q0", "q1"): self.cr_sched})
sched.assign_references({("xp", "q0"): self.xp_sched})
# Check updated references
assigned_refs = sched.references
self.assertEqual(assigned_refs[("cr", "q0", "q1")], self.cr_sched)
self.assertEqual(assigned_refs[("xp", "q0")], self.xp_sched)
# Parameter added from subroutines
scoped_params = {p.name for p in sched.scoped_parameters()}
ref_params = {
# This is the cr parameter that belongs to phase_offset instruction in the root scope
"root::cr",
# This is the same cr parameter that belongs to the play instruction in a child scope
"root::cr,q0,q1::cr",
"root::cr,q0,q1::amp",
"root::cr,q0,q1::dur",
"root::cr,q0,q1::risefall",
"root::cr,q0,q1::sigma",
"root::xp,q0::ctrl",
"root::xp,q0::amp",
"root::xp,q0::beta",
"root::xp,q0::dur",
"root::xp,q0::sigma",
}
self.assertSetEqual(scoped_params, ref_params)
# Get parameter without scope, cr amp and xp amp are hit.
params = sched.get_parameters(parameter_name="amp")
self.assertEqual(len(params), 2)
# Get parameter with scope, only xp amp
params = sched.search_parameters(parameter_regex="root::xp,q0::amp")
self.assertEqual(len(params), 1)
def test_cnot(self):
"""Integration test with CNOT schedule construction."""
# echeod cross resonance
with pulse.build(name="ecr", default_alignment="sequential") as ecr_sched:
pulse.call(self.cr_sched, name="cr")
pulse.call(self.xp_sched, name="xp")
with pulse.phase_offset(np.pi, pulse.ControlChannel(self.cr_ch)):
pulse.call(self.cr_sched, name="cr")
pulse.call(self.xp_sched, name="xp")
# cnot gate, locally equivalent to ecr
with pulse.build(name="cx", default_alignment="sequential") as cx_sched:
pulse.shift_phase(np.pi / 2, pulse.DriveChannel(self.control_ch))
pulse.call(self.sx_sched, name="sx")
pulse.call(ecr_sched, name="ecr")
# get parameter with scope, full scope is not needed
xp_amp = cx_sched.search_parameters(r"\S:xp::amp")[0]
self.assertEqual(self.xp_amp, xp_amp)
# get parameter with scope, of course full scope can be specified
xp_amp_full_scoped = cx_sched.search_parameters("root::ecr::xp::amp")[0]
self.assertEqual(xp_amp_full_scoped, xp_amp)
# assign parameters
assigned_cx = cx_sched.assign_parameters(
value_dict={
self.cr_ch: 0,
self.control_ch: 0,
self.target_ch: 1,
self.sxp_amp: 0.1,
self.xp_amp: 0.2,
self.xp_dur: 160,
self.xp_sigma: 40,
self.xp_beta: 3.0,
self.cr_amp: 0.5,
self.cr_dur: 800,
self.cr_sigma: 64,
self.cr_risefall: 2,
},
inplace=True,
)
flatten_cx = inline_subroutines(assigned_cx)
with pulse.build(default_alignment="sequential") as ref_cx:
# sz
pulse.shift_phase(np.pi / 2, pulse.DriveChannel(0))
with pulse.align_left():
# sx
pulse.play(
pulse.Drag(
duration=160,
amp=0.1,
sigma=40,
beta=3.0,
),
channel=pulse.DriveChannel(1),
)
with pulse.align_sequential():
# cr
with pulse.align_left():
pulse.play(
pulse.GaussianSquare(
duration=800,
amp=0.5,
sigma=64,
risefall_sigma_ratio=2,
),
channel=pulse.ControlChannel(0),
)
# xp
with pulse.align_left():
pulse.play(
pulse.Drag(
duration=160,
amp=0.2,
sigma=40,
beta=3.0,
),
channel=pulse.DriveChannel(0),
)
with pulse.phase_offset(np.pi, pulse.ControlChannel(0)):
# cr
with pulse.align_left():
pulse.play(
pulse.GaussianSquare(
duration=800,
amp=0.5,
sigma=64,
risefall_sigma_ratio=2,
),
channel=pulse.ControlChannel(0),
)
# xp
with pulse.align_left():
pulse.play(
pulse.Drag(
duration=160,
amp=0.2,
sigma=40,
beta=3.0,
),
channel=pulse.DriveChannel(0),
)
self.assertEqual(flatten_cx, ref_cx)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test cases for the pulse Schedule transforms."""
import unittest
from typing import List, Set
import numpy as np
from qiskit import pulse
from qiskit.pulse import (
Play,
Delay,
Acquire,
Schedule,
Waveform,
Drag,
Gaussian,
GaussianSquare,
Constant,
)
from qiskit.pulse import transforms, instructions
from qiskit.pulse.channels import (
MemorySlot,
DriveChannel,
AcquireChannel,
RegisterSlot,
SnapshotChannel,
)
from qiskit.pulse.instructions import directives
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeOpenPulse2Q
class TestAlignMeasures(QiskitTestCase):
"""Test the helper function which aligns acquires."""
def setUp(self):
super().setUp()
self.backend = FakeOpenPulse2Q()
self.config = self.backend.configuration()
self.inst_map = self.backend.defaults().instruction_schedule_map
self.short_pulse = pulse.Waveform(
samples=np.array([0.02739068], dtype=np.complex128), name="p0"
)
def test_align_measures(self):
"""Test that one acquire is delayed to match the time of the later acquire."""
sched = pulse.Schedule(name="fake_experiment")
sched.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True)
sched.insert(1, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
sched.insert(10, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True)
sched.insert(10, Play(self.short_pulse, self.config.measure(0)), inplace=True)
sched.insert(11, Play(self.short_pulse, self.config.measure(0)), inplace=True)
sched.insert(10, Play(self.short_pulse, self.config.measure(1)), inplace=True)
aligned = transforms.align_measures([sched])[0]
self.assertEqual(aligned.name, "fake_experiment")
ref = pulse.Schedule(name="fake_experiment")
ref.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True)
ref.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
ref.insert(10, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True)
ref.insert(19, Play(self.short_pulse, self.config.measure(0)), inplace=True)
ref.insert(20, Play(self.short_pulse, self.config.measure(0)), inplace=True)
ref.insert(10, Play(self.short_pulse, self.config.measure(1)), inplace=True)
self.assertEqual(aligned, ref)
aligned = transforms.align_measures([sched], self.inst_map, align_time=20)[0]
ref = pulse.Schedule(name="fake_experiment")
ref.insert(10, Play(self.short_pulse, self.config.drive(0)), inplace=True)
ref.insert(20, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
ref.insert(20, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True)
ref.insert(29, Play(self.short_pulse, self.config.measure(0)), inplace=True)
ref.insert(30, Play(self.short_pulse, self.config.measure(0)), inplace=True)
ref.insert(20, Play(self.short_pulse, self.config.measure(1)), inplace=True)
self.assertEqual(aligned, ref)
def test_align_post_u3(self):
"""Test that acquires are scheduled no sooner than the duration of the longest X gate."""
sched = pulse.Schedule(name="fake_experiment")
sched = sched.insert(0, Play(self.short_pulse, self.config.drive(0)))
sched = sched.insert(1, Acquire(5, self.config.acquire(0), MemorySlot(0)))
sched = transforms.align_measures([sched], self.inst_map)[0]
for time, inst in sched.instructions:
if isinstance(inst, Acquire):
self.assertEqual(time, 4)
sched = transforms.align_measures([sched], self.inst_map, max_calibration_duration=10)[0]
for time, inst in sched.instructions:
if isinstance(inst, Acquire):
self.assertEqual(time, 10)
def test_multi_acquire(self):
"""Test that the last acquire is aligned to if multiple acquires occur on the
same channel."""
sched = pulse.Schedule()
sched.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True)
sched.insert(4, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
sched.insert(20, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True)
sched.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
aligned = transforms.align_measures([sched], self.inst_map)
ref = pulse.Schedule()
ref.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True)
ref.insert(20, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
ref.insert(20, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True)
ref.insert(26, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
self.assertEqual(aligned[0], ref)
def test_multiple_acquires(self):
"""Test that multiple acquires are also aligned."""
sched = pulse.Schedule(name="fake_experiment")
sched.insert(0, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
sched.insert(5, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
sched.insert(10, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True)
ref = pulse.Schedule()
ref.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
ref.insert(15, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
ref.insert(10, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True)
aligned = transforms.align_measures([sched], self.inst_map)[0]
self.assertEqual(aligned, ref)
def test_align_across_schedules(self):
"""Test that acquires are aligned together across multiple schedules."""
sched1 = pulse.Schedule(name="fake_experiment")
sched1 = sched1.insert(0, Play(self.short_pulse, self.config.drive(0)))
sched1 = sched1.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0)))
sched2 = pulse.Schedule(name="fake_experiment")
sched2 = sched2.insert(3, Play(self.short_pulse, self.config.drive(0)))
sched2 = sched2.insert(25, Acquire(5, self.config.acquire(0), MemorySlot(0)))
schedules = transforms.align_measures([sched1, sched2], self.inst_map)
for time, inst in schedules[0].instructions:
if isinstance(inst, Acquire):
self.assertEqual(time, 25)
for time, inst in schedules[0].instructions:
if isinstance(inst, Acquire):
self.assertEqual(time, 25)
def test_align_all(self):
"""Test alignment of all instructions in a schedule."""
sched0 = pulse.Schedule()
sched0.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True)
sched0.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
sched1 = pulse.Schedule()
sched1.insert(25, Play(self.short_pulse, self.config.drive(0)), inplace=True)
sched1.insert(25, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
all_aligned = transforms.align_measures([sched0, sched1], self.inst_map, align_all=True)
ref1_aligned = pulse.Schedule()
ref1_aligned.insert(15, Play(self.short_pulse, self.config.drive(0)), inplace=True)
ref1_aligned.insert(25, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
self.assertEqual(all_aligned[0], ref1_aligned)
self.assertEqual(all_aligned[1], sched1)
ref1_not_aligned = pulse.Schedule()
ref1_not_aligned.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True)
ref1_not_aligned.insert(25, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
all_not_aligned = transforms.align_measures(
[sched0, sched1],
self.inst_map,
align_all=False,
)
self.assertEqual(all_not_aligned[0], ref1_not_aligned)
self.assertEqual(all_not_aligned[1], sched1)
def test_measurement_at_zero(self):
"""Test that acquire at t=0 works."""
sched1 = pulse.Schedule(name="fake_experiment")
sched1 = sched1.insert(0, Play(self.short_pulse, self.config.drive(0)))
sched1 = sched1.insert(0, Acquire(5, self.config.acquire(0), MemorySlot(0)))
sched2 = pulse.Schedule(name="fake_experiment")
sched2 = sched2.insert(0, Play(self.short_pulse, self.config.drive(0)))
sched2 = sched2.insert(0, Acquire(5, self.config.acquire(0), MemorySlot(0)))
schedules = transforms.align_measures([sched1, sched2], max_calibration_duration=0)
for time, inst in schedules[0].instructions:
if isinstance(inst, Acquire):
self.assertEqual(time, 0)
for time, inst in schedules[0].instructions:
if isinstance(inst, Acquire):
self.assertEqual(time, 0)
class TestAddImplicitAcquires(QiskitTestCase):
"""Test the helper function which makes implicit acquires explicit."""
def setUp(self):
super().setUp()
self.backend = FakeOpenPulse2Q()
self.config = self.backend.configuration()
self.short_pulse = pulse.Waveform(
samples=np.array([0.02739068], dtype=np.complex128), name="p0"
)
sched = pulse.Schedule(name="fake_experiment")
sched = sched.insert(0, Play(self.short_pulse, self.config.drive(0)))
sched = sched.insert(5, Acquire(5, self.config.acquire(0), MemorySlot(0)))
sched = sched.insert(5, Acquire(5, self.config.acquire(1), MemorySlot(1)))
self.sched = sched
def test_add_implicit(self):
"""Test that implicit acquires are made explicit according to the meas map."""
sched = transforms.add_implicit_acquires(self.sched, [[0, 1]])
acquired_qubits = set()
for _, inst in sched.instructions:
if isinstance(inst, Acquire):
acquired_qubits.add(inst.acquire.index)
self.assertEqual(acquired_qubits, {0, 1})
def test_add_across_meas_map_sublists(self):
"""Test that implicit acquires in separate meas map sublists are all added."""
sched = transforms.add_implicit_acquires(self.sched, [[0, 2], [1, 3]])
acquired_qubits = set()
for _, inst in sched.instructions:
if isinstance(inst, Acquire):
acquired_qubits.add(inst.acquire.index)
self.assertEqual(acquired_qubits, {0, 1, 2, 3})
def test_dont_add_all(self):
"""Test that acquires aren't added if no qubits in the sublist aren't being acquired."""
sched = transforms.add_implicit_acquires(self.sched, [[4, 5], [0, 2], [1, 3]])
acquired_qubits = set()
for _, inst in sched.instructions:
if isinstance(inst, Acquire):
acquired_qubits.add(inst.acquire.index)
self.assertEqual(acquired_qubits, {0, 1, 2, 3})
def test_multiple_acquires(self):
"""Test for multiple acquires."""
sched = pulse.Schedule()
acq_q0 = pulse.Acquire(1200, AcquireChannel(0), MemorySlot(0))
sched += acq_q0
sched += acq_q0 << sched.duration
sched = transforms.add_implicit_acquires(sched, meas_map=[[0]])
self.assertEqual(sched.instructions, ((0, acq_q0), (2400, acq_q0)))
class TestPad(QiskitTestCase):
"""Test padding of schedule with delays."""
def test_padding_empty_schedule(self):
"""Test padding of empty schedule."""
self.assertEqual(pulse.Schedule(), transforms.pad(pulse.Schedule()))
def test_padding_schedule(self):
"""Test padding schedule."""
delay = 10
sched = (
Delay(delay, DriveChannel(0)).shift(10)
+ Delay(delay, DriveChannel(0)).shift(10)
+ Delay(delay, DriveChannel(1)).shift(10)
)
ref_sched = (
sched # pylint: disable=unsupported-binary-operation
| Delay(delay, DriveChannel(0))
| Delay(delay, DriveChannel(0)).shift(20)
| Delay(delay, DriveChannel(1))
| Delay( # pylint: disable=unsupported-binary-operation
2 * delay, DriveChannel(1)
).shift(20)
)
self.assertEqual(transforms.pad(sched), ref_sched)
def test_padding_schedule_inverse_order(self):
"""Test padding schedule is insensitive to order in which commands were added.
This test is the same as `test_adding_schedule` but the order by channel
in which commands were added to the schedule to be padded has been reversed.
"""
delay = 10
sched = (
Delay(delay, DriveChannel(1)).shift(10)
+ Delay(delay, DriveChannel(0)).shift(10)
+ Delay(delay, DriveChannel(0)).shift(10)
)
ref_sched = (
sched # pylint: disable=unsupported-binary-operation
| Delay(delay, DriveChannel(0))
| Delay(delay, DriveChannel(0)).shift(20)
| Delay(delay, DriveChannel(1))
| Delay( # pylint: disable=unsupported-binary-operation
2 * delay, DriveChannel(1)
).shift(20)
)
self.assertEqual(transforms.pad(sched), ref_sched)
def test_padding_until_less(self):
"""Test padding until time that is less than schedule duration."""
delay = 10
sched = Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(1))
ref_sched = sched | Delay(delay, DriveChannel(0)) | Delay(5, DriveChannel(1)).shift(10)
self.assertEqual(transforms.pad(sched, until=15), ref_sched)
def test_padding_until_greater(self):
"""Test padding until time that is greater than schedule duration."""
delay = 10
sched = Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(1))
ref_sched = (
sched # pylint: disable=unsupported-binary-operation
| Delay(delay, DriveChannel(0))
| Delay(30, DriveChannel(0)).shift(20)
| Delay(40, DriveChannel(1)).shift(10) # pylint: disable=unsupported-binary-operation
)
self.assertEqual(transforms.pad(sched, until=50), ref_sched)
def test_padding_supplied_channels(self):
"""Test padding of only specified channels."""
delay = 10
sched = Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(1))
ref_sched = sched | Delay(delay, DriveChannel(0)) | Delay(2 * delay, DriveChannel(2))
channels = [DriveChannel(0), DriveChannel(2)]
self.assertEqual(transforms.pad(sched, channels=channels), ref_sched)
def test_padding_less_than_sched_duration(self):
"""Test that the until arg is respected even for less than the input schedule duration."""
delay = 10
sched = Delay(delay, DriveChannel(0)) + Delay(delay, DriveChannel(0)).shift(20)
ref_sched = sched | pulse.Delay(5, DriveChannel(0)).shift(10)
self.assertEqual(transforms.pad(sched, until=15), ref_sched)
def test_padding_prepended_delay(self):
"""Test that there is delay before the first instruction."""
delay = 10
sched = Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(0))
ref_sched = (
Delay(delay, DriveChannel(0))
+ Delay(delay, DriveChannel(0))
+ Delay(delay, DriveChannel(0))
)
self.assertEqual(transforms.pad(sched, until=30, inplace=True), ref_sched)
def test_pad_no_delay_on_classical_io_channels(self):
"""Test padding does not apply to classical IO channels."""
delay = 10
sched = (
Delay(delay, MemorySlot(0)).shift(20)
+ Delay(delay, RegisterSlot(0)).shift(10)
+ Delay(delay, SnapshotChannel())
)
ref_sched = (
Delay(delay, MemorySlot(0)).shift(20)
+ Delay(delay, RegisterSlot(0)).shift(10)
+ Delay(delay, SnapshotChannel())
)
self.assertEqual(transforms.pad(sched, until=15), ref_sched)
def get_pulse_ids(schedules: List[Schedule]) -> Set[int]:
"""Returns ids of pulses used in Schedules."""
ids = set()
for schedule in schedules:
for _, inst in schedule.instructions:
ids.add(inst.pulse.id)
return ids
class TestCompressTransform(QiskitTestCase):
"""Compress function test."""
def test_with_duplicates(self):
"""Test compression of schedule."""
schedule = Schedule()
drive_channel = DriveChannel(0)
schedule += Play(Waveform([0.0, 0.1]), drive_channel)
schedule += Play(Waveform([0.0, 0.1]), drive_channel)
compressed_schedule = transforms.compress_pulses([schedule])
original_pulse_ids = get_pulse_ids([schedule])
compressed_pulse_ids = get_pulse_ids(compressed_schedule)
self.assertEqual(len(compressed_pulse_ids), 1)
self.assertEqual(len(original_pulse_ids), 2)
self.assertTrue(next(iter(compressed_pulse_ids)) in original_pulse_ids)
def test_sample_pulse_with_clipping(self):
"""Test sample pulses with clipping."""
schedule = Schedule()
drive_channel = DriveChannel(0)
schedule += Play(Waveform([0.0, 1.0]), drive_channel)
schedule += Play(Waveform([0.0, 1.001], epsilon=1e-3), drive_channel)
schedule += Play(Waveform([0.0, 1.0000000001]), drive_channel)
compressed_schedule = transforms.compress_pulses([schedule])
original_pulse_ids = get_pulse_ids([schedule])
compressed_pulse_ids = get_pulse_ids(compressed_schedule)
self.assertEqual(len(compressed_pulse_ids), 1)
self.assertEqual(len(original_pulse_ids), 3)
self.assertTrue(next(iter(compressed_pulse_ids)) in original_pulse_ids)
def test_no_duplicates(self):
"""Test with no pulse duplicates."""
schedule = Schedule()
drive_channel = DriveChannel(0)
schedule += Play(Waveform([0.0, 1.0]), drive_channel)
schedule += Play(Waveform([0.0, 0.9]), drive_channel)
schedule += Play(Waveform([0.0, 0.3]), drive_channel)
compressed_schedule = transforms.compress_pulses([schedule])
original_pulse_ids = get_pulse_ids([schedule])
compressed_pulse_ids = get_pulse_ids(compressed_schedule)
self.assertEqual(len(original_pulse_ids), len(compressed_pulse_ids))
def test_parametric_pulses_with_duplicates(self):
"""Test with parametric pulses."""
schedule = Schedule()
drive_channel = DriveChannel(0)
schedule += Play(Gaussian(duration=25, sigma=4, amp=0.5, angle=np.pi / 2), drive_channel)
schedule += Play(Gaussian(duration=25, sigma=4, amp=0.5, angle=np.pi / 2), drive_channel)
schedule += Play(GaussianSquare(duration=150, amp=0.2, sigma=8, width=140), drive_channel)
schedule += Play(GaussianSquare(duration=150, amp=0.2, sigma=8, width=140), drive_channel)
schedule += Play(Constant(duration=150, amp=0.5, angle=0.7), drive_channel)
schedule += Play(Constant(duration=150, amp=0.5, angle=0.7), drive_channel)
schedule += Play(Drag(duration=25, amp=0.4, angle=-0.3, sigma=7.8, beta=4), drive_channel)
schedule += Play(Drag(duration=25, amp=0.4, angle=-0.3, sigma=7.8, beta=4), drive_channel)
compressed_schedule = transforms.compress_pulses([schedule])
original_pulse_ids = get_pulse_ids([schedule])
compressed_pulse_ids = get_pulse_ids(compressed_schedule)
self.assertEqual(len(original_pulse_ids), 8)
self.assertEqual(len(compressed_pulse_ids), 4)
def test_parametric_pulses_with_no_duplicates(self):
"""Test parametric pulses with no duplicates."""
schedule = Schedule()
drive_channel = DriveChannel(0)
schedule += Play(Gaussian(duration=25, sigma=4, amp=0.5, angle=np.pi / 2), drive_channel)
schedule += Play(Gaussian(duration=25, sigma=4, amp=0.49, angle=np.pi / 2), drive_channel)
schedule += Play(GaussianSquare(duration=150, amp=0.2, sigma=8, width=140), drive_channel)
schedule += Play(GaussianSquare(duration=150, amp=0.19, sigma=8, width=140), drive_channel)
schedule += Play(Constant(duration=150, amp=0.5, angle=0.3), drive_channel)
schedule += Play(Constant(duration=150, amp=0.51, angle=0.3), drive_channel)
schedule += Play(Drag(duration=25, amp=0.5, angle=0.5, sigma=7.8, beta=4), drive_channel)
schedule += Play(Drag(duration=25, amp=0.5, angle=0.51, sigma=7.8, beta=4), drive_channel)
compressed_schedule = transforms.compress_pulses([schedule])
original_pulse_ids = get_pulse_ids([schedule])
compressed_pulse_ids = get_pulse_ids(compressed_schedule)
self.assertEqual(len(original_pulse_ids), len(compressed_pulse_ids))
def test_with_different_channels(self):
"""Test with different channels."""
schedule = Schedule()
schedule += Play(Waveform([0.0, 0.1]), DriveChannel(0))
schedule += Play(Waveform([0.0, 0.1]), DriveChannel(1))
compressed_schedule = transforms.compress_pulses([schedule])
original_pulse_ids = get_pulse_ids([schedule])
compressed_pulse_ids = get_pulse_ids(compressed_schedule)
self.assertEqual(len(original_pulse_ids), 2)
self.assertEqual(len(compressed_pulse_ids), 1)
def test_sample_pulses_with_tolerance(self):
"""Test sample pulses with tolerance."""
schedule = Schedule()
schedule += Play(Waveform([0.0, 0.1001], epsilon=1e-3), DriveChannel(0))
schedule += Play(Waveform([0.0, 0.1], epsilon=1e-3), DriveChannel(1))
compressed_schedule = transforms.compress_pulses([schedule])
original_pulse_ids = get_pulse_ids([schedule])
compressed_pulse_ids = get_pulse_ids(compressed_schedule)
self.assertEqual(len(original_pulse_ids), 2)
self.assertEqual(len(compressed_pulse_ids), 1)
def test_multiple_schedules(self):
"""Test multiple schedules."""
schedules = []
for _ in range(2):
schedule = Schedule()
drive_channel = DriveChannel(0)
schedule += Play(Waveform([0.0, 0.1]), drive_channel)
schedule += Play(Waveform([0.0, 0.1]), drive_channel)
schedule += Play(Waveform([0.0, 0.2]), drive_channel)
schedules.append(schedule)
compressed_schedule = transforms.compress_pulses(schedules)
original_pulse_ids = get_pulse_ids(schedules)
compressed_pulse_ids = get_pulse_ids(compressed_schedule)
self.assertEqual(len(original_pulse_ids), 6)
self.assertEqual(len(compressed_pulse_ids), 2)
class TestAlignSequential(QiskitTestCase):
"""Test sequential alignment transform."""
def test_align_sequential(self):
"""Test sequential alignment without a barrier."""
context = transforms.AlignSequential()
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
schedule = pulse.Schedule()
schedule.insert(1, instructions.Delay(3, d0), inplace=True)
schedule.insert(4, instructions.Delay(5, d1), inplace=True)
schedule.insert(12, instructions.Delay(7, d0), inplace=True)
schedule = context.align(schedule)
reference = pulse.Schedule()
# d0
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(8, instructions.Delay(7, d0), inplace=True)
# d1
reference.insert(3, instructions.Delay(5, d1), inplace=True)
self.assertEqual(schedule, reference)
def test_align_sequential_with_barrier(self):
"""Test sequential alignment with a barrier."""
context = transforms.AlignSequential()
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
schedule = pulse.Schedule()
schedule.insert(1, instructions.Delay(3, d0), inplace=True)
schedule.append(directives.RelativeBarrier(d0, d1), inplace=True)
schedule.insert(4, instructions.Delay(5, d1), inplace=True)
schedule.insert(12, instructions.Delay(7, d0), inplace=True)
schedule = context.align(schedule)
reference = pulse.Schedule()
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(3, directives.RelativeBarrier(d0, d1), inplace=True)
reference.insert(3, instructions.Delay(5, d1), inplace=True)
reference.insert(8, instructions.Delay(7, d0), inplace=True)
self.assertEqual(schedule, reference)
class TestAlignLeft(QiskitTestCase):
"""Test left alignment transform."""
def test_align_left(self):
"""Test left alignment without a barrier."""
context = transforms.AlignLeft()
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
d2 = pulse.DriveChannel(2)
schedule = pulse.Schedule()
schedule.insert(1, instructions.Delay(3, d0), inplace=True)
schedule.insert(17, instructions.Delay(11, d2), inplace=True)
sched_grouped = pulse.Schedule()
sched_grouped += instructions.Delay(5, d1)
sched_grouped += instructions.Delay(7, d0)
schedule.append(sched_grouped, inplace=True)
schedule = context.align(schedule)
reference = pulse.Schedule()
# d0
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(3, instructions.Delay(7, d0), inplace=True)
# d1
reference.insert(3, instructions.Delay(5, d1), inplace=True)
# d2
reference.insert(0, instructions.Delay(11, d2), inplace=True)
self.assertEqual(schedule, reference)
def test_align_left_with_barrier(self):
"""Test left alignment with a barrier."""
context = transforms.AlignLeft()
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
d2 = pulse.DriveChannel(2)
schedule = pulse.Schedule()
schedule.insert(1, instructions.Delay(3, d0), inplace=True)
schedule.append(directives.RelativeBarrier(d0, d1, d2), inplace=True)
schedule.insert(17, instructions.Delay(11, d2), inplace=True)
sched_grouped = pulse.Schedule()
sched_grouped += instructions.Delay(5, d1)
sched_grouped += instructions.Delay(7, d0)
schedule.append(sched_grouped, inplace=True)
schedule = transforms.remove_directives(context.align(schedule))
reference = pulse.Schedule()
# d0
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(3, instructions.Delay(7, d0), inplace=True)
# d1
reference = reference.insert(3, instructions.Delay(5, d1))
# d2
reference = reference.insert(3, instructions.Delay(11, d2))
self.assertEqual(schedule, reference)
class TestAlignRight(QiskitTestCase):
"""Test right alignment transform."""
def test_align_right(self):
"""Test right alignment without a barrier."""
context = transforms.AlignRight()
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
d2 = pulse.DriveChannel(2)
schedule = pulse.Schedule()
schedule.insert(1, instructions.Delay(3, d0), inplace=True)
schedule.insert(17, instructions.Delay(11, d2), inplace=True)
sched_grouped = pulse.Schedule()
sched_grouped.insert(2, instructions.Delay(5, d1), inplace=True)
sched_grouped += instructions.Delay(7, d0)
schedule.append(sched_grouped, inplace=True)
schedule = context.align(schedule)
reference = pulse.Schedule()
# d0
reference.insert(1, instructions.Delay(3, d0), inplace=True)
reference.insert(4, instructions.Delay(7, d0), inplace=True)
# d1
reference.insert(6, instructions.Delay(5, d1), inplace=True)
# d2
reference.insert(0, instructions.Delay(11, d2), inplace=True)
self.assertEqual(schedule, reference)
def test_align_right_with_barrier(self):
"""Test right alignment with a barrier."""
context = transforms.AlignRight()
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
d2 = pulse.DriveChannel(2)
schedule = pulse.Schedule()
schedule.insert(1, instructions.Delay(3, d0), inplace=True)
schedule.append(directives.RelativeBarrier(d0, d1, d2), inplace=True)
schedule.insert(17, instructions.Delay(11, d2), inplace=True)
sched_grouped = pulse.Schedule()
sched_grouped.insert(2, instructions.Delay(5, d1), inplace=True)
sched_grouped += instructions.Delay(7, d0)
schedule.append(sched_grouped, inplace=True)
schedule = transforms.remove_directives(context.align(schedule))
reference = pulse.Schedule()
# d0
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(7, instructions.Delay(7, d0), inplace=True)
# d1
reference.insert(9, instructions.Delay(5, d1), inplace=True)
# d2
reference.insert(3, instructions.Delay(11, d2), inplace=True)
self.assertEqual(schedule, reference)
class TestAlignEquispaced(QiskitTestCase):
"""Test equispaced alignment transform."""
def test_equispaced_with_short_duration(self):
"""Test equispaced context with duration shorter than the schedule duration."""
context = transforms.AlignEquispaced(duration=20)
d0 = pulse.DriveChannel(0)
schedule = pulse.Schedule()
for _ in range(3):
schedule.append(Delay(10, d0), inplace=True)
schedule = context.align(schedule)
reference = pulse.Schedule()
reference.insert(0, Delay(10, d0), inplace=True)
reference.insert(10, Delay(10, d0), inplace=True)
reference.insert(20, Delay(10, d0), inplace=True)
self.assertEqual(schedule, reference)
def test_equispaced_with_longer_duration(self):
"""Test equispaced context with duration longer than the schedule duration."""
context = transforms.AlignEquispaced(duration=50)
d0 = pulse.DriveChannel(0)
schedule = pulse.Schedule()
for _ in range(3):
schedule.append(Delay(10, d0), inplace=True)
schedule = context.align(schedule)
reference = pulse.Schedule()
reference.insert(0, Delay(10, d0), inplace=True)
reference.insert(20, Delay(10, d0), inplace=True)
reference.insert(40, Delay(10, d0), inplace=True)
self.assertEqual(schedule, reference)
def test_equispaced_with_multiple_channels_short_duration(self):
"""Test equispaced context with multiple channels and duration shorter than the total
duration."""
context = transforms.AlignEquispaced(duration=20)
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
schedule = pulse.Schedule()
schedule.append(Delay(10, d0), inplace=True)
schedule.append(Delay(20, d1), inplace=True)
schedule = context.align(schedule)
reference = pulse.Schedule()
reference.insert(0, Delay(10, d0), inplace=True)
reference.insert(0, Delay(20, d1), inplace=True)
self.assertEqual(schedule, reference)
def test_equispaced_with_multiple_channels_longer_duration(self):
"""Test equispaced context with multiple channels and duration longer than the total
duration."""
context = transforms.AlignEquispaced(duration=30)
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
schedule = pulse.Schedule()
schedule.append(Delay(10, d0), inplace=True)
schedule.append(Delay(20, d1), inplace=True)
schedule = context.align(schedule)
reference = pulse.Schedule()
reference.insert(0, Delay(10, d0), inplace=True)
reference.insert(10, Delay(20, d1), inplace=True)
self.assertEqual(schedule, reference)
class TestAlignFunc(QiskitTestCase):
"""Test callback alignment transform."""
@staticmethod
def _position(ind):
"""Returns 0.25, 0.5, 0.75 for ind = 1, 2, 3."""
return ind / (3 + 1)
def test_numerical_with_short_duration(self):
"""Test numerical alignment context with duration shorter than the schedule duration."""
context = transforms.AlignFunc(duration=20, func=self._position)
d0 = pulse.DriveChannel(0)
schedule = pulse.Schedule()
for _ in range(3):
schedule.append(Delay(10, d0), inplace=True)
schedule = context.align(schedule)
reference = pulse.Schedule()
reference.insert(0, Delay(10, d0), inplace=True)
reference.insert(10, Delay(10, d0), inplace=True)
reference.insert(20, Delay(10, d0), inplace=True)
self.assertEqual(schedule, reference)
def test_numerical_with_longer_duration(self):
"""Test numerical alignment context with duration longer than the schedule duration."""
context = transforms.AlignFunc(duration=80, func=self._position)
d0 = pulse.DriveChannel(0)
schedule = pulse.Schedule()
for _ in range(3):
schedule.append(Delay(10, d0), inplace=True)
schedule = context.align(schedule)
reference = pulse.Schedule()
reference.insert(15, Delay(10, d0), inplace=True)
reference.insert(35, Delay(10, d0), inplace=True)
reference.insert(55, Delay(10, d0), inplace=True)
self.assertEqual(schedule, reference)
class TestFlatten(QiskitTestCase):
"""Test flattening transform."""
def test_flatten(self):
"""Test the flatten transform."""
context_left = transforms.AlignLeft()
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
schedule = pulse.Schedule()
schedule += instructions.Delay(3, d0)
grouped = pulse.Schedule()
grouped += instructions.Delay(5, d1)
grouped += instructions.Delay(7, d0)
# include a grouped schedule
grouped = schedule + grouped
# flatten the schedule inline internal groups
flattened = transforms.flatten(grouped)
# align all the instructions to the left after flattening
flattened = context_left.align(flattened)
grouped = context_left.align(grouped)
reference = pulse.Schedule()
# d0
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(3, instructions.Delay(7, d0), inplace=True)
# d1
reference.insert(0, instructions.Delay(5, d1), inplace=True)
self.assertEqual(flattened, reference)
self.assertNotEqual(grouped, reference)
class _TestDirective(directives.Directive):
"""Pulse ``RelativeBarrier`` directive."""
def __init__(self, *channels):
"""Test directive"""
super().__init__(operands=tuple(channels))
@property
def channels(self):
return self.operands
class TestRemoveDirectives(QiskitTestCase):
"""Test removing of directives."""
def test_remove_directives(self):
"""Test that all directives are removed."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
schedule = pulse.Schedule()
schedule += _TestDirective(d0, d1)
schedule += instructions.Delay(3, d0)
schedule += _TestDirective(d0, d1)
schedule = transforms.remove_directives(schedule)
reference = pulse.Schedule()
# d0
reference += instructions.Delay(3, d0)
self.assertEqual(schedule, reference)
class TestRemoveTrivialBarriers(QiskitTestCase):
"""Test scheduling transforms."""
def test_remove_trivial_barriers(self):
"""Test that trivial barriers are properly removed."""
schedule = pulse.Schedule()
schedule += directives.RelativeBarrier()
schedule += directives.RelativeBarrier(pulse.DriveChannel(0))
schedule += directives.RelativeBarrier(pulse.DriveChannel(0), pulse.DriveChannel(1))
schedule = transforms.remove_trivial_barriers(schedule)
reference = pulse.Schedule()
reference += directives.RelativeBarrier(pulse.DriveChannel(0), pulse.DriveChannel(1))
self.assertEqual(schedule, reference)
class TestRemoveSubroutines(QiskitTestCase):
"""Test removing of subroutines."""
def test_remove_subroutines(self):
"""Test that nested subroutiens are removed."""
d0 = pulse.DriveChannel(0)
nested_routine = pulse.Schedule()
nested_routine.insert(10, pulse.Delay(10, d0), inplace=True)
subroutine = pulse.Schedule()
subroutine.insert(0, pulse.Delay(20, d0), inplace=True)
with self.assertWarns(DeprecationWarning):
subroutine.insert(20, pulse.instructions.Call(nested_routine), inplace=True)
subroutine.insert(50, pulse.Delay(10, d0), inplace=True)
main_program = pulse.Schedule()
main_program.insert(0, pulse.Delay(10, d0), inplace=True)
with self.assertWarns(DeprecationWarning):
main_program.insert(30, pulse.instructions.Call(subroutine), inplace=True)
target = transforms.inline_subroutines(main_program)
reference = pulse.Schedule()
reference.insert(0, pulse.Delay(10, d0), inplace=True)
reference.insert(30, pulse.Delay(20, d0), inplace=True)
reference.insert(60, pulse.Delay(10, d0), inplace=True)
reference.insert(80, pulse.Delay(10, d0), inplace=True)
self.assertEqual(target, reference)
def test_call_in_nested_schedule(self):
"""Test that subroutines in nested schedule."""
d0 = pulse.DriveChannel(0)
subroutine = pulse.Schedule()
subroutine.insert(10, pulse.Delay(10, d0), inplace=True)
nested_sched = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
nested_sched.insert(0, pulse.instructions.Call(subroutine), inplace=True)
main_sched = pulse.Schedule()
main_sched.insert(0, nested_sched, inplace=True)
target = transforms.inline_subroutines(main_sched)
# no call instruction
reference_nested = pulse.Schedule()
reference_nested.insert(0, subroutine, inplace=True)
reference = pulse.Schedule()
reference.insert(0, reference_nested, inplace=True)
self.assertEqual(target, reference)
def test_call_in_nested_block(self):
"""Test that subroutines in nested schedule."""
d0 = pulse.DriveChannel(0)
subroutine = pulse.ScheduleBlock()
subroutine.append(pulse.Delay(10, d0), inplace=True)
nested_block = pulse.ScheduleBlock()
with self.assertWarns(DeprecationWarning):
nested_block.append(pulse.instructions.Call(subroutine), inplace=True)
main_block = pulse.ScheduleBlock()
main_block.append(nested_block, inplace=True)
target = transforms.inline_subroutines(main_block)
# no call instruction
reference_nested = pulse.ScheduleBlock()
reference_nested.append(subroutine, inplace=True)
reference = pulse.ScheduleBlock()
reference.append(reference_nested, inplace=True)
self.assertEqual(target, reference)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""These tests are the examples given in the arXiv paper describing OpenQASM 2. Specifically, there
is a test for each subsection (except the description of 'qelib1.inc') in section 3 of
https://arxiv.org/abs/1707.03429v2. The examples are copy/pasted from the source files there."""
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
import math
import os
import tempfile
import ddt
from qiskit import qasm2
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister, Qubit
from qiskit.circuit.library import U1Gate, U3Gate, CU1Gate
from qiskit.test import QiskitTestCase
from . import gate_builder
def load(string, *args, **kwargs):
# We're deliberately not using the context-manager form here because we need to use it in a
# slightly odd pattern.
# pylint: disable=consider-using-with
temp = tempfile.NamedTemporaryFile(mode="w", delete=False)
try:
temp.write(string)
# NamedTemporaryFile claims not to be openable a second time on Windows, so close it
# (without deletion) so Rust can open it again.
temp.close()
return qasm2.load(temp.name, *args, **kwargs)
finally:
# Now actually clean up after ourselves.
os.unlink(temp.name)
@ddt.ddt
class TestArxivExamples(QiskitTestCase):
@ddt.data(qasm2.loads, load)
def test_teleportation(self, parser):
example = """\
// quantum teleportation example
OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
creg c0[1];
creg c1[1];
creg c2[1];
// optional post-rotation for state tomography
gate post q { }
u3(0.3,0.2,0.1) q[0];
h q[1];
cx q[1],q[2];
barrier q;
cx q[0],q[1];
h q[0];
measure q[0] -> c0[0];
measure q[1] -> c1[0];
if(c0==1) z q[2];
if(c1==1) x q[2];
post q[2];
measure q[2] -> c2[0];"""
parsed = parser(example)
post = gate_builder("post", [], QuantumCircuit([Qubit()]))
q = QuantumRegister(3, "q")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
c2 = ClassicalRegister(1, "c2")
qc = QuantumCircuit(q, c0, c1, c2)
qc.append(U3Gate(0.3, 0.2, 0.1), [q[0]], [])
qc.h(q[1])
qc.cx(q[1], q[2])
qc.barrier(q)
qc.cx(q[0], q[1])
qc.h(q[0])
qc.measure(q[0], c0[0])
qc.measure(q[1], c1[0])
qc.z(q[2]).c_if(c0, 1)
qc.x(q[2]).c_if(c1, 1)
qc.append(post(), [q[2]], [])
qc.measure(q[2], c2[0])
self.assertEqual(parsed, qc)
@ddt.data(qasm2.loads, load)
def test_qft(self, parser):
example = """\
// quantum Fourier transform
OPENQASM 2.0;
include "qelib1.inc";
qreg q[4];
creg c[4];
x q[0];
x q[2];
barrier q;
h q[0];
cu1(pi/2) q[1],q[0];
h q[1];
cu1(pi/4) q[2],q[0];
cu1(pi/2) q[2],q[1];
h q[2];
cu1(pi/8) q[3],q[0];
cu1(pi/4) q[3],q[1];
cu1(pi/2) q[3],q[2];
h q[3];
measure q -> c;"""
parsed = parser(example)
qc = QuantumCircuit(QuantumRegister(4, "q"), ClassicalRegister(4, "c"))
qc.x(0)
qc.x(2)
qc.barrier(range(4))
qc.h(0)
qc.append(CU1Gate(math.pi / 2), [1, 0])
qc.h(1)
qc.append(CU1Gate(math.pi / 4), [2, 0])
qc.append(CU1Gate(math.pi / 2), [2, 1])
qc.h(2)
qc.append(CU1Gate(math.pi / 8), [3, 0])
qc.append(CU1Gate(math.pi / 4), [3, 1])
qc.append(CU1Gate(math.pi / 2), [3, 2])
qc.h(3)
qc.measure(range(4), range(4))
self.assertEqual(parsed, qc)
@ddt.data(qasm2.loads, load)
def test_inverse_qft_1(self, parser):
example = """\
// QFT and measure, version 1
OPENQASM 2.0;
include "qelib1.inc";
qreg q[4];
creg c[4];
h q;
barrier q;
h q[0];
measure q[0] -> c[0];
if(c==1) u1(pi/2) q[1];
h q[1];
measure q[1] -> c[1];
if(c==1) u1(pi/4) q[2];
if(c==2) u1(pi/2) q[2];
if(c==3) u1(pi/2+pi/4) q[2];
h q[2];
measure q[2] -> c[2];
if(c==1) u1(pi/8) q[3];
if(c==2) u1(pi/4) q[3];
if(c==3) u1(pi/4+pi/8) q[3];
if(c==4) u1(pi/2) q[3];
if(c==5) u1(pi/2+pi/8) q[3];
if(c==6) u1(pi/2+pi/4) q[3];
if(c==7) u1(pi/2+pi/4+pi/8) q[3];
h q[3];
measure q[3] -> c[3];"""
parsed = parser(example)
q = QuantumRegister(4, "q")
c = ClassicalRegister(4, "c")
qc = QuantumCircuit(q, c)
qc.h(q)
qc.barrier(q)
qc.h(q[0])
qc.measure(q[0], c[0])
qc.append(U1Gate(math.pi / 2).c_if(c, 1), [q[1]])
qc.h(q[1])
qc.measure(q[1], c[1])
qc.append(U1Gate(math.pi / 4).c_if(c, 1), [q[2]])
qc.append(U1Gate(math.pi / 2).c_if(c, 2), [q[2]])
qc.append(U1Gate(math.pi / 4 + math.pi / 2).c_if(c, 3), [q[2]])
qc.h(q[2])
qc.measure(q[2], c[2])
qc.append(U1Gate(math.pi / 8).c_if(c, 1), [q[3]])
qc.append(U1Gate(math.pi / 4).c_if(c, 2), [q[3]])
qc.append(U1Gate(math.pi / 8 + math.pi / 4).c_if(c, 3), [q[3]])
qc.append(U1Gate(math.pi / 2).c_if(c, 4), [q[3]])
qc.append(U1Gate(math.pi / 8 + math.pi / 2).c_if(c, 5), [q[3]])
qc.append(U1Gate(math.pi / 4 + math.pi / 2).c_if(c, 6), [q[3]])
qc.append(U1Gate(math.pi / 8 + math.pi / 4 + math.pi / 2).c_if(c, 7), [q[3]])
qc.h(q[3])
qc.measure(q[3], c[3])
self.assertEqual(parsed, qc)
@ddt.data(qasm2.loads, load)
def test_inverse_qft_2(self, parser):
example = """\
// QFT and measure, version 2
OPENQASM 2.0;
include "qelib1.inc";
qreg q[4];
creg c0[1];
creg c1[1];
creg c2[1];
creg c3[1];
h q;
barrier q;
h q[0];
measure q[0] -> c0[0];
if(c0==1) u1(pi/2) q[1];
h q[1];
measure q[1] -> c1[0];
if(c0==1) u1(pi/4) q[2];
if(c1==1) u1(pi/2) q[2];
h q[2];
measure q[2] -> c2[0];
if(c0==1) u1(pi/8) q[3];
if(c1==1) u1(pi/4) q[3];
if(c2==1) u1(pi/2) q[3];
h q[3];
measure q[3] -> c3[0];"""
parsed = parser(example)
q = QuantumRegister(4, "q")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
c2 = ClassicalRegister(1, "c2")
c3 = ClassicalRegister(1, "c3")
qc = QuantumCircuit(q, c0, c1, c2, c3)
qc.h(q)
qc.barrier(q)
qc.h(q[0])
qc.measure(q[0], c0[0])
qc.append(U1Gate(math.pi / 2).c_if(c0, 1), [q[1]])
qc.h(q[1])
qc.measure(q[1], c1[0])
qc.append(U1Gate(math.pi / 4).c_if(c0, 1), [q[2]])
qc.append(U1Gate(math.pi / 2).c_if(c1, 1), [q[2]])
qc.h(q[2])
qc.measure(q[2], c2[0])
qc.append(U1Gate(math.pi / 8).c_if(c0, 1), [q[3]])
qc.append(U1Gate(math.pi / 4).c_if(c1, 1), [q[3]])
qc.append(U1Gate(math.pi / 2).c_if(c2, 1), [q[3]])
qc.h(q[3])
qc.measure(q[3], c3[0])
self.assertEqual(parsed, qc)
@ddt.data(qasm2.loads, load)
def test_ripple_carry_adder(self, parser):
example = """\
// quantum ripple-carry adder from Cuccaro et al, quant-ph/0410184
OPENQASM 2.0;
include "qelib1.inc";
gate majority a,b,c
{
cx c,b;
cx c,a;
ccx a,b,c;
}
gate unmaj a,b,c
{
ccx a,b,c;
cx c,a;
cx a,b;
}
qreg cin[1];
qreg a[4];
qreg b[4];
qreg cout[1];
creg ans[5];
// set input states
x a[0]; // a = 0001
x b; // b = 1111
// add a to b, storing result in b
majority cin[0],b[0],a[0];
majority a[0],b[1],a[1];
majority a[1],b[2],a[2];
majority a[2],b[3],a[3];
cx a[3],cout[0];
unmaj a[2],b[3],a[3];
unmaj a[1],b[2],a[2];
unmaj a[0],b[1],a[1];
unmaj cin[0],b[0],a[0];
measure b[0] -> ans[0];
measure b[1] -> ans[1];
measure b[2] -> ans[2];
measure b[3] -> ans[3];
measure cout[0] -> ans[4];"""
parsed = parser(example)
majority_definition = QuantumCircuit([Qubit(), Qubit(), Qubit()])
majority_definition.cx(2, 1)
majority_definition.cx(2, 0)
majority_definition.ccx(0, 1, 2)
majority = gate_builder("majority", [], majority_definition)
unmaj_definition = QuantumCircuit([Qubit(), Qubit(), Qubit()])
unmaj_definition.ccx(0, 1, 2)
unmaj_definition.cx(2, 0)
unmaj_definition.cx(0, 1)
unmaj = gate_builder("unmaj", [], unmaj_definition)
cin = QuantumRegister(1, "cin")
a = QuantumRegister(4, "a")
b = QuantumRegister(4, "b")
cout = QuantumRegister(1, "cout")
ans = ClassicalRegister(5, "ans")
qc = QuantumCircuit(cin, a, b, cout, ans)
qc.x(a[0])
qc.x(b)
qc.append(majority(), [cin[0], b[0], a[0]])
qc.append(majority(), [a[0], b[1], a[1]])
qc.append(majority(), [a[1], b[2], a[2]])
qc.append(majority(), [a[2], b[3], a[3]])
qc.cx(a[3], cout[0])
qc.append(unmaj(), [a[2], b[3], a[3]])
qc.append(unmaj(), [a[1], b[2], a[2]])
qc.append(unmaj(), [a[0], b[1], a[1]])
qc.append(unmaj(), [cin[0], b[0], a[0]])
qc.measure(b, ans[:4])
qc.measure(cout[0], ans[4])
self.assertEqual(parsed, qc)
@ddt.data(qasm2.loads, load)
def test_randomised_benchmarking(self, parser):
example = """\
// One randomized benchmarking sequence
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[2];
h q[0];
barrier q;
cz q[0],q[1];
barrier q;
s q[0];
cz q[0],q[1];
barrier q;
s q[0];
z q[0];
h q[0];
barrier q;
measure q -> c;
"""
parsed = parser(example)
q = QuantumRegister(2, "q")
c = ClassicalRegister(2, "c")
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.barrier(q)
qc.cz(q[0], q[1])
qc.barrier(q)
qc.s(q[0])
qc.cz(q[0], q[1])
qc.barrier(q)
qc.s(q[0])
qc.z(q[0])
qc.h(q[0])
qc.barrier(q)
qc.measure(q, c)
self.assertEqual(parsed, qc)
@ddt.data(qasm2.loads, load)
def test_process_tomography(self, parser):
example = """\
OPENQASM 2.0;
include "qelib1.inc";
gate pre q { } // pre-rotation
gate post q { } // post-rotation
qreg q[1];
creg c[1];
pre q[0];
barrier q;
h q[0];
barrier q;
post q[0];
measure q[0] -> c[0];"""
parsed = parser(example)
pre = gate_builder("pre", [], QuantumCircuit([Qubit()]))
post = gate_builder("post", [], QuantumCircuit([Qubit()]))
qc = QuantumCircuit(QuantumRegister(1, "q"), ClassicalRegister(1, "c"))
qc.append(pre(), [0])
qc.barrier(qc.qubits)
qc.h(0)
qc.barrier(qc.qubits)
qc.append(post(), [0])
qc.measure(0, 0)
self.assertEqual(parsed, qc)
@ddt.data(qasm2.loads, load)
def test_error_correction(self, parser):
example = """\
// Repetition code syndrome measurement
OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
qreg a[2];
creg c[3];
creg syn[2];
gate syndrome d1,d2,d3,a1,a2
{
cx d1,a1; cx d2,a1;
cx d2,a2; cx d3,a2;
}
x q[0]; // error
barrier q;
syndrome q[0],q[1],q[2],a[0],a[1];
measure a -> syn;
if(syn==1) x q[0];
if(syn==2) x q[2];
if(syn==3) x q[1];
measure q -> c;"""
parsed = parser(example)
syndrome_definition = QuantumCircuit([Qubit() for _ in [None] * 5])
syndrome_definition.cx(0, 3)
syndrome_definition.cx(1, 3)
syndrome_definition.cx(1, 4)
syndrome_definition.cx(2, 4)
syndrome = gate_builder("syndrome", [], syndrome_definition)
q = QuantumRegister(3, "q")
a = QuantumRegister(2, "a")
c = ClassicalRegister(3, "c")
syn = ClassicalRegister(2, "syn")
qc = QuantumCircuit(q, a, c, syn)
qc.x(q[0])
qc.barrier(q)
qc.append(syndrome(), [q[0], q[1], q[2], a[0], a[1]])
qc.measure(a, syn)
qc.x(q[0]).c_if(syn, 1)
qc.x(q[2]).c_if(syn, 2)
qc.x(q[1]).c_if(syn, 3)
qc.measure(q, c)
self.assertEqual(parsed, qc)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test cases for the circuit qasm_file and qasm_string method."""
import os
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.circuit import Gate, Parameter
from qiskit.exceptions import QiskitError
from qiskit.test import QiskitTestCase
from qiskit.transpiler.passes import Unroller
from qiskit.converters.circuit_to_dag import circuit_to_dag
class LoadFromQasmTest(QiskitTestCase):
"""Test circuit.from_qasm_* set of methods."""
def setUp(self):
super().setUp()
self.qasm_file_name = "entangled_registers.qasm"
self.qasm_dir = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm"
)
self.qasm_file_path = os.path.join(self.qasm_dir, self.qasm_file_name)
def test_qasm_file(self):
"""
Test qasm_file and get_circuit.
If all is correct we should get the qasm file loaded in _qasm_file_path
"""
q_circuit = QuantumCircuit.from_qasm_file(self.qasm_file_path)
qr_a = QuantumRegister(4, "a")
qr_b = QuantumRegister(4, "b")
cr_c = ClassicalRegister(4, "c")
cr_d = ClassicalRegister(4, "d")
q_circuit_2 = QuantumCircuit(qr_a, qr_b, cr_c, cr_d)
q_circuit_2.h(qr_a)
q_circuit_2.cx(qr_a, qr_b)
q_circuit_2.barrier(qr_a)
q_circuit_2.barrier(qr_b)
q_circuit_2.measure(qr_a, cr_c)
q_circuit_2.measure(qr_b, cr_d)
self.assertEqual(q_circuit, q_circuit_2)
def test_loading_all_qelib1_gates(self):
"""Test setting up a circuit with all gates defined in qiskit/qasm/libs/qelib1.inc."""
from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate, UGate
all_gates_qasm = os.path.join(self.qasm_dir, "all_gates.qasm")
qasm_circuit = QuantumCircuit.from_qasm_file(all_gates_qasm)
ref_circuit = QuantumCircuit(3, 3)
# abstract gates (legacy)
ref_circuit.append(UGate(0.2, 0.1, 0.6), [0])
ref_circuit.cx(0, 1)
# the hardware primitives
ref_circuit.append(U3Gate(0.2, 0.1, 0.6), [0])
ref_circuit.append(U2Gate(0.1, 0.6), [0])
ref_circuit.append(U1Gate(0.6), [0])
ref_circuit.id(0)
ref_circuit.cx(0, 1)
# the standard single qubit gates
ref_circuit.u(0.2, 0.1, 0.6, 0)
ref_circuit.p(0.6, 0)
ref_circuit.x(0)
ref_circuit.y(0)
ref_circuit.z(0)
ref_circuit.h(0)
ref_circuit.s(0)
ref_circuit.t(0)
ref_circuit.sdg(0)
ref_circuit.tdg(0)
ref_circuit.sx(0)
ref_circuit.sxdg(0)
# the standard rotations
ref_circuit.rx(0.1, 0)
ref_circuit.ry(0.1, 0)
ref_circuit.rz(0.1, 0)
# the barrier
ref_circuit.barrier()
# the standard user-defined gates
ref_circuit.swap(0, 1)
ref_circuit.cswap(0, 1, 2)
ref_circuit.cy(0, 1)
ref_circuit.cz(0, 1)
ref_circuit.ch(0, 1)
ref_circuit.csx(0, 1)
ref_circuit.append(CU1Gate(0.6), [0, 1])
ref_circuit.append(CU3Gate(0.2, 0.1, 0.6), [0, 1])
ref_circuit.cp(0.6, 0, 1)
ref_circuit.cu(0.2, 0.1, 0.6, 0, 0, 1)
ref_circuit.ccx(0, 1, 2)
ref_circuit.crx(0.6, 0, 1)
ref_circuit.cry(0.6, 0, 1)
ref_circuit.crz(0.6, 0, 1)
ref_circuit.rxx(0.2, 0, 1)
ref_circuit.rzz(0.2, 0, 1)
ref_circuit.measure([0, 1, 2], [0, 1, 2])
self.assertEqual(qasm_circuit, ref_circuit)
def test_fail_qasm_file(self):
"""
Test fail_qasm_file.
If all is correct we should get a QiskitError
"""
self.assertRaises(QiskitError, QuantumCircuit.from_qasm_file, "")
def test_qasm_text(self):
"""
Test qasm_text and get_circuit.
If all is correct we should get the qasm file loaded from the string
"""
qasm_string = "// A simple 8 qubit example\nOPENQASM 2.0;\n"
qasm_string += 'include "qelib1.inc";\nqreg a[4];\n'
qasm_string += "qreg b[4];\ncreg c[4];\ncreg d[4];\nh a;\ncx a, b;\n"
qasm_string += "barrier a;\nbarrier b;\nmeasure a[0]->c[0];\n"
qasm_string += "measure a[1]->c[1];\nmeasure a[2]->c[2];\n"
qasm_string += "measure a[3]->c[3];\nmeasure b[0]->d[0];\n"
qasm_string += "measure b[1]->d[1];\nmeasure b[2]->d[2];\n"
qasm_string += "measure b[3]->d[3];"
q_circuit = QuantumCircuit.from_qasm_str(qasm_string)
qr_a = QuantumRegister(4, "a")
qr_b = QuantumRegister(4, "b")
cr_c = ClassicalRegister(4, "c")
cr_d = ClassicalRegister(4, "d")
ref = QuantumCircuit(qr_a, qr_b, cr_c, cr_d)
ref.h(qr_a[3])
ref.cx(qr_a[3], qr_b[3])
ref.h(qr_a[2])
ref.cx(qr_a[2], qr_b[2])
ref.h(qr_a[1])
ref.cx(qr_a[1], qr_b[1])
ref.h(qr_a[0])
ref.cx(qr_a[0], qr_b[0])
ref.barrier(qr_b)
ref.measure(qr_b, cr_d)
ref.barrier(qr_a)
ref.measure(qr_a, cr_c)
self.assertEqual(len(q_circuit.cregs), 2)
self.assertEqual(len(q_circuit.qregs), 2)
self.assertEqual(q_circuit, ref)
def test_qasm_text_conditional(self):
"""
Test qasm_text and get_circuit when conditionals are present.
"""
qasm_string = (
"\n".join(
[
"OPENQASM 2.0;",
'include "qelib1.inc";',
"qreg q[1];",
"creg c0[4];",
"creg c1[4];",
"x q[0];",
"if(c1==4) x q[0];",
]
)
+ "\n"
)
q_circuit = QuantumCircuit.from_qasm_str(qasm_string)
qr = QuantumRegister(1, "q")
cr0 = ClassicalRegister(4, "c0")
cr1 = ClassicalRegister(4, "c1")
ref = QuantumCircuit(qr, cr0, cr1)
ref.x(qr[0])
ref.x(qr[0]).c_if(cr1, 4)
self.assertEqual(len(q_circuit.cregs), 2)
self.assertEqual(len(q_circuit.qregs), 1)
self.assertEqual(q_circuit, ref)
def test_opaque_gate(self):
"""
Test parse an opaque gate
See https://github.com/Qiskit/qiskit-terra/issues/1566.
"""
qasm_string = (
"\n".join(
[
"OPENQASM 2.0;",
'include "qelib1.inc";',
"opaque my_gate(theta,phi,lambda) a,b;",
"qreg q[3];",
"my_gate(1,2,3) q[1],q[2];",
]
)
+ "\n"
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
qr = QuantumRegister(3, "q")
expected = QuantumCircuit(qr)
expected.append(Gate(name="my_gate", num_qubits=2, params=[1, 2, 3]), [qr[1], qr[2]])
self.assertEqual(circuit, expected)
def test_qasm_example_file(self):
"""Loads qasm/example.qasm."""
qasm_filename = os.path.join(self.qasm_dir, "example.qasm")
expected_circuit = QuantumCircuit.from_qasm_str(
"\n".join(
[
"OPENQASM 2.0;",
'include "qelib1.inc";',
"qreg q[3];",
"qreg r[3];",
"creg c[3];",
"creg d[3];",
"h q[2];",
"cx q[2],r[2];",
"measure r[2] -> d[2];",
"h q[1];",
"cx q[1],r[1];",
"measure r[1] -> d[1];",
"h q[0];",
"cx q[0],r[0];",
"measure r[0] -> d[0];",
"barrier q[0],q[1],q[2];",
"measure q[2] -> c[2];",
"measure q[1] -> c[1];",
"measure q[0] -> c[0];",
]
)
+ "\n"
)
q_circuit = QuantumCircuit.from_qasm_file(qasm_filename)
self.assertEqual(q_circuit, expected_circuit)
self.assertEqual(len(q_circuit.cregs), 2)
self.assertEqual(len(q_circuit.qregs), 2)
def test_qasm_qas_string_order(self):
"""Test that gates are returned in qasm in ascending order."""
expected_qasm = (
"\n".join(
[
"OPENQASM 2.0;",
'include "qelib1.inc";',
"qreg q[3];",
"h q[0];",
"h q[1];",
"h q[2];",
]
)
+ "\n"
)
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
h q;"""
q_circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(q_circuit.qasm(), expected_qasm)
def test_from_qasm_str_custom_gate1(self):
"""Test load custom gates (simple case)"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate rinv q {sdg q; h q; sdg q; h q; }
qreg qr[1];
rinv qr[0];"""
circuit = QuantumCircuit.from_qasm_str(qasm_string)
rinv_q = QuantumRegister(1, name="q")
rinv_gate = QuantumCircuit(rinv_q, name="rinv")
rinv_gate.sdg(rinv_q)
rinv_gate.h(rinv_q)
rinv_gate.sdg(rinv_q)
rinv_gate.h(rinv_q)
rinv = rinv_gate.to_instruction()
qr = QuantumRegister(1, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.append(rinv, [qr[0]])
self.assertEqualUnroll(["sdg", "h"], circuit, expected)
def test_from_qasm_str_custom_gate2(self):
"""Test load custom gates (no so simple case, different bit order)
See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate swap2 a,b {
cx a,b;
cx b,a; // different bit order
cx a,b;
}
qreg qr[3];
swap2 qr[0], qr[1];
swap2 qr[1], qr[2];"""
circuit = QuantumCircuit.from_qasm_str(qasm_string)
ab_args = QuantumRegister(2, name="ab")
swap_gate = QuantumCircuit(ab_args, name="swap2")
swap_gate.cx(ab_args[0], ab_args[1])
swap_gate.cx(ab_args[1], ab_args[0])
swap_gate.cx(ab_args[0], ab_args[1])
swap = swap_gate.to_instruction()
qr = QuantumRegister(3, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.append(swap, [qr[0], qr[1]])
expected.append(swap, [qr[1], qr[2]])
self.assertEqualUnroll(["cx"], expected, circuit)
def test_from_qasm_str_custom_gate3(self):
"""Test load custom gates (no so simple case, different bit count)
See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate cswap2 a,b,c
{
cx c,b; // different bit count
ccx a,b,c; //previously defined gate
cx c,b;
}
qreg qr[3];
cswap2 qr[1], qr[0], qr[2];"""
circuit = QuantumCircuit.from_qasm_str(qasm_string)
abc_args = QuantumRegister(3, name="abc")
cswap_gate = QuantumCircuit(abc_args, name="cswap2")
cswap_gate.cx(abc_args[2], abc_args[1])
cswap_gate.ccx(abc_args[0], abc_args[1], abc_args[2])
cswap_gate.cx(abc_args[2], abc_args[1])
cswap = cswap_gate.to_instruction()
qr = QuantumRegister(3, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.append(cswap, [qr[1], qr[0], qr[2]])
self.assertEqualUnroll(["cx", "h", "tdg", "t"], circuit, expected)
def test_from_qasm_str_custom_gate4(self):
"""Test load custom gates (parameterized)
See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate my_gate(phi,lambda) q {u(1.5707963267948966,phi,lambda) q;}
qreg qr[1];
my_gate(pi, pi) qr[0];"""
circuit = QuantumCircuit.from_qasm_str(qasm_string)
my_gate_circuit = QuantumCircuit(1, name="my_gate")
phi = Parameter("phi")
lam = Parameter("lambda")
my_gate_circuit.u(1.5707963267948966, phi, lam, 0)
my_gate = my_gate_circuit.to_gate()
qr = QuantumRegister(1, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.append(my_gate, [qr[0]])
expected = expected.bind_parameters({phi: 3.141592653589793, lam: 3.141592653589793})
self.assertEqualUnroll("u", circuit, expected)
def test_from_qasm_str_custom_gate5(self):
"""Test load custom gates (parameterized, with biop and constant)
See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate my_gate(phi,lambda) q {u(pi/2,phi,lambda) q;} // biop with pi
qreg qr[1];
my_gate(pi, pi) qr[0];"""
circuit = QuantumCircuit.from_qasm_str(qasm_string)
my_gate_circuit = QuantumCircuit(1, name="my_gate")
phi = Parameter("phi")
lam = Parameter("lambda")
my_gate_circuit.u(1.5707963267948966, phi, lam, 0)
my_gate = my_gate_circuit.to_gate()
qr = QuantumRegister(1, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.append(my_gate, [qr[0]])
expected = expected.bind_parameters({phi: 3.141592653589793, lam: 3.141592653589793})
self.assertEqualUnroll("u", circuit, expected)
def test_from_qasm_str_custom_gate6(self):
"""Test load custom gates (parameters used in expressions)
See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-591668924
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate my_gate(phi,lambda) q
{rx(phi+pi) q; ry(lambda/2) q;} // parameters used in expressions
qreg qr[1];
my_gate(pi, pi) qr[0];"""
circuit = QuantumCircuit.from_qasm_str(qasm_string)
my_gate_circuit = QuantumCircuit(1, name="my_gate")
phi = Parameter("phi")
lam = Parameter("lambda")
my_gate_circuit.rx(phi + 3.141592653589793, 0)
my_gate_circuit.ry(lam / 2, 0)
my_gate = my_gate_circuit.to_gate()
qr = QuantumRegister(1, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.append(my_gate, [qr[0]])
expected = expected.bind_parameters({phi: 3.141592653589793, lam: 3.141592653589793})
self.assertEqualUnroll(["rx", "ry"], circuit, expected)
def test_from_qasm_str_custom_gate7(self):
"""Test load custom gates (build in functions)
See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-592208951
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate my_gate(phi,lambda) q
{u(asin(cos(phi)/2), phi+pi, lambda/2) q;} // build func
qreg qr[1];
my_gate(pi, pi) qr[0];"""
circuit = QuantumCircuit.from_qasm_str(qasm_string)
qr = QuantumRegister(1, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.u(-0.5235987755982988, 6.283185307179586, 1.5707963267948966, qr[0])
self.assertEqualUnroll("u", circuit, expected)
def test_from_qasm_str_nested_custom_gate(self):
"""Test chain of custom gates
See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-592261942
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate my_other_gate(phi,lambda) q
{u(asin(cos(phi)/2), phi+pi, lambda/2) q;}
gate my_gate(phi) r
{my_other_gate(phi, phi+pi) r;}
qreg qr[1];
my_gate(pi) qr[0];"""
circuit = QuantumCircuit.from_qasm_str(qasm_string)
qr = QuantumRegister(1, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.u(-0.5235987755982988, 6.283185307179586, 3.141592653589793, qr[0])
self.assertEqualUnroll("u", circuit, expected)
def test_from_qasm_str_delay(self):
"""Test delay instruction/opaque-gate
See: https://github.com/Qiskit/qiskit-terra/issues/6510
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
opaque delay(time) q;
qreg q[1];
delay(172) q[0];"""
circuit = QuantumCircuit.from_qasm_str(qasm_string)
qr = QuantumRegister(1, name="q")
expected = QuantumCircuit(qr, name="circuit")
expected.delay(172, qr[0])
self.assertEqualUnroll("u", circuit, expected)
def test_definition_with_u_cx(self):
"""Test that gate-definition bodies can use U and CX."""
qasm_string = """
OPENQASM 2.0;
gate bell q0, q1 { U(pi/2, 0, pi) q0; CX q0, q1; }
qreg q[2];
bell q[0], q[1];
"""
circuit = QuantumCircuit.from_qasm_str(qasm_string)
qr = QuantumRegister(2, "q")
expected = QuantumCircuit(qr)
expected.h(0)
expected.cx(0, 1)
self.assertEqualUnroll(["u", "cx"], circuit, expected)
def assertEqualUnroll(self, basis, circuit, expected):
"""Compares the dags after unrolling to basis"""
circuit_dag = circuit_to_dag(circuit)
expected_dag = circuit_to_dag(expected)
circuit_result = Unroller(basis).run(circuit_dag)
expected_result = Unroller(basis).run(expected_dag)
self.assertEqual(circuit_result, expected_result)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
import itertools
import math
import sys
import ddt
import qiskit.qasm2
from qiskit.test import QiskitTestCase
@ddt.ddt
class TestSimple(QiskitTestCase):
def test_unary_constants(self):
program = "qreg q[1]; U(-(0.5 + 0.5), +(+1 - 2), -+-+2) q[0];"
parsed = qiskit.qasm2.loads(program)
expected = [-1.0, -1.0, 2.0]
self.assertEqual(list(parsed.data[0].operation.params), expected)
def test_unary_symbolic(self):
program = """
gate u(a, b, c) q {
U(-(a + a), +(+b - c), -+-+c) q;
}
qreg q[1];
u(0.5, 1.0, 2.0) q[0];
"""
parsed = qiskit.qasm2.loads(program)
expected = [-1.0, -1.0, 2.0]
actual = [float(x) for x in parsed.data[0].operation.definition.data[0].operation.params]
self.assertEqual(list(actual), expected)
@ddt.data(
("+", lambda a, b: a + b),
("-", lambda a, b: a - b),
("*", lambda a, b: a * b),
("/", lambda a, b: a / b),
("^", lambda a, b: a**b),
)
@ddt.unpack
def test_binary_constants(self, str_op, py_op):
program = f"qreg q[1]; U(0.25{str_op}0.5, 1.0{str_op}0.5, 3.2{str_op}-0.8) q[0];"
parsed = qiskit.qasm2.loads(program)
expected = [py_op(0.25, 0.5), py_op(1.0, 0.5), py_op(3.2, -0.8)]
# These should be bit-for-bit exact.
self.assertEqual(list(parsed.data[0].operation.params), expected)
@ddt.data(
("+", lambda a, b: a + b),
("-", lambda a, b: a - b),
("*", lambda a, b: a * b),
("/", lambda a, b: a / b),
("^", lambda a, b: a**b),
)
@ddt.unpack
def test_binary_symbolic(self, str_op, py_op):
program = f"""
gate u(a, b, c) q {{
U(a {str_op} b, a {str_op} (b {str_op} c), 0.0) q;
}}
qreg q[1];
u(1.0, 2.0, 3.0) q[0];
"""
parsed = qiskit.qasm2.loads(program)
outer = [1.0, 2.0, 3.0]
abstract_op = parsed.data[0].operation
self.assertEqual(list(abstract_op.params), outer)
expected = [py_op(1.0, 2.0), py_op(1.0, py_op(2.0, 3.0)), 0.0]
actual = [float(x) for x in abstract_op.definition.data[0].operation.params]
self.assertEqual(list(actual), expected)
@ddt.data(
("cos", math.cos),
("exp", math.exp),
("ln", math.log),
("sin", math.sin),
("sqrt", math.sqrt),
("tan", math.tan),
)
@ddt.unpack
def test_function_constants(self, function_str, function_py):
program = f"qreg q[1]; U({function_str}(0.5),{function_str}(1.0),{function_str}(pi)) q[0];"
parsed = qiskit.qasm2.loads(program)
expected = [function_py(0.5), function_py(1.0), function_py(math.pi)]
# These should be bit-for-bit exact.
self.assertEqual(list(parsed.data[0].operation.params), expected)
@ddt.data(
("cos", math.cos),
("exp", math.exp),
("ln", math.log),
("sin", math.sin),
("sqrt", math.sqrt),
("tan", math.tan),
)
@ddt.unpack
def test_function_symbolic(self, function_str, function_py):
program = f"""
gate u(a, b, c) q {{
U({function_str}(a), {function_str}(b), {function_str}(c)) q;
}}
qreg q[1];
u(0.5, 1.0, pi) q[0];
"""
parsed = qiskit.qasm2.loads(program)
outer = [0.5, 1.0, math.pi]
abstract_op = parsed.data[0].operation
self.assertEqual(list(abstract_op.params), outer)
expected = [function_py(x) for x in outer]
actual = [float(x) for x in abstract_op.definition.data[0].operation.params]
self.assertEqual(list(actual), expected)
class TestPrecedenceAssociativity(QiskitTestCase):
def test_precedence(self):
# OQ3's precedence rules are the same as Python's, so we can effectively just eval.
expr = " 1.0 + 2.0 * -3.0 ^ 1.5 - 0.5 / +0.25"
expected = 1.0 + 2.0 * -(3.0**1.5) - 0.5 / +0.25
program = f"qreg q[1]; U({expr}, 0, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(parsed.data[0].operation.params[0], expected)
def test_addition_left(self):
# `eps` is the smallest floating-point value such that `1 + eps != 1`. That means that if
# addition is correctly parsed and resolved as left-associative, then the first parameter
# should first calculate `1 + (eps / 2)`, which will be 1, and then the same again, whereas
# the second will do `(eps / 2) + (eps / 2) = eps`, then `eps + 1` will be different.
eps = sys.float_info.epsilon
program = f"qreg q[1]; U(1 + {eps / 2} + {eps / 2}, {eps / 2} + {eps / 2} + 1, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertNotEqual(1.0 + eps, 1.0) # Sanity check for the test.
self.assertEqual(list(parsed.data[0].operation.params), [1.0, 1.0 + eps, 0.0])
def test_multiplication_left(self):
# A similar principle to the epsilon test for addition; if multiplication associates right,
# then `(0.5 * 2.0 * fmax)` is `inf`, otherwise it's `fmax`.
fmax = sys.float_info.max
program = f"qreg q[1]; U({fmax} * 0.5 * 2.0, 2.0 * 0.5 * {fmax}, 2.0 * {fmax} * 0.5) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(list(parsed.data[0].operation.params), [fmax, fmax, math.inf])
def test_subtraction_left(self):
# If subtraction associated right, we'd accidentally get 2.
program = "qreg q[1]; U(2.0 - 1.0 - 1.0, 0, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(list(parsed.data[0].operation.params), [0.0, 0.0, 0.0])
def test_division_left(self):
# If division associated right, we'd accidentally get 4.
program = "qreg q[1]; U(4.0 / 2.0 / 2.0, 0, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(list(parsed.data[0].operation.params), [1.0, 0.0, 0.0])
def test_power_right(self):
# If the power operator associated left, we'd accidentally get 64 instead.
program = "qreg q[1]; U(2.0 ^ 3.0 ^ 2.0, 0, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(list(parsed.data[0].operation.params), [512.0, 0.0, 0.0])
class TestCustomClassical(QiskitTestCase):
def test_evaluation_order(self):
"""We should be evaluating all functions, including custom user ones the exact number of
times we expect, and left-to-right in parameter lists."""
# pylint: disable=invalid-name
order = itertools.count()
def f():
return next(order)
program = """
qreg q[1];
U(f(), 2 * f() + f(), atan2(f(), f()) - f()) q[0];
"""
parsed = qiskit.qasm2.loads(
program,
custom_classical=[
qiskit.qasm2.CustomClassical("f", 0, f),
qiskit.qasm2.CustomClassical("atan2", 2, math.atan2),
],
)
self.assertEqual(
list(parsed.data[0].operation.params), [0, 2 * 1 + 2, math.atan2(3, 4) - 5]
)
self.assertEqual(next(order), 6)
@ddt.ddt
class TestErrors(QiskitTestCase):
@ddt.data("0.0", "(1.0 - 1.0)")
def test_refuses_to_divide_by_zero(self, denom):
program = f"qreg q[1]; U(2.0 / {denom}, 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "divide by zero"):
qiskit.qasm2.loads(program)
program = f"gate rx(a) q {{ U(a / {denom}, 0.0, 0.0) q; }}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "divide by zero"):
qiskit.qasm2.loads(program)
@ddt.data("0.0", "1.0 - 1.0", "-2.0", "2.0 - 3.0")
def test_refuses_to_ln_non_positive(self, operand):
program = f"qreg q[1]; U(ln({operand}), 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "ln of non-positive"):
qiskit.qasm2.loads(program)
program = f"gate rx(a) q {{ U(a + ln({operand}), 0.0, 0.0) q; }}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "ln of non-positive"):
qiskit.qasm2.loads(program)
@ddt.data("-2.0", "2.0 - 3.0")
def test_refuses_to_sqrt_negative(self, operand):
program = f"qreg q[1]; U(sqrt({operand}), 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "sqrt of negative"):
qiskit.qasm2.loads(program)
program = f"gate rx(a) q {{ U(a + sqrt({operand}), 0.0, 0.0) q; }}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "sqrt of negative"):
qiskit.qasm2.loads(program)
@ddt.data("*", "/", "^")
def test_cannot_use_nonunary_operators_in_unary_position(self, operator):
program = f"qreg q[1]; U({operator}1.0, 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not a valid unary operator"):
qiskit.qasm2.loads(program)
@ddt.data("+", "-", "*", "/", "^")
def test_missing_binary_operand_errors(self, operator):
program = f"qreg q[1]; U(1.0 {operator}, 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "missing operand"):
qiskit.qasm2.loads(program)
program = f"qreg q[1]; U((1.0 {operator}), 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "missing operand"):
qiskit.qasm2.loads(program)
def test_parenthesis_must_be_closed(self):
program = "qreg q[1]; U((1 + 1 2), 3, 2) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "needed a closing parenthesis"):
qiskit.qasm2.loads(program)
def test_premature_right_parenthesis(self):
program = "qreg q[1]; U(sin(), 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "did not find an .* expression"):
qiskit.qasm2.loads(program)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test cases for the legacy OpenQASM 2 parser."""
# pylint: disable=missing-function-docstring
import os
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.circuit import Gate, Parameter
from qiskit.converters import ast_to_dag, dag_to_circuit
from qiskit.exceptions import QiskitError
from qiskit.qasm import Qasm
from qiskit.test import QiskitTestCase
from qiskit.transpiler.passes import Unroller
from qiskit.converters.circuit_to_dag import circuit_to_dag
def from_qasm_str(qasm_str):
return dag_to_circuit(ast_to_dag(Qasm(data=qasm_str).parse()))
def from_qasm_file(path):
return dag_to_circuit(ast_to_dag(Qasm(filename=path).parse()))
class LoadFromQasmTest(QiskitTestCase):
"""Test circuit.from_qasm_* set of methods."""
def setUp(self):
super().setUp()
self.qasm_file_name = "entangled_registers.qasm"
self.qasm_dir = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm"
)
self.qasm_file_path = os.path.join(self.qasm_dir, self.qasm_file_name)
def test_qasm_file(self):
"""
Test qasm_file and get_circuit.
If all is correct we should get the qasm file loaded in _qasm_file_path
"""
q_circuit = from_qasm_file(self.qasm_file_path)
qr_a = QuantumRegister(4, "a")
qr_b = QuantumRegister(4, "b")
cr_c = ClassicalRegister(4, "c")
cr_d = ClassicalRegister(4, "d")
q_circuit_2 = QuantumCircuit(qr_a, qr_b, cr_c, cr_d)
q_circuit_2.h(qr_a)
q_circuit_2.cx(qr_a, qr_b)
q_circuit_2.barrier(qr_a)
q_circuit_2.barrier(qr_b)
q_circuit_2.measure(qr_a, cr_c)
q_circuit_2.measure(qr_b, cr_d)
self.assertEqual(q_circuit, q_circuit_2)
def test_loading_all_qelib1_gates(self):
"""Test setting up a circuit with all gates defined in qiskit/qasm/libs/qelib1.inc."""
from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate, UGate
all_gates_qasm = os.path.join(self.qasm_dir, "all_gates.qasm")
qasm_circuit = from_qasm_file(all_gates_qasm)
ref_circuit = QuantumCircuit(3, 3)
# abstract gates (legacy)
ref_circuit.append(UGate(0.2, 0.1, 0.6), [0])
ref_circuit.cx(0, 1)
# the hardware primitives
ref_circuit.append(U3Gate(0.2, 0.1, 0.6), [0])
ref_circuit.append(U2Gate(0.1, 0.6), [0])
ref_circuit.append(U1Gate(0.6), [0])
ref_circuit.id(0)
ref_circuit.cx(0, 1)
# the standard single qubit gates
ref_circuit.u(0.2, 0.1, 0.6, 0)
ref_circuit.p(0.6, 0)
ref_circuit.x(0)
ref_circuit.y(0)
ref_circuit.z(0)
ref_circuit.h(0)
ref_circuit.s(0)
ref_circuit.t(0)
ref_circuit.sdg(0)
ref_circuit.tdg(0)
ref_circuit.sx(0)
ref_circuit.sxdg(0)
# the standard rotations
ref_circuit.rx(0.1, 0)
ref_circuit.ry(0.1, 0)
ref_circuit.rz(0.1, 0)
# the barrier
ref_circuit.barrier()
# the standard user-defined gates
ref_circuit.swap(0, 1)
ref_circuit.cswap(0, 1, 2)
ref_circuit.cy(0, 1)
ref_circuit.cz(0, 1)
ref_circuit.ch(0, 1)
ref_circuit.csx(0, 1)
ref_circuit.append(CU1Gate(0.6), [0, 1])
ref_circuit.append(CU3Gate(0.2, 0.1, 0.6), [0, 1])
ref_circuit.cp(0.6, 0, 1)
ref_circuit.cu(0.2, 0.1, 0.6, 0, 0, 1)
ref_circuit.ccx(0, 1, 2)
ref_circuit.crx(0.6, 0, 1)
ref_circuit.cry(0.6, 0, 1)
ref_circuit.crz(0.6, 0, 1)
ref_circuit.rxx(0.2, 0, 1)
ref_circuit.rzz(0.2, 0, 1)
ref_circuit.measure([0, 1, 2], [0, 1, 2])
self.assertEqual(qasm_circuit, ref_circuit)
def test_fail_qasm_file(self):
"""
Test fail_qasm_file.
If all is correct we should get a QiskitError
"""
self.assertRaises(QiskitError, from_qasm_file, "")
def test_qasm_text(self):
"""
Test qasm_text and get_circuit.
If all is correct we should get the qasm file loaded from the string
"""
qasm_string = "// A simple 8 qubit example\nOPENQASM 2.0;\n"
qasm_string += 'include "qelib1.inc";\nqreg a[4];\n'
qasm_string += "qreg b[4];\ncreg c[4];\ncreg d[4];\nh a;\ncx a, b;\n"
qasm_string += "barrier a;\nbarrier b;\nmeasure a[0]->c[0];\n"
qasm_string += "measure a[1]->c[1];\nmeasure a[2]->c[2];\n"
qasm_string += "measure a[3]->c[3];\nmeasure b[0]->d[0];\n"
qasm_string += "measure b[1]->d[1];\nmeasure b[2]->d[2];\n"
qasm_string += "measure b[3]->d[3];"
q_circuit = from_qasm_str(qasm_string)
qr_a = QuantumRegister(4, "a")
qr_b = QuantumRegister(4, "b")
cr_c = ClassicalRegister(4, "c")
cr_d = ClassicalRegister(4, "d")
ref = QuantumCircuit(qr_a, qr_b, cr_c, cr_d)
ref.h(qr_a[3])
ref.cx(qr_a[3], qr_b[3])
ref.h(qr_a[2])
ref.cx(qr_a[2], qr_b[2])
ref.h(qr_a[1])
ref.cx(qr_a[1], qr_b[1])
ref.h(qr_a[0])
ref.cx(qr_a[0], qr_b[0])
ref.barrier(qr_b)
ref.measure(qr_b, cr_d)
ref.barrier(qr_a)
ref.measure(qr_a, cr_c)
self.assertEqual(len(q_circuit.cregs), 2)
self.assertEqual(len(q_circuit.qregs), 2)
self.assertEqual(q_circuit, ref)
def test_qasm_text_conditional(self):
"""
Test qasm_text and get_circuit when conditionals are present.
"""
qasm_string = (
"\n".join(
[
"OPENQASM 2.0;",
'include "qelib1.inc";',
"qreg q[1];",
"creg c0[4];",
"creg c1[4];",
"x q[0];",
"if(c1==4) x q[0];",
]
)
+ "\n"
)
q_circuit = from_qasm_str(qasm_string)
qr = QuantumRegister(1, "q")
cr0 = ClassicalRegister(4, "c0")
cr1 = ClassicalRegister(4, "c1")
ref = QuantumCircuit(qr, cr0, cr1)
ref.x(qr[0])
ref.x(qr[0]).c_if(cr1, 4)
self.assertEqual(len(q_circuit.cregs), 2)
self.assertEqual(len(q_circuit.qregs), 1)
self.assertEqual(q_circuit, ref)
def test_opaque_gate(self):
"""
Test parse an opaque gate
See https://github.com/Qiskit/qiskit-terra/issues/1566.
"""
qasm_string = (
"\n".join(
[
"OPENQASM 2.0;",
'include "qelib1.inc";',
"opaque my_gate(theta,phi,lambda) a,b;",
"qreg q[3];",
"my_gate(1,2,3) q[1],q[2];",
]
)
+ "\n"
)
circuit = from_qasm_str(qasm_string)
qr = QuantumRegister(3, "q")
expected = QuantumCircuit(qr)
expected.append(Gate(name="my_gate", num_qubits=2, params=[1, 2, 3]), [qr[1], qr[2]])
self.assertEqual(circuit, expected)
def test_qasm_example_file(self):
"""Loads qasm/example.qasm."""
qasm_filename = os.path.join(self.qasm_dir, "example.qasm")
expected_circuit = from_qasm_str(
"\n".join(
[
"OPENQASM 2.0;",
'include "qelib1.inc";',
"qreg q[3];",
"qreg r[3];",
"creg c[3];",
"creg d[3];",
"h q[2];",
"cx q[2],r[2];",
"measure r[2] -> d[2];",
"h q[1];",
"cx q[1],r[1];",
"measure r[1] -> d[1];",
"h q[0];",
"cx q[0],r[0];",
"measure r[0] -> d[0];",
"barrier q[0],q[1],q[2];",
"measure q[2] -> c[2];",
"measure q[1] -> c[1];",
"measure q[0] -> c[0];",
]
)
+ "\n"
)
q_circuit = from_qasm_file(qasm_filename)
self.assertEqual(q_circuit, expected_circuit)
self.assertEqual(len(q_circuit.cregs), 2)
self.assertEqual(len(q_circuit.qregs), 2)
def test_qasm_qas_string_order(self):
"""Test that gates are returned in qasm in ascending order."""
expected_qasm = (
"\n".join(
[
"OPENQASM 2.0;",
'include "qelib1.inc";',
"qreg q[3];",
"h q[0];",
"h q[1];",
"h q[2];",
]
)
+ "\n"
)
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
h q;"""
q_circuit = from_qasm_str(qasm_string)
self.assertEqual(q_circuit.qasm(), expected_qasm)
def test_from_qasm_str_custom_gate1(self):
"""Test load custom gates (simple case)"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate rinv q {sdg q; h q; sdg q; h q; }
qreg qr[1];
rinv qr[0];"""
circuit = from_qasm_str(qasm_string)
rinv_q = QuantumRegister(1, name="q")
rinv_gate = QuantumCircuit(rinv_q, name="rinv")
rinv_gate.sdg(rinv_q)
rinv_gate.h(rinv_q)
rinv_gate.sdg(rinv_q)
rinv_gate.h(rinv_q)
rinv = rinv_gate.to_instruction()
qr = QuantumRegister(1, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.append(rinv, [qr[0]])
self.assertEqualUnroll(["sdg", "h"], circuit, expected)
def test_from_qasm_str_custom_gate2(self):
"""Test load custom gates (no so simple case, different bit order)
See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate swap2 a,b {
cx a,b;
cx b,a; // different bit order
cx a,b;
}
qreg qr[3];
swap2 qr[0], qr[1];
swap2 qr[1], qr[2];"""
circuit = from_qasm_str(qasm_string)
ab_args = QuantumRegister(2, name="ab")
swap_gate = QuantumCircuit(ab_args, name="swap2")
swap_gate.cx(ab_args[0], ab_args[1])
swap_gate.cx(ab_args[1], ab_args[0])
swap_gate.cx(ab_args[0], ab_args[1])
swap = swap_gate.to_instruction()
qr = QuantumRegister(3, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.append(swap, [qr[0], qr[1]])
expected.append(swap, [qr[1], qr[2]])
self.assertEqualUnroll(["cx"], expected, circuit)
def test_from_qasm_str_custom_gate3(self):
"""Test load custom gates (no so simple case, different bit count)
See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate cswap2 a,b,c
{
cx c,b; // different bit count
ccx a,b,c; //previously defined gate
cx c,b;
}
qreg qr[3];
cswap2 qr[1], qr[0], qr[2];"""
circuit = from_qasm_str(qasm_string)
abc_args = QuantumRegister(3, name="abc")
cswap_gate = QuantumCircuit(abc_args, name="cswap2")
cswap_gate.cx(abc_args[2], abc_args[1])
cswap_gate.ccx(abc_args[0], abc_args[1], abc_args[2])
cswap_gate.cx(abc_args[2], abc_args[1])
cswap = cswap_gate.to_instruction()
qr = QuantumRegister(3, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.append(cswap, [qr[1], qr[0], qr[2]])
self.assertEqualUnroll(["cx", "h", "tdg", "t"], circuit, expected)
def test_from_qasm_str_custom_gate4(self):
"""Test load custom gates (parameterized)
See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate my_gate(phi,lambda) q {u(1.5707963267948966,phi,lambda) q;}
qreg qr[1];
my_gate(pi, pi) qr[0];"""
circuit = from_qasm_str(qasm_string)
my_gate_circuit = QuantumCircuit(1, name="my_gate")
phi = Parameter("phi")
lam = Parameter("lambda")
my_gate_circuit.u(1.5707963267948966, phi, lam, 0)
my_gate = my_gate_circuit.to_gate()
qr = QuantumRegister(1, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.append(my_gate, [qr[0]])
expected = expected.bind_parameters({phi: 3.141592653589793, lam: 3.141592653589793})
self.assertEqualUnroll("u", circuit, expected)
def test_from_qasm_str_custom_gate5(self):
"""Test load custom gates (parameterized, with biop and constant)
See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate my_gate(phi,lambda) q {u(pi/2,phi,lambda) q;} // biop with pi
qreg qr[1];
my_gate(pi, pi) qr[0];"""
circuit = from_qasm_str(qasm_string)
my_gate_circuit = QuantumCircuit(1, name="my_gate")
phi = Parameter("phi")
lam = Parameter("lambda")
my_gate_circuit.u(1.5707963267948966, phi, lam, 0)
my_gate = my_gate_circuit.to_gate()
qr = QuantumRegister(1, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.append(my_gate, [qr[0]])
expected = expected.bind_parameters({phi: 3.141592653589793, lam: 3.141592653589793})
self.assertEqualUnroll("u", circuit, expected)
def test_from_qasm_str_custom_gate6(self):
"""Test load custom gates (parameters used in expressions)
See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-591668924
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate my_gate(phi,lambda) q
{rx(phi+pi) q; ry(lambda/2) q;} // parameters used in expressions
qreg qr[1];
my_gate(pi, pi) qr[0];"""
circuit = from_qasm_str(qasm_string)
my_gate_circuit = QuantumCircuit(1, name="my_gate")
phi = Parameter("phi")
lam = Parameter("lambda")
my_gate_circuit.rx(phi + 3.141592653589793, 0)
my_gate_circuit.ry(lam / 2, 0)
my_gate = my_gate_circuit.to_gate()
qr = QuantumRegister(1, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.append(my_gate, [qr[0]])
expected = expected.bind_parameters({phi: 3.141592653589793, lam: 3.141592653589793})
self.assertEqualUnroll(["rx", "ry"], circuit, expected)
def test_from_qasm_str_custom_gate7(self):
"""Test load custom gates (build in functions)
See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-592208951
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate my_gate(phi,lambda) q
{u(asin(cos(phi)/2), phi+pi, lambda/2) q;} // build func
qreg qr[1];
my_gate(pi, pi) qr[0];"""
circuit = from_qasm_str(qasm_string)
qr = QuantumRegister(1, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.u(-0.5235987755982988, 6.283185307179586, 1.5707963267948966, qr[0])
self.assertEqualUnroll("u", circuit, expected)
def test_from_qasm_str_nested_custom_gate(self):
"""Test chain of custom gates
See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-592261942
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
gate my_other_gate(phi,lambda) q
{u(asin(cos(phi)/2), phi+pi, lambda/2) q;}
gate my_gate(phi) r
{my_other_gate(phi, phi+pi) r;}
qreg qr[1];
my_gate(pi) qr[0];"""
circuit = from_qasm_str(qasm_string)
qr = QuantumRegister(1, name="qr")
expected = QuantumCircuit(qr, name="circuit")
expected.u(-0.5235987755982988, 6.283185307179586, 3.141592653589793, qr[0])
self.assertEqualUnroll("u", circuit, expected)
def test_from_qasm_str_delay(self):
"""Test delay instruction/opaque-gate
See: https://github.com/Qiskit/qiskit-terra/issues/6510
"""
qasm_string = """OPENQASM 2.0;
include "qelib1.inc";
opaque delay(time) q;
qreg q[1];
delay(172) q[0];"""
circuit = from_qasm_str(qasm_string)
qr = QuantumRegister(1, name="q")
expected = QuantumCircuit(qr, name="circuit")
expected.delay(172, qr[0])
self.assertEqualUnroll("u", circuit, expected)
def assertEqualUnroll(self, basis, circuit, expected):
"""Compares the dags after unrolling to basis"""
circuit_dag = circuit_to_dag(circuit)
expected_dag = circuit_to_dag(expected)
circuit_result = Unroller(basis).run(circuit_dag)
expected_result = Unroller(basis).run(expected_dag)
self.assertEqual(circuit_result, expected_result)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
import ddt
import qiskit.qasm2
from qiskit.test import QiskitTestCase
@ddt.ddt
class TestLexer(QiskitTestCase):
# Most of the lexer is fully exercised in the parser tests. These tests here are really mopping
# up some error messages and whatnot that might otherwise be missed.
def test_pathological_formatting(self):
# This is deliberately _terribly_ formatted, included multiple blanks lines in quick
# succession and comments in places you really wouldn't expect to see comments.
program = """
OPENQASM
// do we really need a comment here?
2.0//and another comment very squished up
;
include // this line introduces a file import
"qelib1.inc" // this is the file imported
; // this is a semicolon
gate // we're making a gate
bell( // void, with loose parenthesis in comment )
) a,//
b{h a;cx a //,,,,
,b;}
qreg // a quantum register
q
[ // a square bracket
2];bell q[0],//
q[1];creg c[2];measure q->c;"""
parsed = qiskit.qasm2.loads(program)
expected_unrolled = qiskit.QuantumCircuit(
qiskit.QuantumRegister(2, "q"), qiskit.ClassicalRegister(2, "c")
)
expected_unrolled.h(0)
expected_unrolled.cx(0, 1)
expected_unrolled.measure([0, 1], [0, 1])
self.assertEqual(parsed.decompose(), expected_unrolled)
@ddt.data("0.25", "00.25", "2.5e-1", "2.5e-01", "0.025E+1", ".25", ".025e1", "25e-2")
def test_float_lexes(self, number):
program = f"qreg q[1]; U({number}, 0, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(list(parsed.data[0].operation.params), [0.25, 0, 0])
def test_no_decimal_float_rejected_in_strict_mode(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError,
r"\[strict\] all floats must include a decimal point",
):
qiskit.qasm2.loads("OPENQASM 2.0; qreg q[1]; U(25e-2, 0, 0) q[0];", strict=True)
@ddt.data("", "qre", "cre", ".")
def test_non_ascii_bytes_error(self, prefix):
token = f"{prefix}\xff"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "encountered a non-ASCII byte"):
qiskit.qasm2.loads(token)
def test_integers_cannot_start_with_zero(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "integers cannot have leading zeroes"
):
qiskit.qasm2.loads("0123")
@ddt.data("", "+", "-")
def test_float_exponents_must_have_a_digit(self, sign):
token = f"12.34e{sign}"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "needed to see an integer exponent"
):
qiskit.qasm2.loads(token)
def test_non_builtins_cannot_be_capitalised(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "identifiers cannot start with capital"
):
qiskit.qasm2.loads("Qubit")
def test_unterminated_filename_is_invalid(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "unexpected end-of-file while lexing string literal"
):
qiskit.qasm2.loads('include "qelib1.inc')
def test_filename_with_linebreak_is_invalid(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "unexpected line break while lexing string literal"
):
qiskit.qasm2.loads('include "qe\nlib1.inc";')
def test_strict_single_quoted_path_rejected(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"\[strict\] paths must be in double quotes"
):
qiskit.qasm2.loads("OPENQASM 2.0; include 'qelib1.inc';", strict=True)
def test_version_must_have_word_boundary_after(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a version"
):
qiskit.qasm2.loads("OPENQASM 2a;")
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a version"
):
qiskit.qasm2.loads("OPENQASM 2.0a;")
def test_no_boundary_float_in_version_position(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float"
):
qiskit.qasm2.loads("OPENQASM .5a;")
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float"
):
qiskit.qasm2.loads("OPENQASM 0.2e1a;")
def test_integers_must_have_word_boundaries_after(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after an integer"
):
qiskit.qasm2.loads("OPENQASM 2.0; qreg q[2a];")
def test_floats_must_have_word_boundaries_after(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float"
):
qiskit.qasm2.loads("OPENQASM 2.0; qreg q[1]; U(2.0a, 0, 0) q[0];")
def test_single_equals_is_rejected(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"single equals '=' is never valid"
):
qiskit.qasm2.loads("if (a = 2) U(0, 0, 0) q[0];")
def test_bare_dot_is_not_valid_float(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a numeric fractional part"
):
qiskit.qasm2.loads("qreg q[0]; U(2 + ., 0, 0) q[0];")
def test_invalid_token(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"encountered '!', which doesn't match"
):
qiskit.qasm2.loads("!")
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
import enum
import math
import ddt
import qiskit.qasm2
from qiskit.circuit import Gate, library as lib
from qiskit.test import QiskitTestCase
from test import combine # pylint: disable=wrong-import-order
# We need to use this enum a _bunch_ of times, so let's not give it a long name.
# pylint: disable=invalid-name
class T(enum.Enum):
# This is a deliberately stripped-down list that doesn't include most of the expression-specific
# tokens, because we don't want to complicate matters with those in tests of the general parser
# errors. We test the expression subparser elsewhere.
OPENQASM = "OPENQASM"
BARRIER = "barrier"
CREG = "creg"
GATE = "gate"
IF = "if"
INCLUDE = "include"
MEASURE = "measure"
OPAQUE = "opaque"
QREG = "qreg"
RESET = "reset"
PI = "pi"
ARROW = "->"
EQUALS = "=="
SEMICOLON = ";"
COMMA = ","
LPAREN = "("
RPAREN = ")"
LBRACKET = "["
RBRACKET = "]"
LBRACE = "{"
RBRACE = "}"
ID = "q"
REAL = "1.5"
INTEGER = "1"
FILENAME = '"qelib1.inc"'
def bad_token_parametrisation():
"""Generate the test cases for the "bad token" tests; this makes a sequence of OpenQASM 2
statements, then puts various invalid tokens after them to verify that the parser correctly
throws an error on them."""
token_set = frozenset(T)
def without(*tokens):
return token_set - set(tokens)
# ddt isn't a particularly great parametriser - it'll only correctly unpack tuples and lists in
# the way we really want, but if we want to control the test id, we also have to set `__name__`
# which isn't settable on either of those. We can't use unpack, then, so we just need a class
# to pass.
class BadTokenCase:
def __init__(self, statement, disallowed, name=None):
self.statement = statement
self.disallowed = disallowed
self.__name__ = name
for statement, disallowed in [
# This should only include stopping points where the next token is somewhat fixed; in
# places where there's a real decision to be made (such as number of qubits in a gate,
# or the statement type in a gate body), there should be a better error message.
#
# There's a large subset of OQ2 that's reducible to a regular language, so we _could_
# define that, build a DFA for it, and use that to very quickly generate a complete set
# of tests. That would be more complex to read and verify for correctness, though.
(
"",
without(
T.OPENQASM,
T.ID,
T.INCLUDE,
T.OPAQUE,
T.GATE,
T.QREG,
T.CREG,
T.IF,
T.RESET,
T.BARRIER,
T.MEASURE,
T.SEMICOLON,
),
),
("OPENQASM", without(T.REAL, T.INTEGER)),
("OPENQASM 2.0", without(T.SEMICOLON)),
("include", without(T.FILENAME)),
('include "qelib1.inc"', without(T.SEMICOLON)),
("opaque", without(T.ID)),
("opaque bell", without(T.LPAREN, T.ID, T.SEMICOLON)),
("opaque bell (", without(T.ID, T.RPAREN)),
("opaque bell (a", without(T.COMMA, T.RPAREN)),
("opaque bell (a,", without(T.ID, T.RPAREN)),
("opaque bell (a, b", without(T.COMMA, T.RPAREN)),
("opaque bell (a, b)", without(T.ID, T.SEMICOLON)),
("opaque bell (a, b) q1", without(T.COMMA, T.SEMICOLON)),
("opaque bell (a, b) q1,", without(T.ID, T.SEMICOLON)),
("opaque bell (a, b) q1, q2", without(T.COMMA, T.SEMICOLON)),
("gate", without(T.ID)),
("gate bell (", without(T.ID, T.RPAREN)),
("gate bell (a", without(T.COMMA, T.RPAREN)),
("gate bell (a,", without(T.ID, T.RPAREN)),
("gate bell (a, b", without(T.COMMA, T.RPAREN)),
("gate bell (a, b) q1", without(T.COMMA, T.LBRACE)),
("gate bell (a, b) q1,", without(T.ID, T.LBRACE)),
("gate bell (a, b) q1, q2", without(T.COMMA, T.LBRACE)),
("qreg", without(T.ID)),
("qreg reg", without(T.LBRACKET)),
("qreg reg[", without(T.INTEGER)),
("qreg reg[5", without(T.RBRACKET)),
("qreg reg[5]", without(T.SEMICOLON)),
("creg", without(T.ID)),
("creg reg", without(T.LBRACKET)),
("creg reg[", without(T.INTEGER)),
("creg reg[5", without(T.RBRACKET)),
("creg reg[5]", without(T.SEMICOLON)),
("CX", without(T.LPAREN, T.ID, T.SEMICOLON)),
("CX(", without(T.PI, T.INTEGER, T.REAL, T.ID, T.LPAREN, T.RPAREN)),
("CX()", without(T.ID, T.SEMICOLON)),
("CX q", without(T.LBRACKET, T.COMMA, T.SEMICOLON)),
("CX q[", without(T.INTEGER)),
("CX q[0", without(T.RBRACKET)),
("CX q[0]", without(T.COMMA, T.SEMICOLON)),
("CX q[0],", without(T.ID, T.SEMICOLON)),
("CX q[0], q", without(T.LBRACKET, T.COMMA, T.SEMICOLON)),
# No need to repeatedly "every" possible number of arguments.
("measure", without(T.ID)),
("measure q", without(T.LBRACKET, T.ARROW)),
("measure q[", without(T.INTEGER)),
("measure q[0", without(T.RBRACKET)),
("measure q[0]", without(T.ARROW)),
("measure q[0] ->", without(T.ID)),
("measure q[0] -> c", without(T.LBRACKET, T.SEMICOLON)),
("measure q[0] -> c[", without(T.INTEGER)),
("measure q[0] -> c[0", without(T.RBRACKET)),
("measure q[0] -> c[0]", without(T.SEMICOLON)),
("reset", without(T.ID)),
("reset q", without(T.LBRACKET, T.SEMICOLON)),
("reset q[", without(T.INTEGER)),
("reset q[0", without(T.RBRACKET)),
("reset q[0]", without(T.SEMICOLON)),
("barrier", without(T.ID, T.SEMICOLON)),
("barrier q", without(T.LBRACKET, T.COMMA, T.SEMICOLON)),
("barrier q[", without(T.INTEGER)),
("barrier q[0", without(T.RBRACKET)),
("barrier q[0]", without(T.COMMA, T.SEMICOLON)),
("if", without(T.LPAREN)),
("if (", without(T.ID)),
("if (cond", without(T.EQUALS)),
("if (cond ==", without(T.INTEGER)),
("if (cond == 0", without(T.RPAREN)),
("if (cond == 0)", without(T.ID, T.RESET, T.MEASURE)),
]:
for token in disallowed:
yield BadTokenCase(statement, token.value, name=f"'{statement}'-{token.name.lower()}")
def eof_parametrisation():
for tokens in [
("OPENQASM", "2.0", ";"),
("include", '"qelib1.inc"', ";"),
("opaque", "bell", "(", "a", ",", "b", ")", "q1", ",", "q2", ";"),
("gate", "bell", "(", "a", ",", "b", ")", "q1", ",", "q2", "{", "}"),
("qreg", "qr", "[", "5", "]", ";"),
("creg", "cr", "[", "5", "]", ";"),
("CX", "(", ")", "q", "[", "0", "]", ",", "q", "[", "1", "]", ";"),
("measure", "q", "[", "0", "]", "->", "c", "[", "0", "]", ";"),
("reset", "q", "[", "0", "]", ";"),
("barrier", "q", ";"),
# No need to test every combination of `if`, really.
("if", "(", "cond", "==", "0", ")", "CX q[0], q[1];"),
]:
prefix = ""
for token in tokens[:-1]:
prefix = f"{prefix} {token}".strip()
yield prefix
@ddt.ddt
class TestIncompleteStructure(QiskitTestCase):
PRELUDE = "OPENQASM 2.0; qreg q[5]; creg c[5]; creg cond[1];"
@ddt.idata(bad_token_parametrisation())
def test_bad_token(self, case):
"""Test that the parser raises an error when an incorrect token is given."""
statement = case.statement
disallowed = case.disallowed
prelude = "" if statement.startswith("OPENQASM") else self.PRELUDE
full = f"{prelude} {statement} {disallowed}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "needed .*, but instead"):
qiskit.qasm2.loads(full)
@ddt.idata(eof_parametrisation())
def test_eof(self, statement):
"""Test that the parser raises an error when the end-of-file is reached instead of a token
that is required."""
prelude = "" if statement.startswith("OPENQASM") else self.PRELUDE
full = f"{prelude} {statement}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "unexpected end-of-file"):
qiskit.qasm2.loads(full)
def test_loading_directory(self):
"""Test that the correct error is raised when a file fails to open."""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "failed to read"):
qiskit.qasm2.load(".")
class TestVersion(QiskitTestCase):
def test_invalid_version(self):
program = "OPENQASM 3.0;"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "can only handle OpenQASM 2.0"):
qiskit.qasm2.loads(program)
program = "OPENQASM 2.1;"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "can only handle OpenQASM 2.0"):
qiskit.qasm2.loads(program)
program = "OPENQASM 20.e-1;"
with self.assertRaises(qiskit.qasm2.QASM2ParseError):
qiskit.qasm2.loads(program)
def test_openqasm_must_be_first_statement(self):
program = "qreg q[0]; OPENQASM 2.0;"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "only the first statement"):
qiskit.qasm2.loads(program)
@ddt.ddt
class TestScoping(QiskitTestCase):
def test_register_use_before_definition(self):
program = "CX after[0], after[1]; qreg after[2];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not defined in this scope"):
qiskit.qasm2.loads(program)
program = "qreg q[2]; measure q[0] -> c[0]; creg c[2];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not defined in this scope"):
qiskit.qasm2.loads(program)
@combine(
definer=["qreg reg[2];", "creg reg[2];", "gate reg a {}", "opaque reg a;"],
bad_definer=["qreg reg[2];", "creg reg[2];"],
)
def test_register_already_defined(self, definer, bad_definer):
program = f"{definer} {bad_definer}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
def test_qelib1_not_implicit(self):
program = """
OPENQASM 2.0;
qreg q[2];
cx q[0], q[1];
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'cx' is not defined"):
qiskit.qasm2.loads(program)
def test_cannot_access_gates_before_definition(self):
program = """
qreg q[2];
cx q[0], q[1];
gate cx a, b {
CX a, b;
}
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'cx' is not defined"):
qiskit.qasm2.loads(program)
def test_cannot_access_gate_recursively(self):
program = """
gate cx a, b {
cx a, b;
}
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'cx' is not defined"):
qiskit.qasm2.loads(program)
def test_cannot_access_qubits_from_previous_gate(self):
program = """
gate cx a, b {
CX a, b;
}
gate other c {
CX a, b;
}
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'a' is not defined"):
qiskit.qasm2.loads(program)
def test_cannot_access_parameters_from_previous_gate(self):
program = """
gate first(a, b) q {
U(a, 0, b) q;
}
gate second q {
U(a, 0, b) q;
}
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "'a' is not a parameter.*defined"
):
qiskit.qasm2.loads(program)
def test_cannot_access_quantum_registers_within_gate(self):
program = """
qreg q[2];
gate my_gate a {
CX a, q;
}
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is a quantum register"):
qiskit.qasm2.loads(program)
def test_parameters_not_defined_outside_gate(self):
program = """
gate my_gate(a) q {}
qreg qr[2];
U(a, 0, 0) qr;
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "'a' is not a parameter.*defined"
):
qiskit.qasm2.loads(program)
def test_qubits_not_defined_outside_gate(self):
program = """
gate my_gate(a) q {}
U(0, 0, 0) q;
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is not defined"):
qiskit.qasm2.loads(program)
@ddt.data('include "qelib1.inc";', "gate h q { }")
def test_gates_cannot_redefine(self, definer):
program = f"{definer} gate h q {{ }}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
def test_cannot_use_undeclared_register_conditional(self):
program = "qreg q[1]; if (c == 0) U(0, 0, 0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not defined"):
qiskit.qasm2.loads(program)
@ddt.ddt
class TestTyping(QiskitTestCase):
@ddt.data(
"CX q[0], U;",
"measure U -> c[0];",
"measure q[0] -> U;",
"reset U;",
"barrier U;",
"if (U == 0) CX q[0], q[1];",
"gate my_gate a { U(0, 0, 0) U; }",
)
def test_cannot_use_gates_incorrectly(self, usage):
program = f"qreg q[2]; creg c[2]; {usage}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'U' is a gate"):
qiskit.qasm2.loads(program)
@ddt.data(
"measure q[0] -> q[1];",
"if (q == 0) CX q[0], q[1];",
"q q[0], q[1];",
"gate my_gate a { U(0, 0, 0) q; }",
)
def test_cannot_use_qregs_incorrectly(self, usage):
program = f"qreg q[2]; creg c[2]; {usage}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is a quantum register"):
qiskit.qasm2.loads(program)
@ddt.data(
"CX q[0], c[1];",
"measure c[0] -> c[1];",
"reset c[0];",
"barrier c[0];",
"c q[0], q[1];",
"gate my_gate a { U(0, 0, 0) c; }",
)
def test_cannot_use_cregs_incorrectly(self, usage):
program = f"qreg q[2]; creg c[2]; {usage}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'c' is a classical register"):
qiskit.qasm2.loads(program)
def test_cannot_use_parameters_incorrectly(self):
program = "gate my_gate(p) q { CX p, q; }"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'p' is a parameter"):
qiskit.qasm2.loads(program)
def test_cannot_use_qubits_incorrectly(self):
program = "gate my_gate(p) q { U(q, q, q) q; }"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is a gate qubit"):
qiskit.qasm2.loads(program)
@ddt.data(("h", 0), ("h", 2), ("CX", 0), ("CX", 1), ("CX", 3), ("ccx", 2), ("ccx", 4))
@ddt.unpack
def test_gates_accept_only_valid_number_qubits(self, gate, bad_count):
arguments = ", ".join(f"q[{i}]" for i in range(bad_count))
program = f'include "qelib1.inc"; qreg q[5];\n{gate} {arguments};'
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "takes .* quantum arguments?"):
qiskit.qasm2.loads(program)
@ddt.data(("U", 2), ("U", 4), ("rx", 0), ("rx", 2), ("u3", 1))
@ddt.unpack
def test_gates_accept_only_valid_number_parameters(self, gate, bad_count):
arguments = ", ".join("0" for _ in [None] * bad_count)
program = f'include "qelib1.inc"; qreg q[5];\n{gate}({arguments}) q[0];'
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "takes .* parameters?"):
qiskit.qasm2.loads(program)
@ddt.ddt
class TestGateDefinition(QiskitTestCase):
def test_no_zero_qubit(self):
program = "gate zero {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"):
qiskit.qasm2.loads(program)
program = "gate zero(a) {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"):
qiskit.qasm2.loads(program)
def test_no_zero_qubit_opaque(self):
program = "opaque zero;"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"):
qiskit.qasm2.loads(program)
program = "opaque zero(a);"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"):
qiskit.qasm2.loads(program)
def test_cannot_subscript_qubit(self):
program = """
gate my_gate a {
CX a[0], a[1];
}
"""
with self.assertRaises(qiskit.qasm2.QASM2ParseError):
qiskit.qasm2.loads(program)
def test_cannot_repeat_parameters(self):
program = "gate my_gate(a, a) q {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
def test_cannot_repeat_qubits(self):
program = "gate my_gate a, a {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
def test_qubit_cannot_shadow_parameter(self):
program = "gate my_gate(a) a {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
@ddt.data("measure q -> c;", "reset q", "if (c == 0) U(0, 0, 0) q;", "gate my_x q {}")
def test_definition_cannot_contain_nonunitary(self, statement):
program = f"OPENQASM 2.0; creg c[5]; gate my_gate q {{ {statement} }}"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "only gate applications are valid"
):
qiskit.qasm2.loads(program)
def test_cannot_redefine_u(self):
program = "gate U(a, b, c) q {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
def test_cannot_redefine_cx(self):
program = "gate CX a, b {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
@ddt.ddt
class TestBitResolution(QiskitTestCase):
def test_disallow_out_of_range(self):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "out-of-range"):
qiskit.qasm2.loads("qreg q[2]; U(0, 0, 0) q[2];")
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "out-of-range"):
qiskit.qasm2.loads("qreg q[2]; creg c[2]; measure q[2] -> c[0];")
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "out-of-range"):
qiskit.qasm2.loads("qreg q[2]; creg c[2]; measure q[0] -> c[2];")
@combine(
conditional=[True, False],
call=[
"CX q1[0], q1[0];",
"CX q1, q1[0];",
"CX q1[0], q1;",
"CX q1, q1;",
"ccx q1[0], q1[1], q1[0];",
"ccx q2, q1, q2[0];",
],
)
def test_disallow_duplicate_qubits(self, call, conditional):
program = """
include "qelib1.inc";
qreg q1[3];
qreg q2[3];
qreg q3[3];
"""
if conditional:
program += "creg cond[1]; if (cond == 0) "
program += call
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "duplicate qubit"):
qiskit.qasm2.loads(program)
@ddt.data(
(("q1[1]", "q2[2]"), "CX q1, q2"),
(("q1[1]", "q2[2]"), "CX q2, q1"),
(("q1[3]", "q2[2]"), "CX q1, q2"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q1, q2, q3"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q2, q3, q1"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q3, q1, q2"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q1, q2[0], q3"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q2[0], q3, q1"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q3, q1, q2[0]"),
)
@ddt.unpack
def test_incorrect_gate_broadcast_lengths(self, registers, call):
setup = 'include "qelib1.inc";\n' + "\n".join(f"qreg {reg};" for reg in registers)
program = f"{setup}\n{call};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"):
qiskit.qasm2.loads(program)
cond = "creg cond[1];\nif (cond == 0)"
program = f"{setup}\n{cond} {call};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"):
qiskit.qasm2.loads(program)
@ddt.data(
("qreg q[2]; creg c[2];", "q[0] -> c"),
("qreg q[2]; creg c[2];", "q -> c[0]"),
("qreg q[1]; creg c[2];", "q -> c[0]"),
("qreg q[2]; creg c[1];", "q[0] -> c"),
("qreg q[2]; creg c[3];", "q -> c"),
)
@ddt.unpack
def test_incorrect_measure_broadcast_lengths(self, setup, operands):
program = f"{setup}\nmeasure {operands};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"):
qiskit.qasm2.loads(program)
program = f"{setup}\ncreg cond[1];\nif (cond == 0) measure {operands};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"):
qiskit.qasm2.loads(program)
@ddt.ddt
class TestCustomInstructions(QiskitTestCase):
def test_cannot_use_custom_before_definition(self):
program = "qreg q[2]; my_gate q[0], q[1];"
class MyGate(Gate):
def __init__(self):
super().__init__("my_gate", 2, [])
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "cannot use .* before definition"
):
qiskit.qasm2.loads(
program,
custom_instructions=[qiskit.qasm2.CustomInstruction("my_gate", 0, 2, MyGate)],
)
def test_cannot_misdefine_u(self):
program = "qreg q[1]; U(0.5, 0.25) q[0]"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "custom instruction .* mismatched"
):
qiskit.qasm2.loads(
program, custom_instructions=[qiskit.qasm2.CustomInstruction("U", 2, 1, lib.U2Gate)]
)
def test_cannot_misdefine_cx(self):
program = "qreg q[1]; CX q[0]"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "custom instruction .* mismatched"
):
qiskit.qasm2.loads(
program, custom_instructions=[qiskit.qasm2.CustomInstruction("CX", 0, 1, lib.XGate)]
)
def test_builtin_is_typechecked(self):
program = "qreg q[1]; my(0.5) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' takes 2 quantum arguments"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RXXGate, builtin=True)
],
)
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' takes 2 parameters"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("my", 2, 1, lib.U2Gate, builtin=True)
],
)
def test_cannot_define_builtin_twice(self):
program = "gate builtin q {}; gate builtin q {};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'builtin' is already defined"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("builtin", 0, 1, lambda: Gate("builtin", 1, []))
],
)
def test_cannot_redefine_custom_u(self):
program = "gate U(a, b, c) q {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("U", 3, 1, lib.UGate, builtin=True)
],
)
def test_cannot_redefine_custom_cx(self):
program = "gate CX a, b {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("CX", 0, 2, lib.CXGate, builtin=True)
],
)
@combine(
program=["gate my(a) q {}", "opaque my(a) q;"],
builtin=[True, False],
)
def test_custom_definition_must_match_gate(self, program, builtin):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' is mismatched"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RXXGate, builtin=builtin)
],
)
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' is mismatched"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("my", 2, 1, lib.U2Gate, builtin=builtin)
],
)
def test_cannot_have_duplicate_customs(self):
customs = [
qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RXXGate),
qiskit.qasm2.CustomInstruction("x", 0, 1, lib.XGate),
qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RZZGate),
]
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "duplicate custom instruction"):
qiskit.qasm2.loads("", custom_instructions=customs)
def test_qiskit_delay_float_input_wraps_exception(self):
program = "opaque delay(t) q; qreg q[1]; delay(1.5) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "can only accept an integer"):
qiskit.qasm2.loads(program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS)
def test_u0_float_input_wraps_exception(self):
program = "opaque u0(n) q; qreg q[1]; u0(1.1) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "must be an integer"):
qiskit.qasm2.loads(program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS)
@ddt.ddt
class TestCustomClassical(QiskitTestCase):
@ddt.data("cos", "exp", "sin", "sqrt", "tan", "ln")
def test_cannot_override_builtin(self, builtin):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"cannot override builtin"):
qiskit.qasm2.loads(
"",
custom_classical=[qiskit.qasm2.CustomClassical(builtin, 1, math.exp)],
)
def test_duplicate_names_disallowed(self):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"duplicate custom classical"):
qiskit.qasm2.loads(
"",
custom_classical=[
qiskit.qasm2.CustomClassical("f", 1, math.exp),
qiskit.qasm2.CustomClassical("f", 1, math.exp),
],
)
def test_cannot_shadow_custom_instruction(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"custom classical.*naming clash"
):
qiskit.qasm2.loads(
"",
custom_instructions=[
qiskit.qasm2.CustomInstruction("f", 0, 1, lib.RXGate, builtin=True)
],
custom_classical=[qiskit.qasm2.CustomClassical("f", 1, math.exp)],
)
def test_cannot_shadow_builtin_instruction(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"custom classical.*cannot shadow"
):
qiskit.qasm2.loads(
"",
custom_classical=[qiskit.qasm2.CustomClassical("U", 1, math.exp)],
)
def test_cannot_shadow_with_gate_definition(self):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"'f' is already defined"):
qiskit.qasm2.loads(
"gate f q {}",
custom_classical=[qiskit.qasm2.CustomClassical("f", 1, math.exp)],
)
@ddt.data("qreg", "creg")
def test_cannot_shadow_with_register_definition(self, regtype):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"'f' is already defined"):
qiskit.qasm2.loads(
f"{regtype} f[2];",
custom_classical=[qiskit.qasm2.CustomClassical("f", 1, math.exp)],
)
@ddt.data((0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1))
@ddt.unpack
def test_mismatched_argument_count(self, n_good, n_bad):
arg_string = ", ".join(["0" for _ in [None] * n_bad])
program = f"""
qreg q[1];
U(f({arg_string}), 0, 0) q[0];
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"custom function argument-count mismatch"
):
qiskit.qasm2.loads(
program, custom_classical=[qiskit.qasm2.CustomClassical("f", n_good, lambda *_: 0)]
)
def test_output_type_error_is_caught(self):
program = """
qreg q[1];
U(f(), 0, 0) q[0];
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"user.*returned non-float"):
qiskit.qasm2.loads(
program,
custom_classical=[qiskit.qasm2.CustomClassical("f", 0, lambda: "not a float")],
)
def test_inner_exception_is_wrapped(self):
inner_exception = Exception("custom exception")
def raises():
raise inner_exception
program = """
qreg q[1];
U(raises(), 0, 0) q[0];
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "caught exception when constant folding"
) as excinfo:
qiskit.qasm2.loads(
program, custom_classical=[qiskit.qasm2.CustomClassical("raises", 0, raises)]
)
assert excinfo.exception.__cause__ is inner_exception
def test_cannot_be_used_as_gate(self):
program = """
qreg q[1];
f(0) q[0];
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"'f' is a custom classical function"
):
qiskit.qasm2.loads(
program, custom_classical=[qiskit.qasm2.CustomClassical("f", 1, lambda x: x)]
)
def test_cannot_be_used_as_qarg(self):
program = """
U(0, 0, 0) f;
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"'f' is a custom classical function"
):
qiskit.qasm2.loads(
program, custom_classical=[qiskit.qasm2.CustomClassical("f", 1, lambda x: x)]
)
def test_cannot_be_used_as_carg(self):
program = """
qreg q[1];
measure q[0] -> f;
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"'f' is a custom classical function"
):
qiskit.qasm2.loads(
program, custom_classical=[qiskit.qasm2.CustomClassical("f", 1, lambda x: x)]
)
@ddt.ddt
class TestStrict(QiskitTestCase):
@ddt.data(
"gate my_gate(p0, p1,) q0, q1 {}",
"gate my_gate(p0, p1) q0, q1, {}",
"opaque my_gate(p0, p1,) q0, q1;",
"opaque my_gate(p0, p1) q0, q1,;",
'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125,) q[0], q[1];',
'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125) q[0], q[1],;',
"qreg q[2]; barrier q[0], q[1],;",
'include "qelib1.inc"; qreg q[1]; rx(sin(pi,)) q[0];',
)
def test_trailing_comma(self, program):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"\[strict\] .*trailing comma"):
qiskit.qasm2.loads("OPENQASM 2.0;\n" + program, strict=True)
def test_trailing_semicolon_after_gate(self):
program = "OPENQASM 2.0; gate my_gate q {};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"\[strict\] .*extra semicolon"):
qiskit.qasm2.loads(program, strict=True)
def test_empty_statement(self):
program = "OPENQASM 2.0; ;"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"\[strict\] .*empty statement"):
qiskit.qasm2.loads(program, strict=True)
def test_required_version_regular(self):
program = "qreg q[1];"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"\[strict\] the first statement"
):
qiskit.qasm2.loads(program, strict=True)
def test_required_version_empty(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"\[strict\] .*needed a version statement"
):
qiskit.qasm2.loads("", strict=True)
def test_barrier_requires_args(self):
program = "OPENQASM 2.0; qreg q[2]; barrier;"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"\[strict\] barrier statements must have at least one"
):
qiskit.qasm2.loads(program, strict=True)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
import io
import math
import os
import pathlib
import pickle
import shutil
import tempfile
import unittest
import ddt
import qiskit.qasm2
from qiskit import qpy
from qiskit.circuit import (
ClassicalRegister,
Gate,
Parameter,
QuantumCircuit,
QuantumRegister,
Qubit,
library as lib,
)
from qiskit.test import QiskitTestCase
from . import gate_builder
class TestEmpty(QiskitTestCase):
def test_allows_empty(self):
self.assertEqual(qiskit.qasm2.loads(""), QuantumCircuit())
class TestVersion(QiskitTestCase):
def test_complete_version(self):
program = "OPENQASM 2.0;"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(parsed, QuantumCircuit())
def test_incomplete_version(self):
program = "OPENQASM 2;"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(parsed, QuantumCircuit())
def test_after_comment(self):
program = """
// hello, world
OPENQASM 2.0;
qreg q[2];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
self.assertEqual(parsed, qc)
class TestRegisters(QiskitTestCase):
def test_qreg(self):
program = "qreg q1[2]; qreg q2[1]; qreg q3[4];"
parsed = qiskit.qasm2.loads(program)
regs = [QuantumRegister(2, "q1"), QuantumRegister(1, "q2"), QuantumRegister(4, "q3")]
self.assertEqual(list(parsed.qregs), regs)
self.assertEqual(list(parsed.cregs), [])
def test_creg(self):
program = "creg c1[2]; creg c2[1]; creg c3[4];"
parsed = qiskit.qasm2.loads(program)
regs = [ClassicalRegister(2, "c1"), ClassicalRegister(1, "c2"), ClassicalRegister(4, "c3")]
self.assertEqual(list(parsed.cregs), regs)
self.assertEqual(list(parsed.qregs), [])
def test_interleaved_registers(self):
program = "qreg q1[3]; creg c1[2]; qreg q2[1]; creg c2[1];"
parsed = qiskit.qasm2.loads(program)
qregs = [QuantumRegister(3, "q1"), QuantumRegister(1, "q2")]
cregs = [ClassicalRegister(2, "c1"), ClassicalRegister(1, "c2")]
self.assertEqual(list(parsed.qregs), qregs)
self.assertEqual(list(parsed.cregs), cregs)
def test_registers_after_gate(self):
program = "qreg before[2]; CX before[0], before[1]; qreg after[2]; CX after[0], after[1];"
parsed = qiskit.qasm2.loads(program)
before = QuantumRegister(2, "before")
after = QuantumRegister(2, "after")
qc = QuantumCircuit(before, after)
qc.cx(before[0], before[1])
qc.cx(after[0], after[1])
self.assertEqual(parsed, qc)
def test_empty_registers(self):
program = "qreg q[0]; creg c[0];"
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(0, "q"), ClassicalRegister(0, "c"))
self.assertEqual(parsed, qc)
@ddt.ddt
class TestGateApplication(QiskitTestCase):
def test_builtin_single(self):
program = """
qreg q[2];
U(0, 0, 0) q[0];
CX q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.u(0, 0, 0, 0)
qc.cx(0, 1)
self.assertEqual(parsed, qc)
def test_builtin_1q_broadcast(self):
program = "qreg q[2]; U(0, 0, 0) q;"
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.u(0, 0, 0, 0)
qc.u(0, 0, 0, 1)
self.assertEqual(parsed, qc)
def test_builtin_2q_broadcast(self):
program = """
qreg q1[2];
qreg q2[2];
CX q1[0], q2;
barrier;
CX q1, q2[1];
barrier;
CX q1, q2;
"""
parsed = qiskit.qasm2.loads(program)
q1 = QuantumRegister(2, "q1")
q2 = QuantumRegister(2, "q2")
qc = QuantumCircuit(q1, q2)
qc.cx(q1[0], q2[0])
qc.cx(q1[0], q2[1])
qc.barrier()
qc.cx(q1[0], q2[1])
qc.cx(q1[1], q2[1])
qc.barrier()
qc.cx(q1[0], q2[0])
qc.cx(q1[1], q2[1])
self.assertEqual(parsed, qc)
def test_3q_broadcast(self):
program = """
include "qelib1.inc";
qreg q1[2];
qreg q2[2];
qreg q3[2];
ccx q1, q2[0], q3[1];
ccx q1[1], q2, q3[0];
ccx q1[0], q2[1], q3;
barrier;
ccx q1, q2, q3[1];
ccx q1[1], q2, q3;
ccx q1, q2[1], q3;
barrier;
ccx q1, q2, q3;
"""
parsed = qiskit.qasm2.loads(program)
q1 = QuantumRegister(2, "q1")
q2 = QuantumRegister(2, "q2")
q3 = QuantumRegister(2, "q3")
qc = QuantumCircuit(q1, q2, q3)
qc.ccx(q1[0], q2[0], q3[1])
qc.ccx(q1[1], q2[0], q3[1])
qc.ccx(q1[1], q2[0], q3[0])
qc.ccx(q1[1], q2[1], q3[0])
qc.ccx(q1[0], q2[1], q3[0])
qc.ccx(q1[0], q2[1], q3[1])
qc.barrier()
qc.ccx(q1[0], q2[0], q3[1])
qc.ccx(q1[1], q2[1], q3[1])
qc.ccx(q1[1], q2[0], q3[0])
qc.ccx(q1[1], q2[1], q3[1])
qc.ccx(q1[0], q2[1], q3[0])
qc.ccx(q1[1], q2[1], q3[1])
qc.barrier()
qc.ccx(q1[0], q2[0], q3[0])
qc.ccx(q1[1], q2[1], q3[1])
self.assertEqual(parsed, qc)
@ddt.data(True, False)
def test_broadcast_against_empty_register(self, conditioned):
cond = "if (cond == 0) " if conditioned else ""
program = f"""
OPENQASM 2;
include "qelib1.inc";
qreg q1[1];
qreg q2[1];
qreg empty1[0];
qreg empty2[0];
qreg empty3[0];
creg cond[1];
// None of the following statements should produce any gate applications.
{cond}h empty1;
{cond}cx q1[0], empty1;
{cond}cx empty1, q2[0];
{cond}cx empty1, empty2;
{cond}ccx empty1, q1[0], q2[0];
{cond}ccx q1[0], empty2, q2[0];
{cond}ccx q1[0], q2[0], empty3;
{cond}ccx empty1, empty2, q1[0];
{cond}ccx empty1, q1[0], empty2;
{cond}ccx q1[0], empty1, empty2;
{cond}ccx empty1, empty2, empty3;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(
QuantumRegister(1, "q1"),
QuantumRegister(1, "q2"),
QuantumRegister(0, "empty1"),
QuantumRegister(0, "empty2"),
QuantumRegister(0, "empty3"),
ClassicalRegister(1, "cond"),
)
self.assertEqual(parsed, qc)
def test_conditioned(self):
program = """
qreg q[2];
creg cond[1];
if (cond == 0) U(0, 0, 0) q[0];
if (cond == 1) CX q[1], q[0];
"""
parsed = qiskit.qasm2.loads(program)
cond = ClassicalRegister(1, "cond")
qc = QuantumCircuit(QuantumRegister(2, "q"), cond)
qc.u(0, 0, 0, 0).c_if(cond, 0)
qc.cx(1, 0).c_if(cond, 1)
self.assertEqual(parsed, qc)
def test_conditioned_broadcast(self):
program = """
qreg q1[2];
qreg q2[2];
creg cond[1];
if (cond == 0) U(0, 0, 0) q1;
if (cond == 1) CX q1[0], q2;
"""
parsed = qiskit.qasm2.loads(program)
cond = ClassicalRegister(1, "cond")
q1 = QuantumRegister(2, "q1")
q2 = QuantumRegister(2, "q2")
qc = QuantumCircuit(q1, q2, cond)
qc.u(0, 0, 0, q1[0]).c_if(cond, 0)
qc.u(0, 0, 0, q1[1]).c_if(cond, 0)
qc.cx(q1[0], q2[0]).c_if(cond, 1)
qc.cx(q1[0], q2[1]).c_if(cond, 1)
self.assertEqual(parsed, qc)
def test_constant_folding(self):
# Most expression-related things are tested in `test_expression.py` instead.
program = """
qreg q[1];
U(4 + 3 * 2 ^ 2, cos(pi) * (1 - ln(1)), 2 ^ 3 ^ 2) q[0];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.u(16.0, -1.0, 512.0, 0)
self.assertEqual(parsed, qc)
def test_call_defined_gate(self):
program = """
gate my_gate a {
U(0, 0, 0) a;
}
qreg q[2];
my_gate q[0];
my_gate q;
"""
parsed = qiskit.qasm2.loads(program)
my_gate_def = QuantumCircuit([Qubit()])
my_gate_def.u(0, 0, 0, 0)
my_gate = gate_builder("my_gate", [], my_gate_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(my_gate(), [0])
qc.append(my_gate(), [0])
qc.append(my_gate(), [1])
self.assertEqual(parsed, qc)
def test_parameterless_gates_accept_parentheses(self):
program = """
qreg q[2];
CX q[0], q[1];
CX() q[1], q[0];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.cx(0, 1)
qc.cx(1, 0)
self.assertEqual(parsed, qc)
class TestGateDefinition(QiskitTestCase):
def test_simple_definition(self):
program = """
gate not_bell a, b {
U(0, 0, 0) a;
CX a, b;
}
qreg q[2];
not_bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
not_bell_def = QuantumCircuit([Qubit(), Qubit()])
not_bell_def.u(0, 0, 0, 0)
not_bell_def.cx(0, 1)
not_bell = gate_builder("not_bell", [], not_bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(not_bell(), [0, 1])
self.assertEqual(parsed, qc)
def test_conditioned(self):
program = """
gate not_bell a, b {
U(0, 0, 0) a;
CX a, b;
}
qreg q[2];
creg cond[1];
if (cond == 0) not_bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
not_bell_def = QuantumCircuit([Qubit(), Qubit()])
not_bell_def.u(0, 0, 0, 0)
not_bell_def.cx(0, 1)
not_bell = gate_builder("not_bell", [], not_bell_def)
cond = ClassicalRegister(1, "cond")
qc = QuantumCircuit(QuantumRegister(2, "q"), cond)
qc.append(not_bell().c_if(cond, 0), [0, 1])
self.assertEqual(parsed, qc)
def test_constant_folding_in_definition(self):
program = """
gate bell a, b {
U(pi/2, 0, pi) a;
CX a, b;
}
qreg q[2];
bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
bell_def = QuantumCircuit([Qubit(), Qubit()])
bell_def.u(math.pi / 2, 0, math.pi, 0)
bell_def.cx(0, 1)
bell = gate_builder("bell", [], bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(bell(), [0, 1])
self.assertEqual(parsed, qc)
def test_parameterised_gate(self):
# Most of the tests of deep parameter expressions are in `test_expression.py`.
program = """
gate my_gate(a, b) c {
U(a, b, a + 2 * b) c;
}
qreg q[1];
my_gate(0.25, 0.5) q[0];
my_gate(0.5, 0.25) q[0];
"""
parsed = qiskit.qasm2.loads(program)
a, b = Parameter("a"), Parameter("b")
my_gate_def = QuantumCircuit([Qubit()])
my_gate_def.u(a, b, a + 2 * b, 0)
my_gate = gate_builder("my_gate", [a, b], my_gate_def)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(my_gate(0.25, 0.5), [0])
qc.append(my_gate(0.5, 0.25), [0])
self.assertEqual(parsed, qc)
# Also check the decomposition has come out exactly as expected. The floating-point
# assertions are safe as exact equality checks because there are no lossy operations with
# these parameters, and the answer should be exact.
decomposed = qc.decompose()
self.assertEqual(decomposed.data[0].operation.name, "u")
self.assertEqual(list(decomposed.data[0].operation.params), [0.25, 0.5, 1.25])
self.assertEqual(decomposed.data[1].operation.name, "u")
self.assertEqual(list(decomposed.data[1].operation.params), [0.5, 0.25, 1.0])
def test_parameterless_gate_with_parentheses(self):
program = """
gate my_gate() a {
U(0, 0, 0) a;
}
qreg q[1];
my_gate q[0];
my_gate() q[0];
"""
parsed = qiskit.qasm2.loads(program)
my_gate_def = QuantumCircuit([Qubit()])
my_gate_def.u(0, 0, 0, 0)
my_gate = gate_builder("my_gate", [], my_gate_def)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(my_gate(), [0])
qc.append(my_gate(), [0])
self.assertEqual(parsed, qc)
def test_access_includes_in_definition(self):
program = """
include "qelib1.inc";
gate bell a, b {
h a;
cx a, b;
}
qreg q[2];
bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
bell_def = QuantumCircuit([Qubit(), Qubit()])
bell_def.h(0)
bell_def.cx(0, 1)
bell = gate_builder("bell", [], bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(bell(), [0, 1])
self.assertEqual(parsed, qc)
def test_access_previous_defined_gate(self):
program = """
include "qelib1.inc";
gate bell a, b {
h a;
cx a, b;
}
gate second_bell a, b {
bell b, a;
}
qreg q[2];
second_bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
bell_def = QuantumCircuit([Qubit(), Qubit()])
bell_def.h(0)
bell_def.cx(0, 1)
bell = gate_builder("bell", [], bell_def)
second_bell_def = QuantumCircuit([Qubit(), Qubit()])
second_bell_def.append(bell(), [1, 0])
second_bell = gate_builder("second_bell", [], second_bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(second_bell(), [0, 1])
self.assertEqual(parsed, qc)
def test_qubits_lookup_differently_to_gates(self):
# The spec is somewhat unclear on this, and this leads to super weird text, but it's
# technically unambiguously resolvable and this is more permissive.
program = """
include "qelib1.inc";
gate bell h, cx {
h h;
cx h, cx;
}
qreg q[2];
bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
bell_def = QuantumCircuit([Qubit(), Qubit()])
bell_def.h(0)
bell_def.cx(0, 1)
bell = gate_builder("bell", [], bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(bell(), [0, 1])
self.assertEqual(parsed, qc)
def test_parameters_lookup_differently_to_gates(self):
# The spec is somewhat unclear on this, and this leads to super weird text, but it's
# technically unambiguously resolvable and this is more permissive.
program = """
include "qelib1.inc";
gate shadow(rx, rz) a {
rz(rz) a;
rx(rx) a;
}
qreg q[1];
shadow(0.5, 2.0) q[0];
"""
parsed = qiskit.qasm2.loads(program)
rx, rz = Parameter("rx"), Parameter("rz")
shadow_def = QuantumCircuit([Qubit()])
shadow_def.rz(rz, 0)
shadow_def.rx(rx, 0)
shadow = gate_builder("shadow", [rx, rz], shadow_def)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(shadow(0.5, 2.0), [0])
self.assertEqual(parsed, qc)
def test_unused_parameters_convert_correctly(self):
# The main risk here is that there might be lazy application in the gate definition
# bindings, and we might accidentally try and bind parameters that aren't actually in the
# definition.
program = """
gate my_gate(p) q {
U(0, 0, 0) q;
}
qreg q[1];
my_gate(0.5) q[0];
"""
parsed = qiskit.qasm2.loads(program)
# No top-level circuit equality test here, because all the internals of gate application are
# an implementation detail, and we don't want to tie the tests and implementation together
# too closely.
self.assertEqual(list(parsed.qregs), [QuantumRegister(1, "q")])
self.assertEqual(list(parsed.cregs), [])
self.assertEqual(len(parsed.data), 1)
self.assertEqual(parsed.data[0].qubits, (parsed.qubits[0],))
self.assertEqual(parsed.data[0].clbits, ())
self.assertEqual(parsed.data[0].operation.name, "my_gate")
self.assertEqual(list(parsed.data[0].operation.params), [0.5])
decomposed = QuantumCircuit(QuantumRegister(1, "q"))
decomposed.u(0, 0, 0, 0)
self.assertEqual(parsed.decompose(), decomposed)
def test_qubit_barrier_in_definition(self):
program = """
gate my_gate a, b {
barrier a;
barrier b;
barrier a, b;
}
qreg q[2];
my_gate q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
my_gate_def = QuantumCircuit([Qubit(), Qubit()])
my_gate_def.barrier(0)
my_gate_def.barrier(1)
my_gate_def.barrier([0, 1])
my_gate = gate_builder("my_gate", [], my_gate_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(my_gate(), [0, 1])
self.assertEqual(parsed, qc)
def test_bare_barrier_in_definition(self):
program = """
gate my_gate a, b {
barrier;
}
qreg q[2];
my_gate q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
my_gate_def = QuantumCircuit([Qubit(), Qubit()])
my_gate_def.barrier(my_gate_def.qubits)
my_gate = gate_builder("my_gate", [], my_gate_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(my_gate(), [0, 1])
self.assertEqual(parsed, qc)
def test_duplicate_barrier_in_definition(self):
program = """
gate my_gate a, b {
barrier a, a;
barrier b, a, b;
}
qreg q[2];
my_gate q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
my_gate_def = QuantumCircuit([Qubit(), Qubit()])
my_gate_def.barrier(0)
my_gate_def.barrier([1, 0])
my_gate = gate_builder("my_gate", [], my_gate_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(my_gate(), [0, 1])
self.assertEqual(parsed, qc)
def test_pickleable(self):
program = """
include "qelib1.inc";
gate my_gate(a) b, c {
rz(2 * a) b;
h b;
cx b, c;
}
qreg q[2];
my_gate(0.5) q[0], q[1];
my_gate(0.25) q[1], q[0];
"""
parsed = qiskit.qasm2.loads(program)
a = Parameter("a")
my_gate_def = QuantumCircuit([Qubit(), Qubit()])
my_gate_def.rz(2 * a, 0)
my_gate_def.h(0)
my_gate_def.cx(0, 1)
my_gate = gate_builder("my_gate", [a], my_gate_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(my_gate(0.5), [0, 1])
qc.append(my_gate(0.25), [1, 0])
self.assertEqual(parsed, qc)
with io.BytesIO() as fptr:
pickle.dump(parsed, fptr)
fptr.seek(0)
loaded = pickle.load(fptr)
self.assertEqual(parsed, loaded)
def test_qpy_single_call_roundtrip(self):
program = """
include "qelib1.inc";
gate my_gate(a) b, c {
rz(2 * a) b;
h b;
cx b, c;
}
qreg q[2];
my_gate(0.5) q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
# QPY won't persist custom gates by design choice, so instead let us check against the
# explicit form it uses.
my_gate_def = QuantumCircuit([Qubit(), Qubit()])
my_gate_def.rz(1.0, 0)
my_gate_def.h(0)
my_gate_def.cx(0, 1)
my_gate = Gate("my_gate", 2, [0.5])
my_gate.definition = my_gate_def
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(my_gate, [0, 1])
with io.BytesIO() as fptr:
qpy.dump(parsed, fptr)
fptr.seek(0)
loaded = qpy.load(fptr)[0]
self.assertEqual(loaded, qc)
# See https://github.com/Qiskit/qiskit-terra/issues/8941
@unittest.expectedFailure
def test_qpy_double_call_roundtrip(self):
program = """
include "qelib1.inc";
gate my_gate(a) b, c {
rz(2 * a) b;
h b;
cx b, c;
}
qreg q[2];
my_gate(0.5) q[0], q[1];
my_gate(0.25) q[1], q[0];
"""
parsed = qiskit.qasm2.loads(program)
my_gate1_def = QuantumCircuit([Qubit(), Qubit()])
my_gate1_def.rz(1.0, 0)
my_gate1_def.h(0)
my_gate1_def.cx(0, 1)
my_gate1 = Gate("my_gate", 2, [0.5])
my_gate1.definition = my_gate1_def
my_gate2_def = QuantumCircuit([Qubit(), Qubit()])
my_gate2_def.rz(0.5, 0)
my_gate2_def.h(0)
my_gate2_def.cx(0, 1)
my_gate2 = Gate("my_gate", 2, [0.25])
my_gate2.definition = my_gate2_def
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(my_gate1, [0, 1])
qc.append(my_gate2, [1, 0])
with io.BytesIO() as fptr:
qpy.dump(parsed, fptr)
fptr.seek(0)
loaded = qpy.load(fptr)[0]
self.assertEqual(loaded, qc)
class TestOpaque(QiskitTestCase):
def test_simple(self):
program = """
opaque my_gate a;
opaque my_gate2() a;
qreg q[2];
my_gate q[0];
my_gate() q[1];
my_gate2 q[0];
my_gate2() q[1];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(Gate("my_gate", 1, []), [0])
qc.append(Gate("my_gate", 1, []), [1])
qc.append(Gate("my_gate2", 1, []), [0])
qc.append(Gate("my_gate2", 1, []), [1])
self.assertEqual(parsed, qc)
def test_parameterised(self):
program = """
opaque my_gate(a, b) c, d;
qreg q[2];
my_gate(0.5, 0.25) q[1], q[0];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(Gate("my_gate", 2, [0.5, 0.25]), [1, 0])
self.assertEqual(parsed, qc)
class TestBarrier(QiskitTestCase):
def test_single_register_argument(self):
program = """
qreg first[3];
qreg second[3];
barrier first;
barrier second;
"""
parsed = qiskit.qasm2.loads(program)
first = QuantumRegister(3, "first")
second = QuantumRegister(3, "second")
qc = QuantumCircuit(first, second)
qc.barrier(first)
qc.barrier(second)
self.assertEqual(parsed, qc)
def test_single_qubit_argument(self):
program = """
qreg first[3];
qreg second[3];
barrier first[1];
barrier second[0];
"""
parsed = qiskit.qasm2.loads(program)
first = QuantumRegister(3, "first")
second = QuantumRegister(3, "second")
qc = QuantumCircuit(first, second)
qc.barrier(first[1])
qc.barrier(second[0])
self.assertEqual(parsed, qc)
def test_empty_circuit_empty_arguments(self):
program = "barrier;"
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit()
self.assertEqual(parsed, qc)
def test_one_register_circuit_empty_arguments(self):
program = "qreg q1[2]; barrier;"
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q1"))
qc.barrier(qc.qubits)
self.assertEqual(parsed, qc)
def test_multi_register_circuit_empty_arguments(self):
program = "qreg q1[2]; qreg q2[3]; qreg q3[1]; barrier;"
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(
QuantumRegister(2, "q1"), QuantumRegister(3, "q2"), QuantumRegister(1, "q3")
)
qc.barrier(qc.qubits)
self.assertEqual(parsed, qc)
def test_include_empty_register(self):
program = """
qreg q[2];
qreg empty[0];
barrier empty;
barrier q, empty;
barrier;
"""
parsed = qiskit.qasm2.loads(program)
q = QuantumRegister(2, "q")
qc = QuantumCircuit(q, QuantumRegister(0, "empty"))
qc.barrier(q)
qc.barrier(qc.qubits)
self.assertEqual(parsed, qc)
def test_allows_duplicate_arguments(self):
# There's nothing in the paper that implies this should be forbidden.
program = """
qreg q1[3];
qreg q2[2];
barrier q1, q1;
barrier q1[0], q1;
barrier q1, q1[0];
barrier q1, q2, q1;
"""
parsed = qiskit.qasm2.loads(program)
q1 = QuantumRegister(3, "q1")
q2 = QuantumRegister(2, "q2")
qc = QuantumCircuit(q1, q2)
qc.barrier(q1)
qc.barrier(q1)
qc.barrier(q1)
qc.barrier(q1, q2)
self.assertEqual(parsed, qc)
class TestMeasure(QiskitTestCase):
def test_single(self):
program = """
qreg q[1];
creg c[1];
measure q[0] -> c[0];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(1, "q"), ClassicalRegister(1, "c"))
qc.measure(0, 0)
self.assertEqual(parsed, qc)
def test_broadcast(self):
program = """
qreg q[2];
creg c[2];
measure q -> c;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "c"))
qc.measure(0, 0)
qc.measure(1, 1)
self.assertEqual(parsed, qc)
def test_conditioned(self):
program = """
qreg q[2];
creg c[2];
creg cond[1];
if (cond == 0) measure q[0] -> c[0];
if (cond == 1) measure q -> c;
"""
parsed = qiskit.qasm2.loads(program)
cond = ClassicalRegister(1, "cond")
qc = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "c"), cond)
qc.measure(0, 0).c_if(cond, 0)
qc.measure(0, 0).c_if(cond, 1)
qc.measure(1, 1).c_if(cond, 1)
self.assertEqual(parsed, qc)
def test_broadcast_against_empty_register(self):
program = """
qreg q_empty[0];
creg c_empty[0];
measure q_empty -> c_empty;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(0, "q_empty"), ClassicalRegister(0, "c_empty"))
self.assertEqual(parsed, qc)
def test_conditioned_broadcast_against_empty_register(self):
program = """
qreg q_empty[0];
creg c_empty[0];
creg cond[1];
if (cond == 0) measure q_empty -> c_empty;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(
QuantumRegister(0, "q_empty"),
ClassicalRegister(0, "c_empty"),
ClassicalRegister(1, "cond"),
)
self.assertEqual(parsed, qc)
class TestReset(QiskitTestCase):
def test_single(self):
program = """
qreg q[1];
reset q[0];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.reset(0)
self.assertEqual(parsed, qc)
def test_broadcast(self):
program = """
qreg q[2];
reset q;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.reset(0)
qc.reset(1)
self.assertEqual(parsed, qc)
def test_conditioned(self):
program = """
qreg q[2];
creg cond[1];
if (cond == 0) reset q[0];
if (cond == 1) reset q;
"""
parsed = qiskit.qasm2.loads(program)
cond = ClassicalRegister(1, "cond")
qc = QuantumCircuit(QuantumRegister(2, "q"), cond)
qc.reset(0).c_if(cond, 0)
qc.reset(0).c_if(cond, 1)
qc.reset(1).c_if(cond, 1)
self.assertEqual(parsed, qc)
def test_broadcast_against_empty_register(self):
program = """
qreg empty[0];
reset empty;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(0, "empty"))
self.assertEqual(parsed, qc)
def test_conditioned_broadcast_against_empty_register(self):
program = """
qreg empty[0];
creg cond[1];
if (cond == 0) reset empty;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(0, "empty"), ClassicalRegister(1, "cond"))
self.assertEqual(parsed, qc)
class TestInclude(QiskitTestCase):
def setUp(self):
super().setUp()
self.tmp_dir = pathlib.Path(tempfile.mkdtemp())
def tearDown(self):
# Doesn't really matter if the removal fails, since this was a tempdir anyway; it'll get
# cleaned up by the OS at some point.
shutil.rmtree(self.tmp_dir, ignore_errors=True)
super().tearDown()
def test_qelib1_include(self):
program = """
include "qelib1.inc";
qreg q[3];
u3(0.5, 0.25, 0.125) q[0];
u2(0.5, 0.25) q[0];
u1(0.5) q[0];
cx q[0], q[1];
id q[0];
x q[0];
y q[0];
z q[0];
h q[0];
s q[0];
sdg q[0];
t q[0];
tdg q[0];
rx(0.5) q[0];
ry(0.5) q[0];
rz(0.5) q[0];
cz q[0], q[1];
cy q[0], q[1];
ch q[0], q[1];
ccx q[0], q[1], q[2];
crz(0.5) q[0], q[1];
cu1(0.5) q[0], q[1];
cu3(0.5, 0.25, 0.125) q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(3, "q"))
qc.append(lib.U3Gate(0.5, 0.25, 0.125), [0])
qc.append(lib.U2Gate(0.5, 0.25), [0])
qc.append(lib.U1Gate(0.5), [0])
qc.append(lib.CXGate(), [0, 1])
qc.append(lib.UGate(0, 0, 0), [0]) # Stand-in for id.
qc.append(lib.XGate(), [0])
qc.append(lib.YGate(), [0])
qc.append(lib.ZGate(), [0])
qc.append(lib.HGate(), [0])
qc.append(lib.SGate(), [0])
qc.append(lib.SdgGate(), [0])
qc.append(lib.TGate(), [0])
qc.append(lib.TdgGate(), [0])
qc.append(lib.RXGate(0.5), [0])
qc.append(lib.RYGate(0.5), [0])
qc.append(lib.RZGate(0.5), [0])
qc.append(lib.CZGate(), [0, 1])
qc.append(lib.CYGate(), [0, 1])
qc.append(lib.CHGate(), [0, 1])
qc.append(lib.CCXGate(), [0, 1, 2])
qc.append(lib.CRZGate(0.5), [0, 1])
qc.append(lib.CU1Gate(0.5), [0, 1])
qc.append(lib.CU3Gate(0.5, 0.25, 0.125), [0, 1])
self.assertEqual(parsed, qc)
def test_qelib1_after_gate_definition(self):
program = """
gate bell a, b {
U(pi/2, 0, pi) a;
CX a, b;
}
include "qelib1.inc";
qreg q[2];
bell q[0], q[1];
rx(0.5) q[0];
bell q[1], q[0];
"""
parsed = qiskit.qasm2.loads(program)
bell_def = QuantumCircuit([Qubit(), Qubit()])
bell_def.u(math.pi / 2, 0, math.pi, 0)
bell_def.cx(0, 1)
bell = gate_builder("bell", [], bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(bell(), [0, 1])
qc.rx(0.5, 0)
qc.append(bell(), [1, 0])
self.assertEqual(parsed, qc)
def test_include_can_define_version(self):
include = """
OPENQASM 2.0;
qreg inner_q[2];
"""
with open(self.tmp_dir / "include.qasm", "w") as fp:
fp.write(include)
program = """
OPENQASM 2.0;
include "include.qasm";
"""
parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,))
qc = QuantumCircuit(QuantumRegister(2, "inner_q"))
self.assertEqual(parsed, qc)
def test_can_define_gates(self):
include = """
gate bell a, b {
h a;
cx a, b;
}
"""
with open(self.tmp_dir / "include.qasm", "w") as fp:
fp.write(include)
program = """
OPENQASM 2.0;
include "qelib1.inc";
include "include.qasm";
qreg q[2];
bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,))
bell_def = QuantumCircuit([Qubit(), Qubit()])
bell_def.h(0)
bell_def.cx(0, 1)
bell = gate_builder("bell", [], bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(bell(), [0, 1])
self.assertEqual(parsed, qc)
def test_nested_include(self):
inner = "creg c[2];"
with open(self.tmp_dir / "inner.qasm", "w") as fp:
fp.write(inner)
outer = """
qreg q[2];
include "inner.qasm";
"""
with open(self.tmp_dir / "outer.qasm", "w") as fp:
fp.write(outer)
program = """
OPENQASM 2.0;
include "outer.qasm";
"""
parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,))
qc = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "c"))
self.assertEqual(parsed, qc)
def test_first_hit_is_used(self):
empty = self.tmp_dir / "empty"
empty.mkdir()
first = self.tmp_dir / "first"
first.mkdir()
with open(first / "include.qasm", "w") as fp:
fp.write("qreg q[1];")
second = self.tmp_dir / "second"
second.mkdir()
with open(second / "include.qasm", "w") as fp:
fp.write("qreg q[2];")
program = 'include "include.qasm";'
parsed = qiskit.qasm2.loads(program, include_path=(empty, first, second))
qc = QuantumCircuit(QuantumRegister(1, "q"))
self.assertEqual(parsed, qc)
def test_qelib1_ignores_search_path(self):
with open(self.tmp_dir / "qelib1.inc", "w") as fp:
fp.write("qreg not_used[2];")
program = 'include "qelib1.inc";'
parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,))
qc = QuantumCircuit()
self.assertEqual(parsed, qc)
def test_include_from_current_directory(self):
include = """
qreg q[2];
"""
with open(self.tmp_dir / "include.qasm", "w") as fp:
fp.write(include)
program = """
OPENQASM 2.0;
include "include.qasm";
"""
prevdir = os.getcwd()
os.chdir(self.tmp_dir)
try:
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
self.assertEqual(parsed, qc)
finally:
os.chdir(prevdir)
def test_load_searches_source_directory(self):
with open(self.tmp_dir / "include.qasm", "w") as fp:
fp.write("qreg q[2];")
program = 'include "include.qasm";'
with open(self.tmp_dir / "program.qasm", "w") as fp:
fp.write(program)
parsed = qiskit.qasm2.load(self.tmp_dir / "program.qasm")
qc = QuantumCircuit(QuantumRegister(2, "q"))
self.assertEqual(parsed, qc)
def test_load_searches_source_directory_last(self):
first = self.tmp_dir / "first"
first.mkdir()
with open(first / "include.qasm", "w") as fp:
fp.write("qreg q[2];")
with open(self.tmp_dir / "include.qasm", "w") as fp:
fp.write("qreg not_used[2];")
program = 'include "include.qasm";'
with open(self.tmp_dir / "program.qasm", "w") as fp:
fp.write(program)
parsed = qiskit.qasm2.load(self.tmp_dir / "program.qasm", include_path=(first,))
qc = QuantumCircuit(QuantumRegister(2, "q"))
self.assertEqual(parsed, qc)
def test_load_searches_source_directory_prepend(self):
first = self.tmp_dir / "first"
first.mkdir()
with open(first / "include.qasm", "w") as fp:
fp.write("qreg not_used[2];")
with open(self.tmp_dir / "include.qasm", "w") as fp:
fp.write("qreg q[2];")
program = 'include "include.qasm";'
with open(self.tmp_dir / "program.qasm", "w") as fp:
fp.write(program)
parsed = qiskit.qasm2.load(
self.tmp_dir / "program.qasm", include_path=(first,), include_input_directory="prepend"
)
qc = QuantumCircuit(QuantumRegister(2, "q"))
self.assertEqual(parsed, qc)
def test_load_can_ignore_source_directory(self):
with open(self.tmp_dir / "include.qasm", "w") as fp:
fp.write("qreg q[2];")
program = 'include "include.qasm";'
with open(self.tmp_dir / "program.qasm", "w") as fp:
fp.write(program)
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "unable to find 'include.qasm'"):
qiskit.qasm2.load(self.tmp_dir / "program.qasm", include_input_directory=None)
@ddt.ddt
class TestCustomInstructions(QiskitTestCase):
def test_qelib1_include_overridden(self):
program = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
u3(0.5, 0.25, 0.125) q[0];
u2(0.5, 0.25) q[0];
u1(0.5) q[0];
cx q[0], q[1];
id q[0];
x q[0];
y q[0];
z q[0];
h q[0];
s q[0];
sdg q[0];
t q[0];
tdg q[0];
rx(0.5) q[0];
ry(0.5) q[0];
rz(0.5) q[0];
cz q[0], q[1];
cy q[0], q[1];
ch q[0], q[1];
ccx q[0], q[1], q[2];
crz(0.5) q[0], q[1];
cu1(0.5) q[0], q[1];
cu3(0.5, 0.25, 0.125) q[0], q[1];
"""
parsed = qiskit.qasm2.loads(
program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS
)
qc = QuantumCircuit(QuantumRegister(3, "q"))
qc.append(lib.U3Gate(0.5, 0.25, 0.125), [0])
qc.append(lib.U2Gate(0.5, 0.25), [0])
qc.append(lib.U1Gate(0.5), [0])
qc.append(lib.CXGate(), [0, 1])
qc.append(lib.IGate(), [0])
qc.append(lib.XGate(), [0])
qc.append(lib.YGate(), [0])
qc.append(lib.ZGate(), [0])
qc.append(lib.HGate(), [0])
qc.append(lib.SGate(), [0])
qc.append(lib.SdgGate(), [0])
qc.append(lib.TGate(), [0])
qc.append(lib.TdgGate(), [0])
qc.append(lib.RXGate(0.5), [0])
qc.append(lib.RYGate(0.5), [0])
qc.append(lib.RZGate(0.5), [0])
qc.append(lib.CZGate(), [0, 1])
qc.append(lib.CYGate(), [0, 1])
qc.append(lib.CHGate(), [0, 1])
qc.append(lib.CCXGate(), [0, 1, 2])
qc.append(lib.CRZGate(0.5), [0, 1])
qc.append(lib.CU1Gate(0.5), [0, 1])
qc.append(lib.CU3Gate(0.5, 0.25, 0.125), [0, 1])
self.assertEqual(parsed, qc)
# Also test that the output matches what Qiskit puts out.
from_qiskit = QuantumCircuit.from_qasm_str(program)
self.assertEqual(parsed, from_qiskit)
def test_qelib1_sparse_overrides(self):
"""Test that the qelib1 special import still works as expected when a couple of gates in the
middle of it are custom. As long as qelib1 is handled specially, there is a risk that this
handling will break in weird ways when custom instructions overlap it."""
program = """
include "qelib1.inc";
qreg q[3];
u3(0.5, 0.25, 0.125) q[0];
u2(0.5, 0.25) q[0];
u1(0.5) q[0];
cx q[0], q[1];
id q[0];
x q[0];
y q[0];
z q[0];
h q[0];
s q[0];
sdg q[0];
t q[0];
tdg q[0];
rx(0.5) q[0];
ry(0.5) q[0];
rz(0.5) q[0];
cz q[0], q[1];
cy q[0], q[1];
ch q[0], q[1];
ccx q[0], q[1], q[2];
crz(0.5) q[0], q[1];
cu1(0.5) q[0], q[1];
cu3(0.5, 0.25, 0.125) q[0], q[1];
"""
parsed = qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("id", 0, 1, lib.IGate),
qiskit.qasm2.CustomInstruction("h", 0, 1, lib.HGate),
qiskit.qasm2.CustomInstruction("crz", 1, 2, lib.CRZGate),
],
)
qc = QuantumCircuit(QuantumRegister(3, "q"))
qc.append(lib.U3Gate(0.5, 0.25, 0.125), [0])
qc.append(lib.U2Gate(0.5, 0.25), [0])
qc.append(lib.U1Gate(0.5), [0])
qc.append(lib.CXGate(), [0, 1])
qc.append(lib.IGate(), [0])
qc.append(lib.XGate(), [0])
qc.append(lib.YGate(), [0])
qc.append(lib.ZGate(), [0])
qc.append(lib.HGate(), [0])
qc.append(lib.SGate(), [0])
qc.append(lib.SdgGate(), [0])
qc.append(lib.TGate(), [0])
qc.append(lib.TdgGate(), [0])
qc.append(lib.RXGate(0.5), [0])
qc.append(lib.RYGate(0.5), [0])
qc.append(lib.RZGate(0.5), [0])
qc.append(lib.CZGate(), [0, 1])
qc.append(lib.CYGate(), [0, 1])
qc.append(lib.CHGate(), [0, 1])
qc.append(lib.CCXGate(), [0, 1, 2])
qc.append(lib.CRZGate(0.5), [0, 1])
qc.append(lib.CU1Gate(0.5), [0, 1])
qc.append(lib.CU3Gate(0.5, 0.25, 0.125), [0, 1])
self.assertEqual(parsed, qc)
def test_user_gate_after_overidden_qelib1(self):
program = """
include "qelib1.inc";
qreg q[1];
opaque my_gate q;
my_gate q[0];
"""
parsed = qiskit.qasm2.loads(
program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(Gate("my_gate", 1, []), [0])
self.assertEqual(parsed, qc)
def test_qiskit_extra_builtins(self):
program = """
qreg q[5];
u(0.5 ,0.25, 0.125) q[0];
p(0.5) q[0];
sx q[0];
sxdg q[0];
swap q[0], q[1];
cswap q[0], q[1], q[2];
crx(0.5) q[0], q[1];
cry(0.5) q[0], q[1];
cp(0.5) q[0], q[1];
csx q[0], q[1];
cu(0.5, 0.25, 0.125, 0.0625) q[0], q[1];
rxx(0.5) q[0], q[1];
rzz(0.5) q[0], q[1];
rccx q[0], q[1], q[2];
rc3x q[0], q[1], q[2], q[3];
c3x q[0], q[1], q[2], q[3];
c3sqrtx q[0], q[1], q[2], q[3];
c4x q[0], q[1], q[2], q[3], q[4];
"""
parsed = qiskit.qasm2.loads(
program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS
)
qc = QuantumCircuit(QuantumRegister(5, "q"))
qc.append(lib.UGate(0.5, 0.25, 0.125), [0])
qc.append(lib.PhaseGate(0.5), [0])
qc.append(lib.SXGate(), [0])
qc.append(lib.SXdgGate(), [0])
qc.append(lib.SwapGate(), [0, 1])
qc.append(lib.CSwapGate(), [0, 1, 2])
qc.append(lib.CRXGate(0.5), [0, 1])
qc.append(lib.CRYGate(0.5), [0, 1])
qc.append(lib.CPhaseGate(0.5), [0, 1])
qc.append(lib.CSXGate(), [0, 1])
qc.append(lib.CUGate(0.5, 0.25, 0.125, 0.0625), [0, 1])
qc.append(lib.RXXGate(0.5), [0, 1])
qc.append(lib.RZZGate(0.5), [0, 1])
qc.append(lib.RCCXGate(), [0, 1, 2])
qc.append(lib.RC3XGate(), [0, 1, 2, 3])
qc.append(lib.C3XGate(), [0, 1, 2, 3])
qc.append(lib.C3SXGate(), [0, 1, 2, 3])
qc.append(lib.C4XGate(), [0, 1, 2, 3, 4])
self.assertEqual(parsed, qc)
# There's also the 'u0' gate, but this is weird so we don't wildly care what its definition
# is and it has no Qiskit equivalent, so we'll just test that it using it doesn't produce an
# error.
parsed = qiskit.qasm2.loads(
"qreg q[1]; u0(1) q[0];", custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS
)
self.assertEqual(parsed.data[0].operation.name, "u0")
def test_qiskit_override_delay_opaque(self):
program = """
opaque delay(t) q;
qreg q[1];
delay(1) q[0];
"""
parsed = qiskit.qasm2.loads(
program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.delay(1, 0, unit="dt")
self.assertEqual(parsed, qc)
def test_qiskit_override_u0_opaque(self):
program = """
opaque u0(n) q;
qreg q[1];
u0(2) q[0];
"""
parsed = qiskit.qasm2.loads(
program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.id(0)
qc.id(0)
self.assertEqual(parsed.decompose(), qc)
def test_can_override_u(self):
program = """
qreg q[1];
U(0.5, 0.25, 0.125) q[0];
"""
class MyGate(Gate):
def __init__(self, a, b, c):
super().__init__("u", 1, [a, b, c])
parsed = qiskit.qasm2.loads(
program,
custom_instructions=[qiskit.qasm2.CustomInstruction("U", 3, 1, MyGate, builtin=True)],
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(MyGate(0.5, 0.25, 0.125), [0])
self.assertEqual(parsed, qc)
def test_can_override_cx(self):
program = """
qreg q[2];
CX q[0], q[1];
"""
class MyGate(Gate):
def __init__(self):
super().__init__("cx", 2, [])
parsed = qiskit.qasm2.loads(
program,
custom_instructions=[qiskit.qasm2.CustomInstruction("CX", 0, 2, MyGate, builtin=True)],
)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(MyGate(), [0, 1])
self.assertEqual(parsed, qc)
@ddt.data(lambda x: x, reversed)
def test_can_override_both_builtins_with_other_gates(self, order):
program = """
gate unimportant q {}
qreg q[2];
U(0.5, 0.25, 0.125) q[0];
CX q[0], q[1];
"""
class MyUGate(Gate):
def __init__(self, a, b, c):
super().__init__("u", 1, [a, b, c])
class MyCXGate(Gate):
def __init__(self):
super().__init__("cx", 2, [])
custom = [
qiskit.qasm2.CustomInstruction("unused", 0, 1, lambda: Gate("unused", 1, [])),
qiskit.qasm2.CustomInstruction("U", 3, 1, MyUGate, builtin=True),
qiskit.qasm2.CustomInstruction("CX", 0, 2, MyCXGate, builtin=True),
]
custom = order(custom)
parsed = qiskit.qasm2.loads(program, custom_instructions=custom)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(MyUGate(0.5, 0.25, 0.125), [0])
qc.append(MyCXGate(), [0, 1])
self.assertEqual(parsed, qc)
def test_custom_builtin_gate(self):
program = """
qreg q[1];
builtin(0.5) q[0];
"""
class MyGate(Gate):
def __init__(self, a):
super().__init__("builtin", 1, [a])
parsed = qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("builtin", 1, 1, MyGate, builtin=True)
],
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(MyGate(0.5), [0])
self.assertEqual(parsed, qc)
def test_can_define_builtin_as_gate(self):
program = """
qreg q[1];
gate builtin(t) q {}
builtin(0.5) q[0];
"""
class MyGate(Gate):
def __init__(self, a):
super().__init__("builtin", 1, [a])
parsed = qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("builtin", 1, 1, MyGate, builtin=True)
],
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(MyGate(0.5), [0])
self.assertEqual(parsed, qc)
def test_can_define_builtin_as_opaque(self):
program = """
qreg q[1];
opaque builtin(t) q;
builtin(0.5) q[0];
"""
class MyGate(Gate):
def __init__(self, a):
super().__init__("builtin", 1, [a])
parsed = qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("builtin", 1, 1, MyGate, builtin=True)
],
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(MyGate(0.5), [0])
self.assertEqual(parsed, qc)
def test_can_define_custom_as_gate(self):
program = """
qreg q[1];
gate my_gate(t) q {}
my_gate(0.5) q[0];
"""
class MyGate(Gate):
def __init__(self, a):
super().__init__("my_gate", 1, [a])
parsed = qiskit.qasm2.loads(
program, custom_instructions=[qiskit.qasm2.CustomInstruction("my_gate", 1, 1, MyGate)]
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(MyGate(0.5), [0])
self.assertEqual(parsed, qc)
def test_can_define_custom_as_opaque(self):
program = """
qreg q[1];
opaque my_gate(t) q;
my_gate(0.5) q[0];
"""
class MyGate(Gate):
def __init__(self, a):
super().__init__("my_gate", 1, [a])
parsed = qiskit.qasm2.loads(
program, custom_instructions=[qiskit.qasm2.CustomInstruction("my_gate", 1, 1, MyGate)]
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(MyGate(0.5), [0])
self.assertEqual(parsed, qc)
class TestCustomClassical(QiskitTestCase):
def test_qiskit_extensions(self):
program = """
include "qelib1.inc";
qreg q[1];
rx(asin(0.3)) q[0];
ry(acos(0.3)) q[0];
rz(atan(0.3)) q[0];
"""
parsed = qiskit.qasm2.loads(program, custom_classical=qiskit.qasm2.LEGACY_CUSTOM_CLASSICAL)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.rx(math.asin(0.3), 0)
qc.ry(math.acos(0.3), 0)
qc.rz(math.atan(0.3), 0)
self.assertEqual(parsed, qc)
def test_zero_parameter_custom(self):
program = """
qreg q[1];
U(f(), 0, 0) q[0];
"""
parsed = qiskit.qasm2.loads(
program, custom_classical=[qiskit.qasm2.CustomClassical("f", 0, lambda: 0.2)]
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.u(0.2, 0, 0, 0)
self.assertEqual(parsed, qc)
def test_multi_parameter_custom(self):
program = """
qreg q[1];
U(f(0.2), g(0.4, 0.1), h(1, 2, 3)) q[0];
"""
parsed = qiskit.qasm2.loads(
program,
custom_classical=[
qiskit.qasm2.CustomClassical("f", 1, lambda x: 1 + x),
qiskit.qasm2.CustomClassical("g", 2, math.atan2),
qiskit.qasm2.CustomClassical("h", 3, lambda x, y, z: z - y + x),
],
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.u(1.2, math.atan2(0.4, 0.1), 2, 0)
self.assertEqual(parsed, qc)
def test_use_in_gate_definition(self):
# pylint: disable=invalid-name
program = """
gate my_gate(a, b) q {
U(f(a, b), g(f(b, f(b, a))), b) q;
}
qreg q[1];
my_gate(0.5, 0.25) q[0];
my_gate(0.25, 0.5) q[0];
"""
f = lambda x, y: x - y
g = lambda x: 2 * x
parsed = qiskit.qasm2.loads(
program,
custom_classical=[
qiskit.qasm2.CustomClassical("f", 2, f),
qiskit.qasm2.CustomClassical("g", 1, g),
],
)
first_gate = parsed.data[0].operation
second_gate = parsed.data[1].operation
self.assertEqual(list(first_gate.params), [0.5, 0.25])
self.assertEqual(list(second_gate.params), [0.25, 0.5])
self.assertEqual(
list(first_gate.definition.data[0].operation.params),
[
f(0.5, 0.25),
g(f(0.25, f(0.25, 0.5))),
0.25,
],
)
self.assertEqual(
list(second_gate.definition.data[0].operation.params),
[
f(0.25, 0.5),
g(f(0.5, f(0.5, 0.25))),
0.5,
],
)
@ddt.ddt
class TestStrict(QiskitTestCase):
@ddt.data(
"gate my_gate(p0, p1$) q0, q1 {}",
"gate my_gate(p0, p1) q0, q1$ {}",
"opaque my_gate(p0, p1$) q0, q1;",
"opaque my_gate(p0, p1) q0, q1$;",
'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125$) q[0], q[1];',
'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125) q[0], q[1]$;',
"qreg q[2]; barrier q[0], q[1]$;",
'include "qelib1.inc"; qreg q[1]; rx(sin(pi$)) q[0];',
)
def test_trailing_comma(self, program):
without = qiskit.qasm2.loads("OPENQASM 2.0;\n" + program.replace("$", ""), strict=True)
with_ = qiskit.qasm2.loads(program.replace("$", ","), strict=False)
self.assertEqual(with_, without)
def test_trailing_semicolon_after_gate(self):
program = """
include "qelib1.inc";
gate bell a, b {
h a;
cx a, b;
}; // <- the important bit of the test
qreg q[2];
bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
bell_def = QuantumCircuit([Qubit(), Qubit()])
bell_def.h(0)
bell_def.cx(0, 1)
bell = gate_builder("bell", [], bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(bell(), [0, 1])
self.assertEqual(parsed, qc)
def test_empty_statement(self):
# This is allowed more as a side-effect of allowing the trailing semicolon after gate
# definitions.
program = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
h q[0];
;
cx q[0], q[1];
;;;;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.h(0)
qc.cx(0, 1)
self.assertEqual(parsed, qc)
def test_single_quoted_path(self):
program = """
include 'qelib1.inc';
qreg q[1];
h q[0];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.h(0)
self.assertEqual(parsed, qc)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test QASM3 exporter."""
# We can't really help how long the lines output by the exporter are in some cases.
# pylint: disable=line-too-long
from io import StringIO
from math import pi
import re
import unittest
from ddt import ddt, data
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile
from qiskit.circuit import Parameter, Qubit, Clbit, Instruction, Gate, Delay, Barrier
from qiskit.circuit.classical import expr
from qiskit.circuit.controlflow import CASE_DEFAULT
from qiskit.test import QiskitTestCase
from qiskit.qasm3 import Exporter, dumps, dump, QASM3ExporterError, ExperimentalFeatures
from qiskit.qasm3.exporter import QASM3Builder
from qiskit.qasm3.printer import BasicPrinter
# Tests marked with this decorator should be restored after gate definition with parameters is fixed
# properly, and the dummy tests after them should be deleted. See gh-7335.
requires_fixed_parameterisation = unittest.expectedFailure
class TestQASM3Functions(QiskitTestCase):
"""QASM3 module - high level functions"""
def setUp(self):
self.circuit = QuantumCircuit(2)
self.circuit.u(2 * pi, 3 * pi, -5 * pi, 0)
self.expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"qubit[2] q;",
"U(2*pi, 3*pi, -5*pi) q[0];",
"",
]
)
super().setUp()
def test_dumps(self):
"""Test dumps."""
result = dumps(self.circuit)
self.assertEqual(result, self.expected_qasm)
def test_dump(self):
"""Test dump into an IO stream."""
io = StringIO()
dump(self.circuit, io)
result = io.getvalue()
self.assertEqual(result, self.expected_qasm)
@ddt
class TestCircuitQASM3(QiskitTestCase):
"""QASM3 exporter."""
maxDiff = 1_000_000
@classmethod
def setUpClass(cls):
# These regexes are not perfect by any means, but sufficient for simple tests on controlled
# input circuits. They can allow false negatives (in which case, update the regex), but to
# be useful for the tests must _never_ have false positive matches. We use an explicit
# space (`\s`) or semicolon rather than the end-of-word `\b` because we want to ensure that
# the exporter isn't putting out invalid characters as part of the identifiers.
cls.register_regex = re.compile(
r"^\s*(let|(qu)?bit(\[\d+\])?)\s+(?P<name>\w+)[\s;]", re.U | re.M
)
scalar_type_names = {
"angle",
"duration",
"float",
"int",
"stretch",
"uint",
}
cls.scalar_parameter_regex = re.compile(
r"^\s*((input|output|const)\s+)?" # Modifier
rf"({'|'.join(scalar_type_names)})\s*(\[[^\]]+\])?\s+" # Type name and designator
r"(?P<name>\w+)[\s;]", # Parameter name
re.U | re.M,
)
super().setUpClass()
def test_regs_conds_qasm(self):
"""Test with registers and conditionals."""
qr1 = QuantumRegister(1, "qr1")
qr2 = QuantumRegister(2, "qr2")
cr = ClassicalRegister(3, "cr")
qc = QuantumCircuit(qr1, qr2, cr)
qc.measure(qr1[0], cr[0])
qc.measure(qr2[0], cr[1])
qc.measure(qr2[1], cr[2])
qc.x(qr2[1]).c_if(cr, 0)
qc.y(qr1[0]).c_if(cr, 1)
qc.z(qr1[0]).c_if(cr, 2)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[3] cr;",
"qubit[1] qr1;",
"qubit[2] qr2;",
"cr[0] = measure qr1[0];",
"cr[1] = measure qr2[0];",
"cr[2] = measure qr2[1];",
"if (cr == 0) {",
" x qr2[1];",
"}",
"if (cr == 1) {",
" y qr1[0];",
"}",
"if (cr == 2) {",
" z qr1[0];",
"}",
"",
]
)
self.assertEqual(Exporter().dumps(qc), expected_qasm)
def test_registers_as_aliases(self):
"""Test that different types of alias creation and concatenation work."""
qubits = [Qubit() for _ in [None] * 10]
first_four = QuantumRegister(name="first_four", bits=qubits[:4])
last_five = QuantumRegister(name="last_five", bits=qubits[5:])
alternate = QuantumRegister(name="alternate", bits=qubits[::2])
sporadic = QuantumRegister(name="sporadic", bits=[qubits[4], qubits[2], qubits[9]])
qc = QuantumCircuit(qubits, first_four, last_five, alternate, sporadic)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"qubit _qubit0;",
"qubit _qubit1;",
"qubit _qubit2;",
"qubit _qubit3;",
"qubit _qubit4;",
"qubit _qubit5;",
"qubit _qubit6;",
"qubit _qubit7;",
"qubit _qubit8;",
"qubit _qubit9;",
"let first_four = {_qubit0, _qubit1, _qubit2, _qubit3};",
"let last_five = {_qubit5, _qubit6, _qubit7, _qubit8, _qubit9};",
"let alternate = {first_four[0], first_four[2], _qubit4, last_five[1], last_five[3]};",
"let sporadic = {alternate[2], alternate[1], last_five[4]};",
"",
]
)
self.assertEqual(Exporter(allow_aliasing=True).dumps(qc), expected_qasm)
def test_composite_circuit(self):
"""Test with a composite circuit instruction and barriers"""
composite_circ_qreg = QuantumRegister(2)
composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ")
composite_circ.h(0)
composite_circ.x(1)
composite_circ.cx(0, 1)
composite_circ_instr = composite_circ.to_gate()
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.cx(0, 1)
qc.barrier()
qc.append(composite_circ_instr, [0, 1])
qc.measure([0, 1], [0, 1])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate composite_circ _gate_q_0, _gate_q_1 {",
" h _gate_q_0;",
" x _gate_q_1;",
" cx _gate_q_0, _gate_q_1;",
"}",
"bit[2] cr;",
"qubit[2] qr;",
"h qr[0];",
"cx qr[0], qr[1];",
"barrier qr[0], qr[1];",
"composite_circ qr[0], qr[1];",
"cr[0] = measure qr[0];",
"cr[1] = measure qr[1];",
"",
]
)
self.assertEqual(Exporter().dumps(qc), expected_qasm)
def test_custom_gate(self):
"""Test custom gates (via to_gate)."""
composite_circ_qreg = QuantumRegister(2)
composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ")
composite_circ.h(0)
composite_circ.x(1)
composite_circ.cx(0, 1)
composite_circ_instr = composite_circ.to_gate()
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.cx(0, 1)
qc.barrier()
qc.append(composite_circ_instr, [0, 1])
qc.measure([0, 1], [0, 1])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate composite_circ _gate_q_0, _gate_q_1 {",
" h _gate_q_0;",
" x _gate_q_1;",
" cx _gate_q_0, _gate_q_1;",
"}",
"bit[2] cr;",
"qubit[2] qr;",
"h qr[0];",
"cx qr[0], qr[1];",
"barrier qr[0], qr[1];",
"composite_circ qr[0], qr[1];",
"cr[0] = measure qr[0];",
"cr[1] = measure qr[1];",
"",
]
)
self.assertEqual(Exporter().dumps(qc), expected_qasm)
def test_same_composite_circuits(self):
"""Test when a composite circuit is added to the circuit multiple times."""
composite_circ_qreg = QuantumRegister(2)
composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ")
composite_circ.h(0)
composite_circ.x(1)
composite_circ.cx(0, 1)
composite_circ_instr = composite_circ.to_gate()
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.cx(0, 1)
qc.barrier()
qc.append(composite_circ_instr, [0, 1])
qc.append(composite_circ_instr, [0, 1])
qc.measure([0, 1], [0, 1])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate composite_circ _gate_q_0, _gate_q_1 {",
" h _gate_q_0;",
" x _gate_q_1;",
" cx _gate_q_0, _gate_q_1;",
"}",
"bit[2] cr;",
"qubit[2] qr;",
"h qr[0];",
"cx qr[0], qr[1];",
"barrier qr[0], qr[1];",
"composite_circ qr[0], qr[1];",
"composite_circ qr[0], qr[1];",
"cr[0] = measure qr[0];",
"cr[1] = measure qr[1];",
"",
]
)
self.assertEqual(Exporter().dumps(qc), expected_qasm)
def test_composite_circuits_with_same_name(self):
"""Test when multiple composite circuit instructions same name and different
implementation."""
my_gate = QuantumCircuit(1, name="my_gate")
my_gate.h(0)
my_gate_inst1 = my_gate.to_gate()
my_gate = QuantumCircuit(1, name="my_gate")
my_gate.x(0)
my_gate_inst2 = my_gate.to_gate()
my_gate = QuantumCircuit(1, name="my_gate")
my_gate.x(0)
my_gate_inst3 = my_gate.to_gate()
qr = QuantumRegister(1, name="qr")
circuit = QuantumCircuit(qr, name="circuit")
circuit.append(my_gate_inst1, [qr[0]])
circuit.append(my_gate_inst2, [qr[0]])
my_gate_inst2_id = id(circuit.data[-1].operation)
circuit.append(my_gate_inst3, [qr[0]])
my_gate_inst3_id = id(circuit.data[-1].operation)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate my_gate _gate_q_0 {",
" h _gate_q_0;",
"}",
f"gate my_gate_{my_gate_inst2_id} _gate_q_0 {{",
" x _gate_q_0;",
"}",
f"gate my_gate_{my_gate_inst3_id} _gate_q_0 {{",
" x _gate_q_0;",
"}",
"qubit[1] qr;",
"my_gate qr[0];",
f"my_gate_{my_gate_inst2_id} qr[0];",
f"my_gate_{my_gate_inst3_id} qr[0];",
"",
]
)
self.assertEqual(Exporter().dumps(circuit), expected_qasm)
def test_pi_disable_constants_false(self):
"""Test pi constant (disable_constants=False)"""
circuit = QuantumCircuit(2)
circuit.u(2 * pi, 3 * pi, -5 * pi, 0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"qubit[2] q;",
"U(2*pi, 3*pi, -5*pi) q[0];",
"",
]
)
self.assertEqual(Exporter(disable_constants=False).dumps(circuit), expected_qasm)
def test_pi_disable_constants_true(self):
"""Test pi constant (disable_constants=True)"""
circuit = QuantumCircuit(2)
circuit.u(2 * pi, 3 * pi, -5 * pi, 0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"qubit[2] q;",
"U(6.283185307179586, 9.42477796076938, -15.707963267948966) q[0];",
"",
]
)
self.assertEqual(Exporter(disable_constants=True).dumps(circuit), expected_qasm)
def test_custom_gate_with_unbound_parameter(self):
"""Test custom gate with unbound parameter."""
parameter_a = Parameter("a")
custom = QuantumCircuit(1, name="custom")
custom.rx(parameter_a, 0)
circuit = QuantumCircuit(1)
circuit.append(custom.to_gate(), [0])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"input float[64] a;",
"gate custom(a) _gate_q_0 {",
" rx(a) _gate_q_0;",
"}",
"qubit[1] q;",
"custom(a) q[0];",
"",
]
)
self.assertEqual(Exporter().dumps(circuit), expected_qasm)
def test_custom_gate_with_bound_parameter(self):
"""Test custom gate with bound parameter."""
parameter_a = Parameter("a")
custom = QuantumCircuit(1)
custom.rx(parameter_a, 0)
custom_gate = custom.bind_parameters({parameter_a: 0.5}).to_gate()
custom_gate.name = "custom"
circuit = QuantumCircuit(1)
circuit.append(custom_gate, [0])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate custom _gate_q_0 {",
" rx(0.5) _gate_q_0;",
"}",
"qubit[1] q;",
"custom q[0];",
"",
]
)
self.assertEqual(Exporter().dumps(circuit), expected_qasm)
@requires_fixed_parameterisation
def test_custom_gate_with_params_bound_main_call(self):
"""Custom gate with unbound parameters that are bound in the main circuit"""
parameter0 = Parameter("p0")
parameter1 = Parameter("p1")
custom = QuantumCircuit(2, name="custom")
custom.rz(parameter0, 0)
custom.rz(parameter1 / 2, 1)
qr_all_qubits = QuantumRegister(3, "q")
qr_r = QuantumRegister(3, "r")
circuit = QuantumCircuit(qr_all_qubits, qr_r)
circuit.append(custom.to_gate(), [qr_all_qubits[0], qr_r[0]])
circuit.assign_parameters({parameter0: pi, parameter1: pi / 2}, inplace=True)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate custom(_gate_p_0, _gate_p_0) _gate_q_0, _gate_q_1 {",
" rz(pi) _gate_q_0;",
" rz(pi/4) _gate_q_1;",
"}",
"qubit[3] q;",
"qubit[3] r;",
"custom(pi, pi/2) q[0], r[0];",
"",
]
)
self.assertEqual(Exporter().dumps(circuit), expected_qasm)
def test_reused_custom_parameter(self):
"""Test reused custom gate with parameter."""
parameter_a = Parameter("a")
custom = QuantumCircuit(1)
custom.rx(parameter_a, 0)
circuit = QuantumCircuit(1)
circuit.append(custom.bind_parameters({parameter_a: 0.5}).to_gate(), [0])
circuit.append(custom.bind_parameters({parameter_a: 1}).to_gate(), [0])
circuit_name_0 = circuit.data[0].operation.definition.name
circuit_name_1 = circuit.data[1].operation.definition.name
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
f"gate {circuit_name_0} _gate_q_0 {{",
" rx(0.5) _gate_q_0;",
"}",
f"gate {circuit_name_1} _gate_q_0 {{",
" rx(1.0) _gate_q_0;",
"}",
"qubit[1] q;",
f"{circuit_name_0} q[0];",
f"{circuit_name_1} q[0];",
"",
]
)
self.assertEqual(Exporter().dumps(circuit), expected_qasm)
def test_unbound_circuit(self):
"""Test with unbound parameters (turning them into inputs)."""
qc = QuantumCircuit(1)
theta = Parameter("ΞΈ")
qc.rz(theta, 0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"input float[64] ΞΈ;",
"qubit[1] q;",
"rz(ΞΈ) q[0];",
"",
]
)
self.assertEqual(Exporter().dumps(qc), expected_qasm)
def test_unknown_parameterized_gate_called_multiple_times(self):
"""Test that a parameterised gate is called correctly if the first instance of it is
generic."""
x, y = Parameter("x"), Parameter("y")
qc = QuantumCircuit(2)
qc.rzx(x, 0, 1)
qc.rzx(y, 0, 1)
qc.rzx(0.5, 0, 1)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
"input float[64] x;",
"input float[64] y;",
"gate rzx(x) _gate_q_0, _gate_q_1 {",
" h _gate_q_1;",
" cx _gate_q_0, _gate_q_1;",
" rz(x) _gate_q_1;",
" cx _gate_q_0, _gate_q_1;",
" h _gate_q_1;",
"}",
"qubit[2] q;",
"rzx(x) q[0], q[1];",
"rzx(y) q[0], q[1];",
"rzx(0.5) q[0], q[1];",
"",
]
)
# Set the includes and basis gates to ensure that this gate is unknown.
exporter = Exporter(includes=[], basis_gates=("rz", "h", "cx"))
self.assertEqual(exporter.dumps(qc), expected_qasm)
def test_gate_qasm_with_ctrl_state(self):
"""Test with open controlled gate that has ctrl_state"""
qc = QuantumCircuit(2)
qc.ch(0, 1, ctrl_state=0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate ch_o0 _gate_q_0, _gate_q_1 {",
" x _gate_q_0;",
" ch _gate_q_0, _gate_q_1;",
" x _gate_q_0;",
"}",
"qubit[2] q;",
"ch_o0 q[0], q[1];",
"",
]
)
self.assertEqual(Exporter().dumps(qc), expected_qasm)
def test_custom_gate_collision_with_stdlib(self):
"""Test a custom gate with name collision with the standard library."""
custom = QuantumCircuit(2, name="cx")
custom.cx(0, 1)
custom_gate = custom.to_gate()
qc = QuantumCircuit(2)
qc.append(custom_gate, [0, 1])
custom_gate_id = id(qc.data[-1].operation)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
f"gate cx_{custom_gate_id} _gate_q_0, _gate_q_1 {{",
" cx _gate_q_0, _gate_q_1;",
"}",
"qubit[2] q;",
f"cx_{custom_gate_id} q[0], q[1];",
"",
]
)
self.assertEqual(Exporter().dumps(qc), expected_qasm)
@requires_fixed_parameterisation
def test_no_include(self):
"""Test explicit gate declaration (no include)"""
q = QuantumRegister(2, "q")
circuit = QuantumCircuit(q)
circuit.rz(pi / 2, 0)
circuit.sx(0)
circuit.cx(0, 1)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
"gate u3(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {",
" U(0, 0, pi/2) _gate_q_0;",
"}",
"gate u1(_gate_p_0) _gate_q_0 {",
" u3(0, 0, pi/2) _gate_q_0;",
"}",
"gate rz(_gate_p_0) _gate_q_0 {",
" u1(pi/2) _gate_q_0;",
"}",
"gate sdg _gate_q_0 {",
" u1(-pi/2) _gate_q_0;",
"}",
"gate u2(_gate_p_0, _gate_p_1) _gate_q_0 {",
" u3(pi/2, 0, pi) _gate_q_0;",
"}",
"gate h _gate_q_0 {",
" u2(0, pi) _gate_q_0;",
"}",
"gate sx _gate_q_0 {",
" sdg _gate_q_0;",
" h _gate_q_0;",
" sdg _gate_q_0;",
"}",
"gate cx c, t {",
" ctrl @ U(pi, 0, pi) c, t;",
"}",
"qubit[2] q;",
"rz(pi/2) q[0];",
"sx q[0];",
"cx q[0], q[1];",
"",
]
)
self.assertEqual(Exporter(includes=[]).dumps(circuit), expected_qasm)
@requires_fixed_parameterisation
def test_teleportation(self):
"""Teleportation with physical qubits"""
qc = QuantumCircuit(3, 2)
qc.h(1)
qc.cx(1, 2)
qc.barrier()
qc.cx(0, 1)
qc.h(0)
qc.barrier()
qc.measure([0, 1], [0, 1])
qc.barrier()
qc.x(2).c_if(qc.clbits[1], 1)
qc.z(2).c_if(qc.clbits[0], 1)
transpiled = transpile(qc, initial_layout=[0, 1, 2])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
"gate u3(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {",
" U(pi/2, 0, pi) _gate_q_0;",
"}",
"gate u2(_gate_p_0, _gate_p_1) _gate_q_0 {",
" u3(pi/2, 0, pi) _gate_q_0;",
"}",
"gate h _gate_q_0 {",
" u2(0, pi) _gate_q_0;",
"}",
"gate cx c, t {",
" ctrl @ U(pi, 0, pi) c, t;",
"}",
"gate x _gate_q_0 {",
" u3(pi, 0, pi) _gate_q_0;",
"}",
"gate u1(_gate_p_0) _gate_q_0 {",
" u3(0, 0, pi) _gate_q_0;",
"}",
"gate z _gate_q_0 {",
" u1(pi) _gate_q_0;",
"}",
"bit[2] c;",
"h $1;",
"cx $1, $2;",
"barrier $0, $1, $2;",
"cx $0, $1;",
"h $0;",
"barrier $0, $1, $2;",
"c[0] = measure $0;",
"c[1] = measure $1;",
"barrier $0, $1, $2;",
"if (c[1]) {",
" x $2;",
"}",
"if (c[0]) {",
" z $2;",
"}",
"",
]
)
self.assertEqual(Exporter(includes=[]).dumps(transpiled), expected_qasm)
@requires_fixed_parameterisation
def test_basis_gates(self):
"""Teleportation with physical qubits"""
qc = QuantumCircuit(3, 2)
qc.h(1)
qc.cx(1, 2)
qc.barrier()
qc.cx(0, 1)
qc.h(0)
qc.barrier()
qc.measure([0, 1], [0, 1])
qc.barrier()
qc.x(2).c_if(qc.clbits[1], 1)
qc.z(2).c_if(qc.clbits[0], 1)
transpiled = transpile(qc, initial_layout=[0, 1, 2])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
"gate u3(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {",
" U(pi/2, 0, pi) _gate_q_0;",
"}",
"gate u2(_gate_p_0, _gate_p_1) _gate_q_0 {",
" u3(pi/2, 0, pi) _gate_q_0;",
"}",
"gate h _gate_q_0 {",
" u2(0, pi) _gate_q_0;",
"}",
"gate x _gate_q_0 {",
" u3(pi, 0, pi) _gate_q_0;",
"}",
"bit[2] c;",
"h $1;",
"cx $1, $2;",
"barrier $0, $1, $2;",
"cx $0, $1;",
"h $0;",
"barrier $0, $1, $2;",
"c[0] = measure $0;",
"c[1] = measure $1;",
"barrier $0, $1, $2;",
"if (c[1]) {",
" x $2;",
"}",
"if (c[0]) {",
" z $2;",
"}",
"",
]
)
self.assertEqual(
Exporter(includes=[], basis_gates=["cx", "z", "U"]).dumps(transpiled),
expected_qasm,
)
def test_opaque_instruction_in_basis_gates(self):
"""Test that an instruction that is set in the basis gates is output verbatim with no
definition."""
qc = QuantumCircuit(1)
qc.x(0)
qc.append(Gate("my_gate", 1, []), [0], [])
basis_gates = ["my_gate", "x"]
transpiled = transpile(qc, initial_layout=[0])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
"x $0;",
"my_gate $0;",
"",
]
)
self.assertEqual(
Exporter(includes=[], basis_gates=basis_gates).dumps(transpiled), expected_qasm
)
def test_reset_statement(self):
"""Test that a reset statement gets output into valid QASM 3. This includes tests of reset
operations on single qubits and in nested scopes."""
qreg = QuantumRegister(2, "qr")
qc = QuantumCircuit(qreg)
qc.reset(0)
qc.reset([0, 1])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
"qubit[2] qr;",
"reset qr[0];",
"reset qr[0];",
"reset qr[1];",
"",
]
)
self.assertEqual(Exporter(includes=[]).dumps(qc), expected_qasm)
def test_delay_statement(self):
"""Test that delay operations get output into valid QASM 3."""
qreg = QuantumRegister(2, "qr")
qc = QuantumCircuit(qreg)
qc.delay(100, qreg[0], unit="ms")
qc.delay(2, qreg[1], unit="ps") # "ps" is not a valid unit in OQ3, so we need to convert.
expected_qasm = "\n".join(
[
"OPENQASM 3;",
"qubit[2] qr;",
"delay[100ms] qr[0];",
"delay[2000ns] qr[1];",
"",
]
)
self.assertEqual(Exporter(includes=[]).dumps(qc), expected_qasm)
def test_loose_qubits(self):
"""Test that qubits that are not in any register can be used without issue."""
bits = [Qubit(), Qubit()]
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(bits, qr, cr)
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit _qubit0;",
"qubit _qubit1;",
"qubit[2] qr;",
"h _qubit0;",
"h _qubit1;",
"h qr[0];",
"h qr[1];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_loose_clbits(self):
"""Test that clbits that are not in any register can be used without issue."""
qreg = QuantumRegister(1, name="qr")
bits = [Clbit() for _ in [None] * 7]
cr1 = ClassicalRegister(name="cr1", bits=bits[1:3])
cr2 = ClassicalRegister(name="cr2", bits=bits[4:6])
qc = QuantumCircuit(bits, qreg, cr1, cr2)
qc.measure(0, 0)
qc.measure(0, 1)
qc.measure(0, 2)
qc.measure(0, 3)
qc.measure(0, 4)
qc.measure(0, 5)
qc.measure(0, 6)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit _bit0;",
"bit _bit3;",
"bit _bit6;",
"bit[2] cr1;",
"bit[2] cr2;",
"qubit[1] qr;",
"_bit0 = measure qr[0];",
"cr1[0] = measure qr[0];",
"cr1[1] = measure qr[0];",
"_bit3 = measure qr[0];",
"cr2[0] = measure qr[0];",
"cr2[1] = measure qr[0];",
"_bit6 = measure qr[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_classical_register_aliasing(self):
"""Test that clbits that are not in any register can be used without issue."""
qreg = QuantumRegister(1, name="qr")
bits = [Clbit() for _ in [None] * 7]
cr1 = ClassicalRegister(name="cr1", bits=bits[1:3])
cr2 = ClassicalRegister(name="cr2", bits=bits[4:6])
# cr3 overlaps cr2, but this should be allowed in this alias form.
cr3 = ClassicalRegister(name="cr3", bits=bits[5:])
qc = QuantumCircuit(bits, qreg, cr1, cr2, cr3)
qc.measure(0, 0)
qc.measure(0, 1)
qc.measure(0, 2)
qc.measure(0, 3)
qc.measure(0, 4)
qc.measure(0, 5)
qc.measure(0, 6)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit _bit0;",
"bit _bit1;",
"bit _bit2;",
"bit _bit3;",
"bit _bit4;",
"bit _bit5;",
"bit _bit6;",
"let cr1 = {_bit1, _bit2};",
"let cr2 = {_bit4, _bit5};",
"let cr3 = {cr2[1], _bit6};",
"qubit[1] qr;",
"_bit0 = measure qr[0];",
"cr1[0] = measure qr[0];",
"cr1[1] = measure qr[0];",
"_bit3 = measure qr[0];",
"cr2[0] = measure qr[0];",
"cr3[0] = measure qr[0];",
"cr3[1] = measure qr[0];",
"",
]
)
self.assertEqual(dumps(qc, allow_aliasing=True), expected_qasm)
def test_old_alias_classical_registers_option(self):
"""Test that the ``alias_classical_registers`` option still functions during its changeover
period."""
qreg = QuantumRegister(1, name="qr")
bits = [Clbit() for _ in [None] * 7]
cr1 = ClassicalRegister(name="cr1", bits=bits[1:3])
cr2 = ClassicalRegister(name="cr2", bits=bits[4:6])
# cr3 overlaps cr2, but this should be allowed in this alias form.
cr3 = ClassicalRegister(name="cr3", bits=bits[5:])
qc = QuantumCircuit(bits, qreg, cr1, cr2, cr3)
qc.measure(0, 0)
qc.measure(0, 1)
qc.measure(0, 2)
qc.measure(0, 3)
qc.measure(0, 4)
qc.measure(0, 5)
qc.measure(0, 6)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit _bit0;",
"bit _bit1;",
"bit _bit2;",
"bit _bit3;",
"bit _bit4;",
"bit _bit5;",
"bit _bit6;",
"let cr1 = {_bit1, _bit2};",
"let cr2 = {_bit4, _bit5};",
"let cr3 = {cr2[1], _bit6};",
"qubit[1] qr;",
"_bit0 = measure qr[0];",
"cr1[0] = measure qr[0];",
"cr1[1] = measure qr[0];",
"_bit3 = measure qr[0];",
"cr2[0] = measure qr[0];",
"cr3[0] = measure qr[0];",
"cr3[1] = measure qr[0];",
"",
]
)
self.assertEqual(dumps(qc, alias_classical_registers=True), expected_qasm)
def test_simple_for_loop(self):
"""Test that a simple for loop outputs the expected result."""
parameter = Parameter("x")
loop_body = QuantumCircuit(1)
loop_body.rx(parameter, 0)
loop_body.break_loop()
loop_body.continue_loop()
qc = QuantumCircuit(2)
qc.for_loop([0, 3, 4], parameter, loop_body, [1], [])
qc.x(0)
qr_name = qc.qregs[0].name
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
f"qubit[2] {qr_name};",
f"for {parameter.name} in {{0, 3, 4}} {{",
f" rx({parameter.name}) {qr_name}[1];",
" break;",
" continue;",
"}",
f"x {qr_name}[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_nested_for_loop(self):
"""Test that a for loop nested inside another outputs the expected result."""
inner_parameter = Parameter("x")
outer_parameter = Parameter("y")
inner_body = QuantumCircuit(2)
inner_body.rz(inner_parameter, 0)
inner_body.rz(outer_parameter, 1)
inner_body.break_loop()
outer_body = QuantumCircuit(2)
outer_body.h(0)
outer_body.rz(outer_parameter, 1)
# Note we reverse the order of the bits here to test that this is traced.
outer_body.for_loop(range(1, 5, 2), inner_parameter, inner_body, [1, 0], [])
outer_body.continue_loop()
qc = QuantumCircuit(2)
qc.for_loop(range(4), outer_parameter, outer_body, [0, 1], [])
qc.x(0)
qr_name = qc.qregs[0].name
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
f"qubit[2] {qr_name};",
f"for {outer_parameter.name} in [0:3] {{",
f" h {qr_name}[0];",
f" rz({outer_parameter.name}) {qr_name}[1];",
f" for {inner_parameter.name} in [1:2:4] {{",
# Note the reversed bit order.
f" rz({inner_parameter.name}) {qr_name}[1];",
f" rz({outer_parameter.name}) {qr_name}[0];",
" break;",
" }",
" continue;",
"}",
f"x {qr_name}[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_regular_parameter_in_nested_for_loop(self):
"""Test that a for loop nested inside another outputs the expected result, including
defining parameters that are used in nested loop scopes."""
inner_parameter = Parameter("x")
outer_parameter = Parameter("y")
regular_parameter = Parameter("t")
inner_body = QuantumCircuit(2)
inner_body.h(0)
inner_body.rx(regular_parameter, 1)
inner_body.break_loop()
outer_body = QuantumCircuit(2)
outer_body.h(0)
outer_body.h(1)
# Note we reverse the order of the bits here to test that this is traced.
outer_body.for_loop(range(1, 5, 2), inner_parameter, inner_body, [1, 0], [])
outer_body.continue_loop()
qc = QuantumCircuit(2)
qc.for_loop(range(4), outer_parameter, outer_body, [0, 1], [])
qc.x(0)
qr_name = qc.qregs[0].name
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
# This next line will be missing until gh-7280 is fixed.
f"input float[64] {regular_parameter.name};",
f"qubit[2] {qr_name};",
f"for {outer_parameter.name} in [0:3] {{",
f" h {qr_name}[0];",
f" h {qr_name}[1];",
f" for {inner_parameter.name} in [1:2:4] {{",
# Note the reversed bit order.
f" h {qr_name}[1];",
f" rx({regular_parameter.name}) {qr_name}[0];",
" break;",
" }",
" continue;",
"}",
f"x {qr_name}[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_for_loop_with_no_parameter(self):
"""Test that a for loop with the parameter set to ``None`` outputs the expected result."""
loop_body = QuantumCircuit(1)
loop_body.h(0)
qc = QuantumCircuit(2)
qc.for_loop([0, 3, 4], None, loop_body, [1], [])
qr_name = qc.qregs[0].name
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
f"qubit[2] {qr_name};",
"for _ in {0, 3, 4} {",
f" h {qr_name}[1];",
"}",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_simple_while_loop(self):
"""Test that a simple while loop works correctly."""
loop_body = QuantumCircuit(1)
loop_body.h(0)
loop_body.break_loop()
loop_body.continue_loop()
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(qr, cr)
qc.while_loop((cr, 0), loop_body, [1], [])
qc.x(0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit[2] qr;",
"while (cr == 0) {",
" h qr[1];",
" break;",
" continue;",
"}",
"x qr[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_nested_while_loop(self):
"""Test that a while loop nested inside another outputs the expected result."""
inner_body = QuantumCircuit(2, 2)
inner_body.measure(0, 0)
inner_body.measure(1, 1)
inner_body.break_loop()
outer_body = QuantumCircuit(2, 2)
outer_body.measure(0, 0)
outer_body.measure(1, 1)
# We reverse the order of the bits here to test this works, and test a single-bit condition.
outer_body.while_loop((outer_body.clbits[0], 0), inner_body, [1, 0], [1, 0])
outer_body.continue_loop()
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(qr, cr)
qc.while_loop((cr, 0), outer_body, [0, 1], [0, 1])
qc.x(0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit[2] qr;",
"while (cr == 0) {",
" cr[0] = measure qr[0];",
" cr[1] = measure qr[1];",
# Note the reversed bits in the body.
" while (!cr[0]) {",
" cr[1] = measure qr[1];",
" cr[0] = measure qr[0];",
" break;",
" }",
" continue;",
"}",
"x qr[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_simple_if_statement(self):
"""Test that a simple if statement with no else works correctly."""
true_body = QuantumCircuit(1)
true_body.h(0)
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(qr, cr)
qc.if_test((cr, 0), true_body, [1], [])
qc.x(0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit[2] qr;",
"if (cr == 0) {",
" h qr[1];",
"}",
"x qr[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_simple_if_else_statement(self):
"""Test that a simple if statement with an else branch works correctly."""
true_body = QuantumCircuit(1)
true_body.h(0)
false_body = QuantumCircuit(1)
false_body.z(0)
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(qr, cr)
qc.if_else((cr, 0), true_body, false_body, [1], [])
qc.x(0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit[2] qr;",
"if (cr == 0) {",
" h qr[1];",
"} else {",
" z qr[1];",
"}",
"x qr[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_nested_if_else_statement(self):
"""Test that a nested if/else statement works correctly."""
inner_true_body = QuantumCircuit(2, 2)
inner_true_body.measure(0, 0)
inner_false_body = QuantumCircuit(2, 2)
inner_false_body.measure(1, 1)
outer_true_body = QuantumCircuit(2, 2)
outer_true_body.if_else(
(outer_true_body.clbits[0], 0), inner_true_body, inner_false_body, [0, 1], [0, 1]
)
outer_false_body = QuantumCircuit(2, 2)
# Note the flipped bits here.
outer_false_body.if_else(
(outer_false_body.clbits[0], 1), inner_true_body, inner_false_body, [1, 0], [1, 0]
)
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(qr, cr)
qc.if_else((cr, 0), outer_true_body, outer_false_body, [0, 1], [0, 1])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit[2] qr;",
"if (cr == 0) {",
" if (!cr[0]) {",
" cr[0] = measure qr[0];",
" } else {",
" cr[1] = measure qr[1];",
" }",
"} else {",
" if (cr[0]) {",
" cr[1] = measure qr[1];",
" } else {",
" cr[0] = measure qr[0];",
" }",
"}",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_chain_else_if(self):
"""Test the basic 'else/if' chaining logic for flattening the else scope if its content is a
single if/else statement."""
inner_true_body = QuantumCircuit(2, 2)
inner_true_body.measure(0, 0)
inner_false_body = QuantumCircuit(2, 2)
inner_false_body.measure(1, 1)
outer_true_body = QuantumCircuit(2, 2)
outer_true_body.if_else(
(outer_true_body.clbits[0], 0), inner_true_body, inner_false_body, [0, 1], [0, 1]
)
outer_false_body = QuantumCircuit(2, 2)
# Note the flipped bits here.
outer_false_body.if_else(
(outer_false_body.clbits[0], 1), inner_true_body, inner_false_body, [1, 0], [1, 0]
)
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(qr, cr)
qc.if_else((cr, 0), outer_true_body, outer_false_body, [0, 1], [0, 1])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit[2] qr;",
"if (cr == 0) {",
" if (!cr[0]) {",
" cr[0] = measure qr[0];",
" } else {",
" cr[1] = measure qr[1];",
" }",
"} else if (cr[0]) {",
" cr[1] = measure qr[1];",
"} else {",
" cr[0] = measure qr[0];",
"}",
"",
]
)
# This is not the default behaviour, and it's pretty buried how you'd access it.
builder = QASM3Builder(
qc,
includeslist=("stdgates.inc",),
basis_gates=("U",),
disable_constants=False,
allow_aliasing=False,
)
stream = StringIO()
BasicPrinter(stream, indent=" ", chain_else_if=True).visit(builder.build_program())
self.assertEqual(stream.getvalue(), expected_qasm)
def test_chain_else_if_does_not_chain_if_extra_instructions(self):
"""Test the basic 'else/if' chaining logic for flattening the else scope if its content is a
single if/else statement does not cause a flattening if the 'else' block is not a single
if/else."""
inner_true_body = QuantumCircuit(2, 2)
inner_true_body.measure(0, 0)
inner_false_body = QuantumCircuit(2, 2)
inner_false_body.measure(1, 1)
outer_true_body = QuantumCircuit(2, 2)
outer_true_body.if_else(
(outer_true_body.clbits[0], 0), inner_true_body, inner_false_body, [0, 1], [0, 1]
)
outer_false_body = QuantumCircuit(2, 2)
# Note the flipped bits here.
outer_false_body.if_else(
(outer_false_body.clbits[0], 1), inner_true_body, inner_false_body, [1, 0], [1, 0]
)
outer_false_body.h(0)
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(qr, cr)
qc.if_else((cr, 0), outer_true_body, outer_false_body, [0, 1], [0, 1])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit[2] qr;",
"if (cr == 0) {",
" if (!cr[0]) {",
" cr[0] = measure qr[0];",
" } else {",
" cr[1] = measure qr[1];",
" }",
"} else {",
" if (cr[0]) {",
" cr[1] = measure qr[1];",
" } else {",
" cr[0] = measure qr[0];",
" }",
" h qr[0];",
"}",
"",
]
)
# This is not the default behaviour, and it's pretty buried how you'd access it.
builder = QASM3Builder(
qc,
includeslist=("stdgates.inc",),
basis_gates=("U",),
disable_constants=False,
allow_aliasing=False,
)
stream = StringIO()
BasicPrinter(stream, indent=" ", chain_else_if=True).visit(builder.build_program())
self.assertEqual(stream.getvalue(), expected_qasm)
def test_custom_gate_used_in_loop_scope(self):
"""Test that a custom gate only used within a loop scope still gets a definition at the top
level."""
parameter_a = Parameter("a")
parameter_b = Parameter("b")
custom = QuantumCircuit(1)
custom.rx(parameter_a, 0)
custom_gate = custom.bind_parameters({parameter_a: 0.5}).to_gate()
custom_gate.name = "custom"
loop_body = QuantumCircuit(1)
loop_body.append(custom_gate, [0])
qc = QuantumCircuit(1)
qc.for_loop(range(2), parameter_b, loop_body, [0], [])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate custom _gate_q_0 {",
" rx(0.5) _gate_q_0;",
"}",
"qubit[1] q;",
"for b in [0:1] {",
" custom q[0];",
"}",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_registers_have_escaped_names(self):
"""Test that both types of register are emitted with safely escaped names if they begin with
invalid names. Regression test of gh-9658."""
qc = QuantumCircuit(
QuantumRegister(2, name="q_{reg}"), ClassicalRegister(2, name="c_{reg}")
)
qc.measure([0, 1], [0, 1])
out_qasm = dumps(qc)
matches = {match_["name"] for match_ in self.register_regex.finditer(out_qasm)}
self.assertEqual(len(matches), 2, msg=f"Observed OQ3 output:\n{out_qasm}")
def test_parameters_have_escaped_names(self):
"""Test that parameters are emitted with safely escaped names if they begin with invalid
names. Regression test of gh-9658."""
qc = QuantumCircuit(1)
qc.u(Parameter("p_{0}"), 2 * Parameter("p_?0!"), 0, 0)
out_qasm = dumps(qc)
matches = {match_["name"] for match_ in self.scalar_parameter_regex.finditer(out_qasm)}
self.assertEqual(len(matches), 2, msg=f"Observed OQ3 output:\n{out_qasm}")
def test_parameter_expression_after_naming_escape(self):
"""Test that :class:`.Parameter` instances are correctly renamed when they are used with
:class:`.ParameterExpression` blocks, even if they have names that needed to be escaped."""
param = Parameter("measure") # an invalid name
qc = QuantumCircuit(1)
qc.u(2 * param, 0, 0, 0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"input float[64] _measure;",
"qubit[1] q;",
"U(2*_measure, 0, 0) q[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_parameters_and_registers_cannot_have_naming_clashes(self):
"""Test that parameters and registers are considered part of the same symbol table for the
purposes of avoiding clashes."""
qreg = QuantumRegister(1, "clash")
param = Parameter("clash")
qc = QuantumCircuit(qreg)
qc.u(param, 0, 0, 0)
out_qasm = dumps(qc)
register_name = self.register_regex.search(out_qasm)
parameter_name = self.scalar_parameter_regex.search(out_qasm)
self.assertTrue(register_name)
self.assertTrue(parameter_name)
self.assertIn("clash", register_name["name"])
self.assertIn("clash", parameter_name["name"])
self.assertNotEqual(register_name["name"], parameter_name["name"])
# Not necessarily all the reserved keywords, just a sensibly-sized subset.
@data("bit", "const", "def", "defcal", "float", "gate", "include", "int", "let", "measure")
def test_reserved_keywords_as_names_are_escaped(self, keyword):
"""Test that reserved keywords used to name registers and parameters are escaped into
another form when output, and the escaping cannot introduce new conflicts."""
with self.subTest("register"):
qreg = QuantumRegister(1, keyword)
qc = QuantumCircuit(qreg)
out_qasm = dumps(qc)
register_name = self.register_regex.search(out_qasm)
self.assertTrue(register_name, msg=f"Observed OQ3:\n{out_qasm}")
self.assertNotEqual(keyword, register_name["name"])
with self.subTest("parameter"):
qc = QuantumCircuit(1)
param = Parameter(keyword)
qc.u(param, 0, 0, 0)
out_qasm = dumps(qc)
parameter_name = self.scalar_parameter_regex.search(out_qasm)
self.assertTrue(parameter_name, msg=f"Observed OQ3:\n{out_qasm}")
self.assertNotEqual(keyword, parameter_name["name"])
def test_expr_condition(self):
"""Simple test that the conditions of `if`s and `while`s can be `Expr` nodes."""
bits = [Qubit(), Clbit()]
cr = ClassicalRegister(2, "cr")
if_body = QuantumCircuit(1)
if_body.x(0)
while_body = QuantumCircuit(1)
while_body.x(0)
qc = QuantumCircuit(bits, cr)
qc.if_test(expr.logic_not(qc.clbits[0]), if_body, [0], [])
qc.while_loop(expr.equal(cr, 3), while_body, [0], [])
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit _bit0;
bit[2] cr;
qubit _qubit0;
if (!_bit0) {
x _qubit0;
}
while (cr == 3) {
x _qubit0;
}
"""
self.assertEqual(dumps(qc), expected)
def test_expr_nested_condition(self):
"""Simple test that the conditions of `if`s and `while`s can be `Expr` nodes when nested,
and the mapping of inner bits to outer bits is correct."""
bits = [Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
inner_if_body = QuantumCircuit(1)
inner_if_body.x(0)
outer_if_body = QuantumCircuit(1, 1)
outer_if_body.if_test(expr.lift(outer_if_body.clbits[0]), inner_if_body, [0], [])
inner_while_body = QuantumCircuit(1)
inner_while_body.x(0)
outer_while_body = QuantumCircuit([Qubit()], cr)
outer_while_body.while_loop(expr.equal(expr.bit_and(cr, 3), 3), inner_while_body, [0], [])
qc = QuantumCircuit(bits, cr)
qc.if_test(expr.logic_not(qc.clbits[0]), outer_if_body, [0], [1])
qc.while_loop(expr.equal(cr, 3), outer_while_body, [0], cr)
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit _bit0;
bit _bit1;
bit[2] cr;
qubit _qubit0;
if (!_bit0) {
if (_bit1) {
x _qubit0;
}
}
while (cr == 3) {
while ((cr & 3) == 3) {
x _qubit0;
}
}
"""
self.assertEqual(dumps(qc), expected)
def test_expr_associativity_left(self):
"""Test that operations that are in the expression tree in a left-associative form are
output to OQ3 correctly."""
body = QuantumCircuit()
cr1 = ClassicalRegister(3, "cr1")
cr2 = ClassicalRegister(3, "cr2")
cr3 = ClassicalRegister(3, "cr3")
qc = QuantumCircuit(cr1, cr2, cr3)
qc.if_test(expr.equal(expr.bit_and(expr.bit_and(cr1, cr2), cr3), 7), body.copy(), [], [])
qc.if_test(expr.equal(expr.bit_or(expr.bit_or(cr1, cr2), cr3), 7), body.copy(), [], [])
qc.if_test(expr.equal(expr.bit_xor(expr.bit_xor(cr1, cr2), cr3), 7), body.copy(), [], [])
qc.if_test(expr.logic_and(expr.logic_and(cr1[0], cr1[1]), cr1[2]), body.copy(), [], [])
qc.if_test(expr.logic_or(expr.logic_or(cr1[0], cr1[1]), cr1[2]), body.copy(), [], [])
# Note that bitwise operations have lower priority than `==` so there's extra parentheses.
# All these operators are left-associative in OQ3.
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[3] cr1;
bit[3] cr2;
bit[3] cr3;
if ((cr1 & cr2 & cr3) == 7) {
}
if ((cr1 | cr2 | cr3) == 7) {
}
if ((cr1 ^ cr2 ^ cr3) == 7) {
}
if (cr1[0] && cr1[1] && cr1[2]) {
}
if (cr1[0] || cr1[1] || cr1[2]) {
}
"""
self.assertEqual(dumps(qc), expected)
def test_expr_associativity_right(self):
"""Test that operations that are in the expression tree in a right-associative form are
output to OQ3 correctly."""
body = QuantumCircuit()
cr1 = ClassicalRegister(3, "cr1")
cr2 = ClassicalRegister(3, "cr2")
cr3 = ClassicalRegister(3, "cr3")
qc = QuantumCircuit(cr1, cr2, cr3)
qc.if_test(expr.equal(expr.bit_and(cr1, expr.bit_and(cr2, cr3)), 7), body.copy(), [], [])
qc.if_test(expr.equal(expr.bit_or(cr1, expr.bit_or(cr2, cr3)), 7), body.copy(), [], [])
qc.if_test(expr.equal(expr.bit_xor(cr1, expr.bit_xor(cr2, cr3)), 7), body.copy(), [], [])
qc.if_test(expr.logic_and(cr1[0], expr.logic_and(cr1[1], cr1[2])), body.copy(), [], [])
qc.if_test(expr.logic_or(cr1[0], expr.logic_or(cr1[1], cr1[2])), body.copy(), [], [])
# Note that bitwise operations have lower priority than `==` so there's extra parentheses.
# All these operators are left-associative in OQ3, so we need parentheses for them to be
# parsed correctly. Mathematically, they're all actually associative in general, so the
# order doesn't _technically_ matter.
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[3] cr1;
bit[3] cr2;
bit[3] cr3;
if ((cr1 & (cr2 & cr3)) == 7) {
}
if ((cr1 | (cr2 | cr3)) == 7) {
}
if ((cr1 ^ (cr2 ^ cr3)) == 7) {
}
if (cr1[0] && (cr1[1] && cr1[2])) {
}
if (cr1[0] || (cr1[1] || cr1[2])) {
}
"""
self.assertEqual(dumps(qc), expected)
def test_expr_binding_unary(self):
"""Test that nested unary operators don't insert unnecessary brackets."""
body = QuantumCircuit()
cr = ClassicalRegister(2, "cr")
qc = QuantumCircuit(cr)
qc.if_test(expr.equal(expr.bit_not(expr.bit_not(cr)), 3), body.copy(), [], [])
qc.if_test(expr.logic_not(expr.logic_not(cr[0])), body.copy(), [], [])
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[2] cr;
if (~~cr == 3) {
}
if (!!cr[0]) {
}
"""
self.assertEqual(dumps(qc), expected)
def test_expr_precedence(self):
"""Test that the precedence properties of operators are correctly output."""
body = QuantumCircuit()
cr = ClassicalRegister(2, "cr")
# This tree is _completely_ inside out, so there's brackets needed round every operand.
inside_out = expr.logic_not(
expr.less(
expr.bit_and(
expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)),
expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)),
),
expr.bit_and(
expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)),
expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)),
),
)
)
# This one is the other way round - the tightest-binding operations are on the inside, so no
# brackets should be needed at all except to put in a comparison to a bitwise binary
# operation, since those bind less tightly than anything that can cast them to a bool.
outside_in = expr.logic_or(
expr.logic_and(
expr.equal(expr.bit_or(cr, cr), expr.bit_and(cr, cr)),
expr.equal(expr.bit_and(cr, cr), expr.bit_or(cr, cr)),
),
expr.logic_and(
expr.greater(expr.bit_or(cr, cr), expr.bit_xor(cr, cr)),
expr.less_equal(expr.bit_xor(cr, cr), expr.bit_or(cr, cr)),
),
)
# And an extra test of the logical operator order.
logics = expr.logic_or(
expr.logic_and(
expr.logic_or(expr.logic_not(cr[0]), expr.logic_not(cr[0])),
expr.logic_not(expr.logic_and(cr[0], cr[0])),
),
expr.logic_and(
expr.logic_not(expr.logic_and(cr[0], cr[0])),
expr.logic_or(expr.logic_not(cr[0]), expr.logic_not(cr[0])),
),
)
qc = QuantumCircuit(cr)
qc.if_test(inside_out, body.copy(), [], [])
qc.if_test(outside_in, body.copy(), [], [])
qc.if_test(logics, body.copy(), [], [])
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[2] cr;
if (!((((cr | cr) ^ (cr | cr)) & ((cr | cr) ^ (cr | cr)))\
< (((cr | cr) ^ (cr | cr)) & ((cr | cr) ^ (cr | cr))))) {
}
if ((cr | cr) == (cr & cr) && (cr & cr) == (cr | cr)\
|| (cr | cr) > (cr ^ cr) && (cr ^ cr) <= (cr | cr)) {
}
if ((!cr[0] || !cr[0]) && !(cr[0] && cr[0]) || !(cr[0] && cr[0]) && (!cr[0] || !cr[0])) {
}
"""
self.assertEqual(dumps(qc), expected)
def test_no_unnecessary_cast(self):
"""This is a bit of a cross `Expr`-constructor / OQ3-exporter test. It doesn't really
matter whether or not the `Expr` constructor functions insert cast nodes into their output
for the literals (at the time of writing [commit 2616602], they don't because they do some
type inference) but the OQ3 export definitely shouldn't have them."""
cr = ClassicalRegister(8, "cr")
qc = QuantumCircuit(cr)
# Note that the integer '1' has a minimum bit-width of 1, whereas the register has a width
# of 8. We're testing to make sure that there's no spurious cast up from `bit[1]` to
# `bit[8]`, or anything like that, _whether or not_ the `Expr` node includes one.
qc.if_test(expr.equal(cr, 1), QuantumCircuit(), [], [])
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[8] cr;
if (cr == 1) {
}
"""
self.assertEqual(dumps(qc), expected)
class TestCircuitQASM3ExporterTemporaryCasesWithBadParameterisation(QiskitTestCase):
"""Test functionality that is not what we _want_, but is what we need to do while the definition
of custom gates with parameterisation does not work correctly.
These tests are modified versions of those marked with the `requires_fixed_parameterisation`
decorator, and this whole class can be deleted once those are fixed. See gh-7335.
"""
maxDiff = 1_000_000
def test_basis_gates(self):
"""Teleportation with physical qubits"""
qc = QuantumCircuit(3, 2)
first_h = qc.h(1)[0].operation
qc.cx(1, 2)
qc.barrier()
qc.cx(0, 1)
qc.h(0)
qc.barrier()
qc.measure([0, 1], [0, 1])
qc.barrier()
first_x = qc.x(2).c_if(qc.clbits[1], 1)[0].operation
qc.z(2).c_if(qc.clbits[0], 1)
u2 = first_h.definition.data[0].operation
u3_1 = u2.definition.data[0].operation
u3_2 = first_x.definition.data[0].operation
expected_qasm = "\n".join(
[
"OPENQASM 3;",
f"gate u3_{id(u3_1)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(pi/2, 0, pi) _gate_q_0;",
"}",
f"gate u2_{id(u2)}(_gate_p_0, _gate_p_1) _gate_q_0 {{",
f" u3_{id(u3_1)}(pi/2, 0, pi) _gate_q_0;",
"}",
"gate h _gate_q_0 {",
f" u2_{id(u2)}(0, pi) _gate_q_0;",
"}",
f"gate u3_{id(u3_2)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(pi, 0, pi) _gate_q_0;",
"}",
"gate x _gate_q_0 {",
f" u3_{id(u3_2)}(pi, 0, pi) _gate_q_0;",
"}",
"bit[2] c;",
"qubit[3] q;",
"h q[1];",
"cx q[1], q[2];",
"barrier q[0], q[1], q[2];",
"cx q[0], q[1];",
"h q[0];",
"barrier q[0], q[1], q[2];",
"c[0] = measure q[0];",
"c[1] = measure q[1];",
"barrier q[0], q[1], q[2];",
"if (c[1]) {",
" x q[2];",
"}",
"if (c[0]) {",
" z q[2];",
"}",
"",
]
)
self.assertEqual(
Exporter(includes=[], basis_gates=["cx", "z", "U"]).dumps(qc),
expected_qasm,
)
def test_teleportation(self):
"""Teleportation with physical qubits"""
qc = QuantumCircuit(3, 2)
qc.h(1)
qc.cx(1, 2)
qc.barrier()
qc.cx(0, 1)
qc.h(0)
qc.barrier()
qc.measure([0, 1], [0, 1])
qc.barrier()
qc.x(2).c_if(qc.clbits[1], 1)
qc.z(2).c_if(qc.clbits[0], 1)
transpiled = transpile(qc, initial_layout=[0, 1, 2])
first_h = transpiled.data[0].operation
u2 = first_h.definition.data[0].operation
u3_1 = u2.definition.data[0].operation
first_x = transpiled.data[-2].operation
u3_2 = first_x.definition.data[0].operation
first_z = transpiled.data[-1].operation
u1 = first_z.definition.data[0].operation
u3_3 = u1.definition.data[0].operation
expected_qasm = "\n".join(
[
"OPENQASM 3;",
f"gate u3_{id(u3_1)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(pi/2, 0, pi) _gate_q_0;",
"}",
f"gate u2_{id(u2)}(_gate_p_0, _gate_p_1) _gate_q_0 {{",
f" u3_{id(u3_1)}(pi/2, 0, pi) _gate_q_0;",
"}",
"gate h _gate_q_0 {",
f" u2_{id(u2)}(0, pi) _gate_q_0;",
"}",
"gate cx c, t {",
" ctrl @ U(pi, 0, pi) c, t;",
"}",
f"gate u3_{id(u3_2)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(pi, 0, pi) _gate_q_0;",
"}",
"gate x _gate_q_0 {",
f" u3_{id(u3_2)}(pi, 0, pi) _gate_q_0;",
"}",
f"gate u3_{id(u3_3)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(0, 0, pi) _gate_q_0;",
"}",
f"gate u1_{id(u1)}(_gate_p_0) _gate_q_0 {{",
f" u3_{id(u3_3)}(0, 0, pi) _gate_q_0;",
"}",
"gate z _gate_q_0 {",
f" u1_{id(u1)}(pi) _gate_q_0;",
"}",
"bit[2] c;",
"h $1;",
"cx $1, $2;",
"barrier $0, $1, $2;",
"cx $0, $1;",
"h $0;",
"barrier $0, $1, $2;",
"c[0] = measure $0;",
"c[1] = measure $1;",
"barrier $0, $1, $2;",
"if (c[1]) {",
" x $2;",
"}",
"if (c[0]) {",
" z $2;",
"}",
"",
]
)
self.assertEqual(Exporter(includes=[]).dumps(transpiled), expected_qasm)
def test_custom_gate_with_params_bound_main_call(self):
"""Custom gate with unbound parameters that are bound in the main circuit"""
parameter0 = Parameter("p0")
parameter1 = Parameter("p1")
custom = QuantumCircuit(2, name="custom")
custom.rz(parameter0, 0)
custom.rz(parameter1 / 2, 1)
qr_all_qubits = QuantumRegister(3, "q")
qr_r = QuantumRegister(3, "r")
circuit = QuantumCircuit(qr_all_qubits, qr_r)
circuit.append(custom.to_gate(), [qr_all_qubits[0], qr_r[0]])
circuit.assign_parameters({parameter0: pi, parameter1: pi / 2}, inplace=True)
custom_id = id(circuit.data[0].operation)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
f"gate custom_{custom_id}(_gate_p_0, _gate_p_1) _gate_q_0, _gate_q_1 {{",
" rz(pi) _gate_q_0;",
" rz(pi/4) _gate_q_1;",
"}",
"qubit[3] q;",
"qubit[3] r;",
f"custom_{custom_id}(pi, pi/2) q[0], r[0];",
"",
]
)
self.assertEqual(Exporter().dumps(circuit), expected_qasm)
def test_no_include(self):
"""Test explicit gate declaration (no include)"""
q = QuantumRegister(2, "q")
circuit = QuantumCircuit(q)
circuit.rz(pi / 2, 0)
circuit.sx(0)
circuit.cx(0, 1)
rz = circuit.data[0].operation
u1_1 = rz.definition.data[0].operation
u3_1 = u1_1.definition.data[0].operation
sx = circuit.data[1].operation
sdg = sx.definition.data[0].operation
u1_2 = sdg.definition.data[0].operation
u3_2 = u1_2.definition.data[0].operation
h_ = sx.definition.data[1].operation
u2_1 = h_.definition.data[0].operation
u3_3 = u2_1.definition.data[0].operation
expected_qasm = "\n".join(
[
"OPENQASM 3;",
f"gate u3_{id(u3_1)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(0, 0, pi/2) _gate_q_0;",
"}",
f"gate u1_{id(u1_1)}(_gate_p_0) _gate_q_0 {{",
f" u3_{id(u3_1)}(0, 0, pi/2) _gate_q_0;",
"}",
f"gate rz_{id(rz)}(_gate_p_0) _gate_q_0 {{",
f" u1_{id(u1_1)}(pi/2) _gate_q_0;",
"}",
f"gate u3_{id(u3_2)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(0, 0, -pi/2) _gate_q_0;",
"}",
f"gate u1_{id(u1_2)}(_gate_p_0) _gate_q_0 {{",
f" u3_{id(u3_2)}(0, 0, -pi/2) _gate_q_0;",
"}",
"gate sdg _gate_q_0 {",
f" u1_{id(u1_2)}(-pi/2) _gate_q_0;",
"}",
f"gate u3_{id(u3_3)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(pi/2, 0, pi) _gate_q_0;",
"}",
f"gate u2_{id(u2_1)}(_gate_p_0, _gate_p_1) _gate_q_0 {{",
f" u3_{id(u3_3)}(pi/2, 0, pi) _gate_q_0;",
"}",
"gate h _gate_q_0 {",
f" u2_{id(u2_1)}(0, pi) _gate_q_0;",
"}",
"gate sx _gate_q_0 {",
" sdg _gate_q_0;",
" h _gate_q_0;",
" sdg _gate_q_0;",
"}",
"gate cx c, t {",
" ctrl @ U(pi, 0, pi) c, t;",
"}",
"qubit[2] q;",
f"rz_{id(rz)}(pi/2) q[0];",
"sx q[0];",
"cx q[0], q[1];",
"",
]
)
self.assertEqual(Exporter(includes=[]).dumps(circuit), expected_qasm)
def test_unusual_conditions(self):
"""Test that special QASM constructs such as ``measure`` are correctly handled when the
Terra instructions have old-style conditions."""
qc = QuantumCircuit(3, 2)
qc.h(0)
qc.measure(0, 0)
qc.measure(1, 1).c_if(0, True)
qc.reset([0, 1]).c_if(0, True)
with qc.while_loop((qc.clbits[0], True)):
qc.break_loop().c_if(0, True)
qc.continue_loop().c_if(0, True)
# Terra forbids delay and barrier from being conditioned through `c_if`, but in theory they
# should work fine in a dynamic-circuits sense (although what a conditional barrier _means_
# is a whole other kettle of fish).
delay = Delay(16, "dt")
delay.condition = (qc.clbits[0], True)
qc.append(delay, [0], [])
barrier = Barrier(2)
barrier.condition = (qc.clbits[0], True)
qc.append(barrier, [0, 1], [])
expected = """
OPENQASM 3;
include "stdgates.inc";
bit[2] c;
qubit[3] q;
h q[0];
c[0] = measure q[0];
if (c[0]) {
c[1] = measure q[1];
}
if (c[0]) {
reset q[0];
}
if (c[0]) {
reset q[1];
}
while (c[0]) {
if (c[0]) {
break;
}
if (c[0]) {
continue;
}
}
if (c[0]) {
delay[16dt] q[0];
}
if (c[0]) {
barrier q[0], q[1];
}"""
self.assertEqual(dumps(qc).strip(), expected.strip())
class TestExperimentalFeatures(QiskitTestCase):
"""Tests of features that are hidden behind experimental flags."""
maxDiff = None
def test_switch_forbidden_without_flag(self):
"""Omitting the feature flag should raise an error."""
case = QuantumCircuit(1)
circuit = QuantumCircuit(1, 1)
circuit.switch(circuit.clbits[0], [((True, False), case)], [0], [])
with self.assertRaisesRegex(QASM3ExporterError, "'switch' statements are not stabilized"):
dumps(circuit)
def test_switch_clbit(self):
"""Test that a switch statement can be constructed with a bit as a condition."""
qubit = Qubit()
clbit = Clbit()
case1 = QuantumCircuit([qubit, clbit])
case1.x(0)
case2 = QuantumCircuit([qubit, clbit])
case2.z(0)
circuit = QuantumCircuit([qubit, clbit])
circuit.switch(clbit, [(True, case1), (False, case2)], [0], [0])
test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1)
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit _bit0;
int switch_dummy;
qubit _qubit0;
switch_dummy = _bit0;
switch (switch_dummy) {
case 1: {
x _qubit0;
}
break;
case 0: {
z _qubit0;
}
break;
}
"""
self.assertEqual(test, expected)
def test_switch_register(self):
"""Test that a switch statement can be constructed with a register as a condition."""
qubit = Qubit()
creg = ClassicalRegister(2, "c")
case1 = QuantumCircuit([qubit], creg)
case1.x(0)
case2 = QuantumCircuit([qubit], creg)
case2.y(0)
case3 = QuantumCircuit([qubit], creg)
case3.z(0)
circuit = QuantumCircuit([qubit], creg)
circuit.switch(creg, [(0, case1), (1, case2), (2, case3)], [0], circuit.clbits)
test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1)
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[2] c;
int switch_dummy;
qubit _qubit0;
switch_dummy = c;
switch (switch_dummy) {
case 0: {
x _qubit0;
}
break;
case 1: {
y _qubit0;
}
break;
case 2: {
z _qubit0;
}
break;
}
"""
self.assertEqual(test, expected)
def test_switch_with_default(self):
"""Test that a switch statement can be constructed with a default case at the end."""
qubit = Qubit()
creg = ClassicalRegister(2, "c")
case1 = QuantumCircuit([qubit], creg)
case1.x(0)
case2 = QuantumCircuit([qubit], creg)
case2.y(0)
case3 = QuantumCircuit([qubit], creg)
case3.z(0)
circuit = QuantumCircuit([qubit], creg)
circuit.switch(creg, [(0, case1), (1, case2), (CASE_DEFAULT, case3)], [0], circuit.clbits)
test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1)
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[2] c;
int switch_dummy;
qubit _qubit0;
switch_dummy = c;
switch (switch_dummy) {
case 0: {
x _qubit0;
}
break;
case 1: {
y _qubit0;
}
break;
default: {
z _qubit0;
}
break;
}
"""
self.assertEqual(test, expected)
def test_switch_multiple_cases_to_same_block(self):
"""Test that it is possible to add multiple cases that apply to the same block, if they are
given as a compound value. This is an allowed special case of block fall-through."""
qubit = Qubit()
creg = ClassicalRegister(2, "c")
case1 = QuantumCircuit([qubit], creg)
case1.x(0)
case2 = QuantumCircuit([qubit], creg)
case2.y(0)
circuit = QuantumCircuit([qubit], creg)
circuit.switch(creg, [(0, case1), ((1, 2), case2)], [0], circuit.clbits)
test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1)
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[2] c;
int switch_dummy;
qubit _qubit0;
switch_dummy = c;
switch (switch_dummy) {
case 0: {
x _qubit0;
}
break;
case 1:
case 2: {
y _qubit0;
}
break;
}
"""
self.assertEqual(test, expected)
def test_multiple_switches_dont_clash_on_dummy(self):
"""Test that having more than one switch statement in the circuit doesn't cause naming
clashes in the dummy integer value used."""
qubit = Qubit()
creg = ClassicalRegister(2, "switch_dummy")
case1 = QuantumCircuit([qubit], creg)
case1.x(0)
case2 = QuantumCircuit([qubit], creg)
case2.y(0)
circuit = QuantumCircuit([qubit], creg)
circuit.switch(creg, [(0, case1), ((1, 2), case2)], [0], circuit.clbits)
circuit.switch(creg, [(0, case1), ((1, 2), case2)], [0], circuit.clbits)
test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1)
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[2] switch_dummy;
int switch_dummy__generated0;
int switch_dummy__generated1;
qubit _qubit0;
switch_dummy__generated0 = switch_dummy;
switch (switch_dummy__generated0) {
case 0: {
x _qubit0;
}
break;
case 1:
case 2: {
y _qubit0;
}
break;
}
switch_dummy__generated1 = switch_dummy;
switch (switch_dummy__generated1) {
case 0: {
x _qubit0;
}
break;
case 1:
case 2: {
y _qubit0;
}
break;
}
"""
self.assertEqual(test, expected)
def test_switch_nested_in_if(self):
"""Test that the switch statement works when in a nested scope, including the dummy
classical variable being declared globally. This isn't necessary in the OQ3 language, but
it is universally valid and the IBM QSS stack prefers that. They're our primary consumers
of OQ3 strings, so it's best to play nicely with them."""
qubit = Qubit()
creg = ClassicalRegister(2, "c")
case1 = QuantumCircuit([qubit], creg)
case1.x(0)
case2 = QuantumCircuit([qubit], creg)
case2.y(0)
body = QuantumCircuit([qubit], creg)
body.switch(creg, [(0, case1), ((1, 2), case2)], [0], body.clbits)
circuit = QuantumCircuit([qubit], creg)
circuit.if_else((creg, 1), body.copy(), body, [0], body.clbits)
test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1)
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[2] c;
int switch_dummy;
int switch_dummy__generated0;
qubit _qubit0;
if (c == 1) {
switch_dummy = c;
switch (switch_dummy) {
case 0: {
x _qubit0;
}
break;
case 1:
case 2: {
y _qubit0;
}
break;
}
} else {
switch_dummy__generated0 = c;
switch (switch_dummy__generated0) {
case 0: {
x _qubit0;
}
break;
case 1:
case 2: {
y _qubit0;
}
break;
}
}
"""
self.assertEqual(test, expected)
def test_expr_target(self):
"""Simple test that the target of `switch` can be `Expr` nodes."""
bits = [Qubit(), Clbit()]
cr = ClassicalRegister(2, "cr")
case0 = QuantumCircuit(1)
case0.x(0)
case1 = QuantumCircuit(1)
case1.x(0)
qc = QuantumCircuit(bits, cr)
qc.switch(expr.logic_not(bits[1]), [(False, case0)], [0], [])
qc.switch(expr.bit_and(cr, 3), [(3, case1)], [0], [])
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit _bit0;
bit[2] cr;
int switch_dummy;
int switch_dummy__generated0;
qubit _qubit0;
switch_dummy = !_bit0;
switch (switch_dummy) {
case 0: {
x _qubit0;
}
break;
}
switch_dummy__generated0 = cr & 3;
switch (switch_dummy__generated0) {
case 3: {
x _qubit0;
}
break;
}
"""
test = dumps(qc, experimental=ExperimentalFeatures.SWITCH_CASE_V1)
self.assertEqual(test, expected)
@ddt
class TestQASM3ExporterFailurePaths(QiskitTestCase):
"""Tests of the failure paths for the exporter."""
def test_disallow_overlapping_classical_registers_if_no_aliasing(self):
"""Test that the exporter rejects circuits with a classical bit in more than one register if
the ``alias_classical_registers`` option is set false."""
qubits = [Qubit() for _ in [None] * 3]
clbits = [Clbit() for _ in [None] * 5]
registers = [ClassicalRegister(bits=clbits[:4]), ClassicalRegister(bits=clbits[1:])]
qc = QuantumCircuit(qubits, *registers)
exporter = Exporter(alias_classical_registers=False)
with self.assertRaisesRegex(QASM3ExporterError, r"classical registers .* overlap"):
exporter.dumps(qc)
@data([1, 2, 1.1], [1j, 2])
def test_disallow_for_loops_with_non_integers(self, indices):
"""Test that the exporter rejects ``for`` loops that include non-integer values in their
index sets."""
loop_body = QuantumCircuit()
qc = QuantumCircuit(2, 2)
qc.for_loop(indices, None, loop_body, [], [])
exporter = Exporter()
with self.assertRaisesRegex(
QASM3ExporterError, r"The values in QASM 3 'for' loops must all be integers.*"
):
exporter.dumps(qc)
def test_disallow_custom_subroutine_with_parameters(self):
"""Test that the exporter throws an error instead of trying to export a subroutine with
parameters, while this is not supported."""
subroutine = QuantumCircuit(1)
subroutine.rx(Parameter("x"), 0)
qc = QuantumCircuit(1)
qc.append(subroutine.to_instruction(), [0], [])
exporter = Exporter()
with self.assertRaisesRegex(
QASM3ExporterError, "Exporting non-unitary instructions is not yet supported"
):
exporter.dumps(qc)
def test_disallow_opaque_instruction(self):
"""Test that the exporter throws an error instead of trying to export something into a
``defcal`` block, while this is not supported."""
qc = QuantumCircuit(1)
qc.append(Instruction("opaque", 1, 0, []), [0], [])
exporter = Exporter()
with self.assertRaisesRegex(
QASM3ExporterError, "Exporting opaque instructions .* is not yet supported"
):
exporter.dumps(qc)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
# Since the import is nearly entirely delegated to an external package, most of the testing is done
# there. Here we need to test our wrapping behaviour for base functionality and exceptions. We
# don't want to get into a situation where updates to `qiskit_qasm3_import` breaks Terra's test
# suite due to too specific tests on the Terra side.
import os
import tempfile
import unittest
from qiskit import qasm3
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.test import QiskitTestCase
from qiskit.utils import optionals
class TestQASM3Import(QiskitTestCase):
@unittest.skipUnless(
optionals.HAS_QASM3_IMPORT, "need qiskit-qasm3-import for OpenQASM 3 imports"
)
def test_import_errors_converted(self):
with self.assertRaises(qasm3.QASM3ImporterError):
qasm3.loads("OPENQASM 3.0; qubit[2.5] q;")
@unittest.skipUnless(
optionals.HAS_QASM3_IMPORT, "need qiskit-qasm3-import for OpenQASM 3 imports"
)
def test_loads_can_succeed(self):
program = """
OPENQASM 3.0;
include "stdgates.inc";
qubit[2] qr;
bit[2] cr;
h qr[0];
cx qr[0], qr[1];
cr[0] = measure qr[0];
cr[1] = measure qr[1];
"""
parsed = qasm3.loads(program)
expected = QuantumCircuit(QuantumRegister(2, "qr"), ClassicalRegister(2, "cr"))
expected.h(0)
expected.cx(0, 1)
expected.measure(0, 0)
expected.measure(1, 1)
self.assertEqual(parsed, expected)
@unittest.skipUnless(
optionals.HAS_QASM3_IMPORT, "need qiskit-qasm3-import for OpenQASM 3 imports"
)
def test_load_can_succeed(self):
program = """
OPENQASM 3.0;
include "stdgates.inc";
qubit[2] qr;
bit[2] cr;
h qr[0];
cx qr[0], qr[1];
cr[0] = measure qr[0];
cr[1] = measure qr[1];
"""
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_path = os.path.join(tmp_dir, "bell.qasm")
with open(tmp_path, "w") as fptr:
fptr.write(program)
parsed = qasm3.load(tmp_path)
expected = QuantumCircuit(QuantumRegister(2, "qr"), ClassicalRegister(2, "cr"))
expected.h(0)
expected.cx(0, 1)
expected.measure(0, 0)
expected.measure(1, 1)
self.assertEqual(parsed, expected)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Qobj tests."""
import copy
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.compiler import assemble
from qiskit.qobj import (
QasmQobj,
PulseQobj,
QobjHeader,
PulseQobjInstruction,
PulseQobjExperiment,
PulseQobjConfig,
QobjMeasurementOption,
PulseLibraryItem,
QasmQobjInstruction,
QasmQobjExperiment,
QasmQobjConfig,
QasmExperimentCalibrations,
GateCalibration,
)
from qiskit.test import QiskitTestCase
class TestQASMQobj(QiskitTestCase):
"""Tests for QasmQobj."""
def setUp(self):
super().setUp()
self.valid_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2),
experiments=[
QasmQobjExperiment(
instructions=[
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]),
]
)
],
)
self.valid_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.2.0",
"header": {},
"config": {"memory_slots": 2, "shots": 1024},
"experiments": [
{
"instructions": [
{"name": "u1", "params": [0.4], "qubits": [1]},
{"name": "u2", "params": [0.4, 0.2], "qubits": [1]},
]
}
],
}
self.bad_qobj = copy.deepcopy(self.valid_qobj)
self.bad_qobj.experiments = []
def test_from_dict_per_class(self):
"""Test Qobj and its subclass representations given a dictionary."""
test_parameters = {
QasmQobj: (self.valid_qobj, self.valid_dict),
QasmQobjConfig: (
QasmQobjConfig(shots=1, memory_slots=2),
{"shots": 1, "memory_slots": 2},
),
QasmQobjExperiment: (
QasmQobjExperiment(
instructions=[QasmQobjInstruction(name="u1", qubits=[1], params=[0.4])]
),
{"instructions": [{"name": "u1", "qubits": [1], "params": [0.4]}]},
),
QasmQobjInstruction: (
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
{"name": "u1", "qubits": [1], "params": [0.4]},
),
}
for qobj_class, (qobj_item, expected_dict) in test_parameters.items():
with self.subTest(msg=str(qobj_class)):
self.assertEqual(qobj_item, qobj_class.from_dict(expected_dict))
def test_snapshot_instruction_to_dict(self):
"""Test snapshot instruction to dict."""
valid_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2),
experiments=[
QasmQobjExperiment(
instructions=[
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]),
QasmQobjInstruction(
name="snapshot",
qubits=[1],
snapshot_type="statevector",
label="my_snap",
),
]
)
],
)
res = valid_qobj.to_dict()
expected_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.3.0",
"header": {},
"config": {"memory_slots": 2, "shots": 1024},
"experiments": [
{
"instructions": [
{"name": "u1", "params": [0.4], "qubits": [1]},
{"name": "u2", "params": [0.4, 0.2], "qubits": [1]},
{
"name": "snapshot",
"qubits": [1],
"snapshot_type": "statevector",
"label": "my_snap",
},
],
"config": {},
"header": {},
}
],
}
self.assertEqual(expected_dict, res)
def test_snapshot_instruction_from_dict(self):
"""Test snapshot instruction from dict."""
expected_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2),
experiments=[
QasmQobjExperiment(
instructions=[
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]),
QasmQobjInstruction(
name="snapshot",
qubits=[1],
snapshot_type="statevector",
label="my_snap",
),
]
)
],
)
qobj_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.2.0",
"header": {},
"config": {"memory_slots": 2, "shots": 1024},
"experiments": [
{
"instructions": [
{"name": "u1", "params": [0.4], "qubits": [1]},
{"name": "u2", "params": [0.4, 0.2], "qubits": [1]},
{
"name": "snapshot",
"qubits": [1],
"snapshot_type": "statevector",
"label": "my_snap",
},
]
}
],
}
self.assertEqual(expected_qobj, QasmQobj.from_dict(qobj_dict))
def test_change_qobj_after_compile(self):
"""Test modifying Qobj parameters after compile."""
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
qc1 = QuantumCircuit(qr, cr)
qc2 = QuantumCircuit(qr, cr)
qc1.h(qr[0])
qc1.cx(qr[0], qr[1])
qc1.cx(qr[0], qr[2])
qc2.h(qr)
qc1.measure(qr, cr)
qc2.measure(qr, cr)
circuits = [qc1, qc2]
qobj1 = assemble(circuits, shots=1024, seed=88)
qobj1.experiments[0].config.shots = 50
qobj1.experiments[1].config.shots = 1
self.assertTrue(qobj1.experiments[0].config.shots == 50)
self.assertTrue(qobj1.experiments[1].config.shots == 1)
self.assertTrue(qobj1.config.shots == 1024)
def test_gate_calibrations_to_dict(self):
"""Test gate calibrations to dict."""
pulse_library = [PulseLibraryItem(name="test", samples=[1j, 1j])]
valid_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2, pulse_library=pulse_library),
experiments=[
QasmQobjExperiment(
instructions=[QasmQobjInstruction(name="u1", qubits=[1], params=[0.4])],
config=QasmQobjConfig(
calibrations=QasmExperimentCalibrations(
gates=[
GateCalibration(
name="u1", qubits=[1], params=[0.4], instructions=[]
)
]
)
),
)
],
)
res = valid_qobj.to_dict()
expected_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.3.0",
"header": {},
"config": {
"memory_slots": 2,
"shots": 1024,
"pulse_library": [{"name": "test", "samples": [1j, 1j]}],
},
"experiments": [
{
"instructions": [{"name": "u1", "params": [0.4], "qubits": [1]}],
"config": {
"calibrations": {
"gates": [
{"name": "u1", "qubits": [1], "params": [0.4], "instructions": []}
]
}
},
"header": {},
}
],
}
self.assertEqual(expected_dict, res)
class TestPulseQobj(QiskitTestCase):
"""Tests for PulseQobj."""
def setUp(self):
super().setUp()
self.valid_qobj = PulseQobj(
qobj_id="12345",
header=QobjHeader(),
config=PulseQobjConfig(
shots=1024,
memory_slots=2,
meas_level=1,
memory_slot_size=8192,
meas_return="avg",
pulse_library=[
PulseLibraryItem(name="pulse0", samples=[0.0 + 0.0j, 0.5 + 0.0j, 0.0 + 0.0j])
],
qubit_lo_freq=[4.9],
meas_lo_freq=[6.9],
rep_time=1000,
),
experiments=[
PulseQobjExperiment(
instructions=[
PulseQobjInstruction(name="pulse0", t0=0, ch="d0"),
PulseQobjInstruction(name="fc", t0=5, ch="d0", phase=1.57),
PulseQobjInstruction(name="fc", t0=5, ch="d0", phase=0.0),
PulseQobjInstruction(name="fc", t0=5, ch="d0", phase="P1"),
PulseQobjInstruction(name="setp", t0=10, ch="d0", phase=3.14),
PulseQobjInstruction(name="setf", t0=10, ch="d0", frequency=8.0),
PulseQobjInstruction(name="shiftf", t0=10, ch="d0", frequency=4.0),
PulseQobjInstruction(
name="acquire",
t0=15,
duration=5,
qubits=[0],
memory_slot=[0],
kernels=[
QobjMeasurementOption(
name="boxcar", params={"start_window": 0, "stop_window": 5}
)
],
),
]
)
],
)
self.valid_dict = {
"qobj_id": "12345",
"type": "PULSE",
"schema_version": "1.2.0",
"header": {},
"config": {
"memory_slots": 2,
"shots": 1024,
"meas_level": 1,
"memory_slot_size": 8192,
"meas_return": "avg",
"pulse_library": [{"name": "pulse0", "samples": [0, 0.5, 0]}],
"qubit_lo_freq": [4.9],
"meas_lo_freq": [6.9],
"rep_time": 1000,
},
"experiments": [
{
"instructions": [
{"name": "pulse0", "t0": 0, "ch": "d0"},
{"name": "fc", "t0": 5, "ch": "d0", "phase": 1.57},
{"name": "fc", "t0": 5, "ch": "d0", "phase": 0},
{"name": "fc", "t0": 5, "ch": "d0", "phase": "P1"},
{"name": "setp", "t0": 10, "ch": "d0", "phase": 3.14},
{"name": "setf", "t0": 10, "ch": "d0", "frequency": 8.0},
{"name": "shiftf", "t0": 10, "ch": "d0", "frequency": 4.0},
{
"name": "acquire",
"t0": 15,
"duration": 5,
"qubits": [0],
"memory_slot": [0],
"kernels": [
{"name": "boxcar", "params": {"start_window": 0, "stop_window": 5}}
],
},
]
}
],
}
def test_from_dict_per_class(self):
"""Test converting to Qobj and its subclass representations given a dictionary."""
test_parameters = {
PulseQobj: (self.valid_qobj, self.valid_dict),
PulseQobjConfig: (
PulseQobjConfig(
meas_level=1,
memory_slot_size=8192,
meas_return="avg",
pulse_library=[PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j])],
qubit_lo_freq=[4.9],
meas_lo_freq=[6.9],
rep_time=1000,
),
{
"meas_level": 1,
"memory_slot_size": 8192,
"meas_return": "avg",
"pulse_library": [{"name": "pulse0", "samples": [0.1 + 0j]}],
"qubit_lo_freq": [4.9],
"meas_lo_freq": [6.9],
"rep_time": 1000,
},
),
PulseLibraryItem: (
PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j]),
{"name": "pulse0", "samples": [0.1 + 0j]},
),
PulseQobjExperiment: (
PulseQobjExperiment(
instructions=[PulseQobjInstruction(name="pulse0", t0=0, ch="d0")]
),
{"instructions": [{"name": "pulse0", "t0": 0, "ch": "d0"}]},
),
PulseQobjInstruction: (
PulseQobjInstruction(name="pulse0", t0=0, ch="d0"),
{"name": "pulse0", "t0": 0, "ch": "d0"},
),
}
for qobj_class, (qobj_item, expected_dict) in test_parameters.items():
with self.subTest(msg=str(qobj_class)):
self.assertEqual(qobj_item, qobj_class.from_dict(expected_dict))
def test_to_dict_per_class(self):
"""Test converting from Qobj and its subclass representations given a dictionary."""
test_parameters = {
PulseQobj: (self.valid_qobj, self.valid_dict),
PulseQobjConfig: (
PulseQobjConfig(
meas_level=1,
memory_slot_size=8192,
meas_return="avg",
pulse_library=[PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j])],
qubit_lo_freq=[4.9],
meas_lo_freq=[6.9],
rep_time=1000,
),
{
"meas_level": 1,
"memory_slot_size": 8192,
"meas_return": "avg",
"pulse_library": [{"name": "pulse0", "samples": [0.1 + 0j]}],
"qubit_lo_freq": [4.9],
"meas_lo_freq": [6.9],
"rep_time": 1000,
},
),
PulseLibraryItem: (
PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j]),
{"name": "pulse0", "samples": [0.1 + 0j]},
),
PulseQobjExperiment: (
PulseQobjExperiment(
instructions=[PulseQobjInstruction(name="pulse0", t0=0, ch="d0")]
),
{"instructions": [{"name": "pulse0", "t0": 0, "ch": "d0"}]},
),
PulseQobjInstruction: (
PulseQobjInstruction(name="pulse0", t0=0, ch="d0"),
{"name": "pulse0", "t0": 0, "ch": "d0"},
),
}
for qobj_class, (qobj_item, expected_dict) in test_parameters.items():
with self.subTest(msg=str(qobj_class)):
self.assertEqual(qobj_item.to_dict(), expected_dict)
def _nop():
pass
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for qiskit.quantum_info.analysis"""
import unittest
import qiskit
from qiskit import BasicAer
from qiskit.quantum_info.analysis.average import average_data
from qiskit.quantum_info.analysis.make_observable import make_dict_observable
from qiskit.quantum_info.analysis import hellinger_fidelity
from qiskit.test import QiskitTestCase
class TestAnalyzation(QiskitTestCase):
"""Test qiskit.Result API"""
def test_average_data_dict_observable(self):
"""Test average_data for dictionary observable input"""
qr = qiskit.QuantumRegister(2)
cr = qiskit.ClassicalRegister(2)
qc = qiskit.QuantumCircuit(qr, cr, name="qc")
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
shots = 10000
backend = BasicAer.get_backend("qasm_simulator")
result = qiskit.execute(qc, backend, shots=shots).result()
counts = result.get_counts(qc)
observable = {"00": 1, "11": 1, "01": -1, "10": -1}
mean_zz = average_data(counts=counts, observable=observable)
observable = {"00": 1, "11": -1, "01": 1, "10": -1}
mean_zi = average_data(counts, observable)
observable = {"00": 1, "11": -1, "01": -1, "10": 1}
mean_iz = average_data(counts, observable)
self.assertAlmostEqual(mean_zz, 1, places=1)
self.assertAlmostEqual(mean_zi, 0, places=1)
self.assertAlmostEqual(mean_iz, 0, places=1)
def test_average_data_list_observable(self):
"""Test average_data for list observable input."""
qr = qiskit.QuantumRegister(3)
cr = qiskit.ClassicalRegister(3)
qc = qiskit.QuantumCircuit(qr, cr, name="qc")
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.cx(qr[0], qr[2])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
qc.measure(qr[2], cr[2])
shots = 10000
backend = BasicAer.get_backend("qasm_simulator")
result = qiskit.execute(qc, backend, shots=shots).result()
counts = result.get_counts(qc)
observable = [1, -1, -1, 1, -1, 1, 1, -1]
mean_zzz = average_data(counts=counts, observable=observable)
observable = [1, 1, 1, 1, -1, -1, -1, -1]
mean_zii = average_data(counts, observable)
observable = [1, 1, -1, -1, 1, 1, -1, -1]
mean_izi = average_data(counts, observable)
observable = [1, 1, -1, -1, -1, -1, 1, 1]
mean_zzi = average_data(counts, observable)
self.assertAlmostEqual(mean_zzz, 0, places=1)
self.assertAlmostEqual(mean_zii, 0, places=1)
self.assertAlmostEqual(mean_izi, 0, places=1)
self.assertAlmostEqual(mean_zzi, 1, places=1)
def test_average_data_matrix_observable(self):
"""Test average_data for matrix observable input."""
qr = qiskit.QuantumRegister(2)
cr = qiskit.ClassicalRegister(2)
qc = qiskit.QuantumCircuit(qr, cr, name="qc")
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
shots = 10000
backend = BasicAer.get_backend("qasm_simulator")
result = qiskit.execute(qc, backend, shots=shots).result()
counts = result.get_counts(qc)
observable = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]]
mean_zz = average_data(counts=counts, observable=observable)
observable = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]]
mean_zi = average_data(counts, observable)
observable = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]]
mean_iz = average_data(counts, observable)
self.assertAlmostEqual(mean_zz, 1, places=1)
self.assertAlmostEqual(mean_zi, 0, places=1)
self.assertAlmostEqual(mean_iz, 0, places=1)
def test_make_dict_observable(self):
"""Test make_dict_observable."""
list_in = [1, 1, -1, -1]
list_out = make_dict_observable(list_in)
list_expected = {"00": 1, "01": 1, "10": -1, "11": -1}
matrix_in = [[4, 0, 0, 0], [0, -3, 0, 0], [0, 0, 2, 0], [0, 0, 0, -1]]
matrix_out = make_dict_observable(matrix_in)
matrix_expected = {"00": 4, "01": -3, "10": 2, "11": -1}
long_list_in = [1, 1, -1, -1, -1, -1, 1, 1]
long_list_out = make_dict_observable(long_list_in)
long_list_expected = {
"000": 1,
"001": 1,
"010": -1,
"011": -1,
"100": -1,
"101": -1,
"110": 1,
"111": 1,
}
self.assertEqual(list_out, list_expected)
self.assertEqual(matrix_out, matrix_expected)
self.assertEqual(long_list_out, long_list_expected)
def test_hellinger_fidelity_same(self):
"""Test hellinger fidelity is one for same dist."""
qc = qiskit.QuantumCircuit(5, 5)
qc.h(2)
qc.cx(2, 1)
qc.cx(2, 3)
qc.cx(3, 4)
qc.cx(1, 0)
qc.measure(range(5), range(5))
sim = BasicAer.get_backend("qasm_simulator")
res = qiskit.execute(qc, sim).result()
ans = hellinger_fidelity(res.get_counts(), res.get_counts())
self.assertEqual(ans, 1.0)
def test_hellinger_fidelity_no_overlap(self):
"""Test hellinger fidelity is zero for no overlap."""
# βββββ βββ
# q_0: βββββββββββ€ X βββββββ€Mβββββββββββββ
# ββββββββ¬ββ ββ₯ββββ
# q_1: ββββββ€ X ββββ βββββββββ«ββ€Mββββββββββ
# ββββββββ¬ββ β ββ₯ββββ
# q_2: β€ H ββββ βββββ βββββββββ«βββ«ββ€Mβββββββ
# βββββ βββ΄ββ β β ββ₯ββββ
# q_3: βββββββββββ€ X ββββ ββββ«βββ«βββ«ββ€Mββββ
# ββββββββ΄ββ β β β ββ₯ββββ
# q_4: ββββββββββββββββ€ X βββ«βββ«βββ«βββ«ββ€Mβ
# βββββ β β β β ββ₯β
# c: 5/ββββββββββββββββββββββ©βββ©βββ©βββ©βββ©β
# 0 1 2 3 4
qc = qiskit.QuantumCircuit(5, 5)
qc.h(2)
qc.cx(2, 1)
qc.cx(2, 3)
qc.cx(3, 4)
qc.cx(1, 0)
qc.measure(range(5), range(5))
# βββββ βββ
# q_0: βββββββββββ€ X βββββββ€Mββββββββββ
# ββββββββ¬ββ ββ₯ββββ
# q_1: ββββββ€ X ββββ βββββββββ«ββ€Mβββββββ
# ββββββββ¬βββββββ β ββ₯ββββ
# q_2: β€ H ββββ βββ€ Y ββββ ββββ«βββ«ββ€Mββββ
# βββββ ββββββββ΄ββ β β ββ₯ββββ
# q_3: ββββββββββββββββ€ X βββ«βββ«βββ«ββ€Mβ
# βββ βββββ β β β ββ₯β
# q_4: ββ€Mβββββββββββββββββββ«βββ«βββ«βββ«β
# ββ₯β β β β β
# c: 5/βββ©βββββββββββββββββββ©βββ©βββ©βββ©β
# 4 0 1 2 3
qc2 = qiskit.QuantumCircuit(5, 5)
qc2.h(2)
qc2.cx(2, 1)
qc2.y(2)
qc2.cx(2, 3)
qc2.cx(1, 0)
qc2.measure(range(5), range(5))
sim = BasicAer.get_backend("qasm_simulator")
res1 = qiskit.execute(qc, sim).result()
res2 = qiskit.execute(qc2, sim).result()
ans = hellinger_fidelity(res1.get_counts(), res2.get_counts())
self.assertEqual(ans, 0.0)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Randomized tests of quantum synthesis."""
import unittest
from test.python.quantum_info.test_synthesis import CheckDecompositions
from hypothesis import given, strategies, settings
import numpy as np
from qiskit import execute
from qiskit.circuit import QuantumCircuit, QuantumRegister
from qiskit.extensions import UnitaryGate
from qiskit.providers.basicaer import UnitarySimulatorPy
from qiskit.quantum_info.random import random_unitary
from qiskit.quantum_info.synthesis.two_qubit_decompose import (
two_qubit_cnot_decompose,
TwoQubitBasisDecomposer,
Ud,
)
class TestSynthesis(CheckDecompositions):
"""Test synthesis"""
seed = strategies.integers(min_value=0, max_value=2**32 - 1)
rotation = strategies.floats(min_value=-np.pi * 10, max_value=np.pi * 10)
@given(seed)
def test_1q_random(self, seed):
"""Checks one qubit decompositions"""
unitary = random_unitary(2, seed=seed)
self.check_one_qubit_euler_angles(unitary)
self.check_one_qubit_euler_angles(unitary, "U3")
self.check_one_qubit_euler_angles(unitary, "U1X")
self.check_one_qubit_euler_angles(unitary, "PSX")
self.check_one_qubit_euler_angles(unitary, "ZSX")
self.check_one_qubit_euler_angles(unitary, "ZYZ")
self.check_one_qubit_euler_angles(unitary, "ZXZ")
self.check_one_qubit_euler_angles(unitary, "XYX")
self.check_one_qubit_euler_angles(unitary, "RR")
@settings(deadline=None)
@given(seed)
def test_2q_random(self, seed):
"""Checks two qubit decompositions"""
unitary = random_unitary(4, seed=seed)
self.check_exact_decomposition(unitary.data, two_qubit_cnot_decompose)
@given(strategies.tuples(*[seed] * 5))
def test_exact_supercontrolled_decompose_random(self, seeds):
"""Exact decomposition for random supercontrolled basis and random target"""
k1 = np.kron(random_unitary(2, seed=seeds[0]).data, random_unitary(2, seed=seeds[1]).data)
k2 = np.kron(random_unitary(2, seed=seeds[2]).data, random_unitary(2, seed=seeds[3]).data)
basis_unitary = k1 @ Ud(np.pi / 4, 0, 0) @ k2
decomposer = TwoQubitBasisDecomposer(UnitaryGate(basis_unitary))
self.check_exact_decomposition(random_unitary(4, seed=seeds[4]).data, decomposer)
@given(strategies.tuples(*[rotation] * 6), seed)
def test_cx_equivalence_0cx_random(self, rnd, seed):
"""Check random circuits with 0 cx gates locally equivalent to identity."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 0)
@given(strategies.tuples(*[rotation] * 12), seed)
def test_cx_equivalence_1cx_random(self, rnd, seed):
"""Check random circuits with 1 cx gates locally equivalent to a cx."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[6], rnd[7], rnd[8], qr[0])
qc.u(rnd[9], rnd[10], rnd[11], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 1)
@given(strategies.tuples(*[rotation] * 18), seed)
def test_cx_equivalence_2cx_random(self, rnd, seed):
"""Check random circuits with 2 cx gates locally equivalent to some circuit with 2 cx."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[6], rnd[7], rnd[8], qr[0])
qc.u(rnd[9], rnd[10], rnd[11], qr[1])
qc.cx(qr[0], qr[1])
qc.u(rnd[12], rnd[13], rnd[14], qr[0])
qc.u(rnd[15], rnd[16], rnd[17], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 2)
@given(strategies.tuples(*[rotation] * 24), seed)
def test_cx_equivalence_3cx_random(self, rnd, seed):
"""Check random circuits with 3 cx gates are outside the 0, 1, and 2 qubit regions."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[6], rnd[7], rnd[8], qr[0])
qc.u(rnd[9], rnd[10], rnd[11], qr[1])
qc.cx(qr[0], qr[1])
qc.u(rnd[12], rnd[13], rnd[14], qr[0])
qc.u(rnd[15], rnd[16], rnd[17], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[18], rnd[19], rnd[20], qr[0])
qc.u(rnd[21], rnd[22], rnd[23], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 3)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""Tests for Operator matrix linear operator class."""
import unittest
import logging
import copy
from test import combine
import numpy as np
from ddt import ddt
from numpy.testing import assert_allclose
import scipy.linalg as la
from qiskit import QiskitError
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit.library import HGate, CHGate, CXGate, QFT
from qiskit.test import QiskitTestCase
from qiskit.transpiler.layout import Layout, TranspileLayout
from qiskit.quantum_info.operators import Operator, ScalarOp
from qiskit.quantum_info.operators.predicates import matrix_equal
from qiskit.compiler.transpiler import transpile
from qiskit.circuit import Qubit
from qiskit.circuit.library import Permutation, PermutationGate
logger = logging.getLogger(__name__)
class OperatorTestCase(QiskitTestCase):
"""Test utils for Operator"""
# Pauli-matrix unitaries
UI = np.eye(2)
UX = np.array([[0, 1], [1, 0]])
UY = np.array([[0, -1j], [1j, 0]])
UZ = np.diag([1, -1])
UH = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
@classmethod
def rand_rho(cls, n):
"""Return random density matrix"""
seed = np.random.randint(0, np.iinfo(np.int32).max)
logger.debug("rand_rho default_rng seeded with seed=%s", seed)
rng = np.random.default_rng(seed)
psi = rng.random(n) + 1j * rng.random(n)
rho = np.outer(psi, psi.conj())
rho /= np.trace(rho)
return rho
@classmethod
def rand_matrix(cls, rows, cols=None, real=False):
"""Return a random matrix."""
seed = np.random.randint(0, np.iinfo(np.int32).max)
logger.debug("rand_matrix default_rng seeded with seed=%s", seed)
rng = np.random.default_rng(seed)
if cols is None:
cols = rows
if real:
return rng.random(size=(rows, cols))
return rng.random(size=(rows, cols)) + 1j * rng.random(size=(rows, cols))
def simple_circuit_no_measure(self):
"""Return a unitary circuit and the corresponding unitary array."""
qr = QuantumRegister(3)
circ = QuantumCircuit(qr)
circ.h(qr[0])
circ.x(qr[1])
circ.ry(np.pi / 2, qr[2])
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = Operator(np.kron(y90, np.kron(self.UX, self.UH)))
return circ, target
def simple_circuit_with_measure(self):
"""Return a unitary circuit with measurement."""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circ = QuantumCircuit(qr, cr)
circ.h(qr[0])
circ.x(qr[1])
circ.measure(qr, cr)
return circ
@ddt
class TestOperator(OperatorTestCase):
"""Tests for Operator linear operator class."""
def test_init_array_qubit(self):
"""Test subsystem initialization from N-qubit array."""
# Test automatic inference of qubit subsystems
mat = self.rand_matrix(8, 8)
op = Operator(mat)
assert_allclose(op.data, mat)
self.assertEqual(op.dim, (8, 8))
self.assertEqual(op.input_dims(), (2, 2, 2))
self.assertEqual(op.output_dims(), (2, 2, 2))
self.assertEqual(op.num_qubits, 3)
op = Operator(mat, input_dims=8, output_dims=8)
assert_allclose(op.data, mat)
self.assertEqual(op.dim, (8, 8))
self.assertEqual(op.input_dims(), (2, 2, 2))
self.assertEqual(op.output_dims(), (2, 2, 2))
self.assertEqual(op.num_qubits, 3)
def test_init_array(self):
"""Test initialization from array."""
mat = np.eye(3)
op = Operator(mat)
assert_allclose(op.data, mat)
self.assertEqual(op.dim, (3, 3))
self.assertEqual(op.input_dims(), (3,))
self.assertEqual(op.output_dims(), (3,))
self.assertIsNone(op.num_qubits)
mat = self.rand_matrix(2 * 3 * 4, 4 * 5)
op = Operator(mat, input_dims=[4, 5], output_dims=[2, 3, 4])
assert_allclose(op.data, mat)
self.assertEqual(op.dim, (4 * 5, 2 * 3 * 4))
self.assertEqual(op.input_dims(), (4, 5))
self.assertEqual(op.output_dims(), (2, 3, 4))
self.assertIsNone(op.num_qubits)
def test_init_array_except(self):
"""Test initialization exception from array."""
mat = self.rand_matrix(4, 4)
self.assertRaises(QiskitError, Operator, mat, input_dims=[4, 2])
self.assertRaises(QiskitError, Operator, mat, input_dims=[2, 4])
self.assertRaises(QiskitError, Operator, mat, input_dims=5)
def test_init_operator(self):
"""Test initialization from Operator."""
op1 = Operator(self.rand_matrix(4, 4))
op2 = Operator(op1)
self.assertEqual(op1, op2)
def test_circuit_init(self):
"""Test initialization from a circuit."""
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.x(1)
circuit.ry(np.pi / 2, 2)
op = Operator(circuit)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of Controlled-Phase gate
lam = np.pi / 4
circuit = QuantumCircuit(2)
circuit.cp(lam, 0, 1)
op = Operator(circuit)
target = np.diag([1, 1, 1, np.exp(1j * lam)])
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of controlled-H gate
circuit = QuantumCircuit(2)
circuit.ch(0, 1)
op = Operator(circuit)
target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1]))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_instruction_init(self):
"""Test initialization from a circuit."""
gate = CXGate()
op = Operator(gate).data
target = gate.to_matrix()
global_phase_equivalent = matrix_equal(op, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
gate = CHGate()
op = Operator(gate).data
had = HGate().to_matrix()
target = np.kron(had, np.diag([0, 1])) + np.kron(np.eye(2), np.diag([1, 0]))
global_phase_equivalent = matrix_equal(op, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_circuit_init_except(self):
"""Test initialization from circuit with measure raises exception."""
circuit = self.simple_circuit_with_measure()
self.assertRaises(QiskitError, Operator, circuit)
def test_equal(self):
"""Test __eq__ method"""
mat = self.rand_matrix(2, 2, real=True)
self.assertEqual(Operator(np.array(mat, dtype=complex)), Operator(mat))
mat = self.rand_matrix(4, 4)
self.assertEqual(Operator(mat.tolist()), Operator(mat))
def test_data(self):
"""Test Operator representation string property."""
mat = self.rand_matrix(2, 2)
op = Operator(mat)
assert_allclose(mat, op.data)
def test_to_matrix(self):
"""Test Operator to_matrix method."""
mat = self.rand_matrix(2, 2)
op = Operator(mat)
assert_allclose(mat, op.to_matrix())
def test_dim(self):
"""Test Operator dim property."""
mat = self.rand_matrix(4, 4)
self.assertEqual(Operator(mat).dim, (4, 4))
self.assertEqual(Operator(mat, input_dims=[4], output_dims=[4]).dim, (4, 4))
self.assertEqual(Operator(mat, input_dims=[2, 2], output_dims=[2, 2]).dim, (4, 4))
def test_input_dims(self):
"""Test Operator input_dims method."""
op = Operator(self.rand_matrix(2 * 3 * 4, 4 * 5), input_dims=[4, 5], output_dims=[2, 3, 4])
self.assertEqual(op.input_dims(), (4, 5))
self.assertEqual(op.input_dims(qargs=[0, 1]), (4, 5))
self.assertEqual(op.input_dims(qargs=[1, 0]), (5, 4))
self.assertEqual(op.input_dims(qargs=[0]), (4,))
self.assertEqual(op.input_dims(qargs=[1]), (5,))
def test_output_dims(self):
"""Test Operator output_dims method."""
op = Operator(self.rand_matrix(2 * 3 * 4, 4 * 5), input_dims=[4, 5], output_dims=[2, 3, 4])
self.assertEqual(op.output_dims(), (2, 3, 4))
self.assertEqual(op.output_dims(qargs=[0, 1, 2]), (2, 3, 4))
self.assertEqual(op.output_dims(qargs=[2, 1, 0]), (4, 3, 2))
self.assertEqual(op.output_dims(qargs=[2, 0, 1]), (4, 2, 3))
self.assertEqual(op.output_dims(qargs=[0]), (2,))
self.assertEqual(op.output_dims(qargs=[1]), (3,))
self.assertEqual(op.output_dims(qargs=[2]), (4,))
self.assertEqual(op.output_dims(qargs=[0, 2]), (2, 4))
self.assertEqual(op.output_dims(qargs=[2, 0]), (4, 2))
def test_reshape(self):
"""Test Operator reshape method."""
op = Operator(self.rand_matrix(8, 8))
reshaped1 = op.reshape(input_dims=[8], output_dims=[8])
reshaped2 = op.reshape(input_dims=[4, 2], output_dims=[2, 4])
self.assertEqual(op.output_dims(), (2, 2, 2))
self.assertEqual(op.input_dims(), (2, 2, 2))
self.assertEqual(reshaped1.output_dims(), (8,))
self.assertEqual(reshaped1.input_dims(), (8,))
self.assertEqual(reshaped2.output_dims(), (2, 4))
self.assertEqual(reshaped2.input_dims(), (4, 2))
def test_reshape_num_qubits(self):
"""Test Operator reshape method with num_qubits."""
op = Operator(self.rand_matrix(8, 8), input_dims=(4, 2), output_dims=(2, 4))
reshaped = op.reshape(num_qubits=3)
self.assertEqual(reshaped.num_qubits, 3)
self.assertEqual(reshaped.output_dims(), (2, 2, 2))
self.assertEqual(reshaped.input_dims(), (2, 2, 2))
def test_reshape_raise(self):
"""Test Operator reshape method with invalid args."""
op = Operator(self.rand_matrix(3, 3))
self.assertRaises(QiskitError, op.reshape, num_qubits=2)
def test_copy(self):
"""Test Operator copy method"""
mat = np.eye(2)
with self.subTest("Deep copy"):
orig = Operator(mat)
cpy = orig.copy()
cpy._data[0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = Operator(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_is_unitary(self):
"""Test is_unitary method."""
# X-90 rotation
X90 = la.expm(-1j * 0.5 * np.pi * np.array([[0, 1], [1, 0]]) / 2)
self.assertTrue(Operator(X90).is_unitary())
# Non-unitary should return false
self.assertFalse(Operator([[1, 0], [0, 0]]).is_unitary())
def test_to_operator(self):
"""Test to_operator method."""
op1 = Operator(self.rand_matrix(4, 4))
op2 = op1.to_operator()
self.assertEqual(op1, op2)
def test_conjugate(self):
"""Test conjugate method."""
matr = self.rand_matrix(2, 4, real=True)
mati = self.rand_matrix(2, 4, real=True)
op = Operator(matr + 1j * mati)
uni_conj = op.conjugate()
self.assertEqual(uni_conj, Operator(matr - 1j * mati))
def test_transpose(self):
"""Test transpose method."""
matr = self.rand_matrix(2, 4, real=True)
mati = self.rand_matrix(2, 4, real=True)
op = Operator(matr + 1j * mati)
uni_t = op.transpose()
self.assertEqual(uni_t, Operator(matr.T + 1j * mati.T))
def test_adjoint(self):
"""Test adjoint method."""
matr = self.rand_matrix(2, 4, real=True)
mati = self.rand_matrix(2, 4, real=True)
op = Operator(matr + 1j * mati)
uni_adj = op.adjoint()
self.assertEqual(uni_adj, Operator(matr.T - 1j * mati.T))
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError, Operator(np.eye(2)).compose, Operator(np.eye(3)))
self.assertRaises(QiskitError, Operator(np.eye(2)).compose, 2)
def test_compose(self):
"""Test compose method."""
op1 = Operator(self.UX)
op2 = Operator(self.UY)
targ = Operator(np.dot(self.UY, self.UX))
self.assertEqual(op1.compose(op2), targ)
self.assertEqual(op1 & op2, targ)
targ = Operator(np.dot(self.UX, self.UY))
self.assertEqual(op2.compose(op1), targ)
self.assertEqual(op2 & op1, targ)
def test_dot(self):
"""Test dot method."""
op1 = Operator(self.UY)
op2 = Operator(self.UX)
targ = Operator(np.dot(self.UY, self.UX))
self.assertEqual(op1.dot(op2), targ)
self.assertEqual(op1 @ op2, targ)
targ = Operator(np.dot(self.UX, self.UY))
self.assertEqual(op2.dot(op1), targ)
self.assertEqual(op2 @ op1, targ)
def test_compose_front(self):
"""Test front compose method."""
opYX = Operator(self.UY).compose(Operator(self.UX), front=True)
matYX = np.dot(self.UY, self.UX)
self.assertEqual(opYX, Operator(matYX))
opXY = Operator(self.UX).compose(Operator(self.UY), front=True)
matXY = np.dot(self.UX, self.UY)
self.assertEqual(opXY, Operator(matXY))
def test_compose_subsystem(self):
"""Test subsystem compose method."""
# 3-qubit operator
mat = self.rand_matrix(8, 8)
mat_a = self.rand_matrix(2, 2)
mat_b = self.rand_matrix(2, 2)
mat_c = self.rand_matrix(2, 2)
op = Operator(mat)
op1 = Operator(mat_a)
op2 = Operator(np.kron(mat_b, mat_a))
op3 = Operator(np.kron(mat_c, np.kron(mat_b, mat_a)))
# op3 qargs=[0, 1, 2]
targ = np.dot(np.kron(mat_c, np.kron(mat_b, mat_a)), mat)
self.assertEqual(op.compose(op3, qargs=[0, 1, 2]), Operator(targ))
self.assertEqual(op.compose(op3([0, 1, 2])), Operator(targ))
self.assertEqual(op & op3([0, 1, 2]), Operator(targ))
# op3 qargs=[2, 1, 0]
targ = np.dot(np.kron(mat_a, np.kron(mat_b, mat_c)), mat)
self.assertEqual(op.compose(op3, qargs=[2, 1, 0]), Operator(targ))
self.assertEqual(op & op3([2, 1, 0]), Operator(targ))
# op2 qargs=[0, 1]
targ = np.dot(np.kron(np.eye(2), np.kron(mat_b, mat_a)), mat)
self.assertEqual(op.compose(op2, qargs=[0, 1]), Operator(targ))
self.assertEqual(op & op2([0, 1]), Operator(targ))
# op2 qargs=[2, 0]
targ = np.dot(np.kron(mat_a, np.kron(np.eye(2), mat_b)), mat)
self.assertEqual(op.compose(op2, qargs=[2, 0]), Operator(targ))
self.assertEqual(op & op2([2, 0]), Operator(targ))
# op1 qargs=[0]
targ = np.dot(np.kron(np.eye(4), mat_a), mat)
self.assertEqual(op.compose(op1, qargs=[0]), Operator(targ))
self.assertEqual(op & op1([0]), Operator(targ))
# op1 qargs=[1]
targ = np.dot(np.kron(np.eye(2), np.kron(mat_a, np.eye(2))), mat)
self.assertEqual(op.compose(op1, qargs=[1]), Operator(targ))
self.assertEqual(op & op1([1]), Operator(targ))
# op1 qargs=[2]
targ = np.dot(np.kron(mat_a, np.eye(4)), mat)
self.assertEqual(op.compose(op1, qargs=[2]), Operator(targ))
self.assertEqual(op & op1([2]), Operator(targ))
def test_dot_subsystem(self):
"""Test subsystem dot method."""
# 3-qubit operator
mat = self.rand_matrix(8, 8)
mat_a = self.rand_matrix(2, 2)
mat_b = self.rand_matrix(2, 2)
mat_c = self.rand_matrix(2, 2)
op = Operator(mat)
op1 = Operator(mat_a)
op2 = Operator(np.kron(mat_b, mat_a))
op3 = Operator(np.kron(mat_c, np.kron(mat_b, mat_a)))
# op3 qargs=[0, 1, 2]
targ = np.dot(mat, np.kron(mat_c, np.kron(mat_b, mat_a)))
self.assertEqual(op.dot(op3, qargs=[0, 1, 2]), Operator(targ))
self.assertEqual(op.dot(op3([0, 1, 2])), Operator(targ))
# op3 qargs=[2, 1, 0]
targ = np.dot(mat, np.kron(mat_a, np.kron(mat_b, mat_c)))
self.assertEqual(op.dot(op3, qargs=[2, 1, 0]), Operator(targ))
self.assertEqual(op.dot(op3([2, 1, 0])), Operator(targ))
# op2 qargs=[0, 1]
targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_b, mat_a)))
self.assertEqual(op.dot(op2, qargs=[0, 1]), Operator(targ))
self.assertEqual(op.dot(op2([0, 1])), Operator(targ))
# op2 qargs=[2, 0]
targ = np.dot(mat, np.kron(mat_a, np.kron(np.eye(2), mat_b)))
self.assertEqual(op.dot(op2, qargs=[2, 0]), Operator(targ))
self.assertEqual(op.dot(op2([2, 0])), Operator(targ))
# op1 qargs=[0]
targ = np.dot(mat, np.kron(np.eye(4), mat_a))
self.assertEqual(op.dot(op1, qargs=[0]), Operator(targ))
self.assertEqual(op.dot(op1([0])), Operator(targ))
# op1 qargs=[1]
targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_a, np.eye(2))))
self.assertEqual(op.dot(op1, qargs=[1]), Operator(targ))
self.assertEqual(op.dot(op1([1])), Operator(targ))
# op1 qargs=[2]
targ = np.dot(mat, np.kron(mat_a, np.eye(4)))
self.assertEqual(op.dot(op1, qargs=[2]), Operator(targ))
self.assertEqual(op.dot(op1([2])), Operator(targ))
def test_compose_front_subsystem(self):
"""Test subsystem front compose method."""
# 3-qubit operator
mat = self.rand_matrix(8, 8)
mat_a = self.rand_matrix(2, 2)
mat_b = self.rand_matrix(2, 2)
mat_c = self.rand_matrix(2, 2)
op = Operator(mat)
op1 = Operator(mat_a)
op2 = Operator(np.kron(mat_b, mat_a))
op3 = Operator(np.kron(mat_c, np.kron(mat_b, mat_a)))
# op3 qargs=[0, 1, 2]
targ = np.dot(mat, np.kron(mat_c, np.kron(mat_b, mat_a)))
self.assertEqual(op.compose(op3, qargs=[0, 1, 2], front=True), Operator(targ))
# op3 qargs=[2, 1, 0]
targ = np.dot(mat, np.kron(mat_a, np.kron(mat_b, mat_c)))
self.assertEqual(op.compose(op3, qargs=[2, 1, 0], front=True), Operator(targ))
# op2 qargs=[0, 1]
targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_b, mat_a)))
self.assertEqual(op.compose(op2, qargs=[0, 1], front=True), Operator(targ))
# op2 qargs=[2, 0]
targ = np.dot(mat, np.kron(mat_a, np.kron(np.eye(2), mat_b)))
self.assertEqual(op.compose(op2, qargs=[2, 0], front=True), Operator(targ))
# op1 qargs=[0]
targ = np.dot(mat, np.kron(np.eye(4), mat_a))
self.assertEqual(op.compose(op1, qargs=[0], front=True), Operator(targ))
# op1 qargs=[1]
targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_a, np.eye(2))))
self.assertEqual(op.compose(op1, qargs=[1], front=True), Operator(targ))
# op1 qargs=[2]
targ = np.dot(mat, np.kron(mat_a, np.eye(4)))
self.assertEqual(op.compose(op1, qargs=[2], front=True), Operator(targ))
def test_power(self):
"""Test power method."""
X90 = la.expm(-1j * 0.5 * np.pi * np.array([[0, 1], [1, 0]]) / 2)
op = Operator(X90)
self.assertEqual(op.power(2), Operator([[0, -1j], [-1j, 0]]))
self.assertEqual(op.power(4), Operator(-1 * np.eye(2)))
self.assertEqual(op.power(8), Operator(np.eye(2)))
def test_expand(self):
"""Test expand method."""
mat1 = self.UX
mat2 = np.eye(3, dtype=complex)
mat21 = np.kron(mat2, mat1)
op21 = Operator(mat1).expand(Operator(mat2))
self.assertEqual(op21.dim, (6, 6))
assert_allclose(op21.data, Operator(mat21).data)
mat12 = np.kron(mat1, mat2)
op12 = Operator(mat2).expand(Operator(mat1))
self.assertEqual(op12.dim, (6, 6))
assert_allclose(op12.data, Operator(mat12).data)
def test_tensor(self):
"""Test tensor method."""
mat1 = self.UX
mat2 = np.eye(3, dtype=complex)
mat21 = np.kron(mat2, mat1)
op21 = Operator(mat2).tensor(Operator(mat1))
self.assertEqual(op21.dim, (6, 6))
assert_allclose(op21.data, Operator(mat21).data)
mat12 = np.kron(mat1, mat2)
op12 = Operator(mat1).tensor(Operator(mat2))
self.assertEqual(op12.dim, (6, 6))
assert_allclose(op12.data, Operator(mat12).data)
def test_power_except(self):
"""Test power method raises exceptions if not square."""
op = Operator(self.rand_matrix(2, 3))
# Non-integer power raises error
self.assertRaises(QiskitError, op.power, 0.5)
def test_add(self):
"""Test add method."""
mat1 = self.rand_matrix(4, 4)
mat2 = self.rand_matrix(4, 4)
op1 = Operator(mat1)
op2 = Operator(mat2)
self.assertEqual(op1._add(op2), Operator(mat1 + mat2))
self.assertEqual(op1 + op2, Operator(mat1 + mat2))
self.assertEqual(op1 - op2, Operator(mat1 - mat2))
def test_add_except(self):
"""Test add method raises exceptions."""
op1 = Operator(self.rand_matrix(2, 2))
op2 = Operator(self.rand_matrix(3, 3))
self.assertRaises(QiskitError, op1._add, op2)
def test_add_qargs(self):
"""Test add method with qargs."""
mat = self.rand_matrix(8, 8)
mat0 = self.rand_matrix(2, 2)
mat1 = self.rand_matrix(2, 2)
op = Operator(mat)
op0 = Operator(mat0)
op01 = Operator(np.kron(mat1, mat0))
with self.subTest(msg="qargs=[0]"):
value = op + op0([0])
target = op + Operator(np.kron(np.eye(4), mat0))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op + op0([1])
target = op + Operator(np.kron(np.kron(np.eye(2), mat0), np.eye(2)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op + op0([2])
target = op + Operator(np.kron(mat0, np.eye(4)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op + op01([0, 1])
target = op + Operator(np.kron(np.eye(2), np.kron(mat1, mat0)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op + op01([1, 0])
target = op + Operator(np.kron(np.eye(2), np.kron(mat0, mat1)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op + op01([0, 2])
target = op + Operator(np.kron(mat1, np.kron(np.eye(2), mat0)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op + op01([2, 0])
target = op + Operator(np.kron(mat0, np.kron(np.eye(2), mat1)))
self.assertEqual(value, target)
def test_sub_qargs(self):
"""Test subtract method with qargs."""
mat = self.rand_matrix(8, 8)
mat0 = self.rand_matrix(2, 2)
mat1 = self.rand_matrix(2, 2)
op = Operator(mat)
op0 = Operator(mat0)
op01 = Operator(np.kron(mat1, mat0))
with self.subTest(msg="qargs=[0]"):
value = op - op0([0])
target = op - Operator(np.kron(np.eye(4), mat0))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op - op0([1])
target = op - Operator(np.kron(np.kron(np.eye(2), mat0), np.eye(2)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op - op0([2])
target = op - Operator(np.kron(mat0, np.eye(4)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op - op01([0, 1])
target = op - Operator(np.kron(np.eye(2), np.kron(mat1, mat0)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op - op01([1, 0])
target = op - Operator(np.kron(np.eye(2), np.kron(mat0, mat1)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op - op01([0, 2])
target = op - Operator(np.kron(mat1, np.kron(np.eye(2), mat0)))
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op - op01([2, 0])
target = op - Operator(np.kron(mat0, np.kron(np.eye(2), mat1)))
self.assertEqual(value, target)
def test_multiply(self):
"""Test multiply method."""
mat = self.rand_matrix(4, 4)
val = np.exp(5j)
op = Operator(mat)
self.assertEqual(op._multiply(val), Operator(val * mat))
self.assertEqual(val * op, Operator(val * mat))
self.assertEqual(op * val, Operator(mat * val))
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
op = Operator(self.rand_matrix(2, 2))
self.assertRaises(QiskitError, op._multiply, "s")
self.assertRaises(QiskitError, op.__rmul__, "s")
self.assertRaises(QiskitError, op._multiply, op)
self.assertRaises(QiskitError, op.__rmul__, op)
def test_negate(self):
"""Test negate method"""
mat = self.rand_matrix(4, 4)
op = Operator(mat)
self.assertEqual(-op, Operator(-1 * mat))
def test_equiv(self):
"""Test negate method"""
mat = np.diag([1, np.exp(1j * np.pi / 2)])
phase = np.exp(-1j * np.pi / 4)
op = Operator(mat)
self.assertTrue(op.equiv(phase * mat))
self.assertTrue(op.equiv(Operator(phase * mat)))
self.assertFalse(op.equiv(2 * mat))
def test_reverse_qargs(self):
"""Test reverse_qargs method"""
circ1 = QFT(5)
circ2 = circ1.reverse_bits()
state1 = Operator(circ1)
state2 = Operator(circ2)
self.assertEqual(state1.reverse_qargs(), state2)
def test_drawings(self):
"""Test draw method"""
qc1 = QFT(5)
op = Operator.from_circuit(qc1)
with self.subTest(msg="str(operator)"):
str(op)
for drawtype in ["repr", "text", "latex_source"]:
with self.subTest(msg=f"draw('{drawtype}')"):
op.draw(drawtype)
with self.subTest(msg=" draw('latex')"):
op.draw("latex")
def test_from_circuit_constructor_no_layout(self):
"""Test initialization from a circuit using the from_circuit constructor."""
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.x(1)
circuit.ry(np.pi / 2, 2)
op = Operator.from_circuit(circuit)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of Controlled-Phase gate
lam = np.pi / 4
circuit = QuantumCircuit(2)
circuit.cp(lam, 0, 1)
op = Operator.from_circuit(circuit)
target = np.diag([1, 1, 1, np.exp(1j * lam)])
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of controlled-H gate
circuit = QuantumCircuit(2)
circuit.ch(0, 1)
op = Operator.from_circuit(circuit)
target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1]))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_reverse_embedded_layout(self):
"""Test initialization from a circuit with an embedded reverse layout."""
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(2)
circuit.x(1)
circuit.ry(np.pi / 2, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
op = Operator.from_circuit(circuit)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of Controlled-Phase gate
lam = np.pi / 4
circuit = QuantumCircuit(2)
circuit.cp(lam, 1, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
op = Operator.from_circuit(circuit)
target = np.diag([1, 1, 1, np.exp(1j * lam)])
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of controlled-H gate
circuit = QuantumCircuit(2)
circuit.ch(1, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
op = Operator.from_circuit(circuit)
target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1]))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_reverse_embedded_layout_from_transpile(self):
"""Test initialization from a circuit with an embedded final layout."""
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.x(1)
circuit.ry(np.pi / 2, 2)
output = transpile(circuit, initial_layout=[2, 1, 0])
op = Operator.from_circuit(output)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_reverse_embedded_layout_from_transpile_with_registers(self):
"""Test initialization from a circuit with an embedded final layout."""
# Test tensor product of 1-qubit gates
qr = QuantumRegister(3, name="test_reg")
circuit = QuantumCircuit(qr)
circuit.h(0)
circuit.x(1)
circuit.ry(np.pi / 2, 2)
output = transpile(circuit, initial_layout=[2, 1, 0])
op = Operator.from_circuit(output)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_reverse_embedded_layout_and_final_layout(self):
"""Test initialization from a circuit with an embedded final layout."""
# Test tensor product of 1-qubit gates
qr = QuantumRegister(3, name="test_reg")
circuit = QuantumCircuit(qr)
circuit.h(2)
circuit.x(1)
circuit.ry(np.pi / 2, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
Layout({circuit.qubits[0]: 1, circuit.qubits[1]: 2, circuit.qubits[2]: 0}),
)
circuit.swap(0, 1)
circuit.swap(1, 2)
op = Operator.from_circuit(circuit)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_reverse_embedded_layout_and_manual_final_layout(self):
"""Test initialization from a circuit with an embedded final layout."""
# Test tensor product of 1-qubit gates
qr = QuantumRegister(3, name="test_reg")
circuit = QuantumCircuit(qr)
circuit.h(2)
circuit.x(1)
circuit.ry(np.pi / 2, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
final_layout = Layout({circuit.qubits[0]: 1, circuit.qubits[1]: 2, circuit.qubits[2]: 0})
circuit.swap(0, 1)
circuit.swap(1, 2)
op = Operator.from_circuit(circuit, final_layout=final_layout)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_reverse_embedded_layout_ignore_set_layout(self):
"""Test initialization from a circuit with an ignored embedded reverse layout."""
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(2)
circuit.x(1)
circuit.ry(np.pi / 2, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
op = Operator.from_circuit(circuit, ignore_set_layout=True).reverse_qargs()
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of Controlled-Phase gate
lam = np.pi / 4
circuit = QuantumCircuit(2)
circuit.cp(lam, 1, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
op = Operator.from_circuit(circuit, ignore_set_layout=True).reverse_qargs()
target = np.diag([1, 1, 1, np.exp(1j * lam)])
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of controlled-H gate
circuit = QuantumCircuit(2)
circuit.ch(1, 0)
circuit._layout = TranspileLayout(
Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
op = Operator.from_circuit(circuit, ignore_set_layout=True).reverse_qargs()
target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1]))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_reverse_user_specified_layout(self):
"""Test initialization from a circuit with a user specified reverse layout."""
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(2)
circuit.x(1)
circuit.ry(np.pi / 2, 0)
layout = Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2})
op = Operator.from_circuit(circuit, layout=layout)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = np.kron(y90, np.kron(self.UX, self.UH))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of Controlled-Phase gate
lam = np.pi / 4
circuit = QuantumCircuit(2)
circuit.cp(lam, 1, 0)
layout = Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1})
op = Operator.from_circuit(circuit, layout=layout)
target = np.diag([1, 1, 1, np.exp(1j * lam)])
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
# Test decomposition of controlled-H gate
circuit = QuantumCircuit(2)
circuit.ch(1, 0)
layout = Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1})
op = Operator.from_circuit(circuit, layout=layout)
target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1]))
global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_circuit_constructor_ghz_out_of_order_layout(self):
"""Test an out of order ghz state with a layout set."""
circuit = QuantumCircuit(5)
circuit.h(3)
circuit.cx(3, 4)
circuit.cx(3, 2)
circuit.cx(3, 0)
circuit.cx(3, 1)
circuit._layout = TranspileLayout(
Layout(
{
circuit.qubits[3]: 0,
circuit.qubits[4]: 1,
circuit.qubits[2]: 2,
circuit.qubits[0]: 3,
circuit.qubits[1]: 4,
}
),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
result = Operator.from_circuit(circuit)
expected = QuantumCircuit(5)
expected.h(0)
expected.cx(0, 1)
expected.cx(0, 2)
expected.cx(0, 3)
expected.cx(0, 4)
expected_op = Operator(expected)
self.assertTrue(expected_op.equiv(result))
def test_from_circuit_empty_circuit_empty_layout(self):
"""Test an out of order ghz state with a layout set."""
circuit = QuantumCircuit()
circuit._layout = TranspileLayout(Layout(), {})
op = Operator.from_circuit(circuit)
self.assertEqual(Operator([1]), op)
def test_from_circuit_constructor_empty_layout(self):
"""Test an out of order ghz state with a layout set."""
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0, 1)
layout = Layout()
with self.assertRaises(IndexError):
Operator.from_circuit(circuit, layout=layout)
def test_compose_scalar(self):
"""Test that composition works with a scalar-valued operator over no qubits."""
base = Operator(np.eye(2, dtype=np.complex128))
scalar = Operator(np.array([[-1.0 + 0.0j]]))
composed = base.compose(scalar, qargs=[])
self.assertEqual(composed, Operator(-np.eye(2, dtype=np.complex128)))
def test_compose_scalar_op(self):
"""Test that composition works with an explicit scalar operator over no qubits."""
base = Operator(np.eye(2, dtype=np.complex128))
scalar = ScalarOp(coeff=-1.0 + 0.0j)
composed = base.compose(scalar, qargs=[])
self.assertEqual(composed, Operator(-np.eye(2, dtype=np.complex128)))
def test_from_circuit_single_flat_default_register_transpiled(self):
"""Test a transpiled circuit with layout set from default register."""
circuit = QuantumCircuit(5)
circuit.h(3)
circuit.cx(3, 4)
circuit.cx(3, 2)
circuit.cx(3, 0)
circuit.cx(3, 1)
init_layout = Layout(
{
circuit.qubits[0]: 3,
circuit.qubits[1]: 4,
circuit.qubits[2]: 1,
circuit.qubits[3]: 2,
circuit.qubits[4]: 0,
}
)
tqc = transpile(circuit, initial_layout=init_layout)
result = Operator.from_circuit(tqc)
self.assertTrue(Operator.from_circuit(circuit).equiv(result))
def test_from_circuit_loose_bits_transpiled(self):
"""Test a transpiled circuit with layout set from loose bits."""
bits = [Qubit() for _ in range(5)]
circuit = QuantumCircuit()
circuit.add_bits(bits)
circuit.h(3)
circuit.cx(3, 4)
circuit.cx(3, 2)
circuit.cx(3, 0)
circuit.cx(3, 1)
init_layout = Layout(
{
circuit.qubits[0]: 3,
circuit.qubits[1]: 4,
circuit.qubits[2]: 1,
circuit.qubits[3]: 2,
circuit.qubits[4]: 0,
}
)
tqc = transpile(circuit, initial_layout=init_layout)
result = Operator.from_circuit(tqc)
self.assertTrue(Operator(circuit).equiv(result))
def test_from_circuit_multiple_registers_bits_transpiled(self):
"""Test a transpiled circuit with layout set from loose bits."""
regs = [QuantumRegister(1, name=f"custom_reg-{i}") for i in range(5)]
circuit = QuantumCircuit()
for reg in regs:
circuit.add_register(reg)
circuit.h(3)
circuit.cx(3, 4)
circuit.cx(3, 2)
circuit.cx(3, 0)
circuit.cx(3, 1)
tqc = transpile(circuit, initial_layout=[3, 4, 1, 2, 0])
result = Operator.from_circuit(tqc)
self.assertTrue(Operator(circuit).equiv(result))
def test_from_circuit_single_flat_custom_register_transpiled(self):
"""Test a transpiled circuit with layout set from loose bits."""
circuit = QuantumCircuit(QuantumRegister(5, name="custom_reg"))
circuit.h(3)
circuit.cx(3, 4)
circuit.cx(3, 2)
circuit.cx(3, 0)
circuit.cx(3, 1)
tqc = transpile(circuit, initial_layout=[3, 4, 1, 2, 0])
result = Operator.from_circuit(tqc)
self.assertTrue(Operator(circuit).equiv(result))
def test_from_circuit_mixed_reg_loose_bits_transpiled(self):
"""Test a transpiled circuit with layout set from loose bits."""
bits = [Qubit(), Qubit()]
circuit = QuantumCircuit()
circuit.add_bits(bits)
circuit.add_register(QuantumRegister(3, name="a_reg"))
circuit.h(3)
circuit.cx(3, 4)
circuit.cx(3, 2)
circuit.cx(3, 0)
circuit.cx(3, 1)
init_layout = Layout(
{
circuit.qubits[0]: 3,
circuit.qubits[1]: 4,
circuit.qubits[2]: 1,
circuit.qubits[3]: 2,
circuit.qubits[4]: 0,
}
)
tqc = transpile(circuit, initial_layout=init_layout)
result = Operator.from_circuit(tqc)
self.assertTrue(Operator(circuit).equiv(result))
def test_apply_permutation_back(self):
"""Test applying permutation to the operator,
where the operator is applied first and the permutation second."""
op = Operator(self.rand_matrix(64, 64))
pattern = [1, 2, 0, 3, 5, 4]
# Consider several methods of computing this operator and show
# they all lead to the same result.
# Compose the operator with the operator constructed from the
# permutation circuit.
op2 = op.copy()
perm_op = Operator(Permutation(6, pattern))
op2 &= perm_op
# Compose the operator with the operator constructed from the
# permutation gate.
op3 = op.copy()
perm_op = Operator(PermutationGate(pattern))
op3 &= perm_op
# Modify the operator using apply_permutation method.
op4 = op.copy()
op4 = op4.apply_permutation(pattern, front=False)
self.assertEqual(op2, op3)
self.assertEqual(op2, op4)
def test_apply_permutation_front(self):
"""Test applying permutation to the operator,
where the permutation is applied first and the operator second"""
op = Operator(self.rand_matrix(64, 64))
pattern = [1, 2, 0, 3, 5, 4]
# Consider several methods of computing this operator and show
# they all lead to the same result.
# Compose the operator with the operator constructed from the
# permutation circuit.
op2 = op.copy()
perm_op = Operator(Permutation(6, pattern))
op2 = perm_op & op2
# Compose the operator with the operator constructed from the
# permutation gate.
op3 = op.copy()
perm_op = Operator(PermutationGate(pattern))
op3 = perm_op & op3
# Modify the operator using apply_permutation method.
op4 = op.copy()
op4 = op4.apply_permutation(pattern, front=True)
self.assertEqual(op2, op3)
self.assertEqual(op2, op4)
def test_apply_permutation_qudits_back(self):
"""Test applying permutation to the operator with heterogeneous qudit spaces,
where the operator O is applied first and the permutation P second.
The matrix of the resulting operator is the product [P][O] and
corresponds to suitably permuting the rows of O's matrix.
"""
mat = np.array(range(6 * 6)).reshape((6, 6))
op = Operator(mat, input_dims=(2, 3), output_dims=(2, 3))
perm = [1, 0]
actual = op.apply_permutation(perm, front=False)
# Rows of mat are ordered to 00, 01, 02, 10, 11, 12;
# perm maps these to 00, 10, 20, 01, 11, 21,
# while the default ordering is 00, 01, 10, 11, 20, 21.
permuted_mat = mat.copy()[[0, 2, 4, 1, 3, 5]]
expected = Operator(permuted_mat, input_dims=(2, 3), output_dims=(3, 2))
self.assertEqual(actual, expected)
def test_apply_permutation_qudits_front(self):
"""Test applying permutation to the operator with heterogeneous qudit spaces,
where the permutation P is applied first and the operator O is applied second.
The matrix of the resulting operator is the product [O][P] and
corresponds to suitably permuting the columns of O's matrix.
"""
mat = np.array(range(6 * 6)).reshape((6, 6))
op = Operator(mat, input_dims=(2, 3), output_dims=(2, 3))
perm = [1, 0]
actual = op.apply_permutation(perm, front=True)
# Columns of mat are ordered to 00, 01, 02, 10, 11, 12;
# perm maps these to 00, 10, 20, 01, 11, 21,
# while the default ordering is 00, 01, 10, 11, 20, 21.
permuted_mat = mat.copy()[:, [0, 2, 4, 1, 3, 5]]
expected = Operator(permuted_mat, input_dims=(3, 2), output_dims=(2, 3))
self.assertEqual(actual, expected)
@combine(
dims=((2, 3, 4, 5), (5, 2, 4, 3), (3, 5, 2, 4), (5, 3, 4, 2), (4, 5, 2, 3), (4, 3, 2, 5))
)
def test_reverse_qargs_as_apply_permutation(self, dims):
"""Test reversing qargs by pre- and post-composing with reversal
permutation.
"""
perm = [3, 2, 1, 0]
op = Operator(
np.array(range(120 * 120)).reshape((120, 120)), input_dims=dims, output_dims=dims
)
op2 = op.reverse_qargs()
op3 = op.apply_permutation(perm, front=True).apply_permutation(perm, front=False)
self.assertEqual(op2, op3)
def test_apply_permutation_exceptions(self):
"""Checks that applying permutation raises an error when dimensions do not match."""
op = Operator(
np.array(range(24 * 30)).reshape((24, 30)), input_dims=(6, 5), output_dims=(2, 3, 4)
)
with self.assertRaises(QiskitError):
op.apply_permutation([1, 0], front=False)
with self.assertRaises(QiskitError):
op.apply_permutation([2, 1, 0], front=True)
def test_apply_permutation_dimensions(self):
"""Checks the dimensions of the operator after applying permutation."""
op = Operator(
np.array(range(24 * 30)).reshape((24, 30)), input_dims=(6, 5), output_dims=(2, 3, 4)
)
op2 = op.apply_permutation([1, 2, 0], front=False)
self.assertEqual(op2.output_dims(), (4, 2, 3))
op = Operator(
np.array(range(24 * 30)).reshape((30, 24)), input_dims=(2, 3, 4), output_dims=(6, 5)
)
op2 = op.apply_permutation([2, 0, 1], front=True)
self.assertEqual(op2.input_dims(), (4, 2, 3))
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for Chi quantum channel representation class."""
import copy
import unittest
import numpy as np
from numpy.testing import assert_allclose
from qiskit import QiskitError
from qiskit.quantum_info.states import DensityMatrix
from qiskit.quantum_info.operators.channel import Chi
from .channel_test_case import ChannelTestCase
class TestChi(ChannelTestCase):
"""Tests for Chi channel representation."""
def test_init(self):
"""Test initialization"""
mat4 = np.eye(4) / 2.0
chan = Chi(mat4)
assert_allclose(chan.data, mat4)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
mat16 = np.eye(16) / 4
chan = Chi(mat16)
assert_allclose(chan.data, mat16)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(chan.num_qubits, 2)
# Wrong input or output dims should raise exception
self.assertRaises(QiskitError, Chi, mat16, input_dims=2, output_dims=4)
# Non multi-qubit dimensions should raise exception
self.assertRaises(QiskitError, Chi, np.eye(6) / 2, input_dims=3, output_dims=2)
def test_circuit_init(self):
"""Test initialization from a circuit."""
circuit, target = self.simple_circuit_no_measure()
op = Chi(circuit)
target = Chi(target)
self.assertEqual(op, target)
def test_circuit_init_except(self):
"""Test initialization from circuit with measure raises exception."""
circuit = self.simple_circuit_with_measure()
self.assertRaises(QiskitError, Chi, circuit)
def test_equal(self):
"""Test __eq__ method"""
mat = self.rand_matrix(4, 4, real=True)
self.assertEqual(Chi(mat), Chi(mat))
def test_copy(self):
"""Test copy method"""
mat = np.eye(4)
with self.subTest("Deep copy"):
orig = Chi(mat)
cpy = orig.copy()
cpy._data[0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = Chi(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_is_cptp(self):
"""Test is_cptp method."""
self.assertTrue(Chi(self.depol_chi(0.25)).is_cptp())
# Non-CPTP should return false
self.assertFalse(Chi(1.25 * self.chiI - 0.25 * self.depol_chi(1)).is_cptp())
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError, Chi(np.eye(4)).compose, Chi(np.eye(16)))
self.assertRaises(QiskitError, Chi(np.eye(4)).compose, 2)
def test_compose(self):
"""Test compose method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Chi(self.chiX)
chan2 = Chi(self.chiY)
chan = chan1.compose(chan2)
target = rho.evolve(Chi(self.chiZ))
output = rho.evolve(chan)
self.assertEqual(output, target)
# 50% depolarizing channel
chan1 = Chi(self.depol_chi(0.5))
chan = chan1.compose(chan1)
target = rho.evolve(Chi(self.depol_chi(0.75)))
output = rho.evolve(chan)
self.assertEqual(output, target)
# Compose random
chi1 = self.rand_matrix(4, 4, real=True)
chi2 = self.rand_matrix(4, 4, real=True)
chan1 = Chi(chi1, input_dims=2, output_dims=2)
chan2 = Chi(chi2, input_dims=2, output_dims=2)
target = rho.evolve(chan1).evolve(chan2)
chan = chan1.compose(chan2)
output = rho.evolve(chan)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(output, target)
chan = chan1 & chan2
output = rho.evolve(chan)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(output, target)
def test_dot(self):
"""Test dot method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Chi(self.chiX)
chan2 = Chi(self.chiY)
target = rho.evolve(Chi(self.chiZ))
output = rho.evolve(chan2.dot(chan1))
self.assertEqual(output, target)
# Compose random
chi1 = self.rand_matrix(4, 4, real=True)
chi2 = self.rand_matrix(4, 4, real=True)
chan1 = Chi(chi1, input_dims=2, output_dims=2)
chan2 = Chi(chi2, input_dims=2, output_dims=2)
target = rho.evolve(chan1).evolve(chan2)
chan = chan2.dot(chan1)
output = rho.evolve(chan)
self.assertEqual(output, target)
chan = chan2 @ chan1
output = rho.evolve(chan)
self.assertEqual(output, target)
def test_compose_front(self):
"""Test front compose method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Chi(self.chiX)
chan2 = Chi(self.chiY)
chan = chan2.compose(chan1, front=True)
target = rho.evolve(Chi(self.chiZ))
output = rho.evolve(chan)
self.assertEqual(output, target)
# Compose random
chi1 = self.rand_matrix(4, 4, real=True)
chi2 = self.rand_matrix(4, 4, real=True)
chan1 = Chi(chi1, input_dims=2, output_dims=2)
chan2 = Chi(chi2, input_dims=2, output_dims=2)
target = rho.evolve(chan1).evolve(chan2)
chan = chan2.compose(chan1, front=True)
output = rho.evolve(chan)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(output, target)
def test_expand(self):
"""Test expand method."""
# Pauli channels
paulis = [self.chiI, self.chiX, self.chiY, self.chiZ]
targs = 4 * np.eye(16) # diagonals of Pauli channel Chi mats
for i, chi1 in enumerate(paulis):
for j, chi2 in enumerate(paulis):
chan1 = Chi(chi1)
chan2 = Chi(chi2)
chan = chan1.expand(chan2)
# Target for diagonal Pauli channel
targ = Chi(np.diag(targs[i + 4 * j]))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(chan, targ)
# Completely depolarizing
rho = DensityMatrix(np.diag([1, 0, 0, 0]))
chan_dep = Chi(self.depol_chi(1))
chan = chan_dep.expand(chan_dep)
target = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
output = rho.evolve(chan)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(output, target)
def test_tensor(self):
"""Test tensor method."""
# Pauli channels
paulis = [self.chiI, self.chiX, self.chiY, self.chiZ]
targs = 4 * np.eye(16) # diagonals of Pauli channel Chi mats
for i, chi1 in enumerate(paulis):
for j, chi2 in enumerate(paulis):
chan1 = Chi(chi1)
chan2 = Chi(chi2)
chan = chan2.tensor(chan1)
# Target for diagonal Pauli channel
targ = Chi(np.diag(targs[i + 4 * j]))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(chan, targ)
# Test overload
chan = chan2 ^ chan1
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(chan, targ)
# Completely depolarizing
rho = DensityMatrix(np.diag([1, 0, 0, 0]))
chan_dep = Chi(self.depol_chi(1))
chan = chan_dep.tensor(chan_dep)
target = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
output = rho.evolve(chan)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(output, target)
# Test operator overload
chan = chan_dep ^ chan_dep
output = rho.evolve(chan)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(output, target)
def test_power(self):
"""Test power method."""
# 10% depolarizing channel
p_id = 0.9
depol = Chi(self.depol_chi(1 - p_id))
# Compose 3 times
p_id3 = p_id**3
chan3 = depol.power(3)
targ3 = Chi(self.depol_chi(1 - p_id3))
self.assertEqual(chan3, targ3)
def test_add(self):
"""Test add method."""
mat1 = 0.5 * self.chiI
mat2 = 0.5 * self.depol_chi(1)
chan1 = Chi(mat1)
chan2 = Chi(mat2)
targ = Chi(mat1 + mat2)
self.assertEqual(chan1._add(chan2), targ)
self.assertEqual(chan1 + chan2, targ)
targ = Chi(mat1 - mat2)
self.assertEqual(chan1 - chan2, targ)
def test_add_qargs(self):
"""Test add method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = Chi(mat)
op0 = Chi(mat0)
op1 = Chi(mat1)
op01 = op1.tensor(op0)
eye = Chi(self.chiI)
with self.subTest(msg="qargs=[0]"):
value = op + op0([0])
target = op + eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op + op0([1])
target = op + eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op + op0([2])
target = op + op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op + op01([0, 1])
target = op + eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op + op01([1, 0])
target = op + eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op + op01([0, 2])
target = op + op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op + op01([2, 0])
target = op + op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_sub_qargs(self):
"""Test subtract method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = Chi(mat)
op0 = Chi(mat0)
op1 = Chi(mat1)
op01 = op1.tensor(op0)
eye = Chi(self.chiI)
with self.subTest(msg="qargs=[0]"):
value = op - op0([0])
target = op - eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op - op0([1])
target = op - eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op - op0([2])
target = op - op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op - op01([0, 1])
target = op - eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op - op01([1, 0])
target = op - eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op - op01([0, 2])
target = op - op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op - op01([2, 0])
target = op - op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_add_except(self):
"""Test add method raises exceptions."""
chan1 = Chi(self.chiI)
chan2 = Chi(np.eye(16))
self.assertRaises(QiskitError, chan1._add, chan2)
self.assertRaises(QiskitError, chan1._add, 5)
def test_multiply(self):
"""Test multiply method."""
chan = Chi(self.chiI)
val = 0.5
targ = Chi(val * self.chiI)
self.assertEqual(chan._multiply(val), targ)
self.assertEqual(val * chan, targ)
targ = Chi(self.chiI * val)
self.assertEqual(chan * val, targ)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
chan = Chi(self.chiI)
self.assertRaises(QiskitError, chan._multiply, "s")
self.assertRaises(QiskitError, chan.__rmul__, "s")
self.assertRaises(QiskitError, chan._multiply, chan)
self.assertRaises(QiskitError, chan.__rmul__, chan)
def test_negate(self):
"""Test negate method"""
chan = Chi(self.chiI)
targ = Chi(-self.chiI)
self.assertEqual(-chan, targ)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""Tests for Choi quantum channel representation class."""
import copy
import unittest
import numpy as np
from numpy.testing import assert_allclose
from qiskit import QiskitError
from qiskit.quantum_info.states import DensityMatrix
from qiskit.quantum_info.operators.channel import Choi
from .channel_test_case import ChannelTestCase
class TestChoi(ChannelTestCase):
"""Tests for Choi channel representation."""
def test_init(self):
"""Test initialization"""
mat4 = np.eye(4) / 2.0
chan = Choi(mat4)
assert_allclose(chan.data, mat4)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
mat8 = np.eye(8) / 2.0
chan = Choi(mat8, input_dims=4)
assert_allclose(chan.data, mat8)
self.assertEqual(chan.dim, (4, 2))
self.assertIsNone(chan.num_qubits)
chan = Choi(mat8, input_dims=2)
assert_allclose(chan.data, mat8)
self.assertEqual(chan.dim, (2, 4))
self.assertIsNone(chan.num_qubits)
mat16 = np.eye(16) / 4
chan = Choi(mat16)
assert_allclose(chan.data, mat16)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(chan.num_qubits, 2)
# Wrong input or output dims should raise exception
self.assertRaises(QiskitError, Choi, mat8, input_dims=[4], output_dims=[4])
def test_circuit_init(self):
"""Test initialization from a circuit."""
circuit, target = self.simple_circuit_no_measure()
op = Choi(circuit)
target = Choi(target)
self.assertEqual(op, target)
def test_circuit_init_except(self):
"""Test initialization from circuit with measure raises exception."""
circuit = self.simple_circuit_with_measure()
self.assertRaises(QiskitError, Choi, circuit)
def test_equal(self):
"""Test __eq__ method"""
mat = self.rand_matrix(4, 4)
self.assertEqual(Choi(mat), Choi(mat))
def test_copy(self):
"""Test copy method"""
mat = np.eye(2)
with self.subTest("Deep copy"):
orig = Choi(mat)
cpy = orig.copy()
cpy._data[0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = Choi(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_clone(self):
"""Test clone method"""
mat = np.eye(4)
orig = Choi(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_is_cptp(self):
"""Test is_cptp method."""
self.assertTrue(Choi(self.depol_choi(0.25)).is_cptp())
# Non-CPTP should return false
self.assertFalse(Choi(1.25 * self.choiI - 0.25 * self.depol_choi(1)).is_cptp())
def test_conjugate(self):
"""Test conjugate method."""
# Test channel measures in Z basis and prepares in Y basis
# Zp -> Yp, Zm -> Ym
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Yp, Ym = np.array([[1, -1j], [1j, 1]]) / 2, np.array([[1, 1j], [-1j, 1]]) / 2
chan = Choi(np.kron(Zp, Yp) + np.kron(Zm, Ym))
# Conjugate channel swaps Y-basis states
targ = Choi(np.kron(Zp, Ym) + np.kron(Zm, Yp))
chan_conj = chan.conjugate()
self.assertEqual(chan_conj, targ)
def test_transpose(self):
"""Test transpose method."""
# Test channel measures in Z basis and prepares in Y basis
# Zp -> Yp, Zm -> Ym
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Yp, Ym = np.array([[1, -1j], [1j, 1]]) / 2, np.array([[1, 1j], [-1j, 1]]) / 2
chan = Choi(np.kron(Zp, Yp) + np.kron(Zm, Ym))
# Transpose channel swaps basis
targ = Choi(np.kron(Yp, Zp) + np.kron(Ym, Zm))
chan_t = chan.transpose()
self.assertEqual(chan_t, targ)
def test_adjoint(self):
"""Test adjoint method."""
# Test channel measures in Z basis and prepares in Y basis
# Zp -> Yp, Zm -> Ym
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Yp, Ym = np.array([[1, -1j], [1j, 1]]) / 2, np.array([[1, 1j], [-1j, 1]]) / 2
chan = Choi(np.kron(Zp, Yp) + np.kron(Zm, Ym))
# Ajoint channel swaps Y-basis elements and Z<->Y bases
targ = Choi(np.kron(Ym, Zp) + np.kron(Yp, Zm))
chan_adj = chan.adjoint()
self.assertEqual(chan_adj, targ)
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError, Choi(np.eye(4)).compose, Choi(np.eye(8)))
self.assertRaises(QiskitError, Choi(np.eye(4)).compose, 2)
def test_compose(self):
"""Test compose method."""
# UnitaryChannel evolution
chan1 = Choi(self.choiX)
chan2 = Choi(self.choiY)
chan = chan1.compose(chan2)
targ = Choi(self.choiZ)
self.assertEqual(chan, targ)
# 50% depolarizing channel
chan1 = Choi(self.depol_choi(0.5))
chan = chan1.compose(chan1)
targ = Choi(self.depol_choi(0.75))
self.assertEqual(chan, targ)
# Measure and rotation
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Xp, Xm = np.array([[1, 1], [1, 1]]) / 2, np.array([[1, -1], [-1, 1]]) / 2
chan1 = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
chan2 = Choi(self.choiX)
# X-gate second does nothing
targ = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
self.assertEqual(chan1.compose(chan2), targ)
self.assertEqual(chan1 & chan2, targ)
# X-gate first swaps Z states
targ = Choi(np.kron(Zm, Xp) + np.kron(Zp, Xm))
self.assertEqual(chan2.compose(chan1), targ)
self.assertEqual(chan2 & chan1, targ)
# Compose different dimensions
chan1 = Choi(np.eye(8) / 4, input_dims=2, output_dims=4)
chan2 = Choi(np.eye(8) / 2, input_dims=4, output_dims=2)
chan = chan1.compose(chan2)
self.assertEqual(chan.dim, (2, 2))
chan = chan2.compose(chan1)
self.assertEqual(chan.dim, (4, 4))
def test_dot(self):
"""Test dot method."""
# UnitaryChannel evolution
chan1 = Choi(self.choiX)
chan2 = Choi(self.choiY)
targ = Choi(self.choiZ)
self.assertEqual(chan1.dot(chan2), targ)
self.assertEqual(chan1 @ chan2, targ)
# 50% depolarizing channel
chan1 = Choi(self.depol_choi(0.5))
targ = Choi(self.depol_choi(0.75))
self.assertEqual(chan1.dot(chan1), targ)
self.assertEqual(chan1 @ chan1, targ)
# Measure and rotation
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Xp, Xm = np.array([[1, 1], [1, 1]]) / 2, np.array([[1, -1], [-1, 1]]) / 2
chan1 = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
chan2 = Choi(self.choiX)
# X-gate second does nothing
targ = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
self.assertEqual(chan2.dot(chan1), targ)
self.assertEqual(chan2 @ chan1, targ)
# X-gate first swaps Z states
targ = Choi(np.kron(Zm, Xp) + np.kron(Zp, Xm))
self.assertEqual(chan1.dot(chan2), targ)
self.assertEqual(chan1 @ chan2, targ)
# Compose different dimensions
chan1 = Choi(np.eye(8) / 4, input_dims=2, output_dims=4)
chan2 = Choi(np.eye(8) / 2, input_dims=4, output_dims=2)
chan = chan1.dot(chan2)
self.assertEqual(chan.dim, (4, 4))
chan = chan1 @ chan2
self.assertEqual(chan.dim, (4, 4))
chan = chan2.dot(chan1)
self.assertEqual(chan.dim, (2, 2))
chan = chan2 @ chan1
self.assertEqual(chan.dim, (2, 2))
def test_compose_front(self):
"""Test front compose method."""
# UnitaryChannel evolution
chan1 = Choi(self.choiX)
chan2 = Choi(self.choiY)
chan = chan1.compose(chan2, front=True)
targ = Choi(self.choiZ)
self.assertEqual(chan, targ)
# 50% depolarizing channel
chan1 = Choi(self.depol_choi(0.5))
chan = chan1.compose(chan1, front=True)
targ = Choi(self.depol_choi(0.75))
self.assertEqual(chan, targ)
# Measure and rotation
Zp, Zm = np.diag([1, 0]), np.diag([0, 1])
Xp, Xm = np.array([[1, 1], [1, 1]]) / 2, np.array([[1, -1], [-1, 1]]) / 2
chan1 = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
chan2 = Choi(self.choiX)
# X-gate second does nothing
chan = chan2.compose(chan1, front=True)
targ = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm))
self.assertEqual(chan, targ)
# X-gate first swaps Z states
chan = chan1.compose(chan2, front=True)
targ = Choi(np.kron(Zm, Xp) + np.kron(Zp, Xm))
self.assertEqual(chan, targ)
# Compose different dimensions
chan1 = Choi(np.eye(8) / 4, input_dims=2, output_dims=4)
chan2 = Choi(np.eye(8) / 2, input_dims=4, output_dims=2)
chan = chan1.compose(chan2, front=True)
self.assertEqual(chan.dim, (4, 4))
chan = chan2.compose(chan1, front=True)
self.assertEqual(chan.dim, (2, 2))
def test_expand(self):
"""Test expand method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = Choi(self.choiI)
chan2 = Choi(self.choiX)
# X \otimes I
chan = chan1.expand(chan2)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan2.expand(chan1)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Completely depolarizing
chan_dep = Choi(self.depol_choi(1))
chan = chan_dep.expand(chan_dep)
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_tensor(self):
"""Test tensor method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = Choi(self.choiI)
chan2 = Choi(self.choiX)
# X \otimes I
rho_targ = DensityMatrix(np.kron(rho1, rho0))
chan = chan2.tensor(chan1)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan2 ^ chan1
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
rho_targ = DensityMatrix(np.kron(rho0, rho1))
chan = chan1.tensor(chan2)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan1 ^ chan2
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Completely depolarizing
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
chan_dep = Choi(self.depol_choi(1))
chan = chan_dep.tensor(chan_dep)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan_dep ^ chan_dep
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_power(self):
"""Test power method."""
# 10% depolarizing channel
p_id = 0.9
depol = Choi(self.depol_choi(1 - p_id))
# Compose 3 times
p_id3 = p_id**3
chan3 = depol.power(3)
targ3 = Choi(self.depol_choi(1 - p_id3))
self.assertEqual(chan3, targ3)
def test_add(self):
"""Test add method."""
mat1 = 0.5 * self.choiI
mat2 = 0.5 * self.depol_choi(1)
chan1 = Choi(mat1)
chan2 = Choi(mat2)
targ = Choi(mat1 + mat2)
self.assertEqual(chan1._add(chan2), targ)
self.assertEqual(chan1 + chan2, targ)
targ = Choi(mat1 - mat2)
self.assertEqual(chan1 - chan2, targ)
def test_add_qargs(self):
"""Test add method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = Choi(mat)
op0 = Choi(mat0)
op1 = Choi(mat1)
op01 = op1.tensor(op0)
eye = Choi(self.choiI)
with self.subTest(msg="qargs=[0]"):
value = op + op0([0])
target = op + eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op + op0([1])
target = op + eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op + op0([2])
target = op + op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op + op01([0, 1])
target = op + eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op + op01([1, 0])
target = op + eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op + op01([0, 2])
target = op + op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op + op01([2, 0])
target = op + op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_sub_qargs(self):
"""Test subtract method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = Choi(mat)
op0 = Choi(mat0)
op1 = Choi(mat1)
op01 = op1.tensor(op0)
eye = Choi(self.choiI)
with self.subTest(msg="qargs=[0]"):
value = op - op0([0])
target = op - eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op - op0([1])
target = op - eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op - op0([2])
target = op - op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op - op01([0, 1])
target = op - eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op - op01([1, 0])
target = op - eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op - op01([0, 2])
target = op - op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op - op01([2, 0])
target = op - op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_add_except(self):
"""Test add method raises exceptions."""
chan1 = Choi(self.choiI)
chan2 = Choi(np.eye(8))
self.assertRaises(QiskitError, chan1._add, chan2)
self.assertRaises(QiskitError, chan1._add, 5)
def test_multiply(self):
"""Test multiply method."""
chan = Choi(self.choiI)
val = 0.5
targ = Choi(val * self.choiI)
self.assertEqual(chan._multiply(val), targ)
self.assertEqual(val * chan, targ)
targ = Choi(self.choiI * val)
self.assertEqual(chan * val, targ)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
chan = Choi(self.choiI)
self.assertRaises(QiskitError, chan._multiply, "s")
self.assertRaises(QiskitError, chan.__rmul__, "s")
self.assertRaises(QiskitError, chan._multiply, chan)
self.assertRaises(QiskitError, chan.__rmul__, chan)
def test_negate(self):
"""Test negate method"""
chan = Choi(self.choiI)
targ = Choi(-1 * self.choiI)
self.assertEqual(-chan, targ)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for Kraus quantum channel representation class."""
import copy
import unittest
import numpy as np
from numpy.testing import assert_allclose
from qiskit import QiskitError
from qiskit.quantum_info.states import DensityMatrix
from qiskit.quantum_info import Kraus
from .channel_test_case import ChannelTestCase
class TestKraus(ChannelTestCase):
"""Tests for Kraus channel representation."""
def test_init(self):
"""Test initialization"""
# Initialize from unitary
chan = Kraus(self.UI)
assert_allclose(chan.data, [self.UI])
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize from Kraus
chan = Kraus(self.depol_kraus(0.5))
assert_allclose(chan.data, self.depol_kraus(0.5))
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize from Non-CPTP
kraus_l, kraus_r = [self.UI, self.UX], [self.UY, self.UZ]
chan = Kraus((kraus_l, kraus_r))
assert_allclose(chan.data, (kraus_l, kraus_r))
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize with redundant second op
chan = Kraus((kraus_l, kraus_l))
assert_allclose(chan.data, kraus_l)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize from rectangular
kraus = [np.zeros((4, 2))]
chan = Kraus(kraus)
assert_allclose(chan.data, kraus)
self.assertEqual(chan.dim, (2, 4))
self.assertIsNone(chan.num_qubits)
# Wrong input or output dims should raise exception
self.assertRaises(QiskitError, Kraus, kraus, input_dims=4, output_dims=4)
def test_circuit_init(self):
"""Test initialization from a circuit."""
circuit, target = self.simple_circuit_no_measure()
op = Kraus(circuit)
target = Kraus(target)
self.assertEqual(op, target)
def test_circuit_init_except(self):
"""Test initialization from circuit with measure raises exception."""
circuit = self.simple_circuit_with_measure()
self.assertRaises(QiskitError, Kraus, circuit)
def test_equal(self):
"""Test __eq__ method"""
kraus = [self.rand_matrix(2, 2) for _ in range(2)]
self.assertEqual(Kraus(kraus), Kraus(kraus))
def test_copy(self):
"""Test copy method"""
mat = np.eye(2)
with self.subTest("Deep copy"):
orig = Kraus(mat)
cpy = orig.copy()
cpy._data[0][0][0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = Kraus(mat)
clone = copy.copy(orig)
clone._data[0][0][0, 0] = 0.0
self.assertTrue(clone == orig)
def test_clone(self):
"""Test clone method"""
mat = np.eye(4)
orig = Kraus(mat)
clone = copy.copy(orig)
clone._data[0][0][0, 0] = 0.0
self.assertTrue(clone == orig)
def test_is_cptp(self):
"""Test is_cptp method."""
self.assertTrue(Kraus(self.depol_kraus(0.5)).is_cptp())
self.assertTrue(Kraus(self.UX).is_cptp())
# Non-CPTP should return false
self.assertFalse(Kraus(([self.UI], [self.UX])).is_cptp())
self.assertFalse(Kraus([self.UI, self.UX]).is_cptp())
def test_conjugate(self):
"""Test conjugate method."""
kraus_l, kraus_r = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4)
# Single Kraus list
targ = Kraus([np.conjugate(k) for k in kraus_l])
chan1 = Kraus(kraus_l)
chan = chan1.conjugate()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (2, 4))
# Double Kraus list
targ = Kraus(([np.conjugate(k) for k in kraus_l], [np.conjugate(k) for k in kraus_r]))
chan1 = Kraus((kraus_l, kraus_r))
chan = chan1.conjugate()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (2, 4))
def test_transpose(self):
"""Test transpose method."""
kraus_l, kraus_r = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4)
# Single Kraus list
targ = Kraus([np.transpose(k) for k in kraus_l])
chan1 = Kraus(kraus_l)
chan = chan1.transpose()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
# Double Kraus list
targ = Kraus(([np.transpose(k) for k in kraus_l], [np.transpose(k) for k in kraus_r]))
chan1 = Kraus((kraus_l, kraus_r))
chan = chan1.transpose()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
def test_adjoint(self):
"""Test adjoint method."""
kraus_l, kraus_r = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4)
# Single Kraus list
targ = Kraus([np.transpose(k).conj() for k in kraus_l])
chan1 = Kraus(kraus_l)
chan = chan1.adjoint()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
# Double Kraus list
targ = Kraus(
([np.transpose(k).conj() for k in kraus_l], [np.transpose(k).conj() for k in kraus_r])
)
chan1 = Kraus((kraus_l, kraus_r))
chan = chan1.adjoint()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError, Kraus(np.eye(2)).compose, Kraus(np.eye(4)))
self.assertRaises(QiskitError, Kraus(np.eye(2)).compose, 2)
def test_compose(self):
"""Test compose method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Kraus(self.UX)
chan2 = Kraus(self.UY)
chan = chan1.compose(chan2)
targ = rho & Kraus(self.UZ)
self.assertEqual(rho & chan, targ)
# 50% depolarizing channel
chan1 = Kraus(self.depol_kraus(0.5))
chan = chan1.compose(chan1)
targ = rho & Kraus(self.depol_kraus(0.75))
self.assertEqual(rho & chan, targ)
# Compose different dimensions
kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(4, 2, 4)
chan1 = Kraus(kraus1)
chan2 = Kraus(kraus2)
targ = rho & chan1 & chan2
chan = chan1.compose(chan2)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho & chan, targ)
chan = chan1 & chan2
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho & chan, targ)
def test_dot(self):
"""Test dot method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Kraus(self.UX)
chan2 = Kraus(self.UY)
targ = rho.evolve(Kraus(self.UZ))
self.assertEqual(rho.evolve(chan1.dot(chan2)), targ)
self.assertEqual(rho.evolve(chan1 @ chan2), targ)
# 50% depolarizing channel
chan1 = Kraus(self.depol_kraus(0.5))
targ = rho & Kraus(self.depol_kraus(0.75))
self.assertEqual(rho.evolve(chan1.dot(chan1)), targ)
self.assertEqual(rho.evolve(chan1 @ chan1), targ)
# Compose different dimensions
kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(4, 2, 4)
chan1 = Kraus(kraus1)
chan2 = Kraus(kraus2)
targ = rho & chan1 & chan2
self.assertEqual(rho.evolve(chan2.dot(chan1)), targ)
self.assertEqual(rho.evolve(chan2 @ chan1), targ)
def test_compose_front(self):
"""Test deprecated front compose method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Kraus(self.UX)
chan2 = Kraus(self.UY)
chan = chan1.compose(chan2, front=True)
targ = rho & Kraus(self.UZ)
self.assertEqual(rho & chan, targ)
# 50% depolarizing channel
chan1 = Kraus(self.depol_kraus(0.5))
chan = chan1.compose(chan1, front=True)
targ = rho & Kraus(self.depol_kraus(0.75))
self.assertEqual(rho & chan, targ)
# Compose different dimensions
kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(4, 2, 4)
chan1 = Kraus(kraus1)
chan2 = Kraus(kraus2)
targ = rho & chan1 & chan2
chan = chan2.compose(chan1, front=True)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho & chan, targ)
def test_expand(self):
"""Test expand method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = Kraus(self.UI)
chan2 = Kraus(self.UX)
# X \otimes I
chan = chan1.expand(chan2)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init & chan, rho_targ)
# I \otimes X
chan = chan2.expand(chan1)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init & chan, rho_targ)
# Completely depolarizing
chan_dep = Kraus(self.depol_kraus(1))
chan = chan_dep.expand(chan_dep)
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init & chan, rho_targ)
def test_tensor(self):
"""Test tensor method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = Kraus(self.UI)
chan2 = Kraus(self.UX)
# X \otimes I
chan = chan2.tensor(chan1)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init & chan, rho_targ)
# I \otimes X
chan = chan1.tensor(chan2)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init & chan, rho_targ)
# Completely depolarizing
chan_dep = Kraus(self.depol_kraus(1))
chan = chan_dep.tensor(chan_dep)
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init & chan, rho_targ)
def test_power(self):
"""Test power method."""
# 10% depolarizing channel
rho = DensityMatrix(np.diag([1, 0]))
p_id = 0.9
chan = Kraus(self.depol_kraus(1 - p_id))
# Compose 3 times
p_id3 = p_id**3
chan3 = chan.power(3)
targ3a = rho & chan & chan & chan
self.assertEqual(rho & chan3, targ3a)
targ3b = rho & Kraus(self.depol_kraus(1 - p_id3))
self.assertEqual(rho & chan3, targ3b)
def test_add(self):
"""Test add method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4)
# Random Single-Kraus maps
chan1 = Kraus(kraus1)
chan2 = Kraus(kraus2)
targ = (rho & chan1) + (rho & chan2)
chan = chan1._add(chan2)
self.assertEqual(rho & chan, targ)
chan = chan1 + chan2
self.assertEqual(rho & chan, targ)
# Random Single-Kraus maps
chan = Kraus((kraus1, kraus2))
targ = 2 * (rho & chan)
chan = chan._add(chan)
self.assertEqual(rho & chan, targ)
def test_add_qargs(self):
"""Test add method with qargs."""
rho = DensityMatrix(self.rand_rho(8))
kraus = self.rand_kraus(8, 8, 4)
kraus0 = self.rand_kraus(2, 2, 4)
op = Kraus(kraus)
op0 = Kraus(kraus0)
eye = Kraus(self.UI)
with self.subTest(msg="qargs=[0]"):
value = op + op0([0])
target = op + eye.tensor(eye).tensor(op0)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[1]"):
value = op + op0([1])
target = op + eye.tensor(op0).tensor(eye)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[2]"):
value = op + op0([2])
target = op + op0.tensor(eye).tensor(eye)
self.assertEqual(rho & value, rho & target)
def test_sub_qargs(self):
"""Test sub method with qargs."""
rho = DensityMatrix(self.rand_rho(8))
kraus = self.rand_kraus(8, 8, 4)
kraus0 = self.rand_kraus(2, 2, 4)
op = Kraus(kraus)
op0 = Kraus(kraus0)
eye = Kraus(self.UI)
with self.subTest(msg="qargs=[0]"):
value = op - op0([0])
target = op - eye.tensor(eye).tensor(op0)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[1]"):
value = op - op0([1])
target = op - eye.tensor(op0).tensor(eye)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[2]"):
value = op - op0([2])
target = op - op0.tensor(eye).tensor(eye)
self.assertEqual(rho & value, rho & target)
def test_subtract(self):
"""Test subtract method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4)
# Random Single-Kraus maps
chan1 = Kraus(kraus1)
chan2 = Kraus(kraus2)
targ = (rho & chan1) - (rho & chan2)
chan = chan1 - chan2
self.assertEqual(rho & chan, targ)
# Random Single-Kraus maps
chan = Kraus((kraus1, kraus2))
targ = 0 * (rho & chan)
chan = chan - chan
self.assertEqual(rho & chan, targ)
def test_multiply(self):
"""Test multiply method."""
# Random initial state and Kraus ops
rho = DensityMatrix(self.rand_rho(2))
val = 0.5
kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4)
# Single Kraus set
chan1 = Kraus(kraus1)
targ = val * (rho & chan1)
chan = chan1._multiply(val)
self.assertEqual(rho & chan, targ)
chan = val * chan1
self.assertEqual(rho & chan, targ)
targ = (rho & chan1) * val
chan = chan1 * val
self.assertEqual(rho & chan, targ)
# Double Kraus set
chan2 = Kraus((kraus1, kraus2))
targ = val * (rho & chan2)
chan = chan2._multiply(val)
self.assertEqual(rho & chan, targ)
chan = val * chan2
self.assertEqual(rho & chan, targ)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
chan = Kraus(self.depol_kraus(1))
self.assertRaises(QiskitError, chan._multiply, "s")
self.assertRaises(QiskitError, chan.__rmul__, "s")
self.assertRaises(QiskitError, chan._multiply, chan)
self.assertRaises(QiskitError, chan.__rmul__, chan)
def test_negate(self):
"""Test negate method"""
rho = DensityMatrix(np.diag([1, 0]))
targ = DensityMatrix(np.diag([-0.5, -0.5]))
chan = -Kraus(self.depol_kraus(1))
self.assertEqual(rho & chan, targ)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for PTM quantum channel representation class."""
import copy
import unittest
import numpy as np
from numpy.testing import assert_allclose
from qiskit import QiskitError
from qiskit.quantum_info.states import DensityMatrix
from qiskit.quantum_info.operators.channel import PTM
from .channel_test_case import ChannelTestCase
class TestPTM(ChannelTestCase):
"""Tests for PTM channel representation."""
def test_init(self):
"""Test initialization"""
mat4 = np.eye(4) / 2.0
chan = PTM(mat4)
assert_allclose(chan.data, mat4)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
mat16 = np.eye(16) / 4
chan = PTM(mat16)
assert_allclose(chan.data, mat16)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(chan.num_qubits, 2)
# Wrong input or output dims should raise exception
self.assertRaises(QiskitError, PTM, mat16, input_dims=2, output_dims=4)
# Non multi-qubit dimensions should raise exception
self.assertRaises(QiskitError, PTM, np.eye(6) / 2, input_dims=3, output_dims=2)
def test_circuit_init(self):
"""Test initialization from a circuit."""
circuit, target = self.simple_circuit_no_measure()
op = PTM(circuit)
target = PTM(target)
self.assertEqual(op, target)
def test_circuit_init_except(self):
"""Test initialization from circuit with measure raises exception."""
circuit = self.simple_circuit_with_measure()
self.assertRaises(QiskitError, PTM, circuit)
def test_equal(self):
"""Test __eq__ method"""
mat = self.rand_matrix(4, 4, real=True)
self.assertEqual(PTM(mat), PTM(mat))
def test_copy(self):
"""Test copy method"""
mat = np.eye(4)
with self.subTest("Deep copy"):
orig = PTM(mat)
cpy = orig.copy()
cpy._data[0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = PTM(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_clone(self):
"""Test clone method"""
mat = np.eye(4)
orig = PTM(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_is_cptp(self):
"""Test is_cptp method."""
self.assertTrue(PTM(self.depol_ptm(0.25)).is_cptp())
# Non-CPTP should return false
self.assertFalse(PTM(1.25 * self.ptmI - 0.25 * self.depol_ptm(1)).is_cptp())
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError, PTM(np.eye(4)).compose, PTM(np.eye(16)))
self.assertRaises(QiskitError, PTM(np.eye(4)).compose, 2)
def test_compose(self):
"""Test compose method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = PTM(self.ptmX)
chan2 = PTM(self.ptmY)
chan = chan1.compose(chan2)
rho_targ = rho.evolve(PTM(self.ptmZ))
self.assertEqual(rho.evolve(chan), rho_targ)
# 50% depolarizing channel
chan1 = PTM(self.depol_ptm(0.5))
chan = chan1.compose(chan1)
rho_targ = rho.evolve(PTM(self.depol_ptm(0.75)))
self.assertEqual(rho.evolve(chan), rho_targ)
# Compose random
ptm1 = self.rand_matrix(4, 4, real=True)
ptm2 = self.rand_matrix(4, 4, real=True)
chan1 = PTM(ptm1, input_dims=2, output_dims=2)
chan2 = PTM(ptm2, input_dims=2, output_dims=2)
rho_targ = rho.evolve(chan1).evolve(chan2)
chan = chan1.compose(chan2)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho.evolve(chan), rho_targ)
chan = chan1 & chan2
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho.evolve(chan), rho_targ)
def test_dot(self):
"""Test dot method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = PTM(self.ptmX)
chan2 = PTM(self.ptmY)
rho_targ = rho.evolve(PTM(self.ptmZ))
self.assertEqual(rho.evolve(chan2.dot(chan1)), rho_targ)
self.assertEqual(rho.evolve(chan2 @ chan1), rho_targ)
# Compose random
ptm1 = self.rand_matrix(4, 4, real=True)
ptm2 = self.rand_matrix(4, 4, real=True)
chan1 = PTM(ptm1, input_dims=2, output_dims=2)
chan2 = PTM(ptm2, input_dims=2, output_dims=2)
rho_targ = rho.evolve(chan1).evolve(chan2)
self.assertEqual(rho.evolve(chan2.dot(chan1)), rho_targ)
self.assertEqual(rho.evolve(chan2 @ chan1), rho_targ)
def test_compose_front(self):
"""Test deprecated front compose method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = PTM(self.ptmX)
chan2 = PTM(self.ptmY)
chan = chan2.compose(chan1, front=True)
rho_targ = rho.evolve(PTM(self.ptmZ))
self.assertEqual(rho.evolve(chan), rho_targ)
# Compose random
ptm1 = self.rand_matrix(4, 4, real=True)
ptm2 = self.rand_matrix(4, 4, real=True)
chan1 = PTM(ptm1, input_dims=2, output_dims=2)
chan2 = PTM(ptm2, input_dims=2, output_dims=2)
rho_targ = rho.evolve(chan1).evolve(chan2)
chan = chan2.compose(chan1, front=True)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho.evolve(chan), rho_targ)
def test_expand(self):
"""Test expand method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = PTM(self.ptmI)
chan2 = PTM(self.ptmX)
# X \otimes I
chan = chan1.expand(chan2)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan2.expand(chan1)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Completely depolarizing
chan_dep = PTM(self.depol_ptm(1))
chan = chan_dep.expand(chan_dep)
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_tensor(self):
"""Test tensor method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = PTM(self.ptmI)
chan2 = PTM(self.ptmX)
# X \otimes I
chan = chan2.tensor(chan1)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan1.tensor(chan2)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Completely depolarizing
chan_dep = PTM(self.depol_ptm(1))
chan = chan_dep.tensor(chan_dep)
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_power(self):
"""Test power method."""
# 10% depolarizing channel
p_id = 0.9
depol = PTM(self.depol_ptm(1 - p_id))
# Compose 3 times
p_id3 = p_id**3
chan3 = depol.power(3)
targ3 = PTM(self.depol_ptm(1 - p_id3))
self.assertEqual(chan3, targ3)
def test_add(self):
"""Test add method."""
mat1 = 0.5 * self.ptmI
mat2 = 0.5 * self.depol_ptm(1)
chan1 = PTM(mat1)
chan2 = PTM(mat2)
targ = PTM(mat1 + mat2)
self.assertEqual(chan1._add(chan2), targ)
self.assertEqual(chan1 + chan2, targ)
targ = PTM(mat1 - mat2)
self.assertEqual(chan1 - chan2, targ)
def test_add_qargs(self):
"""Test add method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = PTM(mat)
op0 = PTM(mat0)
op1 = PTM(mat1)
op01 = op1.tensor(op0)
eye = PTM(self.ptmI)
with self.subTest(msg="qargs=[0]"):
value = op + op0([0])
target = op + eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op + op0([1])
target = op + eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op + op0([2])
target = op + op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op + op01([0, 1])
target = op + eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op + op01([1, 0])
target = op + eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op + op01([0, 2])
target = op + op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op + op01([2, 0])
target = op + op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_sub_qargs(self):
"""Test subtract method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = PTM(mat)
op0 = PTM(mat0)
op1 = PTM(mat1)
op01 = op1.tensor(op0)
eye = PTM(self.ptmI)
with self.subTest(msg="qargs=[0]"):
value = op - op0([0])
target = op - eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op - op0([1])
target = op - eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op - op0([2])
target = op - op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op - op01([0, 1])
target = op - eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op - op01([1, 0])
target = op - eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op - op01([0, 2])
target = op - op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op - op01([2, 0])
target = op - op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_add_except(self):
"""Test add method raises exceptions."""
chan1 = PTM(self.ptmI)
chan2 = PTM(np.eye(16))
self.assertRaises(QiskitError, chan1._add, chan2)
self.assertRaises(QiskitError, chan1._add, 5)
def test_multiply(self):
"""Test multiply method."""
chan = PTM(self.ptmI)
val = 0.5
targ = PTM(val * self.ptmI)
self.assertEqual(chan._multiply(val), targ)
self.assertEqual(val * chan, targ)
targ = PTM(self.ptmI * val)
self.assertEqual(chan * val, targ)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
chan = PTM(self.ptmI)
self.assertRaises(QiskitError, chan._multiply, "s")
self.assertRaises(QiskitError, chan.__rmul__, "s")
self.assertRaises(QiskitError, chan._multiply, chan)
self.assertRaises(QiskitError, chan.__rmul__, chan)
def test_negate(self):
"""Test negate method"""
chan = PTM(self.ptmI)
targ = PTM(-self.ptmI)
self.assertEqual(-chan, targ)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for Stinespring quantum channel representation class."""
import copy
import unittest
import numpy as np
from numpy.testing import assert_allclose
from qiskit import QiskitError
from qiskit.quantum_info.states import DensityMatrix
from qiskit.quantum_info import Stinespring
from .channel_test_case import ChannelTestCase
class TestStinespring(ChannelTestCase):
"""Tests for Stinespring channel representation."""
def test_init(self):
"""Test initialization"""
# Initialize from unitary
chan = Stinespring(self.UI)
assert_allclose(chan.data, self.UI)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize from Stinespring
chan = Stinespring(self.depol_stine(0.5))
assert_allclose(chan.data, self.depol_stine(0.5))
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize from Non-CPTP
stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2)
chan = Stinespring((stine_l, stine_r))
assert_allclose(chan.data, (stine_l, stine_r))
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize with redundant second op
chan = Stinespring((stine_l, stine_l))
assert_allclose(chan.data, stine_l)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Wrong input or output dims should raise exception
self.assertRaises(QiskitError, Stinespring, stine_l, input_dims=4, output_dims=4)
def test_circuit_init(self):
"""Test initialization from a circuit."""
circuit, target = self.simple_circuit_no_measure()
op = Stinespring(circuit)
target = Stinespring(target)
self.assertEqual(op, target)
def test_circuit_init_except(self):
"""Test initialization from circuit with measure raises exception."""
circuit = self.simple_circuit_with_measure()
self.assertRaises(QiskitError, Stinespring, circuit)
def test_equal(self):
"""Test __eq__ method"""
stine = tuple(self.rand_matrix(4, 2) for _ in range(2))
self.assertEqual(Stinespring(stine), Stinespring(stine))
def test_copy(self):
"""Test copy method"""
mat = np.eye(4)
with self.subTest("Deep copy"):
orig = Stinespring(mat)
cpy = orig.copy()
cpy._data[0][0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = Stinespring(mat)
clone = copy.copy(orig)
clone._data[0][0, 0] = 0.0
self.assertTrue(clone == orig)
def test_clone(self):
"""Test clone method"""
mat = np.eye(4)
orig = Stinespring(mat)
clone = copy.copy(orig)
clone._data[0][0, 0] = 0.0
self.assertTrue(clone == orig)
def test_is_cptp(self):
"""Test is_cptp method."""
self.assertTrue(Stinespring(self.depol_stine(0.5)).is_cptp())
self.assertTrue(Stinespring(self.UX).is_cptp())
# Non-CP
stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2)
self.assertFalse(Stinespring((stine_l, stine_r)).is_cptp())
self.assertFalse(Stinespring(self.UI + self.UX).is_cptp())
def test_conjugate(self):
"""Test conjugate method."""
stine_l, stine_r = self.rand_matrix(16, 2), self.rand_matrix(16, 2)
# Single Stinespring list
targ = Stinespring(stine_l.conj(), output_dims=4)
chan1 = Stinespring(stine_l, output_dims=4)
chan = chan1.conjugate()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (2, 4))
# Double Stinespring list
targ = Stinespring((stine_l.conj(), stine_r.conj()), output_dims=4)
chan1 = Stinespring((stine_l, stine_r), output_dims=4)
chan = chan1.conjugate()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (2, 4))
def test_transpose(self):
"""Test transpose method."""
stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2)
# Single square Stinespring list
targ = Stinespring(stine_l.T, 4, 2)
chan1 = Stinespring(stine_l, 2, 4)
chan = chan1.transpose()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
# Double square Stinespring list
targ = Stinespring((stine_l.T, stine_r.T), 4, 2)
chan1 = Stinespring((stine_l, stine_r), 2, 4)
chan = chan1.transpose()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
def test_adjoint(self):
"""Test adjoint method."""
stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2)
# Single square Stinespring list
targ = Stinespring(stine_l.T.conj(), 4, 2)
chan1 = Stinespring(stine_l, 2, 4)
chan = chan1.adjoint()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
# Double square Stinespring list
targ = Stinespring((stine_l.T.conj(), stine_r.T.conj()), 4, 2)
chan1 = Stinespring((stine_l, stine_r), 2, 4)
chan = chan1.adjoint()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError, Stinespring(np.eye(2)).compose, Stinespring(np.eye(4)))
self.assertRaises(QiskitError, Stinespring(np.eye(2)).compose, 2)
def test_compose(self):
"""Test compose method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Stinespring(self.UX)
chan2 = Stinespring(self.UY)
chan = chan1.compose(chan2)
rho_targ = rho_init & Stinespring(self.UZ)
self.assertEqual(rho_init.evolve(chan), rho_targ)
# 50% depolarizing channel
chan1 = Stinespring(self.depol_stine(0.5))
chan = chan1.compose(chan1)
rho_targ = rho_init & Stinespring(self.depol_stine(0.75))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Compose different dimensions
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(8, 4)
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=4, output_dims=2)
rho_targ = rho_init & chan1 & chan2
chan = chan1.compose(chan2)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan1 & chan2
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_dot(self):
"""Test deprecated front compose method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Stinespring(self.UX)
chan2 = Stinespring(self.UY)
rho_targ = rho_init.evolve(Stinespring(self.UZ))
self.assertEqual(rho_init.evolve(chan1.dot(chan2)), rho_targ)
self.assertEqual(rho_init.evolve(chan1 @ chan2), rho_targ)
# 50% depolarizing channel
chan1 = Stinespring(self.depol_stine(0.5))
rho_targ = rho_init & Stinespring(self.depol_stine(0.75))
self.assertEqual(rho_init.evolve(chan1.dot(chan1)), rho_targ)
self.assertEqual(rho_init.evolve(chan1 @ chan1), rho_targ)
# Compose different dimensions
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(8, 4)
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=4, output_dims=2)
rho_targ = rho_init & chan1 & chan2
self.assertEqual(rho_init.evolve(chan2.dot(chan1)), rho_targ)
self.assertEqual(rho_init.evolve(chan2 @ chan1), rho_targ)
def test_compose_front(self):
"""Test deprecated front compose method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Stinespring(self.UX)
chan2 = Stinespring(self.UY)
chan = chan1.compose(chan2, front=True)
rho_targ = rho_init & Stinespring(self.UZ)
self.assertEqual(rho_init.evolve(chan), rho_targ)
# 50% depolarizing channel
chan1 = Stinespring(self.depol_stine(0.5))
chan = chan1.compose(chan1, front=True)
rho_targ = rho_init & Stinespring(self.depol_stine(0.75))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Compose different dimensions
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(8, 4)
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=4, output_dims=2)
rho_targ = rho_init & chan1 & chan2
chan = chan2.compose(chan1, front=True)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_expand(self):
"""Test expand method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = Stinespring(self.UI)
chan2 = Stinespring(self.UX)
# X \otimes I
chan = chan1.expand(chan2)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan2.expand(chan1)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Completely depolarizing
chan_dep = Stinespring(self.depol_stine(1))
chan = chan_dep.expand(chan_dep)
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_tensor(self):
"""Test tensor method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = Stinespring(self.UI)
chan2 = Stinespring(self.UX)
# X \otimes I
chan = chan2.tensor(chan1)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan1.tensor(chan2)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Completely depolarizing
chan_dep = Stinespring(self.depol_stine(1))
chan = chan_dep.tensor(chan_dep)
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_power(self):
"""Test power method."""
# 10% depolarizing channel
rho_init = DensityMatrix(np.diag([1, 0]))
p_id = 0.9
chan1 = Stinespring(self.depol_stine(1 - p_id))
# Compose 3 times
p_id3 = p_id**3
chan = chan1.power(3)
rho_targ = rho_init & chan1 & chan1 & chan1
self.assertEqual(rho_init & chan, rho_targ)
rho_targ = rho_init & Stinespring(self.depol_stine(1 - p_id3))
self.assertEqual(rho_init & chan, rho_targ)
def test_add(self):
"""Test add method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(16, 2)
# Random Single-Stinespring maps
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=2, output_dims=4)
rho_targ = (rho_init & chan1) + (rho_init & chan2)
chan = chan1._add(chan2)
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan1 + chan2
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Random Single-Stinespring maps
chan = Stinespring((stine1, stine2))
rho_targ = 2 * (rho_init & chan)
chan = chan._add(chan)
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_subtract(self):
"""Test subtract method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(16, 2)
# Random Single-Stinespring maps
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=2, output_dims=4)
rho_targ = (rho_init & chan1) - (rho_init & chan2)
chan = chan1 - chan2
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Random Single-Stinespring maps
chan = Stinespring((stine1, stine2))
rho_targ = 0 * (rho_init & chan)
chan = chan - chan
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_add_qargs(self):
"""Test add method with qargs."""
rho = DensityMatrix(self.rand_rho(8))
stine = self.rand_matrix(32, 8)
stine0 = self.rand_matrix(8, 2)
op = Stinespring(stine)
op0 = Stinespring(stine0)
eye = Stinespring(self.UI)
with self.subTest(msg="qargs=[0]"):
value = op + op0([0])
target = op + eye.tensor(eye).tensor(op0)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[1]"):
value = op + op0([1])
target = op + eye.tensor(op0).tensor(eye)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[2]"):
value = op + op0([2])
target = op + op0.tensor(eye).tensor(eye)
self.assertEqual(rho & value, rho & target)
def test_sub_qargs(self):
"""Test sub method with qargs."""
rho = DensityMatrix(self.rand_rho(8))
stine = self.rand_matrix(32, 8)
stine0 = self.rand_matrix(8, 2)
op = Stinespring(stine)
op0 = Stinespring(stine0)
eye = Stinespring(self.UI)
with self.subTest(msg="qargs=[0]"):
value = op - op0([0])
target = op - eye.tensor(eye).tensor(op0)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[1]"):
value = op - op0([1])
target = op - eye.tensor(op0).tensor(eye)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[2]"):
value = op - op0([2])
target = op - op0.tensor(eye).tensor(eye)
self.assertEqual(rho & value, rho & target)
def test_multiply(self):
"""Test multiply method."""
# Random initial state and Stinespring ops
rho_init = DensityMatrix(self.rand_rho(2))
val = 0.5
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(16, 2)
# Single Stinespring set
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
rho_targ = val * (rho_init & chan1)
chan = chan1._multiply(val)
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = val * chan1
self.assertEqual(rho_init.evolve(chan), rho_targ)
rho_targ = (rho_init & chan1) * val
chan = chan1 * val
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Double Stinespring set
chan2 = Stinespring((stine1, stine2), input_dims=2, output_dims=4)
rho_targ = val * (rho_init & chan2)
chan = chan2._multiply(val)
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = val * chan2
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
chan = Stinespring(self.depol_stine(1))
self.assertRaises(QiskitError, chan._multiply, "s")
self.assertRaises(QiskitError, chan.__rmul__, "s")
self.assertRaises(QiskitError, chan._multiply, chan)
self.assertRaises(QiskitError, chan.__rmul__, chan)
def test_negate(self):
"""Test negate method"""
rho_init = DensityMatrix(np.diag([1, 0]))
rho_targ = DensityMatrix(np.diag([-0.5, -0.5]))
chan = -Stinespring(self.depol_stine(1))
self.assertEqual(rho_init.evolve(chan), rho_targ)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for SuperOp quantum channel representation class."""
import copy
import unittest
import numpy as np
from numpy.testing import assert_allclose
from qiskit import QiskitError, QuantumCircuit
from qiskit.quantum_info.states import DensityMatrix
from qiskit.quantum_info.operators import Operator
from qiskit.quantum_info.operators.channel import SuperOp
from .channel_test_case import ChannelTestCase
class TestSuperOp(ChannelTestCase):
"""Tests for SuperOp channel representation."""
def test_init(self):
"""Test initialization"""
chan = SuperOp(self.sopI)
assert_allclose(chan.data, self.sopI)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
mat = np.zeros((4, 16))
chan = SuperOp(mat)
assert_allclose(chan.data, mat)
self.assertEqual(chan.dim, (4, 2))
self.assertIsNone(chan.num_qubits)
chan = SuperOp(mat.T)
assert_allclose(chan.data, mat.T)
self.assertEqual(chan.dim, (2, 4))
self.assertIsNone(chan.num_qubits)
# Wrong input or output dims should raise exception
self.assertRaises(QiskitError, SuperOp, mat, input_dims=[4], output_dims=[4])
def test_circuit_init(self):
"""Test initialization from a circuit."""
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.x(1)
circuit.ry(np.pi / 2, 2)
op = SuperOp(circuit)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = SuperOp(Operator(np.kron(y90, np.kron(self.UX, self.UH))))
self.assertEqual(target, op)
# Test decomposition of Controlled-Phase gate
lam = np.pi / 4
circuit = QuantumCircuit(2)
circuit.cp(lam, 0, 1)
op = SuperOp(circuit)
target = SuperOp(Operator(np.diag([1, 1, 1, np.exp(1j * lam)])))
self.assertEqual(target, op)
# Test decomposition of controlled-H gate
circuit = QuantumCircuit(2)
circuit.ch(0, 1)
op = SuperOp(circuit)
target = SuperOp(
Operator(np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1])))
)
self.assertEqual(target, op)
def test_circuit_init_except(self):
"""Test initialization from circuit with measure raises exception."""
circuit = self.simple_circuit_with_measure()
self.assertRaises(QiskitError, SuperOp, circuit)
def test_equal(self):
"""Test __eq__ method"""
mat = self.rand_matrix(4, 4)
self.assertEqual(SuperOp(mat), SuperOp(mat))
def test_copy(self):
"""Test copy method"""
mat = np.eye(4)
with self.subTest("Deep copy"):
orig = SuperOp(mat)
cpy = orig.copy()
cpy._data[0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = SuperOp(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_clone(self):
"""Test clone method"""
mat = np.eye(4)
orig = SuperOp(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_evolve(self):
"""Test evolve method."""
input_rho = DensityMatrix([[0, 0], [0, 1]])
# Identity channel
chan = SuperOp(self.sopI)
target_rho = DensityMatrix([[0, 0], [0, 1]])
self.assertEqual(input_rho.evolve(chan), target_rho)
# Hadamard channel
mat = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
chan = SuperOp(np.kron(mat.conj(), mat))
target_rho = DensityMatrix(np.array([[1, -1], [-1, 1]]) / 2)
self.assertEqual(input_rho.evolve(chan), target_rho)
# Completely depolarizing channel
chan = SuperOp(self.depol_sop(1))
target_rho = DensityMatrix(np.eye(2) / 2)
self.assertEqual(input_rho.evolve(chan), target_rho)
def test_evolve_subsystem(self):
"""Test subsystem evolve method."""
# Single-qubit random superoperators
op_a = SuperOp(self.rand_matrix(4, 4))
op_b = SuperOp(self.rand_matrix(4, 4))
op_c = SuperOp(self.rand_matrix(4, 4))
id1 = SuperOp(np.eye(4))
id2 = SuperOp(np.eye(16))
rho = DensityMatrix(self.rand_rho(8))
# Test evolving single-qubit of 3-qubit system
op = op_a
# Evolve on qubit 0
full_op = id2.tensor(op_a)
rho_targ = rho.evolve(full_op)
rho_test = rho.evolve(op, qargs=[0])
self.assertEqual(rho_test, rho_targ)
# Evolve on qubit 1
full_op = id1.tensor(op_a).tensor(id1)
rho_targ = rho.evolve(full_op)
rho_test = rho.evolve(op, qargs=[1])
self.assertEqual(rho_test, rho_targ)
# Evolve on qubit 2
full_op = op_a.tensor(id2)
rho_targ = rho.evolve(full_op)
rho_test = rho.evolve(op, qargs=[2])
self.assertEqual(rho_test, rho_targ)
# Test 2-qubit evolution
op = op_b.tensor(op_a)
# Evolve on qubits [0, 2]
full_op = op_b.tensor(id1).tensor(op_a)
rho_targ = rho.evolve(full_op)
rho_test = rho.evolve(op, qargs=[0, 2])
self.assertEqual(rho_test, rho_targ)
# Evolve on qubits [2, 0]
full_op = op_a.tensor(id1).tensor(op_b)
rho_targ = rho.evolve(full_op)
rho_test = rho.evolve(op, qargs=[2, 0])
self.assertEqual(rho_test, rho_targ)
# Test 3-qubit evolution
op = op_c.tensor(op_b).tensor(op_a)
# Evolve on qubits [0, 1, 2]
full_op = op
rho_targ = rho.evolve(full_op)
rho_test = rho.evolve(op, qargs=[0, 1, 2])
self.assertEqual(rho_test, rho_targ)
# Evolve on qubits [2, 1, 0]
full_op = op_a.tensor(op_b).tensor(op_c)
rho_targ = rho.evolve(full_op)
rho_test = rho.evolve(op, qargs=[2, 1, 0])
self.assertEqual(rho_test, rho_targ)
def test_is_cptp(self):
"""Test is_cptp method."""
self.assertTrue(SuperOp(self.depol_sop(0.25)).is_cptp())
# Non-CPTP should return false
self.assertFalse(SuperOp(1.25 * self.sopI - 0.25 * self.depol_sop(1)).is_cptp())
def test_conjugate(self):
"""Test conjugate method."""
mat = self.rand_matrix(4, 4)
chan = SuperOp(mat)
targ = SuperOp(np.conjugate(mat))
self.assertEqual(chan.conjugate(), targ)
def test_transpose(self):
"""Test transpose method."""
mat = self.rand_matrix(4, 4)
chan = SuperOp(mat)
targ = SuperOp(np.transpose(mat))
self.assertEqual(chan.transpose(), targ)
def test_adjoint(self):
"""Test adjoint method."""
mat = self.rand_matrix(4, 4)
chan = SuperOp(mat)
targ = SuperOp(np.transpose(np.conj(mat)))
self.assertEqual(chan.adjoint(), targ)
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError, SuperOp(np.eye(4)).compose, SuperOp(np.eye(16)))
self.assertRaises(QiskitError, SuperOp(np.eye(4)).compose, 2)
def test_compose(self):
"""Test compose method."""
# UnitaryChannel evolution
chan1 = SuperOp(self.sopX)
chan2 = SuperOp(self.sopY)
chan = chan1.compose(chan2)
targ = SuperOp(self.sopZ)
self.assertEqual(chan, targ)
# 50% depolarizing channel
chan1 = SuperOp(self.depol_sop(0.5))
chan = chan1.compose(chan1)
targ = SuperOp(self.depol_sop(0.75))
self.assertEqual(chan, targ)
# Random superoperator
mat1 = self.rand_matrix(4, 4)
mat2 = self.rand_matrix(4, 4)
chan1 = SuperOp(mat1)
chan2 = SuperOp(mat2)
targ = SuperOp(np.dot(mat2, mat1))
self.assertEqual(chan1.compose(chan2), targ)
self.assertEqual(chan1 & chan2, targ)
targ = SuperOp(np.dot(mat1, mat2))
self.assertEqual(chan2.compose(chan1), targ)
self.assertEqual(chan2 & chan1, targ)
# Compose different dimensions
chan1 = SuperOp(self.rand_matrix(16, 4))
chan2 = SuperOp(
self.rand_matrix(4, 16),
)
chan = chan1.compose(chan2)
self.assertEqual(chan.dim, (2, 2))
chan = chan2.compose(chan1)
self.assertEqual(chan.dim, (4, 4))
def test_dot(self):
"""Test dot method."""
# UnitaryChannel evolution
chan1 = SuperOp(self.sopX)
chan2 = SuperOp(self.sopY)
targ = SuperOp(self.sopZ)
self.assertEqual(chan1.dot(chan2), targ)
self.assertEqual(chan1 @ chan2, targ)
# 50% depolarizing channel
chan1 = SuperOp(self.depol_sop(0.5))
targ = SuperOp(self.depol_sop(0.75))
self.assertEqual(chan1.dot(chan1), targ)
self.assertEqual(chan1 @ chan1, targ)
# Random superoperator
mat1 = self.rand_matrix(4, 4)
mat2 = self.rand_matrix(4, 4)
chan1 = SuperOp(mat1)
chan2 = SuperOp(mat2)
targ = SuperOp(np.dot(mat2, mat1))
self.assertEqual(chan2.dot(chan1), targ)
targ = SuperOp(np.dot(mat1, mat2))
# Compose different dimensions
chan1 = SuperOp(self.rand_matrix(16, 4))
chan2 = SuperOp(self.rand_matrix(4, 16))
chan = chan1.dot(chan2)
self.assertEqual(chan.dim, (4, 4))
chan = chan1 @ chan2
self.assertEqual(chan.dim, (4, 4))
chan = chan2.dot(chan1)
self.assertEqual(chan.dim, (2, 2))
chan = chan2 @ chan1
self.assertEqual(chan.dim, (2, 2))
def test_compose_front(self):
"""Test front compose method."""
# DEPRECATED
# UnitaryChannel evolution
chan1 = SuperOp(self.sopX)
chan2 = SuperOp(self.sopY)
chan = chan1.compose(chan2, front=True)
targ = SuperOp(self.sopZ)
self.assertEqual(chan, targ)
# 50% depolarizing channel
chan1 = SuperOp(self.depol_sop(0.5))
chan = chan1.compose(chan1, front=True)
targ = SuperOp(self.depol_sop(0.75))
self.assertEqual(chan, targ)
# Random superoperator
mat1 = self.rand_matrix(4, 4)
mat2 = self.rand_matrix(4, 4)
chan1 = SuperOp(mat1)
chan2 = SuperOp(mat2)
targ = SuperOp(np.dot(mat2, mat1))
self.assertEqual(chan2.compose(chan1, front=True), targ)
targ = SuperOp(np.dot(mat1, mat2))
self.assertEqual(chan1.compose(chan2, front=True), targ)
# Compose different dimensions
chan1 = SuperOp(self.rand_matrix(16, 4))
chan2 = SuperOp(self.rand_matrix(4, 16))
chan = chan1.compose(chan2, front=True)
self.assertEqual(chan.dim, (4, 4))
chan = chan2.compose(chan1, front=True)
self.assertEqual(chan.dim, (2, 2))
def test_compose_subsystem(self):
"""Test subsystem compose method."""
# 3-qubit superoperator
mat = self.rand_matrix(64, 64)
mat_a = self.rand_matrix(4, 4)
mat_b = self.rand_matrix(4, 4)
mat_c = self.rand_matrix(4, 4)
iden = SuperOp(np.eye(4))
op = SuperOp(mat)
op1 = SuperOp(mat_a)
op2 = SuperOp(mat_b).tensor(SuperOp(mat_a))
op3 = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
# op3 qargs=[0, 1, 2]
full_op = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
targ = np.dot(full_op.data, mat)
self.assertEqual(op.compose(op3, qargs=[0, 1, 2]), SuperOp(targ))
self.assertEqual(op & op3([0, 1, 2]), SuperOp(targ))
# op3 qargs=[2, 1, 0]
full_op = SuperOp(mat_a).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_c))
targ = np.dot(full_op.data, mat)
self.assertEqual(op.compose(op3, qargs=[2, 1, 0]), SuperOp(targ))
self.assertEqual(op & op3([2, 1, 0]), SuperOp(targ))
# op2 qargs=[0, 1]
full_op = iden.tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
targ = np.dot(full_op.data, mat)
self.assertEqual(op.compose(op2, qargs=[0, 1]), SuperOp(targ))
self.assertEqual(op & op2([0, 1]), SuperOp(targ))
# op2 qargs=[2, 0]
full_op = SuperOp(mat_a).tensor(iden).tensor(SuperOp(mat_b))
targ = np.dot(full_op.data, mat)
self.assertEqual(op.compose(op2, qargs=[2, 0]), SuperOp(targ))
self.assertEqual(op & op2([2, 0]), SuperOp(targ))
# op1 qargs=[0]
full_op = iden.tensor(iden).tensor(SuperOp(mat_a))
targ = np.dot(full_op.data, mat)
self.assertEqual(op.compose(op1, qargs=[0]), SuperOp(targ))
self.assertEqual(op & op1([0]), SuperOp(targ))
# op1 qargs=[1]
full_op = iden.tensor(SuperOp(mat_a)).tensor(iden)
targ = np.dot(full_op.data, mat)
self.assertEqual(op.compose(op1, qargs=[1]), SuperOp(targ))
self.assertEqual(op & op1([1]), SuperOp(targ))
# op1 qargs=[2]
full_op = SuperOp(mat_a).tensor(iden).tensor(iden)
targ = np.dot(full_op.data, mat)
self.assertEqual(op.compose(op1, qargs=[2]), SuperOp(targ))
self.assertEqual(op & op1([2]), SuperOp(targ))
def test_dot_subsystem(self):
"""Test subsystem dot method."""
# 3-qubit operator
mat = self.rand_matrix(64, 64)
mat_a = self.rand_matrix(4, 4)
mat_b = self.rand_matrix(4, 4)
mat_c = self.rand_matrix(4, 4)
iden = SuperOp(np.eye(4))
op = SuperOp(mat)
op1 = SuperOp(mat_a)
op2 = SuperOp(mat_b).tensor(SuperOp(mat_a))
op3 = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
# op3 qargs=[0, 1, 2]
full_op = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.dot(op3, qargs=[0, 1, 2]), SuperOp(targ))
# op3 qargs=[2, 1, 0]
full_op = SuperOp(mat_a).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_c))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.dot(op3, qargs=[2, 1, 0]), SuperOp(targ))
# op2 qargs=[0, 1]
full_op = iden.tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.dot(op2, qargs=[0, 1]), SuperOp(targ))
# op2 qargs=[2, 0]
full_op = SuperOp(mat_a).tensor(iden).tensor(SuperOp(mat_b))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.dot(op2, qargs=[2, 0]), SuperOp(targ))
# op1 qargs=[0]
full_op = iden.tensor(iden).tensor(SuperOp(mat_a))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.dot(op1, qargs=[0]), SuperOp(targ))
# op1 qargs=[1]
full_op = iden.tensor(SuperOp(mat_a)).tensor(iden)
targ = np.dot(mat, full_op.data)
self.assertEqual(op.dot(op1, qargs=[1]), SuperOp(targ))
# op1 qargs=[2]
full_op = SuperOp(mat_a).tensor(iden).tensor(iden)
targ = np.dot(mat, full_op.data)
self.assertEqual(op.dot(op1, qargs=[2]), SuperOp(targ))
def test_compose_front_subsystem(self):
"""Test subsystem front compose method."""
# 3-qubit operator
mat = self.rand_matrix(64, 64)
mat_a = self.rand_matrix(4, 4)
mat_b = self.rand_matrix(4, 4)
mat_c = self.rand_matrix(4, 4)
iden = SuperOp(np.eye(4))
op = SuperOp(mat)
op1 = SuperOp(mat_a)
op2 = SuperOp(mat_b).tensor(SuperOp(mat_a))
op3 = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
# op3 qargs=[0, 1, 2]
full_op = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.compose(op3, qargs=[0, 1, 2], front=True), SuperOp(targ))
# op3 qargs=[2, 1, 0]
full_op = SuperOp(mat_a).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_c))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.compose(op3, qargs=[2, 1, 0], front=True), SuperOp(targ))
# op2 qargs=[0, 1]
full_op = iden.tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.compose(op2, qargs=[0, 1], front=True), SuperOp(targ))
# op2 qargs=[2, 0]
full_op = SuperOp(mat_a).tensor(iden).tensor(SuperOp(mat_b))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.compose(op2, qargs=[2, 0], front=True), SuperOp(targ))
# op1 qargs=[0]
full_op = iden.tensor(iden).tensor(SuperOp(mat_a))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.compose(op1, qargs=[0], front=True), SuperOp(targ))
# op1 qargs=[1]
full_op = iden.tensor(SuperOp(mat_a)).tensor(iden)
targ = np.dot(mat, full_op.data)
self.assertEqual(op.compose(op1, qargs=[1], front=True), SuperOp(targ))
# op1 qargs=[2]
full_op = SuperOp(mat_a).tensor(iden).tensor(iden)
targ = np.dot(mat, full_op.data)
self.assertEqual(op.compose(op1, qargs=[2], front=True), SuperOp(targ))
def test_expand(self):
"""Test expand method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = SuperOp(self.sopI)
chan2 = SuperOp(self.sopX)
# X \otimes I
chan = chan1.expand(chan2)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan2.expand(chan1)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_tensor(self):
"""Test tensor method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = SuperOp(self.sopI)
chan2 = SuperOp(self.sopX)
# X \otimes I
chan = chan2.tensor(chan1)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan2 ^ chan1
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan1.tensor(chan2)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan1 ^ chan2
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_power(self):
"""Test power method."""
# 10% depolarizing channel
p_id = 0.9
depol = SuperOp(self.depol_sop(1 - p_id))
# Compose 3 times
p_id3 = p_id**3
chan3 = depol.power(3)
targ3 = SuperOp(self.depol_sop(1 - p_id3))
self.assertEqual(chan3, targ3)
def test_add(self):
"""Test add method."""
mat1 = 0.5 * self.sopI
mat2 = 0.5 * self.depol_sop(1)
chan1 = SuperOp(mat1)
chan2 = SuperOp(mat2)
targ = SuperOp(mat1 + mat2)
self.assertEqual(chan1._add(chan2), targ)
self.assertEqual(chan1 + chan2, targ)
targ = SuperOp(mat1 - mat2)
self.assertEqual(chan1 - chan2, targ)
def test_add_qargs(self):
"""Test add method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = SuperOp(mat)
op0 = SuperOp(mat0)
op1 = SuperOp(mat1)
op01 = op1.tensor(op0)
eye = SuperOp(self.sopI)
with self.subTest(msg="qargs=[0]"):
value = op + op0([0])
target = op + eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op + op0([1])
target = op + eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op + op0([2])
target = op + op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op + op01([0, 1])
target = op + eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op + op01([1, 0])
target = op + eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op + op01([0, 2])
target = op + op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op + op01([2, 0])
target = op + op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_sub_qargs(self):
"""Test subtract method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = SuperOp(mat)
op0 = SuperOp(mat0)
op1 = SuperOp(mat1)
op01 = op1.tensor(op0)
eye = SuperOp(self.sopI)
with self.subTest(msg="qargs=[0]"):
value = op - op0([0])
target = op - eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op - op0([1])
target = op - eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op - op0([2])
target = op - op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op - op01([0, 1])
target = op - eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op - op01([1, 0])
target = op - eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op - op01([0, 2])
target = op - op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op - op01([2, 0])
target = op - op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_add_except(self):
"""Test add method raises exceptions."""
chan1 = SuperOp(self.sopI)
chan2 = SuperOp(np.eye(16))
self.assertRaises(QiskitError, chan1._add, chan2)
self.assertRaises(QiskitError, chan1._add, 5)
def test_multiply(self):
"""Test multiply method."""
chan = SuperOp(self.sopI)
val = 0.5
targ = SuperOp(val * self.sopI)
self.assertEqual(chan._multiply(val), targ)
self.assertEqual(val * chan, targ)
targ = SuperOp(self.sopI * val)
self.assertEqual(chan * val, targ)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
chan = SuperOp(self.sopI)
self.assertRaises(QiskitError, chan._multiply, "s")
self.assertRaises(QiskitError, chan.__rmul__, "s")
self.assertRaises(QiskitError, chan._multiply, chan)
self.assertRaises(QiskitError, chan.__rmul__, chan)
def test_negate(self):
"""Test negate method"""
chan = SuperOp(self.sopI)
targ = SuperOp(-self.sopI)
self.assertEqual(-chan, targ)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for quantum channel representation transformations."""
import unittest
import numpy as np
from qiskit import QiskitError
from qiskit.quantum_info.states import DensityMatrix
from qiskit.quantum_info.operators.predicates import matrix_equal
from qiskit.quantum_info.operators.operator import Operator
from qiskit.quantum_info.operators.channel.choi import Choi
from qiskit.quantum_info.operators.channel.superop import SuperOp
from qiskit.quantum_info.operators.channel.kraus import Kraus
from qiskit.quantum_info.operators.channel.stinespring import Stinespring
from qiskit.quantum_info.operators.channel.ptm import PTM
from qiskit.quantum_info.operators.channel.chi import Chi
from .channel_test_case import ChannelTestCase
class TestTransformations(ChannelTestCase):
"""Tests for Operator channel representation."""
unitary_mat = [
ChannelTestCase.UI,
ChannelTestCase.UX,
ChannelTestCase.UY,
ChannelTestCase.UZ,
ChannelTestCase.UH,
]
unitary_choi = [
ChannelTestCase.choiI,
ChannelTestCase.choiX,
ChannelTestCase.choiY,
ChannelTestCase.choiZ,
ChannelTestCase.choiH,
]
unitary_chi = [
ChannelTestCase.chiI,
ChannelTestCase.chiX,
ChannelTestCase.chiY,
ChannelTestCase.chiZ,
ChannelTestCase.chiH,
]
unitary_sop = [
ChannelTestCase.sopI,
ChannelTestCase.sopX,
ChannelTestCase.sopY,
ChannelTestCase.sopZ,
ChannelTestCase.sopH,
]
unitary_ptm = [
ChannelTestCase.ptmI,
ChannelTestCase.ptmX,
ChannelTestCase.ptmY,
ChannelTestCase.ptmZ,
ChannelTestCase.ptmH,
]
def test_operator_to_operator(self):
"""Test Operator to Operator transformation."""
# Test unitary channels
for mat in self.unitary_mat:
chan1 = Operator(mat)
chan2 = Operator(chan1)
self.assertEqual(chan1, chan2)
def test_operator_to_choi(self):
"""Test Operator to Choi transformation."""
# Test unitary channels
for mat, choi in zip(self.unitary_mat, self.unitary_choi):
chan1 = Choi(choi)
chan2 = Choi(Operator(mat))
self.assertEqual(chan1, chan2)
def test_operator_to_superop(self):
"""Test Operator to SuperOp transformation."""
# Test unitary channels
for mat, sop in zip(self.unitary_mat, self.unitary_sop):
chan1 = SuperOp(sop)
chan2 = SuperOp(Operator(mat))
self.assertEqual(chan1, chan2)
def test_operator_to_kraus(self):
"""Test Operator to Kraus transformation."""
# Test unitary channels
for mat in self.unitary_mat:
chan1 = Kraus(mat)
chan2 = Kraus(Operator(mat))
self.assertEqual(chan1, chan2)
def test_operator_to_stinespring(self):
"""Test Operator to Stinespring transformation."""
# Test unitary channels
for mat in self.unitary_mat:
chan1 = Stinespring(mat)
chan2 = Stinespring(Operator(chan1))
self.assertEqual(chan1, chan2)
def test_operator_to_chi(self):
"""Test Operator to Chi transformation."""
# Test unitary channels
for mat, chi in zip(self.unitary_mat, self.unitary_chi):
chan1 = Chi(chi)
chan2 = Chi(Operator(mat))
self.assertEqual(chan1, chan2)
def test_operator_to_ptm(self):
"""Test Operator to PTM transformation."""
# Test unitary channels
for mat, ptm in zip(self.unitary_mat, self.unitary_ptm):
chan1 = PTM(ptm)
chan2 = PTM(Operator(mat))
self.assertEqual(chan1, chan2)
def test_choi_to_operator(self):
"""Test Choi to Operator transformation."""
# Test unitary channels
for mat, choi in zip(self.unitary_mat, self.unitary_choi):
chan1 = Operator(mat)
chan2 = Operator(Choi(choi))
self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True))
def test_choi_to_choi(self):
"""Test Choi to Choi transformation."""
# Test unitary channels
for choi in self.unitary_choi:
chan1 = Choi(choi)
chan2 = Choi(chan1)
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Choi(self.depol_choi(p))
chan2 = Choi(chan1)
self.assertEqual(chan1, chan2)
def test_choi_to_superop(self):
"""Test Choi to SuperOp transformation."""
# Test unitary channels
for choi, sop in zip(self.unitary_choi, self.unitary_sop):
chan1 = SuperOp(sop)
chan2 = SuperOp(Choi(choi))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = SuperOp(self.depol_sop(p))
chan2 = SuperOp(Choi(self.depol_choi(p)))
self.assertEqual(chan1, chan2)
def test_choi_to_kraus(self):
"""Test Choi to Kraus transformation."""
# Test unitary channels
for mat, choi in zip(self.unitary_mat, self.unitary_choi):
chan1 = Kraus(mat)
chan2 = Kraus(Choi(choi))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Kraus(self.depol_kraus(p)))
output = rho.evolve(Kraus(Choi(self.depol_choi(p))))
self.assertEqual(output, target)
def test_choi_to_stinespring(self):
"""Test Choi to Stinespring transformation."""
# Test unitary channels
for mat, choi in zip(self.unitary_mat, self.unitary_choi):
chan1 = Kraus(mat)
chan2 = Kraus(Choi(choi))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Stinespring(self.depol_stine(p)))
output = rho.evolve(Stinespring(Choi(self.depol_choi(p))))
self.assertEqual(output, target)
def test_choi_to_chi(self):
"""Test Choi to Chi transformation."""
# Test unitary channels
for choi, chi in zip(self.unitary_choi, self.unitary_chi):
chan1 = Chi(chi)
chan2 = Chi(Choi(choi))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Chi(self.depol_chi(p))
chan2 = Chi(Choi(self.depol_choi(p)))
self.assertEqual(chan1, chan2)
def test_choi_to_ptm(self):
"""Test Choi to PTM transformation."""
# Test unitary channels
for choi, ptm in zip(self.unitary_choi, self.unitary_ptm):
chan1 = PTM(ptm)
chan2 = PTM(Choi(choi))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = PTM(self.depol_ptm(p))
chan2 = PTM(Choi(self.depol_choi(p)))
self.assertEqual(chan1, chan2)
def test_superop_to_operator(self):
"""Test SuperOp to Operator transformation."""
for mat, sop in zip(self.unitary_mat, self.unitary_sop):
chan1 = Operator(mat)
chan2 = Operator(SuperOp(sop))
self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True))
self.assertRaises(QiskitError, Operator, SuperOp(self.depol_sop(0.5)))
def test_superop_to_choi(self):
"""Test SuperOp to Choi transformation."""
# Test unitary channels
for choi, sop in zip(self.unitary_choi, self.unitary_sop):
chan1 = Choi(choi)
chan2 = Choi(SuperOp(sop))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0, 0.25, 0.5, 0.75, 1]:
chan1 = Choi(self.depol_choi(p))
chan2 = Choi(SuperOp(self.depol_sop(p)))
self.assertEqual(chan1, chan2)
def test_superop_to_superop(self):
"""Test SuperOp to SuperOp transformation."""
# Test unitary channels
for sop in self.unitary_sop:
chan1 = SuperOp(sop)
chan2 = SuperOp(chan1)
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0, 0.25, 0.5, 0.75, 1]:
chan1 = SuperOp(self.depol_sop(p))
chan2 = SuperOp(chan1)
self.assertEqual(chan1, chan2)
def test_superop_to_kraus(self):
"""Test SuperOp to Kraus transformation."""
# Test unitary channels
for mat, sop in zip(self.unitary_mat, self.unitary_sop):
chan1 = Kraus(mat)
chan2 = Kraus(SuperOp(sop))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Kraus(self.depol_kraus(p)))
output = rho.evolve(Kraus(SuperOp(self.depol_sop(p))))
self.assertEqual(output, target)
def test_superop_to_stinespring(self):
"""Test SuperOp to Stinespring transformation."""
# Test unitary channels
for mat, sop in zip(self.unitary_mat, self.unitary_sop):
chan1 = Stinespring(mat)
chan2 = Stinespring(SuperOp(sop))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Stinespring(self.depol_stine(p)))
output = rho.evolve(Stinespring(SuperOp(self.depol_sop(p))))
self.assertEqual(output, target)
def test_superop_to_chi(self):
"""Test SuperOp to Chi transformation."""
# Test unitary channels
for sop, ptm in zip(self.unitary_sop, self.unitary_ptm):
chan1 = PTM(ptm)
chan2 = PTM(SuperOp(sop))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Chi(self.depol_chi(p))
chan2 = Chi(SuperOp(self.depol_sop(p)))
self.assertEqual(chan1, chan2)
def test_superop_to_ptm(self):
"""Test SuperOp to PTM transformation."""
# Test unitary channels
for sop, ptm in zip(self.unitary_sop, self.unitary_ptm):
chan1 = PTM(ptm)
chan2 = PTM(SuperOp(sop))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = PTM(self.depol_ptm(p))
chan2 = PTM(SuperOp(self.depol_sop(p)))
self.assertEqual(chan1, chan2)
def test_kraus_to_operator(self):
"""Test Kraus to Operator transformation."""
for mat in self.unitary_mat:
chan1 = Operator(mat)
chan2 = Operator(Kraus(mat))
self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True))
self.assertRaises(QiskitError, Operator, Kraus(self.depol_kraus(0.5)))
def test_kraus_to_choi(self):
"""Test Kraus to Choi transformation."""
# Test unitary channels
for mat, choi in zip(self.unitary_mat, self.unitary_choi):
chan1 = Choi(choi)
chan2 = Choi(Kraus(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Choi(self.depol_choi(p))
chan2 = Choi(Kraus(self.depol_kraus(p)))
self.assertEqual(chan1, chan2)
def test_kraus_to_superop(self):
"""Test Kraus to SuperOp transformation."""
# Test unitary channels
for mat, sop in zip(self.unitary_mat, self.unitary_sop):
chan1 = SuperOp(sop)
chan2 = SuperOp(Kraus(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = SuperOp(self.depol_sop(p))
chan2 = SuperOp(Kraus(self.depol_kraus(p)))
self.assertEqual(chan1, chan2)
def test_kraus_to_kraus(self):
"""Test Kraus to Kraus transformation."""
# Test unitary channels
for mat in self.unitary_mat:
chan1 = Kraus(mat)
chan2 = Kraus(chan1)
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Kraus(self.depol_kraus(p))
chan2 = Kraus(chan1)
self.assertEqual(chan1, chan2)
def test_kraus_to_stinespring(self):
"""Test Kraus to Stinespring transformation."""
# Test unitary channels
for mat in self.unitary_mat:
chan1 = Stinespring(mat)
chan2 = Stinespring(Kraus(mat))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Stinespring(self.depol_stine(p)))
output = rho.evolve(Stinespring(Kraus(self.depol_kraus(p))))
self.assertEqual(output, target)
def test_kraus_to_chi(self):
"""Test Kraus to Chi transformation."""
# Test unitary channels
for mat, chi in zip(self.unitary_mat, self.unitary_chi):
chan1 = Chi(chi)
chan2 = Chi(Kraus(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Chi(self.depol_chi(p))
chan2 = Chi(Kraus(self.depol_kraus(p)))
self.assertEqual(chan1, chan2)
def test_kraus_to_ptm(self):
"""Test Kraus to PTM transformation."""
# Test unitary channels
for mat, ptm in zip(self.unitary_mat, self.unitary_ptm):
chan1 = PTM(ptm)
chan2 = PTM(Kraus(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = PTM(self.depol_ptm(p))
chan2 = PTM(Kraus(self.depol_kraus(p)))
self.assertEqual(chan1, chan2)
def test_stinespring_to_operator(self):
"""Test Stinespring to Operator transformation."""
for mat in self.unitary_mat:
chan1 = Operator(mat)
chan2 = Operator(Stinespring(mat))
self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True))
self.assertRaises(QiskitError, Operator, Stinespring(self.depol_stine(0.5)))
def test_stinespring_to_choi(self):
"""Test Stinespring to Choi transformation."""
# Test unitary channels
for mat, choi in zip(self.unitary_mat, self.unitary_choi):
chan1 = Choi(choi)
chan2 = Choi(Stinespring(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Choi(self.depol_choi(p))
chan2 = Choi(Stinespring(self.depol_stine(p)))
self.assertEqual(chan1, chan2)
def test_stinespring_to_superop(self):
"""Test Stinespring to SuperOp transformation."""
# Test unitary channels
for mat, sop in zip(self.unitary_mat, self.unitary_sop):
chan1 = SuperOp(sop)
chan2 = SuperOp(Kraus(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = SuperOp(self.depol_sop(p))
chan2 = SuperOp(Stinespring(self.depol_stine(p)))
self.assertEqual(chan1, chan2)
def test_stinespring_to_kraus(self):
"""Test Stinespring to Kraus transformation."""
# Test unitary channels
for mat in self.unitary_mat:
chan1 = Kraus(mat)
chan2 = Kraus(Stinespring(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Kraus(self.depol_kraus(p))
chan2 = Kraus(Stinespring(self.depol_stine(p)))
self.assertEqual(chan1, chan2)
def test_stinespring_to_stinespring(self):
"""Test Stinespring to Stinespring transformation."""
# Test unitary channels
for mat in self.unitary_mat:
chan1 = Stinespring(mat)
chan2 = Stinespring(chan1)
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Stinespring(self.depol_stine(p))
chan2 = Stinespring(chan1)
self.assertEqual(chan1, chan2)
def test_stinespring_to_chi(self):
"""Test Stinespring to Chi transformation."""
# Test unitary channels
for mat, chi in zip(self.unitary_mat, self.unitary_chi):
chan1 = Chi(chi)
chan2 = Chi(Stinespring(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Chi(self.depol_chi(p))
chan2 = Chi(Stinespring(self.depol_stine(p)))
self.assertEqual(chan1, chan2)
def test_stinespring_to_ptm(self):
"""Test Stinespring to PTM transformation."""
# Test unitary channels
for mat, ptm in zip(self.unitary_mat, self.unitary_ptm):
chan1 = PTM(ptm)
chan2 = PTM(Stinespring(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = PTM(self.depol_ptm(p))
chan2 = PTM(Stinespring(self.depol_stine(p)))
self.assertEqual(chan1, chan2)
def test_chi_to_operator(self):
"""Test Chi to Operator transformation."""
for mat, chi in zip(self.unitary_mat, self.unitary_chi):
chan1 = Operator(mat)
chan2 = Operator(Chi(chi))
self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True))
self.assertRaises(QiskitError, Operator, Chi(self.depol_chi(0.5)))
def test_chi_to_choi(self):
"""Test Chi to Choi transformation."""
# Test unitary channels
for chi, choi in zip(self.unitary_chi, self.unitary_choi):
chan1 = Choi(choi)
chan2 = Choi(Chi(chi))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Choi(self.depol_choi(p))
chan2 = Choi(Chi(self.depol_chi(p)))
self.assertEqual(chan1, chan2)
def test_chi_to_superop(self):
"""Test Chi to SuperOp transformation."""
# Test unitary channels
for chi, sop in zip(self.unitary_chi, self.unitary_sop):
chan1 = SuperOp(sop)
chan2 = SuperOp(Chi(chi))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = SuperOp(self.depol_sop(p))
chan2 = SuperOp(Chi(self.depol_chi(p)))
self.assertEqual(chan1, chan2)
def test_chi_to_kraus(self):
"""Test Chi to Kraus transformation."""
# Test unitary channels
for mat, chi in zip(self.unitary_mat, self.unitary_chi):
chan1 = Kraus(mat)
chan2 = Kraus(Chi(chi))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Kraus(self.depol_kraus(p)))
output = rho.evolve(Kraus(Chi(self.depol_chi(p))))
self.assertEqual(output, target)
def test_chi_to_stinespring(self):
"""Test Chi to Stinespring transformation."""
# Test unitary channels
for mat, chi in zip(self.unitary_mat, self.unitary_chi):
chan1 = Kraus(mat)
chan2 = Kraus(Chi(chi))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Stinespring(self.depol_stine(p)))
output = rho.evolve(Stinespring(Chi(self.depol_chi(p))))
self.assertEqual(output, target)
def test_chi_to_chi(self):
"""Test Chi to Chi transformation."""
# Test unitary channels
for chi in self.unitary_chi:
chan1 = Chi(chi)
chan2 = Chi(chan1)
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Chi(self.depol_chi(p))
chan2 = Chi(chan1)
self.assertEqual(chan1, chan2)
def test_chi_to_ptm(self):
"""Test Chi to PTM transformation."""
# Test unitary channels
for chi, ptm in zip(self.unitary_chi, self.unitary_ptm):
chan1 = PTM(ptm)
chan2 = PTM(Chi(chi))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = PTM(self.depol_ptm(p))
chan2 = PTM(Chi(self.depol_chi(p)))
self.assertEqual(chan1, chan2)
def test_ptm_to_operator(self):
"""Test PTM to Operator transformation."""
for mat, ptm in zip(self.unitary_mat, self.unitary_ptm):
chan1 = Operator(mat)
chan2 = Operator(PTM(ptm))
self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True))
self.assertRaises(QiskitError, Operator, PTM(self.depol_ptm(0.5)))
def test_ptm_to_choi(self):
"""Test PTM to Choi transformation."""
# Test unitary channels
for ptm, choi in zip(self.unitary_ptm, self.unitary_choi):
chan1 = Choi(choi)
chan2 = Choi(PTM(ptm))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Choi(self.depol_choi(p))
chan2 = Choi(PTM(self.depol_ptm(p)))
self.assertEqual(chan1, chan2)
def test_ptm_to_superop(self):
"""Test PTM to SuperOp transformation."""
# Test unitary channels
for ptm, sop in zip(self.unitary_ptm, self.unitary_sop):
chan1 = SuperOp(sop)
chan2 = SuperOp(PTM(ptm))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = SuperOp(self.depol_sop(p))
chan2 = SuperOp(PTM(self.depol_ptm(p)))
self.assertEqual(chan1, chan2)
def test_ptm_to_kraus(self):
"""Test PTM to Kraus transformation."""
# Test unitary channels
for mat, ptm in zip(self.unitary_mat, self.unitary_ptm):
chan1 = Kraus(mat)
chan2 = Kraus(PTM(ptm))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Kraus(self.depol_kraus(p)))
output = rho.evolve(Kraus(PTM(self.depol_ptm(p))))
self.assertEqual(output, target)
def test_ptm_to_stinespring(self):
"""Test PTM to Stinespring transformation."""
# Test unitary channels
for mat, ptm in zip(self.unitary_mat, self.unitary_ptm):
chan1 = Kraus(mat)
chan2 = Kraus(PTM(ptm))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Stinespring(self.depol_stine(p)))
output = rho.evolve(Stinespring(PTM(self.depol_ptm(p))))
self.assertEqual(output, target)
def test_ptm_to_chi(self):
"""Test PTM to Chi transformation."""
# Test unitary channels
for chi, ptm in zip(self.unitary_chi, self.unitary_ptm):
chan1 = Chi(chi)
chan2 = Chi(PTM(ptm))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Chi(self.depol_chi(p))
chan2 = Chi(PTM(self.depol_ptm(p)))
self.assertEqual(chan1, chan2)
def test_ptm_to_ptm(self):
"""Test PTM to PTM transformation."""
# Test unitary channels
for ptm in self.unitary_ptm:
chan1 = PTM(ptm)
chan2 = PTM(chan1)
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = PTM(self.depol_ptm(p))
chan2 = PTM(chan1)
self.assertEqual(chan1, chan2)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""Tests for Pauli operator class."""
import re
import unittest
import itertools as it
from functools import lru_cache
import numpy as np
from ddt import ddt, data, unpack
from qiskit import QuantumCircuit
from qiskit.exceptions import QiskitError
from qiskit.circuit.library import (
IGate,
XGate,
YGate,
ZGate,
HGate,
SGate,
SdgGate,
CXGate,
CZGate,
CYGate,
SwapGate,
)
from qiskit.circuit.library.generalized_gates import PauliGate
from qiskit.test import QiskitTestCase
from qiskit.quantum_info.random import random_clifford, random_pauli
from qiskit.quantum_info.operators import Pauli, Operator
LABEL_REGEX = re.compile(r"(?P<coeff>[+-]?1?[ij]?)(?P<pauli>[IXYZ]*)")
PHASE_MAP = {"": 0, "-i": 1, "-": 2, "i": 3}
def _split_pauli_label(label):
match_ = LABEL_REGEX.fullmatch(label)
return match_["pauli"], match_["coeff"]
def _phase_from_label(label):
coeff = LABEL_REGEX.fullmatch(label)["coeff"] or ""
return PHASE_MAP[coeff.replace("+", "").replace("1", "").replace("j", "i")]
@lru_cache(maxsize=8)
def pauli_group_labels(nq, full_group=True):
"""Generate list of the N-qubit pauli group string labels"""
labels = ["".join(i) for i in it.product(("I", "X", "Y", "Z"), repeat=nq)]
if full_group:
labels = ["".join(i) for i in it.product(("", "-i", "-", "i"), labels)]
return labels
def operator_from_label(label):
"""Construct operator from full Pauli group label"""
pauli, coeff = _split_pauli_label(label)
coeff = (-1j) ** _phase_from_label(coeff)
return coeff * Operator.from_label(pauli)
@ddt
class TestPauliConversions(QiskitTestCase):
"""Test representation conversions of Pauli"""
@data(*pauli_group_labels(1), *pauli_group_labels(2))
def test_labels(self, label):
"""Test round trip label conversion"""
pauli = Pauli(label)
self.assertEqual(Pauli(str(pauli)), pauli)
@data("S", "XX-")
def test_invalid_labels(self, label):
"""Test raise if invalid labels are supplied"""
with self.assertRaises(QiskitError):
Pauli(label)
@data(*pauli_group_labels(1), *pauli_group_labels(2))
def test_to_operator(self, label):
"""Test Pauli operator conversion"""
value = Operator(Pauli(label))
target = operator_from_label(label)
self.assertEqual(value, target)
@data(*pauli_group_labels(1), *pauli_group_labels(2))
def test_to_matrix_sparse(self, label):
"""Test Pauli operator conversion"""
spmat = Pauli(label).to_matrix(sparse=True)
value = Operator(spmat.todense())
target = operator_from_label(label)
self.assertEqual(value, target)
@data(*pauli_group_labels(1), *pauli_group_labels(2))
def test_to_instruction(self, label):
"""Test Pauli to instruction"""
pauli = Pauli(label)
value = Operator(pauli.to_instruction())
target = Operator(pauli)
self.assertEqual(value, target)
@data((IGate(), "I"), (XGate(), "X"), (YGate(), "Y"), (ZGate(), "Z"))
@unpack
def test_init_single_pauli_gate(self, gate, label):
"""Test initialization from Pauli basis gates"""
self.assertEqual(str(Pauli(gate)), label)
@data("IXYZ", "XXY", "ZYX", "ZI", "Y")
def test_init_pauli_gate(self, label):
"""Test initialization from Pauli basis gates"""
pauli = Pauli(PauliGate(label))
self.assertEqual(str(pauli), label)
@ddt
class TestPauliProperties(QiskitTestCase):
"""Test Pauli properties"""
@data("I", "XY", "XYZ", "IXYZ", "IXYZX")
def test_len(self, label):
"""Test __len__ method"""
self.assertEqual(len(Pauli(label)), len(label))
@data(*it.product(pauli_group_labels(1, full_group=False), pauli_group_labels(1)))
@unpack
def test_equal(self, label1, label2):
"""Test __eq__ method"""
pauli1 = Pauli(label1)
pauli2 = Pauli(label2)
target = (
np.all(pauli1.z == pauli2.z)
and np.all(pauli1.x == pauli2.x)
and pauli1.phase == pauli2.phase
)
self.assertEqual(pauli1 == pauli2, target)
@data(*it.product(pauli_group_labels(1, full_group=False), pauli_group_labels(1)))
@unpack
def test_equiv(self, label1, label2):
"""Test equiv method"""
pauli1 = Pauli(label1)
pauli2 = Pauli(label2)
target = np.all(pauli1.z == pauli2.z) and np.all(pauli1.x == pauli2.x)
self.assertEqual(pauli1.equiv(pauli2), target)
@data(*pauli_group_labels(1))
def test_phase(self, label):
"""Test phase attribute"""
pauli = Pauli(label)
_, coeff = _split_pauli_label(str(pauli))
target = _phase_from_label(coeff)
self.assertEqual(pauli.phase, target)
@data(*((p, q) for p in ["I", "X", "Y", "Z"] for q in range(4)))
@unpack
def test_phase_setter(self, pauli, phase):
"""Test phase setter"""
pauli = Pauli(pauli)
pauli.phase = phase
_, coeff = _split_pauli_label(str(pauli))
value = _phase_from_label(coeff)
self.assertEqual(value, phase)
def test_x_setter(self):
"""Test phase attribute"""
pauli = Pauli("II")
pauli.x = True
self.assertEqual(pauli, Pauli("XX"))
def test_z_setter(self):
"""Test phase attribute"""
pauli = Pauli("II")
pauli.z = True
self.assertEqual(pauli, Pauli("ZZ"))
@data(
*(
("IXYZ", i)
for i in [0, 1, 2, 3, slice(None, None, None), slice(None, 2, None), [0, 3], [2, 1, 3]]
)
)
@unpack
def test_getitem(self, label, qubits):
"""Test __getitem__"""
pauli = Pauli(label)
value = str(pauli[qubits])
val_array = np.array(list(reversed(label)))[qubits]
target = "".join(reversed(val_array.tolist()))
self.assertEqual(value, target, msg=f"indices = {qubits}")
@data(
(0, "iY", "iIIY"),
([1, 0], "XZ", "IZX"),
(slice(None, None, None), "XYZ", "XYZ"),
(slice(None, None, -1), "XYZ", "ZYX"),
)
@unpack
def test_setitem(self, qubits, value, target):
"""Test __setitem__"""
pauli = Pauli("III")
pauli[qubits] = value
self.assertEqual(str(pauli), target)
def test_insert(self):
"""Test insert method"""
pauli = Pauli("III")
pauli = pauli.insert([2, 0, 4], "XYZ")
self.assertEqual(str(pauli), "IXIZIY")
def test_delete(self):
"""Test delete method"""
pauli = Pauli("IXYZ")
pauli = pauli.delete([0, 2])
self.assertEqual(str(pauli), "IY")
@ddt
class TestPauli(QiskitTestCase):
"""Tests for Pauli operator class."""
@data(*pauli_group_labels(2))
def test_conjugate(self, label):
"""Test conjugate method."""
value = Pauli(label).conjugate()
target = operator_from_label(label).conjugate()
self.assertEqual(Operator(value), target)
@data(*pauli_group_labels(2))
def test_transpose(self, label):
"""Test transpose method."""
value = Pauli(label).transpose()
target = operator_from_label(label).transpose()
self.assertEqual(Operator(value), target)
@data(*pauli_group_labels(2))
def test_adjoint(self, label):
"""Test adjoint method."""
value = Pauli(label).adjoint()
target = operator_from_label(label).adjoint()
self.assertEqual(Operator(value), target)
@data(*pauli_group_labels(2))
def test_inverse(self, label):
"""Test inverse method."""
pauli = Pauli(label)
value = pauli.inverse()
target = pauli.adjoint()
self.assertEqual(value, target)
@data(*it.product(pauli_group_labels(2, full_group=False), repeat=2))
@unpack
def test_dot(self, label1, label2):
"""Test dot method."""
p1 = Pauli(label1)
p2 = Pauli(label2)
value = Operator(p1.dot(p2))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.dot(op2)
self.assertEqual(value, target)
target = op1 @ op2
self.assertEqual(value, target)
@data(*pauli_group_labels(1))
def test_dot_qargs(self, label2):
"""Test dot method with qargs."""
label1 = "-iXYZ"
p1 = Pauli(label1)
p2 = Pauli(label2)
qargs = [0]
value = Operator(p1.dot(p2, qargs=qargs))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.dot(op2, qargs=qargs)
self.assertEqual(value, target)
@data(*it.product(pauli_group_labels(2, full_group=False), repeat=2))
@unpack
def test_compose(self, label1, label2):
"""Test compose method."""
p1 = Pauli(label1)
p2 = Pauli(label2)
value = Operator(p1.compose(p2))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.compose(op2)
self.assertEqual(value, target)
@data(*pauli_group_labels(1))
def test_compose_qargs(self, label2):
"""Test compose method with qargs."""
label1 = "-XYZ"
p1 = Pauli(label1)
p2 = Pauli(label2)
qargs = [0]
value = Operator(p1.compose(p2, qargs=qargs))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.compose(op2, qargs=qargs)
self.assertEqual(value, target)
@data(*it.product(pauli_group_labels(1, full_group=False), repeat=2))
@unpack
def test_tensor(self, label1, label2):
"""Test tensor method."""
p1 = Pauli(label1)
p2 = Pauli(label2)
value = Operator(p1.tensor(p2))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.tensor(op2)
self.assertEqual(value, target)
@data(*it.product(pauli_group_labels(1, full_group=False), repeat=2))
@unpack
def test_expand(self, label1, label2):
"""Test expand method."""
p1 = Pauli(label1)
p2 = Pauli(label2)
value = Operator(p1.expand(p2))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.expand(op2)
self.assertEqual(value, target)
@data("II", "XI", "YX", "ZZ", "YZ")
def test_power(self, label):
"""Test power method."""
iden = Pauli("II")
op = Pauli(label)
self.assertTrue(op**2, iden)
@data(1, 1.0, -1, -1.0, 1j, -1j)
def test_multiply(self, val):
"""Test multiply method."""
op = val * Pauli(([True, True], [False, False], 0))
phase = (-1j) ** op.phase
self.assertEqual(phase, val)
op = Pauli(([True, True], [False, False], 0)) * val
phase = (-1j) ** op.phase
self.assertEqual(phase, val)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
op = Pauli("XYZ")
self.assertRaises(QiskitError, op._multiply, 2)
@data(0, 1, 2, 3)
def test_negate(self, phase):
"""Test negate method"""
op = Pauli(([False], [True], phase))
neg = -op
self.assertTrue(op.equiv(neg))
self.assertEqual(neg.phase, (op.phase + 2) % 4)
@data(*it.product(pauli_group_labels(1, False), repeat=2))
@unpack
def test_commutes(self, p1, p2):
"""Test commutes method"""
P1 = Pauli(p1)
P2 = Pauli(p2)
self.assertEqual(P1.commutes(P2), P1.dot(P2) == P2.dot(P1))
@data(*it.product(pauli_group_labels(1, False), repeat=2))
@unpack
def test_anticommutes(self, p1, p2):
"""Test anticommutes method"""
P1 = Pauli(p1)
P2 = Pauli(p2)
self.assertEqual(P1.anticommutes(P2), P1.dot(P2) == -P2.dot(P1))
@data(
*it.product(
(IGate(), XGate(), YGate(), ZGate(), HGate(), SGate(), SdgGate()),
pauli_group_labels(1, False),
)
)
@unpack
def test_evolve_clifford1(self, gate, label):
"""Test evolve method for 1-qubit Clifford gates."""
op = Operator(gate)
pauli = Pauli(label)
value = Operator(pauli.evolve(gate))
value_h = Operator(pauli.evolve(gate, frame="h"))
value_s = Operator(pauli.evolve(gate, frame="s"))
value_inv = Operator(pauli.evolve(gate.inverse()))
target = op.adjoint().dot(pauli).dot(op)
self.assertEqual(value, target)
self.assertEqual(value, value_h)
self.assertEqual(value_inv, value_s)
@data(*it.product((CXGate(), CYGate(), CZGate(), SwapGate()), pauli_group_labels(2, False)))
@unpack
def test_evolve_clifford2(self, gate, label):
"""Test evolve method for 2-qubit Clifford gates."""
op = Operator(gate)
pauli = Pauli(label)
value = Operator(pauli.evolve(gate))
value_h = Operator(pauli.evolve(gate, frame="h"))
value_s = Operator(pauli.evolve(gate, frame="s"))
value_inv = Operator(pauli.evolve(gate.inverse()))
target = op.adjoint().dot(pauli).dot(op)
self.assertEqual(value, target)
self.assertEqual(value, value_h)
self.assertEqual(value_inv, value_s)
@data(
*it.product(
(
IGate(),
XGate(),
YGate(),
ZGate(),
HGate(),
SGate(),
SdgGate(),
CXGate(),
CYGate(),
CZGate(),
SwapGate(),
),
[int, np.int8, np.uint8, np.int16, np.uint16, np.int32, np.uint32, np.int64, np.uint64],
)
)
@unpack
def test_phase_dtype_evolve_clifford(self, gate, dtype):
"""Test phase dtype for evolve method for Clifford gates."""
z = np.ones(gate.num_qubits, dtype=bool)
x = np.ones(gate.num_qubits, dtype=bool)
phase = (np.sum(z & x) % 4).astype(dtype)
paulis = Pauli((z, x, phase))
evo = paulis.evolve(gate)
self.assertEqual(evo.phase.dtype, dtype)
def test_evolve_clifford_qargs(self):
"""Test evolve method for random Clifford"""
cliff = random_clifford(3, seed=10)
op = Operator(cliff)
pauli = random_pauli(5, seed=10)
qargs = [3, 0, 1]
value = Operator(pauli.evolve(cliff, qargs=qargs))
value_h = Operator(pauli.evolve(cliff, qargs=qargs, frame="h"))
value_s = Operator(pauli.evolve(cliff, qargs=qargs, frame="s"))
value_inv = Operator(pauli.evolve(cliff.adjoint(), qargs=qargs))
target = Operator(pauli).compose(op.adjoint(), qargs=qargs).dot(op, qargs=qargs)
self.assertEqual(value, target)
self.assertEqual(value, value_h)
self.assertEqual(value_inv, value_s)
def test_barrier_delay_sim(self):
"""Test barrier and delay instructions can be simulated"""
target_circ = QuantumCircuit(2)
target_circ.x(0)
target_circ.y(1)
target = Pauli(target_circ)
circ = QuantumCircuit(2)
circ.x(0)
circ.delay(100, 0)
circ.barrier([0, 1])
circ.y(1)
value = Pauli(circ)
self.assertEqual(value, target)
@data(("", 0), ("-", 2), ("i", 3), ("-1j", 1))
@unpack
def test_zero_qubit_pauli_construction(self, label, phase):
"""Test that Paulis of zero qubits can be constructed."""
expected = Pauli(label + "X")[0:0] # Empty slice from a 1q Pauli, which becomes phaseless
expected.phase = phase
test = Pauli(label)
self.assertEqual(expected, test)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for PauliList class."""
import itertools
import unittest
from test import combine
import numpy as np
from ddt import ddt
from scipy.sparse import csr_matrix
from qiskit import QiskitError
from qiskit.circuit.library import (
CXGate,
CYGate,
CZGate,
HGate,
IGate,
SdgGate,
SGate,
SwapGate,
XGate,
YGate,
ZGate,
)
from qiskit.quantum_info.operators import (
Clifford,
Operator,
Pauli,
PauliList,
PauliTable,
StabilizerTable,
)
from qiskit.quantum_info.random import random_clifford, random_pauli_list
from qiskit.test import QiskitTestCase
from .test_pauli import pauli_group_labels
def pauli_mat(label):
"""Return Pauli matrix from a Pauli label"""
mat = np.eye(1, dtype=complex)
if label[0:2] == "-i":
mat *= -1j
label = label[2:]
elif label[0] == "-":
mat *= -1
label = label[1:]
elif label[0] == "i":
mat *= 1j
label = label[1:]
for i in label:
if i == "I":
mat = np.kron(mat, np.eye(2, dtype=complex))
elif i == "X":
mat = np.kron(mat, np.array([[0, 1], [1, 0]], dtype=complex))
elif i == "Y":
mat = np.kron(mat, np.array([[0, -1j], [1j, 0]], dtype=complex))
elif i == "Z":
mat = np.kron(mat, np.array([[1, 0], [0, -1]], dtype=complex))
else:
raise QiskitError(f"Invalid Pauli string {i}")
return mat
class TestPauliListInit(QiskitTestCase):
"""Tests for PauliList initialization."""
def test_array_init(self):
"""Test array initialization."""
# Matrix array initialization
with self.subTest(msg="Empty array"):
x = np.array([], dtype=bool).reshape((1, 0))
z = np.array([], dtype=bool).reshape((1, 0))
pauli_list = PauliList.from_symplectic(x, z)
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg="bool array"):
z = np.array([[False], [True]])
x = np.array([[False], [True]])
pauli_list = PauliList.from_symplectic(z, x)
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg="bool array no copy"):
z = np.array([[False], [True]])
x = np.array([[True], [True]])
pauli_list = PauliList.from_symplectic(z, x)
z[0, 0] = not z[0, 0]
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
def test_string_init(self):
"""Test string initialization."""
# String initialization
with self.subTest(msg='str init "I"'):
pauli_list = PauliList("I")
z = np.array([[False]])
x = np.array([[False]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg='str init "X"'):
pauli_list = PauliList("X")
z = np.array([[False]])
x = np.array([[True]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg='str init "Y"'):
pauli_list = PauliList("Y")
z = np.array([[True]])
x = np.array([[True]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg='str init "Z"'):
pauli_list = PauliList("Z")
z = np.array([[True]])
x = np.array([[False]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg='str init "iZ"'):
pauli_list = PauliList("iZ")
z = np.array([[True]])
x = np.array([[False]])
phase = np.array([3])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
np.testing.assert_equal(pauli_list.phase, phase)
with self.subTest(msg='str init "-Z"'):
pauli_list = PauliList("-Z")
z = np.array([[True]])
x = np.array([[False]])
phase = np.array([2])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
np.testing.assert_equal(pauli_list.phase, phase)
with self.subTest(msg='str init "-iZ"'):
pauli_list = PauliList("-iZ")
z = np.array([[True]])
x = np.array([[False]])
phase = np.array([1])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
np.testing.assert_equal(pauli_list.phase, phase)
with self.subTest(msg='str init "IX"'):
pauli_list = PauliList("IX")
z = np.array([[False, False]])
x = np.array([[True, False]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg='str init "XI"'):
pauli_list = PauliList("XI")
z = np.array([[False, False]])
x = np.array([[False, True]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg='str init "YZ"'):
pauli_list = PauliList("YZ")
z = np.array([[True, True]])
x = np.array([[False, True]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg='str init "iZY"'):
pauli_list = PauliList("iZY")
z = np.array([[True, True]])
x = np.array([[True, False]])
phase = np.array([3])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
np.testing.assert_equal(pauli_list.phase, phase)
with self.subTest(msg='str init "XIZ"'):
pauli_list = PauliList("XIZ")
z = np.array([[True, False, False]])
x = np.array([[False, False, True]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg="str init prevent broadcasting"):
with self.assertRaises(ValueError):
PauliList(["XYZ", "I"])
def test_list_init(self):
"""Test list initialization."""
with self.subTest(msg="PauliList"):
target = PauliList(["iXI", "IX", "IZ"])
value = PauliList(target)
self.assertEqual(value, target)
with self.subTest(msg="PauliList no copy"):
target = PauliList(["iXI", "IX", "IZ"])
value = PauliList(target)
value[0] = "-iII"
self.assertEqual(value, target)
def test_pauli_table_init(self):
"""Test table initialization."""
with self.subTest(msg="PauliTable"):
target = PauliTable.from_labels(["XI", "IX", "IZ"])
value = PauliList(target)
self.assertEqual(value, target)
with self.subTest(msg="PauliTable no copy"):
target = PauliTable.from_labels(["XI", "IX", "IZ"])
value = PauliList(target)
value[0] = "II"
self.assertEqual(value, target)
def test_stabilizer_table_init(self):
"""Test table initialization."""
with self.subTest(msg="PauliTable"):
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(["+II", "-XZ"])
value = PauliList(target)
self.assertEqual(value, target)
with self.subTest(msg="PauliTable no copy"):
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(["+YY", "-XZ", "XI"])
value = PauliList(target)
value[0] = "II"
self.assertEqual(value, target)
def test_init_from_settings(self):
"""Test initializing from the settings dictionary."""
pauli_list = PauliList(["IX", "-iYZ", "YY"])
from_settings = PauliList(**pauli_list.settings)
self.assertEqual(pauli_list, from_settings)
@ddt
class TestPauliListProperties(QiskitTestCase):
"""Tests for PauliList properties."""
def test_x_property(self):
"""Test X property"""
with self.subTest(msg="X"):
pauli = PauliList(["XI", "IZ", "YY"])
array = np.array([[False, True], [False, False], [True, True]], dtype=bool)
self.assertTrue(np.all(pauli.x == array))
with self.subTest(msg="set X"):
pauli = PauliList(["XI", "IZ"])
val = np.array([[False, False], [True, True]], dtype=bool)
pauli.x = val
self.assertEqual(pauli, PauliList(["II", "iXY"]))
with self.subTest(msg="set X raises"):
with self.assertRaises(Exception):
pauli = PauliList(["XI", "IZ"])
val = np.array([[False, False, False], [True, True, True]], dtype=bool)
pauli.x = val
def test_z_property(self):
"""Test Z property"""
with self.subTest(msg="Z"):
pauli = PauliList(["XI", "IZ", "YY"])
array = np.array([[False, False], [True, False], [True, True]], dtype=bool)
self.assertTrue(np.all(pauli.z == array))
with self.subTest(msg="set Z"):
pauli = PauliList(["XI", "IZ"])
val = np.array([[False, False], [True, True]], dtype=bool)
pauli.z = val
self.assertEqual(pauli, PauliList(["XI", "ZZ"]))
with self.subTest(msg="set Z raises"):
with self.assertRaises(Exception):
pauli = PauliList(["XI", "IZ"])
val = np.array([[False, False, False], [True, True, True]], dtype=bool)
pauli.z = val
def test_phase_property(self):
"""Test phase property"""
with self.subTest(msg="phase"):
pauli = PauliList(["XI", "IZ", "YY", "YI"])
array = np.array([0, 0, 0, 0], dtype=int)
np.testing.assert_equal(pauli.phase, array)
with self.subTest(msg="set phase"):
pauli = PauliList(["XI", "IZ"])
val = np.array([2, 3], dtype=int)
pauli.phase = val
self.assertEqual(pauli, PauliList(["-XI", "iIZ"]))
with self.subTest(msg="set Z raises"):
with self.assertRaises(Exception):
pauli = PauliList(["XI", "IZ"])
val = np.array([1, 2, 3], dtype=int)
pauli.phase = val
def test_shape_property(self):
"""Test shape property"""
shape = (3, 4)
pauli = PauliList.from_symplectic(np.zeros(shape), np.zeros(shape))
self.assertEqual(pauli.shape, shape)
@combine(j=range(1, 10))
def test_size_property(self, j):
"""Test size property"""
shape = (j, 4)
pauli = PauliList.from_symplectic(np.zeros(shape), np.zeros(shape))
self.assertEqual(len(pauli), j)
@combine(j=range(1, 10))
def test_n_qubit_property(self, j):
"""Test n_qubit property"""
shape = (5, j)
pauli = PauliList.from_symplectic(np.zeros(shape), np.zeros(shape))
self.assertEqual(pauli.num_qubits, j)
def test_eq(self):
"""Test __eq__ method."""
pauli1 = PauliList(["II", "XI"])
pauli2 = PauliList(["XI", "II"])
self.assertEqual(pauli1, pauli1)
self.assertNotEqual(pauli1, pauli2)
def test_len_methods(self):
"""Test __len__ method."""
for j in range(1, 10):
labels = j * ["XX"]
pauli = PauliList(labels)
self.assertEqual(len(pauli), j)
def test_add_methods(self):
"""Test __add__ method."""
labels1 = ["XXI", "IXX"]
labels2 = ["XXI", "ZZI", "ZYZ"]
pauli1 = PauliList(labels1)
pauli2 = PauliList(labels2)
target = PauliList(labels1 + labels2)
self.assertEqual(target, pauli1 + pauli2)
def test_add_qargs(self):
"""Test add method with qargs."""
pauli1 = PauliList(["IIII", "YYYY"])
pauli2 = PauliList(["XY", "YZ"])
pauli3 = PauliList(["X", "Y", "Z"])
with self.subTest(msg="qargs=[0, 1]"):
target = PauliList(["IIII", "YYYY", "IIXY", "IIYZ"])
self.assertEqual(pauli1 + pauli2([0, 1]), target)
with self.subTest(msg="qargs=[0, 3]"):
target = PauliList(["IIII", "YYYY", "XIIY", "YIIZ"])
self.assertEqual(pauli1 + pauli2([0, 3]), target)
with self.subTest(msg="qargs=[2, 1]"):
target = PauliList(["IIII", "YYYY", "IYXI", "IZYI"])
self.assertEqual(pauli1 + pauli2([2, 1]), target)
with self.subTest(msg="qargs=[3, 1]"):
target = PauliList(["IIII", "YYYY", "YIXI", "ZIYI"])
self.assertEqual(pauli1 + pauli2([3, 1]), target)
with self.subTest(msg="qargs=[0]"):
target = PauliList(["IIII", "YYYY", "IIIX", "IIIY", "IIIZ"])
self.assertEqual(pauli1 + pauli3([0]), target)
with self.subTest(msg="qargs=[1]"):
target = PauliList(["IIII", "YYYY", "IIXI", "IIYI", "IIZI"])
self.assertEqual(pauli1 + pauli3([1]), target)
with self.subTest(msg="qargs=[2]"):
target = PauliList(["IIII", "YYYY", "IXII", "IYII", "IZII"])
self.assertEqual(pauli1 + pauli3([2]), target)
with self.subTest(msg="qargs=[3]"):
target = PauliList(["IIII", "YYYY", "XIII", "YIII", "ZIII"])
self.assertEqual(pauli1 + pauli3([3]), target)
def test_getitem_methods(self):
"""Test __getitem__ method."""
with self.subTest(msg="__getitem__ single"):
labels = ["XI", "IY"]
pauli = PauliList(labels)
self.assertEqual(pauli[0], PauliList(labels[0]))
self.assertEqual(pauli[1], PauliList(labels[1]))
with self.subTest(msg="__getitem__ array"):
labels = np.array(["XI", "IY", "IZ", "XY", "ZX"])
pauli = PauliList(labels)
inds = [0, 3]
self.assertEqual(pauli[inds], PauliList(labels[inds]))
inds = np.array([4, 1])
self.assertEqual(pauli[inds], PauliList(labels[inds]))
with self.subTest(msg="__getitem__ slice"):
labels = np.array(["XI", "IY", "IZ", "XY", "ZX"])
pauli = PauliList(labels)
self.assertEqual(pauli[:], pauli)
self.assertEqual(pauli[1:3], PauliList(labels[1:3]))
def test_setitem_methods(self):
"""Test __setitem__ method."""
with self.subTest(msg="__setitem__ single"):
labels = ["XI", "IY"]
pauli = PauliList(["XI", "IY"])
pauli[0] = "II"
self.assertEqual(pauli[0], PauliList("II"))
pauli[1] = "-iXX"
self.assertEqual(pauli[1], PauliList("-iXX"))
with self.assertRaises(Exception):
# Wrong size Pauli
pauli[0] = "XXX"
with self.subTest(msg="__setitem__ array"):
labels = np.array(["XI", "IY", "IZ"])
pauli = PauliList(labels)
target = PauliList(["II", "ZZ"])
inds = [2, 0]
pauli[inds] = target
self.assertEqual(pauli[inds], target)
with self.assertRaises(Exception):
pauli[inds] = PauliList(["YY", "ZZ", "XX"])
with self.subTest(msg="__setitem__ slice"):
labels = np.array(5 * ["III"])
pauli = PauliList(labels)
target = PauliList(5 * ["XXX"])
pauli[:] = target
self.assertEqual(pauli[:], target)
target = PauliList(2 * ["ZZZ"])
pauli[1:3] = target
self.assertEqual(pauli[1:3], target)
class TestPauliListLabels(QiskitTestCase):
"""Tests PauliList label representation conversions."""
def test_from_labels_1q(self):
"""Test 1-qubit from_labels method."""
labels = ["I", "Z", "Z", "X", "Y"]
target = PauliList.from_symplectic(
np.array([[False], [True], [True], [False], [True]]),
np.array([[False], [False], [False], [True], [True]]),
)
value = PauliList(labels)
self.assertEqual(target, value)
def test_from_labels_1q_with_phase(self):
"""Test 1-qubit from_labels method with phase."""
labels = ["-I", "iZ", "iZ", "X", "-iY"]
target = PauliList.from_symplectic(
np.array([[False], [True], [True], [False], [True]]),
np.array([[False], [False], [False], [True], [True]]),
np.array([2, 3, 3, 0, 1]),
)
value = PauliList(labels)
self.assertEqual(target, value)
def test_from_labels_2q(self):
"""Test 2-qubit from_labels method."""
labels = ["II", "YY", "XZ"]
target = PauliList.from_symplectic(
np.array([[False, False], [True, True], [True, False]]),
np.array([[False, False], [True, True], [False, True]]),
)
value = PauliList(labels)
self.assertEqual(target, value)
def test_from_labels_2q_with_phase(self):
"""Test 2-qubit from_labels method."""
labels = ["iII", "iYY", "-iXZ"]
target = PauliList.from_symplectic(
np.array([[False, False], [True, True], [True, False]]),
np.array([[False, False], [True, True], [False, True]]),
np.array([3, 3, 1]),
)
value = PauliList(labels)
self.assertEqual(target, value)
def test_from_labels_5q(self):
"""Test 5-qubit from_labels method."""
labels = [5 * "I", 5 * "X", 5 * "Y", 5 * "Z"]
target = PauliList.from_symplectic(
np.array([[False] * 5, [False] * 5, [True] * 5, [True] * 5]),
np.array([[False] * 5, [True] * 5, [True] * 5, [False] * 5]),
)
value = PauliList(labels)
self.assertEqual(target, value)
def test_to_labels_1q(self):
"""Test 1-qubit to_labels method."""
pauli = PauliList.from_symplectic(
np.array([[False], [True], [True], [False], [True]]),
np.array([[False], [False], [False], [True], [True]]),
)
target = ["I", "Z", "Z", "X", "Y"]
value = pauli.to_labels()
self.assertEqual(value, target)
def test_to_labels_1q_with_phase(self):
"""Test 1-qubit to_labels method with phase."""
pauli = PauliList.from_symplectic(
np.array([[False], [True], [True], [False], [True]]),
np.array([[False], [False], [False], [True], [True]]),
np.array([1, 3, 2, 3, 1]),
)
target = ["-iI", "iZ", "-Z", "iX", "-iY"]
value = pauli.to_labels()
self.assertEqual(value, target)
def test_to_labels_1q_array(self):
"""Test 1-qubit to_labels method w/ array=True."""
pauli = PauliList.from_symplectic(
np.array([[False], [True], [True], [False], [True]]),
np.array([[False], [False], [False], [True], [True]]),
)
target = np.array(["I", "Z", "Z", "X", "Y"])
value = pauli.to_labels(array=True)
self.assertTrue(np.all(value == target))
def test_to_labels_1q_array_with_phase(self):
"""Test 1-qubit to_labels method w/ array=True."""
pauli = PauliList.from_symplectic(
np.array([[False], [True], [True], [False], [True]]),
np.array([[False], [False], [False], [True], [True]]),
np.array([2, 3, 0, 1, 0]),
)
target = np.array(["-I", "iZ", "Z", "-iX", "Y"])
value = pauli.to_labels(array=True)
self.assertTrue(np.all(value == target))
def test_labels_round_trip(self):
"""Test from_labels and to_labels round trip."""
target = ["III", "IXZ", "XYI", "ZZZ", "-iZIX", "-IYX"]
value = PauliList(target).to_labels()
self.assertEqual(value, target)
def test_labels_round_trip_array(self):
"""Test from_labels and to_labels round trip w/ array=True."""
labels = ["III", "IXZ", "XYI", "ZZZ", "-iZIX", "-IYX"]
target = np.array(labels)
value = PauliList(labels).to_labels(array=True)
self.assertTrue(np.all(value == target))
class TestPauliListMatrix(QiskitTestCase):
"""Tests PauliList matrix representation conversions."""
def test_to_matrix_1q(self):
"""Test 1-qubit to_matrix method."""
labels = ["X", "I", "Z", "Y"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_1q_array(self):
"""Test 1-qubit to_matrix method w/ array=True."""
labels = ["Z", "I", "Y", "X"]
target = np.array([pauli_mat(i) for i in labels])
value = PauliList(labels).to_matrix(array=True)
self.assertTrue(isinstance(value, np.ndarray))
self.assertTrue(np.all(value == target))
def test_to_matrix_1q_sparse(self):
"""Test 1-qubit to_matrix method w/ sparse=True."""
labels = ["X", "I", "Z", "Y"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
def test_to_matrix_2q(self):
"""Test 2-qubit to_matrix method."""
labels = ["IX", "YI", "II", "ZZ"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_2q_array(self):
"""Test 2-qubit to_matrix method w/ array=True."""
labels = ["ZZ", "XY", "YX", "IZ"]
target = np.array([pauli_mat(i) for i in labels])
value = PauliList(labels).to_matrix(array=True)
self.assertTrue(isinstance(value, np.ndarray))
self.assertTrue(np.all(value == target))
def test_to_matrix_2q_sparse(self):
"""Test 2-qubit to_matrix method w/ sparse=True."""
labels = ["IX", "II", "ZY", "YZ"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
def test_to_matrix_5q(self):
"""Test 5-qubit to_matrix method."""
labels = ["IXIXI", "YZIXI", "IIXYZ"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_5q_sparse(self):
"""Test 5-qubit to_matrix method w/ sparse=True."""
labels = ["XXXYY", "IXIZY", "ZYXIX"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
def test_to_matrix_5q_with_phase(self):
"""Test 5-qubit to_matrix method with phase."""
labels = ["iIXIXI", "-YZIXI", "-iIIXYZ"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_5q_sparse_with_phase(self):
"""Test 5-qubit to_matrix method w/ sparse=True with phase."""
labels = ["iXXXYY", "-IXIZY", "-iZYXIX"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
class TestPauliListIteration(QiskitTestCase):
"""Tests for PauliList iterators class."""
def test_enumerate(self):
"""Test enumerate with PauliList."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for idx, i in enumerate(pauli):
self.assertEqual(i, PauliList(labels[idx]))
def test_iter(self):
"""Test iter with PauliList."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for idx, i in enumerate(iter(pauli)):
self.assertEqual(i, PauliList(labels[idx]))
def test_zip(self):
"""Test zip with PauliList."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for label, i in zip(labels, pauli):
self.assertEqual(i, PauliList(label))
def test_label_iter(self):
"""Test PauliList label_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for idx, i in enumerate(pauli.label_iter()):
self.assertEqual(i, labels[idx])
def test_matrix_iter(self):
"""Test PauliList dense matrix_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for idx, i in enumerate(pauli.matrix_iter()):
self.assertTrue(np.all(i == pauli_mat(labels[idx])))
def test_matrix_iter_sparse(self):
"""Test PauliList sparse matrix_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for idx, i in enumerate(pauli.matrix_iter(sparse=True)):
self.assertTrue(isinstance(i, csr_matrix))
self.assertTrue(np.all(i.toarray() == pauli_mat(labels[idx])))
@ddt
class TestPauliListOperator(QiskitTestCase):
"""Tests for PauliList base operator methods."""
@combine(j=range(1, 10))
def test_tensor(self, j):
"""Test tensor method j={j}."""
labels1 = ["XX", "YY"]
labels2 = [j * "I", j * "Z"]
pauli1 = PauliList(labels1)
pauli2 = PauliList(labels2)
value = pauli1.tensor(pauli2)
target = PauliList([l1 + l2 for l1 in labels1 for l2 in labels2])
self.assertEqual(value, target)
@combine(j=range(1, 10))
def test_tensor_with_phase(self, j):
"""Test tensor method j={j} with phase."""
labels1 = ["XX", "iYY"]
labels2 = [j * "I", "i" + j * "Z"]
pauli1 = PauliList(labels1)
pauli2 = PauliList(labels2)
value = pauli1.tensor(pauli2)
target = PauliList(["XX" + "I" * j, "iXX" + "Z" * j, "iYY" + "I" * j, "-YY" + "Z" * j])
self.assertEqual(value, target)
@combine(j=range(1, 10))
def test_expand(self, j):
"""Test expand method j={j}."""
labels1 = ["XX", "YY"]
labels2 = [j * "I", j * "Z"]
pauli1 = PauliList(labels1)
pauli2 = PauliList(labels2)
value = pauli1.expand(pauli2)
target = PauliList([j + i for j in labels2 for i in labels1])
self.assertEqual(value, target)
@combine(j=range(1, 10))
def test_expand_with_phase(self, j):
"""Test expand method j={j}."""
labels1 = ["-XX", "iYY"]
labels2 = ["i" + j * "I", "-i" + j * "Z"]
pauli1 = PauliList(labels1)
pauli2 = PauliList(labels2)
value = pauli1.expand(pauli2)
target = PauliList(
["-i" + "I" * j + "XX", "-" + "I" * j + "YY", "i" + "Z" * j + "XX", "Z" * j + "YY"]
)
self.assertEqual(value, target)
def test_compose_1q(self):
"""Test 1-qubit compose methods."""
# Test single qubit Pauli dot products
pauli = PauliList(["I", "X", "Y", "Z"])
with self.subTest(msg="compose single I"):
target = PauliList(["I", "X", "Y", "Z"])
value = pauli.compose("I")
self.assertEqual(target, value)
with self.subTest(msg="compose single X"):
target = PauliList(["X", "I", "iZ", "-iY"])
value = pauli.compose("X")
self.assertEqual(target, value)
with self.subTest(msg="compose single Y"):
target = PauliList(["Y", "-iZ", "I", "iX"])
value = pauli.compose("Y")
self.assertEqual(target, value)
with self.subTest(msg="compose single Z"):
target = PauliList(["Z", "iY", "-iX", "I"])
value = pauli.compose("Z")
self.assertEqual(target, value)
def test_dot_1q(self):
"""Test 1-qubit dot method."""
# Test single qubit Pauli dot products
pauli = PauliList(["I", "X", "Y", "Z"])
with self.subTest(msg="dot single I"):
target = PauliList(["I", "X", "Y", "Z"])
value = pauli.dot("I")
self.assertEqual(target, value)
with self.subTest(msg="dot single X"):
target = PauliList(["X", "I", "-iZ", "iY"])
value = pauli.dot("X")
self.assertEqual(target, value)
with self.subTest(msg="dot single Y"):
target = PauliList(["Y", "iZ", "I", "-iX"])
value = pauli.dot("Y")
self.assertEqual(target, value)
with self.subTest(msg="dot single Z"):
target = PauliList(["Z", "-iY", "iX", "I"])
value = pauli.dot("Z")
self.assertEqual(target, value)
def test_qargs_compose_1q(self):
"""Test 1-qubit compose method with qargs."""
pauli1 = PauliList(["III", "XXX"])
pauli2 = PauliList("Z")
with self.subTest(msg="compose 1-qubit qargs=[0]"):
target = PauliList(["IIZ", "iXXY"])
value = pauli1.compose(pauli2, qargs=[0])
self.assertEqual(value, target)
with self.subTest(msg="compose 1-qubit qargs=[1]"):
target = PauliList(["IZI", "iXYX"])
value = pauli1.compose(pauli2, qargs=[1])
self.assertEqual(value, target)
with self.subTest(msg="compose 1-qubit qargs=[2]"):
target = PauliList(["ZII", "iYXX"])
value = pauli1.compose(pauli2, qargs=[2])
self.assertEqual(value, target)
def test_qargs_dot_1q(self):
"""Test 1-qubit dot method with qargs."""
pauli1 = PauliList(["III", "XXX"])
pauli2 = PauliList("Z")
with self.subTest(msg="dot 1-qubit qargs=[0]"):
target = PauliList(["IIZ", "-iXXY"])
value = pauli1.dot(pauli2, qargs=[0])
self.assertEqual(value, target)
with self.subTest(msg="dot 1-qubit qargs=[1]"):
target = PauliList(["IZI", "-iXYX"])
value = pauli1.dot(pauli2, qargs=[1])
self.assertEqual(value, target)
with self.subTest(msg="dot 1-qubit qargs=[2]"):
target = PauliList(["ZII", "-iYXX"])
value = pauli1.dot(pauli2, qargs=[2])
self.assertEqual(value, target)
def test_qargs_compose_2q(self):
"""Test 2-qubit compose method with qargs."""
pauli1 = PauliList(["III", "XXX"])
pauli2 = PauliList("ZY")
with self.subTest(msg="compose 2-qubit qargs=[0, 1]"):
target = PauliList(["IZY", "XYZ"])
value = pauli1.compose(pauli2, qargs=[0, 1])
self.assertEqual(value, target)
with self.subTest(msg="compose 2-qubit qargs=[1, 0]"):
target = PauliList(["IYZ", "XZY"])
value = pauli1.compose(pauli2, qargs=[1, 0])
self.assertEqual(value, target)
with self.subTest(msg="compose 2-qubit qargs=[0, 2]"):
target = PauliList(["ZIY", "YXZ"])
value = pauli1.compose(pauli2, qargs=[0, 2])
self.assertEqual(value, target)
with self.subTest(msg="compose 2-qubit qargs=[2, 0]"):
target = PauliList(["YIZ", "ZXY"])
value = pauli1.compose(pauli2, qargs=[2, 0])
self.assertEqual(value, target)
def test_qargs_dot_2q(self):
"""Test 2-qubit dot method with qargs."""
pauli1 = PauliList(["III", "XXX"])
pauli2 = PauliList("ZY")
with self.subTest(msg="dot 2-qubit qargs=[0, 1]"):
target = PauliList(["IZY", "XYZ"])
value = pauli1.dot(pauli2, qargs=[0, 1])
self.assertEqual(value, target)
with self.subTest(msg="dot 2-qubit qargs=[1, 0]"):
target = PauliList(["IYZ", "XZY"])
value = pauli1.dot(pauli2, qargs=[1, 0])
self.assertEqual(value, target)
with self.subTest(msg="dot 2-qubit qargs=[0, 2]"):
target = PauliList(["ZIY", "YXZ"])
value = pauli1.dot(pauli2, qargs=[0, 2])
self.assertEqual(value, target)
with self.subTest(msg="dot 2-qubit qargs=[2, 0]"):
target = PauliList(["YIZ", "ZXY"])
value = pauli1.dot(pauli2, qargs=[2, 0])
self.assertEqual(value, target)
def test_qargs_compose_3q(self):
"""Test 3-qubit compose method with qargs."""
pauli1 = PauliList(["III", "XXX"])
pauli2 = PauliList("XYZ")
with self.subTest(msg="compose 3-qubit qargs=None"):
target = PauliList(["XYZ", "IZY"])
value = pauli1.compose(pauli2)
self.assertEqual(value, target)
with self.subTest(msg="compose 3-qubit qargs=[0, 1, 2]"):
target = PauliList(["XYZ", "IZY"])
value = pauli1.compose(pauli2, qargs=[0, 1, 2])
self.assertEqual(value, target)
with self.subTest(msg="compose 3-qubit qargs=[2, 1, 0]"):
target = PauliList(["ZYX", "YZI"])
value = pauli1.compose(pauli2, qargs=[2, 1, 0])
self.assertEqual(value, target)
with self.subTest(msg="compose 3-qubit qargs=[1, 0, 2]"):
target = PauliList(["XZY", "IYZ"])
value = pauli1.compose(pauli2, qargs=[1, 0, 2])
self.assertEqual(value, target)
def test_qargs_dot_3q(self):
"""Test 3-qubit dot method with qargs."""
pauli1 = PauliList(["III", "XXX"])
pauli2 = PauliList("XYZ")
with self.subTest(msg="dot 3-qubit qargs=None"):
target = PauliList(["XYZ", "IZY"])
value = pauli1.dot(pauli2, qargs=[0, 1, 2])
self.assertEqual(value, target)
with self.subTest(msg="dot 3-qubit qargs=[0, 1, 2]"):
target = PauliList(["XYZ", "IZY"])
value = pauli1.dot(pauli2, qargs=[0, 1, 2])
self.assertEqual(value, target)
with self.subTest(msg="dot 3-qubit qargs=[2, 1, 0]"):
target = PauliList(["ZYX", "YZI"])
value = pauli1.dot(pauli2, qargs=[2, 1, 0])
self.assertEqual(value, target)
with self.subTest(msg="dot 3-qubit qargs=[1, 0, 2]"):
target = PauliList(["XZY", "IYZ"])
value = pauli1.dot(pauli2, qargs=[1, 0, 2])
self.assertEqual(value, target)
@ddt
class TestPauliListMethods(QiskitTestCase):
"""Tests for PauliList utility methods class."""
def test_sort(self):
"""Test sort method."""
with self.subTest(msg="1 qubit standard order"):
unsrt = ["X", "Z", "I", "Y", "-iI", "X", "Z", "iI", "-I", "-iY"]
srt = ["I", "-iI", "-I", "iI", "X", "X", "Y", "-iY", "Z", "Z"]
target = PauliList(srt)
value = PauliList(unsrt).sort()
self.assertEqual(target, value)
with self.subTest(msg="1 qubit weight order"):
unsrt = ["X", "Z", "I", "Y", "-iI", "X", "Z", "iI", "-I", "-iY"]
srt = ["I", "-iI", "-I", "iI", "X", "X", "Y", "-iY", "Z", "Z"]
target = PauliList(srt)
value = PauliList(unsrt).sort(weight=True)
self.assertEqual(target, value)
with self.subTest(msg="1 qubit phase order"):
unsrt = ["X", "Z", "I", "Y", "-iI", "X", "Z", "iI", "-I", "-iY"]
srt = ["I", "X", "X", "Y", "Z", "Z", "-iI", "-iY", "-I", "iI"]
target = PauliList(srt)
value = PauliList(unsrt).sort(phase=True)
self.assertEqual(target, value)
with self.subTest(msg="1 qubit weight & phase order"):
unsrt = ["X", "Z", "I", "Y", "-iI", "X", "Z", "iI", "-I", "-iY"]
srt = ["I", "X", "X", "Y", "Z", "Z", "-iI", "-iY", "-I", "iI"]
target = PauliList(srt)
value = PauliList(unsrt).sort(weight=True, phase=True)
self.assertEqual(target, value)
with self.subTest(msg="2 qubit standard order"):
srt = [
"II",
"IX",
"IX",
"IY",
"IZ",
"iIZ",
"XI",
"XX",
"XX",
"iXX",
"XY",
"XZ",
"iXZ",
"YI",
"YI",
"-YI",
"YX",
"-iYX",
"YY",
"-iYY",
"-YY",
"iYY",
"YZ",
"ZI",
"ZX",
"ZX",
"ZY",
"ZZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort()
self.assertEqual(target, value)
with self.subTest(msg="2 qubit weight order"):
srt = [
"II",
"IX",
"IX",
"IY",
"IZ",
"iIZ",
"XI",
"YI",
"YI",
"-YI",
"ZI",
"XX",
"XX",
"iXX",
"XY",
"XZ",
"iXZ",
"YX",
"-iYX",
"YY",
"YY",
"-YY",
"YZ",
"ZX",
"ZX",
"ZY",
"ZZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort(weight=True)
self.assertEqual(target, value)
with self.subTest(msg="2 qubit phase order"):
srt = [
"II",
"IX",
"IX",
"IY",
"IZ",
"XI",
"XX",
"XX",
"XY",
"XZ",
"YI",
"YI",
"YX",
"YY",
"YY",
"YZ",
"ZI",
"ZX",
"ZX",
"ZY",
"ZZ",
"-iYX",
"-YI",
"-YY",
"iIZ",
"iXX",
"iXZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort(phase=True)
self.assertEqual(target, value)
with self.subTest(msg="2 qubit weight & phase order"):
srt = [
"II",
"IX",
"IX",
"IY",
"IZ",
"XI",
"YI",
"YI",
"ZI",
"XX",
"XX",
"XY",
"XZ",
"YX",
"YY",
"YY",
"YZ",
"ZX",
"ZX",
"ZY",
"ZZ",
"-iYX",
"-YI",
"-YY",
"iIZ",
"iXX",
"iXZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort(weight=True, phase=True)
self.assertEqual(target, value)
with self.subTest(msg="3 qubit standard order"):
srt = [
"III",
"III",
"IIX",
"IIY",
"-IIY",
"IIZ",
"IXI",
"IXX",
"IXY",
"iIXY",
"IXZ",
"IYI",
"IYX",
"IYY",
"IYZ",
"IZI",
"IZX",
"IZY",
"IZY",
"IZZ",
"XII",
"XII",
"XIX",
"XIY",
"XIZ",
"XXI",
"XXX",
"-iXXX",
"XXY",
"XXZ",
"XYI",
"XYX",
"iXYX",
"XYY",
"XYZ",
"XYZ",
"XZI",
"XZX",
"XZY",
"XZZ",
"YII",
"YIX",
"YIY",
"YIZ",
"YXI",
"YXX",
"YXY",
"YXZ",
"YXZ",
"YYI",
"YYX",
"YYX",
"YYY",
"YYZ",
"YZI",
"YZX",
"YZY",
"YZZ",
"ZII",
"ZIX",
"ZIY",
"ZIZ",
"ZXI",
"ZXX",
"iZXX",
"ZXY",
"ZXZ",
"ZYI",
"ZYI",
"ZYX",
"ZYY",
"ZYZ",
"ZZI",
"ZZX",
"ZZY",
"ZZZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort()
self.assertEqual(target, value)
with self.subTest(msg="3 qubit weight order"):
srt = [
"III",
"III",
"IIX",
"IIY",
"-IIY",
"IIZ",
"IXI",
"IYI",
"IZI",
"XII",
"XII",
"YII",
"ZII",
"IXX",
"IXY",
"iIXY",
"IXZ",
"IYX",
"IYY",
"IYZ",
"IZX",
"IZY",
"IZY",
"IZZ",
"XIX",
"XIY",
"XIZ",
"XXI",
"XYI",
"XZI",
"YIX",
"YIY",
"YIZ",
"YXI",
"YYI",
"YZI",
"ZIX",
"ZIY",
"ZIZ",
"ZXI",
"ZYI",
"ZYI",
"ZZI",
"XXX",
"-iXXX",
"XXY",
"XXZ",
"XYX",
"iXYX",
"XYY",
"XYZ",
"XYZ",
"XZX",
"XZY",
"XZZ",
"YXX",
"YXY",
"YXZ",
"YXZ",
"YYX",
"YYX",
"YYY",
"YYZ",
"YZX",
"YZY",
"YZZ",
"ZXX",
"iZXX",
"ZXY",
"ZXZ",
"ZYX",
"ZYY",
"ZYZ",
"ZZX",
"ZZY",
"ZZZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort(weight=True)
self.assertEqual(target, value)
with self.subTest(msg="3 qubit phase order"):
srt = [
"III",
"III",
"IIX",
"IIY",
"IIZ",
"IXI",
"IXX",
"IXY",
"IXZ",
"IYI",
"IYX",
"IYY",
"IYZ",
"IZI",
"IZX",
"IZY",
"IZY",
"IZZ",
"XII",
"XII",
"XIX",
"XIY",
"XIZ",
"XXI",
"XXX",
"XXY",
"XXZ",
"XYI",
"XYX",
"XYY",
"XYZ",
"XYZ",
"XZI",
"XZX",
"XZY",
"XZZ",
"YII",
"YIX",
"YIY",
"YIZ",
"YXI",
"YXX",
"YXY",
"YXZ",
"YXZ",
"YYI",
"YYX",
"YYX",
"YYY",
"YYZ",
"YZI",
"YZX",
"YZY",
"YZZ",
"ZII",
"ZIX",
"ZIY",
"ZIZ",
"ZXI",
"ZXX",
"ZXY",
"ZXZ",
"ZYI",
"ZYI",
"ZYX",
"ZYY",
"ZYZ",
"ZZI",
"ZZX",
"ZZY",
"ZZZ",
"-iXXX",
"-IIY",
"iIXY",
"iXYX",
"iZXX",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort(phase=True)
self.assertEqual(target, value)
with self.subTest(msg="3 qubit weight & phase order"):
srt = [
"III",
"III",
"IIX",
"IIY",
"IYI",
"IZI",
"XII",
"XII",
"YII",
"ZII",
"IXX",
"IXY",
"IXZ",
"IYX",
"IYY",
"IYZ",
"IZX",
"IZY",
"IZY",
"IZZ",
"XIX",
"XIY",
"XIZ",
"XXI",
"XYI",
"XZI",
"YIX",
"YIY",
"YIZ",
"YYI",
"YZI",
"ZIX",
"ZIY",
"ZIZ",
"ZXI",
"ZYI",
"ZYI",
"ZZI",
"XXX",
"XXY",
"XXZ",
"XYX",
"XYY",
"XYZ",
"XZX",
"XZY",
"XZZ",
"YXX",
"YXY",
"YXZ",
"YXZ",
"YYX",
"YYX",
"YYY",
"YYZ",
"YZX",
"YZY",
"YZZ",
"ZXX",
"ZXY",
"ZXZ",
"ZYX",
"ZYY",
"ZYZ",
"ZZX",
"ZZY",
"ZZZ",
"-iZIZ",
"-iXXX",
"-IIY",
"iIXI",
"iIXY",
"iYXI",
"iXYX",
"iXYZ",
"iZXX",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort(weight=True, phase=True)
self.assertEqual(target, value)
def test_unique(self):
"""Test unique method."""
with self.subTest(msg="1 qubit"):
labels = ["X", "Z", "X", "X", "I", "Y", "I", "X", "Z", "Z", "X", "I"]
unique = ["X", "Z", "I", "Y"]
target = PauliList(unique)
value = PauliList(labels).unique()
self.assertEqual(target, value)
with self.subTest(msg="2 qubit"):
labels = ["XX", "IX", "XX", "II", "IZ", "ZI", "YX", "YX", "ZZ", "IX", "XI"]
unique = ["XX", "IX", "II", "IZ", "ZI", "YX", "ZZ", "XI"]
target = PauliList(unique)
value = PauliList(labels).unique()
self.assertEqual(target, value)
with self.subTest(msg="10 qubit"):
labels = [10 * "X", 10 * "I", 10 * "X"]
unique = [10 * "X", 10 * "I"]
target = PauliList(unique)
value = PauliList(labels).unique()
self.assertEqual(target, value)
def test_delete(self):
"""Test delete method."""
with self.subTest(msg="single row"):
for j in range(1, 6):
pauli = PauliList([j * "X", j * "Y"])
self.assertEqual(pauli.delete(0), PauliList(j * "Y"))
self.assertEqual(pauli.delete(1), PauliList(j * "X"))
with self.subTest(msg="multiple rows"):
for j in range(1, 6):
pauli = PauliList([j * "X", "-i" + j * "Y", j * "Z"])
self.assertEqual(pauli.delete([0, 2]), PauliList("-i" + j * "Y"))
self.assertEqual(pauli.delete([1, 2]), PauliList(j * "X"))
self.assertEqual(pauli.delete([0, 1]), PauliList(j * "Z"))
with self.subTest(msg="single qubit"):
pauli = PauliList(["IIX", "iIYI", "ZII"])
value = pauli.delete(0, qubit=True)
target = PauliList(["II", "iIY", "ZI"])
self.assertEqual(value, target)
value = pauli.delete(1, qubit=True)
target = PauliList(["IX", "iII", "ZI"])
self.assertEqual(value, target)
value = pauli.delete(2, qubit=True)
target = PauliList(["IX", "iYI", "II"])
self.assertEqual(value, target)
with self.subTest(msg="multiple qubits"):
pauli = PauliList(["IIX", "IYI", "-ZII"])
value = pauli.delete([0, 1], qubit=True)
target = PauliList(["I", "I", "-Z"])
self.assertEqual(value, target)
value = pauli.delete([1, 2], qubit=True)
target = PauliList(["X", "I", "-I"])
self.assertEqual(value, target)
value = pauli.delete([0, 2], qubit=True)
target = PauliList(["I", "Y", "-I"])
self.assertEqual(value, target)
def test_insert(self):
"""Test insert method."""
# Insert single row
for j in range(1, 10):
pauli = PauliList(j * "X")
target0 = PauliList([j * "I", j * "X"])
target1 = PauliList([j * "X", j * "I"])
with self.subTest(msg=f"single row from str ({j})"):
value0 = pauli.insert(0, j * "I")
self.assertEqual(value0, target0)
value1 = pauli.insert(1, j * "I")
self.assertEqual(value1, target1)
with self.subTest(msg=f"single row from PauliList ({j})"):
value0 = pauli.insert(0, PauliList(j * "I"))
self.assertEqual(value0, target0)
value1 = pauli.insert(1, PauliList(j * "I"))
self.assertEqual(value1, target1)
target0 = PauliList(["i" + j * "I", j * "X"])
target1 = PauliList([j * "X", "i" + j * "I"])
with self.subTest(msg=f"single row with phase from str ({j})"):
value0 = pauli.insert(0, "i" + j * "I")
self.assertEqual(value0, target0)
value1 = pauli.insert(1, "i" + j * "I")
self.assertEqual(value1, target1)
with self.subTest(msg=f"single row with phase from PauliList ({j})"):
value0 = pauli.insert(0, PauliList("i" + j * "I"))
self.assertEqual(value0, target0)
value1 = pauli.insert(1, PauliList("i" + j * "I"))
self.assertEqual(value1, target1)
# Insert multiple rows
for j in range(1, 10):
pauli = PauliList("i" + j * "X")
insert = PauliList([j * "I", j * "Y", j * "Z", "-i" + j * "X"])
target0 = insert + pauli
target1 = pauli + insert
with self.subTest(msg=f"multiple-rows from PauliList ({j})"):
value0 = pauli.insert(0, insert)
self.assertEqual(value0, target0)
value1 = pauli.insert(1, insert)
self.assertEqual(value1, target1)
# Insert single column
pauli = PauliList(["X", "Y", "Z", "-iI"])
for i in ["I", "X", "Y", "Z", "iY"]:
phase = "" if len(i) == 1 else i[0]
p = i if len(i) == 1 else i[1]
target0 = PauliList(
[
phase + "X" + p,
phase + "Y" + p,
phase + "Z" + p,
("" if phase else "-i") + "I" + p,
]
)
target1 = PauliList(
[
i + "X",
i + "Y",
i + "Z",
("" if phase else "-i") + p + "I",
]
)
with self.subTest(msg="single-column single-val from str"):
value = pauli.insert(0, i, qubit=True)
self.assertEqual(value, target0)
value = pauli.insert(1, i, qubit=True)
self.assertEqual(value, target1)
with self.subTest(msg="single-column single-val from PauliList"):
value = pauli.insert(0, PauliList(i), qubit=True)
self.assertEqual(value, target0)
value = pauli.insert(1, PauliList(i), qubit=True)
self.assertEqual(value, target1)
# Insert single column with multiple values
pauli = PauliList(["X", "Y", "iZ"])
for i in [["I", "X", "Y"], ["X", "iY", "Z"], ["Y", "Z", "I"]]:
target0 = PauliList(
["X" + i[0], "Y" + i[1] if len(i[1]) == 1 else i[1][0] + "Y" + i[1][1], "iZ" + i[2]]
)
target1 = PauliList([i[0] + "X", i[1] + "Y", "i" + i[2] + "Z"])
with self.subTest(msg="single-column multiple-vals from PauliList"):
value = pauli.insert(0, PauliList(i), qubit=True)
self.assertEqual(value, target0)
value = pauli.insert(1, PauliList(i), qubit=True)
self.assertEqual(value, target1)
# Insert multiple columns from single
pauli = PauliList(["X", "iY", "Z"])
for j in range(1, 5):
for i in [j * "I", j * "X", j * "Y", "i" + j * "Z"]:
phase = "" if len(i) == j else i[0]
p = i if len(i) == j else i[1:]
target0 = PauliList(
[
phase + "X" + p,
("-" if phase else "i") + "Y" + p,
phase + "Z" + p,
]
)
target1 = PauliList([i + "X", ("-" if phase else "i") + p + "Y", i + "Z"])
with self.subTest(msg="multiple-columns single-val from str"):
value = pauli.insert(0, i, qubit=True)
self.assertEqual(value, target0)
value = pauli.insert(1, i, qubit=True)
self.assertEqual(value, target1)
with self.subTest(msg="multiple-columns single-val from PauliList"):
value = pauli.insert(0, PauliList(i), qubit=True)
self.assertEqual(value, target0)
value = pauli.insert(1, PauliList(i), qubit=True)
self.assertEqual(value, target1)
# Insert multiple columns multiple row values
pauli = PauliList(["X", "Y", "-iZ"])
for j in range(1, 5):
for i in [
[j * "I", j * "X", j * "Y"],
[j * "X", j * "Z", "i" + j * "Y"],
[j * "Y", j * "Z", j * "I"],
]:
target0 = PauliList(
[
"X" + i[0],
"Y" + i[1],
("-i" if len(i[2]) == j else "") + "Z" + i[2][-j:],
]
)
target1 = PauliList(
[
i[0] + "X",
i[1] + "Y",
("-i" if len(i[2]) == j else "") + i[2][-j:] + "Z",
]
)
with self.subTest(msg="multiple-column multiple-vals from PauliList"):
value = pauli.insert(0, PauliList(i), qubit=True)
self.assertEqual(value, target0)
value = pauli.insert(1, PauliList(i), qubit=True)
self.assertEqual(value, target1)
def test_commutes(self):
"""Test commutes method."""
# Single qubit Pauli
pauli = PauliList(["I", "X", "Y", "Z", "-iY"])
with self.subTest(msg="commutes single-Pauli I"):
value = list(pauli.commutes("I"))
target = [True, True, True, True, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli X"):
value = list(pauli.commutes("X"))
target = [True, True, False, False, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli Y"):
value = list(pauli.commutes("Y"))
target = [True, False, True, False, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli Z"):
value = list(pauli.commutes("Z"))
target = [True, False, False, True, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli iZ"):
value = list(pauli.commutes("iZ"))
target = [True, False, False, True, False]
self.assertEqual(value, target)
# 2-qubit Pauli
pauli = PauliList(["II", "IX", "YI", "XY", "ZZ", "-iYY"])
with self.subTest(msg="commutes single-Pauli II"):
value = list(pauli.commutes("II"))
target = [True, True, True, True, True, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli IX"):
value = list(pauli.commutes("IX"))
target = [True, True, True, False, False, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli XI"):
value = list(pauli.commutes("XI"))
target = [True, True, False, True, False, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli YI"):
value = list(pauli.commutes("YI"))
target = [True, True, True, False, False, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli IY"):
value = list(pauli.commutes("IY"))
target = [True, False, True, True, False, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli XY"):
value = list(pauli.commutes("XY"))
target = [True, False, False, True, True, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli YX"):
value = list(pauli.commutes("YX"))
target = [True, True, True, True, True, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli ZZ"):
value = list(pauli.commutes("ZZ"))
target = [True, False, False, True, True, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli iYX"):
value = list(pauli.commutes("iYX"))
target = [True, True, True, True, True, False]
self.assertEqual(value, target)
def test_anticommutes(self):
"""Test anticommutes method."""
# Single qubit Pauli
pauli = PauliList(["I", "X", "Y", "Z", "-iY"])
with self.subTest(msg="anticommutes single-Pauli I"):
value = list(pauli.anticommutes("I"))
target = [False, False, False, False, False]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli X"):
value = list(pauli.anticommutes("X"))
target = [False, False, True, True, True]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli Y"):
value = list(pauli.anticommutes("Y"))
target = [False, True, False, True, False]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli Z"):
value = list(pauli.anticommutes("Z"))
target = [False, True, True, False, True]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli iZ"):
value = list(pauli.anticommutes("iZ"))
target = [False, True, True, False, True]
self.assertEqual(value, target)
# 2-qubit Pauli
pauli = PauliList(["II", "IX", "YI", "XY", "ZZ", "iZX"])
with self.subTest(msg="anticommutes single-Pauli II"):
value = list(pauli.anticommutes("II"))
target = [False, False, False, False, False, False]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli IX"):
value = list(pauli.anticommutes("IX"))
target = [False, False, False, True, True, False]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli XI"):
value = list(pauli.anticommutes("XI"))
target = [False, False, True, False, True, True]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli YI"):
value = list(pauli.anticommutes("YI"))
target = [False, False, False, True, True, True]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli IY"):
value = list(pauli.anticommutes("IY"))
target = [False, True, False, False, True, True]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli XY"):
value = list(pauli.anticommutes("XY"))
target = [False, True, True, False, False, False]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli YX"):
value = list(pauli.anticommutes("YX"))
target = [False, False, False, False, False, True]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli ZZ"):
value = list(pauli.anticommutes("ZZ"))
target = [False, True, True, False, False, True]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli iXY"):
value = list(pauli.anticommutes("iXY"))
target = [False, True, True, False, False, False]
self.assertEqual(value, target)
def test_commutes_with_all(self):
"""Test commutes_with_all method."""
# 1-qubit
pauli = PauliList(["I", "X", "Y", "Z", "-iY"])
with self.subTest(msg="commutes_with_all [I]"):
value = list(pauli.commutes_with_all("I"))
target = [0, 1, 2, 3, 4]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [X]"):
value = list(pauli.commutes_with_all("X"))
target = [0, 1]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [Y]"):
value = list(pauli.commutes_with_all("Y"))
target = [0, 2, 4]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [Z]"):
value = list(pauli.commutes_with_all("Z"))
target = [0, 3]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [iY]"):
value = list(pauli.commutes_with_all("iY"))
target = [0, 2, 4]
self.assertEqual(value, target)
# 2-qubit Pauli
pauli = PauliList(["II", "IX", "YI", "XY", "ZZ", "iXY"])
with self.subTest(msg="commutes_with_all [IX, YI]"):
other = PauliList(["IX", "YI"])
value = list(pauli.commutes_with_all(other))
target = [0, 1, 2]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [XY, ZZ]"):
other = PauliList(["XY", "ZZ"])
value = list(pauli.commutes_with_all(other))
target = [0, 3, 4, 5]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [YX, ZZ]"):
other = PauliList(["YX", "ZZ"])
value = list(pauli.commutes_with_all(other))
target = [0, 3, 4, 5]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [XY, YX]"):
other = PauliList(["XY", "YX"])
value = list(pauli.commutes_with_all(other))
target = [0, 3, 4, 5]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [XY, IX]"):
other = PauliList(["XY", "IX"])
value = list(pauli.commutes_with_all(other))
target = [0]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [YX, IX]"):
other = PauliList(["YX", "IX"])
value = list(pauli.commutes_with_all(other))
target = [0, 1, 2]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [-iYX, iZZ]"):
other = PauliList(["-iYX", "iZZ"])
value = list(pauli.commutes_with_all(other))
target = [0, 3, 4, 5]
self.assertEqual(value, target)
def test_anticommutes_with_all(self):
"""Test anticommutes_with_all method."""
# 1-qubit
pauli = PauliList(["I", "X", "Y", "Z", "-iY"])
with self.subTest(msg="anticommutes_with_all [I]"):
value = list(pauli.anticommutes_with_all("I"))
target = []
self.assertEqual(value, target)
with self.subTest(msg="antianticommutes_with_all [X]"):
value = list(pauli.anticommutes_with_all("X"))
target = [2, 3, 4]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [Y]"):
value = list(pauli.anticommutes_with_all("Y"))
target = [1, 3]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [Z]"):
value = list(pauli.anticommutes_with_all("Z"))
target = [1, 2, 4]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [iY]"):
value = list(pauli.anticommutes_with_all("iY"))
target = [1, 3]
self.assertEqual(value, target)
# 2-qubit Pauli
pauli = PauliList(["II", "IX", "YI", "XY", "ZZ", "iZX"])
with self.subTest(msg="anticommutes_with_all [IX, YI]"):
other = PauliList(["IX", "YI"])
value = list(pauli.anticommutes_with_all(other))
target = [3, 4]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [XY, ZZ]"):
other = PauliList(["XY", "ZZ"])
value = list(pauli.anticommutes_with_all(other))
target = [1, 2]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [YX, ZZ]"):
other = PauliList(["YX", "ZZ"])
value = list(pauli.anticommutes_with_all(other))
target = [5]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [XY, YX]"):
other = PauliList(["XY", "YX"])
value = list(pauli.anticommutes_with_all(other))
target = []
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [XY, IX]"):
other = PauliList(["XY", "IX"])
value = list(pauli.anticommutes_with_all(other))
target = []
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [YX, IX]"):
other = PauliList(["YX", "IX"])
value = list(pauli.anticommutes_with_all(other))
target = []
self.assertEqual(value, target)
@combine(
gate=(
IGate(),
XGate(),
YGate(),
ZGate(),
HGate(),
SGate(),
SdgGate(),
Clifford(IGate()),
Clifford(XGate()),
Clifford(YGate()),
Clifford(ZGate()),
Clifford(HGate()),
Clifford(SGate()),
Clifford(SdgGate()),
)
)
def test_evolve_clifford1(self, gate):
"""Test evolve method for 1-qubit Clifford gates."""
op = Operator(gate)
pauli_list = PauliList(pauli_group_labels(1, True))
value = [Operator(pauli) for pauli in pauli_list.evolve(gate)]
value_h = [Operator(pauli) for pauli in pauli_list.evolve(gate, frame="h")]
value_s = [Operator(pauli) for pauli in pauli_list.evolve(gate, frame="s")]
if isinstance(gate, Clifford):
value_inv = [Operator(pauli) for pauli in pauli_list.evolve(gate.adjoint())]
else:
value_inv = [Operator(pauli) for pauli in pauli_list.evolve(gate.inverse())]
target = [op.adjoint().dot(pauli).dot(op) for pauli in pauli_list]
self.assertListEqual(value, target)
self.assertListEqual(value, value_h)
self.assertListEqual(value_inv, value_s)
@combine(
gate=(
CXGate(),
CYGate(),
CZGate(),
SwapGate(),
Clifford(CXGate()),
Clifford(CYGate()),
Clifford(CZGate()),
Clifford(SwapGate()),
)
)
def test_evolve_clifford2(self, gate):
"""Test evolve method for 2-qubit Clifford gates."""
op = Operator(gate)
pauli_list = PauliList(pauli_group_labels(2, True))
value = [Operator(pauli) for pauli in pauli_list.evolve(gate)]
value_h = [Operator(pauli) for pauli in pauli_list.evolve(gate, frame="h")]
value_s = [Operator(pauli) for pauli in pauli_list.evolve(gate, frame="s")]
if isinstance(gate, Clifford):
value_inv = [Operator(pauli) for pauli in pauli_list.evolve(gate.adjoint())]
else:
value_inv = [Operator(pauli) for pauli in pauli_list.evolve(gate.inverse())]
target = [op.adjoint().dot(pauli).dot(op) for pauli in pauli_list]
self.assertListEqual(value, target)
self.assertListEqual(value, value_h)
self.assertListEqual(value_inv, value_s)
def test_phase_dtype_evolve_clifford(self):
"""Test phase dtype during evolve method for Clifford gates."""
gates = (
IGate(),
XGate(),
YGate(),
ZGate(),
HGate(),
SGate(),
SdgGate(),
CXGate(),
CYGate(),
CZGate(),
SwapGate(),
)
dtypes = [
int,
np.int8,
np.uint8,
np.int16,
np.uint16,
np.int32,
np.uint32,
np.int64,
np.uint64,
]
for gate, dtype in itertools.product(gates, dtypes):
z = np.ones(gate.num_qubits, dtype=bool)
x = np.ones(gate.num_qubits, dtype=bool)
phase = (np.sum(z & x) % 4).astype(dtype)
paulis = Pauli((z, x, phase))
evo = paulis.evolve(gate)
self.assertEqual(evo.phase.dtype, dtype)
@combine(phase=(True, False))
def test_evolve_clifford_qargs(self, phase):
"""Test evolve method for random Clifford"""
cliff = random_clifford(3, seed=10)
op = Operator(cliff)
pauli_list = random_pauli_list(5, 3, seed=10, phase=phase)
qargs = [3, 0, 1]
value = [Operator(pauli) for pauli in pauli_list.evolve(cliff, qargs=qargs)]
value_inv = [Operator(pauli) for pauli in pauli_list.evolve(cliff.adjoint(), qargs=qargs)]
value_h = [Operator(pauli) for pauli in pauli_list.evolve(cliff, qargs=qargs, frame="h")]
value_s = [Operator(pauli) for pauli in pauli_list.evolve(cliff, qargs=qargs, frame="s")]
target = [
Operator(pauli).compose(op.adjoint(), qargs=qargs).dot(op, qargs=qargs)
for pauli in pauli_list
]
self.assertListEqual(value, target)
self.assertListEqual(value, value_h)
self.assertListEqual(value_inv, value_s)
def test_group_qubit_wise_commuting(self):
"""Test grouping qubit-wise commuting operators"""
def qubitwise_commutes(left: Pauli, right: Pauli) -> bool:
return len(left) == len(right) and all(a.commutes(b) for a, b in zip(left, right))
input_labels = ["IY", "ZX", "XZ", "YI", "YX", "YY", "YZ", "ZI", "ZX", "ZY", "iZZ", "II"]
np.random.shuffle(input_labels)
pauli_list = PauliList(input_labels)
groups = pauli_list.group_qubit_wise_commuting()
# checking that every input Pauli in pauli_list is in a group in the ouput
output_labels = [pauli.to_label() for group in groups for pauli in group]
self.assertListEqual(sorted(output_labels), sorted(input_labels))
# Within each group, every operator qubit-wise commutes with every other operator.
for group in groups:
self.assertTrue(
all(
qubitwise_commutes(pauli1, pauli2)
for pauli1, pauli2 in itertools.combinations(group, 2)
)
)
# For every pair of groups, at least one element from one does not qubit-wise commute with
# at least one element of the other.
for group1, group2 in itertools.combinations(groups, 2):
self.assertFalse(
all(
qubitwise_commutes(group1_pauli, group2_pauli)
for group1_pauli, group2_pauli in itertools.product(group1, group2)
)
)
def test_group_commuting(self):
"""Test general grouping commuting operators"""
def commutes(left: Pauli, right: Pauli) -> bool:
return len(left) == len(right) and left.commutes(right)
input_labels = ["IY", "ZX", "XZ", "YI", "YX", "YY", "YZ", "ZI", "ZX", "ZY", "iZZ", "II"]
np.random.shuffle(input_labels)
pauli_list = PauliList(input_labels)
# if qubit_wise=True, equivalent to test_group_qubit_wise_commuting
groups = pauli_list.group_commuting(qubit_wise=False)
# checking that every input Pauli in pauli_list is in a group in the ouput
output_labels = [pauli.to_label() for group in groups for pauli in group]
self.assertListEqual(sorted(output_labels), sorted(input_labels))
# Within each group, every operator commutes with every other operator.
for group in groups:
self.assertTrue(
all(commutes(pauli1, pauli2) for pauli1, pauli2 in itertools.combinations(group, 2))
)
# For every pair of groups, at least one element from one group does not commute with
# at least one element of the other.
for group1, group2 in itertools.combinations(groups, 2):
self.assertFalse(
all(
commutes(group1_pauli, group2_pauli)
for group1_pauli, group2_pauli in itertools.product(group1, group2)
)
)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for PauliTable class."""
import unittest
from test import combine
import numpy as np
from ddt import ddt
from scipy.sparse import csr_matrix
from qiskit import QiskitError
from qiskit.quantum_info.operators.symplectic import PauliTable
from qiskit.test import QiskitTestCase
def pauli_mat(label):
"""Return Pauli matrix from a Pauli label"""
mat = np.eye(1, dtype=complex)
for i in label:
if i == "I":
mat = np.kron(mat, np.eye(2, dtype=complex))
elif i == "X":
mat = np.kron(mat, np.array([[0, 1], [1, 0]], dtype=complex))
elif i == "Y":
mat = np.kron(mat, np.array([[0, -1j], [1j, 0]], dtype=complex))
elif i == "Z":
mat = np.kron(mat, np.array([[1, 0], [0, -1]], dtype=complex))
else:
raise QiskitError(f"Invalid Pauli string {i}")
return mat
class TestPauliTableInit(QiskitTestCase):
"""Tests for PauliTable initialization."""
def test_array_init(self):
"""Test array initialization."""
# Matrix array initialization
with self.subTest(msg="bool array"):
target = np.array([[False, False], [True, True]])
with self.assertWarns(DeprecationWarning):
value = PauliTable(target)._array
self.assertTrue(np.all(value == target))
with self.subTest(msg="bool array no copy"):
target = np.array([[False, True], [True, True]])
with self.assertWarns(DeprecationWarning):
value = PauliTable(target)._array
value[0, 0] = not value[0, 0]
self.assertTrue(np.all(value == target))
with self.subTest(msg="bool array raises"):
array = np.array([[False, False, False], [True, True, True]])
with self.assertWarns(DeprecationWarning):
self.assertRaises(QiskitError, PauliTable, array)
def test_vector_init(self):
"""Test vector initialization."""
# Vector array initialization
with self.subTest(msg="bool vector"):
target = np.array([False, False, False, False])
with self.assertWarns(DeprecationWarning):
value = PauliTable(target)._array
self.assertTrue(np.all(value == target))
with self.subTest(msg="bool vector no copy"):
target = np.array([False, True, True, False])
with self.assertWarns(DeprecationWarning):
value = PauliTable(target)._array
value[0, 0] = not value[0, 0]
self.assertTrue(np.all(value == target))
def test_string_init(self):
"""Test string initialization."""
# String initialization
with self.subTest(msg='str init "I"'):
with self.assertWarns(DeprecationWarning):
value = PauliTable("I")._array
target = np.array([[False, False]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
with self.subTest(msg='str init "X"'):
with self.assertWarns(DeprecationWarning):
value = PauliTable("X")._array
target = np.array([[True, False]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
with self.subTest(msg='str init "Y"'):
with self.assertWarns(DeprecationWarning):
value = PauliTable("Y")._array
target = np.array([[True, True]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
with self.subTest(msg='str init "Z"'):
with self.assertWarns(DeprecationWarning):
value = PauliTable("Z")._array
target = np.array([[False, True]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
with self.subTest(msg='str init "IX"'):
with self.assertWarns(DeprecationWarning):
value = PauliTable("IX")._array
target = np.array([[True, False, False, False]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
with self.subTest(msg='str init "XI"'):
with self.assertWarns(DeprecationWarning):
value = PauliTable("XI")._array
target = np.array([[False, True, False, False]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
with self.subTest(msg='str init "YZ"'):
with self.assertWarns(DeprecationWarning):
value = PauliTable("YZ")._array
target = np.array([[False, True, True, True]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
with self.subTest(msg='str init "XIZ"'):
with self.assertWarns(DeprecationWarning):
value = PauliTable("XIZ")._array
target = np.array([[False, False, True, True, False, False]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
def test_table_init(self):
"""Test table initialization."""
# Pauli Table initialization
with self.subTest(msg="PauliTable"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["XI", "IX", "IZ"])
value = PauliTable(target)
self.assertEqual(value, target)
with self.subTest(msg="PauliTable no copy"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["XI", "IX", "IZ"])
value = PauliTable(target)
value[0] = "II"
self.assertEqual(value, target)
class TestPauliTableProperties(QiskitTestCase):
"""Tests for PauliTable properties."""
def test_array_propertiy(self):
"""Test array property"""
with self.subTest(msg="array"):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable("II")
array = np.zeros([2, 4], dtype=bool)
self.assertTrue(np.all(pauli.array == array))
with self.subTest(msg="set array"):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable("XX")
array = np.zeros([1, 4], dtype=bool)
pauli.array = array
self.assertTrue(np.all(pauli.array == array))
with self.subTest(msg="set array raises"):
def set_array_raise():
with self.assertWarns(DeprecationWarning):
pauli = PauliTable("XXX")
pauli.array = np.eye(4)
return pauli
self.assertRaises(ValueError, set_array_raise)
def test_x_propertiy(self):
"""Test X property"""
with self.subTest(msg="X"):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["XI", "IZ", "YY"])
array = np.array([[False, True], [False, False], [True, True]], dtype=bool)
self.assertTrue(np.all(pauli.X == array))
with self.subTest(msg="set X"):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["XI", "IZ"])
val = np.array([[False, False], [True, True]], dtype=bool)
pauli.X = val
with self.assertWarns(DeprecationWarning):
self.assertEqual(pauli, PauliTable.from_labels(["II", "XY"]))
with self.subTest(msg="set X raises"):
def set_x():
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["XI", "IZ"])
val = np.array([[False, False, False], [True, True, True]], dtype=bool)
pauli.X = val
return pauli
self.assertRaises(Exception, set_x)
def test_z_propertiy(self):
"""Test Z property"""
with self.subTest(msg="Z"):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["XI", "IZ", "YY"])
array = np.array([[False, False], [True, False], [True, True]], dtype=bool)
self.assertTrue(np.all(pauli.Z == array))
with self.subTest(msg="set Z"):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["XI", "IZ"])
val = np.array([[False, False], [True, True]], dtype=bool)
pauli.Z = val
with self.assertWarns(DeprecationWarning):
self.assertEqual(pauli, PauliTable.from_labels(["XI", "ZZ"]))
with self.subTest(msg="set Z raises"):
def set_z():
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["XI", "IZ"])
val = np.array([[False, False, False], [True, True, True]], dtype=bool)
pauli.Z = val
return pauli
self.assertRaises(Exception, set_z)
def test_shape_propertiy(self):
"""Test shape property"""
shape = (3, 8)
with self.assertWarns(DeprecationWarning):
pauli = PauliTable(np.zeros(shape))
self.assertEqual(pauli.shape, shape)
def test_size_propertiy(self):
"""Test size property"""
with self.subTest(msg="size"):
for j in range(1, 10):
shape = (j, 8)
with self.assertWarns(DeprecationWarning):
pauli = PauliTable(np.zeros(shape))
self.assertEqual(pauli.size, j)
def test_n_qubit_propertiy(self):
"""Test n_qubit property"""
with self.subTest(msg="num_qubits"):
for j in range(1, 10):
shape = (5, 2 * j)
with self.assertWarns(DeprecationWarning):
pauli = PauliTable(np.zeros(shape))
self.assertEqual(pauli.num_qubits, j)
def test_eq(self):
"""Test __eq__ method."""
with self.assertWarns(DeprecationWarning):
pauli1 = PauliTable.from_labels(["II", "XI"])
pauli2 = PauliTable.from_labels(["XI", "II"])
self.assertEqual(pauli1, pauli1)
self.assertNotEqual(pauli1, pauli2)
def test_len_methods(self):
"""Test __len__ method."""
for j in range(1, 10):
labels = j * ["XX"]
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
self.assertEqual(len(pauli), j)
def test_add_methods(self):
"""Test __add__ method."""
labels1 = ["XXI", "IXX"]
labels2 = ["XXI", "ZZI", "ZYZ"]
with self.assertWarns(DeprecationWarning):
pauli1 = PauliTable.from_labels(labels1)
pauli2 = PauliTable.from_labels(labels2)
target = PauliTable.from_labels(labels1 + labels2)
self.assertEqual(target, pauli1 + pauli2)
def test_add_qargs(self):
"""Test add method with qargs."""
with self.assertWarns(DeprecationWarning):
pauli1 = PauliTable.from_labels(["IIII", "YYYY"])
pauli2 = PauliTable.from_labels(["XY", "YZ"])
with self.subTest(msg="qargs=[0, 1]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IIII", "YYYY", "IIXY", "IIYZ"])
self.assertEqual(pauli1 + pauli2([0, 1]), target)
with self.subTest(msg="qargs=[0, 3]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IIII", "YYYY", "XIIY", "YIIZ"])
self.assertEqual(pauli1 + pauli2([0, 3]), target)
with self.subTest(msg="qargs=[2, 1]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IIII", "YYYY", "IYXI", "IZYI"])
self.assertEqual(pauli1 + pauli2([2, 1]), target)
with self.subTest(msg="qargs=[3, 1]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IIII", "YYYY", "YIXI", "ZIYI"])
self.assertEqual(pauli1 + pauli2([3, 1]), target)
def test_getitem_methods(self):
"""Test __getitem__ method."""
with self.subTest(msg="__getitem__ single"):
labels = ["XI", "IY"]
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
self.assertEqual(pauli[0], PauliTable(labels[0]))
self.assertEqual(pauli[1], PauliTable(labels[1]))
with self.subTest(msg="__getitem__ array"):
labels = np.array(["XI", "IY", "IZ", "XY", "ZX"])
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
inds = [0, 3]
with self.assertWarns(DeprecationWarning):
self.assertEqual(pauli[inds], PauliTable.from_labels(labels[inds]))
inds = np.array([4, 1])
with self.assertWarns(DeprecationWarning):
self.assertEqual(pauli[inds], PauliTable.from_labels(labels[inds]))
with self.subTest(msg="__getitem__ slice"):
labels = np.array(["XI", "IY", "IZ", "XY", "ZX"])
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
self.assertEqual(pauli[:], pauli)
with self.assertWarns(DeprecationWarning):
self.assertEqual(pauli[1:3], PauliTable.from_labels(labels[1:3]))
def test_setitem_methods(self):
"""Test __setitem__ method."""
with self.subTest(msg="__setitem__ single"):
labels = ["XI", "IY"]
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["XI", "IY"])
pauli[0] = "II"
with self.assertWarns(DeprecationWarning):
self.assertEqual(pauli[0], PauliTable("II"))
pauli[1] = "XX"
with self.assertWarns(DeprecationWarning):
self.assertEqual(pauli[1], PauliTable("XX"))
def raises_single():
# Wrong size Pauli
pauli[0] = "XXX"
self.assertRaises(Exception, raises_single)
with self.subTest(msg="__setitem__ array"):
labels = np.array(["XI", "IY", "IZ"])
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
target = PauliTable.from_labels(["II", "ZZ"])
inds = [2, 0]
pauli[inds] = target
self.assertEqual(pauli[inds], target)
def raises_array():
with self.assertWarns(DeprecationWarning):
pauli[inds] = PauliTable.from_labels(["YY", "ZZ", "XX"])
self.assertRaises(Exception, raises_array)
with self.subTest(msg="__setitem__ slice"):
labels = np.array(5 * ["III"])
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
target = PauliTable.from_labels(5 * ["XXX"])
pauli[:] = target
self.assertEqual(pauli[:], target)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(2 * ["ZZZ"])
pauli[1:3] = target
self.assertEqual(pauli[1:3], target)
class TestPauliTableLabels(QiskitTestCase):
"""Tests PauliTable label representation conversions."""
def test_from_labels_1q(self):
"""Test 1-qubit from_labels method."""
labels = ["I", "Z", "Z", "X", "Y"]
array = np.array(
[[False, False], [False, True], [False, True], [True, False], [True, True]], dtype=bool
)
with self.assertWarns(DeprecationWarning):
target = PauliTable(array)
value = PauliTable.from_labels(labels)
self.assertEqual(target, value)
def test_from_labels_2q(self):
"""Test 2-qubit from_labels method."""
labels = ["II", "YY", "XZ"]
array = np.array(
[[False, False, False, False], [True, True, True, True], [False, True, True, False]],
dtype=bool,
)
with self.assertWarns(DeprecationWarning):
target = PauliTable(array)
value = PauliTable.from_labels(labels)
self.assertEqual(target, value)
def test_from_labels_5q(self):
"""Test 5-qubit from_labels method."""
labels = [5 * "I", 5 * "X", 5 * "Y", 5 * "Z"]
array = np.array(
[10 * [False], 5 * [True] + 5 * [False], 10 * [True], 5 * [False] + 5 * [True]],
dtype=bool,
)
with self.assertWarns(DeprecationWarning):
target = PauliTable(array)
value = PauliTable.from_labels(labels)
self.assertEqual(target, value)
def test_to_labels_1q(self):
"""Test 1-qubit to_labels method."""
with self.assertWarns(DeprecationWarning):
pauli = PauliTable(
np.array(
[[False, False], [False, True], [False, True], [True, False], [True, True]],
dtype=bool,
)
)
target = ["I", "Z", "Z", "X", "Y"]
value = pauli.to_labels()
self.assertEqual(value, target)
def test_to_labels_1q_array(self):
"""Test 1-qubit to_labels method w/ array=True."""
with self.assertWarns(DeprecationWarning):
pauli = PauliTable(
np.array(
[[False, False], [False, True], [False, True], [True, False], [True, True]],
dtype=bool,
)
)
target = np.array(["I", "Z", "Z", "X", "Y"])
value = pauli.to_labels(array=True)
self.assertTrue(np.all(value == target))
def test_labels_round_trip(self):
"""Test from_labels and to_labels round trip."""
target = ["III", "IXZ", "XYI", "ZZZ"]
with self.assertWarns(DeprecationWarning):
value = PauliTable.from_labels(target).to_labels()
self.assertEqual(value, target)
def test_labels_round_trip_array(self):
"""Test from_labels and to_labels round trip w/ array=True."""
labels = ["III", "IXZ", "XYI", "ZZZ"]
target = np.array(labels)
with self.assertWarns(DeprecationWarning):
value = PauliTable.from_labels(labels).to_labels(array=True)
self.assertTrue(np.all(value == target))
class TestPauliTableMatrix(QiskitTestCase):
"""Tests PauliTable matrix representation conversions."""
def test_to_matrix_1q(self):
"""Test 1-qubit to_matrix method."""
labels = ["X", "I", "Z", "Y"]
targets = [pauli_mat(i) for i in labels]
with self.assertWarns(DeprecationWarning):
values = PauliTable.from_labels(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_1q_array(self):
"""Test 1-qubit to_matrix method w/ array=True."""
labels = ["Z", "I", "Y", "X"]
target = np.array([pauli_mat(i) for i in labels])
with self.assertWarns(DeprecationWarning):
value = PauliTable.from_labels(labels).to_matrix(array=True)
self.assertTrue(isinstance(value, np.ndarray))
self.assertTrue(np.all(value == target))
def test_to_matrix_1q_sparse(self):
"""Test 1-qubit to_matrix method w/ sparse=True."""
labels = ["X", "I", "Z", "Y"]
targets = [pauli_mat(i) for i in labels]
with self.assertWarns(DeprecationWarning):
values = PauliTable.from_labels(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
def test_to_matrix_2q(self):
"""Test 2-qubit to_matrix method."""
labels = ["IX", "YI", "II", "ZZ"]
targets = [pauli_mat(i) for i in labels]
with self.assertWarns(DeprecationWarning):
values = PauliTable.from_labels(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_2q_array(self):
"""Test 2-qubit to_matrix method w/ array=True."""
labels = ["ZZ", "XY", "YX", "IZ"]
target = np.array([pauli_mat(i) for i in labels])
with self.assertWarns(DeprecationWarning):
value = PauliTable.from_labels(labels).to_matrix(array=True)
self.assertTrue(isinstance(value, np.ndarray))
self.assertTrue(np.all(value == target))
def test_to_matrix_2q_sparse(self):
"""Test 2-qubit to_matrix method w/ sparse=True."""
labels = ["IX", "II", "ZY", "YZ"]
targets = [pauli_mat(i) for i in labels]
with self.assertWarns(DeprecationWarning):
values = PauliTable.from_labels(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
def test_to_matrix_5q(self):
"""Test 5-qubit to_matrix method."""
labels = ["IXIXI", "YZIXI", "IIXYZ"]
targets = [pauli_mat(i) for i in labels]
with self.assertWarns(DeprecationWarning):
values = PauliTable.from_labels(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_5q_sparse(self):
"""Test 5-qubit to_matrix method w/ sparse=True."""
labels = ["XXXYY", "IXIZY", "ZYXIX"]
targets = [pauli_mat(i) for i in labels]
with self.assertWarns(DeprecationWarning):
values = PauliTable.from_labels(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
class TestPauliTableIteration(QiskitTestCase):
"""Tests for PauliTable iterators class."""
def test_enumerate(self):
"""Test enumerate with PauliTable."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
for idx, i in enumerate(pauli):
with self.assertWarns(DeprecationWarning):
self.assertEqual(i, PauliTable(labels[idx]))
def test_iter(self):
"""Test iter with PauliTable."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
for idx, i in enumerate(iter(pauli)):
with self.assertWarns(DeprecationWarning):
self.assertEqual(i, PauliTable(labels[idx]))
def test_zip(self):
"""Test zip with PauliTable."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
for label, i in zip(labels, pauli):
with self.assertWarns(DeprecationWarning):
self.assertEqual(i, PauliTable(label))
def test_label_iter(self):
"""Test PauliTable label_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
for idx, i in enumerate(pauli.label_iter()):
self.assertEqual(i, labels[idx])
def test_matrix_iter(self):
"""Test PauliTable dense matrix_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
for idx, i in enumerate(pauli.matrix_iter()):
self.assertTrue(np.all(i == pauli_mat(labels[idx])))
def test_matrix_iter_sparse(self):
"""Test PauliTable sparse matrix_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
for idx, i in enumerate(pauli.matrix_iter(sparse=True)):
self.assertTrue(isinstance(i, csr_matrix))
self.assertTrue(np.all(i.toarray() == pauli_mat(labels[idx])))
@ddt
class TestPauliTableOperator(QiskitTestCase):
"""Tests for PauliTable base operator methods."""
@combine(j=range(1, 10))
def test_tensor(self, j):
"""Test tensor method j={j}."""
labels1 = ["XX", "YY"]
labels2 = [j * "I", j * "Z"]
with self.assertWarns(DeprecationWarning):
pauli1 = PauliTable.from_labels(labels1)
pauli2 = PauliTable.from_labels(labels2)
value = pauli1.tensor(pauli2)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels([i + j for i in labels1 for j in labels2])
self.assertEqual(value, target)
@combine(j=range(1, 10))
def test_expand(self, j):
"""Test expand method j={j}."""
labels1 = ["XX", "YY"]
labels2 = [j * "I", j * "Z"]
with self.assertWarns(DeprecationWarning):
pauli1 = PauliTable.from_labels(labels1)
pauli2 = PauliTable.from_labels(labels2)
value = pauli1.expand(pauli2)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels([j + i for j in labels2 for i in labels1])
self.assertEqual(value, target)
def test_compose_1q(self):
"""Test 1-qubit compose methods."""
# Test single qubit Pauli dot products
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["I", "X", "Y", "Z"])
with self.subTest(msg="compose single I"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["I", "X", "Y", "Z"])
value = pauli.compose("I")
self.assertEqual(target, value)
with self.subTest(msg="compose single X"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["X", "I", "Z", "Y"])
value = pauli.compose("X")
self.assertEqual(target, value)
with self.subTest(msg="compose single Y"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["Y", "Z", "I", "X"])
value = pauli.compose("Y")
self.assertEqual(target, value)
with self.subTest(msg="compose single Z"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["Z", "Y", "X", "I"])
value = pauli.compose("Z")
self.assertEqual(target, value)
def test_dot_1q(self):
"""Test 1-qubit dot method."""
# Test single qubit Pauli dot products
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["I", "X", "Y", "Z"])
with self.subTest(msg="dot single I"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["I", "X", "Y", "Z"])
value = pauli.dot("I")
self.assertEqual(target, value)
with self.subTest(msg="dot single X"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["X", "I", "Z", "Y"])
value = pauli.dot("X")
self.assertEqual(target, value)
with self.subTest(msg="dot single Y"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["Y", "Z", "I", "X"])
value = pauli.dot("Y")
self.assertEqual(target, value)
with self.subTest(msg="dot single Z"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["Z", "Y", "X", "I"])
value = pauli.dot("Z")
self.assertEqual(target, value)
def test_qargs_compose_1q(self):
"""Test 1-qubit compose method with qargs."""
with self.assertWarns(DeprecationWarning):
pauli1 = PauliTable.from_labels(["III", "XXX"])
pauli2 = PauliTable("Z")
with self.subTest(msg="compose 1-qubit qargs=[0]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IIZ", "XXY"])
value = pauli1.compose(pauli2, qargs=[0])
self.assertEqual(value, target)
with self.subTest(msg="compose 1-qubit qargs=[1]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IZI", "XYX"])
value = pauli1.compose(pauli2, qargs=[1])
self.assertEqual(value, target)
with self.subTest(msg="compose 1-qubit qargs=[2]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["ZII", "YXX"])
value = pauli1.compose(pauli2, qargs=[2])
self.assertEqual(value, target)
def test_qargs_dot_1q(self):
"""Test 1-qubit dot method with qargs."""
with self.assertWarns(DeprecationWarning):
pauli1 = PauliTable.from_labels(["III", "XXX"])
pauli2 = PauliTable("Z")
with self.subTest(msg="dot 1-qubit qargs=[0]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IIZ", "XXY"])
value = pauli1.dot(pauli2, qargs=[0])
self.assertEqual(value, target)
with self.subTest(msg="dot 1-qubit qargs=[1]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IZI", "XYX"])
value = pauli1.dot(pauli2, qargs=[1])
self.assertEqual(value, target)
with self.subTest(msg="dot 1-qubit qargs=[2]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["ZII", "YXX"])
value = pauli1.dot(pauli2, qargs=[2])
self.assertEqual(value, target)
def test_qargs_compose_2q(self):
"""Test 2-qubit compose method with qargs."""
with self.assertWarns(DeprecationWarning):
pauli1 = PauliTable.from_labels(["III", "XXX"])
pauli2 = PauliTable("ZY")
with self.subTest(msg="compose 2-qubit qargs=[0, 1]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IZY", "XYZ"])
value = pauli1.compose(pauli2, qargs=[0, 1])
self.assertEqual(value, target)
with self.subTest(msg="compose 2-qubit qargs=[1, 0]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IYZ", "XZY"])
value = pauli1.compose(pauli2, qargs=[1, 0])
self.assertEqual(value, target)
with self.subTest(msg="compose 2-qubit qargs=[0, 2]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["ZIY", "YXZ"])
value = pauli1.compose(pauli2, qargs=[0, 2])
self.assertEqual(value, target)
with self.subTest(msg="compose 2-qubit qargs=[2, 0]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["YIZ", "ZXY"])
value = pauli1.compose(pauli2, qargs=[2, 0])
self.assertEqual(value, target)
def test_qargs_dot_2q(self):
"""Test 2-qubit dot method with qargs."""
with self.assertWarns(DeprecationWarning):
pauli1 = PauliTable.from_labels(["III", "XXX"])
pauli2 = PauliTable("ZY")
with self.subTest(msg="dot 2-qubit qargs=[0, 1]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IZY", "XYZ"])
value = pauli1.dot(pauli2, qargs=[0, 1])
self.assertEqual(value, target)
with self.subTest(msg="dot 2-qubit qargs=[1, 0]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IYZ", "XZY"])
value = pauli1.dot(pauli2, qargs=[1, 0])
self.assertEqual(value, target)
with self.subTest(msg="dot 2-qubit qargs=[0, 2]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["ZIY", "YXZ"])
value = pauli1.dot(pauli2, qargs=[0, 2])
self.assertEqual(value, target)
with self.subTest(msg="dot 2-qubit qargs=[2, 0]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["YIZ", "ZXY"])
value = pauli1.dot(pauli2, qargs=[2, 0])
self.assertEqual(value, target)
def test_qargs_compose_3q(self):
"""Test 3-qubit compose method with qargs."""
with self.assertWarns(DeprecationWarning):
pauli1 = PauliTable.from_labels(["III", "XXX"])
pauli2 = PauliTable("XYZ")
with self.subTest(msg="compose 3-qubit qargs=None"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["XYZ", "IZY"])
value = pauli1.compose(pauli2)
self.assertEqual(value, target)
with self.subTest(msg="compose 3-qubit qargs=[0, 1, 2]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["XYZ", "IZY"])
value = pauli1.compose(pauli2, qargs=[0, 1, 2])
self.assertEqual(value, target)
with self.subTest(msg="compose 3-qubit qargs=[2, 1, 0]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["ZYX", "YZI"])
value = pauli1.compose(pauli2, qargs=[2, 1, 0])
self.assertEqual(value, target)
with self.subTest(msg="compose 3-qubit qargs=[1, 0, 2]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["XZY", "IYZ"])
value = pauli1.compose(pauli2, qargs=[1, 0, 2])
self.assertEqual(value, target)
def test_qargs_dot_3q(self):
"""Test 3-qubit dot method with qargs."""
with self.assertWarns(DeprecationWarning):
pauli1 = PauliTable.from_labels(["III", "XXX"])
pauli2 = PauliTable("XYZ")
with self.subTest(msg="dot 3-qubit qargs=None"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["XYZ", "IZY"])
value = pauli1.dot(pauli2, qargs=[0, 1, 2])
self.assertEqual(value, target)
with self.subTest(msg="dot 3-qubit qargs=[0, 1, 2]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["XYZ", "IZY"])
value = pauli1.dot(pauli2, qargs=[0, 1, 2])
self.assertEqual(value, target)
with self.subTest(msg="dot 3-qubit qargs=[2, 1, 0]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["ZYX", "YZI"])
value = pauli1.dot(pauli2, qargs=[2, 1, 0])
self.assertEqual(value, target)
with self.subTest(msg="dot 3-qubit qargs=[1, 0, 2]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["XZY", "IYZ"])
value = pauli1.dot(pauli2, qargs=[1, 0, 2])
self.assertEqual(value, target)
class TestPauliTableMethods(QiskitTestCase):
"""Tests for PauliTable utility methods class."""
def test_sort(self):
"""Test sort method."""
with self.subTest(msg="1 qubit standard order"):
unsrt = ["X", "Z", "I", "Y", "X", "Z"]
srt = ["I", "X", "X", "Y", "Z", "Z"]
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(srt)
value = PauliTable.from_labels(unsrt).sort()
self.assertEqual(target, value)
with self.subTest(msg="1 qubit weight order"):
unsrt = ["X", "Z", "I", "Y", "X", "Z"]
srt = ["I", "X", "X", "Y", "Z", "Z"]
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(srt)
value = PauliTable.from_labels(unsrt).sort(weight=True)
self.assertEqual(target, value)
with self.subTest(msg="2 qubit standard order"):
srt = [
"II",
"IX",
"IY",
"IY",
"XI",
"XX",
"XY",
"XZ",
"YI",
"YX",
"YY",
"YZ",
"ZI",
"ZI",
"ZX",
"ZY",
"ZZ",
"ZZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(srt)
value = PauliTable.from_labels(unsrt).sort()
self.assertEqual(target, value)
with self.subTest(msg="2 qubit weight order"):
srt = [
"II",
"IX",
"IX",
"IY",
"IZ",
"XI",
"YI",
"YI",
"ZI",
"XX",
"XX",
"XY",
"XZ",
"YX",
"YY",
"YY",
"YZ",
"ZX",
"ZX",
"ZY",
"ZZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(srt)
value = PauliTable.from_labels(unsrt).sort(weight=True)
self.assertEqual(target, value)
with self.subTest(msg="3 qubit standard order"):
srt = [
"III",
"III",
"IIX",
"IIY",
"IIZ",
"IXI",
"IXX",
"IXY",
"IXZ",
"IYI",
"IYX",
"IYY",
"IYZ",
"IZI",
"IZX",
"IZY",
"IZY",
"IZZ",
"XII",
"XII",
"XIX",
"XIY",
"XIZ",
"XXI",
"XXX",
"XXY",
"XXZ",
"XYI",
"XYX",
"XYY",
"XYZ",
"XYZ",
"XZI",
"XZX",
"XZY",
"XZZ",
"YII",
"YIX",
"YIY",
"YIZ",
"YXI",
"YXX",
"YXY",
"YXZ",
"YXZ",
"YYI",
"YYX",
"YYX",
"YYY",
"YYZ",
"YZI",
"YZX",
"YZY",
"YZZ",
"ZII",
"ZIX",
"ZIY",
"ZIZ",
"ZXI",
"ZXX",
"ZXX",
"ZXY",
"ZXZ",
"ZYI",
"ZYI",
"ZYX",
"ZYY",
"ZYZ",
"ZZI",
"ZZX",
"ZZY",
"ZZZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(srt)
value = PauliTable.from_labels(unsrt).sort()
self.assertEqual(target, value)
with self.subTest(msg="3 qubit weight order"):
srt = [
"III",
"IIX",
"IIY",
"IIZ",
"IXI",
"IYI",
"IZI",
"XII",
"YII",
"ZII",
"IXX",
"IXY",
"IXZ",
"IYX",
"IYY",
"IYZ",
"IZX",
"IZY",
"IZZ",
"XIX",
"XIY",
"XIZ",
"XXI",
"XYI",
"XZI",
"XZI",
"YIX",
"YIY",
"YIZ",
"YXI",
"YYI",
"YZI",
"YZI",
"ZIX",
"ZIY",
"ZIZ",
"ZXI",
"ZYI",
"ZZI",
"ZZI",
"XXX",
"XXY",
"XXZ",
"XYX",
"XYY",
"XYZ",
"XZX",
"XZY",
"XZZ",
"YXX",
"YXY",
"YXZ",
"YYX",
"YYY",
"YYZ",
"YZX",
"YZY",
"YZZ",
"ZXX",
"ZXY",
"ZXZ",
"ZYX",
"ZYY",
"ZYZ",
"ZZX",
"ZZY",
"ZZZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(srt)
value = PauliTable.from_labels(unsrt).sort(weight=True)
self.assertEqual(target, value)
def test_unique(self):
"""Test unique method."""
with self.subTest(msg="1 qubit"):
labels = ["X", "Z", "X", "X", "I", "Y", "I", "X", "Z", "Z", "X", "I"]
unique = ["X", "Z", "I", "Y"]
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(unique)
value = PauliTable.from_labels(labels).unique()
self.assertEqual(target, value)
with self.subTest(msg="2 qubit"):
labels = ["XX", "IX", "XX", "II", "IZ", "ZI", "YX", "YX", "ZZ", "IX", "XI"]
unique = ["XX", "IX", "II", "IZ", "ZI", "YX", "ZZ", "XI"]
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(unique)
value = PauliTable.from_labels(labels).unique()
self.assertEqual(target, value)
with self.subTest(msg="10 qubit"):
labels = [10 * "X", 10 * "I", 10 * "X"]
unique = [10 * "X", 10 * "I"]
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(unique)
value = PauliTable.from_labels(labels).unique()
self.assertEqual(target, value)
def test_delete(self):
"""Test delete method."""
with self.subTest(msg="single row"):
for j in range(1, 6):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels([j * "X", j * "Y"])
self.assertEqual(pauli.delete(0), PauliTable(j * "Y"))
self.assertEqual(pauli.delete(1), PauliTable(j * "X"))
with self.subTest(msg="multiple rows"):
for j in range(1, 6):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels([j * "X", j * "Y", j * "Z"])
self.assertEqual(pauli.delete([0, 2]), PauliTable(j * "Y"))
self.assertEqual(pauli.delete([1, 2]), PauliTable(j * "X"))
self.assertEqual(pauli.delete([0, 1]), PauliTable(j * "Z"))
with self.subTest(msg="single qubit"):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["IIX", "IYI", "ZII"])
value = pauli.delete(0, qubit=True)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["II", "IY", "ZI"])
self.assertEqual(value, target)
value = pauli.delete(1, qubit=True)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IX", "II", "ZI"])
self.assertEqual(value, target)
value = pauli.delete(2, qubit=True)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IX", "YI", "II"])
self.assertEqual(value, target)
with self.subTest(msg="multiple qubits"):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["IIX", "IYI", "ZII"])
value = pauli.delete([0, 1], qubit=True)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["I", "I", "Z"])
self.assertEqual(value, target)
value = pauli.delete([1, 2], qubit=True)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["X", "I", "I"])
self.assertEqual(value, target)
value = pauli.delete([0, 2], qubit=True)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["I", "Y", "I"])
self.assertEqual(value, target)
def test_insert(self):
"""Test insert method."""
# Insert single row
for j in range(1, 10):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable(j * "X")
target0 = PauliTable.from_labels([j * "I", j * "X"])
target1 = PauliTable.from_labels([j * "X", j * "I"])
with self.subTest(msg=f"single row from str ({j})"):
value0 = pauli.insert(0, j * "I")
self.assertEqual(value0, target0)
value1 = pauli.insert(1, j * "I")
self.assertEqual(value1, target1)
with self.subTest(msg=f"single row from PauliTable ({j})"):
with self.assertWarns(DeprecationWarning):
value0 = pauli.insert(0, PauliTable(j * "I"))
self.assertEqual(value0, target0)
with self.assertWarns(DeprecationWarning):
value1 = pauli.insert(1, PauliTable(j * "I"))
self.assertEqual(value1, target1)
with self.subTest(msg=f"single row from array ({j})"):
with self.assertWarns(DeprecationWarning):
value0 = pauli.insert(0, PauliTable(j * "I").array)
self.assertEqual(value0, target0)
with self.assertWarns(DeprecationWarning):
value1 = pauli.insert(1, PauliTable(j * "I").array)
self.assertEqual(value1, target1)
# Insert multiple rows
for j in range(1, 10):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable(j * "X")
insert = PauliTable.from_labels([j * "I", j * "Y", j * "Z"])
target0 = insert + pauli
target1 = pauli + insert
with self.subTest(msg=f"multiple-rows from PauliTable ({j})"):
value0 = pauli.insert(0, insert)
self.assertEqual(value0, target0)
value1 = pauli.insert(1, insert)
self.assertEqual(value1, target1)
with self.subTest(msg=f"multiple-rows from array ({j})"):
value0 = pauli.insert(0, insert.array)
self.assertEqual(value0, target0)
value1 = pauli.insert(1, insert.array)
self.assertEqual(value1, target1)
# Insert single column
pauli = PauliTable.from_labels(["X", "Y", "Z"])
for i in ["I", "X", "Y", "Z"]:
with self.assertWarns(DeprecationWarning):
target0 = PauliTable.from_labels(["X" + i, "Y" + i, "Z" + i])
target1 = PauliTable.from_labels([i + "X", i + "Y", i + "Z"])
with self.subTest(msg="single-column single-val from str"):
value = pauli.insert(0, i, qubit=True)
self.assertEqual(value, target0)
value = pauli.insert(1, i, qubit=True)
self.assertEqual(value, target1)
with self.subTest(msg="single-column single-val from PauliTable"):
with self.assertWarns(DeprecationWarning):
value = pauli.insert(0, PauliTable(i), qubit=True)
self.assertEqual(value, target0)
with self.assertWarns(DeprecationWarning):
value = pauli.insert(1, PauliTable(i), qubit=True)
self.assertEqual(value, target1)
with self.subTest(msg="single-column single-val from array"):
with self.assertWarns(DeprecationWarning):
value = pauli.insert(0, PauliTable(i).array, qubit=True)
self.assertEqual(value, target0)
with self.assertWarns(DeprecationWarning):
value = pauli.insert(1, PauliTable(i).array, qubit=True)
self.assertEqual(value, target1)
# Insert single column with multiple values
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["X", "Y", "Z"])
for i in [("I", "X", "Y"), ("X", "Y", "Z"), ("Y", "Z", "I")]:
with self.assertWarns(DeprecationWarning):
target0 = PauliTable.from_labels(["X" + i[0], "Y" + i[1], "Z" + i[2]])
target1 = PauliTable.from_labels([i[0] + "X", i[1] + "Y", i[2] + "Z"])
with self.subTest(msg="single-column multiple-vals from PauliTable"):
with self.assertWarns(DeprecationWarning):
value = pauli.insert(0, PauliTable.from_labels(i), qubit=True)
self.assertEqual(value, target0)
with self.assertWarns(DeprecationWarning):
value = pauli.insert(1, PauliTable.from_labels(i), qubit=True)
self.assertEqual(value, target1)
with self.subTest(msg="single-column multiple-vals from array"):
with self.assertWarns(DeprecationWarning):
value = pauli.insert(0, PauliTable.from_labels(i).array, qubit=True)
self.assertEqual(value, target0)
with self.assertWarns(DeprecationWarning):
value = pauli.insert(1, PauliTable.from_labels(i).array, qubit=True)
self.assertEqual(value, target1)
# Insert multiple columns from single
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["X", "Y", "Z"])
for j in range(1, 5):
for i in [j * "I", j * "X", j * "Y", j * "Z"]:
with self.assertWarns(DeprecationWarning):
target0 = PauliTable.from_labels(["X" + i, "Y" + i, "Z" + i])
target1 = PauliTable.from_labels([i + "X", i + "Y", i + "Z"])
with self.subTest(msg="multiple-columns single-val from str"):
value = pauli.insert(0, i, qubit=True)
self.assertEqual(value, target0)
value = pauli.insert(1, i, qubit=True)
self.assertEqual(value, target1)
with self.subTest(msg="multiple-columns single-val from PauliTable"):
with self.assertWarns(DeprecationWarning):
value = pauli.insert(0, PauliTable(i), qubit=True)
self.assertEqual(value, target0)
with self.assertWarns(DeprecationWarning):
value = pauli.insert(1, PauliTable(i), qubit=True)
self.assertEqual(value, target1)
with self.subTest(msg="multiple-columns single-val from array"):
with self.assertWarns(DeprecationWarning):
value = pauli.insert(0, PauliTable(i).array, qubit=True)
self.assertEqual(value, target0)
with self.assertWarns(DeprecationWarning):
value = pauli.insert(1, PauliTable(i).array, qubit=True)
self.assertEqual(value, target1)
# Insert multiple columns multiple row values
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["X", "Y", "Z"])
for j in range(1, 5):
for i in [
(j * "I", j * "X", j * "Y"),
(j * "X", j * "Z", j * "Y"),
(j * "Y", j * "Z", j * "I"),
]:
with self.assertWarns(DeprecationWarning):
target0 = PauliTable.from_labels(["X" + i[0], "Y" + i[1], "Z" + i[2]])
target1 = PauliTable.from_labels([i[0] + "X", i[1] + "Y", i[2] + "Z"])
with self.subTest(msg="multiple-column multiple-vals from PauliTable"):
with self.assertWarns(DeprecationWarning):
value = pauli.insert(0, PauliTable.from_labels(i), qubit=True)
self.assertEqual(value, target0)
with self.assertWarns(DeprecationWarning):
value = pauli.insert(1, PauliTable.from_labels(i), qubit=True)
self.assertEqual(value, target1)
with self.subTest(msg="multiple-column multiple-vals from array"):
with self.assertWarns(DeprecationWarning):
value = pauli.insert(0, PauliTable.from_labels(i).array, qubit=True)
self.assertEqual(value, target0)
with self.assertWarns(DeprecationWarning):
value = pauli.insert(1, PauliTable.from_labels(i).array, qubit=True)
self.assertEqual(value, target1)
def test_commutes(self):
"""Test commutes method."""
# Single qubit Pauli
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["I", "X", "Y", "Z"])
with self.subTest(msg="commutes single-Pauli I"):
value = list(pauli.commutes("I"))
target = [True, True, True, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli X"):
value = list(pauli.commutes("X"))
target = [True, True, False, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli Y"):
value = list(pauli.commutes("Y"))
target = [True, False, True, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli Z"):
value = list(pauli.commutes("Z"))
target = [True, False, False, True]
self.assertEqual(value, target)
# 2-qubit Pauli
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["II", "IX", "YI", "XY", "ZZ"])
with self.subTest(msg="commutes single-Pauli II"):
value = list(pauli.commutes("II"))
target = [True, True, True, True, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli IX"):
value = list(pauli.commutes("IX"))
target = [True, True, True, False, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli XI"):
value = list(pauli.commutes("XI"))
target = [True, True, False, True, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli YI"):
value = list(pauli.commutes("YI"))
target = [True, True, True, False, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli IY"):
value = list(pauli.commutes("IY"))
target = [True, False, True, True, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli XY"):
value = list(pauli.commutes("XY"))
target = [True, False, False, True, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli YX"):
value = list(pauli.commutes("YX"))
target = [True, True, True, True, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli ZZ"):
value = list(pauli.commutes("ZZ"))
target = [True, False, False, True, True]
self.assertEqual(value, target)
def test_commutes_with_all(self):
"""Test commutes_with_all method."""
# 1-qubit
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["I", "X", "Y", "Z"])
with self.subTest(msg="commutes_with_all [I]"):
value = list(pauli.commutes_with_all("I"))
target = [0, 1, 2, 3]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [X]"):
value = list(pauli.commutes_with_all("X"))
target = [0, 1]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [Y]"):
value = list(pauli.commutes_with_all("Y"))
target = [0, 2]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [Z]"):
value = list(pauli.commutes_with_all("Z"))
target = [0, 3]
self.assertEqual(value, target)
# 2-qubit Pauli
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["II", "IX", "YI", "XY", "ZZ"])
with self.subTest(msg="commutes_with_all [IX, YI]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["IX", "YI"])
value = list(pauli.commutes_with_all(other))
target = [0, 1, 2]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [XY, ZZ]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["XY", "ZZ"])
value = list(pauli.commutes_with_all(other))
target = [0, 3, 4]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [YX, ZZ]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["YX", "ZZ"])
value = list(pauli.commutes_with_all(other))
target = [0, 3, 4]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [XY, YX]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["XY", "YX"])
value = list(pauli.commutes_with_all(other))
target = [0, 3, 4]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [XY, IX]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["XY", "IX"])
value = list(pauli.commutes_with_all(other))
target = [0]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [YX, IX]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["YX", "IX"])
value = list(pauli.commutes_with_all(other))
target = [0, 1, 2]
self.assertEqual(value, target)
def test_anticommutes_with_all(self):
"""Test anticommutes_with_all method."""
# 1-qubit
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["I", "X", "Y", "Z"])
with self.subTest(msg="anticommutes_with_all [I]"):
value = list(pauli.anticommutes_with_all("I"))
target = []
self.assertEqual(value, target)
with self.subTest(msg="antianticommutes_with_all [X]"):
value = list(pauli.anticommutes_with_all("X"))
target = [2, 3]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [Y]"):
value = list(pauli.anticommutes_with_all("Y"))
target = [1, 3]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [Z]"):
value = list(pauli.anticommutes_with_all("Z"))
target = [1, 2]
self.assertEqual(value, target)
# 2-qubit Pauli
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["II", "IX", "YI", "XY", "ZZ"])
with self.subTest(msg="anticommutes_with_all [IX, YI]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["IX", "YI"])
value = list(pauli.anticommutes_with_all(other))
target = [3, 4]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [XY, ZZ]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["XY", "ZZ"])
value = list(pauli.anticommutes_with_all(other))
target = [1, 2]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [YX, ZZ]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["YX", "ZZ"])
value = list(pauli.anticommutes_with_all(other))
target = []
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [XY, YX]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["XY", "YX"])
value = list(pauli.anticommutes_with_all(other))
target = []
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [XY, IX]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["XY", "IX"])
value = list(pauli.anticommutes_with_all(other))
target = []
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [YX, IX]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["YX", "IX"])
value = list(pauli.anticommutes_with_all(other))
target = []
self.assertEqual(value, target)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for SparsePauliOp class."""
import itertools as it
import unittest
from test import combine
import numpy as np
from ddt import ddt
from qiskit import QiskitError
from qiskit.circuit import ParameterExpression, Parameter, ParameterVector
from qiskit.circuit.parametertable import ParameterView
from qiskit.quantum_info.operators import Operator, Pauli, PauliList, PauliTable, SparsePauliOp
from qiskit.test import QiskitTestCase
def pauli_mat(label):
"""Return Pauli matrix from a Pauli label"""
mat = np.eye(1, dtype=complex)
for i in label:
if i == "I":
mat = np.kron(mat, np.eye(2, dtype=complex))
elif i == "X":
mat = np.kron(mat, np.array([[0, 1], [1, 0]], dtype=complex))
elif i == "Y":
mat = np.kron(mat, np.array([[0, -1j], [1j, 0]], dtype=complex))
elif i == "Z":
mat = np.kron(mat, np.array([[1, 0], [0, -1]], dtype=complex))
else:
raise QiskitError(f"Invalid Pauli string {i}")
return mat
class TestSparsePauliOpInit(QiskitTestCase):
"""Tests for SparsePauliOp initialization."""
def test_pauli_table_init(self):
"""Test PauliTable initialization."""
labels = ["I", "X", "Y", "Z"]
table = PauliTable.from_labels(labels)
paulis = PauliList(labels)
with self.subTest(msg="no coeffs"):
spp_op = SparsePauliOp(table)
np.testing.assert_array_equal(spp_op.coeffs, np.ones(len(labels)))
self.assertEqual(spp_op.paulis, paulis)
with self.subTest(msg="no coeffs"):
coeffs = [1, 2, 3, 4]
spp_op = SparsePauliOp(table, coeffs)
np.testing.assert_array_equal(spp_op.coeffs, coeffs)
self.assertEqual(spp_op.paulis, paulis)
def test_str_init(self):
"""Test str initialization."""
for label in ["IZ", "XI", "YX", "ZZ"]:
pauli_list = PauliList(label)
spp_op = SparsePauliOp(label)
self.assertEqual(spp_op.paulis, pauli_list)
np.testing.assert_array_equal(spp_op.coeffs, [1])
def test_pauli_list_init(self):
"""Test PauliList initialization."""
labels = ["I", "X", "Y", "-Z", "iZ", "-iX"]
paulis = PauliList(labels)
with self.subTest(msg="no coeffs"):
spp_op = SparsePauliOp(paulis)
np.testing.assert_array_equal(spp_op.coeffs, [1, 1, 1, -1, 1j, -1j])
paulis.phase = 0
self.assertEqual(spp_op.paulis, paulis)
paulis = PauliList(labels)
with self.subTest(msg="with coeffs"):
coeffs = [1, 2, 3, 4, 5, 6]
spp_op = SparsePauliOp(paulis, coeffs)
np.testing.assert_array_equal(spp_op.coeffs, [1, 2, 3, -4, 5j, -6j])
paulis.phase = 0
self.assertEqual(spp_op.paulis, paulis)
paulis = PauliList(labels)
with self.subTest(msg="with Parameterized coeffs"):
params = ParameterVector("params", 6)
coeffs = np.array(params)
spp_op = SparsePauliOp(paulis, coeffs)
target = coeffs.copy()
target[3] *= -1
target[4] *= 1j
target[5] *= -1j
np.testing.assert_array_equal(spp_op.coeffs, target)
paulis.phase = 0
self.assertEqual(spp_op.paulis, paulis)
def test_sparse_pauli_op_init(self):
"""Test SparsePauliOp initialization."""
labels = ["I", "X", "Y", "-Z", "iZ", "-iX"]
with self.subTest(msg="make SparsePauliOp from SparsePauliOp"):
op = SparsePauliOp(labels)
ref_op = op.copy()
spp_op = SparsePauliOp(op)
self.assertEqual(spp_op, ref_op)
np.testing.assert_array_equal(ref_op.paulis.phase, np.zeros(ref_op.size))
np.testing.assert_array_equal(spp_op.paulis.phase, np.zeros(spp_op.size))
# make sure the changes of `op` do not propagate through to `spp_op`
op.paulis.z[:] = False
op.coeffs *= 2
self.assertNotEqual(spp_op, op)
self.assertEqual(spp_op, ref_op)
with self.subTest(msg="make SparsePauliOp from SparsePauliOp and ndarray"):
op = SparsePauliOp(labels)
coeffs = np.array([1, 2, 3, 4, 5, 6])
spp_op = SparsePauliOp(op, coeffs)
ref_op = SparsePauliOp(op.paulis.copy(), coeffs.copy())
self.assertEqual(spp_op, ref_op)
np.testing.assert_array_equal(ref_op.paulis.phase, np.zeros(ref_op.size))
np.testing.assert_array_equal(spp_op.paulis.phase, np.zeros(spp_op.size))
# make sure the changes of `op` and `coeffs` do not propagate through to `spp_op`
op.paulis.z[:] = False
coeffs *= 2
self.assertNotEqual(spp_op, op)
self.assertEqual(spp_op, ref_op)
with self.subTest(msg="make SparsePauliOp from PauliList"):
paulis = PauliList(labels)
spp_op = SparsePauliOp(paulis)
ref_op = SparsePauliOp(labels)
self.assertEqual(spp_op, ref_op)
np.testing.assert_array_equal(ref_op.paulis.phase, np.zeros(ref_op.size))
np.testing.assert_array_equal(spp_op.paulis.phase, np.zeros(spp_op.size))
# make sure the change of `paulis` does not propagate through to `spp_op`
paulis.z[:] = False
self.assertEqual(spp_op, ref_op)
with self.subTest(msg="make SparsePauliOp from PauliList and ndarray"):
paulis = PauliList(labels)
coeffs = np.array([1, 2, 3, 4, 5, 6])
spp_op = SparsePauliOp(paulis, coeffs)
ref_op = SparsePauliOp(labels, coeffs.copy())
self.assertEqual(spp_op, ref_op)
np.testing.assert_array_equal(ref_op.paulis.phase, np.zeros(ref_op.size))
np.testing.assert_array_equal(spp_op.paulis.phase, np.zeros(spp_op.size))
# make sure the changes of `paulis` and `coeffs` do not propagate through to `spp_op`
paulis.z[:] = False
coeffs[:] = 0
self.assertEqual(spp_op, ref_op)
class TestSparsePauliOpConversions(QiskitTestCase):
"""Tests SparsePauliOp representation conversions."""
def test_from_operator(self):
"""Test from_operator methods."""
for tup in it.product(["I", "X", "Y", "Z"], repeat=2):
label = "".join(tup)
with self.subTest(msg=label):
spp_op = SparsePauliOp.from_operator(Operator(pauli_mat(label)))
np.testing.assert_array_equal(spp_op.coeffs, [1])
self.assertEqual(spp_op.paulis, PauliList(label))
def test_from_list(self):
"""Test from_list method."""
labels = ["XXZ", "IXI", "YZZ", "III"]
coeffs = [3.0, 5.5, -1j, 23.3333]
spp_op = SparsePauliOp.from_list(zip(labels, coeffs))
np.testing.assert_array_equal(spp_op.coeffs, coeffs)
self.assertEqual(spp_op.paulis, PauliList(labels))
def test_from_list_parameters(self):
"""Test from_list method with parameters."""
labels = ["XXZ", "IXI", "YZZ", "III"]
coeffs = ParameterVector("a", 4)
spp_op = SparsePauliOp.from_list(zip(labels, coeffs), dtype=object)
np.testing.assert_array_equal(spp_op.coeffs, coeffs)
self.assertEqual(spp_op.paulis, PauliList(labels))
def test_from_index_list(self):
"""Test from_list method specifying the Paulis via indices."""
expected_labels = ["XXZ", "IXI", "YIZ", "III"]
paulis = ["XXZ", "X", "YZ", ""]
indices = [[2, 1, 0], [1], [2, 0], []]
coeffs = [3.0, 5.5, -1j, 23.3333]
spp_op = SparsePauliOp.from_sparse_list(zip(paulis, indices, coeffs), num_qubits=3)
np.testing.assert_array_equal(spp_op.coeffs, coeffs)
self.assertEqual(spp_op.paulis, PauliList(expected_labels))
def test_from_index_list_parameters(self):
"""Test from_list method specifying the Paulis via indices with paramteres."""
expected_labels = ["XXZ", "IXI", "YIZ", "III"]
paulis = ["XXZ", "X", "YZ", ""]
indices = [[2, 1, 0], [1], [2, 0], []]
coeffs = ParameterVector("a", 4)
spp_op = SparsePauliOp.from_sparse_list(
zip(paulis, indices, coeffs), num_qubits=3, dtype=object
)
np.testing.assert_array_equal(spp_op.coeffs, coeffs)
self.assertEqual(spp_op.paulis, PauliList(expected_labels))
def test_from_index_list_endianness(self):
"""Test the construction from index list has the right endianness."""
spp_op = SparsePauliOp.from_sparse_list([("ZX", [1, 4], 1)], num_qubits=5)
expected = Pauli("XIIZI")
self.assertEqual(spp_op.paulis[0], expected)
def test_from_index_list_raises(self):
"""Test from_list via Pauli + indices raises correctly, if number of qubits invalid."""
with self.assertRaises(QiskitError):
_ = SparsePauliOp.from_sparse_list([("Z", [2], 1)], 1)
def test_from_index_list_same_index(self):
"""Test from_list via Pauli + number of qubits raises correctly, if indices duplicate."""
with self.assertRaises(QiskitError):
_ = SparsePauliOp.from_sparse_list([("ZZ", [0, 0], 1)], 2)
with self.assertRaises(QiskitError):
_ = SparsePauliOp.from_sparse_list([("ZI", [0, 0], 1)], 2)
with self.assertRaises(QiskitError):
_ = SparsePauliOp.from_sparse_list([("IZ", [0, 0], 1)], 2)
def test_from_zip(self):
"""Test from_list method for zipped input."""
labels = ["XXZ", "IXI", "YZZ", "III"]
coeffs = [3.0, 5.5, -1j, 23.3333]
spp_op = SparsePauliOp.from_list(zip(labels, coeffs))
np.testing.assert_array_equal(spp_op.coeffs, coeffs)
self.assertEqual(spp_op.paulis, PauliList(labels))
def test_to_matrix(self):
"""Test to_matrix method."""
labels = ["XI", "YZ", "YY", "ZZ"]
coeffs = [-3, 4.4j, 0.2 - 0.1j, 66.12]
spp_op = SparsePauliOp(labels, coeffs)
target = np.zeros((4, 4), dtype=complex)
for coeff, label in zip(coeffs, labels):
target += coeff * pauli_mat(label)
np.testing.assert_array_equal(spp_op.to_matrix(), target)
np.testing.assert_array_equal(spp_op.to_matrix(sparse=True).toarray(), target)
def test_to_matrix_large(self):
"""Test to_matrix method with a large number of qubits."""
reps = 5
labels = ["XI" * reps, "YZ" * reps, "YY" * reps, "ZZ" * reps]
coeffs = [-3, 4.4j, 0.2 - 0.1j, 66.12]
spp_op = SparsePauliOp(labels, coeffs)
size = 1 << 2 * reps
target = np.zeros((size, size), dtype=complex)
for coeff, label in zip(coeffs, labels):
target += coeff * pauli_mat(label)
np.testing.assert_array_equal(spp_op.to_matrix(), target)
np.testing.assert_array_equal(spp_op.to_matrix(sparse=True).toarray(), target)
def test_to_matrix_parameters(self):
"""Test to_matrix method for parameterized SparsePauliOp."""
labels = ["XI", "YZ", "YY", "ZZ"]
coeffs = np.array(ParameterVector("a", 4))
spp_op = SparsePauliOp(labels, coeffs)
target = np.zeros((4, 4), dtype=object)
for coeff, label in zip(coeffs, labels):
target += coeff * pauli_mat(label)
np.testing.assert_array_equal(spp_op.to_matrix(), target)
def test_to_operator(self):
"""Test to_operator method."""
labels = ["XI", "YZ", "YY", "ZZ"]
coeffs = [-3, 4.4j, 0.2 - 0.1j, 66.12]
spp_op = SparsePauliOp(labels, coeffs)
target = Operator(np.zeros((4, 4), dtype=complex))
for coeff, label in zip(coeffs, labels):
target = target + Operator(coeff * pauli_mat(label))
self.assertEqual(spp_op.to_operator(), target)
def test_to_list(self):
"""Test to_operator method."""
labels = ["XI", "YZ", "YY", "ZZ"]
coeffs = [-3, 4.4j, 0.2 - 0.1j, 66.12]
op = SparsePauliOp(labels, coeffs)
target = list(zip(labels, coeffs))
self.assertEqual(op.to_list(), target)
def test_to_list_parameters(self):
"""Test to_operator method with paramters."""
labels = ["XI", "YZ", "YY", "ZZ"]
coeffs = np.array(ParameterVector("a", 4))
op = SparsePauliOp(labels, coeffs)
target = list(zip(labels, coeffs))
self.assertEqual(op.to_list(), target)
class TestSparsePauliOpIteration(QiskitTestCase):
"""Tests for SparsePauliOp iterators class."""
def test_enumerate(self):
"""Test enumerate with SparsePauliOp."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
coeffs = np.array([1, 2, 3, 4, 5, 6])
op = SparsePauliOp(labels, coeffs)
for idx, i in enumerate(op):
self.assertEqual(i, SparsePauliOp(labels[idx], coeffs[[idx]]))
def test_enumerate_parameters(self):
"""Test enumerate with SparsePauliOp with parameters."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
coeffs = np.array(ParameterVector("a", 6))
op = SparsePauliOp(labels, coeffs)
for idx, i in enumerate(op):
self.assertEqual(i, SparsePauliOp(labels[idx], coeffs[[idx]]))
def test_iter(self):
"""Test iter with SparsePauliOp."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
coeffs = np.array([1, 2, 3, 4, 5, 6])
op = SparsePauliOp(labels, coeffs)
for idx, i in enumerate(iter(op)):
self.assertEqual(i, SparsePauliOp(labels[idx], coeffs[[idx]]))
def test_iter_parameters(self):
"""Test iter with SparsePauliOp with parameters."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
coeffs = np.array(ParameterVector("a", 6))
op = SparsePauliOp(labels, coeffs)
for idx, i in enumerate(iter(op)):
self.assertEqual(i, SparsePauliOp(labels[idx], coeffs[[idx]]))
def test_label_iter(self):
"""Test SparsePauliOp label_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
coeffs = np.array([1, 2, 3, 4, 5, 6])
op = SparsePauliOp(labels, coeffs)
for idx, i in enumerate(op.label_iter()):
self.assertEqual(i, (labels[idx], coeffs[idx]))
def test_label_iter_parameters(self):
"""Test SparsePauliOp label_iter method with parameters."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
coeffs = np.array(ParameterVector("a", 6))
op = SparsePauliOp(labels, coeffs)
for idx, i in enumerate(op.label_iter()):
self.assertEqual(i, (labels[idx], coeffs[idx]))
def test_matrix_iter(self):
"""Test SparsePauliOp dense matrix_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
coeffs = np.array([1, 2, 3, 4, 5, 6])
op = SparsePauliOp(labels, coeffs)
for idx, i in enumerate(op.matrix_iter()):
np.testing.assert_array_equal(i, coeffs[idx] * pauli_mat(labels[idx]))
def test_matrix_iter_parameters(self):
"""Test SparsePauliOp dense matrix_iter method. with parameters"""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
coeffs = np.array(ParameterVector("a", 6))
op = SparsePauliOp(labels, coeffs)
for idx, i in enumerate(op.matrix_iter()):
np.testing.assert_array_equal(i, coeffs[idx] * pauli_mat(labels[idx]))
def test_matrix_iter_sparse(self):
"""Test SparsePauliOp sparse matrix_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
coeffs = np.array([1, 2, 3, 4, 5, 6])
op = SparsePauliOp(labels, coeffs)
for idx, i in enumerate(op.matrix_iter(sparse=True)):
np.testing.assert_array_equal(i.toarray(), coeffs[idx] * pauli_mat(labels[idx]))
def bind_parameters_to_one(array):
"""Bind parameters to one. The purpose of using this method is to bind some value and
use ``assert_allclose``, since it is impossible to verify equivalence in the case of
numerical errors with parameters existing.
"""
def bind_one(a):
parameters = a.parameters
return complex(a.bind(dict(zip(parameters, [1] * len(parameters)))))
return np.vectorize(bind_one, otypes=[complex])(array)
@ddt
class TestSparsePauliOpMethods(QiskitTestCase):
"""Tests for SparsePauliOp operator methods."""
RNG = np.random.default_rng(1994)
def setUp(self):
super().setUp()
self.parameter_names = (f"param_{x}" for x in it.count())
def random_spp_op(self, num_qubits, num_terms, use_parameters=False):
"""Generate a pseudo-random SparsePauliOp"""
if use_parameters:
coeffs = np.array(ParameterVector(next(self.parameter_names), num_terms))
else:
coeffs = self.RNG.uniform(-1, 1, size=num_terms) + 1j * self.RNG.uniform(
-1, 1, size=num_terms
)
labels = [
"".join(self.RNG.choice(["I", "X", "Y", "Z"], size=num_qubits))
for _ in range(num_terms)
]
return SparsePauliOp(labels, coeffs)
@combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False])
def test_conjugate(self, num_qubits, use_parameters):
"""Test conjugate method for {num_qubits}-qubits."""
spp_op = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
target = spp_op.to_matrix().conjugate()
op = spp_op.conjugate()
value = op.to_matrix()
np.testing.assert_array_equal(value, target)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False])
def test_transpose(self, num_qubits, use_parameters):
"""Test transpose method for {num_qubits}-qubits."""
spp_op = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
target = spp_op.to_matrix().transpose()
op = spp_op.transpose()
value = op.to_matrix()
np.testing.assert_array_equal(value, target)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False])
def test_adjoint(self, num_qubits, use_parameters):
"""Test adjoint method for {num_qubits}-qubits."""
spp_op = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
target = spp_op.to_matrix().transpose().conjugate()
op = spp_op.adjoint()
value = op.to_matrix()
np.testing.assert_array_equal(value, target)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False])
def test_compose(self, num_qubits, use_parameters):
"""Test {num_qubits}-qubit compose methods."""
spp_op1 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
target = spp_op2.to_matrix() @ spp_op1.to_matrix()
op = spp_op1.compose(spp_op2)
value = op.to_matrix()
if use_parameters:
value = bind_parameters_to_one(value)
target = bind_parameters_to_one(target)
np.testing.assert_allclose(value, target, atol=1e-8)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
op = spp_op1 & spp_op2
value = op.to_matrix()
if use_parameters:
value = bind_parameters_to_one(value)
np.testing.assert_allclose(value, target, atol=1e-8)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False])
def test_dot(self, num_qubits, use_parameters):
"""Test {num_qubits}-qubit dot methods."""
spp_op1 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
target = spp_op1.to_matrix() @ spp_op2.to_matrix()
op = spp_op1.dot(spp_op2)
value = op.to_matrix()
if use_parameters:
value = bind_parameters_to_one(value)
target = bind_parameters_to_one(target)
np.testing.assert_allclose(value, target, atol=1e-8)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
op = spp_op1 @ spp_op2
value = op.to_matrix()
if use_parameters:
value = bind_parameters_to_one(value)
np.testing.assert_allclose(value, target, atol=1e-8)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits=[1, 2, 3])
def test_qargs_compose(self, num_qubits):
"""Test 3-qubit compose method with {num_qubits}-qubit qargs."""
spp_op1 = self.random_spp_op(3, 2**3)
spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits)
qargs = self.RNG.choice(3, size=num_qubits, replace=False).tolist()
target = Operator(spp_op1).compose(Operator(spp_op2), qargs=qargs)
op = spp_op1.compose(spp_op2, qargs=qargs)
value = op.to_operator()
self.assertEqual(value, target)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
op = spp_op1 & spp_op2(qargs)
value = op.to_operator()
self.assertEqual(value, target)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits=[1, 2, 3])
def test_qargs_dot(self, num_qubits):
"""Test 3-qubit dot method with {num_qubits}-qubit qargs."""
spp_op1 = self.random_spp_op(3, 2**3)
spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits)
qargs = self.RNG.choice(3, size=num_qubits, replace=False).tolist()
target = Operator(spp_op1).dot(Operator(spp_op2), qargs=qargs)
op = spp_op1.dot(spp_op2, qargs=qargs)
value = op.to_operator()
self.assertEqual(value, target)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits1=[1, 2, 3], num_qubits2=[1, 2, 3], use_parameters=[True, False])
def test_tensor(self, num_qubits1, num_qubits2, use_parameters):
"""Test tensor method for {num_qubits1} and {num_qubits2} qubits."""
spp_op1 = self.random_spp_op(num_qubits1, 2**num_qubits1, use_parameters)
spp_op2 = self.random_spp_op(num_qubits2, 2**num_qubits2, use_parameters)
target = np.kron(spp_op1.to_matrix(), spp_op2.to_matrix())
op = spp_op1.tensor(spp_op2)
value = op.to_matrix()
if use_parameters:
value = bind_parameters_to_one(value)
target = bind_parameters_to_one(target)
np.testing.assert_allclose(value, target, atol=1e-8)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits1=[1, 2, 3], num_qubits2=[1, 2, 3], use_parameters=[True, False])
def test_expand(self, num_qubits1, num_qubits2, use_parameters):
"""Test expand method for {num_qubits1} and {num_qubits2} qubits."""
spp_op1 = self.random_spp_op(num_qubits1, 2**num_qubits1, use_parameters)
spp_op2 = self.random_spp_op(num_qubits2, 2**num_qubits2, use_parameters)
target = np.kron(spp_op2.to_matrix(), spp_op1.to_matrix())
op = spp_op1.expand(spp_op2)
value = op.to_matrix()
if use_parameters:
value = bind_parameters_to_one(value)
target = bind_parameters_to_one(target)
np.testing.assert_allclose(value, target, atol=1e-8)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False])
def test_add(self, num_qubits, use_parameters):
"""Test + method for {num_qubits} qubits."""
spp_op1 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
target = spp_op1.to_matrix() + spp_op2.to_matrix()
op = spp_op1 + spp_op2
value = op.to_matrix()
if use_parameters:
value = bind_parameters_to_one(value)
target = bind_parameters_to_one(target)
np.testing.assert_allclose(value, target, atol=1e-8)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False])
def test_sub(self, num_qubits, use_parameters):
"""Test + method for {num_qubits} qubits."""
spp_op1 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
target = spp_op1.to_matrix() - spp_op2.to_matrix()
op = spp_op1 - spp_op2
value = op.to_matrix()
if use_parameters:
value = bind_parameters_to_one(value)
target = bind_parameters_to_one(target)
np.testing.assert_allclose(value, target, atol=1e-8)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits=[1, 2, 3])
def test_add_qargs(self, num_qubits):
"""Test + method for 3 qubits with {num_qubits} qubit qargs."""
spp_op1 = self.random_spp_op(3, 2**3)
spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits)
qargs = self.RNG.choice(3, size=num_qubits, replace=False).tolist()
target = Operator(spp_op1) + Operator(spp_op2)(qargs)
op = spp_op1 + spp_op2(qargs)
value = op.to_operator()
self.assertEqual(value, target)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits=[1, 2, 3])
def test_sub_qargs(self, num_qubits):
"""Test - method for 3 qubits with {num_qubits} qubit qargs."""
spp_op1 = self.random_spp_op(3, 2**3)
spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits)
qargs = self.RNG.choice(3, size=num_qubits, replace=False).tolist()
target = Operator(spp_op1) - Operator(spp_op2)(qargs)
op = spp_op1 - spp_op2(qargs)
value = op.to_operator()
self.assertEqual(value, target)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(
num_qubits=[1, 2, 3],
value=[
0,
1,
1j,
-3 + 4.4j,
np.int64(2),
Parameter("x"),
0 * Parameter("x"),
(-2 + 1.7j) * Parameter("x"),
],
param=[None, "a"],
)
def test_mul(self, num_qubits, value, param):
"""Test * method for {num_qubits} qubits and value {value}."""
spp_op = self.random_spp_op(num_qubits, 2**num_qubits, param)
target = value * spp_op.to_matrix()
op = value * spp_op
value_mat = op.to_matrix()
has_parameters = isinstance(value, ParameterExpression) or param is not None
if value != 0 and has_parameters:
value_mat = bind_parameters_to_one(value_mat)
target = bind_parameters_to_one(target)
if value == 0:
np.testing.assert_array_equal(value_mat, target.astype(complex))
else:
np.testing.assert_allclose(value_mat, target, atol=1e-8)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
target = spp_op.to_matrix() * value
op = spp_op * value
value_mat = op.to_matrix()
if value != 0 and has_parameters:
value_mat = bind_parameters_to_one(value_mat)
target = bind_parameters_to_one(target)
if value == 0:
np.testing.assert_array_equal(value_mat, target.astype(complex))
else:
np.testing.assert_allclose(value_mat, target, atol=1e-8)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
@combine(num_qubits=[1, 2, 3], value=[1, 1j, -3 + 4.4j], param=[None, "a"])
def test_div(self, num_qubits, value, param):
"""Test / method for {num_qubits} qubits and value {value}."""
spp_op = self.random_spp_op(num_qubits, 2**num_qubits, param)
target = spp_op.to_matrix() / value
op = spp_op / value
value_mat = op.to_matrix()
if param is not None:
value_mat = bind_parameters_to_one(value_mat)
target = bind_parameters_to_one(target)
np.testing.assert_allclose(value_mat, target, atol=1e-8)
np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size))
def test_simplify(self):
"""Test simplify method"""
coeffs = [3 + 1j, -3 - 1j, 0, 4, -5, 2.2, -1.1j]
labels = ["IXI", "IXI", "ZZZ", "III", "III", "XXX", "XXX"]
spp_op = SparsePauliOp.from_list(zip(labels, coeffs))
simplified_op = spp_op.simplify()
target_coeffs = [-1, 2.2 - 1.1j]
target_labels = ["III", "XXX"]
target_op = SparsePauliOp.from_list(zip(target_labels, target_coeffs))
self.assertEqual(simplified_op, target_op)
np.testing.assert_array_equal(simplified_op.paulis.phase, np.zeros(simplified_op.size))
@combine(num_qubits=[1, 2, 3, 4], num_adds=[0, 1, 2, 3])
def test_simplify2(self, num_qubits, num_adds):
"""Test simplify method for {num_qubits} qubits with {num_adds} `add` calls."""
spp_op = self.random_spp_op(num_qubits, 2**num_qubits)
for _ in range(num_adds):
spp_op += spp_op
simplified_op = spp_op.simplify()
value = Operator(simplified_op)
target = Operator(spp_op)
self.assertEqual(value, target)
np.testing.assert_array_equal(spp_op.paulis.phase, np.zeros(spp_op.size))
np.testing.assert_array_equal(simplified_op.paulis.phase, np.zeros(simplified_op.size))
@combine(num_qubits=[1, 2, 3, 4])
def test_simplify_zero(self, num_qubits):
"""Test simplify method for {num_qubits} qubits with zero operators."""
spp_op = self.random_spp_op(num_qubits, 2**num_qubits)
zero_op = spp_op - spp_op
simplified_op = zero_op.simplify()
value = Operator(simplified_op)
target = Operator(zero_op)
self.assertEqual(value, target)
np.testing.assert_array_equal(simplified_op.coeffs, [0])
np.testing.assert_array_equal(zero_op.paulis.phase, np.zeros(zero_op.size))
np.testing.assert_array_equal(simplified_op.paulis.phase, np.zeros(simplified_op.size))
def test_simplify_parameters(self):
"""Test simplify methods for parameterized SparsePauliOp."""
a = Parameter("a")
coeffs = np.array([a, -a, 0, a, a, a, 2 * a])
labels = ["IXI", "IXI", "ZZZ", "III", "III", "XXX", "XXX"]
spp_op = SparsePauliOp(labels, coeffs)
simplified_op = spp_op.simplify()
target_coeffs = np.array([2 * a, 3 * a])
target_labels = ["III", "XXX"]
target_op = SparsePauliOp(target_labels, target_coeffs)
self.assertEqual(simplified_op, target_op)
np.testing.assert_array_equal(simplified_op.paulis.phase, np.zeros(simplified_op.size))
def test_sort(self):
"""Test sort method."""
with self.assertRaises(QiskitError):
target = SparsePauliOp([], [])
with self.subTest(msg="1 qubit real number"):
target = SparsePauliOp(
["I", "I", "I", "I"], [-3.0 + 0.0j, 1.0 + 0.0j, 2.0 + 0.0j, 4.0 + 0.0j]
)
value = SparsePauliOp(["I", "I", "I", "I"], [1, 2, -3, 4]).sort()
self.assertEqual(target, value)
with self.subTest(msg="1 qubit complex"):
target = SparsePauliOp(
["I", "I", "I", "I"], [-1.0 + 0.0j, 0.0 - 1.0j, 0.0 + 1.0j, 1.0 + 0.0j]
)
value = SparsePauliOp(
["I", "I", "I", "I"], [1.0 + 0.0j, 0.0 + 1.0j, 0.0 - 1.0j, -1.0 + 0.0j]
).sort()
self.assertEqual(target, value)
with self.subTest(msg="1 qubit Pauli I, X, Y, Z"):
target = SparsePauliOp(
["I", "X", "Y", "Z"], [-1.0 + 2.0j, 1.0 + 0.0j, 2.0 + 0.0j, 3.0 - 4.0j]
)
value = SparsePauliOp(
["Y", "X", "Z", "I"], [2.0 + 0.0j, 1.0 + 0.0j, 3.0 - 4.0j, -1.0 + 2.0j]
).sort()
self.assertEqual(target, value)
with self.subTest(msg="1 qubit weight order"):
target = SparsePauliOp(
["I", "X", "Y", "Z"], [-1.0 + 2.0j, 1.0 + 0.0j, 2.0 + 0.0j, 3.0 - 4.0j]
)
value = SparsePauliOp(
["Y", "X", "Z", "I"], [2.0 + 0.0j, 1.0 + 0.0j, 3.0 - 4.0j, -1.0 + 2.0j]
).sort(weight=True)
self.assertEqual(target, value)
with self.subTest(msg="1 qubit multi Pauli"):
target = SparsePauliOp(
["I", "I", "I", "I", "X", "X", "Y", "Z"],
[
-1.0 + 2.0j,
1.0 + 0.0j,
2.0 + 0.0j,
3.0 - 4.0j,
-1.0 + 4.0j,
-1.0 + 5.0j,
-1.0 + 3.0j,
-1.0 + 2.0j,
],
)
value = SparsePauliOp(
["I", "I", "I", "I", "X", "Z", "Y", "X"],
[
2.0 + 0.0j,
1.0 + 0.0j,
3.0 - 4.0j,
-1.0 + 2.0j,
-1.0 + 5.0j,
-1.0 + 2.0j,
-1.0 + 3.0j,
-1.0 + 4.0j,
],
).sort()
self.assertEqual(target, value)
with self.subTest(msg="2 qubit standard order"):
target = SparsePauliOp(
["II", "XI", "XX", "XX", "XX", "XY", "XZ", "YI"],
[
4.0 + 0.0j,
7.0 + 0.0j,
2.0 + 1.0j,
2.0 + 2.0j,
3.0 + 0.0j,
6.0 + 0.0j,
5.0 + 0.0j,
3.0 + 0.0j,
],
)
value = SparsePauliOp(
["XX", "XX", "XX", "YI", "II", "XZ", "XY", "XI"],
[
2.0 + 1.0j,
2.0 + 2.0j,
3.0 + 0.0j,
3.0 + 0.0j,
4.0 + 0.0j,
5.0 + 0.0j,
6.0 + 0.0j,
7.0 + 0.0j,
],
).sort()
self.assertEqual(target, value)
with self.subTest(msg="2 qubit weight order"):
target = SparsePauliOp(
["II", "XI", "YI", "XX", "XX", "XX", "XY", "XZ"],
[
4.0 + 0.0j,
7.0 + 0.0j,
3.0 + 0.0j,
2.0 + 1.0j,
2.0 + 2.0j,
3.0 + 0.0j,
6.0 + 0.0j,
5.0 + 0.0j,
],
)
value = SparsePauliOp(
["XX", "XX", "XX", "YI", "II", "XZ", "XY", "XI"],
[
2.0 + 1.0j,
2.0 + 2.0j,
3.0 + 0.0j,
3.0 + 0.0j,
4.0 + 0.0j,
5.0 + 0.0j,
6.0 + 0.0j,
7.0 + 0.0j,
],
).sort(weight=True)
self.assertEqual(target, value)
def test_chop(self):
"""Test chop, which individually truncates real and imaginary parts of the coeffs."""
eps = 1e-10
op = SparsePauliOp(
["XYZ", "ZII", "ZII", "YZY"], coeffs=[eps + 1j * eps, 1 + 1j * eps, eps + 1j, 1 + 1j]
)
simplified = op.chop(tol=eps)
expected_coeffs = [1, 1j, 1 + 1j]
expected_paulis = ["ZII", "ZII", "YZY"]
self.assertListEqual(simplified.coeffs.tolist(), expected_coeffs)
self.assertListEqual(simplified.paulis.to_labels(), expected_paulis)
def test_chop_all(self):
"""Test that chop returns an identity operator with coeff 0 if all coeffs are chopped."""
eps = 1e-10
op = SparsePauliOp(["X", "Z"], coeffs=[eps, eps])
simplified = op.chop(tol=eps)
expected = SparsePauliOp(["I"], coeffs=[0.0])
self.assertEqual(simplified, expected)
@combine(num_qubits=[1, 2, 3, 4], num_ops=[1, 2, 3, 4], param=[None, "a"])
def test_sum(self, num_qubits, num_ops, param):
"""Test sum method for {num_qubits} qubits with {num_ops} operators."""
ops = [
self.random_spp_op(
num_qubits, 2**num_qubits, param if param is None else f"{param}_{i}"
)
for i in range(num_ops)
]
sum_op = SparsePauliOp.sum(ops)
value = sum_op.to_matrix()
target_operator = sum((op.to_matrix() for op in ops[1:]), ops[0].to_matrix())
if param is not None:
value = bind_parameters_to_one(value)
target_operator = bind_parameters_to_one(target_operator)
np.testing.assert_allclose(value, target_operator, atol=1e-8)
target_spp_op = sum((op for op in ops[1:]), ops[0])
self.assertEqual(sum_op, target_spp_op)
np.testing.assert_array_equal(sum_op.paulis.phase, np.zeros(sum_op.size))
def test_sum_error(self):
"""Test sum method with invalid cases."""
with self.assertRaises(QiskitError):
SparsePauliOp.sum([])
with self.assertRaises(QiskitError):
ops = [self.random_spp_op(num_qubits, 2**num_qubits) for num_qubits in [1, 2]]
SparsePauliOp.sum(ops)
with self.assertRaises(QiskitError):
SparsePauliOp.sum([1, 2])
@combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False])
def test_eq(self, num_qubits, use_parameters):
"""Test __eq__ method for {num_qubits} qubits."""
spp_op1 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
spp_op3 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters)
zero = spp_op3 - spp_op3
self.assertEqual(spp_op1, spp_op1)
self.assertEqual(spp_op2, spp_op2)
self.assertNotEqual(spp_op1, spp_op1 + zero)
self.assertNotEqual(spp_op2, spp_op2 + zero)
if spp_op1 != spp_op2:
self.assertNotEqual(spp_op1 + spp_op2, spp_op2 + spp_op1)
@combine(num_qubits=[1, 2, 3, 4])
def test_equiv(self, num_qubits):
"""Test equiv method for {num_qubits} qubits."""
spp_op1 = self.random_spp_op(num_qubits, 2**num_qubits)
spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits)
spp_op3 = self.random_spp_op(num_qubits, 2**num_qubits)
spp_op4 = self.random_spp_op(num_qubits, 2**num_qubits)
zero = spp_op3 - spp_op3
zero2 = spp_op4 - spp_op4
self.assertTrue(spp_op1.equiv(spp_op1))
self.assertTrue(spp_op1.equiv(spp_op1 + zero))
self.assertTrue(spp_op2.equiv(spp_op2))
self.assertTrue(spp_op2.equiv(spp_op2 + zero))
self.assertTrue(zero.equiv(zero2))
self.assertTrue((zero + zero2).equiv(zero2 + zero))
self.assertTrue((zero2 + zero).equiv(zero + zero2))
self.assertTrue((spp_op1 + spp_op2).equiv(spp_op2 + spp_op1))
self.assertTrue((spp_op2 + spp_op1).equiv(spp_op1 + spp_op2))
self.assertTrue((spp_op1 - spp_op1).equiv(spp_op2 - spp_op2))
self.assertTrue((2 * spp_op1).equiv(spp_op1 + spp_op1))
self.assertTrue((2 * spp_op2).equiv(spp_op2 + spp_op2))
if not spp_op1.equiv(zero):
self.assertFalse(spp_op1.equiv(spp_op1 + spp_op1))
if not spp_op2.equiv(zero):
self.assertFalse(spp_op2.equiv(spp_op2 + spp_op2))
def test_equiv_atol(self):
"""Test equiv method with atol."""
op1 = SparsePauliOp.from_list([("X", 1), ("Y", 2)])
op2 = op1 + 1e-7 * SparsePauliOp.from_list([("I", 1)])
self.assertFalse(op1.equiv(op2))
self.assertTrue(op1.equiv(op2, atol=1e-7))
def test_eq_equiv(self):
"""Test __eq__ and equiv methods with some specific cases."""
with self.subTest("shuffled"):
spp_op1 = SparsePauliOp.from_list([("X", 1), ("Y", 2)])
spp_op2 = SparsePauliOp.from_list([("Y", 2), ("X", 1)])
self.assertNotEqual(spp_op1, spp_op2)
self.assertTrue(spp_op1.equiv(spp_op2))
with self.subTest("w/ zero"):
spp_op1 = SparsePauliOp.from_list([("X", 1), ("Y", 1)])
spp_op2 = SparsePauliOp.from_list([("X", 1), ("Y", 1), ("Z", 0)])
self.assertNotEqual(spp_op1, spp_op2)
self.assertTrue(spp_op1.equiv(spp_op2))
@combine(parameterized=[True, False], qubit_wise=[True, False])
def test_group_commuting(self, parameterized, qubit_wise):
"""Test general grouping commuting operators"""
def commutes(left: Pauli, right: Pauli, qubit_wise: bool) -> bool:
if len(left) != len(right):
return False
if not qubit_wise:
return left.commutes(right)
else:
# qubit-wise commuting check
vec_l = left.z + 2 * left.x
vec_r = right.z + 2 * right.x
qubit_wise_comparison = (vec_l * vec_r) * (vec_l - vec_r)
return np.all(qubit_wise_comparison == 0)
input_labels = ["IX", "IY", "IZ", "XX", "YY", "ZZ", "XY", "YX", "ZX", "ZY", "XZ", "YZ"]
np.random.shuffle(input_labels)
if parameterized:
coeffs = np.array(ParameterVector("a", len(input_labels)))
else:
coeffs = np.random.random(len(input_labels)) + np.random.random(len(input_labels)) * 1j
sparse_pauli_list = SparsePauliOp(input_labels, coeffs)
groups = sparse_pauli_list.group_commuting(qubit_wise)
# checking that every input Pauli in sparse_pauli_list is in a group in the ouput
output_labels = [pauli.to_label() for group in groups for pauli in group.paulis]
self.assertListEqual(sorted(output_labels), sorted(input_labels))
# checking that every coeffs are grouped according to sparse_pauli_list group
paulis_coeff_dict = dict(
sum([list(zip(group.paulis.to_labels(), group.coeffs)) for group in groups], [])
)
self.assertDictEqual(dict(zip(input_labels, coeffs)), paulis_coeff_dict)
# Within each group, every operator commutes with every other operator.
for group in groups:
self.assertTrue(
all(
commutes(pauli1, pauli2, qubit_wise)
for pauli1, pauli2 in it.combinations(group.paulis, 2)
)
)
# For every pair of groups, at least one element from one group does not commute with
# at least one element of the other.
for group1, group2 in it.combinations(groups, 2):
self.assertFalse(
all(
commutes(group1_pauli, group2_pauli, qubit_wise)
for group1_pauli, group2_pauli in it.product(group1.paulis, group2.paulis)
)
)
def test_dot_real(self):
"""Test dot for real coefficiets."""
x = SparsePauliOp("X", np.array([1]))
y = SparsePauliOp("Y", np.array([1]))
iz = SparsePauliOp("Z", 1j)
self.assertEqual(x.dot(y), iz)
def test_get_parameters(self):
"""Test getting the parameters."""
x, y = Parameter("x"), Parameter("y")
op = SparsePauliOp(["X", "Y", "Z"], coeffs=[1, x, x * y])
with self.subTest(msg="all parameters"):
self.assertEqual(ParameterView([x, y]), op.parameters)
op.assign_parameters({y: 2}, inplace=True)
with self.subTest(msg="after partial binding"):
self.assertEqual(ParameterView([x]), op.parameters)
def test_assign_parameters(self):
"""Test assign parameters."""
x, y = Parameter("x"), Parameter("y")
op = SparsePauliOp(["X", "Y", "Z"], coeffs=[1, x, x * y])
# partial binding inplace
op.assign_parameters({y: 2}, inplace=True)
with self.subTest(msg="partial binding"):
self.assertListEqual(op.coeffs.tolist(), [1, x, 2 * x])
# bind via array
bound = op.assign_parameters([3])
with self.subTest(msg="fully bound"):
self.assertTrue(np.allclose(bound.coeffs.astype(complex), [1, 3, 6]))
def test_paulis_setter_rejects_bad_inputs(self):
"""Test that the setter for `paulis` rejects different-sized inputs."""
op = SparsePauliOp(["XY", "ZX"], coeffs=[1, 1j])
with self.assertRaisesRegex(ValueError, "incorrect number of qubits"):
op.paulis = PauliList([Pauli("X"), Pauli("Y")])
with self.assertRaisesRegex(ValueError, "incorrect number of operators"):
op.paulis = PauliList([Pauli("XY"), Pauli("ZX"), Pauli("YZ")])
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for StabilizerTable class."""
import unittest
import numpy as np
from scipy.sparse import csr_matrix
from qiskit import QiskitError
from qiskit.quantum_info.operators.symplectic import PauliTable, StabilizerTable
from qiskit.test import QiskitTestCase
def stab_mat(label):
"""Return stabilizer matrix from a stabilizer label"""
mat = np.eye(1, dtype=complex)
if label[0] == "-":
mat *= -1
if label[0] in ["-", "+"]:
label = label[1:]
for i in label:
if i == "I":
mat = np.kron(mat, np.eye(2))
elif i == "X":
mat = np.kron(mat, np.array([[0, 1], [1, 0]]))
elif i == "Y":
mat = np.kron(mat, np.array([[0, 1], [-1, 0]]))
elif i == "Z":
mat = np.kron(mat, np.array([[1, 0], [0, -1]]))
else:
raise QiskitError(f"Invalid stabilizer string {i}")
return mat
class TestStabilizerTableInit(QiskitTestCase):
"""Tests for StabilizerTable initialization."""
def test_array_init(self):
"""Test array initialization."""
with self.subTest(msg="bool array"):
target = np.array([[False, False], [True, True]])
with self.assertWarns(DeprecationWarning):
value = StabilizerTable(target)._array
self.assertTrue(np.all(value == target))
with self.subTest(msg="bool array no copy"):
target = np.array([[False, True], [True, True]])
with self.assertWarns(DeprecationWarning):
value = StabilizerTable(target)._array
value[0, 0] = not value[0, 0]
self.assertTrue(np.all(value == target))
with self.subTest(msg="bool array raises"):
array = np.array([[False, False, False], [True, True, True]])
with self.assertWarns(DeprecationWarning):
self.assertRaises(QiskitError, StabilizerTable, array)
def test_vector_init(self):
"""Test vector initialization."""
with self.subTest(msg="bool vector"):
target = np.array([False, False, False, False])
with self.assertWarns(DeprecationWarning):
value = StabilizerTable(target)._array
self.assertTrue(np.all(value == target))
with self.subTest(msg="bool vector no copy"):
target = np.array([False, True, True, False])
with self.assertWarns(DeprecationWarning):
value = StabilizerTable(target)._array
value[0, 0] = not value[0, 0]
self.assertTrue(np.all(value == target))
def test_string_init(self):
"""Test string initialization."""
with self.subTest(msg='str init "I"'):
with self.assertWarns(DeprecationWarning):
value = StabilizerTable("I")._array
target = np.array([[False, False]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
with self.subTest(msg='str init "X"'):
with self.assertWarns(DeprecationWarning):
value = StabilizerTable("X")._array
target = np.array([[True, False]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
with self.subTest(msg='str init "Y"'):
with self.assertWarns(DeprecationWarning):
value = StabilizerTable("Y")._array
target = np.array([[True, True]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
with self.subTest(msg='str init "Z"'):
with self.assertWarns(DeprecationWarning):
value = StabilizerTable("Z")._array
target = np.array([[False, True]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
with self.subTest(msg='str init "IX"'):
with self.assertWarns(DeprecationWarning):
value = StabilizerTable("IX")._array
target = np.array([[True, False, False, False]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
with self.subTest(msg='str init "XI"'):
with self.assertWarns(DeprecationWarning):
value = StabilizerTable("XI")._array
target = np.array([[False, True, False, False]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
with self.subTest(msg='str init "YZ"'):
with self.assertWarns(DeprecationWarning):
value = StabilizerTable("YZ")._array
target = np.array([[False, True, True, True]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
with self.subTest(msg='str init "XIZ"'):
with self.assertWarns(DeprecationWarning):
value = StabilizerTable("XIZ")._array
target = np.array([[False, False, True, True, False, False]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
def test_table_init(self):
"""Test StabilizerTable initialization."""
with self.subTest(msg="StabilizerTable"):
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(["XI", "IX", "IZ"])
value = StabilizerTable(target)
self.assertEqual(value, target)
with self.subTest(msg="StabilizerTable no copy"):
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(["XI", "IX", "IZ"])
value = StabilizerTable(target)
value[0] = "II"
self.assertEqual(value, target)
class TestStabilizerTableProperties(QiskitTestCase):
"""Tests for StabilizerTable properties."""
def test_array_property(self):
"""Test array property"""
with self.subTest(msg="array"):
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable("II")
array = np.zeros([2, 4], dtype=bool)
self.assertTrue(np.all(stab.array == array))
with self.subTest(msg="set array"):
def set_array():
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable("XXX")
stab.array = np.eye(4)
return stab
self.assertRaises(Exception, set_array)
def test_x_property(self):
"""Test X property"""
with self.subTest(msg="X"):
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels(["XI", "IZ", "YY"])
array = np.array([[False, True], [False, False], [True, True]], dtype=bool)
self.assertTrue(np.all(stab.X == array))
with self.subTest(msg="set X"):
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels(["XI", "IZ"])
val = np.array([[False, False], [True, True]], dtype=bool)
stab.X = val
with self.assertWarns(DeprecationWarning):
self.assertEqual(stab, StabilizerTable.from_labels(["II", "XY"]))
with self.subTest(msg="set X raises"):
def set_x():
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels(["XI", "IZ"])
val = np.array([[False, False, False], [True, True, True]], dtype=bool)
stab.X = val
return stab
self.assertRaises(Exception, set_x)
def test_z_property(self):
"""Test Z property"""
with self.subTest(msg="Z"):
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels(["XI", "IZ", "YY"])
array = np.array([[False, False], [True, False], [True, True]], dtype=bool)
self.assertTrue(np.all(stab.Z == array))
with self.subTest(msg="set Z"):
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels(["XI", "IZ"])
val = np.array([[False, False], [True, True]], dtype=bool)
stab.Z = val
with self.assertWarns(DeprecationWarning):
self.assertEqual(stab, StabilizerTable.from_labels(["XI", "ZZ"]))
with self.subTest(msg="set Z raises"):
def set_z():
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels(["XI", "IZ"])
val = np.array([[False, False, False], [True, True, True]], dtype=bool)
stab.Z = val
return stab
self.assertRaises(Exception, set_z)
def test_shape_property(self):
"""Test shape property"""
shape = (3, 8)
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable(np.zeros(shape))
self.assertEqual(stab.shape, shape)
def test_size_property(self):
"""Test size property"""
with self.subTest(msg="size"):
for j in range(1, 10):
shape = (j, 8)
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable(np.zeros(shape))
self.assertEqual(stab.size, j)
def test_num_qubits_property(self):
"""Test num_qubits property"""
with self.subTest(msg="num_qubits"):
for j in range(1, 10):
shape = (5, 2 * j)
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable(np.zeros(shape))
self.assertEqual(stab.num_qubits, j)
def test_phase_property(self):
"""Test phase property"""
with self.subTest(msg="phase"):
phase = np.array([False, True, True, False])
array = np.eye(4, dtype=bool)
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable(array, phase)
self.assertTrue(np.all(stab.phase == phase))
with self.subTest(msg="set phase"):
phase = np.array([False, True, True, False])
array = np.eye(4, dtype=bool)
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable(array)
stab.phase = phase
self.assertTrue(np.all(stab.phase == phase))
with self.subTest(msg="set phase raises"):
phase = np.array([False, True, False])
array = np.eye(4, dtype=bool)
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable(array)
def set_phase_raise():
"""Raise exception"""
stab.phase = phase
self.assertRaises(ValueError, set_phase_raise)
def test_pauli_property(self):
"""Test pauli property"""
with self.subTest(msg="pauli"):
phase = np.array([False, True, True, False])
array = np.eye(4, dtype=bool)
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable(array, phase)
pauli = PauliTable(array)
self.assertEqual(stab.pauli, pauli)
with self.subTest(msg="set pauli"):
phase = np.array([False, True, True, False])
array = np.zeros((4, 4), dtype=bool)
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable(array, phase)
pauli = PauliTable(np.eye(4, dtype=bool))
stab.pauli = pauli
self.assertTrue(np.all(stab.array == pauli.array))
self.assertTrue(np.all(stab.phase == phase))
with self.subTest(msg="set pauli"):
phase = np.array([False, True, True, False])
array = np.zeros((4, 4), dtype=bool)
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable(array, phase)
pauli = PauliTable(np.eye(4, dtype=bool)[1:])
def set_pauli_raise():
"""Raise exception"""
stab.pauli = pauli
self.assertRaises(ValueError, set_pauli_raise)
def test_eq(self):
"""Test __eq__ method."""
with self.assertWarns(DeprecationWarning):
stab1 = StabilizerTable.from_labels(["II", "XI"])
stab2 = StabilizerTable.from_labels(["XI", "II"])
self.assertEqual(stab1, stab1)
self.assertNotEqual(stab1, stab2)
def test_len_methods(self):
"""Test __len__ method."""
for j in range(1, 10):
labels = j * ["XX"]
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels(labels)
self.assertEqual(len(stab), j)
def test_add_methods(self):
"""Test __add__ method."""
labels1 = ["+XXI", "-IXX"]
labels2 = ["+XXI", "-ZZI", "+ZYZ"]
with self.assertWarns(DeprecationWarning):
stab1 = StabilizerTable.from_labels(labels1)
stab2 = StabilizerTable.from_labels(labels2)
target = StabilizerTable.from_labels(labels1 + labels2)
self.assertEqual(target, stab1 + stab2)
def test_add_qargs(self):
"""Test add method with qargs."""
with self.assertWarns(DeprecationWarning):
stab1 = StabilizerTable.from_labels(["+IIII", "-YYYY"])
stab2 = StabilizerTable.from_labels(["-XY", "+YZ"])
with self.subTest(msg="qargs=[0, 1]"):
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(["+IIII", "-YYYY", "-IIXY", "+IIYZ"])
self.assertEqual(stab1 + stab2([0, 1]), target)
with self.subTest(msg="qargs=[0, 3]"):
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(["+IIII", "-YYYY", "-XIIY", "+YIIZ"])
self.assertEqual(stab1 + stab2([0, 3]), target)
with self.subTest(msg="qargs=[2, 1]"):
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(["+IIII", "-YYYY", "-IYXI", "+IZYI"])
self.assertEqual(stab1 + stab2([2, 1]), target)
with self.subTest(msg="qargs=[3, 1]"):
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(["+IIII", "-YYYY", "-YIXI", "+ZIYI"])
self.assertEqual(stab1 + stab2([3, 1]), target)
def test_getitem_methods(self):
"""Test __getitem__ method."""
with self.subTest(msg="__getitem__ single"):
labels = ["+XI", "-IY"]
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels(labels)
self.assertEqual(stab[0], StabilizerTable(labels[0]))
self.assertEqual(stab[1], StabilizerTable(labels[1]))
with self.subTest(msg="__getitem__ array"):
labels = np.array(["+XI", "-IY", "+IZ", "-XY", "+ZX"])
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels(labels)
inds = [0, 3]
with self.assertWarns(DeprecationWarning):
self.assertEqual(stab[inds], StabilizerTable.from_labels(labels[inds]))
inds = np.array([4, 1])
with self.assertWarns(DeprecationWarning):
self.assertEqual(stab[inds], StabilizerTable.from_labels(labels[inds]))
with self.subTest(msg="__getitem__ slice"):
labels = np.array(["+XI", "-IY", "+IZ", "-XY", "+ZX"])
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels(labels)
self.assertEqual(stab[:], stab)
self.assertEqual(stab[1:3], StabilizerTable.from_labels(labels[1:3]))
def test_setitem_methods(self):
"""Test __setitem__ method."""
with self.subTest(msg="__setitem__ single"):
labels = ["+XI", "IY"]
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels(["+XI", "IY"])
stab[0] = "+II"
self.assertEqual(stab[0], StabilizerTable("+II"))
stab[1] = "-XX"
self.assertEqual(stab[1], StabilizerTable("-XX"))
def raises_single():
# Wrong size Pauli
stab[0] = "+XXX"
self.assertRaises(Exception, raises_single)
with self.subTest(msg="__setitem__ array"):
labels = np.array(["+XI", "-IY", "+IZ"])
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels(labels)
target = StabilizerTable.from_labels(["+II", "-ZZ"])
inds = [2, 0]
stab[inds] = target
with self.assertWarns(DeprecationWarning):
self.assertEqual(stab[inds], target)
def raises_array():
with self.assertWarns(DeprecationWarning):
stab[inds] = StabilizerTable.from_labels(["+YY", "-ZZ", "+XX"])
self.assertRaises(Exception, raises_array)
with self.subTest(msg="__setitem__ slice"):
labels = np.array(5 * ["+III"])
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels(labels)
target = StabilizerTable.from_labels(5 * ["-XXX"])
stab[:] = target
with self.assertWarns(DeprecationWarning):
self.assertEqual(stab[:], target)
target = StabilizerTable.from_labels(2 * ["+ZZZ"])
stab[1:3] = target
self.assertEqual(stab[1:3], target)
class TestStabilizerTableLabels(QiskitTestCase):
"""Tests for StabilizerTable label converions."""
def test_from_labels_1q(self):
"""Test 1-qubit from_labels method."""
labels = ["I", "X", "Y", "Z", "+I", "+X", "+Y", "+Z", "-I", "-X", "-Y", "-Z"]
array = np.vstack(
3 * [np.array([[False, False], [True, False], [True, True], [False, True]], dtype=bool)]
)
phase = np.array(8 * [False] + 4 * [True], dtype=bool)
with self.assertWarns(DeprecationWarning):
target = StabilizerTable(array, phase)
value = StabilizerTable.from_labels(labels)
self.assertEqual(target, value)
def test_from_labels_2q(self):
"""Test 2-qubit from_labels method."""
labels = ["II", "-YY", "+XZ"]
array = np.array(
[[False, False, False, False], [True, True, True, True], [False, True, True, False]],
dtype=bool,
)
phase = np.array([False, True, False])
with self.assertWarns(DeprecationWarning):
target = StabilizerTable(array, phase)
value = StabilizerTable.from_labels(labels)
self.assertEqual(target, value)
def test_from_labels_5q(self):
"""Test 5-qubit from_labels method."""
labels = ["IIIII", "-XXXXX", "YYYYY", "ZZZZZ"]
array = np.array(
[10 * [False], 5 * [True] + 5 * [False], 10 * [True], 5 * [False] + 5 * [True]],
dtype=bool,
)
phase = np.array([False, True, False, False])
with self.assertWarns(DeprecationWarning):
target = StabilizerTable(array, phase)
value = StabilizerTable.from_labels(labels)
self.assertEqual(target, value)
def test_to_labels_1q(self):
"""Test 1-qubit to_labels method."""
array = np.vstack(
2 * [np.array([[False, False], [True, False], [True, True], [False, True]], dtype=bool)]
)
phase = np.array(4 * [False] + 4 * [True], dtype=bool)
with self.assertWarns(DeprecationWarning):
value = StabilizerTable(array, phase).to_labels()
target = ["+I", "+X", "+Y", "+Z", "-I", "-X", "-Y", "-Z"]
self.assertEqual(value, target)
def test_to_labels_1q_array(self):
"""Test 1-qubit to_labels method w/ array=True."""
array = np.vstack(
2 * [np.array([[False, False], [True, False], [True, True], [False, True]], dtype=bool)]
)
phase = np.array(4 * [False] + 4 * [True], dtype=bool)
with self.assertWarns(DeprecationWarning):
value = StabilizerTable(array, phase).to_labels(array=True)
target = np.array(["+I", "+X", "+Y", "+Z", "-I", "-X", "-Y", "-Z"])
self.assertTrue(np.all(value == target))
def test_labels_round_trip(self):
"""Test from_labels and to_labels round trip."""
target = ["+III", "-IXZ", "-XYI", "+ZZZ"]
with self.assertWarns(DeprecationWarning):
value = StabilizerTable.from_labels(target).to_labels()
self.assertEqual(value, target)
def test_labels_round_trip_array(self):
"""Test from_labels and to_labels round trip w/ array=True."""
labels = ["+III", "-IXZ", "-XYI", "+ZZZ"]
target = np.array(labels)
with self.assertWarns(DeprecationWarning):
value = StabilizerTable.from_labels(labels).to_labels(array=True)
self.assertTrue(np.all(value == target))
class TestStabilizerTableMatrix(QiskitTestCase):
"""Tests for StabilizerTable matrix converions."""
def test_to_matrix_1q(self):
"""Test 1-qubit to_matrix method."""
labels = ["+I", "+X", "+Y", "+Z", "-I", "-X", "-Y", "-Z"]
targets = [stab_mat(i) for i in labels]
with self.assertWarns(DeprecationWarning):
values = StabilizerTable.from_labels(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_1q_array(self):
"""Test 1-qubit to_matrix method w/ array=True."""
labels = ["+I", "+X", "+Y", "+Z", "-I", "-X", "-Y", "-Z"]
target = np.array([stab_mat(i) for i in labels])
with self.assertWarns(DeprecationWarning):
value = StabilizerTable.from_labels(labels).to_matrix(array=True)
self.assertTrue(isinstance(value, np.ndarray))
self.assertTrue(np.all(value == target))
def test_to_matrix_1q_sparse(self):
"""Test 1-qubit to_matrix method w/ sparse=True."""
labels = ["+I", "+X", "+Y", "+Z", "-I", "-X", "-Y", "-Z"]
targets = [stab_mat(i) for i in labels]
with self.assertWarns(DeprecationWarning):
values = StabilizerTable.from_labels(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
def test_to_matrix_2q(self):
"""Test 2-qubit to_matrix method."""
labels = ["+IX", "-YI", "-II", "+ZZ"]
targets = [stab_mat(i) for i in labels]
with self.assertWarns(DeprecationWarning):
values = StabilizerTable.from_labels(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_2q_array(self):
"""Test 2-qubit to_matrix method w/ array=True."""
labels = ["-ZZ", "-XY", "+YX", "-IZ"]
target = np.array([stab_mat(i) for i in labels])
with self.assertWarns(DeprecationWarning):
value = StabilizerTable.from_labels(labels).to_matrix(array=True)
self.assertTrue(isinstance(value, np.ndarray))
self.assertTrue(np.all(value == target))
def test_to_matrix_2q_sparse(self):
"""Test 2-qubit to_matrix method w/ sparse=True."""
labels = ["+IX", "+II", "-ZY", "-YZ"]
targets = [stab_mat(i) for i in labels]
with self.assertWarns(DeprecationWarning):
values = StabilizerTable.from_labels(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
def test_to_matrix_5q(self):
"""Test 5-qubit to_matrix method."""
labels = ["IXIXI", "YZIXI", "IIXYZ"]
targets = [stab_mat(i) for i in labels]
with self.assertWarns(DeprecationWarning):
values = StabilizerTable.from_labels(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_5q_sparse(self):
"""Test 5-qubit to_matrix method w/ sparse=True."""
labels = ["-XXXYY", "IXIZY", "-ZYXIX", "+ZXIYZ"]
targets = [stab_mat(i) for i in labels]
with self.assertWarns(DeprecationWarning):
values = StabilizerTable.from_labels(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
class TestStabilizerTableMethods(QiskitTestCase):
"""Tests for StabilizerTable methods."""
def test_sort(self):
"""Test sort method."""
with self.subTest(msg="1 qubit"):
unsrt = ["X", "-Z", "I", "Y", "-X", "Z"]
srt = ["I", "X", "-X", "Y", "-Z", "Z"]
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(srt)
value = StabilizerTable.from_labels(unsrt).sort()
self.assertEqual(target, value)
with self.subTest(msg="1 qubit weight order"):
unsrt = ["X", "-Z", "I", "Y", "-X", "Z"]
srt = ["I", "X", "-X", "Y", "-Z", "Z"]
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(srt)
value = StabilizerTable.from_labels(unsrt).sort(weight=True)
self.assertEqual(target, value)
with self.subTest(msg="2 qubit standard order"):
srt_p = [
"II",
"IX",
"IY",
"XI",
"XX",
"XY",
"XZ",
"YI",
"YX",
"YY",
"YZ",
"ZI",
"ZX",
"ZY",
"ZZ",
]
srt_m = ["-" + i for i in srt_p]
unsrt_p = srt_p.copy()
np.random.shuffle(unsrt_p)
unsrt_m = srt_m.copy()
np.random.shuffle(unsrt_m)
# Sort with + cases all first in shuffled list
srt = [val for pair in zip(srt_p, srt_m) for val in pair]
unsrt = unsrt_p + unsrt_m
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(srt)
value = StabilizerTable.from_labels(unsrt).sort()
self.assertEqual(target, value)
# Sort with - cases all first in shuffled list
srt = [val for pair in zip(srt_m, srt_p) for val in pair]
unsrt = unsrt_m + unsrt_p
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(srt)
value = StabilizerTable.from_labels(unsrt).sort()
self.assertEqual(target, value)
with self.subTest(msg="2 qubit weight order"):
srt_p = [
"II",
"IX",
"IY",
"IZ",
"XI",
"YI",
"ZI",
"XX",
"XY",
"XZ",
"YX",
"YY",
"YZ",
"ZX",
"ZY",
"ZZ",
]
srt_m = ["-" + i for i in srt_p]
unsrt_p = srt_p.copy()
np.random.shuffle(unsrt_p)
unsrt_m = srt_m.copy()
np.random.shuffle(unsrt_m)
# Sort with + cases all first in shuffled list
srt = [val for pair in zip(srt_p, srt_m) for val in pair]
unsrt = unsrt_p + unsrt_m
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(srt)
value = StabilizerTable.from_labels(unsrt).sort(weight=True)
self.assertEqual(target, value)
# Sort with - cases all first in shuffled list
srt = [val for pair in zip(srt_m, srt_p) for val in pair]
unsrt = unsrt_m + unsrt_p
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(srt)
value = StabilizerTable.from_labels(unsrt).sort(weight=True)
self.assertEqual(target, value)
def test_unique(self):
"""Test unique method."""
with self.subTest(msg="1 qubit"):
labels = ["X", "Z", "-I", "-X", "X", "I", "Y", "-I", "-X", "-Z", "Z", "X", "I"]
unique = ["X", "Z", "-I", "-X", "I", "Y", "-Z"]
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(unique)
value = StabilizerTable.from_labels(labels).unique()
self.assertEqual(target, value)
with self.subTest(msg="2 qubit"):
labels = [
"XX",
"IX",
"-XX",
"XX",
"-IZ",
"II",
"IZ",
"ZI",
"YX",
"YX",
"ZZ",
"IX",
"XI",
]
unique = ["XX", "IX", "-XX", "-IZ", "II", "IZ", "ZI", "YX", "ZZ", "XI"]
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(unique)
value = StabilizerTable.from_labels(labels).unique()
self.assertEqual(target, value)
with self.subTest(msg="10 qubit"):
labels = [10 * "X", "-" + 10 * "X", "-" + 10 * "X", 10 * "I", 10 * "X"]
unique = [10 * "X", "-" + 10 * "X", 10 * "I"]
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(unique)
value = StabilizerTable.from_labels(labels).unique()
self.assertEqual(target, value)
def test_delete(self):
"""Test delete method."""
with self.subTest(msg="single row"):
for j in range(1, 6):
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels([j * "X", "-" + j * "Y"])
self.assertEqual(stab.delete(0), StabilizerTable("-" + j * "Y"))
self.assertEqual(stab.delete(1), StabilizerTable(j * "X"))
with self.subTest(msg="multiple rows"):
for j in range(1, 6):
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels([j * "X", "-" + j * "Y", j * "Z"])
self.assertEqual(stab.delete([0, 2]), StabilizerTable("-" + j * "Y"))
self.assertEqual(stab.delete([1, 2]), StabilizerTable(j * "X"))
self.assertEqual(stab.delete([0, 1]), StabilizerTable(j * "Z"))
with self.subTest(msg="single qubit"):
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels(["IIX", "IYI", "ZII"])
value = stab.delete(0, qubit=True)
target = StabilizerTable.from_labels(["II", "IY", "ZI"])
self.assertEqual(value, target)
value = stab.delete(1, qubit=True)
target = StabilizerTable.from_labels(["IX", "II", "ZI"])
self.assertEqual(value, target)
value = stab.delete(2, qubit=True)
target = StabilizerTable.from_labels(["IX", "YI", "II"])
self.assertEqual(value, target)
with self.subTest(msg="multiple qubits"):
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels(["IIX", "IYI", "ZII"])
value = stab.delete([0, 1], qubit=True)
target = StabilizerTable.from_labels(["I", "I", "Z"])
self.assertEqual(value, target)
value = stab.delete([1, 2], qubit=True)
target = StabilizerTable.from_labels(["X", "I", "I"])
self.assertEqual(value, target)
value = stab.delete([0, 2], qubit=True)
target = StabilizerTable.from_labels(["I", "Y", "I"])
self.assertEqual(value, target)
def test_insert(self):
"""Test insert method."""
# Insert single row
for j in range(1, 10):
l_px = j * "X"
l_mi = "-" + j * "I"
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable(l_px)
target0 = StabilizerTable.from_labels([l_mi, l_px])
target1 = StabilizerTable.from_labels([l_px, l_mi])
with self.subTest(msg=f"single row from str ({j})"):
with self.assertWarns(DeprecationWarning):
value0 = stab.insert(0, l_mi)
self.assertEqual(value0, target0)
value1 = stab.insert(1, l_mi)
self.assertEqual(value1, target1)
with self.subTest(msg=f"single row from StabilizerTable ({j})"):
with self.assertWarns(DeprecationWarning):
value0 = stab.insert(0, StabilizerTable(l_mi))
self.assertEqual(value0, target0)
value1 = stab.insert(1, StabilizerTable(l_mi))
self.assertEqual(value1, target1)
# Insert multiple rows
for j in range(1, 10):
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable(j * "X")
insert = StabilizerTable.from_labels(["-" + j * "I", j * "Y", "-" + j * "Z"])
target0 = insert + stab
target1 = stab + insert
with self.subTest(msg=f"multiple-rows from StabilizerTable ({j})"):
with self.assertWarns(DeprecationWarning):
value0 = stab.insert(0, insert)
self.assertEqual(value0, target0)
value1 = stab.insert(1, insert)
self.assertEqual(value1, target1)
# Insert single column
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels(["X", "Y", "Z"])
for sgn in ["+", "-"]:
for i in ["I", "X", "Y", "Z"]:
with self.assertWarns(DeprecationWarning):
target0 = StabilizerTable.from_labels(
[sgn + "X" + i, sgn + "Y" + i, sgn + "Z" + i]
)
target1 = StabilizerTable.from_labels(
[sgn + i + "X", sgn + i + "Y", sgn + i + "Z"]
)
with self.subTest(msg=f"single-column single-val from str {sgn + i}"):
with self.assertWarns(DeprecationWarning):
value = stab.insert(0, sgn + i, qubit=True)
self.assertEqual(value, target0)
value = stab.insert(1, sgn + i, qubit=True)
self.assertEqual(value, target1)
with self.subTest(msg=f"single-column single-val from StabilizerTable {sgn + i}"):
with self.assertWarns(DeprecationWarning):
value = stab.insert(0, StabilizerTable(sgn + i), qubit=True)
self.assertEqual(value, target0)
value = stab.insert(1, StabilizerTable(sgn + i), qubit=True)
self.assertEqual(value, target1)
# Insert single column with multiple values
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels(["X", "Y", "Z"])
for i in [("I", "X", "Y"), ("X", "Y", "Z"), ("Y", "Z", "I")]:
with self.assertWarns(DeprecationWarning):
target0 = StabilizerTable.from_labels(["X" + i[0], "Y" + i[1], "Z" + i[2]])
target1 = StabilizerTable.from_labels([i[0] + "X", i[1] + "Y", i[2] + "Z"])
with self.subTest(msg="single-column multiple-vals from StabilizerTable"):
with self.assertWarns(DeprecationWarning):
value = stab.insert(0, StabilizerTable.from_labels(i), qubit=True)
self.assertEqual(value, target0)
value = stab.insert(1, StabilizerTable.from_labels(i), qubit=True)
self.assertEqual(value, target1)
with self.subTest(msg="single-column multiple-vals from array"):
with self.assertWarns(DeprecationWarning):
value = stab.insert(0, StabilizerTable.from_labels(i).array, qubit=True)
self.assertEqual(value, target0)
value = stab.insert(1, StabilizerTable.from_labels(i).array, qubit=True)
self.assertEqual(value, target1)
# Insert multiple columns from single
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels(["X", "Y", "Z"])
for j in range(1, 5):
for i in [j * "I", j * "X", j * "Y", j * "Z"]:
with self.assertWarns(DeprecationWarning):
target0 = StabilizerTable.from_labels(["X" + i, "Y" + i, "Z" + i])
target1 = StabilizerTable.from_labels([i + "X", i + "Y", i + "Z"])
with self.subTest(msg="multiple-columns single-val from str"):
with self.assertWarns(DeprecationWarning):
value = stab.insert(0, i, qubit=True)
self.assertEqual(value, target0)
value = stab.insert(1, i, qubit=True)
self.assertEqual(value, target1)
with self.subTest(msg="multiple-columns single-val from StabilizerTable"):
with self.assertWarns(DeprecationWarning):
value = stab.insert(0, StabilizerTable(i), qubit=True)
self.assertEqual(value, target0)
value = stab.insert(1, StabilizerTable(i), qubit=True)
self.assertEqual(value, target1)
with self.subTest(msg="multiple-columns single-val from array"):
with self.assertWarns(DeprecationWarning):
value = stab.insert(0, StabilizerTable(i).array, qubit=True)
self.assertEqual(value, target0)
value = stab.insert(1, StabilizerTable(i).array, qubit=True)
self.assertEqual(value, target1)
# Insert multiple columns multiple row values
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels(["X", "Y", "Z"])
for j in range(1, 5):
for i in [
(j * "I", j * "X", j * "Y"),
(j * "X", j * "Z", j * "Y"),
(j * "Y", j * "Z", j * "I"),
]:
with self.assertWarns(DeprecationWarning):
target0 = StabilizerTable.from_labels(["X" + i[0], "Y" + i[1], "Z" + i[2]])
target1 = StabilizerTable.from_labels([i[0] + "X", i[1] + "Y", i[2] + "Z"])
with self.subTest(msg="multiple-column multiple-vals from StabilizerTable"):
with self.assertWarns(DeprecationWarning):
value = stab.insert(0, StabilizerTable.from_labels(i), qubit=True)
self.assertEqual(value, target0)
value = stab.insert(1, StabilizerTable.from_labels(i), qubit=True)
self.assertEqual(value, target1)
with self.subTest(msg="multiple-column multiple-vals from array"):
with self.assertWarns(DeprecationWarning):
value = stab.insert(0, StabilizerTable.from_labels(i).array, qubit=True)
self.assertEqual(value, target0)
value = stab.insert(1, StabilizerTable.from_labels(i).array, qubit=True)
self.assertEqual(value, target1)
def test_iteration(self):
"""Test iteration methods."""
labels = ["+III", "+IXI", "-IYY", "+YIZ", "-ZIZ", "+XYZ", "-III"]
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels(labels)
with self.subTest(msg="enumerate"):
with self.assertWarns(DeprecationWarning):
for idx, i in enumerate(stab):
self.assertEqual(i, StabilizerTable(labels[idx]))
with self.subTest(msg="iter"):
with self.assertWarns(DeprecationWarning):
for idx, i in enumerate(iter(stab)):
self.assertEqual(i, StabilizerTable(labels[idx]))
with self.subTest(msg="zip"):
with self.assertWarns(DeprecationWarning):
for label, i in zip(labels, stab):
self.assertEqual(i, StabilizerTable(label))
with self.subTest(msg="label_iter"):
for idx, i in enumerate(stab.label_iter()):
self.assertEqual(i, labels[idx])
with self.subTest(msg="matrix_iter (dense)"):
for idx, i in enumerate(stab.matrix_iter()):
self.assertTrue(np.all(i == stab_mat(labels[idx])))
with self.subTest(msg="matrix_iter (sparse)"):
for idx, i in enumerate(stab.matrix_iter(sparse=True)):
self.assertTrue(isinstance(i, csr_matrix))
self.assertTrue(np.all(i.toarray() == stab_mat(labels[idx])))
def test_tensor(self):
"""Test tensor method."""
labels1 = ["-XX", "YY"]
labels2 = ["III", "-ZZZ"]
with self.assertWarns(DeprecationWarning):
stab1 = StabilizerTable.from_labels(labels1)
stab2 = StabilizerTable.from_labels(labels2)
target = StabilizerTable.from_labels(["-XXIII", "XXZZZ", "YYIII", "-YYZZZ"])
value = stab1.tensor(stab2)
self.assertEqual(value, target)
def test_expand(self):
"""Test expand method."""
labels1 = ["-XX", "YY"]
labels2 = ["III", "-ZZZ"]
with self.assertWarns(DeprecationWarning):
stab1 = StabilizerTable.from_labels(labels1)
stab2 = StabilizerTable.from_labels(labels2)
target = StabilizerTable.from_labels(["-IIIXX", "IIIYY", "ZZZXX", "-ZZZYY"])
value = stab1.expand(stab2)
self.assertEqual(value, target)
def test_compose(self):
"""Test compose and dot methods."""
# Test single qubit Pauli dot products
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels(["I", "X", "Y", "Z"])
# Test single qubit Pauli dot products
with self.assertWarns(DeprecationWarning):
stab = StabilizerTable.from_labels(["I", "X", "Y", "Z", "-I", "-X", "-Y", "-Z"])
with self.subTest(msg="dot single I"):
with self.assertWarns(DeprecationWarning):
value = stab.compose("I")
target = StabilizerTable.from_labels(["I", "X", "Y", "Z", "-I", "-X", "-Y", "-Z"])
self.assertEqual(target, value)
with self.subTest(msg="dot single -I"):
with self.assertWarns(DeprecationWarning):
value = stab.compose("-I")
target = StabilizerTable.from_labels(["-I", "-X", "-Y", "-Z", "I", "X", "Y", "Z"])
self.assertEqual(target, value)
with self.subTest(msg="dot single I"):
with self.assertWarns(DeprecationWarning):
value = stab.dot("I")
target = StabilizerTable.from_labels(["I", "X", "Y", "Z", "-I", "-X", "-Y", "-Z"])
self.assertEqual(target, value)
with self.subTest(msg="dot single -I"):
with self.assertWarns(DeprecationWarning):
value = stab.dot("-I")
target = StabilizerTable.from_labels(["-I", "-X", "-Y", "-Z", "I", "X", "Y", "Z"])
self.assertEqual(target, value)
with self.subTest(msg="compose single X"):
with self.assertWarns(DeprecationWarning):
value = stab.compose("X")
target = StabilizerTable.from_labels(["X", "I", "-Z", "Y", "-X", "-I", "Z", "-Y"])
self.assertEqual(target, value)
with self.subTest(msg="compose single -X"):
with self.assertWarns(DeprecationWarning):
value = stab.compose("-X")
target = StabilizerTable.from_labels(["-X", "-I", "Z", "-Y", "X", "I", "-Z", "Y"])
self.assertEqual(target, value)
with self.subTest(msg="dot single X"):
with self.assertWarns(DeprecationWarning):
value = stab.dot("X")
target = StabilizerTable.from_labels(["X", "I", "Z", "-Y", "-X", "-I", "-Z", "Y"])
self.assertEqual(target, value)
with self.subTest(msg="dot single -X"):
with self.assertWarns(DeprecationWarning):
value = stab.dot("-X")
target = StabilizerTable.from_labels(["-X", "-I", "-Z", "Y", "X", "I", "Z", "-Y"])
self.assertEqual(target, value)
with self.subTest(msg="compose single Y"):
with self.assertWarns(DeprecationWarning):
value = stab.compose("Y")
target = StabilizerTable.from_labels(["Y", "Z", "-I", "-X", "-Y", "-Z", "I", "X"])
self.assertEqual(target, value)
with self.subTest(msg="compose single -Y"):
with self.assertWarns(DeprecationWarning):
value = stab.compose("-Y")
target = StabilizerTable.from_labels(["-Y", "-Z", "I", "X", "Y", "Z", "-I", "-X"])
self.assertEqual(target, value)
with self.subTest(msg="dot single Y"):
with self.assertWarns(DeprecationWarning):
value = stab.dot("Y")
target = StabilizerTable.from_labels(["Y", "-Z", "-I", "X", "-Y", "Z", "I", "-X"])
self.assertEqual(target, value)
with self.subTest(msg="dot single -Y"):
with self.assertWarns(DeprecationWarning):
value = stab.dot("-Y")
target = StabilizerTable.from_labels(["-Y", "Z", "I", "-X", "Y", "-Z", "-I", "X"])
self.assertEqual(target, value)
with self.subTest(msg="compose single Z"):
with self.assertWarns(DeprecationWarning):
value = stab.compose("Z")
target = StabilizerTable.from_labels(["Z", "-Y", "X", "I", "-Z", "Y", "-X", "-I"])
self.assertEqual(target, value)
with self.subTest(msg="compose single -Z"):
with self.assertWarns(DeprecationWarning):
value = stab.compose("-Z")
target = StabilizerTable.from_labels(["-Z", "Y", "-X", "-I", "Z", "-Y", "X", "I"])
self.assertEqual(target, value)
with self.subTest(msg="dot single Z"):
with self.assertWarns(DeprecationWarning):
value = stab.dot("Z")
target = StabilizerTable.from_labels(["Z", "Y", "-X", "I", "-Z", "-Y", "X", "-I"])
self.assertEqual(target, value)
with self.subTest(msg="dot single -Z"):
with self.assertWarns(DeprecationWarning):
value = stab.dot("-Z")
target = StabilizerTable.from_labels(["-Z", "-Y", "X", "-I", "Z", "Y", "-X", "I"])
self.assertEqual(target, value)
def test_compose_qargs(self):
"""Test compose and dot methods with qargs."""
# Dot product with qargs
with self.assertWarns(DeprecationWarning):
stab1 = StabilizerTable.from_labels(["III", "-XXX", "YYY", "-ZZZ"])
# 1-qubit qargs
with self.assertWarns(DeprecationWarning):
stab2 = StabilizerTable("-Z")
with self.subTest(msg="dot 1-qubit qargs=[0]"):
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(["-IIZ", "XXY", "YYX", "ZZI"])
value = stab1.dot(stab2, qargs=[0])
self.assertEqual(value, target)
with self.subTest(msg="compose 1-qubit qargs=[0]"):
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(["-IIZ", "-XXY", "-YYX", "ZZI"])
value = stab1.compose(stab2, qargs=[0])
self.assertEqual(value, target)
with self.subTest(msg="dot 1-qubit qargs=[1]"):
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(["-IZI", "XYX", "YXY", "ZIZ"])
value = stab1.dot(stab2, qargs=[1])
self.assertEqual(value, target)
with self.subTest(msg="compose 1-qubit qargs=[1]"):
with self.assertWarns(DeprecationWarning):
value = stab1.compose(stab2, qargs=[1])
target = StabilizerTable.from_labels(["-IZI", "-XYX", "-YXY", "ZIZ"])
self.assertEqual(value, target)
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(["ZII", "YXX"])
with self.subTest(msg="dot 1-qubit qargs=[2]"):
with self.assertWarns(DeprecationWarning):
value = stab1.dot(stab2, qargs=[2])
target = StabilizerTable.from_labels(["-ZII", "YXX", "XYY", "IZZ"])
self.assertEqual(value, target)
with self.subTest(msg="compose 1-qubit qargs=[2]"):
with self.assertWarns(DeprecationWarning):
value = stab1.compose(stab2, qargs=[2])
target = StabilizerTable.from_labels(["-ZII", "-YXX", "-XYY", "IZZ"])
self.assertEqual(value, target)
# 2-qubit qargs
with self.assertWarns(DeprecationWarning):
stab2 = StabilizerTable("-ZY")
with self.subTest(msg="dot 2-qubit qargs=[0, 1]"):
with self.assertWarns(DeprecationWarning):
value = stab1.dot(stab2, qargs=[0, 1])
target = StabilizerTable.from_labels(["-IZY", "-XYZ", "-YXI", "ZIX"])
self.assertEqual(value, target)
with self.subTest(msg="compose 2-qubit qargs=[0, 1]"):
with self.assertWarns(DeprecationWarning):
value = stab1.compose(stab2, qargs=[0, 1])
target = StabilizerTable.from_labels(["-IZY", "-XYZ", "YXI", "-ZIX"])
self.assertEqual(value, target)
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(["YIZ", "ZXY"])
with self.subTest(msg="dot 2-qubit qargs=[2, 0]"):
with self.assertWarns(DeprecationWarning):
value = stab1.dot(stab2, qargs=[2, 0])
target = StabilizerTable.from_labels(["-YIZ", "-ZXY", "-IYX", "XZI"])
self.assertEqual(value, target)
with self.subTest(msg="compose 2-qubit qargs=[2, 0]"):
with self.assertWarns(DeprecationWarning):
value = stab1.compose(stab2, qargs=[2, 0])
target = StabilizerTable.from_labels(["-YIZ", "-ZXY", "IYX", "-XZI"])
self.assertEqual(value, target)
# 3-qubit qargs
with self.assertWarns(DeprecationWarning):
stab2 = StabilizerTable("-XYZ")
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(["XYZ", "IZY"])
with self.subTest(msg="dot 3-qubit qargs=None"):
with self.assertWarns(DeprecationWarning):
value = stab1.dot(stab2, qargs=[0, 1, 2])
target = StabilizerTable.from_labels(["-XYZ", "-IZY", "-ZIX", "-YXI"])
self.assertEqual(value, target)
with self.subTest(msg="dot 3-qubit qargs=[0, 1, 2]"):
with self.assertWarns(DeprecationWarning):
value = stab1.dot(stab2, qargs=[0, 1, 2])
target = StabilizerTable.from_labels(["-XYZ", "-IZY", "-ZIX", "-YXI"])
self.assertEqual(value, target)
with self.subTest(msg="dot 3-qubit qargs=[2, 1, 0]"):
with self.assertWarns(DeprecationWarning):
value = stab1.dot(stab2, qargs=[2, 1, 0])
target = StabilizerTable.from_labels(["-ZYX", "-YZI", "-XIZ", "-IXY"])
self.assertEqual(value, target)
with self.subTest(msg="compose 3-qubit qargs=[2, 1, 0]"):
with self.assertWarns(DeprecationWarning):
value = stab1.compose(stab2, qargs=[2, 1, 0])
target = StabilizerTable.from_labels(["-ZYX", "-YZI", "-XIZ", "-IXY"])
self.assertEqual(value, target)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for DensityMatrix quantum state class."""
import logging
import unittest
import numpy as np
from ddt import data, ddt
from numpy.testing import assert_allclose
from qiskit import QiskitError, QuantumCircuit, QuantumRegister
from qiskit.circuit.library import QFT, HGate
from qiskit.quantum_info.operators.operator import Operator
from qiskit.quantum_info.operators.symplectic import Pauli, SparsePauliOp
from qiskit.quantum_info.random import random_density_matrix, random_pauli, random_unitary
from qiskit.quantum_info.states import DensityMatrix, Statevector
from qiskit.test import QiskitTestCase
from qiskit.utils import optionals
logger = logging.getLogger(__name__)
@ddt
class TestDensityMatrix(QiskitTestCase):
"""Tests for DensityMatrix class."""
@classmethod
def rand_vec(cls, n, normalize=False):
"""Return complex vector or statevector"""
seed = np.random.randint(0, np.iinfo(np.int32).max)
logger.debug("rand_vec default_rng seeded with seed=%s", seed)
rng = np.random.default_rng(seed)
vec = rng.random(n) + 1j * rng.random(n)
if normalize:
vec /= np.sqrt(np.dot(vec, np.conj(vec)))
return vec
@classmethod
def rand_rho(cls, n):
"""Return random pure state density matrix"""
rho = cls.rand_vec(n, normalize=True)
return np.outer(rho, np.conjugate(rho))
def test_init_array_qubit(self):
"""Test subsystem initialization from N-qubit array."""
# Test automatic inference of qubit subsystems
rho = self.rand_rho(8)
for dims in [None, 8]:
state = DensityMatrix(rho, dims=dims)
assert_allclose(state.data, rho)
self.assertEqual(state.dim, 8)
self.assertEqual(state.dims(), (2, 2, 2))
self.assertEqual(state.num_qubits, 3)
def test_init_array(self):
"""Test initialization from array."""
rho = self.rand_rho(3)
state = DensityMatrix(rho)
assert_allclose(state.data, rho)
self.assertEqual(state.dim, 3)
self.assertEqual(state.dims(), (3,))
self.assertIsNone(state.num_qubits)
rho = self.rand_rho(2 * 3 * 4)
state = DensityMatrix(rho, dims=[2, 3, 4])
assert_allclose(state.data, rho)
self.assertEqual(state.dim, 2 * 3 * 4)
self.assertEqual(state.dims(), (2, 3, 4))
self.assertIsNone(state.num_qubits)
def test_init_array_except(self):
"""Test initialization exception from array."""
rho = self.rand_rho(4)
self.assertRaises(QiskitError, DensityMatrix, rho, dims=[4, 2])
self.assertRaises(QiskitError, DensityMatrix, rho, dims=[2, 4])
self.assertRaises(QiskitError, DensityMatrix, rho, dims=5)
def test_init_densitymatrix(self):
"""Test initialization from DensityMatrix."""
rho1 = DensityMatrix(self.rand_rho(4))
rho2 = DensityMatrix(rho1)
self.assertEqual(rho1, rho2)
def test_init_statevector(self):
"""Test initialization from DensityMatrix."""
vec = self.rand_vec(4)
target = DensityMatrix(np.outer(vec, np.conjugate(vec)))
rho = DensityMatrix(Statevector(vec))
self.assertEqual(rho, target)
def test_init_circuit(self):
"""Test initialization from a circuit."""
# random unitaries
u0 = random_unitary(2).data
u1 = random_unitary(2).data
# add to circuit
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.unitary(u0, [qr[0]])
circ.unitary(u1, [qr[1]])
target_vec = Statevector(np.kron(u1, u0).dot([1, 0, 0, 0]))
target = DensityMatrix(target_vec)
rho = DensityMatrix(circ)
self.assertEqual(rho, target)
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.x(1)
circuit.ry(np.pi / 2, 2)
target = DensityMatrix.from_label("000").evolve(Operator(circuit))
rho = DensityMatrix(circuit)
self.assertEqual(rho, target)
# Test decomposition of Controlled-Phase gate
lam = np.pi / 4
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.h(1)
circuit.cp(lam, 0, 1)
target = DensityMatrix.from_label("00").evolve(Operator(circuit))
rho = DensityMatrix(circuit)
self.assertEqual(rho, target)
def test_from_circuit(self):
"""Test initialization from a circuit."""
# random unitaries
u0 = random_unitary(2).data
u1 = random_unitary(2).data
# add to circuit
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.unitary(u0, [qr[0]])
circ.unitary(u1, [qr[1]])
# Test decomposition of controlled-H gate
circuit = QuantumCircuit(2)
circ.x(0)
circuit.ch(0, 1)
target = DensityMatrix.from_label("00").evolve(Operator(circuit))
rho = DensityMatrix.from_instruction(circuit)
self.assertEqual(rho, target)
# Test initialize instruction
init = Statevector([1, 0, 0, 1j]) / np.sqrt(2)
target = DensityMatrix(init)
circuit = QuantumCircuit(2)
circuit.initialize(init.data, [0, 1])
rho = DensityMatrix.from_instruction(circuit)
self.assertEqual(rho, target)
# Test reset instruction
target = DensityMatrix([1, 0])
circuit = QuantumCircuit(1)
circuit.h(0)
circuit.reset(0)
rho = DensityMatrix.from_instruction(circuit)
self.assertEqual(rho, target)
def test_from_instruction(self):
"""Test initialization from an instruction."""
target_vec = Statevector(np.dot(HGate().to_matrix(), [1, 0]))
target = DensityMatrix(target_vec)
rho = DensityMatrix.from_instruction(HGate())
self.assertEqual(rho, target)
def test_from_label(self):
"""Test initialization from a label"""
x_p = DensityMatrix(np.array([[0.5, 0.5], [0.5, 0.5]]))
x_m = DensityMatrix(np.array([[0.5, -0.5], [-0.5, 0.5]]))
y_p = DensityMatrix(np.array([[0.5, -0.5j], [0.5j, 0.5]]))
y_m = DensityMatrix(np.array([[0.5, 0.5j], [-0.5j, 0.5]]))
z_p = DensityMatrix(np.diag([1, 0]))
z_m = DensityMatrix(np.diag([0, 1]))
label = "0+r"
target = z_p.tensor(x_p).tensor(y_p)
self.assertEqual(target, DensityMatrix.from_label(label))
label = "-l1"
target = x_m.tensor(y_m).tensor(z_m)
self.assertEqual(target, DensityMatrix.from_label(label))
def test_equal(self):
"""Test __eq__ method"""
for _ in range(10):
rho = self.rand_rho(4)
self.assertEqual(DensityMatrix(rho), DensityMatrix(rho.tolist()))
def test_copy(self):
"""Test DensityMatrix copy method"""
for _ in range(5):
rho = self.rand_rho(4)
orig = DensityMatrix(rho)
cpy = orig.copy()
cpy._data[0] += 1.0
self.assertFalse(cpy == orig)
def test_is_valid(self):
"""Test is_valid method."""
state = DensityMatrix(np.eye(2))
self.assertFalse(state.is_valid())
for _ in range(10):
state = DensityMatrix(self.rand_rho(4))
self.assertTrue(state.is_valid())
def test_to_operator(self):
"""Test to_operator method for returning projector."""
for _ in range(10):
rho = self.rand_rho(4)
target = Operator(rho)
op = DensityMatrix(rho).to_operator()
self.assertEqual(op, target)
def test_evolve(self):
"""Test evolve method for operators."""
for _ in range(10):
op = random_unitary(4)
rho = self.rand_rho(4)
target = DensityMatrix(np.dot(op.data, rho).dot(op.adjoint().data))
evolved = DensityMatrix(rho).evolve(op)
self.assertEqual(target, evolved)
def test_evolve_subsystem(self):
"""Test subsystem evolve method for operators."""
# Test evolving single-qubit of 3-qubit system
for _ in range(5):
rho = self.rand_rho(8)
state = DensityMatrix(rho)
op0 = random_unitary(2)
op1 = random_unitary(2)
op2 = random_unitary(2)
# Test evolve on 1-qubit
op = op0
op_full = Operator(np.eye(4)).tensor(op)
target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data))
self.assertEqual(state.evolve(op, qargs=[0]), target)
# Evolve on qubit 1
op_full = Operator(np.eye(2)).tensor(op).tensor(np.eye(2))
target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data))
self.assertEqual(state.evolve(op, qargs=[1]), target)
# Evolve on qubit 2
op_full = op.tensor(np.eye(4))
target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data))
self.assertEqual(state.evolve(op, qargs=[2]), target)
# Test evolve on 2-qubits
op = op1.tensor(op0)
# Evolve on qubits [0, 2]
op_full = op1.tensor(np.eye(2)).tensor(op0)
target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data))
self.assertEqual(state.evolve(op, qargs=[0, 2]), target)
# Evolve on qubits [2, 0]
op_full = op0.tensor(np.eye(2)).tensor(op1)
target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data))
self.assertEqual(state.evolve(op, qargs=[2, 0]), target)
# Test evolve on 3-qubits
op = op2.tensor(op1).tensor(op0)
# Evolve on qubits [0, 1, 2]
op_full = op
target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data))
self.assertEqual(state.evolve(op, qargs=[0, 1, 2]), target)
# Evolve on qubits [2, 1, 0]
op_full = op0.tensor(op1).tensor(op2)
target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data))
self.assertEqual(state.evolve(op, qargs=[2, 1, 0]), target)
def test_evolve_qudit_subsystems(self):
"""Test nested evolve calls on qudit subsystems."""
dims = (3, 4, 5)
init = self.rand_rho(np.prod(dims))
ops = [random_unitary((dim,)) for dim in dims]
state = DensityMatrix(init, dims)
for i, op in enumerate(ops):
state = state.evolve(op, [i])
target_op = np.eye(1)
for op in ops:
target_op = np.kron(op.data, target_op)
target = DensityMatrix(np.dot(target_op, init).dot(target_op.conj().T), dims)
self.assertEqual(state, target)
def test_conjugate(self):
"""Test conjugate method."""
for _ in range(10):
rho = self.rand_rho(4)
target = DensityMatrix(np.conj(rho))
state = DensityMatrix(rho).conjugate()
self.assertEqual(state, target)
def test_expand(self):
"""Test expand method."""
for _ in range(10):
rho0 = self.rand_rho(2)
rho1 = self.rand_rho(3)
target = np.kron(rho1, rho0)
state = DensityMatrix(rho0).expand(DensityMatrix(rho1))
self.assertEqual(state.dim, 6)
self.assertEqual(state.dims(), (2, 3))
assert_allclose(state.data, target)
def test_tensor(self):
"""Test tensor method."""
for _ in range(10):
rho0 = self.rand_rho(2)
rho1 = self.rand_rho(3)
target = np.kron(rho0, rho1)
state = DensityMatrix(rho0).tensor(DensityMatrix(rho1))
self.assertEqual(state.dim, 6)
self.assertEqual(state.dims(), (3, 2))
assert_allclose(state.data, target)
def test_add(self):
"""Test add method."""
for _ in range(10):
rho0 = self.rand_rho(4)
rho1 = self.rand_rho(4)
state0 = DensityMatrix(rho0)
state1 = DensityMatrix(rho1)
self.assertEqual(state0 + state1, DensityMatrix(rho0 + rho1))
def test_add_except(self):
"""Test add method raises exceptions."""
state1 = DensityMatrix(self.rand_rho(2))
state2 = DensityMatrix(self.rand_rho(3))
self.assertRaises(QiskitError, state1.__add__, state2)
def test_subtract(self):
"""Test subtract method."""
for _ in range(10):
rho0 = self.rand_rho(4)
rho1 = self.rand_rho(4)
state0 = DensityMatrix(rho0)
state1 = DensityMatrix(rho1)
self.assertEqual(state0 - state1, DensityMatrix(rho0 - rho1))
def test_multiply(self):
"""Test multiply method."""
for _ in range(10):
rho = self.rand_rho(4)
state = DensityMatrix(rho)
val = np.random.rand() + 1j * np.random.rand()
self.assertEqual(val * state, DensityMatrix(val * state))
def test_negate(self):
"""Test negate method"""
for _ in range(10):
rho = self.rand_rho(4)
state = DensityMatrix(rho)
self.assertEqual(-state, DensityMatrix(-1 * rho))
def test_to_dict(self):
"""Test to_dict method"""
with self.subTest(msg="dims = (2, 2)"):
rho = DensityMatrix(np.arange(1, 17).reshape(4, 4))
target = {
"00|00": 1,
"01|00": 2,
"10|00": 3,
"11|00": 4,
"00|01": 5,
"01|01": 6,
"10|01": 7,
"11|01": 8,
"00|10": 9,
"01|10": 10,
"10|10": 11,
"11|10": 12,
"00|11": 13,
"01|11": 14,
"10|11": 15,
"11|11": 16,
}
self.assertDictAlmostEqual(target, rho.to_dict())
with self.subTest(msg="dims = (2, 3)"):
rho = DensityMatrix(np.diag(np.arange(1, 7)), dims=(2, 3))
target = {}
for i in range(2):
for j in range(3):
key = "{1}{0}|{1}{0}".format(i, j)
target[key] = 2 * j + i + 1
self.assertDictAlmostEqual(target, rho.to_dict())
with self.subTest(msg="dims = (2, 11)"):
vec = DensityMatrix(np.diag(np.arange(1, 23)), dims=(2, 11))
target = {}
for i in range(2):
for j in range(11):
key = "{1},{0}|{1},{0}".format(i, j)
target[key] = 2 * j + i + 1
self.assertDictAlmostEqual(target, vec.to_dict())
def test_densitymatrix_to_statevector_pure(self):
"""Test converting a pure density matrix to statevector."""
state = 1 / np.sqrt(2) * (np.array([1, 0, 0, 0, 0, 0, 0, 1]))
psi = Statevector(state)
rho = DensityMatrix(psi)
phi = rho.to_statevector()
self.assertTrue(psi.equiv(phi))
def test_densitymatrix_to_statevector_mixed(self):
"""Test converting a pure density matrix to statevector."""
state_1 = 1 / np.sqrt(2) * (np.array([1, 0, 0, 0, 0, 0, 0, 1]))
state_2 = 1 / np.sqrt(2) * (np.array([0, 0, 0, 0, 0, 0, 1, 1]))
psi = 0.5 * (Statevector(state_1) + Statevector(state_2))
rho = DensityMatrix(psi)
self.assertRaises(QiskitError, rho.to_statevector)
def test_probabilities_product(self):
"""Test probabilities method for product state"""
state = DensityMatrix.from_label("+0")
# 2-qubit qargs
with self.subTest(msg="P(None)"):
probs = state.probabilities()
target = np.array([0.5, 0, 0.5, 0])
self.assertTrue(np.allclose(probs, target))
with self.subTest(msg="P([0, 1])"):
probs = state.probabilities([0, 1])
target = np.array([0.5, 0, 0.5, 0])
self.assertTrue(np.allclose(probs, target))
with self.subTest(msg="P([1, 0]"):
probs = state.probabilities([1, 0])
target = np.array([0.5, 0.5, 0, 0])
self.assertTrue(np.allclose(probs, target))
# 1-qubit qargs
with self.subTest(msg="P([0])"):
probs = state.probabilities([0])
target = np.array([1, 0])
self.assertTrue(np.allclose(probs, target))
with self.subTest(msg="P([1])"):
probs = state.probabilities([1])
target = np.array([0.5, 0.5])
self.assertTrue(np.allclose(probs, target))
def test_probabilities_ghz(self):
"""Test probabilities method for GHZ state"""
psi = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2)
state = DensityMatrix(psi)
# 3-qubit qargs
target = np.array([0.5, 0, 0, 0, 0, 0, 0, 0.5])
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
# 2-qubit qargs
target = np.array([0.5, 0, 0, 0.5])
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
# 1-qubit qargs
target = np.array([0.5, 0.5])
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
def test_probabilities_w(self):
"""Test probabilities method with W state"""
psi = (
Statevector.from_label("001")
+ Statevector.from_label("010")
+ Statevector.from_label("100")
) / np.sqrt(3)
state = DensityMatrix(psi)
# 3-qubit qargs
target = np.array([0, 1 / 3, 1 / 3, 0, 1 / 3, 0, 0, 0])
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
# 2-qubit qargs
target = np.array([1 / 3, 1 / 3, 1 / 3, 0])
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
# 1-qubit qargs
target = np.array([2 / 3, 1 / 3])
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
def test_probabilities_dict_product(self):
"""Test probabilities_dict method for product state"""
state = DensityMatrix.from_label("+0")
# 2-qubit qargs
with self.subTest(msg="P(None)"):
probs = state.probabilities_dict()
target = {"00": 0.5, "10": 0.5}
self.assertDictAlmostEqual(probs, target)
with self.subTest(msg="P([0, 1])"):
probs = state.probabilities_dict([0, 1])
target = {"00": 0.5, "10": 0.5}
self.assertDictAlmostEqual(probs, target)
with self.subTest(msg="P([1, 0]"):
probs = state.probabilities_dict([1, 0])
target = {"00": 0.5, "01": 0.5}
self.assertDictAlmostEqual(probs, target)
# 1-qubit qargs
with self.subTest(msg="P([0])"):
probs = state.probabilities_dict([0])
target = {"0": 1}
self.assertDictAlmostEqual(probs, target)
with self.subTest(msg="P([1])"):
probs = state.probabilities_dict([1])
target = {"0": 0.5, "1": 0.5}
self.assertDictAlmostEqual(probs, target)
def test_probabilities_dict_ghz(self):
"""Test probabilities_dict method for GHZ state"""
psi = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2)
state = DensityMatrix(psi)
# 3-qubit qargs
target = {"000": 0.5, "111": 0.5}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
# 2-qubit qargs
target = {"00": 0.5, "11": 0.5}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
# 1-qubit qargs
target = {"0": 0.5, "1": 0.5}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
def test_probabilities_dict_w(self):
"""Test probabilities_dict method with W state"""
psi = (
Statevector.from_label("001")
+ Statevector.from_label("010")
+ Statevector.from_label("100")
) / np.sqrt(3)
state = DensityMatrix(psi)
# 3-qubit qargs
target = np.array([0, 1 / 3, 1 / 3, 0, 1 / 3, 0, 0, 0])
target = {"001": 1 / 3, "010": 1 / 3, "100": 1 / 3}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
# 2-qubit qargs
target = {"00": 1 / 3, "01": 1 / 3, "10": 1 / 3}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
# 1-qubit qargs
target = {"0": 2 / 3, "1": 1 / 3}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
def test_sample_counts_ghz(self):
"""Test sample_counts method for GHZ state"""
shots = 2000
threshold = 0.02 * shots
state = DensityMatrix(
(Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2)
)
state.seed(100)
# 3-qubit qargs
target = {"000": shots / 2, "111": shots / 2}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
# 2-qubit qargs
target = {"00": shots / 2, "11": shots / 2}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
# 1-qubit qargs
target = {"0": shots / 2, "1": shots / 2}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
def test_sample_counts_w(self):
"""Test sample_counts method for W state"""
shots = 3000
threshold = 0.02 * shots
state = DensityMatrix(
(
Statevector.from_label("001")
+ Statevector.from_label("010")
+ Statevector.from_label("100")
)
/ np.sqrt(3)
)
state.seed(100)
target = {"001": shots / 3, "010": shots / 3, "100": shots / 3}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"P({qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
# 2-qubit qargs
target = {"00": shots / 3, "01": shots / 3, "10": shots / 3}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"P({qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
# 1-qubit qargs
target = {"0": 2 * shots / 3, "1": shots / 3}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"P({qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
def test_probabilities_dict_unequal_dims(self):
"""Test probabilities_dict for a state with unequal subsystem dimensions."""
vec = np.zeros(60, dtype=float)
vec[15:20] = np.ones(5)
vec[40:46] = np.ones(6)
state = DensityMatrix(vec / np.sqrt(11.0), dims=[3, 4, 5])
p = 1.0 / 11.0
self.assertDictEqual(
state.probabilities_dict(),
{
s: p
for s in [
"110",
"111",
"112",
"120",
"121",
"311",
"312",
"320",
"321",
"322",
"330",
]
},
)
# differences due to rounding
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[0]), {"0": 4 * p, "1": 4 * p, "2": 3 * p}, delta=1e-10
)
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[1]), {"1": 5 * p, "2": 5 * p, "3": p}, delta=1e-10
)
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[2]), {"1": 5 * p, "3": 6 * p}, delta=1e-10
)
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[0, 1]),
{"10": p, "11": 2 * p, "12": 2 * p, "20": 2 * p, "21": 2 * p, "22": p, "30": p},
delta=1e-10,
)
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[1, 0]),
{"01": p, "11": 2 * p, "21": 2 * p, "02": 2 * p, "12": 2 * p, "22": p, "03": p},
delta=1e-10,
)
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[0, 2]),
{"10": 2 * p, "11": 2 * p, "12": p, "31": 2 * p, "32": 2 * p, "30": 2 * p},
delta=1e-10,
)
def test_sample_counts_qutrit(self):
"""Test sample_counts method for qutrit state"""
p = 0.3
shots = 1000
threshold = 0.03 * shots
state = DensityMatrix(np.diag([p, 0, 1 - p]))
state.seed(100)
with self.subTest(msg="counts"):
target = {"0": shots * p, "2": shots * (1 - p)}
counts = state.sample_counts(shots=shots)
self.assertDictAlmostEqual(counts, target, threshold)
def test_sample_memory_ghz(self):
"""Test sample_memory method for GHZ state"""
shots = 2000
state = DensityMatrix(
(Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2)
)
state.seed(100)
# 3-qubit qargs
target = {"000": shots / 2, "111": shots / 2}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
# 2-qubit qargs
target = {"00": shots / 2, "11": shots / 2}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
# 1-qubit qargs
target = {"0": shots / 2, "1": shots / 2}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
def test_sample_memory_w(self):
"""Test sample_memory method for W state"""
shots = 3000
state = DensityMatrix(
(
Statevector.from_label("001")
+ Statevector.from_label("010")
+ Statevector.from_label("100")
)
/ np.sqrt(3)
)
state.seed(100)
target = {"001": shots / 3, "010": shots / 3, "100": shots / 3}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
# 2-qubit qargs
target = {"00": shots / 3, "01": shots / 3, "10": shots / 3}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
# 1-qubit qargs
target = {"0": 2 * shots / 3, "1": shots / 3}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
def test_sample_memory_qutrit(self):
"""Test sample_memory method for qutrit state"""
p = 0.3
shots = 1000
state = DensityMatrix(np.diag([p, 0, 1 - p]))
state.seed(100)
with self.subTest(msg="memory"):
memory = state.sample_memory(shots)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), {"0", "2"})
def test_reset_2qubit(self):
"""Test reset method for 2-qubit state"""
state = DensityMatrix(np.diag([0.5, 0, 0, 0.5]))
with self.subTest(msg="reset"):
rho = state.copy()
value = rho.reset()
target = DensityMatrix(np.diag([1, 0, 0, 0]))
self.assertEqual(value, target)
with self.subTest(msg="reset"):
rho = state.copy()
value = rho.reset([0, 1])
target = DensityMatrix(np.diag([1, 0, 0, 0]))
self.assertEqual(value, target)
with self.subTest(msg="reset [0]"):
rho = state.copy()
value = rho.reset([0])
target = DensityMatrix(np.diag([0.5, 0, 0.5, 0]))
self.assertEqual(value, target)
with self.subTest(msg="reset [0]"):
rho = state.copy()
value = rho.reset([1])
target = DensityMatrix(np.diag([0.5, 0.5, 0, 0]))
self.assertEqual(value, target)
def test_reset_qutrit(self):
"""Test reset method for qutrit"""
state = DensityMatrix(np.diag([1, 1, 1]) / 3)
state.seed(200)
value = state.reset()
target = DensityMatrix(np.diag([1, 0, 0]))
self.assertEqual(value, target)
def test_measure_2qubit(self):
"""Test measure method for 2-qubit state"""
state = DensityMatrix.from_label("+0")
seed = 200
shots = 100
with self.subTest(msg="measure"):
for i in range(shots):
rho = state.copy()
rho.seed(seed + i)
outcome, value = rho.measure()
self.assertIn(outcome, ["00", "10"])
if outcome == "00":
target = DensityMatrix.from_label("00")
self.assertEqual(value, target)
else:
target = DensityMatrix.from_label("10")
self.assertEqual(value, target)
with self.subTest(msg="measure [0, 1]"):
for i in range(shots):
rho = state.copy()
outcome, value = rho.measure([0, 1])
self.assertIn(outcome, ["00", "10"])
if outcome == "00":
target = DensityMatrix.from_label("00")
self.assertEqual(value, target)
else:
target = DensityMatrix.from_label("10")
self.assertEqual(value, target)
with self.subTest(msg="measure [1, 0]"):
for i in range(shots):
rho = state.copy()
outcome, value = rho.measure([1, 0])
self.assertIn(outcome, ["00", "01"])
if outcome == "00":
target = DensityMatrix.from_label("00")
self.assertEqual(value, target)
else:
target = DensityMatrix.from_label("10")
self.assertEqual(value, target)
with self.subTest(msg="measure [0]"):
for i in range(shots):
rho = state.copy()
outcome, value = rho.measure([0])
self.assertEqual(outcome, "0")
target = DensityMatrix.from_label("+0")
self.assertEqual(value, target)
with self.subTest(msg="measure [1]"):
for i in range(shots):
rho = state.copy()
outcome, value = rho.measure([1])
self.assertIn(outcome, ["0", "1"])
if outcome == "0":
target = DensityMatrix.from_label("00")
self.assertEqual(value, target)
else:
target = DensityMatrix.from_label("10")
self.assertEqual(value, target)
def test_measure_qutrit(self):
"""Test measure method for qutrit"""
state = DensityMatrix(np.diag([1, 1, 1]) / 3)
seed = 200
shots = 100
for i in range(shots):
rho = state.copy()
rho.seed(seed + i)
outcome, value = rho.measure()
self.assertIn(outcome, ["0", "1", "2"])
if outcome == "0":
target = DensityMatrix(np.diag([1, 0, 0]))
self.assertEqual(value, target)
elif outcome == "1":
target = DensityMatrix(np.diag([0, 1, 0]))
self.assertEqual(value, target)
else:
target = DensityMatrix(np.diag([0, 0, 1]))
self.assertEqual(value, target)
def test_from_int(self):
"""Test from_int method"""
with self.subTest(msg="from_int(0, 4)"):
target = DensityMatrix([1, 0, 0, 0])
value = DensityMatrix.from_int(0, 4)
self.assertEqual(target, value)
with self.subTest(msg="from_int(3, 4)"):
target = DensityMatrix([0, 0, 0, 1])
value = DensityMatrix.from_int(3, 4)
self.assertEqual(target, value)
with self.subTest(msg="from_int(8, (3, 3))"):
target = DensityMatrix([0, 0, 0, 0, 0, 0, 0, 0, 1], dims=(3, 3))
value = DensityMatrix.from_int(8, (3, 3))
self.assertEqual(target, value)
def test_expval(self):
"""Test expectation_value method"""
psi = Statevector([1, 0, 0, 1]) / np.sqrt(2)
rho = DensityMatrix(psi)
for label, target in [
("II", 1),
("XX", 1),
("YY", -1),
("ZZ", 1),
("IX", 0),
("YZ", 0),
("ZX", 0),
("YI", 0),
]:
with self.subTest(msg=f"<{label}>"):
op = Pauli(label)
expval = rho.expectation_value(op)
self.assertAlmostEqual(expval, target)
psi = Statevector([np.sqrt(2), 0, 0, 0, 0, 0, 0, 1 + 1j]) / 2
rho = DensityMatrix(psi)
for label, target in [
("XXX", np.sqrt(2) / 2),
("YYY", -np.sqrt(2) / 2),
("ZZZ", 0),
("XYZ", 0),
("YIY", 0),
]:
with self.subTest(msg=f"<{label}>"):
op = Pauli(label)
expval = rho.expectation_value(op)
self.assertAlmostEqual(expval, target)
labels = ["XXX", "IXI", "YYY", "III"]
coeffs = [3.0, 5.5, -1j, 23]
spp_op = SparsePauliOp.from_list(list(zip(labels, coeffs)))
expval = rho.expectation_value(spp_op)
target = 25.121320343559642 + 0.7071067811865476j
self.assertAlmostEqual(expval, target)
@data(
"II",
"IX",
"IY",
"IZ",
"XI",
"XX",
"XY",
"XZ",
"YI",
"YX",
"YY",
"YZ",
"ZI",
"ZX",
"ZY",
"ZZ",
"-II",
"-IX",
"-IY",
"-IZ",
"-XI",
"-XX",
"-XY",
"-XZ",
"-YI",
"-YX",
"-YY",
"-YZ",
"-ZI",
"-ZX",
"-ZY",
"-ZZ",
"iII",
"iIX",
"iIY",
"iIZ",
"iXI",
"iXX",
"iXY",
"iXZ",
"iYI",
"iYX",
"iYY",
"iYZ",
"iZI",
"iZX",
"iZY",
"iZZ",
"-iII",
"-iIX",
"-iIY",
"-iIZ",
"-iXI",
"-iXX",
"-iXY",
"-iXZ",
"-iYI",
"-iYX",
"-iYY",
"-iYZ",
"-iZI",
"-iZX",
"-iZY",
"-iZZ",
)
def test_expval_pauli_f_contiguous(self, pauli):
"""Test expectation_value method for Pauli op"""
seed = 1020
op = Pauli(pauli)
rho = random_density_matrix(2**op.num_qubits, seed=seed)
rho._data = np.reshape(rho.data.flatten(order="F"), rho.data.shape, order="F")
target = rho.expectation_value(op.to_matrix())
expval = rho.expectation_value(op)
self.assertAlmostEqual(expval, target)
@data(
"II",
"IX",
"IY",
"IZ",
"XI",
"XX",
"XY",
"XZ",
"YI",
"YX",
"YY",
"YZ",
"ZI",
"ZX",
"ZY",
"ZZ",
"-II",
"-IX",
"-IY",
"-IZ",
"-XI",
"-XX",
"-XY",
"-XZ",
"-YI",
"-YX",
"-YY",
"-YZ",
"-ZI",
"-ZX",
"-ZY",
"-ZZ",
"iII",
"iIX",
"iIY",
"iIZ",
"iXI",
"iXX",
"iXY",
"iXZ",
"iYI",
"iYX",
"iYY",
"iYZ",
"iZI",
"iZX",
"iZY",
"iZZ",
"-iII",
"-iIX",
"-iIY",
"-iIZ",
"-iXI",
"-iXX",
"-iXY",
"-iXZ",
"-iYI",
"-iYX",
"-iYY",
"-iYZ",
"-iZI",
"-iZX",
"-iZY",
"-iZZ",
)
def test_expval_pauli_c_contiguous(self, pauli):
"""Test expectation_value method for Pauli op"""
seed = 1020
op = Pauli(pauli)
rho = random_density_matrix(2**op.num_qubits, seed=seed)
rho._data = np.reshape(rho.data.flatten(order="C"), rho.data.shape, order="C")
target = rho.expectation_value(op.to_matrix())
expval = rho.expectation_value(op)
self.assertAlmostEqual(expval, target)
@data([0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1])
def test_expval_pauli_qargs(self, qubits):
"""Test expectation_value method for Pauli op"""
seed = 1020
op = random_pauli(2, seed=seed)
state = random_density_matrix(2**3, seed=seed)
target = state.expectation_value(op.to_matrix(), qubits)
expval = state.expectation_value(op, qubits)
self.assertAlmostEqual(expval, target)
def test_reverse_qargs(self):
"""Test reverse_qargs method"""
circ1 = QFT(5)
circ2 = circ1.reverse_bits()
state1 = DensityMatrix.from_instruction(circ1)
state2 = DensityMatrix.from_instruction(circ2)
self.assertEqual(state1.reverse_qargs(), state2)
@unittest.skipUnless(optionals.HAS_MATPLOTLIB, "requires matplotlib")
@unittest.skipUnless(optionals.HAS_PYLATEX, "requires pylatexenc")
def test_drawings(self):
"""Test draw method"""
qc1 = QFT(5)
dm = DensityMatrix.from_instruction(qc1)
with self.subTest(msg="str(density_matrix)"):
str(dm)
for drawtype in ["repr", "text", "latex", "latex_source", "qsphere", "hinton", "bloch"]:
with self.subTest(msg=f"draw('{drawtype}')"):
dm.draw(drawtype)
def test_density_matrix_partial_transpose(self):
"""Test partial_transpose function on density matrices"""
with self.subTest(msg="separable"):
rho = DensityMatrix.from_label("10+")
rho1 = np.zeros((8, 8), complex)
rho1[4, 4] = 0.5
rho1[4, 5] = 0.5
rho1[5, 4] = 0.5
rho1[5, 5] = 0.5
self.assertEqual(rho.partial_transpose([0, 1]), DensityMatrix(rho1))
self.assertEqual(rho.partial_transpose([0, 2]), DensityMatrix(rho1))
with self.subTest(msg="entangled"):
rho = DensityMatrix([[0, 0, 0, 0], [0, 0.5, -0.5, 0], [0, -0.5, 0.5, 0], [0, 0, 0, 0]])
rho1 = DensityMatrix([[0, 0, 0, -0.5], [0, 0.5, 0, 0], [0, 0, 0.5, 0], [-0.5, 0, 0, 0]])
self.assertEqual(rho.partial_transpose([0]), DensityMatrix(rho1))
self.assertEqual(rho.partial_transpose([1]), DensityMatrix(rho1))
with self.subTest(msg="dims(3,3)"):
mat = np.zeros((9, 9))
mat1 = np.zeros((9, 9))
mat[8, 0] = 1
mat1[0, 8] = 1
rho = DensityMatrix(mat, dims=(3, 3))
rho1 = DensityMatrix(mat1, dims=(3, 3))
self.assertEqual(rho.partial_transpose([0, 1]), rho1)
def test_clip_probabilities(self):
"""Test probabilities are clipped to [0, 1]."""
dm = DensityMatrix([[1.1, 0], [0, 0]])
self.assertEqual(list(dm.probabilities()), [1.0, 0.0])
# The "1" key should be exactly zero and therefore omitted.
self.assertEqual(dm.probabilities_dict(), {"0": 1.0})
def test_round_probabilities(self):
"""Test probabilities are correctly rounded.
This is good to test to ensure clipping, renormalizing and rounding work together.
"""
p = np.sqrt(1 / 3)
amplitudes = [p, p, p, 0]
dm = DensityMatrix(np.outer(amplitudes, amplitudes))
expected = [0.33, 0.33, 0.33, 0]
# Exact floating-point check because fixing the rounding should ensure this is exact.
self.assertEqual(list(dm.probabilities(decimals=2)), expected)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Quick program to test the quantum information states modules."""
import unittest
import numpy as np
from qiskit import QiskitError
from qiskit.test import QiskitTestCase
from qiskit.quantum_info.states import DensityMatrix, Statevector
from qiskit.quantum_info import state_fidelity
from qiskit.quantum_info import purity
from qiskit.quantum_info import entropy
from qiskit.quantum_info import concurrence
from qiskit.quantum_info import entanglement_of_formation
from qiskit.quantum_info import mutual_information
from qiskit.quantum_info.states import shannon_entropy
from qiskit.quantum_info import negativity
class TestStateMeasures(QiskitTestCase):
"""Tests state measure functions"""
def test_state_fidelity_statevector(self):
"""Test state_fidelity function for statevector inputs"""
psi1 = [0.70710678118654746, 0, 0, 0.70710678118654746]
psi2 = [0.0, 0.70710678118654746, 0.70710678118654746, 0.0]
self.assertAlmostEqual(state_fidelity(psi1, psi1), 1.0, places=7, msg="vector-vector input")
self.assertAlmostEqual(state_fidelity(psi2, psi2), 1.0, places=7, msg="vector-vector input")
self.assertAlmostEqual(state_fidelity(psi1, psi2), 0.0, places=7, msg="vector-vector input")
psi1 = Statevector([0.70710678118654746, 0, 0, 0.70710678118654746])
psi2 = Statevector([0.0, 0.70710678118654746, 0.70710678118654746, 0.0])
self.assertAlmostEqual(state_fidelity(psi1, psi1), 1.0, places=7, msg="vector-vector input")
self.assertAlmostEqual(state_fidelity(psi2, psi2), 1.0, places=7, msg="vector-vector input")
self.assertAlmostEqual(state_fidelity(psi1, psi2), 0.0, places=7, msg="vector-vector input")
psi1 = Statevector([1, 0, 0, 1]) # invalid state
psi2 = Statevector([1, 0, 0, 0])
self.assertRaises(QiskitError, state_fidelity, psi1, psi2)
self.assertRaises(QiskitError, state_fidelity, psi1, psi2, validate=True)
self.assertEqual(state_fidelity(psi1, psi2, validate=False), 1)
def test_state_fidelity_density_matrix(self):
"""Test state_fidelity function for density matrix inputs"""
rho1 = [[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]]
mix = [[0.25, 0, 0, 0], [0, 0.25, 0, 0], [0, 0, 0.25, 0], [0, 0, 0, 0.25]]
self.assertAlmostEqual(state_fidelity(rho1, rho1), 1.0, places=7, msg="matrix-matrix input")
self.assertAlmostEqual(state_fidelity(mix, mix), 1.0, places=7, msg="matrix-matrix input")
self.assertAlmostEqual(state_fidelity(rho1, mix), 0.25, places=7, msg="matrix-matrix input")
rho1 = DensityMatrix(rho1)
mix = DensityMatrix(mix)
self.assertAlmostEqual(state_fidelity(rho1, rho1), 1.0, places=7, msg="matrix-matrix input")
self.assertAlmostEqual(state_fidelity(mix, mix), 1.0, places=7, msg="matrix-matrix input")
self.assertAlmostEqual(state_fidelity(rho1, mix), 0.25, places=7, msg="matrix-matrix input")
rho1 = DensityMatrix([1, 0, 0, 0])
mix = DensityMatrix(np.diag([1, 0, 0, 1]))
self.assertRaises(QiskitError, state_fidelity, rho1, mix)
self.assertRaises(QiskitError, state_fidelity, rho1, mix, validate=True)
self.assertEqual(state_fidelity(rho1, mix, validate=False), 1)
def test_state_fidelity_mixed(self):
"""Test state_fidelity function for statevector and density matrix inputs"""
psi1 = Statevector([0.70710678118654746, 0, 0, 0.70710678118654746])
rho1 = DensityMatrix([[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]])
mix = DensityMatrix([[0.25, 0, 0, 0], [0, 0.25, 0, 0], [0, 0, 0.25, 0], [0, 0, 0, 0.25]])
self.assertAlmostEqual(state_fidelity(psi1, rho1), 1.0, places=7, msg="vector-matrix input")
self.assertAlmostEqual(state_fidelity(psi1, mix), 0.25, places=7, msg="vector-matrix input")
self.assertAlmostEqual(state_fidelity(rho1, psi1), 1.0, places=7, msg="matrix-vector input")
def test_purity_statevector(self):
"""Test purity function on statevector inputs"""
psi = Statevector([1, 0, 0, 0])
self.assertEqual(purity(psi), 1)
self.assertEqual(purity(psi, validate=True), 1)
self.assertEqual(purity(psi, validate=False), 1)
psi = [0.70710678118654746, 0.70710678118654746]
self.assertAlmostEqual(purity(psi), 1)
self.assertAlmostEqual(purity(psi, validate=True), 1)
self.assertAlmostEqual(purity(psi, validate=False), 1)
psi = np.array([0.5, 0.5j, -0.5j, -0.5])
self.assertAlmostEqual(purity(psi), 1)
self.assertAlmostEqual(purity(psi, validate=True), 1)
self.assertAlmostEqual(purity(psi, validate=False), 1)
psi = Statevector([1, 0, 0, 1])
self.assertRaises(QiskitError, purity, psi)
self.assertRaises(QiskitError, purity, psi, validate=True)
self.assertEqual(purity(psi, validate=False), 4)
def test_purity_density_matrix(self):
"""Test purity function on density matrix inputs"""
rho = DensityMatrix(np.diag([1, 0, 0, 0]))
self.assertEqual(purity(rho), 1)
self.assertEqual(purity(rho, validate=True), 1)
self.assertEqual(purity(rho, validate=False), 1)
rho = np.diag([0.25, 0.25, 0.25, 0.25])
self.assertEqual(purity(rho), 0.25)
self.assertEqual(purity(rho, validate=True), 0.25)
self.assertEqual(purity(rho, validate=False), 0.25)
rho = [[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]]
self.assertEqual(purity(rho), 1)
self.assertEqual(purity(rho, validate=True), 1)
self.assertEqual(purity(rho, validate=False), 1)
rho = np.diag([1, 0, 0, 1])
self.assertRaises(QiskitError, purity, rho)
self.assertRaises(QiskitError, purity, rho, validate=True)
self.assertEqual(purity(rho, validate=False), 2)
def test_purity_equivalence(self):
"""Test purity is same for equivalent inputs"""
for alpha, beta in [
(0, 0),
(0, 0.25),
(0.25, 0),
(0.33, 0.33),
(0.5, 0.5),
(0.75, 0.25),
(0, 0.75),
]:
psi = Statevector([alpha, beta, 0, 1j * np.sqrt(1 - alpha**2 - beta**2)])
rho = DensityMatrix(psi)
self.assertAlmostEqual(purity(psi), purity(rho))
def test_entropy_statevector(self):
"""Test entropy function on statevector inputs"""
test_psis = [
[1, 0],
[0, 1, 0, 0],
[0.5, 0.5, 0.5, 0.5],
[0.5, 0.5j, -0.5j, 0.5],
[0.70710678118654746, 0, 0, -0.70710678118654746j],
[0.70710678118654746] + (14 * [0]) + [0.70710678118654746j],
]
for psi_ls in test_psis:
self.assertEqual(entropy(psi_ls), 0)
self.assertEqual(entropy(np.array(psi_ls)), 0)
def test_entropy_density_matrix(self):
"""Test entropy function on density matrix inputs"""
# Density matrix input
rhos = [DensityMatrix(np.diag([0.5] + (n * [0]) + [0.5])) for n in range(1, 5)]
for rho in rhos:
self.assertAlmostEqual(entropy(rho), 1)
self.assertAlmostEqual(entropy(rho, base=2), 1)
self.assertAlmostEqual(entropy(rho, base=np.e), -1 * np.log(0.5))
# Array input
for prob in [0.001, 0.3, 0.7, 0.999]:
rho = np.diag([prob, 1 - prob])
self.assertAlmostEqual(entropy(rho), shannon_entropy([prob, 1 - prob]))
self.assertAlmostEqual(
entropy(rho, base=np.e), shannon_entropy([prob, 1 - prob], base=np.e)
)
self.assertAlmostEqual(entropy(rho, base=2), shannon_entropy([prob, 1 - prob], base=2))
# List input
rho = [[0.5, 0], [0, 0.5]]
self.assertAlmostEqual(entropy(rho), 1)
def test_entropy_equivalence(self):
"""Test entropy is same for equivalent inputs"""
for alpha, beta in [
(0, 0),
(0, 0.25),
(0.25, 0),
(0.33, 0.33),
(0.5, 0.5),
(0.75, 0.25),
(0, 0.75),
]:
psi = Statevector([alpha, beta, 0, 1j * np.sqrt(1 - alpha**2 - beta**2)])
rho = DensityMatrix(psi)
self.assertAlmostEqual(entropy(psi), entropy(rho))
def test_concurrence_statevector(self):
"""Test concurrence function on statevector inputs"""
# Statevector input
psi = Statevector([0.70710678118654746, 0, 0, -0.70710678118654746j])
self.assertAlmostEqual(concurrence(psi), 1)
# List input
psi = [1, 0, 0, 0]
self.assertAlmostEqual(concurrence(psi), 0)
# Array input
psi = np.array([0.5, 0.5, 0.5, 0.5])
self.assertAlmostEqual(concurrence(psi), 0)
# Larger than 2 qubit input
psi_ls = [0.70710678118654746] + (14 * [0]) + [0.70710678118654746j]
psi = Statevector(psi_ls, dims=(2, 8))
self.assertAlmostEqual(concurrence(psi), 1)
psi = Statevector(psi_ls, dims=(4, 4))
self.assertAlmostEqual(concurrence(psi), 1)
psi = Statevector(psi_ls, dims=(8, 2))
self.assertAlmostEqual(concurrence(psi), 1)
def test_concurrence_density_matrix(self):
"""Test concurrence function on density matrix inputs"""
# Density matrix input
rho1 = DensityMatrix([[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]])
rho2 = DensityMatrix([[0, 0, 0, 0], [0, 0.5, -0.5j, 0], [0, 0.5j, 0.5, 0], [0, 0, 0, 0]])
self.assertAlmostEqual(concurrence(rho1), 1)
self.assertAlmostEqual(concurrence(rho2), 1)
self.assertAlmostEqual(concurrence(0.5 * rho1 + 0.5 * rho2), 0)
self.assertAlmostEqual(concurrence(0.75 * rho1 + 0.25 * rho2), 0.5)
# List input
rho = [[0.5, 0.5, 0, 0], [0.5, 0.5, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
self.assertEqual(concurrence(rho), 0)
# Array input
rho = np.diag([0.25, 0.25, 0.25, 0.25])
self.assertEqual(concurrence(rho), 0)
def test_concurrence_equivalence(self):
"""Test concurrence is same for equivalent inputs"""
for alpha, beta in [
(0, 0),
(0, 0.25),
(0.25, 0),
(0.33, 0.33),
(0.5, 0.5),
(0.75, 0.25),
(0, 0.75),
]:
psi = Statevector([alpha, beta, 0, 1j * np.sqrt(1 - alpha**2 - beta**2)])
rho = DensityMatrix(psi)
self.assertAlmostEqual(concurrence(psi), concurrence(rho))
def test_entanglement_of_formation_statevector(self):
"""Test entanglement of formation function on statevector inputs"""
# Statevector input
psi = Statevector([0.70710678118654746, 0, 0, -0.70710678118654746j])
self.assertAlmostEqual(entanglement_of_formation(psi), 1)
# List input
psi = [1, 0, 0, 0]
self.assertAlmostEqual(entanglement_of_formation(psi), 0)
# Array input
psi = np.array([0.5, 0.5, 0.5, 0.5])
self.assertAlmostEqual(entanglement_of_formation(psi), 0)
# Larger than 2 qubit input
psi_ls = [0.70710678118654746] + (14 * [0]) + [0.70710678118654746j]
psi = Statevector(psi_ls, dims=(2, 8))
self.assertAlmostEqual(entanglement_of_formation(psi), 1)
psi = Statevector(psi_ls, dims=(4, 4))
self.assertAlmostEqual(entanglement_of_formation(psi), 1)
psi = Statevector(psi_ls, dims=(8, 2))
self.assertAlmostEqual(entanglement_of_formation(psi), 1)
def test_entanglement_of_formation_density_matrix(self):
"""Test entanglement of formation function on density matrix inputs"""
# Density matrix input
rho1 = DensityMatrix([[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]])
rho2 = DensityMatrix([[0, 0, 0, 0], [0, 0.5, -0.5j, 0], [0, 0.5j, 0.5, 0], [0, 0, 0, 0]])
self.assertAlmostEqual(entanglement_of_formation(rho1), 1)
self.assertAlmostEqual(entanglement_of_formation(rho2), 1)
self.assertAlmostEqual(entanglement_of_formation(0.5 * rho1 + 0.5 * rho2), 0)
self.assertAlmostEqual(
entanglement_of_formation(0.75 * rho1 + 0.25 * rho2), 0.35457890266527003
)
# List input
rho = [[0.5, 0.5, 0, 0], [0.5, 0.5, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
self.assertEqual(entanglement_of_formation(rho), 0)
# Array input
rho = np.diag([0.25, 0.25, 0.25, 0.25])
self.assertEqual(entanglement_of_formation(rho), 0)
def test_entanglement_of_formation_equivalence(self):
"""Test entanglement of formation is same for equivalent inputs"""
for alpha, beta in [
(0, 0),
(0, 0.25),
(0.25, 0),
(0.33, 0.33),
(0.5, 0.5),
(0.75, 0.25),
(0, 0.75),
]:
psi = Statevector([alpha, beta, 0, 1j * np.sqrt(1 - alpha**2 - beta**2)])
rho = DensityMatrix(psi)
self.assertAlmostEqual(entanglement_of_formation(psi), entanglement_of_formation(rho))
def test_mutual_information_statevector(self):
"""Test mutual_information function on statevector inputs"""
# Statevector input
psi = Statevector([0.70710678118654746, 0, 0, -0.70710678118654746j])
self.assertAlmostEqual(mutual_information(psi), 2)
# List input
psi = [1, 0, 0, 0]
self.assertAlmostEqual(mutual_information(psi), 0)
# Array input
psi = np.array([0.5, 0.5, 0.5, 0.5])
self.assertAlmostEqual(mutual_information(psi), 0)
# Larger than 2 qubit input
psi_ls = [0.70710678118654746] + (14 * [0]) + [0.70710678118654746j]
psi = Statevector(psi_ls, dims=(2, 8))
self.assertAlmostEqual(mutual_information(psi), 2)
psi = Statevector(psi_ls, dims=(4, 4))
self.assertAlmostEqual(mutual_information(psi), 2)
psi = Statevector(psi_ls, dims=(8, 2))
self.assertAlmostEqual(mutual_information(psi), 2)
def test_mutual_information_density_matrix(self):
"""Test mutual_information function on density matrix inputs"""
# Density matrix input
rho1 = DensityMatrix([[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]])
rho2 = DensityMatrix([[0, 0, 0, 0], [0, 0.5, -0.5j, 0], [0, 0.5j, 0.5, 0], [0, 0, 0, 0]])
self.assertAlmostEqual(mutual_information(rho1), 2)
self.assertAlmostEqual(mutual_information(rho2), 2)
# List input
rho = [[0.5, 0.5, 0, 0], [0.5, 0.5, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
self.assertEqual(mutual_information(rho), 0)
# Array input
rho = np.diag([0.25, 0.25, 0.25, 0.25])
self.assertEqual(mutual_information(rho), 0)
def test_mutual_information_equivalence(self):
"""Test mutual_information is same for equivalent inputs"""
for alpha, beta in [
(0, 0),
(0, 0.25),
(0.25, 0),
(0.33, 0.33),
(0.5, 0.5),
(0.75, 0.25),
(0, 0.75),
]:
psi = Statevector([alpha, beta, 0, 1j * np.sqrt(1 - alpha**2 - beta**2)])
rho = DensityMatrix(psi)
self.assertAlmostEqual(mutual_information(psi), mutual_information(rho))
def test_negativity_statevector(self):
"""Test negativity function on statevector inputs"""
# Constructing separable quantum statevector
state = Statevector([1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0])
negv = negativity(state, [0])
self.assertAlmostEqual(negv, 0, places=7)
# Constructing entangled quantum statevector
state = Statevector([0, 1 / np.sqrt(2), -1 / np.sqrt(2), 0])
negv = negativity(state, [1])
self.assertAlmostEqual(negv, 0.5, places=7)
def test_negativity_density_matrix(self):
"""Test negativity function on density matrix inputs"""
# Constructing separable quantum state
rho = DensityMatrix.from_label("10+")
negv = negativity(rho, [0, 1])
self.assertAlmostEqual(negv, 0, places=7)
negv = negativity(rho, [0, 2])
self.assertAlmostEqual(negv, 0, places=7)
# Constructing entangled quantum state
rho = DensityMatrix([[0, 0, 0, 0], [0, 0.5, -0.5, 0], [0, -0.5, 0.5, 0], [0, 0, 0, 0]])
negv = negativity(rho, [0])
self.assertAlmostEqual(negv, 0.5, places=7)
negv = negativity(rho, [1])
self.assertAlmostEqual(negv, 0.5, places=7)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for Stabilizerstate quantum state class."""
import unittest
from test import combine
import logging
from ddt import ddt, data, unpack
import numpy as np
from qiskit.test import QiskitTestCase
from qiskit import QuantumCircuit
from qiskit.quantum_info.random import random_clifford, random_pauli
from qiskit.quantum_info.states import StabilizerState, Statevector
from qiskit.circuit.library import IGate, XGate, HGate
from qiskit.quantum_info.operators import Clifford, Pauli, Operator
logger = logging.getLogger(__name__)
@ddt
class TestStabilizerState(QiskitTestCase):
"""Tests for StabilizerState class."""
rng = np.random.default_rng(12345)
samples = 10
shots = 1000
threshold = 0.1 * shots
@combine(num_qubits=[2, 3, 4, 5])
def test_init_clifford(self, num_qubits):
"""Test initialization from Clifford."""
stab1 = StabilizerState(random_clifford(num_qubits, seed=self.rng))
stab2 = StabilizerState(stab1)
self.assertEqual(stab1, stab2)
@combine(num_qubits=[2, 3, 4, 5])
def test_init_circuit(self, num_qubits):
"""Test initialization from a Clifford circuit."""
cliff = random_clifford(num_qubits, seed=self.rng)
stab1 = StabilizerState(cliff.to_circuit())
stab2 = StabilizerState(cliff)
self.assertEqual(stab1, stab2)
@combine(num_qubits=[2, 3, 4, 5])
def test_init_instruction(self, num_qubits):
"""Test initialization from a Clifford instruction."""
cliff = random_clifford(num_qubits, seed=self.rng)
stab1 = StabilizerState(cliff.to_instruction())
stab2 = StabilizerState(cliff)
self.assertEqual(stab1, stab2)
@combine(num_qubits=[2, 3, 4, 5])
def test_init_pauli(self, num_qubits):
"""Test initialization from pauli."""
pauli = random_pauli(num_qubits, seed=self.rng)
stab1 = StabilizerState(pauli)
stab2 = StabilizerState(stab1)
self.assertEqual(stab1, stab2)
@combine(num_qubits=[2, 3, 4, 5])
def test_to_operator(self, num_qubits):
"""Test to_operator method for returning projector."""
for _ in range(self.samples):
stab = StabilizerState(random_clifford(num_qubits, seed=self.rng))
target = Operator(stab)
op = StabilizerState(stab).to_operator()
self.assertEqual(op, target)
@combine(num_qubits=[2, 3, 4])
def test_trace(self, num_qubits):
"""Test trace methods"""
stab = StabilizerState(random_clifford(num_qubits, seed=self.rng))
trace = stab.trace()
self.assertEqual(trace, 1.0)
@combine(num_qubits=[2, 3, 4])
def test_purity(self, num_qubits):
"""Test purity methods"""
stab = StabilizerState(random_clifford(num_qubits, seed=self.rng))
purity = stab.purity()
self.assertEqual(purity, 1.0)
@combine(num_qubits=[2, 3])
def test_conjugate(self, num_qubits):
"""Test conjugate method."""
for _ in range(self.samples):
cliff = random_clifford(num_qubits, seed=self.rng)
target = StabilizerState(cliff.conjugate())
state = StabilizerState(cliff).conjugate()
self.assertEqual(state, target)
def test_tensor(self):
"""Test tensor method."""
for _ in range(self.samples):
cliff1 = random_clifford(2, seed=self.rng)
cliff2 = random_clifford(3, seed=self.rng)
stab1 = StabilizerState(cliff1)
stab2 = StabilizerState(cliff2)
target = StabilizerState(cliff1.tensor(cliff2))
state = stab1.tensor(stab2)
self.assertEqual(state, target)
def test_expand(self):
"""Test expand method."""
for _ in range(self.samples):
cliff1 = random_clifford(2, seed=self.rng)
cliff2 = random_clifford(3, seed=self.rng)
stab1 = StabilizerState(cliff1)
stab2 = StabilizerState(cliff2)
target = StabilizerState(cliff1.expand(cliff2))
state = stab1.expand(stab2)
self.assertEqual(state, target)
@combine(num_qubits=[2, 3, 4])
def test_evolve(self, num_qubits):
"""Test evolve method."""
for _ in range(self.samples):
cliff1 = random_clifford(num_qubits, seed=self.rng)
cliff2 = random_clifford(num_qubits, seed=self.rng)
stab1 = StabilizerState(cliff1)
stab2 = StabilizerState(cliff2)
target = StabilizerState(cliff1.compose(cliff2))
state = stab1.evolve(stab2)
self.assertEqual(state, target)
@combine(num_qubits_1=[4, 5, 6], num_qubits_2=[1, 2, 3])
def test_evolve_subsystem(self, num_qubits_1, num_qubits_2):
"""Test subsystem evolve method."""
for _ in range(self.samples):
cliff1 = random_clifford(num_qubits_1, seed=self.rng)
cliff2 = random_clifford(num_qubits_2, seed=self.rng)
stab1 = StabilizerState(cliff1)
stab2 = StabilizerState(cliff2)
qargs = sorted(np.random.choice(range(num_qubits_1), num_qubits_2, replace=False))
target = StabilizerState(cliff1.compose(cliff2, qargs))
state = stab1.evolve(stab2, qargs)
self.assertEqual(state, target)
def test_measure_single_qubit(self):
"""Test a measurement of a single qubit"""
for _ in range(self.samples):
cliff = Clifford(XGate())
stab = StabilizerState(cliff)
value = stab.measure()[0]
self.assertEqual(value, "1")
cliff = Clifford(IGate())
stab = StabilizerState(cliff)
value = stab.measure()[0]
self.assertEqual(value, "0")
cliff = Clifford(HGate())
stab = StabilizerState(cliff)
value = stab.measure()[0]
self.assertIn(value, ["0", "1"])
def test_measure_qubits(self):
"""Test a measurement of a subsystem of qubits"""
for _ in range(self.samples):
num_qubits = 4
qc = QuantumCircuit(num_qubits)
stab = StabilizerState(qc)
value = stab.measure()[0]
self.assertEqual(value, "0000")
value = stab.measure([0, 2])[0]
self.assertEqual(value, "00")
value = stab.measure([1])[0]
self.assertEqual(value, "0")
for i in range(num_qubits):
qc.x(i)
stab = StabilizerState(qc)
value = stab.measure()[0]
self.assertEqual(value, "1111")
value = stab.measure([2, 0])[0]
self.assertEqual(value, "11")
value = stab.measure([1])[0]
self.assertEqual(value, "1")
qc = QuantumCircuit(num_qubits)
qc.h(0)
stab = StabilizerState(qc)
value = stab.measure()[0]
self.assertIn(value, ["0000", "0001"])
value = stab.measure([0, 1])[0]
self.assertIn(value, ["00", "01"])
value = stab.measure([2])[0]
self.assertEqual(value, "0")
qc = QuantumCircuit(num_qubits)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
stab = StabilizerState(qc)
value = stab.measure()[0]
self.assertIn(value, ["0000", "1111"])
value = stab.measure([3, 1])[0]
self.assertIn(value, ["00", "11"])
value = stab.measure([2])[0]
self.assertIn(value, ["0", "1"])
def test_reset_single_qubit(self):
"""Test reset method of a single qubit"""
empty_qc = QuantumCircuit(1)
for _ in range(self.samples):
cliff = Clifford(XGate())
stab = StabilizerState(cliff)
value = stab.reset([0])
target = StabilizerState(empty_qc)
self.assertEqual(value, target)
cliff = Clifford(HGate())
stab = StabilizerState(cliff)
value = stab.reset([0])
target = StabilizerState(empty_qc)
self.assertEqual(value, target)
def test_reset_qubits(self):
"""Test reset method of a subsystem of qubits"""
num_qubits = 3
qc = QuantumCircuit(num_qubits)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
for _ in range(self.samples):
with self.subTest(msg="reset (None)"):
stab = StabilizerState(qc)
res = stab.reset()
value = res.measure()[0]
self.assertEqual(value, "000")
for _ in range(self.samples):
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"reset (qargs={qargs})"):
stab = StabilizerState(qc)
res = stab.reset(qargs)
value = res.measure()[0]
self.assertEqual(value, "000")
for _ in range(self.samples):
with self.subTest(msg="reset ([0])"):
stab = StabilizerState(qc)
res = stab.reset([0])
value = res.measure()[0]
self.assertIn(value, ["000", "110"])
for _ in range(self.samples):
with self.subTest(msg="reset ([1])"):
stab = StabilizerState(qc)
res = stab.reset([1])
value = res.measure()[0]
self.assertIn(value, ["000", "101"])
for _ in range(self.samples):
with self.subTest(msg="reset ([2])"):
stab = StabilizerState(qc)
res = stab.reset([2])
value = res.measure()[0]
self.assertIn(value, ["000", "011"])
for _ in range(self.samples):
for qargs in [[0, 1], [1, 0]]:
with self.subTest(msg=f"reset (qargs={qargs})"):
stab = StabilizerState(qc)
res = stab.reset(qargs)
value = res.measure()[0]
self.assertIn(value, ["000", "100"])
for _ in range(self.samples):
for qargs in [[0, 2], [2, 0]]:
with self.subTest(msg=f"reset (qargs={qargs})"):
stab = StabilizerState(qc)
res = stab.reset(qargs)
value = res.measure()[0]
self.assertIn(value, ["000", "010"])
for _ in range(self.samples):
for qargs in [[1, 2], [2, 1]]:
with self.subTest(msg=f"reset (qargs={qargs})"):
stab = StabilizerState(qc)
res = stab.reset(qargs)
value = res.measure()[0]
self.assertIn(value, ["000", "001"])
def test_probablities_dict_single_qubit(self):
"""Test probabilities and probabilities_dict methods of a single qubit"""
num_qubits = 1
qc = QuantumCircuit(num_qubits)
for _ in range(self.samples):
with self.subTest(msg="P(id(0))"):
stab = StabilizerState(qc)
value = stab.probabilities_dict()
target = {"0": 1}
self.assertEqual(value, target)
probs = stab.probabilities()
target = np.array([1, 0])
self.assertTrue(np.allclose(probs, target))
qc.x(0)
for _ in range(self.samples):
with self.subTest(msg="P(x(0))"):
stab = StabilizerState(qc)
value = stab.probabilities_dict()
target = {"1": 1}
self.assertEqual(value, target)
probs = stab.probabilities()
target = np.array([0, 1])
self.assertTrue(np.allclose(probs, target))
qc = QuantumCircuit(num_qubits)
qc.h(0)
for _ in range(self.samples):
with self.subTest(msg="P(h(0))"):
stab = StabilizerState(qc)
value = stab.probabilities_dict()
target = {"0": 0.5, "1": 0.5}
self.assertEqual(value, target)
probs = stab.probabilities()
target = np.array([0.5, 0.5])
self.assertTrue(np.allclose(probs, target))
def test_probablities_dict_two_qubits(self):
"""Test probabilities and probabilities_dict methods of two qubits"""
num_qubits = 2
qc = QuantumCircuit(num_qubits)
qc.h(0)
stab = StabilizerState(qc)
for _ in range(self.samples):
with self.subTest(msg="P(None)"):
value = stab.probabilities_dict()
target = {"00": 0.5, "01": 0.5}
self.assertEqual(value, target)
probs = stab.probabilities()
target = np.array([0.5, 0.5, 0, 0])
self.assertTrue(np.allclose(probs, target))
for _ in range(self.samples):
with self.subTest(msg="P([0, 1])"):
value = stab.probabilities_dict([0, 1])
target = {"00": 0.5, "01": 0.5}
self.assertEqual(value, target)
probs = stab.probabilities([0, 1])
target = np.array([0.5, 0.5, 0, 0])
self.assertTrue(np.allclose(probs, target))
for _ in range(self.samples):
with self.subTest(msg="P([1, 0])"):
value = stab.probabilities_dict([1, 0])
target = {"00": 0.5, "10": 0.5}
self.assertEqual(value, target)
probs = stab.probabilities([1, 0])
target = np.array([0.5, 0, 0.5, 0])
self.assertTrue(np.allclose(probs, target))
for _ in range(self.samples):
with self.subTest(msg="P[0]"):
value = stab.probabilities_dict([0])
target = {"0": 0.5, "1": 0.5}
self.assertEqual(value, target)
probs = stab.probabilities([0])
target = np.array([0.5, 0.5])
self.assertTrue(np.allclose(probs, target))
for _ in range(self.samples):
with self.subTest(msg="P([1])"):
value = stab.probabilities_dict([1])
target = {"0": 1.0}
self.assertEqual(value, target)
probs = stab.probabilities([1])
target = np.array([1, 0])
self.assertTrue(np.allclose(probs, target))
def test_probablities_dict_qubits(self):
"""Test probabilities and probabilities_dict methods of a subsystem of qubits"""
num_qubits = 3
qc = QuantumCircuit(num_qubits)
qc.h(0)
qc.h(1)
qc.h(2)
stab = StabilizerState(qc)
for _ in range(self.samples):
with self.subTest(msg="P(None), decimals=1"):
value = stab.probabilities_dict(decimals=1)
target = {
"000": 0.1,
"001": 0.1,
"010": 0.1,
"011": 0.1,
"100": 0.1,
"101": 0.1,
"110": 0.1,
"111": 0.1,
}
self.assertEqual(value, target)
probs = stab.probabilities(decimals=1)
target = np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
self.assertTrue(np.allclose(probs, target))
for _ in range(self.samples):
with self.subTest(msg="P(None), decimals=2"):
value = stab.probabilities_dict(decimals=2)
target = {
"000": 0.12,
"001": 0.12,
"010": 0.12,
"011": 0.12,
"100": 0.12,
"101": 0.12,
"110": 0.12,
"111": 0.12,
}
self.assertEqual(value, target)
probs = stab.probabilities(decimals=2)
target = np.array([0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12])
self.assertTrue(np.allclose(probs, target))
for _ in range(self.samples):
with self.subTest(msg="P(None), decimals=3"):
value = stab.probabilities_dict(decimals=3)
target = {
"000": 0.125,
"001": 0.125,
"010": 0.125,
"011": 0.125,
"100": 0.125,
"101": 0.125,
"110": 0.125,
"111": 0.125,
}
self.assertEqual(value, target)
probs = stab.probabilities(decimals=3)
target = np.array([0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125])
self.assertTrue(np.allclose(probs, target))
def test_probablities_dict_ghz(self):
"""Test probabilities and probabilities_dict method of a subsystem of qubits"""
num_qubits = 3
qc = QuantumCircuit(num_qubits)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
with self.subTest(msg="P(None)"):
stab = StabilizerState(qc)
value = stab.probabilities_dict()
target = {"000": 0.5, "111": 0.5}
self.assertEqual(value, target)
probs = stab.probabilities()
target = np.array([0.5, 0, 0, 0, 0, 0, 0, 0.5])
self.assertTrue(np.allclose(probs, target))
# 3-qubit qargs
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = stab.probabilities_dict(qargs)
target = {"000": 0.5, "111": 0.5}
self.assertDictAlmostEqual(probs, target)
probs = stab.probabilities(qargs)
target = np.array([0.5, 0, 0, 0, 0, 0, 0, 0.5])
self.assertTrue(np.allclose(probs, target))
# 2-qubit qargs
for qargs in [[0, 1], [2, 1], [1, 0], [1, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = stab.probabilities_dict(qargs)
target = {"00": 0.5, "11": 0.5}
self.assertDictAlmostEqual(probs, target)
probs = stab.probabilities(qargs)
target = np.array([0.5, 0, 0, 0.5])
self.assertTrue(np.allclose(probs, target))
# 1-qubit qargs
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"P({qargs})"):
probs = stab.probabilities_dict(qargs)
target = {"0": 0.5, "1": 0.5}
self.assertDictAlmostEqual(probs, target)
probs = stab.probabilities(qargs)
target = np.array([0.5, 0.5])
self.assertTrue(np.allclose(probs, target))
@combine(num_qubits=[2, 3, 4])
def test_probs_random_subsystem(self, num_qubits):
"""Test probabilities and probabilities_dict methods
of random cliffords for a subsystem of qubits"""
for _ in range(self.samples):
for subsystem_size in range(1, num_qubits):
cliff = random_clifford(num_qubits, seed=self.rng)
qargs = np.random.choice(num_qubits, size=subsystem_size, replace=False)
qc = cliff.to_circuit()
stab = StabilizerState(cliff)
probs = stab.probabilities(qargs)
probs_dict = stab.probabilities_dict(qargs)
target = Statevector(qc).probabilities(qargs)
target_dict = Statevector(qc).probabilities_dict(qargs)
self.assertTrue(np.allclose(probs, target))
self.assertDictAlmostEqual(probs_dict, target_dict)
@combine(num_qubits=[2, 3, 4, 5])
def test_expval_from_random_clifford(self, num_qubits):
"""Test that the expectation values for a random Clifford,
where the Pauli operators are all its stabilizers,
are equal to 1."""
for _ in range(self.samples):
cliff = random_clifford(num_qubits, seed=self.rng)
qc = cliff.to_circuit()
stab = StabilizerState(qc)
stab_gen = stab.clifford.to_dict()["stabilizer"]
for i in range(num_qubits):
op = Pauli(stab_gen[i])
exp_val = stab.expectation_value(op)
self.assertEqual(exp_val, 1)
def test_sample_counts_reset_bell(self):
"""Test sample_counts after reset for Bell state"""
num_qubits = 2
qc = QuantumCircuit(num_qubits)
qc.h(0)
qc.cx(0, 1)
stab = StabilizerState(qc)
target = {"00": self.shots / 2, "10": self.shots / 2}
counts = {"00": 0, "10": 0}
for _ in range(self.shots):
res = stab.reset([0])
value = res.measure()[0]
counts[value] += 1
self.assertDictAlmostEqual(counts, target, self.threshold)
target = {"00": self.shots / 2, "01": self.shots / 2}
counts = {"00": 0, "01": 0}
for _ in range(self.shots):
res = stab.reset([1])
value = res.measure()[0]
counts[value] += 1
self.assertDictAlmostEqual(counts, target, self.threshold)
def test_sample_counts_memory_ghz(self):
"""Test sample_counts and sample_memory method for GHZ state"""
num_qubits = 3
qc = QuantumCircuit(num_qubits)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
stab = StabilizerState(qc)
# 3-qubit qargs
target = {"000": self.shots / 2, "111": self.shots / 2}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = stab.sample_counts(self.shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, self.threshold)
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = stab.sample_memory(self.shots, qargs=qargs)
self.assertEqual(len(memory), self.shots)
self.assertEqual(set(memory), set(target))
# 2-qubit qargs
target = {"00": self.shots / 2, "11": self.shots / 2}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 0]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = stab.sample_counts(self.shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, self.threshold)
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = stab.sample_memory(self.shots, qargs=qargs)
self.assertEqual(len(memory), self.shots)
self.assertEqual(set(memory), set(target))
# 1-qubit qargs
target = {"0": self.shots / 2, "1": self.shots / 2}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = stab.sample_counts(self.shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, self.threshold)
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = stab.sample_memory(self.shots, qargs=qargs)
self.assertEqual(len(memory), self.shots)
self.assertEqual(set(memory), set(target))
def test_sample_counts_memory_superposition(self):
"""Test sample_counts and sample_memory method of a 3-qubit superposition"""
num_qubits = 3
qc = QuantumCircuit(num_qubits)
qc.h(0)
qc.h(1)
qc.h(2)
stab = StabilizerState(qc)
# 3-qubit qargs
target = {
"000": self.shots / 8,
"001": self.shots / 8,
"010": self.shots / 8,
"011": self.shots / 8,
"100": self.shots / 8,
"101": self.shots / 8,
"110": self.shots / 8,
"111": self.shots / 8,
}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = stab.sample_counts(self.shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, self.threshold)
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = stab.sample_memory(self.shots, qargs=qargs)
self.assertEqual(len(memory), self.shots)
self.assertEqual(set(memory), set(target))
# 2-qubit qargs
target = {
"00": self.shots / 4,
"01": self.shots / 4,
"10": self.shots / 4,
"11": self.shots / 4,
}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 0]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = stab.sample_counts(self.shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, self.threshold)
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = stab.sample_memory(self.shots, qargs=qargs)
self.assertEqual(len(memory), self.shots)
self.assertEqual(set(memory), set(target))
# 1-qubit qargs
target = {"0": self.shots / 2, "1": self.shots / 2}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = stab.sample_counts(self.shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, self.threshold)
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = stab.sample_memory(self.shots, qargs=qargs)
self.assertEqual(len(memory), self.shots)
self.assertEqual(set(memory), set(target))
@ddt
class TestStabilizerStateExpectationValue(QiskitTestCase):
"""Tests for StabilizerState.expectation_value method."""
rng = np.random.default_rng(12345)
samples = 10
shots = 1000
threshold = 0.1 * shots
@data(("Z", 1), ("X", 0), ("Y", 0), ("I", 1), ("Z", 1), ("-Z", -1), ("iZ", 1j), ("-iZ", -1j))
@unpack
def test_expval_single_qubit_0(self, label, target):
"""Test expectation_value method of a single qubit on |0>"""
qc = QuantumCircuit(1)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(("Z", -1), ("X", 0), ("Y", 0), ("I", 1))
@unpack
def test_expval_single_qubit_1(self, label, target):
"""Test expectation_value method of a single qubit on |1>"""
qc = QuantumCircuit(1)
qc.x(0)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(("Z", 0), ("X", 1), ("Y", 0), ("I", 1), ("X", 1), ("-X", -1), ("iX", 1j), ("-iX", -1j))
@unpack
def test_expval_single_qubit_plus(self, label, target):
"""Test expectation_value method of a single qubit on |+>"""
qc = QuantumCircuit(1)
qc.h(0)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(
("II", 1),
("XX", 0),
("YY", 0),
("ZZ", 1),
("IX", 0),
("IY", 0),
("IZ", 1),
("XY", 0),
("XZ", 0),
("YZ", 0),
("-ZZ", -1),
("iZZ", 1j),
("-iZZ", -1j),
)
@unpack
def test_expval_two_qubits_00(self, label, target):
"""Test expectation_value method of two qubits in |00>"""
num_qubits = 2
qc = QuantumCircuit(num_qubits)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(
("II", 1),
("XX", 0),
("YY", 0),
("ZZ", 1),
("IX", 0),
("IY", 0),
("IZ", -1),
("XY", 0),
("XZ", 0),
("YZ", 0),
)
@unpack
def test_expval_two_qubits_11(self, label, target):
"""Test expectation_value method of two qubits in |11>"""
qc = QuantumCircuit(2)
qc.x(0)
qc.x(1)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(
("II", 1),
("XX", 1),
("YY", 0),
("ZZ", 0),
("IX", 1),
("IY", 0),
("IZ", 0),
("XY", 0),
("XZ", 0),
("YZ", 0),
("-XX", -1),
("iXX", 1j),
("-iXX", -1j),
)
@unpack
def test_expval_two_qubits_plusplus(self, label, target):
"""Test expectation_value method of two qubits in |++>"""
qc = QuantumCircuit(2)
qc.h(0)
qc.h(1)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(
("II", 1),
("XX", 0),
("YY", 0),
("ZZ", 0),
("IX", 0),
("IY", 0),
("IZ", -1),
("XY", 0),
("XZ", -1),
("YZ", 0),
)
@unpack
def test_expval_two_qubits_plus1(self, label, target):
"""Test expectation_value method of two qubits in |+1>"""
qc = QuantumCircuit(2)
qc.x(0)
qc.h(1)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(
("II", 1),
("XX", 1),
("YY", -1),
("ZZ", 1),
("IX", 0),
("IY", 0),
("IZ", 0),
("XY", 0),
("XZ", 0),
("YZ", 0),
("-YY", 1),
("iYY", -1j),
("-iYY", 1j),
)
@unpack
def test_expval_two_qubits_bell_phi_plus(self, label, target):
"""Test expectation_value method of two qubits in bell phi plus"""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(
("II", 1),
("XX", 1),
("YY", 1),
("ZZ", -1),
("IX", 0),
("IY", 0),
("IZ", 0),
("XY", 0),
("XZ", 0),
("YZ", 0),
("-XX", -1),
("-YY", -1),
("iXX", 1j),
("iYY", 1j),
("-iXX", -1j),
("-iYY", -1j),
)
@unpack
def test_expval_two_qubits_bell_phi_minus(self, label, target):
"""Test expectation_value method of two qubits in bell phi minus"""
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
qc.cx(0, 1)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(
("II", 1),
("XX", 1),
("YY", 1),
("ZZ", -1),
("IX", 0),
("IY", 0),
("IZ", 0),
("XY", 0),
("XZ", 0),
("YZ", 0),
("-XX", -1),
("-YY", -1),
("iXX", 1j),
("iYY", 1j),
("-iXX", -1j),
("-iYY", -1j),
)
@unpack
def test_expval_two_qubits_bell_sdg_h(self, label, target):
"""Test expectation_value method of two qubits in bell followed by sdg and h"""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.sdg(0)
qc.sdg(1)
qc.h(0)
qc.h(1)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@combine(num_qubits=[2, 3, 4, 5])
def test_expval_random(self, num_qubits):
"""Test expectation_value method of random Cliffords"""
for _ in range(self.samples):
cliff = random_clifford(num_qubits, seed=self.rng)
op = random_pauli(num_qubits, group_phase=True, seed=self.rng)
qc = cliff.to_circuit()
stab = StabilizerState(cliff)
exp_val = stab.expectation_value(op)
target = Statevector(qc).expectation_value(op)
self.assertAlmostEqual(exp_val, target)
@combine(num_qubits=[2, 3, 4, 5])
def test_expval_random_subsystem(self, num_qubits):
"""Test expectation_value method of random Cliffords and a subsystem"""
for _ in range(self.samples):
cliff = random_clifford(num_qubits, seed=self.rng)
op = random_pauli(2, group_phase=True, seed=self.rng)
qargs = np.random.choice(num_qubits, size=2, replace=False)
qc = cliff.to_circuit()
stab = StabilizerState(cliff)
exp_val = stab.expectation_value(op, qargs)
target = Statevector(qc).expectation_value(op, qargs)
self.assertAlmostEqual(exp_val, target)
def test_stabilizer_bell_equiv(self):
"""Test that two circuits produce the same stabilizer group."""
qc1 = QuantumCircuit(2)
qc1.h(0)
qc1.x(1)
qc1.cx(0, 1)
qc2 = QuantumCircuit(2)
qc2.h(0)
qc2.cx(0, 1)
qc2.sdg(0)
qc2.sdg(1)
qc2.h(0)
qc2.h(1)
qc3 = QuantumCircuit(2)
qc3.h(0)
qc3.cx(0, 1)
qc4 = QuantumCircuit(2)
qc4.h(0)
qc4.cx(0, 1)
qc4.s(0)
qc4.sdg(1)
qc4.h(0)
qc4.h(1)
cliff1 = StabilizerState(qc1) # ['+XX', '-ZZ']
cliff2 = StabilizerState(qc2) # ['+YY', '+XX']
cliff3 = StabilizerState(qc3) # ['+XX', '+ZZ']
cliff4 = StabilizerState(qc4) # ['-YY', '+XX']
# [XX, -ZZ] and [XX, YY] both generate the stabilizer group {II, XX, YY, -ZZ}
self.assertTrue(cliff1.equiv(cliff2))
self.assertEqual(cliff1.probabilities_dict(), cliff2.probabilities_dict())
# [XX, ZZ] and [XX, -YY] both generate the stabilizer group {II, XX, -YY, ZZ}
self.assertTrue(cliff3.equiv(cliff4))
self.assertEqual(cliff3.probabilities_dict(), cliff4.probabilities_dict())
self.assertFalse(cliff1.equiv(cliff3))
self.assertFalse(cliff2.equiv(cliff4))
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for Statevector quantum state class."""
import unittest
import logging
from itertools import permutations
from ddt import ddt, data
import numpy as np
from numpy.testing import assert_allclose
from qiskit.test import QiskitTestCase
from qiskit import QiskitError
from qiskit import QuantumRegister, QuantumCircuit
from qiskit import transpile
from qiskit.circuit.library import HGate, QFT, GlobalPhaseGate
from qiskit.providers.basicaer import QasmSimulatorPy
from qiskit.utils import optionals
from qiskit.quantum_info.random import random_unitary, random_statevector, random_pauli
from qiskit.quantum_info.states import Statevector
from qiskit.quantum_info.operators.operator import Operator
from qiskit.quantum_info.operators.symplectic import Pauli, SparsePauliOp
from qiskit.quantum_info.operators.predicates import matrix_equal
from qiskit.visualization.state_visualization import numbers_to_latex_terms, state_to_latex
logger = logging.getLogger(__name__)
@ddt
class TestStatevector(QiskitTestCase):
"""Tests for Statevector class."""
@classmethod
def rand_vec(cls, n, normalize=False):
"""Return complex vector or statevector"""
seed = np.random.randint(0, np.iinfo(np.int32).max)
logger.debug("rand_vec default_rng seeded with seed=%s", seed)
rng = np.random.default_rng(seed)
vec = rng.random(n) + 1j * rng.random(n)
if normalize:
vec /= np.sqrt(np.dot(vec, np.conj(vec)))
return vec
def test_init_array_qubit(self):
"""Test subsystem initialization from N-qubit array."""
# Test automatic inference of qubit subsystems
vec = self.rand_vec(8)
for dims in [None, 8]:
state = Statevector(vec, dims=dims)
assert_allclose(state.data, vec)
self.assertEqual(state.dim, 8)
self.assertEqual(state.dims(), (2, 2, 2))
self.assertEqual(state.num_qubits, 3)
def test_init_array(self):
"""Test initialization from array."""
vec = self.rand_vec(3)
state = Statevector(vec)
assert_allclose(state.data, vec)
self.assertEqual(state.dim, 3)
self.assertEqual(state.dims(), (3,))
self.assertIsNone(state.num_qubits)
vec = self.rand_vec(2 * 3 * 4)
state = Statevector(vec, dims=[2, 3, 4])
assert_allclose(state.data, vec)
self.assertEqual(state.dim, 2 * 3 * 4)
self.assertEqual(state.dims(), (2, 3, 4))
self.assertIsNone(state.num_qubits)
def test_init_circuit(self):
"""Test initialization from circuit."""
circuit = QuantumCircuit(3)
circuit.x(0)
state = Statevector(circuit)
self.assertEqual(state.dim, 8)
self.assertEqual(state.dims(), (2, 2, 2))
self.assertTrue(all(state.data == np.array([0, 1, 0, 0, 0, 0, 0, 0], dtype=complex)))
self.assertEqual(state.num_qubits, 3)
def test_init_array_except(self):
"""Test initialization exception from array."""
vec = self.rand_vec(4)
self.assertRaises(QiskitError, Statevector, vec, dims=[4, 2])
self.assertRaises(QiskitError, Statevector, vec, dims=[2, 4])
self.assertRaises(QiskitError, Statevector, vec, dims=5)
def test_init_statevector(self):
"""Test initialization from Statevector."""
vec1 = Statevector(self.rand_vec(4))
vec2 = Statevector(vec1)
self.assertEqual(vec1, vec2)
def test_from_circuit(self):
"""Test initialization from a circuit."""
# random unitaries
u0 = random_unitary(2).data
u1 = random_unitary(2).data
# add to circuit
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.unitary(u0, [qr[0]])
circ.unitary(u1, [qr[1]])
target = Statevector(np.kron(u1, u0).dot([1, 0, 0, 0]))
vec = Statevector.from_instruction(circ)
self.assertEqual(vec, target)
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.x(1)
circuit.ry(np.pi / 2, 2)
target = Statevector.from_label("000").evolve(Operator(circuit))
psi = Statevector.from_instruction(circuit)
self.assertEqual(psi, target)
# Test decomposition of Controlled-Phase gate
lam = np.pi / 4
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.h(1)
circuit.cp(lam, 0, 1)
target = Statevector.from_label("00").evolve(Operator(circuit))
psi = Statevector.from_instruction(circuit)
self.assertEqual(psi, target)
# Test decomposition of controlled-H gate
circuit = QuantumCircuit(2)
circ.x(0)
circuit.ch(0, 1)
target = Statevector.from_label("00").evolve(Operator(circuit))
psi = Statevector.from_instruction(circuit)
self.assertEqual(psi, target)
# Test custom controlled gate
qc = QuantumCircuit(2)
qc.x(0)
qc.h(1)
gate = qc.to_gate()
gate_ctrl = gate.control()
circuit = QuantumCircuit(3)
circuit.x(0)
circuit.append(gate_ctrl, range(3))
target = Statevector.from_label("000").evolve(Operator(circuit))
psi = Statevector.from_instruction(circuit)
self.assertEqual(psi, target)
# Test initialize instruction
target = Statevector([1, 0, 0, 1j]) / np.sqrt(2)
circuit = QuantumCircuit(2)
circuit.initialize(target.data, [0, 1])
psi = Statevector.from_instruction(circuit)
self.assertEqual(psi, target)
target = Statevector([1, 0, 1, 0]) / np.sqrt(2)
circuit = QuantumCircuit(2)
circuit.initialize("+", [1])
psi = Statevector.from_instruction(circuit)
self.assertEqual(psi, target)
target = Statevector([1, 0, 0, 0])
circuit = QuantumCircuit(2)
circuit.initialize(0, [0, 1]) # initialize from int
psi = Statevector.from_instruction(circuit)
self.assertEqual(psi, target)
# Test reset instruction
target = Statevector([1, 0])
circuit = QuantumCircuit(1)
circuit.h(0)
circuit.reset(0)
psi = Statevector.from_instruction(circuit)
self.assertEqual(psi, target)
# Test 0q instruction
target = Statevector([1j, 0])
circuit = QuantumCircuit(1)
circuit.append(GlobalPhaseGate(np.pi / 2), [], [])
psi = Statevector.from_instruction(circuit)
self.assertEqual(psi, target)
def test_from_instruction(self):
"""Test initialization from an instruction."""
target = np.dot(HGate().to_matrix(), [1, 0])
vec = Statevector.from_instruction(HGate()).data
global_phase_equivalent = matrix_equal(vec, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_label(self):
"""Test initialization from a label"""
x_p = Statevector(np.array([1, 1]) / np.sqrt(2))
x_m = Statevector(np.array([1, -1]) / np.sqrt(2))
y_p = Statevector(np.array([1, 1j]) / np.sqrt(2))
y_m = Statevector(np.array([1, -1j]) / np.sqrt(2))
z_p = Statevector(np.array([1, 0]))
z_m = Statevector(np.array([0, 1]))
label = "01"
target = z_p.tensor(z_m)
self.assertEqual(target, Statevector.from_label(label))
label = "+-"
target = x_p.tensor(x_m)
self.assertEqual(target, Statevector.from_label(label))
label = "rl"
target = y_p.tensor(y_m)
self.assertEqual(target, Statevector.from_label(label))
def test_equal(self):
"""Test __eq__ method"""
for _ in range(10):
vec = self.rand_vec(4)
self.assertEqual(Statevector(vec), Statevector(vec.tolist()))
def test_getitem(self):
"""Test __getitem__ method"""
for _ in range(10):
vec = self.rand_vec(4)
state = Statevector(vec)
for i in range(4):
self.assertEqual(state[i], vec[i])
self.assertEqual(state[format(i, "b")], vec[i])
def test_getitem_except(self):
"""Test __getitem__ method raises exceptions."""
for i in range(1, 4):
state = Statevector(self.rand_vec(2**i))
self.assertRaises(QiskitError, state.__getitem__, 2**i)
self.assertRaises(QiskitError, state.__getitem__, -1)
def test_copy(self):
"""Test Statevector copy method"""
for _ in range(5):
vec = self.rand_vec(4)
orig = Statevector(vec)
cpy = orig.copy()
cpy._data[0] += 1.0
self.assertFalse(cpy == orig)
def test_is_valid(self):
"""Test is_valid method."""
state = Statevector([1, 1])
self.assertFalse(state.is_valid())
for _ in range(10):
state = Statevector(self.rand_vec(4, normalize=True))
self.assertTrue(state.is_valid())
def test_to_operator(self):
"""Test to_operator method for returning projector."""
for _ in range(10):
vec = self.rand_vec(4)
target = Operator(np.outer(vec, np.conj(vec)))
op = Statevector(vec).to_operator()
self.assertEqual(op, target)
def test_evolve(self):
"""Test _evolve method."""
for _ in range(10):
op = random_unitary(4)
vec = self.rand_vec(4)
target = Statevector(np.dot(op.data, vec))
evolved = Statevector(vec).evolve(op)
self.assertEqual(target, evolved)
def test_evolve_subsystem(self):
"""Test subsystem _evolve method."""
# Test evolving single-qubit of 3-qubit system
for _ in range(5):
vec = self.rand_vec(8)
state = Statevector(vec)
op0 = random_unitary(2)
op1 = random_unitary(2)
op2 = random_unitary(2)
# Test evolve on 1-qubit
op = op0
op_full = Operator(np.eye(4)).tensor(op)
target = Statevector(np.dot(op_full.data, vec))
self.assertEqual(state.evolve(op, qargs=[0]), target)
# Evolve on qubit 1
op_full = Operator(np.eye(2)).tensor(op).tensor(np.eye(2))
target = Statevector(np.dot(op_full.data, vec))
self.assertEqual(state.evolve(op, qargs=[1]), target)
# Evolve on qubit 2
op_full = op.tensor(np.eye(4))
target = Statevector(np.dot(op_full.data, vec))
self.assertEqual(state.evolve(op, qargs=[2]), target)
# Test evolve on 2-qubits
op = op1.tensor(op0)
# Evolve on qubits [0, 2]
op_full = op1.tensor(np.eye(2)).tensor(op0)
target = Statevector(np.dot(op_full.data, vec))
self.assertEqual(state.evolve(op, qargs=[0, 2]), target)
# Evolve on qubits [2, 0]
op_full = op0.tensor(np.eye(2)).tensor(op1)
target = Statevector(np.dot(op_full.data, vec))
self.assertEqual(state.evolve(op, qargs=[2, 0]), target)
# Test evolve on 3-qubits
op = op2.tensor(op1).tensor(op0)
# Evolve on qubits [0, 1, 2]
op_full = op
target = Statevector(np.dot(op_full.data, vec))
self.assertEqual(state.evolve(op, qargs=[0, 1, 2]), target)
# Evolve on qubits [2, 1, 0]
op_full = op0.tensor(op1).tensor(op2)
target = Statevector(np.dot(op_full.data, vec))
self.assertEqual(state.evolve(op, qargs=[2, 1, 0]), target)
def test_evolve_qudit_subsystems(self):
"""Test nested evolve calls on qudit subsystems."""
dims = (3, 4, 5)
init = self.rand_vec(np.prod(dims))
ops = [random_unitary((dim,)) for dim in dims]
state = Statevector(init, dims)
for i, op in enumerate(ops):
state = state.evolve(op, [i])
target_op = np.eye(1)
for op in ops:
target_op = np.kron(op.data, target_op)
target = Statevector(np.dot(target_op, init), dims)
self.assertEqual(state, target)
def test_evolve_global_phase(self):
"""Test evolve circuit with global phase."""
state_i = Statevector([1, 0])
qr = QuantumRegister(2)
phase = np.pi / 4
circ = QuantumCircuit(qr, global_phase=phase)
circ.x(0)
state_f = state_i.evolve(circ, qargs=[0])
target = Statevector([0, 1]) * np.exp(1j * phase)
self.assertEqual(state_f, target)
def test_conjugate(self):
"""Test conjugate method."""
for _ in range(10):
vec = self.rand_vec(4)
target = Statevector(np.conj(vec))
state = Statevector(vec).conjugate()
self.assertEqual(state, target)
def test_expand(self):
"""Test expand method."""
for _ in range(10):
vec0 = self.rand_vec(2)
vec1 = self.rand_vec(3)
target = np.kron(vec1, vec0)
state = Statevector(vec0).expand(Statevector(vec1))
self.assertEqual(state.dim, 6)
self.assertEqual(state.dims(), (2, 3))
assert_allclose(state.data, target)
def test_tensor(self):
"""Test tensor method."""
for _ in range(10):
vec0 = self.rand_vec(2)
vec1 = self.rand_vec(3)
target = np.kron(vec0, vec1)
state = Statevector(vec0).tensor(Statevector(vec1))
self.assertEqual(state.dim, 6)
self.assertEqual(state.dims(), (3, 2))
assert_allclose(state.data, target)
def test_inner(self):
"""Test inner method."""
for _ in range(10):
vec0 = Statevector(self.rand_vec(4))
vec1 = Statevector(self.rand_vec(4))
target = np.vdot(vec0.data, vec1.data)
result = vec0.inner(vec1)
self.assertAlmostEqual(result, target)
vec0 = Statevector(self.rand_vec(6), dims=(2, 3))
vec1 = Statevector(self.rand_vec(6), dims=(2, 3))
target = np.vdot(vec0.data, vec1.data)
result = vec0.inner(vec1)
self.assertAlmostEqual(result, target)
def test_inner_except(self):
"""Test inner method raises exceptions."""
vec0 = Statevector(self.rand_vec(4))
vec1 = Statevector(self.rand_vec(3))
self.assertRaises(QiskitError, vec0.inner, vec1)
vec0 = Statevector(self.rand_vec(6), dims=(2, 3))
vec1 = Statevector(self.rand_vec(6), dims=(3, 2))
self.assertRaises(QiskitError, vec0.inner, vec1)
def test_add(self):
"""Test add method."""
for _ in range(10):
vec0 = self.rand_vec(4)
vec1 = self.rand_vec(4)
state0 = Statevector(vec0)
state1 = Statevector(vec1)
self.assertEqual(state0 + state1, Statevector(vec0 + vec1))
def test_add_except(self):
"""Test add method raises exceptions."""
state1 = Statevector(self.rand_vec(2))
state2 = Statevector(self.rand_vec(3))
self.assertRaises(QiskitError, state1.__add__, state2)
def test_subtract(self):
"""Test subtract method."""
for _ in range(10):
vec0 = self.rand_vec(4)
vec1 = self.rand_vec(4)
state0 = Statevector(vec0)
state1 = Statevector(vec1)
self.assertEqual(state0 - state1, Statevector(vec0 - vec1))
def test_multiply(self):
"""Test multiply method."""
for _ in range(10):
vec = self.rand_vec(4)
state = Statevector(vec)
val = np.random.rand() + 1j * np.random.rand()
self.assertEqual(val * state, Statevector(val * state))
def test_negate(self):
"""Test negate method"""
for _ in range(10):
vec = self.rand_vec(4)
state = Statevector(vec)
self.assertEqual(-state, Statevector(-1 * vec))
def test_equiv(self):
"""Test equiv method"""
vec = np.array([1, 0, 0, -1j]) / np.sqrt(2)
phase = np.exp(-1j * np.pi / 4)
statevec = Statevector(vec)
self.assertTrue(statevec.equiv(phase * vec))
self.assertTrue(statevec.equiv(Statevector(phase * vec)))
self.assertFalse(statevec.equiv(2 * vec))
def test_equiv_on_circuit(self):
"""Test the equiv method on different types of input."""
statevec = Statevector([1, 0])
qc = QuantumCircuit(1)
self.assertTrue(statevec.equiv(qc))
qc.x(0)
self.assertFalse(statevec.equiv(qc))
def test_to_dict(self):
"""Test to_dict method"""
with self.subTest(msg="dims = (2, 3)"):
vec = Statevector(np.arange(1, 7), dims=(2, 3))
target = {"00": 1, "01": 2, "10": 3, "11": 4, "20": 5, "21": 6}
self.assertDictAlmostEqual(target, vec.to_dict())
with self.subTest(msg="dims = (11, )"):
vec = Statevector(np.arange(1, 12), dims=(11,))
target = {str(i): i + 1 for i in range(11)}
self.assertDictAlmostEqual(target, vec.to_dict())
with self.subTest(msg="dims = (2, 11)"):
vec = Statevector(np.arange(1, 23), dims=(2, 11))
target = {}
for i in range(11):
for j in range(2):
key = f"{i},{j}"
target[key] = 2 * i + j + 1
self.assertDictAlmostEqual(target, vec.to_dict())
def test_probabilities_product(self):
"""Test probabilities method for product state"""
state = Statevector.from_label("+0")
# 2-qubit qargs
with self.subTest(msg="P(None)"):
probs = state.probabilities()
target = np.array([0.5, 0, 0.5, 0])
self.assertTrue(np.allclose(probs, target))
with self.subTest(msg="P([0, 1])"):
probs = state.probabilities([0, 1])
target = np.array([0.5, 0, 0.5, 0])
self.assertTrue(np.allclose(probs, target))
with self.subTest(msg="P([1, 0]"):
probs = state.probabilities([1, 0])
target = np.array([0.5, 0.5, 0, 0])
self.assertTrue(np.allclose(probs, target))
# 1-qubit qargs
with self.subTest(msg="P([0])"):
probs = state.probabilities([0])
target = np.array([1, 0])
self.assertTrue(np.allclose(probs, target))
with self.subTest(msg="P([1])"):
probs = state.probabilities([1])
target = np.array([0.5, 0.5])
self.assertTrue(np.allclose(probs, target))
def test_probabilities_ghz(self):
"""Test probabilities method for GHZ state"""
state = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2)
# 3-qubit qargs
target = np.array([0.5, 0, 0, 0, 0, 0, 0, 0.5])
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
# 2-qubit qargs
target = np.array([0.5, 0, 0, 0.5])
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
# 1-qubit qargs
target = np.array([0.5, 0.5])
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
def test_probabilities_w(self):
"""Test probabilities method with W state"""
state = (
Statevector.from_label("001")
+ Statevector.from_label("010")
+ Statevector.from_label("100")
) / np.sqrt(3)
# 3-qubit qargs
target = np.array([0, 1 / 3, 1 / 3, 0, 1 / 3, 0, 0, 0])
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
# 2-qubit qargs
target = np.array([1 / 3, 1 / 3, 1 / 3, 0])
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
# 1-qubit qargs
target = np.array([2 / 3, 1 / 3])
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
def test_probabilities_dict_product(self):
"""Test probabilities_dict method for product state"""
state = Statevector.from_label("+0")
# 2-qubit qargs
with self.subTest(msg="P(None)"):
probs = state.probabilities_dict()
target = {"00": 0.5, "10": 0.5}
self.assertDictAlmostEqual(probs, target)
with self.subTest(msg="P([0, 1])"):
probs = state.probabilities_dict([0, 1])
target = {"00": 0.5, "10": 0.5}
self.assertDictAlmostEqual(probs, target)
with self.subTest(msg="P([1, 0]"):
probs = state.probabilities_dict([1, 0])
target = {"00": 0.5, "01": 0.5}
self.assertDictAlmostEqual(probs, target)
# 1-qubit qargs
with self.subTest(msg="P([0])"):
probs = state.probabilities_dict([0])
target = {"0": 1}
self.assertDictAlmostEqual(probs, target)
with self.subTest(msg="P([1])"):
probs = state.probabilities_dict([1])
target = {"0": 0.5, "1": 0.5}
self.assertDictAlmostEqual(probs, target)
def test_probabilities_dict_ghz(self):
"""Test probabilities_dict method for GHZ state"""
state = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2)
# 3-qubit qargs
target = {"000": 0.5, "111": 0.5}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
# 2-qubit qargs
target = {"00": 0.5, "11": 0.5}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
# 1-qubit qargs
target = {"0": 0.5, "1": 0.5}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
def test_probabilities_dict_w(self):
"""Test probabilities_dict method with W state"""
state = (
Statevector.from_label("001")
+ Statevector.from_label("010")
+ Statevector.from_label("100")
) / np.sqrt(3)
# 3-qubit qargs
target = np.array([0, 1 / 3, 1 / 3, 0, 1 / 3, 0, 0, 0])
target = {"001": 1 / 3, "010": 1 / 3, "100": 1 / 3}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
# 2-qubit qargs
target = {"00": 1 / 3, "01": 1 / 3, "10": 1 / 3}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
# 1-qubit qargs
target = {"0": 2 / 3, "1": 1 / 3}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
def test_sample_counts_ghz(self):
"""Test sample_counts method for GHZ state"""
shots = 2000
threshold = 0.02 * shots
state = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2)
state.seed(100)
# 3-qubit qargs
target = {"000": shots / 2, "111": shots / 2}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
# 2-qubit qargs
target = {"00": shots / 2, "11": shots / 2}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
# 1-qubit qargs
target = {"0": shots / 2, "1": shots / 2}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
def test_sample_counts_w(self):
"""Test sample_counts method for W state"""
shots = 3000
threshold = 0.02 * shots
state = (
Statevector.from_label("001")
+ Statevector.from_label("010")
+ Statevector.from_label("100")
) / np.sqrt(3)
state.seed(100)
target = {"001": shots / 3, "010": shots / 3, "100": shots / 3}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"P({qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
# 2-qubit qargs
target = {"00": shots / 3, "01": shots / 3, "10": shots / 3}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"P({qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
# 1-qubit qargs
target = {"0": 2 * shots / 3, "1": shots / 3}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"P({qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
def test_probabilities_dict_unequal_dims(self):
"""Test probabilities_dict for a state with unequal subsystem dimensions."""
vec = np.zeros(60, dtype=float)
vec[15:20] = np.ones(5)
vec[40:46] = np.ones(6)
state = Statevector(vec / np.sqrt(11.0), dims=[3, 4, 5])
p = 1.0 / 11.0
self.assertDictEqual(
state.probabilities_dict(),
{
s: p
for s in [
"110",
"111",
"112",
"120",
"121",
"311",
"312",
"320",
"321",
"322",
"330",
]
},
)
# differences due to rounding
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[0]), {"0": 4 * p, "1": 4 * p, "2": 3 * p}, delta=1e-10
)
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[1]), {"1": 5 * p, "2": 5 * p, "3": p}, delta=1e-10
)
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[2]), {"1": 5 * p, "3": 6 * p}, delta=1e-10
)
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[0, 1]),
{"10": p, "11": 2 * p, "12": 2 * p, "20": 2 * p, "21": 2 * p, "22": p, "30": p},
delta=1e-10,
)
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[1, 0]),
{"01": p, "11": 2 * p, "21": 2 * p, "02": 2 * p, "12": 2 * p, "22": p, "03": p},
delta=1e-10,
)
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[0, 2]),
{"10": 2 * p, "11": 2 * p, "12": p, "31": 2 * p, "32": 2 * p, "30": 2 * p},
delta=1e-10,
)
def test_sample_counts_qutrit(self):
"""Test sample_counts method for qutrit state"""
p = 0.3
shots = 1000
threshold = 0.03 * shots
state = Statevector([np.sqrt(p), 0, np.sqrt(1 - p)])
state.seed(100)
with self.subTest(msg="counts"):
target = {"0": shots * p, "2": shots * (1 - p)}
counts = state.sample_counts(shots=shots)
self.assertDictAlmostEqual(counts, target, threshold)
def test_sample_memory_ghz(self):
"""Test sample_memory method for GHZ state"""
shots = 2000
state = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2)
state.seed(100)
# 3-qubit qargs
target = {"000": shots / 2, "111": shots / 2}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
# 2-qubit qargs
target = {"00": shots / 2, "11": shots / 2}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
# 1-qubit qargs
target = {"0": shots / 2, "1": shots / 2}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
def test_sample_memory_w(self):
"""Test sample_memory method for W state"""
shots = 3000
state = (
Statevector.from_label("001")
+ Statevector.from_label("010")
+ Statevector.from_label("100")
) / np.sqrt(3)
state.seed(100)
target = {"001": shots / 3, "010": shots / 3, "100": shots / 3}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
# 2-qubit qargs
target = {"00": shots / 3, "01": shots / 3, "10": shots / 3}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
# 1-qubit qargs
target = {"0": 2 * shots / 3, "1": shots / 3}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
def test_sample_memory_qutrit(self):
"""Test sample_memory method for qutrit state"""
p = 0.3
shots = 1000
state = Statevector([np.sqrt(p), 0, np.sqrt(1 - p)])
state.seed(100)
with self.subTest(msg="memory"):
memory = state.sample_memory(shots)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), {"0", "2"})
def test_reset_2qubit(self):
"""Test reset method for 2-qubit state"""
state = Statevector(np.array([1, 0, 0, 1]) / np.sqrt(2))
state.seed(100)
with self.subTest(msg="reset"):
psi = state.copy()
value = psi.reset()
target = Statevector(np.array([1, 0, 0, 0]))
self.assertEqual(value, target)
with self.subTest(msg="reset"):
psi = state.copy()
value = psi.reset([0, 1])
target = Statevector(np.array([1, 0, 0, 0]))
self.assertEqual(value, target)
with self.subTest(msg="reset [0]"):
psi = state.copy()
value = psi.reset([0])
targets = [Statevector(np.array([1, 0, 0, 0])), Statevector(np.array([0, 0, 1, 0]))]
self.assertIn(value, targets)
with self.subTest(msg="reset [0]"):
psi = state.copy()
value = psi.reset([1])
targets = [Statevector(np.array([1, 0, 0, 0])), Statevector(np.array([0, 1, 0, 0]))]
self.assertIn(value, targets)
def test_reset_qutrit(self):
"""Test reset method for qutrit"""
state = Statevector(np.array([1, 1, 1]) / np.sqrt(3))
state.seed(200)
value = state.reset()
target = Statevector(np.array([1, 0, 0]))
self.assertEqual(value, target)
def test_measure_2qubit(self):
"""Test measure method for 2-qubit state"""
state = Statevector.from_label("+0")
seed = 200
shots = 100
with self.subTest(msg="measure"):
for i in range(shots):
psi = state.copy()
psi.seed(seed + i)
outcome, value = psi.measure()
self.assertIn(outcome, ["00", "10"])
if outcome == "00":
target = Statevector.from_label("00")
self.assertEqual(value, target)
else:
target = Statevector.from_label("10")
self.assertEqual(value, target)
with self.subTest(msg="measure [0, 1]"):
for i in range(shots):
psi = state.copy()
outcome, value = psi.measure([0, 1])
self.assertIn(outcome, ["00", "10"])
if outcome == "00":
target = Statevector.from_label("00")
self.assertEqual(value, target)
else:
target = Statevector.from_label("10")
self.assertEqual(value, target)
with self.subTest(msg="measure [1, 0]"):
for i in range(shots):
psi = state.copy()
outcome, value = psi.measure([1, 0])
self.assertIn(outcome, ["00", "01"])
if outcome == "00":
target = Statevector.from_label("00")
self.assertEqual(value, target)
else:
target = Statevector.from_label("10")
self.assertEqual(value, target)
with self.subTest(msg="measure [0]"):
for i in range(shots):
psi = state.copy()
outcome, value = psi.measure([0])
self.assertEqual(outcome, "0")
target = Statevector(np.array([1, 0, 1, 0]) / np.sqrt(2))
self.assertEqual(value, target)
with self.subTest(msg="measure [1]"):
for i in range(shots):
psi = state.copy()
outcome, value = psi.measure([1])
self.assertIn(outcome, ["0", "1"])
if outcome == "0":
target = Statevector.from_label("00")
self.assertEqual(value, target)
else:
target = Statevector.from_label("10")
self.assertEqual(value, target)
def test_measure_qutrit(self):
"""Test measure method for qutrit"""
state = Statevector(np.array([1, 1, 1]) / np.sqrt(3))
seed = 200
shots = 100
for i in range(shots):
psi = state.copy()
psi.seed(seed + i)
outcome, value = psi.measure()
self.assertIn(outcome, ["0", "1", "2"])
if outcome == "0":
target = Statevector([1, 0, 0])
self.assertEqual(value, target)
elif outcome == "1":
target = Statevector([0, 1, 0])
self.assertEqual(value, target)
else:
target = Statevector([0, 0, 1])
self.assertEqual(value, target)
def test_from_int(self):
"""Test from_int method"""
with self.subTest(msg="from_int(0, 4)"):
target = Statevector([1, 0, 0, 0])
value = Statevector.from_int(0, 4)
self.assertEqual(target, value)
with self.subTest(msg="from_int(3, 4)"):
target = Statevector([0, 0, 0, 1])
value = Statevector.from_int(3, 4)
self.assertEqual(target, value)
with self.subTest(msg="from_int(8, (3, 3))"):
target = Statevector([0, 0, 0, 0, 0, 0, 0, 0, 1], dims=(3, 3))
value = Statevector.from_int(8, (3, 3))
self.assertEqual(target, value)
def test_expval(self):
"""Test expectation_value method"""
psi = Statevector([1, 0, 0, 1]) / np.sqrt(2)
for label, target in [
("II", 1),
("XX", 1),
("YY", -1),
("ZZ", 1),
("IX", 0),
("YZ", 0),
("ZX", 0),
("YI", 0),
]:
with self.subTest(msg=f"<{label}>"):
op = Pauli(label)
expval = psi.expectation_value(op)
self.assertAlmostEqual(expval, target)
psi = Statevector([np.sqrt(2), 0, 0, 0, 0, 0, 0, 1 + 1j]) / 2
for label, target in [
("XXX", np.sqrt(2) / 2),
("YYY", -np.sqrt(2) / 2),
("ZZZ", 0),
("XYZ", 0),
("YIY", 0),
]:
with self.subTest(msg=f"<{label}>"):
op = Pauli(label)
expval = psi.expectation_value(op)
self.assertAlmostEqual(expval, target)
labels = ["XXX", "IXI", "YYY", "III"]
coeffs = [3.0, 5.5, -1j, 23]
spp_op = SparsePauliOp.from_list(list(zip(labels, coeffs)))
expval = psi.expectation_value(spp_op)
target = 25.121320343559642 + 0.7071067811865476j
self.assertAlmostEqual(expval, target)
@data(
"II",
"IX",
"IY",
"IZ",
"XI",
"XX",
"XY",
"XZ",
"YI",
"YX",
"YY",
"YZ",
"ZI",
"ZX",
"ZY",
"ZZ",
"-II",
"-IX",
"-IY",
"-IZ",
"-XI",
"-XX",
"-XY",
"-XZ",
"-YI",
"-YX",
"-YY",
"-YZ",
"-ZI",
"-ZX",
"-ZY",
"-ZZ",
"iII",
"iIX",
"iIY",
"iIZ",
"iXI",
"iXX",
"iXY",
"iXZ",
"iYI",
"iYX",
"iYY",
"iYZ",
"iZI",
"iZX",
"iZY",
"iZZ",
"-iII",
"-iIX",
"-iIY",
"-iIZ",
"-iXI",
"-iXX",
"-iXY",
"-iXZ",
"-iYI",
"-iYX",
"-iYY",
"-iYZ",
"-iZI",
"-iZX",
"-iZY",
"-iZZ",
)
def test_expval_pauli(self, pauli):
"""Test expectation_value method for Pauli op"""
seed = 1020
op = Pauli(pauli)
state = random_statevector(2**op.num_qubits, seed=seed)
target = state.expectation_value(op.to_matrix())
expval = state.expectation_value(op)
self.assertAlmostEqual(expval, target)
@data([0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1])
def test_expval_pauli_qargs(self, qubits):
"""Test expectation_value method for Pauli op"""
seed = 1020
op = random_pauli(2, seed=seed)
state = random_statevector(2**3, seed=seed)
target = state.expectation_value(op.to_matrix(), qubits)
expval = state.expectation_value(op, qubits)
self.assertAlmostEqual(expval, target)
@data(*(qargs for i in range(4) for qargs in permutations(range(4), r=i + 1)))
def test_probabilities_qargs(self, qargs):
"""Test probabilities method with qargs"""
# Get initial state
nq = 4
nc = len(qargs)
state_circ = QuantumCircuit(nq, nc)
for i in range(nq):
state_circ.ry((i + 1) * np.pi / (nq + 1), i)
# Get probabilities
state = Statevector(state_circ)
probs = state.probabilities(qargs)
# Estimate target probs from simulator measurement
sim = QasmSimulatorPy()
shots = 5000
seed = 100
circ = transpile(state_circ, sim)
circ.measure(qargs, range(nc))
result = sim.run(circ, shots=shots, seed_simulator=seed).result()
target = np.zeros(2**nc, dtype=float)
for i, p in result.get_counts(0).int_outcomes().items():
target[i] = p / shots
# Compare
delta = np.linalg.norm(probs - target)
self.assertLess(delta, 0.05)
def test_global_phase(self):
"""Test global phase is handled correctly when evolving statevector."""
qc = QuantumCircuit(1)
qc.rz(0.5, 0)
qc2 = transpile(qc, basis_gates=["p"])
sv = Statevector.from_instruction(qc2)
expected = np.array([0.96891242 - 0.24740396j, 0])
self.assertEqual(float(qc2.global_phase), 2 * np.pi - 0.25)
self.assertEqual(sv, Statevector(expected))
def test_reverse_qargs(self):
"""Test reverse_qargs method"""
circ1 = QFT(5)
circ2 = circ1.reverse_bits()
state1 = Statevector.from_instruction(circ1)
state2 = Statevector.from_instruction(circ2)
self.assertEqual(state1.reverse_qargs(), state2)
@unittest.skipUnless(optionals.HAS_MATPLOTLIB, "requires matplotlib")
@unittest.skipUnless(optionals.HAS_PYLATEX, "requires pylatexenc")
def test_drawings(self):
"""Test draw method"""
qc1 = QFT(5)
sv = Statevector.from_instruction(qc1)
with self.subTest(msg="str(statevector)"):
str(sv)
for drawtype in ["repr", "text", "latex", "latex_source", "qsphere", "hinton", "bloch"]:
with self.subTest(msg=f"draw('{drawtype}')"):
sv.draw(drawtype)
with self.subTest(msg=" draw('latex', convention='vector')"):
sv.draw("latex", convention="vector")
def test_state_to_latex_for_none(self):
"""
Test for `\rangleNone` output in latex representation
See https://github.com/Qiskit/qiskit-terra/issues/8169
"""
sv = Statevector(
[
7.07106781e-01 - 8.65956056e-17j,
-5.55111512e-17 - 8.65956056e-17j,
7.85046229e-17 + 8.65956056e-17j,
-7.07106781e-01 + 8.65956056e-17j,
0.00000000e00 + 0.00000000e00j,
-0.00000000e00 + 0.00000000e00j,
-0.00000000e00 + 0.00000000e00j,
0.00000000e00 - 0.00000000e00j,
],
dims=(2, 2, 2),
)
latex_representation = state_to_latex(sv)
self.assertEqual(
latex_representation,
"\\frac{\\sqrt{2}}{2} |000\\rangle- \\frac{\\sqrt{2}}{2} |011\\rangle",
)
def test_state_to_latex_for_large_statevector(self):
"""Test conversion of large dense state vector"""
sv = Statevector(np.ones((2**15, 1)))
latex_representation = state_to_latex(sv)
self.assertEqual(
latex_representation,
" |000000000000000\\rangle+ |000000000000001\\rangle+ |000000000000010\\rangle+"
" |000000000000011\\rangle+ |000000000000100\\rangle+ |000000000000101\\rangle +"
" \\ldots + |111111111111011\\rangle+ |111111111111100\\rangle+"
" |111111111111101\\rangle+ |111111111111110\\rangle+ |111111111111111\\rangle",
)
def test_state_to_latex_with_prefix(self):
"""Test adding prefix to state vector latex output"""
psi = Statevector(np.array([np.sqrt(1 / 2), 0, 0, np.sqrt(1 / 2)]))
prefix = "|\\psi_{AB}\\rangle = "
latex_sv = state_to_latex(psi)
latex_expected = prefix + latex_sv
latex_representation = state_to_latex(psi, prefix=prefix)
self.assertEqual(latex_representation, latex_expected)
def test_state_to_latex_for_large_sparse_statevector(self):
"""Test conversion of large sparse state vector"""
sv = Statevector(np.eye(2**15, 1))
latex_representation = state_to_latex(sv)
self.assertEqual(latex_representation, " |000000000000000\\rangle")
def test_state_to_latex_with_max_size_limit(self):
"""Test limit the maximum number of non-zero terms in the expression"""
sv = Statevector(
[
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.0 + 0.0j,
0.0 + 0.0j,
0.0 + 0.0j,
0.0 + 0.0j,
0.0 + 0.0j,
0.0 + 0.0j,
0.0 + 0.0j,
0.0 + 0.0j,
0.0 - 0.35355339j,
0.0 + 0.35355339j,
0.0 + 0.35355339j,
0.0 - 0.35355339j,
],
dims=(2, 2, 2, 2),
)
latex_representation = state_to_latex(sv, max_size=5)
self.assertEqual(
latex_representation,
"\\frac{\\sqrt{2}}{4} |0000\\rangle+"
"\\frac{\\sqrt{2}}{4} |0001\\rangle + "
"\\ldots +"
"\\frac{\\sqrt{2} i}{4} |1110\\rangle- "
"\\frac{\\sqrt{2} i}{4} |1111\\rangle",
)
def test_state_to_latex_with_decimals_round(self):
"""Test rounding of decimal places in the expression"""
sv = Statevector(
[
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.0 + 0.0j,
0.0 + 0.0j,
0.0 + 0.0j,
0.0 + 0.0j,
0.0 - 0.35355339j,
0.0 + 0.35355339j,
],
dims=(2, 2, 2),
)
latex_representation = state_to_latex(sv, decimals=3)
self.assertEqual(
latex_representation,
"0.354 |000\\rangle+0.354 |001\\rangle- 0.354 i |110\\rangle+0.354 i |111\\rangle",
)
def test_number_to_latex_terms(self):
"""Test conversions of complex numbers to latex terms"""
cases = [
([1 - 8e-17, 0], ["", None]),
([0, -1], [None, "-"]),
([0, 1], [None, ""]),
([0, 1j], [None, "i"]),
([-1, 1], ["-", "+"]),
([0, 1j], [None, "i"]),
([-1, 1j], ["-", "+i"]),
([1e-16 + 1j], ["i"]),
([-1 + 1e-16 * 1j], ["-"]),
([-1, -1 - 1j], ["-", "+(-1 - i)"]),
([np.sqrt(2) / 2, np.sqrt(2) / 2], ["\\frac{\\sqrt{2}}{2}", "+\\frac{\\sqrt{2}}{2}"]),
([1 + np.sqrt(2)], ["(1 + \\sqrt{2})"]),
]
with self.assertWarns(DeprecationWarning):
for numbers, latex_terms in cases:
terms = numbers_to_latex_terms(numbers, 15)
self.assertListEqual(terms, latex_terms)
def test_statevector_draw_latex_regression(self):
"""Test numerical rounding errors are not printed"""
sv = Statevector(np.array([1 - 8e-17, 8.32667268e-17j]))
latex_string = sv.draw(output="latex_source")
self.assertTrue(latex_string.startswith(" |0\\rangle"))
self.assertNotIn("|1\\rangle", latex_string)
def test_statevctor_iter(self):
"""Test iteration over a state vector"""
empty_vector = []
dummy_vector = [1, 2, 3]
empty_sv = Statevector([])
sv = Statevector(dummy_vector)
# Assert that successive iterations behave as expected, i.e., the
# iterator is reset upon each exhaustion of the corresponding
# collection of elements.
for _ in range(2):
self.assertEqual(empty_vector, list(empty_sv))
self.assertEqual(dummy_vector, list(sv))
def test_statevector_len(self):
"""Test state vector length"""
empty_vector = []
dummy_vector = [1, 2, 3]
empty_sv = Statevector([])
sv = Statevector(dummy_vector)
self.assertEqual(len(empty_vector), len(empty_sv))
self.assertEqual(len(dummy_vector), len(sv))
def test_clip_probabilities(self):
"""Test probabilities are clipped to [0, 1]."""
sv = Statevector([1.1, 0])
self.assertEqual(list(sv.probabilities()), [1.0, 0.0])
# The "1" key should be zero and therefore omitted.
self.assertEqual(sv.probabilities_dict(), {"0": 1.0})
def test_round_probabilities(self):
"""Test probabilities are correctly rounded.
This is good to test to ensure clipping, renormalizing and rounding work together.
"""
p = np.sqrt(1 / 3)
sv = Statevector([p, p, p, 0])
expected = [0.33, 0.33, 0.33, 0]
self.assertEqual(list(sv.probabilities(decimals=2)), expected)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.providers.aer import QasmSimulator
from qiskit.visualization import plot_histogram
# Use Aer's qasm_simulator
simulator = QasmSimulator()
# Create a Quantum Circuit acting on the q register
circuit = QuantumCircuit(2, 2)
# Add a H gate on qubit 0
circuit.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1
circuit.cx(0, 1)
# Map the quantum measurement to the classical bits
circuit.measure([0,1], [0,1])
# compile the circuit down to low-level QASM instructions
# supported by the backend (not needed for simple circuits)
compiled_circuit = transpile(circuit, simulator)
# Execute the circuit on the qasm simulator
job = simulator.run(compiled_circuit, shots=1000)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(compiled_circuit)
# print("\nTotal count for 00 and 11 are:",counts)
# Draw the ci
circuit.draw(output="latex", filename="printing.png")
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Tests for qiskit-terra/qiskit/quantum_info/synthesis/xx_decompose/qiskit.py .
"""
from statistics import mean
import unittest
import ddt
import numpy as np
from scipy.stats import unitary_group
import qiskit
from qiskit.circuit.quantumcircuit import QuantumCircuit
from qiskit.quantum_info.operators import Operator
from qiskit.quantum_info.synthesis.xx_decompose.decomposer import (
XXDecomposer,
TwoQubitWeylDecomposition,
)
from .utilities import canonical_matrix
EPSILON = 1e-8
@ddt.ddt
class TestXXDecomposer(unittest.TestCase):
"""Tests for decomposition of two-qubit unitaries over discrete gates from XX family."""
decomposer = XXDecomposer(euler_basis="PSX")
def __init__(self, *args, seed=42, **kwargs):
super().__init__(*args, **kwargs)
self._random_state = np.random.Generator(np.random.PCG64(seed))
def test_random_compilation(self):
"""Test that compilation gives correct results."""
for _ in range(100):
unitary = unitary_group.rvs(4, random_state=self._random_state)
unitary /= np.linalg.det(unitary) ** (1 / 4)
# decompose into CX, CX/2, and CX/3
circuit = self.decomposer(unitary, approximate=False)
decomposed_unitary = Operator(circuit).data
self.assertTrue(np.all(unitary - decomposed_unitary < EPSILON))
def test_compilation_determinism(self):
"""Test that compilation is stable under multiple calls."""
for _ in range(10):
unitary = unitary_group.rvs(4, random_state=self._random_state)
unitary /= np.linalg.det(unitary) ** (1 / 4)
# decompose into CX, CX/2, and CX/3
circuit1 = self.decomposer(unitary, approximate=False)
circuit2 = self.decomposer(unitary, approximate=False)
self.assertEqual(circuit1, circuit2)
@ddt.data(np.pi / 3, np.pi / 5, np.pi / 2)
def test_default_embodiment(self, angle):
"""Test that _default_embodiment actually does yield XX gates."""
embodiment = self.decomposer._default_embodiment(angle)
embodiment_matrix = Operator(embodiment).data
self.assertTrue(np.all(canonical_matrix(angle, 0, 0) - embodiment_matrix < EPSILON))
def test_check_embodiment(self):
"""Test that XXDecomposer._check_embodiments correctly diagnoses il/legal embodiments."""
# build the member of the XX family corresponding to a single CX
good_angle = np.pi / 2
good_embodiment = qiskit.QuantumCircuit(2)
good_embodiment.h(0)
good_embodiment.cx(0, 1)
good_embodiment.h(1)
good_embodiment.rz(np.pi / 2, 0)
good_embodiment.rz(np.pi / 2, 1)
good_embodiment.h(1)
good_embodiment.h(0)
good_embodiment.global_phase += np.pi / 4
# mismatch two members of the XX family
bad_angle = np.pi / 10
bad_embodiment = qiskit.QuantumCircuit(2)
# "self.assertDoesNotRaise"
XXDecomposer(embodiments={good_angle: good_embodiment})
self.assertRaises(
qiskit.exceptions.QiskitError, XXDecomposer, embodiments={bad_angle: bad_embodiment}
)
def test_compilation_improvement(self):
"""Test that compilation to CX, CX/2, CX/3 improves over CX alone."""
slope, offset = (64 * 90) / 1000000, 909 / 1000000 + 1 / 1000
strength_table = self.decomposer._strength_to_infidelity(
basis_fidelity={
strength: 1 - (slope * strength / (np.pi / 2) + offset)
for strength in [np.pi / 2, np.pi / 4, np.pi / 6]
},
approximate=True,
)
limited_strength_table = {np.pi / 2: strength_table[np.pi / 2]}
clever_costs = []
naive_costs = []
for _ in range(200):
unitary = unitary_group.rvs(4, random_state=self._random_state)
unitary /= np.linalg.det(unitary) ** (1 / 4)
weyl_decomposition = TwoQubitWeylDecomposition(unitary)
target = [getattr(weyl_decomposition, x) for x in ("a", "b", "c")]
if target[-1] < -EPSILON:
target = [np.pi / 2 - target[0], target[1], -target[2]]
# decompose into CX, CX/2, and CX/3
clever_costs.append(self.decomposer._best_decomposition(target, strength_table)["cost"])
naive_costs.append(
self.decomposer._best_decomposition(target, limited_strength_table)["cost"]
)
# the following are taken from Fig 14 of the XX synthesis paper
self.assertAlmostEqual(mean(clever_costs), 1.445e-2, delta=5e-3)
self.assertAlmostEqual(mean(naive_costs), 2.058e-2, delta=5e-3)
def test_error_on_empty_basis_fidelity(self):
"""Test synthesizing entangling gate with no entangling basis fails."""
decomposer = XXDecomposer(basis_fidelity={})
qc = QuantumCircuit(2)
qc.cx(0, 1)
mat = Operator(qc).to_matrix()
with self.assertRaisesRegex(
qiskit.exceptions.QiskitError,
"Attempting to synthesize entangling gate with no controlled gates in basis set.",
):
decomposer(mat)
def test_no_error_on_empty_basis_fidelity_trivial_target(self):
"""Test synthesizing non-entangling gate with no entangling basis succeeds."""
decomposer = XXDecomposer(basis_fidelity={})
qc = QuantumCircuit(2)
qc.x(0)
qc.y(1)
mat = Operator(qc).to_matrix()
dqc = decomposer(mat)
self.assertTrue(np.allclose(mat, Operator(dqc).to_matrix()))
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-class-docstring,missing-function-docstring
"""Test Counts class."""
import unittest
import numpy as np
from qiskit.result import counts
from qiskit import exceptions
from qiskit.result import utils
class TestCounts(unittest.TestCase):
def test_just_counts(self):
raw_counts = {"0x0": 21, "0x2": 12}
expected = {"0": 21, "10": 12}
result = counts.Counts(raw_counts)
self.assertEqual(expected, result)
def test_counts_with_exta_formatting_data(self):
raw_counts = {"0x0": 4, "0x2": 10}
expected = {"0 0 00": 4, "0 0 10": 10}
result = counts.Counts(
raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4
)
self.assertEqual(result, expected)
def test_marginal_counts(self):
raw_counts = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_counts(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_marginal_distribution(self):
raw_counts = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_distribution(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_marginal_distribution_numpy_indices(self):
raw_counts = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8}
expected = {"00": 4, "01": 27, "10": 23}
indices = np.asarray([0, 1])
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_distribution(counts_obj, indices)
self.assertEqual(expected, result)
def test_int_outcomes(self):
raw_counts = {"0x0": 21, "0x2": 12, "0x3": 5, "0x2E": 265}
expected = {0: 21, 2: 12, 3: 5, 46: 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.int_outcomes()
self.assertEqual(expected, result)
def test_most_frequent(self):
raw_counts = {"0x0": 21, "0x2": 12, "0x3": 5, "0x2E": 265}
expected = "101110"
counts_obj = counts.Counts(raw_counts)
result = counts_obj.most_frequent()
self.assertEqual(expected, result)
def test_most_frequent_duplicate(self):
raw_counts = {"0x0": 265, "0x2": 12, "0x3": 5, "0x2E": 265}
counts_obj = counts.Counts(raw_counts)
self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent)
def test_hex_outcomes(self):
raw_counts = {"0x0": 21, "0x2": 12, "0x3": 5, "0x2E": 265}
expected = {"0x0": 21, "0x2": 12, "0x3": 5, "0x2e": 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.hex_outcomes()
self.assertEqual(expected, result)
def test_just_int_counts(self):
raw_counts = {0: 21, 2: 12}
expected = {"0": 21, "10": 12}
result = counts.Counts(raw_counts)
self.assertEqual(expected, result)
def test_int_counts_with_exta_formatting_data(self):
raw_counts = {0: 4, 2: 10}
expected = {"0 0 00": 4, "0 0 10": 10}
result = counts.Counts(
raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4
)
self.assertEqual(result, expected)
def test_marginal_int_counts(self):
raw_counts = {0: 4, 1: 7, 2: 10, 6: 5, 9: 11, 13: 9, 14: 8}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_counts(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_marginal_distribution_int_counts(self):
raw_counts = {0: 4, 1: 7, 2: 10, 6: 5, 9: 11, 13: 9, 14: 8}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_distribution(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_marginal_distribution_int_counts_numpy_64_bit(self):
raw_counts = {
0: np.int64(4),
1: np.int64(7),
2: np.int64(10),
6: np.int64(5),
9: np.int64(11),
13: np.int64(9),
14: np.int64(8),
}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_distribution(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_marginal_distribution_int_counts_numpy_8_bit(self):
raw_counts = {
0: np.int8(4),
1: np.int8(7),
2: np.int8(10),
6: np.int8(5),
9: np.int8(11),
13: np.int8(9),
14: np.int8(8),
}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_distribution(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_int_outcomes_with_int_counts(self):
raw_counts = {0: 21, 2: 12, 3: 5, 46: 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.int_outcomes()
self.assertEqual(raw_counts, result)
def test_most_frequent_int_counts(self):
raw_counts = {0: 21, 2: 12, 3: 5, 46: 265}
expected = "101110"
counts_obj = counts.Counts(raw_counts)
result = counts_obj.most_frequent()
self.assertEqual(expected, result)
def test_most_frequent_duplicate_int_counts(self):
raw_counts = {0: 265, 2: 12, 3: 5, 46: 265}
counts_obj = counts.Counts(raw_counts)
self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent)
def test_hex_outcomes_int_counts(self):
raw_counts = {0: 265, 2: 12, 3: 5, 46: 265}
expected = {"0x0": 265, "0x2": 12, "0x3": 5, "0x2e": 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.hex_outcomes()
self.assertEqual(expected, result)
def test_invalid_input_type(self):
self.assertRaises(TypeError, counts.Counts, {2.4: 1024})
def test_just_bitstring_counts(self):
raw_counts = {"0": 21, "10": 12}
expected = {"0": 21, "10": 12}
result = counts.Counts(raw_counts)
self.assertEqual(expected, result)
def test_bistring_counts_with_exta_formatting_data(self):
raw_counts = {"0": 4, "10": 10}
expected = {"0 0 00": 4, "0 0 10": 10}
result = counts.Counts(
raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4
)
self.assertEqual(result, expected)
def test_marginal_bitstring_counts(self):
raw_counts = {"0": 4, "1": 7, "10": 10, "110": 5, "1001": 11, "1101": 9, "1110": 8}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_counts(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_marginal_distribution_bitstring_counts(self):
raw_counts = {"0": 4, "1": 7, "10": 10, "110": 5, "1001": 11, "1101": 9, "1110": 8}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_distribution(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_int_outcomes_with_bitstring_counts(self):
raw_counts = {"0": 21, "10": 12, "11": 5, "101110": 265}
expected = {0: 21, 2: 12, 3: 5, 46: 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.int_outcomes()
self.assertEqual(expected, result)
def test_most_frequent_bitstring_counts(self):
raw_counts = {"0": 21, "10": 12, "11": 5, "101110": 265}
expected = "101110"
counts_obj = counts.Counts(raw_counts)
result = counts_obj.most_frequent()
self.assertEqual(expected, result)
def test_most_frequent_duplicate_bitstring_counts(self):
raw_counts = {"0": 265, "10": 12, "11": 5, "101110": 265}
counts_obj = counts.Counts(raw_counts)
self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent)
def test_hex_outcomes_bitstring_counts(self):
raw_counts = {"0": 265, "10": 12, "11": 5, "101110": 265}
expected = {"0x0": 265, "0x2": 12, "0x3": 5, "0x2e": 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.hex_outcomes()
self.assertEqual(expected, result)
def test_qudit_counts(self):
raw_counts = {
"00": 121,
"01": 109,
"02": 114,
"10": 113,
"11": 106,
"12": 114,
"20": 117,
"21": 104,
"22": 102,
}
result = counts.Counts(raw_counts)
self.assertEqual(raw_counts, result)
def test_qudit_counts_raises_with_format(self):
raw_counts = {
"00": 121,
"01": 109,
"02": 114,
"10": 113,
"11": 106,
"12": 114,
"20": 117,
"21": 104,
"22": 102,
}
self.assertRaises(exceptions.QiskitError, counts.Counts, raw_counts, creg_sizes=[["c0", 4]])
def test_qudit_counts_hex_outcome(self):
raw_counts = {
"00": 121,
"01": 109,
"02": 114,
"10": 113,
"11": 106,
"12": 114,
"20": 117,
"21": 104,
"22": 102,
}
counts_obj = counts.Counts(raw_counts)
self.assertRaises(exceptions.QiskitError, counts_obj.hex_outcomes)
def test_qudit_counts_int_outcome(self):
raw_counts = {
"00": 121,
"01": 109,
"02": 114,
"10": 113,
"11": 106,
"12": 114,
"20": 117,
"21": 104,
"22": 102,
}
counts_obj = counts.Counts(raw_counts)
self.assertRaises(exceptions.QiskitError, counts_obj.int_outcomes)
def test_qudit_counts_most_frequent(self):
raw_counts = {
"00": 121,
"01": 109,
"02": 114,
"10": 113,
"11": 106,
"12": 114,
"20": 117,
"21": 104,
"22": 102,
}
counts_obj = counts.Counts(raw_counts)
self.assertEqual("00", counts_obj.most_frequent())
def test_just_0b_bitstring_counts(self):
raw_counts = {"0b0": 21, "0b10": 12}
expected = {"0": 21, "10": 12}
result = counts.Counts(raw_counts)
self.assertEqual(expected, result)
def test_0b_bistring_counts_with_exta_formatting_data(self):
raw_counts = {"0b0": 4, "0b10": 10}
expected = {"0 0 00": 4, "0 0 10": 10}
result = counts.Counts(
raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4
)
self.assertEqual(result, expected)
def test_marginal_0b_string_counts(self):
raw_counts = {
"0b0": 4,
"0b1": 7,
"0b10": 10,
"0b110": 5,
"0b1001": 11,
"0b1101": 9,
"0b1110": 8,
}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_counts(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_marginal_distribution_0b_string_counts(self):
raw_counts = {
"0b0": 4,
"0b1": 7,
"0b10": 10,
"0b110": 5,
"0b1001": 11,
"0b1101": 9,
"0b1110": 8,
}
expected = {"00": 4, "01": 27, "10": 23}
counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4)
result = utils.marginal_distribution(counts_obj, [0, 1])
self.assertEqual(expected, result)
def test_int_outcomes_with_0b_bitstring_counts(self):
raw_counts = {"0b0": 21, "0b10": 12, "0b11": 5, "0b101110": 265}
expected = {0: 21, 2: 12, 3: 5, 46: 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.int_outcomes()
self.assertEqual(expected, result)
def test_most_frequent_0b_bitstring_counts(self):
raw_counts = {"0b0": 21, "0b10": 12, "0b11": 5, "0b101110": 265}
expected = "101110"
counts_obj = counts.Counts(raw_counts)
result = counts_obj.most_frequent()
self.assertEqual(expected, result)
def test_most_frequent_duplicate_0b_bitstring_counts(self):
raw_counts = {"0b0": 265, "0b10": 12, "0b11": 5, "0b101110": 265}
counts_obj = counts.Counts(raw_counts)
self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent)
def test_hex_outcomes_0b_bitstring_counts(self):
raw_counts = {"0b0": 265, "0b10": 12, "0b11": 5, "0b101110": 265}
expected = {"0x0": 265, "0x2": 12, "0x3": 5, "0x2e": 265}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.hex_outcomes()
self.assertEqual(expected, result)
def test_empty_bitstring_counts(self):
raw_counts = {}
expected = {}
result = counts.Counts(raw_counts)
self.assertEqual(expected, result)
def test_empty_bistring_counts_with_exta_formatting_data(self):
raw_counts = {}
expected = {}
result = counts.Counts(
raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4
)
self.assertEqual(result, expected)
def test_int_outcomes_with_empty_counts(self):
raw_counts = {}
expected = {}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.int_outcomes()
self.assertEqual(expected, result)
def test_most_frequent_empty_bitstring_counts(self):
raw_counts = {}
counts_obj = counts.Counts(raw_counts)
self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent)
def test_hex_outcomes_empty_bitstring_counts(self):
raw_counts = {}
expected = {}
counts_obj = counts.Counts(raw_counts)
result = counts_obj.hex_outcomes()
self.assertEqual(expected, result)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""Tests for error mitigation routines."""
import unittest
from collections import Counter
import numpy as np
from qiskit import QiskitError, QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.quantum_info.operators.predicates import matrix_equal
from qiskit.result import (
CorrelatedReadoutMitigator,
Counts,
LocalReadoutMitigator,
)
from qiskit.result.mitigation.utils import (
counts_probability_vector,
expval_with_stddev,
stddev,
str2diag,
)
from qiskit.result.utils import marginal_counts
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeYorktown
class TestReadoutMitigation(QiskitTestCase):
"""Tests for correlated and local readout mitigation."""
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.rng = np.random.default_rng(42)
@staticmethod
def compare_results(res1, res2):
"""Compare the results between two runs"""
res1_total_shots = sum(res1.values())
res2_total_shots = sum(res2.values())
keys = set(res1.keys()).union(set(res2.keys()))
total = 0
for key in keys:
val1 = res1.get(key, 0) / res1_total_shots
val2 = res2.get(key, 0) / res2_total_shots
total += abs(val1 - val2) ** 2
return total
@staticmethod
def mitigators(assignment_matrices, qubits=None):
"""Generates the mitigators to test for given assignment matrices"""
full_assignment_matrix = assignment_matrices[0]
for m in assignment_matrices[1:]:
full_assignment_matrix = np.kron(full_assignment_matrix, m)
CRM = CorrelatedReadoutMitigator(full_assignment_matrix, qubits)
LRM = LocalReadoutMitigator(assignment_matrices, qubits)
mitigators = [CRM, LRM]
return mitigators
@staticmethod
def simulate_circuit(circuit, assignment_matrix, num_qubits, shots=1024):
"""Simulates the given circuit under the given readout noise"""
probs = Statevector.from_instruction(circuit).probabilities()
noisy_probs = assignment_matrix @ probs
labels = [bin(a)[2:].zfill(num_qubits) for a in range(2**num_qubits)]
results = TestReadoutMitigation.rng.choice(labels, size=shots, p=noisy_probs)
return Counts(dict(Counter(results)))
@staticmethod
def ghz_3_circuit():
"""A 3-qubit circuit generating |000>+|111>"""
c = QuantumCircuit(3)
c.h(0)
c.cx(0, 1)
c.cx(1, 2)
return (c, "ghz_3_ciruit", 3)
@staticmethod
def first_qubit_h_3_circuit():
"""A 3-qubit circuit generating |000>+|001>"""
c = QuantumCircuit(3)
c.h(0)
return (c, "first_qubit_h_3_circuit", 3)
@staticmethod
def assignment_matrices():
"""A 3-qubit readout noise assignment matrices"""
return LocalReadoutMitigator(backend=FakeYorktown())._assignment_mats[0:3]
@staticmethod
def counts_data(circuit, assignment_matrices, shots=1024):
"""Generates count data for the noisy and noiseless versions of the circuit simulation"""
full_assignment_matrix = assignment_matrices[0]
for m in assignment_matrices[1:]:
full_assignment_matrix = np.kron(full_assignment_matrix, m)
num_qubits = len(assignment_matrices)
ideal_assignment_matrix = np.eye(2**num_qubits)
counts_ideal = TestReadoutMitigation.simulate_circuit(
circuit, ideal_assignment_matrix, num_qubits, shots
)
counts_noise = TestReadoutMitigation.simulate_circuit(
circuit, full_assignment_matrix, num_qubits, shots
)
probs_noise = {key: value / shots for key, value in counts_noise.items()}
return counts_ideal, counts_noise, probs_noise
def test_mitigation_improvement(self):
"""Test whether readout mitigation led to more accurate results"""
shots = 1024
assignment_matrices = self.assignment_matrices()
num_qubits = len(assignment_matrices)
mitigators = self.mitigators(assignment_matrices)
circuit, circuit_name, num_qubits = self.ghz_3_circuit()
counts_ideal, counts_noise, probs_noise = self.counts_data(
circuit, assignment_matrices, shots
)
unmitigated_error = self.compare_results(counts_ideal, counts_noise)
unmitigated_stddev = stddev(probs_noise, shots)
for mitigator in mitigators:
mitigated_quasi_probs = mitigator.quasi_probabilities(counts_noise)
mitigated_probs = (
mitigated_quasi_probs.nearest_probability_distribution().binary_probabilities(
num_bits=num_qubits
)
)
mitigated_error = self.compare_results(counts_ideal, mitigated_probs)
self.assertLess(
mitigated_error,
unmitigated_error * 0.8,
"Mitigator {} did not improve circuit {} measurements".format(
mitigator, circuit_name
),
)
mitigated_stddev_upper_bound = mitigated_quasi_probs._stddev_upper_bound
max_unmitigated_stddev = max(unmitigated_stddev.values())
self.assertGreaterEqual(
mitigated_stddev_upper_bound,
max_unmitigated_stddev,
"Mitigator {} on circuit {} gave stddev upper bound {} "
"while unmitigated stddev maximum is {}".format(
mitigator,
circuit_name,
mitigated_stddev_upper_bound,
max_unmitigated_stddev,
),
)
def test_expectation_improvement(self):
"""Test whether readout mitigation led to more accurate results
and that its standard deviation is increased"""
shots = 1024
assignment_matrices = self.assignment_matrices()
mitigators = self.mitigators(assignment_matrices)
num_qubits = len(assignment_matrices)
diagonals = []
diagonals.append("IZ0")
diagonals.append("101")
diagonals.append("IZZ")
qubit_index = {i: i for i in range(num_qubits)}
circuit, circuit_name, num_qubits = self.ghz_3_circuit()
counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots)
probs_ideal, _ = counts_probability_vector(counts_ideal, qubit_index=qubit_index)
probs_noise, _ = counts_probability_vector(counts_noise, qubit_index=qubit_index)
for diagonal in diagonals:
if isinstance(diagonal, str):
diagonal = str2diag(diagonal)
unmitigated_expectation, unmitigated_stddev = expval_with_stddev(
diagonal, probs_noise, shots=counts_noise.shots()
)
ideal_expectation = np.dot(probs_ideal, diagonal)
unmitigated_error = np.abs(ideal_expectation - unmitigated_expectation)
for mitigator in mitigators:
mitigated_expectation, mitigated_stddev = mitigator.expectation_value(
counts_noise, diagonal
)
mitigated_error = np.abs(ideal_expectation - mitigated_expectation)
self.assertLess(
mitigated_error,
unmitigated_error,
"Mitigator {} did not improve circuit {} expectation computation for diagonal {} "
"ideal: {}, unmitigated: {} mitigated: {}".format(
mitigator,
circuit_name,
diagonal,
ideal_expectation,
unmitigated_expectation,
mitigated_expectation,
),
)
self.assertGreaterEqual(
mitigated_stddev,
unmitigated_stddev,
"Mitigator {} did not increase circuit {} the standard deviation".format(
mitigator, circuit_name
),
)
def test_clbits_parameter(self):
"""Test whether the clbits parameter is handled correctly"""
shots = 10000
assignment_matrices = self.assignment_matrices()
mitigators = self.mitigators(assignment_matrices)
circuit, _, _ = self.first_qubit_h_3_circuit()
counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots)
counts_ideal_12 = marginal_counts(counts_ideal, [1, 2])
counts_ideal_02 = marginal_counts(counts_ideal, [0, 2])
for mitigator in mitigators:
mitigated_probs_12 = (
mitigator.quasi_probabilities(counts_noise, qubits=[1, 2], clbits=[1, 2])
.nearest_probability_distribution()
.binary_probabilities(num_bits=2)
)
mitigated_error = self.compare_results(counts_ideal_12, mitigated_probs_12)
self.assertLess(
mitigated_error,
0.001,
"Mitigator {} did not correctly marganalize for qubits 1,2".format(mitigator),
)
mitigated_probs_02 = (
mitigator.quasi_probabilities(counts_noise, qubits=[0, 2], clbits=[0, 2])
.nearest_probability_distribution()
.binary_probabilities(num_bits=2)
)
mitigated_error = self.compare_results(counts_ideal_02, mitigated_probs_02)
self.assertLess(
mitigated_error,
0.001,
"Mitigator {} did not correctly marganalize for qubits 0,2".format(mitigator),
)
def test_qubits_parameter(self):
"""Test whether the qubits parameter is handled correctly"""
shots = 10000
assignment_matrices = self.assignment_matrices()
mitigators = self.mitigators(assignment_matrices)
circuit, _, _ = self.first_qubit_h_3_circuit()
counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots)
counts_ideal_012 = counts_ideal
counts_ideal_210 = Counts({"000": counts_ideal["000"], "100": counts_ideal["001"]})
counts_ideal_102 = Counts({"000": counts_ideal["000"], "010": counts_ideal["001"]})
for mitigator in mitigators:
mitigated_probs_012 = (
mitigator.quasi_probabilities(counts_noise, qubits=[0, 1, 2])
.nearest_probability_distribution()
.binary_probabilities(num_bits=3)
)
mitigated_error = self.compare_results(counts_ideal_012, mitigated_probs_012)
self.assertLess(
mitigated_error,
0.001,
"Mitigator {} did not correctly handle qubit order 0, 1, 2".format(mitigator),
)
mitigated_probs_210 = (
mitigator.quasi_probabilities(counts_noise, qubits=[2, 1, 0])
.nearest_probability_distribution()
.binary_probabilities(num_bits=3)
)
mitigated_error = self.compare_results(counts_ideal_210, mitigated_probs_210)
self.assertLess(
mitigated_error,
0.001,
"Mitigator {} did not correctly handle qubit order 2, 1, 0".format(mitigator),
)
mitigated_probs_102 = (
mitigator.quasi_probabilities(counts_noise, qubits=[1, 0, 2])
.nearest_probability_distribution()
.binary_probabilities(num_bits=3)
)
mitigated_error = self.compare_results(counts_ideal_102, mitigated_probs_102)
self.assertLess(
mitigated_error,
0.001,
"Mitigator {} did not correctly handle qubit order 1, 0, 2".format(mitigator),
)
def test_repeated_qubits_parameter(self):
"""Tests the order of mitigated qubits."""
shots = 10000
assignment_matrices = self.assignment_matrices()
mitigators = self.mitigators(assignment_matrices, qubits=[0, 1, 2])
circuit, _, _ = self.first_qubit_h_3_circuit()
counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots)
counts_ideal_012 = counts_ideal
counts_ideal_210 = Counts({"000": counts_ideal["000"], "100": counts_ideal["001"]})
for mitigator in mitigators:
mitigated_probs_210 = (
mitigator.quasi_probabilities(counts_noise, qubits=[2, 1, 0])
.nearest_probability_distribution()
.binary_probabilities(num_bits=3)
)
mitigated_error = self.compare_results(counts_ideal_210, mitigated_probs_210)
self.assertLess(
mitigated_error,
0.001,
"Mitigator {} did not correctly handle qubit order 2,1,0".format(mitigator),
)
# checking qubit order 2,1,0 should not "overwrite" the default 0,1,2
mitigated_probs_012 = (
mitigator.quasi_probabilities(counts_noise)
.nearest_probability_distribution()
.binary_probabilities(num_bits=3)
)
mitigated_error = self.compare_results(counts_ideal_012, mitigated_probs_012)
self.assertLess(
mitigated_error,
0.001,
"Mitigator {} did not correctly handle qubit order 0,1,2 (the expected default)".format(
mitigator
),
)
def test_qubits_subset_parameter(self):
"""Tests mitigation on a subset of the initial set of qubits."""
shots = 10000
assignment_matrices = self.assignment_matrices()
mitigators = self.mitigators(assignment_matrices, qubits=[2, 4, 6])
circuit, _, _ = self.first_qubit_h_3_circuit()
counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots)
counts_ideal_2 = marginal_counts(counts_ideal, [0])
counts_ideal_6 = marginal_counts(counts_ideal, [2])
for mitigator in mitigators:
mitigated_probs_2 = (
mitigator.quasi_probabilities(counts_noise, qubits=[2])
.nearest_probability_distribution()
.binary_probabilities(num_bits=1)
)
mitigated_error = self.compare_results(counts_ideal_2, mitigated_probs_2)
self.assertLess(
mitigated_error,
0.001,
"Mitigator {} did not correctly handle qubit subset".format(mitigator),
)
mitigated_probs_6 = (
mitigator.quasi_probabilities(counts_noise, qubits=[6])
.nearest_probability_distribution()
.binary_probabilities(num_bits=1)
)
mitigated_error = self.compare_results(counts_ideal_6, mitigated_probs_6)
self.assertLess(
mitigated_error,
0.001,
"Mitigator {} did not correctly handle qubit subset".format(mitigator),
)
diagonal = str2diag("ZZ")
ideal_expectation = 0
mitigated_expectation, _ = mitigator.expectation_value(
counts_noise, diagonal, qubits=[2, 6]
)
mitigated_error = np.abs(ideal_expectation - mitigated_expectation)
self.assertLess(
mitigated_error,
0.1,
"Mitigator {} did not improve circuit expectation".format(mitigator),
)
def test_from_backend(self):
"""Test whether a local mitigator can be created directly from backend properties"""
backend = FakeYorktown()
num_qubits = len(backend.properties().qubits)
probs = TestReadoutMitigation.rng.random((num_qubits, 2))
for qubit_idx, qubit_prop in enumerate(backend.properties().qubits):
for prop in qubit_prop:
if prop.name == "prob_meas1_prep0":
prop.value = probs[qubit_idx][0]
if prop.name == "prob_meas0_prep1":
prop.value = probs[qubit_idx][1]
LRM_from_backend = LocalReadoutMitigator(backend=backend)
mats = []
for qubit_idx in range(num_qubits):
mat = np.array(
[
[1 - probs[qubit_idx][0], probs[qubit_idx][1]],
[probs[qubit_idx][0], 1 - probs[qubit_idx][1]],
]
)
mats.append(mat)
LRM_from_matrices = LocalReadoutMitigator(assignment_matrices=mats)
self.assertTrue(
matrix_equal(
LRM_from_backend.assignment_matrix(), LRM_from_matrices.assignment_matrix()
)
)
def test_error_handling(self):
"""Test that the assignment matrices are valid."""
bad_matrix_A = np.array([[-0.3, 1], [1.3, 0]]) # negative indices
bad_matrix_B = np.array([[0.2, 1], [0.7, 0]]) # columns not summing to 1
good_matrix_A = np.array([[0.2, 1], [0.8, 0]])
for bad_matrix in [bad_matrix_A, bad_matrix_B]:
with self.assertRaises(QiskitError) as cm:
CorrelatedReadoutMitigator(bad_matrix)
self.assertEqual(
cm.exception.message,
"Assignment matrix columns must be valid probability distributions",
)
with self.assertRaises(QiskitError) as cm:
amats = [good_matrix_A, bad_matrix_A]
LocalReadoutMitigator(amats)
self.assertEqual(
cm.exception.message,
"Assignment matrix columns must be valid probability distributions",
)
with self.assertRaises(QiskitError) as cm:
amats = [bad_matrix_B, good_matrix_A]
LocalReadoutMitigator(amats)
self.assertEqual(
cm.exception.message,
"Assignment matrix columns must be valid probability distributions",
)
def test_expectation_value_endian(self):
"""Test that endian for expval is little."""
mitigators = self.mitigators(self.assignment_matrices())
counts = Counts({"10": 3, "11": 24, "00": 74, "01": 923})
for mitigator in mitigators:
expval, _ = mitigator.expectation_value(counts, diagonal="IZ", qubits=[0, 1])
self.assertAlmostEqual(expval, -1.0, places=0)
def test_quasi_probabilities_shots_passing(self):
"""Test output of LocalReadoutMitigator.quasi_probabilities
We require the number of shots to be set in the output.
"""
mitigator = LocalReadoutMitigator([np.array([[0.9, 0.1], [0.1, 0.9]])], qubits=[0])
counts = Counts({"10": 3, "11": 24, "00": 74, "01": 923})
quasi_dist = mitigator.quasi_probabilities(counts)
self.assertEqual(quasi_dist.shots, sum(counts.values()))
# custom number of shots
quasi_dist = mitigator.quasi_probabilities(counts, shots=1025)
self.assertEqual(quasi_dist.shots, 1025)
class TestLocalReadoutMitigation(QiskitTestCase):
"""Tests specific to the local readout mitigator"""
def test_assignment_matrix(self):
"""Tests that the local mitigator generates the full assignment matrix correctly"""
qubits = [7, 2, 3]
assignment_matrices = LocalReadoutMitigator(backend=FakeYorktown())._assignment_mats[0:3]
expected_assignment_matrix = np.kron(
np.kron(assignment_matrices[2], assignment_matrices[1]), assignment_matrices[0]
)
expected_mitigation_matrix = np.linalg.inv(expected_assignment_matrix)
LRM = LocalReadoutMitigator(assignment_matrices, qubits)
self.assertTrue(matrix_equal(expected_mitigation_matrix, LRM.mitigation_matrix()))
self.assertTrue(matrix_equal(expected_assignment_matrix, LRM.assignment_matrix()))
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test cases for the pulse scheduler passes."""
from numpy import pi
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, schedule
from qiskit.circuit import Gate, Parameter
from qiskit.circuit.library import U1Gate, U2Gate, U3Gate
from qiskit.exceptions import QiskitError
from qiskit.pulse import (
Schedule,
DriveChannel,
AcquireChannel,
Acquire,
MeasureChannel,
MemorySlot,
Gaussian,
Play,
transforms,
)
from qiskit.pulse import build, macros, play, InstructionScheduleMap
from qiskit.providers.fake_provider import FakeBackend, FakeOpenPulse2Q, FakeOpenPulse3Q
from qiskit.test import QiskitTestCase
class TestBasicSchedule(QiskitTestCase):
"""Scheduling tests."""
def setUp(self):
super().setUp()
self.backend = FakeOpenPulse2Q()
self.inst_map = self.backend.defaults().instruction_schedule_map
def test_unavailable_defaults(self):
"""Test backend with unavailable defaults."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
backend = FakeBackend(None)
backend.defaults = backend.configuration
self.assertRaises(QiskitError, lambda: schedule(qc, backend))
def test_alap_pass(self):
"""Test ALAP scheduling."""
# βββββββββββββββββ β βββ
# q0_0: β€ U2(3.14,1.57) ββββββββββββββββββββββββββ βββ€Mββββ
# ββ¬βββββββββββββββ€ β ββββββββββββββββ β βββ΄ββββ₯ββββ
# q0_1: ββ€ U2(0.5,0.25) βββββ€ U2(0.5,0.25) βββββ€ X βββ«ββ€Mβ
# ββββββββββββββββ β ββββββββββββββββ β βββββ β ββ₯β
# c0: 2/ββββββββββββββββββββββββββββββββββββββββββββββ©βββ©β
# 0 1
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.append(U2Gate(3.14, 1.57), [q[0]])
qc.append(U2Gate(0.5, 0.25), [q[1]])
qc.barrier(q[1])
qc.append(U2Gate(0.5, 0.25), [q[1]])
qc.barrier(q[0], [q[1]])
qc.cx(q[0], q[1])
qc.measure(q, c)
sched = schedule(qc, self.backend)
# X pulse on q0 should end at the start of the CNOT
expected = Schedule(
(2, self.inst_map.get("u2", [0], 3.14, 1.57)),
self.inst_map.get("u2", [1], 0.5, 0.25),
(2, self.inst_map.get("u2", [1], 0.5, 0.25)),
(4, self.inst_map.get("cx", [0, 1])),
(26, self.inst_map.get("measure", [0, 1])),
)
for actual, expected in zip(sched.instructions, expected.instructions):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
def test_single_circuit_list_schedule(self):
"""Test that passing a single circuit list to schedule() returns a list."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
sched = schedule([qc], self.backend, method="alap")
expected = Schedule()
self.assertIsInstance(sched, list)
self.assertEqual(sched[0].instructions, expected.instructions)
def test_alap_with_barriers(self):
"""Test that ALAP respects barriers on new qubits."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.append(U2Gate(0, 0), [q[0]])
qc.barrier(q[0], q[1])
qc.append(U2Gate(0, 0), [q[1]])
sched = schedule(qc, self.backend, method="alap")
expected = Schedule(
self.inst_map.get("u2", [0], 0, 0), (2, self.inst_map.get("u2", [1], 0, 0))
)
for actual, expected in zip(sched.instructions, expected.instructions):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
def test_empty_circuit_schedule(self):
"""Test empty circuit being scheduled."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
sched = schedule(qc, self.backend, method="alap")
expected = Schedule()
self.assertEqual(sched.instructions, expected.instructions)
def test_alap_aligns_end(self):
"""Test that ALAP always acts as though there is a final global barrier."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.append(U3Gate(0, 0, 0), [q[0]])
qc.append(U2Gate(0, 0), [q[1]])
sched = schedule(qc, self.backend, method="alap")
expected_sched = Schedule(
(2, self.inst_map.get("u2", [1], 0, 0)), self.inst_map.get("u3", [0], 0, 0, 0)
)
for actual, expected in zip(sched.instructions, expected_sched.instructions):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
self.assertEqual(
sched.ch_duration(DriveChannel(0)), expected_sched.ch_duration(DriveChannel(1))
)
def test_asap_pass(self):
"""Test ASAP scheduling."""
# βββββββββββββββββ β βββ
# q0_0: β€ U2(3.14,1.57) ββββββββββββββββββββββββββ βββ€Mββββ
# ββ¬βββββββββββββββ€ β ββββββββββββββββ β βββ΄ββββ₯ββββ
# q0_1: ββ€ U2(0.5,0.25) βββββ€ U2(0.5,0.25) βββββ€ X βββ«ββ€Mβ
# ββββββββββββββββ β ββββββββββββββββ β βββββ β ββ₯β
# c0: 2/ββββββββββββββββββββββββββββββββββββββββββββββ©βββ©β
# 0 1
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.append(U2Gate(3.14, 1.57), [q[0]])
qc.append(U2Gate(0.5, 0.25), [q[1]])
qc.barrier(q[1])
qc.append(U2Gate(0.5, 0.25), [q[1]])
qc.barrier(q[0], q[1])
qc.cx(q[0], q[1])
qc.measure(q, c)
sched = schedule(qc, self.backend, method="as_soon_as_possible")
# X pulse on q0 should start at t=0
expected = Schedule(
self.inst_map.get("u2", [0], 3.14, 1.57),
self.inst_map.get("u2", [1], 0.5, 0.25),
(2, self.inst_map.get("u2", [1], 0.5, 0.25)),
(4, self.inst_map.get("cx", [0, 1])),
(26, self.inst_map.get("measure", [0, 1])),
)
for actual, expected in zip(sched.instructions, expected.instructions):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
def test_alap_resource_respecting(self):
"""Test that the ALAP pass properly respects busy resources when backwards scheduling.
For instance, a CX on 0 and 1 followed by an X on only 1 must respect both qubits'
timeline."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.cx(q[0], q[1])
qc.append(U2Gate(0.5, 0.25), [q[1]])
sched = schedule(qc, self.backend, method="as_late_as_possible")
insts = sched.instructions
self.assertEqual(insts[0][0], 0)
self.assertEqual(insts[6][0], 22)
qc = QuantumCircuit(q, c)
qc.cx(q[0], q[1])
qc.append(U2Gate(0.5, 0.25), [q[1]])
qc.measure(q, c)
sched = schedule(qc, self.backend, method="as_late_as_possible")
self.assertEqual(sched.instructions[-1][0], 24)
def test_inst_map_schedules_unaltered(self):
"""Test that forward scheduling doesn't change relative timing with a command."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.cx(q[0], q[1])
sched1 = schedule(qc, self.backend, method="as_soon_as_possible")
sched2 = schedule(qc, self.backend, method="as_late_as_possible")
for asap, alap in zip(sched1.instructions, sched2.instructions):
self.assertEqual(asap[0], alap[0])
self.assertEqual(asap[1], alap[1])
insts = sched1.instructions
self.assertEqual(insts[0][0], 0) # shift phase
self.assertEqual(insts[1][0], 0) # ym_d0
self.assertEqual(insts[2][0], 0) # x90p_d1
self.assertEqual(insts[3][0], 2) # cr90p_u0
self.assertEqual(insts[4][0], 11) # xp_d0
self.assertEqual(insts[5][0], 13) # cr90m_u0
def test_measure_combined(self):
"""
Test to check for measure on the same qubit which generated another measure schedule.
The measures on different qubits are combined, but measures on the same qubit
adds another measure to the schedule.
"""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.append(U2Gate(3.14, 1.57), [q[0]])
qc.cx(q[0], q[1])
qc.measure(q[0], c[0])
qc.measure(q[1], c[1])
qc.measure(q[1], c[1])
sched = schedule(qc, self.backend, method="as_soon_as_possible")
expected = Schedule(
self.inst_map.get("u2", [0], 3.14, 1.57),
(2, self.inst_map.get("cx", [0, 1])),
(24, self.inst_map.get("measure", [0, 1])),
(34, self.inst_map.get("measure", [0, 1]).filter(channels=[MeasureChannel(1)])),
(34, Acquire(10, AcquireChannel(1), MemorySlot(1))),
)
self.assertEqual(sched.instructions, expected.instructions)
def test_3q_schedule(self):
"""Test a schedule that was recommended by David McKay :D"""
# βββββββββββββββββββ
# q0_0: ββββββββββ ββββββββββ€ U3(3.14,1.57,0) βββββββββββββββββββββββββ
# βββ΄ββ ββ¬ββββββββββββββββ¬β
# q0_1: ββββββββ€ X ββββββββββ€ U2(3.14,1.57) βββββ βββββββββββββββββββββ
# ββββββββ΄ββββ΄βββββββ βββββββββββββββββ βββ΄βββββββββββββββββββββ
# q0_2: β€ U2(0.778,0.122) βββββββββββββββββββββ€ X ββ€ U2(0.778,0.122) β
# βββββββββββββββββββ ββββββββββββββββββββββββ
backend = FakeOpenPulse3Q()
inst_map = backend.defaults().instruction_schedule_map
q = QuantumRegister(3)
c = ClassicalRegister(3)
qc = QuantumCircuit(q, c)
qc.cx(q[0], q[1])
qc.append(U2Gate(0.778, 0.122), [q[2]])
qc.append(U3Gate(3.14, 1.57, 0), [q[0]])
qc.append(U2Gate(3.14, 1.57), [q[1]])
qc.cx(q[1], q[2])
qc.append(U2Gate(0.778, 0.122), [q[2]])
sched = schedule(qc, backend)
expected = Schedule(
inst_map.get("cx", [0, 1]),
(22, inst_map.get("u2", [1], 3.14, 1.57)),
(22, inst_map.get("u2", [2], 0.778, 0.122)),
(24, inst_map.get("cx", [1, 2])),
(44, inst_map.get("u3", [0], 3.14, 1.57, 0)),
(46, inst_map.get("u2", [2], 0.778, 0.122)),
)
for actual, expected in zip(sched.instructions, expected.instructions):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
def test_schedule_multi(self):
"""Test scheduling multiple circuits at once."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc0 = QuantumCircuit(q, c)
qc0.cx(q[0], q[1])
qc1 = QuantumCircuit(q, c)
qc1.cx(q[0], q[1])
schedules = schedule([qc0, qc1], self.backend)
expected_insts = schedule(qc0, self.backend).instructions
for actual, expected in zip(schedules[0].instructions, expected_insts):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
def test_circuit_name_kept(self):
"""Test that the new schedule gets its name from the circuit."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c, name="CIRCNAME")
qc.cx(q[0], q[1])
sched = schedule(qc, self.backend, method="asap")
self.assertEqual(sched.name, qc.name)
sched = schedule(qc, self.backend, method="alap")
self.assertEqual(sched.name, qc.name)
def test_can_add_gates_into_free_space(self):
"""The scheduler does some time bookkeeping to know when qubits are free to be
scheduled. Make sure this works for qubits that are used in the future. This was
a bug, uncovered by this example:
q0 = - - - - |X|
q1 = |X| |u2| |X|
In ALAP scheduling, the next operation on qubit 0 would be added at t=0 rather
than immediately before the X gate.
"""
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
for i in range(2):
qc.append(U2Gate(0, 0), [qr[i]])
qc.append(U1Gate(3.14), [qr[i]])
qc.append(U2Gate(0, 0), [qr[i]])
sched = schedule(qc, self.backend, method="alap")
expected = Schedule(
self.inst_map.get("u2", [0], 0, 0),
self.inst_map.get("u2", [1], 0, 0),
(2, self.inst_map.get("u1", [0], 3.14)),
(2, self.inst_map.get("u1", [1], 3.14)),
(2, self.inst_map.get("u2", [0], 0, 0)),
(2, self.inst_map.get("u2", [1], 0, 0)),
)
for actual, expected in zip(sched.instructions, expected.instructions):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
def test_barriers_in_middle(self):
"""As a follow on to `test_can_add_gates_into_free_space`, similar issues
arose for barriers, specifically.
"""
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
for i in range(2):
qc.append(U2Gate(0, 0), [qr[i]])
qc.barrier(qr[i])
qc.append(U1Gate(3.14), [qr[i]])
qc.barrier(qr[i])
qc.append(U2Gate(0, 0), [qr[i]])
sched = schedule(qc, self.backend, method="alap")
expected = Schedule(
self.inst_map.get("u2", [0], 0, 0),
self.inst_map.get("u2", [1], 0, 0),
(2, self.inst_map.get("u1", [0], 3.14)),
(2, self.inst_map.get("u1", [1], 3.14)),
(2, self.inst_map.get("u2", [0], 0, 0)),
(2, self.inst_map.get("u2", [1], 0, 0)),
)
for actual, expected in zip(sched.instructions, expected.instructions):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
def test_parametric_input(self):
"""Test that scheduling works with parametric pulses as input."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.append(Gate("gauss", 1, []), qargs=[qr[0]])
custom_gauss = Schedule(
Play(Gaussian(duration=25, sigma=4, amp=0.5, angle=pi / 2), DriveChannel(0))
)
self.inst_map.add("gauss", [0], custom_gauss)
sched = schedule(qc, self.backend, inst_map=self.inst_map)
self.assertEqual(sched.instructions[0], custom_gauss.instructions[0])
def test_pulse_gates(self):
"""Test scheduling calibrated pulse gates."""
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.append(U2Gate(0, 0), [q[0]])
qc.barrier(q[0], q[1])
qc.append(U2Gate(0, 0), [q[1]])
qc.add_calibration("u2", [0], Schedule(Play(Gaussian(28, 0.2, 4), DriveChannel(0))), [0, 0])
qc.add_calibration("u2", [1], Schedule(Play(Gaussian(28, 0.2, 4), DriveChannel(1))), [0, 0])
sched = schedule(qc, self.backend)
expected = Schedule(
Play(Gaussian(28, 0.2, 4), DriveChannel(0)),
(28, Schedule(Play(Gaussian(28, 0.2, 4), DriveChannel(1)))),
)
self.assertEqual(sched.instructions, expected.instructions)
def test_calibrated_measurements(self):
"""Test scheduling calibrated measurements."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.append(U2Gate(0, 0), [q[0]])
qc.measure(q[0], c[0])
meas_sched = Play(Gaussian(1200, 0.2, 4), MeasureChannel(0))
meas_sched |= Acquire(1200, AcquireChannel(0), MemorySlot(0))
qc.add_calibration("measure", [0], meas_sched)
sched = schedule(qc, self.backend)
expected = Schedule(self.inst_map.get("u2", [0], 0, 0), (2, meas_sched))
self.assertEqual(sched.instructions, expected.instructions)
def test_subset_calibrated_measurements(self):
"""Test that measurement calibrations can be added and used for some qubits, even
if the other qubits do not also have calibrated measurements."""
qc = QuantumCircuit(3, 3)
qc.measure(0, 0)
qc.measure(1, 1)
qc.measure(2, 2)
meas_scheds = []
for qubit in [0, 2]:
meas = Play(Gaussian(1200, 0.2, 4), MeasureChannel(qubit)) + Acquire(
1200, AcquireChannel(qubit), MemorySlot(qubit)
)
meas_scheds.append(meas)
qc.add_calibration("measure", [qubit], meas)
meas = macros.measure([1], FakeOpenPulse3Q())
meas = meas.exclude(channels=[AcquireChannel(0), AcquireChannel(2)])
sched = schedule(qc, FakeOpenPulse3Q())
expected = Schedule(meas_scheds[0], meas_scheds[1], meas)
self.assertEqual(sched.instructions, expected.instructions)
def test_clbits_of_calibrated_measurements(self):
"""Test that calibrated measurements are only used when the classical bits also match."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.measure(q[0], c[1])
meas_sched = Play(Gaussian(1200, 0.2, 4), MeasureChannel(0))
meas_sched |= Acquire(1200, AcquireChannel(0), MemorySlot(0))
qc.add_calibration("measure", [0], meas_sched)
sched = schedule(qc, self.backend)
# Doesn't use the calibrated schedule because the classical memory slots do not match
expected = Schedule(macros.measure([0], self.backend, qubit_mem_slots={0: 1}))
self.assertEqual(sched.instructions, expected.instructions)
def test_metadata_is_preserved_alap(self):
"""Test that circuit metadata is preserved in output schedule with alap."""
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.append(U2Gate(0, 0), [q[0]])
qc.barrier(q[0], q[1])
qc.append(U2Gate(0, 0), [q[1]])
qc.metadata = {"experiment_type": "gst", "execution_number": "1234"}
sched = schedule(qc, self.backend, method="alap")
self.assertEqual({"experiment_type": "gst", "execution_number": "1234"}, sched.metadata)
def test_metadata_is_preserved_asap(self):
"""Test that circuit metadata is preserved in output schedule with asap."""
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.append(U2Gate(0, 0), [q[0]])
qc.barrier(q[0], q[1])
qc.append(U2Gate(0, 0), [q[1]])
qc.metadata = {"experiment_type": "gst", "execution_number": "1234"}
sched = schedule(qc, self.backend, method="asap")
self.assertEqual({"experiment_type": "gst", "execution_number": "1234"}, sched.metadata)
def test_scheduler_with_params_bound(self):
"""Test scheduler with parameters defined and bound"""
x = Parameter("x")
qc = QuantumCircuit(2)
qc.append(Gate("pulse_gate", 1, [x]), [0])
expected_schedule = Schedule()
qc.add_calibration(gate="pulse_gate", qubits=[0], schedule=expected_schedule, params=[x])
qc = qc.assign_parameters({x: 1})
sched = schedule(qc, self.backend)
self.assertEqual(sched, expected_schedule)
def test_scheduler_with_params_not_bound(self):
"""Test scheduler with parameters defined but not bound"""
x = Parameter("amp")
qc = QuantumCircuit(2)
qc.append(Gate("pulse_gate", 1, [x]), [0])
with build() as expected_schedule:
play(Gaussian(duration=160, amp=x, sigma=40), DriveChannel(0))
qc.add_calibration(gate="pulse_gate", qubits=[0], schedule=expected_schedule, params=[x])
sched = schedule(qc, self.backend)
self.assertEqual(sched, transforms.target_qobj_transform(expected_schedule))
def test_schedule_block_in_instmap(self):
"""Test schedule block in instmap can be scheduled."""
duration = Parameter("duration")
with build() as pulse_prog:
play(Gaussian(duration, 0.1, 10), DriveChannel(0))
instmap = InstructionScheduleMap()
instmap.add("block_gate", (0,), pulse_prog, ["duration"])
qc = QuantumCircuit(1)
qc.append(Gate("block_gate", 1, [duration]), [0])
qc.assign_parameters({duration: 100}, inplace=True)
sched = schedule(qc, self.backend, inst_map=instmap)
ref_sched = Schedule()
ref_sched += Play(Gaussian(100, 0.1, 10), DriveChannel(0))
self.assertEqual(sched, ref_sched)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test -CZ-CX- joint synthesis function."""
import unittest
from test import combine
import numpy as np
from ddt import ddt
from qiskit import QuantumCircuit
from qiskit.quantum_info import Clifford
from qiskit.synthesis.linear_phase.cx_cz_depth_lnn import synth_cx_cz_depth_line_my
from qiskit.synthesis.linear import (
synth_cnot_depth_line_kms,
random_invertible_binary_matrix,
)
from qiskit.synthesis.linear.linear_circuits_utils import check_lnn_connectivity
from qiskit.test import QiskitTestCase
@ddt
class TestCXCZSynth(QiskitTestCase):
"""Test the linear reversible circuit synthesis functions."""
@combine(num_qubits=[3, 4, 5, 6, 7, 8, 9, 10])
def test_cx_cz_synth_lnn(self, num_qubits):
"""Test the CXCZ synthesis code for linear nearest neighbour connectivity."""
seed = 1234
rng = np.random.default_rng(seed)
num_gates = 10
num_trials = 8
for _ in range(num_trials):
# Generate a random CZ circuit
mat_z = np.zeros((num_qubits, num_qubits))
cir_z = QuantumCircuit(num_qubits)
for _ in range(num_gates):
i = rng.integers(num_qubits)
j = rng.integers(num_qubits)
if i != j:
cir_z.cz(i, j)
if j > i:
mat_z[i][j] = (mat_z[i][j] + 1) % 2
else:
mat_z[j][i] = (mat_z[j][i] + 1) % 2
# Generate a random CX circuit
mat_x = random_invertible_binary_matrix(num_qubits, seed=rng)
mat_x = np.array(mat_x, dtype=bool)
cir_x = synth_cnot_depth_line_kms(mat_x)
# Joint Synthesis
cir_zx_test = QuantumCircuit.compose(cir_z, cir_x)
cir_zx = synth_cx_cz_depth_line_my(mat_x, mat_z)
# Check that the output circuit 2-qubit depth is at most 5n
depth2q = cir_zx.depth(filter_function=lambda x: x.operation.num_qubits == 2)
self.assertTrue(depth2q <= 5 * num_qubits)
# Check that the output circuit has LNN connectivity
self.assertTrue(check_lnn_connectivity(cir_zx))
# Assert that we get the same elements as other methods
self.assertEqual(Clifford(cir_zx), Clifford(cir_zx_test))
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test CZ circuits synthesis functions."""
import unittest
from test import combine
import numpy as np
from ddt import ddt
from qiskit import QuantumCircuit
from qiskit.circuit.library import Permutation
from qiskit.synthesis.linear_phase import synth_cz_depth_line_mr
from qiskit.synthesis.linear.linear_circuits_utils import check_lnn_connectivity
from qiskit.quantum_info import Clifford
from qiskit.test import QiskitTestCase
@ddt
class TestCZSynth(QiskitTestCase):
"""Test the linear reversible circuit synthesis functions."""
@combine(num_qubits=[3, 4, 5, 6, 7])
def test_cz_synth_lnn(self, num_qubits):
"""Test the CZ synthesis code for linear nearest neighbour connectivity."""
seed = 1234
rng = np.random.default_rng(seed)
num_gates = 10
num_trials = 5
for _ in range(num_trials):
mat = np.zeros((num_qubits, num_qubits))
qctest = QuantumCircuit(num_qubits)
# Generate a random CZ circuit
for _ in range(num_gates):
i = rng.integers(num_qubits)
j = rng.integers(num_qubits)
if i != j:
qctest.cz(i, j)
if j > i:
mat[i][j] = (mat[i][j] + 1) % 2
else:
mat[j][i] = (mat[j][i] + 1) % 2
qc = synth_cz_depth_line_mr(mat)
# Check that the output circuit 2-qubit depth equals to 2*n+2
depth2q = qc.depth(filter_function=lambda x: x.operation.num_qubits == 2)
self.assertTrue(depth2q == 2 * num_qubits + 2)
# Check that the output circuit has LNN connectivity
self.assertTrue(check_lnn_connectivity(qc))
# Assert that we get the same element, up to reverse order of qubits
perm = Permutation(num_qubits=num_qubits, pattern=range(num_qubits)[::-1])
qctest = qctest.compose(perm)
self.assertEqual(Clifford(qc), Clifford(qctest))
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test linear reversible circuits synthesis functions."""
import unittest
import numpy as np
from ddt import ddt, data
from qiskit import QuantumCircuit
from qiskit.circuit.library import LinearFunction
from qiskit.synthesis.linear import (
synth_cnot_count_full_pmh,
synth_cnot_depth_line_kms,
random_invertible_binary_matrix,
check_invertible_binary_matrix,
calc_inverse_matrix,
)
from qiskit.synthesis.linear.linear_circuits_utils import transpose_cx_circ, optimize_cx_4_options
from qiskit.test import QiskitTestCase
@ddt
class TestLinearSynth(QiskitTestCase):
"""Test the linear reversible circuit synthesis functions."""
def test_lnn_circuit(self):
"""Test the synthesis of a CX circuit with LNN connectivity."""
n = 5
qc = QuantumCircuit(n)
for i in range(n - 1):
qc.cx(i, i + 1)
mat = LinearFunction(qc).linear
for optimized in [True, False]:
optimized_qc = optimize_cx_4_options(
synth_cnot_count_full_pmh, mat, optimize_count=optimized
)
self.assertEqual(optimized_qc.depth(), 4)
self.assertEqual(optimized_qc.count_ops()["cx"], 4)
def test_full_circuit(self):
"""Test the synthesis of a CX circuit with full connectivity."""
n = 5
qc = QuantumCircuit(n)
for i in range(n):
for j in range(i + 1, n):
qc.cx(i, j)
mat = LinearFunction(qc).linear
for optimized in [True, False]:
optimized_qc = optimize_cx_4_options(
synth_cnot_count_full_pmh, mat, optimize_count=optimized
)
self.assertEqual(optimized_qc.depth(), 4)
self.assertEqual(optimized_qc.count_ops()["cx"], 4)
def test_transpose_circ(self):
"""Test the transpose_cx_circ() function."""
n = 5
mat = random_invertible_binary_matrix(n, seed=1234)
qc = synth_cnot_count_full_pmh(mat)
transposed_qc = transpose_cx_circ(qc)
transposed_mat = LinearFunction(transposed_qc).linear.astype(int)
self.assertTrue((mat.transpose() == transposed_mat).all())
def test_example_circuit(self):
"""Test the synthesis of an example CX circuit which provides different CX count
and depth for different optimization methods."""
qc = QuantumCircuit(9)
qc.swap(8, 7)
qc.swap(7, 6)
qc.cx(5, 6)
qc.cx(6, 5)
qc.swap(4, 5)
qc.cx(3, 4)
qc.cx(4, 3)
qc.swap(2, 3)
qc.cx(1, 2)
qc.cx(2, 1)
qc.cx(0, 1)
qc.cx(1, 0)
mat = LinearFunction(qc).linear
optimized_qc = optimize_cx_4_options(synth_cnot_count_full_pmh, mat, optimize_count=True)
self.assertEqual(optimized_qc.depth(), 17)
self.assertEqual(optimized_qc.count_ops()["cx"], 20)
optimized_qc = optimize_cx_4_options(synth_cnot_count_full_pmh, mat, optimize_count=False)
self.assertEqual(optimized_qc.depth(), 15)
self.assertEqual(optimized_qc.count_ops()["cx"], 23)
@data(5, 6)
def test_invertible_matrix(self, n):
"""Test the functions for generating a random invertible matrix and inverting it."""
mat = random_invertible_binary_matrix(n, seed=1234)
out = check_invertible_binary_matrix(mat)
mat_inv = calc_inverse_matrix(mat, verify=True)
mat_out = np.dot(mat, mat_inv) % 2
self.assertTrue(np.array_equal(mat_out, np.eye(n)))
self.assertTrue(out)
@data(5, 6)
def test_synth_lnn_kms(self, num_qubits):
"""Test that synth_cnot_depth_line_kms produces the correct synthesis."""
rng = np.random.default_rng(1234)
num_trials = 10
for _ in range(num_trials):
mat = random_invertible_binary_matrix(num_qubits, seed=rng)
mat = np.array(mat, dtype=bool)
qc = synth_cnot_depth_line_kms(mat)
mat1 = LinearFunction(qc).linear
self.assertTrue((mat == mat1).all())
# Check that the circuit depth is bounded by 5*num_qubits
depth = qc.depth()
self.assertTrue(depth <= 5 * num_qubits)
# Check that the synthesized circuit qc fits LNN connectivity
for inst in qc.data:
self.assertEqual(inst.operation.name, "cx")
q0 = qc.find_bit(inst.qubits[0]).index
q1 = qc.find_bit(inst.qubits[1]).index
dist = abs(q0 - q1)
self.assertEqual(dist, 1)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for qiskit/tools/parallel"""
import os
import time
from unittest.mock import patch
from qiskit.tools.parallel import get_platform_parallel_default, parallel_map
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.pulse import Schedule
from qiskit.test import QiskitTestCase
def _parfunc(x):
"""Function for testing parallel_map"""
time.sleep(1)
return x
def _build_simple_circuit(_):
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
qc = QuantumCircuit(qreg, creg)
return qc
def _build_simple_schedule(_):
return Schedule()
class TestGetPlatformParallelDefault(QiskitTestCase):
"""Tests get_parallel_default_for_platform."""
def test_windows_parallel_default(self):
"""Verifies the parallel default for Windows."""
with patch("sys.platform", "win32"):
parallel_default = get_platform_parallel_default()
self.assertEqual(parallel_default, False)
def test_mac_os_unsupported_version_parallel_default(self):
"""Verifies the parallel default for macOS."""
with patch("sys.platform", "darwin"):
with patch("sys.version_info", (3, 8, 0, "final", 0)):
parallel_default = get_platform_parallel_default()
self.assertEqual(parallel_default, False)
def test_other_os_parallel_default(self):
"""Verifies the parallel default for Linux and other OSes."""
with patch("sys.platform", "linux"):
parallel_default = get_platform_parallel_default()
self.assertEqual(parallel_default, True)
class TestParallel(QiskitTestCase):
"""A class for testing parallel_map functionality."""
def test_parallel_env_flag(self):
"""Verify parallel env flag is set"""
self.assertEqual(os.getenv("QISKIT_IN_PARALLEL", None), "FALSE")
def test_parallel(self):
"""Test parallel_map"""
ans = parallel_map(_parfunc, list(range(10)))
self.assertEqual(ans, list(range(10)))
def test_parallel_circuit_names(self):
"""Verify unique circuit names in parallel"""
out_circs = parallel_map(_build_simple_circuit, list(range(10)))
names = [circ.name for circ in out_circs]
self.assertEqual(len(names), len(set(names)))
def test_parallel_schedule_names(self):
"""Verify unique schedule names in parallel"""
out_schedules = parallel_map(_build_simple_schedule, list(range(10)))
names = [schedule.name for schedule in out_schedules]
self.assertEqual(len(names), len(set(names)))
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for the wrapper functionality."""
import os
import sys
import unittest
from qiskit.utils import optionals
from qiskit.test import Path, QiskitTestCase, slow_test
# Timeout (in seconds) for a single notebook.
TIMEOUT = 1000
# Jupyter kernel to execute the notebook in.
JUPYTER_KERNEL = "python3"
@unittest.skipUnless(optionals.HAS_IBMQ, "requires IBMQ provider")
@unittest.skipUnless(optionals.HAS_JUPYTER, "involves running Jupyter notebooks")
class TestJupyter(QiskitTestCase):
"""Notebooks test case."""
def setUp(self):
super().setUp()
self.execution_path = os.path.join(Path.SDK.value, "..")
self.notebook_dir = os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
"notebooks",
)
def _execute_notebook(self, filename):
import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
# Create the preprocessor.
execute_preprocessor = ExecutePreprocessor(timeout=TIMEOUT, kernel_name=JUPYTER_KERNEL)
# Read the notebook.
with open(filename) as file_:
notebook = nbformat.read(file_, as_version=4)
top_str = """
import qiskit
import qiskit.providers.ibmq
import sys
from unittest.mock import create_autospec, MagicMock
from qiskit.providers.fake_provider import FakeProviderFactory
from qiskit.providers import basicaer
fake_prov = FakeProviderFactory()
qiskit.IBMQ = fake_prov
ibmq_mock = create_autospec(basicaer)
ibmq_mock.IBMQJobApiError = MagicMock()
sys.modules['qiskit.providers.ibmq'] = ibmq_mock
sys.modules['qiskit.providers.ibmq.job'] = ibmq_mock
sys.modules['qiskit.providers.ibmq.job.exceptions'] = ibmq_mock
"""
top = nbformat.notebooknode.NotebookNode(
{
"cell_type": "code",
"execution_count": 0,
"metadata": {},
"outputs": [],
"source": top_str,
}
)
notebook.cells = [top] + notebook.cells
# Run the notebook into the folder containing the `qiskit/` module.
execute_preprocessor.preprocess(notebook, {"metadata": {"path": self.execution_path}})
@unittest.skipIf(
sys.platform != "linux",
"Fails with Python >=3.8 on osx and windows",
)
def test_jupyter_jobs_pbars(self):
"""Test Jupyter progress bars and job status functionality"""
self._execute_notebook(os.path.join(self.notebook_dir, "test_pbar_status.ipynb"))
@unittest.skipIf(not optionals.HAS_MATPLOTLIB, "matplotlib not available.")
@slow_test
def test_backend_tools(self):
"""Test Jupyter backend tools."""
self._execute_notebook(os.path.join(self.notebook_dir, "test_backend_tools.ipynb"))
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for the wrapper functionality."""
import sys
import unittest
from unittest.mock import patch
from unittest.mock import MagicMock
from io import StringIO
import qiskit
from qiskit import providers
from qiskit.tools.monitor import backend_overview, backend_monitor
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeProviderFactory, FakeBackend, FakeVigo
class TestBackendOverview(QiskitTestCase):
"""Tools test case."""
def _restore_ibmq(self):
if not self.import_error:
qiskit.IBMQ = self.ibmq_back
else:
del qiskit.IBMQ
if self.prov_backup:
providers.ibmq = self.prov_backup
else:
del providers.ibmq
def _restore_ibmq_mod(self):
if self.ibmq_module_backup is not None:
sys.modules["qiskit.providers.ibmq"] = self.ibmq_module_backup
else:
sys.modules.pop("qiskit.providers.ibmq")
def setUp(self):
super().setUp()
ibmq_mock = MagicMock()
ibmq_mock.IBMQBackend = FakeBackend
if "qiskit.providers.ibmq" in sys.modules:
self.ibmq_module_backup = sys.modules["qiskit.providers.ibmq"]
else:
self.ibmq_module_backup = None
sys.modules["qiskit.providers.ibmq"] = ibmq_mock
self.addCleanup(self._restore_ibmq_mod)
if hasattr(qiskit, "IBMQ"):
self.import_error = False
else:
self.import_error = True
qiskit.IBMQ = None
self.ibmq_back = qiskit.IBMQ
qiskit.IBMQ = FakeProviderFactory()
self.addCleanup(self._restore_ibmq)
if hasattr(providers, "ibmq"):
self.prov_backup = providers.ibmq
else:
self.prov_backup = None
providers.ibmq = MagicMock()
@patch("qiskit.tools.monitor.overview.get_unique_backends", return_value=[FakeVigo()])
def test_backend_overview(self, _):
"""Test backend_overview"""
with patch("sys.stdout", new=StringIO()) as fake_stdout:
backend_overview()
stdout = fake_stdout.getvalue()
self.assertIn("Operational:", stdout)
self.assertIn("Avg. T1:", stdout)
self.assertIn("Num. Qubits:", stdout)
@patch("qiskit.tools.monitor.overview.get_unique_backends", return_value=[FakeVigo()])
def test_backend_monitor(self, _):
"""Test backend_monitor"""
for back in [FakeVigo()]:
if not back.configuration().simulator:
backend = back
break
with patch("sys.stdout", new=StringIO()) as fake_stdout:
backend_monitor(backend)
stdout = fake_stdout.getvalue()
self.assertIn("Configuration", stdout)
self.assertIn("Qubits [Name / Freq / T1 / T2 / ", stdout)
for gate in backend.properties().gates:
if gate.gate not in ["id"] and len(gate.qubits) == 1:
self.assertIn(gate.gate.upper() + " err", stdout)
self.assertIn("Readout err", stdout)
self.assertIn("Multi-Qubit Gates [Name / Type / Gate Error]", stdout)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for the wrapper functionality."""
import io
import unittest
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import BasicAer
from qiskit import execute
from qiskit.tools.monitor import job_monitor
from qiskit.test import QiskitTestCase
class TestJobMonitor(QiskitTestCase):
"""Tools test case."""
def test_job_monitor(self):
"""Test job_monitor"""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
qc = QuantumCircuit(qreg, creg)
qc.h(qreg[0])
qc.cx(qreg[0], qreg[1])
qc.measure(qreg, creg)
backend = BasicAer.get_backend("qasm_simulator")
job_sim = execute([qc] * 10, backend)
output = io.StringIO()
job_monitor(job_sim, output=output)
self.assertEqual(job_sim.status().name, "DONE")
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests preset pass managers with 1Q backend"""
from test import combine
from ddt import ddt
from qiskit import QuantumCircuit
from qiskit.compiler import transpile
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import Fake1Q
from qiskit.transpiler import TranspilerError
def emptycircuit():
"""Empty circuit"""
return QuantumCircuit()
def circuit_3516():
"""Circuit from https://github.com/Qiskit/qiskit-terra/issues/3516 should fail"""
circuit = QuantumCircuit(2, 1)
circuit.h(0)
circuit.ry(0.11, 1)
circuit.measure([0], [0])
return circuit
@ddt
class Test1QFailing(QiskitTestCase):
"""1Q tests that should fail."""
@combine(
circuit=[circuit_3516],
level=[0, 1, 2, 3],
dsc="Transpiling {circuit.__name__} at level {level} should fail",
name="{circuit.__name__}_level{level}_fail",
)
def test(self, circuit, level):
"""All the levels with all the 1Q backend"""
with self.assertRaises(TranspilerError):
transpile(circuit(), backend=Fake1Q(), optimization_level=level, seed_transpiler=42)
@ddt
class Test1QWorking(QiskitTestCase):
"""1Q tests that should work."""
@combine(
circuit=[emptycircuit],
level=[0, 1, 2, 3],
dsc="Transpiling {circuit.__name__} at level {level} should work",
name="{circuit.__name__}_level{level}_valid",
)
def test_device(self, circuit, level):
"""All the levels with all the 1Q backend"""
result = transpile(
circuit(), backend=Fake1Q(), optimization_level=level, seed_transpiler=42
)
self.assertIsInstance(result, QuantumCircuit)
@combine(
circuit=[circuit_3516],
level=[0, 1, 2, 3],
dsc="Transpiling {circuit.__name__} at level {level} should work for simulator",
name="{circuit.__name__}_level{level}_valid",
)
def test_simulator(self, circuit, level):
"""All the levels with all the 1Q simulator backend"""
# Set fake backend config to simulator
backend = Fake1Q()
backend._configuration.simulator = True
result = transpile(circuit(), backend=backend, optimization_level=level, seed_transpiler=42)
self.assertIsInstance(result, QuantumCircuit)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the MergeAdjacentBarriers pass"""
import random
import unittest
from qiskit.transpiler.passes import MergeAdjacentBarriers
from qiskit.converters import circuit_to_dag
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
class TestMergeAdjacentBarriers(QiskitTestCase):
"""Test the MergeAdjacentBarriers pass"""
def test_two_identical_barriers(self):
"""Merges two barriers that are identical into one
β β β
q_0: |0>ββββββ -> q_0: |0>βββ
β β β
"""
qr = QuantumRegister(1, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr)
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_numerous_identical_barriers(self):
"""Merges 5 identical barriers in a row into one
β β β β β β β
q_0: |0>ββββββββββββββββββ -> q_0: |0>βββ
β β β β β β β
"""
qr = QuantumRegister(1, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr)
circuit.barrier(qr)
circuit.barrier(qr)
circuit.barrier(qr)
circuit.barrier(qr)
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_of_different_sizes(self):
"""Test two barriers of different sizes are merged into one
β β β
q_0: |0>ββββββ q_0: |0>βββ
β β -> β
q_1: |0>ββββββ q_1: |0>βββ
β β
"""
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr[0])
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_not_overlapping_barriers(self):
"""Test two barriers with no overlap are not merged
(NB in these pictures they look like 1 barrier but they are
actually 2 distinct barriers, this is just how the text
drawer draws them)
β β
q_0: |0>βββ q_0: |0>βββ
β -> β
q_1: |0>βββ q_1: |0>βββ
β β
"""
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr[0])
circuit.barrier(qr[1])
expected = QuantumCircuit(qr)
expected.barrier(qr[0])
expected.barrier(qr[1])
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_with_obstacle_before(self):
"""Test with an obstacle before the larger barrier
β β β
q_0: |0>ββββββββ q_0: |0>ββββββββ
βββββ β -> βββββ β
q_1: |0>β€ H ββββ q_1: |0>β€ H ββββ
βββββ β βββββ β
"""
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr[0])
circuit.h(qr[1])
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.h(qr[1])
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_with_obstacle_after(self):
"""Test with an obstacle after the larger barrier
β β β
q_0: |0>ββββββββ q_0: |0>ββββββββ
β βββββ -> β βββββ
q_1: |0>ββββ€ H β q_1: |0>ββββ€ H β
β βββββ β βββββ
"""
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr)
circuit.barrier(qr[0])
circuit.h(qr[1])
expected = QuantumCircuit(qr)
expected.barrier(qr)
expected.h(qr[1])
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_with_blocking_obstacle(self):
"""Test that barriers don't merge if there is an obstacle that
is blocking
β βββββ β β βββββ β
q_0: |0>ββββ€ H ββββ -> q_0: |0>ββββ€ H ββββ
β βββββ β β βββββ β
"""
qr = QuantumRegister(1, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr)
circuit.h(qr)
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr)
expected.h(qr)
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_with_blocking_obstacle_long(self):
"""Test that barriers don't merge if there is an obstacle that
is blocking
β βββββ β β βββββ β
q_0: |0>ββββ€ H ββββ q_0: |0>ββββ€ H ββββ
β βββββ β -> β βββββ β
q_1: |0>βββββββββββ q_1: |0>βββββββββββ
β β
"""
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr[0])
circuit.h(qr[0])
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr[0])
expected.h(qr[0])
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_with_blocking_obstacle_narrow(self):
"""Test that barriers don't merge if there is an obstacle that
is blocking
β βββββ β β βββββ β
q_0: |0>ββββ€ H ββββ q_0: |0>ββββ€ H ββββ
β βββββ β -> β βββββ β
q_1: |0>βββββββββββ q_1: |0>βββββββββββ
β β β β
"""
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr)
circuit.h(qr[0])
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr)
expected.h(qr[0])
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_with_blocking_obstacle_twoQ(self):
"""Test that barriers don't merge if there is an obstacle that
is blocking
β β β β
q_0: |0>βββββββββββ q_0: |0>βββββββββββ
β β β β
q_1: |0>ββββββ βββββ -> q_1: |0>ββββββ βββββ
β βββ΄ββ β β βββ΄ββ β
q_2: |0>ββββ€ X ββββ q_2: |0>ββββ€ X ββββ
βββββ β βββββ β
"""
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(0, 1)
circuit.cx(1, 2)
circuit.barrier(0, 2)
expected = QuantumCircuit(qr)
expected.barrier(0, 1)
expected.cx(1, 2)
expected.barrier(0, 2)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_output_deterministic(self):
"""Test that the output barriers have a deterministic ordering (independent of
PYTHONHASHSEED). This is important to guarantee that any subsequent topological iterations
through the circuit are also deterministic; it's in general not possible for all transpiler
passes to produce identical outputs across all valid topological orderings, especially if
those passes have some stochastic element."""
order = list(range(20))
random.Random(2023_02_10).shuffle(order)
circuit = QuantumCircuit(20)
circuit.barrier([5, 2, 3])
circuit.barrier([7, 11, 14, 2, 4])
circuit.barrier(order)
# All the barriers should get merged together.
expected = QuantumCircuit(20)
expected.barrier(range(20))
output = MergeAdjacentBarriers()(circuit)
self.assertEqual(expected, output)
# This assertion is that the ordering of the arguments in the barrier is fixed.
self.assertEqual(list(output.data[0].qubits), list(output.qubits))
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the BasicSwap pass"""
import unittest
from qiskit.transpiler.passes import BasicSwap
from qiskit.transpiler.passmanager import PassManager
from qiskit.transpiler.layout import Layout
from qiskit.transpiler import CouplingMap, Target
from qiskit.circuit.library import CXGate
from qiskit.converters import circuit_to_dag
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
class TestBasicSwap(QiskitTestCase):
"""Tests the BasicSwap pass."""
def test_trivial_case(self):
"""No need to have any swap, the CX are distance 1 to each other
q0:--(+)-[U]-(+)-
| |
q1:---.-------|--
|
q2:-----------.--
CouplingMap map: [1]--[0]--[2]
"""
coupling = CouplingMap([[0, 1], [0, 2]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.cx(qr[0], qr[2])
dag = circuit_to_dag(circuit)
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_trivial_in_same_layer(self):
"""No need to have any swap, two CXs distance 1 to each other, in the same layer
q0:--(+)--
|
q1:---.---
q2:--(+)--
|
q3:---.---
CouplingMap map: [0]--[1]--[2]--[3]
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[2], qr[3])
circuit.cx(qr[0], qr[1])
dag = circuit_to_dag(circuit)
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_a_single_swap(self):
"""Adding a swap
q0:-------
q1:--(+)--
|
q2:---.---
CouplingMap map: [1]--[0]--[2]
q0:--X---.---
| |
q1:--X---|---
|
q2:-----(+)--
"""
coupling = CouplingMap([[0, 1], [0, 2]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[1], qr[0])
expected.cx(qr[0], qr[2])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_a_single_swap_with_target(self):
"""Adding a swap
q0:-------
q1:--(+)--
|
q2:---.---
CouplingMap map: [1]--[0]--[2]
q0:--X---.---
| |
q1:--X---|---
|
q2:-----(+)--
"""
target = Target()
target.add_instruction(CXGate(), {(0, 1): None, (0, 2): None})
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[1], qr[0])
expected.cx(qr[0], qr[2])
pass_ = BasicSwap(target)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_a_single_swap_bigger_cm(self):
"""Swapper in a bigger coupling map
q0:-------
q1:---.---
|
q2:--(+)--
CouplingMap map: [1]--[0]--[2]--[3]
q0:--X---.---
| |
q1:--X---|---
|
q2:-----(+)--
"""
coupling = CouplingMap([[0, 1], [0, 2], [2, 3]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[1], qr[0])
expected.cx(qr[0], qr[2])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_keep_layout(self):
"""After a swap, the following gates also change the wires.
qr0:---.---[H]--
|
qr1:---|--------
|
qr2:--(+)-------
CouplingMap map: [0]--[1]--[2]
qr0:--X-----------
|
qr1:--X---.--[H]--
|
qr2:-----(+)------
"""
coupling = CouplingMap([[1, 0], [1, 2]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[2])
circuit.h(qr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[0], qr[1])
expected.cx(qr[1], qr[2])
expected.h(qr[1])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_far_swap(self):
"""A far swap that affects coming CXs.
qr0:--(+)---.--
| |
qr1:---|----|--
| |
qr2:---|----|--
| |
qr3:---.---(+)-
CouplingMap map: [0]--[1]--[2]--[3]
qr0:--X--------------
|
qr1:--X--X-----------
|
qr2:-----X--(+)---.--
| |
qr3:---------.---(+)-
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[3])
circuit.cx(qr[3], qr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[0], qr[1])
expected.swap(qr[1], qr[2])
expected.cx(qr[2], qr[3])
expected.cx(qr[3], qr[2])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_far_swap_with_gate_the_front(self):
"""A far swap with a gate in the front.
q0:------(+)--
|
q1:-------|---
|
q2:-------|---
|
q3:--[H]--.---
CouplingMap map: [0]--[1]--[2]--[3]
q0:-----------(+)--
|
q1:---------X--.---
|
q2:------X--X------
|
q3:-[H]--X---------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.h(qr[3])
circuit.cx(qr[3], qr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.h(qr[3])
expected.swap(qr[3], qr[2])
expected.swap(qr[2], qr[1])
expected.cx(qr[1], qr[0])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_far_swap_with_gate_the_back(self):
"""A far swap with a gate in the back.
q0:--(+)------
|
q1:---|-------
|
q2:---|-------
|
q3:---.--[H]--
CouplingMap map: [0]--[1]--[2]--[3]
q0:-------(+)------
|
q1:-----X--.--[H]--
|
q2:--X--X----------
|
q3:--X-------------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[3], qr[0])
circuit.h(qr[3])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[3], qr[2])
expected.swap(qr[2], qr[1])
expected.cx(qr[1], qr[0])
expected.h(qr[1])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_far_swap_with_gate_the_middle(self):
"""A far swap with a gate in the middle.
q0:--(+)-------.--
| |
q1:---|--------|--
|
q2:---|--------|--
| |
q3:---.--[H]--(+)-
CouplingMap map: [0]--[1]--[2]--[3]
q0:-------(+)-------.---
| |
q1:-----X--.--[H]--(+)--
|
q2:--X--X---------------
|
q3:--X------------------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[3], qr[0])
circuit.h(qr[3])
circuit.cx(qr[0], qr[3])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[3], qr[2])
expected.swap(qr[2], qr[1])
expected.cx(qr[1], qr[0])
expected.h(qr[1])
expected.cx(qr[0], qr[1])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_fake_run(self):
"""A fake run, doesn't change dag
q0:--(+)-------.--
| |
q1:---|--------|--
|
q2:---|--------|--
| |
q3:---.--[H]--(+)-
CouplingMap map: [0]--[1]--[2]--[3]
q0:-------(+)-------.---
| |
q1:-----X--.--[H]--(+)--
|
q2:--X--X---------------
|
q3:--X------------------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[3], qr[0])
circuit.h(qr[3])
circuit.cx(qr[0], qr[3])
fake_pm = PassManager([BasicSwap(coupling, fake_run=True)])
real_pm = PassManager([BasicSwap(coupling, fake_run=False)])
self.assertEqual(circuit, fake_pm.run(circuit))
self.assertNotEqual(circuit, real_pm.run(circuit))
self.assertIsInstance(fake_pm.property_set["final_layout"], Layout)
self.assertEqual(fake_pm.property_set["final_layout"], real_pm.property_set["final_layout"])
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the BasisTranslator pass"""
import os
from numpy import pi
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import transpile
from qiskit.test import QiskitTestCase
from qiskit.circuit import Gate, Parameter, EquivalenceLibrary, Qubit, Clbit
from qiskit.circuit.library import (
U1Gate,
U2Gate,
U3Gate,
CU1Gate,
CU3Gate,
UGate,
RZGate,
XGate,
SXGate,
CXGate,
)
from qiskit.converters import circuit_to_dag, dag_to_circuit, circuit_to_instruction
from qiskit.exceptions import QiskitError
from qiskit.quantum_info import Operator
from qiskit.transpiler.target import Target, InstructionProperties
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.passes.basis import BasisTranslator, UnrollCustomDefinitions
from qiskit.circuit.library.standard_gates.equivalence_library import (
StandardEquivalenceLibrary as std_eqlib,
)
class OneQubitZeroParamGate(Gate):
"""Mock one qubit zero param gate."""
def __init__(self, name="1q0p"):
super().__init__(name, 1, [])
class OneQubitOneParamGate(Gate):
"""Mock one qubit one param gate."""
def __init__(self, theta, name="1q1p"):
super().__init__(name, 1, [theta])
class OneQubitOneParamPrimeGate(Gate):
"""Mock one qubit one param gate."""
def __init__(self, alpha):
super().__init__("1q1p_prime", 1, [alpha])
class OneQubitTwoParamGate(Gate):
"""Mock one qubit two param gate."""
def __init__(self, phi, lam, name="1q2p"):
super().__init__(name, 1, [phi, lam])
class TwoQubitZeroParamGate(Gate):
"""Mock one qubit zero param gate."""
def __init__(self, name="2q0p"):
super().__init__(name, 2, [])
class VariadicZeroParamGate(Gate):
"""Mock variadic zero param gate."""
def __init__(self, num_qubits, name="vq0p"):
super().__init__(name, num_qubits, [])
class TestBasisTranslator(QiskitTestCase):
"""Test the BasisTranslator pass."""
def test_circ_in_basis_no_op(self):
"""Verify we don't change a circuit already in the target basis."""
eq_lib = EquivalenceLibrary()
qc = QuantumCircuit(1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = circuit_to_dag(qc)
pass_ = BasisTranslator(eq_lib, ["1q0p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected)
def test_raise_if_target_basis_unreachable(self):
"""Verify we raise if the circuit cannot be transformed to the target."""
eq_lib = EquivalenceLibrary()
qc = QuantumCircuit(1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
pass_ = BasisTranslator(eq_lib, ["1q1p"])
with self.assertRaises(TranspilerError):
pass_.run(dag)
def test_single_substitution(self):
"""Verify we correctly unroll gates through a single equivalence."""
eq_lib = EquivalenceLibrary()
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1)
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1)
expected.append(OneQubitOneParamGate(pi), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q1p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_double_substitution(self):
"""Verify we correctly unroll gates through multiple equivalences."""
eq_lib = EquivalenceLibrary()
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1)
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
theta = Parameter("theta")
gate = OneQubitOneParamGate(theta)
equiv = QuantumCircuit(1)
equiv.append(OneQubitTwoParamGate(theta, pi / 2), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1)
expected.append(OneQubitTwoParamGate(pi, pi / 2), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q2p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_single_substitution_with_global_phase(self):
"""Verify we correctly unroll gates through a single equivalence with global phase."""
eq_lib = EquivalenceLibrary()
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1, global_phase=0.2)
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1, global_phase=0.1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1, global_phase=0.1 + 0.2)
expected.append(OneQubitOneParamGate(pi), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q1p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_single_two_gate_substitution_with_global_phase(self):
"""Verify we correctly unroll gates through a single equivalence with global phase."""
eq_lib = EquivalenceLibrary()
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1, global_phase=0.2)
equiv.append(OneQubitOneParamGate(pi), [0])
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1, global_phase=0.1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1, global_phase=0.1 + 0.2)
expected.append(OneQubitOneParamGate(pi), [0])
expected.append(OneQubitOneParamGate(pi), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q1p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_two_substitutions_with_global_phase(self):
"""Verify we correctly unroll gates through a single equivalences with global phase."""
eq_lib = EquivalenceLibrary()
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1, global_phase=0.2)
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1, global_phase=0.1)
qc.append(OneQubitZeroParamGate(), [0])
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1, global_phase=0.1 + 2 * 0.2)
expected.append(OneQubitOneParamGate(pi), [0])
expected.append(OneQubitOneParamGate(pi), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q1p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_two_single_two_gate_substitutions_with_global_phase(self):
"""Verify we correctly unroll gates through a single equivalence with global phase."""
eq_lib = EquivalenceLibrary()
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1, global_phase=0.2)
equiv.append(OneQubitOneParamGate(pi), [0])
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1, global_phase=0.1)
qc.append(OneQubitZeroParamGate(), [0])
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1, global_phase=0.1 + 2 * 0.2)
expected.append(OneQubitOneParamGate(pi), [0])
expected.append(OneQubitOneParamGate(pi), [0])
expected.append(OneQubitOneParamGate(pi), [0])
expected.append(OneQubitOneParamGate(pi), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q1p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_double_substitution_with_global_phase(self):
"""Verify we correctly unroll gates through multiple equivalences with global phase."""
eq_lib = EquivalenceLibrary()
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1, global_phase=0.2)
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
theta = Parameter("theta")
gate = OneQubitOneParamGate(theta)
equiv = QuantumCircuit(1, global_phase=0.4)
equiv.append(OneQubitTwoParamGate(theta, pi / 2), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1, global_phase=0.1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1, global_phase=0.1 + 0.2 + 0.4)
expected.append(OneQubitTwoParamGate(pi, pi / 2), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q2p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_multiple_variadic(self):
"""Verify circuit with multiple instances of variadic gate."""
eq_lib = EquivalenceLibrary()
# e.g. MSGate
oneq_gate = VariadicZeroParamGate(1)
equiv = QuantumCircuit(1)
equiv.append(OneQubitZeroParamGate(), [0])
eq_lib.add_equivalence(oneq_gate, equiv)
twoq_gate = VariadicZeroParamGate(2)
equiv = QuantumCircuit(2)
equiv.append(TwoQubitZeroParamGate(), [0, 1])
eq_lib.add_equivalence(twoq_gate, equiv)
qc = QuantumCircuit(2)
qc.append(VariadicZeroParamGate(1), [0])
qc.append(VariadicZeroParamGate(2), [0, 1])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(2)
expected.append(OneQubitZeroParamGate(), [0])
expected.append(TwoQubitZeroParamGate(), [0, 1])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q0p", "2q0p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_diamond_path(self):
"""Verify we find a path when there are multiple paths to the target basis."""
eq_lib = EquivalenceLibrary()
# Path 1: 1q0p -> 1q1p(pi) -> 1q2p(pi, pi/2)
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1)
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
theta = Parameter("theta")
gate = OneQubitOneParamGate(theta)
equiv = QuantumCircuit(1)
equiv.append(OneQubitTwoParamGate(theta, pi / 2), [0])
eq_lib.add_equivalence(gate, equiv)
# Path 2: 1q0p -> 1q1p_prime(pi/2) -> 1q2p(2 * pi/2, pi/2)
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1)
equiv.append(OneQubitOneParamPrimeGate(pi / 2), [0])
eq_lib.add_equivalence(gate, equiv)
alpha = Parameter("alpha")
gate = OneQubitOneParamPrimeGate(alpha)
equiv = QuantumCircuit(1)
equiv.append(OneQubitTwoParamGate(2 * alpha, pi / 2), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1)
expected.append(OneQubitTwoParamGate(pi, pi / 2), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q2p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_if_else(self):
"""Test a simple if-else with parameters."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
alpha = Parameter("alpha")
beta = Parameter("beta")
gate = OneQubitOneParamGate(alpha)
equiv = QuantumCircuit([qubits[0]])
equiv.append(OneQubitZeroParamGate(name="1q0p_2"), [qubits[0]])
equiv.append(OneQubitOneParamGate(alpha, name="1q1p_2"), [qubits[0]])
eq_lib = EquivalenceLibrary()
eq_lib.add_equivalence(gate, equiv)
circ = QuantumCircuit(qubits, clbits)
circ.append(OneQubitOneParamGate(beta), [qubits[0]])
circ.measure(qubits[0], clbits[1])
with circ.if_test((clbits[1], 0)) as else_:
circ.append(OneQubitOneParamGate(alpha), [qubits[0]])
circ.append(TwoQubitZeroParamGate(), qubits)
with else_:
circ.append(TwoQubitZeroParamGate(), [qubits[1], qubits[0]])
dag = circuit_to_dag(circ)
dag_translated = BasisTranslator(eq_lib, ["if_else", "1q0p_2", "1q1p_2", "2q0p"]).run(dag)
expected = QuantumCircuit(qubits, clbits)
expected.append(OneQubitZeroParamGate(name="1q0p_2"), [qubits[0]])
expected.append(OneQubitOneParamGate(beta, name="1q1p_2"), [qubits[0]])
expected.measure(qubits[0], clbits[1])
with expected.if_test((clbits[1], 0)) as else_:
expected.append(OneQubitZeroParamGate(name="1q0p_2"), [qubits[0]])
expected.append(OneQubitOneParamGate(alpha, name="1q1p_2"), [qubits[0]])
expected.append(TwoQubitZeroParamGate(), qubits)
with else_:
expected.append(TwoQubitZeroParamGate(), [qubits[1], qubits[0]])
dag_expected = circuit_to_dag(expected)
self.assertEqual(dag_translated, dag_expected)
def test_nested_loop(self):
"""Test a simple if-else with parameters."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
cr = ClassicalRegister(bits=clbits)
index1 = Parameter("index1")
alpha = Parameter("alpha")
gate = OneQubitOneParamGate(alpha)
equiv = QuantumCircuit([qubits[0]])
equiv.append(OneQubitZeroParamGate(name="1q0p_2"), [qubits[0]])
equiv.append(OneQubitOneParamGate(alpha, name="1q1p_2"), [qubits[0]])
eq_lib = EquivalenceLibrary()
eq_lib.add_equivalence(gate, equiv)
circ = QuantumCircuit(qubits, cr)
with circ.for_loop(range(3), loop_parameter=index1) as ind:
with circ.while_loop((cr, 0)):
circ.append(OneQubitOneParamGate(alpha * ind), [qubits[0]])
dag = circuit_to_dag(circ)
dag_translated = BasisTranslator(
eq_lib, ["if_else", "for_loop", "while_loop", "1q0p_2", "1q1p_2"]
).run(dag)
expected = QuantumCircuit(qubits, cr)
with expected.for_loop(range(3), loop_parameter=index1) as ind:
with expected.while_loop((cr, 0)):
expected.append(OneQubitZeroParamGate(name="1q0p_2"), [qubits[0]])
expected.append(OneQubitOneParamGate(alpha * ind, name="1q1p_2"), [qubits[0]])
dag_expected = circuit_to_dag(expected)
self.assertEqual(dag_translated, dag_expected)
def test_different_bits(self):
"""Test that the basis translator correctly works when the inner blocks of control-flow
operations are not over the same bits as the outer blocks."""
base = QuantumCircuit([Qubit() for _ in [None] * 4], [Clbit()])
for_body = QuantumCircuit([Qubit(), Qubit()])
for_body.h(0)
for_body.cz(0, 1)
base.for_loop((1,), None, for_body, [1, 2], [])
while_body = QuantumCircuit([Qubit(), Qubit(), Clbit()])
while_body.cz(0, 1)
true_body = QuantumCircuit([Qubit(), Qubit(), Clbit()])
true_body.measure(0, 0)
true_body.while_loop((0, True), while_body, [0, 1], [0])
false_body = QuantumCircuit([Qubit(), Qubit(), Clbit()])
false_body.cz(0, 1)
base.if_else((0, True), true_body, false_body, [0, 3], [0])
basis = {"rz", "sx", "cx", "for_loop", "if_else", "while_loop", "measure"}
out = BasisTranslator(std_eqlib, basis).run(circuit_to_dag(base))
self.assertEqual(set(out.count_ops(recurse=True)), basis)
class TestUnrollerCompatability(QiskitTestCase):
"""Tests backward compatability with the Unroller pass.
Duplicate of TestUnroller from test.python.transpiler.test_unroller with
Unroller replaced by UnrollCustomDefinitions -> BasisTranslator.
"""
def test_basic_unroll(self):
"""Test decompose a single H into u2."""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
dag = circuit_to_dag(circuit)
pass_ = UnrollCustomDefinitions(std_eqlib, ["u2"])
dag = pass_.run(dag)
pass_ = BasisTranslator(std_eqlib, ["u2"])
unrolled_dag = pass_.run(dag)
op_nodes = unrolled_dag.op_nodes()
self.assertEqual(len(op_nodes), 1)
self.assertEqual(op_nodes[0].name, "u2")
def test_unroll_toffoli(self):
"""Test unroll toffoli on multi regs to h, t, tdg, cx."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(1, "qr2")
circuit = QuantumCircuit(qr1, qr2)
circuit.ccx(qr1[0], qr1[1], qr2[0])
dag = circuit_to_dag(circuit)
pass_ = UnrollCustomDefinitions(std_eqlib, ["h", "t", "tdg", "cx"])
dag = pass_.run(dag)
pass_ = BasisTranslator(std_eqlib, ["h", "t", "tdg", "cx"])
unrolled_dag = pass_.run(dag)
op_nodes = unrolled_dag.op_nodes()
self.assertEqual(len(op_nodes), 15)
for node in op_nodes:
self.assertIn(node.name, ["h", "t", "tdg", "cx"])
def test_unroll_1q_chain_conditional(self):
"""Test unroll chain of 1-qubit gates interrupted by conditional."""
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ βββββ βββββ Β»
# qr: β€ H ββ€ Tdg ββ€ Z ββ€ T ββ€ Ry(0.5) ββ€ Rz(0.3) ββ€ Rx(0.1) ββ€Mβββ€ X ββββ€ Y ββΒ»
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ₯β βββ₯ββ βββ₯ββ Β»
# β ββββ¨βββββββ¨βββΒ»
# cr: 1/βββββββββββββββββββββββββββββββββββββββββββββββββββββββ©ββ‘ 0x1 ββ‘ 0x1 βΒ»
# 0 ββββββββββββββΒ»
# Β« βββββ
# Β« qr: ββ€ Z ββ
# Β« βββ₯ββ
# Β« ββββ¨βββ
# Β«cr: 1/β‘ 0x1 β
# Β« βββββββ
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr)
circuit.tdg(qr)
circuit.z(qr)
circuit.t(qr)
circuit.ry(0.5, qr)
circuit.rz(0.3, qr)
circuit.rx(0.1, qr)
circuit.measure(qr, cr)
circuit.x(qr).c_if(cr, 1)
circuit.y(qr).c_if(cr, 1)
circuit.z(qr).c_if(cr, 1)
dag = circuit_to_dag(circuit)
pass_ = UnrollCustomDefinitions(std_eqlib, ["u1", "u2", "u3"])
dag = pass_.run(dag)
pass_ = BasisTranslator(std_eqlib, ["u1", "u2", "u3"])
unrolled_dag = pass_.run(dag)
# Pick up -1 * 0.3 / 2 global phase for one RZ -> U1.
#
# global phase: 6.1332
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββΒ»
# qr: β€ U2(0,Ο) ββ€ U1(-Ο/4) ββ€ U1(Ο) ββ€ U1(Ο/4) ββ€ U3(0.5,0,0) ββ€ U1(0.3) βΒ»
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββΒ»
# cr: 1/βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββΒ»
# Β»
# Β« ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Β« qr: β€ U3(0.1,-Ο/2,Ο/2) ββ€Mββ€ U3(Ο,0,Ο) ββ€ U3(Ο,Ο/2,Ο/2) ββ€ U1(Ο) β
# Β« ββββββββββββββββββββββ₯ββββββββ₯βββββββββββββββ₯βββββββββββββ₯ββββ
# Β« β ββββ¨βββ ββββ¨βββ ββββ¨βββ
# Β«cr: 1/ββββββββββββββββββββββ©βββββ‘ 0x1 ββββββββββ‘ 0x1 ββββββββ‘ 0x1 ββ
# Β« 0 βββββββ βββββββ βββββββ
ref_circuit = QuantumCircuit(qr, cr, global_phase=-0.3 / 2)
ref_circuit.append(U2Gate(0, pi), [qr[0]])
ref_circuit.append(U1Gate(-pi / 4), [qr[0]])
ref_circuit.append(U1Gate(pi), [qr[0]])
ref_circuit.append(U1Gate(pi / 4), [qr[0]])
ref_circuit.append(U3Gate(0.5, 0, 0), [qr[0]])
ref_circuit.append(U1Gate(0.3), [qr[0]])
ref_circuit.append(U3Gate(0.1, -pi / 2, pi / 2), [qr[0]])
ref_circuit.measure(qr[0], cr[0])
ref_circuit.append(U3Gate(pi, 0, pi), [qr[0]]).c_if(cr, 1)
ref_circuit.append(U3Gate(pi, pi / 2, pi / 2), [qr[0]]).c_if(cr, 1)
ref_circuit.append(U1Gate(pi), [qr[0]]).c_if(cr, 1)
ref_dag = circuit_to_dag(ref_circuit)
self.assertEqual(unrolled_dag, ref_dag)
def test_unroll_no_basis(self):
"""Test when a given gate has no decompositions."""
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr)
dag = circuit_to_dag(circuit)
pass_ = UnrollCustomDefinitions(std_eqlib, [])
dag = pass_.run(dag)
pass_ = BasisTranslator(std_eqlib, [])
with self.assertRaises(QiskitError):
pass_.run(dag)
def test_unroll_all_instructions(self):
"""Test unrolling a circuit containing all standard instructions."""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.crx(0.5, qr[1], qr[2])
circuit.cry(0.5, qr[1], qr[2])
circuit.ccx(qr[0], qr[1], qr[2])
circuit.ch(qr[0], qr[2])
circuit.crz(0.5, qr[1], qr[2])
circuit.cswap(qr[1], qr[0], qr[2])
circuit.append(CU1Gate(0.1), [qr[0], qr[2]])
circuit.append(CU3Gate(0.2, 0.1, 0.0), [qr[1], qr[2]])
circuit.cx(qr[1], qr[0])
circuit.cy(qr[1], qr[2])
circuit.cz(qr[2], qr[0])
circuit.h(qr[1])
circuit.i(qr[0])
circuit.rx(0.1, qr[0])
circuit.ry(0.2, qr[1])
circuit.rz(0.3, qr[2])
circuit.rzz(0.6, qr[1], qr[0])
circuit.s(qr[0])
circuit.sdg(qr[1])
circuit.swap(qr[1], qr[2])
circuit.t(qr[2])
circuit.tdg(qr[0])
circuit.append(U1Gate(0.1), [qr[1]])
circuit.append(U2Gate(0.2, -0.1), [qr[0]])
circuit.append(U3Gate(0.3, 0.0, -0.1), [qr[2]])
circuit.x(qr[2])
circuit.y(qr[1])
circuit.z(qr[0])
# circuit.snapshot('0')
# circuit.measure(qr, cr)
dag = circuit_to_dag(circuit)
pass_ = UnrollCustomDefinitions(std_eqlib, ["u3", "cx", "id"])
dag = pass_.run(dag)
pass_ = BasisTranslator(std_eqlib, ["u3", "cx", "id"])
unrolled_dag = pass_.run(dag)
ref_circuit = QuantumCircuit(qr, cr)
ref_circuit.append(U3Gate(0, 0, pi / 2), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(-0.25, 0, 0), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(0.25, -pi / 2, 0), [qr[2]])
ref_circuit.append(U3Gate(0.25, 0, 0), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(-0.25, 0, 0), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]])
ref_circuit.cx(qr[0], qr[2])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[1]])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]])
ref_circuit.cx(qr[0], qr[2])
ref_circuit.cx(qr[0], qr[1])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[0]])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[1]])
ref_circuit.cx(qr[0], qr[1])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
ref_circuit.append(U3Gate(0, 0, pi / 2), [qr[2]])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
ref_circuit.cx(qr[0], qr[2])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
ref_circuit.append(U3Gate(0, 0, -pi / 2), [qr[2]])
ref_circuit.append(U3Gate(0, 0, 0.25), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(0, 0, -0.25), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.cx(qr[2], qr[0])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
ref_circuit.cx(qr[0], qr[2])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
ref_circuit.cx(qr[0], qr[2])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[0]])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.cx(qr[1], qr[0])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[0]])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[1]])
ref_circuit.cx(qr[1], qr[0])
ref_circuit.append(U3Gate(0, 0, 0.05), [qr[1]])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
ref_circuit.cx(qr[2], qr[0])
ref_circuit.append(U3Gate(0, 0, 0.05), [qr[0]])
ref_circuit.cx(qr[0], qr[2])
ref_circuit.append(U3Gate(0, 0, -0.05), [qr[2]])
ref_circuit.cx(qr[0], qr[2])
ref_circuit.append(U3Gate(0, 0, 0.05), [qr[2]])
ref_circuit.append(U3Gate(0, 0, -0.05), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(-0.1, 0, -0.05), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.cx(qr[1], qr[0])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[0]])
ref_circuit.append(U3Gate(0.1, 0.1, 0), [qr[2]])
ref_circuit.append(U3Gate(0, 0, -pi / 2), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[1]])
ref_circuit.append(U3Gate(0.2, 0, 0), [qr[1]])
ref_circuit.append(U3Gate(0, 0, pi / 2), [qr[2]])
ref_circuit.cx(qr[2], qr[0])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[0]])
ref_circuit.i(qr[0])
ref_circuit.append(U3Gate(0.1, -pi / 2, pi / 2), [qr[0]])
ref_circuit.cx(qr[1], qr[0])
ref_circuit.append(U3Gate(0, 0, 0.6), [qr[0]])
ref_circuit.cx(qr[1], qr[0])
ref_circuit.append(U3Gate(0, 0, pi / 2), [qr[0]])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[0]])
ref_circuit.append(U3Gate(pi / 2, 0.2, -0.1), [qr[0]])
ref_circuit.append(U3Gate(0, 0, pi), [qr[0]])
ref_circuit.append(U3Gate(0, 0, -pi / 2), [qr[1]])
ref_circuit.append(U3Gate(0, 0, 0.3), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.cx(qr[2], qr[1])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(0, 0, 0.1), [qr[1]])
ref_circuit.append(U3Gate(pi, pi / 2, pi / 2), [qr[1]])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
ref_circuit.append(U3Gate(0.3, 0.0, -0.1), [qr[2]])
ref_circuit.append(U3Gate(pi, 0, pi), [qr[2]])
# ref_circuit.snapshot('0')
# ref_circuit.measure(qr, cr)
# ref_dag = circuit_to_dag(ref_circuit)
self.assertTrue(Operator(dag_to_circuit(unrolled_dag)).equiv(ref_circuit))
def test_simple_unroll_parameterized_without_expressions(self):
"""Verify unrolling parameterized gates without expressions."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.rz(theta, qr[0])
dag = circuit_to_dag(qc)
pass_ = UnrollCustomDefinitions(std_eqlib, ["u1", "cx"])
dag = pass_.run(dag)
unrolled_dag = BasisTranslator(std_eqlib, ["u1", "cx"]).run(dag)
expected = QuantumCircuit(qr, global_phase=-theta / 2)
expected.append(U1Gate(theta), [qr[0]])
self.assertEqual(circuit_to_dag(expected), unrolled_dag)
def test_simple_unroll_parameterized_with_expressions(self):
"""Verify unrolling parameterized gates with expressions."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
theta = Parameter("theta")
phi = Parameter("phi")
sum_ = theta + phi
qc.rz(sum_, qr[0])
dag = circuit_to_dag(qc)
pass_ = UnrollCustomDefinitions(std_eqlib, ["p", "cx"])
dag = pass_.run(dag)
unrolled_dag = BasisTranslator(std_eqlib, ["p", "cx"]).run(dag)
expected = QuantumCircuit(qr, global_phase=-sum_ / 2)
expected.p(sum_, qr[0])
self.assertEqual(circuit_to_dag(expected), unrolled_dag)
def test_definition_unroll_parameterized(self):
"""Verify that unrolling complex gates with parameters does not raise."""
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.cp(theta, qr[1], qr[0])
qc.cp(theta * theta, qr[0], qr[1])
dag = circuit_to_dag(qc)
pass_ = UnrollCustomDefinitions(std_eqlib, ["p", "cx"])
dag = pass_.run(dag)
out_dag = BasisTranslator(std_eqlib, ["p", "cx"]).run(dag)
self.assertEqual(out_dag.count_ops(), {"p": 6, "cx": 4})
def test_unrolling_parameterized_composite_gates(self):
"""Verify unrolling circuits with parameterized composite gates."""
mock_sel = EquivalenceLibrary(base=std_eqlib)
qr1 = QuantumRegister(2)
subqc = QuantumCircuit(qr1)
theta = Parameter("theta")
subqc.rz(theta, qr1[0])
subqc.cx(qr1[0], qr1[1])
subqc.rz(theta, qr1[1])
# Expanding across register with shared parameter
qr2 = QuantumRegister(4)
qc = QuantumCircuit(qr2)
sub_instr = circuit_to_instruction(subqc, equivalence_library=mock_sel)
qc.append(sub_instr, [qr2[0], qr2[1]])
qc.append(sub_instr, [qr2[2], qr2[3]])
dag = circuit_to_dag(qc)
pass_ = UnrollCustomDefinitions(mock_sel, ["p", "cx"])
dag = pass_.run(dag)
out_dag = BasisTranslator(mock_sel, ["p", "cx"]).run(dag)
# Pick up -1 * theta / 2 global phase four twice (once for each RZ -> P
# in each of the two sub_instr instructions).
expected = QuantumCircuit(qr2, global_phase=-1 * 4 * theta / 2.0)
expected.p(theta, qr2[0])
expected.p(theta, qr2[2])
expected.cx(qr2[0], qr2[1])
expected.cx(qr2[2], qr2[3])
expected.p(theta, qr2[1])
expected.p(theta, qr2[3])
self.assertEqual(circuit_to_dag(expected), out_dag)
# Expanding across register with shared parameter
qc = QuantumCircuit(qr2)
phi = Parameter("phi")
gamma = Parameter("gamma")
sub_instr = circuit_to_instruction(subqc, {theta: phi}, mock_sel)
qc.append(sub_instr, [qr2[0], qr2[1]])
sub_instr = circuit_to_instruction(subqc, {theta: gamma}, mock_sel)
qc.append(sub_instr, [qr2[2], qr2[3]])
dag = circuit_to_dag(qc)
pass_ = UnrollCustomDefinitions(mock_sel, ["p", "cx"])
dag = pass_.run(dag)
out_dag = BasisTranslator(mock_sel, ["p", "cx"]).run(dag)
expected = QuantumCircuit(qr2, global_phase=-1 * (2 * phi + 2 * gamma) / 2.0)
expected.p(phi, qr2[0])
expected.p(gamma, qr2[2])
expected.cx(qr2[0], qr2[1])
expected.cx(qr2[2], qr2[3])
expected.p(phi, qr2[1])
expected.p(gamma, qr2[3])
self.assertEqual(circuit_to_dag(expected), out_dag)
class TestBasisExamples(QiskitTestCase):
"""Test example circuits targeting example bases over the StandardEquivalenceLibrary."""
def test_cx_bell_to_cz(self):
"""Verify we can translate a CX bell circuit to CZ,RX,RZ."""
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
in_dag = circuit_to_dag(bell)
out_dag = BasisTranslator(std_eqlib, ["cz", "rx", "rz"]).run(in_dag)
self.assertTrue(set(out_dag.count_ops()).issubset(["cz", "rx", "rz"]))
self.assertEqual(Operator(bell), Operator(dag_to_circuit(out_dag)))
def test_cx_bell_to_iswap(self):
"""Verify we can translate a CX bell to iSwap,U3."""
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
in_dag = circuit_to_dag(bell)
out_dag = BasisTranslator(std_eqlib, ["iswap", "u"]).run(in_dag)
self.assertTrue(set(out_dag.count_ops()).issubset(["iswap", "u"]))
self.assertEqual(Operator(bell), Operator(dag_to_circuit(out_dag)))
def test_cx_bell_to_ecr(self):
"""Verify we can translate a CX bell to ECR,U."""
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
in_dag = circuit_to_dag(bell)
out_dag = BasisTranslator(std_eqlib, ["ecr", "u"]).run(in_dag)
# ββββββββββββββ βββββββββββββββββββββββββββββββββββ
# q_0: ββββ€ U(Ο/2,0,Ο) βββββ€ U(0,0,-Ο/2) ββ€0 ββ€ U(Ο,0,Ο) β
# ββββ΄βββββββββββββ΄βββββββββββββββββββ Ecr βββββββββββββ
# q_1: β€ U(-Ο/2,-Ο/2,Ο/2) βββββββββββββββββ€1 βββββββββββββ
# ββββββββββββββββββββ ββββββββ
qr = QuantumRegister(2, "q")
expected = QuantumCircuit(2)
expected.u(pi / 2, 0, pi, qr[0])
expected.u(0, 0, -pi / 2, qr[0])
expected.u(-pi / 2, -pi / 2, pi / 2, qr[1])
expected.ecr(0, 1)
expected.u(pi, 0, pi, qr[0])
expected_dag = circuit_to_dag(expected)
self.assertEqual(out_dag, expected_dag)
def test_cx_bell_to_cp(self):
"""Verify we can translate a CX bell to CP,U."""
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
in_dag = circuit_to_dag(bell)
out_dag = BasisTranslator(std_eqlib, ["cp", "u"]).run(in_dag)
self.assertTrue(set(out_dag.count_ops()).issubset(["cp", "u"]))
self.assertEqual(Operator(bell), Operator(dag_to_circuit(out_dag)))
qr = QuantumRegister(2, "q")
expected = QuantumCircuit(qr)
expected.u(pi / 2, 0, pi, 0)
expected.u(pi / 2, 0, pi, 1)
expected.cp(pi, 0, 1)
expected.u(pi / 2, 0, pi, 1)
expected_dag = circuit_to_dag(expected)
self.assertEqual(out_dag, expected_dag)
def test_cx_bell_to_crz(self):
"""Verify we can translate a CX bell to CRZ,U."""
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
in_dag = circuit_to_dag(bell)
out_dag = BasisTranslator(std_eqlib, ["crz", "u"]).run(in_dag)
self.assertTrue(set(out_dag.count_ops()).issubset(["crz", "u"]))
self.assertEqual(Operator(bell), Operator(dag_to_circuit(out_dag)))
qr = QuantumRegister(2, "q")
expected = QuantumCircuit(qr)
expected.u(pi / 2, 0, pi, 0)
expected.u(0, 0, pi / 2, 0)
expected.u(pi / 2, 0, pi, 1)
expected.crz(pi, 0, 1)
expected.u(pi / 2, 0, pi, 1)
expected_dag = circuit_to_dag(expected)
self.assertEqual(out_dag, expected_dag)
def test_global_phase(self):
"""Verify global phase preserved in basis translation"""
circ = QuantumCircuit(1)
gate_angle = pi / 5
circ_angle = pi / 3
circ.rz(gate_angle, 0)
circ.global_phase = circ_angle
in_dag = circuit_to_dag(circ)
out_dag = BasisTranslator(std_eqlib, ["p"]).run(in_dag)
qr = QuantumRegister(1, "q")
expected = QuantumCircuit(qr)
expected.p(gate_angle, qr)
expected.global_phase = circ_angle - gate_angle / 2
expected_dag = circuit_to_dag(expected)
self.assertEqual(out_dag, expected_dag)
self.assertAlmostEqual(
float(out_dag.global_phase), float(expected_dag.global_phase), places=14
)
self.assertEqual(Operator(dag_to_circuit(out_dag)), Operator(expected))
def test_condition_set_substitute_node(self):
"""Verify condition is set in BasisTranslator on substitute_node"""
# βββββ βββββ
# q_0: β€ H ββββ βββββββ€ H ββ
# ββββββββ΄βββββ βββ₯ββ
# q_1: ββββββ€ X ββ€Mβββββ«βββ
# βββββββ₯βββββ¨βββ
# c: 2/ββββββββββββ©ββ‘ 0x1 β
# 1 βββββββ
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circ = QuantumCircuit(qr, cr)
circ.h(0)
circ.cx(0, 1)
circ.measure(1, 1)
circ.h(0).c_if(cr, 1)
circ_transpiled = transpile(circ, optimization_level=3, basis_gates=["cx", "id", "u"])
# ββββββββββββββ ββββββββββββββ
# q_0: β€ U(Ο/2,0,Ο) ββββ ββββββ€ U(Ο/2,0,Ο) β
# βββββββββββββββββ΄ββββββββββββ₯βββββββ
# q_1: βββββββββββββββ€ X ββ€Mββββββββ«βββββββ
# βββββββ₯β ββββ¨βββ
# c: 2/βββββββββββββββββββββ©βββββ‘ 0x1 βββββ
# 1 βββββββ
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
expected = QuantumCircuit(qr, cr)
expected.u(pi / 2, 0, pi, 0)
expected.cx(0, 1)
expected.measure(1, 1)
expected.u(pi / 2, 0, pi, 0).c_if(cr, 1)
self.assertEqual(circ_transpiled, expected)
def test_skip_target_basis_equivalences_1(self):
"""Test that BasisTranslator skips gates in the target_basis - #6085"""
circ = QuantumCircuit()
qasm_file = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"qasm",
"TestBasisTranslator_skip_target.qasm",
)
circ = circ.from_qasm_file(qasm_file)
circ_transpiled = transpile(
circ,
basis_gates=["id", "rz", "sx", "x", "cx"],
seed_transpiler=42,
)
self.assertEqual(circ_transpiled.count_ops(), {"cx": 91, "rz": 66, "sx": 22})
class TestBasisTranslatorWithTarget(QiskitTestCase):
"""Test the basis translator when running with a Target."""
def setUp(self):
super().setUp()
self.target = Target()
# U gate in qubit 0.
self.theta = Parameter("theta")
self.phi = Parameter("phi")
self.lam = Parameter("lambda")
u_props = {
(0,): InstructionProperties(duration=5.23e-8, error=0.00038115),
}
self.target.add_instruction(UGate(self.theta, self.phi, self.lam), u_props)
# Rz gate in qubit 1.
rz_props = {
(1,): InstructionProperties(duration=0.0, error=0),
}
self.target.add_instruction(RZGate(self.phi), rz_props)
# X gate in qubit 1.
x_props = {
(1,): InstructionProperties(
duration=3.5555555555555554e-08, error=0.00020056469709026198
),
}
self.target.add_instruction(XGate(), x_props)
# SX gate in qubit 1.
sx_props = {
(1,): InstructionProperties(
duration=3.5555555555555554e-08, error=0.00020056469709026198
),
}
self.target.add_instruction(SXGate(), sx_props)
cx_props = {
(0, 1): InstructionProperties(duration=5.23e-7, error=0.00098115),
(1, 0): InstructionProperties(duration=4.52e-7, error=0.00132115),
}
self.target.add_instruction(CXGate(), cx_props)
def test_2q_with_non_global_1q(self):
"""Test translation works with a 2q gate on an non-global 1q basis."""
qc = QuantumCircuit(2)
qc.cz(0, 1)
bt_pass = BasisTranslator(std_eqlib, target_basis=None, target=self.target)
output = bt_pass(qc)
# We need a second run of BasisTranslator to correct gates outside of
# the target basis. This is a known isssue, see:
# https://qiskit.org/documentation/release_notes.html#release-notes-0-19-0-known-issues
output = bt_pass(output)
expected = QuantumCircuit(2)
expected.rz(pi, 1)
expected.sx(1)
expected.rz(3 * pi / 2, 1)
expected.sx(1)
expected.rz(3 * pi, 1)
expected.cx(0, 1)
expected.rz(pi, 1)
expected.sx(1)
expected.rz(3 * pi / 2, 1)
expected.sx(1)
expected.rz(3 * pi, 1)
self.assertEqual(output, expected)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the BIPMapping pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.circuit import Barrier
from qiskit.circuit.library.standard_gates import SwapGate, CXGate
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeLima
from qiskit.transpiler import CouplingMap, Layout, PassManager, Target
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.passes import BIPMapping
from qiskit.transpiler.passes import CheckMap, Collect2qBlocks, ConsolidateBlocks, UnitarySynthesis
from qiskit.utils import optionals
@unittest.skipUnless(optionals.HAS_CPLEX, "cplex is required to run the BIPMapping tests")
@unittest.skipUnless(optionals.HAS_DOCPLEX, "docplex is required to run the BIPMapping tests")
class TestBIPMapping(QiskitTestCase):
"""Tests the BIPMapping pass."""
def test_empty(self):
"""Returns the original circuit if the circuit is empty."""
coupling = CouplingMap([[0, 1]])
circuit = QuantumCircuit(2)
with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"):
actual = BIPMapping(coupling)(circuit)
self.assertEqual(circuit, actual)
def test_no_two_qubit_gates(self):
"""Returns the original circuit if the circuit has no 2q-gates
q0:--[H]--
q1:-------
CouplingMap map: [0]--[1]
"""
coupling = CouplingMap([[0, 1]])
circuit = QuantumCircuit(2)
circuit.h(0)
with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"):
actual = BIPMapping(coupling)(circuit)
self.assertEqual(circuit, actual)
def test_trivial_case(self):
"""No need to have any swap, the CX are distance 1 to each other
q0:--(+)-[H]-(+)-
| |
q1:---.-------|--
|
q2:-----------.--
CouplingMap map: [1]--[0]--[2]
"""
coupling = CouplingMap([[0, 1], [0, 2]])
circuit = QuantumCircuit(3)
circuit.cx(1, 0)
circuit.h(0)
circuit.cx(2, 0)
with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"):
actual = BIPMapping(coupling)(circuit)
self.assertEqual(3, len(actual))
for inst, _, _ in actual.data: # there are no swaps
self.assertFalse(isinstance(inst, SwapGate))
def test_no_swap(self):
"""Adding no swap if not giving initial layout"""
coupling = CouplingMap([[0, 1], [0, 2]])
circuit = QuantumCircuit(3)
circuit.cx(1, 2)
with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"):
actual = BIPMapping(coupling)(circuit)
q = QuantumRegister(3, name="q")
expected = QuantumCircuit(q)
expected.cx(q[0], q[1])
self.assertEqual(expected, actual)
def test_ignore_initial_layout(self):
"""Ignoring initial layout even when it is supplied"""
coupling = CouplingMap([[0, 1], [0, 2]])
circuit = QuantumCircuit(3)
circuit.cx(1, 2)
property_set = {"layout": Layout.generate_trivial_layout(*circuit.qubits)}
with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"):
actual = BIPMapping(coupling)(circuit, property_set)
q = QuantumRegister(3, name="q")
expected = QuantumCircuit(q)
expected.cx(q[0], q[1])
self.assertEqual(expected, actual)
def test_can_map_measurements_correctly(self):
"""Verify measurement nodes are updated to map correct cregs to re-mapped qregs."""
coupling = CouplingMap([[0, 1], [0, 2]])
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[1], qr[2])
circuit.measure(qr[1], cr[0])
circuit.measure(qr[2], cr[1])
with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"):
actual = BIPMapping(coupling)(circuit)
q = QuantumRegister(3, "q")
expected = QuantumCircuit(q, cr)
expected.cx(q[0], q[1])
expected.measure(q[0], cr[0]) # <- changed due to initial layout change
expected.measure(q[1], cr[1]) # <- changed due to initial layout change
self.assertEqual(expected, actual)
def test_can_map_measurements_correctly_with_target(self):
"""Verify measurement nodes are updated to map correct cregs to re-mapped qregs."""
target = Target()
target.add_instruction(CXGate(), {(0, 1): None, (0, 2): None})
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[1], qr[2])
circuit.measure(qr[1], cr[0])
circuit.measure(qr[2], cr[1])
with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"):
actual = BIPMapping(target)(circuit)
q = QuantumRegister(3, "q")
expected = QuantumCircuit(q, cr)
expected.cx(q[0], q[1])
expected.measure(q[0], cr[0]) # <- changed due to initial layout change
expected.measure(q[1], cr[1]) # <- changed due to initial layout change
self.assertEqual(expected, actual)
def test_never_modify_mapped_circuit(self):
"""Test that the mapping is idempotent.
It should not modify a circuit which is already compatible with the
coupling map, and can be applied repeatedly without modifying the circuit.
"""
coupling = CouplingMap([[0, 1], [0, 2]])
circuit = QuantumCircuit(3, 2)
circuit.cx(1, 2)
circuit.measure(1, 0)
circuit.measure(2, 1)
dag = circuit_to_dag(circuit)
with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"):
mapped_dag = BIPMapping(coupling).run(dag)
remapped_dag = BIPMapping(coupling).run(mapped_dag)
self.assertEqual(mapped_dag, remapped_dag)
def test_no_swap_multi_layer(self):
"""Can find the best layout for a circuit with multiple layers."""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, name="qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[3])
property_set = {}
with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"):
actual = BIPMapping(coupling, objective="depth")(circuit, property_set)
self.assertEqual(2, actual.depth())
CheckMap(coupling)(actual, property_set)
self.assertTrue(property_set["is_swap_mapped"])
def test_unmappable_cnots_in_a_layer(self):
"""Test mapping of a circuit with 2 cnots in a layer into T-shape coupling,
which BIPMapping cannot map."""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
circuit.measure(qr, cr)
coupling = CouplingMap([[0, 1], [1, 2], [1, 3]]) # {0: [1], 1: [2, 3]}
with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"):
actual = BIPMapping(coupling)(circuit)
# Fails to map and returns the original circuit
self.assertEqual(circuit, actual)
def test_multi_cregs(self):
"""Test for multiple ClassicalRegisters."""
# βββββ β βββ
# qr_0: βββ βββββββββββββ€ X βββββ€Mββββββββββ
# βββ΄ββ ββββββββ¬ββ β ββ₯ββββ
# qr_1: β€ X ββββ βββ€ H ββββ βββββββ«ββ€Mβββββββ
# ββββββββ΄βββββββ β β ββ₯ββββ
# qr_2: βββ βββ€ X ββββββββββββββββ«βββ«ββ€Mββββ
# βββ΄βββββββ β β β ββ₯ββββ
# qr_3: β€ X βββββββββββββββββββββ«βββ«βββ«ββ€Mβ
# βββββ β β β β ββ₯β
# c: 2/βββββββββββββββββββββββββ©βββ¬βββ©βββ¬β
# 0 β 1 β
# β β
# d: 2/ββββββββββββββββββββββββββββ©ββββββ©β
# 0 1
qr = QuantumRegister(4, "qr")
cr1 = ClassicalRegister(2, "c")
cr2 = ClassicalRegister(2, "d")
circuit = QuantumCircuit(qr, cr1, cr2)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[1], qr[2])
circuit.h(qr[1])
circuit.cx(qr[1], qr[0])
circuit.barrier(qr)
circuit.measure(qr[0], cr1[0])
circuit.measure(qr[1], cr2[0])
circuit.measure(qr[2], cr1[1])
circuit.measure(qr[3], cr2[1])
coupling = CouplingMap([[0, 1], [0, 2], [2, 3]]) # linear [1, 0, 2, 3]
property_set = {}
with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"):
actual = BIPMapping(coupling, objective="depth")(circuit, property_set)
self.assertEqual(5, actual.depth())
CheckMap(coupling)(actual, property_set)
self.assertTrue(property_set["is_swap_mapped"])
def test_swaps_in_dummy_steps(self):
"""Test the case when swaps are inserted in dummy steps."""
# βββββ β β
# q_0: βββ βββ€ H βββββββ βββββββββββββ βββββββ
# βββ΄βββββββ€ β β β β
# q_1: β€ X ββ€ H βββββββΌβββββ ββββββββΌβββββ ββ
# ββββββββββ€ β β βββ΄ββ β βββ΄ββ β
# q_2: βββ βββ€ H βββββββΌβββ€ X βββββ€ X ββββΌββ
# βββ΄βββββββ€ β βββ΄βββββββ β ββββββββ΄ββ
# q_3: β€ X ββ€ H βββββ€ X βββββββββββββββ€ X β
# ββββββββββ β βββββ β βββββ
circuit = QuantumCircuit(4)
circuit.cx(0, 1)
circuit.cx(2, 3)
circuit.h([0, 1, 2, 3])
circuit.barrier()
circuit.cx(0, 3)
circuit.cx(1, 2)
circuit.barrier()
circuit.cx(0, 2)
circuit.cx(1, 3)
coupling = CouplingMap.from_line(4)
property_set = {}
with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"):
actual = BIPMapping(coupling, objective="depth")(circuit, property_set)
self.assertEqual(7, actual.depth())
CheckMap(coupling)(actual, property_set)
self.assertTrue(property_set["is_swap_mapped"])
# no swaps before the first barrier
for inst, _, _ in actual.data:
if isinstance(inst, Barrier):
break
self.assertFalse(isinstance(inst, SwapGate))
def test_different_number_of_virtual_and_physical_qubits(self):
"""Test the case when number of virtual and physical qubits are different."""
# q_0: βββ βββββ βββββββ
# βββ΄ββ β
# q_1: β€ X ββββΌβββββ ββ
# βββββ β βββ΄ββ
# q_2: βββ βββββΌβββ€ X β
# βββ΄βββββ΄βββββββ
# q_3: β€ X ββ€ X ββββββ
# ββββββββββ
circuit = QuantumCircuit(4)
circuit.cx(0, 1)
circuit.cx(2, 3)
circuit.cx(0, 3)
circuit.cx(1, 2)
coupling = CouplingMap.from_line(5)
with self.assertRaises(TranspilerError):
with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"):
BIPMapping(coupling)(circuit)
def test_qubit_subset(self):
"""Test if `qubit_subset` option works as expected."""
circuit = QuantumCircuit(3)
circuit.cx(0, 1)
circuit.cx(1, 2)
circuit.cx(0, 2)
coupling = CouplingMap([(0, 1), (1, 3), (3, 2)])
qubit_subset = [0, 1, 3]
with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"):
actual = BIPMapping(coupling, qubit_subset=qubit_subset)(circuit)
# all used qubits are in qubit_subset
bit_indices = {bit: index for index, bit in enumerate(actual.qubits)}
for _, qargs, _ in actual.data:
for q in qargs:
self.assertTrue(bit_indices[q] in qubit_subset)
# ancilla qubits are set in the resulting qubit
idle = QuantumRegister(1, name="ancilla")
self.assertEqual(idle[0], actual._layout.initial_layout[2])
def test_unconnected_qubit_subset(self):
"""Fails if qubits in `qubit_subset` are not connected."""
circuit = QuantumCircuit(3)
circuit.cx(0, 1)
coupling = CouplingMap([(0, 1), (1, 3), (3, 2)])
with self.assertRaises(TranspilerError):
with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"):
BIPMapping(coupling, qubit_subset=[0, 1, 2])(circuit)
def test_objective_function(self):
"""Test if ``objective`` functions prioritize metrics correctly."""
# ββββββββββββββββ ββββββββ
# q_0: β€0 ββ€0 βββββββ€0 β
# β Dcx ββ β β Dcx β
# q_1: β€1 ββ€ Dcx ββββ βββ€1 β
# βββββββββ β β ββββββββ
# q_2: ββββ βββββ€1 ββββΌββββββ ββββ
# βββ΄ββ βββββββββββ΄ββ βββ΄ββ
# q_3: ββ€ X ββββββββββββ€ X βββ€ X βββ
# βββββ βββββ βββββ
qc = QuantumCircuit(4)
qc.dcx(0, 1)
qc.cx(2, 3)
qc.dcx(0, 2)
qc.cx(1, 3)
qc.dcx(0, 1)
qc.cx(2, 3)
coupling = CouplingMap(FakeLima().configuration().coupling_map)
with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"):
dep_opt = BIPMapping(coupling, objective="depth", qubit_subset=[0, 1, 3, 4])(qc)
with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"):
err_opt = BIPMapping(
coupling,
objective="gate_error",
qubit_subset=[0, 1, 3, 4],
backend_prop=FakeLima().properties(),
)(qc)
# depth = number of su4 layers (mirrored gates have to be consolidated as single su4 gates)
pm_ = PassManager([Collect2qBlocks(), ConsolidateBlocks(basis_gates=["cx", "u"])])
dep_opt = pm_.run(dep_opt)
err_opt = pm_.run(err_opt)
self.assertLessEqual(dep_opt.depth(), err_opt.depth())
# count CNOTs after synthesized
dep_opt = UnitarySynthesis(basis_gates=["cx", "u"])(dep_opt)
err_opt = UnitarySynthesis(basis_gates=["cx", "u"])(err_opt)
self.assertGreater(dep_opt.count_ops()["cx"], err_opt.count_ops()["cx"])
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the RZXCalibrationBuilderNoEcho."""
from math import pi, erf
import numpy as np
from ddt import data, ddt
from qiskit.converters import circuit_to_dag
from qiskit import circuit, schedule, QiskitError
from qiskit.circuit.library.standard_gates import SXGate, RZGate
from qiskit.providers.fake_provider import FakeHanoi # TODO - include FakeHanoiV2, FakeSherbrooke
from qiskit.providers.fake_provider import FakeArmonk
from qiskit.pulse import (
ControlChannel,
DriveChannel,
GaussianSquare,
Waveform,
Play,
InstructionScheduleMap,
Schedule,
)
from qiskit.pulse import builder
from qiskit.pulse.transforms import target_qobj_transform
from qiskit.test import QiskitTestCase
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes.calibration.builders import (
RZXCalibrationBuilder,
RZXCalibrationBuilderNoEcho,
)
class TestCalibrationBuilder(QiskitTestCase):
"""Test the Calibration Builder."""
# CR parameters
__risefall = 4
__angle = np.pi / 2
__granularity = 16
@staticmethod
def get_cr_play(cr_schedule, name):
"""A helper function to filter CR pulses."""
def _filter_func(time_inst):
return isinstance(time_inst[1], Play) and time_inst[1].pulse.name.startswith(name)
return cr_schedule.filter(_filter_func).instructions[0][1]
def compute_stretch_duration(self, play_gaussian_square_pulse, theta):
"""Compute duration of stretched Gaussian Square pulse."""
pulse = play_gaussian_square_pulse.pulse
sigma = pulse.sigma
width = self.compute_stretch_width(play_gaussian_square_pulse, theta)
duration = width + sigma * self.__risefall
return round(duration / self.__granularity) * self.__granularity
def compute_stretch_width(self, play_gaussian_square_pulse, theta):
"""Compute width of stretched Gaussian Square pulse."""
pulse = play_gaussian_square_pulse.pulse
sigma = pulse.sigma
width = pulse.width
risefall_area = sigma * np.sqrt(2 * np.pi) * erf(self.__risefall)
full_area = risefall_area + width
target_area = abs(theta) / self.__angle * full_area
return max(0, target_area - risefall_area)
def u0p_play(self, cr_schedule):
"""Returns the positive CR pulse from cr_schedule."""
return self.get_cr_play(cr_schedule, "CR90p_u")
def u0m_play(self, cr_schedule):
"""Returns the negative CR pulse from cr_schedule."""
return self.get_cr_play(cr_schedule, "CR90m_u")
def d1p_play(self, cr_schedule):
"""Returns the positive rotary echo pulse from cr_schedule."""
return self.get_cr_play(cr_schedule, "CR90p_d")
def d1m_play(self, cr_schedule):
"""Returns the negative rotary echo pulse from cr_schedule."""
return self.get_cr_play(cr_schedule, "CR90m_d")
@ddt
class TestRZXCalibrationBuilder(TestCalibrationBuilder):
"""Test RZXCalibrationBuilder."""
def build_forward(
self,
backend,
theta,
u0p_play,
d1p_play,
u0m_play,
d1m_play,
):
"""A helper function to generate reference pulse schedule for forward direction."""
duration = self.compute_stretch_duration(u0p_play, theta)
width = self.compute_stretch_width(u0p_play, theta)
with builder.build(
backend,
default_alignment="sequential",
default_transpiler_settings={"optimization_level": 0},
) as ref_sched:
with builder.align_left():
# Positive CRs
u0p_params = u0p_play.pulse.parameters
u0p_params["duration"] = duration
u0p_params["width"] = width
builder.play(
GaussianSquare(**u0p_params),
ControlChannel(0),
)
d1p_params = d1p_play.pulse.parameters
d1p_params["duration"] = duration
d1p_params["width"] = width
builder.play(
GaussianSquare(**d1p_params),
DriveChannel(1),
)
builder.x(0)
with builder.align_left():
# Negative CRs
u0m_params = u0m_play.pulse.parameters
u0m_params["duration"] = duration
u0m_params["width"] = width
builder.play(
GaussianSquare(**u0m_params),
ControlChannel(0),
)
d1m_params = d1m_play.pulse.parameters
d1m_params["duration"] = duration
d1m_params["width"] = width
builder.play(
GaussianSquare(**d1m_params),
DriveChannel(1),
)
builder.x(0)
return ref_sched
def build_reverse(
self,
backend,
theta,
u0p_play,
d1p_play,
u0m_play,
d1m_play,
):
"""A helper function to generate reference pulse schedule for backward direction."""
duration = self.compute_stretch_duration(u0p_play, theta)
width = self.compute_stretch_width(u0p_play, theta)
with builder.build(
backend,
default_alignment="sequential",
default_transpiler_settings={"optimization_level": 0},
) as ref_sched:
# Hadamard gates
builder.call_gate(RZGate(np.pi / 2), qubits=(0,))
builder.call_gate(SXGate(), qubits=(0,))
builder.call_gate(RZGate(np.pi / 2), qubits=(0,))
builder.call_gate(RZGate(np.pi / 2), qubits=(1,))
builder.call_gate(SXGate(), qubits=(1,))
builder.call_gate(RZGate(np.pi / 2), qubits=(1,))
with builder.align_left():
# Positive CRs
u0p_params = u0p_play.pulse.parameters
u0p_params["duration"] = duration
u0p_params["width"] = width
builder.play(
GaussianSquare(**u0p_params),
ControlChannel(0),
)
d1p_params = d1p_play.pulse.parameters
d1p_params["duration"] = duration
d1p_params["width"] = width
builder.play(
GaussianSquare(**d1p_params),
DriveChannel(1),
)
builder.x(0)
with builder.align_left():
# Negative CRs
u0m_params = u0m_play.pulse.parameters
u0m_params["duration"] = duration
u0m_params["width"] = width
builder.play(
GaussianSquare(**u0m_params),
ControlChannel(0),
)
d1m_params = d1m_play.pulse.parameters
d1m_params["duration"] = duration
d1m_params["width"] = width
builder.play(
GaussianSquare(**d1m_params),
DriveChannel(1),
)
builder.x(0)
# Hadamard gates
builder.call_gate(RZGate(np.pi / 2), qubits=(0,))
builder.call_gate(SXGate(), qubits=(0,))
builder.call_gate(RZGate(np.pi / 2), qubits=(0,))
builder.call_gate(RZGate(np.pi / 2), qubits=(1,))
builder.call_gate(SXGate(), qubits=(1,))
builder.call_gate(RZGate(np.pi / 2), qubits=(1,))
return ref_sched
@data(-np.pi / 4, 0.1, np.pi / 4, np.pi / 2, np.pi)
def test_rzx_calibration_cr_pulse_stretch(self, theta: float):
"""Test that cross resonance pulse durations are computed correctly."""
backend = FakeHanoi()
inst_map = backend.defaults().instruction_schedule_map
cr_schedule = inst_map.get("cx", (0, 1))
with builder.build() as test_sched:
RZXCalibrationBuilder.rescale_cr_inst(self.u0p_play(cr_schedule), theta)
self.assertEqual(
test_sched.duration, self.compute_stretch_duration(self.u0p_play(cr_schedule), theta)
)
@data(-np.pi / 4, 0.1, np.pi / 4, np.pi / 2, np.pi)
def test_rzx_calibration_rotary_pulse_stretch(self, theta: float):
"""Test that rotary pulse durations are computed correctly."""
backend = FakeHanoi()
inst_map = backend.defaults().instruction_schedule_map
cr_schedule = inst_map.get("cx", (0, 1))
with builder.build() as test_sched:
RZXCalibrationBuilder.rescale_cr_inst(self.d1p_play(cr_schedule), theta)
self.assertEqual(
test_sched.duration, self.compute_stretch_duration(self.d1p_play(cr_schedule), theta)
)
def test_raise(self):
"""Test that the correct error is raised."""
theta = np.pi / 4
qc = circuit.QuantumCircuit(2)
qc.rzx(theta, 0, 1)
dag = circuit_to_dag(qc)
backend = FakeArmonk()
inst_map = backend.defaults().instruction_schedule_map
_pass = RZXCalibrationBuilder(inst_map)
qubit_map = {qubit: i for i, qubit in enumerate(dag.qubits)}
with self.assertRaises(QiskitError):
for node in dag.gate_nodes():
qubits = [qubit_map[q] for q in node.qargs]
_pass.get_calibration(node.op, qubits)
def test_ecr_cx_forward(self):
"""Test that correct pulse sequence is generated for native CR pair."""
# Sufficiently large angle to avoid minimum duration, i.e. amplitude rescaling
theta = np.pi / 4
qc = circuit.QuantumCircuit(2)
qc.rzx(theta, 0, 1)
backend = FakeHanoi()
inst_map = backend.defaults().instruction_schedule_map
_pass = RZXCalibrationBuilder(inst_map)
test_qc = PassManager(_pass).run(qc)
cr_schedule = inst_map.get("cx", (0, 1))
ref_sched = self.build_forward(
backend,
theta,
self.u0p_play(cr_schedule),
self.d1p_play(cr_schedule),
self.u0m_play(cr_schedule),
self.d1m_play(cr_schedule),
)
self.assertEqual(schedule(test_qc, backend), target_qobj_transform(ref_sched))
def test_ecr_cx_reverse(self):
"""Test that correct pulse sequence is generated for non-native CR pair."""
# Sufficiently large angle to avoid minimum duration, i.e. amplitude rescaling
theta = np.pi / 4
qc = circuit.QuantumCircuit(2)
qc.rzx(theta, 1, 0)
backend = FakeHanoi()
inst_map = backend.defaults().instruction_schedule_map
_pass = RZXCalibrationBuilder(inst_map)
test_qc = PassManager(_pass).run(qc)
cr_schedule = inst_map.get("cx", (0, 1))
ref_sched = self.build_reverse(
backend,
theta,
self.u0p_play(cr_schedule),
self.d1p_play(cr_schedule),
self.u0m_play(cr_schedule),
self.d1m_play(cr_schedule),
)
self.assertEqual(schedule(test_qc, backend), target_qobj_transform(ref_sched))
def test_pass_alive_with_dcx_ish(self):
"""Test if the pass is not terminated by error with direct CX input."""
cx_sched = Schedule()
# Fake direct cr
cx_sched.insert(0, Play(GaussianSquare(800, 0.2, 64, 544), ControlChannel(1)), inplace=True)
# Fake direct compensation tone
# Compensation tone doesn't have dedicated pulse class.
# So it's reported as a waveform now.
compensation_tone = Waveform(0.1 * np.ones(800, dtype=complex))
cx_sched.insert(0, Play(compensation_tone, DriveChannel(0)), inplace=True)
inst_map = InstructionScheduleMap()
inst_map.add("cx", (1, 0), schedule=cx_sched)
theta = pi / 3
rzx_qc = circuit.QuantumCircuit(2)
rzx_qc.rzx(theta, 1, 0)
pass_ = RZXCalibrationBuilder(instruction_schedule_map=inst_map)
with self.assertWarns(UserWarning):
# User warning that says q0 q1 is invalid
cal_qc = PassManager(pass_).run(rzx_qc)
self.assertEqual(cal_qc, rzx_qc)
class TestRZXCalibrationBuilderNoEcho(TestCalibrationBuilder):
"""Test RZXCalibrationBuilderNoEcho."""
def build_forward(
self,
theta,
u0p_play,
d1p_play,
):
"""A helper function to generate reference pulse schedule for forward direction."""
duration = self.compute_stretch_duration(u0p_play, 2.0 * theta)
width = self.compute_stretch_width(u0p_play, 2.0 * theta)
with builder.build() as ref_sched:
# Positive CRs
u0p_params = u0p_play.pulse.parameters
u0p_params["duration"] = duration
u0p_params["width"] = width
builder.play(
GaussianSquare(**u0p_params),
ControlChannel(0),
)
d1p_params = d1p_play.pulse.parameters
d1p_params["duration"] = duration
d1p_params["width"] = width
builder.play(
GaussianSquare(**d1p_params),
DriveChannel(1),
)
builder.delay(duration, DriveChannel(0))
return ref_sched
def test_ecr_cx_forward(self):
"""Test that correct pulse sequence is generated for native CR pair.
.. notes::
No echo builder only supports native direction.
"""
# Sufficiently large angle to avoid minimum duration, i.e. amplitude rescaling
theta = np.pi / 4
qc = circuit.QuantumCircuit(2)
qc.rzx(theta, 0, 1)
backend = FakeHanoi()
inst_map = backend.defaults().instruction_schedule_map
_pass = RZXCalibrationBuilderNoEcho(inst_map)
test_qc = PassManager(_pass).run(qc)
cr_schedule = inst_map.get("cx", (0, 1))
ref_sched = self.build_forward(
theta,
self.u0p_play(cr_schedule),
self.d1p_play(cr_schedule),
)
self.assertEqual(schedule(test_qc, backend), target_qobj_transform(ref_sched))
# # TODO - write test for forward ECR native pulse
# def test_ecr_forward(self):
def test_pass_alive_with_dcx_ish(self):
"""Test if the pass is not terminated by error with direct CX input."""
cx_sched = Schedule()
# Fake direct cr
cx_sched.insert(0, Play(GaussianSquare(800, 0.2, 64, 544), ControlChannel(1)), inplace=True)
# Fake direct compensation tone
# Compensation tone doesn't have dedicated pulse class.
# So it's reported as a waveform now.
compensation_tone = Waveform(0.1 * np.ones(800, dtype=complex))
cx_sched.insert(0, Play(compensation_tone, DriveChannel(0)), inplace=True)
inst_map = InstructionScheduleMap()
inst_map.add("cx", (1, 0), schedule=cx_sched)
theta = pi / 3
rzx_qc = circuit.QuantumCircuit(2)
rzx_qc.rzx(theta, 1, 0)
pass_ = RZXCalibrationBuilderNoEcho(instruction_schedule_map=inst_map)
with self.assertWarns(UserWarning):
# User warning that says q0 q1 is invalid
cal_qc = PassManager(pass_).run(rzx_qc)
self.assertEqual(cal_qc, rzx_qc)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the Check CNOT direction pass"""
import unittest
import ddt
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import CXGate, CZGate, ECRGate
from qiskit.transpiler.passes import CheckGateDirection
from qiskit.transpiler import CouplingMap, Target
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
@ddt.ddt
class TestCheckGateDirection(QiskitTestCase):
"""Tests the CheckGateDirection pass"""
def test_trivial_map(self):
"""Trivial map in a circuit without entanglement
qr0:---[H]---
qr1:---[H]---
qr2:---[H]---
CouplingMap map: None
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr)
coupling = CouplingMap()
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_direction_mapped"])
def test_true_direction(self):
"""Mapped is easy to check
qr0:---.--[H]--.--
| |
qr1:--(+)------|--
|
qr2:----------(+)-
CouplingMap map: [1]<-[0]->[2]
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.cx(qr[0], qr[2])
coupling = CouplingMap([[0, 1], [0, 2]])
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_direction_mapped"])
def test_true_direction_in_same_layer(self):
"""Two CXs distance_qubits 1 to each other, in the same layer
qr0:--(+)--
|
qr1:---.---
qr2:--(+)--
|
qr3:---.---
CouplingMap map: [0]->[1]->[2]->[3]
"""
qr = QuantumRegister(4, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_direction_mapped"])
def test_wrongly_mapped(self):
"""Needs [0]-[1] in a [0]--[2]--[1]
qr0:--(+)--
|
qr1:---.---
CouplingMap map: [0]->[2]->[1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
coupling = CouplingMap([[0, 2], [2, 1]])
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_direction_mapped"])
def test_true_direction_undirected(self):
"""Mapped but with wrong direction
qr0:--(+)-[H]--.--
| |
qr1:---.-------|--
|
qr2:----------(+)-
CouplingMap map: [1]<-[0]->[2]
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.cx(qr[2], qr[0])
coupling = CouplingMap([[0, 1], [0, 2]])
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_direction_mapped"])
def test_false_direction_in_same_layer_undirected(self):
"""Two CXs in the same layer, but one is wrongly directed
qr0:--(+)--
|
qr1:---.---
qr2:---.---
|
qr3:--(+)--
CouplingMap map: [0]->[1]->[2]->[3]
"""
qr = QuantumRegister(4, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[3], qr[2])
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_direction_mapped"])
def test_2q_barrier(self):
"""A 2q barrier should be ignored
qr0:--|--
|
qr1:--|--
CouplingMap map: None
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.barrier(qr[0], qr[1])
coupling = CouplingMap()
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_direction_mapped"])
def test_ecr_gate(self):
"""A directional ECR gate is detected.
ββββββββ
q_0: β€1 β
β ECR β
q_1: β€0 β
ββββββββ
CouplingMap map: [0, 1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.ecr(qr[1], qr[0])
coupling = CouplingMap()
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_direction_mapped"])
@ddt.data(CXGate(), CZGate(), ECRGate())
def test_target_static(self, gate):
"""Test that static 2q gates are detected correctly both if available and not available."""
circuit = QuantumCircuit(2)
circuit.append(gate, [0, 1], [])
matching = Target(num_qubits=2)
matching.add_instruction(gate, {(0, 1): None})
pass_ = CheckGateDirection(None, target=matching)
pass_(circuit)
self.assertTrue(pass_.property_set["is_direction_mapped"])
swapped = Target(num_qubits=2)
swapped.add_instruction(gate, {(1, 0): None})
pass_ = CheckGateDirection(None, target=swapped)
pass_(circuit)
self.assertFalse(pass_.property_set["is_direction_mapped"])
def test_coupling_map_control_flow(self):
"""Test recursing into control-flow operations with a coupling map."""
matching = CouplingMap.from_line(5, bidirectional=True)
swapped = CouplingMap.from_line(5, bidirectional=False)
circuit = QuantumCircuit(5, 1)
circuit.h(0)
circuit.measure(0, 0)
with circuit.for_loop((2,)):
circuit.cx(1, 0)
pass_ = CheckGateDirection(matching)
pass_(circuit)
self.assertTrue(pass_.property_set["is_direction_mapped"])
pass_ = CheckGateDirection(swapped)
pass_(circuit)
self.assertFalse(pass_.property_set["is_direction_mapped"])
circuit = QuantumCircuit(5, 1)
circuit.h(0)
circuit.measure(0, 0)
with circuit.for_loop((2,)):
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.cz(3, 2)
with else_:
with circuit.while_loop((circuit.clbits[0], True)):
circuit.ecr(4, 3)
pass_ = CheckGateDirection(matching)
pass_(circuit)
self.assertTrue(pass_.property_set["is_direction_mapped"])
pass_ = CheckGateDirection(swapped)
pass_(circuit)
self.assertFalse(pass_.property_set["is_direction_mapped"])
def test_target_control_flow(self):
"""Test recursing into control-flow operations with a coupling map."""
swapped = Target(num_qubits=5)
for gate in (CXGate(), CZGate(), ECRGate()):
swapped.add_instruction(gate, {qargs: None for qargs in zip(range(4), range(1, 5))})
matching = Target(num_qubits=5)
for gate in (CXGate(), CZGate(), ECRGate()):
matching.add_instruction(gate, {None: None})
circuit = QuantumCircuit(5, 1)
circuit.h(0)
circuit.measure(0, 0)
with circuit.for_loop((2,)):
circuit.cx(1, 0)
pass_ = CheckGateDirection(None, target=matching)
pass_(circuit)
self.assertTrue(pass_.property_set["is_direction_mapped"])
pass_ = CheckGateDirection(None, target=swapped)
pass_(circuit)
self.assertFalse(pass_.property_set["is_direction_mapped"])
circuit = QuantumCircuit(5, 1)
circuit.h(0)
circuit.measure(0, 0)
with circuit.for_loop((2,)):
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.cz(3, 2)
with else_:
with circuit.while_loop((circuit.clbits[0], True)):
circuit.ecr(4, 3)
pass_ = CheckGateDirection(None, target=matching)
pass_(circuit)
self.assertTrue(pass_.property_set["is_direction_mapped"])
pass_ = CheckGateDirection(None, target=swapped)
pass_(circuit)
self.assertFalse(pass_.property_set["is_direction_mapped"])
if __name__ == "__main__":
unittest.main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.