internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: Qiskit/qiskit

Issue:
LHS circuit calibration lost when combining with another circuit
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Information

- **Qiskit Terra version**:0.17.0
- **Python version**:3.9.1
- **Operating system**:macOS Catalina

### What is the current behavior?
Calibration information is lost when using "+"(extend) for a lhs calibrated circuit.


### Steps to reproduce the problem

from qiskit import QuantumCircuit
from qiskit.circuit.library import RZXGate
from qiskit.pulse import Schedule

qc_cal = QuantumCircuit(2)
qc_cal.rzx(0.5, 0, 1)
qc_cal.add_calibration(RZXGate, (0, 1), params=[0.5], schedule=Schedule())
# qc_cal = transpile(qc_cal,backend)
print(qc_cal.calibrations)

qc = QuantumCircuit(2)
qc.h(0)


new_circ_cal_on_lhs = qc_cal + qc
print(new_circ_cal_on_lhs.calibrations) #calibration information is lost

new_circ_cal_on_rhs = qc +qc_cal
print(new_circ_cal_on_rhs.calibrations) #calibration information is kept

### What is the expected behavior?
For the calibrations information to be maintained when making new circuit from "calibrated_circuit+uncalibrated_circuit" 


### Suggested solutions

Modify extend function to check and add calibrations from lhs circuit.



Discussion:
Fixed by #5910
Hi @taalexander - this issue still exists even with #5910.   #5910 fixes calibrations that exist in the right hand circuit but not the left.  (The above code should confirm this)

Resolving patch:
diff --git a/qiskit/circuit/quantumcircuit.py b/qiskit/circuit/quantumcircuit.py
--- a/qiskit/circuit/quantumcircuit.py
+++ b/qiskit/circuit/quantumcircuit.py
@@ -572,6 +572,10 @@ def combine(self, rhs):
             for key, sched in cals.items():
                 circuit.add_calibration(gate, qubits=key[0], schedule=sched, params=key[1])
 
+        for gate, cals in self.calibrations.items():
+            for key, sched in cals.items():
+                circuit.add_calibration(gate, qubits=key[0], schedule=sched, params=key[1])
+
         return circuit
 
     def extend(self, rhs):


Test patch:
diff --git a/test/python/circuit/test_calibrations.py b/test/python/circuit/test_calibrations.py
--- a/test/python/circuit/test_calibrations.py
+++ b/test/python/circuit/test_calibrations.py
@@ -46,6 +46,11 @@ def test_add(self):
         self.assertEqual(qc.calibrations[RZXGate], {((0, 1), (0.5,)): Schedule(name="test")})
         self.assertEqual(qc_cal.calibrations, qc.calibrations)
 
+        qc = qc_cal + QuantumCircuit(2)
+
+        self.assertEqual(qc.calibrations[RZXGate], {((0, 1), (0.5,)): Schedule(name="test")})
+        self.assertEqual(qc_cal.calibrations, qc.calibrations)
+
 
 if __name__ == '__main__':
     unittest.main()
Repository: Qiskit/qiskit

Issue:
Evaluating expectations with ComposedOps return vectors instead of scalars in the ``~StateFn(op) @ state`` representation
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Information

- **Qiskit Terra version**: 90387a20be329f3752c4acfceb2420f89c895178
- **Python version**: 3.7.9
- **Operating system**: macOS Big Sur

### What is the current behavior?

```python
>>> from qiskit import QuantumCircuit
>>> from qiskit.opflow import CircuitOp, StateFn, I
>>> circuit = QuantumCircuit(1)
>>> vector = [1, 0]
>>> state = CircuitOp(circuit) @ StateFn(vector)
>>> (~state @ I @ state).eval()
(1+0j)
>>> (~StateFn(I) @ state).eval()
VectorStateFn(Statevector([1.-0.j 0.-0.j]), coeff=1.0, is_measurement=True)
>>>
```

### Steps to reproduce the problem

See above.

### What is the expected behavior?

Evaluating `~StateFn(I) @ state` should produce the same result as `~state @ I @ state`.

### Suggested solutions

#6009



Discussion:
I've checked this code at master now 90387a2.

It returns
```
VectorStateFn(Statevector([1.-0.j 0.-0.j]), coeff=1.0, is_measurement=True)
```

Python 3.8.5, Catalina

```python
(~StateFn(I) @ CircuitOp(circuit) @ StateFn(vector)).eval()
```
returns `(1+0j)` correctly.

Resolving patch:
diff --git a/qiskit/opflow/state_fns/state_fn.py b/qiskit/opflow/state_fns/state_fn.py
--- a/qiskit/opflow/state_fns/state_fn.py
+++ b/qiskit/opflow/state_fns/state_fn.py
@@ -275,6 +275,9 @@ def compose(self, other: OperatorBase,
                            coeff=self.coeff * other.coeff)
 
         from ..list_ops.composed_op import ComposedOp
+        if isinstance(other, ComposedOp):
+            return ComposedOp([new_self] + other.oplist, coeff=new_self.coeff * other.coeff)
+
         return ComposedOp([new_self, other])
 
     def power(self, exponent: int) -> OperatorBase:


Test patch:
diff --git a/test/python/opflow/test_state_construction.py b/test/python/opflow/test_state_construction.py
--- a/test/python/opflow/test_state_construction.py
+++ b/test/python/opflow/test_state_construction.py
@@ -23,7 +23,7 @@
 from qiskit.circuit import ParameterVector
 from qiskit.quantum_info import Statevector
 
-from qiskit.opflow import (StateFn, Zero, One, Plus, Minus, PrimitiveOp,
+from qiskit.opflow import (StateFn, Zero, One, Plus, Minus, PrimitiveOp, CircuitOp,
                            SummedOp, H, I, Z, X, Y, CX, CircuitStateFn, DictToCircuitSum)
 
 
@@ -208,6 +208,16 @@ def test_primitive_param_binding(self):
         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)
+
 
 if __name__ == '__main__':
     unittest.main()
Repository: Qiskit/qiskit

Issue:
Inverse U gate parameter ordering issue
To whom it may concern,

It came to my attention that the inverse of U gate doesn't have the right order of parameters as the math notation and understanding.

Though it is working as expected in the simulation, the user needs to swap the orders, which is mathematically incorrect.

Please look at the order of parameters and mathematical order.

https://qiskit.org/documentation/_modules/qiskit/circuit/library/standard_gates/u.html#UGate.inverse

math:`U(\theta,\phi,\lambda)^{\dagger} =U3(-\theta,-\phi,-\lambda)`)
        """
        return UGate(-self.params[0], **-**self.params[2], -self.params[1]****)


Discussion:
Thanks for reporting this @sternparky , you're right that the order in the docstring here is incorrect, and should be updated to match the order returned by the function.

Resolving patch:
diff --git a/qiskit/circuit/library/standard_gates/u.py b/qiskit/circuit/library/standard_gates/u.py
--- a/qiskit/circuit/library/standard_gates/u.py
+++ b/qiskit/circuit/library/standard_gates/u.py
@@ -66,7 +66,7 @@ def __init__(self, theta, phi, lam, label=None):
     def inverse(self):
         r"""Return inverted U gate.
 
-        :math:`U(\theta,\phi,\lambda)^{\dagger} =U3(-\theta,-\phi,-\lambda)`)
+        :math:`U(\theta,\phi,\lambda)^{\dagger} =U(-\theta,-\lambda,-\phi)`)
         """
         return UGate(-self.params[0], -self.params[2], -self.params[1])
 
diff --git a/qiskit/circuit/library/standard_gates/u3.py b/qiskit/circuit/library/standard_gates/u3.py
--- a/qiskit/circuit/library/standard_gates/u3.py
+++ b/qiskit/circuit/library/standard_gates/u3.py
@@ -65,7 +65,7 @@ def __init__(self, theta, phi, lam, label=None):
     def inverse(self):
         r"""Return inverted U3 gate.
 
-        :math:`U3(\theta,\phi,\lambda)^{\dagger} =U3(-\theta,-\phi,-\lambda)`)
+        :math:`U3(\theta,\phi,\lambda)^{\dagger} =U3(-\theta,-\lambda,-\phi)`)
         """
         return U3Gate(-self.params[0], -self.params[2], -self.params[1])
 


Test patch:
Repository: Qiskit/qiskit

Issue:
QuantumCircuit.copy doesn't copy metadata
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Information

- **Qiskit Terra version**: 0.17
- **Python version**:
- **Operating system**:

### What is the current behavior?

`QuantumCircuit.copy()` is supposed to return a deep copy of a circuit, however if the circuit has a metadata dictionary it is not copied, hence if the copy metadata is modified, these changes affect the original circuit too.

### Steps to reproduce the problem

Basic example

```python
from qiskit import QuantumCircuit

qc1 = QuantumCircuit(1)
qc1.metadata = {'a': 0}

qc2 = qc1.copy()
qc2.metadata['a'] = 1000

print(qc1.metadata)
print(qc2.metadata)
# Both return {'a': 1000}
```

### What is the expected behavior?

When copying a circuit metadata should also be copied. In the above example the final print statements should return
```python
{'a': 0}
{'a': 1000}
```

### Suggested solutions

Check how copying is handled in `QuantumCircuit.copy` and update it so that `circ_cpy.metadata = circ.metadata.copy()`




Discussion:

Resolving patch:
diff --git a/qiskit/circuit/quantumcircuit.py b/qiskit/circuit/quantumcircuit.py
--- a/qiskit/circuit/quantumcircuit.py
+++ b/qiskit/circuit/quantumcircuit.py
@@ -1727,6 +1727,7 @@ def copy(self, name=None):
                      for inst, qargs, cargs in self._data]
 
         cpy._calibrations = copy.deepcopy(self._calibrations)
+        cpy._metadata = copy.deepcopy(self._metadata)
 
         if name:
             cpy.name = name


Test patch:
diff --git a/test/python/circuit/test_circuit_properties.py b/test/python/circuit/test_circuit_properties.py
--- a/test/python/circuit/test_circuit_properties.py
+++ b/test/python/circuit/test_circuit_properties.py
@@ -671,6 +671,18 @@ def test_calibrations_no_params(self):
         self.assertEqual(circ.calibrations['h'][((0,), ())].instructions,
                          q0_x180.instructions)
 
+    def test_metadata_copy_does_not_share_state(self):
+        """Verify mutating the metadata of a circuit copy does not impact original."""
+        # ref: https://github.com/Qiskit/qiskit-terra/issues/6057
+
+        qc1 = QuantumCircuit(1)
+        qc1.metadata = {'a': 0}
+
+        qc2 = qc1.copy()
+        qc2.metadata['a'] = 1000
+
+        self.assertEqual(qc1.metadata['a'], 0)
+
 
 if __name__ == '__main__':
     unittest.main()
Repository: Qiskit/qiskit

Issue:
Copying `QuantumCircuit` fails after `circuit.remove_final_measurements()`
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Information

- **Qiskit Terra version**: 0.17
- **Python version**: 3.8
- **Operating system**: MacOS

### What is the current behavior?

Creating a `QuantumCircuit`, calling `circuit.remove_final_measurements()` and then copying the `circuit` fails with raising a `KeyError`.

### Steps to reproduce the problem

```
qc = QuantumCircuit(2)
qc = qc.compose(RealAmplitudes(2))
qc.remove_final_measurements()
qc.copy()
```

### What is the expected behavior?

Expected behavior would be to just get back a copy of the modified circuit.


### Suggested solutions

Fix `remove_final_measurements()`.




Discussion:

Resolving patch:
diff --git a/qiskit/circuit/quantumcircuit.py b/qiskit/circuit/quantumcircuit.py
--- a/qiskit/circuit/quantumcircuit.py
+++ b/qiskit/circuit/quantumcircuit.py
@@ -1847,6 +1847,7 @@ def remove_final_measurements(self, inplace=True):
 
         # Set circ cregs and instructions to match the new DAGCircuit's
         circ.data.clear()
+        circ._parameter_table.clear()
         circ.cregs = list(new_dag.cregs.values())
 
         for node in new_dag.topological_op_nodes():


Test patch:
diff --git a/test/python/circuit/test_circuit_operations.py b/test/python/circuit/test_circuit_operations.py
--- a/test/python/circuit/test_circuit_operations.py
+++ b/test/python/circuit/test_circuit_operations.py
@@ -353,6 +353,23 @@ def test_remove_final_measurements_copy(self):
         self.assertEqual(expected, new_circuit)
         self.assertTrue('measure' in circuit.count_ops().keys())
 
+    def test_remove_final_measurements_copy_with_parameters(self):
+        """Test remove_final_measurements doesn't corrupt ParameterTable
+
+        See https://github.com/Qiskit/qiskit-terra/issues/6108 for more details
+        """
+        qr = QuantumRegister(2)
+        cr = ClassicalRegister(2, 'meas')
+        theta = Parameter('theta')
+
+        circuit = QuantumCircuit(qr, cr)
+        circuit.rz(theta, qr)
+        circuit.measure(qr, cr)
+        circuit.remove_final_measurements()
+        copy = circuit.copy()
+
+        self.assertEqual(copy, circuit)
+
     def test_remove_final_measurements_multiple_measures(self):
         """Test remove_final_measurements only removes measurements at the end of the circuit
         remove_final_measurements should not remove measurements in the beginning or middle of the
Repository: Qiskit/qiskit

Issue:
Typo in docstring for MCX gate
The docstring for the ```mcx``` method in [```QuantumCircuit.py```](https://github.com/Qiskit/qiskit-terra/blob/master/qiskit/circuit/quantumcircuit.py#L2532) has a typo regarding the ```mode``` kwarg (```no-ancilla``` rather than ```noancilla```).


Discussion:
Hi @jsistos,

I got what is the problem and would love to fix this issue. Please assign this issue to me so that I can start working on it.

Best,
Abhishek

Resolving patch:
diff --git a/qiskit/circuit/quantumcircuit.py b/qiskit/circuit/quantumcircuit.py
--- a/qiskit/circuit/quantumcircuit.py
+++ b/qiskit/circuit/quantumcircuit.py
@@ -2530,7 +2530,7 @@ def mcx(self, control_qubits, target_qubit, ancilla_qubits=None, mode='noancilla
 
         The multi-cX gate can be implemented using different techniques, which use different numbers
         of ancilla qubits and have varying circuit depth. These modes are:
-        - 'no-ancilla': Requires 0 ancilla qubits.
+        - 'noancilla': Requires 0 ancilla qubits.
         - 'recursion': Requires 1 ancilla qubit if more than 4 controls are used, otherwise 0.
         - 'v-chain': Requires 2 less ancillas than the number of control qubits.
         - 'v-chain-dirty': Same as for the clean ancillas (but the circuit will be longer).


Test patch:
Repository: Qiskit/qiskit

Issue:
num_qubits() for DictStateFn is inefficient
To get the number of qubits, a list of all keys in the dictionary is constructed. But, only the length of the first key is used. Constructing the entire list is wasteful.

https://github.com/Qiskit/qiskit-terra/blob/c3b2d7acb80fa89043e6f38efb501275ec296616/qiskit/opflow/state_fns/dict_state_fn.py#L82

This code should work:
```python
len(next(iter(self.primitive)))
```

`%timeit` shows that the latter is faster even when the dict contains only two keys.

- **Qiskit Terra version**:  123d829ac, Feb 3 master







Discussion:

Resolving patch:
diff --git a/qiskit/opflow/state_fns/dict_state_fn.py b/qiskit/opflow/state_fns/dict_state_fn.py
--- a/qiskit/opflow/state_fns/dict_state_fn.py
+++ b/qiskit/opflow/state_fns/dict_state_fn.py
@@ -81,7 +81,7 @@ def primitive_strings(self) -> Set[str]:
 
     @property
     def num_qubits(self) -> int:
-        return len(list(self.primitive.keys())[0])
+        return len(next(iter(self.primitive)))
 
     def add(self, other: OperatorBase) -> OperatorBase:
         if not self.num_qubits == other.num_qubits:


Test patch:
Repository: Qiskit/qiskit

Issue:
quantum_info.Kraus: Possible redundant documentation
In the `Kraus` class of `quantum_info` module, the current [documentation](https://qiskit.org/documentation/stubs/qiskit.quantum_info.Kraus.html) is as follows:

![image](https://user-images.githubusercontent.com/61590679/113423624-733eea00-93ec-11eb-8fd3-99485494e8a8.png)

I believe the 2nd line, 'The Kraus representation for a quantum channel $\mathcal{E}$ is a set of matrices $[A_0, ... A_{K-1}]$ such that' can be removed, as it does not convey much information, and the next line 'For a quantum channel...' conveys the required information quite completely. If removing the line is not acceptable, perhaps at the least the two lines can be combined (and the dangling 'such that' removed).


Discussion:
If you believe this is a good first issue, I would like to attempt the fix, as I am new to this project.
Welcome! Thanks for spotting this.

Resolving patch:
diff --git a/qiskit/quantum_info/operators/channel/kraus.py b/qiskit/quantum_info/operators/channel/kraus.py
--- a/qiskit/quantum_info/operators/channel/kraus.py
+++ b/qiskit/quantum_info/operators/channel/kraus.py
@@ -33,9 +33,6 @@
 class Kraus(QuantumChannel):
     r"""Kraus representation of a quantum channel.
 
-    The Kraus representation for a quantum channel :math:`\mathcal{E}` is a
-    set of matrices :math:`[A_0,...,A_{K-1}]` such that
-
     For a quantum channel :math:`\mathcal{E}`, the Kraus representation is
     given by a set of matrices :math:`[A_0,...,A_{K-1}]` such that the
     evolution of a :class:`~qiskit.quantum_info.DensityMatrix`


Test patch:
Repository: Qiskit/qiskit

Issue:
Convert DAGNode.name attribute to property
An unrelated thing here is I think maybe we need a similar property lookup as to DAGNode.condtion so for op nodes we just pull the name directly from the op node. something like:
```python3
@property
def name(self):
   if self._name:
       return self._name
   return self.op.name
```
just because it seems like there is a lot of mixing of node.name and node.op.name and while they should always be the same thing, it's probably good to actually enforce that.

_Originally posted by @mtreinish in https://github.com/Qiskit/qiskit-terra/pull/6187#discussion_r610764534_


Discussion:
I can pick this up.

Resolving patch:
diff --git a/qiskit/dagcircuit/dagcircuit.py b/qiskit/dagcircuit/dagcircuit.py
--- a/qiskit/dagcircuit/dagcircuit.py
+++ b/qiskit/dagcircuit/dagcircuit.py
@@ -369,8 +369,7 @@ def _add_op_node(self, op, qargs, cargs):
             int: The integer node index for the new op node on the DAG
         """
         # Add a new operation node to the graph
-        new_node = DAGNode(type="op", op=op, name=op.name, qargs=qargs,
-                           cargs=cargs)
+        new_node = DAGNode(type="op", op=op, qargs=qargs, cargs=cargs)
         node_index = self._multi_graph.add_node(new_node)
         new_node._node_id = node_index
         return node_index
diff --git a/qiskit/dagcircuit/dagnode.py b/qiskit/dagcircuit/dagnode.py
--- a/qiskit/dagcircuit/dagnode.py
+++ b/qiskit/dagcircuit/dagnode.py
@@ -26,14 +26,19 @@ class DAGNode:
     be supplied to functions that take a node.
     """
 
-    __slots__ = ['type', '_op', 'name', '_qargs', 'cargs', '_wire', 'sort_key', '_node_id']
+    __slots__ = ['type', '_op', '_qargs', 'cargs', '_wire', 'sort_key', '_node_id']
 
     def __init__(self, type=None, op=None, name=None, qargs=None, cargs=None,
                  wire=None, nid=-1):
         """Create a node """
         self.type = type
         self._op = op
-        self.name = name
+        if name is not None:
+            warnings.warn(
+                "The DAGNode 'name' attribute is deprecated as of 0.18.0 and "
+                "will be removed no earlier than 3 months after the release date. "
+                "You can use 'DAGNode.op.name' if the DAGNode is of type 'op'.",
+                DeprecationWarning, 2)
         self._qargs = qargs if qargs is not None else []
         self.cargs = cargs if cargs is not None else []
         self._wire = wire
@@ -51,6 +56,18 @@ def op(self):
     def op(self, data):
         self._op = data
 
+    @property
+    def name(self):
+        """Returns the Instruction name corresponding to the op for this node"""
+        if self.type and self.type == 'op':
+            return self._op.name
+        return None
+
+    @name.setter
+    def name(self, name):
+        if self.type and self.type == 'op':
+            self._op.name = name
+
     @property
     def condition(self):
         """Returns the condition of the node.op"""


Test patch:
Repository: Qiskit/qiskit

Issue:
Fix dag_drawer() that raises file access error on Windows.
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Information

- **Qiskit Terra version**: 0.17
- **Python version**: 3.8
- **Operating system**: Windows

### What is the current behavior?

When running the `dag_drawer` the following exception is generated
```
...
 def _rmtree_unsafe(path, onerror):
    592     try:
--> 593         with os.scandir(path) as scandir_it:
    594             entries = list(scandir_it)
    595     except OSError:

NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\\Users\\EENDEB~1\\AppData\\Local\\Temp\\tmplyv2yqtq\\dag.png'
```

The problem is related to the `PIL` package openining an image, but keeping a file handle locked.

### Steps to reproduce the problem

Run the following minimal example (from jupyter)

```
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import transpile, schedule
from qiskit.dagcircuit import DAGCircuit
from qiskit.converters import circuit_to_dag
from qiskit.visualization import dag_drawer
from qiskit.visualization.pulse_v2 import draw as draw_pulse
import qiskit
import matplotlib.pyplot as plt


q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c, 2)

dag = circuit_to_dag(circ)
dag_drawer(dag)
```

### What is the expected behavior?

No error should be generated.

A similar error was addressed in https://github.com/Qiskit/qiskit-terra/pull/4794, this is a variation of the same problem.

### Suggested solutions

In `dag_visualization.py` replace

```
        with tempfile.TemporaryDirectory() as tmpdirname:
            tmp_path = os.path.join(tmpdirname, 'dag.png')
            dot.write_png(tmp_path)
            image = Image.open(tmp_path)
            os.remove(tmp_path)
            return image
```
with 
```
        with tempfile.TemporaryDirectory() as tmpdirname:
            tmp_path = os.path.join(tmpdirname, 'dag.png')
            dot.write_png(tmp_path)
            image = Image.open(tmp_path)
            import copy
            image2=copy.copy(image)
            os.remove(tmp_path)
            return image2
```


Discussion:

Resolving patch:
diff --git a/qiskit/visualization/dag_visualization.py b/qiskit/visualization/dag_visualization.py
--- a/qiskit/visualization/dag_visualization.py
+++ b/qiskit/visualization/dag_visualization.py
@@ -170,7 +170,8 @@ def edge_attr_func(edge):
         with tempfile.TemporaryDirectory() as tmpdirname:
             tmp_path = os.path.join(tmpdirname, 'dag.png')
             dot.write_png(tmp_path)
-            image = Image.open(tmp_path)
+            with Image.open(tmp_path) as test_image:
+                image = test_image.copy()
             os.remove(tmp_path)
             return image
     else:


Test patch: