Skip to content

Commit

Permalink
Remove deprecated log_of_measurement_results parameters (#5233)
Browse files Browse the repository at this point in the history
* deprecate log_of_measurement_results

* Fix test

* coverage

* Add empty ClassicalDataDictionaryStore.repr test

* Add ActOnArgs test

* Add tests

* Add ActOnStabilizerArgs tests

* nits

* coverGE

* format

Co-authored-by: Cirq Bot <[email protected]>
  • Loading branch information
daxfohl and CirqBot authored Apr 13, 2022
1 parent 32fa8b6 commit f85e731
Show file tree
Hide file tree
Showing 17 changed files with 358 additions and 399 deletions.
84 changes: 29 additions & 55 deletions cirq-core/cirq/contrib/quimb/mps_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
import quimb.tensor as qtn

from cirq import devices, protocols, qis, value
from cirq._compat import deprecated
from cirq._compat import deprecated_parameter
from cirq.sim import simulator_base
from cirq.sim.act_on_args import ActOnArgs

Expand Down Expand Up @@ -53,9 +53,7 @@ class MPSOptions:


class MPSSimulator(
simulator_base.SimulatorBase[
'MPSSimulatorStepResult', 'MPSTrialResult', 'MPSState', 'MPSState'
],
simulator_base.SimulatorBase['MPSSimulatorStepResult', 'MPSTrialResult', 'MPSState', 'MPSState']
):
"""An efficient simulator for MPS circuits."""

Expand Down Expand Up @@ -83,10 +81,7 @@ def __init__(
raise ValueError(f'noise must be unitary or mixture but was {noise_model}')
self.simulation_options = simulation_options
self.grouping = grouping
super().__init__(
noise=noise,
seed=seed,
)
super().__init__(noise=noise, seed=seed)

def _create_partial_act_on_args(
self,
Expand Down Expand Up @@ -120,10 +115,7 @@ def _create_partial_act_on_args(
classical_data=classical_data,
)

def _create_step_result(
self,
sim_state: 'cirq.OperationTarget[MPSState]',
):
def _create_step_result(self, sim_state: 'cirq.OperationTarget[MPSState]'):
return MPSSimulatorStepResult(sim_state)

def _create_simulator_trial_result(
Expand Down Expand Up @@ -182,10 +174,7 @@ def _repr_pretty_(self, p: Any, cycle: bool):
class MPSSimulatorStepResult(simulator_base.StepResultBase['MPSState', 'MPSState']):
"""A `StepResult` that can perform measurements."""

def __init__(
self,
sim_state: 'cirq.OperationTarget[MPSState]',
):
def __init__(self, sim_state: 'cirq.OperationTarget[MPSState]'):
"""Results of a step of the simulator.
Attributes:
sim_state: The qubit:ActOnArgs lookup for this step.
Expand Down Expand Up @@ -576,6 +565,19 @@ def sample(
class MPSState(ActOnArgs):
"""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'],
Expand Down Expand Up @@ -614,13 +616,16 @@ def __init__(
simulation_options=simulation_options,
grouping={qubit_map[k]: v for k, v in final_grouping.items()},
)
super().__init__(
state=state,
prng=prng,
qubits=qubits,
log_of_measurement_results=log_of_measurement_results,
classical_data=classical_data,
)
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)
self._state: _MPSHandler = state

def i_str(self, i: int) -> str:
Expand Down Expand Up @@ -665,21 +670,8 @@ def to_numpy(self) -> np.ndarray:
"""An alias for the state vector."""
return self._state.to_numpy()

@deprecated(deadline="v0.15", fix="Use cirq.act_on(op, mps_state)")
def apply_op(self, op: 'cirq.Operation', prng: np.random.RandomState):
"""Applies a unitary operation, mutating the object to represent the new state.
op:
The operation that mutates the object. Note that currently, only 1-
and 2- qubit operations are currently supported.
"""
return self._state.apply_op(op, self.get_axes(op.qubits), prng)

def _act_on_fallback_(
self,
action: Any,
qubits: Sequence['cirq.Qid'],
allow_decompose: bool = True,
self, action: Any, qubits: Sequence['cirq.Qid'], allow_decompose: bool = True
) -> bool:
"""Delegates the action to self.apply_op"""
return self._state.apply_op(action, self.get_axes(qubits), self.prng)
Expand All @@ -691,21 +683,3 @@ def estimation_stats(self):
@property
def M(self):
return self._state._M

@deprecated(deadline="v0.15", fix="Use cirq.act_on(measurement, mps_state)")
def perform_measurement(
self, qubits: Sequence['cirq.Qid'], prng: np.random.RandomState, collapse_state_vector=True
) -> List[int]:
"""Performs a measurement over one or more qubits.
Args:
qubits: The sequence of qids to measure, in that order.
prng: A random number generator, used to simulate measurements.
collapse_state_vector: A Boolean specifying whether we should mutate
the state after the measurement.
Raises:
ValueError: If the probabilities for the measurements differ too much from one for the
tolerance specified in simulation options.
"""
return self._state._measure(self.get_axes(qubits), prng, collapse_state_vector)
33 changes: 10 additions & 23 deletions cirq-core/cirq/contrib/quimb/mps_simulator_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,7 @@ def test_various_gates_1d():
def test_various_gates_1d_flip():
q0, q1 = cirq.LineQubit.range(2)

circuit = cirq.Circuit(
cirq.H(q1),
cirq.CNOT(q1, q0),
)
circuit = cirq.Circuit(cirq.H(q1), cirq.CNOT(q1, q0))

assert_same_output_as_dense(circuit=circuit, qubit_order=[q0, q1])
assert_same_output_as_dense(circuit=circuit, qubit_order=[q1, q0])
Expand Down Expand Up @@ -378,10 +375,7 @@ def test_supremacy_equal_more_cols():
def test_tensor_index_names():
qubits = cirq.LineQubit.range(12)
qubit_map = {qubit: i for i, qubit in enumerate(qubits)}
state = ccq.mps_simulator.MPSState(
qubit_map,
prng=value.parse_random_state(0),
)
state = ccq.mps_simulator.MPSState(qubits=qubit_map, prng=value.parse_random_state(0))

assert state.i_str(0) == "i_00"
assert state.i_str(11) == "i_11"
Expand Down Expand Up @@ -559,10 +553,7 @@ def test_state_act_on_args_initializer():


def test_act_on_gate():
args = ccq.mps_simulator.MPSState(
qubits=cirq.LineQubit.range(3),
prng=np.random.RandomState(0),
)
args = ccq.mps_simulator.MPSState(qubits=cirq.LineQubit.range(3), prng=np.random.RandomState(0))

cirq.act_on(cirq.X, args, [cirq.LineQubit(1)])
np.testing.assert_allclose(
Expand All @@ -571,15 +562,11 @@ def test_act_on_gate():
)


def test_deprectated():
q0 = cirq.LineQubit(0)
def test_deprecated():
prng = np.random.RandomState(0)
args = ccq.mps_simulator.MPSState(
qubits=cirq.LineQubit.range(3),
prng=prng,
log_of_measurement_results={},
)
with cirq.testing.assert_deprecated(deadline='0.15'):
args.perform_measurement([q0], prng)
with cirq.testing.assert_deprecated(deadline='0.15'):
args.apply_op(cirq.X(q0), prng)
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)
7 changes: 2 additions & 5 deletions cirq-core/cirq/protocols/act_on_protocol_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,11 @@ def measure(self, axes, seed=None):

class DummyActOnArgs(cirq.ActOnArgs):
def __init__(self, fallback_result: Any = NotImplemented):
super().__init__(np.random.RandomState(), state=DummyQuantumState())
super().__init__(prng=np.random.RandomState(), state=DummyQuantumState())
self.fallback_result = fallback_result

def _act_on_fallback_(
self,
action: Any,
qubits: Sequence['cirq.Qid'],
allow_decompose: bool = True,
self, action: Any, qubits: Sequence['cirq.Qid'], allow_decompose: bool = True
):
return self.fallback_result

Expand Down
Original file line number Diff line number Diff line change
@@ -1,60 +1,69 @@
{
"cirq_type": "ClassicalDataDictionaryStore",
"records": [
[
{
"cirq_type": "MeasurementKey",
"name": "m",
"path": []
},
[[0, 1]]
]
],
"measured_qubits": [
[
{
"cirq_type": "MeasurementKey",
"name": "m",
"path": []
},
[[
[
{
"cirq_type": "ClassicalDataDictionaryStore",
"records": [
[
{
"cirq_type": "LineQubit",
"x": 0
"cirq_type": "MeasurementKey",
"name": "m",
"path": []
},
[[0, 1]]
]
],
"measured_qubits": [
[
{
"cirq_type": "LineQubit",
"x": 1
}
]]
]
],
"channel_records": [
[
{
"cirq_type": "MeasurementKey",
"name": "c",
"path": []
},
[3]
]
],
"measurement_types": [
[
{
"cirq_type": "MeasurementKey",
"name": "m",
"path": []
},
1
"cirq_type": "MeasurementKey",
"name": "m",
"path": []
},
[[
{
"cirq_type": "LineQubit",
"x": 0
},
{
"cirq_type": "LineQubit",
"x": 1
}
]]
]
],
"channel_records": [
[
{
"cirq_type": "MeasurementKey",
"name": "c",
"path": []
},
[3]
]
],
[
{
"cirq_type": "MeasurementKey",
"name": "c",
"path": []
},
2
"measurement_types": [
[
{
"cirq_type": "MeasurementKey",
"name": "m",
"path": []
},
1
],
[
{
"cirq_type": "MeasurementKey",
"name": "c",
"path": []
},
2
]
]
]
}
},
{
"cirq_type": "ClassicalDataDictionaryStore",
"records": [],
"measured_qubits": [],
"channel_records": [],
"measurement_types": []
}
]
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
cirq.ClassicalDataDictionaryStore(_records={cirq.MeasurementKey('m'): [[0, 1]]}, _measured_qubits={cirq.MeasurementKey('m'): [[cirq.LineQubit(0), cirq.LineQubit(1)]]}, _channel_records={cirq.MeasurementKey('c'): [3]}, _measurement_types={cirq.MeasurementKey('m'): cirq.MeasurementType.MEASUREMENT, cirq.MeasurementKey('c'): cirq.MeasurementType.CHANNEL})
[
cirq.ClassicalDataDictionaryStore(_records={cirq.MeasurementKey('m'): [[0, 1]]}, _measured_qubits={cirq.MeasurementKey('m'): [[cirq.LineQubit(0), cirq.LineQubit(1)]]}, _channel_records={cirq.MeasurementKey('c'): [3]}, _measurement_types={cirq.MeasurementKey('m'): cirq.MeasurementType.MEASUREMENT, cirq.MeasurementKey('c'): cirq.MeasurementType.CHANNEL}),
cirq.ClassicalDataDictionaryStore(),
]
Loading

0 comments on commit f85e731

Please sign in to comment.