Skip to content

Commit

Permalink
Fix typing complaints showing at numpy 1.23 (#5856)
Browse files Browse the repository at this point in the history
- Revert "Restrict numpy version to unblock inflight PRs from failing (#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 #5852.

Reverts #5853.
  • Loading branch information
pavoljuhas authored Sep 6, 2022
1 parent 7b17cf8 commit 0781f16
Show file tree
Hide file tree
Showing 11 changed files with 17 additions and 15 deletions.
2 changes: 1 addition & 1 deletion cirq-core/cirq/contrib/quantum_volume/quantum_volume.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ def sample_heavy_set(

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

# Return the number of Heavy outputs over the number of valid runs.
return num_in_heavy_set / len(results)
Expand Down
8 changes: 4 additions & 4 deletions cirq-core/cirq/experiments/fidelity_estimation.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def linear_xeb_fidelity_from_probabilities(
Estimate of fidelity associated with an experimental realization
of a quantum circuit.
"""
return hilbert_space_dimension * np.mean(probabilities) - 1
return hilbert_space_dimension * np.mean(probabilities).item() - 1


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

if isinstance(bitstrings, tuple):
bitstrings = list(bitstrings)
Expand All @@ -190,9 +190,9 @@ def xeb_fidelity(
if amplitudes is None:
output_state = final_state_vector(circuit, qubit_order=qubit_order)
output_probabilities = state_vector_to_probabilities(output_state)
bitstring_probabilities = output_probabilities[bitstrings]
bitstring_probabilities = output_probabilities[bitstrings].tolist()
else:
bitstring_probabilities = np.abs([amplitudes[bitstring] for bitstring in bitstrings]) ** 2
bitstring_probabilities = [abs(amplitudes[bitstring]) ** 2 for bitstring in bitstrings]
return estimator(dim, bitstring_probabilities)


Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/experiments/purity_estimation.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,4 @@ def purity_from_probabilities(
"""
D = hilbert_space_dimension
porter_thomas_variance = (D - 1) / (D + 1) / D**2
return np.var(probabilities) / porter_thomas_variance
return np.var(probabilities).item() / porter_thomas_variance
1 change: 1 addition & 0 deletions cirq-core/cirq/interop/quirk/cells/input_rotation_cells.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ def _apply_unitary_(self, args: 'cirq.ApplyUnitaryArgs'):
control_max = np.prod([q.dimension for q in self.register], dtype=np.int64).item()

for i in range(control_max):
assert isinstance(self.base_operation, cirq.GateOperation)
operation = self.base_operation ** (self.exponent_sign * i / control_max)
control_index = linalg.slice_for_qubits_equal_to(control_axes, big_endian_qureg_value=i)
sub_args = cirq.ApplyUnitaryArgs(
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/linalg/decompositions.py
Original file line number Diff line number Diff line change
Expand Up @@ -865,7 +865,7 @@ def kak_decomposition(
# Recover pieces.
a1, a0 = so4_to_magic_su2s(left.T, atol=atol, rtol=rtol, check_preconditions=False)
b1, b0 = so4_to_magic_su2s(right.T, atol=atol, rtol=rtol, check_preconditions=False)
w, x, y, z = (KAK_GAMMA @ np.vstack(np.angle(d))).flatten()
w, x, y, z = (KAK_GAMMA @ np.angle(d).reshape(-1, 1)).flatten()
g = np.exp(1j * w)

# Canonicalize.
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/linalg/transformations.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ def partial_trace(tensor: np.ndarray, keep_indices: Sequence[int]) -> np.ndarray
left_indices = [keep_map[i] if i in keep_set else i for i in range(ndim)]
right_indices = [ndim + i if i in keep_set else i for i in left_indices]
# TODO(#5757): remove type ignore when numpy has proper override signature.
return np.einsum(tensor, left_indices + right_indices) # type: ignore
return np.einsum(tensor, left_indices + right_indices)


class EntangledStateError(ValueError):
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/protocols/trace_distance_bound.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def _strat_distance_from_unitary(val: Any) -> Optional[float]:
return 0.0
return squared**0.5

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


def trace_distance_from_angle_list(angle_list: Union[Sequence[float], np.ndarray]) -> float:
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/qis/states.py
Original file line number Diff line number Diff line change
Expand Up @@ -684,7 +684,7 @@ def density_matrix_from_state_vector(
np.conj(state_vector),
cast(List, sum_inds.tolist()),
indices + cast(List, sum_inds[indices].tolist()),
) # type: ignore
)
new_shape = np.prod([shape[i] for i in indices], dtype=np.int64)

return rho.reshape((new_shape, new_shape))
Expand Down
6 changes: 3 additions & 3 deletions cirq-core/cirq/sim/density_matrix_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,14 +250,14 @@ def _validate_num_qubits(density_matrix: np.ndarray) -> int:
"""
shape = density_matrix.shape
half_index = len(shape) // 2
row_size = np.prod(shape[:half_index], dtype=np.int64) if len(shape) != 0 else 0
col_size = np.prod(shape[half_index:], dtype=np.int64) if len(shape) != 0 else 0
row_size = np.prod(shape[:half_index]).item() if shape else 0
col_size = np.prod(shape[half_index:]).item() if shape else 0
if row_size != col_size:
raise ValueError(f'Matrix was not square. Shape was {shape}')
if row_size & (row_size - 1):
raise ValueError(
'Matrix could not be shaped into a square matrix with dimensions '
'not a power of two. Shape was {}'.format(shape)
'that are a power of two. Shape was {}'.format(shape)
)
if len(shape) > 2 and not np.allclose(shape, 2):
raise ValueError(
Expand Down
3 changes: 2 additions & 1 deletion cirq-core/cirq/sim/state_vector_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,8 @@ def compute_amplitudes_sweep_iter(
trial_result_iter = self.simulate_sweep_iter(program, params, qubit_order)

yield from (
trial_result.final_state_vector[bitstrings] for trial_result in trial_result_iter
trial_result.final_state_vector[bitstrings].tolist()
for trial_result in trial_result_iter
)


Expand Down
2 changes: 1 addition & 1 deletion cirq-core/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ backports.cached_property~=1.0.1; python_version < '3.8'
duet~=0.2.7
matplotlib~=3.0
networkx~=2.4
numpy >= 1.16, < 1.23
numpy~=1.16
pandas
sortedcontainers~=2.0
scipy
Expand Down

0 comments on commit 0781f16

Please sign in to comment.