From 05790edcaf03cd3121eac7616d87abbeceb02df8 Mon Sep 17 00:00:00 2001 From: Victory Omole Date: Tue, 12 Jul 2022 01:36:43 -0500 Subject: [PATCH] More numpy types (#5683) 12 errors left Part of https://github.com/quantumlib/Cirq/issues/3767 --- cirq-core/cirq/circuits/circuit.py | 11 ++++++++--- cirq-core/cirq/circuits/circuit_operation.py | 2 +- cirq-core/cirq/contrib/quimb/state_vector.py | 2 +- cirq-core/cirq/ops/pauli_string.py | 3 ++- .../protocols/circuit_diagram_info_protocol.py | 2 +- .../cirq/protocols/trace_distance_bound.py | 4 ++-- cirq-core/cirq/qis/clifford_tableau.py | 8 ++++---- .../sim/clifford/stabilizer_state_ch_form.py | 4 ++-- cirq-core/cirq/sim/density_matrix_utils.py | 17 ++++++++--------- .../cirq/sim/state_vector_simulation_state.py | 8 +++----- .../gate_tabulation_math_utils.py | 3 ++- cirq-core/cirq/value/type_alias.py | 1 + cirq-core/cirq/vis/state_histogram.py | 4 ++-- .../engine/virtual_engine_factory.py | 2 +- 14 files changed, 38 insertions(+), 33 deletions(-) diff --git a/cirq-core/cirq/circuits/circuit.py b/cirq-core/cirq/circuits/circuit.py index f58b5d4cfed..757b4305b6e 100644 --- a/cirq-core/cirq/circuits/circuit.py +++ b/cirq-core/cirq/circuits/circuit.py @@ -30,6 +30,7 @@ Any, Callable, Mapping, + MutableSequence, cast, Dict, FrozenSet, @@ -1462,7 +1463,7 @@ def concat_ragged( # Allocate a buffer large enough to append and prepend all the circuits. pad_len = sum(len(c) for c in circuits) - n_acc - buffer = np.zeros(shape=pad_len * 2 + n_acc, dtype=object) + buffer: MutableSequence['cirq.Moment'] = [cirq.Moment()] * (pad_len * 2 + n_acc) # Put the initial circuit in the center of the buffer. offset = pad_len @@ -1601,7 +1602,11 @@ def _overlap_collision_time( def _concat_ragged_helper( - c1_offset: int, n1: int, buf: np.ndarray, c2: Sequence['cirq.Moment'], align: 'cirq.Alignment' + c1_offset: int, + n1: int, + buf: MutableSequence['cirq.Moment'], + c2: Sequence['cirq.Moment'], + align: 'cirq.Alignment', ) -> Tuple[int, int]: n2 = len(c2) shift = _overlap_collision_time(buf[c1_offset : c1_offset + n1], c2, align) @@ -2369,7 +2374,7 @@ def _resolve_parameters_( return Circuit(resolved_moments) @property - def moments(self): + def moments(self) -> Sequence['cirq.Moment']: return self._moments def with_noise(self, noise: 'cirq.NOISE_MODEL_LIKE') -> 'cirq.Circuit': diff --git a/cirq-core/cirq/circuits/circuit_operation.py b/cirq-core/cirq/circuits/circuit_operation.py index fe6f9b3b22d..afcbf9300aa 100644 --- a/cirq-core/cirq/circuits/circuit_operation.py +++ b/cirq-core/cirq/circuits/circuit_operation.py @@ -589,7 +589,7 @@ def repeat( # As CircuitOperation is immutable, this can safely return the original. return self - expected_repetition_id_length = abs(repetitions) + expected_repetition_id_length: int = np.abs(repetitions) if repetition_ids is None: if self.use_repetition_ids: diff --git a/cirq-core/cirq/contrib/quimb/state_vector.py b/cirq-core/cirq/contrib/quimb/state_vector.py index 20a4ecdbd9f..e1c8f82da73 100644 --- a/cirq-core/cirq/contrib/quimb/state_vector.py +++ b/cirq-core/cirq/contrib/quimb/state_vector.py @@ -76,7 +76,7 @@ def circuit_to_tensors( for moment in circuit.moments: for op in moment.operations: - assert op.gate._has_unitary_() + assert cirq.has_unitary(op.gate) start_inds = [f'i{qubit_frontier[q]}_q{q}' for q in op.qubits] for q in op.qubits: qubit_frontier[q] += 1 diff --git a/cirq-core/cirq/ops/pauli_string.py b/cirq-core/cirq/ops/pauli_string.py index 54093fd7884..6f366dbbf84 100644 --- a/cirq-core/cirq/ops/pauli_string.py +++ b/cirq-core/cirq/ops/pauli_string.py @@ -744,7 +744,8 @@ def _expectation_from_density_matrix_no_validation( while any(result.shape): result = np.trace(result, axis1=0, axis2=len(result.shape) // 2) - return result * self.coefficient + + return float(result * self.coefficient) def zip_items( self, other: 'cirq.PauliString[TKey]' diff --git a/cirq-core/cirq/protocols/circuit_diagram_info_protocol.py b/cirq-core/cirq/protocols/circuit_diagram_info_protocol.py index 856513da19b..3c89fb853f4 100644 --- a/cirq-core/cirq/protocols/circuit_diagram_info_protocol.py +++ b/cirq-core/cirq/protocols/circuit_diagram_info_protocol.py @@ -274,7 +274,7 @@ def format_radians(self, radians: Union[sympy.Basic, int, float]) -> str: return '0' if radians == -np.pi: return '-' + unit - if self.precision is not None: + if self.precision is not None and not isinstance(radians, sympy.Basic): quantity = self.format_real(radians / np.pi) return quantity + unit return repr(radians) diff --git a/cirq-core/cirq/protocols/trace_distance_bound.py b/cirq-core/cirq/protocols/trace_distance_bound.py index 69cd6ee89cf..4326b05d7a1 100644 --- a/cirq-core/cirq/protocols/trace_distance_bound.py +++ b/cirq-core/cirq/protocols/trace_distance_bound.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from typing import Any, TypeVar, Optional, Sequence +from typing import Any, TypeVar, Optional, Sequence, Union import numpy as np from typing_extensions import Protocol @@ -109,7 +109,7 @@ def _strat_distance_from_unitary(val: Any) -> Optional[float]: return trace_distance_from_angle_list(np.angle(np.linalg.eigvals(u))) -def trace_distance_from_angle_list(angle_list: Sequence[float]) -> float: +def trace_distance_from_angle_list(angle_list: Union[Sequence[float], np.ndarray]) -> float: """Given a list of arguments of the eigenvalues of a unitary matrix, calculates the trace distance bound of the unitary effect. diff --git a/cirq-core/cirq/qis/clifford_tableau.py b/cirq-core/cirq/qis/clifford_tableau.py index a0f19f459ef..460f260a613 100644 --- a/cirq-core/cirq/qis/clifford_tableau.py +++ b/cirq-core/cirq/qis/clifford_tableau.py @@ -19,7 +19,7 @@ from cirq import protocols from cirq._compat import proper_repr from cirq.qis import quantum_state_representation -from cirq.value import big_endian_int_to_digits, linear_dict +from cirq.value import big_endian_int_to_digits, linear_dict, random_state if TYPE_CHECKING: import cirq @@ -509,7 +509,7 @@ def destabilizers(self) -> List['cirq.DensePauliString']: generators above generate the full Pauli group on n qubits.""" return [self._row_to_dense_pauli(i) for i in range(self.n)] - def _measure(self, q, prng: np.random.RandomState = np.random) -> int: + def _measure(self, q, prng: np.random.RandomState) -> int: """Performs a projective measurement on the q'th qubit. Returns: the result (0 or 1) of the measurement. @@ -651,6 +651,6 @@ def apply_global_phase(self, coefficient: linear_dict.Scalar): pass def measure( - self, axes: Sequence[int], seed: Optional['cirq.RANDOM_STATE_OR_SEED_LIKE'] = None + self, axes: Sequence[int], seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None ) -> List[int]: - return [self._measure(axis, seed) for axis in axes] + return [self._measure(axis, random_state.parse_random_state(seed)) for axis in axes] diff --git a/cirq-core/cirq/sim/clifford/stabilizer_state_ch_form.py b/cirq-core/cirq/sim/clifford/stabilizer_state_ch_form.py index 3f2827b6359..29a6d696641 100644 --- a/cirq-core/cirq/sim/clifford/stabilizer_state_ch_form.py +++ b/cirq-core/cirq/sim/clifford/stabilizer_state_ch_form.py @@ -17,7 +17,7 @@ import cirq from cirq import protocols, qis, value -from cirq.value import big_endian_int_to_digits +from cirq.value import big_endian_int_to_digits, random_state @value.value_equality @@ -388,7 +388,7 @@ def apply_global_phase(self, coefficient: value.Scalar): def measure( self, axes: Sequence[int], seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None ) -> List[int]: - return [self._measure(axis, seed) for axis in axes] + return [self._measure(axis, random_state.parse_random_state(seed)) for axis in axes] def _phase(exponent, global_shift): diff --git a/cirq-core/cirq/sim/density_matrix_utils.py b/cirq-core/cirq/sim/density_matrix_utils.py index 8e0ea6ffca9..dc947fdc2c6 100644 --- a/cirq-core/cirq/sim/density_matrix_utils.py +++ b/cirq-core/cirq/sim/density_matrix_utils.py @@ -68,7 +68,6 @@ def sample_density_matrix( qid_shape = (2,) * num_qubits else: _validate_density_matrix_qid_shape(density_matrix, qid_shape) - num_qubits = len(qid_shape) meas_shape = _indices_shape(qid_shape, indices) if repetitions == 0 or len(indices) == 0: @@ -139,16 +138,16 @@ def measure_density_matrix( qid_shape = (2,) * num_qubits else: _validate_density_matrix_qid_shape(density_matrix, qid_shape) - num_qubits = len(qid_shape) meas_shape = _indices_shape(qid_shape, indices) - arrout: np.ndarray = ( - np.copy(density_matrix) - if out is None - else density_matrix - if out is density_matrix - else (np.copyto(dst=out, src=density_matrix), out)[-1] - ) + arrout: np.ndarray + if out is None: + arrout = np.copy(density_matrix) + elif out is density_matrix: + arrout = density_matrix + else: + np.copyto(dst=out, src=density_matrix) + arrout = out if len(indices) == 0: return ([], arrout) diff --git a/cirq-core/cirq/sim/state_vector_simulation_state.py b/cirq-core/cirq/sim/state_vector_simulation_state.py index bb470013456..63c3a916777 100644 --- a/cirq-core/cirq/sim/state_vector_simulation_state.py +++ b/cirq-core/cirq/sim/state_vector_simulation_state.py @@ -12,7 +12,6 @@ # See the License for the specific language governing permissions and # limitations under the License. """Objects and methods for acting efficiently on a state vector.""" - from typing import Any, Callable, List, Optional, Sequence, Tuple, Type, TYPE_CHECKING, Union import numpy as np @@ -225,13 +224,12 @@ def prepare_into_buffer(k: int): e.reshape(shape * 2).astype(self._state_vector.dtype) for e in kraus_operators ] p = prng.random() - weight = None - fallback_weight = 0 + fallback_weight = 0.0 fallback_weight_index = 0 - index = None + for index in range(len(kraus_tensors)): prepare_into_buffer(index) - weight = np.linalg.norm(self._buffer) ** 2 + weight = float(np.linalg.norm(self._buffer) ** 2) if weight > fallback_weight: fallback_weight_index = index diff --git a/cirq-core/cirq/transformers/heuristic_decompositions/gate_tabulation_math_utils.py b/cirq-core/cirq/transformers/heuristic_decompositions/gate_tabulation_math_utils.py index 11d613582ce..9e6c95c3fbe 100644 --- a/cirq-core/cirq/transformers/heuristic_decompositions/gate_tabulation_math_utils.py +++ b/cirq-core/cirq/transformers/heuristic_decompositions/gate_tabulation_math_utils.py @@ -3,6 +3,7 @@ from typing import Union, Sequence, Optional import numpy as np +from cirq.value import random_state _RealArraylike = Union[np.ndarray, float] @@ -58,7 +59,7 @@ def random_qubit_unitary( rng: Random number generator to be used in sampling. Default is numpy.random. """ - real_rng: np.random.RandomState = np.random if rng is None else rng + real_rng = random_state.parse_random_state(rng) theta = np.arcsin(np.sqrt(real_rng.rand(*shape))) phi_d = real_rng.rand(*shape) * np.pi * 2 diff --git a/cirq-core/cirq/value/type_alias.py b/cirq-core/cirq/value/type_alias.py index 4996e41fadd..820f4a6ecd6 100644 --- a/cirq-core/cirq/value/type_alias.py +++ b/cirq-core/cirq/value/type_alias.py @@ -13,6 +13,7 @@ # limitations under the License. from typing import Union + import sympy from cirq._doc import document diff --git a/cirq-core/cirq/vis/state_histogram.py b/cirq-core/cirq/vis/state_histogram.py index 7fdf9cd46bb..51ccfc5f073 100644 --- a/cirq-core/cirq/vis/state_histogram.py +++ b/cirq-core/cirq/vis/state_histogram.py @@ -93,8 +93,8 @@ def plot_state_histogram( tick_label, values = zip(*sorted(data.items())) else: values = np.array(data) - if not tick_label: - tick_label = np.arange(len(values)) + if tick_label is None: + tick_label = [str(i) for i in range(len(values))] ax.bar(np.arange(len(values)), values, tick_label=tick_label) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) diff --git a/cirq-google/cirq_google/engine/virtual_engine_factory.py b/cirq-google/cirq_google/engine/virtual_engine_factory.py index 7ecca420d05..dddffd427d2 100644 --- a/cirq-google/cirq_google/engine/virtual_engine_factory.py +++ b/cirq-google/cirq_google/engine/virtual_engine_factory.py @@ -393,7 +393,7 @@ def create_default_noisy_quantum_virtual_machine( try: # coverage: ignore import qsimcirq # type: ignore - simulator_class = qsimcirq.Simulator # coverage: ignore + simulator_class = qsimcirq.QSimSimulator # coverage: ignore except ImportError: simulator_class = cirq.Simulator # coverage: ignore