Skip to content

Commit 845836a

Browse files
authored
Fix most numpy errors in cirq/qis and friends (#4002)
Part of #3767
1 parent 259dd91 commit 845836a

File tree

9 files changed

+74
-47
lines changed

9 files changed

+74
-47
lines changed

cirq/interop/quirk/cells/parse.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def _segment_by(seq: Iterable[T], *, key: Callable[[T], Any]) -> Iterator[List[T
7070

7171

7272
def _tokenize(text: str) -> List[str]:
73-
def classify(e: str) -> str:
73+
def classify(e: str) -> Union[str, float]:
7474
assert e.strip() != '' # Because _segment_by drops empty entries.
7575
if re.match(r'[.0-9]', e):
7676
return "#"

cirq/qis/measures.py

+13-13
Original file line numberDiff line numberDiff line change
@@ -138,9 +138,9 @@ def fidelity(
138138
)
139139
state1 = quantum_state(state1, qid_shape=qid_shape, validate=validate, atol=atol)
140140
state2 = quantum_state(state2, qid_shape=qid_shape, validate=validate, atol=atol)
141-
state1 = state1.density_matrix() if state1._is_density_matrix() else state1.state_vector()
142-
state2 = state2.density_matrix() if state2._is_density_matrix() else state2.state_vector()
143-
return _fidelity_state_vectors_or_density_matrices(state1, state2)
141+
state1_arr = state1.state_vector_or_density_matrix()
142+
state2_arr = state2.state_vector_or_density_matrix()
143+
return _fidelity_state_vectors_or_density_matrices(state1_arr, state2_arr)
144144

145145

146146
def _numpy_arrays_to_state_vectors_or_density_matrices(
@@ -152,10 +152,10 @@ def _numpy_arrays_to_state_vectors_or_density_matrices(
152152
) -> Tuple[np.ndarray, np.ndarray]:
153153
if state1.ndim > 2 or (state1.ndim == 2 and state1.shape[0] != state1.shape[1]):
154154
# State tensor, convert to state vector
155-
state1 = np.reshape(state1, (np.prod(state1.shape),))
155+
state1 = np.reshape(state1, (np.prod(state1.shape).item(),))
156156
if state2.ndim > 2 or (state2.ndim == 2 and state2.shape[0] != state2.shape[1]):
157157
# State tensor, convert to state vector
158-
state2 = np.reshape(state2, (np.prod(state2.shape),))
158+
state2 = np.reshape(state2, (np.prod(state2.shape).item(),))
159159
if state1.ndim == 2 and state2.ndim == 2:
160160
# Must be square matrices
161161
if state1.shape == state2.shape:
@@ -168,26 +168,26 @@ def _numpy_arrays_to_state_vectors_or_density_matrices(
168168
)
169169
if state1.shape == qid_shape:
170170
# State tensors, convert to state vectors
171-
state1 = np.reshape(state1, (np.prod(qid_shape),))
172-
state2 = np.reshape(state2, (np.prod(qid_shape),))
171+
state1 = np.reshape(state1, (np.prod(qid_shape).item(),))
172+
state2 = np.reshape(state2, (np.prod(qid_shape).item(),))
173173
elif state1.shape[0] < state2.shape[0]:
174174
# state1 is state tensor and state2 is density matrix.
175175
# Convert state1 to state vector
176-
state1 = np.reshape(state1, (np.prod(state1.shape),))
176+
state1 = np.reshape(state1, (np.prod(state1.shape).item(),))
177177
else: # state1.shape[0] > state2.shape[0]
178178
# state2 is state tensor and state1 is density matrix.
179179
# Convert state2 to state vector
180-
state2 = np.reshape(state2, (np.prod(state2.shape),))
180+
state2 = np.reshape(state2, (np.prod(state2.shape).item(),))
181181
elif state1.ndim == 2 and state2.ndim < 2 and np.prod(state1.shape) == np.prod(state2.shape):
182182
# state1 is state tensor, convert to state vector
183-
state1 = np.reshape(state1, (np.prod(state1.shape),))
183+
state1 = np.reshape(state1, (np.prod(state1.shape).item(),))
184184
elif state1.ndim < 2 and state2.ndim == 2 and np.prod(state1.shape) == np.prod(state2.shape):
185185
# state2 is state tensor, convert to state vector
186-
state2 = np.reshape(state2, (np.prod(state2.shape),))
186+
state2 = np.reshape(state2, (np.prod(state2.shape).item(),))
187187

188188
if validate:
189-
dim1 = state1.shape[0] if state1.ndim == 2 else np.prod(state1.shape)
190-
dim2 = state2.shape[0] if state2.ndim == 2 else np.prod(state2.shape)
189+
dim1: int = state1.shape[0] if state1.ndim == 2 else np.prod(state1.shape).item()
190+
dim2: int = state2.shape[0] if state2.ndim == 2 else np.prod(state2.shape).item()
191191
if dim1 != dim2:
192192
raise ValueError('Mismatched dimensions in given states: ' f'{dim1} and {dim2}.')
193193
if qid_shape is None:

cirq/qis/states.py

+38-20
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
"""Classes and methods for quantum states."""
1515

1616
import itertools
17-
from typing import Any, cast, Iterable, Optional, Sequence, TYPE_CHECKING, Tuple, Type, Union
17+
from typing import Any, cast, Iterable, Optional, Sequence, TYPE_CHECKING, Tuple, Union
1818

1919
import numpy as np
2020

@@ -23,6 +23,7 @@
2323

2424
if TYPE_CHECKING:
2525
import cirq
26+
from numpy.typing import DTypeLike
2627

2728
DEFAULT_COMPLEX_DTYPE = np.complex64
2829

@@ -61,7 +62,7 @@ def __init__(
6162
data: np.ndarray,
6263
qid_shape: Optional[Tuple[int, ...]] = None,
6364
*, # Force keyword arguments
64-
dtype: Optional[Type[np.number]] = None,
65+
dtype: Optional['DTypeLike'] = None,
6566
validate: bool = True,
6667
atol: float = 1e-7,
6768
) -> None:
@@ -87,7 +88,7 @@ def __init__(
8788
)
8889
self._data = data
8990
self._qid_shape = qid_shape
90-
self._dim = np.prod(self.qid_shape, dtype=int)
91+
self._dim = np.prod(self.qid_shape, dtype=int).item()
9192
if validate:
9293
self.validate(dtype=dtype, atol=atol)
9394

@@ -102,7 +103,7 @@ def qid_shape(self) -> Tuple[int, ...]:
102103
return self._qid_shape
103104

104105
@property
105-
def dtype(self) -> np.ndarray:
106+
def dtype(self) -> np.dtype:
106107
"""The data type of the quantum state."""
107108
return self._data.dtype
108109

@@ -136,15 +137,27 @@ def density_matrix(self) -> np.ndarray:
136137
"""
137138
if not self._is_density_matrix():
138139
state_vector = self.state_vector()
140+
assert state_vector is not None, 'only None if _is_density_matrix'
139141
return np.outer(state_vector, np.conj(state_vector))
140142
return self.data
141143

144+
def state_vector_or_density_matrix(self) -> np.ndarray:
145+
"""Return the state vector or density matrix of this state.
146+
147+
If the state is a denity matrix, return the density matrix. Otherwise, return the state
148+
vector.
149+
"""
150+
state_vector = self.state_vector()
151+
if state_vector is not None:
152+
return state_vector
153+
return self.data
154+
142155
def _is_density_matrix(self) -> bool:
143156
"""Whether this quantum state is a density matrix."""
144157
return self.data.shape == (self._dim, self._dim)
145158

146159
def validate(
147-
self, *, dtype: Optional[Type[np.number]] = None, atol=1e-7 # Force keyword arguments
160+
self, *, dtype: Optional['DTypeLike'] = None, atol=1e-7 # Force keyword arguments
148161
) -> None:
149162
"""Check if this quantum state is valid.
150163
@@ -158,8 +171,13 @@ def validate(
158171
is_state_vector = self.data.shape == (self._dim,)
159172
is_state_tensor = self.data.shape == self.qid_shape
160173
if is_state_vector or is_state_tensor:
174+
state_vector = self.state_vector()
175+
assert state_vector is not None
161176
validate_normalized_state_vector(
162-
self.state_vector(), qid_shape=self.qid_shape, dtype=dtype, atol=atol
177+
state_vector,
178+
qid_shape=self.qid_shape,
179+
dtype=dtype,
180+
atol=atol,
163181
)
164182
elif self._is_density_matrix():
165183
validate_density_matrix(
@@ -179,7 +197,7 @@ def quantum_state(
179197
*, # Force keyword arguments
180198
copy: bool = False,
181199
validate: bool = True,
182-
dtype: Optional[Type[np.number]] = None,
200+
dtype: Optional['DTypeLike'] = None,
183201
atol: float = 1e-7,
184202
) -> QuantumState:
185203
"""Create a QuantumState object from a state-like object.
@@ -239,7 +257,7 @@ def quantum_state(
239257
'Please specify the qid shape explicitly using '
240258
'the qid_shape argument.'
241259
)
242-
dim = np.prod(qid_shape, dtype=int)
260+
dim = np.prod(qid_shape, dtype=int).item()
243261
if dtype is None:
244262
dtype = DEFAULT_COMPLEX_DTYPE
245263
data = one_hot(index=state, shape=(dim,), dtype=dtype)
@@ -279,7 +297,7 @@ def density_matrix(
279297
*, # Force keyword arguments
280298
copy: bool = False,
281299
validate: bool = True,
282-
dtype: Optional[Type[np.number]] = None,
300+
dtype: Optional['DTypeLike'] = None,
283301
atol: float = 1e-7,
284302
) -> QuantumState:
285303
"""Create a QuantumState object from a density matrix.
@@ -494,7 +512,7 @@ def to_valid_state_vector(
494512
num_qubits: Optional[int] = None,
495513
*, # Force keyword arguments
496514
qid_shape: Optional[Sequence[int]] = None,
497-
dtype: Optional[Type[np.number]] = None,
515+
dtype: Optional['DTypeLike'] = None,
498516
atol: float = 1e-7,
499517
) -> np.ndarray:
500518
"""Verifies the state_rep is valid and converts it to ndarray form.
@@ -555,7 +573,7 @@ def _state_like_to_state_tensor(
555573
*,
556574
state_like: 'cirq.STATE_VECTOR_LIKE',
557575
qid_shape: Tuple[int, ...],
558-
dtype: Optional[Type[np.number]],
576+
dtype: Optional['DTypeLike'],
559577
atol: float,
560578
) -> np.ndarray:
561579

@@ -619,7 +637,7 @@ def _amplitudes_to_validated_state_tensor(
619637
*,
620638
state_vector: np.ndarray,
621639
qid_shape: Tuple[int, ...],
622-
dtype: Optional[Type[np.number]],
640+
dtype: Optional['DTypeLike'],
623641
atol: float,
624642
) -> np.ndarray:
625643
if dtype is None:
@@ -630,7 +648,7 @@ def _amplitudes_to_validated_state_tensor(
630648

631649

632650
def _qudit_values_to_state_tensor(
633-
*, state_vector: np.ndarray, qid_shape: Tuple[int, ...], dtype: Optional[Type[np.number]]
651+
*, state_vector: np.ndarray, qid_shape: Tuple[int, ...], dtype: Optional['DTypeLike']
634652
) -> np.ndarray:
635653

636654
for i in range(len(qid_shape)):
@@ -661,9 +679,9 @@ def _qudit_values_to_state_tensor(
661679

662680

663681
def _computational_basis_state_to_state_tensor(
664-
*, state_rep: int, qid_shape: Tuple[int, ...], dtype: Optional[Type[np.number]]
682+
*, state_rep: int, qid_shape: Tuple[int, ...], dtype: Optional['DTypeLike']
665683
) -> np.ndarray:
666-
n = np.prod(qid_shape, dtype=int)
684+
n = np.prod(qid_shape, dtype=int).item()
667685
if not 0 <= state_rep < n:
668686
raise ValueError(
669687
f'Computational basis state is out of range.\n'
@@ -682,7 +700,7 @@ def validate_normalized_state_vector(
682700
state_vector: np.ndarray,
683701
*, # Force keyword arguments
684702
qid_shape: Tuple[int, ...],
685-
dtype: Optional[np.dtype] = None,
703+
dtype: Optional['DTypeLike'] = None,
686704
atol: float = 1e-7,
687705
) -> None:
688706
"""Checks that the given state vector is valid.
@@ -754,7 +772,7 @@ def to_valid_density_matrix(
754772
num_qubits: Optional[int] = None,
755773
*, # Force keyword arguments
756774
qid_shape: Optional[Tuple[int, ...]] = None,
757-
dtype: Optional[np.dtype] = None,
775+
dtype: Optional['DTypeLike'] = None,
758776
atol: float = 1e-7,
759777
) -> np.ndarray:
760778
"""Verifies the density_matrix_rep is valid and converts it to ndarray form.
@@ -799,7 +817,7 @@ def validate_density_matrix(
799817
density_matrix: np.ndarray,
800818
*, # Force keyword arguments
801819
qid_shape: Tuple[int, ...],
802-
dtype: Optional[Type[np.number]] = None,
820+
dtype: Optional['DTypeLike'] = None,
803821
atol: float = 1e-7,
804822
) -> None:
805823
"""Checks that the given density matrix is valid.
@@ -867,7 +885,7 @@ def one_hot(
867885
index: Union[None, int, Sequence[int]] = None,
868886
shape: Union[int, Sequence[int]],
869887
value: Any = 1,
870-
dtype: Type[np.number],
888+
dtype: 'DTypeLike',
871889
) -> np.ndarray:
872890
"""Returns a numpy array with all 0s and a single non-zero entry(default 1).
873891
@@ -888,7 +906,7 @@ def one_hot(
888906
return result
889907

890908

891-
def eye_tensor(half_shape: Tuple[int, ...], *, dtype: np.dtype) -> np.ndarray:
909+
def eye_tensor(half_shape: Tuple[int, ...], *, dtype: 'DTypeLike') -> np.ndarray:
892910
"""Returns an identity matrix reshaped into a tensor.
893911
894912
Args:

cirq/qis/states_test.py

+3
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ def test_quantum_state():
5050
np.testing.assert_array_equal(state.state_vector(), state_vector_1)
5151
np.testing.assert_array_equal(state.state_tensor(), state_tensor_1)
5252
np.testing.assert_array_equal(state.density_matrix(), density_matrix_1)
53+
np.testing.assert_array_equal(state.state_vector_or_density_matrix(), state_vector_1)
5354

5455
state = cirq.QuantumState(state_tensor_1, qid_shape=(2, 2))
5556
assert state.data is state_tensor_1
@@ -58,6 +59,7 @@ def test_quantum_state():
5859
np.testing.assert_array_equal(state.state_vector(), state_vector_1)
5960
np.testing.assert_array_equal(state.state_tensor(), state_tensor_1)
6061
np.testing.assert_array_equal(state.density_matrix(), density_matrix_1)
62+
np.testing.assert_array_equal(state.state_vector_or_density_matrix(), state_vector_1)
6163

6264
state = cirq.QuantumState(density_matrix_1, qid_shape=(2, 2))
6365
assert state.data is density_matrix_1
@@ -66,6 +68,7 @@ def test_quantum_state():
6668
assert state.state_vector() is None
6769
assert state.state_tensor() is None
6870
np.testing.assert_array_equal(state.density_matrix(), density_matrix_1)
71+
np.testing.assert_array_equal(state.state_vector_or_density_matrix(), density_matrix_1)
6972

7073

7174
def test_quantum_state_quantum_state():

cirq/sim/density_matrix_simulator.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
# limitations under the License.
1414
"""Simulator for density matrices that simulates noisy quantum circuits."""
1515
import collections
16-
from typing import Any, Dict, Iterator, List, TYPE_CHECKING, Tuple, Type, Union
16+
from typing import Any, Dict, Iterator, List, TYPE_CHECKING, Tuple, Union
1717

1818
import numpy as np
1919

@@ -24,6 +24,7 @@
2424

2525
if TYPE_CHECKING:
2626
import cirq
27+
from numpy.typing import DTypeLike
2728

2829

2930
class DensityMatrixSimulator(
@@ -114,7 +115,7 @@ class DensityMatrixSimulator(
114115
def __init__(
115116
self,
116117
*,
117-
dtype: Type[np.number] = np.complex64,
118+
dtype: 'DTypeLike' = np.complex64,
118119
noise: 'cirq.NOISE_MODEL_LIKE' = None,
119120
seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None,
120121
ignore_measurement_results: bool = False,
@@ -320,7 +321,7 @@ def __init__(
320321
density_matrix: np.ndarray,
321322
measurements: Dict[str, np.ndarray],
322323
qubit_map: Dict[ops.Qid, int],
323-
dtype: Type[np.number] = np.complex64,
324+
dtype: 'DTypeLike' = np.complex64,
324325
):
325326
"""DensityMatrixStepResult.
326327

cirq/study/result.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -356,8 +356,8 @@ def _pack_digits(digits: np.ndarray, pack_bits: str = 'auto') -> Tuple[str, bool
356356
# Do error checking here, otherwise the following logic will work
357357
# for both "auto" and "never".
358358

359-
if pack_bits == 'auto' and np.array_equal(digits, digits.astype(np.bool)):
360-
return _pack_bits(digits.astype(np.bool)), True
359+
if pack_bits == 'auto' and np.array_equal(digits, digits.astype(np.bool_)):
360+
return _pack_bits(digits.astype(np.bool_)), True
361361

362362
buffer = io.BytesIO()
363363
np.save(buffer, digits, allow_pickle=False)
@@ -404,4 +404,4 @@ def _unpack_digits(
404404
def _unpack_bits(packed_bits: str, dtype: str, shape: Sequence[int]) -> np.ndarray:
405405
bits_bytes = bytes.fromhex(packed_bits)
406406
bits = np.unpackbits(np.frombuffer(bits_bytes, dtype=np.uint8))
407-
return bits[: np.prod(shape)].reshape(shape).astype(dtype)
407+
return bits[: np.prod(shape).item()].reshape(shape).astype(dtype)

cirq/testing/consistent_qasm.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414
import warnings
15-
from typing import Any, List, Sequence
15+
from typing import Any, List, Sequence, Optional
1616

1717
import numpy as np
1818

@@ -81,6 +81,8 @@ def assert_qasm_is_consistent_with_unitary(val: Any):
8181
qasm_unitary, unitary, rtol=1e-8, atol=1e-8
8282
)
8383
except Exception as ex:
84+
p_unitary: Optional[np.ndarray]
85+
p_qasm_unitary: Optional[np.ndarray]
8486
if qasm_unitary is not None:
8587
p_unitary, p_qasm_unitary = linalg.match_global_phase(unitary, qasm_unitary)
8688
else:

cirq/value/product_state.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ def state_vector(self, qubit_order: 'cirq.QubitOrder' = None) -> np.ndarray:
131131
qubit_order = ops.QubitOrder.as_qubit_order(qubit_order)
132132
qubits = qubit_order.order_for(self.qubits)
133133

134-
mat = 1.0 + 0.0j
134+
mat = np.ones(1, dtype=np.complex128)
135135
for qubit in qubits:
136136
oneq_state = self[qubit]
137137
state_vector = oneq_state.state_vector()
@@ -151,7 +151,7 @@ def projector(self, qubit_order: 'cirq.QubitOrder' = None) -> np.ndarray:
151151
qubit_order = ops.QubitOrder.as_qubit_order(qubit_order)
152152
qubits = qubit_order.order_for(self.qubits)
153153

154-
mat = 1.0 + 0.0j
154+
mat = np.ones(1, dtype=np.complex128)
155155
for qubit in qubits:
156156
oneq_state = self[qubit]
157157
oneq_proj = oneq_state.projector()

0 commit comments

Comments
 (0)