|
14 | 14 | """
|
15 | 15 |
|
16 | 16 | import numpy
|
| 17 | + |
| 18 | +from qiskit import _numpy_compat |
17 | 19 | from qiskit.exceptions import QiskitError
|
18 | 20 | from qiskit.circuit.exceptions import CircuitError
|
19 | 21 | from .parametervector import ParameterVectorElement
|
@@ -116,8 +118,9 @@ def with_gate_array(base_array):
|
116 | 118 | nonwritable = numpy.array(base_array, dtype=numpy.complex128)
|
117 | 119 | nonwritable.setflags(write=False)
|
118 | 120 |
|
119 |
| - def __array__(_self, dtype=None): |
120 |
| - return numpy.asarray(nonwritable, dtype=dtype) |
| 121 | + def __array__(_self, dtype=None, copy=_numpy_compat.COPY_ONLY_IF_NEEDED): |
| 122 | + dtype = nonwritable.dtype if dtype is None else dtype |
| 123 | + return numpy.array(nonwritable, dtype=dtype, copy=copy) |
121 | 124 |
|
122 | 125 | def decorator(cls):
|
123 | 126 | if hasattr(cls, "__array__"):
|
@@ -148,15 +151,21 @@ def matrix_for_control_state(state):
|
148 | 151 | if cached_states is None:
|
149 | 152 | nonwritables = [matrix_for_control_state(state) for state in range(2**num_ctrl_qubits)]
|
150 | 153 |
|
151 |
| - def __array__(self, dtype=None): |
152 |
| - return numpy.asarray(nonwritables[self.ctrl_state], dtype=dtype) |
| 154 | + def __array__(self, dtype=None, copy=_numpy_compat.COPY_ONLY_IF_NEEDED): |
| 155 | + arr = nonwritables[self.ctrl_state] |
| 156 | + dtype = arr.dtype if dtype is None else dtype |
| 157 | + return numpy.array(arr, dtype=dtype, copy=copy) |
153 | 158 |
|
154 | 159 | else:
|
155 | 160 | nonwritables = {state: matrix_for_control_state(state) for state in cached_states}
|
156 | 161 |
|
157 |
| - def __array__(self, dtype=None): |
158 |
| - if (out := nonwritables.get(self.ctrl_state)) is not None: |
159 |
| - return numpy.asarray(out, dtype=dtype) |
| 162 | + def __array__(self, dtype=None, copy=_numpy_compat.COPY_ONLY_IF_NEEDED): |
| 163 | + if (arr := nonwritables.get(self.ctrl_state)) is not None: |
| 164 | + dtype = arr.dtype if dtype is None else dtype |
| 165 | + return numpy.array(arr, dtype=dtype, copy=copy) |
| 166 | + |
| 167 | + if copy is False and copy is not _numpy_compat.COPY_ONLY_IF_NEEDED: |
| 168 | + raise ValueError("could not produce matrix without calculation") |
160 | 169 | return numpy.asarray(
|
161 | 170 | _compute_control_matrix(base, num_ctrl_qubits, self.ctrl_state), dtype=dtype
|
162 | 171 | )
|
|
0 commit comments