diff --git a/cirq-core/cirq/circuits/circuit.py b/cirq-core/cirq/circuits/circuit.py index b09495cd256..24de6a0a5d4 100644 --- a/cirq-core/cirq/circuits/circuit.py +++ b/cirq-core/cirq/circuits/circuit.py @@ -2014,7 +2014,7 @@ def transform_qubits( if callable(qubit_map): transform = qubit_map elif isinstance(qubit_map, dict): - transform = lambda q: qubit_map.get(q, q) # type: ignore + transform = lambda q: qubit_map.get(q, q) else: raise TypeError('qubit_map must be a function or dict mapping qubits to qubits.') diff --git a/cirq-core/cirq/circuits/circuit_operation.py b/cirq-core/cirq/circuits/circuit_operation.py index 98952d4a95a..d84269b0448 100644 --- a/cirq-core/cirq/circuits/circuit_operation.py +++ b/cirq-core/cirq/circuits/circuit_operation.py @@ -267,7 +267,7 @@ def replace(self, **changes) -> 'cirq.CircuitOperation': 'repeat_until': self.repeat_until, **changes, } - return CircuitOperation(**kwargs) # type: ignore + return CircuitOperation(**kwargs) def __eq__(self, other) -> bool: if not isinstance(other, type(self)): @@ -688,7 +688,7 @@ def with_qubit_mapping( if callable(qubit_map): transform = qubit_map elif isinstance(qubit_map, dict): - transform = lambda q: qubit_map.get(q, q) # type: ignore + transform = lambda q: qubit_map.get(q, q) else: raise TypeError('qubit_map must be a function or dict mapping qubits to qubits.') new_map = {} diff --git a/cirq-core/cirq/circuits/qasm_output.py b/cirq-core/cirq/circuits/qasm_output.py index 2539799540c..2ae5ae20b61 100644 --- a/cirq-core/cirq/circuits/qasm_output.py +++ b/cirq-core/cirq/circuits/qasm_output.py @@ -14,7 +14,7 @@ """Utility classes for representing QASM.""" -from typing import Callable, Dict, Optional, Sequence, Set, Tuple, Union, TYPE_CHECKING +from typing import Callable, Dict, Iterator, Optional, Sequence, Set, Tuple, Union, TYPE_CHECKING import re import numpy as np @@ -126,7 +126,7 @@ def from_matrix(mat: np.ndarray, atol=1e-8) -> 'QasmTwoQubitGate': def _unitary_(self): return protocols.unitary(self.kak) - def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE': + def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']: q0, q1 = qubits x, y, z = self.kak.interaction_coefficients a = x * -2 / np.pi + 0.5 diff --git a/cirq-core/cirq/contrib/acquaintance/bipartite.py b/cirq-core/cirq/contrib/acquaintance/bipartite.py index 53a518976f3..3d0f85e86b3 100644 --- a/cirq-core/cirq/contrib/acquaintance/bipartite.py +++ b/cirq-core/cirq/contrib/acquaintance/bipartite.py @@ -14,7 +14,7 @@ import enum import itertools -from typing import Dict, Sequence, Tuple, Union, TYPE_CHECKING +from typing import Dict, Iterator, Sequence, Tuple, Union, TYPE_CHECKING from cirq import ops @@ -72,7 +72,7 @@ def __init__( ) self.swap_gate = swap_gate - def decompose_complete(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE': + def decompose_complete(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']: swap_gate = SwapPermutationGate(self.swap_gate) if self.part_size == 1: yield acquaint(*qubits) @@ -87,7 +87,7 @@ def decompose_complete(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE': yield acquaint(*qubits[x : x + 2]) yield swap_gate(*qubits[x : x + 2]) - def decompose_matching(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE': + def decompose_matching(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']: swap_gate = SwapPermutationGate(self.swap_gate) for k in range(-self.part_size + 1, self.part_size): for x in range(abs(k), 2 * self.part_size - abs(k), 2): diff --git a/cirq-core/cirq/contrib/acquaintance/executor.py b/cirq-core/cirq/contrib/acquaintance/executor.py index a2b27d068f3..4559471cc69 100644 --- a/cirq-core/cirq/contrib/acquaintance/executor.py +++ b/cirq-core/cirq/contrib/acquaintance/executor.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from typing import DefaultDict, Dict, Sequence, TYPE_CHECKING, Optional +from typing import DefaultDict, Dict, Iterator, Sequence, TYPE_CHECKING, Optional import abc from collections import defaultdict @@ -208,7 +208,7 @@ def device(self) -> 'cirq.Device': def get_operations( self, indices: Sequence[LogicalIndex], qubits: Sequence['cirq.Qid'] - ) -> 'cirq.OP_TREE': + ) -> Iterator['cirq.OP_TREE']: index_set = frozenset(indices) if index_set in self.index_set_to_gates: gates = self.index_set_to_gates.pop(index_set) diff --git a/cirq-core/cirq/contrib/acquaintance/gates.py b/cirq-core/cirq/contrib/acquaintance/gates.py index 065646dbd3e..d532de27be8 100644 --- a/cirq-core/cirq/contrib/acquaintance/gates.py +++ b/cirq-core/cirq/contrib/acquaintance/gates.py @@ -16,7 +16,17 @@ import itertools import math import operator -from typing import Dict, Iterable, List, NamedTuple, Optional, Sequence, Tuple, TYPE_CHECKING +from typing import ( + Dict, + Iterable, + Iterator, + List, + NamedTuple, + Optional, + Sequence, + Tuple, + TYPE_CHECKING, +) from cirq import ops, protocols, value @@ -276,7 +286,7 @@ def __init__( self.part_lens = tuple(part_lens) self.acquaintance_size = acquaintance_size - def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE': + def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']: qubit_to_position = {q: i for i, q in enumerate(qubits)} mapping = dict(qubit_to_position) parts = [] diff --git a/cirq-core/cirq/contrib/acquaintance/inspection_utils.py b/cirq-core/cirq/contrib/acquaintance/inspection_utils.py index 789e65dd8aa..ba3d410fcc9 100644 --- a/cirq-core/cirq/contrib/acquaintance/inspection_utils.py +++ b/cirq-core/cirq/contrib/acquaintance/inspection_utils.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from typing import FrozenSet, Sequence, Set, TYPE_CHECKING +from typing import FrozenSet, Iterator, Sequence, Set, TYPE_CHECKING from cirq import devices @@ -46,7 +46,7 @@ def device(self) -> 'cirq.Device': def get_operations( self, indices: Sequence[LogicalIndex], qubits: Sequence['cirq.Qid'] - ) -> 'cirq.OP_TREE': + ) -> Iterator['cirq.OP_TREE']: yield AcquaintanceOperation(qubits, indices) diff --git a/cirq-core/cirq/contrib/acquaintance/permutation.py b/cirq-core/cirq/contrib/acquaintance/permutation.py index b4457a55d12..cae68eee1ef 100644 --- a/cirq-core/cirq/contrib/acquaintance/permutation.py +++ b/cirq-core/cirq/contrib/acquaintance/permutation.py @@ -18,6 +18,7 @@ cast, Dict, Iterable, + Iterator, Optional, Sequence, Tuple, @@ -152,7 +153,7 @@ def __init__(self, swap_gate: 'cirq.Gate' = ops.SWAP): def permutation(self) -> Dict[int, int]: return {0: 1, 1: 0} - def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE': + def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']: yield self.swap_gate(*qubits) def __repr__(self) -> str: @@ -201,7 +202,7 @@ def __init__( def permutation(self) -> Dict[int, int]: return self._permutation - def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE': + def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']: swap_gate = SwapPermutationGate(self.swap_gate) n_qubits = len(qubits) mapping = {i: self._permutation.get(i, i) for i in range(n_qubits)} diff --git a/cirq-core/cirq/contrib/acquaintance/shift.py b/cirq-core/cirq/contrib/acquaintance/shift.py index 29a8b01622f..0658b2ff153 100644 --- a/cirq-core/cirq/contrib/acquaintance/shift.py +++ b/cirq-core/cirq/contrib/acquaintance/shift.py @@ -13,7 +13,7 @@ # limitations under the License. import itertools -from typing import Any, Dict, Sequence, Tuple, TYPE_CHECKING +from typing import Any, Dict, Iterator, Sequence, Tuple, TYPE_CHECKING from cirq import ops, value from cirq.contrib.acquaintance.permutation import SwapPermutationGate, PermutationGate @@ -47,7 +47,7 @@ def __repr__(self) -> str: def _value_equality_values_(self) -> Any: return self.shift, self.swap_gate, self.num_qubits() - def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE': + def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']: n = len(qubits) left_shift = self.shift % n right_shift = n - left_shift diff --git a/cirq-core/cirq/contrib/acquaintance/shift_swap_network.py b/cirq-core/cirq/contrib/acquaintance/shift_swap_network.py index 4bd6617efc7..5b3554ff74b 100644 --- a/cirq-core/cirq/contrib/acquaintance/shift_swap_network.py +++ b/cirq-core/cirq/contrib/acquaintance/shift_swap_network.py @@ -14,7 +14,7 @@ import functools import itertools -from typing import Dict, Iterable, Optional, Sequence, Tuple, TYPE_CHECKING +from typing import Dict, Iterable, Iterator, Optional, Sequence, Tuple, TYPE_CHECKING from cirq import ops from cirq.contrib.acquaintance.gates import acquaint @@ -65,7 +65,7 @@ def __init__( def acquaintance_size(self) -> int: return sum(max(self.part_lens[side]) for side in ('left', 'right')) - def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE': + def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']: part_lens = list(itertools.chain(*(self.part_lens[side] for side in ('left', 'right')))) n_qubits = 0 diff --git a/cirq-core/cirq/contrib/bayesian_network/bayesian_network_gate.py b/cirq-core/cirq/contrib/bayesian_network/bayesian_network_gate.py index fe54988de4e..c6ae5e47bd3 100644 --- a/cirq-core/cirq/contrib/bayesian_network/bayesian_network_gate.py +++ b/cirq-core/cirq/contrib/bayesian_network/bayesian_network_gate.py @@ -13,7 +13,7 @@ # limitations under the License. import math -from typing import Any, cast, Dict, List, Optional, Sequence, Tuple, TYPE_CHECKING, Union +from typing import Any, cast, Dict, Iterator, List, Optional, Sequence, Tuple, TYPE_CHECKING, Union from sympy.combinatorics import GrayCode @@ -158,7 +158,7 @@ def __init__( raise ValueError('Conditional prob should be between 0 and 1.') self._arc_probs = arc_probs - def _decompose_(self, qubits: Sequence['raw_types.Qid']) -> 'cirq.OP_TREE': + def _decompose_(self, qubits: Sequence['raw_types.Qid']) -> Iterator['cirq.OP_TREE']: parameter_names = [init_prob[0] for init_prob in self._init_probs] qubit_map = dict(zip(parameter_names, qubits)) diff --git a/cirq-core/cirq/contrib/paulistring/separate.py b/cirq-core/cirq/contrib/paulistring/separate.py index d559d5afa9b..e6acb5fabe6 100644 --- a/cirq-core/cirq/contrib/paulistring/separate.py +++ b/cirq-core/cirq/contrib/paulistring/separate.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from typing import Tuple +from typing import Iterator, Tuple from cirq import ops, circuits, transformers @@ -89,7 +89,7 @@ def pauli_string_half(circuit: circuits.Circuit) -> circuits.Circuit: ) -def _pull_non_clifford_before(circuit: circuits.Circuit) -> ops.OP_TREE: +def _pull_non_clifford_before(circuit: circuits.Circuit) -> Iterator[ops.OP_TREE]: def _iter_ops_range_reversed(moment_end): for i in reversed(range(moment_end)): moment = circuit[i] diff --git a/cirq-core/cirq/experiments/random_quantum_circuit_generation.py b/cirq-core/cirq/experiments/random_quantum_circuit_generation.py index f559c72a825..8a5d92058eb 100644 --- a/cirq-core/cirq/experiments/random_quantum_circuit_generation.py +++ b/cirq-core/cirq/experiments/random_quantum_circuit_generation.py @@ -21,6 +21,7 @@ Container, Dict, Iterable, + Iterator, List, Sequence, TYPE_CHECKING, @@ -691,7 +692,7 @@ def _two_qubit_layer( ], layer: GridInteractionLayer, prng: 'np.random.RandomState', -) -> 'cirq.OP_TREE': +) -> Iterator['cirq.OP_TREE']: for a, b in coupled_qubit_pairs: if (a, b) in layer or (b, a) in layer: yield two_qubit_op_factory(a, b, prng) diff --git a/cirq-core/cirq/interop/quirk/cells/control_cells.py b/cirq-core/cirq/interop/quirk/cells/control_cells.py index 3bc23e210c3..2f8adedacdc 100644 --- a/cirq-core/cirq/interop/quirk/cells/control_cells.py +++ b/cirq-core/cirq/interop/quirk/cells/control_cells.py @@ -109,7 +109,7 @@ def modify_column(self, column: List[Optional['Cell']]): elif gate is not None: column[i] = gate.controlled_by(self.qubits[0]) - def basis_change(self) -> 'cirq.OP_TREE': + def basis_change(self) -> Iterator['cirq.OP_TREE']: yield from self._basis_change # Temporarily move the ZZZ..Z parity observable onto a single qubit. diff --git a/cirq-core/cirq/interop/quirk/cells/parse.py b/cirq-core/cirq/interop/quirk/cells/parse.py index 8d680ef15fb..f69e5cd2c96 100644 --- a/cirq-core/cirq/interop/quirk/cells/parse.py +++ b/cirq-core/cirq/interop/quirk/cells/parse.py @@ -191,7 +191,9 @@ def feed_op(could_be_binary: bool, token: Any) -> None: elif token.unary_action is not None: burn_ops(token.priority) vals.append(None) - ops.append(_HangingNode(func=lambda _, b: token.unary_action(b), weight=np.inf)) + # this avoids mypy complaint about None not being callable + token_unary_action = token.unary_action + ops.append(_HangingNode(func=lambda _, b: token_unary_action(b), weight=np.inf)) elif token.binary_action is not None: raise ValueError("Bad expression: binary op in bad spot.\ntext={text!r}") diff --git a/cirq-core/cirq/ops/diagonal_gate.py b/cirq-core/cirq/ops/diagonal_gate.py index ec5e6ad44d0..57a15761013 100644 --- a/cirq-core/cirq/ops/diagonal_gate.py +++ b/cirq-core/cirq/ops/diagonal_gate.py @@ -166,7 +166,7 @@ def _decompose_for_basis( self, index: int, bit_flip: int, theta: 'cirq.TParamVal', qubits: Sequence['cirq.Qid'] ) -> Iterator[Union['cirq.ZPowGate', 'cirq.CXPowGate']]: if index == 0: - return [] + return largest_digit = self._num_qubits_() - (len(bin(index)) - 2) yield common_gates.rz(2 * theta)(qubits[largest_digit]) _flip_bit = self._num_qubits_() - bit_flip - 1 diff --git a/cirq-core/cirq/ops/fsim_gate.py b/cirq-core/cirq/ops/fsim_gate.py index 01cf6291b8b..e323d971f48 100644 --- a/cirq-core/cirq/ops/fsim_gate.py +++ b/cirq-core/cirq/ops/fsim_gate.py @@ -23,7 +23,7 @@ import cmath import math -from typing import AbstractSet, Any, Dict, Optional, Tuple +from typing import AbstractSet, Any, Dict, Iterator, Optional, Tuple import numpy as np import sympy @@ -187,7 +187,7 @@ def _apply_unitary_(self, args: 'cirq.ApplyUnitaryArgs') -> Optional[np.ndarray] out[ii] *= cmath.exp(-1j * self.phi) return out - def _decompose_(self, qubits) -> 'cirq.OP_TREE': + def _decompose_(self, qubits) -> Iterator['cirq.OP_TREE']: a, b = qubits xx = cirq.XXPowGate(exponent=self.theta / np.pi, global_shift=-0.5) yy = cirq.YYPowGate(exponent=self.theta / np.pi, global_shift=-0.5) @@ -452,7 +452,7 @@ def _apply_unitary_(self, args: 'cirq.ApplyUnitaryArgs') -> Optional[np.ndarray] out[ii] *= f * f return out - def _decompose_(self, qubits) -> 'cirq.OP_TREE': + def _decompose_(self, qubits) -> Iterator['cirq.OP_TREE']: """Decomposes self into Z rotations and FSimGate. Note that Z rotations returned by this method have unusual global phase diff --git a/cirq-core/cirq/ops/linear_combinations.py b/cirq-core/cirq/ops/linear_combinations.py index e0f4e80b7ee..d830b68a789 100644 --- a/cirq-core/cirq/ops/linear_combinations.py +++ b/cirq-core/cirq/ops/linear_combinations.py @@ -805,7 +805,7 @@ def __imul__(self, other: PauliSumLike): if not isinstance(other, (numbers.Complex, PauliString, PauliSum)): return NotImplemented if isinstance(other, numbers.Complex): - self._linear_dict *= other + self._linear_dict *= complex(other) elif isinstance(other, PauliString): temp = PauliSum.from_pauli_strings([term * other for term in self]) self._linear_dict = temp._linear_dict diff --git a/cirq-core/cirq/ops/parity_gates.py b/cirq-core/cirq/ops/parity_gates.py index 4522a0a04e0..b19163cd695 100644 --- a/cirq-core/cirq/ops/parity_gates.py +++ b/cirq-core/cirq/ops/parity_gates.py @@ -14,7 +14,7 @@ """Quantum gates that phase with respect to product-of-pauli observables.""" -from typing import Any, Dict, List, Optional, Tuple, Union, TYPE_CHECKING, Sequence +from typing import Any, Dict, List, Iterator, Optional, Tuple, Union, TYPE_CHECKING, Sequence from typing_extensions import Self import numpy as np @@ -118,7 +118,7 @@ def _decompose_into_clifford_with_qubits_(self, qubits): def _has_stabilizer_effect_(self) -> bool: return self.exponent % 2 in (0, 0.5, 1, 1.5) - def _decompose_(self, qubits: Tuple['cirq.Qid', ...]) -> 'cirq.OP_TREE': + def _decompose_(self, qubits: Tuple['cirq.Qid', ...]) -> Iterator['cirq.OP_TREE']: yield common_gates.YPowGate(exponent=-0.5).on_each(*qubits) yield ZZPowGate(exponent=self.exponent, global_shift=self.global_shift)(*qubits) yield common_gates.YPowGate(exponent=0.5).on_each(*qubits) @@ -227,7 +227,7 @@ def _decompose_into_clifford_with_qubits_(self, qubits): def _has_stabilizer_effect_(self) -> bool: return self.exponent % 2 in (0, 0.5, 1, 1.5) - def _decompose_(self, qubits: Tuple['cirq.Qid', ...]) -> 'cirq.OP_TREE': + def _decompose_(self, qubits: Tuple['cirq.Qid', ...]) -> Iterator['cirq.OP_TREE']: yield common_gates.XPowGate(exponent=0.5).on_each(*qubits) yield ZZPowGate(exponent=self.exponent, global_shift=self.global_shift)(*qubits) yield common_gates.XPowGate(exponent=-0.5).on_each(*qubits) diff --git a/cirq-core/cirq/ops/pauli_interaction_gate.py b/cirq-core/cirq/ops/pauli_interaction_gate.py index f6a0eb71bc8..963176bfb07 100644 --- a/cirq-core/cirq/ops/pauli_interaction_gate.py +++ b/cirq-core/cirq/ops/pauli_interaction_gate.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from typing import Any, Dict, List, Sequence, TYPE_CHECKING, Tuple +from typing import Any, Dict, Iterator, List, Sequence, TYPE_CHECKING, Tuple import numpy as np @@ -108,7 +108,7 @@ def _eigen_components(self) -> List[Tuple[float, np.ndarray]]: comp0 = np.eye(4) - comp1 return [(0, comp0), (1, comp1)] - def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE': + def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']: q0, q1 = qubits right_gate0 = SingleQubitCliffordGate.from_single_map(z_to=(self.pauli0, self.invert0)) right_gate1 = SingleQubitCliffordGate.from_single_map(z_to=(self.pauli1, self.invert1)) diff --git a/cirq-core/cirq/ops/pauli_measurement_gate.py b/cirq-core/cirq/ops/pauli_measurement_gate.py index 8a53047c514..291371445d6 100644 --- a/cirq-core/cirq/ops/pauli_measurement_gate.py +++ b/cirq-core/cirq/ops/pauli_measurement_gate.py @@ -17,6 +17,7 @@ Dict, FrozenSet, Iterable, + Iterator, Mapping, Tuple, Sequence, @@ -144,7 +145,7 @@ def observable(self) -> 'cirq.DensePauliString': def _decompose_( self, qubits: Tuple['cirq.Qid', ...] - ) -> 'protocols.decompose_protocol.DecomposeResult': + ) -> Iterator['protocols.decompose_protocol.DecomposeResult']: any_qubit = qubits[0] to_z_ops = op_tree.freeze_op_tree(self._observable.on(*qubits).to_z_basis_ops()) xor_decomp = tuple(pauli_string_phasor.xor_nonlocal_decompose(qubits, any_qubit)) diff --git a/cirq-core/cirq/ops/pauli_string_phasor.py b/cirq-core/cirq/ops/pauli_string_phasor.py index 7497b165fb2..1cbb232350d 100644 --- a/cirq-core/cirq/ops/pauli_string_phasor.py +++ b/cirq-core/cirq/ops/pauli_string_phasor.py @@ -351,7 +351,7 @@ def _to_z_basis_ops(self, qubits: Sequence['cirq.Qid']) -> Iterator[raw_types.Op """Returns operations to convert the qubits to the computational basis.""" return self.dense_pauli_string.on(*qubits).to_z_basis_ops() - def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE': + def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']: if len(self.dense_pauli_string) <= 0: return any_qubit = qubits[0] diff --git a/cirq-core/cirq/ops/permutation_gate.py b/cirq-core/cirq/ops/permutation_gate.py index e8eddcc0381..a7a40501fee 100644 --- a/cirq-core/cirq/ops/permutation_gate.py +++ b/cirq-core/cirq/ops/permutation_gate.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from typing import Any, Dict, Sequence, Tuple, TYPE_CHECKING +from typing import Any, Dict, Iterator, Sequence, Tuple, TYPE_CHECKING from cirq import protocols, value from cirq.ops import raw_types, swap_gates @@ -73,7 +73,7 @@ def num_qubits(self): def _has_unitary_(self): return True - def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE': + def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']: permutation = [p for p in self.permutation] for i in range(len(permutation)): diff --git a/cirq-core/cirq/ops/phased_iswap_gate.py b/cirq-core/cirq/ops/phased_iswap_gate.py index f216ef8ae52..54c8eefca88 100644 --- a/cirq-core/cirq/ops/phased_iswap_gate.py +++ b/cirq-core/cirq/ops/phased_iswap_gate.py @@ -13,7 +13,7 @@ # limitations under the License. """ISWAPPowGate conjugated by tensor product Rz(phi) and Rz(-phi).""" -from typing import AbstractSet, Any, cast, Dict, List, Optional, Sequence, Tuple, Union +from typing import AbstractSet, Any, cast, Dict, Iterator, List, Optional, Sequence, Tuple, Union import numpy as np import sympy @@ -157,7 +157,7 @@ def _apply_unitary_(self, args: 'protocols.ApplyUnitaryArgs') -> Optional[np.nda ) return args.available_buffer - def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE': + def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']: if len(qubits) != 2: raise ValueError(f'Expected two qubits, got {len(qubits)}') a, b = qubits diff --git a/cirq-core/cirq/ops/phased_x_z_gate.py b/cirq-core/cirq/ops/phased_x_z_gate.py index 20711939fd3..bf447b63745 100644 --- a/cirq-core/cirq/ops/phased_x_z_gate.py +++ b/cirq-core/cirq/ops/phased_x_z_gate.py @@ -11,7 +11,8 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -from typing import AbstractSet, Any, Dict, Optional, Sequence, Tuple, TYPE_CHECKING, Union + +from typing import AbstractSet, Any, Dict, Iterator, Optional, Sequence, Tuple, TYPE_CHECKING, Union import numbers import numpy as np @@ -188,7 +189,7 @@ def _unitary_(self) -> Optional[np.ndarray]: z_post = protocols.unitary(ops.Z ** (self._axis_phase_exponent + self._z_exponent)) return z_post @ x @ z_pre - def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE': + def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']: q = qubits[0] yield ops.Z(q) ** -self._axis_phase_exponent yield ops.X(q) ** self._x_exponent diff --git a/cirq-core/cirq/ops/projector.py b/cirq-core/cirq/ops/projector.py index 2e301591e4d..68fcef9621c 100644 --- a/cirq-core/cirq/ops/projector.py +++ b/cirq-core/cirq/ops/projector.py @@ -1,5 +1,6 @@ # pylint: disable=wrong-or-nonexistent-copyright-notice import itertools +import math from typing import Any, Dict, Iterable, List, Mapping, Optional, Union import numpy as np @@ -61,7 +62,7 @@ def matrix(self, projector_qids: Optional[Iterable[raw_types.Qid]] = None) -> cs for qid in projector_qids ] - total_d = np.prod([qid.dimension for qid in projector_qids], dtype=np.int64) + total_d = math.prod(qid.dimension for qid in projector_qids) ones_idx = [] for idx in itertools.product(*idx_to_keep): diff --git a/cirq-core/cirq/ops/raw_types.py b/cirq-core/cirq/ops/raw_types.py index abc2397fff1..5c67151a826 100644 --- a/cirq-core/cirq/ops/raw_types.py +++ b/cirq-core/cirq/ops/raw_types.py @@ -580,7 +580,7 @@ def transform_qubits( if callable(qubit_map): transform = qubit_map elif isinstance(qubit_map, dict): - transform = lambda q: qubit_map.get(q, q) # type: ignore + transform = lambda q: qubit_map.get(q, q) else: raise TypeError('qubit_map must be a function or dict mapping qubits to qubits.') return self.with_qubits(*(transform(q) for q in self.qubits)) diff --git a/cirq-core/cirq/ops/three_qubit_gates.py b/cirq-core/cirq/ops/three_qubit_gates.py index 4b1aa00b280..a4f8250dba5 100644 --- a/cirq-core/cirq/ops/three_qubit_gates.py +++ b/cirq-core/cirq/ops/three_qubit_gates.py @@ -19,6 +19,7 @@ Any, Collection, Dict, + Iterator, List, Optional, Sequence, @@ -573,7 +574,7 @@ def _decompose_(self, qubits): def _decompose_inside_control( self, target1: 'cirq.Qid', control: 'cirq.Qid', target2: 'cirq.Qid' - ) -> 'cirq.OP_TREE': + ) -> Iterator['cirq.OP_TREE']: """A decomposition assuming the control separates the targets. target1: ─@─X───────T──────@────────@─────────X───@─────X^-0.5─ @@ -617,7 +618,7 @@ def _apply_unitary_(self, args: 'protocols.ApplyUnitaryArgs') -> np.ndarray: def _decompose_outside_control( self, control: 'cirq.Qid', near_target: 'cirq.Qid', far_target: 'cirq.Qid' - ) -> 'cirq.OP_TREE': + ) -> Iterator['cirq.OP_TREE']: """A decomposition assuming one of the targets is in the middle. control: ───T──────@────────@───@────────────@──────────────── diff --git a/cirq-core/cirq/ops/two_qubit_diagonal_gate.py b/cirq-core/cirq/ops/two_qubit_diagonal_gate.py index 7b7e34ebc9f..ba7d6755dea 100644 --- a/cirq-core/cirq/ops/two_qubit_diagonal_gate.py +++ b/cirq-core/cirq/ops/two_qubit_diagonal_gate.py @@ -18,7 +18,7 @@ passed as a list. """ -from typing import AbstractSet, Any, Dict, Tuple, Optional, Sequence, TYPE_CHECKING +from typing import AbstractSet, Any, Dict, Iterator, Tuple, Optional, Sequence, TYPE_CHECKING import numpy as np import sympy @@ -93,7 +93,7 @@ def _unitary_(self) -> Optional[np.ndarray]: return None return np.diag([np.exp(1j * angle) for angle in self._diag_angles_radians]) - def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE': + def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']: x0, x1, x2, x3 = self._diag_angles_radians q0, q1 = qubits yield common_gates.ZPowGate(exponent=x2 / np.pi).on(q0) diff --git a/cirq-core/cirq/ops/uniform_superposition_gate.py b/cirq-core/cirq/ops/uniform_superposition_gate.py index 87349482704..3c9e8f680ac 100644 --- a/cirq-core/cirq/ops/uniform_superposition_gate.py +++ b/cirq-core/cirq/ops/uniform_superposition_gate.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from typing import Sequence, Any, Dict, TYPE_CHECKING +from typing import Iterator, Sequence, Any, Dict, TYPE_CHECKING import numpy as np from cirq.ops.common_gates import H, ry @@ -58,7 +58,7 @@ def __init__(self, m_value: int, num_qubits: int) -> None: self._m_value = m_value self._num_qubits = num_qubits - def _decompose_(self, qubits: Sequence["cirq.Qid"]) -> "cirq.OP_TREE": + def _decompose_(self, qubits: Sequence["cirq.Qid"]) -> Iterator["cirq.OP_TREE"]: """Decomposes the gate into a sequence of standard gates. Implements the construction from https://arxiv.org/pdf/2306.11747. """ diff --git a/cirq-core/cirq/sim/state_vector_test.py b/cirq-core/cirq/sim/state_vector_test.py index 206c2220fb1..708fdc6e03b 100644 --- a/cirq-core/cirq/sim/state_vector_test.py +++ b/cirq-core/cirq/sim/state_vector_test.py @@ -14,16 +14,24 @@ """Tests for state_vector.py""" import itertools -from typing import Optional -import pytest +from typing import Iterator, Optional +from unittest import mock import numpy as np +import pytest import cirq import cirq.testing from cirq import linalg +@pytest.fixture +def use_np_transpose(request) -> Iterator[bool]: + value: bool = request.param + with mock.patch.object(linalg, 'can_numpy_support_shape', lambda shape: value): + yield value + + def test_state_mixin(): class TestClass(cirq.StateVectorMixin): def state_vector(self, copy: Optional[bool] = None) -> np.ndarray: @@ -173,9 +181,10 @@ def test_sample_no_indices_repetitions(): ) -@pytest.mark.parametrize('use_np_transpose', [False, True]) +@pytest.mark.parametrize('use_np_transpose', [False, True], indirect=True) def test_measure_state_computational_basis(use_np_transpose: bool): - linalg.can_numpy_support_shape = lambda s: use_np_transpose + # verify patching of can_numpy_support_shape in the use_np_transpose fixture + assert linalg.can_numpy_support_shape([1]) is use_np_transpose results = [] for x in range(8): initial_state = cirq.to_valid_state_vector(x, 3) @@ -186,9 +195,8 @@ def test_measure_state_computational_basis(use_np_transpose: bool): assert results == expected -@pytest.mark.parametrize('use_np_transpose', [False, True]) +@pytest.mark.parametrize('use_np_transpose', [False, True], indirect=True) def test_measure_state_reshape(use_np_transpose: bool): - linalg.can_numpy_support_shape = lambda s: use_np_transpose results = [] for x in range(8): initial_state = np.reshape(cirq.to_valid_state_vector(x, 3), [2] * 3) @@ -199,9 +207,8 @@ def test_measure_state_reshape(use_np_transpose: bool): assert results == expected -@pytest.mark.parametrize('use_np_transpose', [False, True]) +@pytest.mark.parametrize('use_np_transpose', [False, True], indirect=True) def test_measure_state_partial_indices(use_np_transpose: bool): - linalg.can_numpy_support_shape = lambda s: use_np_transpose for index in range(3): for x in range(8): initial_state = cirq.to_valid_state_vector(x, 3) @@ -210,9 +217,8 @@ def test_measure_state_partial_indices(use_np_transpose: bool): assert bits == [bool(1 & (x >> (2 - index)))] -@pytest.mark.parametrize('use_np_transpose', [False, True]) +@pytest.mark.parametrize('use_np_transpose', [False, True], indirect=True) def test_measure_state_partial_indices_order(use_np_transpose: bool): - linalg.can_numpy_support_shape = lambda s: use_np_transpose for x in range(8): initial_state = cirq.to_valid_state_vector(x, 3) bits, state = cirq.measure_state_vector(initial_state, [2, 1]) @@ -220,9 +226,8 @@ def test_measure_state_partial_indices_order(use_np_transpose: bool): assert bits == [bool(1 & (x >> 0)), bool(1 & (x >> 1))] -@pytest.mark.parametrize('use_np_transpose', [False, True]) +@pytest.mark.parametrize('use_np_transpose', [False, True], indirect=True) def test_measure_state_partial_indices_all_orders(use_np_transpose: bool): - linalg.can_numpy_support_shape = lambda s: use_np_transpose for perm in itertools.permutations([0, 1, 2]): for x in range(8): initial_state = cirq.to_valid_state_vector(x, 3) @@ -231,9 +236,8 @@ def test_measure_state_partial_indices_all_orders(use_np_transpose: bool): assert bits == [bool(1 & (x >> (2 - p))) for p in perm] -@pytest.mark.parametrize('use_np_transpose', [False, True]) +@pytest.mark.parametrize('use_np_transpose', [False, True], indirect=True) def test_measure_state_collapse(use_np_transpose: bool): - linalg.can_numpy_support_shape = lambda s: use_np_transpose initial_state = np.zeros(8, dtype=np.complex64) initial_state[0] = 1 / np.sqrt(2) initial_state[2] = 1 / np.sqrt(2) @@ -256,9 +260,8 @@ def test_measure_state_collapse(use_np_transpose: bool): assert bits == [False] -@pytest.mark.parametrize('use_np_transpose', [False, True]) +@pytest.mark.parametrize('use_np_transpose', [False, True], indirect=True) def test_measure_state_seed(use_np_transpose: bool): - linalg.can_numpy_support_shape = lambda s: use_np_transpose n = 10 initial_state = np.ones(2**n) / 2 ** (n / 2) @@ -277,9 +280,8 @@ def test_measure_state_seed(use_np_transpose: bool): np.testing.assert_allclose(state1, state2) -@pytest.mark.parametrize('use_np_transpose', [False, True]) +@pytest.mark.parametrize('use_np_transpose', [False, True], indirect=True) def test_measure_state_out_is_state(use_np_transpose: bool): - linalg.can_numpy_support_shape = lambda s: use_np_transpose initial_state = np.zeros(8, dtype=np.complex64) initial_state[0] = 1 / np.sqrt(2) initial_state[2] = 1 / np.sqrt(2) @@ -290,9 +292,8 @@ def test_measure_state_out_is_state(use_np_transpose: bool): assert state is initial_state -@pytest.mark.parametrize('use_np_transpose', [False, True]) +@pytest.mark.parametrize('use_np_transpose', [False, True], indirect=True) def test_measure_state_out_is_not_state(use_np_transpose: bool): - linalg.can_numpy_support_shape = lambda s: use_np_transpose initial_state = np.zeros(8, dtype=np.complex64) initial_state[0] = 1 / np.sqrt(2) initial_state[2] = 1 / np.sqrt(2) @@ -302,18 +303,16 @@ def test_measure_state_out_is_not_state(use_np_transpose: bool): assert out is state -@pytest.mark.parametrize('use_np_transpose', [False, True]) +@pytest.mark.parametrize('use_np_transpose', [False, True], indirect=True) def test_measure_state_not_power_of_two(use_np_transpose: bool): - linalg.can_numpy_support_shape = lambda s: use_np_transpose with pytest.raises(ValueError, match='3'): _, _ = cirq.measure_state_vector(np.array([1, 0, 0]), [1]) with pytest.raises(ValueError, match='5'): cirq.measure_state_vector(np.array([0, 1, 0, 0, 0]), [1]) -@pytest.mark.parametrize('use_np_transpose', [False, True]) +@pytest.mark.parametrize('use_np_transpose', [False, True], indirect=True) def test_measure_state_index_out_of_range(use_np_transpose: bool): - linalg.can_numpy_support_shape = lambda s: use_np_transpose state = cirq.to_valid_state_vector(0, 3) with pytest.raises(IndexError, match='-2'): cirq.measure_state_vector(state, [-2]) @@ -321,18 +320,16 @@ def test_measure_state_index_out_of_range(use_np_transpose: bool): cirq.measure_state_vector(state, [3]) -@pytest.mark.parametrize('use_np_transpose', [False, True]) +@pytest.mark.parametrize('use_np_transpose', [False, True], indirect=True) def test_measure_state_no_indices(use_np_transpose: bool): - linalg.can_numpy_support_shape = lambda s: use_np_transpose initial_state = cirq.to_valid_state_vector(0, 3) bits, state = cirq.measure_state_vector(initial_state, []) assert [] == bits np.testing.assert_almost_equal(state, initial_state) -@pytest.mark.parametrize('use_np_transpose', [False, True]) +@pytest.mark.parametrize('use_np_transpose', [False, True], indirect=True) def test_measure_state_no_indices_out_is_state(use_np_transpose: bool): - linalg.can_numpy_support_shape = lambda s: use_np_transpose initial_state = cirq.to_valid_state_vector(0, 3) bits, state = cirq.measure_state_vector(initial_state, [], out=initial_state) assert [] == bits @@ -340,9 +337,8 @@ def test_measure_state_no_indices_out_is_state(use_np_transpose: bool): assert state is initial_state -@pytest.mark.parametrize('use_np_transpose', [False, True]) +@pytest.mark.parametrize('use_np_transpose', [False, True], indirect=True) def test_measure_state_no_indices_out_is_not_state(use_np_transpose: bool): - linalg.can_numpy_support_shape = lambda s: use_np_transpose initial_state = cirq.to_valid_state_vector(0, 3) out = np.zeros_like(initial_state) bits, state = cirq.measure_state_vector(initial_state, [], out=out) @@ -352,9 +348,8 @@ def test_measure_state_no_indices_out_is_not_state(use_np_transpose: bool): assert out is not initial_state -@pytest.mark.parametrize('use_np_transpose', [False, True]) +@pytest.mark.parametrize('use_np_transpose', [False, True], indirect=True) def test_measure_state_empty_state(use_np_transpose: bool): - linalg.can_numpy_support_shape = lambda s: use_np_transpose initial_state = np.array([1.0]) bits, state = cirq.measure_state_vector(initial_state, []) assert [] == bits diff --git a/cirq-core/cirq/transformers/eject_phased_paulis.py b/cirq-core/cirq/transformers/eject_phased_paulis.py index 4e6e78aa671..a29cac780ae 100644 --- a/cirq-core/cirq/transformers/eject_phased_paulis.py +++ b/cirq-core/cirq/transformers/eject_phased_paulis.py @@ -14,7 +14,7 @@ """Transformer pass that pushes 180° rotations around axes in the XY plane later in the circuit.""" -from typing import Optional, cast, TYPE_CHECKING, Iterable, Tuple, Dict +from typing import Optional, cast, TYPE_CHECKING, Iterable, Iterator, Tuple, Dict import sympy import numpy as np @@ -127,7 +127,7 @@ def _absorb_z_into_w( def _dump_held( qubits: Iterable[ops.Qid], held_w_phases: Dict[ops.Qid, value.TParamVal] -) -> 'cirq.OP_TREE': +) -> Iterator['cirq.OP_TREE']: # Note: sorting is to avoid non-determinism in the insertion order. for q in sorted(qubits): p = held_w_phases.get(q) diff --git a/cirq-core/cirq/transformers/eject_z.py b/cirq-core/cirq/transformers/eject_z.py index fc22718d06f..54964ebce42 100644 --- a/cirq-core/cirq/transformers/eject_z.py +++ b/cirq-core/cirq/transformers/eject_z.py @@ -14,7 +14,7 @@ """Transformer pass that pushes Z gates later and later in the circuit.""" -from typing import Dict, Iterable, Optional, Tuple, TYPE_CHECKING +from typing import Dict, Iterable, Iterator, Optional, Tuple, TYPE_CHECKING from collections import defaultdict import numpy as np @@ -76,7 +76,7 @@ def eject_z( lambda: None ) - def dump_tracked_phase(qubits: Iterable[ops.Qid]) -> 'cirq.OP_TREE': + def dump_tracked_phase(qubits: Iterable[ops.Qid]) -> Iterator['cirq.OP_TREE']: """Zeroes qubit_phase entries by emitting Z gates.""" for q in qubits: p, key = qubit_phase[q], last_phased_xz_op[q] diff --git a/cirq-core/cirq/transformers/transformer_primitives_test.py b/cirq-core/cirq/transformers/transformer_primitives_test.py index 9b99703ee0f..4667397d257 100644 --- a/cirq-core/cirq/transformers/transformer_primitives_test.py +++ b/cirq-core/cirq/transformers/transformer_primitives_test.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from typing import Optional, List +from typing import Iterator, List, Optional import pytest import cirq @@ -64,7 +64,7 @@ def test_map_operations_does_not_insert_too_many_moments(): q = cirq.LineQubit.range(5) c_orig = cirq.Circuit(cirq.CX(q[0], q[1]), cirq.CX(q[3], q[2]), cirq.CX(q[3], q[4])) - def map_func(op: cirq.Operation, _: int) -> cirq.OP_TREE: + def map_func(op: cirq.Operation, _: int) -> Iterator[cirq.OP_TREE]: yield cirq.Z.on_each(*op.qubits) yield cirq.CX(*op.qubits) yield cirq.Z.on_each(*op.qubits) @@ -130,7 +130,7 @@ def test_map_operations_deep_subcircuits(): .with_tags("external") ) - def map_func(op: cirq.Operation, _: int) -> cirq.OP_TREE: + def map_func(op: cirq.Operation, _: int) -> Iterator[cirq.OP_TREE]: yield ( [cirq.Z.on_each(*op.qubits), cirq.CX(*op.qubits), cirq.Z.on_each(*op.qubits)] if op.gate == cirq.CX diff --git a/cirq-core/cirq/value/linear_dict.py b/cirq-core/cirq/value/linear_dict.py index ea886ab5d57..312e9bdb05a 100644 --- a/cirq-core/cirq/value/linear_dict.py +++ b/cirq-core/cirq/value/linear_dict.py @@ -13,7 +13,7 @@ # limitations under the License. """Linear combination represented as mapping of things to coefficients.""" -import numbers + from typing import ( Any, Callable, @@ -34,7 +34,9 @@ ) from typing_extensions import Self -Scalar = Union[complex, float, numbers.Complex] +import numpy as np + +Scalar = Union[complex, np.number] TVector = TypeVar('TVector') TDefault = TypeVar('TDefault') @@ -124,7 +126,7 @@ def _check_vector_valid(self, vector: TVector) -> None: def clean(self, *, atol: float = 1e-9) -> Self: """Remove terms with coefficients of absolute value atol or less.""" - negligible = [v for v, c in self._terms.items() if abs(c) <= atol] # type: ignore[operator] + negligible = [v for v, c in self._terms.items() if abs(complex(c)) <= atol] for v in negligible: del self._terms[v] return self @@ -245,7 +247,7 @@ def __mul__(self, a: Scalar) -> Self: result *= a return result - def __rmul__(self, a: Scalar) -> Self: + def __rmul__(self, a: Scalar) -> Self: # type: ignore return self.__mul__(a) def __truediv__(self, a: Scalar) -> Self: diff --git a/cirq-core/cirq/vis/heatmap.py b/cirq-core/cirq/vis/heatmap.py index 70d8d1a6e8f..0556663f0c0 100644 --- a/cirq-core/cirq/vis/heatmap.py +++ b/cirq-core/cirq/vis/heatmap.py @@ -11,6 +11,9 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. + +from __future__ import annotations + import copy from dataclasses import astuple, dataclass from typing import ( @@ -25,6 +28,7 @@ SupportsFloat, Tuple, Union, + TYPE_CHECKING, ) import matplotlib as mpl @@ -36,6 +40,9 @@ from cirq.devices import grid_qubit from cirq.vis import vis_utils +if TYPE_CHECKING: + from numpy.typing import ArrayLike + QubitTuple = Tuple[grid_qubit.GridQubit, ...] Polygon = Sequence[Tuple[float, float]] @@ -233,13 +240,14 @@ def _write_annotations( ax: plt.Axes, ) -> None: """Writes annotations to the center of cells. Internal.""" + facecolor: ArrayLike for (center, annotation), facecolor in zip(centers_and_annot, collection.get_facecolor()): # Calculate the center of the cell, assuming that it is a square # centered at (x=col, y=row). if not annotation: continue x, y = center - face_luminance = vis_utils.relative_luminance(facecolor) # type: ignore + face_luminance = vis_utils.relative_luminance(facecolor) text_color = 'black' if face_luminance > 0.4 else 'white' text_kwargs: Dict[str, Any] = dict(color=text_color, ha="center", va="center") text_kwargs.update(self._config.get('annotation_text_kwargs', {})) diff --git a/cirq-core/cirq/vis/state_histogram.py b/cirq-core/cirq/vis/state_histogram.py index 2a47693fc85..e1b441f9f1c 100644 --- a/cirq-core/cirq/vis/state_histogram.py +++ b/cirq-core/cirq/vis/state_histogram.py @@ -90,7 +90,8 @@ def plot_state_histogram( if isinstance(data, result.Result): values = get_state_histogram(data) elif isinstance(data, collections.Counter): - tick_label, values = zip(*sorted(data.items())) + tick_label, counts = zip(*sorted(data.items())) + values = np.asarray(counts) else: values = np.array(data) if tick_label is None: diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/async_client.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/async_client.py index 91d7ec3e232..19c087cb71e 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/async_client.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/async_client.py @@ -14,7 +14,6 @@ # limitations under the License. # -import functools import importlib.metadata from typing import Optional, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Union @@ -148,9 +147,7 @@ def transport(self) -> QuantumEngineServiceTransport: """ return self._client.transport - get_transport_class = functools.partial( - type(QuantumEngineServiceClient).get_transport_class, type(QuantumEngineServiceClient) - ) + get_transport_class = QuantumEngineServiceClient.get_transport_class def __init__( self, diff --git a/cirq-google/cirq_google/devices/google_noise_properties.py b/cirq-google/cirq_google/devices/google_noise_properties.py index 9d8e5df6c81..4b045a9e60e 100644 --- a/cirq-google/cirq_google/devices/google_noise_properties.py +++ b/cirq-google/cirq_google/devices/google_noise_properties.py @@ -18,6 +18,7 @@ import dataclasses from functools import cached_property from typing import Any, Dict, List, Sequence, Set, Type, TypeVar, Union + import numpy as np import cirq, cirq_google @@ -138,7 +139,7 @@ def with_params( appear in the original object. """ - replace_args: Dict[str, Dict[Any, Any]] = {} + replace_args: Dict[str, Any] = {} if gate_times_ns is not None: replace_args['gate_times_ns'] = _with_values(self.gate_times_ns, gate_times_ns) if t1_ns is not None: diff --git a/cirq-google/cirq_google/transformers/analytical_decompositions/two_qubit_to_sycamore.py b/cirq-google/cirq_google/transformers/analytical_decompositions/two_qubit_to_sycamore.py index 50fc3f057f5..29b71e60949 100644 --- a/cirq-google/cirq_google/transformers/analytical_decompositions/two_qubit_to_sycamore.py +++ b/cirq-google/cirq_google/transformers/analytical_decompositions/two_qubit_to_sycamore.py @@ -26,7 +26,7 @@ def _decompose_arbitrary_into_syc_tabulation( op: cirq.Operation, tabulation: cirq.TwoQubitGateTabulation -) -> cirq.OP_TREE: +) -> Iterator[cirq.OP_TREE]: """Synthesize an arbitrary 2 qubit operation to a Sycamore operation using the given Tabulation. Args: @@ -155,7 +155,7 @@ def known_2q_op_to_sycamore_operations(op: cirq.Operation) -> Optional[cirq.OP_T def _decompose_phased_iswap_into_syc( phase_exponent: float, a: cirq.Qid, b: cirq.Qid -) -> cirq.OP_TREE: +) -> Iterator[cirq.OP_TREE]: """Decomposes `cirq.PhasedISwapPowGate` with an exponent of 1 into Sycamore gates. This should only be called if the gate has an exponent of 1. Otherwise, @@ -180,7 +180,7 @@ def _decompose_phased_iswap_into_syc( def _decompose_phased_iswap_into_syc_precomputed( theta: float, a: cirq.Qid, b: cirq.Qid -) -> cirq.OP_TREE: +) -> Iterator[cirq.OP_TREE]: """Decomposes `cirq.PhasedISwapPowGate` into Sycamore gates using precomputed coefficients. This should only be called if the Gate has a phase_exponent of .25. If the gate has an @@ -252,7 +252,7 @@ def _decompose_cz_into_syc(a: cirq.Qid, b: cirq.Qid): yield (cirq.Z**-1.333333333333333).on(a), -def _decompose_cphase_into_syc(theta: float, q0: cirq.Qid, q1: cirq.Qid) -> cirq.OP_TREE: +def _decompose_cphase_into_syc(theta: float, q0: cirq.Qid, q1: cirq.Qid) -> Iterator[cirq.OP_TREE]: """Implements a cphase using the Ising gate generated from 2 Sycamore gates. A cphase gate has the matrix diag([1, 1, 1, exp(1j * theta)]) and can be mapped to the Rzz @@ -365,7 +365,7 @@ def _find_local_equivalents(target_unitary: np.ndarray, source_unitary: np.ndarr def _create_corrected_circuit( target_unitary: np.ndarray, program: cirq.Circuit, q0: cirq.Qid, q1: cirq.Qid -) -> cirq.OP_TREE: +) -> Iterator[cirq.OP_TREE]: """Adds pre/post single qubit rotations to `program` to make it equivalent to `target_unitary`. Adds single qubit correction terms to the given circuit on 2 qubit s.t. it implements @@ -410,7 +410,7 @@ def _phased_x_z_ops(mat: np.ndarray, q: cirq.Qid) -> Iterator[cirq.Operation]: yield gate(q) -def _rzz(theta: float, q0: cirq.Qid, q1: cirq.Qid) -> cirq.OP_TREE: +def _rzz(theta: float, q0: cirq.Qid, q1: cirq.Qid) -> Iterator[cirq.OP_TREE]: """Implements the Rzz Ising coupling gate (i.e. exp(-1j * theta * zz)) using Sycamore gates. Args: @@ -432,7 +432,7 @@ def _rzz(theta: float, q0: cirq.Qid, q1: cirq.Qid) -> cirq.OP_TREE: yield _create_corrected_circuit(target_unitary, program, q0, q1) -def _swap_rzz(theta: float, q0: cirq.Qid, q1: cirq.Qid) -> cirq.OP_TREE: +def _swap_rzz(theta: float, q0: cirq.Qid, q1: cirq.Qid) -> Iterator[cirq.OP_TREE]: """An implementation of SWAP * exp(-1j * theta * ZZ) using three sycamore gates. This builds off of the _rzz method. diff --git a/cirq-google/cirq_google/transformers/target_gatesets/sycamore_gateset.py b/cirq-google/cirq_google/transformers/target_gatesets/sycamore_gateset.py index 57599ca1ff9..5b9b7e64342 100644 --- a/cirq-google/cirq_google/transformers/target_gatesets/sycamore_gateset.py +++ b/cirq-google/cirq_google/transformers/target_gatesets/sycamore_gateset.py @@ -15,7 +15,7 @@ """Target gateset used for compiling circuits to Sycamore + 1-q rotations + measurement gates.""" import itertools -from typing import cast, Any, Dict, List, Optional, Sequence +from typing import Any, Dict, List, Optional, Sequence import cirq from cirq.protocols.decompose_protocol import DecomposeResult @@ -93,9 +93,7 @@ def merge_func_swap_rzz( circuit = cirq.map_operations( circuit, map_func=lambda op, _: ( - op - if merged_cop_tags.isdisjoint(op.tags) - else op.with_tags(cast(str, intermediate_result_tag)) + op if merged_cop_tags.isdisjoint(op.tags) else op.with_tags(intermediate_result_tag) ), tags_to_ignore=tags_to_ignore, deep=True, diff --git a/cirq-ionq/cirq_ionq/ionq_gateset.py b/cirq-ionq/cirq_ionq/ionq_gateset.py index 0a67787030c..2b58882ee11 100644 --- a/cirq-ionq/cirq_ionq/ionq_gateset.py +++ b/cirq-ionq/cirq_ionq/ionq_gateset.py @@ -13,10 +13,8 @@ # limitations under the License. """Target gateset used for compiling circuits to IonQ device.""" -from typing import Any -from typing import Dict -from typing import List -from typing import Tuple + +from typing import Any, Dict, Iterator, List, Tuple import cirq @@ -57,7 +55,7 @@ def __init__(self, *, atol: float = 1e-8): ) self.atol = atol - def _decompose_single_qubit_operation(self, op: cirq.Operation, _) -> cirq.OP_TREE: + def _decompose_single_qubit_operation(self, op: cirq.Operation, _) -> Iterator[cirq.OP_TREE]: qubit = op.qubits[0] mat = cirq.unitary(op) for gate in cirq.single_qubit_matrix_to_gates(mat, self.atol): diff --git a/dev_tools/requirements/deps/mypy.txt b/dev_tools/requirements/deps/mypy.txt index fe07829257e..eb8e64c269c 100644 --- a/dev_tools/requirements/deps/mypy.txt +++ b/dev_tools/requirements/deps/mypy.txt @@ -1,8 +1,6 @@ # the mypy dependency file -mypy==1.2.0 +mypy==1.11.1 # packages with stub types for various libraries -types-backports==0.1.3 -types-cachetools types-protobuf>=3.20.0 types-requests==2.28.1