Skip to content

Commit c700603

Browse files
author
jp
committed
Convert more to rng
1 parent 2d12897 commit c700603

22 files changed

+67
-75
lines changed

cirq-core/cirq/contrib/quimb/mps_simulator.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -379,7 +379,7 @@ def to_numpy(self) -> np.ndarray:
379379
"""An alias for the state vector."""
380380
return self.state_vector()
381381

382-
def apply_op(self, op: Any, axes: Sequence[int], prng: np.random.RandomState):
382+
def apply_op(self, op: Any, axes: Sequence[int], prng: np.random.Generator):
383383
"""Applies a unitary operation, mutating the object to represent the new state.
384384
385385
op:
@@ -481,7 +481,7 @@ def estimation_stats(self):
481481
}
482482

483483
def _measure(
484-
self, axes: Sequence[int], prng: np.random.RandomState, collapse_state_vector=True
484+
self, axes: Sequence[int], prng: np.random.Generator, collapse_state_vector=True
485485
) -> List[int]:
486486
results: List[int] = []
487487

@@ -565,7 +565,7 @@ def __init__(
565565
self,
566566
*,
567567
qubits: Sequence['cirq.Qid'],
568-
prng: np.random.RandomState,
568+
prng: Union[np.random.Generator, np.random.RandomState],
569569
simulation_options: MPSOptions = MPSOptions(),
570570
grouping: Optional[Dict['cirq.Qid', int]] = None,
571571
initial_state: int = 0,

cirq-core/cirq/experiments/random_quantum_circuit_generation.py

+9-9
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,7 @@ def random_rotations_between_two_qubit_circuit(
184184
q1: 'cirq.Qid',
185185
depth: int,
186186
two_qubit_op_factory: Callable[
187-
['cirq.Qid', 'cirq.Qid', 'np.random.RandomState'], 'cirq.OP_TREE'
187+
['cirq.Qid', 'cirq.Qid', 'np.random.Generator'], 'cirq.OP_TREE'
188188
] = lambda a, b, _: ops.CZPowGate()(a, b),
189189
single_qubit_gates: Sequence['cirq.Gate'] = (
190190
ops.X**0.5,
@@ -354,7 +354,7 @@ def _get_random_combinations(
354354

355355
combinations_by_layer = []
356356
for pairs, layer in pair_gen:
357-
combinations = rs.randint(0, n_library_circuits, size=(n_combinations, len(pairs)))
357+
combinations = rs.integers(0, n_library_circuits, size=(n_combinations, len(pairs)))
358358
combinations_by_layer.append(
359359
CircuitLibraryCombination(layer=layer, combinations=combinations, pairs=pairs)
360360
)
@@ -553,7 +553,7 @@ def random_rotations_between_grid_interaction_layers_circuit(
553553
depth: int,
554554
*, # forces keyword arguments
555555
two_qubit_op_factory: Callable[
556-
['cirq.GridQubit', 'cirq.GridQubit', 'np.random.RandomState'], 'cirq.OP_TREE'
556+
['cirq.GridQubit', 'cirq.GridQubit', 'np.random.Generator'], 'cirq.OP_TREE'
557557
] = lambda a, b, _: ops.CZPowGate()(a, b),
558558
pattern: Sequence[GridInteractionLayer] = GRID_STAGGERED_PATTERN,
559559
single_qubit_gates: Sequence['cirq.Gate'] = (
@@ -641,7 +641,7 @@ def __init__(
641641
self,
642642
qubits: Sequence['cirq.Qid'],
643643
single_qubit_gates: Sequence['cirq.Gate'],
644-
prng: 'np.random.RandomState',
644+
prng: 'np.random.Generator',
645645
) -> None:
646646
self.qubits = qubits
647647
self.single_qubit_gates = single_qubit_gates
@@ -651,9 +651,9 @@ def new_layer(self, previous_single_qubit_layer: 'cirq.Moment') -> 'cirq.Moment'
651651
def random_gate(qubit: 'cirq.Qid') -> 'cirq.Gate':
652652
excluded_op = previous_single_qubit_layer.operation_at(qubit)
653653
excluded_gate = excluded_op.gate if excluded_op is not None else None
654-
g = self.single_qubit_gates[self.prng.randint(0, len(self.single_qubit_gates))]
654+
g = self.single_qubit_gates[self.prng.integers(0, len(self.single_qubit_gates))]
655655
while g is excluded_gate:
656-
g = self.single_qubit_gates[self.prng.randint(0, len(self.single_qubit_gates))]
656+
g = self.single_qubit_gates[self.prng.integers(0, len(self.single_qubit_gates))]
657657
return g
658658

659659
return circuits.Moment(random_gate(q).on(q) for q in self.qubits)
@@ -673,7 +673,7 @@ def new_layer(self, previous_single_qubit_layer: 'cirq.Moment') -> 'cirq.Moment'
673673
def _single_qubit_gates_arg_to_factory(
674674
single_qubit_gates: Sequence['cirq.Gate'],
675675
qubits: Sequence['cirq.Qid'],
676-
prng: 'np.random.RandomState',
676+
prng: 'np.random.Generator',
677677
) -> _SingleQubitLayerFactory:
678678
"""Parse the `single_qubit_gates` argument for circuit generation functions.
679679
@@ -690,10 +690,10 @@ def _single_qubit_gates_arg_to_factory(
690690
def _two_qubit_layer(
691691
coupled_qubit_pairs: List[GridQubitPairT],
692692
two_qubit_op_factory: Callable[
693-
['cirq.GridQubit', 'cirq.GridQubit', 'np.random.RandomState'], 'cirq.OP_TREE'
693+
['cirq.GridQubit', 'cirq.GridQubit', 'np.random.Generator'], 'cirq.OP_TREE'
694694
],
695695
layer: GridInteractionLayer,
696-
prng: 'np.random.RandomState',
696+
prng: 'np.random.Generator',
697697
) -> Iterator['cirq.OP_TREE']:
698698
for a, b in coupled_qubit_pairs:
699699
if (a, b) in layer or (b, a) in layer:

cirq-core/cirq/experiments/random_quantum_circuit_generation_test.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -52,15 +52,15 @@ def test_random_rotation_between_two_qubit_circuit():
5252
"""\
5353
0 1
5454
│ │
55-
Y^0.5 X^0.5
55+
PhX(0.25)^0.5 Y^0.5
5656
│ │
5757
@─────────────@
5858
│ │
59-
PhX(0.25)^0.5 Y^0.5
59+
X^0.5 PhX(0.25)^0.5
6060
│ │
6161
@─────────────@
6262
│ │
63-
Y^0.5 X^0.5
63+
Y^0.5 Y^0.5
6464
│ │
6565
@─────────────@
6666
│ │
@@ -361,7 +361,7 @@ def test_random_rotations_between_grid_interaction_layers(
361361
qubits: Iterable[cirq.GridQubit],
362362
depth: int,
363363
two_qubit_op_factory: Callable[
364-
[cirq.GridQubit, cirq.GridQubit, np.random.RandomState], cirq.OP_TREE
364+
[cirq.GridQubit, cirq.GridQubit, np.random.Generator], cirq.OP_TREE
365365
],
366366
pattern: Sequence[GridInteractionLayer],
367367
single_qubit_gates: Sequence[cirq.Gate],

cirq-core/cirq/linalg/decompositions_test.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -597,7 +597,7 @@ def _random_two_qubit_unitaries(num_samples: int, random_state: 'cirq.RANDOM_STA
597597

598598
prng = value.parse_random_state(random_state)
599599
# Generate the non-local part by explict matrix exponentiation.
600-
kak_vecs = prng.rand(num_samples, 3) * np.pi
600+
kak_vecs = prng.random((num_samples, 3)) * np.pi
601601
gens = np.einsum('...a,abc->...bc', kak_vecs, _kak_gens)
602602
evals, evecs = np.linalg.eigh(gens)
603603
A = np.einsum('...ab,...b,...cb', evecs, np.exp(1j * evals), evecs.conj())

cirq-core/cirq/protocols/act_on_protocol_test.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def measure(self, axes, seed=None):
3030

3131
class ExampleSimulationState(cirq.SimulationState):
3232
def __init__(self, fallback_result: Any = NotImplemented):
33-
super().__init__(prng=np.random.RandomState(), state=ExampleQuantumState())
33+
super().__init__(prng=np.random.default_rng(), state=ExampleQuantumState())
3434
self.fallback_result = fallback_result
3535

3636
def _act_on_fallback_(

cirq-core/cirq/qis/clifford_tableau.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -509,7 +509,7 @@ def destabilizers(self) -> List['cirq.DensePauliString']:
509509
generators above generate the full Pauli group on n qubits."""
510510
return [self._row_to_dense_pauli(i) for i in range(self.n)]
511511

512-
def _measure(self, q, prng: np.random.RandomState) -> int:
512+
def _measure(self, q, prng: np.random.Generator) -> int:
513513
"""Performs a projective measurement on the q'th qubit.
514514
515515
Returns: the result (0 or 1) of the measurement.
@@ -544,7 +544,7 @@ def _measure(self, q, prng: np.random.RandomState) -> int:
544544

545545
self.zs[p, q] = True
546546

547-
self.rs[p] = bool(prng.randint(2))
547+
self.rs[p] = bool(prng.integers(2))
548548

549549
return int(self.rs[p])
550550

cirq-core/cirq/sim/clifford/clifford_simulator.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ def state_vector(self):
242242

243243
def apply_unitary(self, op: 'cirq.Operation'):
244244
ch_form_args = clifford.StabilizerChFormSimulationState(
245-
prng=np.random.RandomState(), qubits=self.qubit_map.keys(), initial_state=self.ch_form
245+
prng=np.random.default_rng(), qubits=self.qubit_map.keys(), initial_state=self.ch_form
246246
)
247247
try:
248248
act_on(op, ch_form_args)
@@ -254,7 +254,7 @@ def apply_measurement(
254254
self,
255255
op: 'cirq.Operation',
256256
measurements: Dict[str, List[int]],
257-
prng: np.random.RandomState,
257+
prng: Union[np.random.Generator, np.random.RandomState],
258258
collapse_state_vector=True,
259259
):
260260
if not isinstance(op.gate, cirq.MeasurementGate):

cirq-core/cirq/sim/clifford/clifford_tableau_simulation_state.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
"""A protocol for implementing high performance clifford tableau evolutions
1515
for Clifford Simulator."""
1616

17-
from typing import Optional, Sequence, TYPE_CHECKING
17+
from typing import Optional, Sequence, TYPE_CHECKING, Union
1818

1919
import numpy as np
2020

@@ -31,7 +31,7 @@ class CliffordTableauSimulationState(StabilizerSimulationState[clifford_tableau.
3131
def __init__(
3232
self,
3333
tableau: 'cirq.CliffordTableau',
34-
prng: Optional[np.random.RandomState] = None,
34+
prng: Optional[Union[np.random.Generator, np.random.RandomState]] = None,
3535
qubits: Optional[Sequence['cirq.Qid']] = None,
3636
classical_data: Optional['cirq.ClassicalDataStore'] = None,
3737
):

cirq-core/cirq/sim/clifford/stabilizer_ch_form_simulation_state.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ class StabilizerChFormSimulationState(
3232
def __init__(
3333
self,
3434
*,
35-
prng: Optional[np.random.RandomState] = None,
35+
prng: Optional[Union[np.random.Generator, np.random.RandomState]] = None,
3636
qubits: Optional[Sequence['cirq.Qid']] = None,
3737
initial_state: Union[int, 'cirq.StabilizerStateChForm'] = 0,
3838
classical_data: Optional['cirq.ClassicalDataStore'] = None,

cirq-core/cirq/sim/clifford/stabilizer_simulation_state.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def __init__(
4141
self,
4242
*,
4343
state: TStabilizerState,
44-
prng: Optional[np.random.RandomState] = None,
44+
prng: Optional[Union[np.random.Generator, np.random.RandomState]] = None,
4545
qubits: Optional[Sequence['cirq.Qid']] = None,
4646
classical_data: Optional['cirq.ClassicalDataStore'] = None,
4747
):

cirq-core/cirq/sim/clifford/stabilizer_state_ch_form.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,7 @@ def to_state_vector(self) -> np.ndarray:
236236

237237
return arr
238238

239-
def _measure(self, q, prng: np.random.RandomState) -> int:
239+
def _measure(self, q, prng: np.random.Generator) -> int:
240240
"""Measures the q'th qubit.
241241
242242
Reference: Section 4.1 "Simulating measurements"
@@ -246,7 +246,7 @@ def _measure(self, q, prng: np.random.RandomState) -> int:
246246
w = self.s.copy()
247247
for i, v_i in enumerate(self.v):
248248
if v_i == 1:
249-
w[i] = bool(prng.randint(2))
249+
w[i] = bool(prng.integers(2))
250250
x_i = sum(w & self.G[q, :]) % 2
251251
# Project the state to the above measurement outcome.
252252
self.project_Z(q, x_i)

cirq-core/cirq/sim/density_matrix_simulation_state.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ def __init__(
247247
self,
248248
*,
249249
available_buffer: Optional[List[np.ndarray]] = None,
250-
prng: Optional[np.random.RandomState] = None,
250+
prng: Optional[Union[np.random.Generator, np.random.RandomState]] = None,
251251
qubits: Optional[Sequence['cirq.Qid']] = None,
252252
initial_state: Union[np.ndarray, 'cirq.STATE_VECTOR_LIKE'] = 0,
253253
dtype: Type[np.complexfloating] = np.complex64,

cirq-core/cirq/sim/simulation_state.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
TypeVar,
2828
TYPE_CHECKING,
2929
Tuple,
30+
Union,
3031
)
3132
from typing_extensions import Self
3233

@@ -49,7 +50,7 @@ def __init__(
4950
self,
5051
*,
5152
state: TState,
52-
prng: Optional[np.random.RandomState] = None,
53+
prng: Optional[Union[np.random.Generator, np.random.RandomState]] = None,
5354
qubits: Optional[Sequence['cirq.Qid']] = None,
5455
classical_data: Optional['cirq.ClassicalDataStore'] = None,
5556
):
@@ -70,12 +71,14 @@ def __init__(
7071
classical_data = classical_data or value.ClassicalDataDictionaryStore()
7172
super().__init__(qubits=qubits, classical_data=classical_data)
7273
if prng is None:
73-
prng = cast(np.random.RandomState, np.random)
74+
prng = np.random.default_rng()
75+
elif isinstance(prng, np.random.RandomState):
76+
prng = np.random.default_rng(prng._bit_generator)
7477
self._prng = prng
7578
self._state = state
7679

7780
@property
78-
def prng(self) -> np.random.RandomState:
81+
def prng(self) -> np.random.Generator:
7982
return self._prng
8083

8184
def measure(

cirq-core/cirq/sim/simulator_base.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ def __init__(
110110
self._dtype = dtype
111111
if isinstance(seed, np.random.RandomState):
112112
# Convert RandomState to Generator for backward compatibility
113-
self._prng = np.random.default_rng(seed.get_state()[1][0])
113+
self._prng = np.random.Generator(seed._bit_generator)
114114
elif isinstance(seed, np.random.Generator):
115115
self._prng = seed
116116
else:
@@ -409,7 +409,7 @@ def sample(
409409
seed: Optional[Union[int, np.random.Generator, np.random.RandomState]] = None,
410410
) -> np.ndarray:
411411
if isinstance(seed, np.random.RandomState):
412-
rng = np.random.default_rng(seed.get_state()[1][0])
412+
rng = np.random.Generator(seed._bit_generator)
413413
elif isinstance(seed, np.random.Generator):
414414
rng = seed
415415
else:

cirq-core/cirq/sim/state_vector_simulation_state.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,7 @@ def __init__(
321321
self,
322322
*,
323323
available_buffer: Optional[np.ndarray] = None,
324-
prng: Optional[np.random.RandomState] = None,
324+
prng: Optional[Union[np.random.Generator, np.random.RandomState]] = None,
325325
qubits: Optional[Sequence['cirq.Qid']] = None,
326326
initial_state: Union[np.ndarray, 'cirq.STATE_VECTOR_LIKE'] = 0,
327327
dtype: Type[np.complexfloating] = np.complex64,

cirq-core/cirq/testing/consistent_act_on.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def state_vector_has_stabilizer(state_vector: np.ndarray, stabilizer: DensePauli
5252
args = state_vector_simulation_state.StateVectorSimulationState(
5353
available_buffer=np.empty_like(state_vector),
5454
qubits=qubits,
55-
prng=np.random.RandomState(),
55+
prng=np.random.default_rng(),
5656
initial_state=state_vector.copy(),
5757
dtype=complex_dtype,
5858
)
@@ -163,7 +163,7 @@ def _final_clifford_tableau(
163163

164164
tableau = clifford_tableau.CliffordTableau(len(qubit_map))
165165
args = clifford_tableau_simulation_state.CliffordTableauSimulationState(
166-
tableau=tableau, qubits=list(qubit_map.keys()), prng=np.random.RandomState()
166+
tableau=tableau, qubits=list(qubit_map.keys()), prng=np.random.default_rng()
167167
)
168168
for op in circuit.all_operations():
169169
try:
@@ -192,7 +192,7 @@ def _final_stabilizer_state_ch_form(
192192
stabilizer_ch_form = stabilizer_state_ch_form.StabilizerStateChForm(len(qubit_map))
193193
args = stabilizer_ch_form_simulation_state.StabilizerChFormSimulationState(
194194
qubits=list(qubit_map.keys()),
195-
prng=np.random.RandomState(),
195+
prng=np.random.default_rng(),
196196
initial_state=stabilizer_ch_form,
197197
)
198198
for op in circuit.all_operations():

cirq-core/cirq/testing/lin_alg_utils.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
# limitations under the License.
1414
"""A testing class with utilities for checking linear algebra."""
1515

16-
from typing import Optional, TYPE_CHECKING
16+
from typing import Optional, TYPE_CHECKING, Union
1717

1818
import numpy as np
1919

@@ -39,8 +39,8 @@ def random_superposition(
3939
"""
4040
random_state = value.parse_random_state(random_state)
4141

42-
state_vector = random_state.randn(dim).astype(complex)
43-
state_vector += 1j * random_state.randn(dim)
42+
state_vector = random_state.random(dim).astype(complex)
43+
state_vector += 1j * random_state.random(dim)
4444
state_vector /= np.linalg.norm(state_vector)
4545
return state_vector
4646

@@ -63,7 +63,7 @@ def random_density_matrix(
6363
"""
6464
random_state = value.parse_random_state(random_state)
6565

66-
mat = random_state.randn(dim, dim) + 1j * random_state.randn(dim, dim)
66+
mat = random_state.random((dim, dim)) + 1j * random_state.random((dim, dim))
6767
mat = mat @ mat.T.conj()
6868
return mat / np.trace(mat)
6969

@@ -86,7 +86,7 @@ def random_unitary(
8686
"""
8787
random_state = value.parse_random_state(random_state)
8888

89-
z = random_state.randn(dim, dim) + 1j * random_state.randn(dim, dim)
89+
z = random_state.random((dim, dim)) + 1j * random_state.random((dim, dim))
9090
q, r = np.linalg.qr(z)
9191
d = np.diag(r)
9292
return q * (d / abs(d))
@@ -112,14 +112,14 @@ def random_orthogonal(
112112
"""
113113
random_state = value.parse_random_state(random_state)
114114

115-
m = random_state.randn(dim, dim)
115+
m = random_state.random((dim, dim))
116116
q, r = np.linalg.qr(m)
117117
d = np.diag(r)
118118
return q * (d / abs(d))
119119

120120

121121
def random_special_unitary(
122-
dim: int, *, random_state: Optional[np.random.RandomState] = None
122+
dim: int, *, random_state: Optional[Union[np.random.Generator, np.random.RandomState]] = None
123123
) -> np.ndarray:
124124
"""Returns a random special unitary distributed with Haar measure.
125125

0 commit comments

Comments
 (0)