Skip to content

Commit

Permalink
fix a corner case of SparsePauliOp.apply_layout
Browse files Browse the repository at this point in the history
  • Loading branch information
t-imamichi committed May 9, 2024
1 parent 87c14cb commit f221ceb
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
3 changes: 3 additions & 0 deletions qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -1164,6 +1164,9 @@ def apply_layout(
if layout is None:
layout = list(range(self.num_qubits))
new_op = type(self)("I" * n_qubits)
if self.num_qubits == 0:
coeff = self.simplify(atol=0).coeffs[0]
return new_op * coeff
return new_op.compose(self, qargs=layout)


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
fixes:
- |
Fixed :meth:`~.SparsePauliOp.apply_layout` to work correctly with zero-qubit operators.
Original file line number Diff line number Diff line change
Expand Up @@ -1179,6 +1179,25 @@ def test_apply_layout_null_layout_invalid_num_qubits(self):
with self.assertRaises(QiskitError):
op.apply_layout(layout=None, num_qubits=1)

def test_apply_layout_zero_qubit(self):
"""Test apply_layout with a zero-qubit operator"""
with self.subTest("default"):
op = SparsePauliOp("")
res = op.apply_layout(layout=None, num_qubits=5)
self.assertEqual(SparsePauliOp("IIIII"), res)
with self.subTest("coeff"):
op = SparsePauliOp("", 2)
res = op.apply_layout(layout=None, num_qubits=5)
self.assertEqual(SparsePauliOp("IIIII", 2), res)
with self.subTest("layout"):
op = SparsePauliOp("")
res = op.apply_layout(layout=[], num_qubits=5)
self.assertEqual(SparsePauliOp("IIIII"), res)
with self.subTest("multiple ops"):
op = SparsePauliOp.from_list([("", 1), ("", 2)])
res = op.apply_layout(layout=None, num_qubits=5)
self.assertEqual(SparsePauliOp("IIIII", 3), res)


if __name__ == "__main__":
unittest.main()

0 comments on commit f221ceb

Please sign in to comment.