internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: quantumlib/Cirq

Issue:
importlib.abc in Python 3.10
**Description of the issue**

In Python 3.10.0, the command `import cirq` fails with the error:

```
class InstrumentedFinder(importlib.abc.MetaPathFinder):
AttributeError: module 'importlib' has no attribute 'abc'. Did you mean: '_abc'? 
```

**Workaround**

If one imports `importlib.abc` prior to importing cirq, no error occurs:

```python
from importlib import abc
import cirq
```

**Suggestion**

Probably you should add `from importlib import abc` somewhere in the Сirq's code.

Searching on Google, I've found a similar issue in another project: [grpc/issues/26062](https://github.com/grpc/grpc/issues/26062)

**Cirq version**
0.13.1




Discussion:
Thank you for opening this. Please feel free to work on it.

Resolving patch:
diff --git a/cirq-core/cirq/_import.py b/cirq-core/cirq/_import.py
--- a/cirq-core/cirq/_import.py
+++ b/cirq-core/cirq/_import.py
@@ -12,17 +12,18 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-from typing import Any, Callable, List, Optional
+from typing import Any, Callable, cast, List, Optional
+from types import ModuleType
+from importlib.machinery import ModuleSpec
+from importlib.abc import Loader
 
 from contextlib import contextmanager
 import importlib
+from importlib import abc
 import sys
 
-# Bug workaround: https://github.com/python/mypy/issues/1498
-ModuleType = Any
 
-
-class InstrumentedFinder(importlib.abc.MetaPathFinder):
+class InstrumentedFinder(abc.MetaPathFinder):
     """A module finder used to hook the python import statement."""
 
     def __init__(
@@ -74,7 +75,7 @@ def wrap_spec(self, spec: Any) -> Any:
         return spec
 
 
-class InstrumentedLoader(importlib.abc.Loader):
+class InstrumentedLoader(abc.Loader):
     """A module loader used to hook the python import statement."""
 
     def __init__(
@@ -106,12 +107,12 @@ def __init__(
         self.wrap_module = wrap_module
         self.after_exec = after_exec
 
-    def create_module(self, spec: ModuleType) -> ModuleType:
+    def create_module(self, spec: ModuleSpec) -> ModuleType:
         return self.loader.create_module(spec)
 
     def exec_module(self, module: ModuleType) -> None:
-        module = self.wrap_module(module)
-        if module is not None:
+        wrapped_module = self.wrap_module(module)
+        if wrapped_module is not None:
             self.loader.exec_module(module)
             self.after_exec(module)
 
@@ -168,4 +169,5 @@ def wrap_func(module: ModuleType) -> Optional[ModuleType]:
 
     delay = False
     for module in execute_list:
-        module.__loader__.exec_module(module)  # Calls back into wrap_func
+        if module.__loader__ is not None and hasattr(module.__loader__, 'exec_module'):
+            cast(Loader, module.__loader__).exec_module(module)  # Calls back into wrap_func


Test patch:
Repository: quantumlib/Cirq

Issue:
Should an IonDevice accept any qubit type?
Some docstrings ([here](https://github.com/quantumlib/Cirq/blob/master/cirq/ion/ion_device.py#L26)) state qubits are one a line, while others ([here](https://github.com/quantumlib/Cirq/blob/master/cirq/ion/ion_device.py#L42)) state qubits are identified by their x, y location. I believe the latter is a typo due to the [annotation](https://github.com/quantumlib/Cirq/blob/master/cirq/ion/ion_device.py#L34).

If so, should `__init__` raise an error if the input qubits are not `LineQubit`s? (The `at` and `neighbors_of` methods assume `LineQubit`s.)


Discussion:
I agree - I think we should expect `LineQubit`s - now we have an ion-computing expert, @dabacon can you chime in? 
@dabacon was off talking to money people but now he is back and much happier to not have to listen to quantum hype.

LineQubit makes the most sense, even though there is all to all connectivity, when addressing in hardware it makes sense to address on a line.  

The documentation has been fixed, but probably good to be defensive and throw a TypeError in the constructor.



Resolving patch:
diff --git a/cirq-core/cirq/ion/ion_device.py b/cirq-core/cirq/ion/ion_device.py
--- a/cirq-core/cirq/ion/ion_device.py
+++ b/cirq-core/cirq/ion/ion_device.py
@@ -55,11 +55,19 @@ def __init__(
             twoq_gates_duration: The maximum duration of a two qubit operation.
             oneq_gates_duration: The maximum duration of a single qubit
             operation.
-            qubits: Qubits on the device, identified by their x, y location.
+            qubits: Qubits on the device, identified by their x location.
+
+        Raises:
+            TypeError: If not all the qubits supplied are `cirq.LineQubit`s.
         """
         self._measurement_duration = value.Duration(measurement_duration)
         self._twoq_gates_duration = value.Duration(twoq_gates_duration)
         self._oneq_gates_duration = value.Duration(oneq_gates_duration)
+        if not all(isinstance(qubit, devices.LineQubit) for qubit in qubits):
+            raise TypeError(
+                "All qubits were not of type cirq.LineQubit, instead were "
+                f"{set(type(qubit) for qubit in qubits)}"
+            )
         self.qubits = frozenset(qubits)
         self.gateset = get_ion_gateset()
 


Test patch:
diff --git a/cirq-core/cirq/ion/ion_device_test.py b/cirq-core/cirq/ion/ion_device_test.py
--- a/cirq-core/cirq/ion/ion_device_test.py
+++ b/cirq-core/cirq/ion/ion_device_test.py
@@ -56,6 +56,14 @@ def test_init():
     with pytest.raises(ValueError):
         _ = d.duration_of(cirq.SingleQubitGate().on(q0))
 
+    with pytest.raises(TypeError, match="NamedQubit"):
+        _ = cirq.IonDevice(
+            measurement_duration=ms,
+            twoq_gates_duration=ms,
+            oneq_gates_duration=ms,
+            qubits=[cirq.LineQubit(0), cirq.NamedQubit("a")],
+        )
+
 
 def test_init_timedelta():
     d = ion_device(3, use_timedelta=True)
Repository: quantumlib/Cirq

Issue:
Fix deprecation warning for newly added `ClassicallyControlledOperation`
**Description of the issue**
The following deprecation warning is emitted on running the json serialization test and should be fixed.
```python
~/quantum/Cirq/cirq-core/cirq/protocols/json_serialization.py:283: DeprecationWarning: Found 'cirq_type': 'ClassicallyControlledOperation' in _json_dict_. Custom values of this field are not permitted, and will produce an error starting in Cirq v0.15.
```
**Cirq version**
0.14dev



Discussion:

Resolving patch:
diff --git a/cirq-core/cirq/ops/classically_controlled_operation.py b/cirq-core/cirq/ops/classically_controlled_operation.py
--- a/cirq-core/cirq/ops/classically_controlled_operation.py
+++ b/cirq-core/cirq/ops/classically_controlled_operation.py
@@ -171,7 +171,6 @@ def _circuit_diagram_info_(
 
     def _json_dict_(self) -> Dict[str, Any]:
         return {
-            'cirq_type': self.__class__.__name__,
             'conditions': self._conditions,
             'sub_operation': self._sub_operation,
         }


Test patch:
Repository: quantumlib/Cirq

Issue:
Default atol for sub_state_vector is too picky for default precision of simulator
The following raises an exception instead of finishing successfully:

```
import cirq
a, b = cirq.LineQubit.range(2)
final_state_vector = cirq.Simulator().simulate(cirq.Circuit(
    cirq.H(a),
    cirq.H(b),
    cirq.CZ(a, b),
    cirq.measure(a),
)).final_state_vector.reshape((2, 2))
print(cirq.sub_state_vector(final_state_vector, [0]))
```

Giving `atol=1e-6` to the `sub_state_vector` method fixes it. The default of `atol=1e-8` seems to be too strict given that this simple example fails it.


Discussion:

Resolving patch:
diff --git a/cirq-core/cirq/linalg/transformations.py b/cirq-core/cirq/linalg/transformations.py
--- a/cirq-core/cirq/linalg/transformations.py
+++ b/cirq-core/cirq/linalg/transformations.py
@@ -396,7 +396,7 @@ def sub_state_vector(
     keep_indices: List[int],
     *,
     default: np.ndarray = RaiseValueErrorIfNotProvided,
-    atol: Union[int, float] = 1e-8,
+    atol: Union[int, float] = 1e-6,
 ) -> np.ndarray:
     r"""Attempts to factor a state vector into two parts and return one of them.
 


Test patch:
diff --git a/cirq-core/cirq/linalg/transformations_test.py b/cirq-core/cirq/linalg/transformations_test.py
--- a/cirq-core/cirq/linalg/transformations_test.py
+++ b/cirq-core/cirq/linalg/transformations_test.py
@@ -609,3 +609,22 @@ def test_to_special():
     su = cirq.to_special(u)
     assert not cirq.is_special_unitary(u)
     assert cirq.is_special_unitary(su)
+
+
+def test_default_tolerance():
+    a, b = cirq.LineQubit.range(2)
+    final_state_vector = (
+        cirq.Simulator()
+        .simulate(
+            cirq.Circuit(
+                cirq.H(a),
+                cirq.H(b),
+                cirq.CZ(a, b),
+                cirq.measure(a),
+            )
+        )
+        .final_state_vector.reshape((2, 2))
+    )
+    # Here, we do NOT specify the default tolerance. It is merely to check that the default value
+    # is reasonable.
+    cirq.sub_state_vector(final_state_vector, [0])
Repository: quantumlib/Cirq

Issue:
Clifford optimize either should support more general pauli phases or make assert
In the code to merge Clifford operations there is code that only works if a pauli string coefficient is $\pm 1$.  If not it raises a NotImplementError, lines that are not tested :(

My suspicion here is that at this point the phase can only be these two values, but someone will need to better understand this code and the associated TODO.


Discussion:

Resolving patch:
diff --git a/cirq-core/cirq/contrib/paulistring/clifford_optimize.py b/cirq-core/cirq/contrib/paulistring/clifford_optimize.py
--- a/cirq-core/cirq/contrib/paulistring/clifford_optimize.py
+++ b/cirq-core/cirq/contrib/paulistring/clifford_optimize.py
@@ -92,14 +92,6 @@ def try_merge_clifford(cliff_op: ops.GateOperation, start_i: int) -> bool:
 
             qubit, pauli = next(iter(merge_op.pauli_string.items()))
             quarter_turns = round(merge_op.exponent_relative * 2)
-            if merge_op.pauli_string.coefficient not in [1, -1]:
-                # TODO: Add support for more general phases.
-                # Github issue: https://github.com/quantumlib/Cirq/issues/2962
-                # Legacy coverage ignore, we need test code that hits this.
-                # coverage: ignore
-                raise NotImplementedError(
-                    'Only +1/-1 pauli string coefficients currently supported'
-                )
             quarter_turns *= int(merge_op.pauli_string.coefficient.real)
             quarter_turns %= 4
             part_cliff_gate = ops.SingleQubitCliffordGate.from_quarter_turns(pauli, quarter_turns)


Test patch:
Repository: quantumlib/Cirq

Issue:
`TaggedOperation._decompose_` should call `decompose_once` on its sub-operation instead of `decompose`. 
**Description of the issue**
`TaggedOperation`s forward the `_decompose_` request to its underlying `sub_operation`. Right now, it calls `protocols.decompose` directly on the sub-operation -- which breaks `protocols.decompose_once(tagged_op)`. 
**How to reproduce the issue**

```python
>>> import cirq
>>> op = cirq.TaggedOperation(cirq.CircuitOperation(
    circuit=cirq.FrozenCircuit([
        cirq.Moment(
            cirq.SWAP(cirq.LineQubit(0), cirq.LineQubit(1)),
        ),
    ]),
), 'tag')

>>> cirq.decompose_once(op) == cirq.decompose_once(op.untagged) # Should be true. 
False 
```

**Cirq version**
0.14dev



Discussion:

Resolving patch:
diff --git a/cirq-core/cirq/ops/raw_types.py b/cirq-core/cirq/ops/raw_types.py
--- a/cirq-core/cirq/ops/raw_types.py
+++ b/cirq-core/cirq/ops/raw_types.py
@@ -741,7 +741,7 @@ def _json_dict_(self) -> Dict[str, Any]:
         return protocols.obj_to_dict_helper(self, ['sub_operation', 'tags'])
 
     def _decompose_(self) -> 'cirq.OP_TREE':
-        return protocols.decompose(self.sub_operation)
+        return protocols.decompose_once(self.sub_operation, default=None)
 
     def _pauli_expansion_(self) -> value.LinearDict[str]:
         return protocols.pauli_expansion(self.sub_operation)


Test patch:
diff --git a/cirq-core/cirq/protocols/decompose_protocol_test.py b/cirq-core/cirq/protocols/decompose_protocol_test.py
--- a/cirq-core/cirq/protocols/decompose_protocol_test.py
+++ b/cirq-core/cirq/protocols/decompose_protocol_test.py
@@ -304,3 +304,19 @@ def x_to_hzh(op: 'cirq.Operation'):
         cirq.measure(a, b, key='m'),
     )
     assert actual == expected
+
+
+def test_decompose_tagged_operation():
+    op = cirq.TaggedOperation(
+        cirq.CircuitOperation(
+            circuit=cirq.FrozenCircuit(
+                [
+                    cirq.Moment(
+                        cirq.SWAP(cirq.LineQubit(0), cirq.LineQubit(1)),
+                    ),
+                ]
+            ),
+        ),
+        'tag',
+    )
+    assert cirq.decompose_once(op) == cirq.decompose_once(op.untagged)
Repository: quantumlib/Cirq

Issue:
cirq-web doesn't support LineQubit
```python
import cirq
import cirq_web

cirq_circuit = cirq.Circuit(cirq.H(cirq.LineQubit(0)))
cirq_web.Circuit3D(cirq_circuit).generate_html_file(
    file_name="circuit_viewer.html",
    open_in_browser=True,
)
```

results in

```
AttributeError: 'LineQubit' object has no attribute 'row'
```


Discussion:

Resolving patch:
diff --git a/cirq-web/cirq_web/circuits/circuit.py b/cirq-web/cirq_web/circuits/circuit.py
--- a/cirq-web/cirq_web/circuits/circuit.py
+++ b/cirq-web/cirq_web/circuits/circuit.py
@@ -87,5 +87,10 @@ def _build_3D_symbol(self, operation, moment) -> Operation3DSymbol:
         symbol_info = resolve_operation(operation, self._resolvers)
         location_info = []
         for qubit in operation.qubits:
-            location_info.append({'row': qubit.row, 'col': qubit.col})
+            if isinstance(qubit, cirq.GridQubit):
+                location_info.append({'row': qubit.row, 'col': qubit.col})
+            elif isinstance(qubit, cirq.LineQubit):
+                location_info.append({'row': qubit.x, 'col': 0})
+            else:
+                raise ValueError('Unsupported qubit type')
         return Operation3DSymbol(symbol_info.labels, location_info, symbol_info.colors, moment)


Test patch:
diff --git a/cirq-web/cirq_web/circuits/circuit_test.py b/cirq-web/cirq_web/circuits/circuit_test.py
--- a/cirq-web/cirq_web/circuits/circuit_test.py
+++ b/cirq-web/cirq_web/circuits/circuit_test.py
@@ -14,6 +14,8 @@
 import cirq
 import cirq_web
 
+import pytest
+
 
 def strip_ws(string):
     return "".join(string.split())
@@ -28,9 +30,9 @@ def test_circuit_init_type():
     assert isinstance(circuit3d, cirq_web.Circuit3D)
 
 
-def test_circuit_client_code():
-    qubits = [cirq.GridQubit(x, y) for x in range(2) for y in range(2)]
-    moment = cirq.Moment(cirq.H(qubits[0]))
+@pytest.mark.parametrize('qubit', [cirq.GridQubit(0, 0), cirq.LineQubit(0)])
+def test_circuit_client_code(qubit):
+    moment = cirq.Moment(cirq.H(qubit))
     circuit = cirq_web.Circuit3D(cirq.Circuit(moment))
 
     circuit_obj = [
@@ -64,6 +66,14 @@ def test_circuit_client_code():
     assert strip_ws(circuit.get_client_code()) == strip_ws(expected_client_code)
 
 
+def test_circuit_client_code_unsupported_qubit_type():
+    moment = cirq.Moment(cirq.H(cirq.NamedQubit('q0')))
+    circuit = cirq_web.Circuit3D(cirq.Circuit(moment))
+
+    with pytest.raises(ValueError, match='Unsupported qubit type'):
+        circuit.get_client_code()
+
+
 def test_circuit_default_bundle_name():
     qubits = [cirq.GridQubit(x, y) for x in range(2) for y in range(2)]
     moment = cirq.Moment(cirq.H(qubits[0]))
Repository: quantumlib/Cirq

Issue:
ArithmeticOperation examples render with a bunch of xml cruft
**Description of the issue**

The docstring for `ArithmeticOperation` has an `Examples:` section with code in triple backticks: https://github.com/quantumlib/Cirq/blob/master/cirq-core/cirq/ops/arithmetic_operation.py#L43. This renders on the docsite with a bunch of XML cruft: https://quantumai.google/reference/python/cirq/ops/ArithmeticOperation#examples

![arithmetic-operation](https://user-images.githubusercontent.com/129268/162389329-bcdb269a-db3d-4605-a2d1-fd77e1d16e54.png)




Discussion:
xref #5151

Resolving patch:
diff --git a/cirq-core/cirq/ops/arithmetic_operation.py b/cirq-core/cirq/ops/arithmetic_operation.py
--- a/cirq-core/cirq/ops/arithmetic_operation.py
+++ b/cirq-core/cirq/ops/arithmetic_operation.py
@@ -41,7 +41,6 @@ class ArithmeticOperation(Operation, metaclass=abc.ABCMeta):
     boilerplate of implementing the `qubits` and `with_qubits` methods.
 
     Examples:
-    ```
 
         >>> class Add(cirq.ArithmeticOperation):
         ...     def __init__(self, target_register, input_register):
@@ -56,32 +55,33 @@ class ArithmeticOperation(Operation, metaclass=abc.ABCMeta):
         ...
         ...     def apply(self, target_value, input_value):
         ...         return target_value + input_value
+
         >>> cirq.unitary(
-        ...     Add(target_register=cirq.LineQubit.range(2),
-        ...         input_register=1)
+        ...     Add(target_register=cirq.LineQubit.range(2), input_register=1)
         ... ).astype(np.int32)
         array([[0, 0, 0, 1],
                [1, 0, 0, 0],
                [0, 1, 0, 0],
                [0, 0, 1, 0]], dtype=int32)
+
         >>> c = cirq.Circuit(
-        ...    cirq.X(cirq.LineQubit(3)),
-        ...    cirq.X(cirq.LineQubit(2)),
-        ...    cirq.X(cirq.LineQubit(6)),
-        ...    cirq.measure(*cirq.LineQubit.range(4, 8), key='before:in'),
-        ...    cirq.measure(*cirq.LineQubit.range(4), key='before:out'),
+        ...     cirq.X(cirq.LineQubit(3)),
+        ...     cirq.X(cirq.LineQubit(2)),
+        ...     cirq.X(cirq.LineQubit(6)),
+        ...     cirq.measure(*cirq.LineQubit.range(4, 8), key='before:in'),
+        ...     cirq.measure(*cirq.LineQubit.range(4), key='before:out'),
         ...
-        ...    Add(target_register=cirq.LineQubit.range(4),
-        ...        input_register=cirq.LineQubit.range(4, 8)),
+        ...     Add(target_register=cirq.LineQubit.range(4),
+        ...         input_register=cirq.LineQubit.range(4, 8)),
         ...
-        ...    cirq.measure(*cirq.LineQubit.range(4, 8), key='after:in'),
-        ...    cirq.measure(*cirq.LineQubit.range(4), key='after:out'),
+        ...     cirq.measure(*cirq.LineQubit.range(4, 8), key='after:in'),
+        ...     cirq.measure(*cirq.LineQubit.range(4), key='after:out'),
         ... )
+
         >>> cirq.sample(c).data
            before:in  before:out  after:in  after:out
         0          2           3         2          5
 
-    ```
     """
 
     @abc.abstractmethod


Test patch:
Repository: quantumlib/Cirq

Issue:
Gateset: Invalid repr if the gateset is empty
**Description of the issue**
If a `Gateset` doesn't contain any gates, the repr contains an extra comma:
https://github.com/quantumlib/Cirq/blob/e31b48d04c7a3dea6bc2e5e320b0c606bbf13700/cirq-core/cirq/ops/gateset.py#L408-L411

@tanujkhattar Should we fix the repr or make empty Gatesets invalid?

**Cirq version**
0.14



Discussion:
We should fix this. 

Resolving patch:
diff --git a/cirq-core/cirq/ops/gateset.py b/cirq-core/cirq/ops/gateset.py
--- a/cirq-core/cirq/ops/gateset.py
+++ b/cirq-core/cirq/ops/gateset.py
@@ -525,9 +525,10 @@ def _value_equality_values_(self) -> Any:
 
     def __repr__(self) -> str:
         name_str = f'name = "{self.name}", ' if self.name is not None else ''
+        gates_str = f'{self._gates_repr_str}, ' if len(self._gates_repr_str) > 0 else ''
         return (
             f'cirq.Gateset('
-            f'{self._gates_repr_str}, '
+            f'{gates_str}'
             f'{name_str}'
             f'unroll_circuit_op = {self._unroll_circuit_op})'
         )


Test patch:
diff --git a/cirq-core/cirq/ops/gateset_test.py b/cirq-core/cirq/ops/gateset_test.py
--- a/cirq-core/cirq/ops/gateset_test.py
+++ b/cirq-core/cirq/ops/gateset_test.py
@@ -255,11 +255,12 @@ def test_gateset_init():
     )
 
 
-def test_gateset_repr_and_str():
-    cirq.testing.assert_equivalent_repr(gateset)
-    assert gateset.name in str(gateset)
-    for gate_family in gateset.gates:
-        assert str(gate_family) in str(gateset)
+@pytest.mark.parametrize('g', [gateset, cirq.Gateset(name='empty gateset')])
+def test_gateset_repr_and_str(g):
+    cirq.testing.assert_equivalent_repr(g)
+    assert g.name in str(g)
+    for gate_family in g.gates:
+        assert str(gate_family) in str(g)
 
 
 @pytest.mark.parametrize(
Repository: quantumlib/Cirq

Issue:
Automerge bot can't handle empty PR description
**Description of the issue**

If the description of the PR is empty, automerge.py throws this exception:

```
Traceback (most recent call last):
  File "/Users/balintp/dev/proj/Cirq/dev_tools/auto_merge.py", line 953, in main
    duty_cycle(repo, problem_seen_times)
  File "/Users/balintp/dev/proj/Cirq/dev_tools/auto_merge.py", line 918, in duty_cycle
    result = attempt_squash_merge(head_pr)
  File "/Users/balintp/dev/proj/Cirq/dev_tools/auto_merge.py", line 606, in attempt_squash_merge
    raise RuntimeError(
RuntimeError: Merge failed. Code: 422. Content: b'{"message":"Invalid request.\\n\\nFor \'properties/commit_message\', nil is not a string.","documentation_url":"https://docs.github.com/rest/reference/pulls#merge-a-pull-request"}'.
.
```



Discussion:

Resolving patch:
diff --git a/dev_tools/pr_monitor.py b/dev_tools/pr_monitor.py
--- a/dev_tools/pr_monitor.py
+++ b/dev_tools/pr_monitor.py
@@ -772,7 +772,7 @@ def attempt_squash_merge(pr: PullRequestDetails) -> Union[bool, CannotAutomergeE
     )
     data = {
         'commit_title': f'{pr.title} (#{pr.pull_id})',
-        'commit_message': pr.body,
+        'commit_message': pr.body or '',
         'sha': pr.branch_sha,
         'merge_method': 'squash',
     }


Test patch:
Repository: quantumlib/Cirq

Issue:
CircuitOp json parsing inefficient
While looking at #5507 I noticed CircuitOperation uses `with_...` functions to load the data from json, which means unnecessarily reconstructing and revalidating the whole subcircuit for each argument.

https://github.com/quantumlib/Cirq/blob/master/cirq-core/cirq/circuits/circuit_operation.py#L477-L484

Seems like this should instead call the constructor directly with all arguments.


Discussion:

Resolving patch:
diff --git a/cirq-core/cirq/circuits/circuit_operation.py b/cirq-core/cirq/circuits/circuit_operation.py
--- a/cirq-core/cirq/circuits/circuit_operation.py
+++ b/cirq-core/cirq/circuits/circuit_operation.py
@@ -474,13 +474,16 @@ def _from_json_dict_(
         repeat_until=None,
         **kwargs,
     ):
-        return (
-            cls(circuit, use_repetition_ids=use_repetition_ids, repeat_until=repeat_until)
-            .with_qubit_mapping(dict(qubit_map))
-            .with_measurement_key_mapping(measurement_key_map)
-            .with_params(param_resolver)
-            .with_key_path(tuple(parent_path))
-            .repeat(repetitions, repetition_ids)
+        return cls(
+            circuit=circuit,
+            repetitions=repetitions,
+            repetition_ids=repetition_ids,
+            use_repetition_ids=use_repetition_ids,
+            repeat_until=repeat_until,
+            param_resolver=param_resolver,
+            qubit_map=dict(qubit_map),
+            measurement_key_map=measurement_key_map,
+            parent_path=tuple(parent_path),
         )
 
     # Methods for constructing a similar object with one field modified.


Test patch: