Skip to content

Commit

Permalink
Format all files with black-24.3.0 (quantumlib#6513)
Browse files Browse the repository at this point in the history
Executed  check/format-incremental --all --apply

No change in code function.
  • Loading branch information
pavoljuhas authored Mar 20, 2024
1 parent ce045e3 commit 1a6c16a
Show file tree
Hide file tree
Showing 57 changed files with 1,798 additions and 2,786 deletions.
6 changes: 3 additions & 3 deletions cirq-aqt/cirq_aqt/aqt_sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,9 @@ def _generate_json(
RuntimeError: If the circuit is empty.
"""

seq_list: List[
Union[Tuple[str, float, List[int]], Tuple[str, float, float, List[int]]]
] = []
seq_list: List[Union[Tuple[str, float, List[int]], Tuple[str, float, float, List[int]]]] = (
[]
)
circuit = cirq.resolve_parameters(circuit, param_resolver)
for op in circuit.all_operations():
line_qubit = cast(Tuple[cirq.LineQubit], op.qubits)
Expand Down
6 changes: 2 additions & 4 deletions cirq-core/cirq/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,11 @@ def with_debug(value: bool) -> Iterator[None]:


@overload
def cached_method(__func: TFunc) -> TFunc:
...
def cached_method(__func: TFunc) -> TFunc: ...


@overload
def cached_method(*, maxsize: int = 128) -> Callable[[TFunc], TFunc]:
...
def cached_method(*, maxsize: int = 128) -> Callable[[TFunc], TFunc]: ...


def cached_method(method: Optional[TFunc] = None, *, maxsize: int = 128) -> Any:
Expand Down
16 changes: 10 additions & 6 deletions cirq-core/cirq/circuits/moment.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,9 +283,11 @@ def _resolve_parameters_(

def _with_measurement_key_mapping_(self, key_map: Mapping[str, str]):
return Moment(
protocols.with_measurement_key_mapping(op, key_map)
if protocols.measurement_keys_touched(op)
else op
(
protocols.with_measurement_key_mapping(op, key_map)
if protocols.measurement_keys_touched(op)
else op
)
for op in self.operations
)

Expand Down Expand Up @@ -320,9 +322,11 @@ def _with_key_path_(self, path: Tuple[str, ...]):

def _with_key_path_prefix_(self, prefix: Tuple[str, ...]):
return Moment(
protocols.with_key_path_prefix(op, prefix)
if protocols.measurement_keys_touched(op)
else op
(
protocols.with_key_path_prefix(op, prefix)
if protocols.measurement_keys_touched(op)
else op
)
for op in self.operations
)

Expand Down
22 changes: 12 additions & 10 deletions cirq-core/cirq/circuits/qasm_output_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,16 +331,18 @@ def __repr__(self):
cirq.PhasedXPowGate(phase_exponent=0.333, exponent=0.5).on(q1),
cirq.PhasedXPowGate(phase_exponent=0.777, exponent=-0.5).on(q1),
(
cirq.measure(q0, key='xX'),
cirq.measure(q2, key='x_a'),
cirq.measure(q1, key='x?'),
cirq.measure(q3, key='X'),
cirq.measure(q4, key='_x'),
cirq.measure(q2, key='x_a'),
cirq.measure(q1, q2, q3, key='multi', invert_mask=(False, True)),
)
if include_measurements
else (),
(
cirq.measure(q0, key='xX'),
cirq.measure(q2, key='x_a'),
cirq.measure(q1, key='x?'),
cirq.measure(q3, key='X'),
cirq.measure(q4, key='_x'),
cirq.measure(q2, key='x_a'),
cirq.measure(q1, q2, q3, key='multi', invert_mask=(False, True)),
)
if include_measurements
else ()
),
ExampleOperation(),
ExampleCompositeOperation(),
)
Expand Down
16 changes: 9 additions & 7 deletions cirq-core/cirq/contrib/qcircuit/qcircuit_diagram_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,15 @@ def hardcoded_qcircuit_diagram_info(op: ops.Operation) -> Optional[protocols.Cir
symbols = (
(r'\targ',)
if op.gate == ops.X
else (r'\control', r'\control')
if op.gate == ops.CZ
else (r'\control', r'\targ')
if op.gate == ops.CNOT
else (r'\meter',)
if isinstance(op.gate, ops.MeasurementGate)
else ()
else (
(r'\control', r'\control')
if op.gate == ops.CZ
else (
(r'\control', r'\targ')
if op.gate == ops.CNOT
else (r'\meter',) if isinstance(op.gate, ops.MeasurementGate) else ()
)
)
)
return protocols.CircuitDiagramInfo(symbols) if symbols else None

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,9 +180,9 @@ def build_noise_models(self) -> List['cirq.NoiseModel']:
p_00, p_11 = self.readout_errors[qubit]
p = p_11 / (p_00 + p_11)
gamma = p_11 / p
added_measure_errors[
noise_utils.OpIdentifier(ops.MeasurementGate, qubit)
] = ops.generalized_amplitude_damp(p, gamma).on(qubit)
added_measure_errors[noise_utils.OpIdentifier(ops.MeasurementGate, qubit)] = (
ops.generalized_amplitude_damp(p, gamma).on(qubit)
)

noise_models.append(
devices.InsertionNoiseModel(ops_added=added_measure_errors, prepend=True)
Expand Down
12 changes: 2 additions & 10 deletions cirq-core/cirq/experiments/qubit_characterizations.py
Original file line number Diff line number Diff line change
Expand Up @@ -953,16 +953,8 @@ def _single_qubit_cliffords() -> Cliffords:
for z0, x, z1 in phi_xz:
c1_in_xz.append([Z**z0, X**x, Z**z1])

s1: List[List[ops.SingleQubitCliffordGate]] = [
[X**0.0],
[Y**0.5, X**0.5],
[X**-0.5, Y**-0.5],
]
s1_x: List[List[ops.SingleQubitCliffordGate]] = [
[X**0.5],
[X**0.5, Y**0.5, X**0.5],
[Y**-0.5],
]
s1: List[List[ops.SingleQubitCliffordGate]] = [[X**0.0], [Y**0.5, X**0.5], [X**-0.5, Y**-0.5]]
s1_x: List[List[ops.SingleQubitCliffordGate]] = [[X**0.5], [X**0.5, Y**0.5, X**0.5], [Y**-0.5]]
s1_y: List[List[ops.SingleQubitCliffordGate]] = [
[Y**0.5],
[X**-0.5, Y**-0.5, X**0.5],
Expand Down
16 changes: 10 additions & 6 deletions cirq-core/cirq/experiments/single_qubit_readout_calibration.py
Original file line number Diff line number Diff line change
Expand Up @@ -343,15 +343,19 @@ def estimate_parallel_single_qubit_readout_errors(
trial_idx += 1

zero_state_errors = {
q: zero_state_trials[0][qubit_idx] / zero_state_totals[0][qubit_idx]
if zero_state_totals[0][qubit_idx] > 0
else np.nan
q: (
zero_state_trials[0][qubit_idx] / zero_state_totals[0][qubit_idx]
if zero_state_totals[0][qubit_idx] > 0
else np.nan
)
for qubit_idx, q in enumerate(qubits)
}
one_state_errors = {
q: one_state_trials[0][qubit_idx] / one_state_totals[0][qubit_idx]
if one_state_totals[0][qubit_idx] > 0
else np.nan
q: (
one_state_trials[0][qubit_idx] / one_state_totals[0][qubit_idx]
if one_state_totals[0][qubit_idx] > 0
else np.nan
)
for qubit_idx, q in enumerate(qubits)
}

Expand Down
16 changes: 6 additions & 10 deletions cirq-core/cirq/linalg/decompositions.py
Original file line number Diff line number Diff line change
Expand Up @@ -451,18 +451,14 @@ def __init__(
single_qubit_operations_after: a0, a1 from the above equation.
"""
self.global_phase: complex = global_phase
self.single_qubit_operations_before: Tuple[
np.ndarray, np.ndarray
] = single_qubit_operations_before or (
np.eye(2, dtype=np.complex64),
np.eye(2, dtype=np.complex64),
self.single_qubit_operations_before: Tuple[np.ndarray, np.ndarray] = (
single_qubit_operations_before
or (np.eye(2, dtype=np.complex64), np.eye(2, dtype=np.complex64))
)
self.interaction_coefficients = interaction_coefficients
self.single_qubit_operations_after: Tuple[
np.ndarray, np.ndarray
] = single_qubit_operations_after or (
np.eye(2, dtype=np.complex64),
np.eye(2, dtype=np.complex64),
self.single_qubit_operations_after: Tuple[np.ndarray, np.ndarray] = (
single_qubit_operations_after
or (np.eye(2, dtype=np.complex64), np.eye(2, dtype=np.complex64))
)

def _value_equality_values_(self) -> Any:
Expand Down
4 changes: 1 addition & 3 deletions cirq-core/cirq/linalg/decompositions_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -422,9 +422,7 @@ def test_axis_angle_decomposition_str():
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'
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/linalg/transformations_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -584,7 +584,7 @@ def test_partial_trace_of_state_vector_as_mixture_mixed_result():
(0.5, np.array([1, 0, 0, 0]).reshape((2, 2))),
(0.5, np.array([0, 0, 0, 1]).reshape((2, 2))),
)
for (q1, q2) in [(0, 1), (0, 2), (1, 2)]:
for q1, q2 in [(0, 1), (0, 2), (1, 2)]:
mixture = cirq.partial_trace_of_state_vector_as_mixture(state, [q1, q2], atol=1e-8)
assert mixtures_equal(mixture, truth)

Expand Down
3 changes: 1 addition & 2 deletions cirq-core/cirq/ops/common_gates_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,7 @@ def test_cz_unitary():
)

assert np.allclose(
cirq.unitary(cirq.CZ**0),
np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]),
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(
Expand Down
4 changes: 1 addition & 3 deletions cirq-core/cirq/ops/controlled_gate_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -452,9 +452,7 @@ def test_extrapolatable_effect():

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(
a, b
)
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)

Expand Down
4 changes: 1 addition & 3 deletions cirq-core/cirq/ops/phased_iswap_gate_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,7 @@ def test_phased_iswap_init():

def test_phased_iswap_equality():
eq = cirq.testing.EqualsTester()
eq.add_equality_group(
cirq.PhasedISwapPowGate(phase_exponent=0, exponent=0.4), cirq.ISWAP**0.4
)
eq.add_equality_group(cirq.PhasedISwapPowGate(phase_exponent=0, exponent=0.4), cirq.ISWAP**0.4)
eq.add_equality_group(
cirq.PhasedISwapPowGate(phase_exponent=0, exponent=0.4, global_shift=0.3),
cirq.ISwapPowGate(global_shift=0.3) ** 0.4,
Expand Down
9 changes: 3 additions & 6 deletions cirq-core/cirq/ops/qid_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,15 @@


@overload
def q(__x: int) -> 'cirq.LineQubit':
...
def q(__x: int) -> 'cirq.LineQubit': ...


@overload
def q(__row: int, __col: int) -> 'cirq.GridQubit':
...
def q(__row: int, __col: int) -> 'cirq.GridQubit': ...


@overload
def q(__name: str) -> 'cirq.NamedQubit':
...
def q(__name: str) -> 'cirq.NamedQubit': ...


def q(*args: Union[int, str]) -> Union['cirq.LineQubit', 'cirq.GridQubit', 'cirq.NamedQubit']:
Expand Down
8 changes: 5 additions & 3 deletions cirq-core/cirq/protocols/circuit_diagram_info_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,9 +221,11 @@ def _value_equality_values_(self) -> Any:
self.known_qubit_count,
self.use_unicode_characters,
self.precision,
None
if self.label_map is None
else tuple(sorted(self.label_map.items(), key=lambda e: e[0])),
(
None
if self.label_map is None
else tuple(sorted(self.label_map.items(), key=lambda e: e[0]))
),
self.include_tags,
self.transpose,
)
Expand Down
6 changes: 2 additions & 4 deletions cirq-core/cirq/protocols/commutes_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,13 @@ def _commutes_(self, other: Any, *, atol: float) -> Union[None, bool, NotImpleme


@overload
def commutes(v1: Any, v2: Any, *, atol: Union[int, float] = 1e-8) -> bool:
...
def commutes(v1: Any, v2: Any, *, atol: Union[int, float] = 1e-8) -> bool: ...


@overload
def commutes(
v1: Any, v2: Any, *, atol: Union[int, float] = 1e-8, default: TDefault
) -> Union[bool, TDefault]:
...
) -> Union[bool, TDefault]: ...


def commutes(
Expand Down
3 changes: 1 addition & 2 deletions cirq-core/cirq/protocols/decompose_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,7 @@
class OpDecomposerWithContext(Protocol):
def __call__(
self, __op: 'cirq.Operation', *, context: Optional['cirq.DecompositionContext'] = None
) -> DecomposeResult:
...
) -> DecomposeResult: ...


OpDecomposer = Union[Callable[['cirq.Operation'], DecomposeResult], OpDecomposerWithContext]
Expand Down
10 changes: 7 additions & 3 deletions cirq-core/cirq/protocols/decompose_protocol_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,9 +346,13 @@ def _num_qubits_(self) -> int:

def _decompose_impl(self, qubits, mock_qm: mock.Mock):
mock_qm.qalloc(self.recurse)
yield RecursiveDecompose(
recurse=False, mock_qm=self.mock_qm, with_context=self.with_context
).on(*qubits) if self.recurse else cirq.Z.on_each(*qubits)
yield (
RecursiveDecompose(
recurse=False, mock_qm=self.mock_qm, with_context=self.with_context
).on(*qubits)
if self.recurse
else cirq.Z.on_each(*qubits)
)
mock_qm.qfree(self.recurse)

def _decompose_(self, qubits):
Expand Down
3 changes: 1 addition & 2 deletions cirq-core/cirq/protocols/json_serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,7 @@
class JsonResolver(Protocol):
"""Protocol for json resolver functions passed to read_json."""

def __call__(self, cirq_type: str) -> Optional[ObjectFactory]:
...
def __call__(self, cirq_type: str) -> Optional[ObjectFactory]: ...


def _lazy_resolver(dict_factory: Callable[[], Dict[str, ObjectFactory]]) -> JsonResolver:
Expand Down
4 changes: 1 addition & 3 deletions cirq-core/cirq/protocols/pow_protocol_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,4 @@ def test_pow_error():

@pytest.mark.parametrize('val,exponent,out', ((ReturnsExponent(), 2, 2), (1, 2, 1), (2, 3, 8)))
def test_pow_with_result(val, exponent, out):
assert (
cirq.pow(val, exponent) == cirq.pow(val, exponent, default=None) == val**exponent == out
)
assert cirq.pow(val, exponent) == cirq.pow(val, exponent, default=None) == val**exponent == out
8 changes: 5 additions & 3 deletions cirq-core/cirq/sim/mux.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,9 +292,11 @@ def final_density_matrix(
density_result = density_matrix_simulator.DensityMatrixSimulator(
dtype=dtype, noise=noise, seed=seed
).simulate(
program=measurement_transformers.dephase_measurements(circuit_like)
if ignore_measurement_results
else circuit_like,
program=(
measurement_transformers.dephase_measurements(circuit_like)
if ignore_measurement_results
else circuit_like
),
initial_state=initial_state,
qubit_order=qubit_order,
param_resolver=param_resolver,
Expand Down
4 changes: 1 addition & 3 deletions cirq-core/cirq/sim/simulation_product_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,7 @@ def _act_on_fallback_(
gate_opt = (
action
if isinstance(action, ops.Gate)
else action.gate
if isinstance(action, ops.Operation)
else None
else action.gate if isinstance(action, ops.Operation) else None
)

if isinstance(gate_opt, ops.IdentityGate):
Expand Down
6 changes: 3 additions & 3 deletions cirq-core/cirq/sim/simulator_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,9 +261,9 @@ def _run(
for i in range(repetitions):
for step_result in self._core_iterator(
general_suffix,
sim_state=sim_state.copy(deep_copy_buffers=False)
if i < repetitions - 1
else sim_state,
sim_state=(
sim_state.copy(deep_copy_buffers=False) if i < repetitions - 1 else sim_state
),
):
pass
for k, r in step_result._classical_data.records.items():
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ class TwoQubitGateTabulationResult(NamedTuple):
equal to U_target.
success: Whether actual_gate is expected to be close to U_target.
"""

base_gate_unitary: np.ndarray
target_gate: np.ndarray
local_unitaries: Tuple[_SingleQubitGatePair, ...]
Expand Down
Loading

0 comments on commit 1a6c16a

Please sign in to comment.