Skip to content

Commit d613559

Browse files
authored
Fix typing complaints showing at numpy 1.23 (quantumlib#5856)
- Revert "Restrict numpy version to unblock inflight PRs from failing (quantumlib#5853)" - Clarify wording of ValueError message - Fix typing complaints on non-native numeric types - Fix complaint on float.__rpow__(cirq.Operation) use - cirq.Operation has no `__pow__`, but the GateOperation subclass has - Fix complaint about vstack on generic array - clean up unused "type: ignore" comments Resolves quantumlib#5852. Reverts quantumlib#5853.
1 parent a6f7398 commit d613559

11 files changed

+17
-15
lines changed

cirq/contrib/quantum_volume/quantum_volume.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ def sample_heavy_set(
147147

148148
results = results.agg(lambda meas: cirq.value.big_endian_bits_to_int(meas), axis=1)
149149
# Compute the number of outputs that are in the heavy set.
150-
num_in_heavy_set = np.sum(np.in1d(results, heavy_set))
150+
num_in_heavy_set = np.sum(np.in1d(results, heavy_set)).item()
151151

152152
# Return the number of Heavy outputs over the number of valid runs.
153153
return num_in_heavy_set / len(results)

cirq/experiments/fidelity_estimation.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def linear_xeb_fidelity_from_probabilities(
6060
Estimate of fidelity associated with an experimental realization
6161
of a quantum circuit.
6262
"""
63-
return hilbert_space_dimension * np.mean(probabilities) - 1
63+
return hilbert_space_dimension * np.mean(probabilities).item() - 1
6464

6565

6666
def log_xeb_fidelity_from_probabilities(
@@ -175,7 +175,7 @@ def xeb_fidelity(
175175
ValueError: Circuit is inconsistent with qubit order or one of the
176176
bitstrings is inconsistent with the number of qubits.
177177
"""
178-
dim = np.prod(circuit.qid_shape(), dtype=np.int64)
178+
dim = np.prod(circuit.qid_shape()).item()
179179

180180
if isinstance(bitstrings, tuple):
181181
bitstrings = list(bitstrings)
@@ -190,9 +190,9 @@ def xeb_fidelity(
190190
if amplitudes is None:
191191
output_state = final_state_vector(circuit, qubit_order=qubit_order)
192192
output_probabilities = state_vector_to_probabilities(output_state)
193-
bitstring_probabilities = output_probabilities[bitstrings]
193+
bitstring_probabilities = output_probabilities[bitstrings].tolist()
194194
else:
195-
bitstring_probabilities = np.abs([amplitudes[bitstring] for bitstring in bitstrings]) ** 2
195+
bitstring_probabilities = [abs(amplitudes[bitstring]) ** 2 for bitstring in bitstrings]
196196
return estimator(dim, bitstring_probabilities)
197197

198198

cirq/experiments/purity_estimation.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -58,4 +58,4 @@ def purity_from_probabilities(
5858
"""
5959
D = hilbert_space_dimension
6060
porter_thomas_variance = (D - 1) / (D + 1) / D**2
61-
return np.var(probabilities) / porter_thomas_variance
61+
return np.var(probabilities).item() / porter_thomas_variance

cirq/interop/quirk/cells/input_rotation_cells.py

+1
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,7 @@ def _apply_unitary_(self, args: 'cirq.ApplyUnitaryArgs'):
150150
control_max = np.prod([q.dimension for q in self.register], dtype=np.int64).item()
151151

152152
for i in range(control_max):
153+
assert isinstance(self.base_operation, cirq.GateOperation)
153154
operation = self.base_operation ** (self.exponent_sign * i / control_max)
154155
control_index = linalg.slice_for_qubits_equal_to(control_axes, big_endian_qureg_value=i)
155156
sub_args = cirq.ApplyUnitaryArgs(

cirq/linalg/decompositions.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -865,7 +865,7 @@ def kak_decomposition(
865865
# Recover pieces.
866866
a1, a0 = so4_to_magic_su2s(left.T, atol=atol, rtol=rtol, check_preconditions=False)
867867
b1, b0 = so4_to_magic_su2s(right.T, atol=atol, rtol=rtol, check_preconditions=False)
868-
w, x, y, z = (KAK_GAMMA @ np.vstack(np.angle(d))).flatten()
868+
w, x, y, z = (KAK_GAMMA @ np.angle(d).reshape(-1, 1)).flatten()
869869
g = np.exp(1j * w)
870870

871871
# Canonicalize.

cirq/linalg/transformations.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -335,7 +335,7 @@ def partial_trace(tensor: np.ndarray, keep_indices: Sequence[int]) -> np.ndarray
335335
left_indices = [keep_map[i] if i in keep_set else i for i in range(ndim)]
336336
right_indices = [ndim + i if i in keep_set else i for i in left_indices]
337337
# TODO(#5757): remove type ignore when numpy has proper override signature.
338-
return np.einsum(tensor, left_indices + right_indices) # type: ignore
338+
return np.einsum(tensor, left_indices + right_indices)
339339

340340

341341
class EntangledStateError(ValueError):

cirq/protocols/trace_distance_bound.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ def _strat_distance_from_unitary(val: Any) -> Optional[float]:
106106
return 0.0
107107
return squared**0.5
108108

109-
return trace_distance_from_angle_list(np.angle(np.linalg.eigvals(u))) # type: ignore[arg-type]
109+
return trace_distance_from_angle_list(np.angle(np.linalg.eigvals(u)))
110110

111111

112112
def trace_distance_from_angle_list(angle_list: Union[Sequence[float], np.ndarray]) -> float:

cirq/qis/states.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -684,7 +684,7 @@ def density_matrix_from_state_vector(
684684
np.conj(state_vector),
685685
cast(List, sum_inds.tolist()),
686686
indices + cast(List, sum_inds[indices].tolist()),
687-
) # type: ignore
687+
)
688688
new_shape = np.prod([shape[i] for i in indices], dtype=np.int64)
689689

690690
return rho.reshape((new_shape, new_shape))

cirq/sim/density_matrix_utils.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -250,14 +250,14 @@ def _validate_num_qubits(density_matrix: np.ndarray) -> int:
250250
"""
251251
shape = density_matrix.shape
252252
half_index = len(shape) // 2
253-
row_size = np.prod(shape[:half_index], dtype=np.int64) if len(shape) != 0 else 0
254-
col_size = np.prod(shape[half_index:], dtype=np.int64) if len(shape) != 0 else 0
253+
row_size = np.prod(shape[:half_index]).item() if shape else 0
254+
col_size = np.prod(shape[half_index:]).item() if shape else 0
255255
if row_size != col_size:
256256
raise ValueError(f'Matrix was not square. Shape was {shape}')
257257
if row_size & (row_size - 1):
258258
raise ValueError(
259259
'Matrix could not be shaped into a square matrix with dimensions '
260-
'not a power of two. Shape was {}'.format(shape)
260+
'that are a power of two. Shape was {}'.format(shape)
261261
)
262262
if len(shape) > 2 and not np.allclose(shape, 2):
263263
raise ValueError(

cirq/sim/state_vector_simulator.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,8 @@ def compute_amplitudes_sweep_iter(
8585
trial_result_iter = self.simulate_sweep_iter(program, params, qubit_order)
8686

8787
yield from (
88-
trial_result.final_state_vector[bitstrings] for trial_result in trial_result_iter
88+
trial_result.final_state_vector[bitstrings].tolist()
89+
for trial_result in trial_result_iter
8990
)
9091

9192

requirements.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ backports.cached_property~=1.0.1; python_version < '3.8'
66
duet~=0.2.7
77
matplotlib~=3.0
88
networkx~=2.4
9-
numpy >= 1.16, < 1.23
9+
numpy~=1.16
1010
pandas
1111
sortedcontainers~=2.0
1212
scipy

0 commit comments

Comments
 (0)