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

Issue:
720x runtime performance regression in `QuantumCircuit.depth()`
<!-- ⚠️ 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**: main (after 7c30a6e7)
- **Python version**: 3.8
- **Operating system**: Linux

### What is the current behavior?

The nightly benchmark runs flagged a regression in the QUEKO transpiler benchmarks caused by https://github.com/Qiskit/qiskit-terra/pull/6998:

https://qiskit.github.io/qiskit/#queko.QUEKOTranspilerBench.time_transpile_bigd?cpu=Intel(R)%20Xeon(R)%20E-2174G%20CPU%20%40%203.80GHz&machine=qiskit-benchmarking01&num_cpu=8&os=Ubuntu%2020.04&ram=64GB&python=3.8&p-optimization%20level=0&p-routing%2Flayout%20method=None&commits=7c30a6e7

It is showing a 720x runtime performance slowdown (from 35.824ms to 25.810s). At first I was surprised because a transpiler benchmark shouldn't be using `QuantumCircuit.depth()` but looking at the benchmark code calling `.depth()` on the output circuit is part of the timed function: https://github.com/Qiskit/qiskit/blob/master/test/benchmarks/queko.py#L235 This is arguably a benchmark bug, but it did catch the regression in this case so it's useful for that.  The regression wasn't quite as bad on other variants so my guess is the regression scales with number of instructions in the circuit (probably because the filter function runs over circuit.data).

### Steps to reproduce the problem

Run `QuantumCircuit.depth()`

### What is the expected behavior?

depth() doesn't scale so poorly


Discussion:
```
if (instr, qargs, cargs) in filter(filter_function, self._data):
```
on L1814 can instead be
```
if filter_function((instr, qargs, cargs)):
```
so that we only loop over all the circuit elements once.

Resolving patch:
diff --git a/qiskit/circuit/quantumcircuit.py b/qiskit/circuit/quantumcircuit.py
--- a/qiskit/circuit/quantumcircuit.py
+++ b/qiskit/circuit/quantumcircuit.py
@@ -1811,7 +1811,7 @@ def depth(self, filter_function: Optional[callable] = lambda x: not x[0]._direct
                 # Add to the stacks of the qubits and
                 # cbits used in the gate.
                 reg_ints.append(bit_indices[reg])
-                if (instr, qargs, cargs) in filter(filter_function, self._data):
+                if filter_function((instr, qargs, cargs)):
                     levels.append(op_stack[reg_ints[ind]] + 1)
                 else:
                     levels.append(op_stack[reg_ints[ind]])


Test patch:
Repository: Qiskit/qiskit

Issue:
Sympy 1.9 deprecates `expr_free_symbol`, used in `ParameterExpression`
<!-- ⚠️ 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**: any
- **Python version**: 
- **Operating system**:

### What is the current behavior?

Sympy 1.9 has begun issuing deprecation warnings when accessing `expr_free_symbols`, which we do during visualisation.  This breaks CI, and will be removed in a future version.


### Steps to reproduce the problem

Run CI.

### What is the expected behavior?

No deprecation warnings.

### Suggested solutions

To get CI running again immediately, we can just pin Sympy to a lower version (see #7116).  The full fix is to replace the usage with the new form (see #7117).


Discussion:

Resolving patch:
diff --git a/qiskit/circuit/tools/pi_check.py b/qiskit/circuit/tools/pi_check.py
--- a/qiskit/circuit/tools/pi_check.py
+++ b/qiskit/circuit/tools/pi_check.py
@@ -46,13 +46,10 @@ def pi_check(inpt, eps=1e-6, output="text", ndigits=5):
     """
     if isinstance(inpt, ParameterExpression):
         param_str = str(inpt)
-        if not hasattr(inpt._symbol_expr, "expr_free_symbols"):
-            from sympy import sympify
+        from sympy import sympify
 
-            expr = sympify(inpt._symbol_expr)
-        else:
-            expr = inpt._symbol_expr
-        syms = expr.expr_free_symbols
+        expr = sympify(inpt._symbol_expr)
+        syms = expr.atoms()
         for sym in syms:
             if not sym.is_number:
                 continue


Test patch:
Repository: Qiskit/qiskit

Issue:
improve scaling of append method of QuantumCircuit for wide circuits
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
Creating a circuit of fixed depth and variable width scales superlinearly with increasing width. This seems to be due to the issubset method of python sets. Other circuit methods which use append are likely also affected such as `inverse`, `reverse_ops`, `combine`, and `extend`. 

![image](https://user-images.githubusercontent.com/25756217/137263422-21ffe911-1770-42da-a25c-91f1f96e1665.png)

Looking at the call graph this seems to be due to the `issubset` call in `_check_qargs`. Probably a similar issue would exist for `_check_cargs`

![image](https://user-images.githubusercontent.com/25756217/137264183-1c4e9a2e-0bcb-472d-8b15-fc676d655cb8.png)

qiskit version: 0.19.0.dev0+ccb9a6c

### What is the expected enhancement?





Discussion:
Do you have the benchmarked code for this one?  In particular, are you adding a fixed number of 1q/2q gates, or does the gate size scale as well?

The problem is likely that `set.issubset` takes a general iterable, and we're giving it a `dict`, which it doesn't recognise as a set.  I don't have your full benchmarking code, but I strongly suspect that swapping the test to `qargs <= self._qubit_indices.keys()` will solve the problem (dictview key objects implement the set ABC).  I'll PR it so there's something to check.

Resolving patch:
diff --git a/qiskit/circuit/quantumcircuit.py b/qiskit/circuit/quantumcircuit.py
--- a/qiskit/circuit/quantumcircuit.py
+++ b/qiskit/circuit/quantumcircuit.py
@@ -1377,14 +1377,14 @@ def _check_qargs(self, qargs: Sequence[Qubit]) -> None:
         """Raise exception if a qarg is not in this circuit or bad format."""
         if not all(isinstance(i, Qubit) for i in qargs):
             raise CircuitError("qarg is not a Qubit")
-        if not set(qargs).issubset(self._qubit_indices):
+        if not set(qargs) <= self._qubit_indices.keys():
             raise CircuitError("qargs not in this circuit")
 
     def _check_cargs(self, cargs: Sequence[Clbit]) -> None:
         """Raise exception if clbit is not in this circuit or bad format."""
         if not all(isinstance(i, Clbit) for i in cargs):
             raise CircuitError("carg is not a Clbit")
-        if not set(cargs).issubset(self._clbit_indices):
+        if not set(cargs) <= self._clbit_indices.keys():
             raise CircuitError("cargs not in this circuit")
 
     def to_instruction(


Test patch:
Repository: Qiskit/qiskit

Issue:
Wrong expression in UGate docs
<!-- ⚠️ 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.18.13
- **Python version**: All
- **Operating system**: All

### What is the current behavior?

The documentation for [`UGate`](https://github.com/Qiskit/qiskit-terra/blob/main/qiskit/circuit/library/standard_gates/u.py) states that:

```
U(\theta, \phi, \lambda) =
    RZ(\phi - \pi/2) RX(\pi/2) RZ(\pi - \theta) RX(\pi/2) RZ(\lambda - \pi/2)
```

### Steps to reproduce the problem

Problem is in the code documentation of [`UGate`](https://github.com/Qiskit/qiskit-terra/blob/main/qiskit/circuit/library/standard_gates/u.py).


### What is the expected behavior?

The expression above does not correspond to the matrix form given in the documentation of [`UGate`](https://github.com/Qiskit/qiskit-terra/blob/main/qiskit/circuit/library/standard_gates/u.py), nor to the RX and RY expressions in terms of U. Since the latter are all in line with the behaviour of Qiskit's ideal simulator, the expression itself is incorrect. The correct expression is instead:

```
U(\theta, \phi, \lambda) =
    RZ(\phi) RX(\pi/2) RZ(\pi - \theta) RX(\pi/2) RZ(\lambda - \pi)
```

### Suggested solutions

Fix the expression in the documentation. For convenience of the reader, one could also add the following simplified expression, from which the matrix, RX and RY expressions are more readily derived:

```
U(\theta, \phi, \lambda) =
    RZ(\phi + \pi/2) RX(\theta) RZ(\lambda - \pi/2)
```




Discussion:

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
@@ -28,7 +28,13 @@ class UGate(Gate):
 
     .. math::
         U(\theta, \phi, \lambda) =
-            RZ(\phi - \pi/2) RX(\pi/2) RZ(\pi - \theta) RX(\pi/2) RZ(\lambda - \pi/2)
+            RZ(\phi) RX(-\pi/2) RZ(\theta) RX(\pi/2) RZ(\lambda)
+
+    Equivalent simplified form:
+
+    .. math::
+        U(\theta, \phi, \lambda) =
+            RZ(\phi + \pi/2) RX(\theta) RZ(\lambda - \pi/2)
 
     **Circuit symbol:**
 


Test patch:
Repository: Qiskit/qiskit

Issue:
An unrelated warning when transpiling an empty set of circuits
### Environment

- **Qiskit Terra version**: a60374091
- **Python version**: 3.9.5
- **Operating system**: Linux


### What is happening?

Transpilation of an empty set of circuits issues a warning about schedule transpilation.

### How can we reproduce the issue?

```
from qiskit import transpile, IBMQ
backend = IBMQ.load_account().backend.ibmq_belem  # can be any backend
transpile([], backend)
```
Output:
```
qiskit/compiler/transpiler.py:246: UserWarning: Transpiling schedules is not supported yet.
  warnings.warn("Transpiling schedules is not supported yet.", UserWarning)
```

### What should happen?

No warning

### Any suggestions?

Just write
```
if len(circuits) > 0:
```
Write before the line
```
warnings.warn("Transpiling schedules is not supported yet.", UserWarning)
```


Discussion:

Resolving patch:
diff --git a/qiskit/compiler/transpiler.py b/qiskit/compiler/transpiler.py
--- a/qiskit/compiler/transpiler.py
+++ b/qiskit/compiler/transpiler.py
@@ -240,6 +240,9 @@ def callback_func(**kwargs):
     arg_circuits_list = isinstance(circuits, list)
     circuits = circuits if arg_circuits_list else [circuits]
 
+    if not circuits:
+        return []
+
     # transpiling schedules is not supported yet.
     start_time = time()
     if all(isinstance(c, Schedule) for c in circuits):


Test patch:
diff --git a/test/python/compiler/test_transpiler.py b/test/python/compiler/test_transpiler.py
--- a/test/python/compiler/test_transpiler.py
+++ b/test/python/compiler/test_transpiler.py
@@ -48,6 +48,10 @@
 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.
Repository: Qiskit/qiskit

Issue:
Parameters needs examples in the documentation
### What is the expected enhancement?

Many users land in https://qiskit.org/documentation/stubs/qiskit.circuit.Parameter.html  when search on how to parametrize circuits. @Cryoris did a good jobs at explaining them in https://quantumcomputing.stackexchange.com/questions/13558/how-to-add-several-parameters-in-qiskit-circuit . I think the Parameter docstring needs a short example.


Discussion:
@1ucian0 I can write up a small example in the docstring

Resolving patch:
diff --git a/qiskit/circuit/parameter.py b/qiskit/circuit/parameter.py
--- a/qiskit/circuit/parameter.py
+++ b/qiskit/circuit/parameter.py
@@ -26,7 +26,32 @@
 
 
 class Parameter(ParameterExpression):
-    """Parameter Class for variable parameters."""
+    """Parameter Class for variable parameters.
+
+    A parameter is a variable value that is not required to be fixed
+    at circuit definition.
+
+    Examples:
+
+        Construct a variable-rotation X gate using circuit parameters.
+
+        .. jupyter-execute::
+
+            from qiskit.circuit import QuantumCircuit, Parameter
+
+            # create the parameter
+            phi = Parameter('phi')
+            qc = QuantumCircuit(1)
+
+            # parameterize the rotation
+            qc.rx(phi, 0)
+            qc.draw()
+
+            # bind the parameters after circuit to create a bound circuit
+            bc = qc.bind_parameters({phi: 3.14})
+            bc.measure_all()
+            bc.draw()
+    """
 
     def __new__(cls, name, uuid=None):  # pylint: disable=unused-argument
         # Parameter relies on self._uuid being set prior to other attributes


Test patch:
Repository: Qiskit/qiskit

Issue:
Performance regression with two-step transpilation #7217
### What is the expected enhancement?

#7217 causes significant performance regression on VQE. We should fix the performance regression.

```python
from timeit import timeit

from qiskit import Aer
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes
from qiskit.opflow import PauliSumOp
from qiskit.utils import QuantumInstance

quantum_instance = QuantumInstance(backend=Aer.get_backend('aer_simulator'), shots=1)
vqe = VQE(ansatz=RealAmplitudes(), optimizer=COBYLA(maxiter=1), quantum_instance=quantum_instance)
op = PauliSumOp.from_list([("ZZ"*5, 1), ("IX"*5, 2)])
print(f'{timeit(lambda: vqe.compute_minimum_eigenvalue(op), number=10)} sec')
```

fe0abaa7
```
1.525182469 sec
```

01967546
```
3.796546701 sec
```


Discussion:

Resolving patch:
diff --git a/qiskit/opflow/converters/circuit_sampler.py b/qiskit/opflow/converters/circuit_sampler.py
--- a/qiskit/opflow/converters/circuit_sampler.py
+++ b/qiskit/opflow/converters/circuit_sampler.py
@@ -329,7 +329,7 @@ def sample_circuits(
             ready_circs = self._transpiled_circ_cache
 
         # run transpiler passes on bound circuits
-        if self._transpile_before_bind:
+        if self._transpile_before_bind and self.quantum_instance.bound_pass_manager is not None:
             ready_circs = self.quantum_instance.transpile(
                 ready_circs, pass_manager=self.quantum_instance.bound_pass_manager
             )


Test patch:
Repository: Qiskit/qiskit

Issue:
Error in documentation for QuantumCircuit.rz()
### Environment

- **Qiskit Terra version**: 0.19.1
- **Python version**: 3.8.10
- **Operating system**: n/a


### What is happening?

Documentation description of `QuantumCircuit.rz()` says "Apply `RYGate`". Should be "Apply `RZGate`".

### How can we reproduce the issue?

n/a

### What should happen?

Change documentation to "Apply `RZGate`".

### Any suggestions?

_No response_


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
@@ -3135,7 +3135,7 @@ def ryy(
         return self.append(RYYGate(theta), [qubit1, qubit2], [])
 
     def rz(self, phi: ParameterValueType, qubit: QubitSpecifier) -> InstructionSet:
-        """Apply :class:`~qiskit.circuit.library.RYGate`.
+        """Apply :class:`~qiskit.circuit.library.RZGate`.
 
         For the full matrix form of this gate, see the underlying gate documentation.
 


Test patch:
Repository: Qiskit/qiskit

Issue:
Missing f-string in qasm3 export error
### Environment

- **Qiskit Terra version**: latest
- **Python version**: 
- **Operating system**: 


### What is happening?

There is a missing f-string in the following error (L468):
https://github.com/Qiskit/qiskit-terra/blob/531e62f3a3c218fee6db116f54ed41ce4e88d9a9/qiskit/qasm3/exporter.py#L466-L469

### How can we reproduce the issue?

Export a circuit with a parametric subroutine.

### What should happen?

The name `instruction` should be printed.

### Any suggestions?

_No response_


Discussion:
haha, whoops - good catch thanks!  Just needs the `f"` to open the string on line 468.
Can I correct this?
Absolutely, please go ahead - I'll assign you.

Resolving patch:
diff --git a/qiskit/qasm3/exporter.py b/qiskit/qasm3/exporter.py
--- a/qiskit/qasm3/exporter.py
+++ b/qiskit/qasm3/exporter.py
@@ -465,7 +465,8 @@ def build_subroutine_definition(self, instruction):
             # the definition.
             raise QASM3ExporterError(
                 "Exporting subroutines with parameters is not yet supported by the OpenQASM 3"
-                " exporter. Received this instruction, which appears parameterized:\n{instruction}"
+                " exporter. Received this instruction, which appears parameterized:"
+                f"\n{instruction}"
             )
         name = self.global_namespace[instruction]
         self.push_context(instruction.definition)


Test patch:
Repository: Qiskit/qiskit

Issue:
run_circuits is using a hardcoded sleep when checking job status
### Environment

- **Qiskit Terra version**:  `main` branch
- **Python version**: n/a
- **Operating system**:  n/a


### What is happening?

The qiskit `run_circuits` utility is using a hard-coded sleep when it waits to check the job status here https://github.com/Qiskit/qiskit-terra/blob/main/qiskit/utils/run_circuits.py#L219.

### How can we reproduce the issue?

_The issue has to do with using a hard-coded value when there is a configured value that can be used instead._

### What should happen?

The code should instead use `qjob_config["wait"]` which comes from the `QuantumInstance` [constructor](https://github.com/Qiskit/qiskit-terra/blob/main/qiskit/utils/quantum_instance.py#L168) and which can be made available to the code in run_circuits.

### Any suggestions?

_No response_


Discussion:

Resolving patch:
diff --git a/qiskit/utils/run_circuits.py b/qiskit/utils/run_circuits.py
--- a/qiskit/utils/run_circuits.py
+++ b/qiskit/utils/run_circuits.py
@@ -205,7 +205,7 @@ def _safe_submit_qobj(
     return job, job_id
 
 
-def _safe_get_job_status(job: BaseJob, job_id: str, max_job_retries: int) -> JobStatus:
+def _safe_get_job_status(job: BaseJob, job_id: str, max_job_retries: int, wait: float) -> JobStatus:
     for _ in range(max_job_retries):
         try:
             job_status = job.status()
@@ -216,7 +216,7 @@ def _safe_get_job_status(job: BaseJob, job_id: str, max_job_retries: int) -> Job
                 job_id,
                 ex,
             )
-            time.sleep(5)
+            time.sleep(wait)
         except Exception as ex:
             raise QiskitError(
                 f"job id: {job_id}, status: 'FAIL_TO_GET_STATUS' Unknown error: ({ex})"
@@ -308,7 +308,9 @@ def run_qobj(
                 logger.info("Running %s-th qobj, job id: %s", idx, job_id)
                 # try to get result if possible
                 while True:
-                    job_status = _safe_get_job_status(job, job_id, max_job_retries)
+                    job_status = _safe_get_job_status(
+                        job, job_id, max_job_retries, qjob_config["wait"]
+                    )
                     queue_position = 0
                     if job_status in JOB_FINAL_STATES:
                         # do callback again after the job is in the final states
@@ -548,7 +550,7 @@ def run_circuits(
                 # try to get result if possible
                 while True:
                     job_status = _safe_get_job_status(
-                        job, job_id, max_job_retries
+                        job, job_id, max_job_retries, qjob_config["wait"]
                     )  # if the status was broken, an Exception would be raised anyway
                     queue_position = 0
                     if job_status in JOB_FINAL_STATES:


Test patch:
Repository: Qiskit/qiskit

Issue:
Misleading drawing format description in QuantumCircuit
I find that the `matplotlib` in the possible output parameters for drawing a circuit is a bit misleading, see https://qiskit.org/documentation/stubs/qiskit.circuit.QuantumCircuit.draw.html.

https://github.com/Qiskit/qiskit-terra/blob/56b0de6822dec3fe1d97c05f4a5ddf3c3f4d4174/qiskit/circuit/quantumcircuit.py#L1739

The actual argument for output is `mpl`. Following the docstring, a new user most likely will try `matplotlib` first.

### Suggestion

Replace the line with 
```
**mpl**: images with color rendered purely in Python using matplotlib.
```



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
@@ -1736,7 +1736,7 @@ def draw(
 
         **text**: ASCII art TextDrawing that can be printed in the console.
 
-        **matplotlib**: images with color rendered purely in Python.
+        **mpl**: images with color rendered purely in Python using matplotlib.
 
         **latex**: high-quality images compiled via latex.
 


Test patch:
Repository: Qiskit/qiskit

Issue:
Minor documentation errors in `execute`
> I think this too can be fixed:
> 
> ![image](https://user-images.githubusercontent.com/42675093/174397008-bbd8f65c-a2e4-4088-ba05-f44aca6adeeb.png)
> 
> https://github.com/Qiskit/qiskit-terra/blob/186c807877e4af573f1ad8ae6d77bac7a3688e33/qiskit/execute_function.py#L232
> 
> ```
> :math:`m \times n`
> ```

true @prakharb10 , also m and n could already be written in the same math environment upon definition. wanna open a new issue/PR since this one is already merged?

_Originally posted by @johannesgreiner in https://github.com/Qiskit/qiskit-terra/issues/8181#issuecomment-1160522309_


Discussion:
Yeah thanks, the intended LaTeX symbol is presumably `\times`.

Resolving patch:
diff --git a/qiskit/execute_function.py b/qiskit/execute_function.py
--- a/qiskit/execute_function.py
+++ b/qiskit/execute_function.py
@@ -229,7 +229,7 @@ def execute(
             experiments will be executed. Each list element (bind) should be of the form
             ``{Parameter1: value1, Parameter2: value2, ...}``. All binds will be
             executed across all experiments, e.g. if parameter_binds is a
-            length-n list, and there are m experiments, a total of :math:`m x n`
+            length-:math:`n` list, and there are :math:`m` experiments, a total of :math:`m \\times n`
             experiments will be run (one for each experiment/bind pair).
 
         schedule_circuit (bool): If ``True``, ``experiments`` will be converted to


Test patch:
Repository: Qiskit/qiskit

Issue:
Migrat `sphinx-panels` to `sphinx-design` extension in documentation
### What should we add?

`sphinx-panels` extension is not actively maintained and the maintainer recommends migrating to `sphinx-design` extension: https://github.com/executablebooks/sphinx-panels#sphinx-panels A migration guide can be found here: https://sphinx-design.readthedocs.io/en/latest/get_started.html#migrating-from-sphinx-panels

See related discussions here: https://github.com/Qiskit/qiskit-terra/pull/8124#issuecomment-1143704773 and the comments below.


Discussion:

Resolving patch:
diff --git a/docs/conf.py b/docs/conf.py
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -36,7 +36,7 @@
     "jupyter_sphinx",
     "sphinx_autodoc_typehints",
     "reno.sphinxext",
-    "sphinx_panels",
+    "sphinx_design"
 ]
 templates_path = ["_templates"]
 
@@ -46,7 +46,7 @@
 numfig_format = {"table": "Table %s"}
 
 # The language for content autogenerated by Sphinx or the default for gettext content translation.
-language = None
+language = "en"
 
 # Relative to source directory, affects general discovery, and html_static_path and html_extra_path.
 exclude_patterns = ["_build", "**.ipynb_checkpoints"]


Test patch: