Skip to content

Commit

Permalink
Workaround for CircuitInstruction operation mutability.
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinhartman committed Sep 26, 2023
1 parent afecc5d commit 5d9dbad
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
4 changes: 4 additions & 0 deletions crates/accelerate/src/quantum_circuit/circuit_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ pub struct CircuitData {

#[derive(FromPyObject)]
pub struct ElementType {
// Note that _operation_wrapper is used only to support c_if,
// which on the Python-side swaps out the operation that the
// wrapper points to.
#[pyo3(attribute("_operation_wrapper"))]
operation: PyObject,
qubits: Py<PyTuple>,
clbits: Py<PyTuple>,
Expand Down
27 changes: 22 additions & 5 deletions qiskit/circuit/quantumcircuitdata.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@
from .classicalregister import Clbit


class _OperationWrapper:
operation: Operation

def __init__(self, op: Operation):
self.operation = op


class CircuitInstruction:
"""A single instruction in a :class:`.QuantumCircuit`, comprised of the :attr:`operation` and
various operands.
Expand Down Expand Up @@ -58,10 +65,20 @@ class CircuitInstruction:
of distinct items, with no duplicates.
"""

__slots__ = ("operation", "qubits", "clbits")
__slots__ = ("_operation_wrapper", "qubits", "clbits")

_operation_wrapper: _OperationWrapper

@property
def operation(self) -> Operation:
"""The logical operation that this instruction represents an execution of."""
return self._operation_wrapper.operation

@operation.setter
def operation(self, op: Operation):
"""Updates in place the logical operation that this instruction represents an execution of."""
self._operation_wrapper.operation = op

operation: Operation
"""The logical operation that this instruction represents an execution of."""
qubits: Tuple[Qubit, ...]
"""A sequence of the qubits that the operation is applied to."""
clbits: Tuple[Clbit, ...]
Expand All @@ -73,14 +90,14 @@ def __init__(
qubits: Iterable[Qubit] = (),
clbits: Iterable[Clbit] = (),
):
self.operation = operation
self._operation_wrapper = operation if isinstance(operation, _OperationWrapper) else _OperationWrapper(operation)
self.qubits = tuple(qubits)
self.clbits = tuple(clbits)

def copy(self) -> "CircuitInstruction":
"""Return a shallow copy of the :class:`CircuitInstruction`."""
return self.__class__(
operation=self.operation,
operation=self._operation_wrapper,
qubits=self.qubits,
clbits=self.clbits,
)
Expand Down

0 comments on commit 5d9dbad

Please sign in to comment.