Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -39,7 +39,7 @@ def generate_model_circuit(
# Setup the circuit and its qubits.
qubits = cirq.LineQubit.range(num_qubits)
circuit = cirq.Circuit()
random_state = cirq.value.parse_random_state(random_state)
random_state = cirq.value.parse_random_generator(random_state)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit - should we rename LHS to prng here?


# For each layer.
for _ in range(depth):
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/contrib/routing/greedy.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def __init__(
random_state: cirq.RANDOM_STATE_OR_SEED_LIKE = None,
):

self.prng = value.parse_random_state(random_state)
self.prng = value.parse_random_generator(random_state)

self.device_graph = device_graph
self.physical_distances: dict[QidPair, int] = {
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/contrib/routing/initialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def get_initial_mapping(
qubits that minimizes the average distance to already mapped logical
neighbors is selected.
"""
prng = value.parse_random_state(random_state)
prng = value.parse_random_generator(random_state)

unplaced_vertices = set(logical_graph)

Expand Down
20 changes: 8 additions & 12 deletions cirq-core/cirq/contrib/routing/initialization_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def get_seeded_initial_mapping(graph_seed, init_seed) -> dict[cirq.Qid, cirq.Qid

@pytest.mark.parametrize('seed', [random.randint(0, 2**32) for _ in range(10)])

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit - can we replace the above with one static sample, i.e., a fixed list of 10 integers generated as above?

This would let us have constant parameterized test names (which include parameter value) with effectively the same test.

def test_initialization_reproducible_with_seed(seed) -> None:
wrappers = (lambda s: s, np.random.RandomState)
wrappers = (lambda s: s, np.random.default_rng)
mappings = [
get_seeded_initial_mapping(seed, wrapper(seed)) for wrapper in wrappers for _ in range(5)
]
Expand All @@ -43,10 +43,10 @@ def test_initialization_reproducible_with_seed(seed) -> None:

def test_initialization_with_no_seed() -> None:
graph_seed = random.randint(0, 2**32)
state = np.random.get_state()
default_rng_seed = random.randint(0, 2**32)
mappings = []
for _ in range(3):
np.random.set_state(state)
cirq.value.reseed_default_prng(default_rng_seed)
mappings.append(get_seeded_initial_mapping(graph_seed, None))
eq = cirq.testing.EqualsTester()
eq.add_equality_group(*mappings)
Expand All @@ -58,12 +58,8 @@ def test_initialization_reproducible_between_runs() -> None:
logical_graph = nx.relabel_nodes(logical_graph, cirq.LineQubit)
device_graph = ccr.get_grid_device_graph(2, 3)
initial_mapping = ccr.initialization.get_initial_mapping(logical_graph, device_graph, seed)
expected_mapping = {
cirq.GridQubit(0, 0): cirq.LineQubit(5),
cirq.GridQubit(0, 1): cirq.LineQubit(0),
cirq.GridQubit(0, 2): cirq.LineQubit(2),
cirq.GridQubit(1, 0): cirq.LineQubit(3),
cirq.GridQubit(1, 1): cirq.LineQubit(4),
cirq.GridQubit(1, 2): cirq.LineQubit(1),
}
assert initial_mapping == expected_mapping
assert set(initial_mapping) == set(device_graph)
assert sorted(initial_mapping.values()) == sorted(logical_graph)
assert initial_mapping == ccr.initialization.get_initial_mapping(
logical_graph, device_graph, np.random.default_rng(seed)
)
22 changes: 4 additions & 18 deletions cirq-core/cirq/contrib/routing/router_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def test_route_circuit(n_moments, algo, circuit_seed, routing_seed) -> None:
def test_route_circuit_reproducible_with_seed(algo, seed) -> None:
circuit = cirq.testing.random_circuit(8, 20, 0.5, random_state=seed)
device_graph = ccr.get_grid_device_graph(4, 3)
random_states = [seed, seed, seed] + [np.random.RandomState(seed) for _ in range(3)]
random_states = [seed, seed, seed] + [np.random.default_rng(seed) for _ in range(3)]

swap_networks = []
for random_state in random_states:
Expand All @@ -74,23 +74,9 @@ def test_route_circuit_reproducible_between_runs(algo) -> None:
device_graph = ccr.get_grid_device_graph(2, 3)

swap_network = ccr.route_circuit(circuit, device_graph, algo_name=algo, random_state=seed)
swap_network_str = str(swap_network).lstrip('\n').rstrip()
expected_swap_network_str = """
┌──┐ ┌────┐ ┌──────┐
(0, 0): ───4────Z─────4────@───────4──────────────4───
│
(0, 1): ───2────@─────2────┼1↦0────5────@─────────5───
│ ││ │
(0, 2): ───5────┼─────5────┼0↦1────2────┼iSwap────2───
│ │ ││
(1, 0): ───3────┼T────3────@───────3────┼┼────────3───
│ ││
(1, 1): ───1────@─────1────────────1────X┼────────1───
│
(1, 2): ───0────X─────0────────────0─────iSwap────0───
└──┘ └────┘ └──────┘
""".lstrip('\n').rstrip()
assert swap_network_str == expected_swap_network_str
assert ccr.is_valid_routing(circuit, swap_network)
swap_network2 = ccr.route_circuit(circuit, device_graph, algo_name=algo, random_state=seed)
assert swap_network2 == swap_network


@pytest.mark.parametrize(
Expand Down
28 changes: 15 additions & 13 deletions cirq-core/cirq/experiments/random_quantum_circuit_generation.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ def random_rotations_between_two_qubit_circuit(
q1: cirq.Qid,
depth: int,
two_qubit_op_factory: Callable[
[cirq.Qid, cirq.Qid, np.random.RandomState], cirq.OP_TREE
[cirq.Qid, cirq.Qid, np.random.Generator], cirq.OP_TREE
] = lambda a, b, _: ops.CZPowGate()(a, b),
single_qubit_gates: Sequence[cirq.Gate] = (
ops.X**0.5,
Expand Down Expand Up @@ -211,7 +211,7 @@ def random_rotations_between_two_qubit_circuit(
seed: A seed or random state to use for the pseudorandom number
generator.
"""
prng = value.parse_random_state(seed)
prng = value.parse_random_generator(seed)

circuit = circuits.Circuit()
previous_single_qubit_layer = circuits.Moment()
Expand Down Expand Up @@ -258,7 +258,7 @@ def generate_library_of_2q_circuits(
random_state: A random state or seed used to deterministically sample the random circuits.
tags: Tags to add to the two qubit operations.
"""
rs = value.parse_random_state(random_state)
rs = value.parse_random_generator(random_state)
exponents = np.linspace(0, 7 / 4, 8)
single_qubit_gates = [
ops.PhasedXZGate(x_exponent=0.5, z_exponent=z, axis_phase_exponent=a)
Expand Down Expand Up @@ -339,11 +339,11 @@ def _get_random_combinations(
returned list can be provided to `sample_2q_xeb_circuits` to efficiently
sample parallel XEB circuits.
"""
rs = value.parse_random_state(random_state)
rs = value.parse_random_generator(random_state)

combinations_by_layer = []
for pairs, layer in pair_gen:
combinations = rs.randint(0, n_library_circuits, size=(n_combinations, len(pairs)))
combinations = rs.integers(0, n_library_circuits, size=(n_combinations, len(pairs)))
combinations_by_layer.append(
CircuitLibraryCombination(layer=layer, combinations=combinations, pairs=pairs)
)
Expand Down Expand Up @@ -541,7 +541,7 @@ def random_rotations_between_grid_interaction_layers_circuit(
*, # forces keyword arguments
device_graph: nx.Graph | None = None,
two_qubit_op_factory: Callable[
[cirq.GridQubit, cirq.GridQubit, np.random.RandomState], cirq.OP_TREE
[cirq.GridQubit, cirq.GridQubit, np.random.Generator], cirq.OP_TREE
] = lambda a, b, _: ops.CZPowGate()(a, b),
pattern: Sequence[GridInteractionLayer] = GRID_STAGGERED_PATTERN,
single_qubit_gates: Sequence[cirq.Gate] = (
Expand Down Expand Up @@ -586,7 +586,7 @@ def random_rotations_between_grid_interaction_layers_circuit(
seed: A seed or random state to use for the pseudorandom number
generator.
"""
prng = value.parse_random_state(seed)
prng = value.parse_random_generator(seed)
qubits = list(qubits)
if device_graph is None:
coupled_qubit_pairs = _coupled_qubit_pairs(qubits)
Expand Down Expand Up @@ -642,7 +642,7 @@ def __init__(
self,
qubits: Sequence[cirq.Qid],
single_qubit_gates: Sequence[cirq.Gate],
prng: np.random.RandomState,
prng: np.random.Generator,
) -> None:
self.qubits = qubits
self.single_qubit_gates = single_qubit_gates
Expand All @@ -652,9 +652,11 @@ def new_layer(self, previous_single_qubit_layer: cirq.Moment) -> cirq.Moment:
def random_gate(qubit: cirq.Qid) -> cirq.Gate:
excluded_op = previous_single_qubit_layer.operation_at(qubit)
excluded_gate = excluded_op.gate if excluded_op is not None else None
g = self.single_qubit_gates[self.prng.randint(0, len(self.single_qubit_gates))]
g = self.single_qubit_gates[int(self.prng.integers(0, len(self.single_qubit_gates)))]
while g is excluded_gate:
g = self.single_qubit_gates[self.prng.randint(0, len(self.single_qubit_gates))]
g = self.single_qubit_gates[
int(self.prng.integers(0, len(self.single_qubit_gates)))
]
return g

return circuits.Moment(random_gate(q).on(q) for q in self.qubits)
Expand All @@ -672,7 +674,7 @@ def new_layer(self, previous_single_qubit_layer: cirq.Moment) -> cirq.Moment:


def _single_qubit_gates_arg_to_factory(
single_qubit_gates: Sequence[cirq.Gate], qubits: Sequence[cirq.Qid], prng: np.random.RandomState
single_qubit_gates: Sequence[cirq.Gate], qubits: Sequence[cirq.Qid], prng: np.random.Generator
) -> _SingleQubitLayerFactory:
"""Parse the `single_qubit_gates` argument for circuit generation functions.

Expand All @@ -689,10 +691,10 @@ def _single_qubit_gates_arg_to_factory(
def _two_qubit_layer(
coupled_qubit_pairs: list[GridQubitPairT],
two_qubit_op_factory: Callable[
[cirq.GridQubit, cirq.GridQubit, np.random.RandomState], cirq.OP_TREE
[cirq.GridQubit, cirq.GridQubit, np.random.Generator], cirq.OP_TREE
],
layer: GridInteractionLayer,
prng: np.random.RandomState,
prng: np.random.Generator,
) -> Iterator[cirq.OP_TREE]:
for a, b in coupled_qubit_pairs:
if (a, b) in layer or (b, a) in layer:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,29 +51,20 @@ def test_random_rotation_between_two_qubit_circuit() -> None:
assert len(circuit) == 4 * 2
assert circuit.all_qubits() == {q0, q1}

cirq.testing.assert_has_diagram(
circuit,
"""\
0 1
│ │
Y^0.5 X^0.5
│ │
@─────────────@
│ │
PhX(0.25)^0.5 Y^0.5
│ │
@─────────────@
│ │
Y^0.5 X^0.5
│ │
@─────────────@
│ │
X^0.5 PhX(0.25)^0.5
│ │
@─────────────@
│ │""",
transpose=True,
for i, moment in enumerate(circuit):
if i % 2 == 1:
assert moment == cirq.Moment(cirq.CZ(q0, q1))
else:
assert len(moment) == 2 and moment.qubits == {q0, q1}

circuit2 = random_rotations_between_two_qubit_circuit(
q0, q1, 4, seed=np.random.default_rng(52), add_final_single_qubit_layer=False
)
assert circuit2 == circuit
circuit3 = random_rotations_between_two_qubit_circuit(
q0, q1, 4, seed=53, add_final_single_qubit_layer=False
)
assert circuit3 != circuit


def test_generate_library_of_2q_circuits() -> None:
Expand Down Expand Up @@ -370,7 +361,7 @@ def test_random_rotations_between_grid_interaction_layers(
qubits: Iterable[cirq.GridQubit],
depth: int,
two_qubit_op_factory: Callable[
[cirq.GridQubit, cirq.GridQubit, np.random.RandomState], cirq.OP_TREE
[cirq.GridQubit, cirq.GridQubit, np.random.Generator], cirq.OP_TREE
],
pattern: Sequence[GridInteractionLayer],
single_qubit_gates: Sequence[cirq.Gate],
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/experiments/two_qubit_xeb.py
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,7 @@ def parallel_xeb_workflow(
Raises:
ValueError: If qubits are not specified and the sampler has no device.
"""
rs = value.parse_random_state(random_state)
rs = value.parse_random_generator(random_state)

qubits, pairs = qubits_and_pairs(sampler, qubits, pairs)
graph = nx.Graph(pairs)
Expand Down
4 changes: 2 additions & 2 deletions cirq-core/cirq/experiments/two_qubit_xeb_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def test_parallel_two_qubit_xeb(
res = cirq.experiments.parallel_two_qubit_xeb(
sampler=sampler,
qubits=qubits,
n_repetitions=100,
n_repetitions=2000,
n_combinations=1,
n_circuits=1,
cycle_depths=[3, 4, 5],
Expand Down Expand Up @@ -299,7 +299,7 @@ def test_run_rb_and_xeb(
sampler=sampler,
qubits=qubits,
pairs=pairs,
repetitions=100,
repetitions=2000,
num_clifford_range=tuple(np.arange(3, 10, 1)),
xeb_combinations=1,
num_circuits=1,
Expand Down
33 changes: 9 additions & 24 deletions cirq-core/cirq/experiments/xeb_fitting_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,28 +184,13 @@ def test_parameterize_phased_fsim_circuit(gate) -> None:
)

p_circuit = parameterize_circuit(circuit, SqrtISwapXEBOptions())
cirq.testing.assert_has_diagram(
p_circuit,
"""\
0 1
│ │
Y^0.5 X^0.5
│ │
PhFSim(theta, zeta, chi, gamma, phi)─PhFSim(theta, zeta, chi, gamma, phi)
│ │
PhX(0.25)^0.5 Y^0.5
│ │
PhFSim(theta, zeta, chi, gamma, phi)─PhFSim(theta, zeta, chi, gamma, phi)
│ │
Y^0.5 X^0.5
│ │
PhFSim(theta, zeta, chi, gamma, phi)─PhFSim(theta, zeta, chi, gamma, phi)
│ │
X^0.5 PhX(0.25)^0.5
│ │
""",
transpose=True,
)
parameterized_gate = SqrtISwapXEBOptions().get_parameterized_gate()
assert len(p_circuit) == len(circuit)
for moment, p_moment in zip(circuit, p_circuit):
if moment == cirq.Moment(gate(q0, q1)):
assert p_moment == cirq.Moment(parameterized_gate(q0, q1))
else:
assert p_moment == moment


def test_get_initial_simplex() -> None:
Expand All @@ -218,7 +203,7 @@ def test_get_initial_simplex() -> None:

def test_characterize_phased_fsim_parameters_with_xeb(pool) -> None:
q0, q1 = cirq.LineQubit.range(2)
rs = np.random.RandomState(52)
rs = np.random.default_rng(52)
circuits = [
rqcg.random_rotations_between_two_qubit_circuit(
q0, q1, depth=20, two_qubit_op_factory=lambda a, b, _: cirq.SQRT_ISWAP(a, b), seed=rs
Expand Down Expand Up @@ -270,7 +255,7 @@ def test_parallel_full_workflow(request, use_pool) -> None:
cycle_depths = [2, 3, 4]
graph = _gridqubits_to_graph_device(cirq.GridQubit.rect(2, 2))
combs = rqcg.get_random_combinations_for_device(
n_library_circuits=len(circuits), n_combinations=2, device_graph=graph, random_state=10
n_library_circuits=len(circuits), n_combinations=2, device_graph=graph, random_state=20
)

sampled_df = sample_2q_xeb_circuits(
Expand Down
4 changes: 2 additions & 2 deletions cirq-core/cirq/experiments/xeb_sampling.py
Original file line number Diff line number Diff line change
Expand Up @@ -343,8 +343,8 @@ def sample_2q_xeb_circuits(
# Construct truncated-with-measurement circuits to run.
tasks = _generate_sample_2q_xeb_tasks(zipped_circuits, cycle_depths)
if shuffle is not None:
prng = value.parse_random_state(shuffle)
prng.shuffle(tasks) # type: ignore[arg-type]
prng = value.parse_random_generator(shuffle)
prng.shuffle(tasks)

# Batch and run tasks.
records = _execute_sample_2q_xeb_tasks_in_batches(
Expand Down
4 changes: 2 additions & 2 deletions cirq-core/cirq/linalg/decompositions_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -588,9 +588,9 @@ def _random_two_qubit_unitaries(num_samples: int, random_state: cirq.RANDOM_STAT

kr = _local_two_qubit_unitaries(num_samples, random_state)

prng = value.parse_random_state(random_state)
prng = value.parse_random_generator(random_state)
# Generate the non-local part by explicit matrix exponentiation.
kak_vecs = prng.rand(num_samples, 3) * np.pi
kak_vecs = prng.random((num_samples, 3)) * np.pi
gens = np.einsum('...a,abc->...bc', kak_vecs, _kak_gens)
evals, evecs = np.linalg.eigh(gens)
A = np.einsum('...ab,...b,...cb', evecs, np.exp(1j * evals), evecs.conj())
Expand Down
Loading
Loading