Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove some 0.15 items from cirq.sim #5137

Merged
merged 14 commits into from
Apr 7, 2022
58 changes: 7 additions & 51 deletions cirq-core/cirq/sim/act_on_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
"""Objects and methods for acting efficiently on a state tensor."""
import abc
import copy
import inspect
from typing import (
Any,
cast,
Expand All @@ -28,12 +27,11 @@
TYPE_CHECKING,
Tuple,
)
import warnings

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

Expand All @@ -46,18 +44,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,
):
"""Inits ActOnArgs.
Expand All @@ -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.
"""
Expand All @@ -89,7 +76,6 @@ def __init__(
for k, v in (log_of_measurement_results or {}).items()
}
)
self._ignore_measurement_results = ignore_measurement_results

@property
def prng(self) -> np.random.RandomState:
Expand All @@ -99,32 +85,14 @@ 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)}

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.
Expand All @@ -136,9 +104,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(
Expand All @@ -165,17 +130,7 @@ def copy(self: TSelf, deep_copy_buffers: bool = True) -> TSelf:
A copied instance.
"""
args = copy.copy(self)
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)
args._classical_data = self._classical_data.copy()
return args

Expand Down Expand Up @@ -277,9 +232,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', ...]:
Expand Down
35 changes: 3 additions & 32 deletions cirq-core/cirq/sim/act_on_args_container.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Dict,
Expand All @@ -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,
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -160,8 +142,7 @@ def _act_on_fallback_(

# Decouple any measurements or resets
if self.split_untangled_states and (
isinstance(gate, ops.ResetChannel)
or (isinstance(gate, ops.MeasurementGate) and not op_args.ignore_measurement_results)
isinstance(gate, (ops.ResetChannel, ops.MeasurementGate))
):
for q in qubits:
if op_args.allows_factoring:
Expand All @@ -177,17 +158,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()}
Expand Down
14 changes: 0 additions & 14 deletions cirq-core/cirq/sim/act_on_args_container_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,12 +231,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()
Expand Down Expand Up @@ -288,11 +282,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
16 changes: 2 additions & 14 deletions cirq-core/cirq/sim/act_on_args_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,21 +95,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
32 changes: 6 additions & 26 deletions cirq-core/cirq/sim/act_on_density_matrix_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,12 +237,6 @@ class ActOnDensityMatrixArgs(ActOnArgs):
parameter_desc='log_of_measurement_results and positional arguments',
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.',
Expand All @@ -257,7 +251,6 @@ def __init__(
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,
Expand All @@ -280,10 +273,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
Expand All @@ -296,21 +285,12 @@ def __init__(
ValueError: The dimension of `target_tensor` is not divisible by 2
and `qid_shape` is not provided.
"""
if ignore_measurement_results:
super().__init__(
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__(
prng=prng,
qubits=qubits,
log_of_measurement_results=log_of_measurement_results,
classical_data=classical_data,
)
super().__init__(
prng=prng,
qubits=qubits,
log_of_measurement_results=log_of_measurement_results,
classical_data=classical_data,
)
self._state = _BufferedDensityMatrix.create(
initial_state=target_tensor if target_tensor is not None else initial_state,
qid_shape=tuple(q.dimension for q in qubits) if qubits is not None else None,
Expand Down
Loading