Skip to content

Commit 4b7f322

Browse files
authored
More fixes for next version of mypy (#5628)
The cast in `fsim_gate_family` could be done with an assert, but in this case I think it is more readable to just use the cast.
1 parent d2aee41 commit 4b7f322

File tree

9 files changed

+25
-20
lines changed

9 files changed

+25
-20
lines changed

cirq-core/cirq/ops/pauli_interaction_gate.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
if TYPE_CHECKING:
2525
import cirq
2626

27-
PAULI_EIGEN_MAP: Dict[pauli_gates.Pauli, np.ndarray] = {
27+
PAULI_EIGEN_MAP: Dict[pauli_gates.Pauli, Tuple[np.ndarray, np.ndarray]] = {
2828
pauli_gates.X: (np.array([[0.5, 0.5], [0.5, 0.5]]), np.array([[0.5, -0.5], [-0.5, 0.5]])),
2929
pauli_gates.Y: (np.array([[0.5, -0.5j], [0.5j, 0.5]]), np.array([[0.5, 0.5j], [-0.5j, 0.5]])),
3030
pauli_gates.Z: (np.diag([1, 0]), np.diag([0, 1])),

cirq-core/cirq/protocols/apply_channel_protocol.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,9 @@ def _apply_channel_(
162162

163163

164164
def apply_channel(
165-
val: Any, args: ApplyChannelArgs, default: TDefault = RaiseTypeErrorIfNotProvided
165+
val: Any,
166+
args: ApplyChannelArgs,
167+
default: Union[np.ndarray, TDefault] = RaiseTypeErrorIfNotProvided,
166168
) -> Union[np.ndarray, TDefault]:
167169
"""High performance evolution under a channel evolution.
168170

cirq-core/cirq/protocols/apply_mixture_protocol.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,10 @@ def _apply_mixture_(
155155

156156

157157
def apply_mixture(
158-
val: Any, args: ApplyMixtureArgs, *, default: TDefault = RaiseTypeErrorIfNotProvided
158+
val: Any,
159+
args: ApplyMixtureArgs,
160+
*,
161+
default: Union[np.ndarray, TDefault] = RaiseTypeErrorIfNotProvided,
159162
) -> Union[np.ndarray, TDefault]:
160163
"""High performance evolution under a mixture of unitaries evolution.
161164
@@ -357,9 +360,7 @@ def _apply_unitary_from_matrix_strat(
357360
return args.target_tensor
358361

359362

360-
def _mixture_strat(
361-
val: Any, args: 'ApplyMixtureArgs', is_density_matrix: bool
362-
) -> Optional[np.ndarray]:
363+
def _mixture_strat(val: Any, args: 'ApplyMixtureArgs', is_density_matrix: bool) -> np.ndarray:
363364
"""Attempt to use unitary matrices in _mixture_ and return the result."""
364365
args.out_buffer[:] = 0
365366
np.copyto(dst=args.auxiliary_buffer1, src=args.target_tensor)

cirq-core/cirq/protocols/apply_unitary_protocol.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,7 @@ def _apply_unitary_(
277277
def apply_unitary(
278278
unitary_value: Any,
279279
args: ApplyUnitaryArgs,
280-
default: TDefault = RaiseTypeErrorIfNotProvided,
280+
default: Union[np.ndarray, TDefault] = RaiseTypeErrorIfNotProvided,
281281
*,
282282
allow_decompose: bool = True,
283283
) -> Union[np.ndarray, TDefault]:

cirq-core/cirq/protocols/commutes_protocol.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def commutes(
7878
v2: Any,
7979
*,
8080
atol: Union[int, float] = 1e-8,
81-
default: TDefault = RaiseTypeErrorIfNotProvided,
81+
default: Union[bool, TDefault] = RaiseTypeErrorIfNotProvided,
8282
) -> Union[bool, TDefault]:
8383
"""Determines whether two values commute.
8484

cirq-core/cirq/protocols/unitary_protocol.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ def _has_unitary_(self) -> bool:
7777

7878

7979
def unitary(
80-
val: Any, default: TDefault = RaiseTypeErrorIfNotProvided
80+
val: Any, default: Union[np.ndarray, TDefault] = RaiseTypeErrorIfNotProvided
8181
) -> Union[np.ndarray, TDefault]:
8282
"""Returns a unitary matrix describing the given value.
8383

cirq-core/cirq/sim/sparse_simulator_test.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -331,7 +331,9 @@ def test_simulate_random_unitary(dtype: Type[np.complexfloating], split: bool):
331331
result = simulator.simulate(random_circuit, qubit_order=[q0, q1], initial_state=x)
332332
circuit_unitary.append(result.final_state_vector)
333333
np.testing.assert_almost_equal(
334-
np.transpose(circuit_unitary), random_circuit.unitary(qubit_order=[q0, q1]), decimal=6
334+
np.transpose(np.array(circuit_unitary)),
335+
random_circuit.unitary(qubit_order=[q0, q1]),
336+
decimal=6,
335337
)
336338

337339

cirq-google/cirq_google/ops/fsim_gate_family.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242

4343
def _exp(theta: Union[complex, sympy.Basic]):
4444
"""Utility method to return exp(theta) using numpy or sympy, depending on the type of theta."""
45-
return sympy.exp(theta) if cirq.is_parameterized(theta) else np.exp(theta)
45+
return sympy.exp(theta) if cirq.is_parameterized(theta) else np.exp(cast(complex, theta))
4646

4747

4848
def _gates_to_str(gates: Iterable[Any], gettr: Callable[[Any], str] = _gate_str) -> str:
@@ -360,7 +360,7 @@ def _convert_to_fsim(self, g: POSSIBLE_FSIM_GATES) -> Optional[cirq.FSimGate]:
360360
def _convert_to_phased_fsim(self, g: POSSIBLE_FSIM_GATES) -> Optional[cirq.PhasedFSimGate]:
361361
if isinstance(g, cirq.PhasedFSimGate):
362362
return g
363-
chi = 0
363+
chi = 0.0
364364
if isinstance(g, cirq.PhasedISwapPowGate):
365365
chi = g.phase_exponent * 2 * np.pi
366366
g = g._iswap
@@ -376,7 +376,7 @@ def _convert_to_iswap(self, g: POSSIBLE_FSIM_GATES) -> Optional[cirq.ISwapPowGat
376376
return (
377377
None
378378
if (fsim is None or not self._approx_eq_or_symbol(fsim.phi, 0))
379-
else cirq.ISWAP ** (-2 * fsim.theta / np.pi)
379+
else cirq.ISwapPowGate(exponent=-2 * fsim.theta / np.pi)
380380
)
381381

382382
def _convert_to_phased_iswap(self, g: POSSIBLE_FSIM_GATES) -> Optional[cirq.PhasedISwapPowGate]:
@@ -400,7 +400,7 @@ def _convert_to_cz(self, g: POSSIBLE_FSIM_GATES) -> Optional[cirq.CZPowGate]:
400400
return (
401401
None
402402
if (cg is None or not self._approx_eq_or_symbol(cg.theta, 0))
403-
else cirq.CZ ** (-cg.phi / np.pi)
403+
else cirq.CZPowGate(exponent=-cg.phi / np.pi)
404404
)
405405

406406
def _convert_to_identity(self, g: POSSIBLE_FSIM_GATES) -> Optional[cirq.IdentityGate]:

cirq-google/cirq_google/optimizers/two_qubit_gates/example.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -80,16 +80,16 @@ def main(samples: int = 1000, max_infidelity: float = 0.01):
8080

8181
print(f'Gate compilation time : {t_comp:.3f} seconds ({t_comp / samples:.4f} s per gate)')
8282

83-
infidelities = np.array(infidelities)
84-
failed_infidelities = np.array(failed_infidelities)
83+
infidelities_arr = np.array(infidelities)
84+
failed_infidelities_arr = np.array(failed_infidelities)
8585

86-
if np.size(failed_infidelities):
86+
if np.size(failed_infidelities_arr):
8787
# coverage: ignore
88-
print(f'Number of "failed" compilations: {np.size(failed_infidelities)}.')
89-
print(f'Maximum infidelity of "failed" compilation: {np.max(failed_infidelities)}')
88+
print(f'Number of "failed" compilations: {np.size(failed_infidelities_arr)}.')
89+
print(f'Maximum infidelity of "failed" compilation: {np.max(failed_infidelities_arr)}')
9090

9191
plt.figure()
92-
plt.hist(infidelities, bins=25, range=[0, max_infidelity * 1.1])
92+
plt.hist(infidelities_arr, bins=25, range=[0, max_infidelity * 1.1])
9393
ylim = plt.ylim()
9494
plt.plot([max_infidelity] * 2, ylim, '--', label='Maximum tabulation infidelity')
9595
plt.xlabel('Compiled gate infidelity vs target')

0 commit comments

Comments
 (0)