Skip to content

Commit e1862c9

Browse files
daxfohlrht
authored andcommitted
Remove some 0.15 items from cirq.sim (quantumlib#5137)
This covers most of the deprecations for `cirq.sim` in 0.15. The two remaining ones have some challenges: * Removing `target_tensor` etc from the initializers and replacing with `initial_state`: The repr still emits `target_tensor` so it wouldn't round-trip. * Removing `log_of_measurement_results`: Same thing. Plus we forgot to deprecate it in a couple places. Also this closes quantumlib#3898, as the pattern we used to deprecate `copy` without parameters works well.
1 parent a03964a commit e1862c9

22 files changed

+70
-592
lines changed

cirq-core/cirq/protocols/act_on_protocol_test.py

-6
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,6 @@ def __init__(self, fallback_result: Any = NotImplemented, measurements=None):
3131
def _perform_measurement(self, qubits):
3232
return self.measurements # coverage: ignore
3333

34-
def copy(self, deep_copy_buffers: bool = True):
35-
return DummyActOnArgs(self.fallback_result, self.measurements.copy()) # coverage: ignore
36-
3734
def _act_on_fallback_(
3835
self,
3936
action: Any,
@@ -42,9 +39,6 @@ def _act_on_fallback_(
4239
):
4340
return self.fallback_result
4441

45-
def sample(self, qubits, repetitions=1, seed=None):
46-
pass
47-
4842

4943
op = cirq.X(cirq.LineQubit(0))
5044

cirq-core/cirq/sim/act_on_args.py

+7-51
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,6 @@
1313
# limitations under the License.
1414
"""Objects and methods for acting efficiently on a state tensor."""
1515
import copy
16-
import inspect
17-
import warnings
1816
from typing import (
1917
Any,
2018
cast,
@@ -31,8 +29,8 @@
3129

3230
import numpy as np
3331

34-
from cirq import ops, protocols, value
35-
from cirq._compat import deprecated, deprecated_parameter
32+
from cirq import protocols, value
33+
from cirq._compat import deprecated
3634
from cirq.protocols.decompose_protocol import _try_decompose_into_operations_and_qubits
3735
from cirq.sim.operation_target import OperationTarget
3836

@@ -45,18 +43,11 @@
4543
class ActOnArgs(OperationTarget[TSelf]):
4644
"""State and context for an operation acting on a state tensor."""
4745

48-
@deprecated_parameter(
49-
deadline='v0.15',
50-
fix='Use cirq.dephase_measurements to transform the circuit before simulating.',
51-
parameter_desc='ignore_measurement_results',
52-
match=lambda args, kwargs: 'ignore_measurement_results' in kwargs or len(args) > 4,
53-
)
5446
def __init__(
5547
self,
5648
prng: Optional[np.random.RandomState] = None,
5749
qubits: Optional[Sequence['cirq.Qid']] = None,
5850
log_of_measurement_results: Optional[Dict[str, List[int]]] = None,
59-
ignore_measurement_results: bool = False,
6051
classical_data: Optional['cirq.ClassicalDataStore'] = None,
6152
state: Optional['cirq.QuantumStateRepresentation'] = None,
6253
):
@@ -70,10 +61,6 @@ def __init__(
7061
ordering of the computational basis states.
7162
log_of_measurement_results: A mutable object that measurements are
7263
being recorded into.
73-
ignore_measurement_results: If True, then the simulation
74-
will treat measurement as dephasing instead of collapsing
75-
process, and not log the result. This is only applicable to
76-
simulators that can represent mixed states.
7764
classical_data: The shared classical data container for this
7865
simulation.
7966
state: The underlying quantum state of the simulation.
@@ -90,7 +77,6 @@ def __init__(
9077
for k, v in (log_of_measurement_results or {}).items()
9178
}
9279
)
93-
self._ignore_measurement_results = ignore_measurement_results
9480
self._state = state
9581

9682
@property
@@ -101,32 +87,14 @@ def prng(self) -> np.random.RandomState:
10187
def qubit_map(self) -> Mapping['cirq.Qid', int]:
10288
return self._qubit_map
10389

104-
@prng.setter # type: ignore
105-
@deprecated(
106-
deadline="v0.15",
107-
fix="The mutators of this class are deprecated, instantiate a new object instead.",
108-
)
109-
def prng(self, prng):
110-
self._prng = prng
111-
112-
@qubit_map.setter # type: ignore
113-
@deprecated(
114-
deadline="v0.15",
115-
fix="The mutators of this class are deprecated, instantiate a new object instead.",
116-
)
117-
def qubit_map(self, qubit_map):
118-
self._qubit_map = qubit_map
119-
12090
def _set_qubits(self, qubits: Sequence['cirq.Qid']):
12191
self._qubits = tuple(qubits)
12292
self._qubit_map = {q: i for i, q in enumerate(self.qubits)}
12393

12494
def measure(self, qubits: Sequence['cirq.Qid'], key: str, invert_mask: Sequence[bool]):
12595
"""Measures the qubits and records to `log_of_measurement_results`.
12696
127-
Any bitmasks will be applied to the measurement record. If
128-
`self._ignore_measurement_results` is set, it dephases instead of
129-
measuring, and no measurement result will be logged.
97+
Any bitmasks will be applied to the measurement record.
13098
13199
Args:
132100
qubits: The qubits to measure.
@@ -138,9 +106,6 @@ def measure(self, qubits: Sequence['cirq.Qid'], key: str, invert_mask: Sequence[
138106
Raises:
139107
ValueError: If a measurement key has already been logged to a key.
140108
"""
141-
if self.ignore_measurement_results:
142-
self._act_on_fallback_(ops.phase_damp(1), qubits)
143-
return
144109
bits = self._perform_measurement(qubits)
145110
corrected = [bit ^ (bit < 2 and mask) for bit, mask in zip(bits, invert_mask)]
146111
self._classical_data.record_measurement(
@@ -181,18 +146,8 @@ def copy(self: TSelf, deep_copy_buffers: bool = True) -> TSelf:
181146
args._classical_data = self._classical_data.copy()
182147
if self._state is not None:
183148
args._state = self._state.copy(deep_copy_buffers=deep_copy_buffers)
184-
return args
185-
if 'deep_copy_buffers' in inspect.signature(self._on_copy).parameters:
186-
self._on_copy(args, deep_copy_buffers)
187149
else:
188-
warnings.warn(
189-
(
190-
'A new parameter deep_copy_buffers has been added to ActOnArgs._on_copy(). '
191-
'The classes that inherit from ActOnArgs should support it before Cirq 0.15.'
192-
),
193-
DeprecationWarning,
194-
)
195-
self._on_copy(args)
150+
self._on_copy(args, deep_copy_buffers)
196151
return args
197152

198153
def _on_copy(self: TSelf, args: TSelf, deep_copy_buffers: bool = True):
@@ -304,9 +259,10 @@ def _on_transpose_to_qubit_order(self: TSelf, qubits: Sequence['cirq.Qid'], targ
304259
def classical_data(self) -> 'cirq.ClassicalDataStoreReader':
305260
return self._classical_data
306261

307-
@property
262+
@property # type: ignore
263+
@deprecated(deadline='v0.16', fix='Remove this call, it always returns False.')
308264
def ignore_measurement_results(self) -> bool:
309-
return self._ignore_measurement_results
265+
return False
310266

311267
@property
312268
def qubits(self) -> Tuple['cirq.Qid', ...]:

cirq-core/cirq/sim/act_on_args_container.py

+5-36
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,6 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
import inspect
16-
import warnings
1715
from collections import abc
1816
from typing import (
1917
Any,
@@ -31,7 +29,7 @@
3129
import numpy as np
3230

3331
from cirq import ops, protocols, value
34-
from cirq._compat import deprecated, deprecated_parameter
32+
from cirq._compat import deprecated_parameter
3533
from cirq.sim.operation_target import OperationTarget
3634
from cirq.sim.simulator import (
3735
TActOnArgs,
@@ -51,7 +49,7 @@ class ActOnArgsContainer(
5149
@deprecated_parameter(
5250
deadline='v0.15',
5351
fix='Use classical_data.',
54-
parameter_desc='log_of_measurement_results and positional arguments',
52+
parameter_desc='log_of_measurement_results',
5553
match=lambda args, kwargs: 'log_of_measurement_results' in kwargs or len(args) > 4,
5654
)
5755
def __init__(
@@ -94,22 +92,6 @@ def args(self) -> Mapping[Optional['cirq.Qid'], TActOnArgs]:
9492
def split_untangled_states(self) -> bool:
9593
return self._split_untangled_states
9694

97-
@args.setter # type: ignore
98-
@deprecated(
99-
deadline="v0.15",
100-
fix="The mutators of this class are deprecated, instantiate a new object instead.",
101-
)
102-
def args(self, args):
103-
self._args = args
104-
105-
@split_untangled_states.setter # type: ignore
106-
@deprecated(
107-
deadline="v0.15",
108-
fix="The mutators of this class are deprecated, instantiate a new object instead.",
109-
)
110-
def split_untangled_states(self, split_untangled_states):
111-
self._split_untangled_states = split_untangled_states
112-
11395
def create_merged_state(self) -> TActOnArgs:
11496
if not self.split_untangled_states:
11597
return self.args[None]
@@ -169,11 +151,8 @@ def _act_on_fallback_(
169151
protocols.act_on(action, op_args, act_on_qubits, allow_decompose=allow_decompose)
170152

171153
# Decouple any measurements or resets
172-
if self.split_untangled_states and (
173-
isinstance(gate_opt, ops.ResetChannel)
174-
or (
175-
isinstance(gate_opt, ops.MeasurementGate) and not op_args.ignore_measurement_results
176-
)
154+
if self.split_untangled_states and isinstance(
155+
gate_opt, (ops.ResetChannel, ops.MeasurementGate)
177156
):
178157
for q in qubits:
179158
if op_args.allows_factoring:
@@ -189,17 +168,7 @@ def copy(self, deep_copy_buffers: bool = True) -> 'cirq.ActOnArgsContainer[TActO
189168
classical_data = self._classical_data.copy()
190169
copies = {}
191170
for act_on_args in set(self.args.values()):
192-
if 'deep_copy_buffers' in inspect.signature(act_on_args.copy).parameters:
193-
copies[act_on_args] = act_on_args.copy(deep_copy_buffers)
194-
else:
195-
warnings.warn(
196-
(
197-
'A new parameter deep_copy_buffers has been added to ActOnArgs.copy(). The '
198-
'classes that inherit from ActOnArgs should support it before Cirq 0.15.'
199-
),
200-
DeprecationWarning,
201-
)
202-
copies[act_on_args] = act_on_args.copy()
171+
copies[act_on_args] = act_on_args.copy(deep_copy_buffers)
203172
for copy in copies.values():
204173
copy._classical_data = classical_data
205174
args = {q: copies[a] for q, a in self.args.items()}

cirq-core/cirq/sim/act_on_args_container_test.py

-21
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,6 @@ def __init__(self, qubits, classical_data):
2626
def _perform_measurement(self, qubits: Sequence[cirq.Qid]) -> List[int]:
2727
return [0] * len(qubits)
2828

29-
def copy(self) -> 'EmptyActOnArgs': # type: ignore
30-
"""The deep_copy_buffers parameter is omitted to trigger a deprecation warning test."""
31-
return EmptyActOnArgs(
32-
qubits=self.qubits,
33-
classical_data=self.classical_data.copy(),
34-
)
35-
3629
def _act_on_fallback_(
3730
self,
3831
action: Any,
@@ -216,12 +209,6 @@ def test_copy_succeeds():
216209
assert copied.qubits == (q0, q1)
217210

218211

219-
def test_copy_deprecation_warning():
220-
args = create_container(qs2, False)
221-
with cirq.testing.assert_deprecated('deep_copy_buffers', deadline='0.15'):
222-
args.copy(False)
223-
224-
225212
def test_merge_succeeds():
226213
args = create_container(qs2, False)
227214
merged = args.create_merged_state()
@@ -273,11 +260,3 @@ def test_field_getters():
273260
args = create_container(qs2)
274261
assert args.args.keys() == set(qs2) | {None}
275262
assert args.split_untangled_states
276-
277-
278-
def test_field_setters_deprecated():
279-
args = create_container(qs2)
280-
with cirq.testing.assert_deprecated(deadline='v0.15'):
281-
args.args = {}
282-
with cirq.testing.assert_deprecated(deadline='v0.15'):
283-
args.split_untangled_states = False

cirq-core/cirq/sim/act_on_args_test.py

+2-20
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,6 @@ class DummyArgs(cirq.ActOnArgs):
2424
def __init__(self):
2525
super().__init__(qubits=cirq.LineQubit.range(2))
2626

27-
def sample(self, qubits, repetitions=1, seed=None):
28-
pass
29-
3027
def _perform_measurement(self, qubits):
3128
return [5, 3]
3229

@@ -38,9 +35,6 @@ def _act_on_fallback_(
3835
) -> bool:
3936
return True
4037

41-
def _on_copy(self, args):
42-
return super()._on_copy(args)
43-
4438

4539
def test_measurements():
4640
args = DummyArgs()
@@ -95,21 +89,9 @@ def test_transpose_qubits():
9589
args.transpose_to_qubit_order((q0, q1, q1))
9690

9791

98-
def test_on_copy_has_no_param():
99-
args = DummyArgs()
100-
with cirq.testing.assert_deprecated('deep_copy_buffers', deadline='0.15'):
101-
args.copy(False)
102-
103-
10492
def test_field_getters():
10593
args = DummyArgs()
10694
assert args.prng is np.random
10795
assert args.qubit_map == {q: i for i, q in enumerate(cirq.LineQubit.range(2))}
108-
109-
110-
def test_field_setters_deprecated():
111-
args = DummyArgs()
112-
with cirq.testing.assert_deprecated(deadline='v0.15'):
113-
args.prng = 0
114-
with cirq.testing.assert_deprecated(deadline='v0.15'):
115-
args.qubit_map = {}
96+
with cirq.testing.assert_deprecated('always returns False', deadline='v0.16'):
97+
assert not args.ignore_measurement_results

cirq-core/cirq/sim/act_on_density_matrix_args.py

+12-32
Original file line numberDiff line numberDiff line change
@@ -242,30 +242,24 @@ class ActOnDensityMatrixArgs(ActOnArgs):
242242
@_compat.deprecated_parameter(
243243
deadline='v0.15',
244244
fix='Use classical_data.',
245-
parameter_desc='log_of_measurement_results and positional arguments',
245+
parameter_desc='log_of_measurement_results',
246246
match=lambda args, kwargs: 'log_of_measurement_results' in kwargs or len(args) > 5,
247247
)
248248
@_compat.deprecated_parameter(
249249
deadline='v0.15',
250-
fix='Use cirq.dephase_measurements to transform the circuit before simulating.',
251-
parameter_desc='ignore_measurement_results',
252-
match=lambda args, kwargs: 'ignore_measurement_results' in kwargs or len(args) > 7,
253-
)
254-
@_compat.deprecated_parameter(
255-
deadline='v0.15',
256-
fix='Use initial_state instead and specify all the arguments with keywords.',
257-
parameter_desc='target_tensor and positional arguments',
258-
match=lambda args, kwargs: 'target_tensor' in kwargs or len(args) != 1,
250+
fix='Use initial_state instead.',
251+
parameter_desc='target_tensor',
252+
match=lambda args, kwargs: 'target_tensor' in kwargs,
259253
)
260254
def __init__(
261255
self,
256+
*,
262257
target_tensor: Optional[np.ndarray] = None,
263258
available_buffer: Optional[List[np.ndarray]] = None,
264259
qid_shape: Optional[Tuple[int, ...]] = None,
265260
prng: Optional[np.random.RandomState] = None,
266261
log_of_measurement_results: Optional[Dict[str, List[int]]] = None,
267262
qubits: Optional[Sequence['cirq.Qid']] = None,
268-
ignore_measurement_results: bool = False,
269263
initial_state: Union[np.ndarray, 'cirq.STATE_VECTOR_LIKE'] = 0,
270264
dtype: Type[np.number] = np.complex64,
271265
classical_data: Optional['cirq.ClassicalDataStore'] = None,
@@ -288,10 +282,6 @@ def __init__(
288282
effects.
289283
log_of_measurement_results: A mutable object that measurements are
290284
being recorded into.
291-
ignore_measurement_results: If True, then the simulation
292-
will treat measurement as dephasing instead of collapsing
293-
process. This is only applicable to simulators that can
294-
model dephasing.
295285
initial_state: The initial state for the simulation in the
296286
computational basis.
297287
dtype: The `numpy.dtype` of the inferred state vector. One of
@@ -310,23 +300,13 @@ def __init__(
310300
dtype=dtype,
311301
buffer=available_buffer,
312302
)
313-
if ignore_measurement_results:
314-
super().__init__(
315-
state=state,
316-
prng=prng,
317-
qubits=qubits,
318-
log_of_measurement_results=log_of_measurement_results,
319-
ignore_measurement_results=ignore_measurement_results,
320-
classical_data=classical_data,
321-
)
322-
else:
323-
super().__init__(
324-
state=state,
325-
prng=prng,
326-
qubits=qubits,
327-
log_of_measurement_results=log_of_measurement_results,
328-
classical_data=classical_data,
329-
)
303+
super().__init__(
304+
state=state,
305+
prng=prng,
306+
qubits=qubits,
307+
log_of_measurement_results=log_of_measurement_results,
308+
classical_data=classical_data,
309+
)
330310
self._state: _BufferedDensityMatrix = state
331311

332312
def _act_on_fallback_(

0 commit comments

Comments
 (0)