Skip to content

Commit

Permalink
Allow correct retrieval of circuit with initialize instruction from q…
Browse files Browse the repository at this point in the history
…py file (#11206)

* treated cases for StatePreparation initialization when reading from qpy file

* added test for state preparation from qpy

* added docstring to test function

* added fix release note

* Fixup release note

---------

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
  • Loading branch information
SoranaAurelia and jakelishman committed Nov 17, 2023
1 parent 252dbd5 commit 9111d0f
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
14 changes: 11 additions & 3 deletions qiskit/qpy/binary_io/circuits.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,9 +319,17 @@ def _read_instruction(
if condition:
gate = gate.c_if(*condition)
else:
if gate_name in {
"Initialize",
"StatePreparation",
if gate_name in {"Initialize", "StatePreparation"}:
if isinstance(params[0], str):
# the params are the labels of the initial state
gate = gate_class("".join(label for label in params))
elif instruction.num_parameters == 1:
# the params is the integer indicating which qubits to initialize
gate = gate_class(int(params[0].real), instruction.num_qargs)
else:
# the params represent a list of complex amplitudes
gate = gate_class(params)
elif gate_name in {
"UCRXGate",
"UCRYGate",
"UCRZGate",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
fixes:
- |
Fixed QPY deserialization of the :class:`.StatePreparation` and :class:`.Initialize` circuit
instructions with string and integer parameters (as opposed to an explicit statevector, which
was already working). Fixed `#11158 <https://github.com/Qiskit/qiskit/issues/11158>`__.
12 changes: 12 additions & 0 deletions test/python/circuit/test_circuit_load_from_qpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -1685,6 +1685,18 @@ def test_qpy_deprecation(self):
# pylint: disable=no-name-in-module, unused-import, redefined-outer-name, reimported
from qiskit.circuit.qpy_serialization import dump, load

@ddt.data(0, "01", [1, 0, 0, 0])
def test_valid_circuit_with_initialize_instruction(self, param):
"""Tests that circuit that has initialize instruction can be saved and correctly retrieved"""
qc = QuantumCircuit(2)
qc.initialize(param, qc.qubits)
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)


class TestSymengineLoadFromQPY(QiskitTestCase):
"""Test use of symengine in qpy set of methods."""
Expand Down

0 comments on commit 9111d0f

Please sign in to comment.