From 5e2f69265441279d33c3bbbd1301c202c1b0722a Mon Sep 17 00:00:00 2001 From: Dax Fohl Date: Thu, 23 Sep 2021 07:50:34 -0700 Subject: [PATCH 01/14] Fix str/repr explosion in separated states --- .../cirq/sim/act_on_density_matrix_args.py | 9 +++ .../cirq/sim/act_on_state_vector_args.py | 8 ++ .../cirq/sim/density_matrix_simulator.py | 30 +++++++- .../cirq/sim/density_matrix_simulator_test.py | 73 ++++++++++++++++--- cirq-core/cirq/sim/simulator.py | 18 ++++- cirq-core/cirq/sim/state_vector_simulator.py | 43 ++++++++--- 6 files changed, 157 insertions(+), 24 deletions(-) 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 61625190346..8ef84366fe2 100644 --- a/cirq-core/cirq/sim/act_on_density_matrix_args.py +++ b/cirq-core/cirq/sim/act_on_density_matrix_args.py @@ -197,6 +197,15 @@ def sample( seed=seed, ) + def __repr__(self) -> str: + return ( + 'cirq.ActOnDensityMatrixArgs(' + f'target_tensor={self.target_tensor!r},' + f' qid_shape={self.qid_shape!r},' + f' qubits={self.qubits!r},' + f' log_of_measurement_results={self.log_of_measurement_results!r}' + ) + def _strat_apply_channel_to_state( action: Any, args: ActOnDensityMatrixArgs, qubits: Sequence['cirq.Qid'] 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 07f86b370d9..f6de0b47a73 100644 --- a/cirq-core/cirq/sim/act_on_state_vector_args.py +++ b/cirq-core/cirq/sim/act_on_state_vector_args.py @@ -252,6 +252,14 @@ def sample( seed=seed, ) + def __repr__(self) -> str: + return ( + 'cirq.ActOnStateVectorArgs(' + f'target_tensor={self.target_tensor!r},' + f' qubits={self.qubits!r},' + f' log_of_measurement_results={self.log_of_measurement_results!r}' + ) + def _strat_act_on_state_vector_from_apply_unitary( unitary_value: Any, diff --git a/cirq-core/cirq/sim/density_matrix_simulator.py b/cirq-core/cirq/sim/density_matrix_simulator.py index d9d38e0988a..1210d681d89 100644 --- a/cirq-core/cirq/sim/density_matrix_simulator.py +++ b/cirq-core/cirq/sim/density_matrix_simulator.py @@ -12,7 +12,7 @@ # 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, TYPE_CHECKING, Tuple, Union, Sequence, Optional, List +from typing import Any, Dict, TYPE_CHECKING, Tuple, Union, Sequence, Optional, List, cast import numpy as np @@ -362,6 +362,11 @@ def density_matrix(self, copy=True): self._density_matrix = np.reshape(matrix, (size, size)) return self._density_matrix.copy() if copy else self._density_matrix + def __repr__(self) -> str: + return ( + f'cirq.DensityMatrixStepResult(sim_state={self._sim_state!r}, dtype={self._dtype!r}' + ) + @value.value_equality(unhashable=True) class DensityMatrixSimulatorState: @@ -382,7 +387,7 @@ def _qid_shape_(self) -> Tuple[int, ...]: return self._qid_shape def _value_equality_values_(self) -> Any: - return (self.density_matrix.tolist(), self.qubit_map) + return self.density_matrix.tolist(), self.qubit_map def __repr__(self) -> str: return ( @@ -453,13 +458,30 @@ def final_density_matrix(self): def _value_equality_values_(self) -> Any: measurements = {k: v.tolist() for k, v in sorted(self.measurements.items())} - return (self.params, measurements, self._final_simulator_state) + return self.params, measurements, self._final_simulator_state def __str__(self) -> str: samples = super().__str__() - return f'measurements: {samples}\nfinal density matrix:\n{self.final_density_matrix}' + substates = self._substates + if substates is None: + return f'measurements: {samples}\nfinal density matrix:\n{self.final_density_matrix}' + ret = f'measurements: {samples}' + for substate in substates: + substate = cast(act_on_density_matrix_args.ActOnDensityMatrixArgs, substate) + tensor = substate.target_tensor + size = np.prod([tensor.shape[i] for i in range(tensor.ndim // 2)], dtype=np.int64) + dm = tensor.reshape((size, size)) + label = f'qubits: {substate.qubits}' if substate.qubits else 'phase:' + ret += f'\n\n{label}\nfinal density matrix:\n{dm}' + return ret def __repr__(self) -> str: + if self._final_step_result: + return ( + 'cirq.DensityMatrixTrialResult(' + f'params={self.params!r}, measurements={self.measurements!r}, ' + f'final_step_result={self._final_step_result!r})' + ) return ( 'cirq.DensityMatrixTrialResult(' f'params={self.params!r}, measurements={self.measurements!r}, ' diff --git a/cirq-core/cirq/sim/density_matrix_simulator_test.py b/cirq-core/cirq/sim/density_matrix_simulator_test.py index f6b969347e1..227d3a56cff 100644 --- a/cirq-core/cirq/sim/density_matrix_simulator_test.py +++ b/cirq-core/cirq/sim/density_matrix_simulator_test.py @@ -1066,10 +1066,15 @@ def test_density_matrix_trial_result_qid_shape(): def test_density_matrix_trial_result_repr(): q0 = cirq.LineQubit(0) - final_step_result = mock.Mock(cirq.StepResult) - final_step_result._simulator_state.return_value = cirq.DensityMatrixSimulatorState( - density_matrix=np.ones((2, 2)) * 0.5, qubit_map={q0: 0} + args = cirq.ActOnDensityMatrixArgs( + target_tensor=np.ones((2, 2)) * 0.5, + available_buffer=[], + qid_shape=(2,), + prng=np.random.RandomState(0), + log_of_measurement_results={}, + qubits=[q0], ) + final_step_result = cirq.DensityMatrixStepResult(args, cirq.DensityMatrixSimulator()) assert ( repr( cirq.DensityMatrixTrialResult( @@ -1081,10 +1086,13 @@ def test_density_matrix_trial_result_repr(): == "cirq.DensityMatrixTrialResult(" "params=cirq.ParamResolver({'s': 1}), " "measurements={'m': array([[1]])}, " - "final_simulator_state=cirq.DensityMatrixSimulatorState(" - "density_matrix=np.array([[0.5, 0.5], [0.5, 0.5]]), " - "qubit_map={cirq.LineQubit(0): 0}))" - "" + "final_step_result=cirq.DensityMatrixStepResult(" + "sim_state=cirq.ActOnDensityMatrixArgs(" + "target_tensor=array([[0.5, 0.5],\n [0.5, 0.5]]), " + "qid_shape=(2,), " + "qubits=(cirq.LineQubit(0),), " + "log_of_measurement_results={}, " + "dtype=)" ) @@ -1531,7 +1539,7 @@ def test_density_matrices_same_with_or_without_split_untangled_states(): q0, q1 = cirq.LineQubit.range(2) circuit = cirq.Circuit(cirq.H(q0), cirq.CX.on(q0, q1), cirq.reset(q1)) result1 = sim.simulate(circuit).final_density_matrix - sim = cirq.DensityMatrixSimulator(split_untangled_states=True) + sim = cirq.DensityMatrixSimulator() result2 = sim.simulate(circuit).final_density_matrix assert np.allclose(result1, result2) @@ -1548,12 +1556,57 @@ def test_large_untangled_okay(): _ = cirq.DensityMatrixSimulator(split_untangled_states=False).simulate(circuit) # Validate a simulation run - result = cirq.DensityMatrixSimulator(split_untangled_states=True).simulate(circuit) + result = cirq.DensityMatrixSimulator().simulate(circuit) assert set(result._final_step_result._qubits) == set(cirq.LineQubit.range(59)) # _ = result.final_density_matrix hangs (as expected) # Validate a trial run and sampling - result = cirq.DensityMatrixSimulator(split_untangled_states=True).run(circuit, repetitions=1000) + result = cirq.DensityMatrixSimulator().run(circuit, repetitions=1000) assert len(result.measurements) == 59 assert len(result.measurements['0']) == 1000 assert (result.measurements['0'] == np.full(1000, 1)).all() + + +def test_separated_states_str_does_not_merge(): + circuit = cirq.Circuit() + for i in range(2): + circuit.append(cirq.measure(cirq.LineQubit(i))) + + result = cirq.DensityMatrixSimulator().simulate(circuit) + assert ( + str(result) + == """measurements: 0=0 1=0 + +qubits: (cirq.LineQubit(0),) +final density matrix: +[[1.+0.j 0.+0.j] + [0.+0.j 0.+0.j]] + +qubits: (cirq.LineQubit(1),) +final density matrix: +[[1.+0.j 0.+0.j] + [0.+0.j 0.+0.j]] + +phase: +final density matrix: +[[1.+0.j]]""" + ) + + +def test_unseparated_states_str(): + circuit = cirq.Circuit() + for i in range(2): + circuit.append(cirq.measure(cirq.LineQubit(i))) + + result = cirq.DensityMatrixSimulator(split_untangled_states=False).simulate(circuit) + assert ( + str(result) + == """measurements: 0=0 1=0 + +qubits: (cirq.LineQubit(0), cirq.LineQubit(1)) +final density matrix: +[[1.+0.j 0.+0.j 0.+0.j 0.+0.j] + [0.+0.j 0.+0.j 0.+0.j 0.+0.j] + [0.+0.j 0.+0.j 0.+0.j 0.+0.j] + [0.+0.j 0.+0.j 0.+0.j 0.+0.j]]""" + ) diff --git a/cirq-core/cirq/sim/simulator.py b/cirq-core/cirq/sim/simulator.py index 5c14ccfb787..d33e6c349b9 100644 --- a/cirq-core/cirq/sim/simulator.py +++ b/cirq-core/cirq/sim/simulator.py @@ -858,6 +858,22 @@ def _final_simulator_state(self): self._final_simulator_state_cache = self._final_step_result._simulator_state() return self._final_simulator_state_cache + @property + def _substates(self) -> Optional[Sequence['cirq.ActOnArgs']]: + if self._final_step_result is None or not hasattr(self._final_step_result, '_sim_state'): + return None + sim_state = self._final_step_result._sim_state # type: ignore + state = sim_state # type: cirq.OperationTarget[cirq.ActOnArgs] + substates = dict() # type: Dict[cirq.ActOnArgs] + for q in state.qubits: + substates[state[q]] = None + # Add the global phase if it exists + try: + substates[state[None]] = None + except IndexError: + pass + return tuple(substates.keys()) + def __repr__(self) -> str: return ( f'cirq.SimulationTrialResult(params={self.params!r}, ' @@ -885,7 +901,7 @@ def _repr_pretty_(self, p: Any, cycle: bool) -> None: def _value_equality_values_(self) -> Any: measurements = {k: v.tolist() for k, v in sorted(self.measurements.items())} - return (self.params, measurements, self._final_simulator_state) + return self.params, measurements, self._final_simulator_state @property def qubit_map(self) -> Dict[ops.Qid, int]: diff --git a/cirq-core/cirq/sim/state_vector_simulator.py b/cirq-core/cirq/sim/state_vector_simulator.py index 2e00b37f96b..306ea728f09 100644 --- a/cirq-core/cirq/sim/state_vector_simulator.py +++ b/cirq-core/cirq/sim/state_vector_simulator.py @@ -24,7 +24,7 @@ Generic, TypeVar, Type, - Optional, + Optional, cast, ) import numpy as np @@ -121,6 +121,11 @@ def _simulator_state(self) -> 'StateVectorSimulatorState': """ raise NotImplementedError() + def __repr__(self) -> str: + return ( + f'cirq.StateVectorStepResult(sim_state={self._sim_state!r}' + ) + @value.value_equality(unhashable=True) class StateVectorSimulatorState: @@ -140,7 +145,7 @@ def __repr__(self) -> str: ) def _value_equality_values_(self) -> Any: - return (self.state_vector.tolist(), self.qubit_map) + return self.state_vector.tolist(), self.qubit_map @value.value_equality(unhashable=True) @@ -201,16 +206,29 @@ def state_vector(self): def _value_equality_values_(self): measurements = {k: v.tolist() for k, v in sorted(self.measurements.items())} - return (self.params, measurements, self._final_simulator_state) + return self.params, measurements, self._final_simulator_state def __str__(self) -> str: samples = super().__str__() - final = self.state_vector() - if len([1 for e in final if abs(e) > 0.001]) < 16: - state_vector = self.dirac_notation(3) - else: - state_vector = str(final) - return f'measurements: {samples}\noutput vector: {state_vector}' + substates = self._substates + if substates is None: + final = self.state_vector() + if len([1 for e in final if abs(e) > 0.001]) < 16: + state_vector = self.dirac_notation(3) + else: + state_vector = str(final) + return f'measurements: {samples}\noutput vector: {state_vector}' + ret = f'measurements: {samples}' + for substate in substates: + substate = cast(ActOnStateVectorArgs, substate) + final = substate.target_tensor + if len([1 for e in final if abs(e) > 0.001]) < 16: + state_vector = self.dirac_notation(3) + else: + state_vector = str(final) + label = f'qubits: {substate.qubits}' if substate.qubits else 'phase:' + ret += f'\n\n{label}\noutput vector: {state_vector}' + return ret def _repr_pretty_(self, p: Any, cycle: bool) -> None: """Text output in Jupyter.""" @@ -221,8 +239,15 @@ def _repr_pretty_(self, p: Any, cycle: bool) -> None: p.text(str(self)) def __repr__(self) -> str: + if self._final_step_result: + return ( + 'cirq.StateVectorTrialResult(' + f'measurements={self.measurements!r}, ' + f'final_step_result={self._final_step_result!r})' + ) return ( f'cirq.StateVectorTrialResult(params={self.params!r}, ' f'measurements={self.measurements!r}, ' f'final_simulator_state={self._final_simulator_state!r})' ) + From 1652e5e27740c16611fdc626773487b82f738f3b Mon Sep 17 00:00:00 2001 From: Dax Fohl Date: Thu, 23 Sep 2021 07:52:17 -0700 Subject: [PATCH 02/14] format --- cirq-core/cirq/sim/density_matrix_simulator.py | 4 +--- cirq-core/cirq/sim/state_vector_simulator.py | 8 +++----- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/cirq-core/cirq/sim/density_matrix_simulator.py b/cirq-core/cirq/sim/density_matrix_simulator.py index 1210d681d89..e1522321e68 100644 --- a/cirq-core/cirq/sim/density_matrix_simulator.py +++ b/cirq-core/cirq/sim/density_matrix_simulator.py @@ -363,9 +363,7 @@ def density_matrix(self, copy=True): return self._density_matrix.copy() if copy else self._density_matrix def __repr__(self) -> str: - return ( - f'cirq.DensityMatrixStepResult(sim_state={self._sim_state!r}, dtype={self._dtype!r}' - ) + return f'cirq.DensityMatrixStepResult(sim_state={self._sim_state!r}, dtype={self._dtype!r}' @value.value_equality(unhashable=True) diff --git a/cirq-core/cirq/sim/state_vector_simulator.py b/cirq-core/cirq/sim/state_vector_simulator.py index 306ea728f09..8369386ee0a 100644 --- a/cirq-core/cirq/sim/state_vector_simulator.py +++ b/cirq-core/cirq/sim/state_vector_simulator.py @@ -24,7 +24,8 @@ Generic, TypeVar, Type, - Optional, cast, + Optional, + cast, ) import numpy as np @@ -122,9 +123,7 @@ def _simulator_state(self) -> 'StateVectorSimulatorState': raise NotImplementedError() def __repr__(self) -> str: - return ( - f'cirq.StateVectorStepResult(sim_state={self._sim_state!r}' - ) + return f'cirq.StateVectorStepResult(sim_state={self._sim_state!r}' @value.value_equality(unhashable=True) @@ -250,4 +249,3 @@ def __repr__(self) -> str: f'measurements={self.measurements!r}, ' f'final_simulator_state={self._final_simulator_state!r})' ) - From 52d6f2c1e328484d0862c81af840acb1aa59a506 Mon Sep 17 00:00:00 2001 From: Dax Fohl Date: Thu, 23 Sep 2021 10:07:33 -0700 Subject: [PATCH 03/14] Fix str/repr explosion in state vector --- .../cirq/sim/density_matrix_simulator_test.py | 26 ++++++----- cirq-core/cirq/sim/simulator.py | 6 +-- cirq-core/cirq/sim/sparse_simulator_test.py | 44 +++++++++++++++++++ cirq-core/cirq/sim/state_vector_simulator.py | 7 ++- .../cirq/sim/state_vector_simulator_test.py | 23 ++++++---- 5 files changed, 82 insertions(+), 24 deletions(-) diff --git a/cirq-core/cirq/sim/density_matrix_simulator_test.py b/cirq-core/cirq/sim/density_matrix_simulator_test.py index 227d3a56cff..3f78d8a10f1 100644 --- a/cirq-core/cirq/sim/density_matrix_simulator_test.py +++ b/cirq-core/cirq/sim/density_matrix_simulator_test.py @@ -1568,9 +1568,12 @@ def test_large_untangled_okay(): def test_separated_states_str_does_not_merge(): - circuit = cirq.Circuit() - for i in range(2): - circuit.append(cirq.measure(cirq.LineQubit(i))) + q0, q1 = cirq.LineQubit.range(2) + circuit = cirq.Circuit( + cirq.measure(q0), + cirq.measure(q1), + cirq.X(q0), + ) result = cirq.DensityMatrixSimulator().simulate(circuit) assert ( @@ -1579,8 +1582,8 @@ def test_separated_states_str_does_not_merge(): qubits: (cirq.LineQubit(0),) final density matrix: -[[1.+0.j 0.+0.j] - [0.+0.j 0.+0.j]] +[[0.+0.j 0.+0.j] + [0.+0.j 1.+0.j]] qubits: (cirq.LineQubit(1),) final density matrix: @@ -1594,9 +1597,12 @@ def test_separated_states_str_does_not_merge(): def test_unseparated_states_str(): - circuit = cirq.Circuit() - for i in range(2): - circuit.append(cirq.measure(cirq.LineQubit(i))) + q0, q1 = cirq.LineQubit.range(2) + circuit = cirq.Circuit( + cirq.measure(q0), + cirq.measure(q1), + cirq.X(q0), + ) result = cirq.DensityMatrixSimulator(split_untangled_states=False).simulate(circuit) assert ( @@ -1605,8 +1611,8 @@ def test_unseparated_states_str(): qubits: (cirq.LineQubit(0), cirq.LineQubit(1)) final density matrix: -[[1.+0.j 0.+0.j 0.+0.j 0.+0.j] - [0.+0.j 0.+0.j 0.+0.j 0.+0.j] +[[0.+0.j 0.+0.j 0.+0.j 0.+0.j] [0.+0.j 0.+0.j 0.+0.j 0.+0.j] + [0.+0.j 0.+0.j 1.+0.j 0.+0.j] [0.+0.j 0.+0.j 0.+0.j 0.+0.j]]""" ) diff --git a/cirq-core/cirq/sim/simulator.py b/cirq-core/cirq/sim/simulator.py index d33e6c349b9..fddc00e3d94 100644 --- a/cirq-core/cirq/sim/simulator.py +++ b/cirq-core/cirq/sim/simulator.py @@ -863,13 +863,13 @@ def _substates(self) -> Optional[Sequence['cirq.ActOnArgs']]: if self._final_step_result is None or not hasattr(self._final_step_result, '_sim_state'): return None sim_state = self._final_step_result._sim_state # type: ignore - state = sim_state # type: cirq.OperationTarget[cirq.ActOnArgs] + state = sim_state # type: cirq.OperationTarget[cirq.ActOnArgs, int] substates = dict() # type: Dict[cirq.ActOnArgs] for q in state.qubits: - substates[state[q]] = None + substates[state[q]] = 0 # Add the global phase if it exists try: - substates[state[None]] = None + substates[state[None]] = 0 except IndexError: pass return tuple(substates.keys()) diff --git a/cirq-core/cirq/sim/sparse_simulator_test.py b/cirq-core/cirq/sim/sparse_simulator_test.py index c4f1d9ecd57..4aa2a199b2c 100644 --- a/cirq-core/cirq/sim/sparse_simulator_test.py +++ b/cirq-core/cirq/sim/sparse_simulator_test.py @@ -1332,3 +1332,47 @@ def test_noise_model(): result = simulator.run(circuit, repetitions=100) assert 40 <= sum(result.measurements['0'])[0] < 60 + + +def test_separated_states_str_does_not_merge(): + q0, q1 = cirq.LineQubit.range(2) + circuit = cirq.Circuit( + cirq.measure(q0), + cirq.measure(q1), + cirq.H(q0), + cirq.GlobalPhaseOperation(0+1j), + ) + + result = cirq.Simulator().simulate(circuit) + assert ( + str(result) + == """measurements: 0=0 1=0 + +qubits: (cirq.LineQubit(0),) +output vector: 0.707|0⟩ + 0.707|1⟩ + +qubits: (cirq.LineQubit(1),) +output vector: |0⟩ + +phase: +output vector: 1j|⟩""" + ) + + +def test_unseparated_states_str(): + q0, q1 = cirq.LineQubit.range(2) + circuit = cirq.Circuit( + cirq.measure(q0), + cirq.measure(q1), + cirq.H(q0), + cirq.GlobalPhaseOperation(0+1j), + ) + + result = cirq.Simulator(split_untangled_states=False).simulate(circuit) + assert ( + str(result) + == """measurements: 0=0 1=0 + +qubits: (cirq.LineQubit(0), cirq.LineQubit(1)) +output vector: 0.707j|00⟩ + 0.707j|10⟩""" + ) diff --git a/cirq-core/cirq/sim/state_vector_simulator.py b/cirq-core/cirq/sim/state_vector_simulator.py index 8369386ee0a..f83e3fc6d6c 100644 --- a/cirq-core/cirq/sim/state_vector_simulator.py +++ b/cirq-core/cirq/sim/state_vector_simulator.py @@ -30,7 +30,7 @@ import numpy as np -from cirq import ops, study, value +from cirq import ops, study, value, qis from cirq.sim import simulator, state_vector, simulator_base from cirq.sim.act_on_state_vector_args import ActOnStateVectorArgs @@ -221,8 +221,11 @@ def __str__(self) -> str: for substate in substates: substate = cast(ActOnStateVectorArgs, substate) final = substate.target_tensor + shape = final.shape + size = np.prod(shape, dtype=np.int64) + final = final.reshape(size) if len([1 for e in final if abs(e) > 0.001]) < 16: - state_vector = self.dirac_notation(3) + state_vector = qis.dirac_notation(final, 3, shape) else: state_vector = str(final) label = f'qubits: {substate.qubits}' if substate.qubits else 'phase:' diff --git a/cirq-core/cirq/sim/state_vector_simulator_test.py b/cirq-core/cirq/sim/state_vector_simulator_test.py index d533919c2fb..b06ab1cbddf 100644 --- a/cirq-core/cirq/sim/state_vector_simulator_test.py +++ b/cirq-core/cirq/sim/state_vector_simulator_test.py @@ -21,11 +21,15 @@ def test_state_vector_trial_result_repr(): - final_step_result = mock.Mock(cirq.StateVectorStepResult) - final_step_result._qubit_mapping = {} - final_step_result._simulator_state.return_value = cirq.StateVectorSimulatorState( - qubit_map={cirq.NamedQubit('a'): 0}, state_vector=np.array([0, 1]) - ) + q0 = cirq.NamedQubit('a') + args = cirq.ActOnStateVectorArgs( + target_tensor=np.array([0, 1]), + available_buffer=np.array([0, 1]), + prng=np.random.RandomState(0), + log_of_measurement_results={}, + qubits=[q0], + ) + final_step_result = cirq.SparseSimulatorStep(args, cirq.Simulator()) trial_result = cirq.StateVectorTrialResult( params=cirq.ParamResolver({'s': 1}), measurements={'m': np.array([[1]])}, @@ -33,11 +37,12 @@ def test_state_vector_trial_result_repr(): ) assert repr(trial_result) == ( "cirq.StateVectorTrialResult(" - "params=cirq.ParamResolver({'s': 1}), " "measurements={'m': array([[1]])}, " - "final_simulator_state=cirq.StateVectorSimulatorState(" - "state_vector=np.array([0, 1]), " - "qubit_map={cirq.NamedQubit('a'): 0}))" + "final_step_result=cirq.StateVectorStepResult(" + "sim_state=cirq.ActOnStateVectorArgs(" + "target_tensor=array([0, 1]), " + "qubits=(cirq.NamedQubit('a'),), " + "log_of_measurement_results={})" ) From daacdcdb62291920c4d7c2cfd45c9e2b8baef4b4 Mon Sep 17 00:00:00 2001 From: Dax Fohl Date: Thu, 23 Sep 2021 10:11:28 -0700 Subject: [PATCH 04/14] format --- cirq-core/cirq/sim/simulator.py | 4 ++-- cirq-core/cirq/sim/sparse_simulator_test.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/cirq-core/cirq/sim/simulator.py b/cirq-core/cirq/sim/simulator.py index fddc00e3d94..e3b328bdb1f 100644 --- a/cirq-core/cirq/sim/simulator.py +++ b/cirq-core/cirq/sim/simulator.py @@ -863,8 +863,8 @@ def _substates(self) -> Optional[Sequence['cirq.ActOnArgs']]: if self._final_step_result is None or not hasattr(self._final_step_result, '_sim_state'): return None sim_state = self._final_step_result._sim_state # type: ignore - state = sim_state # type: cirq.OperationTarget[cirq.ActOnArgs, int] - substates = dict() # type: Dict[cirq.ActOnArgs] + state = sim_state # type: cirq.OperationTarget[cirq.ActOnArgs] + substates = dict() # type: Dict[cirq.ActOnArgs, int] for q in state.qubits: substates[state[q]] = 0 # Add the global phase if it exists diff --git a/cirq-core/cirq/sim/sparse_simulator_test.py b/cirq-core/cirq/sim/sparse_simulator_test.py index 4aa2a199b2c..ac941509c08 100644 --- a/cirq-core/cirq/sim/sparse_simulator_test.py +++ b/cirq-core/cirq/sim/sparse_simulator_test.py @@ -1340,7 +1340,7 @@ def test_separated_states_str_does_not_merge(): cirq.measure(q0), cirq.measure(q1), cirq.H(q0), - cirq.GlobalPhaseOperation(0+1j), + cirq.GlobalPhaseOperation(0 + 1j), ) result = cirq.Simulator().simulate(circuit) @@ -1365,7 +1365,7 @@ def test_unseparated_states_str(): cirq.measure(q0), cirq.measure(q1), cirq.H(q0), - cirq.GlobalPhaseOperation(0+1j), + cirq.GlobalPhaseOperation(0 + 1j), ) result = cirq.Simulator(split_untangled_states=False).simulate(circuit) From a329d15cb97a3f06a655b32516add2384ba86c1f Mon Sep 17 00:00:00 2001 From: Dax Fohl Date: Thu, 23 Sep 2021 10:45:35 -0700 Subject: [PATCH 05/14] nondirac_str --- cirq-core/cirq/sim/sparse_simulator_test.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/cirq-core/cirq/sim/sparse_simulator_test.py b/cirq-core/cirq/sim/sparse_simulator_test.py index ac941509c08..24af677e39e 100644 --- a/cirq-core/cirq/sim/sparse_simulator_test.py +++ b/cirq-core/cirq/sim/sparse_simulator_test.py @@ -1359,6 +1359,16 @@ def test_separated_states_str_does_not_merge(): ) +def test_separable_non_dirac_str(): + circuit = cirq.Circuit() + for i in range(4): + circuit.append(cirq.H(cirq.LineQubit(i))) + circuit.append(cirq.CX(cirq.LineQubit(0), cirq.LineQubit(i + 1))) + + result = cirq.Simulator().simulate(circuit) + assert '+0.j' in str(result) + + def test_unseparated_states_str(): q0, q1 = cirq.LineQubit.range(2) circuit = cirq.Circuit( From 8c8c481c1a07186493ba55e9560e82425c5634a1 Mon Sep 17 00:00:00 2001 From: Dax Fohl Date: Thu, 23 Sep 2021 12:49:13 -0700 Subject: [PATCH 06/14] TrialResultBase --- cirq-core/cirq/__init__.py | 1 + cirq-core/cirq/contrib/quimb/mps_simulator.py | 2 +- .../cirq/protocols/json_test_data/spec.py | 1 + cirq-core/cirq/sim/__init__.py | 3 +- .../cirq/sim/clifford/clifford_simulator.py | 6 ++- .../cirq/sim/density_matrix_simulator.py | 9 +++-- .../cirq/sim/density_matrix_simulator_test.py | 13 +++++-- cirq-core/cirq/sim/simulator.py | 16 -------- cirq-core/cirq/sim/simulator_base.py | 38 +++++++++++++++++++ cirq-core/cirq/sim/simulator_base_test.py | 2 +- cirq-core/cirq/sim/state_vector_simulator.py | 11 ++++-- .../cirq/sim/state_vector_simulator_test.py | 26 ++++++++----- 12 files changed, 87 insertions(+), 41 deletions(-) diff --git a/cirq-core/cirq/__init__.py b/cirq-core/cirq/__init__.py index a3daa6a0443..d3b2a4b2610 100644 --- a/cirq-core/cirq/__init__.py +++ b/cirq-core/cirq/__init__.py @@ -416,6 +416,7 @@ SimulatesIntermediateStateVector, SimulatesSamples, SimulationTrialResult, + SimulationTrialResultBase, Simulator, SimulatorBase, SparseSimulatorStep, diff --git a/cirq-core/cirq/contrib/quimb/mps_simulator.py b/cirq-core/cirq/contrib/quimb/mps_simulator.py index 05510ac7fa6..38fa6261291 100644 --- a/cirq-core/cirq/contrib/quimb/mps_simulator.py +++ b/cirq-core/cirq/contrib/quimb/mps_simulator.py @@ -149,7 +149,7 @@ def _create_simulator_trial_result( ) -class MPSTrialResult(simulator.SimulationTrialResult): +class MPSTrialResult(simulator_base.SimulationTrialResultBase['MPSState', 'MPSState']): """A single trial reult""" def __init__( diff --git a/cirq-core/cirq/protocols/json_test_data/spec.py b/cirq-core/cirq/protocols/json_test_data/spec.py index e0c155493e3..ddeebea12e4 100644 --- a/cirq-core/cirq/protocols/json_test_data/spec.py +++ b/cirq-core/cirq/protocols/json_test_data/spec.py @@ -66,6 +66,7 @@ 'QuilFormatter', 'QuilOutput', 'SimulationTrialResult', + 'SimulationTrialResultBase', 'SparseSimulatorStep', 'StateVectorMixin', 'TextDiagramDrawer', diff --git a/cirq-core/cirq/sim/__init__.py b/cirq-core/cirq/sim/__init__.py index 02443dbeff1..e09f43eae59 100644 --- a/cirq-core/cirq/sim/__init__.py +++ b/cirq-core/cirq/sim/__init__.py @@ -64,8 +64,9 @@ ) from cirq.sim.simulator_base import ( - StepResultBase, + SimulationTrialResultBase, SimulatorBase, + StepResultBase, ) from cirq.sim.sparse_simulator import ( diff --git a/cirq-core/cirq/sim/clifford/clifford_simulator.py b/cirq-core/cirq/sim/clifford/clifford_simulator.py index daa7034b16c..87e8f6ff014 100644 --- a/cirq-core/cirq/sim/clifford/clifford_simulator.py +++ b/cirq-core/cirq/sim/clifford/clifford_simulator.py @@ -116,7 +116,11 @@ def _create_simulator_trial_result( ) -class CliffordTrialResult(simulator.SimulationTrialResult): +class CliffordTrialResult( + simulator_base.SimulationTrialResultBase[ + 'clifford.CliffordState', 'clifford.ActOnStabilizerCHFormArgs' + ] +): def __init__( self, params: study.ParamResolver, diff --git a/cirq-core/cirq/sim/density_matrix_simulator.py b/cirq-core/cirq/sim/density_matrix_simulator.py index e1522321e68..ca963d2c222 100644 --- a/cirq-core/cirq/sim/density_matrix_simulator.py +++ b/cirq-core/cirq/sim/density_matrix_simulator.py @@ -12,7 +12,7 @@ # 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, TYPE_CHECKING, Tuple, Union, Sequence, Optional, List, cast +from typing import Any, Dict, TYPE_CHECKING, Tuple, Union, Sequence, Optional, List import numpy as np @@ -396,7 +396,11 @@ def __repr__(self) -> str: @value.value_equality(unhashable=True) -class DensityMatrixTrialResult(simulator.SimulationTrialResult): +class DensityMatrixTrialResult( + simulator_base.SimulationTrialResultBase[ + 'DensityMatrixSimulatorState', act_on_density_matrix_args.ActOnDensityMatrixArgs + ] +): """A `SimulationTrialResult` for `DensityMatrixSimulator` runs. The density matrix that is stored in this result is returned in the @@ -465,7 +469,6 @@ def __str__(self) -> str: return f'measurements: {samples}\nfinal density matrix:\n{self.final_density_matrix}' ret = f'measurements: {samples}' for substate in substates: - substate = cast(act_on_density_matrix_args.ActOnDensityMatrixArgs, substate) tensor = substate.target_tensor size = np.prod([tensor.shape[i] for i in range(tensor.ndim // 2)], dtype=np.int64) dm = tensor.reshape((size, size)) diff --git a/cirq-core/cirq/sim/density_matrix_simulator_test.py b/cirq-core/cirq/sim/density_matrix_simulator_test.py index 3f78d8a10f1..cf9d47a7e43 100644 --- a/cirq-core/cirq/sim/density_matrix_simulator_test.py +++ b/cirq-core/cirq/sim/density_matrix_simulator_test.py @@ -1180,10 +1180,15 @@ def test_works_on_pauli_string(): def test_density_matrix_trial_result_str(): q0 = cirq.LineQubit(0) - final_step_result = mock.Mock(cirq.StepResult) - final_step_result._simulator_state.return_value = cirq.DensityMatrixSimulatorState( - density_matrix=np.ones((2, 2)) * 0.5, qubit_map={q0: 0} + args = cirq.ActOnDensityMatrixArgs( + target_tensor=np.ones((2, 2)) * 0.5, + available_buffer=[], + qid_shape=(2,), + prng=np.random.RandomState(0), + log_of_measurement_results={}, + qubits=[q0], ) + final_step_result = cirq.DensityMatrixStepResult(args, cirq.DensityMatrixSimulator()) result = cirq.DensityMatrixTrialResult( params=cirq.ParamResolver({}), measurements={}, final_step_result=final_step_result ) @@ -1192,7 +1197,7 @@ def test_density_matrix_trial_result_str(): # Eliminate whitespace to harden tests against this variation result_no_whitespace = str(result).replace('\n', '').replace(' ', '') assert result_no_whitespace == ( - 'measurements:(nomeasurements)finaldensitymatrix:[[0.50.5][0.50.5]]' + 'measurements:(nomeasurements)qubits:(cirq.LineQubit(0),)finaldensitymatrix:[[0.50.5][0.50.5]]' ) diff --git a/cirq-core/cirq/sim/simulator.py b/cirq-core/cirq/sim/simulator.py index e3b328bdb1f..8cd2f6aca46 100644 --- a/cirq-core/cirq/sim/simulator.py +++ b/cirq-core/cirq/sim/simulator.py @@ -858,22 +858,6 @@ def _final_simulator_state(self): self._final_simulator_state_cache = self._final_step_result._simulator_state() return self._final_simulator_state_cache - @property - def _substates(self) -> Optional[Sequence['cirq.ActOnArgs']]: - if self._final_step_result is None or not hasattr(self._final_step_result, '_sim_state'): - return None - sim_state = self._final_step_result._sim_state # type: ignore - state = sim_state # type: cirq.OperationTarget[cirq.ActOnArgs] - substates = dict() # type: Dict[cirq.ActOnArgs, int] - for q in state.qubits: - substates[state[q]] = 0 - # Add the global phase if it exists - try: - substates[state[None]] = 0 - except IndexError: - pass - return tuple(substates.keys()) - 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 20b752446b8..dbc55b0acde 100644 --- a/cirq-core/cirq/sim/simulator_base.py +++ b/cirq-core/cirq/sim/simulator_base.py @@ -43,6 +43,7 @@ SimulatesIntermediateState, SimulatesSamples, StepResult, + SimulationTrialResult, check_all_resolved, split_into_matching_protocol_then_general, ) @@ -354,3 +355,40 @@ def sample( seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None, ) -> np.ndarray: return self._sim_state.sample(qubits, repetitions, seed) + + +class SimulationTrialResultBase( + Generic[TSimulatorState, TActOnArgs], SimulationTrialResult, abc.ABC +): + """A base class for trial results.""" + + def __init__( + self, + params: study.ParamResolver, + measurements: Dict[str, np.ndarray], + final_step_result: StepResultBase[TSimulatorState, TActOnArgs], + ) -> None: + """Initializes the `SimulationTrialResultBase` class. + + Args: + params: A ParamResolver of settings used for this result. + measurements: A dictionary from measurement gate key to measurement + results. Measurement results are a numpy ndarray of actual + boolean measurement results (ordered by the qubits acted on by + the measurement gate.) + final_step_result: The step result coming from the simulation, that + can be used to get the final simulator state. + """ + super().__init__(params, measurements, final_step_result=final_step_result) + self._final_step_result_typed = final_step_result + + @property + def _substates(self) -> Optional[Sequence[TActOnArgs]]: + state = self._final_step_result_typed._sim_state + if isinstance(state, ActOnArgsContainer): + substates = dict() # type: Dict[TActOnArgs, int] + for q in state.qubits: + substates[state[q]] = 0 + substates[state[None]] = 0 + return tuple(substates.keys()) + return [state.create_merged_state()] diff --git a/cirq-core/cirq/sim/simulator_base_test.py b/cirq-core/cirq/sim/simulator_base_test.py index 4539a764245..b6eac451e5a 100644 --- a/cirq-core/cirq/sim/simulator_base_test.py +++ b/cirq-core/cirq/sim/simulator_base_test.py @@ -91,7 +91,7 @@ def _simulator_state(self) -> CountingActOnArgs: return self._merged_sim_state -class CountingTrialResult(cirq.SimulationTrialResult): +class CountingTrialResult(cirq.SimulationTrialResultBase[CountingActOnArgs, CountingActOnArgs]): pass diff --git a/cirq-core/cirq/sim/state_vector_simulator.py b/cirq-core/cirq/sim/state_vector_simulator.py index f83e3fc6d6c..542b17fe530 100644 --- a/cirq-core/cirq/sim/state_vector_simulator.py +++ b/cirq-core/cirq/sim/state_vector_simulator.py @@ -25,7 +25,6 @@ TypeVar, Type, Optional, - cast, ) import numpy as np @@ -148,7 +147,12 @@ def _value_equality_values_(self) -> Any: @value.value_equality(unhashable=True) -class StateVectorTrialResult(state_vector.StateVectorMixin, simulator.SimulationTrialResult): +class StateVectorTrialResult( + state_vector.StateVectorMixin, + simulator_base.SimulationTrialResultBase[ + StateVectorSimulatorState, 'cirq.ActOnStateVectorArgs' + ], +): """A `SimulationTrialResult` that includes the `StateVectorMixin` methods. Attributes: @@ -219,13 +223,12 @@ def __str__(self) -> str: return f'measurements: {samples}\noutput vector: {state_vector}' ret = f'measurements: {samples}' for substate in substates: - substate = cast(ActOnStateVectorArgs, substate) final = substate.target_tensor shape = final.shape size = np.prod(shape, dtype=np.int64) final = final.reshape(size) if len([1 for e in final if abs(e) > 0.001]) < 16: - state_vector = qis.dirac_notation(final, 3, shape) + state_vector = qis.dirac_notation(final, 3) else: state_vector = str(final) label = f'qubits: {substate.qubits}' if substate.qubits else 'phase:' diff --git a/cirq-core/cirq/sim/state_vector_simulator_test.py b/cirq-core/cirq/sim/state_vector_simulator_test.py index b06ab1cbddf..cca9c39097c 100644 --- a/cirq-core/cirq/sim/state_vector_simulator_test.py +++ b/cirq-core/cirq/sim/state_vector_simulator_test.py @@ -167,25 +167,31 @@ def test_state_vector_trial_state_vector_is_copy(): def test_str_big(): qs = cirq.LineQubit.range(20) - final_step_result = mock.Mock(cirq.StateVectorStepResult) - final_step_result._qubit_mapping = {} - final_step_result._simulator_state.return_value = cirq.StateVectorSimulatorState( - np.array([1] * 2 ** 10), {q: q.x for q in qs} + args = cirq.ActOnStateVectorArgs( + target_tensor=np.array([1] * 2 ** 10), + available_buffer=np.array([1] * 2 ** 10), + prng=np.random.RandomState(0), + log_of_measurement_results={}, + qubits=qs, ) + final_step_result = cirq.SparseSimulatorStep(args, cirq.Simulator()) result = cirq.StateVectorTrialResult( cirq.ParamResolver(), {}, final_step_result, ) - assert str(result).startswith('measurements: (no measurements)\noutput vector: [1 1 1 ..') + assert 'output vector: [1 1 1 ..' in str(result) def test_pretty_print(): - final_step_result = mock.Mock(cirq.StateVectorStepResult) - final_step_result._qubit_mapping = {} - final_step_result._simulator_state.return_value = cirq.StateVectorSimulatorState( - np.array([1]), {} + args = cirq.ActOnStateVectorArgs( + target_tensor=np.array([1]), + available_buffer=np.array([1]), + prng=np.random.RandomState(0), + log_of_measurement_results={}, + qubits=[], ) + final_step_result = cirq.SparseSimulatorStep(args, cirq.Simulator()) result = cirq.StateVectorTrialResult(cirq.ParamResolver(), {}, final_step_result) # Test Jupyter console output from @@ -198,7 +204,7 @@ def text(self, to_print): p = FakePrinter() result._repr_pretty_(p, False) - assert p.text_pretty == 'measurements: (no measurements)\noutput vector: |⟩' + assert p.text_pretty == 'measurements: (no measurements)\n\nphase:\noutput vector: |⟩' # Test cycle handling p = FakePrinter() From 90cd00346a4676a4e563694c568e45eaf46d4f2c Mon Sep 17 00:00:00 2001 From: Dax Fohl Date: Thu, 23 Sep 2021 12:58:52 -0700 Subject: [PATCH 07/14] cleanup --- cirq-core/cirq/contrib/quimb/mps_simulator.py | 2 +- cirq-core/cirq/sim/clifford/clifford_simulator.py | 2 +- cirq-core/cirq/sim/density_matrix_simulator.py | 5 +---- cirq-core/cirq/sim/density_matrix_simulator_test.py | 4 +++- cirq-core/cirq/sim/simulator_base.py | 2 +- cirq-core/cirq/sim/state_vector_simulator.py | 10 +--------- 6 files changed, 8 insertions(+), 17 deletions(-) diff --git a/cirq-core/cirq/contrib/quimb/mps_simulator.py b/cirq-core/cirq/contrib/quimb/mps_simulator.py index 38fa6261291..d6e3d828935 100644 --- a/cirq-core/cirq/contrib/quimb/mps_simulator.py +++ b/cirq-core/cirq/contrib/quimb/mps_simulator.py @@ -26,7 +26,7 @@ from cirq import devices, study, ops, protocols, value from cirq._compat import deprecated_parameter -from cirq.sim import simulator, simulator_base +from cirq.sim import simulator_base from cirq.sim.act_on_args import ActOnArgs if TYPE_CHECKING: diff --git a/cirq-core/cirq/sim/clifford/clifford_simulator.py b/cirq-core/cirq/sim/clifford/clifford_simulator.py index 87e8f6ff014..c1e7d70f9f7 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 study, 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( diff --git a/cirq-core/cirq/sim/density_matrix_simulator.py b/cirq-core/cirq/sim/density_matrix_simulator.py index ca963d2c222..aa9092eff4f 100644 --- a/cirq-core/cirq/sim/density_matrix_simulator.py +++ b/cirq-core/cirq/sim/density_matrix_simulator.py @@ -464,11 +464,8 @@ def _value_equality_values_(self) -> Any: def __str__(self) -> str: samples = super().__str__() - substates = self._substates - if substates is None: - return f'measurements: {samples}\nfinal density matrix:\n{self.final_density_matrix}' ret = f'measurements: {samples}' - for substate in substates: + for substate in self._substates: tensor = substate.target_tensor size = np.prod([tensor.shape[i] for i in range(tensor.ndim // 2)], dtype=np.int64) dm = tensor.reshape((size, size)) diff --git a/cirq-core/cirq/sim/density_matrix_simulator_test.py b/cirq-core/cirq/sim/density_matrix_simulator_test.py index cf9d47a7e43..bab63eae414 100644 --- a/cirq-core/cirq/sim/density_matrix_simulator_test.py +++ b/cirq-core/cirq/sim/density_matrix_simulator_test.py @@ -1197,7 +1197,9 @@ def test_density_matrix_trial_result_str(): # Eliminate whitespace to harden tests against this variation result_no_whitespace = str(result).replace('\n', '').replace(' ', '') assert result_no_whitespace == ( - 'measurements:(nomeasurements)qubits:(cirq.LineQubit(0),)finaldensitymatrix:[[0.50.5][0.50.5]]' + 'measurements:(nomeasurements)' + 'qubits:(cirq.LineQubit(0),)' + 'finaldensitymatrix:[[0.50.5][0.50.5]]' ) diff --git a/cirq-core/cirq/sim/simulator_base.py b/cirq-core/cirq/sim/simulator_base.py index dbc55b0acde..23379b2cc14 100644 --- a/cirq-core/cirq/sim/simulator_base.py +++ b/cirq-core/cirq/sim/simulator_base.py @@ -383,7 +383,7 @@ def __init__( self._final_step_result_typed = final_step_result @property - def _substates(self) -> Optional[Sequence[TActOnArgs]]: + def _substates(self) -> Sequence[TActOnArgs]: state = self._final_step_result_typed._sim_state if isinstance(state, ActOnArgsContainer): substates = dict() # type: Dict[TActOnArgs, int] diff --git a/cirq-core/cirq/sim/state_vector_simulator.py b/cirq-core/cirq/sim/state_vector_simulator.py index 542b17fe530..a43491658fc 100644 --- a/cirq-core/cirq/sim/state_vector_simulator.py +++ b/cirq-core/cirq/sim/state_vector_simulator.py @@ -213,16 +213,8 @@ def _value_equality_values_(self): def __str__(self) -> str: samples = super().__str__() - substates = self._substates - if substates is None: - final = self.state_vector() - if len([1 for e in final if abs(e) > 0.001]) < 16: - state_vector = self.dirac_notation(3) - else: - state_vector = str(final) - return f'measurements: {samples}\noutput vector: {state_vector}' ret = f'measurements: {samples}' - for substate in substates: + for substate in self._substates: final = substate.target_tensor shape = final.shape size = np.prod(shape, dtype=np.int64) From 7fef75f46e1b6cd6766aec5e505b288a8a946fce Mon Sep 17 00:00:00 2001 From: Dax Fohl Date: Thu, 23 Sep 2021 14:04:33 -0700 Subject: [PATCH 08/14] Add get_state_containing_qubit --- cirq-core/cirq/sim/simulator_base.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/cirq-core/cirq/sim/simulator_base.py b/cirq-core/cirq/sim/simulator_base.py index 23379b2cc14..02231cbdc36 100644 --- a/cirq-core/cirq/sim/simulator_base.py +++ b/cirq-core/cirq/sim/simulator_base.py @@ -382,13 +382,23 @@ def __init__( super().__init__(params, measurements, final_step_result=final_step_result) self._final_step_result_typed = final_step_result + def get_state_containing_qubit(self, qubit: 'cirq.Qid') -> TActOnArgs: + """Returns the independent state space containing the qubit. + + Args: + qubit: The qubit whose state space is required. + + Returns: + The state space containing the qubit.""" + return self._final_step_result_typed._sim_state[qubit] + @property def _substates(self) -> Sequence[TActOnArgs]: state = self._final_step_result_typed._sim_state if isinstance(state, ActOnArgsContainer): substates = dict() # type: Dict[TActOnArgs, int] for q in state.qubits: - substates[state[q]] = 0 + substates[self.get_state_containing_qubit(q)] = 0 substates[state[None]] = 0 return tuple(substates.keys()) return [state.create_merged_state()] From e362c870ba222a820336382356c29a924f69f9e8 Mon Sep 17 00:00:00 2001 From: daxfohl Date: Fri, 17 Dec 2021 14:46:21 -0800 Subject: [PATCH 09/14] Ensure eval(repr(obj)) holds --- cirq-core/cirq/_compat.py | 3 +++ .../cirq/sim/act_on_density_matrix_args.py | 10 ++++--- .../cirq/sim/act_on_state_vector_args.py | 10 ++++--- .../cirq/sim/density_matrix_simulator.py | 15 +++++++---- .../cirq/sim/density_matrix_simulator_test.py | 27 ++++++++++--------- cirq-core/cirq/sim/sparse_simulator.py | 11 ++++++-- cirq-core/cirq/sim/sparse_simulator_test.py | 4 +-- cirq-core/cirq/sim/state_vector_simulator.py | 8 +++--- .../cirq/sim/state_vector_simulator_test.py | 15 +++++++---- 9 files changed, 63 insertions(+), 40 deletions(-) diff --git a/cirq-core/cirq/_compat.py b/cirq-core/cirq/_compat.py index 8327e1d4cf4..f0f312c587c 100644 --- a/cirq-core/cirq/_compat.py +++ b/cirq-core/cirq/_compat.py @@ -69,6 +69,9 @@ def proper_repr(value: Any) -> str: f'\n)' ) + if isinstance(value, Dict): + return '{' + ','.join(f"{proper_repr(k)}: {proper_repr(v)}" for k, v in value.items()) + '}' + return repr(value) 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 706be794eeb..2e9734954cd 100644 --- a/cirq-core/cirq/sim/act_on_density_matrix_args.py +++ b/cirq-core/cirq/sim/act_on_density_matrix_args.py @@ -18,6 +18,7 @@ import numpy as np from cirq import protocols, sim +from cirq._compat import proper_repr from cirq.sim.act_on_args import ActOnArgs, strat_act_on_from_apply_decompose from cirq.linalg import transformations @@ -37,8 +38,8 @@ def __init__( target_tensor: np.ndarray, available_buffer: List[np.ndarray], qid_shape: Tuple[int, ...], - prng: np.random.RandomState, - log_of_measurement_results: Dict[str, Any], + prng: np.random.RandomState = None, + log_of_measurement_results: Dict[str, Any] = None, qubits: Sequence['cirq.Qid'] = None, ): """Inits ActOnDensityMatrixArgs. @@ -171,10 +172,11 @@ def sample( def __repr__(self) -> str: return ( 'cirq.ActOnDensityMatrixArgs(' - f'target_tensor={self.target_tensor!r},' + f'target_tensor={proper_repr(self.target_tensor)},' + f' available_buffer={proper_repr(self.available_buffer)},' f' qid_shape={self.qid_shape!r},' f' qubits={self.qubits!r},' - f' log_of_measurement_results={self.log_of_measurement_results!r}' + f' log_of_measurement_results={proper_repr(self.log_of_measurement_results)})' ) 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 432317e3027..a523047c71d 100644 --- a/cirq-core/cirq/sim/act_on_state_vector_args.py +++ b/cirq-core/cirq/sim/act_on_state_vector_args.py @@ -18,6 +18,7 @@ import numpy as np from cirq import linalg, protocols, sim +from cirq._compat import proper_repr from cirq.sim.act_on_args import ActOnArgs, strat_act_on_from_apply_decompose from cirq.linalg import transformations @@ -40,8 +41,8 @@ def __init__( self, target_tensor: np.ndarray, available_buffer: np.ndarray, - prng: np.random.RandomState, - log_of_measurement_results: Dict[str, Any], + prng: np.random.RandomState = None, + log_of_measurement_results: Dict[str, Any] = None, qubits: Sequence['cirq.Qid'] = None, ): """Inits ActOnStateVectorArgs. @@ -227,9 +228,10 @@ def sample( def __repr__(self) -> str: return ( 'cirq.ActOnStateVectorArgs(' - f'target_tensor={self.target_tensor!r},' + f'target_tensor={proper_repr(self.target_tensor)},' + f' available_buffer={proper_repr(self.available_buffer)},' f' qubits={self.qubits!r},' - f' log_of_measurement_results={self.log_of_measurement_results!r}' + f' log_of_measurement_results={proper_repr(self.log_of_measurement_results)})' ) diff --git a/cirq-core/cirq/sim/density_matrix_simulator.py b/cirq-core/cirq/sim/density_matrix_simulator.py index 45528564106..197b36d009e 100644 --- a/cirq-core/cirq/sim/density_matrix_simulator.py +++ b/cirq-core/cirq/sim/density_matrix_simulator.py @@ -17,6 +17,7 @@ import numpy as np from cirq import ops, protocols, qis, study, value +from cirq._compat import proper_repr from cirq.sim import ( simulator, act_on_density_matrix_args, @@ -283,7 +284,7 @@ class DensityMatrixStepResult( def __init__( self, sim_state: 'cirq.OperationTarget[cirq.ActOnDensityMatrixArgs]', - simulator: DensityMatrixSimulator, + simulator: DensityMatrixSimulator = None, dtype: 'DTypeLike' = np.complex64, ): """DensityMatrixStepResult. @@ -315,7 +316,8 @@ def set_density_matrix(self, density_matrix_repr: Union[int, np.ndarray]): mixed state it must be correctly sized and positive semidefinite with trace one. """ - self._sim_state = self._simulator._create_act_on_args(density_matrix_repr, self._qubits) + 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. @@ -362,7 +364,10 @@ def density_matrix(self, copy=True): return self._density_matrix.copy() if copy else self._density_matrix def __repr__(self) -> str: - return f'cirq.DensityMatrixStepResult(sim_state={self._sim_state!r}, dtype={self._dtype!r}' + return ( + f'cirq.DensityMatrixStepResult(sim_state={self._sim_state!r},' + f' dtype=np.{self._dtype.__name__})' + ) @value.value_equality(unhashable=True) @@ -476,12 +481,12 @@ def __repr__(self) -> str: if self._final_step_result: return ( 'cirq.DensityMatrixTrialResult(' - f'params={self.params!r}, measurements={self.measurements!r}, ' + f'params={self.params!r}, measurements={proper_repr(self.measurements)}, ' f'final_step_result={self._final_step_result!r})' ) return ( 'cirq.DensityMatrixTrialResult(' - f'params={self.params!r}, measurements={self.measurements!r}, ' + f'params={self.params!r}, measurements={proper_repr(self.measurements)}, ' f'final_simulator_state={self._final_simulator_state!r})' ) diff --git a/cirq-core/cirq/sim/density_matrix_simulator_test.py b/cirq-core/cirq/sim/density_matrix_simulator_test.py index 9b8d4a849a1..810cb40d08f 100644 --- a/cirq-core/cirq/sim/density_matrix_simulator_test.py +++ b/cirq-core/cirq/sim/density_matrix_simulator_test.py @@ -1095,25 +1095,26 @@ def test_density_matrix_trial_result_repr(): qubits=[q0], ) final_step_result = cirq.DensityMatrixStepResult(args, cirq.DensityMatrixSimulator()) - assert ( - repr( - cirq.DensityMatrixTrialResult( - params=cirq.ParamResolver({'s': 1}), - measurements={'m': np.array([[1]])}, - final_step_result=final_step_result, - ) - ) - == "cirq.DensityMatrixTrialResult(" + trial_result = cirq.DensityMatrixTrialResult( + params=cirq.ParamResolver({'s': 1}), + measurements={'m': np.array([[1]])}, + final_step_result=final_step_result, + ) + expected_repr = ( + "cirq.DensityMatrixTrialResult(" "params=cirq.ParamResolver({'s': 1}), " - "measurements={'m': array([[1]])}, " + "measurements={'m': np.array([[1]], dtype=np.int64)}, " "final_step_result=cirq.DensityMatrixStepResult(" "sim_state=cirq.ActOnDensityMatrixArgs(" - "target_tensor=array([[0.5, 0.5],\n [0.5, 0.5]]), " + "target_tensor=np.array([[0.5, 0.5], [0.5, 0.5]], dtype=np.float64), " + "available_buffer=[], " "qid_shape=(2,), " "qubits=(cirq.LineQubit(0),), " - "log_of_measurement_results={}, " - "dtype=)" + "log_of_measurement_results={}), " + "dtype=np.complex64))" ) + assert repr(trial_result) == expected_repr + assert eval(expected_repr) == trial_result class XAsOp(cirq.Operation): diff --git a/cirq-core/cirq/sim/sparse_simulator.py b/cirq-core/cirq/sim/sparse_simulator.py index 7a72f6e2299..7c4fa5edea6 100644 --- a/cirq-core/cirq/sim/sparse_simulator.py +++ b/cirq-core/cirq/sim/sparse_simulator.py @@ -252,7 +252,7 @@ class SparseSimulatorStep( def __init__( self, sim_state: 'cirq.OperationTarget[cirq.ActOnStateVectorArgs]', - simulator: Simulator, + simulator: Simulator = None, dtype: 'DTypeLike' = np.complex64, ): """Results of a step of the simulator. @@ -329,4 +329,11 @@ def set_state_vector(self, state: 'cirq.STATE_VECTOR_LIKE'): corresponding to a computational basis state. If a numpy array this is the full state vector. """ - self._sim_state = self._simulator._create_act_on_args(state, self._qubits) + 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},' + f' dtype=np.{self._dtype.__name__})' + ) diff --git a/cirq-core/cirq/sim/sparse_simulator_test.py b/cirq-core/cirq/sim/sparse_simulator_test.py index 9ecfffcdf7e..52d18bf85a7 100644 --- a/cirq-core/cirq/sim/sparse_simulator_test.py +++ b/cirq-core/cirq/sim/sparse_simulator_test.py @@ -1337,7 +1337,7 @@ def test_separated_states_str_does_not_merge(): cirq.measure(q0), cirq.measure(q1), cirq.H(q0), - cirq.GlobalPhaseOperation(0 + 1j), + cirq.global_phase_operation(0 + 1j), ) result = cirq.Simulator().simulate(circuit) @@ -1372,7 +1372,7 @@ def test_unseparated_states_str(): cirq.measure(q0), cirq.measure(q1), cirq.H(q0), - cirq.GlobalPhaseOperation(0 + 1j), + cirq.global_phase_operation(0 + 1j), ) result = cirq.Simulator(split_untangled_states=False).simulate(circuit) diff --git a/cirq-core/cirq/sim/state_vector_simulator.py b/cirq-core/cirq/sim/state_vector_simulator.py index 86cbbe271c8..0d739e8ef24 100644 --- a/cirq-core/cirq/sim/state_vector_simulator.py +++ b/cirq-core/cirq/sim/state_vector_simulator.py @@ -30,6 +30,7 @@ import numpy as np from cirq import ops, study, value, qis +from cirq._compat import proper_repr from cirq.sim import simulator, state_vector, simulator_base from cirq.sim.act_on_state_vector_args import ActOnStateVectorArgs @@ -121,9 +122,6 @@ def _simulator_state(self) -> 'StateVectorSimulatorState': """ raise NotImplementedError() - def __repr__(self) -> str: - return f'cirq.StateVectorStepResult(sim_state={self._sim_state!r}' - @value.value_equality(unhashable=True) class StateVectorSimulatorState: @@ -239,11 +237,11 @@ def __repr__(self) -> str: if self._final_step_result: return ( 'cirq.StateVectorTrialResult(' - f'measurements={self.measurements!r}, ' + f'params={self.params!r}, measurements={proper_repr(self.measurements)}, ' f'final_step_result={self._final_step_result!r})' ) return ( f'cirq.StateVectorTrialResult(params={self.params!r}, ' - f'measurements={self.measurements!r}, ' + f'params={self.params!r}, measurements={proper_repr(self.measurements)}, ' f'final_simulator_state={self._final_simulator_state!r})' ) diff --git a/cirq-core/cirq/sim/state_vector_simulator_test.py b/cirq-core/cirq/sim/state_vector_simulator_test.py index cca9c39097c..ce2956e02fa 100644 --- a/cirq-core/cirq/sim/state_vector_simulator_test.py +++ b/cirq-core/cirq/sim/state_vector_simulator_test.py @@ -35,15 +35,20 @@ def test_state_vector_trial_result_repr(): measurements={'m': np.array([[1]])}, final_step_result=final_step_result, ) - assert repr(trial_result) == ( + expected_repr = ( "cirq.StateVectorTrialResult(" - "measurements={'m': array([[1]])}, " - "final_step_result=cirq.StateVectorStepResult(" + "params=cirq.ParamResolver({'s': 1}), " + "measurements={'m': np.array([[1]], dtype=np.int64)}, " + "final_step_result=cirq.SparseSimulatorStep(" "sim_state=cirq.ActOnStateVectorArgs(" - "target_tensor=array([0, 1]), " + "target_tensor=np.array([0, 1], dtype=np.int64), " + "available_buffer=np.array([0, 1], dtype=np.int64), " "qubits=(cirq.NamedQubit('a'),), " - "log_of_measurement_results={})" + "log_of_measurement_results={}), " + "dtype=np.complex64))" ) + assert repr(trial_result) == expected_repr + assert eval(expected_repr) == trial_result def test_state_vector_simulator_state_repr(): From c8f4b096b19e64c145a7d54c46fa09f815c7d1ef Mon Sep 17 00:00:00 2001 From: daxfohl Date: Fri, 17 Dec 2021 14:48:41 -0800 Subject: [PATCH 10/14] substates not a property --- cirq-core/cirq/sim/density_matrix_simulator.py | 2 +- cirq-core/cirq/sim/simulator_base.py | 3 +-- cirq-core/cirq/sim/state_vector_simulator.py | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/cirq-core/cirq/sim/density_matrix_simulator.py b/cirq-core/cirq/sim/density_matrix_simulator.py index 197b36d009e..70cd530f68b 100644 --- a/cirq-core/cirq/sim/density_matrix_simulator.py +++ b/cirq-core/cirq/sim/density_matrix_simulator.py @@ -469,7 +469,7 @@ def _value_equality_values_(self) -> Any: def __str__(self) -> str: samples = super().__str__() ret = f'measurements: {samples}' - for substate in self._substates: + for substate in self._get_substates(): tensor = substate.target_tensor size = np.prod([tensor.shape[i] for i in range(tensor.ndim // 2)], dtype=np.int64) dm = tensor.reshape((size, size)) diff --git a/cirq-core/cirq/sim/simulator_base.py b/cirq-core/cirq/sim/simulator_base.py index 80270e981f2..201eeca70b9 100644 --- a/cirq-core/cirq/sim/simulator_base.py +++ b/cirq-core/cirq/sim/simulator_base.py @@ -442,8 +442,7 @@ def get_state_containing_qubit(self, qubit: 'cirq.Qid') -> TActOnArgs: The state space containing the qubit.""" return self._final_step_result_typed._sim_state[qubit] - @property - def _substates(self) -> Sequence[TActOnArgs]: + def _get_substates(self) -> Sequence[TActOnArgs]: state = self._final_step_result_typed._sim_state if isinstance(state, ActOnArgsContainer): substates = dict() # type: Dict[TActOnArgs, int] diff --git a/cirq-core/cirq/sim/state_vector_simulator.py b/cirq-core/cirq/sim/state_vector_simulator.py index 0d739e8ef24..aea039b5418 100644 --- a/cirq-core/cirq/sim/state_vector_simulator.py +++ b/cirq-core/cirq/sim/state_vector_simulator.py @@ -212,7 +212,7 @@ def _value_equality_values_(self): def __str__(self) -> str: samples = super().__str__() ret = f'measurements: {samples}' - for substate in self._substates: + for substate in self._get_substates(): final = substate.target_tensor shape = final.shape size = np.prod(shape, dtype=np.int64) From 4c27a2134237046dd32c3ea0817cd9eb9bf0942d Mon Sep 17 00:00:00 2001 From: daxfohl Date: Fri, 17 Dec 2021 14:57:41 -0800 Subject: [PATCH 11/14] fix test --- .../cirq/sim/density_matrix_simulator_test.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/cirq-core/cirq/sim/density_matrix_simulator_test.py b/cirq-core/cirq/sim/density_matrix_simulator_test.py index 810cb40d08f..9d0cfa0cd77 100644 --- a/cirq-core/cirq/sim/density_matrix_simulator_test.py +++ b/cirq-core/cirq/sim/density_matrix_simulator_test.py @@ -1226,8 +1226,16 @@ def test_density_matrix_trial_result_str(): def test_density_matrix_trial_result_repr_pretty(): q0 = cirq.LineQubit(0) - final_step_result = mock.Mock(cirq.StepResult) - final_step_result._simulator_state.return_value = cirq.DensityMatrixSimulatorState( + args = cirq.ActOnDensityMatrixArgs( + target_tensor=np.ones((2, 2)) * 0.5, + available_buffer=[], + qid_shape=(2,), + prng=np.random.RandomState(0), + log_of_measurement_results={}, + qubits=[q0], + ) + final_step_result = cirq.DensityMatrixStepResult(args, cirq.DensityMatrixSimulator()) + final_step_result._simulator_state = cirq.DensityMatrixSimulatorState( density_matrix=np.ones((2, 2)) * 0.5, qubit_map={q0: 0} ) result = cirq.DensityMatrixTrialResult( @@ -1240,7 +1248,9 @@ def test_density_matrix_trial_result_repr_pretty(): # Eliminate whitespace to harden tests against this variation result_no_whitespace = fake_printer.text_pretty.replace('\n', '').replace(' ', '') assert result_no_whitespace == ( - 'measurements:(nomeasurements)finaldensitymatrix:[[0.50.5][0.50.5]]' + 'measurements:(nomeasurements)' + 'qubits:(cirq.LineQubit(0),)' + 'finaldensitymatrix:[[0.50.5][0.50.5]]' ) cirq.testing.assert_repr_pretty(result, "cirq.DensityMatrixTrialResult(...)", cycle=True) From 2b215a7931e827e4346967d7e7a5d3127198b398 Mon Sep 17 00:00:00 2001 From: daxfohl Date: Fri, 17 Dec 2021 15:04:04 -0800 Subject: [PATCH 12/14] coverage --- cirq-core/cirq/sim/density_matrix_simulator.py | 8 +------- cirq-core/cirq/sim/state_vector_simulator.py | 10 ++-------- 2 files changed, 3 insertions(+), 15 deletions(-) diff --git a/cirq-core/cirq/sim/density_matrix_simulator.py b/cirq-core/cirq/sim/density_matrix_simulator.py index 70cd530f68b..2cecac2f76d 100644 --- a/cirq-core/cirq/sim/density_matrix_simulator.py +++ b/cirq-core/cirq/sim/density_matrix_simulator.py @@ -478,16 +478,10 @@ def __str__(self) -> str: return ret def __repr__(self) -> str: - if self._final_step_result: - return ( - 'cirq.DensityMatrixTrialResult(' - f'params={self.params!r}, measurements={proper_repr(self.measurements)}, ' - f'final_step_result={self._final_step_result!r})' - ) return ( 'cirq.DensityMatrixTrialResult(' f'params={self.params!r}, measurements={proper_repr(self.measurements)}, ' - f'final_simulator_state={self._final_simulator_state!r})' + f'final_step_result={self._final_step_result!r})' ) def _repr_pretty_(self, p: Any, cycle: bool): diff --git a/cirq-core/cirq/sim/state_vector_simulator.py b/cirq-core/cirq/sim/state_vector_simulator.py index aea039b5418..d0fcb64c8f8 100644 --- a/cirq-core/cirq/sim/state_vector_simulator.py +++ b/cirq-core/cirq/sim/state_vector_simulator.py @@ -234,14 +234,8 @@ def _repr_pretty_(self, p: Any, cycle: bool): p.text(str(self)) def __repr__(self) -> str: - if self._final_step_result: - return ( - 'cirq.StateVectorTrialResult(' - f'params={self.params!r}, measurements={proper_repr(self.measurements)}, ' - f'final_step_result={self._final_step_result!r})' - ) return ( - f'cirq.StateVectorTrialResult(params={self.params!r}, ' + 'cirq.StateVectorTrialResult(' f'params={self.params!r}, measurements={proper_repr(self.measurements)}, ' - f'final_simulator_state={self._final_simulator_state!r})' + f'final_step_result={self._final_step_result!r})' ) From a38d2a09de0068cffbb569178b7b92ea0694f375 Mon Sep 17 00:00:00 2001 From: daxfohl Date: Fri, 17 Dec 2021 15:06:50 -0800 Subject: [PATCH 13/14] test --- cirq-core/cirq/sim/sparse_simulator_test.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cirq-core/cirq/sim/sparse_simulator_test.py b/cirq-core/cirq/sim/sparse_simulator_test.py index 52d18bf85a7..9d2d1369a05 100644 --- a/cirq-core/cirq/sim/sparse_simulator_test.py +++ b/cirq-core/cirq/sim/sparse_simulator_test.py @@ -1328,7 +1328,8 @@ def test_noise_model(): noise_model = cirq.NoiseModel.from_noise_model_like(cirq.depolarize(p=0.01)) simulator = cirq.Simulator(noise=noise_model) result = simulator.run(circuit, repetitions=100) - assert 40 <= sum(result.measurements['0'])[0] < 60 + + assert 20 <= sum(result.measurements['0'])[0] < 80 def test_separated_states_str_does_not_merge(): From e2f98ca8d6ea1c541c3ccb998b31fe1f5ebbe0f4 Mon Sep 17 00:00:00 2001 From: daxfohl Date: Fri, 17 Dec 2021 15:31:09 -0800 Subject: [PATCH 14/14] fix windows --- cirq-core/cirq/sim/density_matrix_simulator_test.py | 4 ++-- cirq-core/cirq/sim/state_vector_simulator_test.py | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/cirq-core/cirq/sim/density_matrix_simulator_test.py b/cirq-core/cirq/sim/density_matrix_simulator_test.py index 9d0cfa0cd77..3e03cc19a05 100644 --- a/cirq-core/cirq/sim/density_matrix_simulator_test.py +++ b/cirq-core/cirq/sim/density_matrix_simulator_test.py @@ -1097,13 +1097,13 @@ def test_density_matrix_trial_result_repr(): final_step_result = cirq.DensityMatrixStepResult(args, cirq.DensityMatrixSimulator()) trial_result = cirq.DensityMatrixTrialResult( params=cirq.ParamResolver({'s': 1}), - measurements={'m': np.array([[1]])}, + measurements={'m': np.array([[1]], dtype=np.int32)}, final_step_result=final_step_result, ) expected_repr = ( "cirq.DensityMatrixTrialResult(" "params=cirq.ParamResolver({'s': 1}), " - "measurements={'m': np.array([[1]], dtype=np.int64)}, " + "measurements={'m': np.array([[1]], dtype=np.int32)}, " "final_step_result=cirq.DensityMatrixStepResult(" "sim_state=cirq.ActOnDensityMatrixArgs(" "target_tensor=np.array([[0.5, 0.5], [0.5, 0.5]], dtype=np.float64), " diff --git a/cirq-core/cirq/sim/state_vector_simulator_test.py b/cirq-core/cirq/sim/state_vector_simulator_test.py index ce2956e02fa..128d54ef7ca 100644 --- a/cirq-core/cirq/sim/state_vector_simulator_test.py +++ b/cirq-core/cirq/sim/state_vector_simulator_test.py @@ -23,8 +23,8 @@ def test_state_vector_trial_result_repr(): q0 = cirq.NamedQubit('a') args = cirq.ActOnStateVectorArgs( - target_tensor=np.array([0, 1]), - available_buffer=np.array([0, 1]), + target_tensor=np.array([0, 1], dtype=np.int32), + available_buffer=np.array([0, 1], dtype=np.int32), prng=np.random.RandomState(0), log_of_measurement_results={}, qubits=[q0], @@ -32,17 +32,17 @@ def test_state_vector_trial_result_repr(): final_step_result = cirq.SparseSimulatorStep(args, cirq.Simulator()) trial_result = cirq.StateVectorTrialResult( params=cirq.ParamResolver({'s': 1}), - measurements={'m': np.array([[1]])}, + measurements={'m': np.array([[1]], dtype=np.int32)}, final_step_result=final_step_result, ) expected_repr = ( "cirq.StateVectorTrialResult(" "params=cirq.ParamResolver({'s': 1}), " - "measurements={'m': np.array([[1]], dtype=np.int64)}, " + "measurements={'m': np.array([[1]], dtype=np.int32)}, " "final_step_result=cirq.SparseSimulatorStep(" "sim_state=cirq.ActOnStateVectorArgs(" - "target_tensor=np.array([0, 1], dtype=np.int64), " - "available_buffer=np.array([0, 1], dtype=np.int64), " + "target_tensor=np.array([0, 1], dtype=np.int32), " + "available_buffer=np.array([0, 1], dtype=np.int32), " "qubits=(cirq.NamedQubit('a'),), " "log_of_measurement_results={}), " "dtype=np.complex64))"