From 51a2b6bb32892e650b198ffa02d7ed85d6e44cdd Mon Sep 17 00:00:00 2001 From: Dax Fohl Date: Thu, 7 Apr 2022 10:12:07 -1000 Subject: [PATCH] Remove some 0.15 items from cirq.sim (#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 #3898, as the pattern we used to deprecate `copy` without parameters works well. --- .../cirq/protocols/act_on_protocol_test.py | 6 - cirq-core/cirq/sim/act_on_args.py | 58 ++------- cirq-core/cirq/sim/act_on_args_container.py | 41 +------ .../cirq/sim/act_on_args_container_test.py | 21 ---- cirq-core/cirq/sim/act_on_args_test.py | 22 +--- .../cirq/sim/act_on_density_matrix_args.py | 44 ++----- .../sim/act_on_density_matrix_args_test.py | 11 -- .../cirq/sim/act_on_state_vector_args.py | 9 +- .../cirq/sim/act_on_state_vector_args_test.py | 7 -- .../clifford/act_on_clifford_tableau_args.py | 2 +- .../act_on_stabilizer_ch_form_args.py | 9 +- .../act_on_stabilizer_ch_form_args_test.py | 7 -- .../cirq/sim/density_matrix_simulator.py | 85 ++------------ .../cirq/sim/density_matrix_simulator_test.py | 111 +----------------- cirq-core/cirq/sim/simulator.py | 15 --- cirq-core/cirq/sim/simulator_base.py | 48 ++------ cirq-core/cirq/sim/simulator_base_test.py | 79 ------------- cirq-core/cirq/sim/simulator_test.py | 19 --- cirq-core/cirq/sim/sparse_simulator.py | 31 ++--- cirq-core/cirq/sim/sparse_simulator_test.py | 13 -- .../cirq/sim/state_vector_simulator_test.py | 6 +- .../measurement_transformers_test.py | 18 --- 22 files changed, 70 insertions(+), 592 deletions(-) diff --git a/cirq-core/cirq/protocols/act_on_protocol_test.py b/cirq-core/cirq/protocols/act_on_protocol_test.py index f67b39a25e1..37dd7d392eb 100644 --- a/cirq-core/cirq/protocols/act_on_protocol_test.py +++ b/cirq-core/cirq/protocols/act_on_protocol_test.py @@ -31,9 +31,6 @@ def __init__(self, fallback_result: Any = NotImplemented, measurements=None): def _perform_measurement(self, qubits): return self.measurements # coverage: ignore - def copy(self, deep_copy_buffers: bool = True): - return DummyActOnArgs(self.fallback_result, self.measurements.copy()) # coverage: ignore - def _act_on_fallback_( self, action: Any, @@ -42,9 +39,6 @@ def _act_on_fallback_( ): return self.fallback_result - def sample(self, qubits, repetitions=1, seed=None): - pass - op = cirq.X(cirq.LineQubit(0)) diff --git a/cirq-core/cirq/sim/act_on_args.py b/cirq-core/cirq/sim/act_on_args.py index e305a9741fd..9e64dd69493 100644 --- a/cirq-core/cirq/sim/act_on_args.py +++ b/cirq-core/cirq/sim/act_on_args.py @@ -13,8 +13,6 @@ # limitations under the License. """Objects and methods for acting efficiently on a state tensor.""" import copy -import inspect -import warnings from typing import ( Any, cast, @@ -31,8 +29,8 @@ import numpy as np -from cirq import ops, protocols, value -from cirq._compat import deprecated, deprecated_parameter +from cirq import protocols, value +from cirq._compat import deprecated from cirq.protocols.decompose_protocol import _try_decompose_into_operations_and_qubits from cirq.sim.operation_target import OperationTarget @@ -45,18 +43,11 @@ class ActOnArgs(OperationTarget[TSelf]): """State and context for an operation acting on a state tensor.""" - @deprecated_parameter( - deadline='v0.15', - fix='Use cirq.dephase_measurements to transform the circuit before simulating.', - parameter_desc='ignore_measurement_results', - match=lambda args, kwargs: 'ignore_measurement_results' in kwargs or len(args) > 4, - ) def __init__( self, prng: Optional[np.random.RandomState] = None, qubits: Optional[Sequence['cirq.Qid']] = None, log_of_measurement_results: Optional[Dict[str, List[int]]] = None, - ignore_measurement_results: bool = False, classical_data: Optional['cirq.ClassicalDataStore'] = None, state: Optional['cirq.QuantumStateRepresentation'] = None, ): @@ -70,10 +61,6 @@ def __init__( ordering of the computational basis states. log_of_measurement_results: A mutable object that measurements are being recorded into. - ignore_measurement_results: If True, then the simulation - will treat measurement as dephasing instead of collapsing - process, and not log the result. This is only applicable to - simulators that can represent mixed states. classical_data: The shared classical data container for this simulation. state: The underlying quantum state of the simulation. @@ -90,7 +77,6 @@ def __init__( for k, v in (log_of_measurement_results or {}).items() } ) - self._ignore_measurement_results = ignore_measurement_results self._state = state @property @@ -101,22 +87,6 @@ def prng(self) -> np.random.RandomState: def qubit_map(self) -> Mapping['cirq.Qid', int]: return self._qubit_map - @prng.setter # type: ignore - @deprecated( - deadline="v0.15", - fix="The mutators of this class are deprecated, instantiate a new object instead.", - ) - def prng(self, prng): - self._prng = prng - - @qubit_map.setter # type: ignore - @deprecated( - deadline="v0.15", - fix="The mutators of this class are deprecated, instantiate a new object instead.", - ) - def qubit_map(self, qubit_map): - self._qubit_map = qubit_map - def _set_qubits(self, qubits: Sequence['cirq.Qid']): self._qubits = tuple(qubits) self._qubit_map = {q: i for i, q in enumerate(self.qubits)} @@ -124,9 +94,7 @@ def _set_qubits(self, qubits: Sequence['cirq.Qid']): def measure(self, qubits: Sequence['cirq.Qid'], key: str, invert_mask: Sequence[bool]): """Measures the qubits and records to `log_of_measurement_results`. - Any bitmasks will be applied to the measurement record. If - `self._ignore_measurement_results` is set, it dephases instead of - measuring, and no measurement result will be logged. + Any bitmasks will be applied to the measurement record. Args: qubits: The qubits to measure. @@ -138,9 +106,6 @@ def measure(self, qubits: Sequence['cirq.Qid'], key: str, invert_mask: Sequence[ Raises: ValueError: If a measurement key has already been logged to a key. """ - if self.ignore_measurement_results: - self._act_on_fallback_(ops.phase_damp(1), qubits) - return bits = self._perform_measurement(qubits) corrected = [bit ^ (bit < 2 and mask) for bit, mask in zip(bits, invert_mask)] self._classical_data.record_measurement( @@ -181,18 +146,8 @@ def copy(self: TSelf, deep_copy_buffers: bool = True) -> TSelf: args._classical_data = self._classical_data.copy() if self._state is not None: args._state = self._state.copy(deep_copy_buffers=deep_copy_buffers) - return args - if 'deep_copy_buffers' in inspect.signature(self._on_copy).parameters: - self._on_copy(args, deep_copy_buffers) else: - warnings.warn( - ( - 'A new parameter deep_copy_buffers has been added to ActOnArgs._on_copy(). ' - 'The classes that inherit from ActOnArgs should support it before Cirq 0.15.' - ), - DeprecationWarning, - ) - self._on_copy(args) + self._on_copy(args, deep_copy_buffers) return args 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 def classical_data(self) -> 'cirq.ClassicalDataStoreReader': return self._classical_data - @property + @property # type: ignore + @deprecated(deadline='v0.16', fix='Remove this call, it always returns False.') def ignore_measurement_results(self) -> bool: - return self._ignore_measurement_results + return False @property def qubits(self) -> Tuple['cirq.Qid', ...]: diff --git a/cirq-core/cirq/sim/act_on_args_container.py b/cirq-core/cirq/sim/act_on_args_container.py index 3162de121d2..239479a6511 100644 --- a/cirq-core/cirq/sim/act_on_args_container.py +++ b/cirq-core/cirq/sim/act_on_args_container.py @@ -12,8 +12,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -import inspect -import warnings from collections import abc from typing import ( Any, @@ -31,7 +29,7 @@ import numpy as np from cirq import ops, protocols, value -from cirq._compat import deprecated, deprecated_parameter +from cirq._compat import deprecated_parameter from cirq.sim.operation_target import OperationTarget from cirq.sim.simulator import ( TActOnArgs, @@ -51,7 +49,7 @@ class ActOnArgsContainer( @deprecated_parameter( deadline='v0.15', fix='Use classical_data.', - parameter_desc='log_of_measurement_results and positional arguments', + parameter_desc='log_of_measurement_results', match=lambda args, kwargs: 'log_of_measurement_results' in kwargs or len(args) > 4, ) def __init__( @@ -94,22 +92,6 @@ def args(self) -> Mapping[Optional['cirq.Qid'], TActOnArgs]: def split_untangled_states(self) -> bool: return self._split_untangled_states - @args.setter # type: ignore - @deprecated( - deadline="v0.15", - fix="The mutators of this class are deprecated, instantiate a new object instead.", - ) - def args(self, args): - self._args = args - - @split_untangled_states.setter # type: ignore - @deprecated( - deadline="v0.15", - fix="The mutators of this class are deprecated, instantiate a new object instead.", - ) - def split_untangled_states(self, split_untangled_states): - self._split_untangled_states = split_untangled_states - def create_merged_state(self) -> TActOnArgs: if not self.split_untangled_states: return self.args[None] @@ -169,11 +151,8 @@ def _act_on_fallback_( protocols.act_on(action, op_args, act_on_qubits, allow_decompose=allow_decompose) # Decouple any measurements or resets - if self.split_untangled_states and ( - isinstance(gate_opt, ops.ResetChannel) - or ( - isinstance(gate_opt, ops.MeasurementGate) and not op_args.ignore_measurement_results - ) + if self.split_untangled_states and isinstance( + gate_opt, (ops.ResetChannel, ops.MeasurementGate) ): for q in qubits: if op_args.allows_factoring: @@ -189,17 +168,7 @@ def copy(self, deep_copy_buffers: bool = True) -> 'cirq.ActOnArgsContainer[TActO classical_data = self._classical_data.copy() copies = {} for act_on_args in set(self.args.values()): - if 'deep_copy_buffers' in inspect.signature(act_on_args.copy).parameters: - copies[act_on_args] = act_on_args.copy(deep_copy_buffers) - else: - warnings.warn( - ( - 'A new parameter deep_copy_buffers has been added to ActOnArgs.copy(). The ' - 'classes that inherit from ActOnArgs should support it before Cirq 0.15.' - ), - DeprecationWarning, - ) - copies[act_on_args] = act_on_args.copy() + copies[act_on_args] = act_on_args.copy(deep_copy_buffers) for copy in copies.values(): copy._classical_data = classical_data args = {q: copies[a] for q, a in self.args.items()} diff --git a/cirq-core/cirq/sim/act_on_args_container_test.py b/cirq-core/cirq/sim/act_on_args_container_test.py index c85abaedfa4..e0f004c7a74 100644 --- a/cirq-core/cirq/sim/act_on_args_container_test.py +++ b/cirq-core/cirq/sim/act_on_args_container_test.py @@ -26,13 +26,6 @@ def __init__(self, qubits, classical_data): def _perform_measurement(self, qubits: Sequence[cirq.Qid]) -> List[int]: return [0] * len(qubits) - def copy(self) -> 'EmptyActOnArgs': # type: ignore - """The deep_copy_buffers parameter is omitted to trigger a deprecation warning test.""" - return EmptyActOnArgs( - qubits=self.qubits, - classical_data=self.classical_data.copy(), - ) - def _act_on_fallback_( self, action: Any, @@ -216,12 +209,6 @@ def test_copy_succeeds(): assert copied.qubits == (q0, q1) -def test_copy_deprecation_warning(): - args = create_container(qs2, False) - with cirq.testing.assert_deprecated('deep_copy_buffers', deadline='0.15'): - args.copy(False) - - def test_merge_succeeds(): args = create_container(qs2, False) merged = args.create_merged_state() @@ -273,11 +260,3 @@ def test_field_getters(): args = create_container(qs2) assert args.args.keys() == set(qs2) | {None} assert args.split_untangled_states - - -def test_field_setters_deprecated(): - args = create_container(qs2) - with cirq.testing.assert_deprecated(deadline='v0.15'): - args.args = {} - with cirq.testing.assert_deprecated(deadline='v0.15'): - args.split_untangled_states = False diff --git a/cirq-core/cirq/sim/act_on_args_test.py b/cirq-core/cirq/sim/act_on_args_test.py index 297cdd97e30..a0cab8402e5 100644 --- a/cirq-core/cirq/sim/act_on_args_test.py +++ b/cirq-core/cirq/sim/act_on_args_test.py @@ -24,9 +24,6 @@ class DummyArgs(cirq.ActOnArgs): def __init__(self): super().__init__(qubits=cirq.LineQubit.range(2)) - def sample(self, qubits, repetitions=1, seed=None): - pass - def _perform_measurement(self, qubits): return [5, 3] @@ -38,9 +35,6 @@ def _act_on_fallback_( ) -> bool: return True - def _on_copy(self, args): - return super()._on_copy(args) - def test_measurements(): args = DummyArgs() @@ -95,21 +89,9 @@ def test_transpose_qubits(): args.transpose_to_qubit_order((q0, q1, q1)) -def test_on_copy_has_no_param(): - args = DummyArgs() - with cirq.testing.assert_deprecated('deep_copy_buffers', deadline='0.15'): - args.copy(False) - - def test_field_getters(): args = DummyArgs() assert args.prng is np.random assert args.qubit_map == {q: i for i, q in enumerate(cirq.LineQubit.range(2))} - - -def test_field_setters_deprecated(): - args = DummyArgs() - with cirq.testing.assert_deprecated(deadline='v0.15'): - args.prng = 0 - with cirq.testing.assert_deprecated(deadline='v0.15'): - args.qubit_map = {} + with cirq.testing.assert_deprecated('always returns False', deadline='v0.16'): + assert not args.ignore_measurement_results diff --git a/cirq-core/cirq/sim/act_on_density_matrix_args.py b/cirq-core/cirq/sim/act_on_density_matrix_args.py index 9347c4a31b4..aa509b192cf 100644 --- a/cirq-core/cirq/sim/act_on_density_matrix_args.py +++ b/cirq-core/cirq/sim/act_on_density_matrix_args.py @@ -242,30 +242,24 @@ class ActOnDensityMatrixArgs(ActOnArgs): @_compat.deprecated_parameter( deadline='v0.15', fix='Use classical_data.', - parameter_desc='log_of_measurement_results and positional arguments', + parameter_desc='log_of_measurement_results', match=lambda args, kwargs: 'log_of_measurement_results' in kwargs or len(args) > 5, ) @_compat.deprecated_parameter( deadline='v0.15', - fix='Use cirq.dephase_measurements to transform the circuit before simulating.', - parameter_desc='ignore_measurement_results', - match=lambda args, kwargs: 'ignore_measurement_results' in kwargs or len(args) > 7, - ) - @_compat.deprecated_parameter( - deadline='v0.15', - fix='Use initial_state instead and specify all the arguments with keywords.', - parameter_desc='target_tensor and positional arguments', - match=lambda args, kwargs: 'target_tensor' in kwargs or len(args) != 1, + fix='Use initial_state instead.', + parameter_desc='target_tensor', + match=lambda args, kwargs: 'target_tensor' in kwargs, ) def __init__( self, + *, target_tensor: Optional[np.ndarray] = None, available_buffer: Optional[List[np.ndarray]] = None, qid_shape: Optional[Tuple[int, ...]] = None, prng: Optional[np.random.RandomState] = None, log_of_measurement_results: Optional[Dict[str, List[int]]] = None, qubits: Optional[Sequence['cirq.Qid']] = None, - ignore_measurement_results: bool = False, initial_state: Union[np.ndarray, 'cirq.STATE_VECTOR_LIKE'] = 0, dtype: Type[np.number] = np.complex64, classical_data: Optional['cirq.ClassicalDataStore'] = None, @@ -288,10 +282,6 @@ def __init__( effects. log_of_measurement_results: A mutable object that measurements are being recorded into. - ignore_measurement_results: If True, then the simulation - will treat measurement as dephasing instead of collapsing - process. This is only applicable to simulators that can - model dephasing. initial_state: The initial state for the simulation in the computational basis. dtype: The `numpy.dtype` of the inferred state vector. One of @@ -310,23 +300,13 @@ def __init__( dtype=dtype, buffer=available_buffer, ) - if ignore_measurement_results: - super().__init__( - state=state, - prng=prng, - qubits=qubits, - log_of_measurement_results=log_of_measurement_results, - ignore_measurement_results=ignore_measurement_results, - classical_data=classical_data, - ) - else: - super().__init__( - state=state, - prng=prng, - qubits=qubits, - log_of_measurement_results=log_of_measurement_results, - classical_data=classical_data, - ) + super().__init__( + state=state, + prng=prng, + qubits=qubits, + log_of_measurement_results=log_of_measurement_results, + classical_data=classical_data, + ) self._state: _BufferedDensityMatrix = state def _act_on_fallback_( diff --git a/cirq-core/cirq/sim/act_on_density_matrix_args_test.py b/cirq-core/cirq/sim/act_on_density_matrix_args_test.py index 82fd6dba366..950c58cabff 100644 --- a/cirq-core/cirq/sim/act_on_density_matrix_args_test.py +++ b/cirq-core/cirq/sim/act_on_density_matrix_args_test.py @@ -44,17 +44,6 @@ def test_shallow_copy_buffers(): assert copy.available_buffer is args.available_buffer -def test_positional_argument(): - qid_shape = (2,) - tensor = cirq.to_valid_density_matrix( - 0, len(qid_shape), qid_shape=qid_shape, dtype=np.complex64 - ) - with cirq.testing.assert_deprecated( - 'specify all the arguments with keywords', deadline='v0.15' - ): - cirq.ActOnDensityMatrixArgs(tensor) - - def test_deprecated_warning_and_default_parameter_error(): tensor = np.ndarray(shape=(2,)) with cirq.testing.assert_deprecated('Use initial_state instead', deadline='v0.15'): diff --git a/cirq-core/cirq/sim/act_on_state_vector_args.py b/cirq-core/cirq/sim/act_on_state_vector_args.py index 451e653c98d..30fce0e833d 100644 --- a/cirq-core/cirq/sim/act_on_state_vector_args.py +++ b/cirq-core/cirq/sim/act_on_state_vector_args.py @@ -340,17 +340,18 @@ class ActOnStateVectorArgs(ActOnArgs): @_compat.deprecated_parameter( deadline='v0.15', fix='Use classical_data.', - parameter_desc='log_of_measurement_results and positional arguments', + parameter_desc='log_of_measurement_results', match=lambda args, kwargs: 'log_of_measurement_results' in kwargs or len(args) > 4, ) @_compat.deprecated_parameter( deadline='v0.15', - fix='Use initial_state instead and specify all the arguments with keywords.', - parameter_desc='target_tensor and positional arguments', - match=lambda args, kwargs: 'target_tensor' in kwargs or len(args) != 1, + fix='Use initial_state instead.', + parameter_desc='target_tensor', + match=lambda args, kwargs: 'target_tensor' in kwargs, ) def __init__( self, + *, target_tensor: Optional[np.ndarray] = None, available_buffer: Optional[np.ndarray] = None, prng: Optional[np.random.RandomState] = None, diff --git a/cirq-core/cirq/sim/act_on_state_vector_args_test.py b/cirq-core/cirq/sim/act_on_state_vector_args_test.py index 46078db300e..99292a814f1 100644 --- a/cirq-core/cirq/sim/act_on_state_vector_args_test.py +++ b/cirq-core/cirq/sim/act_on_state_vector_args_test.py @@ -39,13 +39,6 @@ def test_default_parameter(): assert args.available_buffer.dtype == tensor.dtype -def test_positional_argument(): - with cirq.testing.assert_deprecated( - 'specify all the arguments with keywords', deadline='v0.15' - ): - cirq.ActOnStateVectorArgs(np.array([1.0, 0.0, 0.0, 0.0], dtype=np.complex64)) - - def test_deprecated_target_tensor(): with cirq.testing.assert_deprecated('Use initial_state instead', deadline='v0.15'): cirq.ActOnStateVectorArgs(target_tensor=np.array([1.0, 0.0, 0.0, 0.0], dtype=np.complex64)) diff --git a/cirq-core/cirq/sim/clifford/act_on_clifford_tableau_args.py b/cirq-core/cirq/sim/clifford/act_on_clifford_tableau_args.py index 4c20479fea4..7880212a67f 100644 --- a/cirq-core/cirq/sim/clifford/act_on_clifford_tableau_args.py +++ b/cirq-core/cirq/sim/clifford/act_on_clifford_tableau_args.py @@ -32,7 +32,7 @@ class ActOnCliffordTableauArgs(ActOnStabilizerArgs[clifford_tableau.CliffordTabl @deprecated_parameter( deadline='v0.15', fix='Use classical_data.', - parameter_desc='log_of_measurement_results and positional arguments', + parameter_desc='log_of_measurement_results', match=lambda args, kwargs: 'log_of_measurement_results' in kwargs or len(args) > 3, ) def __init__( diff --git a/cirq-core/cirq/sim/clifford/act_on_stabilizer_ch_form_args.py b/cirq-core/cirq/sim/clifford/act_on_stabilizer_ch_form_args.py index 0cbb88c7ff3..ccb9226d694 100644 --- a/cirq-core/cirq/sim/clifford/act_on_stabilizer_ch_form_args.py +++ b/cirq-core/cirq/sim/clifford/act_on_stabilizer_ch_form_args.py @@ -32,17 +32,18 @@ class ActOnStabilizerCHFormArgs( @_compat.deprecated_parameter( deadline='v0.15', fix='Use classical_data.', - parameter_desc='log_of_measurement_results and positional arguments', + parameter_desc='log_of_measurement_results', match=lambda args, kwargs: 'log_of_measurement_results' in kwargs or len(args) > 3, ) @_compat.deprecated_parameter( deadline='v0.15', - fix='Specify all the arguments with keywords, use initial_state instead of state.', - parameter_desc='positional arguments', - match=lambda args, kwargs: len(args) != 1 or 'state' in kwargs, + fix='Use initial_state instead of state.', + parameter_desc='state', + match=lambda args, kwargs: 'state' in kwargs, ) def __init__( self, + *, state: Optional['cirq.StabilizerStateChForm'] = None, prng: Optional[np.random.RandomState] = None, log_of_measurement_results: Optional[Dict[str, List[int]]] = None, diff --git a/cirq-core/cirq/sim/clifford/act_on_stabilizer_ch_form_args_test.py b/cirq-core/cirq/sim/clifford/act_on_stabilizer_ch_form_args_test.py index 7c9629427a3..7cd10005657 100644 --- a/cirq-core/cirq/sim/clifford/act_on_stabilizer_ch_form_args_test.py +++ b/cirq-core/cirq/sim/clifford/act_on_stabilizer_ch_form_args_test.py @@ -28,13 +28,6 @@ def test_init_state(): _ = cirq.ActOnStabilizerCHFormArgs(initial_state=1) -def test_deprecated_warning(): - with cirq.testing.assert_deprecated( - 'Specify all the arguments with keywords', deadline='v0.15' - ): - cirq.ActOnStabilizerCHFormArgs(cirq.StabilizerStateChForm(num_qubits=3)) - - def test_cannot_act(): class NoDetails(cirq.SingleQubitGate): pass diff --git a/cirq-core/cirq/sim/density_matrix_simulator.py b/cirq-core/cirq/sim/density_matrix_simulator.py index 3e78bc27540..498572f9bc8 100644 --- a/cirq-core/cirq/sim/density_matrix_simulator.py +++ b/cirq-core/cirq/sim/density_matrix_simulator.py @@ -17,7 +17,7 @@ import numpy as np from cirq import ops, protocols, study, value -from cirq._compat import deprecated, deprecated_parameter, proper_repr +from cirq._compat import deprecated_parameter, proper_repr from cirq.sim import ( simulator, act_on_density_matrix_args, @@ -117,19 +117,12 @@ class DensityMatrixSimulator( # step_result.density_matrix() """ - @deprecated_parameter( - deadline='v0.15', - fix='Use cirq.dephase_measurements to transform the circuit before simulating.', - parameter_desc='ignore_measurement_results', - match=lambda _, kwargs: 'ignore_measurement_results' in kwargs, - ) def __init__( self, *, dtype: 'DTypeLike' = np.complex64, noise: 'cirq.NOISE_MODEL_LIKE' = None, seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None, - ignore_measurement_results: bool = False, split_untangled_states: bool = True, ): """Density matrix simulator. @@ -139,9 +132,6 @@ def __init__( `numpy.complex64` or `numpy.complex128` noise: A noise model to apply while simulating. seed: The random seed to use for this simulator. - ignore_measurement_results: if True, then the simulation - will treat measurement as dephasing instead of collapsing - process. split_untangled_states: If True, optimizes simulation by running unentangled qubit sets independently and merging those states at the end. @@ -153,36 +143,13 @@ def __init__( Example: >>> (q0,) = cirq.LineQubit.range(1) >>> circuit = cirq.Circuit(cirq.H(q0), cirq.measure(q0)) - - Default case (ignore_measurement_results = False): - >>> simulator = cirq.DensityMatrixSimulator() - >>> result = simulator.run(circuit) - - The measurement result will be strictly one of 0 or 1. - - In the other case: - >>> simulator = cirq.DensityMatrixSimulator( - ... ignore_measurement_results = True) - - Will raise a `ValueError` exception if you call `simulator.run` - when `ignore_measurement_results` has been set to True - (for more see https://github.com/quantumlib/Cirq/issues/2777). """ - if ignore_measurement_results: - super().__init__( - dtype=dtype, - noise=noise, - seed=seed, - ignore_measurement_results=ignore_measurement_results, - split_untangled_states=split_untangled_states, - ) - else: - super().__init__( - dtype=dtype, - noise=noise, - seed=seed, - split_untangled_states=split_untangled_states, - ) + super().__init__( + dtype=dtype, + noise=noise, + seed=seed, + split_untangled_states=split_untangled_states, + ) if dtype not in {np.complex64, np.complex128}: raise ValueError(f'dtype must be complex64 or complex128, was {dtype}') @@ -209,15 +176,6 @@ def _create_partial_act_on_args( if isinstance(initial_state, act_on_density_matrix_args.ActOnDensityMatrixArgs): return initial_state - if self._ignore_measurement_results: - return act_on_density_matrix_args.ActOnDensityMatrixArgs( - qubits=qubits, - prng=self._prng, - classical_data=classical_data, - ignore_measurement_results=self._ignore_measurement_results, - initial_state=initial_state, - dtype=self._dtype, - ) return act_on_density_matrix_args.ActOnDensityMatrixArgs( qubits=qubits, prng=self._prng, @@ -235,7 +193,6 @@ def _create_step_result( ): return DensityMatrixStepResult( sim_state=sim_state, - simulator=self, dtype=self._dtype, ) @@ -294,6 +251,12 @@ class DensityMatrixStepResult( results, ordered by the qubits that the measurement operates on. """ + @deprecated_parameter( + deadline='v0.16', + fix='Remove parameter `simulator` as it is no longer used.', + parameter_desc='simulator', + match=lambda args, kwargs: 'simulator' in kwargs or len(args) > 2, + ) def __init__( self, sim_state: 'cirq.OperationTarget[cirq.ActOnDensityMatrixArgs]', @@ -311,32 +274,10 @@ def __init__( super().__init__(sim_state) self._dtype = dtype self._density_matrix: Optional[np.ndarray] = None - self._simulator = simulator def _simulator_state(self) -> 'cirq.DensityMatrixSimulatorState': return DensityMatrixSimulatorState(self.density_matrix(copy=False), self._qubit_mapping) - # TODO: When removing, also remove `simulator` from the constructor, and the line - # `sim_state = step_result._sim_state` from `SimulatorBase._core_iterator()`. - @deprecated( - deadline="v0.15", fix='Use `initial_state` to prepare a new simulation on the suffix.' - ) - def set_density_matrix(self, density_matrix_repr: Union[int, np.ndarray]): - """Set the density matrix to a new density matrix. - - Args: - density_matrix_repr: If this is an int, the density matrix is set to - the computational basis state corresponding to this state. Otherwise - if this is a np.ndarray it is the full state, either a pure state - or the full density matrix. If it is the pure state it must be the - correct size, be normalized (an L2 norm of 1), and be safely - castable to an appropriate dtype for the simulator. If it is a - mixed state it must be correctly sized and positive semidefinite - with trace one. - """ - if self._simulator: - self._sim_state = self._simulator._create_act_on_args(density_matrix_repr, self._qubits) - def density_matrix(self, copy=True): """Returns the density matrix at this step in the simulation. diff --git a/cirq-core/cirq/sim/density_matrix_simulator_test.py b/cirq-core/cirq/sim/density_matrix_simulator_test.py index da0a6d7c425..5b65d9aa363 100644 --- a/cirq-core/cirq/sim/density_matrix_simulator_test.py +++ b/cirq-core/cirq/sim/density_matrix_simulator_test.py @@ -69,20 +69,6 @@ def test_invalid_dtype(): cirq.DensityMatrixSimulator(dtype=np.int32) -@pytest.mark.parametrize('dtype', [np.complex64, np.complex128]) -@pytest.mark.parametrize('split', [True, False]) -def test_run_with_ignore_measurement_results(dtype: Type[np.number], split: bool): - q0, q1 = cirq.LineQubit.range(2) - with cirq.testing.assert_deprecated('ignore_measurement_results', deadline='v0.15', count=2): - simulator = cirq.DensityMatrixSimulator( - dtype=dtype, ignore_measurement_results=True, split_untangled_states=split - ) - - circuit = cirq.Circuit(cirq.X(q0), cirq.X(q1), cirq.measure(q0)) - with pytest.raises(ValueError, match="ignore_measurement_results = True"): - simulator.run(circuit) - - @pytest.mark.parametrize('dtype', [np.complex64, np.complex128]) @pytest.mark.parametrize('split', [True, False]) def test_run_no_measurements(dtype: Type[np.number], split: bool): @@ -515,35 +501,6 @@ def test_simulate(dtype: Type[np.number], split: bool): assert len(result.measurements) == 0 -@pytest.mark.parametrize('split', [True, False]) -def test_simulate_ignore_measurements(split: bool): - q0 = cirq.LineQubit(0) - with cirq.testing.assert_deprecated( - 'ignore_measurement_results', deadline='v0.15', count=6 if split else 4 - ): - simulator = cirq.DensityMatrixSimulator( - split_untangled_states=split, ignore_measurement_results=True - ) - circuit = cirq.Circuit(cirq.H(q0), cirq.measure(q0)) - result = simulator.simulate(circuit) - np.testing.assert_almost_equal(result.final_density_matrix, np.eye(2) * 0.5) - assert len(result.measurements) == 0 - - -@pytest.mark.parametrize('split', [True, False]) -def test_simulate_ignore_measurements_subcircuits(split: bool): - q0 = cirq.LineQubit(0) - with cirq.testing.assert_deprecated('ignore_measurement_results', deadline='v0.15', count=None): - simulator = cirq.DensityMatrixSimulator( - split_untangled_states=split, ignore_measurement_results=True - ) - circuit = cirq.Circuit(cirq.H(q0), cirq.measure(q0)) - circuit = cirq.Circuit(cirq.CircuitOperation(circuit.freeze())) - result = simulator.simulate(circuit) - np.testing.assert_almost_equal(result.final_density_matrix, np.eye(2) * 0.5) - assert len(result.measurements) == 0 - - @pytest.mark.parametrize('dtype', [np.complex64, np.complex128]) @pytest.mark.parametrize('split', [True, False]) def test_simulate_qudits(dtype: Type[np.number], split: bool): @@ -576,29 +533,6 @@ def test_reset_one_qubit_does_not_affect_partial_trace_of_other_qubits( np.testing.assert_almost_equal(result.final_density_matrix, expected) -def test_ignore_measurements_remains_entangled(): - q0, q1 = cirq.LineQubit.range(2) - with cirq.testing.assert_deprecated('ignore_measurement_results', deadline='v0.15', count=12): - simulator1 = cirq.DensityMatrixSimulator( - ignore_measurement_results=True, split_untangled_states=False - ) - simulator2 = cirq.DensityMatrixSimulator( - ignore_measurement_results=True, split_untangled_states=True - ) - circuit = cirq.Circuit( - cirq.H(q0), - cirq.CX(q0, q1), - cirq.measure(q0), - ) - result1 = simulator1.simulate(circuit) - result2 = simulator2.simulate(circuit) - np.testing.assert_almost_equal(result2.final_density_matrix, result1.final_density_matrix) - expected = np.zeros((4, 4)) - expected[0, 0] = 0.5 - expected[3, 3] = 0.5 - np.testing.assert_almost_equal(result2.final_density_matrix, expected) - - @pytest.mark.parametrize( 'dtype,circuit', itertools.product( @@ -846,20 +780,6 @@ def test_simulate_moment_steps_empty_circuit(dtype: Type[np.number], split: bool ) -@pytest.mark.parametrize('dtype', [np.complex64, np.complex128]) -def test_simulate_moment_steps_set_state_deprecated(dtype: Type[np.number]): - q0, q1 = cirq.LineQubit.range(2) - circuit = cirq.Circuit(cirq.H(q0), cirq.H(q1), cirq.H(q0), cirq.H(q1)) - simulator = cirq.DensityMatrixSimulator(dtype=dtype) - for i, step in enumerate(simulator.simulate_moment_steps(circuit)): - np.testing.assert_almost_equal(step.density_matrix(), np.ones((4, 4)) * 0.25) - if i == 0: - zero_zero = np.zeros((4, 4), dtype=dtype) - zero_zero[0, 0] = 1 - with cirq.testing.assert_deprecated('initial_state', deadline='v0.15'): - step.set_density_matrix(zero_zero) - - @pytest.mark.parametrize('dtype', [np.complex64, np.complex128]) @pytest.mark.parametrize('split', [True, False]) def test_simulate_moment_steps_sample(dtype: Type[np.number], split: bool): @@ -1143,7 +1063,7 @@ def test_density_matrix_trial_result_repr(): initial_state=np.ones((2, 2), dtype=dtype) * 0.5, dtype=dtype, ) - final_step_result = cirq.DensityMatrixStepResult(args, cirq.DensityMatrixSimulator()) + final_step_result = cirq.DensityMatrixStepResult(args) trial_result = cirq.DensityMatrixTrialResult( params=cirq.ParamResolver({'s': 1}), measurements={'m': np.array([[1]], dtype=np.int32)}, @@ -1209,31 +1129,6 @@ def _kraus_(self): np.testing.assert_allclose(s.simulate(c).final_density_matrix, np.diag([0, 1]), atol=1e-8) -def test_works_on_operation_dephased(): - class HAsOp(cirq.Operation): - def __init__(self, q): - self.q = q - - @property - def qubits(self): - return (self.q,) - - def with_qubits(self, *new_qubits): - raise NotImplementedError() - - def _kraus_(self): - return cirq.kraus(cirq.H) - - with cirq.testing.assert_deprecated('ignore_measurement_results', deadline='v0.15', count=6): - s = cirq.DensityMatrixSimulator(ignore_measurement_results=True) - c = cirq.Circuit(HAsOp(cirq.LineQubit(0))) - np.testing.assert_allclose( - s.simulate(c).final_density_matrix, - [[0.5 + 0.0j, 0.5 + 0.0j], [0.5 + 0.0j, 0.5 + 0.0j]], - atol=1e-8, - ) - - def test_works_on_pauli_string_phasor(): a, b = cirq.LineQubit.range(2) c = cirq.Circuit(np.exp(0.5j * np.pi * cirq.X(a) * cirq.X(b))) @@ -1261,7 +1156,7 @@ def test_density_matrix_trial_result_str(): initial_state=np.ones((2, 2), dtype=dtype) * 0.5, dtype=dtype, ) - final_step_result = cirq.DensityMatrixStepResult(args, cirq.DensityMatrixSimulator()) + final_step_result = cirq.DensityMatrixStepResult(args) result = cirq.DensityMatrixTrialResult( params=cirq.ParamResolver({}), measurements={}, final_step_result=final_step_result ) @@ -1287,7 +1182,7 @@ def test_density_matrix_trial_result_repr_pretty(): initial_state=np.ones((2, 2), dtype=dtype) * 0.5, dtype=dtype, ) - final_step_result = cirq.DensityMatrixStepResult(args, cirq.DensityMatrixSimulator()) + final_step_result = cirq.DensityMatrixStepResult(args) final_step_result._simulator_state = cirq.DensityMatrixSimulatorState( density_matrix=np.ones((2, 2)) * 0.5, qubit_map={q0: 0} ) diff --git a/cirq-core/cirq/sim/simulator.py b/cirq-core/cirq/sim/simulator.py index d8870b53126..62c30e6044b 100644 --- a/cirq-core/cirq/sim/simulator.py +++ b/cirq-core/cirq/sim/simulator.py @@ -44,7 +44,6 @@ TypeVar, Union, ) -import warnings import numpy as np @@ -111,20 +110,6 @@ def run_sweep_iter( records = self._run( circuit=program, param_resolver=param_resolver, repetitions=repetitions ) - flat_records = False - for k, v in records.items(): - if v.ndim == 2: - flat_records = True - records[k] = v.reshape((v.shape[0], 1, v.shape[1])) - if flat_records: - warnings.warn( - ( - 'Starting in Cirq v0.15, values in the output of simulator._run must ' - 'be 3D instead of 2D, with a new dimension between the existing two ' - 'to capture "instances" of a key.' - ), - DeprecationWarning, - ) yield study.ResultDict(params=param_resolver, records=records) @abc.abstractmethod diff --git a/cirq-core/cirq/sim/simulator_base.py b/cirq-core/cirq/sim/simulator_base.py index 551d6f5a9fe..7e3ee53a554 100644 --- a/cirq-core/cirq/sim/simulator_base.py +++ b/cirq-core/cirq/sim/simulator_base.py @@ -16,8 +16,6 @@ import abc import collections -import inspect -import warnings from typing import ( Any, cast, @@ -36,7 +34,6 @@ import numpy as np from cirq import ops, protocols, study, value, devices -from cirq._compat import deprecated_parameter from cirq.sim import ActOnArgsContainer from cirq.sim.operation_target import OperationTarget from cirq.sim.simulator import ( @@ -93,19 +90,12 @@ class SimulatorBase( `_core_iterator` and `_run` methods. """ - @deprecated_parameter( - deadline='v0.15', - fix='Use cirq.dephase_measurements to transform the circuit before simulating.', - parameter_desc='ignore_measurement_results', - match=lambda _, kwargs: 'ignore_measurement_results' in kwargs, - ) def __init__( self, *, dtype: Type[np.number] = np.complex64, noise: 'cirq.NOISE_MODEL_LIKE' = None, seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None, - ignore_measurement_results: bool = False, split_untangled_states: bool = False, ): """Initializes the simulator. @@ -114,10 +104,6 @@ def __init__( dtype: The `numpy.dtype` used by the simulation. noise: A noise model to apply while simulating. seed: The random seed to use for this simulator. - ignore_measurement_results: If True, then the simulation - will treat measurement as dephasing instead of collapsing - process. This is only applicable to simulators that can - model dephasing. split_untangled_states: If True, optimizes simulation by running unentangled qubit sets independently and merging those states at the end. @@ -125,7 +111,6 @@ def __init__( self._dtype = dtype self._prng = value.parse_random_state(seed) self.noise = devices.NoiseModel.from_noise_model_like(noise) - self._ignore_measurement_results = ignore_measurement_results self._split_untangled_states = split_untangled_states @abc.abstractmethod @@ -229,9 +214,7 @@ def _core_iterator( except TypeError: raise TypeError(f"{self.__class__.__name__} doesn't support {op!r}") - step_result = self._create_step_result(sim_state) - yield step_result - sim_state = step_result._sim_state + yield self._create_step_result(sim_state) def _run( self, @@ -240,9 +223,6 @@ def _run( repetitions: int, ) -> Dict[str, np.ndarray]: """See definition in `cirq.SimulatesSamples`.""" - if self._ignore_measurement_results: - raise ValueError("run() is not supported when ignore_measurement_results = True") - param_resolver = param_resolver or study.ParamResolver({}) resolved_circuit = protocols.resolve_parameters(circuit, param_resolver) check_all_resolved(resolved_circuit) @@ -277,26 +257,12 @@ def _run( records: Dict['cirq.MeasurementKey', List[np.ndarray]] = {} for i in range(repetitions): - if 'deep_copy_buffers' in inspect.signature(act_on_args.copy).parameters: - all_step_results = self._core_iterator( - general_suffix, - sim_state=act_on_args.copy(deep_copy_buffers=False) - if i < repetitions - 1 - else act_on_args, - ) - else: - warnings.warn( - ( - 'A new parameter deep_copy_buffers has been added to ActOnArgs.copy(). The ' - 'classes that inherit from ActOnArgs should support it before Cirq 0.15.' - ), - DeprecationWarning, - ) - all_step_results = self._core_iterator( - general_suffix, - sim_state=act_on_args.copy() if i < repetitions - 1 else act_on_args, - ) - for step_result in all_step_results: + for step_result in self._core_iterator( + general_suffix, + sim_state=act_on_args.copy(deep_copy_buffers=False) + if i < repetitions - 1 + else act_on_args, + ): pass for k, r in step_result._classical_data.records.items(): if k not in records: diff --git a/cirq-core/cirq/sim/simulator_base_test.py b/cirq-core/cirq/sim/simulator_base_test.py index 6cb865a1ad0..7d42328ac65 100644 --- a/cirq-core/cirq/sim/simulator_base_test.py +++ b/cirq-core/cirq/sim/simulator_base_test.py @@ -246,73 +246,6 @@ def test_run_non_unitary_circuit(): assert np.allclose(r.measurements['0'], [[1], [1]]) -def test_run_no_reuse_buffer_warning(): - # coverage: ignore - class MockCountingActOnArgs(CountingActOnArgs): - def copy(self) -> 'MockCountingActOnArgs': # type: ignore - return super().copy() # type: ignore - - # coverage: ignore - class MockCountingStepResult(cirq.StepResultBase[MockCountingActOnArgs, MockCountingActOnArgs]): - def sample( - self, - qubits: List[cirq.Qid], - repetitions: int = 1, - seed: cirq.RANDOM_STATE_OR_SEED_LIKE = None, - ) -> np.ndarray: - measurements: List[List[int]] = [] - for _ in range(repetitions): - measurements.append(self._merged_sim_state._perform_measurement(qubits)) - return np.array(measurements, dtype=int) - - def _simulator_state(self) -> MockCountingActOnArgs: - return self._merged_sim_state - - class MockCountingTrialResult( - cirq.SimulationTrialResultBase[MockCountingActOnArgs, MockCountingActOnArgs] - ): - pass - - # coverage: ignore - class MockCountingSimulator( - cirq.SimulatorBase[ - MockCountingStepResult, - MockCountingTrialResult, - MockCountingActOnArgs, - MockCountingActOnArgs, - ] - ): - def _create_partial_act_on_args( - self, - initial_state: Any, - qubits: Sequence['cirq.Qid'], - classical_data: cirq.ClassicalDataStore, - ) -> MockCountingActOnArgs: - return MockCountingActOnArgs( - qubits=qubits, state=initial_state, classical_data=classical_data - ) - - def _create_simulator_trial_result( - self, - params: cirq.ParamResolver, - measurements: Dict[str, np.ndarray], - final_step_result: MockCountingStepResult, - ) -> MockCountingTrialResult: - return MockCountingTrialResult( - params, measurements, final_step_result=final_step_result - ) - - def _create_step_result( - self, - sim_state: cirq.OperationTarget[MockCountingActOnArgs], - ) -> MockCountingStepResult: - return MockCountingStepResult(sim_state) - - sim = MockCountingSimulator() - with cirq.testing.assert_deprecated('deep_copy_buffers', deadline='0.15'): - sim.run(cirq.Circuit(cirq.phase_damp(1).on(q0), cirq.measure(q0))) - - def test_run_non_unitary_circuit_non_unitary_state(): class DensityCountingSimulator(CountingSimulator): def _can_be_in_run_prefix(self, val): @@ -422,18 +355,6 @@ def test_sim_state_instance_unchanged_during_normal_sim(split: bool): assert (step._merged_sim_state is not args) == split -@pytest.mark.parametrize('split', [True, False]) -def test_sim_state_instance_gets_changes_from_step_result(split: bool): - sim = SplittableCountingSimulator(split_untangled_states=split) - args = sim._create_act_on_args(0, (q0, q1)) - circuit = cirq.Circuit(cirq.H(q0), cirq.CNOT(q0, q1), cirq.reset(q1)) - for step in sim.simulate_moment_steps(circuit, initial_state=args): - assert step._sim_state is args - args = sim._create_act_on_args(0, (q0, q1)) - step._sim_state = args - assert (step._merged_sim_state is not args) == split - - def test_measurements_retained_in_step_results(): sim = SplittableCountingSimulator() circuit = cirq.Circuit( diff --git a/cirq-core/cirq/sim/simulator_test.py b/cirq-core/cirq/sim/simulator_test.py index c6bb282262e..adeb7f15fe1 100644 --- a/cirq-core/cirq/sim/simulator_test.py +++ b/cirq-core/cirq/sim/simulator_test.py @@ -116,25 +116,6 @@ def test_run_simulator_sweeps(): ) -def test_run_simulator_sweeps_with_deprecated_run(): - expected_measurements = {'a': np.array([[1]])} - simulator = FakeSimulatesSamples(expected_measurements) - circuit = cirq.Circuit(cirq.measure(cirq.LineQubit(0), key='k')) - param_resolvers = [cirq.ParamResolver({}), cirq.ParamResolver({})] - expected_records = {'a': np.array([[[1]]])} - expected_results = [ - cirq.ResultDict(records=expected_records, params=param_resolvers[0]), - cirq.ResultDict(records=expected_records, params=param_resolvers[1]), - ] - with cirq.testing.assert_deprecated( - 'values in the output of simulator._run must be 3D', - deadline='v0.15', - ): - assert expected_results == simulator.run_sweep( - program=circuit, repetitions=10, params=param_resolvers - ) - - @mock.patch.multiple( SimulatesIntermediateStateImpl, __abstractmethods__=set(), simulate_moment_steps=mock.Mock() ) diff --git a/cirq-core/cirq/sim/sparse_simulator.py b/cirq-core/cirq/sim/sparse_simulator.py index 7da4d31bab5..f18379357db 100644 --- a/cirq-core/cirq/sim/sparse_simulator.py +++ b/cirq-core/cirq/sim/sparse_simulator.py @@ -28,7 +28,7 @@ import numpy as np from cirq import ops -from cirq._compat import deprecated +from cirq._compat import deprecated_parameter from cirq.sim import ( simulator, state_vector, @@ -207,7 +207,6 @@ def _create_step_result( ): return SparseSimulatorStep( sim_state=sim_state, - simulator=self, dtype=self._dtype, ) @@ -245,6 +244,12 @@ class SparseSimulatorStep( ): """A `StepResult` that includes `StateVectorMixin` methods.""" + @deprecated_parameter( + deadline='v0.16', + fix='Remove parameter `simulator` as it is no longer used.', + parameter_desc='simulator', + match=lambda args, kwargs: 'simulator' in kwargs or len(args) > 2, + ) def __init__( self, sim_state: 'cirq.OperationTarget[cirq.ActOnStateVectorArgs]', @@ -263,7 +268,6 @@ def __init__( super().__init__(sim_state=sim_state, qubit_map=qubit_map) self._dtype = dtype self._state_vector: Optional[np.ndarray] = None - self._simulator = simulator def _simulator_state(self) -> 'cirq.StateVectorSimulatorState': return state_vector_simulator.StateVectorSimulatorState( @@ -312,27 +316,6 @@ def state_vector(self, copy: bool = True): self._state_vector = np.reshape(vector, size) return self._state_vector.copy() if copy else self._state_vector - # TODO: When removing, also remove `simulator` from the constructor, and the line - # `sim_state = step_result._sim_state` from `SimulatorBase._core_iterator()`. - @deprecated( - deadline="v0.15", fix='Use `initial_state` to prepare a new simulation on the suffix.' - ) - def set_state_vector(self, state: 'cirq.STATE_VECTOR_LIKE'): - """Set the state vector. - - One can pass a valid full state to this method by passing a numpy - array. Or, alternatively, one can pass an integer, and then the state - will be set to lie entirely in the computation basis state for the - binary expansion of the passed integer. - - Args: - state: If an int, the state vector set is the state vector - corresponding to a computational basis state. If a numpy - array this is the full state vector. - """ - if self._simulator: - self._sim_state = self._simulator._create_act_on_args(state, self._qubits) - def __repr__(self) -> str: return ( f'cirq.SparseSimulatorStep(sim_state={self._sim_state!r},' diff --git a/cirq-core/cirq/sim/sparse_simulator_test.py b/cirq-core/cirq/sim/sparse_simulator_test.py index 4ebee4f32eb..59a948930b6 100644 --- a/cirq-core/cirq/sim/sparse_simulator_test.py +++ b/cirq-core/cirq/sim/sparse_simulator_test.py @@ -579,18 +579,6 @@ def test_simulate_moment_steps_empty_circuit(dtype: Type[np.number], split: bool ) -@pytest.mark.parametrize('dtype', [np.complex64, np.complex128]) -def test_simulate_moment_steps_set_state_deprecated(dtype): - q0, q1 = cirq.LineQubit.range(2) - circuit = cirq.Circuit(cirq.H(q0), cirq.H(q1), cirq.H(q0), cirq.H(q1)) - simulator = cirq.Simulator(dtype=dtype) - for i, step in enumerate(simulator.simulate_moment_steps(circuit)): - np.testing.assert_almost_equal(step.state_vector(), np.array([0.5] * 4)) - if i == 0: - with cirq.testing.assert_deprecated('initial_state', deadline='v0.15'): - step.set_state_vector(np.array([1, 0, 0, 0], dtype=dtype)) - - @pytest.mark.parametrize('dtype', [np.complex64, np.complex128]) @pytest.mark.parametrize('split', [True, False]) def test_simulate_moment_steps_sample(dtype: Type[np.number], split: bool): @@ -775,7 +763,6 @@ def test_simulator_step_state_mixin(): result = cirq.SparseSimulatorStep( sim_state=args, dtype=np.complex64, - simulator=None, # type: ignore ) rho = np.array([[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) np.testing.assert_array_almost_equal(rho, result.density_matrix_of(qubits)) diff --git a/cirq-core/cirq/sim/state_vector_simulator_test.py b/cirq-core/cirq/sim/state_vector_simulator_test.py index 789224f975e..e4b8fcf20f2 100644 --- a/cirq-core/cirq/sim/state_vector_simulator_test.py +++ b/cirq-core/cirq/sim/state_vector_simulator_test.py @@ -29,7 +29,7 @@ def test_state_vector_trial_result_repr(): initial_state=np.array([0, 1], dtype=np.complex64), dtype=np.complex64, ) - final_step_result = cirq.SparseSimulatorStep(args, cirq.Simulator()) + final_step_result = cirq.SparseSimulatorStep(args) trial_result = cirq.StateVectorTrialResult( params=cirq.ParamResolver({'s': 1}), measurements={'m': np.array([[1]], dtype=np.int32)}, @@ -179,7 +179,7 @@ def test_str_big(): initial_state=np.array([1] * 2**10, dtype=np.complex64) * 0.03125, dtype=np.complex64, ) - final_step_result = cirq.SparseSimulatorStep(args, cirq.Simulator()) + final_step_result = cirq.SparseSimulatorStep(args) result = cirq.StateVectorTrialResult( cirq.ParamResolver(), {}, @@ -196,7 +196,7 @@ def test_pretty_print(): initial_state=np.array([1], dtype=np.complex64), dtype=np.complex64, ) - final_step_result = cirq.SparseSimulatorStep(args, cirq.Simulator()) + final_step_result = cirq.SparseSimulatorStep(args) result = cirq.StateVectorTrialResult(cirq.ParamResolver(), {}, final_step_result) # Test Jupyter console output from diff --git a/cirq-core/cirq/transformers/measurement_transformers_test.py b/cirq-core/cirq/transformers/measurement_transformers_test.py index 9280cd4bf39..462665278ab 100644 --- a/cirq-core/cirq/transformers/measurement_transformers_test.py +++ b/cirq-core/cirq/transformers/measurement_transformers_test.py @@ -37,23 +37,6 @@ def assert_equivalent_to_deferred(circuit: cirq.Circuit): np.testing.assert_equal(result.measurements, result1.measurements) -def assert_equivalent_to_dephased(circuit: cirq.Circuit): - qubits = list(circuit.all_qubits()) - with cirq.testing.assert_deprecated('ignore_measurement_results', deadline='v0.15', count=None): - sim = cirq.DensityMatrixSimulator(ignore_measurement_results=True) - num_qubits = len(qubits) - backwards = list(circuit.all_operations())[::-1] - for j in range(num_qubits): - backwards.append(cirq.H(qubits[j]) ** np.random.rand()) - modified = cirq.Circuit(backwards[::-1]) - for j in range(num_qubits): - modified.append(cirq.H(qubits[j]) ** np.random.rand()) - dephased = cirq.dephase_measurements(modified) - result = sim.simulate(modified) - result1 = sim.simulate(dephased) - np.testing.assert_almost_equal(result.final_density_matrix, result1.final_density_matrix) - - def test_basic(): q0, q1 = cirq.LineQubit.range(2) circuit = cirq.Circuit( @@ -319,7 +302,6 @@ def test_dephase(): ) ) ) - assert_equivalent_to_dephased(circuit) dephased = cirq.dephase_measurements(circuit) cirq.testing.assert_same_circuits( dephased,