Repository: Qiskit/qiskit (python)

Issue:
Loading Qpy file with initialized quantum circuit throws "QiskitError: 'Sum of amplitudes-squared is not 1, but 0.0.'"
### Environment

- **Qiskit Terra version**: 0.25.1
- **Python version**:  3.10.1


### What is happening?

When trying to load a Qpy file that was made from a circuit with an initialize instruction, it produces the following error:
```
Traceback (most recent call last):
  Cell In[22], line 13
    qc = qpy.load(fd)[0]
  File /opt/conda/lib/python3.10/site-packages/qiskit/qpy/interface.py:269 in load
    loader(
  File /opt/conda/lib/python3.10/site-packages/qiskit/qpy/binary_io/circuits.py:1092 in read_circuit
    _read_instruction(file_obj, circ, out_registers, custom_operations, version, vectors)
  File /opt/conda/lib/python3.10/site-packages/qiskit/qpy/binary_io/circuits.py:301 in _read_instruction
    gate = gate_class(params)
  File /opt/conda/lib/python3.10/site-packages/qiskit/extensions/quantum_initializer/initializer.py:58 in __init__
    self._stateprep = StatePreparation(params, num_qubits, normalize=normalize)
  File /opt/conda/lib/python3.10/site-packages/qiskit/circuit/library/data_preparation/state_preparation.py:107 in __init__
    raise QiskitError(f"Sum of amplitudes-squared is not 1, but {norm}.")
QiskitError: 'Sum of amplitudes-squared is not 1, but 0.0.'
```

### How can we reproduce the issue?

Run the following:
```python
import qiskit
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import qpy

qr = QuantumRegister(8, name='qr')
cr = ClassicalRegister(8, name='cr')
qc = QuantumCircuit(qr, cr, name='qc')
qc.initialize(0, qc.qubits)

with open('tmp.qpy', 'wb') as fd:
    qpy.dump(qc, fd)
with open('tmp.qpy', 'rb') as fd:
    qc = qpy.load(fd)[0]
```

### What should happen?

Qpy should be able to load the circuit from the file generated.

### Any suggestions?

_No response_

Pull request:
Allow correct retrieval of circuit with initialize instruction from qpy file
<!--
⚠️ If you do not respect this template, your pull request will be closed.
⚠️ Your pull request title should be short detailed and understandable for all.
⚠️ Also, please add a release note file using reno if the change needs to be
  documented in the release notes.
⚠️ If your pull request fixes an open issue, please link to the issue.

- [ ] I have added the tests to cover my changes.
- [ ] I have updated the documentation accordingly.
- [ ] I have read the CONTRIBUTING document.
-->

### Summary
This PR fixes #11158 . It adds the necessary conditions and cases for treating the StatePreparation instruction when reading from a qpy file.


### Details and comments
When loading a circuit that had an initialize instruction (with an index or a label as parameter) from a qpy file, a QiskitError was thrown because these cases were not treated when the circuit was rebuilt, more specifically in the read instruction function. 



Patch:
diff --git a/README.md b/README.md
index c54f433b4..739a03ca4 100644
--- a/README.md
+++ b/README.md
@@ -51,7 +51,7 @@ qc_example.cx(0,1)       # 0th-qubit-Controlled-NOT gate on 1st qubit
 qc_example.cx(0,2)       # 0th-qubit-Controlled-NOT gate on 2nd qubit
 ```
 
-This simple example makes an entangled state known as a [GHZ state](https://en.wikipedia.org/wiki/Greenberger%E2%80%93Horne%E2%80%93Zeilinger_state) $(|000\rangle + |111\rangle)/\sqrt{2}$. It uses the standard quantum gates: Hadamard gate (`h`), Phase gate (`p`), and CNOT gate (`cx`). 
+This simple example makes an entangled state known as a [GHZ state](https://en.wikipedia.org/wiki/Greenberger%E2%80%93Horne%E2%80%93Zeilinger_state) $(|000\rangle + i|111\rangle)/\sqrt{2}$. It uses the standard quantum gates: Hadamard gate (`h`), Phase gate (`p`), and CNOT gate (`cx`). 
 
 Once you've made your first quantum circuit, choose which primitive function you will use. Starting with `sampler`,
 we use `measure_all(inplace=False)` to get a copy of the circuit in which all the qubits are measured:
diff --git a/qiskit/circuit/quantumcircuit.py b/qiskit/circuit/quantumcircuit.py
index bc89e9740..c9f9b04fa 100644
--- a/qiskit/circuit/quantumcircuit.py
+++ b/qiskit/circuit/quantumcircuit.py
@@ -2852,23 +2852,12 @@ class QuantumCircuit:
         """
         from .barrier import Barrier
 
-        qubits: list[QubitSpecifier] = []
-
-        if not qargs:  # None
-            qubits.extend(self.qubits)
-
-        for qarg in qargs:
-            if isinstance(qarg, QuantumRegister):
-                qubits.extend([qarg[j] for j in range(qarg.size)])
-            elif isinstance(qarg, list):
-                qubits.extend(qarg)
-            elif isinstance(qarg, range):
-                qubits.extend(list(qarg))
-            elif isinstance(qarg, slice):
-                qubits.extend(self.qubits[qarg])
-            else:
-                qubits.append(qarg)
-
+        qubits = (
+            # This uses a `dict` not a `set` to guarantee a deterministic order to the arguments.
+            list({q: None for qarg in qargs for q in self.qbit_argument_conversion(qarg)})
+            if qargs
+            else self.qubits.copy()
+        )
         return self.append(Barrier(len(qubits), label=label), qubits, [])
 
     def delay(
diff --git a/qiskit/qpy/binary_io/circuits.py b/qiskit/qpy/binary_io/circuits.py
index 81785bf78..6d910746a 100644
--- a/qiskit/qpy/binary_io/circuits.py
+++ b/qiskit/qpy/binary_io/circuits.py
@@ -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",
diff --git a/releasenotes/notes/fix-circuit-barrier-c696eabae1dcc6c2.yaml b/releasenotes/notes/fix-circuit-barrier-c696eabae1dcc6c2.yaml
new file mode 100644
index 000000000..b16792f8f
--- /dev/null
+++ b/releasenotes/notes/fix-circuit-barrier-c696eabae1dcc6c2.yaml
@@ -0,0 +1,7 @@
+---
+fixes:
+  - |
+    :meth:`.QuantumCircuit.barrier` will now generate correct output when given a :class:`set` as
+    one of its inputs.  Previously, it would append an invalid operation onto the circuit, though in
+    practice this usually would not cause observable problems.
+    Fixed `#11208 <https://github.com/Qiskit/qiskit/issues/11208>`__
diff --git a/releasenotes/notes/fix-qpy-statepreparation-retrieval-1feea5eb74db7f1e.yaml b/releasenotes/notes/fix-qpy-statepreparation-retrieval-1feea5eb74db7f1e.yaml
new file mode 100644
index 000000000..67cdafcb4
--- /dev/null
+++ b/releasenotes/notes/fix-qpy-statepreparation-retrieval-1feea5eb74db7f1e.yaml
@@ -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>`__.


Test patch:
diff --git a/test/python/circuit/test_circuit_load_from_qpy.py b/test/python/circuit/test_circuit_load_from_qpy.py
index f8ba8c260..4f8523358 100644
--- a/test/python/circuit/test_circuit_load_from_qpy.py
+++ b/test/python/circuit/test_circuit_load_from_qpy.py
@@ -1685,6 +1685,18 @@ class TestLoadFromQPY(QiskitTestCase):
             # 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."""
diff --git a/test/python/circuit/test_circuit_operations.py b/test/python/circuit/test_circuit_operations.py
index 11770d896..3f773fb09 100644
--- a/test/python/circuit/test_circuit_operations.py
+++ b/test/python/circuit/test_circuit_operations.py
@@ -420,6 +420,27 @@ class TestCircuitOperations(QiskitTestCase):
         self.assertEqual(len(qc.data), 0)
         self.assertEqual(len(qc._parameter_table), 0)
 
+    def test_barrier(self):
+        """Test multiple argument forms of barrier."""
+        qr1, qr2 = QuantumRegister(3, "qr1"), QuantumRegister(4, "qr2")
+        qc = QuantumCircuit(qr1, qr2)
+        qc.barrier()  # All qubits.
+        qc.barrier(0, 1)
+        qc.barrier([4, 2])
+        qc.barrier(qr1)
+        qc.barrier(slice(3, 5))
+        qc.barrier({1, 4, 2}, range(5, 7))
+
+        expected = QuantumCircuit(qr1, qr2)
+        expected.append(Barrier(expected.num_qubits), expected.qubits.copy(), [])
+        expected.append(Barrier(2), [expected.qubits[0], expected.qubits[1]], [])
+        expected.append(Barrier(2), [expected.qubits[2], expected.qubits[4]], [])
+        expected.append(Barrier(3), expected.qubits[0:3], [])
+        expected.append(Barrier(2), [expected.qubits[3], expected.qubits[4]], [])
+        expected.append(Barrier(5), [expected.qubits[x] for x in [1, 2, 4, 5, 6]], [])
+
+        self.assertEqual(qc, expected)
+
     def test_measure_active(self):
         """Test measure_active
         Applies measurements only to non-idle qubits. Creates a ClassicalRegister of size equal to