From 49b08b9d025399235bf0361ffe2277223e367493 Mon Sep 17 00:00:00 2001 From: Dax Fohl Date: Fri, 8 Jul 2022 11:42:35 -0400 Subject: [PATCH] Remove sim v0.16 deprecations (#5645) Remove all the deprecated classes and functions and clean up other deprecation warnings from `sim` module. --- cirq-core/cirq/__init__.py | 10 - cirq-core/cirq/contrib/quimb/mps_simulator.py | 32 +-- .../cirq/contrib/quimb/mps_simulator_test.py | 10 - .../cirq/protocols/json_test_data/spec.py | 10 - cirq-core/cirq/sim/__init__.py | 15 -- cirq-core/cirq/sim/act_on_args.py | 21 -- cirq-core/cirq/sim/act_on_args_container.py | 21 -- .../cirq/sim/act_on_density_matrix_args.py | 21 -- .../cirq/sim/act_on_state_vector_args.py | 21 -- cirq-core/cirq/sim/clifford/__init__.py | 6 - .../clifford/act_on_clifford_tableau_args.py | 21 -- .../sim/clifford/act_on_stabilizer_args.py | 21 -- .../act_on_stabilizer_ch_form_args.py | 21 -- .../cirq/sim/clifford/clifford_simulator.py | 7 +- .../clifford/stabilizer_simulation_state.py | 31 +-- .../stabilizer_simulation_state_test.py | 7 - .../cirq/sim/density_matrix_simulator.py | 43 +--- .../cirq/sim/density_matrix_simulator_test.py | 53 ----- cirq-core/cirq/sim/operation_target.py | 21 -- .../cirq/sim/simulation_product_state.py | 20 +- .../cirq/sim/simulation_product_state_test.py | 8 - cirq-core/cirq/sim/simulation_state.py | 117 +---------- cirq-core/cirq/sim/simulation_state_test.py | 60 ------ cirq-core/cirq/sim/simulator.py | 188 +----------------- cirq-core/cirq/sim/simulator_base.py | 52 +---- cirq-core/cirq/sim/simulator_base_test.py | 54 ----- cirq-core/cirq/sim/simulator_test.py | 66 ------ cirq-core/cirq/sim/sparse_simulator.py | 9 - .../cirq/sim/state_vector_simulation_state.py | 73 +------ .../sim/state_vector_simulation_state_test.py | 8 - cirq-core/cirq/sim/state_vector_simulator.py | 42 +--- .../cirq/sim/state_vector_simulator_test.py | 8 - cirq-core/cirq/testing/consistent_act_on.py | 2 +- 33 files changed, 36 insertions(+), 1063 deletions(-) delete mode 100644 cirq-core/cirq/sim/act_on_args.py delete mode 100644 cirq-core/cirq/sim/act_on_args_container.py delete mode 100644 cirq-core/cirq/sim/act_on_density_matrix_args.py delete mode 100644 cirq-core/cirq/sim/act_on_state_vector_args.py delete mode 100644 cirq-core/cirq/sim/clifford/act_on_clifford_tableau_args.py delete mode 100644 cirq-core/cirq/sim/clifford/act_on_stabilizer_args.py delete mode 100644 cirq-core/cirq/sim/clifford/act_on_stabilizer_ch_form_args.py delete mode 100644 cirq-core/cirq/sim/operation_target.py diff --git a/cirq-core/cirq/__init__.py b/cirq-core/cirq/__init__.py index 38d84469942..cbb00e5ff00 100644 --- a/cirq-core/cirq/__init__.py +++ b/cirq-core/cirq/__init__.py @@ -443,13 +443,6 @@ ) from cirq.sim import ( - ActOnArgs, - ActOnArgsContainer, - ActOnCliffordTableauArgs, - ActOnDensityMatrixArgs, - ActOnStabilizerCHFormArgs, - ActOnStabilizerArgs, - ActOnStateVectorArgs, CIRCUIT_LIKE, CliffordSimulator, CliffordState, @@ -458,14 +451,12 @@ CliffordTrialResult, DensityMatrixSimulationState, DensityMatrixSimulator, - DensityMatrixSimulatorState, DensityMatrixStepResult, DensityMatrixTrialResult, measure_density_matrix, measure_state_vector, final_density_matrix, final_state_vector, - OperationTarget, sample, sample_density_matrix, sample_state_vector, @@ -490,7 +481,6 @@ StabilizerStateChForm, StateVectorMixin, StateVectorSimulationState, - StateVectorSimulatorState, StateVectorStepResult, StateVectorTrialResult, StepResult, diff --git a/cirq-core/cirq/contrib/quimb/mps_simulator.py b/cirq-core/cirq/contrib/quimb/mps_simulator.py index 6dc3f88a224..cc8bf388d8d 100644 --- a/cirq-core/cirq/contrib/quimb/mps_simulator.py +++ b/cirq-core/cirq/contrib/quimb/mps_simulator.py @@ -25,8 +25,7 @@ import quimb.tensor as qtn from cirq import devices, protocols, qis, value -from cirq._compat import deprecated_parameter -from cirq.sim import simulator, simulator_base +from cirq.sim import simulator_base from cirq.sim.simulation_state import SimulationState if TYPE_CHECKING: @@ -143,7 +142,6 @@ def _create_simulator_trial_result( class MPSTrialResult(simulator_base.SimulationTrialResultBase['MPSState']): """A single trial reult""" - @simulator._deprecated_step_result_parameter(old_position=3) def __init__( self, params: 'cirq.ParamResolver', @@ -563,27 +561,14 @@ def sample( class MPSState(SimulationState[_MPSHandler]): """A state of the MPS simulation.""" - @deprecated_parameter( - deadline='v0.16', - fix='Use kwargs instead of positional args', - parameter_desc='args', - match=lambda args, kwargs: len(args) > 1, - ) - @deprecated_parameter( - deadline='v0.16', - fix='Replace log_of_measurement_results with' - ' classical_data=cirq.ClassicalDataDictionaryStore(_records=logs).', - parameter_desc='log_of_measurement_results', - match=lambda args, kwargs: 'log_of_measurement_results' in kwargs, - ) def __init__( self, + *, qubits: Sequence['cirq.Qid'], prng: np.random.RandomState, simulation_options: MPSOptions = MPSOptions(), grouping: Optional[Dict['cirq.Qid', int]] = None, initial_state: int = 0, - log_of_measurement_results: Dict[str, Any] = None, classical_data: 'cirq.ClassicalDataStore' = None, ): """Creates and MPSState @@ -596,8 +581,6 @@ def __init__( simulation_options: Numerical options for the simulation. grouping: How to group qubits together, if None all are individual. initial_state: An integer representing the initial state. - log_of_measurement_results: A mutable object that measurements are - being recorded into. classical_data: The shared classical data container for this simulation. @@ -614,16 +597,7 @@ def __init__( simulation_options=simulation_options, grouping={qubit_map[k]: v for k, v in final_grouping.items()}, ) - if log_of_measurement_results is not None: - super().__init__( - state=state, - prng=prng, - qubits=qubits, - log_of_measurement_results=log_of_measurement_results, - classical_data=classical_data, - ) - else: - super().__init__(state=state, prng=prng, qubits=qubits, classical_data=classical_data) + super().__init__(state=state, prng=prng, qubits=qubits, classical_data=classical_data) def i_str(self, i: int) -> str: # Returns the index name for the i'th qid. diff --git a/cirq-core/cirq/contrib/quimb/mps_simulator_test.py b/cirq-core/cirq/contrib/quimb/mps_simulator_test.py index 9c520e00d9b..adb3436da02 100644 --- a/cirq-core/cirq/contrib/quimb/mps_simulator_test.py +++ b/cirq-core/cirq/contrib/quimb/mps_simulator_test.py @@ -488,13 +488,3 @@ def test_act_on_gate(): args.state_vector().reshape((2, 2, 2)), cirq.one_hot(index=(0, 1, 0), shape=(2, 2, 2), dtype=np.complex64), ) - - -def test_deprecated(): - prng = np.random.RandomState(0) - with cirq.testing.assert_deprecated('log_of_measurement_results', deadline='0.16', count=2): - _ = ccq.mps_simulator.MPSState( - qubits=cirq.LineQubit.range(3), prng=prng, log_of_measurement_results={} - ) - with cirq.testing.assert_deprecated('positional', deadline='0.16'): - _ = ccq.mps_simulator.MPSState(cirq.LineQubit.range(3), prng=prng) diff --git a/cirq-core/cirq/protocols/json_test_data/spec.py b/cirq-core/cirq/protocols/json_test_data/spec.py index 7e64426b548..443609af2ea 100644 --- a/cirq-core/cirq/protocols/json_test_data/spec.py +++ b/cirq-core/cirq/protocols/json_test_data/spec.py @@ -33,7 +33,6 @@ 'CliffordSimulatorStepResult', 'CliffordTrialResult', 'DensityMatrixSimulator', - 'DensityMatrixSimulatorState', 'DensityMatrixStepResult', 'DensityMatrixTrialResult', 'ExpressionMap', @@ -66,7 +65,6 @@ 'Timestamp', 'TwoQubitGateTabulationResult', 'UnitSweep', - 'StateVectorSimulatorState', 'StateVectorTrialResult', 'ZerosSampler', 'Zip', @@ -76,19 +74,11 @@ 'Heatmap', 'TwoQubitInteractionHeatmap', # Intermediate states with work buffers and unknown external prng guts. - 'ActOnArgs', - 'ActOnArgsContainer', - 'ActOnCliffordTableauArgs', - 'ActOnDensityMatrixArgs', - 'ActOnStabilizerArgs', - 'ActOnStabilizerCHFormArgs', - 'ActOnStateVectorArgs', 'ApplyChannelArgs', 'ApplyMixtureArgs', 'ApplyUnitaryArgs', 'CliffordTableauSimulationState', 'DensityMatrixSimulationState', - 'OperationTarget', 'SimulationProductState', 'SimulationState', 'SimulationStateBase', diff --git a/cirq-core/cirq/sim/__init__.py b/cirq-core/cirq/sim/__init__.py index 116ccb7c237..57fc6f1d8ae 100644 --- a/cirq-core/cirq/sim/__init__.py +++ b/cirq-core/cirq/sim/__init__.py @@ -14,18 +14,7 @@ """Classes for circuit simulators and base implementations of these classes.""" -from cirq.sim.act_on_args import ActOnArgs - -from cirq.sim.act_on_args_container import ActOnArgsContainer - -from cirq.sim.act_on_density_matrix_args import ActOnDensityMatrixArgs - -from cirq.sim.act_on_state_vector_args import ActOnStateVectorArgs - from cirq.sim.clifford import ( - ActOnCliffordTableauArgs, - ActOnStabilizerArgs, - ActOnStabilizerCHFormArgs, CliffordSimulator, CliffordSimulatorStepResult, CliffordState, @@ -41,7 +30,6 @@ from cirq.sim.density_matrix_simulator import ( DensityMatrixSimulator, - DensityMatrixSimulatorState, DensityMatrixStepResult, DensityMatrixTrialResult, ) @@ -56,8 +44,6 @@ sample_sweep, ) -from cirq.sim.operation_target import OperationTarget - from cirq.sim.simulation_product_state import SimulationProductState from cirq.sim.simulation_state import SimulationState @@ -84,7 +70,6 @@ from cirq.sim.state_vector_simulator import ( SimulatesIntermediateStateVector, - StateVectorSimulatorState, StateVectorStepResult, StateVectorTrialResult, ) diff --git a/cirq-core/cirq/sim/act_on_args.py b/cirq-core/cirq/sim/act_on_args.py deleted file mode 100644 index b1f8668bfba..00000000000 --- a/cirq-core/cirq/sim/act_on_args.py +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright 2022 The Cirq Developers -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from cirq import _compat -from cirq.sim.simulation_state import SimulationState - - -@_compat.deprecated_class(deadline='v0.16', fix='Use cirq.SimulationState instead.') -class ActOnArgs(SimulationState): - pass diff --git a/cirq-core/cirq/sim/act_on_args_container.py b/cirq-core/cirq/sim/act_on_args_container.py deleted file mode 100644 index ca5453faca1..00000000000 --- a/cirq-core/cirq/sim/act_on_args_container.py +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright 2022 The Cirq Developers -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from cirq import _compat -from cirq.sim.simulation_product_state import SimulationProductState - - -@_compat.deprecated_class(deadline='v0.16', fix='Use cirq.SimulationProductState instead.') -class ActOnArgsContainer(SimulationProductState): - pass diff --git a/cirq-core/cirq/sim/act_on_density_matrix_args.py b/cirq-core/cirq/sim/act_on_density_matrix_args.py deleted file mode 100644 index b7c840b996d..00000000000 --- a/cirq-core/cirq/sim/act_on_density_matrix_args.py +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright 2022 The Cirq Developers -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from cirq import _compat -from cirq.sim.density_matrix_simulation_state import DensityMatrixSimulationState - - -@_compat.deprecated_class(deadline='v0.16', fix='Use cirq.DensityMatrixSimulationState instead.') -class ActOnDensityMatrixArgs(DensityMatrixSimulationState): - pass diff --git a/cirq-core/cirq/sim/act_on_state_vector_args.py b/cirq-core/cirq/sim/act_on_state_vector_args.py deleted file mode 100644 index 1aaf1c39c81..00000000000 --- a/cirq-core/cirq/sim/act_on_state_vector_args.py +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright 2022 The Cirq Developers -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from cirq import _compat -from cirq.sim.state_vector_simulation_state import StateVectorSimulationState - - -@_compat.deprecated_class(deadline='v0.16', fix='Use cirq.StateVectorSimulationState instead.') -class ActOnStateVectorArgs(StateVectorSimulationState): - pass diff --git a/cirq-core/cirq/sim/clifford/__init__.py b/cirq-core/cirq/sim/clifford/__init__.py index 1de27e171e6..2f7a0a5a46e 100644 --- a/cirq-core/cirq/sim/clifford/__init__.py +++ b/cirq-core/cirq/sim/clifford/__init__.py @@ -1,11 +1,5 @@ # pylint: disable=wrong-or-nonexistent-copyright-notice -from cirq.sim.clifford.act_on_clifford_tableau_args import ActOnCliffordTableauArgs - -from cirq.sim.clifford.act_on_stabilizer_args import ActOnStabilizerArgs - -from cirq.sim.clifford.act_on_stabilizer_ch_form_args import ActOnStabilizerCHFormArgs - from cirq.sim.clifford.clifford_simulator import ( CliffordSimulator, CliffordSimulatorStepResult, 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 deleted file mode 100644 index 4c0c9ea60ae..00000000000 --- a/cirq-core/cirq/sim/clifford/act_on_clifford_tableau_args.py +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright 2022 The Cirq Developers -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from cirq import _compat -from cirq.sim.clifford.clifford_tableau_simulation_state import CliffordTableauSimulationState - - -@_compat.deprecated_class(deadline='v0.16', fix='Use cirq.CliffordTableauSimulationState instead.') -class ActOnCliffordTableauArgs(CliffordTableauSimulationState): - pass diff --git a/cirq-core/cirq/sim/clifford/act_on_stabilizer_args.py b/cirq-core/cirq/sim/clifford/act_on_stabilizer_args.py deleted file mode 100644 index 63758b5a982..00000000000 --- a/cirq-core/cirq/sim/clifford/act_on_stabilizer_args.py +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright 2022 The Cirq Developers -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from cirq import _compat -from cirq.sim.clifford.stabilizer_simulation_state import StabilizerSimulationState - - -@_compat.deprecated_class(deadline='v0.16', fix='Use cirq.StabilizerSimulationState instead.') -class ActOnStabilizerArgs(StabilizerSimulationState): - pass 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 deleted file mode 100644 index b04b18083ec..00000000000 --- a/cirq-core/cirq/sim/clifford/act_on_stabilizer_ch_form_args.py +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright 2022 The Cirq Developers -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from cirq import _compat -from cirq.sim.clifford.stabilizer_ch_form_simulation_state import StabilizerChFormSimulationState - - -@_compat.deprecated_class(deadline='v0.16', fix='Use cirq.StabilizerChFormSimulationState instead.') -class ActOnStabilizerCHFormArgs(StabilizerChFormSimulationState): - pass diff --git a/cirq-core/cirq/sim/clifford/clifford_simulator.py b/cirq-core/cirq/sim/clifford/clifford_simulator.py index c7432da9662..fd89aa3c7d0 100644 --- a/cirq-core/cirq/sim/clifford/clifford_simulator.py +++ b/cirq-core/cirq/sim/clifford/clifford_simulator.py @@ -36,7 +36,7 @@ import cirq from cirq import protocols, value from cirq.protocols import act_on -from cirq.sim import clifford, simulator, simulator_base +from cirq.sim import clifford, simulator_base class CliffordSimulator( @@ -73,7 +73,7 @@ def _create_partial_simulation_state( qubits: Sequence['cirq.Qid'], classical_data: 'cirq.ClassicalDataStore', ) -> 'cirq.StabilizerChFormSimulationState': - """Creates the ActOnStabilizerChFormArgs for a circuit. + """Creates the StabilizerChFormSimulationState for a circuit. Args: initial_state: The initial state for the simulation in the @@ -86,7 +86,7 @@ def _create_partial_simulation_state( simulation. Returns: - ActOnStabilizerChFormArgs for the circuit. + StabilizerChFormSimulationState for the circuit. """ if isinstance(initial_state, clifford.StabilizerChFormSimulationState): return initial_state @@ -118,7 +118,6 @@ def _create_simulator_trial_result( class CliffordTrialResult( simulator_base.SimulationTrialResultBase['clifford.StabilizerChFormSimulationState'] ): - @simulator._deprecated_step_result_parameter(old_position=3) def __init__( self, params: 'cirq.ParamResolver', diff --git a/cirq-core/cirq/sim/clifford/stabilizer_simulation_state.py b/cirq-core/cirq/sim/clifford/stabilizer_simulation_state.py index b483c66c797..b8280d3c3bb 100644 --- a/cirq-core/cirq/sim/clifford/stabilizer_simulation_state.py +++ b/cirq-core/cirq/sim/clifford/stabilizer_simulation_state.py @@ -13,13 +13,12 @@ # limitations under the License. import abc -from typing import Any, cast, Dict, Generic, List, Optional, Sequence, TYPE_CHECKING, TypeVar, Union +from typing import Any, cast, Generic, Optional, Sequence, TYPE_CHECKING, TypeVar, Union import numpy as np import sympy from cirq import linalg, ops, protocols -from cirq._compat import deprecated_parameter from cirq.ops import common_gates, global_phase_op, matrix_gates, swap_gates from cirq.ops.clifford_gate import SingleQubitCliffordGate from cirq.protocols import has_unitary, num_qubits, unitary @@ -38,24 +37,11 @@ class StabilizerSimulationState( ): """Abstract wrapper around a stabilizer state for the act_on protocol.""" - @deprecated_parameter( - deadline='v0.16', - fix='Use kwargs instead of positional args', - parameter_desc='args', - match=lambda args, kwargs: len(args) > 1, - ) - @deprecated_parameter( - deadline='v0.16', - fix='Replace log_of_measurement_results with' - ' classical_data=cirq.ClassicalDataDictionaryStore(_records=logs).', - parameter_desc='log_of_measurement_results', - match=lambda args, kwargs: 'log_of_measurement_results' in kwargs, - ) def __init__( self, + *, state: TStabilizerState, prng: Optional[np.random.RandomState] = None, - log_of_measurement_results: Optional[Dict[str, List[int]]] = None, qubits: Optional[Sequence['cirq.Qid']] = None, classical_data: Optional['cirq.ClassicalDataStore'] = None, ): @@ -69,21 +55,10 @@ def __init__( qubits: Determines the canonical ordering of the qubits. This is often used in specifying the initial state, i.e. the ordering of the computational basis states. - log_of_measurement_results: A mutable object that measurements are - being recorded into. classical_data: The shared classical data container for this simulation. """ - if log_of_measurement_results is not None: - super().__init__( - state=state, - prng=prng, - qubits=qubits, - log_of_measurement_results=log_of_measurement_results, - classical_data=classical_data, - ) - else: - super().__init__(state=state, prng=prng, qubits=qubits, classical_data=classical_data) + super().__init__(state=state, prng=prng, qubits=qubits, classical_data=classical_data) @property def state(self) -> TStabilizerState: diff --git a/cirq-core/cirq/sim/clifford/stabilizer_simulation_state_test.py b/cirq-core/cirq/sim/clifford/stabilizer_simulation_state_test.py index 2cf4a6afc80..3098a5ffce5 100644 --- a/cirq-core/cirq/sim/clifford/stabilizer_simulation_state_test.py +++ b/cirq-core/cirq/sim/clifford/stabilizer_simulation_state_test.py @@ -126,10 +126,3 @@ def _qid_shape_(self): args = cirq.StabilizerSimulationState(state=state, qubits=[q0]) assert args._strat_decompose(XContainer(), [q0]) is True state.apply_x.assert_called_with(0, 1.0, 0.0) - - -def test_deprecated(): - with cirq.testing.assert_deprecated('log_of_measurement_results', deadline='v0.16', count=2): - _ = cirq.StabilizerSimulationState(state=0, log_of_measurement_results={}) - with cirq.testing.assert_deprecated('positional', deadline='v0.16'): - _ = cirq.StabilizerSimulationState(0) diff --git a/cirq-core/cirq/sim/density_matrix_simulator.py b/cirq-core/cirq/sim/density_matrix_simulator.py index a50fdd85ff7..6222276fa4e 100644 --- a/cirq-core/cirq/sim/density_matrix_simulator.py +++ b/cirq-core/cirq/sim/density_matrix_simulator.py @@ -12,12 +12,12 @@ # See the License for the specific language governing permissions and # limitations under the License. """Simulator for density matrices that simulates noisy quantum circuits.""" -from typing import Any, Dict, List, Optional, Sequence, Type, TYPE_CHECKING, Tuple, Union +from typing import Any, Dict, List, Optional, Sequence, Type, TYPE_CHECKING, Union import numpy as np from cirq import ops, protocols, study, value -from cirq._compat import deprecated_class, deprecated_parameter, proper_repr +from cirq._compat import proper_repr from cirq.sim import simulator, density_matrix_simulation_state, simulator_base if TYPE_CHECKING: @@ -239,23 +239,15 @@ class DensityMatrixStepResult(simulator_base.StepResultBase['cirq.DensityMatrixS 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.SimulationStateBase[cirq.DensityMatrixSimulationState]', - simulator: 'cirq.DensityMatrixSimulator' = None, dtype: Type[np.complexfloating] = np.complex64, ): """DensityMatrixStepResult. Args: sim_state: The qubit:SimulationState lookup for this step. - simulator: The simulator used to create this. dtype: The `numpy.dtype` used by the simulation. One of `numpy.complex64` or `numpy.complex128`. """ @@ -315,36 +307,6 @@ def __repr__(self) -> str: ) -@deprecated_class(deadline='v0.16', fix='This class is no longer used.') -@value.value_equality(unhashable=True) -class DensityMatrixSimulatorState: - """The simulator state for DensityMatrixSimulator - - Args: - density_matrix: The density matrix of the simulation. - qubit_map: A map from qid to index used to define the - ordering of the basis in density_matrix. - """ - - def __init__(self, density_matrix: np.ndarray, qubit_map: Dict['cirq.Qid', int]) -> None: - self.density_matrix = density_matrix - self.qubit_map = qubit_map - self._qid_shape = simulator._qubit_map_to_shape(qubit_map) - - def _qid_shape_(self) -> Tuple[int, ...]: - return self._qid_shape - - def _value_equality_values_(self) -> Any: - return self.density_matrix.tolist(), self.qubit_map - - def __repr__(self) -> str: - return ( - 'cirq.DensityMatrixSimulatorState(' - f'density_matrix=np.array({self.density_matrix.tolist()!r}), ' - f'qubit_map={self.qubit_map!r})' - ) - - @value.value_equality(unhashable=True) class DensityMatrixTrialResult( simulator_base.SimulationTrialResultBase[ @@ -388,7 +350,6 @@ class DensityMatrixTrialResult( trial finishes. """ - @simulator._deprecated_step_result_parameter(old_position=3) def __init__( self, params: 'cirq.ParamResolver', diff --git a/cirq-core/cirq/sim/density_matrix_simulator_test.py b/cirq-core/cirq/sim/density_matrix_simulator_test.py index 38c13c48cee..c101318289a 100644 --- a/cirq-core/cirq/sim/density_matrix_simulator_test.py +++ b/cirq-core/cirq/sim/density_matrix_simulator_test.py @@ -940,59 +940,6 @@ def test_simulate_expectation_values_qubit_order(dtype): assert cirq.approx_eq(result_flipped[0], 3, atol=1e-6) -def test_density_matrix_simulator_state_eq_deprecated(): - with cirq.testing.assert_deprecated('no longer used', deadline='v0.16', count=4): - q0, q1 = cirq.LineQubit.range(2) - eq = cirq.testing.EqualsTester() - eq.add_equality_group( - cirq.DensityMatrixSimulatorState( - density_matrix=np.ones((2, 2)) * 0.5, qubit_map={q0: 0} - ), - cirq.DensityMatrixSimulatorState( - density_matrix=np.ones((2, 2)) * 0.5, qubit_map={q0: 0} - ), - ) - eq.add_equality_group( - cirq.DensityMatrixSimulatorState(density_matrix=np.eye(2) * 0.5, qubit_map={q0: 0}) - ) - eq.add_equality_group( - cirq.DensityMatrixSimulatorState( - density_matrix=np.eye(2) * 0.5, qubit_map={q0: 0, q1: 1} - ) - ) - - -def test_density_matrix_simulator_state_qid_shape(): - with cirq.testing.assert_deprecated('no longer used', deadline='v0.16', count=2): - q0, q1 = cirq.LineQubit.range(2) - assert cirq.qid_shape( - cirq.DensityMatrixSimulatorState( - density_matrix=np.ones((4, 4)) / 4, qubit_map={q0: 0, q1: 1} - ) - ) == (2, 2) - q0, q1 = cirq.LineQid.for_qid_shape((3, 4)) - assert cirq.qid_shape( - cirq.DensityMatrixSimulatorState( - density_matrix=np.ones((12, 12)) / 12, qubit_map={q0: 0, q1: 1} - ) - ) == (3, 4) - - -def test_density_matrix_simulator_state_repr(): - with cirq.testing.assert_deprecated('no longer used', deadline='v0.16'): - q0 = cirq.LineQubit(0) - assert ( - repr( - cirq.DensityMatrixSimulatorState( - density_matrix=np.ones((2, 2)) * 0.5, qubit_map={q0: 0} - ) - ) - == "cirq.DensityMatrixSimulatorState(density_matrix=" - "np.array([[0.5, 0.5], [0.5, 0.5]]), " - "qubit_map={cirq.LineQubit(0): 0})" - ) - - def test_density_matrix_step_result_repr(): q0 = cirq.LineQubit(0) assert ( diff --git a/cirq-core/cirq/sim/operation_target.py b/cirq-core/cirq/sim/operation_target.py deleted file mode 100644 index 80448fffea1..00000000000 --- a/cirq-core/cirq/sim/operation_target.py +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright 2022 The Cirq Developers -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from cirq import _compat -from cirq.sim.simulation_state_base import SimulationStateBase - - -@_compat.deprecated_class(deadline='v0.16', fix='Use cirq.SimulationStateBase instead.') -class OperationTarget(SimulationStateBase): - pass diff --git a/cirq-core/cirq/sim/simulation_product_state.py b/cirq-core/cirq/sim/simulation_product_state.py index 0e2c8e1f5ec..1338d7ebf7a 100644 --- a/cirq-core/cirq/sim/simulation_product_state.py +++ b/cirq-core/cirq/sim/simulation_product_state.py @@ -17,7 +17,7 @@ import numpy as np -from cirq import _compat, ops, protocols, value +from cirq import ops, protocols, value from cirq.sim.simulation_state import TSimulationState from cirq.sim.simulation_state_base import SimulationStateBase @@ -25,24 +25,11 @@ import cirq -def _fix_deprecated_args(args, kwargs): - kwargs['sim_states'] = kwargs['args'] - del kwargs['args'] - return args, kwargs - - class SimulationProductState( Generic[TSimulationState], SimulationStateBase[TSimulationState], abc.Mapping ): """A container for a `Qid`-to-`SimulationState` dictionary.""" - @_compat.deprecated_parameter( - deadline='v0.16', - fix='Change argument name to `sim_states`', - parameter_desc='args', - match=lambda args, kwargs: 'args' in kwargs, - rewrite=_fix_deprecated_args, - ) def __init__( self, sim_states: Dict[Optional['cirq.Qid'], TSimulationState], @@ -71,11 +58,6 @@ def __init__( def sim_states(self) -> Mapping[Optional['cirq.Qid'], TSimulationState]: return self._sim_states - @property # type: ignore - @_compat.deprecated(deadline='v0.16', fix='Use `sim_states` instead.') - def args(self) -> Mapping[Optional['cirq.Qid'], TSimulationState]: - return self._sim_states - @property def split_untangled_states(self) -> bool: return self._split_untangled_states diff --git a/cirq-core/cirq/sim/simulation_product_state_test.py b/cirq-core/cirq/sim/simulation_product_state_test.py index 7108f875058..d992177b53c 100644 --- a/cirq-core/cirq/sim/simulation_product_state_test.py +++ b/cirq-core/cirq/sim/simulation_product_state_test.py @@ -269,11 +269,3 @@ def test_field_getters(): state = create_container(qs2) assert state.sim_states.keys() == set(qs2) | {None} assert state.split_untangled_states - - -def test_deprecated_args(): - state = create_container(qs2) - with cirq.testing.assert_deprecated(deadline='v0.16'): - _ = state.args - with cirq.testing.assert_deprecated(deadline='v0.16'): - _ = cirq.SimulationProductState(args={}, qubits=[], split_untangled_states=False) diff --git a/cirq-core/cirq/sim/simulation_state.py b/cirq-core/cirq/sim/simulation_state.py index b7fcf884c00..911082d4927 100644 --- a/cirq-core/cirq/sim/simulation_state.py +++ b/cirq-core/cirq/sim/simulation_state.py @@ -31,7 +31,6 @@ import numpy as np from cirq import protocols, value -from cirq._compat import _warn_or_error, deprecated, deprecated_parameter from cirq.protocols.decompose_protocol import _try_decompose_into_operations_and_qubits from cirq.sim.simulation_state_base import SimulationStateBase @@ -45,26 +44,13 @@ class SimulationState(SimulationStateBase, Generic[TState], metaclass=abc.ABCMeta): """State and context for an operation acting on a state tensor.""" - @deprecated_parameter( - deadline='v0.16', - fix='Use kwargs instead of positional args', - parameter_desc='args', - match=lambda args, kwargs: len(args) > 1, - ) - @deprecated_parameter( - deadline='v0.16', - fix='Replace log_of_measurement_results with' - ' classical_data=cirq.ClassicalDataDictionaryStore(_records=logs).', - parameter_desc='log_of_measurement_results', - match=lambda args, kwargs: 'log_of_measurement_results' in kwargs, - ) def __init__( self, + *, + state: TState, prng: Optional[np.random.RandomState] = None, qubits: Optional[Sequence['cirq.Qid']] = None, - log_of_measurement_results: Optional[Dict[str, List[int]]] = None, classical_data: Optional['cirq.ClassicalDataStore'] = None, - state: Optional[TState] = None, ): """Inits SimulationState. @@ -74,27 +60,18 @@ def __init__( qubits: Determines the canonical ordering of the qubits. This is often used in specifying the initial state, i.e. the ordering of the computational basis states. - log_of_measurement_results: A mutable object that measurements are - being recorded into. classical_data: The shared classical data container for this simulation. state: The underlying quantum state of the simulation. """ if qubits is None: qubits = () - classical_data = classical_data or value.ClassicalDataDictionaryStore( - _records={ - value.MeasurementKey.parse_serialized(k): [tuple(v)] - for k, v in (log_of_measurement_results or {}).items() - } - ) + classical_data = classical_data or value.ClassicalDataDictionaryStore() super().__init__(qubits=qubits, classical_data=classical_data) if prng is None: prng = cast(np.random.RandomState, np.random) self._prng = prng - self._state = cast(TState, state) - if state is None: - _warn_or_error('This function will require a valid `state` input in cirq v0.16.') + self._state = state @property def prng(self) -> np.random.RandomState: @@ -183,24 +160,9 @@ def copy(self: TSelf, deep_copy_buffers: bool = True) -> TSelf: """ args = copy.copy(self) args._classical_data = self._classical_data.copy() - if self._state is not None: - args._state = self._state.copy(deep_copy_buffers=deep_copy_buffers) - else: - _warn_or_error( - 'Pass a `QuantumStateRepresentation` into the `SimulationState` constructor.' - ' The `_on_` overrides will be removed in cirq v0.16.' - ) - self._on_copy(args, deep_copy_buffers) + args._state = self._state.copy(deep_copy_buffers=deep_copy_buffers) return args - @deprecated( - deadline='v0.16', - fix='Pass a `QuantumStateRepresentation` into the `SimulationState` constructor.', - ) - def _on_copy(self: TSelf, args: TSelf, deep_copy_buffers: bool = True): - """Subclasses should implement this with any additional state copy - functionality.""" - def create_merged_state(self: TSelf) -> TSelf: """Creates a final merged state.""" return self @@ -208,25 +170,10 @@ def create_merged_state(self: TSelf) -> TSelf: def kronecker_product(self: TSelf, other: TSelf, *, inplace=False) -> TSelf: """Joins two state spaces together.""" args = self if inplace else copy.copy(self) - if self._state is not None and other._state is not None: - args._state = self._state.kron(other._state) - else: - _warn_or_error( - 'Pass a `QuantumStateRepresentation` into the `SimulationState` constructor.' - ' The `_on_` overrides will be removed in cirq v0.16.' - ) - self._on_kronecker_product(other, args) + args._state = self._state.kron(other._state) args._set_qubits(self.qubits + other.qubits) return args - @deprecated( - deadline='v0.16', - fix='Pass a `QuantumStateRepresentation` into the `SimulationState` constructor.', - ) - def _on_kronecker_product(self: TSelf, other: TSelf, target: TSelf): - """Subclasses should implement this with any additional state product - functionality, if supported.""" - def with_qubits(self: TSelf, qubits) -> TSelf: """Extend current state space with added qubits. @@ -240,7 +187,7 @@ def with_qubits(self: TSelf, qubits) -> TSelf: Regurns: A new subclass object containing the extended state space. """ - new_space = type(self)(qubits=qubits) + new_space = type(self)(qubits=qubits) # type: ignore return self.kronecker_product(new_space) def factor( @@ -249,16 +196,9 @@ def factor( """Splits two state spaces after a measurement or reset.""" extracted = copy.copy(self) remainder = self if inplace else copy.copy(self) - if self._state is not None: - e, r = self._state.factor(self.get_axes(qubits), validate=validate, atol=atol) - extracted._state = e - remainder._state = r - else: - _warn_or_error( - 'Pass a `QuantumStateRepresentation` into the `SimulationState` constructor.' - ' The `_on_` overrides will be removed in cirq v0.16.' - ) - self._on_factor(qubits, extracted, remainder, validate, atol) + e, r = self._state.factor(self.get_axes(qubits), validate=validate, atol=atol) + extracted._state = e + remainder._state = r extracted._set_qubits(qubits) remainder._set_qubits([q for q in self.qubits if q not in qubits]) return extracted, remainder @@ -268,21 +208,6 @@ def allows_factoring(self): """Subclasses that allow factorization should override this.""" return self._state.supports_factor if self._state is not None else False - @deprecated( - deadline='v0.16', - fix='Pass a `QuantumStateRepresentation` into the `SimulationState` constructor.', - ) - def _on_factor( - self: TSelf, - qubits: Sequence['cirq.Qid'], - extracted: TSelf, - remainder: TSelf, - validate=True, - atol=1e-07, - ): - """Subclasses should implement this with any additional state factor - functionality, if supported.""" - def transpose_to_qubit_order( self: TSelf, qubits: Sequence['cirq.Qid'], *, inplace=False ) -> TSelf: @@ -302,30 +227,10 @@ def transpose_to_qubit_order( if len(self.qubits) != len(qubits) or set(qubits) != set(self.qubits): raise ValueError(f'Qubits do not match. Existing: {self.qubits}, provided: {qubits}') args = self if inplace else copy.copy(self) - if self._state is not None: - args._state = self._state.reindex(self.get_axes(qubits)) - else: - _warn_or_error( - 'Pass a `QuantumStateRepresentation` into the `SimulationState` constructor.' - ' The `_on_` overrides will be removed in cirq v0.16.' - ) - self._on_transpose_to_qubit_order(qubits, args) + args._state = self._state.reindex(self.get_axes(qubits)) args._set_qubits(qubits) return args - @deprecated( - deadline='v0.16', - fix='Pass a `QuantumStateRepresentation` into the `SimulationState` constructor.', - ) - def _on_transpose_to_qubit_order(self: TSelf, qubits: Sequence['cirq.Qid'], target: TSelf): - """Subclasses should implement this with any additional state transpose - functionality, if supported.""" - - @property # type: ignore - @deprecated(deadline='v0.16', fix='Remove this call, it always returns False.') - def ignore_measurement_results(self) -> bool: - return False - @property def qubits(self) -> Tuple['cirq.Qid', ...]: return self._qubits diff --git a/cirq-core/cirq/sim/simulation_state_test.py b/cirq-core/cirq/sim/simulation_state_test.py index 87bc80bf1e0..0ba6d675662 100644 --- a/cirq-core/cirq/sim/simulation_state_test.py +++ b/cirq-core/cirq/sim/simulation_state_test.py @@ -101,63 +101,3 @@ def test_field_getters(): args = DummySimulationState() assert args.prng is np.random assert args.qubit_map == {q: i for i, q in enumerate(cirq.LineQubit.range(2))} - with cirq.testing.assert_deprecated('always returns False', deadline='v0.16'): - assert not args.ignore_measurement_results - - -def test_on_methods_deprecated(): - class OldStyleArgs(cirq.SimulationState): - def _act_on_fallback_(self, action, qubits, allow_decompose=True): - pass - - with cirq.testing.assert_deprecated('state', deadline='v0.16'): - args = OldStyleArgs() - with cirq.testing.assert_deprecated('_on_', deadline='v0.16', count=2): - _ = args.copy() - with cirq.testing.assert_deprecated('_on_', deadline='v0.16', count=2): - _ = args.kronecker_product(args) - with cirq.testing.assert_deprecated('_on_', deadline='v0.16', count=2): - _ = args.factor([]) - with cirq.testing.assert_deprecated('_on_', deadline='v0.16', count=2): - _ = args.transpose_to_qubit_order([]) - - -def test_on_methods_deprecated_if_implemented(): - class OldStyleArgs(cirq.SimulationState): - def _act_on_fallback_(self, action, qubits, allow_decompose=True): - pass - - def _on_copy(self, args, deep_copy_buffers=True): - pass - - def _on_kronecker_product(self, other, target): - pass - - def _on_factor(self, qubits, extracted, remainder, validate=True, atol=1e-07): - pass - - def _on_transpose_to_qubit_order(self, qubits, target): - pass - - with cirq.testing.assert_deprecated('state', deadline='v0.16'): - args = OldStyleArgs() - with cirq.testing.assert_deprecated('_on_', deadline='v0.16'): - _ = args.copy() - with cirq.testing.assert_deprecated('_on_', deadline='v0.16'): - _ = args.kronecker_product(args) - with cirq.testing.assert_deprecated('_on_', deadline='v0.16'): - _ = args.factor([]) - with cirq.testing.assert_deprecated('_on_', deadline='v0.16'): - _ = args.transpose_to_qubit_order([]) - - -def test_deprecated(): - class DeprecatedArgs(cirq.SimulationState): - def _act_on_fallback_(self, action, qubits, allow_decompose=True): - pass - - with cirq.testing.assert_deprecated('log_of_measurement_results', deadline='v0.16'): - _ = DeprecatedArgs(state=0, log_of_measurement_results={}) - - with cirq.testing.assert_deprecated('positional', deadline='v0.16'): - _ = DeprecatedArgs(np.random.RandomState(), state=0) diff --git a/cirq-core/cirq/sim/simulator.py b/cirq-core/cirq/sim/simulator.py index 89d1c9013d5..d8dd7dbb712 100644 --- a/cirq-core/cirq/sim/simulator.py +++ b/cirq-core/cirq/sim/simulator.py @@ -29,7 +29,6 @@ import abc import collections -import inspect from typing import ( Any, Callable, @@ -49,7 +48,7 @@ import numpy as np -from cirq import _compat, circuits, ops, protocols, study, value, work +from cirq import circuits, ops, protocols, study, value, work from cirq.sim.simulation_state_base import SimulationStateBase if TYPE_CHECKING: @@ -609,21 +608,11 @@ def simulate_sweep_iter( for step_result in all_step_results: for k, v in step_result.measurements.items(): measurements[k] = np.array(v, dtype=np.uint8) - if ( - 'final_simulator_state' - in inspect.signature(self._create_simulator_trial_result).parameters - ): - yield self._create_simulator_trial_result( - params=param_resolver, - measurements=measurements, - final_simulator_state=step_result._simulator_state(), - ) - else: - yield self._create_simulator_trial_result( # pylint: disable=no-value-for-parameter, unexpected-keyword-arg, line-too-long - params=param_resolver, - measurements=measurements, - final_step_result=step_result, # type: ignore - ) + yield self._create_simulator_trial_result( + params=param_resolver, + measurements=measurements, + final_simulator_state=step_result._simulator_state(), + ) def simulate_moment_steps( self, @@ -659,6 +648,7 @@ def simulate_moment_steps( qubits = ops.QubitOrder.as_qubit_order(qubit_order).order_for(circuit.all_qubits()) return self._base_iterator(resolved_circuit, qubits, actual_initial_state) + @abc.abstractmethod def _base_iterator( self, circuit: 'cirq.AbstractCircuit', qubits: Tuple['cirq.Qid', ...], initial_state: Any ) -> Iterator[TStepResult]: @@ -676,96 +666,6 @@ def _base_iterator( Yields: StepResults from simulating a Moment of the Circuit. """ - # In 0.16 (or 1.0) _base_iterator should be made abstract. Then _create_simulation_state, - # _create_act_on_args, and _core_iterator can all be removed from this class completely. - # (They were only required because of this implementation, which has been moved to - # SimulatorBase instead). - _compat._warn_or_error( - 'Custom implementations of `cirq.SimulatesIntermediateState` should implement' - ' `_base_iterator` directly rather than implementing both `_create_simulation_state`' - ' and `_core_iterator`. The default implementation of `_base_iterator` will be removed' - ' in v0.16, and the method will become abstract.' - ) - if not isinstance(qubits, tuple): - _compat._warn_or_error( - 'The `qubits` parameter of `_base_iterator` will expect an explicit' - ' `Tuple[cirq.Qid, ...]` beginning in v0.16.' - ) - qubits = ops.QubitOrder.as_qubit_order(qubits).order_for(circuit.all_qubits()) - sim_state = self._create_simulation_state(initial_state, qubits) - return self._core_iterator(circuit, sim_state) - - def _create_act_on_args( - self, initial_state: Any, qubits: Sequence['cirq.Qid'] - ) -> TSimulatorState: - """Creates the state for a simulator. - - Custom simulators should implement this method. - - Args: - initial_state: The initial state for the simulation. The form of - this state depends on the simulation implementation. See - documentation of the implementing class for details. - qubits: Determines the canonical ordering of the qubits. This - is often used in specifying the initial state, i.e. the - ordering of the computational basis states. - - Returns: - The `TSimulatorState` for this simulator. - """ - raise NotImplementedError() - - def _create_simulation_state( - self, initial_state: Any, qubits: Sequence['cirq.Qid'] - ) -> TSimulatorState: - """Creates the state for a simulator. - - Custom simulators should implement this method. - - Args: - initial_state: The initial state for the simulation. The form of - this state depends on the simulation implementation. See - documentation of the implementing class for details. - qubits: Determines the canonical ordering of the qubits. This - is often used in specifying the initial state, i.e. the - ordering of the computational basis states. - - Returns: - The `TSimulatorState` for this simulator. - """ - _compat._warn_or_error( - '`_create_act_on_args` has been renamed to `_create_simulation_state` in the' - ' SimulatesIntermediateState interface, so simulators need to rename that method' - f' implementation as well before v0.16. {type(self)}' - ' has no `_create_simulation_state` method, so falling back to `_create_act_on_args`.' - ' This fallback functionality will be removed in v0.16.' - ) - # When cleaning this up in v0.16, mark `_create_simulation_state` as @abc.abstractmethod, - # remove this implementation, and delete `_create_act_on_args` entirely. - return self._create_act_on_args(initial_state, qubits) - - def _core_iterator( - self, - circuit: 'cirq.AbstractCircuit', - sim_state: TSimulatorState, - all_measurements_are_terminal: bool = False, - ) -> Iterator[TStepResult]: - """Iterator over StepResult from Moments of a Circuit. - - Custom simulators should implement this method. - - Args: - circuit: The circuit to simulate. - sim_state: The initial state for the simulation. The form of - this state depends on the simulation implementation. See - documentation of the implementing class for details. - all_measurements_are_terminal: Whether all measurements in - the circuit are terminal. - - Yields: - StepResults from simulating a Moment of the Circuit. - """ - raise NotImplementedError() @abc.abstractmethod def _create_simulator_trial_result( @@ -803,14 +703,6 @@ def __init__(self, sim_state: TSimulatorState) -> None: def measurements(self) -> Mapping[str, Sequence[int]]: return self._measurements - @measurements.setter # type: ignore - @_compat.deprecated( - deadline="v0.16", - fix="The mutators of this class are deprecated, instantiate a new object instead.", - ) - def measurements(self, measurements: Mapping[str, Sequence[int]]): - self._measurements = measurements - def _simulator_state(self) -> TSimulatorState: """Returns the simulator state of the simulator after this step. @@ -960,55 +852,6 @@ def _confuse_results( rep[k] = new_bits[i] -# When removing this, also remove the check in simulate_sweep_iter. -# Basically there should be no "final_step_result" anywhere in the project afterwards. -def _deprecated_step_result_parameter( - old_position: int = 4, new_position: int = 3 -) -> Callable[[Callable], Callable]: - assert old_position >= new_position - - def rewrite_deprecated_step_result_param(args, kwargs): - args = list(args) - state = ( - kwargs['final_simulator_state'] - if 'final_simulator_state' in kwargs - else args[new_position] - if len(args) > new_position and not isinstance(args[new_position], StepResult) - else None - ) - step_result = ( - kwargs['final_step_result'] - if 'final_step_result' in kwargs - else args[old_position] - if len(args) > old_position and isinstance(args[old_position], StepResult) - else None - ) - if (step_result is None) == (state is None): - raise ValueError( - 'Exactly one of final_simulator_state and final_step_result should be provided' - ) - if len(args) > old_position and isinstance(args[old_position], StepResult): - args[new_position] = args[old_position]._simulator_state() - if old_position > new_position: - del args[old_position] - elif 'final_step_result' in kwargs: - sim_state = kwargs['final_step_result']._simulator_state() - if len(args) > new_position: - args[new_position] = sim_state - else: - kwargs['final_simulator_state'] = sim_state - del kwargs['final_step_result'] - return tuple(args), kwargs - - return _compat.deprecated_parameter( - deadline='v0.16', - fix='', - parameter_desc='final_step_result', - match=lambda args, kwargs: 'final_step_result' in kwargs or len(args) > old_position, - rewrite=rewrite_deprecated_step_result_param, - ) - - @value.value_equality(unhashable=True) class SimulationTrialResult(Generic[TSimulatorState]): """Results of a simulation by a SimulatesFinalState. @@ -1026,7 +869,6 @@ class SimulationTrialResult(Generic[TSimulatorState]): measurement gate.) """ - @_deprecated_step_result_parameter() def __init__( self, params: 'cirq.ParamResolver', @@ -1051,26 +893,10 @@ def __init__( def params(self) -> 'cirq.ParamResolver': return self._params - @params.setter # type: ignore - @_compat.deprecated( - deadline='v0.16', - fix='The mutators of this class are deprecated, instantiate a new object instead.', - ) - def params(self, params: 'cirq.ParamResolver'): - self._params = params - @property def measurements(self) -> Mapping[str, np.ndarray]: return self._measurements - @measurements.setter # type: ignore - @_compat.deprecated( - deadline="v0.16", - fix="The mutators of this class are deprecated, instantiate a new object instead.", - ) - def measurements(self, measurements: Mapping[str, np.ndarray]): - self._measurements = measurements - def __repr__(self) -> str: return ( f'cirq.SimulationTrialResult(params={self.params!r}, ' diff --git a/cirq-core/cirq/sim/simulator_base.py b/cirq-core/cirq/sim/simulator_base.py index 9a2e85ea4a0..7a26fc9a6dd 100644 --- a/cirq-core/cirq/sim/simulator_base.py +++ b/cirq-core/cirq/sim/simulator_base.py @@ -33,8 +33,7 @@ import numpy as np -from cirq import _compat, devices, ops, protocols, study, value -from cirq.sim import simulator +from cirq import devices, ops, protocols, study, value from cirq.sim.simulation_product_state import SimulationProductState from cirq.sim.simulation_state import TSimulationState from cirq.sim.simulation_state_base import SimulationStateBase @@ -50,8 +49,6 @@ if TYPE_CHECKING: import cirq - from numpy.typing import DTypeLike - TStepResultBase = TypeVar('TStepResultBase', bound='StepResultBase') @@ -118,34 +115,7 @@ def __init__( def noise(self) -> 'cirq.NoiseModel': return self._noise - @noise.setter # type: ignore - @_compat.deprecated( - deadline="v0.16", - fix="The mutators of this class are deprecated, instantiate a new object instead.", - ) - def noise(self, noise: 'cirq.NoiseModel'): - self._noise = noise - - def _create_partial_act_on_args( - self, - initial_state: Any, - qubits: Sequence['cirq.Qid'], - classical_data: 'cirq.ClassicalDataStore', - ) -> TSimulationState: - """Creates an instance of the TSimulationState class for the simulator. - - It represents the supplied qubits initialized to the provided state. - - Args: - initial_state: The initial state to represent. An integer state is - understood to be a pure state. Other state representations are - simulator-dependent. - qubits: The sequence of qubits to represent. - classical_data: The shared classical data container for this - simulation. - """ - raise NotImplementedError() - + @abc.abstractmethod def _create_partial_simulation_state( self, initial_state: Any, @@ -164,17 +134,6 @@ def _create_partial_simulation_state( classical_data: The shared classical data container for this simulation. """ - _compat._warn_or_error( - '`_create_partial_act_on_args` has been renamed to `_create_partial_simulation_state`' - ' in the SimulatorBase class, so simulators need to rename that method' - f' implementation as well before v0.16. {type(self)}' - ' has no `_create_partial_simulation_state` method, so falling back to' - ' `_create_partial_act_on_args`. This fallback functionality will be removed in v0.16.' - ) - # When cleaning this up in v0.16, mark `_create_partial_simulation_state` as - # @abc.abstractmethod, remove this implementation, and delete `_create_partial_act_on_args` - # entirely. - return self._create_partial_act_on_args(initial_state, qubits, classical_data) @abc.abstractmethod def _create_step_result( @@ -214,12 +173,6 @@ def _can_be_in_run_prefix(self, val: Any): def _base_iterator( self, circuit: 'cirq.AbstractCircuit', qubits: Tuple['cirq.Qid', ...], initial_state: Any ) -> Iterator[TStepResultBase]: - if not isinstance(qubits, tuple): - _compat._warn_or_error( - 'The `qubits` parameter of `_base_iterator` will expect an explicit' - ' `Tuple[cirq.Qid, ...]` beginning in v0.16.' - ) - qubits = ops.QubitOrder.as_qubit_order(qubits).order_for(circuit.all_qubits()) sim_state = self._create_simulation_state(initial_state, qubits) return self._core_iterator(circuit, sim_state) @@ -452,7 +405,6 @@ class SimulationTrialResultBase( ): """A base class for trial results.""" - @simulator._deprecated_step_result_parameter(old_position=3) def __init__( self, params: study.ParamResolver, diff --git a/cirq-core/cirq/sim/simulator_base_test.py b/cirq-core/cirq/sim/simulator_base_test.py index 10dcbd2014e..044e1afb609 100644 --- a/cirq-core/cirq/sim/simulator_base_test.py +++ b/cirq-core/cirq/sim/simulator_base_test.py @@ -434,57 +434,3 @@ def test_inhomogeneous_measurement_count_padding(): results = sim.run(c, repetitions=10) for i in range(10): assert np.sum(results.records['m'][i, :, :]) == 1 - - -def test_deprecated_final_step_result(): - class OldCountingSimulator(CountingSimulator): - def _create_simulator_trial_result( # type: ignore - self, - params: cirq.ParamResolver, - measurements: Dict[str, np.ndarray], - final_step_result: CountingStepResult, - ) -> CountingTrialResult: - return CountingTrialResult(params, measurements, final_step_result=final_step_result) - - sim = OldCountingSimulator() - with cirq.testing.assert_deprecated('final_step_result', deadline='0.16'): - r = sim.simulate(cirq.Circuit()) - assert r._final_simulator_state.gate_count == 0 - assert r._final_simulator_state.measurement_count == 0 - - -def test_deprecated_create_partial_act_on_args(): - class DeprecatedSim(cirq.SimulatorBase): - def _create_partial_act_on_args(self, initial_state, qubits, classical_data): - return 0 - - def _create_step_result(self): - pass - - def _create_simulator_trial_result(self): - pass - - sim = DeprecatedSim() - with cirq.testing.assert_deprecated(deadline='v0.16'): - sim.simulate_moment_steps(cirq.Circuit()) - - -def test_deprecated_qubits_param(): - class Sim(cirq.SimulatorBase): - def _create_partial_simulation_state(self, initial_state, qubits, classical_data): - return 0 - - def _create_step_result(self): - pass - - def _create_simulator_trial_result(self): - pass - - with cirq.testing.assert_deprecated('`qubits` parameter of `_base_iterator', deadline='v0.16'): - Sim()._base_iterator(cirq.Circuit(), cirq.QubitOrder.explicit([]), 0) - - -def test_deprecated_setters(): - sim = CountingSimulator() - with cirq.testing.assert_deprecated(deadline='v0.16'): - sim.noise = cirq.ConstantQubitNoiseModel(cirq.Z) diff --git a/cirq-core/cirq/sim/simulator_test.py b/cirq-core/cirq/sim/simulator_test.py index af79f1d9808..4d3707e82c9 100644 --- a/cirq-core/cirq/sim/simulator_test.py +++ b/cirq-core/cirq/sim/simulator_test.py @@ -528,74 +528,8 @@ class FakeMissingIterSimulatorImpl( def test_trial_result_initializer(): resolver = cirq.ParamResolver() - step = mock.Mock(cirq.StepResultBase) - step._simulator_state.return_value = 1 state = 3 - with pytest.raises(ValueError, match='Exactly one of'): - _ = SimulationTrialResult(resolver, {}, None, None) - with pytest.raises(ValueError, match='Exactly one of'): - _ = SimulationTrialResult(resolver, {}, state, step) - with pytest.raises(ValueError, match='Exactly one of'): - _ = SimulationTrialResult(resolver, {}, final_simulator_state=None, final_step_result=None) - with pytest.raises(ValueError, match='Exactly one of'): - _ = SimulationTrialResult(resolver, {}, final_simulator_state=state, final_step_result=step) - with cirq.testing.assert_deprecated(deadline='v0.16'): - x = SimulationTrialResult(resolver, {}, final_step_result=step) - assert x._final_simulator_state == 1 - with cirq.testing.assert_deprecated(deadline='v0.16'): - x = SimulationTrialResult(resolver, {}, None, final_step_result=step) - assert x._final_simulator_state == 1 - with cirq.testing.assert_deprecated(deadline='v0.16'): - x = SimulationTrialResult(resolver, {}, None, step) - assert x._final_simulator_state == 1 - with cirq.testing.assert_deprecated(deadline='v0.16'): - x = SimulationTrialResult(resolver, {}, final_simulator_state=None, final_step_result=step) - assert x._final_simulator_state == 1 x = SimulationTrialResult(resolver, {}, state) assert x._final_simulator_state == 3 x = SimulationTrialResult(resolver, {}, final_simulator_state=state) assert x._final_simulator_state == 3 - - -def test_deprecated_create_act_on_args(): - class DeprecatedSim(cirq.SimulatesIntermediateState): - def _create_act_on_args(self, initial_state, qubits): - return 0 - - def _core_iterator(self, circuit, sim_state): - pass - - def _create_simulator_trial_result(self): - pass - - sim = DeprecatedSim() - with cirq.testing.assert_deprecated(deadline='v0.16', count=2): - sim.simulate_moment_steps(cirq.Circuit()) - - -def test_deprecated_qubits_param(): - class Sim(cirq.SimulatesIntermediateState): - def _create_simulation_state(self, initial_state, qubits): - return 0 - - def _core_iterator(self, circuit, sim_state): - pass - - def _create_simulator_trial_result(self): - pass - - with cirq.testing.assert_deprecated( - '`qubits` parameter of `_base_iterator', deadline='v0.16', count=2 - ): - Sim()._base_iterator(cirq.Circuit(), cirq.QubitOrder.explicit([]), 0) - - -def test_deprecated_setters(): - step = FakeStepResult() - result = cirq.SimulationTrialResult(cirq.ParamResolver(), {}, 0) - with cirq.testing.assert_deprecated(deadline='v0.16'): - step.measurements = {} - with cirq.testing.assert_deprecated(deadline='v0.16'): - result.measurements = {} - with cirq.testing.assert_deprecated(deadline='v0.16'): - result.params = cirq.ParamResolver() diff --git a/cirq-core/cirq/sim/sparse_simulator.py b/cirq-core/cirq/sim/sparse_simulator.py index dd2c160f1cc..bd93d563172 100644 --- a/cirq-core/cirq/sim/sparse_simulator.py +++ b/cirq-core/cirq/sim/sparse_simulator.py @@ -19,7 +19,6 @@ import numpy as np from cirq import _compat, ops -from cirq._compat import deprecated_parameter from cirq.sim import simulator, state_vector, state_vector_simulator, state_vector_simulation_state if TYPE_CHECKING: @@ -220,23 +219,15 @@ 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.SimulationStateBase[cirq.StateVectorSimulationState]', - simulator: 'cirq.Simulator' = None, dtype: Type[np.complexfloating] = np.complex64, ): """Results of a step of the simulator. Args: sim_state: The qubit:SimulationState lookup for this step. - simulator: The simulator used to create this. dtype: The `numpy.dtype` used by the simulation. One of `numpy.complex64` or `numpy.complex128`. """ diff --git a/cirq-core/cirq/sim/state_vector_simulation_state.py b/cirq-core/cirq/sim/state_vector_simulation_state.py index 7043bc7212b..bb470013456 100644 --- a/cirq-core/cirq/sim/state_vector_simulation_state.py +++ b/cirq-core/cirq/sim/state_vector_simulation_state.py @@ -17,7 +17,7 @@ import numpy as np -from cirq import _compat, linalg, protocols, qis, sim +from cirq import linalg, protocols, qis, sim from cirq._compat import proper_repr from cirq.linalg import transformations from cirq.sim.simulation_state import SimulationState, strat_act_on_from_apply_decompose @@ -357,77 +357,6 @@ def __init__( ) super().__init__(state=state, prng=prng, qubits=qubits, classical_data=classical_data) - @_compat.deprecated( - deadline='v0.16', fix='None, this function was unintentionally made public.' - ) - def swap_target_tensor_for(self, new_target_tensor: np.ndarray): - """Gives a new state vector for the system. - - Typically, the new state vector should be `args.available_buffer` where - `args` is this `cirq.StateVectorSimulationState` instance. - - Args: - new_target_tensor: The new system state. Must have the same shape - and dtype as the old system state. - """ - self._state._swap_target_tensor_for(new_target_tensor) - - @_compat.deprecated( - deadline='v0.16', fix='None, this function was unintentionally made public.' - ) - def subspace_index( - self, axes: Sequence[int], little_endian_bits_int: int = 0, *, big_endian_bits_int: int = 0 - ) -> Tuple[Union[slice, int, 'ellipsis'], ...]: - """An index for the subspace where the target axes equal a value. - - Args: - axes: The qubits that are specified by the index bits. - little_endian_bits_int: The desired value of the qubits at the - targeted `axes`, packed into an integer. The least significant - bit of the integer is the desired bit for the first axis, and - so forth in increasing order. Can't be specified at the same - time as `big_endian_bits_int`. - - When operating on qudits instead of qubits, the same basic logic - applies but in a different basis. For example, if the target - axes have dimension [a:2, b:3, c:2] then the integer 10 - decomposes into [a=0, b=2, c=1] via 7 = 1*(3*2) + 2*(2) + 0. - big_endian_bits_int: The desired value of the qubits at the - targeted `axes`, packed into an integer. The most significant - bit of the integer is the desired bit for the first axis, and - so forth in decreasing order. Can't be specified at the same - time as `little_endian_bits_int`. - - When operating on qudits instead of qubits, the same basic logic - applies but in a different basis. For example, if the target - axes have dimension [a:2, b:3, c:2] then the integer 10 - decomposes into [a=1, b=2, c=0] via 7 = 1*(3*2) + 2*(2) + 0. - - Returns: - A value that can be used to index into `target_tensor` and - `available_buffer`, and manipulate only the part of Hilbert space - corresponding to a given bit assignment. - - Example: - If `target_tensor` is a 4 qubit tensor and `axes` is `[1, 3]` and - then this method will return the following when given - `little_endian_bits=0b01`: - - `(slice(None), 0, slice(None), 1, Ellipsis)` - - Therefore the following two lines would be equivalent: - - args.target_tensor[args.subspace_index(0b01)] += 1 - - args.target_tensor[:, 0, :, 1] += 1 - """ - return linalg.slice_for_qubits_equal_to( - axes, - little_endian_qureg_value=little_endian_bits_int, - big_endian_qureg_value=big_endian_bits_int, - qid_shape=self.target_tensor.shape, - ) - def _act_on_fallback_( self, action: Any, qubits: Sequence['cirq.Qid'], allow_decompose: bool = True ) -> bool: diff --git a/cirq-core/cirq/sim/state_vector_simulation_state_test.py b/cirq-core/cirq/sim/state_vector_simulation_state_test.py index 515ea2b2457..102d5bb5045 100644 --- a/cirq-core/cirq/sim/state_vector_simulation_state_test.py +++ b/cirq-core/cirq/sim/state_vector_simulation_state_test.py @@ -286,11 +286,3 @@ def test_with_qubits(): def test_qid_shape_error(): with pytest.raises(ValueError, match="qid_shape must be provided"): cirq.sim.state_vector_simulation_state._BufferedStateVector.create(initial_state=0) - - -def test_deprecated_methods(): - args = cirq.StateVectorSimulationState(qubits=[cirq.LineQubit(0)]) - with cirq.testing.assert_deprecated('unintentionally made public', deadline='v0.16'): - args.subspace_index([0], 0) - with cirq.testing.assert_deprecated('unintentionally made public', deadline='v0.16'): - args.swap_target_tensor_for(np.array([])) diff --git a/cirq-core/cirq/sim/state_vector_simulator.py b/cirq-core/cirq/sim/state_vector_simulator.py index ecc0f417b89..10b320bee78 100644 --- a/cirq-core/cirq/sim/state_vector_simulator.py +++ b/cirq-core/cirq/sim/state_vector_simulator.py @@ -14,23 +14,12 @@ """Abstract classes for simulations which keep track of state vector.""" import abc -from typing import ( - Any, - Dict, - Iterator, - Sequence, - Type, - TYPE_CHECKING, - Tuple, - Generic, - TypeVar, - Optional, -) +from typing import Any, Dict, Iterator, Sequence, Type, TYPE_CHECKING, Generic, TypeVar, Optional import numpy as np from cirq import _compat, ops, value, qis -from cirq._compat import deprecated_class, proper_repr +from cirq._compat import proper_repr from cirq.sim import simulator, state_vector, simulator_base if TYPE_CHECKING: @@ -107,33 +96,6 @@ class StateVectorStepResult( pass -@deprecated_class(deadline='v0.16', fix='This class is no longer used.') -@value.value_equality(unhashable=True) -class StateVectorSimulatorState: - """Object representing current state of the simulator. - - Includes the state vector, qubit map, and shape information. - """ - - def __init__(self, state_vector: np.ndarray, qubit_map: Dict[ops.Qid, int]) -> None: - self.state_vector = state_vector - self.qubit_map = qubit_map - self._qid_shape = simulator._qubit_map_to_shape(qubit_map) - - def _qid_shape_(self) -> Tuple[int, ...]: - return self._qid_shape - - def __repr__(self) -> str: - return ( - 'cirq.StateVectorSimulatorState(' - f'state_vector=np.{self.state_vector!r}, ' - f'qubit_map={self.qubit_map!r})' - ) - - def _value_equality_values_(self) -> Any: - return self.state_vector.tolist(), self.qubit_map - - @value.value_equality(unhashable=True) class StateVectorTrialResult( state_vector.StateVectorMixin, diff --git a/cirq-core/cirq/sim/state_vector_simulator_test.py b/cirq-core/cirq/sim/state_vector_simulator_test.py index b98353a544a..5498e9e6c5d 100644 --- a/cirq-core/cirq/sim/state_vector_simulator_test.py +++ b/cirq-core/cirq/sim/state_vector_simulator_test.py @@ -45,14 +45,6 @@ def test_state_vector_trial_result_repr(): assert eval(expected_repr) == trial_result -def test_state_vector_simulator_state_repr(): - with cirq.testing.assert_deprecated('no longer used', deadline='v0.16', count=4): - final_simulator_state = cirq.StateVectorSimulatorState( - qubit_map={cirq.NamedQubit('a'): 0}, state_vector=np.array([0, 1]) - ) - cirq.testing.assert_equivalent_repr(final_simulator_state) - - def test_state_vector_trial_result_equality(): eq = cirq.testing.EqualsTester() final_simulator_state = cirq.StateVectorSimulationState(initial_state=np.array([])) diff --git a/cirq-core/cirq/testing/consistent_act_on.py b/cirq-core/cirq/testing/consistent_act_on.py index d521a0a1f5f..0bab03b9005 100644 --- a/cirq-core/cirq/testing/consistent_act_on.py +++ b/cirq-core/cirq/testing/consistent_act_on.py @@ -76,7 +76,7 @@ def assert_all_implemented_act_on_effects_match_unitary( assert_tableau_implemented: asserts that protocols.act_on() works with val and CliffordTableauSimulationState inputs. assert_ch_form_implemented: asserts that protocols.act_on() works with - val and ActOnStabilizerStateChFormArgs inputs. + val and StabilizerChFormSimulationState inputs. """ # pylint: disable=unused-variable