cirq-core 1.3.0.dev20231201141002__py3-none-any.whl → 1.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cirq/__init__.py +4 -0
- cirq/_compat.py +9 -11
- cirq/_compat_test.py +45 -56
- cirq/_version.py +31 -1
- cirq/_version_test.py +1 -1
- cirq/circuits/circuit.py +13 -8
- cirq/circuits/circuit_operation.py +2 -1
- cirq/circuits/circuit_test.py +2 -2
- cirq/circuits/frozen_circuit.py +3 -2
- cirq/circuits/moment.py +12 -10
- cirq/circuits/qasm_output.py +5 -1
- cirq/circuits/qasm_output_test.py +25 -10
- cirq/contrib/qcircuit/qcircuit_diagram_info.py +9 -7
- cirq/contrib/quimb/mps_simulator_test.py +1 -1
- cirq/contrib/quimb/state_vector.py +9 -2
- cirq/contrib/svg/svg.py +2 -1
- cirq/contrib/svg/svg_test.py +1 -0
- cirq/devices/grid_qubit.py +85 -32
- cirq/devices/grid_qubit_test.py +22 -4
- cirq/devices/line_qubit.py +74 -26
- cirq/devices/line_qubit_test.py +19 -0
- cirq/devices/noise_utils.py +33 -31
- cirq/devices/noise_utils_test.py +1 -84
- cirq/devices/superconducting_qubits_noise_properties.py +7 -6
- cirq/experiments/__init__.py +8 -0
- cirq/experiments/qubit_characterizations.py +288 -44
- cirq/experiments/qubit_characterizations_test.py +61 -7
- cirq/experiments/random_quantum_circuit_generation.py +1 -1
- cirq/experiments/single_qubit_readout_calibration.py +132 -6
- cirq/experiments/single_qubit_readout_calibration_test.py +3 -1
- cirq/experiments/t1_decay_experiment.py +14 -7
- cirq/experiments/t1_decay_experiment_test.py +14 -26
- cirq/experiments/two_qubit_xeb.py +483 -0
- cirq/experiments/two_qubit_xeb_test.py +304 -0
- cirq/json_resolver_cache.py +2 -0
- cirq/linalg/decompositions.py +11 -13
- cirq/linalg/decompositions_test.py +1 -3
- cirq/linalg/diagonalize.py +5 -4
- cirq/linalg/predicates.py +8 -6
- cirq/linalg/transformations.py +2 -1
- cirq/linalg/transformations_test.py +1 -1
- cirq/ops/__init__.py +2 -0
- cirq/ops/clifford_gate.py +59 -16
- cirq/ops/common_gates_test.py +1 -2
- cirq/ops/control_values.py +4 -3
- cirq/ops/controlled_gate_test.py +1 -3
- cirq/ops/gate_operation.py +10 -1
- cirq/ops/named_qubit.py +74 -28
- cirq/ops/named_qubit_test.py +19 -0
- cirq/ops/parity_gates.py +5 -0
- cirq/ops/parity_gates_test.py +2 -10
- cirq/ops/pauli_gates.py +5 -2
- cirq/ops/pauli_string.py +2 -2
- cirq/ops/permutation_gate.py +16 -18
- cirq/ops/phased_iswap_gate_test.py +1 -3
- cirq/ops/phased_x_gate.py +1 -1
- cirq/ops/phased_x_z_gate.py +17 -1
- cirq/ops/phased_x_z_gate_test.py +24 -0
- cirq/ops/qid_util.py +4 -8
- cirq/ops/qubit_manager.py +7 -4
- cirq/ops/qubit_manager_test.py +20 -0
- cirq/ops/raw_types.py +5 -2
- cirq/ops/raw_types_test.py +14 -15
- cirq/ops/uniform_superposition_gate.py +123 -0
- cirq/ops/uniform_superposition_gate_test.py +94 -0
- cirq/protocols/approximate_equality_protocol_test.py +2 -2
- cirq/protocols/circuit_diagram_info_protocol.py +6 -4
- cirq/protocols/commutes_protocol.py +2 -4
- cirq/protocols/decompose_protocol.py +7 -12
- cirq/protocols/decompose_protocol_test.py +7 -3
- cirq/protocols/has_stabilizer_effect_protocol.py +1 -5
- cirq/protocols/has_stabilizer_effect_protocol_test.py +13 -4
- cirq/protocols/json_serialization.py +51 -181
- cirq/protocols/json_serialization_test.py +13 -47
- cirq/protocols/json_test_data/CircuitOperation.json +131 -148
- cirq/protocols/json_test_data/CircuitOperation.json_inward +55 -0
- cirq/protocols/json_test_data/CircuitOperation.repr_inward +6 -0
- cirq/protocols/json_test_data/FrozenCircuit.json +196 -210
- cirq/protocols/json_test_data/FrozenCircuit.json_inward +35 -0
- cirq/protocols/json_test_data/FrozenCircuit.repr_inward +4 -0
- cirq/protocols/json_test_data/UniformSuperpositionGate.json +5 -0
- cirq/protocols/json_test_data/UniformSuperpositionGate.repr +1 -0
- cirq/protocols/json_test_data/cirq.MSGate.json +4 -0
- cirq/protocols/json_test_data/cirq.MSGate.repr +1 -0
- cirq/protocols/json_test_data/spec.py +2 -0
- cirq/protocols/pow_protocol_test.py +1 -3
- cirq/protocols/resolve_parameters.py +4 -2
- cirq/qis/__init__.py +10 -0
- cirq/qis/clifford_tableau.py +8 -2
- cirq/qis/noise_utils.py +123 -0
- cirq/qis/noise_utils_test.py +97 -0
- cirq/sim/classical_simulator.py +227 -87
- cirq/sim/classical_simulator_test.py +135 -0
- cirq/sim/clifford/clifford_simulator_test.py +4 -2
- cirq/sim/mux.py +5 -3
- cirq/sim/simulation_product_state.py +15 -10
- cirq/sim/simulation_state.py +1 -1
- cirq/sim/simulation_state_test.py +2 -2
- cirq/sim/simulator_base.py +3 -3
- cirq/sim/state_vector_simulation_state.py +4 -4
- cirq/sim/state_vector_simulator.py +17 -2
- cirq/study/__init__.py +1 -0
- cirq/study/result.py +14 -0
- cirq/study/result_test.py +6 -0
- cirq/study/sweeps.py +4 -2
- cirq/study/sweeps_test.py +8 -0
- cirq/testing/__init__.py +6 -1
- cirq/testing/_compat_test_data/__init__.py +3 -3
- cirq/testing/_compat_test_data/module_a/__init__.py +2 -2
- cirq/testing/circuit_compare.py +1 -1
- cirq/testing/consistent_qasm.py +6 -0
- cirq/testing/gate_features.py +10 -0
- cirq/testing/lin_alg_utils.py +5 -3
- cirq/transformers/__init__.py +15 -0
- cirq/transformers/analytical_decompositions/controlled_gate_decomposition.py +3 -1
- cirq/transformers/analytical_decompositions/two_qubit_to_cz.py +24 -0
- cirq/transformers/analytical_decompositions/two_qubit_to_cz_test.py +17 -0
- cirq/transformers/dynamical_decoupling.py +122 -0
- cirq/transformers/dynamical_decoupling_test.py +123 -0
- cirq/transformers/gauge_compiling/__init__.py +26 -0
- cirq/transformers/gauge_compiling/cz_gauge.py +46 -0
- cirq/transformers/gauge_compiling/cz_gauge_test.py +23 -0
- cirq/transformers/gauge_compiling/gauge_compiling.py +214 -0
- cirq/transformers/gauge_compiling/gauge_compiling_test.py +41 -0
- cirq/transformers/gauge_compiling/gauge_compiling_test_utils.py +83 -0
- cirq/transformers/gauge_compiling/gauge_compiling_test_utils_test.py +52 -0
- cirq/transformers/gauge_compiling/iswap_gauge.py +105 -0
- cirq/transformers/gauge_compiling/iswap_gauge_test.py +23 -0
- cirq/transformers/gauge_compiling/spin_inversion_gauge.py +33 -0
- cirq/transformers/gauge_compiling/spin_inversion_gauge_test.py +37 -0
- cirq/transformers/gauge_compiling/sqrt_cz_gauge.py +64 -0
- cirq/transformers/gauge_compiling/sqrt_cz_gauge_test.py +27 -0
- cirq/transformers/gauge_compiling/sqrt_iswap_gauge.py +94 -0
- cirq/transformers/gauge_compiling/sqrt_iswap_gauge_test.py +22 -0
- cirq/transformers/heuristic_decompositions/two_qubit_gate_tabulation.py +1 -0
- cirq/transformers/merge_k_qubit_gates_test.py +23 -23
- cirq/transformers/merge_single_qubit_gates_test.py +14 -14
- cirq/transformers/optimize_for_target_gateset.py +39 -17
- cirq/transformers/optimize_for_target_gateset_test.py +189 -39
- cirq/transformers/qubit_management_transformers.py +1 -1
- cirq/transformers/routing/visualize_routed_circuit_test.py +17 -17
- cirq/transformers/stratify_test.py +13 -13
- cirq/transformers/target_gatesets/compilation_target_gateset.py +26 -2
- cirq/transformers/target_gatesets/compilation_target_gateset_test.py +16 -16
- cirq/transformers/target_gatesets/cz_gateset.py +4 -0
- cirq/transformers/transformer_api.py +1 -2
- cirq/transformers/transformer_primitives.py +15 -14
- cirq/transformers/transformer_primitives_test.py +99 -72
- cirq/value/classical_data.py +6 -6
- cirq/value/value_equality_attr.py +4 -0
- cirq/work/sampler.py +3 -4
- cirq/work/sampler_test.py +25 -0
- {cirq_core-1.3.0.dev20231201141002.dist-info → cirq_core-1.4.0.dist-info}/METADATA +10 -19
- {cirq_core-1.3.0.dev20231201141002.dist-info → cirq_core-1.4.0.dist-info}/RECORD +157 -130
- {cirq_core-1.3.0.dev20231201141002.dist-info → cirq_core-1.4.0.dist-info}/WHEEL +1 -1
- {cirq_core-1.3.0.dev20231201141002.dist-info → cirq_core-1.4.0.dist-info}/LICENSE +0 -0
- {cirq_core-1.3.0.dev20231201141002.dist-info → cirq_core-1.4.0.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# Copyright 2024 The Cirq Developers
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Transformer pass that adds dynamical decoupling operations to a circuit."""
|
|
16
|
+
|
|
17
|
+
from functools import reduce
|
|
18
|
+
from typing import Dict, Optional, Sequence, Tuple, Union
|
|
19
|
+
|
|
20
|
+
from cirq.transformers import transformer_api
|
|
21
|
+
import cirq
|
|
22
|
+
import numpy as np
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _repeat_sequence(
|
|
26
|
+
base_sequence: Sequence['cirq.Gate'], num_idle_moments: int
|
|
27
|
+
) -> Sequence['cirq.Gate']:
|
|
28
|
+
"""Returns the longest possible dynamical decoupling sequence."""
|
|
29
|
+
repeat_times = num_idle_moments // len(base_sequence)
|
|
30
|
+
return list(base_sequence) * repeat_times
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _get_dd_sequence_from_schema_name(schema: str) -> Sequence['cirq.Gate']:
|
|
34
|
+
"""Gets dynamical decoupling sequence from a schema name."""
|
|
35
|
+
dd_sequence: Sequence['cirq.Gate']
|
|
36
|
+
match schema:
|
|
37
|
+
case 'XX_PAIR':
|
|
38
|
+
dd_sequence = (cirq.X, cirq.X)
|
|
39
|
+
case 'X_XINV':
|
|
40
|
+
dd_sequence = (cirq.X, cirq.X**-1)
|
|
41
|
+
case 'YY_PAIR':
|
|
42
|
+
dd_sequence = (cirq.Y, cirq.Y)
|
|
43
|
+
case 'Y_YINV':
|
|
44
|
+
dd_sequence = (cirq.Y, cirq.Y**-1)
|
|
45
|
+
case _:
|
|
46
|
+
raise ValueError('Invalid schema name.')
|
|
47
|
+
return dd_sequence
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _validate_dd_sequence(dd_sequence: Sequence['cirq.Gate']) -> None:
|
|
51
|
+
"""Validates a given dynamical decoupling sequence.
|
|
52
|
+
|
|
53
|
+
Args:
|
|
54
|
+
dd_sequence: Input dynamical sequence to be validated.
|
|
55
|
+
|
|
56
|
+
Returns:
|
|
57
|
+
A tuple containing:
|
|
58
|
+
- is_valid (bool): True if the dd sequence is valid, False otherwise.
|
|
59
|
+
- error_message (str): An error message if the dd sequence is invalid, else None.
|
|
60
|
+
|
|
61
|
+
Raises:
|
|
62
|
+
ValueError: If dd_sequence is not valid.
|
|
63
|
+
"""
|
|
64
|
+
if len(dd_sequence) < 2:
|
|
65
|
+
raise ValueError('Invalid dynamical decoupling sequence. Expect more than one gates.')
|
|
66
|
+
matrices = [cirq.unitary(gate) for gate in dd_sequence]
|
|
67
|
+
product = reduce(np.matmul, matrices)
|
|
68
|
+
|
|
69
|
+
if not cirq.equal_up_to_global_phase(product, np.eye(2)):
|
|
70
|
+
raise ValueError(
|
|
71
|
+
'Invalid dynamical decoupling sequence. Expect sequence production equals'
|
|
72
|
+
f' identity up to a global phase, got {product}.'.replace('\n', ' ')
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _parse_dd_sequence(schema: Union[str, Sequence['cirq.Gate']]) -> Sequence['cirq.Gate']:
|
|
77
|
+
"""Parses and returns dynamical decoupling sequence from schema."""
|
|
78
|
+
if isinstance(schema, str):
|
|
79
|
+
dd_sequence = _get_dd_sequence_from_schema_name(schema)
|
|
80
|
+
else:
|
|
81
|
+
_validate_dd_sequence(schema)
|
|
82
|
+
dd_sequence = schema
|
|
83
|
+
return dd_sequence
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@transformer_api.transformer
|
|
87
|
+
def add_dynamical_decoupling(
|
|
88
|
+
circuit: 'cirq.AbstractCircuit',
|
|
89
|
+
*,
|
|
90
|
+
context: Optional['cirq.TransformerContext'] = None,
|
|
91
|
+
schema: Union[str, Sequence['cirq.Gate']] = 'X_XINV',
|
|
92
|
+
) -> 'cirq.Circuit':
|
|
93
|
+
"""Adds dynamical decoupling gate operations to idle moments of a given circuit.
|
|
94
|
+
This transformer preserves the moment structure of the circuit.
|
|
95
|
+
|
|
96
|
+
Args:
|
|
97
|
+
circuit: Input circuit to transform.
|
|
98
|
+
context: `cirq.TransformerContext` storing common configurable options for transformers.
|
|
99
|
+
schema: Dynamical decoupling schema name or a dynamical decoupling sequence.
|
|
100
|
+
If a schema is specified, provided dynamical decouping sequence will be used.
|
|
101
|
+
Otherwise, customized dynamical decoupling sequence will be applied.
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
A copy of the input circuit with dynamical decoupling operations.
|
|
105
|
+
"""
|
|
106
|
+
last_busy_moment_by_qubits: Dict['cirq.Qid', int] = {q: 0 for q in circuit.all_qubits()}
|
|
107
|
+
insert_into: list[Tuple[int, 'cirq.OP_TREE']] = []
|
|
108
|
+
|
|
109
|
+
base_dd_sequence = _parse_dd_sequence(schema)
|
|
110
|
+
|
|
111
|
+
for moment_id, moment in enumerate(circuit):
|
|
112
|
+
for q in moment.qubits:
|
|
113
|
+
insert_gates = _repeat_sequence(
|
|
114
|
+
base_dd_sequence, num_idle_moments=moment_id - last_busy_moment_by_qubits[q] - 1
|
|
115
|
+
)
|
|
116
|
+
for idx, gate in enumerate(insert_gates):
|
|
117
|
+
insert_into.append((last_busy_moment_by_qubits[q] + idx + 1, gate.on(q)))
|
|
118
|
+
last_busy_moment_by_qubits[q] = moment_id
|
|
119
|
+
|
|
120
|
+
updated_circuit = circuit.unfreeze(copy=True)
|
|
121
|
+
updated_circuit.batch_insert_into(insert_into)
|
|
122
|
+
return updated_circuit
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# Copyright 2024 The Cirq Developers
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
from typing import Sequence, Union
|
|
16
|
+
import cirq
|
|
17
|
+
from cirq import add_dynamical_decoupling
|
|
18
|
+
import pytest
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def assert_dd(
|
|
22
|
+
input_circuit: cirq.Circuit,
|
|
23
|
+
expected_circuit: cirq.Circuit,
|
|
24
|
+
schema: Union[str, Sequence['cirq.Gate']],
|
|
25
|
+
):
|
|
26
|
+
updated_circuit = add_dynamical_decoupling(input_circuit, schema=schema)
|
|
27
|
+
cirq.testing.assert_same_circuits(updated_circuit, expected_circuit)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def test_no_insert_due_to_no_consecutive_moments():
|
|
31
|
+
a = cirq.NamedQubit('a')
|
|
32
|
+
b = cirq.NamedQubit('b')
|
|
33
|
+
|
|
34
|
+
# No insertion as there is no room for a dd sequence.
|
|
35
|
+
assert_dd(
|
|
36
|
+
input_circuit=cirq.Circuit(
|
|
37
|
+
cirq.Moment(cirq.H(a)), cirq.Moment(cirq.CNOT(a, b)), cirq.Moment(cirq.H(b))
|
|
38
|
+
),
|
|
39
|
+
expected_circuit=cirq.Circuit(
|
|
40
|
+
cirq.Moment(cirq.H(a)), cirq.Moment(cirq.CNOT(a, b)), cirq.Moment(cirq.H(b))
|
|
41
|
+
),
|
|
42
|
+
schema='XX_PAIR',
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@pytest.mark.parametrize(
|
|
47
|
+
'schema,inserted_gates',
|
|
48
|
+
[
|
|
49
|
+
('XX_PAIR', (cirq.X, cirq.X)),
|
|
50
|
+
('X_XINV', (cirq.X, cirq.X**-1)),
|
|
51
|
+
('YY_PAIR', (cirq.Y, cirq.Y)),
|
|
52
|
+
('Y_YINV', (cirq.Y, cirq.Y**-1)),
|
|
53
|
+
],
|
|
54
|
+
)
|
|
55
|
+
def test_insert_provided_schema(schema: str, inserted_gates: Sequence['cirq.Gate']):
|
|
56
|
+
a = cirq.NamedQubit('a')
|
|
57
|
+
b = cirq.NamedQubit('b')
|
|
58
|
+
c = cirq.NamedQubit('c')
|
|
59
|
+
|
|
60
|
+
input_circuit = cirq.Circuit(
|
|
61
|
+
cirq.Moment(cirq.H(a)),
|
|
62
|
+
cirq.Moment(cirq.CNOT(a, b)),
|
|
63
|
+
cirq.Moment(cirq.CNOT(b, c)),
|
|
64
|
+
cirq.Moment(cirq.CNOT(b, c)),
|
|
65
|
+
cirq.Moment(cirq.measure_each(a, b, c)),
|
|
66
|
+
)
|
|
67
|
+
expected_circuit = cirq.Circuit(
|
|
68
|
+
cirq.Moment(cirq.H(a)),
|
|
69
|
+
cirq.Moment(cirq.CNOT(a, b)),
|
|
70
|
+
cirq.Moment(cirq.CNOT(b, c), inserted_gates[0](a)),
|
|
71
|
+
cirq.Moment(cirq.CNOT(b, c), inserted_gates[1](a)),
|
|
72
|
+
cirq.Moment(cirq.measure_each(a, b, c)),
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
# Insert one dynamical decoupling sequence in idle moments.
|
|
76
|
+
assert_dd(input_circuit, expected_circuit, schema=schema)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def test_insert_by_customized_dd_sequence():
|
|
80
|
+
a = cirq.NamedQubit('a')
|
|
81
|
+
b = cirq.NamedQubit('b')
|
|
82
|
+
c = cirq.NamedQubit('c')
|
|
83
|
+
|
|
84
|
+
assert_dd(
|
|
85
|
+
input_circuit=cirq.Circuit(
|
|
86
|
+
cirq.Moment(cirq.H(a)),
|
|
87
|
+
cirq.Moment(cirq.CNOT(a, b)),
|
|
88
|
+
cirq.Moment(cirq.CNOT(b, c)),
|
|
89
|
+
cirq.Moment(cirq.CNOT(b, c)),
|
|
90
|
+
cirq.Moment(cirq.CNOT(b, c)),
|
|
91
|
+
cirq.Moment(cirq.CNOT(b, c)),
|
|
92
|
+
cirq.Moment(cirq.measure_each(a, b, c)),
|
|
93
|
+
),
|
|
94
|
+
expected_circuit=cirq.Circuit(
|
|
95
|
+
cirq.Moment(cirq.H(a)),
|
|
96
|
+
cirq.Moment(cirq.CNOT(a, b)),
|
|
97
|
+
cirq.Moment(cirq.CNOT(b, c), cirq.X(a)),
|
|
98
|
+
cirq.Moment(cirq.CNOT(b, c), cirq.X(a)),
|
|
99
|
+
cirq.Moment(cirq.CNOT(b, c), cirq.Y(a)),
|
|
100
|
+
cirq.Moment(cirq.CNOT(b, c), cirq.Y(a)),
|
|
101
|
+
cirq.Moment(cirq.measure_each(a, b, c)),
|
|
102
|
+
),
|
|
103
|
+
schema=[cirq.X, cirq.X, cirq.Y, cirq.Y],
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@pytest.mark.parametrize(
|
|
108
|
+
'schema,error_msg_regex',
|
|
109
|
+
[
|
|
110
|
+
('INVALID_SCHEMA', 'Invalid schema name.'),
|
|
111
|
+
([cirq.X], 'Invalid dynamical decoupling sequence. Expect more than one gates.'),
|
|
112
|
+
(
|
|
113
|
+
[cirq.X, cirq.H],
|
|
114
|
+
'Invalid dynamical decoupling sequence. Expect sequence production equals identity'
|
|
115
|
+
' up to a global phase, got',
|
|
116
|
+
),
|
|
117
|
+
],
|
|
118
|
+
)
|
|
119
|
+
def test_invalid_dd_schema(schema: Union[str, Sequence['cirq.Gate']], error_msg_regex):
|
|
120
|
+
a = cirq.NamedQubit('a')
|
|
121
|
+
input_circuit = cirq.Circuit(cirq.H(a))
|
|
122
|
+
with pytest.raises(ValueError, match=error_msg_regex):
|
|
123
|
+
add_dynamical_decoupling(input_circuit, schema=schema)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# Copyright 2024 The Cirq Developers
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
from cirq.transformers.gauge_compiling.gauge_compiling import (
|
|
17
|
+
ConstantGauge,
|
|
18
|
+
Gauge,
|
|
19
|
+
GaugeSelector,
|
|
20
|
+
GaugeTransformer,
|
|
21
|
+
)
|
|
22
|
+
from cirq.transformers.gauge_compiling.sqrt_cz_gauge import SqrtCZGaugeTransformer
|
|
23
|
+
from cirq.transformers.gauge_compiling.spin_inversion_gauge import SpinInversionGaugeTransformer
|
|
24
|
+
from cirq.transformers.gauge_compiling.cz_gauge import CZGaugeTransformer
|
|
25
|
+
from cirq.transformers.gauge_compiling.iswap_gauge import ISWAPGaugeTransformer
|
|
26
|
+
from cirq.transformers.gauge_compiling.sqrt_iswap_gauge import SqrtISWAPGaugeTransformer
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# Copyright 2024 The Cirq Developers
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""A Gauge Transformer for the CZ gate."""
|
|
16
|
+
|
|
17
|
+
from cirq.transformers.gauge_compiling.gauge_compiling import (
|
|
18
|
+
GaugeTransformer,
|
|
19
|
+
GaugeSelector,
|
|
20
|
+
ConstantGauge,
|
|
21
|
+
)
|
|
22
|
+
from cirq.ops.common_gates import CZ
|
|
23
|
+
from cirq import ops
|
|
24
|
+
|
|
25
|
+
CZGaugeSelector = GaugeSelector(
|
|
26
|
+
gauges=[
|
|
27
|
+
ConstantGauge(two_qubit_gate=CZ, pre_q0=ops.I, pre_q1=ops.I, post_q0=ops.I, post_q1=ops.I),
|
|
28
|
+
ConstantGauge(two_qubit_gate=CZ, pre_q0=ops.I, pre_q1=ops.X, post_q0=ops.Z, post_q1=ops.X),
|
|
29
|
+
ConstantGauge(two_qubit_gate=CZ, pre_q0=ops.I, pre_q1=ops.Y, post_q0=ops.Z, post_q1=ops.Y),
|
|
30
|
+
ConstantGauge(two_qubit_gate=CZ, pre_q0=ops.I, pre_q1=ops.Z, post_q0=ops.I, post_q1=ops.Z),
|
|
31
|
+
ConstantGauge(two_qubit_gate=CZ, pre_q0=ops.X, pre_q1=ops.I, post_q0=ops.X, post_q1=ops.Z),
|
|
32
|
+
ConstantGauge(two_qubit_gate=CZ, pre_q0=ops.X, pre_q1=ops.X, post_q0=ops.Y, post_q1=ops.Y),
|
|
33
|
+
ConstantGauge(two_qubit_gate=CZ, pre_q0=ops.X, pre_q1=ops.Y, post_q0=ops.Y, post_q1=ops.X),
|
|
34
|
+
ConstantGauge(two_qubit_gate=CZ, pre_q0=ops.X, pre_q1=ops.Z, post_q0=ops.X, post_q1=ops.I),
|
|
35
|
+
ConstantGauge(two_qubit_gate=CZ, pre_q0=ops.Y, pre_q1=ops.I, post_q0=ops.Y, post_q1=ops.Z),
|
|
36
|
+
ConstantGauge(two_qubit_gate=CZ, pre_q0=ops.Y, pre_q1=ops.X, post_q0=ops.X, post_q1=ops.Y),
|
|
37
|
+
ConstantGauge(two_qubit_gate=CZ, pre_q0=ops.Y, pre_q1=ops.Y, post_q0=ops.X, post_q1=ops.X),
|
|
38
|
+
ConstantGauge(two_qubit_gate=CZ, pre_q0=ops.Y, pre_q1=ops.Z, post_q0=ops.Y, post_q1=ops.I),
|
|
39
|
+
ConstantGauge(two_qubit_gate=CZ, pre_q0=ops.Z, pre_q1=ops.I, post_q0=ops.Z, post_q1=ops.I),
|
|
40
|
+
ConstantGauge(two_qubit_gate=CZ, pre_q0=ops.Z, pre_q1=ops.X, post_q0=ops.I, post_q1=ops.X),
|
|
41
|
+
ConstantGauge(two_qubit_gate=CZ, pre_q0=ops.Z, pre_q1=ops.Y, post_q0=ops.I, post_q1=ops.Y),
|
|
42
|
+
ConstantGauge(two_qubit_gate=CZ, pre_q0=ops.Z, pre_q1=ops.Z, post_q0=ops.Z, post_q1=ops.Z),
|
|
43
|
+
]
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
CZGaugeTransformer = GaugeTransformer(target=CZ, gauge_selector=CZGaugeSelector)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# Copyright 2024 The Cirq Developers
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
import cirq
|
|
17
|
+
from cirq.transformers.gauge_compiling import CZGaugeTransformer
|
|
18
|
+
from cirq.transformers.gauge_compiling.gauge_compiling_test_utils import GaugeTester
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class TestCZGauge(GaugeTester):
|
|
22
|
+
two_qubit_gate = cirq.CZ
|
|
23
|
+
gauge_transformer = CZGaugeTransformer
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
# Copyright 2024 The Cirq Developers
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Creates the abstraction for gauge compiling as a cirq transformer."""
|
|
16
|
+
|
|
17
|
+
from typing import Callable, Tuple, Optional, Sequence, Union, List
|
|
18
|
+
import abc
|
|
19
|
+
import itertools
|
|
20
|
+
import functools
|
|
21
|
+
|
|
22
|
+
from dataclasses import dataclass
|
|
23
|
+
from attrs import frozen, field
|
|
24
|
+
import numpy as np
|
|
25
|
+
|
|
26
|
+
from cirq.transformers import transformer_api
|
|
27
|
+
from cirq import ops, circuits
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Gauge(abc.ABC):
|
|
31
|
+
"""A gauge replaces a two qubit gate with an equivalent subcircuit.
|
|
32
|
+
0: pre_q0───────two_qubit_gate───────post_q0
|
|
33
|
+
|
|
|
34
|
+
1: pre_q1───────two_qubit_gate───────post_q1
|
|
35
|
+
|
|
36
|
+
The Gauge class in general represents a family of closely related gauges
|
|
37
|
+
(e.g. random z-rotations); Use `sample` method to get a specific gauge.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def weight(self) -> float:
|
|
41
|
+
"""Returns the relative frequency for selecting this gauge."""
|
|
42
|
+
return 1.0
|
|
43
|
+
|
|
44
|
+
@abc.abstractmethod
|
|
45
|
+
def sample(self, gate: ops.Gate, prng: np.random.Generator) -> "ConstantGauge":
|
|
46
|
+
"""Returns a ConstantGauge sampled from a family of gauges.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
gate: The two qubit gate to replace.
|
|
50
|
+
prng: A numpy random number generator.
|
|
51
|
+
|
|
52
|
+
Returns:
|
|
53
|
+
A ConstantGauge.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@frozen
|
|
58
|
+
class ConstantGauge(Gauge):
|
|
59
|
+
"""A gauge that replaces a two qubit gate with a constant gauge."""
|
|
60
|
+
|
|
61
|
+
two_qubit_gate: ops.Gate
|
|
62
|
+
pre_q0: Tuple[ops.Gate, ...] = field(
|
|
63
|
+
default=(), converter=lambda g: (g,) if isinstance(g, ops.Gate) else tuple(g)
|
|
64
|
+
)
|
|
65
|
+
pre_q1: Tuple[ops.Gate, ...] = field(
|
|
66
|
+
default=(), converter=lambda g: (g,) if isinstance(g, ops.Gate) else tuple(g)
|
|
67
|
+
)
|
|
68
|
+
post_q0: Tuple[ops.Gate, ...] = field(
|
|
69
|
+
default=(), converter=lambda g: (g,) if isinstance(g, ops.Gate) else tuple(g)
|
|
70
|
+
)
|
|
71
|
+
post_q1: Tuple[ops.Gate, ...] = field(
|
|
72
|
+
default=(), converter=lambda g: (g,) if isinstance(g, ops.Gate) else tuple(g)
|
|
73
|
+
)
|
|
74
|
+
swap_qubits: bool = False
|
|
75
|
+
|
|
76
|
+
def sample(self, gate: ops.Gate, prng: np.random.Generator) -> "ConstantGauge":
|
|
77
|
+
return self
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def pre(self) -> Tuple[Tuple[ops.Gate, ...], Tuple[ops.Gate, ...]]:
|
|
81
|
+
"""A tuple (ops to apply to q0, ops to apply to q1)."""
|
|
82
|
+
return self.pre_q0, self.pre_q1
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def post(self) -> Tuple[Tuple[ops.Gate, ...], Tuple[ops.Gate, ...]]:
|
|
86
|
+
"""A tuple (ops to apply to q0, ops to apply to q1)."""
|
|
87
|
+
return self.post_q0, self.post_q1
|
|
88
|
+
|
|
89
|
+
def on(self, q0: ops.Qid, q1: ops.Qid) -> ops.Operation:
|
|
90
|
+
"""Returns the operation that replaces the two qubit gate."""
|
|
91
|
+
if self.swap_qubits:
|
|
92
|
+
return self.two_qubit_gate(q1, q0)
|
|
93
|
+
return self.two_qubit_gate(q0, q1)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@frozen
|
|
97
|
+
class SameGateGauge(Gauge):
|
|
98
|
+
"""Same as ConstantGauge but the new two-qubit gate equals the old gate."""
|
|
99
|
+
|
|
100
|
+
pre_q0: Tuple[ops.Gate, ...] = field(
|
|
101
|
+
default=(), converter=lambda g: (g,) if isinstance(g, ops.Gate) else tuple(g)
|
|
102
|
+
)
|
|
103
|
+
pre_q1: Tuple[ops.Gate, ...] = field(
|
|
104
|
+
default=(), converter=lambda g: (g,) if isinstance(g, ops.Gate) else tuple(g)
|
|
105
|
+
)
|
|
106
|
+
post_q0: Tuple[ops.Gate, ...] = field(
|
|
107
|
+
default=(), converter=lambda g: (g,) if isinstance(g, ops.Gate) else tuple(g)
|
|
108
|
+
)
|
|
109
|
+
post_q1: Tuple[ops.Gate, ...] = field(
|
|
110
|
+
default=(), converter=lambda g: (g,) if isinstance(g, ops.Gate) else tuple(g)
|
|
111
|
+
)
|
|
112
|
+
swap_qubits: bool = False
|
|
113
|
+
|
|
114
|
+
def sample(self, gate: ops.Gate, prng: np.random.Generator) -> ConstantGauge:
|
|
115
|
+
return ConstantGauge(
|
|
116
|
+
two_qubit_gate=gate,
|
|
117
|
+
pre_q0=self.pre_q0,
|
|
118
|
+
pre_q1=self.pre_q1,
|
|
119
|
+
post_q0=self.post_q0,
|
|
120
|
+
post_q1=self.post_q1,
|
|
121
|
+
swap_qubits=self.swap_qubits,
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _select(choices: Sequence[Gauge], probabilites: np.ndarray, prng: np.random.Generator) -> Gauge:
|
|
126
|
+
return choices[prng.choice(len(choices), p=probabilites)]
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
@dataclass(frozen=True)
|
|
130
|
+
class GaugeSelector:
|
|
131
|
+
"""Samples a gauge from a list of gauges."""
|
|
132
|
+
|
|
133
|
+
gauges: Sequence[Gauge]
|
|
134
|
+
|
|
135
|
+
@functools.cached_property
|
|
136
|
+
def _weights(self) -> np.ndarray:
|
|
137
|
+
weights = np.array([g.weight() for g in self.gauges])
|
|
138
|
+
return weights / np.sum(weights)
|
|
139
|
+
|
|
140
|
+
def __call__(self, prng: np.random.Generator) -> Gauge:
|
|
141
|
+
"""Randomly selects a gauge with probability proportional to its weight."""
|
|
142
|
+
return _select(self.gauges, self._weights, prng)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@transformer_api.transformer
|
|
146
|
+
class GaugeTransformer:
|
|
147
|
+
def __init__(
|
|
148
|
+
self,
|
|
149
|
+
# target can be either a specific gate, gatefamily or gateset
|
|
150
|
+
# which allows matching parametric gates.
|
|
151
|
+
target: Union[ops.Gate, ops.Gateset, ops.GateFamily],
|
|
152
|
+
gauge_selector: Callable[[np.random.Generator], Gauge],
|
|
153
|
+
) -> None:
|
|
154
|
+
"""Constructs a GaugeTransformer.
|
|
155
|
+
|
|
156
|
+
Args:
|
|
157
|
+
target: Target two-qubit gate, a gate-family or a gate-set of two-qubit gates.
|
|
158
|
+
gauge_selector: A callable that takes a numpy random number generator
|
|
159
|
+
as an argument and returns a Gauge.
|
|
160
|
+
"""
|
|
161
|
+
self.target = ops.GateFamily(target) if isinstance(target, ops.Gate) else target
|
|
162
|
+
self.gauge_selector = gauge_selector
|
|
163
|
+
|
|
164
|
+
def __call__(
|
|
165
|
+
self,
|
|
166
|
+
circuit: circuits.AbstractCircuit,
|
|
167
|
+
*,
|
|
168
|
+
context: Optional[transformer_api.TransformerContext] = None,
|
|
169
|
+
prng: Optional[np.random.Generator] = None,
|
|
170
|
+
) -> circuits.AbstractCircuit:
|
|
171
|
+
rng = np.random.default_rng() if prng is None else prng
|
|
172
|
+
if context is None:
|
|
173
|
+
context = transformer_api.TransformerContext(deep=False)
|
|
174
|
+
if context.deep:
|
|
175
|
+
raise ValueError('GaugeTransformer cannot be used with deep=True')
|
|
176
|
+
new_moments = []
|
|
177
|
+
left: List[List[ops.Operation]] = []
|
|
178
|
+
right: List[List[ops.Operation]] = []
|
|
179
|
+
for moment in circuit:
|
|
180
|
+
left.clear()
|
|
181
|
+
right.clear()
|
|
182
|
+
center: List[ops.Operation] = []
|
|
183
|
+
for op in moment:
|
|
184
|
+
if isinstance(op, ops.TaggedOperation) and set(op.tags).intersection(
|
|
185
|
+
context.tags_to_ignore
|
|
186
|
+
):
|
|
187
|
+
center.append(op)
|
|
188
|
+
continue
|
|
189
|
+
if op.gate is not None and len(op.qubits) == 2 and op in self.target:
|
|
190
|
+
gauge = self.gauge_selector(rng).sample(op.gate, rng)
|
|
191
|
+
q0, q1 = op.qubits
|
|
192
|
+
left.extend([g(q) for g in gs] for q, gs in zip(op.qubits, gauge.pre))
|
|
193
|
+
center.append(gauge.on(q0, q1))
|
|
194
|
+
right.extend([g(q) for g in gs] for q, gs in zip(op.qubits, gauge.post))
|
|
195
|
+
else:
|
|
196
|
+
center.append(op)
|
|
197
|
+
if left:
|
|
198
|
+
new_moments.extend(_build_moments(left))
|
|
199
|
+
new_moments.append(center)
|
|
200
|
+
if right:
|
|
201
|
+
new_moments.extend(_build_moments(right))
|
|
202
|
+
return circuits.Circuit.from_moments(*new_moments)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _build_moments(operation_by_qubits: List[List[ops.Operation]]) -> List[List[ops.Operation]]:
|
|
206
|
+
"""Builds moments from a list of operations grouped by qubits.
|
|
207
|
+
|
|
208
|
+
Returns a list of moments from a list whose ith element is a list of operations applied
|
|
209
|
+
to qubit i.
|
|
210
|
+
"""
|
|
211
|
+
moments = []
|
|
212
|
+
for moment in itertools.zip_longest(*operation_by_qubits):
|
|
213
|
+
moments.append([op for op in moment if op is not None])
|
|
214
|
+
return moments
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# Copyright 2024 The Cirq Developers
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
import pytest
|
|
16
|
+
import numpy as np
|
|
17
|
+
import cirq
|
|
18
|
+
from cirq.transformers.gauge_compiling import GaugeTransformer, CZGaugeTransformer
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_deep_transformation_not_supported():
|
|
22
|
+
|
|
23
|
+
with pytest.raises(ValueError, match="cannot be used with deep=True"):
|
|
24
|
+
_ = GaugeTransformer(target=cirq.CZ, gauge_selector=lambda _: None)(
|
|
25
|
+
cirq.Circuit(), context=cirq.TransformerContext(deep=True)
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def test_ignore_tags():
|
|
30
|
+
c = cirq.Circuit(cirq.CZ(*cirq.LineQubit.range(2)).with_tags('foo'))
|
|
31
|
+
assert c == CZGaugeTransformer(c, context=cirq.TransformerContext(tags_to_ignore={"foo"}))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_target_can_be_gateset():
|
|
35
|
+
qs = cirq.LineQubit.range(2)
|
|
36
|
+
c = cirq.Circuit(cirq.CZ(*qs))
|
|
37
|
+
transformer = GaugeTransformer(
|
|
38
|
+
target=cirq.Gateset(cirq.CZ), gauge_selector=CZGaugeTransformer.gauge_selector
|
|
39
|
+
)
|
|
40
|
+
want = cirq.Circuit(cirq.Y.on_each(qs), cirq.CZ(*qs), cirq.X.on_each(qs))
|
|
41
|
+
assert transformer(c, prng=np.random.default_rng(0)) == want
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# Copyright 2024 The Cirq Developers
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
from unittest.mock import patch
|
|
17
|
+
import pytest
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
|
|
21
|
+
import cirq
|
|
22
|
+
from cirq.transformers.gauge_compiling import GaugeTransformer, GaugeSelector
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class GaugeTester:
|
|
26
|
+
|
|
27
|
+
two_qubit_gate: cirq.Gate
|
|
28
|
+
gauge_transformer: GaugeTransformer
|
|
29
|
+
must_fail: bool = False
|
|
30
|
+
|
|
31
|
+
@pytest.mark.parametrize(
|
|
32
|
+
['generation_seed', 'transformation_seed'],
|
|
33
|
+
np.random.RandomState(0).randint(2**31, size=(5, 2)).tolist(),
|
|
34
|
+
)
|
|
35
|
+
def test_gauge_transformer(self, generation_seed, transformation_seed):
|
|
36
|
+
c = cirq.Circuit()
|
|
37
|
+
while not any(op.gate == self.two_qubit_gate for op in c.all_operations()):
|
|
38
|
+
c = cirq.testing.random_circuit(
|
|
39
|
+
qubits=3,
|
|
40
|
+
n_moments=3,
|
|
41
|
+
op_density=1,
|
|
42
|
+
gate_domain={self.two_qubit_gate: 2, cirq.X: 1, cirq.Y: 1, cirq.H: 1, cirq.Z: 1},
|
|
43
|
+
random_state=generation_seed,
|
|
44
|
+
)
|
|
45
|
+
generation_seed += 1
|
|
46
|
+
nc = self.gauge_transformer(c, prng=np.random.default_rng(transformation_seed))
|
|
47
|
+
if self.must_fail:
|
|
48
|
+
with pytest.raises(AssertionError):
|
|
49
|
+
cirq.testing.assert_circuits_have_same_unitary_given_final_permutation(
|
|
50
|
+
nc, c, qubit_map={q: q for q in c.all_qubits()}
|
|
51
|
+
)
|
|
52
|
+
else:
|
|
53
|
+
cirq.testing.assert_circuits_have_same_unitary_given_final_permutation(
|
|
54
|
+
nc, c, qubit_map={q: q for q in c.all_qubits()}
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
@patch('cirq.transformers.gauge_compiling.gauge_compiling._select', autospec=True)
|
|
58
|
+
@pytest.mark.parametrize('seed', range(5))
|
|
59
|
+
def test_all_gauges(self, mock_select, seed):
|
|
60
|
+
assert isinstance(
|
|
61
|
+
self.gauge_transformer.gauge_selector, GaugeSelector
|
|
62
|
+
), 'When using a custom selector, please override this method to properly test all gauges'
|
|
63
|
+
c = cirq.Circuit(self.two_qubit_gate(cirq.LineQubit(0), cirq.LineQubit(1)))
|
|
64
|
+
prng = np.random.default_rng(seed)
|
|
65
|
+
for gauge in self.gauge_transformer.gauge_selector.gauges:
|
|
66
|
+
mock_select.return_value = gauge
|
|
67
|
+
assert self.gauge_transformer.gauge_selector(prng) == gauge
|
|
68
|
+
nc = self.gauge_transformer(c, prng=prng)
|
|
69
|
+
|
|
70
|
+
if self.must_fail:
|
|
71
|
+
with pytest.raises(AssertionError):
|
|
72
|
+
_check_equivalent_with_error_message(c, nc, gauge)
|
|
73
|
+
else:
|
|
74
|
+
_check_equivalent_with_error_message(c, nc, gauge)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _check_equivalent_with_error_message(c: cirq.AbstractCircuit, nc: cirq.AbstractCircuit, gauge):
|
|
78
|
+
try:
|
|
79
|
+
cirq.testing.assert_circuits_have_same_unitary_given_final_permutation(
|
|
80
|
+
nc, c, qubit_map={q: q for q in c.all_qubits()}
|
|
81
|
+
)
|
|
82
|
+
except AssertionError as ex:
|
|
83
|
+
raise AssertionError(f"{gauge=} didn't result in an equivalent circuit") from ex
|