diff --git a/cirq/circuits/circuit.py b/cirq/circuits/circuit.py index 7a7e85498eb..8a1e74f3a15 100644 --- a/cirq/circuits/circuit.py +++ b/cirq/circuits/circuit.py @@ -1035,7 +1035,7 @@ def _superoperator_(self) -> np.ndarray: if n > 10: raise ValueError(f"{n} > 10 qubits is too many to compute superoperator") - circuit_superoperator = np.eye(4 ** n) + circuit_superoperator = np.eye(4**n) for moment in self: full_moment = moment.expand_to(all_qubits) moment_superoperator = full_moment._superoperator_() diff --git a/cirq/circuits/circuit_operation.py b/cirq/circuits/circuit_operation.py index 89b260318e7..e05cc5fb7e0 100644 --- a/cirq/circuits/circuit_operation.py +++ b/cirq/circuits/circuit_operation.py @@ -300,7 +300,7 @@ def _mapped_single_loop(self, repetition_id: Optional[str] = None) -> 'cirq.Circ if self.qubit_map: circuit = circuit.transform_qubits(lambda q: self.qubit_map.get(q, q)) if isinstance(self.repetitions, INT_CLASSES) and self.repetitions < 0: - circuit = circuit ** -1 + circuit = circuit**-1 if self.measurement_key_map: circuit = protocols.with_measurement_key_mapping(circuit, self.measurement_key_map) if self.param_resolver: diff --git a/cirq/circuits/circuit_operation_test.py b/cirq/circuits/circuit_operation_test.py index a92c7abbd1b..7b1cd884afd 100644 --- a/cirq/circuits/circuit_operation_test.py +++ b/cirq/circuits/circuit_operation_test.py @@ -307,12 +307,12 @@ def test_repeat(add_measurements, use_default_ids_for_initial_rep): if use_default_ids_for_initial_rep: op_with_reps = op_base.repeat(initial_repetitions) rep_ids = ['0', '1', '2'] - assert op_base ** initial_repetitions == op_with_reps + assert op_base**initial_repetitions == op_with_reps else: rep_ids = ['a', 'b', 'c'] op_with_reps = op_base.repeat(initial_repetitions, rep_ids) - assert op_base ** initial_repetitions != op_with_reps - assert (op_base ** initial_repetitions).replace(repetition_ids=rep_ids) == op_with_reps + assert op_base**initial_repetitions != op_with_reps + assert (op_base**initial_repetitions).replace(repetition_ids=rep_ids) == op_with_reps assert op_with_reps.repetitions == initial_repetitions assert op_with_reps.repetition_ids == rep_ids assert op_with_reps.repeat(1) is op_with_reps @@ -322,7 +322,7 @@ def test_repeat(add_measurements, use_default_ids_for_initial_rep): op_with_consecutive_reps = op_with_reps.repeat(2) assert op_with_consecutive_reps.repetitions == final_repetitions assert op_with_consecutive_reps.repetition_ids == _full_join_string_lists(['0', '1'], rep_ids) - assert op_base ** final_repetitions != op_with_consecutive_reps + assert op_base**final_repetitions != op_with_consecutive_reps op_with_consecutive_reps = op_with_reps.repeat(2, ['a', 'b']) assert op_with_reps.repeat(repetition_ids=['a', 'b']) == op_with_consecutive_reps @@ -357,7 +357,7 @@ def test_repeat_zero_times(add_measurements, use_repetition_ids, initial_reps): ) result = cirq.Simulator().simulate(cirq.Circuit(op)) assert np.allclose(result.state_vector(), [0, 1] if initial_reps % 2 else [1, 0]) - result = cirq.Simulator().simulate(cirq.Circuit(op ** 0)) + result = cirq.Simulator().simulate(cirq.Circuit(op**0)) assert np.allclose(result.state_vector(), [1, 0]) @@ -378,7 +378,7 @@ def test_parameterized_repeat(): cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': 1.5}) with pytest.raises(ValueError, match='Circuit contains ops whose symbols were not specified'): cirq.Simulator().simulate(cirq.Circuit(op)) - op = op ** -1 + op = op**-1 assert cirq.parameter_names(op) == {'a'} assert not cirq.has_unitary(op) result = cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': 0}) @@ -406,7 +406,7 @@ def test_parameterized_repeat(): cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': 1.5, 'b': 1}) with pytest.raises(ValueError, match='Circuit contains ops whose symbols were not specified'): cirq.Simulator().simulate(cirq.Circuit(op)) - op = op ** 2.0 + op = op**2.0 assert cirq.parameter_names(op) == {'a', 'b'} assert not cirq.has_unitary(op) result = cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': 1, 'b': 1}) diff --git a/cirq/circuits/circuit_test.py b/cirq/circuits/circuit_test.py index 05bacd7efd4..5cfb226f645 100644 --- a/cirq/circuits/circuit_test.py +++ b/cirq/circuits/circuit_test.py @@ -1307,7 +1307,7 @@ def test_next_moment_operating_on_distance(circuit_cls): assert c.next_moment_operating_on([a], 1, max_distance=500) == 4 # Huge max distances should be handled quickly due to capping. - assert c.next_moment_operating_on([a], 5, max_distance=10 ** 100) is None + assert c.next_moment_operating_on([a], 5, max_distance=10**100) is None with pytest.raises(ValueError, match='Negative max_distance'): c.next_moment_operating_on([a], 0, max_distance=-1) @@ -1396,7 +1396,7 @@ def test_prev_moment_operating_on_distance(circuit_cls): assert c.prev_moment_operating_on([a], 13, max_distance=500) == 1 # Huge max distances should be handled quickly due to capping. - assert c.prev_moment_operating_on([a], 1, max_distance=10 ** 100) is None + assert c.prev_moment_operating_on([a], 1, max_distance=10**100) is None with pytest.raises(ValueError, match='Negative max_distance'): c.prev_moment_operating_on([a], 6, max_distance=-1) @@ -1703,7 +1703,7 @@ def test_findall_operations_until_blocked(circuit_cls): ) -@pytest.mark.parametrize('seed', [randint(0, 2 ** 31)]) +@pytest.mark.parametrize('seed', [randint(0, 2**31)]) @pytest.mark.parametrize('circuit_cls', [cirq.Circuit, cirq.FrozenCircuit]) def test_findall_operations_until_blocked_docstring_examples(seed, circuit_cls): prng = np.random.RandomState(seed) @@ -2861,7 +2861,7 @@ def pauli_error_probability(r: float, n_qubits: int) -> float: makes it simple to compute the serial composition of depolarizing channels. It is multiplicative under channel composition. """ - d2 = 4 ** n_qubits + d2 = 4**n_qubits return (1 - r) * (d2 - 1) / d2 def depolarize(r: float, n_qubits: int) -> cirq.DepolarizingChannel: @@ -4062,9 +4062,9 @@ def test_submoments(circuit_cls): cirq.H.on(d), cirq.CZ.on(a, d), cirq.CZ.on(b, c), - (cirq.CNOT ** 0.5).on(a, d), - (cirq.CNOT ** 0.5).on(b, e), - (cirq.CNOT ** 0.5).on(c, f), + (cirq.CNOT**0.5).on(a, d), + (cirq.CNOT**0.5).on(b, e), + (cirq.CNOT**0.5).on(c, f), cirq.H.on(c), cirq.H.on(e), ) @@ -4191,15 +4191,12 @@ def test_measurement_key_mapping(circuit_cls): assert simulator.run(c).measurements == {'m1': 1, 'm2': 0} assert simulator.run(c_swapped).measurements == {'m1': 0, 'm2': 1} - assert ( - cirq.with_measurement_key_mapping( - c, - { - 'x': 'z', - }, - ).all_measurement_key_names() - == {'m1', 'm2'} - ) + assert cirq.with_measurement_key_mapping( + c, + { + 'x': 'z', + }, + ).all_measurement_key_names() == {'m1', 'm2'} @pytest.mark.parametrize('circuit_cls', [cirq.Circuit, cirq.FrozenCircuit]) @@ -4222,7 +4219,7 @@ def test_measurement_key_mapping_preserves_moments(circuit_cls): @pytest.mark.parametrize('circuit_cls', [cirq.Circuit, cirq.FrozenCircuit]) def test_inverse(circuit_cls): a, b = cirq.LineQubit.range(2) - forward = circuit_cls((cirq.X ** 0.5)(a), (cirq.Y ** -0.2)(b), cirq.CZ(a, b)) + forward = circuit_cls((cirq.X**0.5)(a), (cirq.Y**-0.2)(b), cirq.CZ(a, b)) backward = circuit_cls((cirq.CZ ** (-1.0))(a, b), (cirq.X ** (-0.5))(a), (cirq.Y ** (0.2))(b)) cirq.testing.assert_same_circuits(cirq.inverse(forward), backward) @@ -4233,7 +4230,7 @@ def test_inverse(circuit_cls): cirq.inverse(no_inverse) # Default when there is no inverse for an op. - default = circuit_cls((cirq.X ** 0.5)(a), (cirq.Y ** -0.2)(b)) + default = circuit_cls((cirq.X**0.5)(a), (cirq.Y**-0.2)(b)) cirq.testing.assert_same_circuits(cirq.inverse(no_inverse, default), default) assert cirq.inverse(no_inverse, None) is None @@ -4241,7 +4238,7 @@ def test_inverse(circuit_cls): @pytest.mark.parametrize('circuit_cls', [cirq.Circuit, cirq.FrozenCircuit]) def test_pow_valid_only_for_minus_1(circuit_cls): a, b = cirq.LineQubit.range(2) - forward = circuit_cls((cirq.X ** 0.5)(a), (cirq.Y ** -0.2)(b), cirq.CZ(a, b)) + forward = circuit_cls((cirq.X**0.5)(a), (cirq.Y**-0.2)(b), cirq.CZ(a, b)) backward = circuit_cls((cirq.CZ ** (-1.0))(a, b), (cirq.X ** (-0.5))(a), (cirq.Y ** (0.2))(b)) cirq.testing.assert_same_circuits(cirq.pow(forward, -1), backward) @@ -4642,28 +4639,22 @@ def _measurement_key_name_(self): assert circuit_cls().all_measurement_key_names() == set() # Order does not matter. - assert ( - circuit_cls( - cirq.Moment( - [ - cirq.measure(a, key='x'), - cirq.measure(b, key='y'), - ] - ) - ).all_measurement_key_names() - == {'x', 'y'} - ) - assert ( - circuit_cls( - cirq.Moment( - [ - cirq.measure(b, key='y'), - cirq.measure(a, key='x'), - ] - ) - ).all_measurement_key_names() - == {'x', 'y'} - ) + assert circuit_cls( + cirq.Moment( + [ + cirq.measure(a, key='x'), + cirq.measure(b, key='y'), + ] + ) + ).all_measurement_key_names() == {'x', 'y'} + assert circuit_cls( + cirq.Moment( + [ + cirq.measure(b, key='y'), + cirq.measure(a, key='x'), + ] + ) + ).all_measurement_key_names() == {'x', 'y'} def test_zip(): diff --git a/cirq/circuits/moment.py b/cirq/circuits/moment.py index 57f16e8e209..2b2a6e3a149 100644 --- a/cirq/circuits/moment.py +++ b/cirq/circuits/moment.py @@ -414,7 +414,7 @@ def kraus_tensors(op: 'cirq.Operation') -> Sequence[np.ndarray]: transpose = input_subscripts + '->' + output_subscripts r = [] - d = 2 ** n + d = 2**n kss = [kraus_tensors(op) for op in self.operations] for ks in itertools.product(*kss): k = np.einsum(transpose, *ks) diff --git a/cirq/circuits/moment_test.py b/cirq/circuits/moment_test.py index c147ac771b5..dfdaefd0e53 100644 --- a/cirq/circuits/moment_test.py +++ b/cirq/circuits/moment_test.py @@ -409,10 +409,10 @@ def test_json_dict(): def test_inverse(): a, b, c = cirq.LineQubit.range(3) m = cirq.Moment([cirq.S(a), cirq.CNOT(b, c)]) - assert m ** 1 is m - assert m ** -1 == cirq.Moment([cirq.S(a) ** -1, cirq.CNOT(b, c)]) - assert m ** 0.5 == cirq.Moment([cirq.T(a), cirq.CNOT(b, c) ** 0.5]) - assert cirq.inverse(m) == m ** -1 + assert m**1 is m + assert m**-1 == cirq.Moment([cirq.S(a) ** -1, cirq.CNOT(b, c)]) + assert m**0.5 == cirq.Moment([cirq.T(a), cirq.CNOT(b, c) ** 0.5]) + assert cirq.inverse(m) == m**-1 assert cirq.inverse(cirq.inverse(m)) == m assert cirq.inverse(cirq.Moment([cirq.measure(a)]), default=None) is None diff --git a/cirq/circuits/optimization_pass_test.py b/cirq/circuits/optimization_pass_test.py index 15184a0f149..a2fe27b489a 100644 --- a/cirq/circuits/optimization_pass_test.py +++ b/cirq/circuits/optimization_pass_test.py @@ -135,7 +135,7 @@ def test_point_optimizer_post_clean_up(): def clean_up(operations): for op in operations: - yield op ** 0.5 + yield op**0.5 ReplaceWithXGates(post_clean_up=clean_up)(c) diff --git a/cirq/contrib/acquaintance/executor_test.py b/cirq/contrib/acquaintance/executor_test.py index 20e2d3572de..231e7ab9d5c 100644 --- a/cirq/contrib/acquaintance/executor_test.py +++ b/cirq/contrib/acquaintance/executor_test.py @@ -89,7 +89,7 @@ def random_diagonal_gates( ) -> Dict[Tuple[cirq.Qid, ...], cirq.Gate]: return { - Q: cirq.DiagonalGate(np.random.random(2 ** acquaintance_size)) + Q: cirq.DiagonalGate(np.random.random(2**acquaintance_size)) for Q in combinations(cirq.LineQubit.range(num_qubits), acquaintance_size) } diff --git a/cirq/contrib/acquaintance/permutation_test.py b/cirq/contrib/acquaintance/permutation_test.py index 2b347961265..a626d777326 100644 --- a/cirq/contrib/acquaintance/permutation_test.py +++ b/cirq/contrib/acquaintance/permutation_test.py @@ -184,7 +184,7 @@ def test_linear_permutation_gate_pow_not_implemented(): def test_linear_permutation_gate_pow_identity(num_qubits, permutation): permutation_gate = cca.LinearPermutationGate(num_qubits, permutation) - assert permutation_gate ** 1 == permutation_gate + assert permutation_gate**1 == permutation_gate @pytest.mark.parametrize( @@ -201,7 +201,7 @@ def test_linear_permutation_gate_pow_inverse(num_qubits, permutation, inverse): permutation_gate = cca.LinearPermutationGate(num_qubits, permutation) inverse_gate = cca.LinearPermutationGate(num_qubits, inverse) - assert permutation_gate ** -1 == inverse_gate + assert permutation_gate**-1 == inverse_gate assert cirq.inverse(permutation_gate) == inverse_gate diff --git a/cirq/contrib/qasm_import/_parser.py b/cirq/contrib/qasm_import/_parser.py index 35c5634b951..a3a56b8cf69 100644 --- a/cirq/contrib/qasm_import/_parser.py +++ b/cirq/contrib/qasm_import/_parser.py @@ -240,8 +240,8 @@ def __init__(self): qasm_gate='cswap', num_params=0, num_args=3, cirq_gate=ops.CSWAP ), 'ccx': QasmGateStatement(qasm_gate='ccx', num_params=0, num_args=3, cirq_gate=ops.CCX), - 'sdg': QasmGateStatement(qasm_gate='sdg', num_params=0, num_args=1, cirq_gate=ops.S ** -1), - 'tdg': QasmGateStatement(qasm_gate='tdg', num_params=0, num_args=1, cirq_gate=ops.T ** -1), + 'sdg': QasmGateStatement(qasm_gate='sdg', num_params=0, num_args=1, cirq_gate=ops.S**-1), + 'tdg': QasmGateStatement(qasm_gate='tdg', num_params=0, num_args=1, cirq_gate=ops.T**-1), } all_gates = {**basic_gates, **qelib_gates} diff --git a/cirq/contrib/qasm_import/_parser_test.py b/cirq/contrib/qasm_import/_parser_test.py index 1cc82753980..d6113a8ee12 100644 --- a/cirq/contrib/qasm_import/_parser_test.py +++ b/cirq/contrib/qasm_import/_parser_test.py @@ -434,8 +434,8 @@ def test_unknown_function(): ('h', cirq.H), ('s', cirq.S), ('t', cirq.T), - ('sdg', cirq.S ** -1), - ('tdg', cirq.T ** -1), + ('sdg', cirq.S**-1), + ('tdg', cirq.T**-1), ('sx', cirq.XPowGate(exponent=0.5)), ] diff --git a/cirq/contrib/quantum_volume/quantum_volume.py b/cirq/contrib/quantum_volume/quantum_volume.py index 902df622e83..042a895d4d4 100644 --- a/cirq/contrib/quantum_volume/quantum_volume.py +++ b/cirq/contrib/quantum_volume/quantum_volume.py @@ -86,7 +86,7 @@ def compute_heavy_set(circuit: cirq.Circuit) -> List[int]: # The output wave function is a vector from the result value (big-endian) to # the probability of that bit-string. Return all of the bit-string # values that have a probability greater than the median. - return [idx for idx, amp in enumerate(results.state_vector()) if np.abs(amp ** 2) > median] + return [idx for idx, amp in enumerate(results.state_vector()) if np.abs(amp**2) > median] @dataclass diff --git a/cirq/contrib/quirk/quirk_gate.py b/cirq/contrib/quirk/quirk_gate.py index eeef0daa379..32869194e1b 100644 --- a/cirq/contrib/quirk/quirk_gate.py +++ b/cirq/contrib/quirk/quirk_gate.py @@ -176,11 +176,11 @@ def z_to_quirk_op(gate: ops.ZPowGate) -> QuirkOp: def cz_to_quirk_op(gate: ops.CZPowGate) -> Optional[QuirkOp]: - return z_to_quirk_op(ops.Z ** gate.exponent).controlled() + return z_to_quirk_op(ops.Z**gate.exponent).controlled() def cnot_to_quirk_op(gate: ops.CXPowGate) -> Optional[QuirkOp]: - return x_to_quirk_op(ops.X ** gate.exponent).controlled() + return x_to_quirk_op(ops.X**gate.exponent).controlled() def h_to_quirk_op(gate: ops.HPowGate) -> Optional[QuirkOp]: diff --git a/cirq/contrib/routing/initialization_test.py b/cirq/contrib/routing/initialization_test.py index d92b2b2607f..66c2aea5b73 100644 --- a/cirq/contrib/routing/initialization_test.py +++ b/cirq/contrib/routing/initialization_test.py @@ -29,7 +29,7 @@ def get_seeded_initial_mapping(graph_seed, init_seed): return ccr.initialization.get_initial_mapping(logical_graph, device_graph, init_seed) -@pytest.mark.parametrize('seed', [random.randint(0, 2 ** 32) for _ in range(10)]) +@pytest.mark.parametrize('seed', [random.randint(0, 2**32) for _ in range(10)]) def test_initialization_reproducible_with_seed(seed): wrappers = (lambda s: s, np.random.RandomState) mappings = [ @@ -39,7 +39,7 @@ def test_initialization_reproducible_with_seed(seed): eq.add_equality_group(*mappings) -@pytest.mark.parametrize('graph_seed,state', [(random.randint(0, 2 ** 32), np.random.get_state())]) +@pytest.mark.parametrize('graph_seed,state', [(random.randint(0, 2**32), np.random.get_state())]) def test_initialization_with_no_seed(graph_seed, state): mappings = [] for _ in range(3): diff --git a/cirq/contrib/routing/router_test.py b/cirq/contrib/routing/router_test.py index 72564355226..7d82eb6a92d 100644 --- a/cirq/contrib/routing/router_test.py +++ b/cirq/contrib/routing/router_test.py @@ -24,7 +24,7 @@ def random_seed(): - return random.randint(0, 2 ** 32) + return random.randint(0, 2**32) @pytest.mark.parametrize( diff --git a/cirq/devices/noise_model_test.py b/cirq/devices/noise_model_test.py index 247961b0c33..ad4c5809f08 100644 --- a/cirq/devices/noise_model_test.py +++ b/cirq/devices/noise_model_test.py @@ -121,7 +121,7 @@ def test_constant_qubit_noise(): cirq.testing.assert_equivalent_repr(damp_all) with pytest.raises(ValueError, match='num_qubits'): - _ = cirq.ConstantQubitNoiseModel(cirq.CNOT ** 0.01) + _ = cirq.ConstantQubitNoiseModel(cirq.CNOT**0.01) def test_noise_composition(): @@ -129,7 +129,7 @@ def test_noise_composition(): # long as the noise operators commute with one another. a, b, c = cirq.LineQubit.range(3) noise_z = cirq.ConstantQubitNoiseModel(cirq.Z) - noise_inv_s = cirq.ConstantQubitNoiseModel(cirq.S ** -1) + noise_inv_s = cirq.ConstantQubitNoiseModel(cirq.S**-1) base_moments = [cirq.Moment([cirq.X(a)]), cirq.Moment([cirq.Y(b)]), cirq.Moment([cirq.H(c)])] circuit_z = cirq.Circuit(noise_z.noisy_moments(base_moments, [a, b, c])) circuit_s = cirq.Circuit(noise_inv_s.noisy_moments(base_moments, [a, b, c])) @@ -154,7 +154,7 @@ def test_noise_composition(): def test_constant_qubit_noise_repr(): - cirq.testing.assert_equivalent_repr(cirq.ConstantQubitNoiseModel(cirq.X ** 0.01)) + cirq.testing.assert_equivalent_repr(cirq.ConstantQubitNoiseModel(cirq.X**0.01)) def test_wrap(): @@ -168,8 +168,8 @@ def noisy_operation(self, operation): assert cirq.NoiseModel.from_noise_model_like( cirq.depolarize(0.1) ) == cirq.ConstantQubitNoiseModel(cirq.depolarize(0.1)) - assert cirq.NoiseModel.from_noise_model_like(cirq.Z ** 0.01) == cirq.ConstantQubitNoiseModel( - cirq.Z ** 0.01 + assert cirq.NoiseModel.from_noise_model_like(cirq.Z**0.01) == cirq.ConstantQubitNoiseModel( + cirq.Z**0.01 ) assert cirq.NoiseModel.from_noise_model_like(forget) is forget @@ -177,7 +177,7 @@ def noisy_operation(self, operation): _ = cirq.NoiseModel.from_noise_model_like('test') with pytest.raises(ValueError, match='Multi-qubit gate'): - _ = cirq.NoiseModel.from_noise_model_like(cirq.CZ ** 0.01) + _ = cirq.NoiseModel.from_noise_model_like(cirq.CZ**0.01) def test_gate_substitution_noise_model(): diff --git a/cirq/devices/noise_utils.py b/cirq/devices/noise_utils.py index 22e21aab89d..3a38ee40abd 100644 --- a/cirq/devices/noise_utils.py +++ b/cirq/devices/noise_utils.py @@ -109,7 +109,7 @@ def decay_constant_to_xeb_fidelity(decay_constant: float, num_qubits: int = 2) - Returns: Calculated XEB fidelity. """ - N = 2 ** num_qubits + N = 2**num_qubits return 1 - ((1 - decay_constant) * (1 - 1 / N)) @@ -123,7 +123,7 @@ def decay_constant_to_pauli_error(decay_constant: float, num_qubits: int = 1) -> Returns: Calculated Pauli error. """ - N = 2 ** num_qubits + N = 2**num_qubits return (1 - decay_constant) * (1 - 1 / N / N) @@ -137,7 +137,7 @@ def pauli_error_to_decay_constant(pauli_error: float, num_qubits: int = 1) -> fl Returns: Calculated depolarization decay constant. """ - N = 2 ** num_qubits + N = 2**num_qubits return 1 - (pauli_error / (1 - 1 / N / N)) @@ -151,7 +151,7 @@ def xeb_fidelity_to_decay_constant(xeb_fidelity: float, num_qubits: int = 2) -> Returns: Calculated depolarization decay constant. """ - N = 2 ** num_qubits + N = 2**num_qubits return 1 - (1 - xeb_fidelity) / (1 - 1 / N) @@ -181,7 +181,7 @@ def average_error(decay_constant: float, num_qubits: int = 1) -> float: Returns: Calculated average error. """ - N = 2 ** num_qubits + N = 2**num_qubits return (1 - decay_constant) * (1 - 1 / N) diff --git a/cirq/devices/thermal_noise_model_test.py b/cirq/devices/thermal_noise_model_test.py index 182fba026fe..42f5375934a 100644 --- a/cirq/devices/thermal_noise_model_test.py +++ b/cirq/devices/thermal_noise_model_test.py @@ -277,7 +277,7 @@ def test_noisy_moment_two_qubit(): dephase_rate_GHz={q0: 3e-4, q1: 4e-4}, require_physical_tag=False, ) - gate = cirq.CZ ** 0.5 + gate = cirq.CZ**0.5 moment = cirq.Moment(gate.on(q0, q1)) noisy_moment = model.noisy_moment(moment, system_qubits=[q0, q1]) assert noisy_moment[0] == moment diff --git a/cirq/experiments/cross_entropy_benchmarking.py b/cirq/experiments/cross_entropy_benchmarking.py index 3d3dfd1571a..b14e428271d 100644 --- a/cirq/experiments/cross_entropy_benchmarking.py +++ b/cirq/experiments/cross_entropy_benchmarking.py @@ -95,7 +95,7 @@ class SpecklePurityDepolarizingModel(CrossEntropyDepolarizingModel): @property def purity(self) -> float: """The purity. Equal to p**2, where p is the cycle depolarization.""" - return self.cycle_depolarization ** 2 + return self.cycle_depolarization**2 @protocols.json_serializable_dataclass(frozen=True) @@ -235,7 +235,7 @@ def _fit_exponential_decay(x: Sequence[int], y: Sequence[float]) -> Tuple[np.nda # Perform nonlinear least squares def f(a, S, p): - return S * p ** a + return S * p**a return optimize.curve_fit(f, x, y, p0=p0) @@ -382,8 +382,8 @@ def cross_entropy_benchmarking( # all trials in two dictionaries. The keys of the dictionaries are the # numbers of cycles. The values are 2D arrays with each row being the # probabilities obtained from a single trial. - probs_meas = {n: np.zeros((num_circuits, 2 ** num_qubits)) for n in cycle_range} - probs_th = {n: np.zeros((num_circuits, 2 ** num_qubits)) for n in cycle_range} + probs_meas = {n: np.zeros((num_circuits, 2**num_qubits)) for n in cycle_range} + probs_th = {n: np.zeros((num_circuits, 2**num_qubits)) for n in cycle_range} for k in range(num_circuits): @@ -552,14 +552,14 @@ def _compute_fidelity(probs_th: np.ndarray, probs_meas: np.ndarray) -> float: """ _, num_states = probs_th.shape pp_cross = probs_th * probs_meas - pp_th = probs_th ** 2 + pp_th = probs_th**2 f_meas = np.mean(num_states * np.sum(pp_cross, axis=1) - 1.0) f_th = np.mean(num_states * np.sum(pp_th, axis=1) - 1.0) return float(f_meas / f_th) def _random_half_rotations(qubits: Sequence[ops.Qid], num_layers: int) -> List[List[ops.OP_TREE]]: - rot_ops = [ops.X ** 0.5, ops.Y ** 0.5, ops.PhasedXPowGate(phase_exponent=0.25, exponent=0.5)] + rot_ops = [ops.X**0.5, ops.Y**0.5, ops.PhasedXPowGate(phase_exponent=0.25, exponent=0.5)] num_qubits = len(qubits) rand_nums = np.random.choice(3, (num_qubits, num_layers)) single_q_layers: List[List[ops.OP_TREE]] = [] diff --git a/cirq/experiments/cross_entropy_benchmarking_test.py b/cirq/experiments/cross_entropy_benchmarking_test.py index 0688a7877ba..f4b0fcc9336 100644 --- a/cirq/experiments/cross_entropy_benchmarking_test.py +++ b/cirq/experiments/cross_entropy_benchmarking_test.py @@ -36,18 +36,18 @@ def test_cross_entropy_benchmarking(): # Sanity check single-qubit-gate causes error with pytest.raises(ValueError): - build_entangling_layers(qubits, cirq.Z ** 0.91) + build_entangling_layers(qubits, cirq.Z**0.91) # Build a sequence of CZ gates. - interleaved_ops = build_entangling_layers(qubits, cirq.CZ ** 0.91) + interleaved_ops = build_entangling_layers(qubits, cirq.CZ**0.91) # Specify a set of single-qubit rotations. Pick prime numbers for the # exponent to avoid evolving the system into a basis state. single_qubit_rots = [ - [cirq.X ** 0.37], - [cirq.Y ** 0.73, cirq.X ** 0.53], - [cirq.Z ** 0.61, cirq.X ** 0.43], - [cirq.Y ** 0.19], + [cirq.X**0.37], + [cirq.Y**0.73, cirq.X**0.53], + [cirq.Z**0.61, cirq.X**0.43], + [cirq.Y**0.19], ] # Simulate XEB using the default single-qubit gate set without two-qubit @@ -104,7 +104,7 @@ def test_cross_entropy_result_depolarizing_models(): S = 0.8 p = 0.99 data = [ - CrossEntropyPair(num_cycle=d, xeb_fidelity=S * p ** d + prng.normal(scale=0.01)) + CrossEntropyPair(num_cycle=d, xeb_fidelity=S * p**d + prng.normal(scale=0.01)) for d in range(10, 211, 20) ] purity_data = [ @@ -116,7 +116,7 @@ def test_cross_entropy_result_depolarizing_models(): purity_model = result.purity_depolarizing_model() np.testing.assert_allclose(model.spam_depolarization, S, atol=1e-2) np.testing.assert_allclose(model.cycle_depolarization, p, atol=1e-2) - np.testing.assert_allclose(purity_model.purity, p ** 2, atol=1e-2) + np.testing.assert_allclose(purity_model.purity, p**2, atol=1e-2) def test_cross_entropy_result_repr(): diff --git a/cirq/experiments/fidelity_estimation_test.py b/cirq/experiments/fidelity_estimation_test.py index ed6ba5b9c1a..3eaf428a7f3 100644 --- a/cirq/experiments/fidelity_estimation_test.py +++ b/cirq/experiments/fidelity_estimation_test.py @@ -36,7 +36,7 @@ def sample_noisy_bitstrings( def make_random_quantum_circuit(qubits: Sequence[cirq.Qid], depth: int) -> cirq.Circuit: - SQ_GATES = [cirq.X ** 0.5, cirq.Y ** 0.5, cirq.T] + SQ_GATES = [cirq.X**0.5, cirq.Y**0.5, cirq.T] circuit = cirq.Circuit() cz_start = 0 for q in qubits: @@ -152,7 +152,7 @@ def test_least_squares_xeb_fidelity_from_expectations(): depolarization = 0.5 n_qubits = 5 - dim = 2 ** n_qubits + dim = 2**n_qubits n_circuits = 10 qubits = cirq.LineQubit.range(n_qubits) @@ -170,7 +170,7 @@ def test_least_squares_xeb_fidelity_from_expectations(): probabilities = cirq.state_vector_to_probabilities(amplitudes) measured_expectations_lin.append(dim * np.mean(probabilities[bitstrings])) - exact_expectations_lin.append(dim * np.sum(probabilities ** 2)) + exact_expectations_lin.append(dim * np.sum(probabilities**2)) measured_expectations_log.append(np.mean(np.log(dim * probabilities[bitstrings]))) exact_expectations_log.append(np.sum(probabilities * np.log(dim * probabilities))) @@ -204,7 +204,7 @@ def test_least_squares_xeb_fidelity_from_probabilities(): depolarization = 0.5 n_qubits = 5 - dim = 2 ** n_qubits + dim = 2**n_qubits n_circuits = 10 qubits = cirq.LineQubit.range(n_qubits) diff --git a/cirq/experiments/grid_parallel_two_qubit_xeb_test.py b/cirq/experiments/grid_parallel_two_qubit_xeb_test.py index 92db8bf13f9..bfe71138b36 100644 --- a/cirq/experiments/grid_parallel_two_qubit_xeb_test.py +++ b/cirq/experiments/grid_parallel_two_qubit_xeb_test.py @@ -18,7 +18,7 @@ def test_estimate_parallel_two_qubit_xeb_fidelity_on_grid_no_noise(tmpdir): # No noise, fidelities should be close to 1 base_dir = os.path.abspath(tmpdir) qubits = cirq.GridQubit.square(2) - two_qubit_gate = cirq.ISWAP ** 0.5 + two_qubit_gate = cirq.ISWAP**0.5 cycles = [5, 10, 15] data_collection_id = collect_grid_parallel_two_qubit_xeb_data( sampler=cirq.Simulator(seed=34310, split_untangled_states=False), @@ -50,7 +50,7 @@ def test_estimate_parallel_two_qubit_xeb_fidelity_on_grid_depolarizing(tmpdir): # With depolarizing probability e base_dir = os.path.abspath(tmpdir) qubits = cirq.GridQubit.square(2) - two_qubit_gate = cirq.ISWAP ** 0.5 + two_qubit_gate = cirq.ISWAP**0.5 cycles = [5, 10, 15] e = 0.01 data_collection_id = collect_grid_parallel_two_qubit_xeb_data( @@ -85,7 +85,7 @@ def test_estimate_parallel_two_qubit_xeb_fidelity_on_grid_concurrent(tmpdir): # Use multiple threads during data collection base_dir = os.path.abspath(tmpdir) qubits = cirq.GridQubit.square(2) - two_qubit_gate = cirq.ISWAP ** 0.5 + two_qubit_gate = cirq.ISWAP**0.5 cycles = [5, 10, 15] data_collection_id = collect_grid_parallel_two_qubit_xeb_data( sampler=cirq.Simulator(seed=34310), diff --git a/cirq/experiments/n_qubit_tomography.py b/cirq/experiments/n_qubit_tomography.py index 87caffb94c4..be9b444a800 100644 --- a/cirq/experiments/n_qubit_tomography.py +++ b/cirq/experiments/n_qubit_tomography.py @@ -98,7 +98,7 @@ def _make_state_tomography_matrix( rotation sequence and bit string outcome for that rotation sequence. """ num_rots = len(self.rot_sweep) - num_states = 2 ** self.num_qubits + num_states = 2**self.num_qubits # Unitary matrices of each rotation circuit. unitaries = np.array( @@ -128,7 +128,7 @@ def fit_density_matrix(self, counts: np.ndarray) -> TomographyResult: probs = counts / np.sum(counts, axis=1)[:, np.newaxis] # use least squares to get solution. c, _, _, _ = np.linalg.lstsq(self.mat, np.asarray(probs).flat, rcond=-1) - rho = c.reshape((2 ** self.num_qubits, 2 ** self.num_qubits)) + rho = c.reshape((2**self.num_qubits, 2**self.num_qubits)) return TomographyResult(rho) diff --git a/cirq/experiments/n_qubit_tomography_test.py b/cirq/experiments/n_qubit_tomography_test.py index d6a2a4488bd..a873700401d 100644 --- a/cirq/experiments/n_qubit_tomography_test.py +++ b/cirq/experiments/n_qubit_tomography_test.py @@ -24,7 +24,7 @@ def test_state_tomography_diagonal(): n = 2 qubits = cirq.LineQubit.range(n) - for state in range(2 ** n): + for state in range(2**n): circuit = cirq.Circuit() for i, q in enumerate(qubits): bit = state & (1 << (n - i - 1)) @@ -37,7 +37,7 @@ def test_state_tomography_diagonal(): repetitions=1000, prerotations=[(0, 0), (0, 0.5), (0.5, 0.5)], ) - should_be = np.zeros((2 ** n, 2 ** n)) + should_be = np.zeros((2**n, 2**n)) should_be[state, state] = 1 assert np.allclose(res.data, should_be, atol=0.05) diff --git a/cirq/experiments/purity_estimation.py b/cirq/experiments/purity_estimation.py index 7bdf61e9b2d..3b581bdf551 100644 --- a/cirq/experiments/purity_estimation.py +++ b/cirq/experiments/purity_estimation.py @@ -58,5 +58,5 @@ def purity_from_probabilities( implementation of a quantum circuit. """ D = hilbert_space_dimension - porter_thomas_variance = (D - 1) / (D + 1) / D ** 2 + porter_thomas_variance = (D - 1) / (D + 1) / D**2 return np.var(probabilities) / porter_thomas_variance diff --git a/cirq/experiments/qubit_characterizations.py b/cirq/experiments/qubit_characterizations.py index e37ebf40d11..0990dc64ecb 100644 --- a/cirq/experiments/qubit_characterizations.py +++ b/cirq/experiments/qubit_characterizations.py @@ -519,7 +519,7 @@ def _measurement(two_qubit_circuit: circuits.Circuit) -> np.ndarray: # different basis rotations). probs = np.array([]) - rots = [ops.X ** 0, ops.X ** 0.5, ops.Y ** 0.5] + rots = [ops.X**0, ops.X**0.5, ops.Y**0.5] # Represents the coefficients in front of the c_ij's (-1, 0 or 1) in the # system of 27 linear equations. @@ -778,14 +778,14 @@ def _single_qubit_cliffords() -> Cliffords: c1_in_xz: List[List['cirq.Gate']] = [] for phi_0, phi_1 in itertools.product([1.0, 0.5, -0.5], [0.0, 0.5, -0.5]): - c1_in_xy.append([X ** phi_0, Y ** phi_1]) - c1_in_xy.append([Y ** phi_0, X ** phi_1]) - c1_in_xz.append([X ** phi_0, Z ** phi_1]) - c1_in_xz.append([Z ** phi_0, X ** phi_1]) + c1_in_xy.append([X**phi_0, Y**phi_1]) + c1_in_xy.append([Y**phi_0, X**phi_1]) + c1_in_xz.append([X**phi_0, Z**phi_1]) + c1_in_xz.append([Z**phi_0, X**phi_1]) # identity - c1_in_xy.append([X ** 0.0]) - c1_in_xz.append([X ** 0.0]) + c1_in_xy.append([X**0.0]) + c1_in_xz.append([X**0.0]) c1_in_xy.append([Y, X]) c1_in_xz.append([Z, X]) @@ -797,7 +797,7 @@ def _single_qubit_cliffords() -> Cliffords: [-0.5, 0.5, -0.5], ] for y0, x, y1 in phi_xy: - c1_in_xy.append([Y ** y0, X ** x, Y ** y1]) + c1_in_xy.append([Y**y0, X**x, Y**y1]) phi_xz = [ [0.5, 0.5, -0.5], @@ -806,22 +806,22 @@ def _single_qubit_cliffords() -> Cliffords: [-0.5, 0.5, -0.5], ] for z0, x, z1 in phi_xz: - c1_in_xz.append([Z ** z0, X ** x, Z ** z1]) + c1_in_xz.append([Z**z0, X**x, Z**z1]) s1: List[List['cirq.Gate']] = [ - [X ** 0.0], - [Y ** 0.5, X ** 0.5], - [X ** -0.5, Y ** -0.5], + [X**0.0], + [Y**0.5, X**0.5], + [X**-0.5, Y**-0.5], ] s1_x: List[List['cirq.Gate']] = [ - [X ** 0.5], - [X ** 0.5, Y ** 0.5, X ** 0.5], - [Y ** -0.5], + [X**0.5], + [X**0.5, Y**0.5, X**0.5], + [Y**-0.5], ] s1_y: List[List['cirq.Gate']] = [ - [Y ** 0.5], - [X ** -0.5, Y ** -0.5, X ** 0.5], - [Y, X ** 0.5], + [Y**0.5], + [X**-0.5, Y**-0.5, X**0.5], + [Y, X**0.5], ] return Cliffords(c1_in_xy, c1_in_xz, s1, s1_x, s1_y) diff --git a/cirq/experiments/random_quantum_circuit_generation.py b/cirq/experiments/random_quantum_circuit_generation.py index 1a57b7b6af8..04243631bf1 100644 --- a/cirq/experiments/random_quantum_circuit_generation.py +++ b/cirq/experiments/random_quantum_circuit_generation.py @@ -186,8 +186,8 @@ def random_rotations_between_two_qubit_circuit( ['cirq.Qid', 'cirq.Qid', 'np.random.RandomState'], 'cirq.OP_TREE' ] = lambda a, b, _: ops.CZPowGate()(a, b), single_qubit_gates: Sequence['cirq.Gate'] = ( - ops.X ** 0.5, - ops.Y ** 0.5, + ops.X**0.5, + ops.Y**0.5, ops.PhasedXPowGate(phase_exponent=0.25, exponent=0.5), ), add_final_single_qubit_layer: bool = True, @@ -520,7 +520,7 @@ def pair_gen(): def get_grid_interaction_layer_circuit( device_graph: nx.Graph, pattern: Sequence[GridInteractionLayer] = HALF_GRID_STAGGERED_PATTERN, - two_qubit_gate=ops.ISWAP ** 0.5, + two_qubit_gate=ops.ISWAP**0.5, ) -> 'cirq.Circuit': """Create a circuit representation of a grid interaction pattern on a given device topology. @@ -554,8 +554,8 @@ def random_rotations_between_grid_interaction_layers_circuit( ] = lambda a, b, _: ops.CZPowGate()(a, b), pattern: Sequence[GridInteractionLayer] = GRID_STAGGERED_PATTERN, single_qubit_gates: Sequence['cirq.Gate'] = ( - ops.X ** 0.5, - ops.Y ** 0.5, + ops.X**0.5, + ops.Y**0.5, ops.PhasedXPowGate(phase_exponent=0.25, exponent=0.5), ), add_final_single_qubit_layer: bool = True, diff --git a/cirq/experiments/random_quantum_circuit_generation_test.py b/cirq/experiments/random_quantum_circuit_generation_test.py index cfa25fcec93..33527269503 100644 --- a/cirq/experiments/random_quantum_circuit_generation_test.py +++ b/cirq/experiments/random_quantum_circuit_generation_test.py @@ -92,7 +92,7 @@ def test_generate_library_of_2q_circuits(): def test_generate_library_of_2q_circuits_custom_qubits(): circuits = generate_library_of_2q_circuits( n_library_circuits=5, - two_qubit_gate=cirq.ISWAP ** 0.5, + two_qubit_gate=cirq.ISWAP**0.5, max_cycle_depth=13, q0=cirq.GridQubit(9, 9), q1=cirq.NamedQubit('hi mom'), @@ -104,7 +104,7 @@ def test_generate_library_of_2q_circuits_custom_qubits(): for m1, m2 in zip(circuit.moments[::2], circuit.moments[1::2]): assert len(m1.operations) == 2 # single qubit layer assert len(m2.operations) == 1 - assert m2.operations[0].gate == cirq.ISWAP ** 0.5 + assert m2.operations[0].gate == cirq.ISWAP**0.5 def _gridqubits_to_graph_device(qubits: Iterable[cirq.GridQubit]): @@ -208,7 +208,7 @@ def test_get_grid_interaction_layer_circuit(): graph = _gridqubits_to_graph_device(cirq.GridQubit.rect(3, 3)) layer_circuit = get_grid_interaction_layer_circuit(graph) - sqrtisw = cirq.ISWAP ** 0.5 + sqrtisw = cirq.ISWAP**0.5 gq = cirq.GridQubit should_be = cirq.Circuit( # Vertical @@ -273,7 +273,7 @@ def __init__(self): 20, lambda a, b, _: cirq.CZ(a, b), cirq.experiments.GRID_STAGGERED_PATTERN, - (cirq.X ** 0.5, cirq.Y ** 0.5, cirq.Z ** 0.5), + (cirq.X**0.5, cirq.Y**0.5, cirq.Z**0.5), True, 1234, 41, @@ -285,7 +285,7 @@ def __init__(self): 20, lambda a, b, _: FakeSycamoreGate()(a, b), cirq.experiments.HALF_GRID_STAGGERED_PATTERN, - (cirq.X ** 0.5, cirq.Y ** 0.5, cirq.Z ** 0.5), + (cirq.X**0.5, cirq.Y**0.5, cirq.Z**0.5), True, 1234, 41, @@ -297,7 +297,7 @@ def __init__(self): 21, lambda a, b, _: cirq.CZ(a, b), cirq.experiments.GRID_ALIGNED_PATTERN, - (cirq.X ** 0.5, cirq.Y ** 0.5, cirq.Z ** 0.5), + (cirq.X**0.5, cirq.Y**0.5, cirq.Z**0.5), True, 1234, 43, @@ -309,7 +309,7 @@ def __init__(self): 22, _cz_with_adjacent_z_rotations, cirq.experiments.GRID_STAGGERED_PATTERN, - (cirq.X ** 0.5, cirq.Y ** 0.5, cirq.Z ** 0.5), + (cirq.X**0.5, cirq.Y**0.5, cirq.Z**0.5), True, 1234, 89, @@ -321,7 +321,7 @@ def __init__(self): 23, lambda a, b, _: cirq.CZ(a, b), cirq.experiments.GRID_ALIGNED_PATTERN, - (cirq.X ** 0.5, cirq.Y ** 0.5, cirq.Z ** 0.5), + (cirq.X**0.5, cirq.Y**0.5, cirq.Z**0.5), False, 1234, 46, @@ -333,7 +333,7 @@ def __init__(self): 24, lambda a, b, _: cirq.CZ(a, b), cirq.experiments.GRID_ALIGNED_PATTERN, - (cirq.X ** 0.5, cirq.X ** 0.5), + (cirq.X**0.5, cirq.X**0.5), True, 1234, 49, diff --git a/cirq/experiments/readout_confusion_matrix_test.py b/cirq/experiments/readout_confusion_matrix_test.py index 5e74d6eeba6..228b6f90de3 100644 --- a/cirq/experiments/readout_confusion_matrix_test.py +++ b/cirq/experiments/readout_confusion_matrix_test.py @@ -20,9 +20,9 @@ def get_expected_cm(num_qubits: int, p0: float, p1: float): - expected_cm = np.zeros((2 ** num_qubits,) * 2) - for i in range(2 ** num_qubits): - for j in range(2 ** num_qubits): + expected_cm = np.zeros((2**num_qubits,) * 2) + for i in range(2**num_qubits): + for j in range(2**num_qubits): p = 1.0 for k in range(num_qubits): b0 = (i >> k) & 1 diff --git a/cirq/experiments/t2_decay_experiment.py b/cirq/experiments/t2_decay_experiment.py index 6c17f74e2aa..370515f1e72 100644 --- a/cirq/experiments/t2_decay_experiment.py +++ b/cirq/experiments/t2_decay_experiment.py @@ -423,7 +423,7 @@ def plot_bloch_vector(self, ax: Optional[plt.Axes] = None, **plot_kwargs: Any) - # Estimate length of Bloch vector (projected to xy plane) # by squaring and expectation values - bloch_vector = self._expectation_pauli_x ** 2 + self._expectation_pauli_y ** 2 + bloch_vector = self._expectation_pauli_x**2 + self._expectation_pauli_y**2 ax.plot(self._expectation_pauli_x['delay_ns'], bloch_vector['value'], 'r+-', **plot_kwargs) ax.set_xlabel(r"Delay between initialization and measurement (nanoseconds)") diff --git a/cirq/experiments/t2_decay_experiment_test.py b/cirq/experiments/t2_decay_experiment_test.py index a626ae8e263..ede53b4f610 100644 --- a/cirq/experiments/t2_decay_experiment_test.py +++ b/cirq/experiments/t2_decay_experiment_test.py @@ -155,7 +155,7 @@ def noisy_moment(self, moment, system_qubits): default=cirq.Duration(nanos=1), ) phase = duration.total_nanos() / 100.0 - yield (cirq.Y ** phase).on_each(system_qubits) + yield (cirq.Y**phase).on_each(system_qubits) yield moment pulses = [1] if experiment_type == t2.ExperimentType.CPMG else None diff --git a/cirq/experiments/xeb_fitting.py b/cirq/experiments/xeb_fitting.py index b277d55a7b3..3adc79488ab 100644 --- a/cirq/experiments/xeb_fitting.py +++ b/cirq/experiments/xeb_fitting.py @@ -100,7 +100,7 @@ def benchmark_2q_xeb_fidelities( D = 4 # two qubits pure_probs = np.array(df['pure_probs'].to_list()) sampled_probs = np.array(df['sampled_probs'].to_list()) - df['e_u'] = np.sum(pure_probs ** 2, axis=1) + df['e_u'] = np.sum(pure_probs**2, axis=1) df['u_u'] = np.sum(pure_probs, axis=1) / D df['m_u'] = np.sum(pure_probs * sampled_probs, axis=1) df['y'] = df['m_u'] - df['u_u'] @@ -539,7 +539,7 @@ def exponential_decay(cycle_depths: np.ndarray, a: float, layer_fid: float) -> n a: A scale parameter in the exponential function. layer_fid: The base of the exponent in the exponential function. """ - return a * layer_fid ** cycle_depths + return a * layer_fid**cycle_depths def _fit_exponential_decay( diff --git a/cirq/experiments/xeb_fitting_test.py b/cirq/experiments/xeb_fitting_test.py index 9cb350195c2..ceabbd48f45 100644 --- a/cirq/experiments/xeb_fitting_test.py +++ b/cirq/experiments/xeb_fitting_test.py @@ -103,7 +103,7 @@ def _manhattan_distance(qubit1: cirq.GridQubit, qubit2: cirq.GridQubit) -> int: def test_benchmark_2q_xeb_fidelities_parallel(): circuits = rqcg.generate_library_of_2q_circuits( - n_library_circuits=5, two_qubit_gate=cirq.ISWAP ** 0.5, max_cycle_depth=4 + n_library_circuits=5, two_qubit_gate=cirq.ISWAP**0.5, max_cycle_depth=4 ) cycle_depths = [2, 3, 4] graph = _gridqubits_to_graph_device(cirq.GridQubit.rect(2, 2)) @@ -155,7 +155,7 @@ def _summary_stats(row): D = 4 # two qubits pure_probs = np.array(df['pure_probs'].to_list()) sampled_probs = np.array(df['sampled_probs'].to_list()) - df['e_u'] = np.sum(pure_probs ** 2, axis=1) + df['e_u'] = np.sum(pure_probs**2, axis=1) df['u_u'] = np.sum(pure_probs, axis=1) / D df['m_u'] = np.sum(pure_probs * sampled_probs, axis=1) df['y'] = df['m_u'] - df['u_u'] @@ -258,7 +258,7 @@ def test_characterize_phased_fsim_parameters_with_xeb(): def test_parallel_full_workflow(use_pool): circuits = rqcg.generate_library_of_2q_circuits( n_library_circuits=5, - two_qubit_gate=cirq.ISWAP ** 0.5, + two_qubit_gate=cirq.ISWAP**0.5, max_cycle_depth=4, random_state=8675309, ) @@ -328,7 +328,7 @@ def test_parallel_full_workflow(use_pool): def test_fit_exponential_decays(): rs = np.random.RandomState(999) cycle_depths = np.arange(3, 100, 11) - fidelities = 0.95 * 0.98 ** cycle_depths + rs.normal(0, 0.2) + fidelities = 0.95 * 0.98**cycle_depths + rs.normal(0, 0.2) a, layer_fid, a_std, layer_fid_std = _fit_exponential_decay(cycle_depths, fidelities) np.testing.assert_allclose([a, layer_fid], [0.95, 0.98], atol=0.02) assert 0 < a_std < 0.2 / len(cycle_depths) @@ -338,7 +338,7 @@ def test_fit_exponential_decays(): def test_fit_exponential_decays_negative_fids(): rs = np.random.RandomState(999) cycle_depths = np.arange(3, 100, 11) - fidelities = 0.5 * 0.5 ** cycle_depths + rs.normal(0, 0.2) - 0.5 + fidelities = 0.5 * 0.5**cycle_depths + rs.normal(0, 0.2) - 0.5 assert np.sum(fidelities > 0) <= 1, 'they go negative' a, layer_fid, a_std, layer_fid_std = _fit_exponential_decay(cycle_depths, fidelities) assert a == 0 @@ -348,9 +348,9 @@ def test_fit_exponential_decays_negative_fids(): def test_options_with_defaults_from_gate(): - options = XEBPhasedFSimCharacterizationOptions().with_defaults_from_gate(cirq.ISWAP ** 0.5) + options = XEBPhasedFSimCharacterizationOptions().with_defaults_from_gate(cirq.ISWAP**0.5) np.testing.assert_allclose(options.theta_default, -np.pi / 4) - options = XEBPhasedFSimCharacterizationOptions().with_defaults_from_gate(cirq.ISWAP ** -0.5) + options = XEBPhasedFSimCharacterizationOptions().with_defaults_from_gate(cirq.ISWAP**-0.5) np.testing.assert_allclose(options.theta_default, np.pi / 4) options = XEBPhasedFSimCharacterizationOptions().with_defaults_from_gate( diff --git a/cirq/experiments/xeb_sampling.py b/cirq/experiments/xeb_sampling.py index 1200ccbb79b..3d4349cc73a 100644 --- a/cirq/experiments/xeb_sampling.py +++ b/cirq/experiments/xeb_sampling.py @@ -90,7 +90,7 @@ def __call__(self, tasks: List[_Sample2qXEBTask]) -> List[Dict[str, Any]]: pair_measurement_key = str(pair_i) pair = self.combinations_by_layer[task.layer_i].pairs[pair_i] sampled_inds = result.data[pair_measurement_key].values - sampled_probs = np.bincount(sampled_inds, minlength=2 ** 2) / len(sampled_inds) + sampled_probs = np.bincount(sampled_inds, minlength=2**2) / len(sampled_inds) records.append( { diff --git a/cirq/experiments/xeb_sampling_test.py b/cirq/experiments/xeb_sampling_test.py index fcfad06022f..1aa731cd43a 100644 --- a/cirq/experiments/xeb_sampling_test.py +++ b/cirq/experiments/xeb_sampling_test.py @@ -105,7 +105,7 @@ def _assert_frame_approx_equal(df, df2, *, atol): def test_sample_2q_parallel_xeb_circuits(tmpdir): circuits = rqcg.generate_library_of_2q_circuits( - n_library_circuits=5, two_qubit_gate=cirq.ISWAP ** 0.5, max_cycle_depth=10 + n_library_circuits=5, two_qubit_gate=cirq.ISWAP**0.5, max_cycle_depth=10 ) cycle_depths = [5, 10] graph = _gridqubits_to_graph_device(cirq.GridQubit.rect(3, 2)) @@ -149,7 +149,7 @@ def test_sample_2q_parallel_xeb_circuits(tmpdir): def test_sample_2q_parallel_xeb_circuits_bad_circuit_library(): circuits = rqcg.generate_library_of_2q_circuits( - n_library_circuits=5, two_qubit_gate=cirq.ISWAP ** 0.5, max_cycle_depth=10 + n_library_circuits=5, two_qubit_gate=cirq.ISWAP**0.5, max_cycle_depth=10 ) cycle_depths = [10] graph = _gridqubits_to_graph_device(cirq.GridQubit.rect(3, 2)) @@ -172,7 +172,7 @@ def test_sample_2q_parallel_xeb_circuits_bad_circuit_library(): def test_sample_2q_parallel_xeb_circuits_error_bad_qubits(): circuits = rqcg.generate_library_of_2q_circuits( n_library_circuits=5, - two_qubit_gate=cirq.ISWAP ** 0.5, + two_qubit_gate=cirq.ISWAP**0.5, max_cycle_depth=10, q0=cirq.GridQubit(0, 0), q1=cirq.GridQubit(1, 1), diff --git a/cirq/interop/quirk/cells/composite_cell.py b/cirq/interop/quirk/cells/composite_cell.py index c204ffb8aba..5b98cfb4bc4 100644 --- a/cirq/interop/quirk/cells/composite_cell.py +++ b/cirq/interop/quirk/cells/composite_cell.py @@ -117,7 +117,7 @@ def circuit(self) -> 'cirq.Circuit': ) result += basis_change result += body - result += basis_change ** -1 + result += basis_change**-1 return result def operations(self) -> 'cirq.OP_TREE': diff --git a/cirq/interop/quirk/cells/control_cells.py b/cirq/interop/quirk/cells/control_cells.py index 93d11e44ab6..dc0d8b85198 100644 --- a/cirq/interop/quirk/cells/control_cells.py +++ b/cirq/interop/quirk/cells/control_cells.py @@ -121,14 +121,14 @@ def generate_all_control_cell_makers() -> Iterator[CellMaker]: # Controls. yield _reg_control("•", basis_change=None) yield _reg_control("◦", basis_change=ops.X) - yield _reg_control("⊕", basis_change=ops.Y ** 0.5) - yield _reg_control("⊖", basis_change=ops.Y ** -0.5) - yield _reg_control("⊗", basis_change=ops.X ** -0.5) - yield _reg_control("(/)", basis_change=ops.X ** 0.5) + yield _reg_control("⊕", basis_change=ops.Y**0.5) + yield _reg_control("⊖", basis_change=ops.Y**-0.5) + yield _reg_control("⊗", basis_change=ops.X**-0.5) + yield _reg_control("(/)", basis_change=ops.X**0.5) # Parity controls. - yield _reg_parity_control("xpar", basis_change=ops.Y ** 0.5) - yield _reg_parity_control("ypar", basis_change=ops.X ** -0.5) + yield _reg_parity_control("xpar", basis_change=ops.Y**0.5) + yield _reg_parity_control("ypar", basis_change=ops.X**-0.5) yield _reg_parity_control("zpar", basis_change=None) diff --git a/cirq/interop/quirk/cells/input_rotation_cells_test.py b/cirq/interop/quirk/cells/input_rotation_cells_test.py index 3f93a2c7b8d..eb75d391231 100644 --- a/cirq/interop/quirk/cells/input_rotation_cells_test.py +++ b/cirq/interop/quirk/cells/input_rotation_cells_test.py @@ -37,7 +37,7 @@ def test_input_rotation_cells(): │ 2: ───A1────────── """, - unitary=np.diag([1, 1, 1, 1, 1j ** 0, 1j ** 0.5, 1j ** 1, 1j ** 1.5]), + unitary=np.diag([1, 1, 1, 1, 1j**0, 1j**0.5, 1j**1, 1j**1.5]), ) assert_url_to_circuit_returns( '{"cols":[["Z^(-A/2^n)","inputA1"]]}', unitary=np.diag([1, 1, 1, -1j]) @@ -45,20 +45,20 @@ def test_input_rotation_cells(): assert_url_to_circuit_returns( '{"cols":[["H"],["X^(A/2^n)","inputA2"],["H"]]}', - unitary=np.diag([1, 1, 1, 1, 1j ** 0, 1j ** 0.5, 1j ** 1, 1j ** 1.5]), + unitary=np.diag([1, 1, 1, 1, 1j**0, 1j**0.5, 1j**1, 1j**1.5]), ) assert_url_to_circuit_returns( '{"cols":[["H"],["X^(-A/2^n)","inputA2"],["H"]]}', - unitary=np.diag([1, 1, 1, 1, 1j ** 0, 1j ** -0.5, 1j ** -1, 1j ** -1.5]), + unitary=np.diag([1, 1, 1, 1, 1j**0, 1j**-0.5, 1j**-1, 1j**-1.5]), ) assert_url_to_circuit_returns( '{"cols":[["X^-½"],["Y^(A/2^n)","inputA2"],["X^½"]]}', - unitary=np.diag([1, 1, 1, 1, 1j ** 0, 1j ** 0.5, 1j ** 1, 1j ** 1.5]), + unitary=np.diag([1, 1, 1, 1, 1j**0, 1j**0.5, 1j**1, 1j**1.5]), ) assert_url_to_circuit_returns( '{"cols":[["X^-½"],["Y^(-A/2^n)","inputA2"],["X^½"]]}', - unitary=np.diag([1, 1, 1, 1, 1j ** 0, 1j ** -0.5, 1j ** -1, 1j ** -1.5]), + unitary=np.diag([1, 1, 1, 1, 1j**0, 1j**-0.5, 1j**-1, 1j**-1.5]), ) assert_url_to_circuit_returns( @@ -72,7 +72,7 @@ def test_input_rotation_cells(): │ 3: ───A1────────── """, - unitary=np.diag([1 + 0j] * 13 + [1j ** 0.5, 1j, 1j ** 1.5]), + unitary=np.diag([1 + 0j] * 13 + [1j**0.5, 1j, 1j**1.5]), ) assert_url_to_circuit_returns( diff --git a/cirq/interop/quirk/cells/measurement_cells.py b/cirq/interop/quirk/cells/measurement_cells.py index 1ccc668de55..5a2be8f9e5a 100644 --- a/cirq/interop/quirk/cells/measurement_cells.py +++ b/cirq/interop/quirk/cells/measurement_cells.py @@ -23,8 +23,8 @@ def generate_all_measurement_cell_makers() -> Iterator[CellMaker]: yield _measurement("Measure") yield _measurement("ZDetector") - yield _measurement("YDetector", basis_change=ops.X ** -0.5) - yield _measurement("XDetector", basis_change=ops.Y ** 0.5) + yield _measurement("YDetector", basis_change=ops.X**-0.5) + yield _measurement("XDetector", basis_change=ops.Y**0.5) def _measurement(identifier: str, basis_change: Optional['cirq.Gate'] = None) -> CellMaker: diff --git a/cirq/interop/quirk/cells/parse_test.py b/cirq/interop/quirk/cells/parse_test.py index 0a3cbc332dc..2d9ad0b8235 100644 --- a/cirq/interop/quirk/cells/parse_test.py +++ b/cirq/interop/quirk/cells/parse_test.py @@ -85,7 +85,7 @@ def test_parse_complex(): assert parse_complex('+i') == 1j assert parse_complex('1 + i - i') == 1 assert parse_complex('1 + 2i - 3 i') == 1 - 1j - np.testing.assert_allclose(parse_complex('exp 2'), np.e ** 2, atol=1e-8) + np.testing.assert_allclose(parse_complex('exp 2'), np.e**2, atol=1e-8) def test_parse_complex_raw_cases_from_quirk(): diff --git a/cirq/interop/quirk/cells/scalar_cells.py b/cirq/interop/quirk/cells/scalar_cells.py index 156c7516d8f..0236b354d78 100644 --- a/cirq/interop/quirk/cells/scalar_cells.py +++ b/cirq/interop/quirk/cells/scalar_cells.py @@ -24,7 +24,7 @@ def generate_all_scalar_cell_makers() -> Iterator[CellMaker]: yield _scalar("NeGate", ops.global_phase_operation(-1)) yield _scalar("i", ops.global_phase_operation(1j)) yield _scalar("-i", ops.global_phase_operation(-1j)) - yield _scalar("√i", ops.global_phase_operation(1j ** 0.5)) + yield _scalar("√i", ops.global_phase_operation(1j**0.5)) yield _scalar("√-i", ops.global_phase_operation((-1j) ** 0.5)) diff --git a/cirq/interop/quirk/cells/scalar_cells_test.py b/cirq/interop/quirk/cells/scalar_cells_test.py index 9e94209b8c5..648da7bc24a 100644 --- a/cirq/interop/quirk/cells/scalar_cells_test.py +++ b/cirq/interop/quirk/cells/scalar_cells_test.py @@ -30,9 +30,9 @@ def test_scalar_operations(): ) assert_url_to_circuit_returns( - '{"cols":[["√i"]]}', cirq.Circuit(cirq.global_phase_operation(1j ** 0.5)) + '{"cols":[["√i"]]}', cirq.Circuit(cirq.global_phase_operation(1j**0.5)) ) assert_url_to_circuit_returns( - '{"cols":[["√-i"]]}', cirq.Circuit(cirq.global_phase_operation(1j ** -0.5)) + '{"cols":[["√-i"]]}', cirq.Circuit(cirq.global_phase_operation(1j**-0.5)) ) diff --git a/cirq/interop/quirk/cells/single_qubit_rotation_cells.py b/cirq/interop/quirk/cells/single_qubit_rotation_cells.py index 73132382a22..cc4edd184bb 100644 --- a/cirq/interop/quirk/cells/single_qubit_rotation_cells.py +++ b/cirq/interop/quirk/cells/single_qubit_rotation_cells.py @@ -83,9 +83,9 @@ def generate_all_single_qubit_rotation_cell_makers() -> Iterator[CellMaker]: yield _gate("e^-iZt", ops.rz(-2 * sympy.pi * sympy.Symbol('t'))) # Formulaic single qubit rotations. - yield _formula_gate("X^ft", "sin(pi*t)", lambda e: ops.X ** e) - yield _formula_gate("Y^ft", "sin(pi*t)", lambda e: ops.Y ** e) - yield _formula_gate("Z^ft", "sin(pi*t)", lambda e: ops.Z ** e) + yield _formula_gate("X^ft", "sin(pi*t)", lambda e: ops.X**e) + yield _formula_gate("Y^ft", "sin(pi*t)", lambda e: ops.Y**e) + yield _formula_gate("Z^ft", "sin(pi*t)", lambda e: ops.Z**e) yield _formula_gate("Rxft", "pi*t*t", ops.rx) yield _formula_gate("Ryft", "pi*t*t", ops.ry) yield _formula_gate("Rzft", "pi*t*t", ops.rz) diff --git a/cirq/interop/quirk/url_to_circuit.py b/cirq/interop/quirk/url_to_circuit.py index dae7b14f663..4007e0722ac 100644 --- a/cirq/interop/quirk/url_to_circuit.py +++ b/cirq/interop/quirk/url_to_circuit.py @@ -51,7 +51,7 @@ def quirk_url_to_circuit( extra_cell_makers: Union[ Dict[str, 'cirq.Gate'], Iterable['cirq.interop.quirk.cells.CellMaker'] ] = (), - max_operation_count: int = 10 ** 6, + max_operation_count: int = 10**6, ) -> 'cirq.Circuit': """Parses a Cirq circuit out of a Quirk URL. @@ -154,7 +154,7 @@ def quirk_json_to_circuit( Dict[str, 'cirq.Gate'], Iterable['cirq.interop.quirk.cells.CellMaker'] ] = (), quirk_url: Optional[str] = None, - max_operation_count: int = 10 ** 6, + max_operation_count: int = 10**6, ) -> 'cirq.Circuit': """Constructs a Cirq circuit from Quirk's JSON format. diff --git a/cirq/interop/quirk/url_to_circuit_test.py b/cirq/interop/quirk/url_to_circuit_test.py index 1762dd18cb0..2205c53870f 100644 --- a/cirq/interop/quirk/url_to_circuit_test.py +++ b/cirq/interop/quirk/url_to_circuit_test.py @@ -83,21 +83,15 @@ def test_parse_with_qubits(): b = cirq.GridQubit(0, 1) c = cirq.GridQubit(0, 2) - assert ( - quirk_url_to_circuit( - 'http://algassert.com/quirk#circuit={"cols":[["H"],["•","X"]]}', - qubits=cirq.GridQubit.rect(4, 4), - ) - == cirq.Circuit(cirq.H(a), cirq.X(b).controlled_by(a)) - ) + assert quirk_url_to_circuit( + 'http://algassert.com/quirk#circuit={"cols":[["H"],["•","X"]]}', + qubits=cirq.GridQubit.rect(4, 4), + ) == cirq.Circuit(cirq.H(a), cirq.X(b).controlled_by(a)) - assert ( - quirk_url_to_circuit( - 'http://algassert.com/quirk#circuit={"cols":[["H"],["•",1,"X"]]}', - qubits=cirq.GridQubit.rect(4, 4), - ) - == cirq.Circuit(cirq.H(a), cirq.X(c).controlled_by(a)) - ) + assert quirk_url_to_circuit( + 'http://algassert.com/quirk#circuit={"cols":[["H"],["•",1,"X"]]}', + qubits=cirq.GridQubit.rect(4, 4), + ) == cirq.Circuit(cirq.H(a), cirq.X(c).controlled_by(a)) with pytest.raises(IndexError, match="qubits specified"): _ = quirk_url_to_circuit( @@ -107,25 +101,19 @@ def test_parse_with_qubits(): def test_extra_cell_makers(): - assert ( - cirq.quirk_url_to_circuit( - 'http://algassert.com/quirk#circuit={"cols":[["iswap"]]}', - extra_cell_makers=[ - cirq.interop.quirk.cells.CellMaker( - identifier='iswap', size=2, maker=lambda args: cirq.ISWAP(*args.qubits) - ) - ], - ) - == cirq.Circuit(cirq.ISWAP(*cirq.LineQubit.range(2))) - ) + assert cirq.quirk_url_to_circuit( + 'http://algassert.com/quirk#circuit={"cols":[["iswap"]]}', + extra_cell_makers=[ + cirq.interop.quirk.cells.CellMaker( + identifier='iswap', size=2, maker=lambda args: cirq.ISWAP(*args.qubits) + ) + ], + ) == cirq.Circuit(cirq.ISWAP(*cirq.LineQubit.range(2))) - assert ( - cirq.quirk_url_to_circuit( - 'http://algassert.com/quirk#circuit={"cols":[["iswap"]]}', - extra_cell_makers={'iswap': cirq.ISWAP}, - ) - == cirq.Circuit(cirq.ISWAP(*cirq.LineQubit.range(2))) - ) + assert cirq.quirk_url_to_circuit( + 'http://algassert.com/quirk#circuit={"cols":[["iswap"]]}', + extra_cell_makers={'iswap': cirq.ISWAP}, + ) == cirq.Circuit(cirq.ISWAP(*cirq.LineQubit.range(2))) assert cirq.quirk_url_to_circuit( 'http://algassert.com/quirk#circuit={"cols":[["iswap"], ["toffoli"]]}', @@ -327,7 +315,7 @@ def test_survives_a_billion_laughs(): '{"id":"~y","circuit":{"cols":[["~x"],["~x"],["~x"],["~x"]]}},' '{"id":"~z","circuit":{"cols":[["~y"],["~y"],["~y"],["~y"]]}}' ']}', - max_operation_count=10 ** 6, + max_operation_count=10**6, ) diff --git a/cirq/ion/ion_decomposition.py b/cirq/ion/ion_decomposition.py index 81c88bbd919..691780e1115 100644 --- a/cirq/ion/ion_decomposition.py +++ b/cirq/ion/ion_decomposition.py @@ -118,6 +118,6 @@ def _non_local_part( return [ _parity_interaction(q0, q1, x, atol), - _parity_interaction(q0, q1, y, atol, ops.Z ** -0.5), - _parity_interaction(q0, q1, z, atol, ops.Y ** 0.5), + _parity_interaction(q0, q1, y, atol, ops.Z**-0.5), + _parity_interaction(q0, q1, z, atol, ops.Y**0.5), ] diff --git a/cirq/ion/ion_gates_test.py b/cirq/ion/ion_gates_test.py index e94c9e9255e..538abb20f0c 100644 --- a/cirq/ion/ion_gates_test.py +++ b/cirq/ion/ion_gates_test.py @@ -27,9 +27,9 @@ def test_ms_str(): ms = cirq.ms(np.pi / 2) assert str(ms) == 'MS(π/2)' assert str(cirq.ms(np.pi)) == 'MS(2.0π/2)' - assert str(ms ** 0.5) == 'MS(0.5π/2)' - assert str(ms ** 2) == 'MS(2.0π/2)' - assert str(ms ** -1) == 'MS(-1.0π/2)' + assert str(ms**0.5) == 'MS(0.5π/2)' + assert str(ms**2) == 'MS(2.0π/2)' + assert str(ms**-1) == 'MS(-1.0π/2)' def test_ms_matrix(): @@ -50,8 +50,8 @@ def test_ms_repr(): assert repr(cirq.ms(np.pi / 4)) == 'cirq.ms(0.5*np.pi/2)' cirq.testing.assert_equivalent_repr(cirq.ms(np.pi / 4)) ms = cirq.ms(np.pi / 2) - assert repr(ms ** 2) == 'cirq.ms(2.0*np.pi/2)' - assert repr(ms ** -0.5) == 'cirq.ms(-0.5*np.pi/2)' + assert repr(ms**2) == 'cirq.ms(2.0*np.pi/2)' + assert repr(ms**-0.5) == 'cirq.ms(-0.5*np.pi/2)' def test_ms_diagrams(): diff --git a/cirq/linalg/decompositions.py b/cirq/linalg/decompositions.py index 163d51b9946..7248dd4ec32 100644 --- a/cirq/linalg/decompositions.py +++ b/cirq/linalg/decompositions.py @@ -726,7 +726,7 @@ def kak_canonicalize_vector(x: float, y: float, z: float, atol: float = 1e-9) -> # Shifting strength by ½π is equivalent to local ops (e.g. exp(i½π XX)∝XX). def shift(k, step): v[k] += step * np.pi / 2 - phase[0] *= 1j ** step + phase[0] *= 1j**step right[0] = combinators.dot(flippers[k] ** (step % 4), right[0]) right[1] = combinators.dot(flippers[k] ** (step % 4), right[1]) diff --git a/cirq/linalg/decompositions_test.py b/cirq/linalg/decompositions_test.py index 855ed96f565..8b1f255f085 100644 --- a/cirq/linalg/decompositions_test.py +++ b/cirq/linalg/decompositions_test.py @@ -425,13 +425,13 @@ def test_axis_angle_decomposition_str(): assert str(cirq.axis_angle(cirq.unitary(cirq.Y))) == '1*π around Y' assert str(cirq.axis_angle(cirq.unitary(cirq.Z))) == '1*π around Z' assert str(cirq.axis_angle(cirq.unitary(cirq.H))) == '1*π around 0.707*X+0.707*Z' - assert str(cirq.axis_angle(cirq.unitary(cirq.H ** 0.5))) == '0.5*π around 0.707*X+0.707*Z' + assert str(cirq.axis_angle(cirq.unitary(cirq.H**0.5))) == '0.5*π around 0.707*X+0.707*Z' assert ( str( cirq.axis_angle( - cirq.unitary(cirq.X ** 0.25) - @ cirq.unitary(cirq.Y ** 0.25) - @ cirq.unitary(cirq.Z ** 0.25) + cirq.unitary(cirq.X**0.25) + @ cirq.unitary(cirq.Y**0.25) + @ cirq.unitary(cirq.Z**0.25) ) ) == '0.477*π around 0.679*X+0.281*Y+0.679*Z' @@ -462,14 +462,14 @@ def test_axis_angle(): atol=1e-8, ) assert cirq.approx_eq( - cirq.axis_angle(cirq.unitary(cirq.X ** 0.5)), + cirq.axis_angle(cirq.unitary(cirq.X**0.5)), cirq.AxisAngleDecomposition( angle=np.pi / 2, axis=(1, 0, 0), global_phase=np.exp(1j * np.pi / 4) ), atol=1e-8, ) assert cirq.approx_eq( - cirq.axis_angle(cirq.unitary(cirq.X ** -0.5)), + cirq.axis_angle(cirq.unitary(cirq.X**-0.5)), cirq.AxisAngleDecomposition( angle=-np.pi / 2, axis=(1, 0, 0), global_phase=np.exp(-1j * np.pi / 4) ), @@ -496,7 +496,7 @@ def test_axis_angle(): ) assert cirq.approx_eq( - cirq.axis_angle(cirq.unitary(cirq.H ** 0.5)), + cirq.axis_angle(cirq.unitary(cirq.H**0.5)), cirq.AxisAngleDecomposition( angle=np.pi / 2, axis=(np.sqrt(0.5), 0, np.sqrt(0.5)), @@ -736,9 +736,9 @@ def test_kak_vector_input_not_unitary(): cirq.testing.random_unitary(4), cirq.unitary(cirq.IdentityGate(2)), cirq.unitary(cirq.SWAP), - cirq.unitary(cirq.SWAP ** 0.25), + cirq.unitary(cirq.SWAP**0.25), cirq.unitary(cirq.ISWAP), - cirq.unitary(cirq.CZ ** 0.5), + cirq.unitary(cirq.CZ**0.5), cirq.unitary(cirq.CZ), ], ) diff --git a/cirq/linalg/operator_spaces_test.py b/cirq/linalg/operator_spaces_test.py index 27decca0627..3070c8ec4df 100644 --- a/cirq/linalg/operator_spaces_test.py +++ b/cirq/linalg/operator_spaces_test.py @@ -123,7 +123,7 @@ def test_kron_bases_consistency(basis1, basis2): @pytest.mark.parametrize('basis,repeat', itertools.product((PAULI_BASIS, STANDARD_BASIS), range(5))) def test_kron_bases_repeat_sanity_checks(basis, repeat): product_basis = cirq.kron_bases(basis, repeat=repeat) - assert len(product_basis) == 4 ** repeat + assert len(product_basis) == 4**repeat for name1, matrix1 in product_basis.items(): for name2, matrix2 in product_basis.items(): p = cirq.hilbert_schmidt_inner_product(matrix1, matrix2) diff --git a/cirq/linalg/transformations.py b/cirq/linalg/transformations.py index 614a34940f1..d407ffe57e2 100644 --- a/cirq/linalg/transformations.py +++ b/cirq/linalg/transformations.py @@ -368,7 +368,7 @@ def partial_trace_of_state_vector_as_mixture( if state_vector.ndim == 1: dims = int(np.log2(state_vector.size)) - if 2 ** dims != state_vector.size: + if 2**dims != state_vector.size: raise ValueError(f'Cannot infer underlying shape of {state_vector.shape}.') state_vector = state_vector.reshape((2,) * dims) ret_shape: Tuple[int, ...] = (2 ** len(keep_indices),) diff --git a/cirq/linalg/transformations_test.py b/cirq/linalg/transformations_test.py index 3303aec9935..d9f5175e18c 100644 --- a/cirq/linalg/transformations_test.py +++ b/cirq/linalg/transformations_test.py @@ -547,7 +547,7 @@ def test_partial_trace_of_state_vector_as_mixture_pure_result(): ) # Shapes of states in the output mixture conform to the input's shape. - state = state.reshape(2 ** 9) + state = state.reshape(2**9) assert mixtures_equal( cirq.partial_trace_of_state_vector_as_mixture(state, [0, 1], atol=1e-8), ((1.0, a),) ) diff --git a/cirq/neutral_atoms/neutral_atom_devices_test.py b/cirq/neutral_atoms/neutral_atom_devices_test.py index a1a410ddd0f..1a3d6f0eb86 100644 --- a/cirq/neutral_atoms/neutral_atom_devices_test.py +++ b/cirq/neutral_atoms/neutral_atom_devices_test.py @@ -23,8 +23,8 @@ def square_device( width: int, height: int, holes=(), max_controls=2, use_timedelta=False ) -> neutral_atoms.NeutralAtomDevice: - us = cirq.Duration(nanos=10 ** 3) if not use_timedelta else timedelta(microseconds=1) - ms = cirq.Duration(nanos=10 ** 6) if not use_timedelta else timedelta(microseconds=1000) + us = cirq.Duration(nanos=10**3) if not use_timedelta else timedelta(microseconds=1) + ms = cirq.Duration(nanos=10**6) if not use_timedelta else timedelta(microseconds=1000) return neutral_atoms.NeutralAtomDevice( # type: ignore measurement_duration=50 * ms, # type: ignore gate_duration=100 * us, # type: ignore @@ -43,8 +43,8 @@ def square_device( def test_init(): d = square_device(2, 2, holes=[cirq.GridQubit(1, 1)]) - us = cirq.Duration(nanos=10 ** 3) - ms = cirq.Duration(nanos=10 ** 6) + us = cirq.Duration(nanos=10**3) + ms = cirq.Duration(nanos=10**6) q00 = cirq.GridQubit(0, 0) q01 = cirq.GridQubit(0, 1) q10 = cirq.GridQubit(1, 0) @@ -73,8 +73,8 @@ def test_metadata(): def test_init_timedelta(): d = square_device(2, 2, holes=[cirq.GridQubit(1, 1)], use_timedelta=True) - us = cirq.Duration(nanos=10 ** 3) - ms = cirq.Duration(nanos=10 ** 6) + us = cirq.Duration(nanos=10**3) + ms = cirq.Duration(nanos=10**6) q00 = cirq.GridQubit(0, 0) q01 = cirq.GridQubit(0, 1) q10 = cirq.GridQubit(1, 0) @@ -88,8 +88,8 @@ def test_init_timedelta(): def test_init_errors(): line = cirq.LineQubit.range(3) - us = cirq.Duration(nanos=10 ** 3) - ms = cirq.Duration(nanos=10 ** 6) + us = cirq.Duration(nanos=10**3) + ms = cirq.Duration(nanos=10**6) with pytest.raises(ValueError, match="Unsupported qubit type"): _ = neutral_atoms.NeutralAtomDevice( measurement_duration=50 * ms, @@ -115,7 +115,7 @@ def test_init_errors(): def test_decompose_error_deprecated(): d = square_device(2, 2, holes=[cirq.GridQubit(1, 1)]) with cirq.testing.assert_deprecated('ConvertToNeutralAtomGates', deadline='v0.15'): - for op in d.decompose_operation((cirq.CCZ ** 1.5).on(*(d.qubit_list()))): + for op in d.decompose_operation((cirq.CCZ**1.5).on(*(d.qubit_list()))): d.validate_operation(op) @@ -176,7 +176,7 @@ def test_validate_moment_errors(): q20 = cirq.GridQubit(2, 0) q21 = cirq.GridQubit(2, 1) - m = cirq.Moment([cirq.Z.on(q00), (cirq.Z ** 2).on(q01)]) + m = cirq.Moment([cirq.Z.on(q00), (cirq.Z**2).on(q01)]) with pytest.raises(ValueError, match="Non-identical simultaneous "): d.validate_moment(m) m = cirq.Moment([cirq.X.on(q00), cirq.Y.on(q01)]) @@ -206,8 +206,8 @@ def test_validate_moment_errors(): ): d.validate_moment(m) d.validate_moment(cirq.Moment([cirq.X.on(q00), cirq.Z.on(q01)])) - us = cirq.Duration(nanos=10 ** 3) - ms = cirq.Duration(nanos=10 ** 6) + us = cirq.Duration(nanos=10**3) + ms = cirq.Duration(nanos=10**6) d2 = neutral_atoms.NeutralAtomDevice( measurement_duration=50 * ms, gate_duration=100 * us, diff --git a/cirq/ops/boolean_hamiltonian_test.py b/cirq/ops/boolean_hamiltonian_test.py index 4932450836d..420131ca05b 100644 --- a/cirq/ops/boolean_hamiltonian_test.py +++ b/cirq/ops/boolean_hamiltonian_test.py @@ -150,7 +150,7 @@ def test_gate_consistent(): ) def test_gray_code_sorting(n_bits, expected_hs): hs_template = [] - for x in range(2 ** n_bits): + for x in range(2**n_bits): h = [] for i in range(n_bits): if x % 2 == 1: diff --git a/cirq/ops/clifford_gate.py b/cirq/ops/clifford_gate.py index 91649fdc1aa..4035770113e 100644 --- a/cirq/ops/clifford_gate.py +++ b/cirq/ops/clifford_gate.py @@ -487,7 +487,7 @@ def equivalent_gate_before(self, after: 'SingleQubitCliffordGate') -> 'SingleQub """Returns a SingleQubitCliffordGate such that the circuits --output--self-- and --self--gate-- are equivalent up to global phase.""" - return self.merged_with(after).merged_with(self ** -1) + return self.merged_with(after).merged_with(self**-1) def __repr__(self) -> str: x = self.transform(pauli_gates.X) diff --git a/cirq/ops/clifford_gate_test.py b/cirq/ops/clifford_gate_test.py index 1a4424f0435..4aa8db2f90d 100644 --- a/cirq/ops/clifford_gate_test.py +++ b/cirq/ops/clifford_gate_test.py @@ -148,7 +148,7 @@ def test_init_90rot_from_single(trans, frm): # Check that flipping the transform produces the inverse rotation trans_rev = cirq.PauliTransform(trans.to, not trans.flip) gate_rev = cirq.SingleQubitCliffordGate.from_single_map({frm: trans_rev}) - assert gate ** -1 == gate_rev + assert gate**-1 == gate_rev @pytest.mark.parametrize( @@ -206,20 +206,20 @@ def test_init_from_pauli(pauli, sqrt, expected): def test_pow(): - assert cirq.SingleQubitCliffordGate.X ** -1 == cirq.SingleQubitCliffordGate.X - assert cirq.SingleQubitCliffordGate.H ** -1 == cirq.SingleQubitCliffordGate.H - assert cirq.SingleQubitCliffordGate.X_sqrt == cirq.SingleQubitCliffordGate.X ** 0.5 - assert cirq.SingleQubitCliffordGate.Y_sqrt == cirq.SingleQubitCliffordGate.Y ** 0.5 - assert cirq.SingleQubitCliffordGate.Z_sqrt == cirq.SingleQubitCliffordGate.Z ** 0.5 - assert cirq.SingleQubitCliffordGate.X_nsqrt == cirq.SingleQubitCliffordGate.X ** -0.5 - assert cirq.SingleQubitCliffordGate.Y_nsqrt == cirq.SingleQubitCliffordGate.Y ** -0.5 - assert cirq.SingleQubitCliffordGate.Z_nsqrt == cirq.SingleQubitCliffordGate.Z ** -0.5 - assert cirq.SingleQubitCliffordGate.X_sqrt ** -1 == cirq.SingleQubitCliffordGate.X_nsqrt + assert cirq.SingleQubitCliffordGate.X**-1 == cirq.SingleQubitCliffordGate.X + assert cirq.SingleQubitCliffordGate.H**-1 == cirq.SingleQubitCliffordGate.H + assert cirq.SingleQubitCliffordGate.X_sqrt == cirq.SingleQubitCliffordGate.X**0.5 + assert cirq.SingleQubitCliffordGate.Y_sqrt == cirq.SingleQubitCliffordGate.Y**0.5 + assert cirq.SingleQubitCliffordGate.Z_sqrt == cirq.SingleQubitCliffordGate.Z**0.5 + assert cirq.SingleQubitCliffordGate.X_nsqrt == cirq.SingleQubitCliffordGate.X**-0.5 + assert cirq.SingleQubitCliffordGate.Y_nsqrt == cirq.SingleQubitCliffordGate.Y**-0.5 + assert cirq.SingleQubitCliffordGate.Z_nsqrt == cirq.SingleQubitCliffordGate.Z**-0.5 + assert cirq.SingleQubitCliffordGate.X_sqrt**-1 == cirq.SingleQubitCliffordGate.X_nsqrt assert cirq.inverse(cirq.SingleQubitCliffordGate.X_nsqrt) == ( cirq.SingleQubitCliffordGate.X_sqrt ) with pytest.raises(TypeError): - _ = cirq.SingleQubitCliffordGate.Z ** 0.25 + _ = cirq.SingleQubitCliffordGate.Z**0.25 def test_init_from_quarter_turns(): @@ -353,17 +353,17 @@ def test_y_rotation(gate, trans_y): @pytest.mark.parametrize( 'gate,gate_equiv', ( - (cirq.SingleQubitCliffordGate.I, cirq.X ** 0), + (cirq.SingleQubitCliffordGate.I, cirq.X**0), (cirq.SingleQubitCliffordGate.H, cirq.H), (cirq.SingleQubitCliffordGate.X, cirq.X), (cirq.SingleQubitCliffordGate.Y, cirq.Y), (cirq.SingleQubitCliffordGate.Z, cirq.Z), - (cirq.SingleQubitCliffordGate.X_sqrt, cirq.X ** 0.5), - (cirq.SingleQubitCliffordGate.X_nsqrt, cirq.X ** -0.5), - (cirq.SingleQubitCliffordGate.Y_sqrt, cirq.Y ** 0.5), - (cirq.SingleQubitCliffordGate.Y_nsqrt, cirq.Y ** -0.5), - (cirq.SingleQubitCliffordGate.Z_sqrt, cirq.Z ** 0.5), - (cirq.SingleQubitCliffordGate.Z_nsqrt, cirq.Z ** -0.5), + (cirq.SingleQubitCliffordGate.X_sqrt, cirq.X**0.5), + (cirq.SingleQubitCliffordGate.X_nsqrt, cirq.X**-0.5), + (cirq.SingleQubitCliffordGate.Y_sqrt, cirq.Y**0.5), + (cirq.SingleQubitCliffordGate.Y_nsqrt, cirq.Y**-0.5), + (cirq.SingleQubitCliffordGate.Z_sqrt, cirq.Z**0.5), + (cirq.SingleQubitCliffordGate.Z_nsqrt, cirq.Z**-0.5), ), ) def test_decompose(gate, gate_equiv): @@ -378,17 +378,17 @@ def test_decompose(gate, gate_equiv): @pytest.mark.parametrize( 'gate,gate_equiv', ( - (cirq.SingleQubitCliffordGate.I, cirq.X ** 0), + (cirq.SingleQubitCliffordGate.I, cirq.X**0), (cirq.SingleQubitCliffordGate.H, cirq.H), (cirq.SingleQubitCliffordGate.X, cirq.X), (cirq.SingleQubitCliffordGate.Y, cirq.Y), (cirq.SingleQubitCliffordGate.Z, cirq.Z), - (cirq.SingleQubitCliffordGate.X_sqrt, cirq.X ** 0.5), - (cirq.SingleQubitCliffordGate.X_nsqrt, cirq.X ** -0.5), - (cirq.SingleQubitCliffordGate.Y_sqrt, cirq.Y ** 0.5), - (cirq.SingleQubitCliffordGate.Y_nsqrt, cirq.Y ** -0.5), - (cirq.SingleQubitCliffordGate.Z_sqrt, cirq.Z ** 0.5), - (cirq.SingleQubitCliffordGate.Z_nsqrt, cirq.Z ** -0.5), + (cirq.SingleQubitCliffordGate.X_sqrt, cirq.X**0.5), + (cirq.SingleQubitCliffordGate.X_nsqrt, cirq.X**-0.5), + (cirq.SingleQubitCliffordGate.Y_sqrt, cirq.Y**0.5), + (cirq.SingleQubitCliffordGate.Y_nsqrt, cirq.Y**-0.5), + (cirq.SingleQubitCliffordGate.Z_sqrt, cirq.Z**0.5), + (cirq.SingleQubitCliffordGate.Z_nsqrt, cirq.Z**-0.5), ), ) def test_known_matrix(gate, gate_equiv): @@ -459,7 +459,7 @@ def test_parses_single_qubit_gate(gate): ) def test_commutes_pauli(gate, pauli, half_turns): # TODO(#4328) cirq.X**1 should be _PauliX instead of XPowGate - pauli_gate = pauli if half_turns == 1 else pauli ** half_turns + pauli_gate = pauli if half_turns == 1 else pauli**half_turns q0 = cirq.NamedQubit('q0') mat = cirq.Circuit( gate(q0), @@ -589,7 +589,7 @@ def test_from_xz_to_clifford_tableau(): seen_tableau = [] for trans_x, trans_z in _all_rotation_pairs(): tableau = cirq.SingleQubitCliffordGate.from_xz_map(trans_x, trans_z).clifford_tableau - tableau_number = sum(2 ** i * t for i, t in enumerate(tableau.matrix().ravel())) + tableau_number = sum(2**i * t for i, t in enumerate(tableau.matrix().ravel())) tableau_number = tableau_number * 4 + 2 * tableau.rs[0] + tableau.rs[1] seen_tableau.append(tableau_number) # Satisfy the symplectic property @@ -630,15 +630,15 @@ def test_common_clifford_gate_caching(clifford_gate_name): def test_multi_qubit_clifford_pow(): - assert cirq.CliffordGate.X ** -1 == cirq.CliffordGate.X - assert cirq.CliffordGate.H ** -1 == cirq.CliffordGate.H - assert cirq.CliffordGate.S ** 2 == cirq.CliffordGate.Z - assert cirq.CliffordGate.S ** -1 == cirq.CliffordGate.S ** 3 - assert cirq.CliffordGate.S ** -3 == cirq.CliffordGate.S - assert cirq.CliffordGate.CNOT ** 3 == cirq.CliffordGate.CNOT - assert cirq.CliffordGate.CNOT ** -3 == cirq.CliffordGate.CNOT + assert cirq.CliffordGate.X**-1 == cirq.CliffordGate.X + assert cirq.CliffordGate.H**-1 == cirq.CliffordGate.H + assert cirq.CliffordGate.S**2 == cirq.CliffordGate.Z + assert cirq.CliffordGate.S**-1 == cirq.CliffordGate.S**3 + assert cirq.CliffordGate.S**-3 == cirq.CliffordGate.S + assert cirq.CliffordGate.CNOT**3 == cirq.CliffordGate.CNOT + assert cirq.CliffordGate.CNOT**-3 == cirq.CliffordGate.CNOT with pytest.raises(TypeError): - _ = cirq.CliffordGate.Z ** 0.25 + _ = cirq.CliffordGate.Z**0.25 def test_stabilizer_effec(): diff --git a/cirq/ops/common_channels.py b/cirq/ops/common_channels.py index 753db55dc78..8b5ec1c5bc2 100644 --- a/cirq/ops/common_channels.py +++ b/cirq/ops/common_channels.py @@ -280,7 +280,7 @@ def __init__(self, p: float, n_qubits: int = 1) -> None: error_probabilities = {} - p_depol = p / (4 ** n_qubits - 1) + p_depol = p / (4**n_qubits - 1) p_identity = 1.0 - p for pauli_tuple in itertools.product(['I', 'X', 'Y', 'Z'], repeat=n_qubits): pauli_string = ''.join(pauli_tuple) diff --git a/cirq/ops/common_gate_families_test.py b/cirq/ops/common_gate_families_test.py index 6c78e128713..5c2a25a72c4 100644 --- a/cirq/ops/common_gate_families_test.py +++ b/cirq/ops/common_gate_families_test.py @@ -65,8 +65,8 @@ def test_any_integer_power_gate_family(): eq.add_equality_group(cirq.AnyIntegerPowerGateFamily(cirq.EigenGate)) cirq.testing.assert_equivalent_repr(gate_family) assert CustomX in gate_family - assert CustomX ** 2 in gate_family - assert CustomX ** 1.5 not in gate_family + assert CustomX**2 in gate_family + assert CustomX**1.5 not in gate_family assert CustomX ** sympy.Symbol('theta') not in gate_family assert 'CustomXPowGate' in gate_family.name assert '`g.exponent` is an integer' in gate_family.description diff --git a/cirq/ops/common_gates.py b/cirq/ops/common_gates.py index 75938f9a385..9ceebe1424c 100644 --- a/cirq/ops/common_gates.py +++ b/cirq/ops/common_gates.py @@ -908,7 +908,7 @@ def _pauli_expansion_(self) -> value.LinearDict[str]: if protocols.is_parameterized(self): return NotImplemented global_phase = 1j ** (2 * self._exponent * self._global_shift) - z_phase = 1j ** self._exponent + z_phase = 1j**self._exponent c = -1j * z_phase * np.sin(np.pi * self._exponent / 2) / 2 return value.LinearDict( { @@ -1090,7 +1090,7 @@ def _pauli_expansion_(self) -> value.LinearDict[str]: if protocols.is_parameterized(self): return NotImplemented global_phase = 1j ** (2 * self._exponent * self._global_shift) - cnot_phase = 1j ** self._exponent + cnot_phase = 1j**self._exponent c = -1j * cnot_phase * np.sin(np.pi * self._exponent / 2) / 2 return value.LinearDict( { diff --git a/cirq/ops/common_gates_test.py b/cirq/ops/common_gates_test.py index f22af2f7501..8e59fa66921 100644 --- a/cirq/ops/common_gates_test.py +++ b/cirq/ops/common_gates_test.py @@ -53,7 +53,7 @@ def test_phase_sensitive_eigen_gates_consistent_protocols(eigen_gate_type): def test_cz_init(): assert cirq.CZPowGate(exponent=0.5).exponent == 0.5 assert cirq.CZPowGate(exponent=5).exponent == 5 - assert (cirq.CZ ** 0.5).exponent == 0.5 + assert (cirq.CZ**0.5).exponent == 0.5 @pytest.mark.parametrize('theta,pi', [(0.4, np.pi), (sympy.Symbol("theta"), sympy.pi)]) @@ -80,14 +80,14 @@ def test_transformations(theta, pi): def test_cz_str(): assert str(cirq.CZ) == 'CZ' - assert str(cirq.CZ ** 0.5) == 'CZ**0.5' - assert str(cirq.CZ ** -0.25) == 'CZ**-0.25' + assert str(cirq.CZ**0.5) == 'CZ**0.5' + assert str(cirq.CZ**-0.25) == 'CZ**-0.25' def test_cz_repr(): assert repr(cirq.CZ) == 'cirq.CZ' - assert repr(cirq.CZ ** 0.5) == '(cirq.CZ**0.5)' - assert repr(cirq.CZ ** -0.25) == '(cirq.CZ**-0.25)' + assert repr(cirq.CZ**0.5) == '(cirq.CZ**0.5)' + assert repr(cirq.CZ**-0.25) == '(cirq.CZ**-0.25)' def test_cz_unitary(): @@ -96,17 +96,17 @@ def test_cz_unitary(): ) assert np.allclose( - cirq.unitary(cirq.CZ ** 0.5), + cirq.unitary(cirq.CZ**0.5), np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1j]]), ) assert np.allclose( - cirq.unitary(cirq.CZ ** 0), + cirq.unitary(cirq.CZ**0), np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]), ) assert np.allclose( - cirq.unitary(cirq.CZ ** -0.5), + cirq.unitary(cirq.CZ**-0.5), np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1j]]), ) @@ -116,9 +116,9 @@ def test_z_init(): assert z.exponent == 5 # Canonicalizes exponent for equality, but keeps the inner details. - assert cirq.Z ** 0.5 != cirq.Z ** -0.5 - assert (cirq.Z ** -1) ** 0.5 == cirq.Z ** -0.5 - assert cirq.Z ** -1 == cirq.Z + assert cirq.Z**0.5 != cirq.Z**-0.5 + assert (cirq.Z**-1) ** 0.5 == cirq.Z**-0.5 + assert cirq.Z**-1 == cirq.Z @pytest.mark.parametrize( @@ -222,11 +222,11 @@ def test_global_phase_controlled_gate(gate, matrix): def test_rot_gates_eq(): eq = cirq.testing.EqualsTester() gates = [ - lambda p: cirq.CZ ** p, - lambda p: cirq.X ** p, - lambda p: cirq.Y ** p, - lambda p: cirq.Z ** p, - lambda p: cirq.CNOT ** p, + lambda p: cirq.CZ**p, + lambda p: cirq.X**p, + lambda p: cirq.Y**p, + lambda p: cirq.Z**p, + lambda p: cirq.CNOT**p, ] for gate in gates: eq.add_equality_group(gate(3.5), gate(-0.5)) @@ -250,22 +250,22 @@ def test_rot_gates_eq(): def test_z_unitary(): assert np.allclose(cirq.unitary(cirq.Z), np.array([[1, 0], [0, -1]])) - assert np.allclose(cirq.unitary(cirq.Z ** 0.5), np.array([[1, 0], [0, 1j]])) - assert np.allclose(cirq.unitary(cirq.Z ** 0), np.array([[1, 0], [0, 1]])) - assert np.allclose(cirq.unitary(cirq.Z ** -0.5), np.array([[1, 0], [0, -1j]])) + assert np.allclose(cirq.unitary(cirq.Z**0.5), np.array([[1, 0], [0, 1j]])) + assert np.allclose(cirq.unitary(cirq.Z**0), np.array([[1, 0], [0, 1]])) + assert np.allclose(cirq.unitary(cirq.Z**-0.5), np.array([[1, 0], [0, -1j]])) def test_y_unitary(): assert np.allclose(cirq.unitary(cirq.Y), np.array([[0, -1j], [1j, 0]])) assert np.allclose( - cirq.unitary(cirq.Y ** 0.5), np.array([[1 + 1j, -1 - 1j], [1 + 1j, 1 + 1j]]) / 2 + cirq.unitary(cirq.Y**0.5), np.array([[1 + 1j, -1 - 1j], [1 + 1j, 1 + 1j]]) / 2 ) - assert np.allclose(cirq.unitary(cirq.Y ** 0), np.array([[1, 0], [0, 1]])) + assert np.allclose(cirq.unitary(cirq.Y**0), np.array([[1, 0], [0, 1]])) assert np.allclose( - cirq.unitary(cirq.Y ** -0.5), np.array([[1 - 1j, 1 - 1j], [-1 + 1j, 1 - 1j]]) / 2 + cirq.unitary(cirq.Y**-0.5), np.array([[1 - 1j, 1 - 1j], [-1 + 1j, 1 - 1j]]) / 2 ) @@ -273,18 +273,18 @@ def test_x_unitary(): assert np.allclose(cirq.unitary(cirq.X), np.array([[0, 1], [1, 0]])) assert np.allclose( - cirq.unitary(cirq.X ** 0.5), np.array([[1 + 1j, 1 - 1j], [1 - 1j, 1 + 1j]]) / 2 + cirq.unitary(cirq.X**0.5), np.array([[1 + 1j, 1 - 1j], [1 - 1j, 1 + 1j]]) / 2 ) - assert np.allclose(cirq.unitary(cirq.X ** 0), np.array([[1, 0], [0, 1]])) + assert np.allclose(cirq.unitary(cirq.X**0), np.array([[1, 0], [0, 1]])) assert np.allclose( - cirq.unitary(cirq.X ** -0.5), np.array([[1 - 1j, 1 + 1j], [1 + 1j, 1 - 1j]]) / 2 + cirq.unitary(cirq.X**-0.5), np.array([[1 - 1j, 1 + 1j], [1 + 1j, 1 - 1j]]) / 2 ) def test_h_unitary(): - sqrt = cirq.unitary(cirq.H ** 0.5) + sqrt = cirq.unitary(cirq.H**0.5) m = np.dot(sqrt, sqrt) assert np.allclose(m, cirq.unitary(cirq.H), atol=1e-8) @@ -296,7 +296,7 @@ def test_h_init(): def test_h_str(): assert str(cirq.H) == 'H' - assert str(cirq.H ** 0.5) == 'H**0.5' + assert str(cirq.H**0.5) == 'H**0.5' def test_x_act_on_tableau(): @@ -311,8 +311,8 @@ def test_x_act_on_tableau(): prng=np.random.RandomState(), ) - cirq.act_on(cirq.X ** 0.5, args, [cirq.LineQubit(1)], allow_decompose=False) - cirq.act_on(cirq.X ** 0.5, args, [cirq.LineQubit(1)], allow_decompose=False) + cirq.act_on(cirq.X**0.5, args, [cirq.LineQubit(1)], allow_decompose=False) + cirq.act_on(cirq.X**0.5, args, [cirq.LineQubit(1)], allow_decompose=False) assert args.log_of_measurement_results == {} assert args.tableau == flipped_tableau @@ -320,18 +320,18 @@ def test_x_act_on_tableau(): assert args.log_of_measurement_results == {} assert args.tableau == original_tableau - cirq.act_on(cirq.X ** 3.5, args, [cirq.LineQubit(1)], allow_decompose=False) - cirq.act_on(cirq.X ** 3.5, args, [cirq.LineQubit(1)], allow_decompose=False) + cirq.act_on(cirq.X**3.5, args, [cirq.LineQubit(1)], allow_decompose=False) + cirq.act_on(cirq.X**3.5, args, [cirq.LineQubit(1)], allow_decompose=False) assert args.log_of_measurement_results == {} assert args.tableau == flipped_tableau - cirq.act_on(cirq.X ** 2, args, [cirq.LineQubit(1)], allow_decompose=False) + cirq.act_on(cirq.X**2, args, [cirq.LineQubit(1)], allow_decompose=False) assert args.log_of_measurement_results == {} assert args.tableau == flipped_tableau foo = sympy.Symbol('foo') with pytest.raises(TypeError, match="Failed to act action on state"): - cirq.act_on(cirq.X ** foo, args, [cirq.LineQubit(1)]) + cirq.act_on(cirq.X**foo, args, [cirq.LineQubit(1)]) class iZGate(cirq.SingleQubitGate): @@ -360,8 +360,8 @@ def test_y_act_on_tableau(): prng=np.random.RandomState(), ) - cirq.act_on(cirq.Y ** 0.5, args, [cirq.LineQubit(1)], allow_decompose=False) - cirq.act_on(cirq.Y ** 0.5, args, [cirq.LineQubit(1)], allow_decompose=False) + cirq.act_on(cirq.Y**0.5, args, [cirq.LineQubit(1)], allow_decompose=False) + cirq.act_on(cirq.Y**0.5, args, [cirq.LineQubit(1)], allow_decompose=False) cirq.act_on(iZGate(), args, [cirq.LineQubit(1)]) assert args.log_of_measurement_results == {} assert args.tableau == flipped_tableau @@ -371,19 +371,19 @@ def test_y_act_on_tableau(): assert args.log_of_measurement_results == {} assert args.tableau == original_tableau - cirq.act_on(cirq.Y ** 3.5, args, [cirq.LineQubit(1)], allow_decompose=False) - cirq.act_on(cirq.Y ** 3.5, args, [cirq.LineQubit(1)], allow_decompose=False) + cirq.act_on(cirq.Y**3.5, args, [cirq.LineQubit(1)], allow_decompose=False) + cirq.act_on(cirq.Y**3.5, args, [cirq.LineQubit(1)], allow_decompose=False) cirq.act_on(iZGate(), args, [cirq.LineQubit(1)]) assert args.log_of_measurement_results == {} assert args.tableau == flipped_tableau - cirq.act_on(cirq.Y ** 2, args, [cirq.LineQubit(1)], allow_decompose=False) + cirq.act_on(cirq.Y**2, args, [cirq.LineQubit(1)], allow_decompose=False) assert args.log_of_measurement_results == {} assert args.tableau == flipped_tableau foo = sympy.Symbol('foo') with pytest.raises(TypeError, match="Failed to act action on state"): - cirq.act_on(cirq.Y ** foo, args, [cirq.LineQubit(1)]) + cirq.act_on(cirq.Y**foo, args, [cirq.LineQubit(1)]) def test_z_h_act_on_tableau(): @@ -401,8 +401,8 @@ def test_z_h_act_on_tableau(): ) cirq.act_on(cirq.H, args, [cirq.LineQubit(1)], allow_decompose=False) - cirq.act_on(cirq.Z ** 0.5, args, [cirq.LineQubit(1)], allow_decompose=False) - cirq.act_on(cirq.Z ** 0.5, args, [cirq.LineQubit(1)], allow_decompose=False) + cirq.act_on(cirq.Z**0.5, args, [cirq.LineQubit(1)], allow_decompose=False) + cirq.act_on(cirq.Z**0.5, args, [cirq.LineQubit(1)], allow_decompose=False) cirq.act_on(cirq.H, args, [cirq.LineQubit(1)], allow_decompose=False) assert args.log_of_measurement_results == {} assert args.tableau == flipped_tableau @@ -414,29 +414,29 @@ def test_z_h_act_on_tableau(): assert args.tableau == original_tableau cirq.act_on(cirq.H, args, [cirq.LineQubit(1)], allow_decompose=False) - cirq.act_on(cirq.Z ** 3.5, args, [cirq.LineQubit(1)], allow_decompose=False) - cirq.act_on(cirq.Z ** 3.5, args, [cirq.LineQubit(1)], allow_decompose=False) + cirq.act_on(cirq.Z**3.5, args, [cirq.LineQubit(1)], allow_decompose=False) + cirq.act_on(cirq.Z**3.5, args, [cirq.LineQubit(1)], allow_decompose=False) cirq.act_on(cirq.H, args, [cirq.LineQubit(1)], allow_decompose=False) assert args.log_of_measurement_results == {} assert args.tableau == flipped_tableau - cirq.act_on(cirq.Z ** 2, args, [cirq.LineQubit(1)], allow_decompose=False) + cirq.act_on(cirq.Z**2, args, [cirq.LineQubit(1)], allow_decompose=False) assert args.log_of_measurement_results == {} assert args.tableau == flipped_tableau - cirq.act_on(cirq.H ** 2, args, [cirq.LineQubit(1)], allow_decompose=False) + cirq.act_on(cirq.H**2, args, [cirq.LineQubit(1)], allow_decompose=False) assert args.log_of_measurement_results == {} assert args.tableau == flipped_tableau foo = sympy.Symbol('foo') with pytest.raises(TypeError, match="Failed to act action on state"): - cirq.act_on(cirq.Z ** foo, args, [cirq.LineQubit(1)]) + cirq.act_on(cirq.Z**foo, args, [cirq.LineQubit(1)]) with pytest.raises(TypeError, match="Failed to act action on state"): - cirq.act_on(cirq.H ** foo, args, [cirq.LineQubit(1)]) + cirq.act_on(cirq.H**foo, args, [cirq.LineQubit(1)]) with pytest.raises(TypeError, match="Failed to act action on state"): - cirq.act_on(cirq.H ** 1.5, args, [cirq.LineQubit(1)]) + cirq.act_on(cirq.H**1.5, args, [cirq.LineQubit(1)]) def test_cx_act_on_tableau(): @@ -471,16 +471,16 @@ def test_cx_act_on_tableau(): assert args.log_of_measurement_results == {} assert args.tableau == original_tableau - cirq.act_on(cirq.CX ** 4, args, cirq.LineQubit.range(2), allow_decompose=False) + cirq.act_on(cirq.CX**4, args, cirq.LineQubit.range(2), allow_decompose=False) assert args.log_of_measurement_results == {} assert args.tableau == original_tableau foo = sympy.Symbol('foo') with pytest.raises(TypeError, match="Failed to act action on state"): - cirq.act_on(cirq.CX ** foo, args, cirq.LineQubit.range(2)) + cirq.act_on(cirq.CX**foo, args, cirq.LineQubit.range(2)) with pytest.raises(TypeError, match="Failed to act action on state"): - cirq.act_on(cirq.CX ** 1.5, args, cirq.LineQubit.range(2)) + cirq.act_on(cirq.CX**1.5, args, cirq.LineQubit.range(2)) def test_cz_act_on_tableau(): @@ -515,16 +515,16 @@ def test_cz_act_on_tableau(): assert args.log_of_measurement_results == {} assert args.tableau == original_tableau - cirq.act_on(cirq.CZ ** 4, args, cirq.LineQubit.range(2), allow_decompose=False) + cirq.act_on(cirq.CZ**4, args, cirq.LineQubit.range(2), allow_decompose=False) assert args.log_of_measurement_results == {} assert args.tableau == original_tableau foo = sympy.Symbol('foo') with pytest.raises(TypeError, match="Failed to act action on state"): - cirq.act_on(cirq.CZ ** foo, args, cirq.LineQubit.range(2)) + cirq.act_on(cirq.CZ**foo, args, cirq.LineQubit.range(2)) with pytest.raises(TypeError, match="Failed to act action on state"): - cirq.act_on(cirq.CZ ** 1.5, args, cirq.LineQubit.range(2)) + cirq.act_on(cirq.CZ**1.5, args, cirq.LineQubit.range(2)) def test_cz_act_on_equivalent_to_h_cx_h_tableau(): @@ -557,33 +557,33 @@ def test_cz_act_on_equivalent_to_h_cx_h_tableau(): @pytest.mark.parametrize( 'input_gate_sequence, outcome', [ - ([cirq.X ** foo], 'Error'), - ([cirq.X ** 0.25], 'Error'), - ([cirq.X ** 4], 'Original'), - ([cirq.X ** 0.5, cirq.X ** 0.5], 'Flipped'), + ([cirq.X**foo], 'Error'), + ([cirq.X**0.25], 'Error'), + ([cirq.X**4], 'Original'), + ([cirq.X**0.5, cirq.X**0.5], 'Flipped'), ([cirq.X], 'Flipped'), - ([cirq.X ** 3.5, cirq.X ** 3.5], 'Flipped'), - ([cirq.Y ** foo], 'Error'), - ([cirq.Y ** 0.25], 'Error'), - ([cirq.Y ** 4], 'Original'), - ([cirq.Y ** 0.5, cirq.Y ** 0.5, iZGate()], 'Flipped'), + ([cirq.X**3.5, cirq.X**3.5], 'Flipped'), + ([cirq.Y**foo], 'Error'), + ([cirq.Y**0.25], 'Error'), + ([cirq.Y**4], 'Original'), + ([cirq.Y**0.5, cirq.Y**0.5, iZGate()], 'Flipped'), ([cirq.Y, iZGate()], 'Flipped'), - ([cirq.Y ** 3.5, cirq.Y ** 3.5, iZGate()], 'Flipped'), - ([cirq.Z ** foo], 'Error'), - ([cirq.H ** foo], 'Error'), - ([cirq.H ** 1.5], 'Error'), - ([cirq.Z ** 4], 'Original'), - ([cirq.H ** 4], 'Original'), + ([cirq.Y**3.5, cirq.Y**3.5, iZGate()], 'Flipped'), + ([cirq.Z**foo], 'Error'), + ([cirq.H**foo], 'Error'), + ([cirq.H**1.5], 'Error'), + ([cirq.Z**4], 'Original'), + ([cirq.H**4], 'Original'), ([cirq.H, cirq.S, cirq.S, cirq.H], 'Flipped'), ([cirq.H, cirq.Z, cirq.H], 'Flipped'), - ([cirq.H, cirq.Z ** 3.5, cirq.Z ** 3.5, cirq.H], 'Flipped'), - ([cirq.CX ** foo], 'Error'), - ([cirq.CX ** 1.5], 'Error'), - ([cirq.CX ** 4], 'Original'), + ([cirq.H, cirq.Z**3.5, cirq.Z**3.5, cirq.H], 'Flipped'), + ([cirq.CX**foo], 'Error'), + ([cirq.CX**1.5], 'Error'), + ([cirq.CX**4], 'Original'), ([cirq.CX], 'Flipped'), - ([cirq.CZ ** foo], 'Error'), - ([cirq.CZ ** 1.5], 'Error'), - ([cirq.CZ ** 4], 'Original'), + ([cirq.CZ**foo], 'Error'), + ([cirq.CZ**1.5], 'Error'), + ([cirq.CZ**4], 'Original'), ([cirq.CZ, MinusOnePhaseGate()], 'Original'), ], ) @@ -625,28 +625,28 @@ def test_act_on_ch_form(input_gate_sequence, outcome): (cirq.X, True), (cirq.Y, True), (cirq.Z, True), - (cirq.X ** 0.5, True), - (cirq.Y ** 0.5, True), - (cirq.Z ** 0.5, True), - (cirq.X ** 3.5, True), - (cirq.Y ** 3.5, True), - (cirq.Z ** 3.5, True), - (cirq.X ** 4, True), - (cirq.Y ** 4, True), - (cirq.Z ** 4, True), + (cirq.X**0.5, True), + (cirq.Y**0.5, True), + (cirq.Z**0.5, True), + (cirq.X**3.5, True), + (cirq.Y**3.5, True), + (cirq.Z**3.5, True), + (cirq.X**4, True), + (cirq.Y**4, True), + (cirq.Z**4, True), (cirq.H, True), (cirq.CX, True), (cirq.CZ, True), - (cirq.H ** 4, True), - (cirq.CX ** 4, True), - (cirq.CZ ** 4, True), + (cirq.H**4, True), + (cirq.CX**4, True), + (cirq.CZ**4, True), # Unsupported gates should not fail too. - (cirq.X ** 0.25, False), - (cirq.Y ** 0.25, False), - (cirq.Z ** 0.25, False), - (cirq.H ** 0.5, False), - (cirq.CX ** 0.5, False), - (cirq.CZ ** 0.5, False), + (cirq.X**0.25, False), + (cirq.Y**0.25, False), + (cirq.Z**0.25, False), + (cirq.H**0.5, False), + (cirq.CX**0.5, False), + (cirq.CZ**0.5, False), ], ) def test_act_on_consistency(input_gate, assert_implemented): @@ -742,7 +742,7 @@ def test_text_diagrams(): def test_cnot_unitary(): np.testing.assert_almost_equal( - cirq.unitary(cirq.CNOT ** 0.5), + cirq.unitary(cirq.CNOT**0.5), np.array( [ [1, 0, 0, 0], @@ -803,23 +803,23 @@ def test_cnot_decompose(): def test_repr(): assert repr(cirq.X) == 'cirq.X' - assert repr(cirq.X ** 0.5) == '(cirq.X**0.5)' + assert repr(cirq.X**0.5) == '(cirq.X**0.5)' assert repr(cirq.Z) == 'cirq.Z' - assert repr(cirq.Z ** 0.5) == 'cirq.S' - assert repr(cirq.Z ** 0.25) == 'cirq.T' - assert repr(cirq.Z ** 0.125) == '(cirq.Z**0.125)' + assert repr(cirq.Z**0.5) == 'cirq.S' + assert repr(cirq.Z**0.25) == 'cirq.T' + assert repr(cirq.Z**0.125) == '(cirq.Z**0.125)' assert repr(cirq.S) == 'cirq.S' - assert repr(cirq.S ** -1) == '(cirq.S**-1)' + assert repr(cirq.S**-1) == '(cirq.S**-1)' assert repr(cirq.T) == 'cirq.T' - assert repr(cirq.T ** -1) == '(cirq.T**-1)' + assert repr(cirq.T**-1) == '(cirq.T**-1)' assert repr(cirq.Y) == 'cirq.Y' - assert repr(cirq.Y ** 0.5) == '(cirq.Y**0.5)' + assert repr(cirq.Y**0.5) == '(cirq.Y**0.5)' assert repr(cirq.CNOT) == 'cirq.CNOT' - assert repr(cirq.CNOT ** 0.5) == '(cirq.CNOT**0.5)' + assert repr(cirq.CNOT**0.5) == '(cirq.CNOT**0.5)' cirq.testing.assert_equivalent_repr( cirq.X ** (sympy.Symbol('a') / 2 - sympy.Symbol('c') * 3 + 5) @@ -832,30 +832,30 @@ def test_repr(): # should be using the "shortest decimal value closer to X than any other # floating point value" strategy, as opposed to the "exactly value in # decimal" strategy. - assert repr(cirq.CZ ** 0.2) == '(cirq.CZ**0.2)' + assert repr(cirq.CZ**0.2) == '(cirq.CZ**0.2)' def test_str(): assert str(cirq.X) == 'X' - assert str(cirq.X ** 0.5) == 'X**0.5' + assert str(cirq.X**0.5) == 'X**0.5' assert str(cirq.rx(np.pi)) == 'Rx(π)' assert str(cirq.rx(0.5 * np.pi)) == 'Rx(0.5π)' assert str(cirq.XPowGate(global_shift=-0.25)) == 'XPowGate(exponent=1.0, global_shift=-0.25)' assert str(cirq.Z) == 'Z' - assert str(cirq.Z ** 0.5) == 'S' - assert str(cirq.Z ** 0.125) == 'Z**0.125' + assert str(cirq.Z**0.5) == 'S' + assert str(cirq.Z**0.125) == 'Z**0.125' assert str(cirq.rz(np.pi)) == 'Rz(π)' assert str(cirq.rz(1.4 * np.pi)) == 'Rz(1.4π)' assert str(cirq.ZPowGate(global_shift=0.25)) == 'ZPowGate(exponent=1.0, global_shift=0.25)' assert str(cirq.S) == 'S' - assert str(cirq.S ** -1) == 'S**-1' + assert str(cirq.S**-1) == 'S**-1' assert str(cirq.T) == 'T' - assert str(cirq.T ** -1) == 'T**-1' + assert str(cirq.T**-1) == 'T**-1' assert str(cirq.Y) == 'Y' - assert str(cirq.Y ** 0.5) == 'Y**0.5' + assert str(cirq.Y**0.5) == 'Y**0.5' assert str(cirq.ry(np.pi)) == 'Ry(π)' assert str(cirq.ry(3.14 * np.pi)) == 'Ry(3.14π)' assert ( @@ -864,9 +864,9 @@ def test_str(): ) assert str(cirq.CX) == 'CNOT' - assert str(cirq.CNOT ** 0.5) == 'CNOT**0.5' + assert str(cirq.CNOT**0.5) == 'CNOT**0.5' assert str(cirq.CZ) == 'CZ' - assert str(cirq.CZ ** 0.5) == 'CZ**0.5' + assert str(cirq.CZ**0.5) == 'CZ**0.5' assert str(cirq.cphase(np.pi)) == 'CZ' assert str(cirq.cphase(np.pi / 2)) == 'CZ**0.5' @@ -938,49 +938,49 @@ def test_cphase_unitary(angle_rads, expected_unitary): def test_parameterized_cphase(): assert cirq.cphase(sympy.pi) == cirq.CZ - assert cirq.cphase(sympy.pi / 2) == cirq.CZ ** 0.5 + assert cirq.cphase(sympy.pi / 2) == cirq.CZ**0.5 @pytest.mark.parametrize('gate', [cirq.X, cirq.Y, cirq.Z]) def test_x_y_z_stabilizer(gate): assert cirq.has_stabilizer_effect(gate) - assert cirq.has_stabilizer_effect(gate ** 0.5) - assert cirq.has_stabilizer_effect(gate ** 0) - assert cirq.has_stabilizer_effect(gate ** -0.5) - assert cirq.has_stabilizer_effect(gate ** 4) - assert not cirq.has_stabilizer_effect(gate ** 1.2) + assert cirq.has_stabilizer_effect(gate**0.5) + assert cirq.has_stabilizer_effect(gate**0) + assert cirq.has_stabilizer_effect(gate**-0.5) + assert cirq.has_stabilizer_effect(gate**4) + assert not cirq.has_stabilizer_effect(gate**1.2) foo = sympy.Symbol('foo') - assert not cirq.has_stabilizer_effect(gate ** foo) + assert not cirq.has_stabilizer_effect(gate**foo) def test_h_stabilizer(): gate = cirq.H assert cirq.has_stabilizer_effect(gate) - assert not cirq.has_stabilizer_effect(gate ** 0.5) - assert cirq.has_stabilizer_effect(gate ** 0) - assert not cirq.has_stabilizer_effect(gate ** -0.5) - assert cirq.has_stabilizer_effect(gate ** 4) - assert not cirq.has_stabilizer_effect(gate ** 1.2) + assert not cirq.has_stabilizer_effect(gate**0.5) + assert cirq.has_stabilizer_effect(gate**0) + assert not cirq.has_stabilizer_effect(gate**-0.5) + assert cirq.has_stabilizer_effect(gate**4) + assert not cirq.has_stabilizer_effect(gate**1.2) foo = sympy.Symbol('foo') - assert not cirq.has_stabilizer_effect(gate ** foo) + assert not cirq.has_stabilizer_effect(gate**foo) @pytest.mark.parametrize('gate', [cirq.CX, cirq.CZ]) def test_cx_cz_stabilizer(gate): assert cirq.has_stabilizer_effect(gate) - assert not cirq.has_stabilizer_effect(gate ** 0.5) - assert cirq.has_stabilizer_effect(gate ** 0) - assert not cirq.has_stabilizer_effect(gate ** -0.5) - assert cirq.has_stabilizer_effect(gate ** 4) - assert not cirq.has_stabilizer_effect(gate ** 1.2) + assert not cirq.has_stabilizer_effect(gate**0.5) + assert cirq.has_stabilizer_effect(gate**0) + assert not cirq.has_stabilizer_effect(gate**-0.5) + assert cirq.has_stabilizer_effect(gate**4) + assert not cirq.has_stabilizer_effect(gate**1.2) foo = sympy.Symbol('foo') - assert not cirq.has_stabilizer_effect(gate ** foo) + assert not cirq.has_stabilizer_effect(gate**foo) def test_phase_by_xy(): assert cirq.phase_by(cirq.X, 0.25, 0) == cirq.Y - assert cirq.phase_by(cirq.X ** 0.5, 0.25, 0) == cirq.Y ** 0.5 - assert cirq.phase_by(cirq.X ** -0.5, 0.25, 0) == cirq.Y ** -0.5 + assert cirq.phase_by(cirq.X**0.5, 0.25, 0) == cirq.Y**0.5 + assert cirq.phase_by(cirq.X**-0.5, 0.25, 0) == cirq.Y**-0.5 def test_ixyz_circuit_diagram(): @@ -1108,12 +1108,12 @@ def test_rxyz_circuit_diagram(): def test_trace_distance(): foo = sympy.Symbol('foo') - sx = cirq.X ** foo - sy = cirq.Y ** foo - sz = cirq.Z ** foo - sh = cirq.H ** foo - scx = cirq.CX ** foo - scz = cirq.CZ ** foo + sx = cirq.X**foo + sy = cirq.Y**foo + sz = cirq.Z**foo + sh = cirq.H**foo + scx = cirq.CX**foo + scz = cirq.CZ**foo # These values should have 1.0 or 0.0 directly returned assert cirq.trace_distance_bound(sx) == 1.0 assert cirq.trace_distance_bound(sy) == 1.0 @@ -1124,23 +1124,23 @@ def test_trace_distance(): assert cirq.trace_distance_bound(cirq.I) == 0.0 # These values are calculated, so we use approx_eq assert cirq.approx_eq(cirq.trace_distance_bound(cirq.X), 1.0) - assert cirq.approx_eq(cirq.trace_distance_bound(cirq.Y ** -1), 1.0) - assert cirq.approx_eq(cirq.trace_distance_bound(cirq.Z ** 0.5), np.sin(np.pi / 4)) - assert cirq.approx_eq(cirq.trace_distance_bound(cirq.H ** 0.25), np.sin(np.pi / 8)) - assert cirq.approx_eq(cirq.trace_distance_bound(cirq.CX ** 2), 0.0) + assert cirq.approx_eq(cirq.trace_distance_bound(cirq.Y**-1), 1.0) + assert cirq.approx_eq(cirq.trace_distance_bound(cirq.Z**0.5), np.sin(np.pi / 4)) + assert cirq.approx_eq(cirq.trace_distance_bound(cirq.H**0.25), np.sin(np.pi / 8)) + assert cirq.approx_eq(cirq.trace_distance_bound(cirq.CX**2), 0.0) assert cirq.approx_eq(cirq.trace_distance_bound(cirq.CZ ** (1 / 9)), np.sin(np.pi / 18)) def test_commutes(): assert cirq.commutes(cirq.ZPowGate(exponent=sympy.Symbol('t')), cirq.Z) assert cirq.commutes(cirq.Z, cirq.Z(cirq.LineQubit(0)), default=None) is None - assert cirq.commutes(cirq.Z ** 0.1, cirq.XPowGate(exponent=0)) + assert cirq.commutes(cirq.Z**0.1, cirq.XPowGate(exponent=0)) def test_approx_eq(): - assert cirq.approx_eq(cirq.Z ** 0.1, cirq.Z ** 0.2, atol=0.3) - assert not cirq.approx_eq(cirq.Z ** 0.1, cirq.Z ** 0.2, atol=0.05) - assert cirq.approx_eq(cirq.Y ** 0.1, cirq.Y ** 0.2, atol=0.3) - assert not cirq.approx_eq(cirq.Y ** 0.1, cirq.Y ** 0.2, atol=0.05) - assert cirq.approx_eq(cirq.X ** 0.1, cirq.X ** 0.2, atol=0.3) - assert not cirq.approx_eq(cirq.X ** 0.1, cirq.X ** 0.2, atol=0.05) + assert cirq.approx_eq(cirq.Z**0.1, cirq.Z**0.2, atol=0.3) + assert not cirq.approx_eq(cirq.Z**0.1, cirq.Z**0.2, atol=0.05) + assert cirq.approx_eq(cirq.Y**0.1, cirq.Y**0.2, atol=0.3) + assert not cirq.approx_eq(cirq.Y**0.1, cirq.Y**0.2, atol=0.05) + assert cirq.approx_eq(cirq.X**0.1, cirq.X**0.2, atol=0.3) + assert not cirq.approx_eq(cirq.X**0.1, cirq.X**0.2, atol=0.05) diff --git a/cirq/ops/controlled_gate_test.py b/cirq/ops/controlled_gate_test.py index 67495a5f47a..1b570938524 100644 --- a/cirq/ops/controlled_gate_test.py +++ b/cirq/ops/controlled_gate_test.py @@ -328,7 +328,7 @@ def test_unitary(): 'gate, should_decompose_to_target', [ (cirq.X, True), - (cirq.X ** 0.5, True), + (cirq.X**0.5, True), (cirq.rx(np.pi), True), (cirq.rx(np.pi / 2), True), (cirq.Z, True), @@ -366,45 +366,45 @@ def test_controlled_gate_is_consistent(gate: cirq.Gate, should_decompose_to_targ def test_pow_inverse(): assert cirq.inverse(CRestricted, None) is None assert cirq.pow(CRestricted, 1.5, None) is None - assert cirq.pow(CY, 1.5) == cirq.ControlledGate(cirq.Y ** 1.5) - assert cirq.inverse(CY) == CY ** -1 == CY + assert cirq.pow(CY, 1.5) == cirq.ControlledGate(cirq.Y**1.5) + assert cirq.inverse(CY) == CY**-1 == CY assert cirq.inverse(C0Restricted, None) is None assert cirq.pow(C0Restricted, 1.5, None) is None - assert cirq.pow(C0Y, 1.5) == cirq.ControlledGate(cirq.Y ** 1.5, control_values=[0]) - assert cirq.inverse(C0Y) == C0Y ** -1 == C0Y + assert cirq.pow(C0Y, 1.5) == cirq.ControlledGate(cirq.Y**1.5, control_values=[0]) + assert cirq.inverse(C0Y) == C0Y**-1 == C0Y assert cirq.inverse(C2Restricted, None) is None assert cirq.pow(C2Restricted, 1.5, None) is None assert cirq.pow(C2Y, 1.5) == cirq.ControlledGate( - cirq.Y ** 1.5, control_values=[2], control_qid_shape=(3,) + cirq.Y**1.5, control_values=[2], control_qid_shape=(3,) ) - assert cirq.inverse(C2Y) == C2Y ** -1 == C2Y + assert cirq.inverse(C2Y) == C2Y**-1 == C2Y def test_extrapolatable_effect(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') - assert cirq.ControlledGate(cirq.Z) ** 0.5 == cirq.ControlledGate(cirq.Z ** 0.5) + assert cirq.ControlledGate(cirq.Z) ** 0.5 == cirq.ControlledGate(cirq.Z**0.5) - assert cirq.ControlledGate(cirq.Z).on(a, b) ** 0.5 == cirq.ControlledGate(cirq.Z ** 0.5).on( + assert cirq.ControlledGate(cirq.Z).on(a, b) ** 0.5 == cirq.ControlledGate(cirq.Z**0.5).on( a, b ) - assert cirq.ControlledGate(cirq.Z) ** 0.5 == cirq.ControlledGate(cirq.Z ** 0.5) + assert cirq.ControlledGate(cirq.Z) ** 0.5 == cirq.ControlledGate(cirq.Z**0.5) def test_reversible(): - assert cirq.inverse(cirq.ControlledGate(cirq.S)) == cirq.ControlledGate(cirq.S ** -1) + assert cirq.inverse(cirq.ControlledGate(cirq.S)) == cirq.ControlledGate(cirq.S**-1) assert cirq.inverse(cirq.ControlledGate(cirq.S, num_controls=4)) == cirq.ControlledGate( - cirq.S ** -1, num_controls=4 + cirq.S**-1, num_controls=4 ) assert cirq.inverse(cirq.ControlledGate(cirq.S, control_values=[1])) == cirq.ControlledGate( - cirq.S ** -1, control_values=[1] + cirq.S**-1, control_values=[1] ) assert cirq.inverse(cirq.ControlledGate(cirq.S, control_qid_shape=(3,))) == cirq.ControlledGate( - cirq.S ** -1, control_qid_shape=(3,) + cirq.S**-1, control_qid_shape=(3,) ) @@ -435,7 +435,7 @@ def test_circuit_diagram_info(): wire_symbols=('(2)', 'Y'), exponent=1 ) - assert cirq.circuit_diagram_info(cirq.ControlledGate(cirq.Y ** 0.5)) == cirq.CircuitDiagramInfo( + assert cirq.circuit_diagram_info(cirq.ControlledGate(cirq.Y**0.5)) == cirq.CircuitDiagramInfo( wire_symbols=('@', 'Y'), exponent=0.5 ) @@ -525,11 +525,11 @@ def test_uninformed_circuit_diagram_info(): def test_bounded_effect(): - assert cirq.trace_distance_bound(CY ** 0.001) < 0.01 + assert cirq.trace_distance_bound(CY**0.001) < 0.01 assert cirq.approx_eq(cirq.trace_distance_bound(CCH), 1.0) assert cirq.approx_eq(cirq.trace_distance_bound(CRestricted), 1.0) foo = sympy.Symbol('foo') - assert cirq.trace_distance_bound(cirq.ControlledGate(cirq.X ** foo)) == 1 + assert cirq.trace_distance_bound(cirq.ControlledGate(cirq.X**foo)) == 1 def test_repr(): @@ -544,7 +544,7 @@ def test_str(): assert str(cirq.ControlledGate(cirq.X)) == 'CX' assert str(cirq.ControlledGate(cirq.Z)) == 'CZ' assert str(cirq.ControlledGate(cirq.S)) == 'CS' - assert str(cirq.ControlledGate(cirq.Z ** 0.125)) == 'CZ**0.125' + assert str(cirq.ControlledGate(cirq.Z**0.125)) == 'CZ**0.125' assert str(cirq.ControlledGate(cirq.ControlledGate(cirq.S))) == 'CCS' assert str(C0Y) == 'C0Y' assert str(C0C1H) == 'C0C1H' diff --git a/cirq/ops/controlled_operation_test.py b/cirq/ops/controlled_operation_test.py index 18198871cab..333b7077108 100644 --- a/cirq/ops/controlled_operation_test.py +++ b/cirq/ops/controlled_operation_test.py @@ -399,7 +399,7 @@ def test_parameterizable(resolve_fn): def test_bounded_effect(): qubits = cirq.LineQubit.range(3) cy = cirq.ControlledOperation(qubits[:1], cirq.Y(qubits[1])) - assert cirq.trace_distance_bound(cy ** 0.001) < 0.01 + assert cirq.trace_distance_bound(cy**0.001) < 0.01 foo = sympy.Symbol('foo') scy = cirq.ControlledOperation(qubits[:1], cirq.Y(qubits[1]) ** foo) assert cirq.trace_distance_bound(scy) == 1.0 diff --git a/cirq/ops/dense_pauli_string.py b/cirq/ops/dense_pauli_string.py index 1aa67bc4e36..143b9e13f61 100644 --- a/cirq/ops/dense_pauli_string.py +++ b/cirq/ops/dense_pauli_string.py @@ -211,7 +211,7 @@ def __pow__(self, power): if self.coefficient in i_group: coef = i_group[i_group.index(self.coefficient) * power % 4] else: - coef = self.coefficient ** power + coef = self.coefficient**power if power % 2 == 0: return coef * DensePauliString.eye(len(self)) return DensePauliString(coefficient=coef, pauli_mask=self.pauli_mask) @@ -585,4 +585,4 @@ def _vectorized_pauli_mul_phase( # Result is i raised to the sum of the per-term phase exponents. s = int(np.sum(t, dtype=np.uint8).item() & 3) - return 1j ** s + return 1j**s diff --git a/cirq/ops/dense_pauli_string_test.py b/cirq/ops/dense_pauli_string_test.py index 44951cab48d..848b4a4d130 100644 --- a/cirq/ops/dense_pauli_string_test.py +++ b/cirq/ops/dense_pauli_string_test.py @@ -278,33 +278,33 @@ def test_pow(): f = cirq.DensePauliString m = cirq.DensePauliString p = 1j * f('IXYZ') - assert p ** 0 == p ** 4 == p ** 8 == cirq.DensePauliString.eye(4) - assert p ** 1 == p ** 5 == p ** -3 == p == p ** 101 - assert p ** 2 == p ** -2 == p ** 6 == -f('IIII') - assert p ** 3 == p ** -1 == p ** 7 == -1j * f('IXYZ') + assert p**0 == p**4 == p**8 == cirq.DensePauliString.eye(4) + assert p**1 == p**5 == p**-3 == p == p**101 + assert p**2 == p**-2 == p**6 == -f('IIII') + assert p**3 == p**-1 == p**7 == -1j * f('IXYZ') p = -f('IXYZ') - assert p == p ** 1 == p ** -1 == p ** -3 == p ** -303 - assert p ** 0 == p ** 2 == p ** -2 == p ** -4 == p ** 102 + assert p == p**1 == p**-1 == p**-3 == p**-303 + assert p**0 == p**2 == p**-2 == p**-4 == p**102 p = 2 * f('XX') - assert p ** -1 == (0.5 + 0j) * f('XX') - assert p ** 0 == f('II') - assert p ** 1 == 2 * f('XX') - assert p ** 2 == 4 * f('II') - assert p ** 3 == 8 * f('XX') - assert p ** 4 == 16 * f('II') + assert p**-1 == (0.5 + 0j) * f('XX') + assert p**0 == f('II') + assert p**1 == 2 * f('XX') + assert p**2 == 4 * f('II') + assert p**3 == 8 * f('XX') + assert p**4 == 16 * f('II') p = -1j * f('XY') - assert p ** 101 == p == p ** -103 + assert p**101 == p == p**-103 p = 2j * f('XY') - assert (p ** -1) ** -1 == p - assert p ** -2 == f('II') / -4 + assert (p**-1) ** -1 == p + assert p**-2 == f('II') / -4 p = f('XY') - assert p ** -100 == p ** 0 == p ** 100 == f('II') - assert p ** -101 == p ** 1 == p ** 101 == f('XY') + assert p**-100 == p**0 == p**100 == f('II') + assert p**-101 == p**1 == p**101 == f('XY') # Becomes an immutable copy. assert m('X') ** 3 == f('X') diff --git a/cirq/ops/diagonal_gate.py b/cirq/ops/diagonal_gate.py index 670a683f675..f05c77af9e5 100644 --- a/cirq/ops/diagonal_gate.py +++ b/cirq/ops/diagonal_gate.py @@ -54,7 +54,7 @@ def _gen_gray_code(n: int) -> Iterator[Tuple[int, int]]: gray code. """ gray_code = 0 - for i in range(1, 2 ** n): + for i in range(1, 2**n): next_gray = i ^ (i >> 1) bit_flip = int(np.log2(gray_code ^ next_gray)) yield gray_code, bit_flip @@ -177,7 +177,7 @@ def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE': https://iopscience.iop.org/article/10.1088/1367-2630/16/3/033040/meta """ n = self._num_qubits_() - hat_angles = _fast_walsh_hadamard_transform(self._diag_angles_radians) / (2 ** n) + hat_angles = _fast_walsh_hadamard_transform(self._diag_angles_radians) / (2**n) # There is one global phase shift between unitary matrix of the diagonal gate and the # decomposed gates. On its own it is not physically observable. However, if using this diff --git a/cirq/ops/diagonal_gate_test.py b/cirq/ops/diagonal_gate_test.py index c4529766628..21690904b71 100644 --- a/cirq/ops/diagonal_gate_test.py +++ b/cirq/ops/diagonal_gate_test.py @@ -41,7 +41,7 @@ def test_consistent_protocols(gate): @pytest.mark.parametrize('n', [1, 2, 3, 4, 5, 6, 7, 8, 9]) def test_decomposition_unitary(n): - diagonal_angles = np.random.randn(2 ** n) + diagonal_angles = np.random.randn(2**n) diagonal_gate = cirq.DiagonalGate(diagonal_angles) decomposed_circ = cirq.Circuit(cirq.decompose(diagonal_gate(*cirq.LineQubit.range(n)))) @@ -53,10 +53,10 @@ def test_decomposition_unitary(n): @pytest.mark.parametrize('n', [1, 2, 3, 4]) def test_diagonal_exponent(n): - diagonal_angles = _candidate_angles[: 2 ** n] + diagonal_angles = _candidate_angles[: 2**n] diagonal_gate = cirq.DiagonalGate(diagonal_angles) - sqrt_diagonal_gate = diagonal_gate ** 0.5 + sqrt_diagonal_gate = diagonal_gate**0.5 expected_angles = [prime / 2 for prime in diagonal_angles] np.testing.assert_allclose(expected_angles, sqrt_diagonal_gate._diag_angles_radians, atol=1e-8) @@ -66,9 +66,9 @@ def test_diagonal_exponent(n): @pytest.mark.parametrize('n', [1, 2, 3, 4]) def test_decomposition_diagonal_exponent(n): - diagonal_angles = np.random.randn(2 ** n) + diagonal_angles = np.random.randn(2**n) diagonal_gate = cirq.DiagonalGate(diagonal_angles) - sqrt_diagonal_gate = diagonal_gate ** 0.5 + sqrt_diagonal_gate = diagonal_gate**0.5 decomposed_circ = cirq.Circuit(cirq.decompose(sqrt_diagonal_gate(*cirq.LineQubit.range(n)))) expected_f = [np.exp(1j * angle / 2) for angle in diagonal_angles] @@ -79,16 +79,16 @@ def test_decomposition_diagonal_exponent(n): @pytest.mark.parametrize('n', [1, 2, 3, 4]) def test_decomposition_with_parameterization(n): - angles = sympy.symbols([f'x_{i}' for i in range(2 ** n)]) + angles = sympy.symbols([f'x_{i}' for i in range(2**n)]) exponent = sympy.Symbol('e') diagonal_gate = cirq.DiagonalGate(angles) ** exponent parameterized_op = diagonal_gate(*cirq.LineQubit.range(n)) decomposed_circuit = cirq.Circuit(cirq.decompose(parameterized_op)) for exponent_value in [-0.5, 0.5, 1]: - for i in range(len(_candidate_angles) - 2 ** n + 1): + for i in range(len(_candidate_angles) - 2**n + 1): resolver = {exponent: exponent_value} resolver.update( - {angles[j]: x_j for j, x_j in enumerate(_candidate_angles[i : i + 2 ** n])} + {angles[j]: x_j for j, x_j in enumerate(_candidate_angles[i : i + 2**n])} ) resolved_op = cirq.resolve_parameters(parameterized_op, resolver) resolved_circuit = cirq.resolve_parameters(decomposed_circuit, resolver) @@ -139,7 +139,7 @@ def test_diagram(): @pytest.mark.parametrize('n', [1, 2, 3, 4]) def test_unitary(n): - diagonal_angles = _candidate_angles[: 2 ** n] + diagonal_angles = _candidate_angles[: 2**n] assert cirq.has_unitary(cirq.DiagonalGate(diagonal_angles)) np.testing.assert_allclose( cirq.unitary(cirq.DiagonalGate(diagonal_angles)).diagonal(), diff --git a/cirq/ops/eigen_gate_test.py b/cirq/ops/eigen_gate_test.py index 49d27d19ce1..8e2d64f8614 100644 --- a/cirq/ops/eigen_gate_test.py +++ b/cirq/ops/eigen_gate_test.py @@ -356,19 +356,19 @@ def _with_exponent(self, exponent): @pytest.mark.parametrize( 'gate1,gate2,eq_up_to_global_phase', [ - (cirq.rz(0.3 * np.pi), cirq.Z ** 0.3, True), + (cirq.rz(0.3 * np.pi), cirq.Z**0.3, True), (cirq.Z, cirq.Gate, False), - (cirq.rz(0.3), cirq.Z ** 0.3, False), + (cirq.rz(0.3), cirq.Z**0.3, False), (cirq.ZZPowGate(global_shift=0.5), cirq.ZZ, True), (cirq.ZPowGate(global_shift=0.5) ** sympy.Symbol('e'), cirq.Z, False), (cirq.Z ** sympy.Symbol('e'), cirq.Z ** sympy.Symbol('f'), False), - (cirq.ZZ ** 1.9, cirq.ZZ ** -0.1, True), + (cirq.ZZ**1.9, cirq.ZZ**-0.1, True), (WeightedZPowGate(0), WeightedZPowGate(0.1), False), (WeightedZPowGate(0.3), WeightedZPowGate(0.3, global_shift=0.1), True), (cirq.X, cirq.Z, False), (cirq.X, cirq.Y, False), (cirq.rz(np.pi), cirq.Z, True), - (cirq.X ** 0.3, cirq.Z ** 0.3, False), + (cirq.X**0.3, cirq.Z**0.3, False), ], ) def test_equal_up_to_global_phase(gate1, gate2, eq_up_to_global_phase): diff --git a/cirq/ops/fourier_transform.py b/cirq/ops/fourier_transform.py index 35560e698e2..4a19c34a911 100644 --- a/cirq/ops/fourier_transform.py +++ b/cirq/ops/fourier_transform.py @@ -122,7 +122,7 @@ def num_qubits(self) -> int: def _decompose_(self, qubits): for i, q in enumerate(qubits): - yield cirq.Z(q) ** (self.exponent / 2 ** i) + yield cirq.Z(q) ** (self.exponent / 2**i) def _apply_unitary_(self, args: 'cirq.ApplyUnitaryArgs'): if isinstance(self.exponent, sympy.Basic): diff --git a/cirq/ops/fourier_transform_test.py b/cirq/ops/fourier_transform_test.py index 57e4d5bf9eb..6b1a474940b 100644 --- a/cirq/ops/fourier_transform_test.py +++ b/cirq/ops/fourier_transform_test.py @@ -59,7 +59,7 @@ def test_quantum_fourier_transform_gate_repr(): def test_pow(): a = cirq.PhaseGradientGate(num_qubits=2, exponent=0.5) - assert a ** 0.5 == cirq.PhaseGradientGate(num_qubits=2, exponent=0.25) + assert a**0.5 == cirq.PhaseGradientGate(num_qubits=2, exponent=0.25) assert a ** sympy.Symbol('t') == cirq.PhaseGradientGate( num_qubits=2, exponent=0.5 * sympy.Symbol('t') ) diff --git a/cirq/ops/gate_operation_test.py b/cirq/ops/gate_operation_test.py index 67554537bb5..aeaceadbc29 100644 --- a/cirq/ops/gate_operation_test.py +++ b/cirq/ops/gate_operation_test.py @@ -138,7 +138,7 @@ def _num_qubits_(self): def test_gate_operation_pow(): Y = cirq.Y q = cirq.NamedQubit('q') - assert (Y ** 0.5)(q) == Y(q) ** 0.5 + assert (Y**0.5)(q) == Y(q) ** 0.5 def test_with_qubits_and_transform_qubits(): @@ -159,11 +159,11 @@ def test_extrapolate(): # If the gate isn't extrapolatable, you get a type error. op0 = cirq.GateOperation(cirq.SingleQubitGate(), [q]) with pytest.raises(TypeError): - _ = op0 ** 0.5 + _ = op0**0.5 op1 = cirq.GateOperation(cirq.Y, [q]) - assert op1 ** 0.5 == cirq.GateOperation(cirq.Y ** 0.5, [q]) - assert (cirq.Y ** 0.5).on(q) == cirq.Y(q) ** 0.5 + assert op1**0.5 == cirq.GateOperation(cirq.Y**0.5, [q]) + assert (cirq.Y**0.5).on(q) == cirq.Y(q) ** 0.5 def test_inverse(): @@ -174,7 +174,7 @@ def test_inverse(): assert cirq.inverse(op0, None) is None op1 = cirq.GateOperation(cirq.S, [q]) - assert cirq.inverse(op1) == op1 ** -1 == cirq.GateOperation(cirq.S ** -1, [q]) + assert cirq.inverse(op1) == op1**-1 == cirq.GateOperation(cirq.S**-1, [q]) assert cirq.inverse(cirq.S).on(q) == cirq.inverse(cirq.S.on(q)) @@ -198,9 +198,9 @@ def test_bounded_effect(): # If the gate isn't bounded, you get a type error. op0 = cirq.GateOperation(cirq.SingleQubitGate(), [q]) assert cirq.trace_distance_bound(op0) >= 1 - op1 = cirq.GateOperation(cirq.Z ** 0.000001, [q]) + op1 = cirq.GateOperation(cirq.Z**0.000001, [q]) op1_bound = cirq.trace_distance_bound(op1) - assert op1_bound == cirq.trace_distance_bound(cirq.Z ** 0.000001) + assert op1_bound == cirq.trace_distance_bound(cirq.Z**0.000001) @pytest.mark.parametrize('resolve_fn', [cirq.resolve_parameters, cirq.resolve_parameters_once]) @@ -304,8 +304,8 @@ def on(self, *qubits): @pytest.mark.parametrize( 'gate1,gate2,eq_up_to_global_phase', [ - (cirq.rz(0.3 * np.pi), cirq.Z ** 0.3, True), - (cirq.rz(0.3), cirq.Z ** 0.3, False), + (cirq.rz(0.3 * np.pi), cirq.Z**0.3, True), + (cirq.rz(0.3), cirq.Z**0.3, False), (cirq.ZZPowGate(global_shift=0.5), cirq.ZZ, True), (cirq.ZPowGate(global_shift=0.5) ** sympy.Symbol('e'), cirq.Z, False), (cirq.Z ** sympy.Symbol('e'), cirq.Z ** sympy.Symbol('f'), False), diff --git a/cirq/ops/gateset_test.py b/cirq/ops/gateset_test.py index 6c1e1a36224..5bfc0c786d1 100644 --- a/cirq/ops/gateset_test.py +++ b/cirq/ops/gateset_test.py @@ -108,10 +108,10 @@ def test_gate_family_json(gate, name, description): def test_gate_family_eq(): eq = cirq.testing.EqualsTester() eq.add_equality_group(cirq.GateFamily(CustomX)) - eq.add_equality_group(cirq.GateFamily(CustomX ** 3)) + eq.add_equality_group(cirq.GateFamily(CustomX**3)) eq.add_equality_group( cirq.GateFamily(CustomX, name='custom_name', description='custom_description'), - cirq.GateFamily(CustomX ** 3, name='custom_name', description='custom_description'), + cirq.GateFamily(CustomX**3, name='custom_name', description='custom_description'), ) eq.add_equality_group(cirq.GateFamily(CustomXPowGate)) eq.add_equality_group( @@ -126,11 +126,11 @@ def test_gate_family_eq(): cirq.GateFamily(CustomXPowGate), [ (CustomX, True), - (CustomX ** 0.5, True), + (CustomX**0.5, True), (CustomX ** sympy.Symbol('theta'), True), (CustomXPowGate(exponent=0.25, global_shift=0.15), True), (cirq.SingleQubitGate(), False), - (cirq.X ** 0.5, False), + (cirq.X**0.5, False), (None, False), (cirq.global_phase_operation(1j), False), ], @@ -140,8 +140,8 @@ def test_gate_family_eq(): [ (CustomX, True), (CustomXPowGate(exponent=1, global_shift=0.15), True), - (CustomX ** 2, False), - (CustomX ** 3, True), + (CustomX**2, False), + (CustomX**3, True), (CustomX ** sympy.Symbol('theta'), False), (None, False), (cirq.global_phase_operation(1j), False), @@ -188,7 +188,7 @@ def __repr__(self): gateset = cirq.Gateset( - CustomX ** 0.5, cirq.testing.TwoQubitGate, CustomXGateFamily(), name='custom gateset' + CustomX**0.5, cirq.testing.TwoQubitGate, CustomXGateFamily(), name='custom gateset' ) @@ -196,7 +196,7 @@ def test_gateset_init(): assert gateset.name == 'custom gateset' assert gateset.gates == frozenset( [ - cirq.GateFamily(CustomX ** 0.5), + cirq.GateFamily(CustomX**0.5), cirq.GateFamily(cirq.testing.TwoQubitGate), CustomXGateFamily(), ] @@ -214,11 +214,11 @@ def test_gateset_repr_and_str(): 'gate, result', [ (CustomX, True), - (CustomX ** 2, True), + (CustomX**2, True), (CustomXPowGate(exponent=3, global_shift=0.5), True), - (CustomX ** 0.5, True), + (CustomX**0.5, True), (CustomXPowGate(exponent=0.5, global_shift=0.5), True), - (CustomX ** 0.25, False), + (CustomX**0.25, False), (CustomX ** sympy.Symbol('theta'), False), (cirq.testing.TwoQubitGate(), True), ], @@ -286,7 +286,7 @@ def test_gateset_validate_circuit_op_negative_reps(): gate = CustomXPowGate(exponent=0.5) op = cirq.CircuitOperation(cirq.FrozenCircuit(gate.on(cirq.LineQubit(0))), repetitions=-1) assert op not in cirq.Gateset(gate) - assert op ** -1 in cirq.Gateset(gate) + assert op**-1 in cirq.Gateset(gate) def test_with_params(): @@ -310,7 +310,7 @@ def test_with_params(): def test_gateset_eq(): eq = cirq.testing.EqualsTester() eq.add_equality_group(cirq.Gateset(CustomX)) - eq.add_equality_group(cirq.Gateset(CustomX ** 3)) + eq.add_equality_group(cirq.Gateset(CustomX**3)) eq.add_equality_group(cirq.Gateset(CustomX, name='Custom Gateset')) eq.add_equality_group(cirq.Gateset(CustomX, name='Custom Gateset', unroll_circuit_op=False)) eq.add_equality_group( @@ -322,7 +322,7 @@ def test_gateset_eq(): cirq.GateFamily(CustomX, name='custom_name', description='custom_description'), ), cirq.Gateset( - cirq.GateFamily(CustomX ** 3, name='custom_name', description='custom_description'), + cirq.GateFamily(CustomX**3, name='custom_name', description='custom_description'), cirq.GateFamily(CustomX, name='custom_name', description='custom_description'), ), ) diff --git a/cirq/ops/global_phase_op.py b/cirq/ops/global_phase_op.py index 139f51ab177..0f5abadf0cc 100644 --- a/cirq/ops/global_phase_op.py +++ b/cirq/ops/global_phase_op.py @@ -74,7 +74,7 @@ def _has_unitary_(self) -> bool: def __pow__(self, power) -> 'cirq.GlobalPhaseGate': if isinstance(power, (int, float)): - return GlobalPhaseGate(self.coefficient ** power) + return GlobalPhaseGate(self.coefficient**power) return NotImplemented def _unitary_(self) -> np.ndarray: diff --git a/cirq/ops/identity_test.py b/cirq/ops/identity_test.py index e8f8f409f1b..c1f13a73f88 100644 --- a/cirq/ops/identity_test.py +++ b/cirq/ops/identity_test.py @@ -95,9 +95,9 @@ def test_identity_on_each_two_qubits(): @pytest.mark.parametrize('num_qubits', [1, 2, 4]) def test_identity_unitary(num_qubits): i = cirq.IdentityGate(num_qubits) - assert np.allclose(cirq.unitary(i), np.identity(2 ** num_qubits)) + assert np.allclose(cirq.unitary(i), np.identity(2**num_qubits)) i3 = cirq.IdentityGate(num_qubits, (3,) * num_qubits) - assert np.allclose(cirq.unitary(i3), np.identity(3 ** num_qubits)) + assert np.allclose(cirq.unitary(i3), np.identity(3**num_qubits)) def test_identity_str(): @@ -153,7 +153,7 @@ def test_identity_pow(): assert I(q) ** (1 + 1j) == I(q) assert I(q) ** sympy.Symbol('x') == I(q) with pytest.raises(TypeError): - _ = (I ** q)(q) + _ = (I**q)(q) with pytest.raises(TypeError): _ = I(q) ** q diff --git a/cirq/ops/linear_combinations.py b/cirq/ops/linear_combinations.py index 90a27f724be..3249d8ef512 100644 --- a/cirq/ops/linear_combinations.py +++ b/cirq/ops/linear_combinations.py @@ -179,7 +179,7 @@ def matrix(self) -> np.ndarray: num_qubits = self.num_qubits() if num_qubits is None: raise ValueError('Unknown number of qubits') - num_dim = 2 ** num_qubits + num_dim = 2**num_qubits result = np.zeros((num_dim, num_dim), dtype=np.complex128) for gate, coefficient in self.items(): result += protocols.unitary(gate) * coefficient @@ -292,7 +292,7 @@ def matrix(self) -> np.ndarray: if self._is_parameterized_(): return NotImplemented num_qubits = len(self.qubits) - num_dim = 2 ** num_qubits + num_dim = 2**num_qubits qubit_to_axis = {q: i for i, q in enumerate(self.qubits)} result = np.zeros((2,) * (2 * num_qubits), dtype=np.complex128) for op, coefficient in self.items(): @@ -487,7 +487,7 @@ def matrix(self, qubits: Optional[Iterable[raw_types.Qid]] = None) -> np.ndarray qubits = self.qubits if qubits is None else tuple(qubits) num_qubits = len(qubits) - num_dim = 2 ** num_qubits + num_dim = 2**num_qubits result = np.zeros((num_dim, num_dim), dtype=np.complex128) for vec, coeff in self._linear_dict.items(): op = _pauli_string_from_unit(vec) diff --git a/cirq/ops/linear_combinations_test.py b/cirq/ops/linear_combinations_test.py index 4282abb9021..74e88bed551 100644 --- a/cirq/ops/linear_combinations_test.py +++ b/cirq/ops/linear_combinations_test.py @@ -203,7 +203,7 @@ def test_linear_combination_of_gates_has_correct_pauli_expansion(terms, expected }, 10, { - cirq.I: 2 ** -10, + cirq.I: 2**-10, }, ), ( @@ -212,7 +212,7 @@ def test_linear_combination_of_gates_has_correct_pauli_expansion(terms, expected }, 11, { - cirq.Y: 2 ** -11, + cirq.Y: 2**-11, }, ), ( @@ -252,7 +252,7 @@ def test_linear_combination_of_gates_has_correct_pauli_expansion(terms, expected ) def test_linear_combinations_of_gates_valid_powers(terms, exponent, expected_terms): combination = cirq.LinearCombinationOfGates(terms) - actual_result = combination ** exponent + actual_result = combination**exponent expected_result = cirq.LinearCombinationOfGates(expected_terms) assert cirq.approx_eq(actual_result, expected_result) assert len(actual_result) == len(expected_terms) @@ -298,7 +298,7 @@ def test_linear_combinations_of_gates_valid_powers(terms, exponent, expected_ter def test_linear_combinations_of_gates_invalid_powers(terms, exponent): combination = cirq.LinearCombinationOfGates(terms) with pytest.raises(TypeError): - _ = combination ** exponent + _ = combination**exponent @pytest.mark.parametrize( @@ -792,7 +792,7 @@ def test_linear_combination_of_operations_has_correct_pauli_expansion(terms, exp }, 10, { - cirq.I(q0): 2 ** -10, + cirq.I(q0): 2**-10, }, ), ( @@ -801,7 +801,7 @@ def test_linear_combination_of_operations_has_correct_pauli_expansion(terms, exp }, 11, { - cirq.Y(q0): 2 ** -11, + cirq.Y(q0): 2**-11, }, ), ( @@ -841,7 +841,7 @@ def test_linear_combination_of_operations_has_correct_pauli_expansion(terms, exp ) def test_linear_combinations_of_operations_valid_powers(terms, exponent, expected_terms): combination = cirq.LinearCombinationOfOperations(terms) - actual_result = combination ** exponent + actual_result = combination**exponent expected_result = cirq.LinearCombinationOfOperations(expected_terms) assert cirq.approx_eq(actual_result, expected_result) assert len(actual_result) == len(expected_terms) @@ -894,7 +894,7 @@ def test_linear_combinations_of_operations_valid_powers(terms, exponent, expecte def test_linear_combinations_of_operations_invalid_powers(terms, exponent): combination = cirq.LinearCombinationOfOperations(terms) with pytest.raises(TypeError): - _ = combination ** exponent + _ = combination**exponent @pytest.mark.parametrize( @@ -1262,10 +1262,10 @@ def test_bad_arithmetic(): _ = psum / [1, 2, 3] with pytest.raises(TypeError): - _ = psum ** 1.2 + _ = psum**1.2 with pytest.raises(TypeError): - _ = psum ** -2 + _ = psum**-2 with pytest.raises(TypeError): _ = psum ** "string" @@ -1333,24 +1333,24 @@ def test_paulisum_mul_paulisum(): def test_pauli_sum_pow(): identity = cirq.PauliSum.from_pauli_strings([cirq.PauliString(coefficient=1)]) psum1 = cirq.X(q0) + cirq.Y(q0) - assert psum1 ** 2 == psum1 * psum1 - assert psum1 ** 2 == 2 * identity + assert psum1**2 == psum1 * psum1 + assert psum1**2 == 2 * identity psum2 = cirq.X(q0) + cirq.Y(q1) - assert psum2 ** 2 == cirq.PauliString(cirq.I(q0)) + 2 * cirq.X(q0) * cirq.Y( + assert psum2**2 == cirq.PauliString(cirq.I(q0)) + 2 * cirq.X(q0) * cirq.Y( q1 ) + cirq.PauliString(cirq.I(q1)) psum3 = cirq.X(q0) * cirq.Z(q1) + 1.3 * cirq.Z(q0) sqd = cirq.PauliSum.from_pauli_strings([2.69 * cirq.PauliString(cirq.I(q0))]) - assert cirq.approx_eq(psum3 ** 2, sqd, atol=1e-8) + assert cirq.approx_eq(psum3**2, sqd, atol=1e-8) psum4 = cirq.X(q0) * cirq.Z(q1) + 1.3 * cirq.Z(q1) sqd2 = cirq.PauliSum.from_pauli_strings([2.69 * cirq.PauliString(cirq.I(q0)), 2.6 * cirq.X(q0)]) - assert cirq.approx_eq(psum4 ** 2, sqd2, atol=1e-8) + assert cirq.approx_eq(psum4**2, sqd2, atol=1e-8) for psum in [psum1, psum2, psum3, psum4]: - assert cirq.approx_eq(psum ** 0, identity) + assert cirq.approx_eq(psum**0, identity) # Using the entries of table 1 of https://arxiv.org/abs/1804.09130 as golden values. diff --git a/cirq/ops/matrix_gates.py b/cirq/ops/matrix_gates.py index 998df1948ba..bb6d53207fe 100644 --- a/cirq/ops/matrix_gates.py +++ b/cirq/ops/matrix_gates.py @@ -71,7 +71,7 @@ def __init__( if qid_shape is None: n = int(np.round(np.log2(matrix.shape[0] or 1))) - if 2 ** n != matrix.shape[0]: + if 2**n != matrix.shape[0]: raise ValueError( f'Matrix width ({matrix.shape[0]}) is not a power of 2 and ' f'qid_shape is not specified.' @@ -109,7 +109,7 @@ def __pow__(self, exponent: Any) -> 'MatrixGate': if not isinstance(exponent, (int, float)): return NotImplemented e = cast(float, exponent) - new_mat = linalg.map_eigenvalues(self._matrix, lambda b: b ** e) + new_mat = linalg.map_eigenvalues(self._matrix, lambda b: b**e) return MatrixGate(new_mat, qid_shape=self._qid_shape) def _phase_by_(self, phase_turns: float, qubit_index: int) -> 'MatrixGate': diff --git a/cirq/ops/matrix_gates_test.py b/cirq/ops/matrix_gates_test.py index 848e685022d..0e66df1f4d0 100644 --- a/cirq/ops/matrix_gates_test.py +++ b/cirq/ops/matrix_gates_test.py @@ -80,16 +80,16 @@ def test_single_qubit_extrapolate(): assert cirq.has_unitary(x2) x2i = cirq.MatrixGate(np.conj(cirq.unitary(x2).T)) - assert cirq.approx_eq(x ** 0, i, atol=1e-9) - assert cirq.approx_eq(x2 ** 0, i, atol=1e-9) - assert cirq.approx_eq(x2 ** 2, x, atol=1e-9) - assert cirq.approx_eq(x2 ** -1, x2i, atol=1e-9) - assert cirq.approx_eq(x2 ** 3, x2i, atol=1e-9) - assert cirq.approx_eq(x ** -1, x, atol=1e-9) + assert cirq.approx_eq(x**0, i, atol=1e-9) + assert cirq.approx_eq(x2**0, i, atol=1e-9) + assert cirq.approx_eq(x2**2, x, atol=1e-9) + assert cirq.approx_eq(x2**-1, x2i, atol=1e-9) + assert cirq.approx_eq(x2**3, x2i, atol=1e-9) + assert cirq.approx_eq(x**-1, x, atol=1e-9) z2 = cirq.MatrixGate(np.array([[1, 0], [0, 1j]])) z4 = cirq.MatrixGate(np.array([[1, 0], [0, (1 + 1j) * np.sqrt(0.5)]])) - assert cirq.approx_eq(z2 ** 0.5, z4, atol=1e-9) + assert cirq.approx_eq(z2**0.5, z4, atol=1e-9) with pytest.raises(TypeError): _ = x ** sympy.Symbol('a') @@ -125,9 +125,9 @@ def test_two_qubit_extrapolate(): cz4 = cirq.MatrixGate(np.diag([1, 1, 1, (1 + 1j) * np.sqrt(0.5)])) i = cirq.MatrixGate(np.eye(4)) - assert cirq.approx_eq(cz2 ** 0, i, atol=1e-9) - assert cirq.approx_eq(cz4 ** 0, i, atol=1e-9) - assert cirq.approx_eq(cz2 ** 0.5, cz4, atol=1e-9) + assert cirq.approx_eq(cz2**0, i, atol=1e-9) + assert cirq.approx_eq(cz4**0, i, atol=1e-9) + assert cirq.approx_eq(cz2**0.5, cz4, atol=1e-9) with pytest.raises(TypeError): _ = cz2 ** sympy.Symbol('a') @@ -278,7 +278,7 @@ def test_str_executes(): @pytest.mark.parametrize('n', [1, 2, 3, 4, 5]) def test_implements_consistent_protocols(n): - u = cirq.testing.random_unitary(2 ** n) + u = cirq.testing.random_unitary(2**n) g1 = cirq.MatrixGate(u) cirq.testing.assert_implements_consistent_protocols(g1, ignoring_global_phase=True) cirq.testing.assert_decompose_ends_at_default_gateset(g1) @@ -323,7 +323,7 @@ def test_matrix_gate_pow(): assert cirq.pow(cirq.MatrixGate(1j * np.eye(1)), 2) == cirq.MatrixGate(-np.eye(1)) m = cirq.MatrixGate(np.diag([1, 1j, -1]), qid_shape=(3,)) - assert m ** 3 == cirq.MatrixGate(np.diag([1, -1j, -1]), qid_shape=(3,)) + assert m**3 == cirq.MatrixGate(np.diag([1, -1j, -1]), qid_shape=(3,)) def test_phase_by(): diff --git a/cirq/ops/measurement_gate_test.py b/cirq/ops/measurement_gate_test.py index e281fb71123..94ac510dae6 100644 --- a/cirq/ops/measurement_gate_test.py +++ b/cirq/ops/measurement_gate_test.py @@ -173,19 +173,16 @@ def test_measurement_gate_diagram(): ) == cirq.CircuitDiagramInfo(("M('test')",)) # Uses known qubit count. - assert ( - cirq.circuit_diagram_info( - cirq.MeasurementGate(3, 'a'), - cirq.CircuitDiagramInfoArgs( - known_qubits=None, - known_qubit_count=3, - use_unicode_characters=True, - precision=None, - label_map=None, - ), - ) - == cirq.CircuitDiagramInfo(("M('a')", 'M', 'M')) - ) + assert cirq.circuit_diagram_info( + cirq.MeasurementGate(3, 'a'), + cirq.CircuitDiagramInfoArgs( + known_qubits=None, + known_qubit_count=3, + use_unicode_characters=True, + precision=None, + label_map=None, + ), + ) == cirq.CircuitDiagramInfo(("M('a')", 'M', 'M')) # Shows invert mask. assert cirq.circuit_diagram_info( diff --git a/cirq/ops/parallel_gate_test.py b/cirq/ops/parallel_gate_test.py index 814f5a3951e..b2d807b90cd 100644 --- a/cirq/ops/parallel_gate_test.py +++ b/cirq/ops/parallel_gate_test.py @@ -22,7 +22,7 @@ 'gate, num_copies, qubits', [ (cirq.SingleQubitGate(), 2, cirq.LineQubit.range(2)), - (cirq.X ** 0.5, 4, cirq.LineQubit.range(4)), + (cirq.X**0.5, 4, cirq.LineQubit.range(4)), ], ) def test_parallel_gate_operation_init(gate, num_copies, qubits): @@ -50,7 +50,7 @@ def test_invalid_parallel_gate_operation(gate, num_copies, qubits, error_msg): 'gate, num_copies, qubits', [ (cirq.X, 2, cirq.LineQubit.range(2)), - (cirq.H ** 0.5, 4, cirq.LineQubit.range(4)), + (cirq.H**0.5, 4, cirq.LineQubit.range(4)), ], ) def test_decompose(gate, num_copies, qubits): @@ -77,11 +77,11 @@ def test_extrapolate(): # If the gate isn't extrapolatable, you get a type error. g = cirq.ParallelGate(cirq.SingleQubitGate(), 2) with pytest.raises(TypeError): - _ = g ** 0.5 + _ = g**0.5 # If the gate is extrapolatable, the effect is applied on the underlying gate. g = cirq.ParallelGate(cirq.Y, 2) - assert g ** 0.5 == cirq.ParallelGate(cirq.Y ** 0.5, 2) - assert cirq.inverse(g) == g ** -1 == cirq.ParallelGate(cirq.Y ** -1, 2) + assert g**0.5 == cirq.ParallelGate(cirq.Y**0.5, 2) + assert cirq.inverse(g) == g**-1 == cirq.ParallelGate(cirq.Y**-1, 2) @pytest.mark.parametrize('resolve_fn', [cirq.resolve_parameters, cirq.resolve_parameters_once]) @@ -103,8 +103,8 @@ def test_no_unitary(gate): @pytest.mark.parametrize( 'gate, num_copies, qubits', [ - (cirq.X ** 0.5, 2, cirq.LineQubit.range(2)), - (cirq.MatrixGate(cirq.unitary(cirq.H ** 0.25)), 6, cirq.LineQubit.range(6)), + (cirq.X**0.5, 2, cirq.LineQubit.range(2)), + (cirq.MatrixGate(cirq.unitary(cirq.H**0.25)), 6, cirq.LineQubit.range(6)), ], ) def test_unitary(gate, num_copies, qubits): @@ -131,14 +131,14 @@ def test_repr(): def test_str(): - assert str(cirq.ParallelGate(cirq.X ** 0.5, 10)) == 'X**0.5 x 10' + assert str(cirq.ParallelGate(cirq.X**0.5, 10)) == 'X**0.5 x 10' def test_equivalent_circuit(): qreg = cirq.LineQubit.range(4) oldc = cirq.Circuit() newc = cirq.Circuit() - single_qubit_gates = [cirq.X ** (1 / 2), cirq.Y ** (1 / 3), cirq.Z ** -1] + single_qubit_gates = [cirq.X ** (1 / 2), cirq.Y ** (1 / 3), cirq.Z**-1] for gate in single_qubit_gates: for qubit in qreg: oldc.append(gate.on(qubit)) @@ -161,7 +161,7 @@ def test_parallel_gate_operation_is_consistent(gate, num_copies): def test_trace_distance(): - s = cirq.X ** 0.25 + s = cirq.X**0.25 two_g = cirq.ParallelGate(s, 2) three_g = cirq.ParallelGate(s, 3) four_g = cirq.ParallelGate(s, 4) diff --git a/cirq/ops/parity_gates_test.py b/cirq/ops/parity_gates_test.py index 19c11676efc..f04502fa3b9 100644 --- a/cirq/ops/parity_gates_test.py +++ b/cirq/ops/parity_gates_test.py @@ -47,23 +47,23 @@ def test_xx_eq(): cirq.XXPowGate(exponent=1, global_shift=0), cirq.XXPowGate(exponent=3, global_shift=0), ) - eq.add_equality_group(cirq.XX ** 0.5, cirq.XX ** 2.5, cirq.XX ** 4.5) - eq.add_equality_group(cirq.XX ** 0.25, cirq.XX ** 2.25, cirq.XX ** -1.75) + eq.add_equality_group(cirq.XX**0.5, cirq.XX**2.5, cirq.XX**4.5) + eq.add_equality_group(cirq.XX**0.25, cirq.XX**2.25, cirq.XX**-1.75) iXX = cirq.XXPowGate(global_shift=0.5) - eq.add_equality_group(iXX ** 0.5, iXX ** 4.5) - eq.add_equality_group(iXX ** 2.5, iXX ** 6.5) + eq.add_equality_group(iXX**0.5, iXX**4.5) + eq.add_equality_group(iXX**2.5, iXX**6.5) def test_xx_pow(): - assert cirq.XX ** 0.5 != cirq.XX ** -0.5 - assert cirq.XX ** -1 == cirq.XX - assert (cirq.XX ** -1) ** 0.5 == cirq.XX ** -0.5 + assert cirq.XX**0.5 != cirq.XX**-0.5 + assert cirq.XX**-1 == cirq.XX + assert (cirq.XX**-1) ** 0.5 == cirq.XX**-0.5 def test_xx_str(): assert str(cirq.XX) == 'XX' - assert str(cirq.XX ** 0.5) == 'XX**0.5' + assert str(cirq.XX**0.5) == 'XX**0.5' assert str(cirq.XXPowGate(global_shift=0.1)) == 'XX' @@ -78,7 +78,7 @@ def test_xx_matrix(): np.array([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]]), atol=1e-8, ) - np.testing.assert_allclose(cirq.unitary(cirq.XX ** 2), np.eye(4), atol=1e-8) + np.testing.assert_allclose(cirq.unitary(cirq.XX**2), np.eye(4), atol=1e-8) c = np.cos(np.pi / 6) s = -1j * np.sin(np.pi / 6) np.testing.assert_allclose( @@ -120,23 +120,23 @@ def test_yy_eq(): cirq.YYPowGate(exponent=1, global_shift=0), cirq.YYPowGate(exponent=3, global_shift=0), ) - eq.add_equality_group(cirq.YY ** 0.5, cirq.YY ** 2.5, cirq.YY ** 4.5) - eq.add_equality_group(cirq.YY ** 0.25, cirq.YY ** 2.25, cirq.YY ** -1.75) + eq.add_equality_group(cirq.YY**0.5, cirq.YY**2.5, cirq.YY**4.5) + eq.add_equality_group(cirq.YY**0.25, cirq.YY**2.25, cirq.YY**-1.75) iYY = cirq.YYPowGate(global_shift=0.5) - eq.add_equality_group(iYY ** 0.5, iYY ** 4.5) - eq.add_equality_group(iYY ** 2.5, iYY ** 6.5) + eq.add_equality_group(iYY**0.5, iYY**4.5) + eq.add_equality_group(iYY**2.5, iYY**6.5) def test_yy_pow(): - assert cirq.YY ** 0.5 != cirq.YY ** -0.5 - assert cirq.YY ** -1 == cirq.YY - assert (cirq.YY ** -1) ** 0.5 == cirq.YY ** -0.5 + assert cirq.YY**0.5 != cirq.YY**-0.5 + assert cirq.YY**-1 == cirq.YY + assert (cirq.YY**-1) ** 0.5 == cirq.YY**-0.5 def test_yy_str(): assert str(cirq.YY) == 'YY' - assert str(cirq.YY ** 0.5) == 'YY**0.5' + assert str(cirq.YY**0.5) == 'YY**0.5' assert str(cirq.YYPowGate(global_shift=0.1)) == 'YY' iYY = cirq.YYPowGate(global_shift=0.5) @@ -154,7 +154,7 @@ def test_yy_matrix(): np.array([[0, 0, 0, -1], [0, 0, 1, 0], [0, 1, 0, 0], [-1, 0, 0, 0]]), atol=1e-8, ) - np.testing.assert_allclose(cirq.unitary(cirq.YY ** 2), np.eye(4), atol=1e-8) + np.testing.assert_allclose(cirq.unitary(cirq.YY**2), np.eye(4), atol=1e-8) c = np.cos(np.pi / 6) s = 1j * np.sin(np.pi / 6) np.testing.assert_allclose( @@ -196,23 +196,23 @@ def test_zz_eq(): cirq.ZZPowGate(exponent=1, global_shift=0), cirq.ZZPowGate(exponent=3, global_shift=0), ) - eq.add_equality_group(cirq.ZZ ** 0.5, cirq.ZZ ** 2.5, cirq.ZZ ** 4.5) - eq.add_equality_group(cirq.ZZ ** 0.25, cirq.ZZ ** 2.25, cirq.ZZ ** -1.75) + eq.add_equality_group(cirq.ZZ**0.5, cirq.ZZ**2.5, cirq.ZZ**4.5) + eq.add_equality_group(cirq.ZZ**0.25, cirq.ZZ**2.25, cirq.ZZ**-1.75) iZZ = cirq.ZZPowGate(global_shift=0.5) - eq.add_equality_group(iZZ ** 0.5, iZZ ** 4.5) - eq.add_equality_group(iZZ ** 2.5, iZZ ** 6.5) + eq.add_equality_group(iZZ**0.5, iZZ**4.5) + eq.add_equality_group(iZZ**2.5, iZZ**6.5) def test_zz_pow(): - assert cirq.ZZ ** 0.5 != cirq.ZZ ** -0.5 - assert cirq.ZZ ** -1 == cirq.ZZ - assert (cirq.ZZ ** -1) ** 0.5 == cirq.ZZ ** -0.5 + assert cirq.ZZ**0.5 != cirq.ZZ**-0.5 + assert cirq.ZZ**-1 == cirq.ZZ + assert (cirq.ZZ**-1) ** 0.5 == cirq.ZZ**-0.5 def test_zz_str(): assert str(cirq.ZZ) == 'ZZ' - assert str(cirq.ZZ ** 0.5) == 'ZZ**0.5' + assert str(cirq.ZZ**0.5) == 'ZZ**0.5' assert str(cirq.ZZPowGate(global_shift=0.1)) == 'ZZ' iZZ = cirq.ZZPowGate(global_shift=0.5) @@ -230,8 +230,8 @@ def test_zz_matrix(): np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]]), atol=1e-8, ) - np.testing.assert_allclose(cirq.unitary(cirq.ZZ ** 2), np.eye(4), atol=1e-8) - b = 1j ** 0.25 + np.testing.assert_allclose(cirq.unitary(cirq.ZZ**2), np.eye(4), atol=1e-8) + b = 1j**0.25 a = np.conj(b) np.testing.assert_allclose( cirq.unitary(cirq.ZZPowGate(exponent=0.25, global_shift=-0.5)), @@ -260,9 +260,9 @@ def test_zz_diagrams(): def test_trace_distance(): foo = sympy.Symbol('foo') - assert cirq.trace_distance_bound(cirq.XX ** foo) == 1.0 - assert cirq.trace_distance_bound(cirq.YY ** foo) == 1.0 - assert cirq.trace_distance_bound(cirq.ZZ ** foo) == 1.0 + assert cirq.trace_distance_bound(cirq.XX**foo) == 1.0 + assert cirq.trace_distance_bound(cirq.YY**foo) == 1.0 + assert cirq.trace_distance_bound(cirq.ZZ**foo) == 1.0 assert cirq.approx_eq(cirq.trace_distance_bound(cirq.XX), 1.0) - assert cirq.approx_eq(cirq.trace_distance_bound(cirq.YY ** 0), 0) + assert cirq.approx_eq(cirq.trace_distance_bound(cirq.YY**0), 0) assert cirq.approx_eq(cirq.trace_distance_bound(cirq.ZZ ** (1 / 3)), np.sin(np.pi / 6)) diff --git a/cirq/ops/pauli_gates_test.py b/cirq/ops/pauli_gates_test.py index 81753b5f019..c6a03e3f3f5 100644 --- a/cirq/ops/pauli_gates_test.py +++ b/cirq/ops/pauli_gates_test.py @@ -210,13 +210,13 @@ def test_powers(): assert isinstance(cirq.X, cirq.Pauli) assert isinstance(cirq.Y, cirq.Pauli) assert isinstance(cirq.Z, cirq.Pauli) - assert not isinstance(cirq.X ** -0.5, cirq.Pauli) - assert not isinstance(cirq.Y ** 0.2, cirq.Pauli) - assert not isinstance(cirq.Z ** 0.5, cirq.Pauli) - assert isinstance(cirq.X ** -0.5, cirq.XPowGate) - assert isinstance(cirq.Y ** 0.2, cirq.YPowGate) - assert isinstance(cirq.Z ** 0.5, cirq.ZPowGate) - - assert isinstance(cirq.X ** 1, cirq.Pauli) - assert isinstance(cirq.Y ** 1, cirq.Pauli) - assert isinstance(cirq.Z ** 1, cirq.Pauli) + assert not isinstance(cirq.X**-0.5, cirq.Pauli) + assert not isinstance(cirq.Y**0.2, cirq.Pauli) + assert not isinstance(cirq.Z**0.5, cirq.Pauli) + assert isinstance(cirq.X**-0.5, cirq.XPowGate) + assert isinstance(cirq.Y**0.2, cirq.YPowGate) + assert isinstance(cirq.Z**0.5, cirq.ZPowGate) + + assert isinstance(cirq.X**1, cirq.Pauli) + assert isinstance(cirq.Y**1, cirq.Pauli) + assert isinstance(cirq.Z**1, cirq.Pauli) diff --git a/cirq/ops/pauli_interaction_gate.py b/cirq/ops/pauli_interaction_gate.py index 5a0a27df8fa..23c464d6a6c 100644 --- a/cirq/ops/pauli_interaction_gate.py +++ b/cirq/ops/pauli_interaction_gate.py @@ -151,8 +151,8 @@ def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE': right_gate0 = SingleQubitCliffordGate.from_single_map(z_to=(self.pauli0, self.invert0)) right_gate1 = SingleQubitCliffordGate.from_single_map(z_to=(self.pauli1, self.invert1)) - left_gate0 = right_gate0 ** -1 - left_gate1 = right_gate1 ** -1 + left_gate0 = right_gate0**-1 + left_gate1 = right_gate1**-1 yield left_gate0(q0) yield left_gate1(q1) yield common_gates.CZ(q0, q1) ** self._exponent diff --git a/cirq/ops/pauli_interaction_gate_test.py b/cirq/ops/pauli_interaction_gate_test.py index 4a7eb6fde98..7af7206457d 100644 --- a/cirq/ops/pauli_interaction_gate_test.py +++ b/cirq/ops/pauli_interaction_gate_test.py @@ -82,7 +82,7 @@ def test_interchangeable_qubits(gate): def test_exponent(): cnot = cirq.PauliInteractionGate(cirq.Z, False, cirq.X, False) np.testing.assert_almost_equal( - cirq.unitary(cnot ** 0.5), + cirq.unitary(cnot**0.5), np.array( [ [1, 0, 0, 0], diff --git a/cirq/ops/pauli_measurement_gate_test.py b/cirq/ops/pauli_measurement_gate_test.py index 533e87f9b21..451058f9e6f 100644 --- a/cirq/ops/pauli_measurement_gate_test.py +++ b/cirq/ops/pauli_measurement_gate_test.py @@ -185,10 +185,10 @@ def test_with_observable(): [ (cirq.I, cirq.DensePauliString("Z", coefficient=+1), 0), (cirq.I, cirq.DensePauliString("Z", coefficient=-1), 1), - (cirq.Y ** 0.5, cirq.DensePauliString("X", coefficient=+1), 0), - (cirq.Y ** 0.5, cirq.DensePauliString("X", coefficient=-1), 1), - (cirq.X ** -0.5, cirq.DensePauliString("Y", coefficient=+1), 0), - (cirq.X ** -0.5, cirq.DensePauliString("Y", coefficient=-1), 1), + (cirq.Y**0.5, cirq.DensePauliString("X", coefficient=+1), 0), + (cirq.Y**0.5, cirq.DensePauliString("X", coefficient=-1), 1), + (cirq.X**-0.5, cirq.DensePauliString("Y", coefficient=+1), 0), + (cirq.X**-0.5, cirq.DensePauliString("Y", coefficient=-1), 1), ], ) def test_pauli_measurement_gate_samples(rot, obs, out): diff --git a/cirq/ops/pauli_string.py b/cirq/ops/pauli_string.py index 9a44cc78176..9d146639143 100644 --- a/cirq/ops/pauli_string.py +++ b/cirq/ops/pauli_string.py @@ -693,7 +693,7 @@ def __pos__(self) -> 'PauliString': def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): """Override behavior of numpy's exp method.""" if ufunc == np.exp and len(inputs) == 1 and inputs[0] is self: - return math.e ** self + return math.e**self return NotImplemented def __pow__(self, power): @@ -701,7 +701,7 @@ def __pow__(self, power): return self if power == -1: return PauliString( - qubit_pauli_map=self._qubit_pauli_map, coefficient=self.coefficient ** -1 + qubit_pauli_map=self._qubit_pauli_map, coefficient=self.coefficient**-1 ) if isinstance(power, (int, float)): r, i = cmath.polar(self.coefficient) diff --git a/cirq/ops/pauli_string_phasor.py b/cirq/ops/pauli_string_phasor.py index aa761f5d503..75a7aa19861 100644 --- a/cirq/ops/pauli_string_phasor.py +++ b/cirq/ops/pauli_string_phasor.py @@ -334,7 +334,7 @@ def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE': def _trace_distance_bound_(self) -> float: if len(self.dense_pauli_string) == 0: return 0.0 - return protocols.trace_distance_bound(pauli_gates.Z ** self.exponent_relative) + return protocols.trace_distance_bound(pauli_gates.Z**self.exponent_relative) def _is_parameterized_(self) -> bool: return protocols.is_parameterized(self.exponent_neg) or protocols.is_parameterized( diff --git a/cirq/ops/pauli_string_phasor_test.py b/cirq/ops/pauli_string_phasor_test.py index d2f72921520..6e0e97fe79d 100644 --- a/cirq/ops/pauli_string_phasor_test.py +++ b/cirq/ops/pauli_string_phasor_test.py @@ -110,10 +110,10 @@ def test_pow(): a = cirq.LineQubit(0) s = cirq.PauliString({a: cirq.X}) p = cirq.PauliStringPhasor(s, exponent_neg=0.25, exponent_pos=0.5) - assert p ** 0.5 == cirq.PauliStringPhasor(s, exponent_neg=0.125, exponent_pos=0.25) + assert p**0.5 == cirq.PauliStringPhasor(s, exponent_neg=0.125, exponent_pos=0.25) with pytest.raises(TypeError, match='unsupported operand'): _ = p ** object() - assert p ** 1 == p + assert p**1 == p def test_consistent(): @@ -139,8 +139,8 @@ def test_extrapolate_effect(): op1 = cirq.PauliStringPhasor(cirq.PauliString({}), exponent_neg=0.5) op2 = cirq.PauliStringPhasor(cirq.PauliString({}), exponent_neg=1.5) op3 = cirq.PauliStringPhasor(cirq.PauliString({}), exponent_neg=0.125) - assert op1 ** 3 == op2 - assert op1 ** 0.25 == op3 + assert op1**3 == op2 + assert op1**0.25 == op3 def test_extrapolate_effect_with_symbol(): @@ -225,7 +225,7 @@ def test_merge_with(): def test_is_parameterized(): op = cirq.PauliStringPhasor(cirq.PauliString({})) assert not cirq.is_parameterized(op) - assert not cirq.is_parameterized(op ** 0.1) + assert not cirq.is_parameterized(op**0.1) assert cirq.is_parameterized(op ** sympy.Symbol('a')) @@ -322,8 +322,8 @@ def test_default_decompose(paulis, phase_exponent_negative: float, sign: int): # Calculate expected matrix to_z_mats = { - cirq.X: cirq.unitary(cirq.Y ** -0.5), - cirq.Y: cirq.unitary(cirq.X ** 0.5), + cirq.X: cirq.unitary(cirq.Y**-0.5), + cirq.Y: cirq.unitary(cirq.X**0.5), cirq.Z: np.eye(2), } expected_convert = np.eye(1) @@ -503,18 +503,18 @@ def test_gate_equal_up_to_global_phase(): def test_gate_pow(): s = dps_x p = cirq.PauliStringPhasorGate(s, exponent_neg=0.25, exponent_pos=0.5) - assert p ** 0.5 == cirq.PauliStringPhasorGate(s, exponent_neg=0.125, exponent_pos=0.25) + assert p**0.5 == cirq.PauliStringPhasorGate(s, exponent_neg=0.125, exponent_pos=0.25) with pytest.raises(TypeError, match='unsupported operand'): _ = p ** object() - assert p ** 1 == p + assert p**1 == p def test_gate_extrapolate_effect(): gate1 = cirq.PauliStringPhasorGate(dps_empty, exponent_neg=0.5) gate2 = cirq.PauliStringPhasorGate(dps_empty, exponent_neg=1.5) gate3 = cirq.PauliStringPhasorGate(dps_empty, exponent_neg=0.125) - assert gate1 ** 3 == gate2 - assert gate1 ** 0.25 == gate3 + assert gate1**3 == gate2 + assert gate1**0.25 == gate3 def test_gate_extrapolate_effect_with_symbol(): @@ -548,7 +548,7 @@ def test_gate_inverse(): def test_gate_is_parameterized(): gate = cirq.PauliStringPhasorGate(dps_empty) assert not cirq.is_parameterized(gate) - assert not cirq.is_parameterized(gate ** 0.1) + assert not cirq.is_parameterized(gate**0.1) assert cirq.is_parameterized(gate ** sympy.Symbol('a')) diff --git a/cirq/ops/pauli_string_test.py b/cirq/ops/pauli_string_test.py index 04f4fd8785f..5c748903045 100644 --- a/cirq/ops/pauli_string_test.py +++ b/cirq/ops/pauli_string_test.py @@ -172,13 +172,13 @@ def test_exponentiation_as_base(): _ = p ** 'test' with pytest.raises(TypeError, match='unsupported'): - _ = p ** 1j + _ = p**1j - assert p ** -1 == p + assert p**-1 == p - assert cirq.approx_eq(p ** 0.5, cirq.PauliStringPhasor(p, exponent_neg=0.5, exponent_pos=0)) + assert cirq.approx_eq(p**0.5, cirq.PauliStringPhasor(p, exponent_neg=0.5, exponent_pos=0)) - assert cirq.approx_eq(p ** -0.5, cirq.PauliStringPhasor(p, exponent_neg=-0.5, exponent_pos=0)) + assert cirq.approx_eq(p**-0.5, cirq.PauliStringPhasor(p, exponent_neg=-0.5, exponent_pos=0)) assert cirq.approx_eq( math.e ** (0.25j * math.pi * p), @@ -535,8 +535,8 @@ def test_pow(): assert cirq.PauliString({a: cirq.Z}) ** 0.25 == cirq.Z(a) ** 0.25 p = cirq.PauliString({a: cirq.X, b: cirq.Y}) - assert p ** 1 == p - assert p ** -1 == p + assert p**1 == p + assert p**-1 == p assert (-p) ** 1 == -p assert (-p) ** -1 == -p assert (1j * p) ** 1 == 1j * p @@ -593,7 +593,7 @@ def test_to_z_basis_ops(): initial_state = cirq.kron(x0, x1, y0, y1, z0, z1, shape_len=1) z_basis_state = circuit.final_state_vector(initial_state) - expected_state = np.zeros(2 ** 6) + expected_state = np.zeros(2**6) expected_state[0b010101] = 1 cirq.testing.assert_allclose_up_to_global_phase( @@ -618,7 +618,7 @@ def test_to_z_basis_ops_product_state(): ) z_basis_state = circuit.final_state_vector(initial_state) - expected_state = np.zeros(2 ** 6) + expected_state = np.zeros(2**6) expected_state[0b010101] = 1 cirq.testing.assert_allclose_up_to_global_phase( @@ -1320,8 +1320,8 @@ def test_pauli_string_expectation_from_density_matrix_pure_state_with_coef(): def test_pauli_string_expectation_from_state_vector_mixed_state_linearity(): n_qubits = 6 - state_vector1 = cirq.testing.random_superposition(2 ** n_qubits) - state_vector2 = cirq.testing.random_superposition(2 ** n_qubits) + state_vector1 = cirq.testing.random_superposition(2**n_qubits) + state_vector2 = cirq.testing.random_superposition(2**n_qubits) rho1 = np.outer(state_vector1, np.conj(state_vector1)) rho2 = np.outer(state_vector2, np.conj(state_vector2)) density_matrix = rho1 / 2 + rho2 / 2 @@ -1390,7 +1390,7 @@ def test_conjugated_by_incorrectly_powered_cliffords(): ] for c in cliffords: with pytest.raises(TypeError, match='not a known Clifford'): - _ = p.conjugated_by(c ** 0.1) + _ = p.conjugated_by(c**0.1) with pytest.raises(TypeError, match='not a known Clifford'): _ = p.conjugated_by(c ** sympy.Symbol('t')) @@ -1444,24 +1444,12 @@ def _decompose_(self, qubits): def test_conjugated_by_move_into_uninvolved(): a, b, c, d = cirq.LineQubit.range(4) p = cirq.X(a) * cirq.Z(b) - assert ( - p.conjugated_by( - [ - cirq.SWAP(c, d), - cirq.SWAP(b, c), - ] - ) - == cirq.X(a) * cirq.Z(d) - ) - assert ( - p.conjugated_by( - [ - cirq.SWAP(b, c), - cirq.SWAP(c, d), - ] - ) - == cirq.X(a) * cirq.Z(c) - ) + assert p.conjugated_by([cirq.SWAP(c, d), cirq.SWAP(b, c),]) == cirq.X( + a + ) * cirq.Z(d) + assert p.conjugated_by([cirq.SWAP(b, c), cirq.SWAP(c, d),]) == cirq.X( + a + ) * cirq.Z(c) def test_conjugated_by_common_single_qubit_gates(): @@ -1472,15 +1460,15 @@ def test_conjugated_by_common_single_qubit_gates(): cirq.X, cirq.Y, cirq.Z, - cirq.X ** -0.5, - cirq.Y ** -0.5, - cirq.Z ** -0.5, - cirq.X ** 0.5, - cirq.Y ** 0.5, - cirq.Z ** 0.5, + cirq.X**-0.5, + cirq.Y**-0.5, + cirq.Z**-0.5, + cirq.X**0.5, + cirq.Y**0.5, + cirq.Z**0.5, cirq.H, ] - single_qubit_gates = [g ** i for i in range(4) for g in base_single_qubit_gates] + single_qubit_gates = [g**i for i in range(4) for g in base_single_qubit_gates] for p in [cirq.X, cirq.Y, cirq.Z]: for g in single_qubit_gates: assert p.on(a).conjugated_by(g.on(b)) == p.on(a) @@ -1504,17 +1492,17 @@ def _decompose_(self, qubits): cirq.CNOT, cirq.CZ, cirq.ISWAP, - cirq.ISWAP ** -1, + cirq.ISWAP**-1, cirq.SWAP, - cirq.XX ** 0.5, - cirq.YY ** 0.5, - cirq.ZZ ** 0.5, + cirq.XX**0.5, + cirq.YY**0.5, + cirq.ZZ**0.5, cirq.XX, cirq.YY, cirq.ZZ, - cirq.XX ** -0.5, - cirq.YY ** -0.5, - cirq.ZZ ** -0.5, + cirq.XX**-0.5, + cirq.YY**-0.5, + cirq.ZZ**-0.5, ] two_qubit_gates.extend( [ @@ -1619,7 +1607,7 @@ def test_circuit_diagram_info(): cirq.X(a) * cirq.Z(c), 1j * cirq.X(a) * cirq.Y(b), -1j * cirq.Y(b), - 1j ** 0.5 * cirq.X(a) * cirq.Y(b), + 1j**0.5 * cirq.X(a) * cirq.Y(b), ), """ 0: ───PauliString(+X)───PauliString(-X)───PauliString(+X)───PauliString(iX)──────────────────────PauliString((0.707+0.707i)*X)─── @@ -1918,7 +1906,7 @@ def __rmul__(self, other): def test_coefficient_precision(): - qs = cirq.LineQubit.range(4 * 10 ** 3) + qs = cirq.LineQubit.range(4 * 10**3) r = cirq.MutablePauliString({q: cirq.X for q in qs}) r2 = cirq.MutablePauliString({q: cirq.Y for q in qs}) r2 *= r diff --git a/cirq/ops/pauli_sum_exponential_test.py b/cirq/ops/pauli_sum_exponential_test.py index 8ea6b7b8cab..e9418e46d86 100644 --- a/cirq/ops/pauli_sum_exponential_test.py +++ b/cirq/ops/pauli_sum_exponential_test.py @@ -129,7 +129,7 @@ def test_pauli_sum_exponential_has_correct_unitary(psum_exp, expected_unitary): ), ) def test_pauli_sum_exponential_pow(psum_exp, power, expected_psum): - assert psum_exp ** power == expected_psum + assert psum_exp**power == expected_psum @pytest.mark.parametrize( diff --git a/cirq/ops/phased_iswap_gate_test.py b/cirq/ops/phased_iswap_gate_test.py index 83f4ed1db22..4ee64f09671 100644 --- a/cirq/ops/phased_iswap_gate_test.py +++ b/cirq/ops/phased_iswap_gate_test.py @@ -31,7 +31,7 @@ def test_phased_iswap_init(): def test_phased_iswap_equality(): - assert cirq.PhasedISwapPowGate(phase_exponent=0, exponent=0.4) == cirq.ISWAP ** 0.4 + assert cirq.PhasedISwapPowGate(phase_exponent=0, exponent=0.4) == cirq.ISWAP**0.4 def test_repr(): @@ -82,7 +82,7 @@ def test_phased_iswap_str(): def test_phased_iswap_pow(): gate1 = cirq.PhasedISwapPowGate(phase_exponent=0.1, exponent=0.25) gate2 = cirq.PhasedISwapPowGate(phase_exponent=0.1, exponent=0.5) - assert gate1 ** 2 == gate2 + assert gate1**2 == gate2 u1 = cirq.unitary(gate1) u2 = cirq.unitary(gate2) diff --git a/cirq/ops/phased_x_gate.py b/cirq/ops/phased_x_gate.py index cf83219fbcd..ef17dfb583c 100644 --- a/cirq/ops/phased_x_gate.py +++ b/cirq/ops/phased_x_gate.py @@ -56,7 +56,7 @@ def _qasm_(self, args: 'cirq.QasmArgs', qubits: Tuple['cirq.Qid', ...]) -> Optio e = cast(float, value.canonicalize_half_turns(self._exponent)) p = cast(float, self.phase_exponent) - epsilon = 10 ** -args.precision + epsilon = 10**-args.precision if abs(e + 0.5) <= epsilon: return args.format( @@ -81,7 +81,7 @@ def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE': q = qubits[0] z = cirq.Z(q) ** self._phase_exponent x = cirq.XPowGate(exponent=self._exponent, global_shift=self.global_shift).on(q) - return z ** -1, x, z + return z**-1, x, z @property def exponent(self) -> Union[float, sympy.Symbol]: @@ -119,8 +119,8 @@ def _unitary_(self) -> Union[np.ndarray, NotImplementedType]: """See `cirq.SupportsUnitary`.""" if self._is_parameterized_(): return None - z = protocols.unitary(cirq.Z ** self._phase_exponent) - x = protocols.unitary(cirq.X ** self._exponent) + z = protocols.unitary(cirq.Z**self._phase_exponent) + x = protocols.unitary(cirq.X**self._exponent) p = np.exp(1j * np.pi * self._global_shift * self._exponent) return np.dot(np.dot(z, x), np.conj(z)) * p diff --git a/cirq/ops/phased_x_gate_test.py b/cirq/ops/phased_x_gate_test.py index 04e8420cafd..c3fdfa1bc91 100644 --- a/cirq/ops/phased_x_gate_test.py +++ b/cirq/ops/phased_x_gate_test.py @@ -75,16 +75,16 @@ def test_no_symbolic_qasm_but_fails_gracefully(sym): def test_extrapolate(): g = cirq.PhasedXPowGate(phase_exponent=0.25) - assert g ** 0.25 == (g ** 0.5) ** 0.5 + assert g**0.25 == (g**0.5) ** 0.5 # The gate is self-inverse, but there are hidden variables tracking the # exponent's sign and scale. - assert g ** -1 == g + assert g**-1 == g assert g.exponent == 1 - assert (g ** -1).exponent == -1 - assert g ** -0.5 == (g ** -1) ** 0.5 != g ** 0.5 - assert g == g ** 3 - assert g ** 0.5 != (g ** 3) ** 0.5 == g ** -0.5 + assert (g**-1).exponent == -1 + assert g**-0.5 == (g**-1) ** 0.5 != g**0.5 + assert g == g**3 + assert g**0.5 != (g**3) ** 0.5 == g**-0.5 def test_eq(): @@ -104,7 +104,7 @@ def test_eq(): cirq.PhasedXPowGate(phase_exponent=2.5, exponent=3), cirq.Y, ) - eq.add_equality_group(cirq.PhasedXPowGate(phase_exponent=0.5, exponent=0.25), cirq.Y ** 0.25) + eq.add_equality_group(cirq.PhasedXPowGate(phase_exponent=0.5, exponent=0.25), cirq.Y**0.25) eq.add_equality_group(cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.25, global_shift=0.1)) eq.add_equality_group(cirq.PhasedXPowGate(phase_exponent=2.25, exponent=0.25, global_shift=0.2)) diff --git a/cirq/ops/phased_x_z_gate.py b/cirq/ops/phased_x_z_gate.py index d4bc1401e3a..053e3bffddb 100644 --- a/cirq/ops/phased_x_z_gate.py +++ b/cirq/ops/phased_x_z_gate.py @@ -145,8 +145,8 @@ def _unitary_(self) -> Optional[np.ndarray]: """See `cirq.SupportsUnitary`.""" if self._is_parameterized_(): return None - z_pre = protocols.unitary(ops.Z ** -self._axis_phase_exponent) - x = protocols.unitary(ops.X ** self._x_exponent) + z_pre = protocols.unitary(ops.Z**-self._axis_phase_exponent) + x = protocols.unitary(ops.X**self._x_exponent) z_post = protocols.unitary(ops.Z ** (self._axis_phase_exponent + self._z_exponent)) return z_post @ x @ z_pre diff --git a/cirq/ops/phased_x_z_gate_test.py b/cirq/ops/phased_x_z_gate_test.py index 0536ff17984..cff85c1bc8e 100644 --- a/cirq/ops/phased_x_z_gate_test.py +++ b/cirq/ops/phased_x_z_gate_test.py @@ -124,32 +124,32 @@ def f(x, z, a): def test_from_matrix(): # Axis rotations. assert cirq.approx_eq( - cirq.PhasedXZGate.from_matrix(cirq.unitary(cirq.X ** 0.1)), + cirq.PhasedXZGate.from_matrix(cirq.unitary(cirq.X**0.1)), cirq.PhasedXZGate(x_exponent=0.1, z_exponent=0, axis_phase_exponent=0), atol=1e-8, ) assert cirq.approx_eq( - cirq.PhasedXZGate.from_matrix(cirq.unitary(cirq.X ** -0.1)), + cirq.PhasedXZGate.from_matrix(cirq.unitary(cirq.X**-0.1)), cirq.PhasedXZGate(x_exponent=-0.1, z_exponent=0, axis_phase_exponent=0), atol=1e-8, ) assert cirq.approx_eq( - cirq.PhasedXZGate.from_matrix(cirq.unitary(cirq.Y ** 0.1)), + cirq.PhasedXZGate.from_matrix(cirq.unitary(cirq.Y**0.1)), cirq.PhasedXZGate(x_exponent=0.1, z_exponent=0, axis_phase_exponent=0.5), atol=1e-8, ) assert cirq.approx_eq( - cirq.PhasedXZGate.from_matrix(cirq.unitary(cirq.Y ** -0.1)), + cirq.PhasedXZGate.from_matrix(cirq.unitary(cirq.Y**-0.1)), cirq.PhasedXZGate(x_exponent=-0.1, z_exponent=0, axis_phase_exponent=0.5), atol=1e-8, ) assert cirq.approx_eq( - cirq.PhasedXZGate.from_matrix(cirq.unitary(cirq.Z ** -0.1)), + cirq.PhasedXZGate.from_matrix(cirq.unitary(cirq.Z**-0.1)), cirq.PhasedXZGate(x_exponent=0, z_exponent=-0.1, axis_phase_exponent=0), atol=1e-8, ) assert cirq.approx_eq( - cirq.PhasedXZGate.from_matrix(cirq.unitary(cirq.Z ** 0.1)), + cirq.PhasedXZGate.from_matrix(cirq.unitary(cirq.Z**0.1)), cirq.PhasedXZGate(x_exponent=0, z_exponent=0.1, axis_phase_exponent=0), atol=1e-8, ) @@ -240,7 +240,7 @@ def test_inverse(): g = cirq.PhasedXZGate(x_exponent=a, z_exponent=b, axis_phase_exponent=c).on(q) cirq.testing.assert_allclose_up_to_global_phase( - cirq.unitary(g ** -1), np.transpose(np.conjugate(cirq.unitary(g))), atol=1e-8 + cirq.unitary(g**-1), np.transpose(np.conjugate(cirq.unitary(g))), atol=1e-8 ) diff --git a/cirq/ops/raw_types.py b/cirq/ops/raw_types.py index 56299bc60f2..b1074306440 100644 --- a/cirq/ops/raw_types.py +++ b/cirq/ops/raw_types.py @@ -598,7 +598,7 @@ def _commutes_( # Don't create gigantic matrices. shape = protocols.qid_shape_protocol.qid_shape(circuit12) - if np.prod(shape, dtype=np.int64) > 2 ** 10: + if np.prod(shape, dtype=np.int64) > 2**10: return NotImplemented # coverage: ignore m12 = protocols.unitary_protocol.unitary(circuit12, default=None) @@ -841,7 +841,7 @@ def _phase_by_(self, phase_turns: float, qubit_index: int) -> 'cirq.Operation': return protocols.phase_by(self.sub_operation, phase_turns, qubit_index) def __pow__(self, exponent: Any) -> 'cirq.Operation': - return self.sub_operation ** exponent + return self.sub_operation**exponent def __mul__(self, other: Any) -> Any: return self.sub_operation * other diff --git a/cirq/ops/raw_types_test.py b/cirq/ops/raw_types_test.py index d27433f8547..15c6c2a1def 100644 --- a/cirq/ops/raw_types_test.py +++ b/cirq/ops/raw_types_test.py @@ -171,9 +171,9 @@ def __repr__(self): TestGate().on(a) t = TestGate().on(a, b) - i = t ** -1 - assert i ** -1 == t - assert t ** -1 == i + i = t**-1 + assert i**-1 == t + assert t**-1 == i assert cirq.decompose(i) == [cirq.X(a), cirq.S(b) ** -1, cirq.Z(a)] cirq.testing.assert_allclose_up_to_global_phase( cirq.unitary(i), cirq.unitary(t).conj().T, atol=1e-8 @@ -188,7 +188,7 @@ def _num_qubits_(self): return 3 def _decompose_(self, qubits): - return (cirq.X ** 0.1).on_each(*qubits) + return (cirq.X**0.1).on_each(*qubits) assert cirq.inverse(TestGate(), None) is not None cirq.testing.assert_has_consistent_qid_shape(cirq.inverse(TestGate())) @@ -214,7 +214,7 @@ def _qid_shape_(self): return (1, 2, 3) def _decompose_(self, qubits): - return (cirq.X ** 0.1).on(qubits[1]) + return (cirq.X**0.1).on(qubits[1]) assert cirq.qid_shape(cirq.inverse(TestGate(), None)) == (1, 2, 3) cirq.testing.assert_has_consistent_qid_shape(cirq.inverse(TestGate())) @@ -616,7 +616,7 @@ def test_tagged_operation_forwards_protocols(): y = cirq.Y(q1) tagged_y = cirq.Y(q1).with_tags(tag) - assert tagged_y ** 0.5 == cirq.YPowGate(exponent=0.5)(q1) + assert tagged_y**0.5 == cirq.YPowGate(exponent=0.5)(q1) assert tagged_y * 2 == (y * 2) assert 3 * tagged_y == (3 * y) assert cirq.phase_by(y, 0.125, 0) == cirq.phase_by(tagged_y, 0.125, 0) @@ -635,8 +635,8 @@ def test_tagged_operation_forwards_protocols(): assert cirq.commutes(clifford_x, tagged_x) assert cirq.commutes(tagged_x, tagged_x) - assert cirq.trace_distance_bound(y ** 0.001) == cirq.trace_distance_bound( - (y ** 0.001).with_tags(tag) + assert cirq.trace_distance_bound(y**0.001) == cirq.trace_distance_bound( + (y**0.001).with_tags(tag) ) flip = cirq.bit_flip(0.5)(q1) diff --git a/cirq/ops/state_preparation_channel.py b/cirq/ops/state_preparation_channel.py index 3c1bcab0b5d..daf6b0faca7 100644 --- a/cirq/ops/state_preparation_channel.py +++ b/cirq/ops/state_preparation_channel.py @@ -43,7 +43,7 @@ def __init__(self, target_state: np.ndarray, *, name: str = "StatePreparation") raise ValueError('`target_state` must be a 1d numpy array.') n = int(np.round(np.log2(target_state.shape[0] or 1))) - if 2 ** n != target_state.shape[0]: + if 2**n != target_state.shape[0]: raise ValueError(f'Matrix width ({target_state.shape[0]}) is not a power of 2') self._state = target_state.astype(np.complex128) / np.linalg.norm(target_state) @@ -104,7 +104,7 @@ def _kraus_(self) -> Iterable[np.ndarray]: This allows is to take any input state to the target state. The operator satisfies the completeness relation Sum(E^ E) = I. """ - operator = np.zeros(shape=(2 ** self._num_qubits,) * 3, dtype=np.complex128) + operator = np.zeros(shape=(2**self._num_qubits,) * 3, dtype=np.complex128) for i in range(len(operator)): operator[i, :, i] = self._state return operator diff --git a/cirq/ops/swap_gates.py b/cirq/ops/swap_gates.py index d0b556a23ca..72b9a1c41ba 100644 --- a/cirq/ops/swap_gates.py +++ b/cirq/ops/swap_gates.py @@ -112,7 +112,7 @@ def _pauli_expansion_(self) -> value.LinearDict[str]: if protocols.is_parameterized(self): return NotImplemented global_phase = 1j ** (2 * self._exponent * self._global_shift) - swap_phase = 1j ** self._exponent + swap_phase = 1j**self._exponent c = -1j * swap_phase * np.sin(np.pi * self._exponent / 2) / 2 return value.LinearDict( { diff --git a/cirq/ops/swap_gates_test.py b/cirq/ops/swap_gates_test.py index 2cdf003693a..17fd161b17b 100644 --- a/cirq/ops/swap_gates_test.py +++ b/cirq/ops/swap_gates_test.py @@ -77,8 +77,8 @@ def test_text_diagrams(): def test_swap_has_stabilizer_effect(): assert cirq.has_stabilizer_effect(cirq.SWAP) - assert cirq.has_stabilizer_effect(cirq.SWAP ** 2) - assert not cirq.has_stabilizer_effect(cirq.SWAP ** 0.5) + assert cirq.has_stabilizer_effect(cirq.SWAP**2) + assert not cirq.has_stabilizer_effect(cirq.SWAP**0.5) assert not cirq.has_stabilizer_effect(cirq.SWAP ** sympy.Symbol('foo')) @@ -139,18 +139,18 @@ def test_sqrt_iswap_inv_unitary(): def test_repr(): assert repr(cirq.SWAP) == 'cirq.SWAP' - assert repr(cirq.SWAP ** 0.5) == '(cirq.SWAP**0.5)' + assert repr(cirq.SWAP**0.5) == '(cirq.SWAP**0.5)' assert repr(cirq.ISWAP) == 'cirq.ISWAP' - assert repr(cirq.ISWAP ** 0.5) == '(cirq.ISWAP**0.5)' + assert repr(cirq.ISWAP**0.5) == '(cirq.ISWAP**0.5)' def test_str(): assert str(cirq.SWAP) == 'SWAP' - assert str(cirq.SWAP ** 0.5) == 'SWAP**0.5' + assert str(cirq.SWAP**0.5) == 'SWAP**0.5' assert str(cirq.ISWAP) == 'ISWAP' - assert str(cirq.ISWAP ** 0.5) == 'ISWAP**0.5' + assert str(cirq.ISWAP**0.5) == 'ISWAP**0.5' def test_iswap_decompose_diagram(): @@ -170,20 +170,20 @@ def test_iswap_decompose_diagram(): def test_trace_distance(): foo = sympy.Symbol('foo') - sswap = cirq.SWAP ** foo - siswap = cirq.ISWAP ** foo + sswap = cirq.SWAP**foo + siswap = cirq.ISWAP**foo # These values should have 1.0 or 0.0 directly returned assert cirq.trace_distance_bound(sswap) == 1.0 assert cirq.trace_distance_bound(siswap) == 1.0 # These values are calculated, so we use approx_eq - assert cirq.approx_eq(cirq.trace_distance_bound(cirq.SWAP ** 0.3), np.sin(0.3 * np.pi / 2)) - assert cirq.approx_eq(cirq.trace_distance_bound(cirq.ISWAP ** 0), 0.0) + assert cirq.approx_eq(cirq.trace_distance_bound(cirq.SWAP**0.3), np.sin(0.3 * np.pi / 2)) + assert cirq.approx_eq(cirq.trace_distance_bound(cirq.ISWAP**0), 0.0) def test_trace_distance_over_range_of_exponents(): for exp in np.linspace(0, 4, 20): - cirq.testing.assert_has_consistent_trace_distance_bound(cirq.SWAP ** exp) - cirq.testing.assert_has_consistent_trace_distance_bound(cirq.ISWAP ** exp) + cirq.testing.assert_has_consistent_trace_distance_bound(cirq.SWAP**exp) + cirq.testing.assert_has_consistent_trace_distance_bound(cirq.ISWAP**exp) @pytest.mark.parametrize('angle_rads', (-np.pi, -np.pi / 3, -0.1, np.pi / 5)) diff --git a/cirq/ops/three_qubit_gates.py b/cirq/ops/three_qubit_gates.py index 25e583f1f73..d32b161547b 100644 --- a/cirq/ops/three_qubit_gates.py +++ b/cirq/ops/three_qubit_gates.py @@ -69,7 +69,7 @@ def _pauli_expansion_(self) -> value.LinearDict[str]: if protocols.is_parameterized(self): return NotImplemented global_phase = 1j ** (2 * self._exponent * self._global_shift) - z_phase = 1j ** self._exponent + z_phase = 1j**self._exponent c = -1j * z_phase * np.sin(np.pi * self._exponent / 2) / 4 return value.LinearDict( { @@ -104,7 +104,7 @@ def _decompose_(self, qubits): elif not b.is_adjacent(c): a, b = b, a - p = common_gates.T ** self._exponent + p = common_gates.T**self._exponent sweep_abc = [common_gates.CNOT(a, b), common_gates.CNOT(b, c)] return [ @@ -389,7 +389,7 @@ def _pauli_expansion_(self) -> value.LinearDict[str]: if protocols.is_parameterized(self): return NotImplemented global_phase = 1j ** (2 * self._exponent * self._global_shift) - z_phase = 1j ** self._exponent + z_phase = 1j**self._exponent c = -1j * z_phase * np.sin(np.pi * self._exponent / 2) / 4 return value.LinearDict( { @@ -415,7 +415,7 @@ def _apply_unitary_(self, args: 'protocols.ApplyUnitaryArgs') -> np.ndarray: args.target_tensor *= p return protocols.apply_unitary( controlled_gate.ControlledGate( - controlled_gate.ControlledGate(pauli_gates.X ** self.exponent) + controlled_gate.ControlledGate(pauli_gates.X**self.exponent) ), protocols.ApplyUnitaryArgs(args.target_tensor, args.available_buffer, args.axes), default=NotImplemented, diff --git a/cirq/ops/three_qubit_gates_test.py b/cirq/ops/three_qubit_gates_test.py index bf9e3f4b7f4..77ecabcbb91 100644 --- a/cirq/ops/three_qubit_gates_test.py +++ b/cirq/ops/three_qubit_gates_test.py @@ -50,10 +50,10 @@ def test_consistent_protocols(gate, ignoring_global_phase): def test_init(): - assert (cirq.CCZ ** 0.5).exponent == 0.5 - assert (cirq.CCZ ** 0.25).exponent == 0.25 - assert (cirq.CCX ** 0.5).exponent == 0.5 - assert (cirq.CCX ** 0.25).exponent == 0.25 + assert (cirq.CCZ**0.5).exponent == 0.5 + assert (cirq.CCZ**0.25).exponent == 0.25 + assert (cirq.CCX**0.5).exponent == 0.5 + assert (cirq.CCX**0.25).exponent == 0.25 def test_unitary(): @@ -75,9 +75,9 @@ def test_unitary(): atol=1e-8, ) - assert cirq.has_unitary(cirq.CCX ** 0.5) + assert cirq.has_unitary(cirq.CCX**0.5) np.testing.assert_allclose( - cirq.unitary(cirq.CCX ** 0.5), + cirq.unitary(cirq.CCX**0.5), np.array( [ [1, 0, 0, 0, 0, 0, 0, 0], @@ -98,9 +98,9 @@ def test_unitary(): cirq.unitary(cirq.CCZ), np.diag([1, 1, 1, 1, 1, 1, 1, -1]), atol=1e-8 ) - assert cirq.has_unitary(cirq.CCZ ** 0.5) + assert cirq.has_unitary(cirq.CCZ**0.5) np.testing.assert_allclose( - cirq.unitary(cirq.CCZ ** 0.5), np.diag([1, 1, 1, 1, 1, 1, 1, 1j]), atol=1e-8 + cirq.unitary(cirq.CCZ**0.5), np.diag([1, 1, 1, 1, 1, 1, 1, 1j]), atol=1e-8 ) assert cirq.has_unitary(cirq.CSWAP) @@ -137,8 +137,8 @@ def test_str(): assert str(cirq.FREDKIN) == 'FREDKIN' assert str(cirq.CCZ) == 'CCZ' - assert str(cirq.CCX ** 0.5) == 'TOFFOLI**0.5' - assert str(cirq.CCZ ** 0.5) == 'CCZ**0.5' + assert str(cirq.CCX**0.5) == 'TOFFOLI**0.5' + assert str(cirq.CCZ**0.5) == 'CCZ**0.5' def test_repr(): @@ -148,8 +148,8 @@ def test_repr(): assert repr(cirq.FREDKIN) == 'cirq.FREDKIN' assert repr(cirq.CCZ) == 'cirq.CCZ' - assert repr(cirq.CCX ** 0.5) == '(cirq.TOFFOLI**0.5)' - assert repr(cirq.CCZ ** 0.5) == '(cirq.CCZ**0.5)' + assert repr(cirq.CCX**0.5) == '(cirq.TOFFOLI**0.5)' + assert repr(cirq.CCZ**0.5) == '(cirq.CCZ**0.5)' def test_eq(): @@ -300,7 +300,7 @@ def test_diagonal_exponent(): diagonal_angles = [2, 3, 5, 7, 11, 13, 17, 19] diagonal_gate = cirq.ThreeQubitDiagonalGate(diagonal_angles) - sqrt_diagonal_gate = diagonal_gate ** 0.5 + sqrt_diagonal_gate = diagonal_gate**0.5 expected_angles = [prime / 2 for prime in diagonal_angles] np.testing.assert_allclose(expected_angles, sqrt_diagonal_gate._diag_angles_radians, atol=1e-8) diff --git a/cirq/ops/two_qubit_diagonal_gate_test.py b/cirq/ops/two_qubit_diagonal_gate_test.py index 966729b01f9..f72550174de 100644 --- a/cirq/ops/two_qubit_diagonal_gate_test.py +++ b/cirq/ops/two_qubit_diagonal_gate_test.py @@ -87,7 +87,7 @@ def test_diagonal_exponent(): diagonal_angles = [2, 3, 5, 7] diagonal_gate = cirq.TwoQubitDiagonalGate(diagonal_angles) - sqrt_diagonal_gate = diagonal_gate ** 0.5 + sqrt_diagonal_gate = diagonal_gate**0.5 expected_angles = [prime / 2 for prime in diagonal_angles] assert cirq.approx_eq(sqrt_diagonal_gate, cirq.TwoQubitDiagonalGate(expected_angles)) diff --git a/cirq/optimizers/merge_interactions_test.py b/cirq/optimizers/merge_interactions_test.py index d508c50a5fd..8df5bcf561c 100644 --- a/cirq/optimizers/merge_interactions_test.py +++ b/cirq/optimizers/merge_interactions_test.py @@ -174,7 +174,7 @@ def test_optimizes_single_iswap(): def test_optimizes_tagged_partial_cz(): a, b = cirq.LineQubit.range(2) - c = cirq.Circuit((cirq.CZ ** 0.5)(a, b).with_tags('mytag')) + c = cirq.Circuit((cirq.CZ**0.5)(a, b).with_tags('mytag')) assert_optimization_not_broken(c) with cirq.testing.assert_deprecated( "Use cirq.optimize_for_target_gateset", deadline='v1.0', count=2 diff --git a/cirq/optimizers/merge_single_qubit_gates_test.py b/cirq/optimizers/merge_single_qubit_gates_test.py index 2a43b1c4377..805965c16d3 100644 --- a/cirq/optimizers/merge_single_qubit_gates_test.py +++ b/cirq/optimizers/merge_single_qubit_gates_test.py @@ -70,7 +70,7 @@ def test_combines_sequence(): assert len(opt_summary.new_operations) == 1 assert isinstance(opt_summary.new_operations[0].gate, cirq.MatrixGate) cirq.testing.assert_allclose_up_to_global_phase( - cirq.unitary(opt_summary.new_operations[0]), cirq.unitary(cirq.Y ** 0.5), atol=1e-7 + cirq.unitary(opt_summary.new_operations[0]), cirq.unitary(cirq.Y**0.5), atol=1e-7 ) diff --git a/cirq/protocols/circuit_diagram_info_protocol.py b/cirq/protocols/circuit_diagram_info_protocol.py index 61ae35661ea..9718617a6c7 100644 --- a/cirq/protocols/circuit_diagram_info_protocol.py +++ b/cirq/protocols/circuit_diagram_info_protocol.py @@ -146,7 +146,7 @@ def _formatted_exponent( # funky behavior of fraction, cast to str in constructor helps. approx_frac = Fraction(self.exponent).limit_denominator(16) if approx_frac.denominator not in [2, 4, 5, 10]: - if abs(float(approx_frac) - self.exponent) < 10 ** -args.precision: + if abs(float(approx_frac) - self.exponent) < 10**-args.precision: return f'({approx_frac})' return args.format_real(self.exponent) diff --git a/cirq/protocols/json_serialization_test.py b/cirq/protocols/json_serialization_test.py index c69a0a017d0..c1c5eb6d2e8 100644 --- a/cirq/protocols/json_serialization_test.py +++ b/cirq/protocols/json_serialization_test.py @@ -412,7 +412,7 @@ def test_sympy(): assert_json_roundtrip_works(t * s) assert_json_roundtrip_works(t / s) assert_json_roundtrip_works(t - s) - assert_json_roundtrip_works(t ** s) + assert_json_roundtrip_works(t**s) # Linear combinations. assert_json_roundtrip_works(t * 2) diff --git a/cirq/protocols/pow_protocol_test.py b/cirq/protocols/pow_protocol_test.py index bce9ddd5389..12185ee003b 100644 --- a/cirq/protocols/pow_protocol_test.py +++ b/cirq/protocols/pow_protocol_test.py @@ -65,5 +65,5 @@ def test_pow_error(): ) def test_pow_with_result(val, exponent, out): assert ( - cirq.pow(val, exponent) == cirq.pow(val, exponent, default=None) == val ** exponent == out + cirq.pow(val, exponent) == cirq.pow(val, exponent, default=None) == val**exponent == out ) diff --git a/cirq/protocols/qid_shape_protocol.py b/cirq/protocols/qid_shape_protocol.py index fa145b17149..bb300496616 100644 --- a/cirq/protocols/qid_shape_protocol.py +++ b/cirq/protocols/qid_shape_protocol.py @@ -27,7 +27,7 @@ # user provides a different (0,) value. RaiseTypeErrorIfNotProvided: Any = (0,) # Equal integers outside the range [-5, 256] aren't identically equal with `is`. -RaiseTypeErrorIfNotProvidedInt: Any = -(2 ** 512) +RaiseTypeErrorIfNotProvidedInt: Any = -(2**512) TDefault = TypeVar('TDefault') diff --git a/cirq/protocols/trace_distance_bound.py b/cirq/protocols/trace_distance_bound.py index 8e833e78c61..69cd6ee89cf 100644 --- a/cirq/protocols/trace_distance_bound.py +++ b/cirq/protocols/trace_distance_bound.py @@ -104,7 +104,7 @@ def _strat_distance_from_unitary(val: Any) -> Optional[float]: squared = 1 - (0.5 * abs(u[0][0] + u[1][1])) ** 2 if squared <= 0: return 0.0 - return squared ** 0.5 + return squared**0.5 return trace_distance_from_angle_list(np.angle(np.linalg.eigvals(u))) diff --git a/cirq/protocols/trace_distance_bound_test.py b/cirq/protocols/trace_distance_bound_test.py index 73b7a9e2832..0a7aa2ccc69 100644 --- a/cirq/protocols/trace_distance_bound_test.py +++ b/cirq/protocols/trace_distance_bound_test.py @@ -37,11 +37,11 @@ def _trace_distance_bound_(self) -> float: x = cirq.MatrixGate(cirq.unitary(cirq.X)) cx = cirq.MatrixGate(cirq.unitary(cirq.CX)) - cxh = cirq.MatrixGate(cirq.unitary(cirq.CX ** 0.5)) + cxh = cirq.MatrixGate(cirq.unitary(cirq.CX**0.5)) assert np.isclose(cirq.trace_distance_bound(x), cirq.trace_distance_bound(cirq.X)) assert np.isclose(cirq.trace_distance_bound(cx), cirq.trace_distance_bound(cirq.CX)) - assert np.isclose(cirq.trace_distance_bound(cxh), cirq.trace_distance_bound(cirq.CX ** 0.5)) + assert np.isclose(cirq.trace_distance_bound(cxh), cirq.trace_distance_bound(cirq.CX**0.5)) assert cirq.trace_distance_bound(NoMethod()) == 1.0 assert cirq.trace_distance_bound(ReturnsNotImplemented()) == 1.0 assert cirq.trace_distance_bound(ReturnsTwo()) == 1.0 diff --git a/cirq/qis/channels_test.py b/cirq/qis/channels_test.py index 28ccab03540..6856684be9e 100644 --- a/cirq/qis/channels_test.py +++ b/cirq/qis/channels_test.py @@ -252,7 +252,7 @@ def test_operation_to_choi(channel): n_qubits = cirq.num_qubits(channel) actual = cirq.operation_to_choi(channel) expected = compute_choi(channel) - assert np.isclose(np.trace(actual), 2 ** n_qubits) + assert np.isclose(np.trace(actual), 2**n_qubits) assert np.all(actual == expected) diff --git a/cirq/qis/clifford_tableau_test.py b/cirq/qis/clifford_tableau_test.py index 06f7aba3120..b8d5add1d47 100644 --- a/cirq/qis/clifford_tableau_test.py +++ b/cirq/qis/clifford_tableau_test.py @@ -45,7 +45,7 @@ def _CNOT(table, q1, q2): @pytest.mark.parametrize('num_qubits', range(1, 4)) def test_tableau_initial_state_string(num_qubits): - for i in range(2 ** num_qubits): + for i in range(2**num_qubits): t = cirq.CliffordTableau(initial_state=i, num_qubits=num_qubits) splitted_represent_string = str(t).split('\n') assert len(splitted_represent_string) == num_qubits @@ -179,7 +179,7 @@ def test_measurement(): def test_validate_tableau(): num_qubits = 4 - for i in range(2 ** num_qubits): + for i in range(2**num_qubits): t = cirq.CliffordTableau(initial_state=i, num_qubits=num_qubits) assert t._validate() diff --git a/cirq/qis/measures.py b/cirq/qis/measures.py index 38602bca319..06da5f8cb13 100644 --- a/cirq/qis/measures.py +++ b/cirq/qis/measures.py @@ -120,7 +120,7 @@ def fidelity( for q, s1 in state1: s2 = state2[q] prod *= np.abs(np.vdot(s1.state_vector(), s2.state_vector())) - return prod ** 2 + return prod**2 # Two numpy arrays that are either state vector, state tensor, or # density matrix @@ -244,7 +244,7 @@ def _fidelity_state_vectors_or_density_matrices(state1: np.ndarray, state2: np.n state1_sqrt = _sqrt_positive_semidefinite_matrix(state1) eigs = linalg.eigvalsh(state1_sqrt @ state2 @ state1_sqrt) trace = np.sum(np.sqrt(np.abs(eigs))) - return trace ** 2 + return trace**2 raise ValueError( 'The given arrays must be one- or two-dimensional. ' f'Got shapes {state1.shape} and {state2.shape}.' @@ -310,4 +310,4 @@ def entanglement_fidelity(operation: 'cirq.SupportsKraus') -> float: for k in protocols.kraus(operation): f += np.abs(np.trace(k)) ** 2 n_qubits = protocols.num_qubits(operation) - return float(f / 4 ** n_qubits) + return float(f / 4**n_qubits) diff --git a/cirq/qis/states_test.py b/cirq/qis/states_test.py index 5088b887e82..518fd51ec48 100644 --- a/cirq/qis/states_test.py +++ b/cirq/qis/states_test.py @@ -198,37 +198,28 @@ def test_infer_qid_shape(): q0, q1 = cirq.LineQubit.range(2) product_state_1 = cirq.KET_PLUS(q0) * cirq.KET_PLUS(q1) - assert ( - cirq.qis.infer_qid_shape( - computational_basis_state_1, - state_vector_1, - state_tensor_1, - density_matrix_1, - product_state_1, - ) - == (2, 2) - ) + assert cirq.qis.infer_qid_shape( + computational_basis_state_1, + state_vector_1, + state_tensor_1, + density_matrix_1, + product_state_1, + ) == (2, 2) - assert ( - cirq.qis.infer_qid_shape( - product_state_1, - density_matrix_1, - state_tensor_1, - state_vector_1, - computational_basis_state_1, - ) - == (2, 2) - ) + assert cirq.qis.infer_qid_shape( + product_state_1, + density_matrix_1, + state_tensor_1, + state_vector_1, + computational_basis_state_1, + ) == (2, 2) - assert ( - cirq.qis.infer_qid_shape( - computational_basis_state_1, - computational_basis_state_2, - computational_basis_state_4, - state_tensor_2, - ) - == (1, 2, 3, 4) - ) + assert cirq.qis.infer_qid_shape( + computational_basis_state_1, + computational_basis_state_2, + computational_basis_state_4, + state_tensor_2, + ) == (1, 2, 3, 4) assert cirq.qis.infer_qid_shape( state_vector_2, density_matrix_2, computational_basis_state_4 @@ -499,7 +490,7 @@ def test_to_valid_state_vector(): np.testing.assert_almost_equal(cirq.to_valid_state_vector(1, 2), np.array([0.0, 1.0, 0.0, 0.0])) v = cirq.to_valid_state_vector([0, 1, 2, 0], qid_shape=(3, 3, 3, 3)) - assert v.shape == (3 ** 4,) + assert v.shape == (3**4,) assert v[6 + 9] == 1 v = cirq.to_valid_state_vector([False, True, False, False], num_qubits=4) diff --git a/cirq/sim/clifford/act_on_stabilizer_ch_form_args_test.py b/cirq/sim/clifford/act_on_stabilizer_ch_form_args_test.py index 13133a0b44e..7c9629427a3 100644 --- a/cirq/sim/clifford/act_on_stabilizer_ch_form_args_test.py +++ b/cirq/sim/clifford/act_on_stabilizer_ch_form_args_test.py @@ -95,7 +95,7 @@ def num_qubits(self) -> int: return 1 def _unitary_(self): - return np.array([[1, 1], [1, -1]]) / (2 ** 0.5) + return np.array([[1, 1], [1, -1]]) / (2**0.5) args = cirq.ActOnStabilizerCHFormArgs( qubits=cirq.LineQubit.range(3), diff --git a/cirq/sim/clifford/stabilizer_state_ch_form.py b/cirq/sim/clifford/stabilizer_state_ch_form.py index ad6c3c63945..3f2827b6359 100644 --- a/cirq/sim/clifford/stabilizer_state_ch_form.py +++ b/cirq/sim/clifford/stabilizer_state_ch_form.py @@ -117,15 +117,15 @@ def inner_product_of_state_and_x(self, x: int) -> Union[float, complex]: return ( self.omega * 2 ** (-sum(self.v) / 2) - * 1j ** mu + * 1j**mu * (-1) ** sum(self.v & u & self.s) * np.all(self.v | (u == self.s)) ) def state_vector(self) -> np.ndarray: - wf = np.zeros(2 ** self.n, dtype=complex) + wf = np.zeros(2**self.n, dtype=complex) - for x in range(2 ** self.n): + for x in range(2**self.n): wf[x] = self.inner_product_of_state_and_x(x) return wf @@ -154,7 +154,7 @@ def update_sum(self, t, u, delta=0, alpha=0): """ if np.all(t == u): self.s = t - self.omega *= 1 / np.sqrt(2) * (-1) ** alpha * (1 + 1j ** delta) + self.omega *= 1 / np.sqrt(2) * (-1) ** alpha * (1 + 1j**delta) return set0 = np.where((~self.v) & (t ^ u))[0] set1 = np.where(self.v & (t ^ u))[0] @@ -221,7 +221,7 @@ def _H_decompose(self, v, y, z, delta): c = bool(delta >> 1) omega = (-1) ** (c & y) else: - omega = 1 / np.sqrt(2) * (1 + 1j ** delta) + omega = 1 / np.sqrt(2) * (1 + 1j**delta) b = True a = True c = not ((delta >> 1) ^ y) @@ -229,7 +229,7 @@ def _H_decompose(self, v, y, z, delta): return omega, a, b, c def to_state_vector(self) -> np.ndarray: - arr = np.zeros(2 ** self.n, dtype=complex) + arr = np.zeros(2**self.n, dtype=complex) for x in range(len(arr)): arr[x] = self.inner_product_of_state_and_x(x) @@ -310,7 +310,7 @@ def apply_y(self, axis: int, exponent: float = 1, global_shift: float = 0): elif exponent % 2 == 0.5: self.apply_z(axis) self.apply_h(axis) - self.omega *= shift * (1 + 1j) / (2 ** 0.5) + self.omega *= shift * (1 + 1j) / (2**0.5) elif exponent % 2 == 1: self.apply_z(axis) self.apply_h(axis) @@ -320,7 +320,7 @@ def apply_y(self, axis: int, exponent: float = 1, global_shift: float = 0): elif exponent % 2 == 1.5: self.apply_h(axis) self.apply_z(axis) - self.omega *= shift * (1 - 1j) / (2 ** 0.5) + self.omega *= shift * (1 - 1j) / (2**0.5) def apply_z(self, axis: int, exponent: float = 1, global_shift: float = 0): if exponent % 2 != 0: diff --git a/cirq/sim/density_matrix_simulator_test.py b/cirq/sim/density_matrix_simulator_test.py index 86aa6d1ae65..da0a6d7c425 100644 --- a/cirq/sim/density_matrix_simulator_test.py +++ b/cirq/sim/density_matrix_simulator_test.py @@ -121,7 +121,7 @@ def test_run_bit_flips(dtype: Type[np.number], split: bool): for b0 in [0, 1]: for b1 in [0, 1]: circuit = cirq.Circuit( - (cirq.X ** b0)(q0), (cirq.X ** b1)(q1), cirq.measure(q0), cirq.measure(q1) + (cirq.X**b0)(q0), (cirq.X**b1)(q1), cirq.measure(q0), cirq.measure(q1) ) result = simulator.run(circuit) np.testing.assert_equal(result.measurements, {'0': [[b0]], '1': [[b1]]}) @@ -135,7 +135,7 @@ def test_run_bit_flips_with_dephasing(dtype: Type[np.number], split: bool): for b0 in [0, 1]: for b1 in [0, 1]: circuit = cirq.Circuit( - (cirq.X ** b0)(q0), (cirq.X ** b1)(q1), cirq.measure(q0), cirq.measure(q1) + (cirq.X**b0)(q0), (cirq.X**b1)(q1), cirq.measure(q0), cirq.measure(q1) ) result = simulator.run(circuit) np.testing.assert_equal(result.measurements, {'0': [[b0]], '1': [[b1]]}) @@ -261,9 +261,9 @@ def _qid_shape_(self): def _kraus_(self): return [ - np.array([[1, 0, 0], [0, 0.5 ** 0.5, 0], [0, 0, 0.5 ** 0.5]]), - np.array([[0, 0.5 ** 0.5, 0], [0, 0, 0], [0, 0, 0]]), - np.array([[0, 0, 0], [0, 0, 0.5 ** 0.5], [0, 0, 0]]), + np.array([[1, 0, 0], [0, 0.5**0.5, 0], [0, 0, 0.5**0.5]]), + np.array([[0, 0.5**0.5, 0], [0, 0, 0], [0, 0, 0]]), + np.array([[0, 0, 0], [0, 0, 0.5**0.5], [0, 0, 0]]), ] q0, q1 = cirq.LineQid.for_qid_shape((3, 4)) @@ -293,7 +293,7 @@ def test_run_measure_at_end_no_repetitions(dtype: Type[np.number], split: bool): for b0 in [0, 1]: for b1 in [0, 1]: circuit = cirq.Circuit( - (cirq.X ** b0)(q0), (cirq.X ** b1)(q1), cirq.measure(q0), cirq.measure(q1) + (cirq.X**b0)(q0), (cirq.X**b1)(q1), cirq.measure(q0), cirq.measure(q1) ) result = simulator.run(circuit, repetitions=0) np.testing.assert_equal( @@ -312,7 +312,7 @@ def test_run_repetitions_measure_at_end(dtype: Type[np.number], split: bool): for b0 in [0, 1]: for b1 in [0, 1]: circuit = cirq.Circuit( - (cirq.X ** b0)(q0), (cirq.X ** b1)(q1), cirq.measure(q0), cirq.measure(q1) + (cirq.X**b0)(q0), (cirq.X**b1)(q1), cirq.measure(q0), cirq.measure(q1) ) result = simulator.run(circuit, repetitions=3) np.testing.assert_equal(result.measurements, {'0': [[b0]] * 3, '1': [[b1]] * 3}) @@ -329,7 +329,7 @@ def test_run_qudits_repetitions_measure_at_end(dtype: Type[np.number], split: bo for b0 in [0, 1]: for b1 in [0, 1, 2]: circuit = cirq.Circuit( - (cirq.X ** b0)(q0), PlusGate(3, b1)(q1), cirq.measure(q0), cirq.measure(q1) + (cirq.X**b0)(q0), PlusGate(3, b1)(q1), cirq.measure(q0), cirq.measure(q1) ) result = simulator.run(circuit, repetitions=3) np.testing.assert_equal( @@ -348,8 +348,8 @@ def test_run_measurement_not_terminal_no_repetitions(dtype: Type[np.number], spl for b0 in [0, 1]: for b1 in [0, 1]: circuit = cirq.Circuit( - (cirq.X ** b0)(q0), - (cirq.X ** b1)(q1), + (cirq.X**b0)(q0), + (cirq.X**b1)(q1), cirq.measure(q0), cirq.measure(q1), cirq.H(q0), @@ -372,8 +372,8 @@ def test_run_repetitions_measurement_not_terminal(dtype: Type[np.number], split: for b0 in [0, 1]: for b1 in [0, 1]: circuit = cirq.Circuit( - (cirq.X ** b0)(q0), - (cirq.X ** b1)(q1), + (cirq.X**b0)(q0), + (cirq.X**b1)(q1), cirq.measure(q0), cirq.measure(q1), cirq.H(q0), @@ -394,7 +394,7 @@ def test_run_qudits_repetitions_measurement_not_terminal(dtype: Type[np.number], for b0 in [0, 1]: for b1 in [0, 1, 2]: circuit = cirq.Circuit( - (cirq.X ** b0)(q0), + (cirq.X**b0)(q0), PlusGate(3, b1)(q1), cirq.measure(q0), cirq.measure(q1), @@ -448,7 +448,7 @@ def test_run_measure_multiple_qubits(dtype: Type[np.number], split: bool): simulator = cirq.DensityMatrixSimulator(dtype=dtype, split_untangled_states=split) for b0 in [0, 1]: for b1 in [0, 1]: - circuit = cirq.Circuit((cirq.X ** b0)(q0), (cirq.X ** b1)(q1), cirq.measure(q0, q1)) + circuit = cirq.Circuit((cirq.X**b0)(q0), (cirq.X**b1)(q1), cirq.measure(q0, q1)) result = simulator.run(circuit, repetitions=3) np.testing.assert_equal(result.measurements, {'0,1': [[b0, b1]] * 3}) @@ -460,7 +460,7 @@ def test_run_measure_multiple_qudits(dtype: Type[np.number], split: bool): simulator = cirq.DensityMatrixSimulator(dtype=dtype, split_untangled_states=split) for b0 in [0, 1]: for b1 in [0, 1, 2]: - circuit = cirq.Circuit((cirq.X ** b0)(q0), PlusGate(3, b1)(q1), cirq.measure(q0, q1)) + circuit = cirq.Circuit((cirq.X**b0)(q0), PlusGate(3, b1)(q1), cirq.measure(q0, q1)) result = simulator.run(circuit, repetitions=3) np.testing.assert_equal(result.measurements, {'0 (d=2),1 (d=3)': [[b0, b1]] * 3}) @@ -628,7 +628,7 @@ def test_simulate_bit_flips(dtype: Type[np.number], split: bool): for b0 in [0, 1]: for b1 in [0, 1]: circuit = cirq.Circuit( - (cirq.X ** b0)(q0), (cirq.X ** b1)(q1), cirq.measure(q0), cirq.measure(q1) + (cirq.X**b0)(q0), (cirq.X**b1)(q1), cirq.measure(q0), cirq.measure(q1) ) result = simulator.simulate(circuit) np.testing.assert_equal(result.measurements, {'0': [b0], '1': [b1]}) @@ -645,7 +645,7 @@ def test_simulate_qudit_increments(dtype: Type[np.number], split: bool): for b0 in [0, 1]: for b1 in [0, 1, 2]: circuit = cirq.Circuit( - (cirq.X ** b0)(q0), (PlusGate(3)(q1),) * b1, cirq.measure(q0), cirq.measure(q1) + (cirq.X**b0)(q0), (PlusGate(3)(q1),) * b1, cirq.measure(q0), cirq.measure(q1) ) result = simulator.simulate(circuit) np.testing.assert_equal(result.measurements, {'0 (d=2)': [b0], '1 (d=3)': [b1]}) @@ -661,7 +661,7 @@ def test_simulate_initial_state(dtype: Type[np.number], split: bool): simulator = cirq.DensityMatrixSimulator(dtype=dtype, split_untangled_states=split) for b0 in [0, 1]: for b1 in [0, 1]: - circuit = cirq.Circuit((cirq.X ** b0)(q0), (cirq.X ** b1)(q1)) + circuit = cirq.Circuit((cirq.X**b0)(q0), (cirq.X**b1)(q1)) result = simulator.simulate(circuit, initial_state=1) expected_density_matrix = np.zeros(shape=(4, 4)) expected_density_matrix[b0 * 2 + 1 - b1, b0 * 2 + 1 - b1] = 1.0 @@ -675,7 +675,7 @@ def test_simulate_act_on_args(dtype: Type[np.number], split: bool): simulator = cirq.DensityMatrixSimulator(dtype=dtype, split_untangled_states=split) for b0 in [0, 1]: for b1 in [0, 1]: - circuit = cirq.Circuit((cirq.X ** b0)(q0), (cirq.X ** b1)(q1)) + circuit = cirq.Circuit((cirq.X**b0)(q0), (cirq.X**b1)(q1)) args = simulator._create_act_on_args(initial_state=1, qubits=(q0, q1)) result = simulator.simulate(circuit, initial_state=args) expected_density_matrix = np.zeros(shape=(4, 4)) @@ -688,7 +688,7 @@ def test_simulate_tps_initial_state(): simulator = cirq.DensityMatrixSimulator() for b0 in [0, 1]: for b1 in [0, 1]: - circuit = cirq.Circuit((cirq.X ** b0)(q0), (cirq.X ** b1)(q1)) + circuit = cirq.Circuit((cirq.X**b0)(q0), (cirq.X**b1)(q1)) result = simulator.simulate(circuit, initial_state=cirq.KET_ZERO(q0) * cirq.KET_ONE(q1)) expected_density_matrix = np.zeros(shape=(4, 4)) expected_density_matrix[b0 * 2 + 1 - b1, b0 * 2 + 1 - b1] = 1.0 @@ -721,7 +721,7 @@ def test_simulate_qubit_order(dtype: Type[np.number], split: bool): simulator = cirq.DensityMatrixSimulator(dtype=dtype, split_untangled_states=split) for b0 in [0, 1]: for b1 in [0, 1]: - circuit = cirq.Circuit((cirq.X ** b0)(q0), (cirq.X ** b1)(q1)) + circuit = cirq.Circuit((cirq.X**b0)(q0), (cirq.X**b1)(q1)) result = simulator.simulate(circuit, qubit_order=[q1, q0]) expected_density_matrix = np.zeros(shape=(4, 4)) expected_density_matrix[2 * b1 + b0, 2 * b1 + b0] = 1.0 @@ -754,7 +754,7 @@ def test_simulate_measure_multiple_qubits(dtype: Type[np.number], split: bool): simulator = cirq.DensityMatrixSimulator(dtype=dtype, split_untangled_states=split) for b0 in [0, 1]: for b1 in [0, 1]: - circuit = cirq.Circuit((cirq.X ** b0)(q0), (cirq.X ** b1)(q1), cirq.measure(q0, q1)) + circuit = cirq.Circuit((cirq.X**b0)(q0), (cirq.X**b1)(q1), cirq.measure(q0, q1)) result = simulator.simulate(circuit) np.testing.assert_equal(result.measurements, {'0,1': [b0, b1]}) @@ -766,7 +766,7 @@ def test_simulate_measure_multiple_qudits(dtype: Type[np.number], split: bool): simulator = cirq.DensityMatrixSimulator(dtype=dtype, split_untangled_states=split) for b0 in [0, 1]: for b1 in [0, 1, 2]: - circuit = cirq.Circuit((cirq.X ** b0)(q0), PlusGate(3, b1)(q1), cirq.measure(q0, q1)) + circuit = cirq.Circuit((cirq.X**b0)(q0), PlusGate(3, b1)(q1), cirq.measure(q0, q1)) result = simulator.simulate(circuit) np.testing.assert_equal(result.measurements, {'0 (d=2),1 (d=3)': [b0, b1]}) @@ -1112,30 +1112,24 @@ def test_density_matrix_trial_result_qid_shape(): final_step_result._simulator_state.return_value = cirq.DensityMatrixSimulatorState( density_matrix=np.ones((4, 4)) / 4, qubit_map={q0: 0, q1: 1} ) - assert ( - cirq.qid_shape( - cirq.DensityMatrixTrialResult( - params=cirq.ParamResolver({}), - measurements={}, - final_step_result=final_step_result, - ), - ) - == (2, 2) - ) + assert cirq.qid_shape( + cirq.DensityMatrixTrialResult( + params=cirq.ParamResolver({}), + measurements={}, + final_step_result=final_step_result, + ), + ) == (2, 2) q0, q1 = cirq.LineQid.for_qid_shape((3, 4)) final_step_result._simulator_state.return_value = cirq.DensityMatrixSimulatorState( density_matrix=np.ones((12, 12)) / 12, qubit_map={q0: 0, q1: 1} ) - assert ( - cirq.qid_shape( - cirq.DensityMatrixTrialResult( - params=cirq.ParamResolver({}), - measurements={}, - final_step_result=final_step_result, - ), - ) - == (3, 4) - ) + assert cirq.qid_shape( + cirq.DensityMatrixTrialResult( + params=cirq.ParamResolver({}), + measurements={}, + final_step_result=final_step_result, + ), + ) == (3, 4) def test_density_matrix_trial_result_repr(): diff --git a/cirq/sim/density_matrix_utils_test.py b/cirq/sim/density_matrix_utils_test.py index da8d672a04a..80e72ef07ee 100644 --- a/cirq/sim/density_matrix_utils_test.py +++ b/cirq/sim/density_matrix_utils_test.py @@ -248,7 +248,7 @@ def test_measure_density_matrix_collapse(): def test_measure_density_matrix_seed(): n = 5 - matrix = np.eye(2 ** n) / 2 ** n + matrix = np.eye(2**n) / 2**n bits, out_matrix1 = cirq.measure_density_matrix(matrix, range(n), seed=1234) assert bits == [False, False, True, True, False] diff --git a/cirq/sim/mux_test.py b/cirq/sim/mux_test.py index c76919a5686..2b47840cacb 100644 --- a/cirq/sim/mux_test.py +++ b/cirq/sim/mux_test.py @@ -197,10 +197,10 @@ def test_final_state_vector_param_resolver(): s = sympy.Symbol('s') with pytest.raises(ValueError, match='not unitary'): - _ = cirq.final_state_vector(cirq.X ** s) + _ = cirq.final_state_vector(cirq.X**s) np.testing.assert_allclose( - cirq.final_state_vector(cirq.X ** s, param_resolver={s: 0.5}), [0.5 + 0.5j, 0.5 - 0.5j] + cirq.final_state_vector(cirq.X**s, param_resolver={s: 0.5}), [0.5 + 0.5j, 0.5 - 0.5j] ) @@ -312,10 +312,10 @@ def test_final_density_matrix_param_resolver(): s = sympy.Symbol('s') with pytest.raises(ValueError, match='not specified in parameter sweep'): - _ = cirq.final_density_matrix(cirq.X ** s) + _ = cirq.final_density_matrix(cirq.X**s) np.testing.assert_allclose( - cirq.final_density_matrix(cirq.X ** s, param_resolver={s: 0.5}), + cirq.final_density_matrix(cirq.X**s, param_resolver={s: 0.5}), [[0.5 - 0.0j, 0.0 + 0.5j], [0.0 - 0.5j, 0.5 - 0.0j]], ) diff --git a/cirq/sim/sparse_simulator_test.py b/cirq/sim/sparse_simulator_test.py index decc516ca42..4ebee4f32eb 100644 --- a/cirq/sim/sparse_simulator_test.py +++ b/cirq/sim/sparse_simulator_test.py @@ -85,7 +85,7 @@ def test_run_bit_flips(dtype: Type[np.number], split: bool): for b0 in [0, 1]: for b1 in [0, 1]: circuit = cirq.Circuit( - (cirq.X ** b0)(q0), (cirq.X ** b1)(q1), cirq.measure(q0), cirq.measure(q1) + (cirq.X**b0)(q0), (cirq.X**b1)(q1), cirq.measure(q0), cirq.measure(q1) ) result = simulator.run(circuit) np.testing.assert_equal(result.measurements, {'0': [[b0]], '1': [[b1]]}) @@ -100,7 +100,7 @@ def test_run_measure_at_end_no_repetitions(dtype: Type[np.number], split: bool): for b0 in [0, 1]: for b1 in [0, 1]: circuit = cirq.Circuit( - (cirq.X ** b0)(q0), (cirq.X ** b1)(q1), cirq.measure(q0), cirq.measure(q1) + (cirq.X**b0)(q0), (cirq.X**b1)(q1), cirq.measure(q0), cirq.measure(q1) ) result = simulator.run(circuit, repetitions=0) np.testing.assert_equal( @@ -126,7 +126,7 @@ def test_run_repetitions_measure_at_end(dtype: Type[np.number], split: bool): for b0 in [0, 1]: for b1 in [0, 1]: circuit = cirq.Circuit( - (cirq.X ** b0)(q0), (cirq.X ** b1)(q1), cirq.measure(q0), cirq.measure(q1) + (cirq.X**b0)(q0), (cirq.X**b1)(q1), cirq.measure(q0), cirq.measure(q1) ) result = simulator.run(circuit, repetitions=3) np.testing.assert_equal(result.measurements, {'0': [[b0]] * 3, '1': [[b1]] * 3}) @@ -144,8 +144,8 @@ def test_run_invert_mask_measure_not_terminal(dtype: Type[np.number], split: boo for b0 in [0, 1]: for b1 in [0, 1]: circuit = cirq.Circuit( - (cirq.X ** b0)(q0), - (cirq.X ** b1)(q1), + (cirq.X**b0)(q0), + (cirq.X**b1)(q1), cirq.measure(q0, q1, key='m', invert_mask=(True, False)), cirq.X(q0), ) @@ -165,8 +165,8 @@ def test_run_partial_invert_mask_measure_not_terminal(dtype: Type[np.number], sp for b0 in [0, 1]: for b1 in [0, 1]: circuit = cirq.Circuit( - (cirq.X ** b0)(q0), - (cirq.X ** b1)(q1), + (cirq.X**b0)(q0), + (cirq.X**b1)(q1), cirq.measure(q0, q1, key='m', invert_mask=(True,)), cirq.X(q0), ) @@ -186,8 +186,8 @@ def test_run_measurement_not_terminal_no_repetitions(dtype: Type[np.number], spl for b0 in [0, 1]: for b1 in [0, 1]: circuit = cirq.Circuit( - (cirq.X ** b0)(q0), - (cirq.X ** b1)(q1), + (cirq.X**b0)(q0), + (cirq.X**b1)(q1), cirq.measure(q0), cirq.measure(q1), cirq.H(q0), @@ -210,8 +210,8 @@ def test_run_repetitions_measurement_not_terminal(dtype: Type[np.number], split: for b0 in [0, 1]: for b1 in [0, 1]: circuit = cirq.Circuit( - (cirq.X ** b0)(q0), - (cirq.X ** b1)(q1), + (cirq.X**b0)(q0), + (cirq.X**b1)(q1), cirq.measure(q0), cirq.measure(q1), cirq.H(q0), @@ -283,7 +283,7 @@ def test_run_measure_multiple_qubits(dtype: Type[np.number], split: bool): simulator = cirq.Simulator(dtype=dtype, split_untangled_states=split) for b0 in [0, 1]: for b1 in [0, 1]: - circuit = cirq.Circuit((cirq.X ** b0)(q0), (cirq.X ** b1)(q1), cirq.measure(q0, q1)) + circuit = cirq.Circuit((cirq.X**b0)(q0), (cirq.X**b1)(q1), cirq.measure(q0, q1)) result = simulator.run(circuit, repetitions=3) np.testing.assert_equal(result.measurements, {'0,1': [[b0, b1]] * 3}) @@ -443,7 +443,7 @@ def test_simulate_bit_flips(dtype: Type[np.number], split: bool): for b0 in [0, 1]: for b1 in [0, 1]: circuit = cirq.Circuit( - (cirq.X ** b0)(q0), (cirq.X ** b1)(q1), cirq.measure(q0), cirq.measure(q1) + (cirq.X**b0)(q0), (cirq.X**b1)(q1), cirq.measure(q0), cirq.measure(q1) ) result = simulator.simulate(circuit) np.testing.assert_equal(result.measurements, {'0': [b0], '1': [b1]}) @@ -459,7 +459,7 @@ def test_simulate_initial_state(dtype: Type[np.number], split: bool): simulator = cirq.Simulator(dtype=dtype, split_untangled_states=split) for b0 in [0, 1]: for b1 in [0, 1]: - circuit = cirq.Circuit((cirq.X ** b0)(q0), (cirq.X ** b1)(q1)) + circuit = cirq.Circuit((cirq.X**b0)(q0), (cirq.X**b1)(q1)) result = simulator.simulate(circuit, initial_state=1) expected_state = np.zeros(shape=(2, 2)) expected_state[b0][1 - b1] = 1.0 @@ -473,7 +473,7 @@ def test_simulate_act_on_args(dtype: Type[np.number], split: bool): simulator = cirq.Simulator(dtype=dtype, split_untangled_states=split) for b0 in [0, 1]: for b1 in [0, 1]: - circuit = cirq.Circuit((cirq.X ** b0)(q0), (cirq.X ** b1)(q1)) + circuit = cirq.Circuit((cirq.X**b0)(q0), (cirq.X**b1)(q1)) args = simulator._create_act_on_args(initial_state=1, qubits=(q0, q1)) result = simulator.simulate(circuit, initial_state=args) expected_state = np.zeros(shape=(2, 2)) @@ -488,7 +488,7 @@ def test_simulate_qubit_order(dtype: Type[np.number], split: bool): simulator = cirq.Simulator(dtype=dtype, split_untangled_states=split) for b0 in [0, 1]: for b1 in [0, 1]: - circuit = cirq.Circuit((cirq.X ** b0)(q0), (cirq.X ** b1)(q1)) + circuit = cirq.Circuit((cirq.X**b0)(q0), (cirq.X**b1)(q1)) result = simulator.simulate(circuit, qubit_order=[q1, q0]) expected_state = np.zeros(shape=(2, 2)) expected_state[b1][b0] = 1.0 @@ -521,7 +521,7 @@ def test_simulate_measure_multiple_qubits(dtype: Type[np.number], split: bool): simulator = cirq.Simulator(dtype=dtype, split_untangled_states=split) for b0 in [0, 1]: for b1 in [0, 1]: - circuit = cirq.Circuit((cirq.X ** b0)(q0), (cirq.X ** b1)(q1), cirq.measure(q0, q1)) + circuit = cirq.Circuit((cirq.X**b0)(q0), (cirq.X**b1)(q1), cirq.measure(q0, q1)) result = simulator.simulate(circuit) np.testing.assert_equal(result.measurements, {'0,1': [b0, b1]}) diff --git a/cirq/sim/state_vector_simulator_test.py b/cirq/sim/state_vector_simulator_test.py index 69911517b8c..789224f975e 100644 --- a/cirq/sim/state_vector_simulator_test.py +++ b/cirq/sim/state_vector_simulator_test.py @@ -176,7 +176,7 @@ def test_str_big(): args = cirq.ActOnStateVectorArgs( prng=np.random.RandomState(0), qubits=qs, - initial_state=np.array([1] * 2 ** 10, dtype=np.complex64) * 0.03125, + initial_state=np.array([1] * 2**10, dtype=np.complex64) * 0.03125, dtype=np.complex64, ) final_step_result = cirq.SparseSimulatorStep(args, cirq.Simulator()) diff --git a/cirq/sim/state_vector_test.py b/cirq/sim/state_vector_test.py index b0af39559cc..7c5928d1948 100644 --- a/cirq/sim/state_vector_test.py +++ b/cirq/sim/state_vector_test.py @@ -244,7 +244,7 @@ def test_measure_state_collapse(): def test_measure_state_seed(): n = 10 - initial_state = np.ones(2 ** n) / 2 ** (n / 2) + initial_state = np.ones(2**n) / 2 ** (n / 2) bits, state1 = cirq.measure_state_vector(initial_state, range(n), seed=1234) np.testing.assert_equal( diff --git a/cirq/testing/consistent_phase_by_test.py b/cirq/testing/consistent_phase_by_test.py index 5bf4bf51bb8..03c9f46eff7 100644 --- a/cirq/testing/consistent_phase_by_test.py +++ b/cirq/testing/consistent_phase_by_test.py @@ -24,7 +24,7 @@ def __init__(self, e): self.e = e def _unitary_(self): - return np.array([[0, 1j ** -self.e], [1j ** self.e, 0]]) + return np.array([[0, 1j**-self.e], [1j**self.e, 0]]) def _phase_by_(self, phase_turns: float, qubit_index: int): return GoodPhaser(self.e + phase_turns * 4) @@ -43,8 +43,8 @@ def _qid_shape_(self): def _unitary_(self): return np.array( [ - [0, 1j ** -self.e, 0], - [0, 0, 1j ** self.e], + [0, 1j**-self.e, 0], + [0, 0, 1j**self.e], [1, 0, 0], ] ) @@ -61,7 +61,7 @@ def __init__(self, e): self.e = e def _unitary_(self): - return np.array([[0, 1j ** -(self.e * 2)], [1j ** self.e, 0]]) + return np.array([[0, 1j ** -(self.e * 2)], [1j**self.e, 0]]) def _phase_by_(self, phase_turns: float, qubit_index: int): return BadPhaser(self.e + phase_turns * 4) diff --git a/cirq/testing/consistent_protocols.py b/cirq/testing/consistent_protocols.py index 8a759384b58..1c0e5666fbd 100644 --- a/cirq/testing/consistent_protocols.py +++ b/cirq/testing/consistent_protocols.py @@ -75,7 +75,7 @@ def assert_implements_consistent_protocols( p = protocols.pow(val, exponent, None) if p is not None: _assert_meets_standards_helper( - val ** exponent, + val**exponent, ignoring_global_phase=ignoring_global_phase, setup_code=setup_code, global_vals=global_vals, diff --git a/cirq/testing/consistent_protocols_test.py b/cirq/testing/consistent_protocols_test.py index 8543f3ae16c..4c9ef31518c 100644 --- a/cirq/testing/consistent_protocols_test.py +++ b/cirq/testing/consistent_protocols_test.py @@ -41,8 +41,8 @@ def _has_unitary_(self): def _unitary_(self) -> Union[np.ndarray, NotImplementedType]: if cirq.is_parameterized(self): return NotImplemented - z = cirq.unitary(cirq.Z ** self.phase_exponent) - x = cirq.unitary(cirq.X ** self.exponent) + z = cirq.unitary(cirq.Z**self.phase_exponent) + x = cirq.unitary(cirq.X**self.exponent) return np.dot(np.dot(z, x), np.conj(z)) def _apply_unitary_(self, args: cirq.ApplyUnitaryArgs) -> Union[np.ndarray, NotImplementedType]: @@ -65,7 +65,7 @@ def _decompose_(self, qubits: Sequence[cirq.Qid]) -> cirq.OP_TREE: q = qubits[0] z = cirq.Z(q) ** self.phase_exponent x = cirq.X(q) ** self.exponent - return z ** -1, x, z + return z**-1, x, z def _pauli_expansion_(self) -> cirq.LinearDict[str]: if self._is_parameterized_(): @@ -159,7 +159,7 @@ def _decompose_(self, qubits: Sequence[cirq.Qid]) -> cirq.OP_TREE: if cirq.is_parameterized(z): # coverage: ignore return NotImplemented - return z ** -1, x, z + return z**-1, x, z class BadGatePauliExpansion(GoodGate): diff --git a/cirq/testing/consistent_qasm.py b/cirq/testing/consistent_qasm.py index a1672e7afff..bcad22f3333 100644 --- a/cirq/testing/consistent_qasm.py +++ b/cirq/testing/consistent_qasm.py @@ -139,5 +139,5 @@ def _reorder_indices_of_matrix(matrix: np.ndarray, new_order: List[int]): new_input_indices = new_order new_output_indices = [i + num_qubits for i in new_input_indices] matrix = np.moveaxis(matrix, all_indices, new_input_indices + new_output_indices) - matrix = np.reshape(matrix, (2 ** num_qubits, 2 ** num_qubits)) + matrix = np.reshape(matrix, (2**num_qubits, 2**num_qubits)) return matrix diff --git a/cirq/testing/random_circuit_test.py b/cirq/testing/random_circuit_test.py index 33bce27b536..9203ef0d0d8 100644 --- a/cirq/testing/random_circuit_test.py +++ b/cirq/testing/random_circuit_test.py @@ -92,7 +92,7 @@ def test_random_circuit( ) -@pytest.mark.parametrize('seed', [random.randint(0, 2 ** 32) for _ in range(10)]) +@pytest.mark.parametrize('seed', [random.randint(0, 2**32) for _ in range(10)]) def test_random_circuit_reproducible_with_seed(seed): wrappers = (lambda s: s, np.random.RandomState) circuits = [ diff --git a/cirq/transformers/analytical_decompositions/clifford_decomposition.py b/cirq/transformers/analytical_decompositions/clifford_decomposition.py index 6c782d59769..1e51d8b866e 100644 --- a/cirq/transformers/analytical_decompositions/clifford_decomposition.py +++ b/cirq/transformers/analytical_decompositions/clifford_decomposition.py @@ -51,7 +51,7 @@ def _Sdg( qubits: List['cirq.Qid'], ): # Apply the tableau with S^\{dagger} - protocols.act_on(ops.S ** -1, args, qubits=[qubits[q]], allow_decompose=False) + protocols.act_on(ops.S**-1, args, qubits=[qubits[q]], allow_decompose=False) operations.append(ops.S(qubits[q])) diff --git a/cirq/transformers/analytical_decompositions/controlled_gate_decomposition.py b/cirq/transformers/analytical_decompositions/controlled_gate_decomposition.py index b6d68f372a6..af01e926499 100644 --- a/cirq/transformers/analytical_decompositions/controlled_gate_decomposition.py +++ b/cirq/transformers/analytical_decompositions/controlled_gate_decomposition.py @@ -25,7 +25,7 @@ def _unitary_power(matrix: np.ndarray, power: float) -> np.ndarray: - return map_eigenvalues(matrix, lambda e: e ** power) + return map_eigenvalues(matrix, lambda e: e**power) def _is_identity(matrix): diff --git a/cirq/transformers/analytical_decompositions/single_qubit_decompositions_test.py b/cirq/transformers/analytical_decompositions/single_qubit_decompositions_test.py index 5f15a6b87af..5b49bee62b0 100644 --- a/cirq/transformers/analytical_decompositions/single_qubit_decompositions_test.py +++ b/cirq/transformers/analytical_decompositions/single_qubit_decompositions_test.py @@ -86,13 +86,13 @@ def test_single_qubit_matrix_to_gates_known_z(): def test_single_qubit_matrix_to_gates_known_s(): actual = cirq.single_qubit_matrix_to_gates(np.array([[1, 0], [0, 1j]]), tolerance=0.01) - assert cirq.approx_eq(actual, [cirq.Z ** 0.5], atol=1e-9) + assert cirq.approx_eq(actual, [cirq.Z**0.5], atol=1e-9) def test_known_s_dag(): actual = cirq.single_qubit_matrix_to_gates(np.array([[1, 0], [0, -1j]]), tolerance=0.01) - assert cirq.approx_eq(actual, [cirq.Z ** -0.5], atol=1e-9) + assert cirq.approx_eq(actual, [cirq.Z**-0.5], atol=1e-9) def test_known_h(): @@ -100,7 +100,7 @@ def test_known_h(): np.array([[1, 1], [1, -1]]) * np.sqrt(0.5), tolerance=0.001 ) - assert cirq.approx_eq(actual, [cirq.Y ** -0.5, cirq.Z], atol=1e-9) + assert cirq.approx_eq(actual, [cirq.Y**-0.5, cirq.Z], atol=1e-9) @pytest.mark.parametrize( @@ -189,10 +189,10 @@ def _random_unitary_with_close_eigenvalues(): np.eye(2), cirq.unitary(cirq.H), cirq.unitary(cirq.X), - cirq.unitary(cirq.X ** 0.5), + cirq.unitary(cirq.X**0.5), cirq.unitary(cirq.Y), cirq.unitary(cirq.Z), - cirq.unitary(cirq.Z ** 0.5), + cirq.unitary(cirq.Z**0.5), _random_unitary_with_close_eigenvalues(), ] + [cirq.testing.random_unitary(2) for _ in range(10)], @@ -214,16 +214,16 @@ def test_single_qubit_matrix_to_phased_x_z_known(): assert cirq.approx_eq(actual, [cirq.Z], atol=1e-9) actual = cirq.single_qubit_matrix_to_phased_x_z(np.array([[1, 0], [0, 1j]]), atol=0.01) - assert cirq.approx_eq(actual, [cirq.Z ** 0.5], atol=1e-9) + assert cirq.approx_eq(actual, [cirq.Z**0.5], atol=1e-9) actual = cirq.single_qubit_matrix_to_phased_x_z(np.array([[1, 0], [0, -1j]]), atol=0.01) - assert cirq.approx_eq(actual, [cirq.Z ** -0.5], atol=1e-9) + assert cirq.approx_eq(actual, [cirq.Z**-0.5], atol=1e-9) actual = cirq.single_qubit_matrix_to_phased_x_z( np.array([[1, 1], [1, -1]]) * np.sqrt(0.5), atol=0.001 ) assert cirq.approx_eq( - actual, [cirq.PhasedXPowGate(phase_exponent=-0.5, exponent=0.5), cirq.Z ** -1], atol=1e-9 + actual, [cirq.PhasedXPowGate(phase_exponent=-0.5, exponent=0.5), cirq.Z**-1], atol=1e-9 ) diff --git a/cirq/transformers/analytical_decompositions/two_qubit_to_cz.py b/cirq/transformers/analytical_decompositions/two_qubit_to_cz.py index ac3d9dae0d3..9d455ed789d 100644 --- a/cirq/transformers/analytical_decompositions/two_qubit_to_cz.py +++ b/cirq/transformers/analytical_decompositions/two_qubit_to_cz.py @@ -251,8 +251,8 @@ def _non_local_part( if allow_partial_czs or all(_is_trivial_angle(e, atol) for e in [x, y, z]): return [ - _parity_interaction(q0, q1, x, atol, ops.Y ** -0.5), - _parity_interaction(q0, q1, y, atol, ops.X ** 0.5), + _parity_interaction(q0, q1, x, atol, ops.Y**-0.5), + _parity_interaction(q0, q1, y, atol, ops.X**0.5), _parity_interaction(q0, q1, z, atol), ] diff --git a/cirq/transformers/analytical_decompositions/two_qubit_to_cz_test.py b/cirq/transformers/analytical_decompositions/two_qubit_to_cz_test.py index ebd22a23d2d..08e6374c088 100644 --- a/cirq/transformers/analytical_decompositions/two_qubit_to_cz_test.py +++ b/cirq/transformers/analytical_decompositions/two_qubit_to_cz_test.py @@ -137,8 +137,8 @@ def assert_ops_implement_unitary(q0, q1, operations, intended_effect, atol=0.01) ] ), ), - (0, 0, cirq.unitary(cirq.CZ ** 0.00000001)), - (0.5, 2, cirq.unitary(cirq.CZ ** 0.5)), + (0, 0, cirq.unitary(cirq.CZ**0.00000001)), + (0.5, 2, cirq.unitary(cirq.CZ**0.5)), (1, 1, cirq.unitary(cirq.CZ)), (1, 1, cirq.unitary(cirq.CNOT)), ( @@ -180,7 +180,7 @@ def assert_ops_implement_unitary(q0, q1, operations, intended_effect, atol=0.01) ) * np.sqrt(0.5), ), - (1.5, 3, cirq.map_eigenvalues(cirq.unitary(cirq.SWAP), lambda e: e ** 0.5)), + (1.5, 3, cirq.map_eigenvalues(cirq.unitary(cirq.SWAP), lambda e: e**0.5)), (2, 2, cirq.unitary(cirq.SWAP).dot(cirq.unitary(cirq.CZ))), (3, 3, cirq.unitary(cirq.SWAP)), ( @@ -250,7 +250,7 @@ def test_kak_decomposition_depth_full_cz(): assert len(c) > 6 # Length should be 13 with extra Pauli gates # Partial single-axis interaction. - u = cirq.unitary(cirq.CNOT ** 0.1) + u = cirq.unitary(cirq.CNOT**0.1) operations_with_part = cirq.two_qubit_matrix_to_cz_operations(a, b, u, False) c = cirq.Circuit(operations_with_part) # 2 CZ, 2+1 PhasedX, 1 Z @@ -282,7 +282,7 @@ def test_kak_decomposition_depth_partial_cz(): assert len(c) <= 6 # Partial single-axis interaction. - u = cirq.unitary(cirq.CNOT ** 0.1) + u = cirq.unitary(cirq.CNOT**0.1) operations_with_part = cirq.two_qubit_matrix_to_cz_operations(a, b, u, True) c = cirq.Circuit(operations_with_part) # 1 CP, 1+1 PhasedX, 1 Z diff --git a/cirq/transformers/analytical_decompositions/two_qubit_to_fsim_test.py b/cirq/transformers/analytical_decompositions/two_qubit_to_fsim_test.py index 2f4aadbbd7e..73106b28db8 100644 --- a/cirq/transformers/analytical_decompositions/two_qubit_to_fsim_test.py +++ b/cirq/transformers/analytical_decompositions/two_qubit_to_fsim_test.py @@ -40,7 +40,7 @@ def test_deprecated_submodule(): UNITARY_OBJS = [ cirq.IdentityGate(2), - cirq.XX ** 0.25, + cirq.XX**0.25, cirq.CNOT, cirq.CNOT(*cirq.LineQubit.range(2)), cirq.CNOT(*cirq.LineQubit.range(2)[::-1]), diff --git a/cirq/transformers/analytical_decompositions/two_qubit_to_sqrt_iswap.py b/cirq/transformers/analytical_decompositions/two_qubit_to_sqrt_iswap.py index 0fabfc32fcb..4cdb8898dc5 100644 --- a/cirq/transformers/analytical_decompositions/two_qubit_to_sqrt_iswap.py +++ b/cirq/transformers/analytical_decompositions/two_qubit_to_sqrt_iswap.py @@ -370,13 +370,13 @@ def append(matrix0, matrix1, final_layer=False): # Commute rightmost Z(q0)**b, Z(q1)**b through next sqrt-iSWAP if len(rots1) > 0 and rots1[-1][0] == ops.Z: _, prev_z = rots1.pop() - z_unitary = protocols.unitary(ops.Z ** prev_z) + z_unitary = protocols.unitary(ops.Z**prev_z) new_commute = new_commute @ z_unitary matrix0 = z_unitary.T.conj() @ matrix0 # Commute rightmost whole X(q0), X(q0) or Y, Y through next sqrt-iSWAP if len(rots1) > 0 and linalg.tolerance.near_zero_mod(rots1[-1][1], 1, atol=atol): pauli, half_turns = rots1.pop() - p_unitary = protocols.unitary(pauli ** half_turns) + p_unitary = protocols.unitary(pauli**half_turns) new_commute = new_commute @ p_unitary matrix0 = p_unitary.T.conj() @ matrix0 rots0 = list( @@ -385,8 +385,8 @@ def append(matrix0, matrix1, final_layer=False): ) ) # Append single qubit ops - operations.extend((pauli ** half_turns).on(q0) for pauli, half_turns in rots0) - operations.extend((pauli ** half_turns).on(q1) for pauli, half_turns in rots1) + operations.extend((pauli**half_turns).on(q0) for pauli, half_turns in rots0) + operations.extend((pauli**half_turns).on(q1) for pauli, half_turns in rots1) prev_commute = new_commute single_ops = list(single_qubit_operations) diff --git a/cirq/transformers/analytical_decompositions/two_qubit_to_sqrt_iswap_test.py b/cirq/transformers/analytical_decompositions/two_qubit_to_sqrt_iswap_test.py index 5d37f64d678..d0542b17f59 100644 --- a/cirq/transformers/analytical_decompositions/two_qubit_to_sqrt_iswap_test.py +++ b/cirq/transformers/analytical_decompositions/two_qubit_to_sqrt_iswap_test.py @@ -127,12 +127,12 @@ def perturbations_weyl(x, y, z, amount=1e-10): ] TWO_SQRT_ISWAP_UNITARIES = [ # Typical gates and nearby Weyl coordinates to simulate numerical noise - *perturbations_gate(cirq.XX ** 0.25), - *perturbations_gate(cirq.YY ** 0.07), - *perturbations_gate(cirq.ZZ ** 0.15), + *perturbations_gate(cirq.XX**0.25), + *perturbations_gate(cirq.YY**0.07), + *perturbations_gate(cirq.ZZ**0.15), *perturbations_gate(cirq.CNOT), *perturbations_gate(cirq.ISWAP), - *perturbations_gate(cirq.ISWAP ** 0.1), + *perturbations_gate(cirq.ISWAP**0.1), # Critical points in the Weyl chamber and nearby coordinates to simulate numerical noise *perturbations_weyl(np.pi / 4, 0, 0), *perturbations_weyl(np.pi / 4, np.pi / 4, 0), @@ -389,7 +389,7 @@ def test_decomp3(u): def test_decomp3_invalid(): # All two-qubit gates can be synthesized with three SQRT_ISWAP gates - u = cirq.unitary(cirq.X ** 0.2) # Pass an invalid size unitary + u = cirq.unitary(cirq.X**0.2) # Pass an invalid size unitary q0, q1 = cirq.LineQubit.range(2) with pytest.raises(ValueError, match='Input must correspond to a 4x4 unitary matrix'): cirq.two_qubit_matrix_to_sqrt_iswap_operations(q0, q1, u, required_sqrt_iswap_count=3) diff --git a/cirq/transformers/eject_phased_paulis_test.py b/cirq/transformers/eject_phased_paulis_test.py index b0e545250dc..9ef93c97777 100644 --- a/cirq/transformers/eject_phased_paulis_test.py +++ b/cirq/transformers/eject_phased_paulis_test.py @@ -65,7 +65,7 @@ def assert_optimizes( # Nested sub-circuits should also get optimized. q = before.all_qubits() c_nested = cirq.Circuit( - [cirq.PhasedXPowGate(phase_exponent=0.5).on_each(*q), (cirq.Z ** 0.5).on_each(*q)], + [cirq.PhasedXPowGate(phase_exponent=0.5).on_each(*q), (cirq.Z**0.5).on_each(*q)], cirq.CircuitOperation(before.freeze()).repeat(2).with_tags("ignore"), [cirq.Y.on_each(*q), cirq.X.on_each(*q)], cirq.CircuitOperation(before.freeze()).repeat(3).with_tags("preserve_tag"), diff --git a/cirq/transformers/eject_z_test.py b/cirq/transformers/eject_z_test.py index d5bf72931fb..7c0daae894a 100644 --- a/cirq/transformers/eject_z_test.py +++ b/cirq/transformers/eject_z_test.py @@ -45,17 +45,17 @@ def assert_optimizes( # Nested sub-circuits should also get optimized. q = before.all_qubits() c_nested = cirq.Circuit( - [(cirq.Z ** 0.5).on_each(*q), (cirq.Y ** 0.25).on_each(*q)], + [(cirq.Z**0.5).on_each(*q), (cirq.Y**0.25).on_each(*q)], cirq.Moment(cirq.CircuitOperation(before.freeze()).repeat(2).with_tags("ignore")), - [(cirq.Z ** 0.5).on_each(*q), (cirq.Y ** 0.25).on_each(*q)], + [(cirq.Z**0.5).on_each(*q), (cirq.Y**0.25).on_each(*q)], cirq.Moment(cirq.CircuitOperation(before.freeze()).repeat(3).with_tags("preserve_tag")), ) c_expected = cirq.Circuit( cirq.PhasedXPowGate(phase_exponent=0, exponent=0.25).on_each(*q), - (cirq.Z ** 0.5).on_each(*q), + (cirq.Z**0.5).on_each(*q), cirq.Moment(cirq.CircuitOperation(before.freeze()).repeat(2).with_tags("ignore")), cirq.PhasedXPowGate(phase_exponent=0, exponent=0.25).on_each(*q), - (cirq.Z ** 0.5).on_each(*q), + (cirq.Z**0.5).on_each(*q), cirq.Moment(cirq.CircuitOperation(expected.freeze()).repeat(3).with_tags("preserve_tag")), ) if context is None: diff --git a/cirq/transformers/measurement_transformers_test.py b/cirq/transformers/measurement_transformers_test.py index cb46c0ff357..9280cd4bf39 100644 --- a/cirq/transformers/measurement_transformers_test.py +++ b/cirq/transformers/measurement_transformers_test.py @@ -24,7 +24,7 @@ def assert_equivalent_to_deferred(circuit: cirq.Circuit): qubits = list(circuit.all_qubits()) sim = cirq.Simulator() num_qubits = len(qubits) - for i in range(2 ** num_qubits): + for i in range(2**num_qubits): bits = cirq.big_endian_int_to_bits(i, bit_count=num_qubits) modified = cirq.Circuit() for j in range(num_qubits): diff --git a/cirq/transformers/merge_k_qubit_gates_test.py b/cirq/transformers/merge_k_qubit_gates_test.py index 6dc1434dc52..1135ce3a1d4 100644 --- a/cirq/transformers/merge_k_qubit_gates_test.py +++ b/cirq/transformers/merge_k_qubit_gates_test.py @@ -44,7 +44,7 @@ def test_merge_1q_unitaries(): assert len(op_list) == 1 assert isinstance(op_list[0].gate, cirq.MatrixGate) cirq.testing.assert_allclose_up_to_global_phase( - cirq.unitary(c), cirq.unitary(cirq.Y ** 0.5), atol=1e-7 + cirq.unitary(c), cirq.unitary(cirq.Y**0.5), atol=1e-7 ) # 2. Gets blocked at a 2q operation. diff --git a/cirq/transformers/target_gatesets/cz_gateset_test.py b/cirq/transformers/target_gatesets/cz_gateset_test.py index fba184f05dc..14b89cab966 100644 --- a/cirq/transformers/target_gatesets/cz_gateset_test.py +++ b/cirq/transformers/target_gatesets/cz_gateset_test.py @@ -174,7 +174,7 @@ def test_optimizes_single_iswap(): def test_optimizes_tagged_partial_cz(): a, b = cirq.LineQubit.range(2) - c = cirq.Circuit((cirq.CZ ** 0.5)(a, b).with_tags('mytag')) + c = cirq.Circuit((cirq.CZ**0.5)(a, b).with_tags('mytag')) assert_optimization_not_broken(c) c = cirq.optimize_for_target_gateset(c, gateset=cirq.CZTargetGateset()) assert ( diff --git a/cirq/value/digits_test.py b/cirq/value/digits_test.py index afc8077afa4..a9f5ec1f937 100644 --- a/cirq/value/digits_test.py +++ b/cirq/value/digits_test.py @@ -70,7 +70,7 @@ def test_big_endian_int_to_digits(): with pytest.raises(ValueError, match='Out of range'): assert cirq.big_endian_int_to_digits(101, base=[], digit_count=0) == [] with pytest.raises(ValueError, match='Out of range'): - _ = cirq.big_endian_int_to_digits(10 ** 100, base=[2, 3, 4, 5, 6]) + _ = cirq.big_endian_int_to_digits(10**100, base=[2, 3, 4, 5, 6]) assert cirq.big_endian_int_to_digits(0, base=[], digit_count=0) == [] assert cirq.big_endian_int_to_digits(0, base=[]) == [] diff --git a/cirq/value/duration_test.py b/cirq/value/duration_test.py index 8ca572e0bd8..3ee689adf92 100644 --- a/cirq/value/duration_test.py +++ b/cirq/value/duration_test.py @@ -47,14 +47,14 @@ def test_init(): def test_init_timedelta(): assert Duration(timedelta(microseconds=0)).total_picos() == 0 - assert Duration(timedelta(microseconds=513)).total_picos() == 513 * 10 ** 6 - assert Duration(timedelta(microseconds=-5)).total_picos() == -5 * 10 ** 6 - assert Duration(timedelta(microseconds=211)).total_picos() == 211 * 10 ** 6 - - assert Duration(timedelta(seconds=3)).total_picos() == 3 * 10 ** 12 - assert Duration(timedelta(seconds=-5)).total_picos() == -5 * 10 ** 12 - assert Duration(timedelta(seconds=3)).total_nanos() == 3 * 10 ** 9 - assert Duration(timedelta(seconds=-5)).total_nanos() == -5 * 10 ** 9 + assert Duration(timedelta(microseconds=513)).total_picos() == 513 * 10**6 + assert Duration(timedelta(microseconds=-5)).total_picos() == -5 * 10**6 + assert Duration(timedelta(microseconds=211)).total_picos() == 211 * 10**6 + + assert Duration(timedelta(seconds=3)).total_picos() == 3 * 10**12 + assert Duration(timedelta(seconds=-5)).total_picos() == -5 * 10**12 + assert Duration(timedelta(seconds=3)).total_nanos() == 3 * 10**9 + assert Duration(timedelta(seconds=-5)).total_nanos() == -5 * 10**9 def test_total(): diff --git a/cirq/value/linear_dict_test.py b/cirq/value/linear_dict_test.py index cc59fc6e66d..0d1ff5575e3 100644 --- a/cirq/value/linear_dict_test.py +++ b/cirq/value/linear_dict_test.py @@ -499,10 +499,10 @@ def test_incomparable(a, b): ({}, '{}', '0'), ({}, '{:.2f}', '0.00'), ({}, '{:.2e}', '0.00e+00'), - ({'X': 2 ** -10}, '{:.2f}', '0.00'), + ({'X': 2**-10}, '{:.2f}', '0.00'), ({'X': 1 / 100}, '{:.2e}', '1.00e-02*X'), - ({'X': 1j * 2 ** -10}, '{:.2f}', '0.00'), - ({'X': 1j * 2 ** -10}, '{:.3f}', '0.001j*X'), + ({'X': 1j * 2**-10}, '{:.2f}', '0.00'), + ({'X': 1j * 2**-10}, '{:.3f}', '0.001j*X'), ({'X': 2j, 'Y': -3}, '{:.2f}', '2.00j*X-3.00*Y'), ({'X': -2j, 'Y': 3}, '{:.2f}', '-2.00j*X+3.00*Y'), ({'X': np.sqrt(1j)}, '{:.3f}', '(0.707+0.707j)*X'), diff --git a/cirq/value/random_state_test.py b/cirq/value/random_state_test.py index 14990f5dd6a..694965ea0a9 100644 --- a/cirq/value/random_state_test.py +++ b/cirq/value/random_state_test.py @@ -33,7 +33,7 @@ def rand(prng): eq = cirq.testing.EqualsTester() eq.add_equality_group(*vals) - seed = np.random.randint(2 ** 31) + seed = np.random.randint(2**31) prngs = [ np.random.RandomState(seed), cirq.value.parse_random_state(np.random.RandomState(seed)), diff --git a/cirq/value/timestamp.py b/cirq/value/timestamp.py index 7833a8c9716..f5c35dfc41a 100644 --- a/cirq/value/timestamp.py +++ b/cirq/value/timestamp.py @@ -49,7 +49,7 @@ def raw_picos(self) -> float: def __add__(self, other) -> 'Timestamp': if isinstance(other, timedelta): - return Timestamp(picos=self._picos + other.total_seconds() * 10 ** 12) + return Timestamp(picos=self._picos + other.total_seconds() * 10**12) if not isinstance(other, Duration): return NotImplemented return Timestamp(picos=self._picos + other.total_picos()) @@ -70,7 +70,7 @@ def __sub__(self, other): if isinstance(other, Duration): return Timestamp(picos=self._picos - other.total_picos()) if isinstance(other, timedelta): - return Timestamp(picos=self._picos - other.total_seconds() * 10 ** 12) + return Timestamp(picos=self._picos - other.total_seconds() * 10**12) if isinstance(other, type(self)): return Duration(picos=self._picos - other._picos) return NotImplemented diff --git a/cirq/vis/density_matrix.py b/cirq/vis/density_matrix.py index 4cf726f77f4..3a06644cd31 100644 --- a/cirq/vis/density_matrix.py +++ b/cirq/vis/density_matrix.py @@ -105,12 +105,12 @@ def plot_density_matrix( matrix = matrix.astype(np.complex128) num_qubits = int(np.log2(matrix.shape[0])) - validate_density_matrix(matrix, qid_shape=(2 ** num_qubits,)) + validate_density_matrix(matrix, qid_shape=(2**num_qubits,)) if ax is None: _, ax = plt.subplots(figsize=(10, 10)) - ax.set_xlim(0 - _padding_around_plot, 2 ** num_qubits + _padding_around_plot) - ax.set_ylim(0 - _padding_around_plot, 2 ** num_qubits + _padding_around_plot) + ax.set_xlim(0 - _padding_around_plot, 2**num_qubits + _padding_around_plot) + ax.set_ylim(0 - _padding_around_plot, 2**num_qubits + _padding_around_plot) for i in range(matrix.shape[0]): for j in range(matrix.shape[1]): diff --git a/cirq/vis/state_histogram.py b/cirq/vis/state_histogram.py index 7bb15cc6aab..d8dcdeb9bb0 100644 --- a/cirq/vis/state_histogram.py +++ b/cirq/vis/state_histogram.py @@ -32,7 +32,7 @@ def get_state_histogram(result: 'result.Result') -> np.ndarray: The state histogram (a numpy array) corresponding to the trial result. """ num_qubits = sum([value.shape[1] for value in result.measurements.values()]) - states = 2 ** num_qubits + states = 2**num_qubits values = np.zeros(states) # measurements is a dict of {measurement gate key: # array(repetitions, boolean result)} diff --git a/cirq/work/observable_measurement_data.py b/cirq/work/observable_measurement_data.py index b4da1a87faf..b638e9f426f 100644 --- a/cirq/work/observable_measurement_data.py +++ b/cirq/work/observable_measurement_data.py @@ -485,7 +485,7 @@ def variance(self, setting: InitObsSetting, *, atol: float = 1e-8): # https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulae # assume cov(a,b) = 0, otherwise there would be another term. - var = f ** 2 * (var_a / (a ** 2) + var_b / (b ** 2)) + var = f**2 * (var_a / (a**2) + var_b / (b**2)) return var diff --git a/cirq/work/observable_measurement_data_test.py b/cirq/work/observable_measurement_data_test.py index 9382a646d17..3054640bfc6 100644 --- a/cirq/work/observable_measurement_data_test.py +++ b/cirq/work/observable_measurement_data_test.py @@ -77,7 +77,7 @@ def test_stats_from_measurements(): # 10 [each obs val deviates by 10]. The variance is 10**2 and the # squared-standard-error-of-the-mean can be found by dividing by the # number of samples minus 1. - assert err == 10 ** 2 / (4 - 1) + assert err == 10**2 / (4 - 1) def test_observable_measured_result(): @@ -89,7 +89,7 @@ def test_observable_measured_result(): observable=cirq.Y(a) * cirq.Y(b), ), mean=0, - variance=5 ** 2, + variance=5**2, repetitions=4, circuit_params={'phi': 52}, ) @@ -381,16 +381,16 @@ def test_bitstring_accumulator_stats(): # so the total contribution is zero, and the matrix is diagonal should_be = np.array( [ - [4 * 7 ** 2, 0, 0], - [0, 4 * 5 ** 2, 0], - [0, 0, 4 * 3 ** 2], + [4 * 7**2, 0, 0], + [0, 4 * 5**2, 0], + [0, 0, 4 * 3**2], ] ) should_be = should_be / (4 - 1) # covariance formula should_be = should_be / 4 # cov of the distribution of sample mean np.testing.assert_allclose(should_be, bsa.covariance()) - for setting, var in zip(settings, [4 * 7 ** 2, 4 * 5 ** 2, 4 * 3 ** 2]): + for setting, var in zip(settings, [4 * 7**2, 4 * 5**2, 4 * 3**2]): np.testing.assert_allclose(0, bsa.mean(setting)) np.testing.assert_allclose(var / 4 / (4 - 1), bsa.variance(setting)) np.testing.assert_allclose(np.sqrt(var / 4 / (4 - 1)), bsa.stderr(setting)) @@ -447,7 +447,7 @@ def test_bitstring_accumulator_stats_2(): should_be = should_be / 4 # cov of the distribution of sample mean np.testing.assert_allclose(should_be, bsa.covariance()) - for setting, var in zip(settings, [4 * 5 ** 2, 4 * 3 ** 2]): + for setting, var in zip(settings, [4 * 5**2, 4 * 3**2]): np.testing.assert_allclose(0, bsa.mean(setting)) np.testing.assert_allclose(var / 4 / (4 - 1), bsa.variance(setting)) np.testing.assert_allclose(np.sqrt(var / 4 / (4 - 1)), bsa.stderr(setting)) diff --git a/cirq/work/observable_measurement_test.py b/cirq/work/observable_measurement_test.py index 4a51b138b74..02a801db5c3 100644 --- a/cirq/work/observable_measurement_test.py +++ b/cirq/work/observable_measurement_test.py @@ -549,7 +549,7 @@ def test_XYZ_point8(circuit, observable): circuit, [observable], cirq.Simulator(seed=52), - stopping_criteria=VarianceStoppingCriteria(1e-3 ** 2), + stopping_criteria=VarianceStoppingCriteria(1e-3**2), ) assert len(df) == 1, 'one observable' mean = df.loc[0]['mean']