From 27152c63cc74d526e3adca721ac12e8842ac6fa5 Mon Sep 17 00:00:00 2001 From: Dave Bacon Date: Thu, 14 Apr 2022 09:21:21 -0700 Subject: [PATCH] Format according to new black rules (#5259) Follow up by will add hash to .git-blame-ignore-revs --- cirq-aqt/cirq_aqt/__init__.py | 4 +- cirq-aqt/cirq_aqt/aqt_sampler.py | 4 +- cirq-aqt/cirq_aqt/aqt_sampler_test.py | 5 +- cirq-aqt/cirq_aqt/aqt_simulator_test.py | 16 +- cirq-aqt/setup.py | 5 +- cirq-core/cirq/__init__.py | 39 +- cirq-core/cirq/_compat.py | 14 +- cirq-core/cirq/circuits/__init__.py | 44 +- .../cirq/circuits/_block_diagram_drawer.py | 6 +- .../circuits/_bucket_priority_queue_test.py | 16 +- cirq-core/cirq/circuits/circuit.py | 24 +- cirq-core/cirq/circuits/circuit_dag_test.py | 31 +- cirq-core/cirq/circuits/circuit_operation.py | 11 +- .../cirq/circuits/circuit_operation_test.py | 119 +---- cirq-core/cirq/circuits/circuit_test.py | 480 ++++-------------- cirq-core/cirq/circuits/frozen_circuit.py | 4 +- cirq-core/cirq/circuits/moment.py | 4 +- cirq-core/cirq/circuits/moment_test.py | 34 +- cirq-core/cirq/circuits/qasm_output.py | 12 +- cirq-core/cirq/circuits/quil_output_test.py | 46 +- .../cirq/circuits/text_diagram_drawer.py | 8 +- .../cirq/contrib/acquaintance/__init__.py | 36 +- cirq-core/cirq/contrib/acquaintance/gates.py | 3 +- .../cirq/contrib/acquaintance/permutation.py | 12 +- .../acquaintance/strategies/__init__.py | 12 +- .../cirq/contrib/graph_device/hypergraph.py | 6 +- cirq-core/cirq/contrib/json.py | 5 +- .../cirq/contrib/noise_models/noise_models.py | 17 +- .../contrib/noise_models/noise_models_test.py | 7 +- .../cirq/contrib/paulistring/__init__.py | 28 +- .../contrib/paulistring/clifford_optimize.py | 4 +- .../paulistring/clifford_optimize_test.py | 75 +-- .../contrib/paulistring/convert_gate_set.py | 8 +- .../paulistring/convert_gate_set_test.py | 16 +- .../paulistring/convert_to_clifford_gates.py | 5 +- .../convert_to_clifford_gates_test.py | 26 +- .../convert_to_pauli_string_phasors.py | 5 +- .../convert_to_pauli_string_phasors_test.py | 20 +- .../cirq/contrib/paulistring/optimize.py | 3 +- .../cirq/contrib/paulistring/optimize_test.py | 22 +- .../paulistring/pauli_string_dag_test.py | 5 +- .../paulistring/pauli_string_optimize_test.py | 29 +- .../cirq/contrib/paulistring/separate.py | 4 +- .../cirq/contrib/paulistring/separate_test.py | 8 +- cirq-core/cirq/contrib/qasm_import/_lexer.py | 11 +- .../cirq/contrib/qasm_import/_lexer_test.py | 13 +- cirq-core/cirq/contrib/qasm_import/_parser.py | 6 +- .../cirq/contrib/qasm_import/_parser_test.py | 43 +- cirq-core/cirq/contrib/qcircuit/__init__.py | 4 +- .../contrib/qcircuit/qcircuit_diagram_info.py | 3 +- .../quantum_volume/quantum_volume_test.py | 37 +- cirq-core/cirq/contrib/quil_import/quil.py | 4 +- cirq-core/cirq/contrib/quimb/grid_circuits.py | 6 +- cirq-core/cirq/contrib/quirk/__init__.py | 4 +- .../contrib/quirk/export_to_quirk_test.py | 4 +- cirq-core/cirq/contrib/routing/device_test.py | 16 +- cirq-core/cirq/contrib/routing/router.py | 4 +- .../cirq/contrib/routing/swap_network.py | 4 +- cirq-core/cirq/contrib/routing/utils_test.py | 7 +- cirq-core/cirq/contrib/svg/__init__.py | 5 +- cirq-core/cirq/devices/__init__.py | 44 +- cirq-core/cirq/devices/device.py | 28 +- .../cirq/devices/grid_device_metadata.py | 9 +- cirq-core/cirq/devices/grid_qubit_test.py | 16 +- .../devices/insertion_noise_model_test.py | 15 +- cirq-core/cirq/devices/line_qubit_test.py | 29 +- .../cirq/devices/named_topologies_test.py | 8 +- cirq-core/cirq/devices/noise_model_test.py | 18 +- cirq-core/cirq/devices/noise_properties.py | 4 +- .../cirq/devices/noise_properties_test.py | 10 +- cirq-core/cirq/devices/noise_utils.py | 5 +- cirq-core/cirq/devices/noise_utils_test.py | 33 +- ...conducting_qubits_noise_properties_test.py | 29 +- cirq-core/cirq/devices/thermal_noise_model.py | 7 +- .../cirq/devices/thermal_noise_model_test.py | 19 +- cirq-core/cirq/experiments/__init__.py | 14 +- .../experiments/cross_entropy_benchmarking.py | 4 +- .../cirq/experiments/fidelity_estimation.py | 19 +- .../grid_parallel_two_qubit_xeb.py | 4 +- .../cirq/experiments/n_qubit_tomography.py | 5 +- .../cirq/experiments/purity_estimation.py | 3 +- .../experiments/qubit_characterizations.py | 32 +- .../random_quantum_circuit_generation.py | 4 +- .../random_quantum_circuit_generation_test.py | 15 +- .../experiments/readout_confusion_matrix.py | 3 +- .../single_qubit_readout_calibration_test.py | 23 +- .../cirq/experiments/t1_decay_experiment.py | 9 +- .../experiments/t1_decay_experiment_test.py | 55 +- .../cirq/experiments/t2_decay_experiment.py | 8 +- .../experiments/t2_decay_experiment_test.py | 89 +--- cirq-core/cirq/experiments/xeb_fitting.py | 19 +- .../cirq/experiments/xeb_fitting_test.py | 21 +- cirq-core/cirq/experiments/xeb_sampling.py | 8 +- .../cirq/experiments/xeb_sampling_test.py | 24 +- cirq-core/cirq/experiments/xeb_simulation.py | 15 +- .../cirq/experiments/xeb_simulation_test.py | 32 +- cirq-core/cirq/interop/__init__.py | 5 +- cirq-core/cirq/interop/quirk/__init__.py | 5 +- .../cirq/interop/quirk/cells/__init__.py | 27 +- .../interop/quirk/cells/arithmetic_cells.py | 3 +- .../quirk/cells/arithmetic_cells_test.py | 273 ++-------- cirq-core/cirq/interop/quirk/cells/cell.py | 8 +- .../quirk/cells/composite_cell_test.py | 12 +- .../interop/quirk/cells/control_cells_test.py | 38 +- .../quirk/cells/frequency_space_cells.py | 6 +- .../quirk/cells/frequency_space_cells_test.py | 32 +- .../interop/quirk/cells/input_cells_test.py | 62 +-- .../quirk/cells/input_rotation_cells.py | 14 +- .../cirq/interop/quirk/cells/parse_test.py | 6 +- .../quirk/cells/qubit_permutation_cells.py | 11 +- .../cells/qubit_permutation_cells_test.py | 4 +- .../cells/single_qubit_rotation_cells_test.py | 38 +- .../cirq/interop/quirk/cells/testing_test.py | 26 +- .../interop/quirk/cells/unsupported_cells.py | 5 +- .../cirq/interop/quirk/url_to_circuit_test.py | 27 +- cirq-core/cirq/ion/__init__.py | 28 +- cirq-core/cirq/ion/ion_decomposition.py | 6 +- cirq-core/cirq/ion/ion_device.py | 13 +- cirq-core/cirq/linalg/__init__.py | 13 +- cirq-core/cirq/linalg/decompositions.py | 4 +- cirq-core/cirq/linalg/decompositions_test.py | 9 +- cirq-core/cirq/linalg/diagonalize_test.py | 8 +- cirq-core/cirq/linalg/operator_spaces.py | 3 +- cirq-core/cirq/linalg/operator_spaces_test.py | 23 +- cirq-core/cirq/linalg/transformations.py | 22 +- cirq-core/cirq/linalg/transformations_test.py | 60 +-- cirq-core/cirq/neutral_atoms/__init__.py | 4 +- .../convert_to_neutral_atom_gates.py | 5 +- .../neutral_atoms/neutral_atom_devices.py | 13 +- cirq-core/cirq/ops/__init__.py | 177 ++----- .../cirq/ops/arithmetic_operation_test.py | 2 + cirq-core/cirq/ops/boolean_hamiltonian.py | 7 +- .../cirq/ops/boolean_hamiltonian_test.py | 20 +- .../ops/classically_controlled_operation.py | 9 +- .../classically_controlled_operation_test.py | 77 +-- cirq-core/cirq/ops/clifford_gate.py | 30 +- cirq-core/cirq/ops/clifford_gate_test.py | 55 +- cirq-core/cirq/ops/common_channels_test.py | 7 +- cirq-core/cirq/ops/common_gates.py | 48 +- cirq-core/cirq/ops/common_gates_test.py | 38 +- cirq-core/cirq/ops/controlled_gate.py | 7 +- cirq-core/cirq/ops/controlled_gate_test.py | 36 +- .../cirq/ops/controlled_operation_test.py | 18 +- cirq-core/cirq/ops/dense_pauli_string_test.py | 38 +- cirq-core/cirq/ops/eigen_gate.py | 4 +- cirq-core/cirq/ops/eigen_gate_test.py | 15 +- cirq-core/cirq/ops/fourier_transform.py | 10 +- cirq-core/cirq/ops/fourier_transform_test.py | 12 +- cirq-core/cirq/ops/fsim_gate.py | 4 + cirq-core/cirq/ops/fsim_gate_test.py | 35 +- cirq-core/cirq/ops/gate_operation.py | 4 +- cirq-core/cirq/ops/gateset.py | 12 +- cirq-core/cirq/ops/gateset_test.py | 18 +- cirq-core/cirq/ops/global_phase_op_test.py | 100 +--- cirq-core/cirq/ops/identity.py | 5 +- cirq-core/cirq/ops/identity_test.py | 6 +- cirq-core/cirq/ops/kraus_channel.py | 4 +- cirq-core/cirq/ops/kraus_channel_test.py | 25 +- cirq-core/cirq/ops/linear_combinations.py | 19 +- .../cirq/ops/linear_combinations_test.py | 271 ++-------- cirq-core/cirq/ops/matrix_gates.py | 5 +- cirq-core/cirq/ops/measurement_gate.py | 4 +- cirq-core/cirq/ops/measurement_gate_test.py | 23 +- cirq-core/cirq/ops/mixed_unitary_channel.py | 17 +- .../cirq/ops/mixed_unitary_channel_test.py | 30 +- cirq-core/cirq/ops/named_qubit_test.py | 17 +- cirq-core/cirq/ops/op_tree_test.py | 6 +- cirq-core/cirq/ops/parallel_gate_test.py | 29 +- cirq-core/cirq/ops/parity_gates.py | 5 +- cirq-core/cirq/ops/parity_gates_test.py | 27 +- cirq-core/cirq/ops/pauli_gates.py | 15 +- cirq-core/cirq/ops/pauli_measurement_gate.py | 14 +- .../cirq/ops/pauli_measurement_gate_test.py | 12 +- cirq-core/cirq/ops/pauli_string.py | 19 +- cirq-core/cirq/ops/pauli_string_phasor.py | 12 +- .../cirq/ops/pauli_string_phasor_test.py | 24 +- cirq-core/cirq/ops/pauli_string_raw_types.py | 4 +- .../cirq/ops/pauli_string_raw_types_test.py | 5 +- cirq-core/cirq/ops/pauli_string_test.py | 52 +- cirq-core/cirq/ops/permutation_gate_test.py | 4 +- cirq-core/cirq/ops/phased_iswap_gate.py | 5 +- cirq-core/cirq/ops/phased_iswap_gate_test.py | 8 +- cirq-core/cirq/ops/phased_x_gate_test.py | 27 +- cirq-core/cirq/ops/projector.py | 22 +- cirq-core/cirq/ops/qubit_order.py | 10 +- cirq-core/cirq/ops/random_gate_channel.py | 11 +- .../cirq/ops/random_gate_channel_test.py | 59 +-- cirq-core/cirq/ops/raw_types_test.py | 5 +- .../cirq/ops/state_preparation_channel.py | 5 +- cirq-core/cirq/ops/swap_gates_test.py | 8 +- cirq-core/cirq/ops/three_qubit_gates.py | 5 +- cirq-core/cirq/ops/three_qubit_gates_test.py | 15 +- cirq-core/cirq/ops/wait_gate.py | 8 +- cirq-core/cirq/optimizers/__init__.py | 44 +- .../convert_to_cz_and_single_gates_test.py | 32 +- .../optimizers/drop_empty_moments_test.py | 13 +- .../cirq/optimizers/drop_negligible_test.py | 4 +- .../optimizers/eject_phased_paulis_test.py | 268 ++-------- cirq-core/cirq/optimizers/eject_z_test.py | 116 +---- cirq-core/cirq/optimizers/expand_composite.py | 5 +- .../cirq/optimizers/merge_interactions.py | 10 +- .../optimizers/merge_interactions_test.py | 37 +- .../merge_interactions_to_sqrt_iswap.py | 5 +- .../merge_interactions_to_sqrt_iswap_test.py | 45 +- .../optimizers/merge_single_qubit_gates.py | 5 +- .../merge_single_qubit_gates_test.py | 53 +- .../synchronize_terminal_measurements_test.py | 23 +- cirq-core/cirq/protocols/__init__.py | 66 +-- cirq-core/cirq/protocols/act_on_protocol.py | 4 +- .../cirq/protocols/apply_channel_protocol.py | 5 +- .../protocols/apply_channel_protocol_test.py | 3 +- .../cirq/protocols/apply_mixture_protocol.py | 5 +- .../cirq/protocols/apply_unitary_protocol.py | 16 +- .../protocols/apply_unitary_protocol_test.py | 48 +- .../approximate_equality_protocol_test.py | 8 +- .../circuit_diagram_info_protocol.py | 3 +- .../circuit_diagram_info_protocol_test.py | 7 +- cirq-core/cirq/protocols/commutes_protocol.py | 10 +- .../cirq/protocols/decompose_protocol.py | 4 +- .../cirq/protocols/decompose_protocol_test.py | 22 +- .../has_stabilizer_effect_protocol.py | 5 +- .../cirq/protocols/has_unitary_protocol.py | 10 +- .../protocols/has_unitary_protocol_test.py | 6 +- .../cirq/protocols/inverse_protocol_test.py | 9 +- .../cirq/protocols/json_serialization.py | 24 +- .../cirq/protocols/json_serialization_test.py | 29 +- .../cirq/protocols/json_test_data/spec.py | 7 +- cirq-core/cirq/protocols/kraus_protocol.py | 4 +- .../protocols/measurement_key_protocol.py | 4 +- .../pauli_expansion_protocol_test.py | 11 +- cirq-core/cirq/protocols/pow_protocol_test.py | 19 +- .../cirq/protocols/resolve_parameters_test.py | 16 +- cirq-core/cirq/protocols/unitary_protocol.py | 16 +- cirq-core/cirq/qis/__init__.py | 6 +- cirq-core/cirq/qis/channels_test.py | 16 +- cirq-core/cirq/qis/states.py | 18 +- cirq-core/cirq/qis/states_test.py | 6 +- cirq-core/cirq/sim/__init__.py | 38 +- .../cirq/sim/act_on_args_container_test.py | 14 +- .../sim/act_on_density_matrix_args_test.py | 14 +- .../cirq/sim/act_on_state_vector_args_test.py | 67 +-- cirq-core/cirq/sim/clifford/__init__.py | 20 +- .../act_on_stabilizer_ch_form_args_test.py | 29 +- .../cirq/sim/clifford/clifford_simulator.py | 28 +- .../cirq/sim/clifford/stabilizer_sampler.py | 14 +- .../sim/clifford/stabilizer_sampler_test.py | 7 +- .../cirq/sim/density_matrix_simulator.py | 21 +- cirq-core/cirq/sim/mux.py | 4 +- cirq-core/cirq/sim/mux_test.py | 28 +- cirq-core/cirq/sim/operation_target.py | 5 +- cirq-core/cirq/sim/simulator.py | 28 +- cirq-core/cirq/sim/simulator_base.py | 36 +- cirq-core/cirq/sim/simulator_test.py | 11 +- cirq-core/cirq/sim/sparse_simulator.py | 36 +- cirq-core/cirq/sim/sparse_simulator_test.py | 31 +- cirq-core/cirq/sim/state_vector_simulator.py | 5 +- cirq-core/cirq/study/__init__.py | 18 +- cirq-core/cirq/study/flatten_expressions.py | 7 +- .../cirq/study/flatten_expressions_test.py | 53 +- cirq-core/cirq/study/resolver.py | 2 +- cirq-core/cirq/study/resolver_test.py | 10 +- cirq-core/cirq/study/result.py | 8 +- cirq-core/cirq/study/result_test.py | 83 +-- cirq-core/cirq/study/sweepable.py | 5 +- cirq-core/cirq/study/sweepable_test.py | 5 +- cirq-core/cirq/testing/__init__.py | 78 +-- .../_compat_test_data/module_a/__init__.py | 12 +- cirq-core/cirq/testing/circuit_compare.py | 3 +- .../cirq/testing/circuit_compare_test.py | 87 +--- cirq-core/cirq/testing/consistent_act_on.py | 4 +- .../consistent_controlled_gate_op_test.py | 21 +- cirq-core/cirq/testing/consistent_phase_by.py | 5 +- .../cirq/testing/consistent_phase_by_test.py | 8 +- .../cirq/testing/consistent_protocols.py | 16 +- .../cirq/testing/consistent_protocols_test.py | 5 +- cirq-core/cirq/testing/deprecation.py | 6 +- .../cirq/testing/equivalent_basis_map_test.py | 12 +- cirq-core/cirq/testing/random_circuit.py | 6 +- cirq-core/cirq/transformers/__init__.py | 5 +- .../clifford_decomposition_test.py | 16 +- .../single_qubit_decompositions.py | 13 +- .../single_qubit_decompositions_test.py | 5 +- .../two_qubit_to_cz_test.py | 55 +- .../two_qubit_to_fsim.py | 33 +- .../two_qubit_to_fsim_test.py | 4 +- .../two_qubit_to_sqrt_iswap.py | 32 +- .../two_qubit_to_sqrt_iswap_test.py | 25 +- .../transformers/drop_empty_moments_test.py | 10 +- .../drop_negligible_operations_test.py | 3 +- .../cirq/transformers/eject_phased_paulis.py | 7 +- .../transformers/eject_phased_paulis_test.py | 267 +++------- cirq-core/cirq/transformers/eject_z_test.py | 130 +---- .../cirq/transformers/expand_composite.py | 6 +- .../transformers/measurement_transformers.py | 5 +- .../measurement_transformers_test.py | 8 +- .../transformers/merge_k_qubit_gates_test.py | 5 +- .../optimize_for_target_gateset_test.py | 5 +- cirq-core/cirq/transformers/stratify.py | 12 +- cirq-core/cirq/transformers/stratify_test.py | 197 +------ .../synchronize_terminal_measurements_test.py | 16 +- .../compilation_target_gateset.py | 5 +- .../target_gatesets/cz_gateset.py | 5 +- .../target_gatesets/cz_gateset_test.py | 38 +- .../target_gatesets/sqrt_iswap_gateset.py | 6 +- .../sqrt_iswap_gateset_test.py | 38 +- .../cirq/transformers/transformer_api.py | 3 +- .../cirq/transformers/transformer_api_test.py | 11 +- .../transformers/transformer_primitives.py | 12 +- .../transformer_primitives_test.py | 17 +- cirq-core/cirq/value/__init__.py | 49 +- cirq-core/cirq/value/condition.py | 19 +- cirq-core/cirq/value/linear_dict_test.py | 63 +-- cirq-core/cirq/value/measurement_key.py | 16 +- cirq-core/cirq/value/periodic_value_test.py | 5 +- cirq-core/cirq/value/product_state.py | 13 +- cirq-core/cirq/value/product_state_test.py | 23 +- cirq-core/cirq/vis/__init__.py | 5 +- cirq-core/cirq/vis/heatmap.py | 21 +- cirq-core/cirq/vis/histogram.py | 8 +- cirq-core/cirq/vis/state_histogram_test.py | 9 +- cirq-core/cirq/work/__init__.py | 31 +- .../cirq/work/observable_grouping_test.py | 14 +- cirq-core/cirq/work/observable_measurement.py | 44 +- .../work/observable_measurement_data_test.py | 138 +---- .../cirq/work/observable_measurement_test.py | 90 +--- .../work/observable_readout_calibration.py | 5 +- .../observable_readout_calibration_test.py | 4 +- .../cirq/work/observable_settings_test.py | 37 +- cirq-core/cirq/work/sampler.py | 10 +- cirq-core/cirq/work/sampler_test.py | 44 +- cirq-core/cirq/work/zeros_sampler.py | 5 +- cirq-core/cirq/work/zeros_sampler_test.py | 5 +- cirq-core/setup.py | 9 +- cirq-google/cirq_google/api/v1/__init__.py | 6 +- cirq-google/cirq_google/api/v1/params.py | 4 +- cirq-google/cirq_google/api/v1/programs.py | 3 +- .../cirq_google/api/v1/programs_test.py | 49 +- cirq-google/cirq_google/api/v2/results.py | 21 +- .../cirq_google/api/v2/results_test.py | 42 +- cirq-google/cirq_google/api/v2/sweeps.py | 4 +- .../cirq_google/ops/sycamore_gate_test.py | 2 + .../serialization/common_serializers_test.py | 10 +- cirq-ionq/cirq_ionq/__init__.py | 35 +- cirq-ionq/cirq_ionq/calibration_test.py | 13 +- cirq-ionq/cirq_ionq/ionq_client.py | 9 +- cirq-ionq/cirq_ionq/ionq_devices.py | 14 +- cirq-ionq/cirq_ionq/ionq_devices_test.py | 20 +- cirq-ionq/cirq_ionq/job_test.py | 24 +- cirq-ionq/cirq_ionq/json_test_data/spec.py | 6 +- cirq-ionq/cirq_ionq/results.py | 5 +- cirq-ionq/cirq_ionq/results_test.py | 5 +- cirq-ionq/cirq_ionq/sampler.py | 5 +- cirq-ionq/cirq_ionq/serializer.py | 41 +- cirq-ionq/cirq_ionq/serializer_test.py | 5 +- cirq-ionq/cirq_ionq/service_test.py | 14 +- cirq-ionq/setup.py | 5 +- cirq-pasqal/cirq_pasqal/__init__.py | 31 +- .../cirq_pasqal/json_test_data/spec.py | 6 +- cirq-pasqal/cirq_pasqal/pasqal_device.py | 18 +- cirq-pasqal/cirq_pasqal/pasqal_device_test.py | 26 +- cirq-pasqal/cirq_pasqal/pasqal_qubits_test.py | 13 +- cirq-pasqal/cirq_pasqal/pasqal_sampler.py | 11 +- cirq-pasqal/setup.py | 5 +- cirq-rigetti/cirq_rigetti/__init__.py | 14 +- cirq-rigetti/cirq_rigetti/aspen_device.py | 28 +- .../cirq_rigetti/aspen_device_test.py | 7 +- .../cirq_rigetti/circuit_sweep_executors.py | 6 +- .../circuit_sweep_executors_test.py | 20 +- .../cirq_rigetti/circuit_transformers.py | 6 +- .../cirq_rigetti/circuit_transformers_test.py | 38 +- cirq-rigetti/cirq_rigetti/conftest.py | 33 +- .../qcs_sampler_and_service_test.py | 49 +- cirq-rigetti/cirq_rigetti/sampler.py | 17 +- .../sampler_parametric_circuit_test.py | 19 +- .../sampler_readout_reassigned_qubits_test.py | 7 +- cirq-rigetti/cirq_rigetti/service.py | 23 +- .../cirq_rigetti/service_bell_circuit_test.py | 4 +- .../service_parametric_circuit_test.py | 8 +- cirq-rigetti/cirq_rigetti/service_test.py | 5 +- cirq-rigetti/setup.py | 5 +- cirq-web/cirq_web/__init__.py | 12 +- .../cirq_web/bloch_sphere/bloch_sphere.py | 6 +- cirq-web/cirq_web/circuits/__init__.py | 4 +- cirq-web/cirq_web/circuits/symbols_test.py | 8 +- dev_tools/modules_test.py | 10 +- dev_tools/notebooks/__init__.py | 6 +- dev_tools/pr_monitor.py | 18 +- dev_tools/prepared_env.py | 6 +- .../profiling/benchmark_serializers_test.py | 6 +- dev_tools/pylint_copyright_checker_test.py | 16 +- dev_tools/shell_tools.py | 24 +- dev_tools/shell_tools_test.py | 19 +- examples/advanced/quantum_volume_test.py | 8 +- examples/bcs_mean_field.py | 4 +- examples/bell_inequality.py | 14 +- examples/bernstein_vazirani.py | 8 +- examples/direct_fidelity_estimation.py | 10 +- examples/direct_fidelity_estimation_test.py | 11 +- examples/examples_test.py | 2 +- examples/grover.py | 8 +- examples/hidden_shift_algorithm.py | 18 +- examples/noisy_simulation_example.py | 4 +- examples/phase_estimator.py | 4 +- examples/shor.py | 30 +- examples/simon_algorithm.py | 6 +- examples/stabilizer_code_test.py | 8 +- examples/swap_networks.py | 2 +- rtd_docs/conf.py | 15 +- setup.py | 4 +- 409 files changed, 1766 insertions(+), 7455 deletions(-) diff --git a/cirq-aqt/cirq_aqt/__init__.py b/cirq-aqt/cirq_aqt/__init__.py index 7aad149dda5..7a5be7e17e0 100644 --- a/cirq-aqt/cirq_aqt/__init__.py +++ b/cirq-aqt/cirq_aqt/__init__.py @@ -14,9 +14,7 @@ """Types and methods related to the AQT ion trap device""" -from cirq_aqt._version import ( - __version__, -) +from cirq_aqt._version import __version__ from cirq_aqt.aqt_sampler import AQTSampler, AQTSamplerLocalSimulator from cirq_aqt.aqt_device import AQTSimulator diff --git a/cirq-aqt/cirq_aqt/aqt_sampler.py b/cirq-aqt/cirq_aqt/aqt_sampler.py index 4f6aab3754c..e3365786230 100644 --- a/cirq-aqt/cirq_aqt/aqt_sampler.py +++ b/cirq-aqt/cirq_aqt/aqt_sampler.py @@ -51,9 +51,7 @@ def __init__(self, remote_host: str, access_token: str): self.access_token = access_token def _generate_json( - self, - circuit: cirq.AbstractCircuit, - param_resolver: cirq.ParamResolverOrSimilarType, + self, circuit: cirq.AbstractCircuit, param_resolver: cirq.ParamResolverOrSimilarType ) -> str: """Generates the JSON string from a Circuit. diff --git a/cirq-aqt/cirq_aqt/aqt_sampler_test.py b/cirq-aqt/cirq_aqt/aqt_sampler_test.py index ad1b84c0164..cedbf931972 100644 --- a/cirq-aqt/cirq_aqt/aqt_sampler_test.py +++ b/cirq-aqt/cirq_aqt/aqt_sampler_test.py @@ -127,10 +127,7 @@ def test_aqt_sampler_empty_circuit(): def test_aqt_sampler(): - put_call_args0 = { - 'access_token': 'testkey', - 'id': '2131da', - } + put_call_args0 = {'access_token': 'testkey', 'id': '2131da'} e_return = EngineReturn() with mock.patch( diff --git a/cirq-aqt/cirq_aqt/aqt_simulator_test.py b/cirq-aqt/cirq_aqt/aqt_simulator_test.py index dfb68857e4f..9b075be2679 100644 --- a/cirq-aqt/cirq_aqt/aqt_simulator_test.py +++ b/cirq-aqt/cirq_aqt/aqt_simulator_test.py @@ -36,13 +36,13 @@ def test_ms_crosstalk_n_noise(): for moment in circuit.moments: noisy_moment = noise_mod.noisy_moment(moment, qubits) assert noisy_moment == [ - (cirq.XX ** 0.5).on(cirq.LineQubit(1), cirq.LineQubit(2)), + (cirq.XX**0.5).on(cirq.LineQubit(1), cirq.LineQubit(2)), cirq.depolarize(p=0.01).on(cirq.LineQubit(1)), cirq.depolarize(p=0.01).on(cirq.LineQubit(2)), - (cirq.XX ** 0.015).on(cirq.LineQubit(1), cirq.LineQubit(0)), - (cirq.XX ** 0.015).on(cirq.LineQubit(1), cirq.LineQubit(3)), - (cirq.XX ** 0.015).on(cirq.LineQubit(2), cirq.LineQubit(0)), - (cirq.XX ** 0.015).on(cirq.LineQubit(2), cirq.LineQubit(3)), + (cirq.XX**0.015).on(cirq.LineQubit(1), cirq.LineQubit(0)), + (cirq.XX**0.015).on(cirq.LineQubit(1), cirq.LineQubit(3)), + (cirq.XX**0.015).on(cirq.LineQubit(2), cirq.LineQubit(0)), + (cirq.XX**0.015).on(cirq.LineQubit(2), cirq.LineQubit(3)), ] @@ -57,8 +57,8 @@ def test_x_crosstalk_n_noise(): for moment in circuit.moments: noisy_moment = noise_mod.noisy_moment(moment, qubits) assert noisy_moment == [ - (cirq.X ** 0.5).on(cirq.LineQubit(1)), + (cirq.X**0.5).on(cirq.LineQubit(1)), cirq.depolarize(p=0.001).on(cirq.LineQubit(1)), - (cirq.X ** 0.015).on(cirq.LineQubit(0)), - (cirq.X ** 0.015).on(cirq.LineQubit(2)), + (cirq.X**0.015).on(cirq.LineQubit(0)), + (cirq.X**0.015).on(cirq.LineQubit(2)), ] diff --git a/cirq-aqt/setup.py b/cirq-aqt/setup.py index ff20b49631c..18945d85c58 100644 --- a/cirq-aqt/setup.py +++ b/cirq-aqt/setup.py @@ -66,8 +66,5 @@ description=description, long_description=long_description, packages=cirq_packages, - package_data={ - 'cirq_aqt': ['py.typed'], - 'cirq_aqt.json_test_data': ['*'], - }, + package_data={'cirq_aqt': ['py.typed'], 'cirq_aqt.json_test_data': ['*']}, ) diff --git a/cirq-core/cirq/__init__.py b/cirq-core/cirq/__init__.py index 19c9c3009be..040eee77296 100644 --- a/cirq-core/cirq/__init__.py +++ b/cirq-core/cirq/__init__.py @@ -58,9 +58,7 @@ # End dependency order list of sub-modules -from cirq._version import ( - __version__, -) +from cirq._version import __version__ # Flattened sub-modules. @@ -125,10 +123,7 @@ xeb_fidelity, ) -from cirq.interop import ( - quirk_json_to_circuit, - quirk_url_to_circuit, -) +from cirq.interop import quirk_json_to_circuit, quirk_url_to_circuit from cirq.linalg import ( all_near_zero, @@ -662,12 +657,7 @@ with_rescoped_keys, ) -from cirq.ion import ( - ConvertToIonGates, - IonDevice, - ms, - two_qubit_matrix_to_ion_operations, -) +from cirq.ion import ConvertToIonGates, IonDevice, ms, two_qubit_matrix_to_ion_operations from cirq.neutral_atoms import ( ConvertToNeutralAtomGates, is_native_neutral_atom_gate, @@ -684,21 +674,13 @@ plot_state_histogram, ) -from cirq.work import ( - CircuitSampleJob, - PauliSumCollector, - Sampler, - Collector, - ZerosSampler, -) +from cirq.work import CircuitSampleJob, PauliSumCollector, Sampler, Collector, ZerosSampler # pylint: enable=redefined-builtin # Unflattened sub-modules. -from cirq import ( - testing, -) +from cirq import testing # Registers cirq-core's public classes for JSON serialization. # pylint: disable=wrong-import-position @@ -710,9 +692,7 @@ # contrib's json resolver cache depends on cirq.DEFAULT_RESOLVER -from cirq import ( - contrib, -) +from cirq import contrib # deprecate cirq.ops and related attributes @@ -727,11 +707,6 @@ ) ops.Moment = Moment # type: ignore -_compat.deprecate_attributes( - 'cirq.ops', - { - 'Moment': ('v0.16', 'Use cirq.circuits.Moment instead'), - }, -) +_compat.deprecate_attributes('cirq.ops', {'Moment': ('v0.16', 'Use cirq.circuits.Moment instead')}) # pylint: enable=wrong-import-position diff --git a/cirq-core/cirq/_compat.py b/cirq-core/cirq/_compat.py index 0d6188d4b61..e17597060c7 100644 --- a/cirq-core/cirq/_compat.py +++ b/cirq-core/cirq/_compat.py @@ -175,11 +175,7 @@ def _warn_or_error(msg): if "_compat.py" in filename: stack_level += 1 - warnings.warn( - msg, - DeprecationWarning, - stacklevel=stack_level, - ) + warnings.warn(msg, DeprecationWarning, stacklevel=stack_level) def _validate_deadline(deadline: str): @@ -324,7 +320,7 @@ def decorated_func(*args, **kwargs) -> Any: f'The {parameter_desc} parameter of {qualname} was ' f'used but is deprecated.\n' f'It will be removed in cirq {deadline}.\n' - f'{fix}\n', + f'{fix}\n' ) return func(*args, **kwargs) @@ -500,7 +496,7 @@ def _deduped_module_warn_or_error(old_module_name: str, new_module_name: str, de _warn_or_error( f"{old_module_name} was used but is deprecated.\n " f"it will be removed in cirq {deadline}.\n " - f"Use {new_module_name} instead.\n", + f"Use {new_module_name} instead.\n" ) @@ -700,8 +696,6 @@ def block_overlapping_deprecation(match_regex: str): """ with warnings.catch_warnings(): warnings.filterwarnings( - action='ignore', - category=DeprecationWarning, - message=f'(.|\n)*{match_regex}(.|\n)*', + action='ignore', category=DeprecationWarning, message=f'(.|\n)*{match_regex}(.|\n)*' ) yield diff --git a/cirq-core/cirq/circuits/__init__.py b/cirq-core/cirq/circuits/__init__.py index 810267de452..665ab1ee31c 100644 --- a/cirq-core/cirq/circuits/__init__.py +++ b/cirq-core/cirq/circuits/__init__.py @@ -14,42 +14,18 @@ """Circuit classes, mutators, and outputs.""" -from cirq.circuits.text_diagram_drawer import ( - TextDiagramDrawer, -) +from cirq.circuits.text_diagram_drawer import TextDiagramDrawer -from cirq.circuits.qasm_output import ( - QasmOutput, -) +from cirq.circuits.qasm_output import QasmOutput -from cirq.circuits.quil_output import ( - QuilOutput, -) +from cirq.circuits.quil_output import QuilOutput -from cirq.circuits.circuit import ( - AbstractCircuit, - Alignment, - Circuit, -) -from cirq.circuits.circuit_dag import ( - CircuitDag, - Unique, -) -from cirq.circuits.circuit_operation import ( - CircuitOperation, -) -from cirq.circuits.frozen_circuit import ( - FrozenCircuit, -) -from cirq.circuits.insert_strategy import ( - InsertStrategy, -) +from cirq.circuits.circuit import AbstractCircuit, Alignment, Circuit +from cirq.circuits.circuit_dag import CircuitDag, Unique +from cirq.circuits.circuit_operation import CircuitOperation +from cirq.circuits.frozen_circuit import FrozenCircuit +from cirq.circuits.insert_strategy import InsertStrategy -from cirq.circuits.moment import ( - Moment, -) +from cirq.circuits.moment import Moment -from cirq.circuits.optimization_pass import ( - PointOptimizer, - PointOptimizationSummary, -) +from cirq.circuits.optimization_pass import PointOptimizer, PointOptimizationSummary diff --git a/cirq-core/cirq/circuits/_block_diagram_drawer.py b/cirq-core/cirq/circuits/_block_diagram_drawer.py index 81e4cf33436..ec83240dea7 100644 --- a/cirq-core/cirq/circuits/_block_diagram_drawer.py +++ b/cirq-core/cirq/circuits/_block_diagram_drawer.py @@ -212,13 +212,11 @@ def render( # Determine desired size of diagram in blocks. if block_span_x is None: block_span_x = 1 + max( - max(x for x, _ in self._blocks.keys()), - max(self._min_widths.keys()), + max(x for x, _ in self._blocks.keys()), max(self._min_widths.keys()) ) if block_span_y is None: block_span_y = 1 + max( - max(y for _, y in self._blocks.keys()), - max(self._min_heights.keys()), + max(y for _, y in self._blocks.keys()), max(self._min_heights.keys()) ) # Method for accessing blocks without creating new entries. diff --git a/cirq-core/cirq/circuits/_bucket_priority_queue_test.py b/cirq-core/cirq/circuits/_bucket_priority_queue_test.py index de39008b4eb..2256ccb4312 100644 --- a/cirq-core/cirq/circuits/_bucket_priority_queue_test.py +++ b/cirq-core/cirq/circuits/_bucket_priority_queue_test.py @@ -55,18 +55,10 @@ def test_eq(): BucketPriorityQueue(entries=[(0, 'a')], drop_duplicate_entries=True), BucketPriorityQueue(entries=[(0, 'a'), (0, 'a')], drop_duplicate_entries=True), ) - eq.add_equality_group( - BucketPriorityQueue(entries=[(0, 'a')]), - ) - eq.add_equality_group( - BucketPriorityQueue(entries=[(0, 'a'), (0, 'a')]), - ) - eq.add_equality_group( - BucketPriorityQueue(entries=[(1, 'a')]), - ) - eq.add_equality_group( - BucketPriorityQueue(entries=[(0, 'b')]), - ) + eq.add_equality_group(BucketPriorityQueue(entries=[(0, 'a')])) + eq.add_equality_group(BucketPriorityQueue(entries=[(0, 'a'), (0, 'a')])) + eq.add_equality_group(BucketPriorityQueue(entries=[(1, 'a')])) + eq.add_equality_group(BucketPriorityQueue(entries=[(0, 'b')])) eq.add_equality_group( BucketPriorityQueue(entries=[(0, 'a'), (1, 'b')]), BucketPriorityQueue(entries=[(1, 'b'), (0, 'a')]), diff --git a/cirq-core/cirq/circuits/circuit.py b/cirq-core/cirq/circuits/circuit.py index 9f4251ebdb7..5013d183f3a 100644 --- a/cirq-core/cirq/circuits/circuit.py +++ b/cirq-core/cirq/circuits/circuit.py @@ -928,9 +928,7 @@ def _with_key_path_prefix_(self, prefix: Tuple[str, ...]): ) def _with_rescoped_keys_( - self, - path: Tuple[str, ...], - bindable_keys: FrozenSet['cirq.MeasurementKey'], + self, path: Tuple[str, ...], bindable_keys: FrozenSet['cirq.MeasurementKey'] ): moments = [] for moment in self.moments: @@ -1689,9 +1687,7 @@ class Circuit(AbstractCircuit): """ def __init__( - self, - *contents: 'cirq.OP_TREE', - strategy: 'cirq.InsertStrategy' = InsertStrategy.EARLIEST, + self, *contents: 'cirq.OP_TREE', strategy: 'cirq.InsertStrategy' = InsertStrategy.EARLIEST ) -> None: """Initializes a circuit. @@ -1826,8 +1822,7 @@ def zip( zip.__doc__ = AbstractCircuit.zip.__doc__ def transform_qubits( - self, - qubit_map: Union[Dict['cirq.Qid', 'cirq.Qid'], Callable[['cirq.Qid'], 'cirq.Qid']], + self, qubit_map: Union[Dict['cirq.Qid', 'cirq.Qid'], Callable[['cirq.Qid'], 'cirq.Qid']] ) -> 'cirq.Circuit': """Returns the same circuit, but with different qubits. @@ -1973,10 +1968,7 @@ def insert( """ moments_and_operations = list( ops.flatten_to_ops_or_moments( - ops.transform_op_tree( - moment_or_operation_tree, - preserve_moments=True, - ), + ops.transform_op_tree(moment_or_operation_tree, preserve_moments=True) ) ) # limit index to 0..len(self._moments), also deal with indices smaller 0 @@ -2313,9 +2305,7 @@ def with_noise(self, noise: 'cirq.NOISE_MODEL_LIKE') -> 'cirq.Circuit': def _pick_inserted_ops_moment_indices( - operations: Sequence['cirq.Operation'], - start: int = 0, - frontier: Dict['cirq.Qid', int] = None, + operations: Sequence['cirq.Operation'], start: int = 0, frontier: Dict['cirq.Qid', int] = None ) -> Tuple[Sequence[int], Dict['cirq.Qid', int]]: """Greedily assigns operations to moments. @@ -2351,9 +2341,7 @@ def _resolve_operations( return resolved_operations -def _get_moment_annotations( - moment: 'cirq.Moment', -) -> Iterator['cirq.Operation']: +def _get_moment_annotations(moment: 'cirq.Moment') -> Iterator['cirq.Operation']: for op in moment.operations: if op.qubits: continue diff --git a/cirq-core/cirq/circuits/circuit_dag_test.py b/cirq-core/cirq/circuits/circuit_dag_test.py index c4dd86ae797..4b9c37a5a1e 100644 --- a/cirq-core/cirq/circuits/circuit_dag_test.py +++ b/cirq-core/cirq/circuits/circuit_dag_test.py @@ -137,22 +137,10 @@ def test_to_circuit(): def test_equality(): q0, q1 = cirq.LineQubit.range(2) circuit1 = cirq.Circuit( - cirq.X(q0), - cirq.Y(q0), - cirq.Z(q1), - cirq.CZ(q0, q1), - cirq.X(q1), - cirq.Y(q1), - cirq.Z(q0), + cirq.X(q0), cirq.Y(q0), cirq.Z(q1), cirq.CZ(q0, q1), cirq.X(q1), cirq.Y(q1), cirq.Z(q0) ) circuit2 = cirq.Circuit( - cirq.Z(q1), - cirq.X(q0), - cirq.Y(q0), - cirq.CZ(q0, q1), - cirq.Z(q0), - cirq.X(q1), - cirq.Y(q1), + cirq.Z(q1), cirq.X(q0), cirq.Y(q0), cirq.CZ(q0, q1), cirq.Z(q0), cirq.X(q1), cirq.Y(q1) ) circuit3 = cirq.Circuit( cirq.X(q0), @@ -164,12 +152,7 @@ def test_equality(): cirq.Z(q0) ** 0.5, ) circuit4 = cirq.Circuit( - cirq.X(q0), - cirq.Y(q0), - cirq.Z(q1), - cirq.CZ(q0, q1), - cirq.X(q1), - cirq.Y(q1), + cirq.X(q0), cirq.Y(q0), cirq.Z(q1), cirq.CZ(q0, q1), cirq.X(q1), cirq.Y(q1) ) eq = cirq.testing.EqualsTester() @@ -177,12 +160,8 @@ def test_equality(): lambda: cirq.CircuitDag.from_circuit(circuit1), lambda: cirq.CircuitDag.from_circuit(circuit2), ) - eq.add_equality_group( - cirq.CircuitDag.from_circuit(circuit3), - ) - eq.add_equality_group( - cirq.CircuitDag.from_circuit(circuit4), - ) + eq.add_equality_group(cirq.CircuitDag.from_circuit(circuit3)) + eq.add_equality_group(cirq.CircuitDag.from_circuit(circuit4)) def test_larger_circuit(): diff --git a/cirq-core/cirq/circuits/circuit_operation.py b/cirq-core/cirq/circuits/circuit_operation.py index 58b9023c0e6..48e46976762 100644 --- a/cirq-core/cirq/circuits/circuit_operation.py +++ b/cirq-core/cirq/circuits/circuit_operation.py @@ -486,9 +486,7 @@ def _from_json_dict_( # Methods for constructing a similar object with one field modified. def repeat( - self, - repetitions: Optional[IntParam] = None, - repetition_ids: Optional[List[str]] = None, + self, repetitions: Optional[IntParam] = None, repetition_ids: Optional[List[str]] = None ) -> 'CircuitOperation': """Returns a copy of this operation repeated 'repetitions' times. Each repetition instance will be identified by a single repetition_id. @@ -550,9 +548,7 @@ def _with_key_path_prefix_(self, prefix: Tuple[str, ...]): return dataclasses.replace(self, parent_path=prefix + self.parent_path) def _with_rescoped_keys_( - self, - path: Tuple[str, ...], - bindable_keys: FrozenSet['cirq.MeasurementKey'], + self, path: Tuple[str, ...], bindable_keys: FrozenSet['cirq.MeasurementKey'] ): # The following line prevents binding to measurement keys in previous repeated subcircuits # "just because their repetition ids matched". If we eventually decide to change that @@ -571,8 +567,7 @@ def with_repetition_ids(self, repetition_ids: List[str]) -> 'cirq.CircuitOperati return self.replace(repetition_ids=repetition_ids) def with_qubit_mapping( - self, - qubit_map: Union[Dict['cirq.Qid', 'cirq.Qid'], Callable[['cirq.Qid'], 'cirq.Qid']], + self, qubit_map: Union[Dict['cirq.Qid', 'cirq.Qid'], Callable[['cirq.Qid'], 'cirq.Qid']] ) -> 'cirq.CircuitOperation': """Returns a copy of this operation with an updated qubit mapping. diff --git a/cirq-core/cirq/circuits/circuit_operation_test.py b/cirq-core/cirq/circuits/circuit_operation_test.py index 7b1cd884afd..2820bd1a654 100644 --- a/cirq-core/cirq/circuits/circuit_operation_test.py +++ b/cirq-core/cirq/circuits/circuit_operation_test.py @@ -20,11 +20,7 @@ import cirq from cirq.circuits.circuit_operation import _full_join_string_lists -ALL_SIMULATORS = ( - cirq.Simulator(), - cirq.DensityMatrixSimulator(), - cirq.CliffordSimulator(), -) +ALL_SIMULATORS = (cirq.Simulator(), cirq.DensityMatrixSimulator(), cirq.CliffordSimulator()) def test_properties(): @@ -198,11 +194,7 @@ def map_fn(qubit: 'cirq.Qid') -> 'cirq.Qid': def test_with_measurement_keys(): a, b = cirq.LineQubit.range(2) - circuit = cirq.FrozenCircuit( - cirq.X(a), - cirq.measure(b, key='mb'), - cirq.measure(a, key='ma'), - ) + circuit = cirq.FrozenCircuit(cirq.X(a), cirq.measure(b, key='mb'), cirq.measure(a, key='ma')) op_base = cirq.CircuitOperation(circuit) op_with_keys = op_base.with_measurement_key_mapping({'ma': 'pa', 'x': 'z'}) @@ -226,11 +218,7 @@ def test_with_params(): circuit = cirq.FrozenCircuit(cirq.Z(a) ** z_exp, cirq.X(a) ** x_exp, cirq.Z(a) ** delta) op_base = cirq.CircuitOperation(circuit) - param_dict = { - z_exp: 2, - x_exp: theta, - sympy.Symbol('k'): sympy.Symbol('phi'), - } + param_dict = {z_exp: 2, x_exp: theta, sympy.Symbol('k'): sympy.Symbol('phi')} op_with_params = op_base.with_params(param_dict) assert op_with_params.base_operation() == op_base assert op_with_params.param_resolver == cirq.ParamResolver( @@ -252,10 +240,7 @@ def test_recursive_params(): q = cirq.LineQubit(0) a, a2, b, b2 = sympy.symbols('a a2 b b2') circuitop = cirq.CircuitOperation( - cirq.FrozenCircuit( - cirq.X(q) ** a, - cirq.Z(q) ** b, - ), + cirq.FrozenCircuit(cirq.X(q) ** a, cirq.Z(q) ** b), # Not recursive, a and b are swapped. param_resolver=cirq.ParamResolver({a: b, b: a}), ) @@ -615,10 +600,7 @@ def test_string_format(): )""" ) - fc3 = cirq.FrozenCircuit( - cirq.X(x) ** sympy.Symbol('b'), - cirq.measure(x, key='m'), - ) + fc3 = cirq.FrozenCircuit(cirq.X(x) ** sympy.Symbol('b'), cirq.measure(x, key='m')) op3 = cirq.CircuitOperation( circuit=fc3, qubit_map={x: y}, @@ -735,10 +717,7 @@ def test_json_dict(): def test_terminal_matches(): a, b = cirq.LineQubit.range(2) - fc = cirq.FrozenCircuit( - cirq.H(a), - cirq.measure(b, key='m1'), - ) + fc = cirq.FrozenCircuit(cirq.H(a), cirq.measure(b, key='m1')) op = cirq.CircuitOperation(fc) c = cirq.Circuit(cirq.X(a), op) @@ -776,11 +755,7 @@ def test_terminal_matches(): def test_nonterminal_in_subcircuit(): a, b = cirq.LineQubit.range(2) - fc = cirq.FrozenCircuit( - cirq.H(a), - cirq.measure(b, key='m1'), - cirq.X(b), - ) + fc = cirq.FrozenCircuit(cirq.H(a), cirq.measure(b, key='m1'), cirq.X(b)) op = cirq.CircuitOperation(fc) c = cirq.Circuit(cirq.X(a), op) assert isinstance(op, cirq.CircuitOperation) @@ -807,10 +782,7 @@ def test_decompose_applies_maps(): ) op = cirq.CircuitOperation( circuit=circuit, - qubit_map={ - c: b, - b: c, - }, + qubit_map={c: b, b: c}, measurement_key_map={'m': 'p'}, param_resolver={exp: theta, theta: exp}, ) @@ -827,40 +799,23 @@ def test_decompose_applies_maps(): def test_decompose_loops(): a, b = cirq.LineQubit.range(2) - circuit = cirq.FrozenCircuit( - cirq.H(a), - cirq.CX(a, b), - ) + circuit = cirq.FrozenCircuit(cirq.H(a), cirq.CX(a, b)) base_op = cirq.CircuitOperation(circuit) op = base_op.with_qubits(b, a).repeat(3) expected_circuit = cirq.Circuit( - cirq.H(b), - cirq.CX(b, a), - cirq.H(b), - cirq.CX(b, a), - cirq.H(b), - cirq.CX(b, a), + cirq.H(b), cirq.CX(b, a), cirq.H(b), cirq.CX(b, a), cirq.H(b), cirq.CX(b, a) ) assert cirq.Circuit(cirq.decompose_once(op)) == expected_circuit op = base_op.repeat(-2) - expected_circuit = cirq.Circuit( - cirq.CX(a, b), - cirq.H(a), - cirq.CX(a, b), - cirq.H(a), - ) + expected_circuit = cirq.Circuit(cirq.CX(a, b), cirq.H(a), cirq.CX(a, b), cirq.H(a)) assert cirq.Circuit(cirq.decompose_once(op)) == expected_circuit def test_decompose_loops_with_measurements(): a, b = cirq.LineQubit.range(2) - circuit = cirq.FrozenCircuit( - cirq.H(a), - cirq.CX(a, b), - cirq.measure(a, b, key='m'), - ) + circuit = cirq.FrozenCircuit(cirq.H(a), cirq.CX(a, b), cirq.measure(a, b, key='m')) base_op = cirq.CircuitOperation(circuit) op = base_op.with_qubits(b, a).repeat(3) @@ -1048,12 +1003,7 @@ def test_tag_propagation(): # Tags are not propagated from the CircuitOperation to its components. # TODO: support tag propagation for better serialization. a, b, c = cirq.LineQubit.range(3) - circuit = cirq.FrozenCircuit( - cirq.X(a), - cirq.H(b), - cirq.H(c), - cirq.CZ(a, c), - ) + circuit = cirq.FrozenCircuit(cirq.X(a), cirq.H(b), cirq.H(c), cirq.CZ(a, c)) op = cirq.CircuitOperation(circuit) test_tag = 'test_tag' op = op.with_tags(test_tag) @@ -1082,25 +1032,17 @@ def test_mapped_circuit_keeps_keys_under_parent_path(): def test_mapped_circuit_allows_repeated_keys(): q = cirq.LineQubit(0) - op1 = cirq.CircuitOperation( - cirq.FrozenCircuit( - cirq.measure(q, key='A'), - ) - ) + op1 = cirq.CircuitOperation(cirq.FrozenCircuit(cirq.measure(q, key='A'))) op2 = cirq.CircuitOperation(cirq.FrozenCircuit(op1, op1)) circuit = op2.mapped_circuit(deep=True) cirq.testing.assert_has_diagram( - circuit, - "0: ───M('A')───M('A')───", - use_unicode_characters=True, + circuit, "0: ───M('A')───M('A')───", use_unicode_characters=True ) op1 = cirq.measure(q, key='A') op2 = cirq.CircuitOperation(cirq.FrozenCircuit(op1, op1)) circuit = op2.mapped_circuit() cirq.testing.assert_has_diagram( - circuit, - "0: ───M('A')───M('A')───", - use_unicode_characters=True, + circuit, "0: ───M('A')───M('A')───", use_unicode_characters=True ) @@ -1154,10 +1096,7 @@ def test_repeat_until(sim): c = cirq.Circuit( cirq.X(q), cirq.CircuitOperation( - cirq.FrozenCircuit( - cirq.X(q), - cirq.measure(q, key=key), - ), + cirq.FrozenCircuit(cirq.X(q), cirq.measure(q, key=key)), use_repetition_ids=False, repeat_until=cirq.KeyCondition(key), ), @@ -1172,17 +1111,11 @@ def test_repeat_until(sim): def test_repeat_until_sympy(sim): q1, q2 = cirq.LineQubit.range(2) circuitop = cirq.CircuitOperation( - cirq.FrozenCircuit( - cirq.X(q2), - cirq.measure(q2, key='b'), - ), + cirq.FrozenCircuit(cirq.X(q2), cirq.measure(q2, key='b')), use_repetition_ids=False, repeat_until=cirq.SympyCondition(sympy.Eq(sympy.Symbol('a'), sympy.Symbol('b'))), ) - c = cirq.Circuit( - cirq.measure(q1, key='a'), - circuitop, - ) + c = cirq.Circuit(cirq.measure(q1, key='a'), circuitop) # Validate commutation assert len(c) == 2 assert cirq.control_keys(circuitop) == {cirq.MeasurementKey('a')} @@ -1198,13 +1131,10 @@ def test_post_selection(sim): key = cirq.MeasurementKey('m') c = cirq.Circuit( cirq.CircuitOperation( - cirq.FrozenCircuit( - cirq.X(q) ** 0.2, - cirq.measure(q, key=key), - ), + cirq.FrozenCircuit(cirq.X(q) ** 0.2, cirq.measure(q, key=key)), use_repetition_ids=False, repeat_until=cirq.KeyCondition(key), - ), + ) ) result = sim.run(c) assert result.records['m'][0][-1] == (1,) @@ -1217,13 +1147,10 @@ def test_repeat_until_diagram(): key = cirq.MeasurementKey('m') c = cirq.Circuit( cirq.CircuitOperation( - cirq.FrozenCircuit( - cirq.X(q) ** 0.2, - cirq.measure(q, key=key), - ), + cirq.FrozenCircuit(cirq.X(q) ** 0.2, cirq.measure(q, key=key)), use_repetition_ids=False, repeat_until=cirq.KeyCondition(key), - ), + ) ) cirq.testing.assert_has_diagram( c, diff --git a/cirq-core/cirq/circuits/circuit_test.py b/cirq-core/cirq/circuits/circuit_test.py index f1d7c131a0f..d1e0873bcc6 100644 --- a/cirq-core/cirq/circuits/circuit_test.py +++ b/cirq-core/cirq/circuits/circuit_test.py @@ -44,12 +44,7 @@ def can_add_operation_into_moment( FOXY = _Foxy( allowed_qubit_types=(cirq.GridQubit,), - allowed_gates=( - ops.CZPowGate, - ops.XPowGate, - ops.YPowGate, - ops.ZPowGate, - ), + allowed_gates=(ops.CZPowGate, ops.XPowGate, ops.YPowGate, ops.ZPowGate), qubits=set(cirq.GridQubit.rect(2, 7)), name=f'{__name__}.FOXY', auto_decompose_gates=(ops.CCXPowGate,), @@ -60,9 +55,7 @@ def can_add_operation_into_moment( BCONE = ValidatingTestDevice( allowed_qubit_types=(cirq.GridQubit,), allowed_gates=(ops.XPowGate,), - qubits={ - cirq.GridQubit(0, 6), - }, + qubits={cirq.GridQubit(0, 6)}, name=f'{__name__}.BCONE', ) @@ -119,11 +112,7 @@ def test_equality(circuit_cls): eq = cirq.testing.EqualsTester() # Default is empty. Iterables get listed. - eq.add_equality_group( - circuit_cls(), - circuit_cls([]), - circuit_cls(()), - ) + eq.add_equality_group(circuit_cls(), circuit_cls([]), circuit_cls(())) eq.add_equality_group(circuit_cls([cirq.Moment()]), circuit_cls((cirq.Moment(),))) # Equality depends on structure and contents. @@ -142,14 +131,7 @@ def test_equality(circuit_cls): ] ) ) - eq.add_equality_group( - circuit_cls( - [ - cirq.Moment([cirq.H(a)]), - cirq.Moment([cirq.CNOT(a, b)]), - ] - ) - ) + eq.add_equality_group(circuit_cls([cirq.Moment([cirq.H(a)]), cirq.Moment([cirq.CNOT(a, b)])])) @pytest.mark.parametrize('circuit_cls', [cirq.Circuit, cirq.FrozenCircuit]) @@ -222,20 +204,12 @@ def test_append_multiple(): c = cirq.Circuit() c.append([cirq.X(a), cirq.X(b)], cirq.InsertStrategy.EARLIEST) - assert c == cirq.Circuit( - [ - cirq.Moment([cirq.X(a), cirq.X(b)]), - ] - ) + assert c == cirq.Circuit([cirq.Moment([cirq.X(a), cirq.X(b)])]) c = cirq.Circuit() c.append(cirq.X(a), cirq.InsertStrategy.EARLIEST) c.append(cirq.X(b), cirq.InsertStrategy.EARLIEST) - assert c == cirq.Circuit( - [ - cirq.Moment([cirq.X(a), cirq.X(b)]), - ] - ) + assert c == cirq.Circuit([cirq.Moment([cirq.X(a), cirq.X(b)])]) def test_append_control_key_subcircuit(): @@ -310,11 +284,7 @@ def test_append_moments(): c = cirq.Circuit() c.append(cirq.Moment([cirq.X(a), cirq.X(b)]), cirq.InsertStrategy.NEW) - assert c == cirq.Circuit( - [ - cirq.Moment([cirq.X(a), cirq.X(b)]), - ] - ) + assert c == cirq.Circuit([cirq.Moment([cirq.X(a), cirq.X(b)])]) c = cirq.Circuit() c.append( @@ -322,10 +292,7 @@ def test_append_moments(): cirq.InsertStrategy.NEW, ) assert c == cirq.Circuit( - [ - cirq.Moment([cirq.X(a), cirq.X(b)]), - cirq.Moment([cirq.X(a), cirq.X(b)]), - ] + [cirq.Moment([cirq.X(a), cirq.X(b)]), cirq.Moment([cirq.X(a), cirq.X(b)])] ) @@ -335,11 +302,7 @@ def test_add_op_tree(circuit_cls): b = cirq.NamedQubit('b') c = circuit_cls() - assert c + [cirq.X(a), cirq.Y(b)] == circuit_cls( - [ - cirq.Moment([cirq.X(a), cirq.Y(b)]), - ] - ) + assert c + [cirq.X(a), cirq.Y(b)] == circuit_cls([cirq.Moment([cirq.X(a), cirq.Y(b)])]) assert c + cirq.X(a) == circuit_cls(cirq.X(a)) assert c + [cirq.X(a)] == circuit_cls(cirq.X(a)) @@ -356,11 +319,7 @@ def test_radd_op_tree(circuit_cls): b = cirq.NamedQubit('b') c = circuit_cls() - assert [cirq.X(a), cirq.Y(b)] + c == circuit_cls( - [ - cirq.Moment([cirq.X(a), cirq.Y(b)]), - ] - ) + assert [cirq.X(a), cirq.Y(b)] + c == circuit_cls([cirq.Moment([cirq.X(a), cirq.Y(b)])]) assert cirq.X(a) + c == circuit_cls(cirq.X(a)) assert [cirq.X(a)] + c == circuit_cls(cirq.X(a)) @@ -406,11 +365,7 @@ def test_repr(circuit_cls): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') c = circuit_cls( - [ - cirq.Moment([cirq.H(a), cirq.H(b)]), - cirq.Moment(), - cirq.Moment([cirq.CZ(a, b)]), - ] + [cirq.Moment([cirq.H(a), cirq.H(b)]), cirq.Moment(), cirq.Moment([cirq.CZ(a, b)])] ) cirq.testing.assert_equivalent_repr(c) assert ( @@ -859,29 +814,13 @@ def test_insert_inline_near_start(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') - c = cirq.Circuit( - [ - cirq.Moment(), - cirq.Moment(), - ] - ) + c = cirq.Circuit([cirq.Moment(), cirq.Moment()]) c.insert(1, cirq.X(a), strategy=cirq.InsertStrategy.INLINE) - assert c == cirq.Circuit( - [ - cirq.Moment([cirq.X(a)]), - cirq.Moment(), - ] - ) + assert c == cirq.Circuit([cirq.Moment([cirq.X(a)]), cirq.Moment()]) c.insert(1, cirq.Y(a), strategy=cirq.InsertStrategy.INLINE) - assert c == cirq.Circuit( - [ - cirq.Moment([cirq.X(a)]), - cirq.Moment([cirq.Y(a)]), - cirq.Moment(), - ] - ) + assert c == cirq.Circuit([cirq.Moment([cirq.X(a)]), cirq.Moment([cirq.Y(a)]), cirq.Moment()]) c.insert(0, cirq.Z(b), strategy=cirq.InsertStrategy.INLINE) assert c == cirq.Circuit( @@ -1163,12 +1102,7 @@ def test_prev_moment_operating_on(circuit_cls): assert c.prev_moment_operating_on([b]) is None c = circuit_cls( - [ - cirq.Moment([cirq.CZ(a, b)]), - cirq.Moment(), - cirq.Moment([cirq.X(a)]), - cirq.Moment(), - ] + [cirq.Moment([cirq.CZ(a, b)]), cirq.Moment(), cirq.Moment([cirq.X(a)]), cirq.Moment()] ) assert c.prev_moment_operating_on([a], 4) == 2 @@ -1342,7 +1276,7 @@ def test_findall_operations_with_gate(circuit_cls): (2, cirq.X(b), cirq.X), ] assert list(c.findall_operations_with_gate_type(cirq.CZPowGate)) == [ - (3, cirq.CZ(a, b), cirq.CZ), + (3, cirq.CZ(a, b), cirq.CZ) ] assert list(c.findall_operations_with_gate_type(cirq.MeasurementGate)) == [ (4, cirq.MeasurementGate(1, key='a').on(a), cirq.MeasurementGate(1, key='a')), @@ -1885,27 +1819,13 @@ def test_all_qubits(circuit_cls): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') - c = circuit_cls( - [ - cirq.Moment([cirq.X(a)]), - cirq.Moment([cirq.X(b)]), - ] - ) + c = circuit_cls([cirq.Moment([cirq.X(a)]), cirq.Moment([cirq.X(b)])]) assert c.all_qubits() == {a, b} - c = circuit_cls( - [ - cirq.Moment([cirq.X(a)]), - cirq.Moment([cirq.X(a)]), - ] - ) + c = circuit_cls([cirq.Moment([cirq.X(a)]), cirq.Moment([cirq.X(a)])]) assert c.all_qubits() == {a} - c = circuit_cls( - [ - cirq.Moment([cirq.CZ(a, b)]), - ] - ) + c = circuit_cls([cirq.Moment([cirq.CZ(a, b)])]) assert c.all_qubits() == {a, b} c = circuit_cls([cirq.Moment([cirq.CZ(a, b)]), cirq.Moment([cirq.X(a)])]) @@ -1917,34 +1837,16 @@ def test_all_operations(circuit_cls): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') - c = circuit_cls( - [ - cirq.Moment([cirq.X(a)]), - cirq.Moment([cirq.X(b)]), - ] - ) + c = circuit_cls([cirq.Moment([cirq.X(a)]), cirq.Moment([cirq.X(b)])]) assert list(c.all_operations()) == [cirq.X(a), cirq.X(b)] - c = circuit_cls( - [ - cirq.Moment([cirq.X(a), cirq.X(b)]), - ] - ) + c = circuit_cls([cirq.Moment([cirq.X(a), cirq.X(b)])]) assert list(c.all_operations()) == [cirq.X(a), cirq.X(b)] - c = circuit_cls( - [ - cirq.Moment([cirq.X(a)]), - cirq.Moment([cirq.X(a)]), - ] - ) + c = circuit_cls([cirq.Moment([cirq.X(a)]), cirq.Moment([cirq.X(a)])]) assert list(c.all_operations()) == [cirq.X(a), cirq.X(a)] - c = circuit_cls( - [ - cirq.Moment([cirq.CZ(a, b)]), - ] - ) + c = circuit_cls([cirq.Moment([cirq.CZ(a, b)])]) assert list(c.all_operations()) == [cirq.CZ(a, b)] c = circuit_cls([cirq.Moment([cirq.CZ(a, b)]), cirq.Moment([cirq.X(a)])]) @@ -1970,12 +1872,7 @@ def test_qid_shape_qubit(circuit_cls): b = cirq.NamedQubit('b') c = cirq.NamedQubit('c') - circuit = circuit_cls( - [ - cirq.Moment([cirq.X(a)]), - cirq.Moment([cirq.X(b)]), - ] - ) + circuit = circuit_cls([cirq.Moment([cirq.X(a)]), cirq.Moment([cirq.X(b)])]) assert cirq.qid_shape(circuit) == (2, 2) assert cirq.num_qubits(circuit) == 2 @@ -2001,11 +1898,7 @@ def _qid_shape_(self): a, b, c = cirq.LineQid.for_qid_shape((3, 2, 1)) - circuit = circuit_cls( - PlusOneMod3Gate().on(a), - C2NotGate().on(a, b), - IdentityGate().on_each(c), - ) + circuit = circuit_cls(PlusOneMod3Gate().on(a), C2NotGate().on(a, b), IdentityGate().on_each(c)) assert cirq.num_qubits(circuit) == 3 assert cirq.qid_shape(circuit) == (3, 2, 1) @@ -2106,10 +1999,7 @@ def _circuit_diagram_info_( ) -> cirq.CircuitDiagramInfo: return cirq.CircuitDiagramInfo(wire_symbols=('W',), exponent='fancy-that') - c = circuit_cls( - WeirdGate().on(cirq.NamedQubit('q')), - WeirderGate().on(cirq.NamedQubit('q')), - ) + c = circuit_cls(WeirdGate().on(cirq.NamedQubit('q')), WeirderGate().on(cirq.NamedQubit('q'))) # The hyphen in the exponent should cause parens to appear. cirq.testing.assert_has_diagram(c, 'q: ───B^fancy───W^(fancy-that)───') @@ -2134,11 +2024,7 @@ def __repr__(self): # Fallback to repr. f = FGate() cirq.testing.assert_has_diagram( - circuit_cls( - [ - cirq.Moment([f.on(q)]), - ] - ), + circuit_cls([cirq.Moment([f.on(q)])]), """ (0, 0): ---python-object-FGate:arbitrary-digits--- """, @@ -2148,11 +2034,7 @@ def __repr__(self): f3 = FGate(3) # When used on multiple qubits, show the qubit order as a digit suffix. cirq.testing.assert_has_diagram( - circuit_cls( - [ - cirq.Moment([f3.on(q, q3, q2)]), - ] - ), + circuit_cls([cirq.Moment([f3.on(q, q3, q2)])]), """ (0, 0): ---python-object-FGate:arbitrary-digits--- | @@ -2444,6 +2326,7 @@ def test_circuit_to_unitary_matrix(circuit_cls): # Single qubit gates. cirq.testing.assert_allclose_up_to_global_phase( circuit_cls(cirq.X(a) ** 0.5).unitary(), + # fmt: off np.array( [ [1j, 1], @@ -2451,6 +2334,7 @@ def test_circuit_to_unitary_matrix(circuit_cls): ] ) * np.sqrt(0.5), + # fmt: on atol=1e-8, ) cirq.testing.assert_allclose_up_to_global_phase( @@ -2458,6 +2342,7 @@ def test_circuit_to_unitary_matrix(circuit_cls): ) cirq.testing.assert_allclose_up_to_global_phase( circuit_cls(cirq.Z(a), cirq.X(b)).unitary(), + # fmt: off np.array( [ [0, 1, 0, 0], @@ -2466,10 +2351,12 @@ def test_circuit_to_unitary_matrix(circuit_cls): [0, 0, -1, 0], ] ), + # fmt: on atol=1e-8, ) # Single qubit gates and two qubit gate. + # fmt: off cirq.testing.assert_allclose_up_to_global_phase( circuit_cls(cirq.Z(a), cirq.X(b), cirq.CNOT(a, b)).unitary(), np.array( @@ -2495,6 +2382,7 @@ def test_circuit_to_unitary_matrix(circuit_cls): * np.sqrt(0.25), atol=1e-8, ) + # fmt: on # Measurement gate has no corresponding matrix. c = circuit_cls(cirq.measure(a)) @@ -2507,9 +2395,17 @@ def test_circuit_to_unitary_matrix(circuit_cls): # Ignoring terminal measurements with further cirq. c = circuit_cls(cirq.Z(a), cirq.measure(a), cirq.Z(b)) + # fmt: off cirq.testing.assert_allclose_up_to_global_phase( - c.unitary(), np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]]), atol=1e-8 + c.unitary(), np.array( + [ + [1, 0, 0, 0], + [0, -1, 0, 0], + [0, 0, -1, 0], + [0, 0, 0, 1], + ]), atol=1e-8 ) + # fmt: on # Optionally don't ignoring terminal measurements. c = circuit_cls(cirq.measure(a)) @@ -2555,17 +2451,8 @@ def test_circuit_unitary(circuit_cls): assert cirq.unitary(with_inner_measure, None) is None cirq.testing.assert_allclose_up_to_global_phase( - cirq.unitary( - circuit_cls(cirq.X(q) ** 0.5), - cirq.measure(q), - ), - np.array( - [ - [1j, 1], - [1, 1j], - ] - ) - * np.sqrt(0.5), + cirq.unitary(circuit_cls(cirq.X(q) ** 0.5), cirq.measure(q)), + np.array([[1j, 1], [1, 1j]]) * np.sqrt(0.5), atol=1e-8, ) @@ -2579,6 +2466,7 @@ def test_simple_circuits_to_unitary_matrix(circuit_cls): c = circuit_cls(cirq.CNOT(a, b), cirq.Z(b), cirq.CNOT(a, b)) assert cirq.has_unitary(c) m = c.unitary() + # fmt: off cirq.testing.assert_allclose_up_to_global_phase( m, np.array( @@ -2591,6 +2479,7 @@ def test_simple_circuits_to_unitary_matrix(circuit_cls): ), atol=1e-8, ) + # fmt: on # 2-qubit matrix matches when qubits in order. for expected in [np.diag([1, 1j, -1, -1j]), cirq.unitary(cirq.CNOT)]: @@ -2638,7 +2527,16 @@ def test_circuit_superoperator_too_many_qubits(): (cirq.Circuit(cirq.IdentityGate(2).on(q0, q1)), np.eye(16)), ( cirq.Circuit(cirq.H(q0)), - np.array([[1, 1, 1, 1], [1, -1, 1, -1], [1, 1, -1, -1], [1, -1, -1, 1]]) / 2, + # fmt: off + np.array( + [ + [1, 1, 1, 1], + [1, -1, 1, -1], + [1, 1, -1, -1], + [1, -1, -1, 1] + ] + ) / 2, + # fmt: on ), (cirq.Circuit(cirq.S(q0)), np.diag([1, -1j, 1j, 1])), (cirq.Circuit(cirq.depolarize(0.75).on(q0)), np.outer([1, 0, 0, 1], [1, 0, 0, 1]) / 2), @@ -2834,11 +2732,7 @@ def _circuit_diagram_info_(self, args: cirq.CircuitDiagramInfoArgs) -> Tuple[str @pytest.mark.parametrize('circuit_cls', [cirq.Circuit, cirq.FrozenCircuit]) def test_transposed_diagram_exponent_order(circuit_cls): a, b, c = cirq.LineQubit.range(3) - circuit = circuit_cls( - cirq.CZ(a, b) ** -0.5, - cirq.CZ(a, c) ** 0.5, - cirq.CZ(b, c) ** 0.125, - ) + circuit = circuit_cls(cirq.CZ(a, b) ** -0.5, cirq.CZ(a, c) ** 0.5, cirq.CZ(b, c) ** 0.125) cirq.testing.assert_has_diagram( circuit, """ @@ -3180,14 +3074,7 @@ def test_batch_remove(): after.batch_remove( [(0, cirq.X(a)), (1, cirq.Z(b)), (2, cirq.CZ(a, b)), (3, cirq.X(a)), (3, cirq.X(b))] ) - assert after == cirq.Circuit( - [ - cirq.Moment(), - cirq.Moment(), - cirq.Moment(), - cirq.Moment(), - ] - ) + assert after == cirq.Circuit([cirq.Moment(), cirq.Moment(), cirq.Moment(), cirq.Moment()]) # Delete moment partially. after = original.copy() @@ -3408,13 +3295,7 @@ def test_batch_insert_multiple_same_index(): c = cirq.Circuit() c.batch_insert([(0, cirq.Z(a)), (0, cirq.Z(b)), (0, cirq.Z(a))]) cirq.testing.assert_same_circuits( - c, - cirq.Circuit( - [ - cirq.Moment([cirq.Z(a), cirq.Z(b)]), - cirq.Moment([cirq.Z(a)]), - ] - ), + c, cirq.Circuit([cirq.Moment([cirq.Z(a), cirq.Z(b)]), cirq.Moment([cirq.Z(a)])]) ) @@ -3437,13 +3318,7 @@ def test_batch_insert_doesnt_overshift_due_to_previous_shifts(): c = cirq.Circuit([cirq.H(a)] * 3) c.batch_insert([(0, cirq.Z(a)), (0, cirq.Z(a)), (1, cirq.X(a)), (2, cirq.Y(a))]) assert c == cirq.Circuit( - cirq.Z(a), - cirq.Z(a), - cirq.H(a), - cirq.X(a), - cirq.H(a), - cirq.Y(a), - cirq.H(a), + cirq.Z(a), cirq.Z(a), cirq.H(a), cirq.X(a), cirq.H(a), cirq.Y(a), cirq.H(a) ) @@ -3588,9 +3463,7 @@ def test_insert_operations_errors(): @pytest.mark.parametrize('circuit_cls', [cirq.Circuit, cirq.FrozenCircuit]) def test_to_qasm(circuit_cls): q0 = cirq.NamedQubit('q0') - circuit = circuit_cls( - cirq.X(q0), - ) + circuit = circuit_cls(cirq.X(q0)) assert circuit.to_qasm() == cirq.qasm(circuit) assert ( circuit.to_qasm() @@ -3613,9 +3486,7 @@ def test_to_qasm(circuit_cls): def test_save_qasm(tmpdir, circuit_cls): file_path = os.path.join(tmpdir, 'test.qasm') q0 = cirq.NamedQubit('q0') - circuit = circuit_cls( - cirq.X(q0), - ) + circuit = circuit_cls(cirq.X(q0)) circuit.save_qasm(file_path) with open(file_path, 'r') as f: @@ -3676,10 +3547,7 @@ def test_findall_operations_between(circuit_cls): # Default end_frontier value is len(circuit. actual = circuit.findall_operations_between(start_frontier={a: 5}, end_frontier={}) - assert actual == [ - (11, cirq.CZ(a, b)), - (12, cirq.H(a)), - ] + assert actual == [(11, cirq.CZ(a, b)), (12, cirq.H(a))] # Default start_frontier value is 0. actual = circuit.findall_operations_between(start_frontier={}, end_frontier={a: 5}) @@ -3689,19 +3557,13 @@ def test_findall_operations_between(circuit_cls): actual = circuit.findall_operations_between( start_frontier={a: 5}, end_frontier={}, omit_crossing_operations=True ) - assert actual == [ - (12, cirq.H(a)), - ] + assert actual == [(12, cirq.H(a))] # omit_crossing_operations keeps operations across included regions. actual = circuit.findall_operations_between( start_frontier={a: 5, b: 5}, end_frontier={}, omit_crossing_operations=True ) - assert actual == [ - (10, cirq.H(b)), - (11, cirq.CZ(a, b)), - (12, cirq.H(a)), - ] + assert actual == [(10, cirq.H(b)), (11, cirq.CZ(a, b)), (12, cirq.H(a))] # Regions are OR'd together, not AND'd together. actual = circuit.findall_operations_between(start_frontier={a: 5}, end_frontier={b: 5}) @@ -3715,28 +3577,15 @@ def test_findall_operations_between(circuit_cls): # Regions are OR'd together, not AND'd together (2). actual = circuit.findall_operations_between(start_frontier={a: 5}, end_frontier={a: 5, b: 5}) - assert actual == [ - (1, cirq.CZ(a, b)), - (2, cirq.H(b)), - (3, cirq.CZ(b, c)), - ] + assert actual == [(1, cirq.CZ(a, b)), (2, cirq.H(b)), (3, cirq.CZ(b, c))] # Inclusive start, exclusive end. actual = circuit.findall_operations_between(start_frontier={c: 4}, end_frontier={c: 8}) - assert actual == [ - (4, cirq.H(c)), - (5, cirq.CZ(c, d)), - (7, cirq.CZ(c, d)), - ] + assert actual == [(4, cirq.H(c)), (5, cirq.CZ(c, d)), (7, cirq.CZ(c, d))] # Out of range is clamped. actual = circuit.findall_operations_between(start_frontier={a: -100}, end_frontier={a: +100}) - assert actual == [ - (0, cirq.H(a)), - (1, cirq.CZ(a, b)), - (11, cirq.CZ(a, b)), - (12, cirq.H(a)), - ] + assert actual == [(0, cirq.H(a)), (1, cirq.CZ(a, b)), (11, cirq.CZ(a, b)), (12, cirq.H(a))] @pytest.mark.parametrize('circuit_cls', [cirq.Circuit, cirq.FrozenCircuit]) @@ -3922,11 +3771,7 @@ def test_decompose(circuit_cls): @pytest.mark.parametrize('circuit_cls', [cirq.Circuit, cirq.FrozenCircuit]) def test_measurement_key_mapping(circuit_cls): a, b = cirq.LineQubit.range(2) - c = circuit_cls( - cirq.X(a), - cirq.measure(a, key='m1'), - cirq.measure(b, key='m2'), - ) + c = circuit_cls(cirq.X(a), cirq.measure(a, key='m1'), cirq.measure(b, key='m2')) assert c.all_measurement_key_names() == {'m1', 'm2'} assert cirq.with_measurement_key_mapping(c, {'m1': 'p1'}).all_measurement_key_names() == { @@ -3946,12 +3791,10 @@ 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]) @@ -4058,9 +3901,7 @@ def test_json_dict(circuit_cls): moments = [cirq.Moment([cirq.CNOT(q0, q1)])] if circuit_cls == cirq.FrozenCircuit: moments = tuple(moments) - assert c._json_dict_() == { - 'moments': moments, - } + assert c._json_dict_() == {'moments': moments} def test_with_noise(): @@ -4071,40 +3912,14 @@ def noisy_operation(self, operation): yield cirq.H(cirq.LineQubit(0)) q0, q1 = cirq.LineQubit.range(2) - c = cirq.Circuit( - cirq.X(q0), - cirq.Y(q1), - cirq.Z(q1), - cirq.Moment([cirq.X(q0)]), - ) + c = cirq.Circuit(cirq.X(q0), cirq.Y(q1), cirq.Z(q1), cirq.Moment([cirq.X(q0)])) c_expected = cirq.Circuit( [ - cirq.Moment( - [ - cirq.X(q0), - cirq.Y(q1), - ] - ), - cirq.Moment( - [ - cirq.H(q0), - ] - ), - cirq.Moment( - [ - cirq.Z(q1), - ] - ), - cirq.Moment( - [ - cirq.X(q0), - ] - ), - cirq.Moment( - [ - cirq.H(q0), - ] - ), + cirq.Moment([cirq.X(q0), cirq.Y(q1)]), + cirq.Moment([cirq.H(q0)]), + cirq.Moment([cirq.Z(q1)]), + cirq.Moment([cirq.X(q0)]), + cirq.Moment([cirq.H(q0)]), ] ) c_noisy = c.with_noise(Noise()) @@ -4129,29 +3944,18 @@ def test_init_contents(circuit_cls): # Moments are not subject to insertion rules. c = circuit_cls( - cirq.Moment([cirq.H(a)]), - cirq.Moment([cirq.X(b)]), - cirq.Moment([cirq.CNOT(a, b)]), + cirq.Moment([cirq.H(a)]), cirq.Moment([cirq.X(b)]), cirq.Moment([cirq.CNOT(a, b)]) ) assert len(c.moments) == 3 # Earliest packing by default. - c = circuit_cls( - cirq.H(a), - cirq.X(b), - cirq.CNOT(a, b), - ) - assert c == circuit_cls( - cirq.Moment([cirq.H(a), cirq.X(b)]), - cirq.Moment([cirq.CNOT(a, b)]), - ) + c = circuit_cls(cirq.H(a), cirq.X(b), cirq.CNOT(a, b)) + assert c == circuit_cls(cirq.Moment([cirq.H(a), cirq.X(b)]), cirq.Moment([cirq.CNOT(a, b)])) # Packing can be controlled. c = circuit_cls(cirq.H(a), cirq.X(b), cirq.CNOT(a, b), strategy=cirq.InsertStrategy.NEW) assert c == circuit_cls( - cirq.Moment([cirq.H(a)]), - cirq.Moment([cirq.X(b)]), - cirq.Moment([cirq.CNOT(a, b)]), + cirq.Moment([cirq.H(a)]), cirq.Moment([cirq.X(b)]), cirq.Moment([cirq.CNOT(a, b)]) ) circuit_cls() @@ -4260,31 +4064,15 @@ def test_indexing_by_pair(circuit_cls): ) # Indexing by several moments and one qubit. - assert c[1:3, q[0]] == circuit_cls( - [ - cirq.H(q[1]).controlled_by(q[0]), - cirq.X(q[0]), - ] - ) - assert c[1::2, q[2]] == circuit_cls( - [ - cirq.Moment([]), - cirq.Moment([cirq.CCNOT(*q)]), - ] - ) + assert c[1:3, q[0]] == circuit_cls([cirq.H(q[1]).controlled_by(q[0]), cirq.X(q[0])]) + assert c[1::2, q[2]] == circuit_cls([cirq.Moment([]), cirq.Moment([cirq.CCNOT(*q)])]) # Indexing by several moments and several qubits. assert c[0:2, q[1:3]] == circuit_cls( - [ - cirq.Moment([]), - cirq.Moment([cirq.H(q[1]).controlled_by(q[0])]), - ] + [cirq.Moment([]), cirq.Moment([cirq.H(q[1]).controlled_by(q[0])])] ) assert c[::2, q[0:2]] == circuit_cls( - [ - cirq.Moment([cirq.H(q[0])]), - cirq.Moment([cirq.H(q[2]).controlled_by(q[1]), cirq.X(q[0])]), - ] + [cirq.Moment([cirq.H(q[0])]), cirq.Moment([cirq.H(q[2]).controlled_by(q[1]), cirq.X(q[0])])] ) # Equivalent ways of indexing. @@ -4335,20 +4123,10 @@ def _measurement_key_name_(self): # Order does not matter. assert circuit_cls( - cirq.Moment( - [ - cirq.measure(a, key='x'), - cirq.measure(b, key='y'), - ] - ) + 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'), - ] - ) + cirq.Moment([cirq.measure(b, key='y'), cirq.measure(a, key='x')]) ).all_measurement_key_names() == {'x', 'y'} @@ -4375,39 +4153,21 @@ def test_zip(): circuit1.zip(circuit2) == circuit2.zip(circuit1) == cirq.Circuit( - cirq.Moment( - cirq.H(a), - cirq.X(c), - ), - cirq.Moment( - cirq.CNOT(a, b), - cirq.Y(c), - ), - cirq.Moment( - cirq.Z(c), - ), + cirq.Moment(cirq.H(a), cirq.X(c)), + cirq.Moment(cirq.CNOT(a, b), cirq.Y(c)), + cirq.Moment(cirq.Z(c)), ) ) assert circuit1.zip(circuit2, circuit3) == cirq.Circuit( - cirq.Moment( - cirq.H(a), - cirq.X(c), - ), - cirq.Moment( - cirq.CNOT(a, b), - cirq.Y(c), - cirq.S(d), - ), - cirq.Moment( - cirq.Z(c), - ), + cirq.Moment(cirq.H(a), cirq.X(c)), + cirq.Moment(cirq.CNOT(a, b), cirq.Y(c), cirq.S(d)), + cirq.Moment(cirq.Z(c)), ) # Overlapping operations. with pytest.raises(ValueError, match="moment index 1.*\n.*CNOT"): _ = cirq.Circuit.zip( - cirq.Circuit(cirq.X(a), cirq.CNOT(a, b)), - cirq.Circuit(cirq.X(b), cirq.Z(b)), + cirq.Circuit(cirq.X(a), cirq.CNOT(a, b)), cirq.Circuit(cirq.X(b), cirq.Z(b)) ) @@ -4601,15 +4361,8 @@ def test_tetris_concat(): for cz_order in [cirq.CZ(a, b), cirq.CZ(b, a)]: assert 3 == len( f( - cirq.Circuit( - cirq.Moment(cz_order), - cirq.Moment(), - cirq.Moment(), - ), - cirq.Circuit( - cirq.Moment(cirq.H(a)), - cirq.Moment(cirq.H(b)), - ), + cirq.Circuit(cirq.Moment(cz_order), cirq.Moment(), cirq.Moment()), + cirq.Circuit(cirq.Moment(cirq.H(a)), cirq.Moment(cirq.H(b))), ) ) @@ -4630,10 +4383,7 @@ def test_tetris_concat_alignment(): a, b = cirq.LineQubit.range(2) assert cirq.Circuit.tetris_concat( - cirq.Circuit(cirq.X(a)), - cirq.Circuit(cirq.Y(b)) * 4, - cirq.Circuit(cirq.Z(a)), - align='first', + cirq.Circuit(cirq.X(a)), cirq.Circuit(cirq.Y(b)) * 4, cirq.Circuit(cirq.Z(a)), align='first' ) == cirq.Circuit( cirq.Moment(cirq.X(a), cirq.Y(b)), cirq.Moment(cirq.Y(b)), @@ -4642,10 +4392,7 @@ def test_tetris_concat_alignment(): ) assert cirq.Circuit.tetris_concat( - cirq.Circuit(cirq.X(a)), - cirq.Circuit(cirq.Y(b)) * 4, - cirq.Circuit(cirq.Z(a)), - align='left', + cirq.Circuit(cirq.X(a)), cirq.Circuit(cirq.Y(b)) * 4, cirq.Circuit(cirq.Z(a)), align='left' ) == cirq.Circuit( cirq.Moment(cirq.X(a), cirq.Y(b)), cirq.Moment(cirq.Z(a), cirq.Y(b)), @@ -4654,10 +4401,7 @@ def test_tetris_concat_alignment(): ) assert cirq.Circuit.tetris_concat( - cirq.Circuit(cirq.X(a)), - cirq.Circuit(cirq.Y(b)) * 4, - cirq.Circuit(cirq.Z(a)), - align='right', + cirq.Circuit(cirq.X(a)), cirq.Circuit(cirq.Y(b)) * 4, cirq.Circuit(cirq.Z(a)), align='right' ) == cirq.Circuit( cirq.Moment(cirq.Y(b)), cirq.Moment(cirq.Y(b)), @@ -4789,10 +4533,7 @@ def _circuit_diagram_info_(self, args) -> str: CustomGateAnnotation("b").on(), CustomOperationAnnotation("c"), ), - cirq.Moment( - CustomOperationAnnotation("e"), - CustomOperationAnnotation("d"), - ), + cirq.Moment(CustomOperationAnnotation("e"), CustomOperationAnnotation("d")), ), """ a e @@ -4807,7 +4548,7 @@ def _circuit_diagram_info_(self, args) -> str: cirq.H(cirq.LineQubit(0)), CustomOperationAnnotation("a"), cirq.global_phase_operation(1j), - ), + ) ), """ 0: ─────────────H────── @@ -4822,7 +4563,7 @@ def _circuit_diagram_info_(self, args) -> str: cirq.Moment( cirq.H(cirq.LineQubit(0)), cirq.CircuitOperation(cirq.FrozenCircuit(CustomOperationAnnotation("a"))), - ), + ) ), """ 0: ───H─── @@ -4838,19 +4579,14 @@ def _circuit_diagram_info_(self, args) -> str: CustomGateAnnotation("b").on(), CustomOperationAnnotation("c"), ), - cirq.Moment( - CustomOperationAnnotation("eee"), - CustomOperationAnnotation("d"), - ), + cirq.Moment(CustomOperationAnnotation("eee"), CustomOperationAnnotation("d")), cirq.Moment( cirq.CNOT(cirq.LineQubit(0), cirq.LineQubit(2)), cirq.CNOT(cirq.LineQubit(1), cirq.LineQubit(3)), CustomOperationAnnotationNoInfo(), CustomOperationAnnotation("zzz"), ), - cirq.Moment( - cirq.H(cirq.LineQubit(2)), - ), + cirq.Moment(cirq.H(cirq.LineQubit(2))), ), """ ┌────────┐ diff --git a/cirq-core/cirq/circuits/frozen_circuit.py b/cirq-core/cirq/circuits/frozen_circuit.py index 9f4b38017ca..13548c2b51e 100644 --- a/cirq-core/cirq/circuits/frozen_circuit.py +++ b/cirq-core/cirq/circuits/frozen_circuit.py @@ -46,9 +46,7 @@ class FrozenCircuit(AbstractCircuit, protocols.SerializableByKey): """ def __init__( - self, - *contents: 'cirq.OP_TREE', - strategy: 'cirq.InsertStrategy' = InsertStrategy.EARLIEST, + self, *contents: 'cirq.OP_TREE', strategy: 'cirq.InsertStrategy' = InsertStrategy.EARLIEST ) -> None: """Initializes a frozen circuit. diff --git a/cirq-core/cirq/circuits/moment.py b/cirq-core/cirq/circuits/moment.py index 8b0f4b56715..75ddecfd612 100644 --- a/cirq-core/cirq/circuits/moment.py +++ b/cirq-core/cirq/circuits/moment.py @@ -262,9 +262,7 @@ def _with_key_path_prefix_(self, prefix: Tuple[str, ...]): ) def _with_rescoped_keys_( - self, - path: Tuple[str, ...], - bindable_keys: FrozenSet['cirq.MeasurementKey'], + self, path: Tuple[str, ...], bindable_keys: FrozenSet['cirq.MeasurementKey'] ): return Moment( protocols.with_rescoped_keys(op, path, bindable_keys) for op in self.operations diff --git a/cirq-core/cirq/circuits/moment_test.py b/cirq-core/cirq/circuits/moment_test.py index dfdaefd0e53..a62a42b15f6 100644 --- a/cirq-core/cirq/circuits/moment_test.py +++ b/cirq-core/cirq/circuits/moment_test.py @@ -22,18 +22,12 @@ def test_deprecated_submodule(): - with cirq.testing.assert_deprecated( - "Use cirq.circuits.moment instead", - deadline="v0.16", - ): + with cirq.testing.assert_deprecated("Use cirq.circuits.moment instead", deadline="v0.16"): _ = cirq.ops.moment.Moment def test_deprecated_attribute_in_cirq_ops(): - with cirq.testing.assert_deprecated( - "Use cirq.circuits.Moment instead", - deadline="v0.16", - ): + with cirq.testing.assert_deprecated("Use cirq.circuits.Moment instead", deadline="v0.16"): _ = cirq.ops.Moment @@ -296,14 +290,7 @@ def test_with_measurement_keys(): a, b = cirq.LineQubit.range(2) m = cirq.Moment(cirq.measure(a, key='m1'), cirq.measure(b, key='m2')) - new_moment = cirq.with_measurement_key_mapping( - m, - { - 'm1': 'p1', - 'm2': 'p2', - 'x': 'z', - }, - ) + new_moment = cirq.with_measurement_key_mapping(m, {'m1': 'p1', 'm2': 'p2', 'x': 'z'}) assert new_moment.operations[0] == cirq.measure(a, key='p1') assert new_moment.operations[1] == cirq.measure(b, key='p2') @@ -472,22 +459,13 @@ def test_op_tree(): eq = cirq.testing.EqualsTester() a, b = cirq.LineQubit.range(2) - eq.add_equality_group( - cirq.Moment(), - cirq.Moment([]), - cirq.Moment([[], [[[]]]]), - ) + eq.add_equality_group(cirq.Moment(), cirq.Moment([]), cirq.Moment([[], [[[]]]])) eq.add_equality_group( - cirq.Moment(cirq.X(a)), - cirq.Moment([cirq.X(a)]), - cirq.Moment({cirq.X(a)}), + cirq.Moment(cirq.X(a)), cirq.Moment([cirq.X(a)]), cirq.Moment({cirq.X(a)}) ) - eq.add_equality_group( - cirq.Moment(cirq.X(a), cirq.Y(b)), - cirq.Moment([cirq.X(a), cirq.Y(b)]), - ) + eq.add_equality_group(cirq.Moment(cirq.X(a), cirq.Y(b)), cirq.Moment([cirq.X(a), cirq.Y(b)])) def test_indexes_by_qubit(): diff --git a/cirq-core/cirq/circuits/qasm_output.py b/cirq-core/cirq/circuits/qasm_output.py index ca8c5a949db..25540ad167a 100644 --- a/cirq-core/cirq/circuits/qasm_output.py +++ b/cirq-core/cirq/circuits/qasm_output.py @@ -45,11 +45,7 @@ def __init__(self, theta, phi, lmda) -> None: @staticmethod def from_matrix(mat: np.ndarray) -> 'QasmUGate': pre_phase, rotation, post_phase = linalg.deconstruct_single_qubit_matrix_into_angles(mat) - return QasmUGate( - rotation / np.pi, - post_phase / np.pi, - pre_phase / np.pi, - ) + return QasmUGate(rotation / np.pi, post_phase / np.pi, pre_phase / np.pi) def _has_unitary_(self): return True @@ -84,11 +80,7 @@ def _value_equality_values_(self): return self.lmda, self.theta, self.phi def _json_dict_(self) -> Dict[str, float]: - return { - 'theta': self.theta, - 'phi': self.phi, - 'lmda': self.lmda, - } + return {'theta': self.theta, 'phi': self.phi, 'lmda': self.lmda} @classmethod def _from_json_dict_(cls, theta: float, phi: float, lmda: float, **kwargs) -> 'QasmUGate': diff --git a/cirq-core/cirq/circuits/quil_output_test.py b/cirq-core/cirq/circuits/quil_output_test.py index c1b16c376b2..d67094f6624 100644 --- a/cirq-core/cirq/circuits/quil_output_test.py +++ b/cirq-core/cirq/circuits/quil_output_test.py @@ -146,13 +146,7 @@ def test_two_quil_one_qubit_gate_output(): (q0,) = _make_qubits(1) gate = QuilOneQubitGate(np.array([[1, 0], [0, 1]])) gate1 = QuilOneQubitGate(np.array([[2, 0], [0, 3]])) - output = cirq.QuilOutput( - ( - gate.on(q0), - gate1.on(q0), - ), - (q0,), - ) + output = cirq.QuilOutput((gate.on(q0), gate1.on(q0)), (q0,)) assert ( str(output) == """# Created using Cirq. @@ -170,18 +164,9 @@ def test_two_quil_one_qubit_gate_output(): def test_quil_two_qubit_gate_output(): - ( - q0, - q1, - ) = _make_qubits(2) + (q0, q1) = _make_qubits(2) gate = QuilTwoQubitGate(np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])) - output = cirq.QuilOutput( - (gate.on(q0, q1),), - ( - q0, - q1, - ), - ) + output = cirq.QuilOutput((gate.on(q0, q1),), (q0, q1)) assert ( str(output) == """# Created using Cirq. @@ -211,13 +196,7 @@ class UnsupportedOperation(cirq.Operation): def test_i_swap_with_power(): q0, q1 = _make_qubits(2) - output = cirq.QuilOutput( - (cirq.ISWAP(q0, q1) ** 0.25,), - ( - q0, - q1, - ), - ) + output = cirq.QuilOutput((cirq.ISWAP(q0, q1) ** 0.25,), (q0, q1)) assert ( str(output) == f"""# Created using Cirq. @@ -382,17 +361,8 @@ class UnrecognizedGate(cirq.testing.ThreeQubitGate): def test_pauli_interaction_gate(): - ( - q0, - q1, - ) = _make_qubits(2) - output = cirq.QuilOutput( - PauliInteractionGate.CZ.on(q0, q1), - ( - q0, - q1, - ), - ) + (q0, q1) = _make_qubits(2) + output = cirq.QuilOutput(PauliInteractionGate.CZ.on(q0, q1), (q0, q1)) assert ( str(output) == """# Created using Cirq. @@ -465,9 +435,7 @@ def test_two_qubit_diagonal_gate_quil_output(): cirq_unitary = cirq.Circuit(cirq.SWAP(q0, q1), operations, cirq.SWAP(q0, q1)).unitary() assert np.allclose(pyquil_unitary, cirq_unitary) # Also test non-CPHASE case, which decomposes into X/RZ/CPhase - operations = [ - cirq.TwoQubitDiagonalGate([0, 0, 0, 0])(q0, q1), - ] + operations = [cirq.TwoQubitDiagonalGate([0, 0, 0, 0])(q0, q1)] output = cirq.QuilOutput(operations, (q0, q1)) program = pyquil.Program(str(output)) assert f"\n{program.out()}" == QUIL_DIAGONAL_DECOMPOSE_PROGRAM diff --git a/cirq-core/cirq/circuits/text_diagram_drawer.py b/cirq-core/cirq/circuits/text_diagram_drawer.py index b25e262fdfb..e701633eb66 100644 --- a/cirq-core/cirq/circuits/text_diagram_drawer.py +++ b/cirq-core/cirq/circuits/text_diagram_drawer.py @@ -63,13 +63,7 @@ ('doubled', bool), ], ) -_DiagramText = NamedTuple( - 'DiagramText', - [ - ('text', str), - ('transposed_text', str), - ], -) +_DiagramText = NamedTuple('DiagramText', [('text', str), ('transposed_text', str)]) def pick_charset(use_unicode: bool, emphasize: bool, doubled: bool) -> BoxDrawCharacterSet: diff --git a/cirq-core/cirq/contrib/acquaintance/__init__.py b/cirq-core/cirq/contrib/acquaintance/__init__.py index e63c7ab4ab4..56093a761f0 100644 --- a/cirq-core/cirq/contrib/acquaintance/__init__.py +++ b/cirq-core/cirq/contrib/acquaintance/__init__.py @@ -14,15 +14,9 @@ """Tools for creating and using acquaintance strategies.""" -from cirq.contrib.acquaintance.bipartite import ( - BipartiteGraphType, - BipartiteSwapNetworkGate, -) +from cirq.contrib.acquaintance.bipartite import BipartiteGraphType, BipartiteSwapNetworkGate -from cirq.contrib.acquaintance.devices import ( - get_acquaintance_size, - UnconstrainedAcquaintanceDevice, -) +from cirq.contrib.acquaintance.devices import get_acquaintance_size, UnconstrainedAcquaintanceDevice from cirq.contrib.acquaintance.executor import ( AcquaintanceOperation, @@ -30,15 +24,9 @@ StrategyExecutor, ) -from cirq.contrib.acquaintance.gates import ( - acquaint, - AcquaintanceOpportunityGate, - SwapNetworkGate, -) +from cirq.contrib.acquaintance.gates import acquaint, AcquaintanceOpportunityGate, SwapNetworkGate -from cirq.contrib.acquaintance.inspection_utils import ( - get_logical_acquaintance_opportunities, -) +from cirq.contrib.acquaintance.inspection_utils import get_logical_acquaintance_opportunities from cirq.contrib.acquaintance.mutation_utils import ( expose_acquaintance_gates, @@ -46,9 +34,7 @@ replace_acquaintance_with_swap_network, ) -from cirq.contrib.acquaintance.optimizers import ( - remove_redundant_acquaintance_opportunities, -) +from cirq.contrib.acquaintance.optimizers import remove_redundant_acquaintance_opportunities from cirq.contrib.acquaintance.permutation import ( LinearPermutationGate, @@ -63,13 +49,9 @@ DECOMPOSE_PERMUTATION_GATES, ) -from cirq.contrib.acquaintance.shift import ( - CircularShiftGate, -) +from cirq.contrib.acquaintance.shift import CircularShiftGate -from cirq.contrib.acquaintance.shift_swap_network import ( - ShiftSwapNetworkGate, -) +from cirq.contrib.acquaintance.shift_swap_network import ShiftSwapNetworkGate from cirq.contrib.acquaintance.strategies import ( complete_acquaintance_strategy, @@ -82,6 +64,4 @@ random_topological_sort, ) -from cirq.contrib.acquaintance import ( - testing, -) +from cirq.contrib.acquaintance import testing diff --git a/cirq-core/cirq/contrib/acquaintance/gates.py b/cirq-core/cirq/contrib/acquaintance/gates.py index 01c8eca7eb7..df258dd407f 100644 --- a/cirq-core/cirq/contrib/acquaintance/gates.py +++ b/cirq-core/cirq/contrib/acquaintance/gates.py @@ -32,8 +32,7 @@ def operations_to_part_lens( - qubit_order: Sequence['cirq.Qid'], - op_tree: 'cirq.OP_TREE', + qubit_order: Sequence['cirq.Qid'], op_tree: 'cirq.OP_TREE' ) -> Tuple[int, ...]: qubit_sort_key = functools.partial(operator.indexOf, qubit_order) op_parts = [tuple(sorted(op.qubits, key=qubit_sort_key)) for op in ops.flatten_op_tree(op_tree)] diff --git a/cirq-core/cirq/contrib/acquaintance/permutation.py b/cirq-core/cirq/contrib/acquaintance/permutation.py index 6e18956a116..073b7a60d02 100644 --- a/cirq-core/cirq/contrib/acquaintance/permutation.py +++ b/cirq-core/cirq/contrib/acquaintance/permutation.py @@ -13,17 +13,7 @@ # limitations under the License. import abc -from typing import ( - Any, - cast, - Dict, - Iterable, - Sequence, - Tuple, - TypeVar, - Union, - TYPE_CHECKING, -) +from typing import Any, cast, Dict, Iterable, Sequence, Tuple, TypeVar, Union, TYPE_CHECKING from cirq import circuits, ops, protocols, transformers, value from cirq.type_workarounds import NotImplementedType diff --git a/cirq-core/cirq/contrib/acquaintance/strategies/__init__.py b/cirq-core/cirq/contrib/acquaintance/strategies/__init__.py index cc207b0b299..e0251ee5282 100644 --- a/cirq-core/cirq/contrib/acquaintance/strategies/__init__.py +++ b/cirq-core/cirq/contrib/acquaintance/strategies/__init__.py @@ -14,12 +14,6 @@ """Acquaintance strategies.""" -from cirq.contrib.acquaintance.strategies.complete import ( - complete_acquaintance_strategy, -) -from cirq.contrib.acquaintance.strategies.cubic import ( - cubic_acquaintance_strategy, -) -from cirq.contrib.acquaintance.strategies.quartic_paired import ( - quartic_paired_acquaintance_strategy, -) +from cirq.contrib.acquaintance.strategies.complete import complete_acquaintance_strategy +from cirq.contrib.acquaintance.strategies.cubic import cubic_acquaintance_strategy +from cirq.contrib.acquaintance.strategies.quartic_paired import quartic_paired_acquaintance_strategy diff --git a/cirq-core/cirq/contrib/graph_device/hypergraph.py b/cirq-core/cirq/contrib/graph_device/hypergraph.py index a92c191f0e0..776d190c452 100644 --- a/cirq-core/cirq/contrib/graph_device/hypergraph.py +++ b/cirq-core/cirq/contrib/graph_device/hypergraph.py @@ -73,11 +73,7 @@ def remove_vertices(self, vertices): for vertex in vertices: self.remove_vertex(vertex) - def add_edge( - self, - vertices: Iterable[Hashable], - label: Any = None, - ) -> None: + def add_edge(self, vertices: Iterable[Hashable], label: Any = None) -> None: vertices = frozenset(vertices) self.add_vertices(vertices) for vertex in vertices: diff --git a/cirq-core/cirq/contrib/json.py b/cirq-core/cirq/contrib/json.py index 79d1a9e4ac6..715e694a360 100644 --- a/cirq-core/cirq/contrib/json.py +++ b/cirq-core/cirq/contrib/json.py @@ -12,10 +12,7 @@ def contrib_class_resolver(cirq_type: str): from cirq.contrib.quantum_volume import QuantumVolumeResult from cirq.contrib.acquaintance import SwapPermutationGate - classes = [ - QuantumVolumeResult, - SwapPermutationGate, - ] + classes = [QuantumVolumeResult, SwapPermutationGate] d = {cls.__name__: cls for cls in classes} return d.get(cirq_type, None) diff --git a/cirq-core/cirq/contrib/noise_models/noise_models.py b/cirq-core/cirq/contrib/noise_models/noise_models.py index be56b352bea..c7a6f0afb05 100644 --- a/cirq-core/cirq/contrib/noise_models/noise_models.py +++ b/cirq-core/cirq/contrib/noise_models/noise_models.py @@ -140,14 +140,8 @@ def __init__(self, depol_prob: float, bitflip_prob: float): def noisy_moment(self, moment: 'cirq.Moment', system_qubits: Sequence['cirq.Qid']): if validate_all_measurements(moment): - return [ - circuits.Moment(self.readout_noise_gate(q) for q in system_qubits), - moment, - ] - return [ - moment, - circuits.Moment(self.qubit_noise_gate(q) for q in system_qubits), - ] + return [circuits.Moment(self.readout_noise_gate(q) for q in system_qubits), moment] + return [moment, circuits.Moment(self.qubit_noise_gate(q) for q in system_qubits)] class DepolarizingWithDampedReadoutNoiseModel(devices.NoiseModel): @@ -159,12 +153,7 @@ class DepolarizingWithDampedReadoutNoiseModel(devices.NoiseModel): also contain gates. """ - def __init__( - self, - depol_prob: float, - bitflip_prob: float, - decay_prob: float, - ): + def __init__(self, depol_prob: float, bitflip_prob: float, decay_prob: float): """A depolarizing noise model with damped readout error. Args: depol_prob: Depolarizing probability. diff --git a/cirq-core/cirq/contrib/noise_models/noise_models_test.py b/cirq-core/cirq/contrib/noise_models/noise_models_test.py index 9d1c8436280..df9e6fbf724 100644 --- a/cirq-core/cirq/contrib/noise_models/noise_models_test.py +++ b/cirq-core/cirq/contrib/noise_models/noise_models_test.py @@ -21,12 +21,7 @@ def test_depol_noise(): noise_model = ccn.DepolarizingNoiseModel(depol_prob=0.005) qubits = cirq.LineQubit.range(2) - moment = cirq.Moment( - [ - cirq.X(qubits[0]), - cirq.Y(qubits[1]), - ] - ) + moment = cirq.Moment([cirq.X(qubits[0]), cirq.Y(qubits[1])]) noisy_mom = noise_model.noisy_moment(moment, system_qubits=qubits) assert len(noisy_mom) == 2 assert noisy_mom[0] == moment diff --git a/cirq-core/cirq/contrib/paulistring/__init__.py b/cirq-core/cirq/contrib/paulistring/__init__.py index 6b3d68c1693..4f111d007cd 100644 --- a/cirq-core/cirq/contrib/paulistring/__init__.py +++ b/cirq-core/cirq/contrib/paulistring/__init__.py @@ -14,17 +14,11 @@ """Methods related to optimizing and transforming PauliStrings.""" -from cirq.contrib.paulistring.convert_to_pauli_string_phasors import ( - ConvertToPauliStringPhasors, -) +from cirq.contrib.paulistring.convert_to_pauli_string_phasors import ConvertToPauliStringPhasors -from cirq.contrib.paulistring.convert_to_clifford_gates import ( - ConvertToSingleQubitCliffordGates, -) +from cirq.contrib.paulistring.convert_to_clifford_gates import ConvertToSingleQubitCliffordGates -from cirq.contrib.paulistring.convert_gate_set import ( - converted_gate_set, -) +from cirq.contrib.paulistring.convert_gate_set import converted_gate_set from cirq.contrib.paulistring.separate import ( convert_and_separate_circuit, @@ -37,18 +31,10 @@ pauli_string_reorder_pred, ) -from cirq.contrib.paulistring.recombine import ( - move_pauli_strings_into_circuit, -) +from cirq.contrib.paulistring.recombine import move_pauli_strings_into_circuit -from cirq.contrib.paulistring.pauli_string_optimize import ( - pauli_string_optimized_circuit, -) +from cirq.contrib.paulistring.pauli_string_optimize import pauli_string_optimized_circuit -from cirq.contrib.paulistring.clifford_optimize import ( - clifford_optimized_circuit, -) +from cirq.contrib.paulistring.clifford_optimize import clifford_optimized_circuit -from cirq.contrib.paulistring.optimize import ( - optimized_circuit, -) +from cirq.contrib.paulistring.optimize import optimized_circuit diff --git a/cirq-core/cirq/contrib/paulistring/clifford_optimize.py b/cirq-core/cirq/contrib/paulistring/clifford_optimize.py index bfb4d6e14a5..b80b6cef6dc 100644 --- a/cirq-core/cirq/contrib/paulistring/clifford_optimize.py +++ b/cirq-core/cirq/contrib/paulistring/clifford_optimize.py @@ -26,9 +26,7 @@ def clifford_optimized_circuit(circuit: circuits.Circuit, atol: float = 1e-8) -> all_ops = list(c_cliff.all_operations()) def find_merge_point( - start_i: int, - string_op: ops.PauliStringPhasor, - stop_at_cz: bool, + start_i: int, string_op: ops.PauliStringPhasor, stop_at_cz: bool ) -> Tuple[int, ops.PauliStringPhasor, int]: STOP = 0 CONTINUE = 1 diff --git a/cirq-core/cirq/contrib/paulistring/clifford_optimize_test.py b/cirq-core/cirq/contrib/paulistring/clifford_optimize_test.py index 00823804da0..12660581e20 100644 --- a/cirq-core/cirq/contrib/paulistring/clifford_optimize_test.py +++ b/cirq-core/cirq/contrib/paulistring/clifford_optimize_test.py @@ -15,10 +15,7 @@ import cirq -from cirq.contrib.paulistring import ( - converted_gate_set, - clifford_optimized_circuit, -) +from cirq.contrib.paulistring import converted_gate_set, clifford_optimized_circuit def test_optimize(): @@ -32,21 +29,12 @@ def test_optimize(): cirq.X(q1) ** -0.5, ) c_expected = converted_gate_set( - cirq.Circuit( - cirq.CZ(q0, q1), - cirq.Z(q0) ** 0.25, - cirq.X(q1) ** 0.25, - cirq.CZ(q0, q1), - ) + cirq.Circuit(cirq.CZ(q0, q1), cirq.Z(q0) ** 0.25, cirq.X(q1) ** 0.25, cirq.CZ(q0, q1)) ) c_opt = clifford_optimized_circuit(c_orig) - cirq.testing.assert_allclose_up_to_global_phase( - c_orig.unitary(), - c_opt.unitary(), - atol=1e-7, - ) + cirq.testing.assert_allclose_up_to_global_phase(c_orig.unitary(), c_opt.unitary(), atol=1e-7) assert c_opt == c_expected @@ -62,23 +50,13 @@ def test_optimize(): def test_remove_czs(): q0, q1 = cirq.LineQubit.range(2) - c_orig = cirq.Circuit( - cirq.CZ(q0, q1), - cirq.Z(q0) ** 0.5, - cirq.CZ(q0, q1), - ) - c_expected = converted_gate_set( - cirq.Circuit( - cirq.Z(q0) ** 0.5, - ) - ) + c_orig = cirq.Circuit(cirq.CZ(q0, q1), cirq.Z(q0) ** 0.5, cirq.CZ(q0, q1)) + c_expected = converted_gate_set(cirq.Circuit(cirq.Z(q0) ** 0.5)) c_opt = clifford_optimized_circuit(c_orig) cirq.testing.assert_allclose_up_to_global_phase( - c_orig.unitary(), - c_opt.unitary(qubits_that_should_be_present=(q0, q1)), - atol=1e-7, + c_orig.unitary(), c_opt.unitary(qubits_that_should_be_present=(q0, q1)), atol=1e-7 ) assert c_opt == c_expected @@ -93,23 +71,13 @@ def test_remove_czs(): def test_remove_staggered_czs(): q0, q1, q2 = cirq.LineQubit.range(3) - c_orig = cirq.Circuit( - cirq.CZ(q0, q1), - cirq.CZ(q1, q2), - cirq.CZ(q0, q1), - ) - c_expected = converted_gate_set( - cirq.Circuit( - cirq.CZ(q1, q2), - ) - ) + c_orig = cirq.Circuit(cirq.CZ(q0, q1), cirq.CZ(q1, q2), cirq.CZ(q0, q1)) + c_expected = converted_gate_set(cirq.Circuit(cirq.CZ(q1, q2))) c_opt = clifford_optimized_circuit(c_orig) cirq.testing.assert_allclose_up_to_global_phase( - c_orig.unitary(), - c_opt.unitary(qubits_that_should_be_present=(q0, q1, q2)), - atol=1e-7, + c_orig.unitary(), c_opt.unitary(qubits_that_should_be_present=(q0, q1, q2)), atol=1e-7 ) assert c_opt == c_expected @@ -126,27 +94,14 @@ def test_remove_staggered_czs(): def test_with_measurements(): q0, q1 = cirq.LineQubit.range(2) - c_orig = cirq.Circuit( - cirq.X(q0), - cirq.CZ(q0, q1), - cirq.measure(q0, q1, key='m'), - ) + c_orig = cirq.Circuit(cirq.X(q0), cirq.CZ(q0, q1), cirq.measure(q0, q1, key='m')) c_expected = converted_gate_set( - cirq.Circuit( - cirq.CZ(q0, q1), - cirq.X(q0), - cirq.Z(q1), - cirq.measure(q0, q1, key='m'), - ) + cirq.Circuit(cirq.CZ(q0, q1), cirq.X(q0), cirq.Z(q1), cirq.measure(q0, q1, key='m')) ) c_opt = clifford_optimized_circuit(c_orig) - cirq.testing.assert_allclose_up_to_global_phase( - c_orig.unitary(), - c_opt.unitary(), - atol=1e-7, - ) + cirq.testing.assert_allclose_up_to_global_phase(c_orig.unitary(), c_opt.unitary(), atol=1e-7) assert c_opt == c_expected @@ -166,8 +121,4 @@ def test_optimize_large_circuit(): c_opt = clifford_optimized_circuit(c_orig) - cirq.testing.assert_allclose_up_to_global_phase( - c_orig.unitary(), - c_opt.unitary(), - atol=1e-7, - ) + cirq.testing.assert_allclose_up_to_global_phase(c_orig.unitary(), c_opt.unitary(), atol=1e-7) diff --git a/cirq-core/cirq/contrib/paulistring/convert_gate_set.py b/cirq-core/cirq/contrib/paulistring/convert_gate_set.py index dd22b118d4e..0e5d43414bb 100644 --- a/cirq-core/cirq/contrib/paulistring/convert_gate_set.py +++ b/cirq-core/cirq/contrib/paulistring/convert_gate_set.py @@ -18,9 +18,7 @@ def converted_gate_set( - circuit: circuits.Circuit, - no_clifford_gates: bool = False, - atol: float = 1e-8, + circuit: circuits.Circuit, no_clifford_gates: bool = False, atol: float = 1e-8 ) -> circuits.Circuit: """Returns a new, equivalent circuit using the gate set {SingleQubitCliffordGate, @@ -31,8 +29,6 @@ def converted_gate_set( ) conv_circuit = transformers.merge_k_qubit_unitaries(conv_circuit, k=1) ConvertToPauliStringPhasors( - ignore_failures=True, - keep_clifford=not no_clifford_gates, - atol=atol, + ignore_failures=True, keep_clifford=not no_clifford_gates, atol=atol ).optimize_circuit(conv_circuit) return transformers.drop_empty_moments(conv_circuit) diff --git a/cirq-core/cirq/contrib/paulistring/convert_gate_set_test.py b/cirq-core/cirq/contrib/paulistring/convert_gate_set_test.py index c1b96e4ae67..75ce83f2b43 100644 --- a/cirq-core/cirq/contrib/paulistring/convert_gate_set_test.py +++ b/cirq-core/cirq/contrib/paulistring/convert_gate_set_test.py @@ -60,14 +60,8 @@ def test_converts_various_ops(op, expected_ops): def test_degenerate_single_qubit_decompose(): q0 = cirq.LineQubit(0) - before = cirq.Circuit( - cirq.Z(q0) ** 0.1, - cirq.X(q0) ** 1.0000000001, - cirq.Z(q0) ** 0.1, - ) - expected = cirq.Circuit( - cirq.SingleQubitCliffordGate.X(q0), - ) + before = cirq.Circuit(cirq.Z(q0) ** 0.1, cirq.X(q0) ** 1.0000000001, cirq.Z(q0) ** 0.1) + expected = cirq.Circuit(cirq.SingleQubitCliffordGate.X(q0)) after = converted_gate_set(before) assert after == expected @@ -100,11 +94,7 @@ def test_converts_single_qubit_series(): def test_converts_single_qubit_then_two(): q0, q1 = cirq.LineQubit.range(2) - before = cirq.Circuit( - cirq.X(q0), - cirq.Y(q0), - cirq.CZ(q0, q1), - ) + before = cirq.Circuit(cirq.X(q0), cirq.Y(q0), cirq.CZ(q0, q1)) after = converted_gate_set(before) cirq.testing.assert_allclose_up_to_global_phase(before.unitary(), after.unitary(), atol=1e-7) diff --git a/cirq-core/cirq/contrib/paulistring/convert_to_clifford_gates.py b/cirq-core/cirq/contrib/paulistring/convert_to_clifford_gates.py index fb8dffcb458..c090cfd1bc9 100644 --- a/cirq-core/cirq/contrib/paulistring/convert_to_clifford_gates.py +++ b/cirq-core/cirq/contrib/paulistring/convert_to_clifford_gates.py @@ -18,10 +18,7 @@ from cirq import ops, protocols, transformers, linalg from cirq.circuits.circuit import Circuit -from cirq.circuits.optimization_pass import ( - PointOptimizationSummary, - PointOptimizer, -) +from cirq.circuits.optimization_pass import PointOptimizationSummary, PointOptimizer if TYPE_CHECKING: import cirq diff --git a/cirq-core/cirq/contrib/paulistring/convert_to_clifford_gates_test.py b/cirq-core/cirq/contrib/paulistring/convert_to_clifford_gates_test.py index 3fc43be9437..f3338544369 100644 --- a/cirq-core/cirq/contrib/paulistring/convert_to_clifford_gates_test.py +++ b/cirq-core/cirq/contrib/paulistring/convert_to_clifford_gates_test.py @@ -15,19 +15,13 @@ import pytest import cirq -from cirq.contrib.paulistring import ( - ConvertToSingleQubitCliffordGates, -) +from cirq.contrib.paulistring import ConvertToSingleQubitCliffordGates def test_convert(): q0, q1 = cirq.LineQubit.range(2) circuit = cirq.Circuit( - cirq.X(q0), - cirq.Y(q1) ** 0.5, - cirq.Z(q0) ** -0.5, - cirq.Z(q1) ** 0, - cirq.H(q0), + cirq.X(q0), cirq.Y(q1) ** 0.5, cirq.Z(q0) ** -0.5, cirq.Z(q1) ** 0, cirq.H(q0) ) c_orig = cirq.Circuit(circuit) ConvertToSingleQubitCliffordGates().optimize_circuit(circuit) @@ -48,9 +42,7 @@ def test_convert(): def test_non_clifford_known_matrix(): q0 = cirq.LineQubit(0) - circuit = cirq.Circuit( - cirq.Z(q0) ** 0.25, - ) + circuit = cirq.Circuit(cirq.Z(q0) ** 0.25) c_orig = cirq.Circuit(circuit) ConvertToSingleQubitCliffordGates(ignore_failures=True).optimize_circuit(circuit) @@ -63,9 +55,7 @@ def test_non_clifford_known_matrix(): def test_already_converted(): q0 = cirq.LineQubit(0) - circuit = cirq.Circuit( - cirq.SingleQubitCliffordGate.H(q0), - ) + circuit = cirq.Circuit(cirq.SingleQubitCliffordGate.H(q0)) c_orig = cirq.Circuit(circuit) ConvertToSingleQubitCliffordGates().optimize_circuit(circuit) @@ -104,9 +94,7 @@ class UnsupportedDummy(cirq.testing.TwoQubitGate): pass q0, q1 = cirq.LineQubit.range(2) - circuit = cirq.Circuit( - UnsupportedDummy()(q0, q1), - ) + circuit = cirq.Circuit(UnsupportedDummy()(q0, q1)) c_orig = cirq.Circuit(circuit) ConvertToSingleQubitCliffordGates(ignore_failures=True).optimize_circuit(circuit) @@ -118,9 +106,7 @@ class UnsupportedDummy(cirq.testing.TwoQubitGate): pass q0, q1 = cirq.LineQubit.range(2) - circuit = cirq.Circuit( - UnsupportedDummy()(q0, q1), - ) + circuit = cirq.Circuit(UnsupportedDummy()(q0, q1)) with pytest.raises(TypeError): ConvertToSingleQubitCliffordGates().optimize_circuit(circuit) diff --git a/cirq-core/cirq/contrib/paulistring/convert_to_pauli_string_phasors.py b/cirq-core/cirq/contrib/paulistring/convert_to_pauli_string_phasors.py index dccb038838a..59b719d00f1 100644 --- a/cirq-core/cirq/contrib/paulistring/convert_to_pauli_string_phasors.py +++ b/cirq-core/cirq/contrib/paulistring/convert_to_pauli_string_phasors.py @@ -18,10 +18,7 @@ from cirq import ops, protocols, linalg, transformers from cirq.circuits.circuit import Circuit -from cirq.circuits.optimization_pass import ( - PointOptimizationSummary, - PointOptimizer, -) +from cirq.circuits.optimization_pass import PointOptimizationSummary, PointOptimizer if TYPE_CHECKING: import cirq diff --git a/cirq-core/cirq/contrib/paulistring/convert_to_pauli_string_phasors_test.py b/cirq-core/cirq/contrib/paulistring/convert_to_pauli_string_phasors_test.py index 04d202ece61..51686a2afeb 100644 --- a/cirq-core/cirq/contrib/paulistring/convert_to_pauli_string_phasors_test.py +++ b/cirq-core/cirq/contrib/paulistring/convert_to_pauli_string_phasors_test.py @@ -20,12 +20,7 @@ def test_convert(): q0, q1 = cirq.LineQubit.range(2) - circuit = cirq.Circuit( - cirq.X(q0), - cirq.Y(q1) ** 0.25, - cirq.Z(q0) ** 0.125, - cirq.H(q1), - ) + circuit = cirq.Circuit(cirq.X(q0), cirq.Y(q1) ** 0.25, cirq.Z(q0) ** 0.125, cirq.H(q1)) c_orig = cirq.Circuit(circuit) ConvertToPauliStringPhasors().optimize_circuit(circuit) @@ -43,10 +38,7 @@ def test_convert(): def test_convert_keep_clifford(): q0, q1 = cirq.LineQubit.range(2) circuit = cirq.Circuit( - cirq.X(q0), - cirq.Y(q1) ** 0.25, - cirq.Z(q0) ** 0.125, - cirq.SingleQubitCliffordGate.H(q1), + cirq.X(q0), cirq.Y(q1) ** 0.25, cirq.Z(q0) ** 0.125, cirq.SingleQubitCliffordGate.H(q1) ) c_orig = cirq.Circuit(circuit) ConvertToPauliStringPhasors(keep_clifford=True).optimize_circuit(circuit) @@ -76,9 +68,7 @@ class UnsupportedDummy(cirq.testing.TwoQubitGate): pass q0, q1 = cirq.LineQubit.range(2) - circuit = cirq.Circuit( - UnsupportedDummy()(q0, q1), - ) + circuit = cirq.Circuit(UnsupportedDummy()(q0, q1)) c_orig = cirq.Circuit(circuit) ConvertToPauliStringPhasors(ignore_failures=True).optimize_circuit(circuit) @@ -90,8 +80,6 @@ class UnsupportedDummy(cirq.testing.TwoQubitGate): pass q0, q1 = cirq.LineQubit.range(2) - circuit = cirq.Circuit( - UnsupportedDummy()(q0, q1), - ) + circuit = cirq.Circuit(UnsupportedDummy()(q0, q1)) with pytest.raises(TypeError): ConvertToPauliStringPhasors().optimize_circuit(circuit) diff --git a/cirq-core/cirq/contrib/paulistring/optimize.py b/cirq-core/cirq/contrib/paulistring/optimize.py index 14ef2c0cd63..325fd891802 100644 --- a/cirq-core/cirq/contrib/paulistring/optimize.py +++ b/cirq-core/cirq/contrib/paulistring/optimize.py @@ -27,8 +27,7 @@ class _CZTargetGateSet(transformers.CZTargetGateset): """ def __init__( - self, - post_clean_up: Callable[[ops.OP_TREE], ops.OP_TREE] = lambda op_tree: op_tree, + self, post_clean_up: Callable[[ops.OP_TREE], ops.OP_TREE] = lambda op_tree: op_tree ): super().__init__() self.post_clean_up = post_clean_up diff --git a/cirq-core/cirq/contrib/paulistring/optimize_test.py b/cirq-core/cirq/contrib/paulistring/optimize_test.py index 24a48dc9119..aacbcaba95c 100644 --- a/cirq-core/cirq/contrib/paulistring/optimize_test.py +++ b/cirq-core/cirq/contrib/paulistring/optimize_test.py @@ -15,9 +15,7 @@ import cirq -from cirq.contrib.paulistring import ( - optimized_circuit, -) +from cirq.contrib.paulistring import optimized_circuit def test_optimize(): @@ -50,11 +48,7 @@ def test_optimize(): c_opt = optimized_circuit(c_orig) - cirq.testing.assert_allclose_up_to_global_phase( - c_orig.unitary(), - c_opt.unitary(), - atol=1e-7, - ) + cirq.testing.assert_allclose_up_to_global_phase(c_orig.unitary(), c_opt.unitary(), atol=1e-7) cirq.testing.assert_has_diagram( c_opt, @@ -74,11 +68,7 @@ def test_optimize_large_circuit(): c_opt = optimized_circuit(c_orig) - cirq.testing.assert_allclose_up_to_global_phase( - c_orig.unitary(), - c_opt.unitary(), - atol=1e-7, - ) + cirq.testing.assert_allclose_up_to_global_phase(c_orig.unitary(), c_opt.unitary(), atol=1e-7) assert ( sum( @@ -96,11 +86,7 @@ def test_repeat_limit(): c_opt = optimized_circuit(c_orig, repeat=1) - cirq.testing.assert_allclose_up_to_global_phase( - c_orig.unitary(), - c_opt.unitary(), - atol=1e-7, - ) + cirq.testing.assert_allclose_up_to_global_phase(c_orig.unitary(), c_opt.unitary(), atol=1e-7) assert ( sum( diff --git a/cirq-core/cirq/contrib/paulistring/pauli_string_dag_test.py b/cirq-core/cirq/contrib/paulistring/pauli_string_dag_test.py index 6331e066b6d..cab93bd5af6 100644 --- a/cirq-core/cirq/contrib/paulistring/pauli_string_dag_test.py +++ b/cirq-core/cirq/contrib/paulistring/pauli_string_dag_test.py @@ -16,10 +16,7 @@ import cirq -from cirq.contrib.paulistring import ( - convert_and_separate_circuit, - pauli_string_dag_from_circuit, -) +from cirq.contrib.paulistring import convert_and_separate_circuit, pauli_string_dag_from_circuit @pytest.mark.parametrize('repetition', range(6)) diff --git a/cirq-core/cirq/contrib/paulistring/pauli_string_optimize_test.py b/cirq-core/cirq/contrib/paulistring/pauli_string_optimize_test.py index 2ea15c5118a..d92e6e40067 100644 --- a/cirq-core/cirq/contrib/paulistring/pauli_string_optimize_test.py +++ b/cirq-core/cirq/contrib/paulistring/pauli_string_optimize_test.py @@ -15,20 +15,13 @@ import cirq -from cirq.contrib.paulistring import ( - converted_gate_set, - pauli_string_optimized_circuit, -) +from cirq.contrib.paulistring import converted_gate_set, pauli_string_optimized_circuit def test_optimize(): q0, q1 = cirq.LineQubit.range(2) c_orig = cirq.Circuit( - cirq.X(q0) ** 0.25, - cirq.H(q0), - cirq.CZ(q0, q1), - cirq.H(q0), - cirq.X(q0) ** 0.125, + cirq.X(q0) ** 0.25, cirq.H(q0), cirq.CZ(q0, q1), cirq.H(q0), cirq.X(q0) ** 0.125 ) c_expected = converted_gate_set( cirq.Circuit( @@ -43,11 +36,7 @@ def test_optimize(): c_opt = pauli_string_optimized_circuit(c_orig) - cirq.testing.assert_allclose_up_to_global_phase( - c_orig.unitary(), - c_opt.unitary(), - atol=1e-7, - ) + cirq.testing.assert_allclose_up_to_global_phase(c_orig.unitary(), c_opt.unitary(), atol=1e-7) assert c_opt == c_expected @@ -74,11 +63,7 @@ def test_handles_measurement_gate(): ) c_opt = pauli_string_optimized_circuit(c_orig) - cirq.testing.assert_allclose_up_to_global_phase( - c_orig.unitary(), - c_opt.unitary(), - atol=1e-7, - ) + cirq.testing.assert_allclose_up_to_global_phase(c_orig.unitary(), c_opt.unitary(), atol=1e-7) cirq.testing.assert_has_diagram( c_opt, @@ -96,8 +81,4 @@ def test_optimize_large_circuit(): c_opt = pauli_string_optimized_circuit(c_orig) - cirq.testing.assert_allclose_up_to_global_phase( - c_orig.unitary(), - c_opt.unitary(), - atol=1e-7, - ) + cirq.testing.assert_allclose_up_to_global_phase(c_orig.unitary(), c_opt.unitary(), atol=1e-7) diff --git a/cirq-core/cirq/contrib/paulistring/separate.py b/cirq-core/cirq/contrib/paulistring/separate.py index 190926280e3..26e107b0288 100644 --- a/cirq-core/cirq/contrib/paulistring/separate.py +++ b/cirq-core/cirq/contrib/paulistring/separate.py @@ -20,9 +20,7 @@ def convert_and_separate_circuit( - circuit: circuits.Circuit, - leave_cliffords: bool = True, - atol: float = 1e-8, + circuit: circuits.Circuit, leave_cliffords: bool = True, atol: float = 1e-8 ) -> Tuple[circuits.Circuit, circuits.Circuit]: """Converts a circuit into two, one made of PauliStringPhasor and the other Clifford gates. diff --git a/cirq-core/cirq/contrib/paulistring/separate_test.py b/cirq-core/cirq/contrib/paulistring/separate_test.py index eb88cd94af2..e6e336d5c68 100644 --- a/cirq-core/cirq/contrib/paulistring/separate_test.py +++ b/cirq-core/cirq/contrib/paulistring/separate_test.py @@ -13,9 +13,7 @@ # limitations under the License. import cirq -from cirq.contrib.paulistring import ( - convert_and_separate_circuit, -) +from cirq.contrib.paulistring import convert_and_separate_circuit def test_toffoli_separate(): @@ -25,9 +23,7 @@ def test_toffoli_separate(): c_left, c_right = convert_and_separate_circuit(circuit) cirq.testing.assert_allclose_up_to_global_phase( - circuit.unitary(), - (c_left + c_right).unitary(), - atol=1e-7, + circuit.unitary(), (c_left + c_right).unitary(), atol=1e-7 ) assert all(isinstance(op, cirq.PauliStringPhasor) for op in c_left.all_operations()) diff --git a/cirq-core/cirq/contrib/qasm_import/_lexer.py b/cirq-core/cirq/contrib/qasm_import/_lexer.py index 46e82689747..1a830ffc17d 100644 --- a/cirq-core/cirq/contrib/qasm_import/_lexer.py +++ b/cirq-core/cirq/contrib/qasm_import/_lexer.py @@ -35,14 +35,9 @@ def __init__(self): '!=': 'NE', } - tokens = [ - 'FORMAT_SPEC', - 'NUMBER', - 'NATURAL_NUMBER', - 'QELIBINC', - 'ID', - 'PI', - ] + list(reserved.values()) + tokens = ['FORMAT_SPEC', 'NUMBER', 'NATURAL_NUMBER', 'QELIBINC', 'ID', 'PI'] + list( + reserved.values() + ) def t_newline(self, t): r"""\n+""" diff --git a/cirq-core/cirq/contrib/qasm_import/_lexer_test.py b/cirq-core/cirq/contrib/qasm_import/_lexer_test.py index b34b7e6fe70..ca5cc5803e1 100644 --- a/cirq-core/cirq/contrib/qasm_import/_lexer_test.py +++ b/cirq-core/cirq/contrib/qasm_import/_lexer_test.py @@ -91,18 +91,7 @@ def test_valid_ids(identifier: str): @pytest.mark.parametrize( 'number', - [ - '1e2', - '1e0', - '3.', - '4.e10', - '.333', - '1.0', - '0.1', - '2.0e-05', - '1.2E+05', - '123123.2132312', - ], + ['1e2', '1e0', '3.', '4.e10', '.333', '1.0', '0.1', '2.0e-05', '1.2E+05', '123123.2132312'], ) def test_numbers(number: str): lexer = QasmLexer() diff --git a/cirq-core/cirq/contrib/qasm_import/_parser.py b/cirq-core/cirq/contrib/qasm_import/_parser.py index a3a56b8cf69..7c779432edc 100644 --- a/cirq-core/cirq/contrib/qasm_import/_parser.py +++ b/cirq-core/cirq/contrib/qasm_import/_parser.py @@ -249,11 +249,7 @@ def __init__(self): tokens = QasmLexer.tokens start = 'start' - precedence = ( - ('left', '+', '-'), - ('left', '*', '/'), - ('right', '^'), - ) + precedence = (('left', '+', '-'), ('left', '*', '/'), ('right', '^')) def p_start(self, p): """start : qasm""" diff --git a/cirq-core/cirq/contrib/qasm_import/_parser_test.py b/cirq-core/cirq/contrib/qasm_import/_parser_test.py index d6113a8ee12..451e30da4c0 100644 --- a/cirq-core/cirq/contrib/qasm_import/_parser_test.py +++ b/cirq-core/cirq/contrib/qasm_import/_parser_test.py @@ -55,14 +55,7 @@ def test_format_header_with_quelibinc_circuit(): ct.assert_same_circuits(parsed_qasm.circuit, Circuit()) -@pytest.mark.parametrize( - 'qasm', - [ - "include \"qelib1.inc\";", - "", - "qreg q[3];", - ], -) +@pytest.mark.parametrize('qasm', ["include \"qelib1.inc\";", "", "qreg q[3];"]) def test_error_not_starting_with_format(qasm: str): parser = QasmParser() @@ -229,8 +222,7 @@ def test_classical_control(): q_0 = cirq.NamedQubit('q_0') q_1 = cirq.NamedQubit('q_1') expected_circuit = cirq.Circuit( - cirq.measure(q_0, key='m_a_0'), - cirq.CNOT(q_0, q_1).with_classical_controls('m_a_0'), + cirq.measure(q_0, key='m_a_0'), cirq.CNOT(q_0, q_1).with_classical_controls('m_a_0') ) parsed_qasm = parser.parse(qasm) @@ -420,11 +412,7 @@ def test_unknown_function(): parser.parse(qasm) -rotation_gates = [ - ('rx', cirq.rx), - ('ry', cirq.ry), - ('rz', cirq.rz), -] +rotation_gates = [('rx', cirq.rx), ('ry', cirq.ry), ('rz', cirq.rz)] single_qubit_gates = [ @@ -458,13 +446,7 @@ def test_rotation_gates(qasm_gate: str, cirq_gate: cirq.SingleQubitGate): expected_circuit = Circuit() expected_circuit.append(cirq.Moment([cirq_gate(np.pi / 2).on(q0), cirq_gate(np.pi).on(q1)])) - expected_circuit.append( - cirq.Moment( - [ - cirq_gate(np.pi).on(q0), - ] - ) - ) + expected_circuit.append(cirq.Moment([cirq_gate(np.pi).on(q0)])) parsed_qasm = parser.parse(qasm) @@ -796,14 +778,7 @@ def test_r_gate(): @pytest.mark.parametrize( 'qasm_gate', - [ - 'id', - 'u2', - 'u3', - 'r', - ] - + [g[0] for g in rotation_gates] - + [g[0] for g in single_qubit_gates], + ['id', 'u2', 'u3', 'r'] + [g[0] for g in rotation_gates] + [g[0] for g in single_qubit_gates], ) def test_standard_single_qubit_gates_wrong_number_of_args(qasm_gate): qasm = f""" @@ -1029,13 +1004,7 @@ def test_single_qubit_gates(qasm_gate: str, cirq_gate: cirq.SingleQubitGate): q0 = cirq.NamedQubit('q_0') q1 = cirq.NamedQubit('q_1') - expected_circuit = Circuit( - [ - cirq_gate.on(q0), - cirq_gate.on(q0), - cirq_gate.on(q1), - ] - ) + expected_circuit = Circuit([cirq_gate.on(q0), cirq_gate.on(q0), cirq_gate.on(q1)]) parsed_qasm = parser.parse(qasm) diff --git a/cirq-core/cirq/contrib/qcircuit/__init__.py b/cirq-core/cirq/contrib/qcircuit/__init__.py index 67d8d16d110..a187c0b206e 100644 --- a/cirq-core/cirq/contrib/qcircuit/__init__.py +++ b/cirq-core/cirq/contrib/qcircuit/__init__.py @@ -14,9 +14,7 @@ """Converts cirq circuits into latex using qcircuit.""" -from cirq.contrib.qcircuit.qcircuit_diagram import ( - circuit_to_latex_using_qcircuit, -) +from cirq.contrib.qcircuit.qcircuit_diagram import circuit_to_latex_using_qcircuit from cirq.contrib.qcircuit.qcircuit_diagram_info import ( escape_text_for_latex, diff --git a/cirq-core/cirq/contrib/qcircuit/qcircuit_diagram_info.py b/cirq-core/cirq/contrib/qcircuit/qcircuit_diagram_info.py index 8f88d0f422c..871dd4470f8 100644 --- a/cirq-core/cirq/contrib/qcircuit/qcircuit_diagram_info.py +++ b/cirq-core/cirq/contrib/qcircuit/qcircuit_diagram_info.py @@ -73,8 +73,7 @@ def convert_text_diagram_info_to_qcircuit_diagram_info( def multigate_qcircuit_diagram_info( - op: ops.Operation, - args: protocols.CircuitDiagramInfoArgs, + op: ops.Operation, args: protocols.CircuitDiagramInfoArgs ) -> Optional[protocols.CircuitDiagramInfo]: if not ( isinstance(op, ops.GateOperation) and isinstance(op.gate, ops.InterchangeableQubitsGate) diff --git a/cirq-core/cirq/contrib/quantum_volume/quantum_volume_test.py b/cirq-core/cirq/contrib/quantum_volume/quantum_volume_test.py index 3b452ebdf2e..7fd36029240 100644 --- a/cirq-core/cirq/contrib/quantum_volume/quantum_volume_test.py +++ b/cirq-core/cirq/contrib/quantum_volume/quantum_volume_test.py @@ -134,11 +134,7 @@ def test_compile_circuit(): """Tests that we are able to compile a model circuit.""" compiler_mock = MagicMock(side_effect=lambda circuit: circuit) a, b, c = cirq.LineQubit.range(3) - model_circuit = cirq.Circuit( - [ - cirq.Moment([cirq.X(a), cirq.Y(b), cirq.Z(c)]), - ] - ) + model_circuit = cirq.Circuit([cirq.Moment([cirq.X(a), cirq.Y(b), cirq.Z(c)])]) compilation_result = cirq.contrib.quantum_volume.compile_circuit( model_circuit, device_graph=ccr.gridqubits_to_graph_device(FakeDevice().qubits), @@ -202,11 +198,7 @@ def test_compile_circuit_with_readout_correction(): router_mock = MagicMock(side_effect=lambda circuit, network: ccr.SwapNetwork(circuit, {})) a, b, c = cirq.LineQubit.range(3) ap, bp, cp = cirq.LineQubit.range(3, 6) - model_circuit = cirq.Circuit( - [ - cirq.Moment([cirq.X(a), cirq.Y(b), cirq.Z(c)]), - ] - ) + model_circuit = cirq.Circuit([cirq.Moment([cirq.X(a), cirq.Y(b), cirq.Z(c)])]) compilation_result = cirq.contrib.quantum_volume.compile_circuit( model_circuit, device_graph=ccr.gridqubits_to_graph_device(FakeDevice().qubits), @@ -230,22 +222,9 @@ def test_compile_circuit_multiple_routing_attempts(): """Tests that we make multiple attempts at routing and keep the best one.""" qubits = cirq.LineQubit.range(3) initial_mapping = dict(zip(qubits, qubits)) - more_operations = cirq.Circuit( - [ - cirq.X.on_each(qubits), - cirq.Y.on_each(qubits), - ] - ) - more_qubits = cirq.Circuit( - [ - cirq.X.on_each(cirq.LineQubit.range(4)), - ] - ) - well_routed = cirq.Circuit( - [ - cirq.X.on_each(qubits), - ] - ) + more_operations = cirq.Circuit([cirq.X.on_each(qubits), cirq.Y.on_each(qubits)]) + more_qubits = cirq.Circuit([cirq.X.on_each(cirq.LineQubit.range(4))]) + well_routed = cirq.Circuit([cirq.X.on_each(qubits)]) router_mock = MagicMock( side_effect=[ ccr.SwapNetwork(more_operations, initial_mapping), @@ -272,11 +251,7 @@ def test_compile_circuit_multiple_routing_attempts(): def test_compile_circuit_no_routing_attempts(): """Tests that setting no routing attempts throws an error.""" a, b, c = cirq.LineQubit.range(3) - model_circuit = cirq.Circuit( - [ - cirq.Moment([cirq.X(a), cirq.Y(b), cirq.Z(c)]), - ] - ) + model_circuit = cirq.Circuit([cirq.Moment([cirq.X(a), cirq.Y(b), cirq.Z(c)])]) with pytest.raises(AssertionError) as e: cirq.contrib.quantum_volume.compile_circuit( diff --git a/cirq-core/cirq/contrib/quil_import/quil.py b/cirq-core/cirq/contrib/quil_import/quil.py index 346f68b90af..a2a6765aa68 100644 --- a/cirq-core/cirq/contrib/quil_import/quil.py +++ b/cirq-core/cirq/contrib/quil_import/quil.py @@ -152,15 +152,17 @@ def pswap(phi: float) -> MatrixGate: Returns: A MatrixGate equivalent to a PSWAP gate of given angle. """ + # fmt: off pswap_matrix = np.array( [ [1, 0, 0, 0], [0, 0, np.exp(1j * phi), 0], [0, np.exp(1j * phi), 0, 0], - [0, 0, 0, 1], + [0, 0, 0, 1] ], dtype=complex, ) + # fmt: on return MatrixGate(pswap_matrix) diff --git a/cirq-core/cirq/contrib/quimb/grid_circuits.py b/cirq-core/cirq/contrib/quimb/grid_circuits.py index 818d4eaa591..85d19ee6ff2 100644 --- a/cirq-core/cirq/contrib/quimb/grid_circuits.py +++ b/cirq-core/cirq/contrib/quimb/grid_circuits.py @@ -92,11 +92,7 @@ def _interaction( class MergeNQubitGates(cirq.PointOptimizer): """Optimizes runs of adjacent unitary n-qubit operations.""" - def __init__( - self, - *, - n_qubits: int, - ): + def __init__(self, *, n_qubits: int): super().__init__() self.n_qubits = n_qubits diff --git a/cirq-core/cirq/contrib/quirk/__init__.py b/cirq-core/cirq/contrib/quirk/__init__.py index 2a68770ac52..250ef97fe66 100644 --- a/cirq-core/cirq/contrib/quirk/__init__.py +++ b/cirq-core/cirq/contrib/quirk/__init__.py @@ -14,6 +14,4 @@ """Converts cirq circuits into quirk circuits.""" -from cirq.contrib.quirk.export_to_quirk import ( - circuit_to_quirk_url, -) +from cirq.contrib.quirk.export_to_quirk import circuit_to_quirk_url diff --git a/cirq-core/cirq/contrib/quirk/export_to_quirk_test.py b/cirq-core/cirq/contrib/quirk/export_to_quirk_test.py index e8fe3d0969a..49d18f75297 100644 --- a/cirq-core/cirq/contrib/quirk/export_to_quirk_test.py +++ b/cirq-core/cirq/contrib/quirk/export_to_quirk_test.py @@ -245,9 +245,7 @@ def test_formulaic_rotation_xyz_export(): t = sympy.Symbol('t') assert_links_to( cirq.Circuit( - cirq.rx(sympy.pi / 2).on(a), - cirq.ry(sympy.pi * t).on(a), - cirq.rz(-sympy.pi * t).on(a), + cirq.rx(sympy.pi / 2).on(a), cirq.ry(sympy.pi * t).on(a), cirq.rz(-sympy.pi * t).on(a) ), """ http://algassert.com/quirk#circuit={"cols":[ diff --git a/cirq-core/cirq/contrib/routing/device_test.py b/cirq-core/cirq/contrib/routing/device_test.py index f9409ce6894..c42a977060e 100644 --- a/cirq-core/cirq/contrib/routing/device_test.py +++ b/cirq-core/cirq/contrib/routing/device_test.py @@ -39,10 +39,7 @@ def test_nx_qubit_layout(): def test_nx_qubit_layout_2(): g = nx.from_edgelist( - [ - (cirq.LineQubit(0), cirq.LineQubit(1)), - (cirq.LineQubit(1), cirq.LineQubit(2)), - ] + [(cirq.LineQubit(0), cirq.LineQubit(1)), (cirq.LineQubit(1), cirq.LineQubit(2))] ) pos = ccr.nx_qubit_layout(g) for k, (x, y) in pos.items(): @@ -52,16 +49,9 @@ def test_nx_qubit_layout_2(): def test_nx_qubit_layout_3(): g = nx.from_edgelist( - [ - (cirq.NamedQubit('a'), cirq.NamedQubit('b')), - (cirq.NamedQubit('b'), cirq.NamedQubit('c')), - ] + [(cirq.NamedQubit('a'), cirq.NamedQubit('b')), (cirq.NamedQubit('b'), cirq.NamedQubit('c'))] ) - node_to_i = { - cirq.NamedQubit('a'): 0, - cirq.NamedQubit('b'): 1, - cirq.NamedQubit('c'): 2, - } + node_to_i = {cirq.NamedQubit('a'): 0, cirq.NamedQubit('b'): 1, cirq.NamedQubit('c'): 2} pos = ccr.nx_qubit_layout(g) for k, (x, y) in pos.items(): diff --git a/cirq-core/cirq/contrib/routing/router.py b/cirq-core/cirq/contrib/routing/router.py index 448710e62fd..1fd13764251 100644 --- a/cirq-core/cirq/contrib/routing/router.py +++ b/cirq-core/cirq/contrib/routing/router.py @@ -20,9 +20,7 @@ from cirq.contrib.routing.greedy import route_circuit_greedily from cirq.contrib.routing.swap_network import SwapNetwork -ROUTERS = { - 'greedy': route_circuit_greedily, -} +ROUTERS = {'greedy': route_circuit_greedily} def route_circuit( diff --git a/cirq-core/cirq/contrib/routing/swap_network.py b/cirq-core/cirq/contrib/routing/swap_network.py index 3e6a91edc0d..8600ee8ed19 100644 --- a/cirq-core/cirq/contrib/routing/swap_network.py +++ b/cirq-core/cirq/contrib/routing/swap_network.py @@ -36,9 +36,7 @@ class SwapNetwork: """ def __init__( - self, - circuit: 'cirq.Circuit', - initial_mapping: Dict['cirq.Qid', 'cirq.Qid'], + self, circuit: 'cirq.Circuit', initial_mapping: Dict['cirq.Qid', 'cirq.Qid'] ) -> None: if not all(isinstance(i, ops.Qid) for I in initial_mapping.items() for i in I): raise ValueError('Mapping must be from Qids to Qids.') diff --git a/cirq-core/cirq/contrib/routing/utils_test.py b/cirq-core/cirq/contrib/routing/utils_test.py index 66ba5aea12b..31b6c1ba115 100644 --- a/cirq-core/cirq/contrib/routing/utils_test.py +++ b/cirq-core/cirq/contrib/routing/utils_test.py @@ -31,12 +31,7 @@ def test_ops_are_consistent_with_device_graph(): def test_get_circuit_connectivity(): a, b, c, d = cirq.LineQubit.range(4) - circuit = cirq.Circuit( - cirq.CZ(a, b), - cirq.CZ(b, c), - cirq.CZ(c, d), - cirq.CZ(d, a), - ) + circuit = cirq.Circuit(cirq.CZ(a, b), cirq.CZ(b, c), cirq.CZ(c, d), cirq.CZ(d, a)) graph = ccr.get_circuit_connectivity(circuit) assert graph.number_of_nodes() == 4 assert graph.number_of_edges() == 4 diff --git a/cirq-core/cirq/contrib/svg/__init__.py b/cirq-core/cirq/contrib/svg/__init__.py index 07f39815c97..03c5ce93113 100644 --- a/cirq-core/cirq/contrib/svg/__init__.py +++ b/cirq-core/cirq/contrib/svg/__init__.py @@ -1,5 +1,2 @@ # pylint: disable=wrong-or-nonexistent-copyright-notice -from cirq.contrib.svg.svg import ( - SVGCircuit, - circuit_to_svg, -) +from cirq.contrib.svg.svg import SVGCircuit, circuit_to_svg diff --git a/cirq-core/cirq/devices/__init__.py b/cirq-core/cirq/devices/__init__.py index 1c9c68f5f59..d75cd967c19 100644 --- a/cirq-core/cirq/devices/__init__.py +++ b/cirq-core/cirq/devices/__init__.py @@ -14,36 +14,17 @@ """Device classes, qubits, and topologies, as well as noise models.""" -from cirq.devices.device import ( - Device, - DeviceMetadata, - SymmetricalQidPair, -) +from cirq.devices.device import Device, DeviceMetadata, SymmetricalQidPair -from cirq.devices.grid_device_metadata import ( - GridDeviceMetadata, -) +from cirq.devices.grid_device_metadata import GridDeviceMetadata -from cirq.devices.grid_qubit import ( - GridQid, - GridQubit, -) +from cirq.devices.grid_qubit import GridQid, GridQubit -from cirq.devices.line_qubit import ( - LineQubit, - LineQid, -) +from cirq.devices.line_qubit import LineQubit, LineQid -from cirq.devices.unconstrained_device import ( - UNCONSTRAINED_DEVICE, -) +from cirq.devices.unconstrained_device import UNCONSTRAINED_DEVICE -from cirq.devices.noise_model import ( - NO_NOISE, - NOISE_MODEL_LIKE, - NoiseModel, - ConstantQubitNoiseModel, -) +from cirq.devices.noise_model import NO_NOISE, NOISE_MODEL_LIKE, NoiseModel, ConstantQubitNoiseModel from cirq.devices.named_topologies import ( NamedTopology, @@ -54,18 +35,11 @@ draw_placements, ) -from cirq.devices.insertion_noise_model import ( - InsertionNoiseModel, -) +from cirq.devices.insertion_noise_model import InsertionNoiseModel -from cirq.devices.thermal_noise_model import ( - ThermalNoiseModel, -) +from cirq.devices.thermal_noise_model import ThermalNoiseModel -from cirq.devices.noise_properties import ( - NoiseModelFromNoiseProperties, - NoiseProperties, -) +from cirq.devices.noise_properties import NoiseModelFromNoiseProperties, NoiseProperties from cirq.devices.superconducting_qubits_noise_properties import ( SuperconductingQubitsNoiseProperties, diff --git a/cirq-core/cirq/devices/device.py b/cirq-core/cirq/devices/device.py index d0acb6a2283..3f265a1e262 100644 --- a/cirq-core/cirq/devices/device.py +++ b/cirq-core/cirq/devices/device.py @@ -13,15 +13,7 @@ # limitations under the License. import abc -from typing import ( - TYPE_CHECKING, - Optional, - AbstractSet, - cast, - FrozenSet, - Iterator, - Iterable, -) +from typing import TYPE_CHECKING, Optional, AbstractSet, cast, FrozenSet, Iterator, Iterable import networkx as nx from cirq import _compat, value from cirq.devices.grid_qubit import _BaseGridQid @@ -60,8 +52,7 @@ def qubit_set(self) -> Optional[AbstractSet['cirq.Qid']]: return None @_compat.deprecated( - deadline='v0.15', - fix='qubit coupling data can now be found in device.metadata if provided.', + deadline='v0.15', fix='qubit coupling data can now be found in device.metadata if provided.' ) def qid_pairs(self) -> Optional[FrozenSet['cirq.SymmetricalQidPair']]: """Returns a set of qubit edges on the device, if possible. @@ -101,10 +92,7 @@ def qid_pairs(self) -> Optional[FrozenSet['cirq.SymmetricalQidPair']]: ) return frozenset([SymmetricalQidPair(q, q2) for q in qs for q2 in qs if q < q2]) - @_compat.deprecated( - deadline='v0.15', - fix='Devices will no longer decompose operations.', - ) + @_compat.deprecated(deadline='v0.15', fix='Devices will no longer decompose operations.') def decompose_operation(self, operation: 'cirq.Operation') -> 'cirq.OP_TREE': """Returns a device-valid decomposition for the given operation. @@ -198,9 +186,7 @@ def __repr__(self): return f'cirq.QidPair({repr(sorted(self.qids))[1:-1]})' def _json_dict_(self): - return { - 'qids': sorted(self.qids), - } + return {'qids': sorted(self.qids)} @classmethod def _from_json_dict_(cls, qids, **kwargs): @@ -220,11 +206,7 @@ def __contains__(self, item: 'cirq.Qid') -> bool: class DeviceMetadata: """Parent type for all device specific metadata classes.""" - def __init__( - self, - qubits: Iterable['cirq.Qid'], - nx_graph: 'nx.Graph', - ): + def __init__(self, qubits: Iterable['cirq.Qid'], nx_graph: 'nx.Graph'): """Construct a DeviceMetadata object. Args: diff --git a/cirq-core/cirq/devices/grid_device_metadata.py b/cirq-core/cirq/devices/grid_device_metadata.py index e0ccd2d55f6..038cb5d8c9e 100644 --- a/cirq-core/cirq/devices/grid_device_metadata.py +++ b/cirq-core/cirq/devices/grid_device_metadata.py @@ -13,14 +13,7 @@ # limitations under the License. """Metadata subtype for 2D Homogenous devices.""" -from typing import ( - TYPE_CHECKING, - Optional, - FrozenSet, - Iterable, - Tuple, - Dict, -) +from typing import TYPE_CHECKING, Optional, FrozenSet, Iterable, Tuple, Dict import networkx as nx from cirq import value diff --git a/cirq-core/cirq/devices/grid_qubit_test.py b/cirq-core/cirq/devices/grid_qubit_test.py index b5ec318e04a..f2d38a07069 100644 --- a/cirq-core/cirq/devices/grid_qubit_test.py +++ b/cirq-core/cirq/devices/grid_qubit_test.py @@ -64,10 +64,7 @@ def test_repr(): def test_cmp(): order = cirq.testing.OrderTester() - order.add_ascending_equivalence_group( - cirq.GridQubit(0, 0), - cirq.GridQid(0, 0, dimension=2), - ) + order.add_ascending_equivalence_group(cirq.GridQubit(0, 0), cirq.GridQid(0, 0, dimension=2)) order.add_ascending( cirq.GridQid(0, 0, dimension=3), cirq.GridQid(0, 1, dimension=1), @@ -320,16 +317,9 @@ def test_neg(): def test_to_json(): - assert cirq.GridQubit(5, 6)._json_dict_() == { - 'row': 5, - 'col': 6, - } + assert cirq.GridQubit(5, 6)._json_dict_() == {'row': 5, 'col': 6} - assert cirq.GridQid(5, 6, dimension=3)._json_dict_() == { - 'row': 5, - 'col': 6, - 'dimension': 3, - } + assert cirq.GridQid(5, 6, dimension=3)._json_dict_() == {'row': 5, 'col': 6, 'dimension': 3} def test_immutable(): diff --git a/cirq-core/cirq/devices/insertion_noise_model_test.py b/cirq-core/cirq/devices/insertion_noise_model_test.py index fea42f315a5..dc15eec2b44 100644 --- a/cirq-core/cirq/devices/insertion_noise_model_test.py +++ b/cirq-core/cirq/devices/insertion_noise_model_test.py @@ -14,10 +14,7 @@ import cirq from cirq.devices.insertion_noise_model import InsertionNoiseModel -from cirq.devices.noise_utils import ( - PHYSICAL_GATE_TAG, - OpIdentifier, -) +from cirq.devices.noise_utils import PHYSICAL_GATE_TAG, OpIdentifier def test_insertion_noise(): @@ -105,13 +102,7 @@ def test_supertype_matching(): ) moment_0 = cirq.Moment(cirq.Rx(rads=1).on(q0)) - assert model.noisy_moment(moment_0, system_qubits=[q0]) == [ - moment_0, - cirq.Moment(cirq.S(q0)), - ] + assert model.noisy_moment(moment_0, system_qubits=[q0]) == [moment_0, cirq.Moment(cirq.S(q0))] moment_1 = cirq.Moment(cirq.Y(q0)) - assert model.noisy_moment(moment_1, system_qubits=[q0]) == [ - moment_1, - cirq.Moment(cirq.T(q0)), - ] + assert model.noisy_moment(moment_1, system_qubits=[q0]) == [moment_1, cirq.Moment(cirq.T(q0))] diff --git a/cirq-core/cirq/devices/line_qubit_test.py b/cirq-core/cirq/devices/line_qubit_test.py index be857fd12d9..72b9b59b444 100644 --- a/cirq-core/cirq/devices/line_qubit_test.py +++ b/cirq-core/cirq/devices/line_qubit_test.py @@ -46,10 +46,7 @@ def test_repr(): def test_cmp(): order = cirq.testing.OrderTester() - order.add_ascending_equivalence_group( - cirq.LineQubit(0), - cirq.LineQid(0, 2), - ) + order.add_ascending_equivalence_group(cirq.LineQubit(0), cirq.LineQid(0, 2)) order.add_ascending( cirq.LineQid(0, dimension=3), cirq.LineQid(1, dimension=1), @@ -111,10 +108,7 @@ def test_range(): def test_qid_range(): assert cirq.LineQid.range(0, dimension=3) == [] assert cirq.LineQid.range(1, dimension=3) == [cirq.LineQid(0, 3)] - assert cirq.LineQid.range(2, dimension=3) == [ - cirq.LineQid(0, 3), - cirq.LineQid(1, 3), - ] + assert cirq.LineQid.range(2, dimension=3) == [cirq.LineQid(0, 3), cirq.LineQid(1, 3)] assert cirq.LineQid.range(5, dimension=3) == [ cirq.LineQid(0, 3), cirq.LineQid(1, 3), @@ -131,15 +125,9 @@ def test_qid_range(): cirq.LineQid(3, 4), ] - assert cirq.LineQid.range(3, 1, -1, dimension=1) == [ - cirq.LineQid(3, 1), - cirq.LineQid(2, 1), - ] + assert cirq.LineQid.range(3, 1, -1, dimension=1) == [cirq.LineQid(3, 1), cirq.LineQid(2, 1)] assert cirq.LineQid.range(3, 5, -1, dimension=2) == [] - assert cirq.LineQid.range(1, 5, 2, dimension=2) == [ - cirq.LineQid(1, 2), - cirq.LineQid(3, 2), - ] + assert cirq.LineQid.range(1, 5, 2, dimension=2) == [cirq.LineQid(1, 2), cirq.LineQid(3, 2)] def test_for_qid_shape(): @@ -213,13 +201,8 @@ def test_neg(): def test_json_dict(): - assert cirq.LineQubit(5)._json_dict_() == { - 'x': 5, - } - assert cirq.LineQid(5, 3)._json_dict_() == { - 'x': 5, - 'dimension': 3, - } + assert cirq.LineQubit(5)._json_dict_() == {'x': 5} + assert cirq.LineQid(5, 3)._json_dict_() == {'x': 5, 'dimension': 3} def test_for_gate(): diff --git a/cirq-core/cirq/devices/named_topologies_test.py b/cirq-core/cirq/devices/named_topologies_test.py index c4adea6902e..476af99a87b 100644 --- a/cirq-core/cirq/devices/named_topologies_test.py +++ b/cirq-core/cirq/devices/named_topologies_test.py @@ -17,13 +17,7 @@ import cirq import networkx as nx import pytest -from cirq import ( - draw_gridlike, - LineTopology, - TiltedSquareLattice, - get_placements, - draw_placements, -) +from cirq import draw_gridlike, LineTopology, TiltedSquareLattice, get_placements, draw_placements @pytest.mark.parametrize('width, height', list(itertools.product([1, 2, 3, 24], repeat=2))) diff --git a/cirq-core/cirq/devices/noise_model_test.py b/cirq-core/cirq/devices/noise_model_test.py index ad4c5809f08..0e66579f981 100644 --- a/cirq-core/cirq/devices/noise_model_test.py +++ b/cirq-core/cirq/devices/noise_model_test.py @@ -205,14 +205,7 @@ def test_moment_is_measurements(): def test_moment_is_measurements_mixed1(): q = cirq.LineQubit.range(2) - circ = cirq.Circuit( - [ - cirq.X(q[0]), - cirq.X(q[1]), - cirq.measure(q[0], key='z'), - cirq.Z(q[1]), - ] - ) + circ = cirq.Circuit([cirq.X(q[0]), cirq.X(q[1]), cirq.measure(q[0], key='z'), cirq.Z(q[1])]) assert not validate_all_measurements(circ[0]) with pytest.raises(ValueError) as e: validate_all_measurements(circ[1]) @@ -221,14 +214,7 @@ def test_moment_is_measurements_mixed1(): def test_moment_is_measurements_mixed2(): q = cirq.LineQubit.range(2) - circ = cirq.Circuit( - [ - cirq.X(q[0]), - cirq.X(q[1]), - cirq.Z(q[0]), - cirq.measure(q[1], key='z'), - ] - ) + circ = cirq.Circuit([cirq.X(q[0]), cirq.X(q[1]), cirq.Z(q[0]), cirq.measure(q[1], key='z')]) assert not validate_all_measurements(circ[0]) with pytest.raises(ValueError) as e: validate_all_measurements(circ[1]) diff --git a/cirq-core/cirq/devices/noise_properties.py b/cirq-core/cirq/devices/noise_properties.py index 1c10d31bb52..5f6afeeb133 100644 --- a/cirq-core/cirq/devices/noise_properties.py +++ b/cirq-core/cirq/devices/noise_properties.py @@ -23,9 +23,7 @@ from typing import Iterable, Sequence, TYPE_CHECKING, List from cirq import _compat, _import, ops, protocols, devices -from cirq.devices.noise_utils import ( - PHYSICAL_GATE_TAG, -) +from cirq.devices.noise_utils import PHYSICAL_GATE_TAG circuits = _import.LazyLoader("circuits", globals(), "cirq.circuits.circuit") diff --git a/cirq-core/cirq/devices/noise_properties_test.py b/cirq-core/cirq/devices/noise_properties_test.py index 582e5754e89..2f748ac2d30 100644 --- a/cirq-core/cirq/devices/noise_properties_test.py +++ b/cirq-core/cirq/devices/noise_properties_test.py @@ -16,14 +16,8 @@ import cirq from cirq.devices.insertion_noise_model import InsertionNoiseModel -from cirq.devices.noise_properties import ( - NoiseProperties, - NoiseModelFromNoiseProperties, -) -from cirq.devices.noise_utils import ( - OpIdentifier, - PHYSICAL_GATE_TAG, -) +from cirq.devices.noise_properties import NoiseProperties, NoiseModelFromNoiseProperties +from cirq.devices.noise_utils import OpIdentifier, PHYSICAL_GATE_TAG # These properties are for testing purposes only - they are not representative diff --git a/cirq-core/cirq/devices/noise_utils.py b/cirq-core/cirq/devices/noise_utils.py index 3a38ee40abd..4086ba5c741 100644 --- a/cirq-core/cirq/devices/noise_utils.py +++ b/cirq-core/cirq/devices/noise_utils.py @@ -87,10 +87,7 @@ def _value_equality_values_(self) -> Any: def _json_dict_(self) -> Dict[str, Any]: gate_json = protocols.json_cirq_type(self._gate_type) - return { - 'gate_type': gate_json, - 'qubits': self._qubits, - } + return {'gate_type': gate_json, 'qubits': self._qubits} @classmethod def _from_json_dict_(cls, gate_type, qubits, **kwargs) -> 'OpIdentifier': diff --git a/cirq-core/cirq/devices/noise_utils_test.py b/cirq-core/cirq/devices/noise_utils_test.py index ac541018bed..3bbca9e370a 100644 --- a/cirq-core/cirq/devices/noise_utils_test.py +++ b/cirq-core/cirq/devices/noise_utils_test.py @@ -66,10 +66,7 @@ def test_op_id_swap(): @pytest.mark.parametrize( 'decay_constant,num_qubits,expected_output', - [ - (0.01, 1, 1 - (0.99 * 1 / 2)), - (0.05, 2, 1 - (0.95 * 3 / 4)), - ], + [(0.01, 1, 1 - (0.99 * 1 / 2)), (0.05, 2, 1 - (0.95 * 3 / 4))], ) def test_decay_constant_to_xeb_fidelity(decay_constant, num_qubits, expected_output): val = decay_constant_to_xeb_fidelity(decay_constant, num_qubits) @@ -78,10 +75,7 @@ def test_decay_constant_to_xeb_fidelity(decay_constant, num_qubits, expected_out @pytest.mark.parametrize( 'decay_constant,num_qubits,expected_output', - [ - (0.01, 1, 0.99 * 3 / 4), - (0.05, 2, 0.95 * 15 / 16), - ], + [(0.01, 1, 0.99 * 3 / 4), (0.05, 2, 0.95 * 15 / 16)], ) def test_decay_constant_to_pauli_error(decay_constant, num_qubits, expected_output): val = decay_constant_to_pauli_error(decay_constant, num_qubits) @@ -90,10 +84,7 @@ def test_decay_constant_to_pauli_error(decay_constant, num_qubits, expected_outp @pytest.mark.parametrize( 'pauli_error,num_qubits,expected_output', - [ - (0.01, 1, 1 - (0.01 / (3 / 4))), - (0.05, 2, 1 - (0.05 / (15 / 16))), - ], + [(0.01, 1, 1 - (0.01 / (3 / 4))), (0.05, 2, 1 - (0.05 / (15 / 16)))], ) def test_pauli_error_to_decay_constant(pauli_error, num_qubits, expected_output): val = pauli_error_to_decay_constant(pauli_error, num_qubits) @@ -102,10 +93,7 @@ def test_pauli_error_to_decay_constant(pauli_error, num_qubits, expected_output) @pytest.mark.parametrize( 'xeb_fidelity,num_qubits,expected_output', - [ - (0.01, 1, 1 - 0.99 / (1 / 2)), - (0.05, 2, 1 - 0.95 / (3 / 4)), - ], + [(0.01, 1, 1 - 0.99 / (1 / 2)), (0.05, 2, 1 - 0.95 / (3 / 4))], ) def test_xeb_fidelity_to_decay_constant(xeb_fidelity, num_qubits, expected_output): val = xeb_fidelity_to_decay_constant(xeb_fidelity, num_qubits) @@ -125,11 +113,7 @@ def test_pauli_error_from_t1(t, t1_ns, expected_output): @pytest.mark.parametrize( - 'decay_constant,num_qubits,expected_output', - [ - (0.01, 1, 0.99 * 1 / 2), - (0.05, 2, 0.95 * 3 / 4), - ], + 'decay_constant,num_qubits,expected_output', [(0.01, 1, 0.99 * 1 / 2), (0.05, 2, 0.95 * 3 / 4)] ) def test_average_error(decay_constant, num_qubits, expected_output): val = average_error(decay_constant, num_qubits) @@ -137,12 +121,7 @@ def test_average_error(decay_constant, num_qubits, expected_output): @pytest.mark.parametrize( - 'T1_ns,Tphi_ns,gate_time_ns', - [ - (1e4, 2e4, 25), - (1e5, 2e3, 25), - (1e4, 2e4, 4000), - ], + 'T1_ns,Tphi_ns,gate_time_ns', [(1e4, 2e4, 25), (1e5, 2e3, 25), (1e4, 2e4, 4000)] ) def test_decoherence_pauli_error(T1_ns, Tphi_ns, gate_time_ns): val = decoherence_pauli_error(T1_ns, Tphi_ns, gate_time_ns) diff --git a/cirq-core/cirq/devices/superconducting_qubits_noise_properties_test.py b/cirq-core/cirq/devices/superconducting_qubits_noise_properties_test.py index e5457a00dcf..053fbb2eab9 100644 --- a/cirq-core/cirq/devices/superconducting_qubits_noise_properties_test.py +++ b/cirq-core/cirq/devices/superconducting_qubits_noise_properties_test.py @@ -17,16 +17,11 @@ import cirq import pytest -from cirq.devices.noise_properties import ( - NoiseModelFromNoiseProperties, -) +from cirq.devices.noise_properties import NoiseModelFromNoiseProperties from cirq.devices.superconducting_qubits_noise_properties import ( SuperconductingQubitsNoiseProperties, ) -from cirq.devices.noise_utils import ( - OpIdentifier, - PHYSICAL_GATE_TAG, -) +from cirq.devices.noise_utils import OpIdentifier, PHYSICAL_GATE_TAG DEFAULT_GATE_NS: Dict[type, float] = { @@ -69,21 +64,11 @@ def __init__(self, *args, **kwargs): @classmethod def single_qubit_gates(cls) -> Set[type]: - return { - cirq.ZPowGate, - cirq.PhasedXZGate, - cirq.MeasurementGate, - cirq.ResetChannel, - } + return {cirq.ZPowGate, cirq.PhasedXZGate, cirq.MeasurementGate, cirq.ResetChannel} @classmethod def symmetric_two_qubit_gates(cls) -> Set[type]: - return { - cirq.FSimGate, - cirq.PhasedFSimGate, - cirq.ISwapPowGate, - cirq.CZPowGate, - } + return {cirq.FSimGate, cirq.PhasedFSimGate, cirq.ISwapPowGate, cirq.CZPowGate} @classmethod def asymmetric_two_qubit_gates(cls) -> Set[type]: @@ -260,11 +245,7 @@ def test_single_qubit_gates(op): @pytest.mark.parametrize( - 'op', - [ - cirq.ISWAP(*cirq.LineQubit.range(2)) ** 0.6, - cirq.CZ(*cirq.LineQubit.range(2)) ** 0.3, - ], + 'op', [cirq.ISWAP(*cirq.LineQubit.range(2)) ** 0.6, cirq.CZ(*cirq.LineQubit.range(2)) ** 0.3] ) def test_two_qubit_gates(op): q0, q1 = cirq.LineQubit.range(2) diff --git a/cirq-core/cirq/devices/thermal_noise_model.py b/cirq-core/cirq/devices/thermal_noise_model.py index a7033b9232f..015fbb88332 100644 --- a/cirq-core/cirq/devices/thermal_noise_model.py +++ b/cirq-core/cirq/devices/thermal_noise_model.py @@ -20,9 +20,7 @@ from cirq import devices, ops, protocols, qis from cirq._import import LazyLoader -from cirq.devices.noise_utils import ( - PHYSICAL_GATE_TAG, -) +from cirq.devices.noise_utils import PHYSICAL_GATE_TAG if TYPE_CHECKING: import cirq @@ -129,8 +127,7 @@ def _decoherence_matrix( def _as_rate_dict( - rate_or_dict: Optional[Union[float, Dict['cirq.Qid', float]]], - qubits: Set['cirq.Qid'], + rate_or_dict: Optional[Union[float, Dict['cirq.Qid', float]]], qubits: Set['cirq.Qid'] ) -> Dict['cirq.Qid', float]: """Convert float or None input into dictionary form. diff --git a/cirq-core/cirq/devices/thermal_noise_model_test.py b/cirq-core/cirq/devices/thermal_noise_model_test.py index 42f5375934a..ca6481b3a58 100644 --- a/cirq-core/cirq/devices/thermal_noise_model_test.py +++ b/cirq-core/cirq/devices/thermal_noise_model_test.py @@ -16,9 +16,7 @@ import pytest import cirq -from cirq.devices.noise_utils import ( - PHYSICAL_GATE_TAG, -) +from cirq.devices.noise_utils import PHYSICAL_GATE_TAG from cirq.devices.thermal_noise_model import ( _left_mul, _right_mul, @@ -176,10 +174,7 @@ def test_noise_from_measurement(): # Verify that a moment with only measurement gates has no noise if # skip_measurements is True. q0, q1 = cirq.LineQubit.range(2) - gate_durations = { - cirq.ZPowGate: 25.0, - cirq.MeasurementGate: 4000.0, - } + gate_durations = {cirq.ZPowGate: 25.0, cirq.MeasurementGate: 4000.0} heat_rate_GHz = {q1: 1e-5} cool_rate_GHz = {q0: 1e-4} model = ThermalNoiseModel( @@ -205,10 +200,7 @@ def test_noisy_moment_one_qubit(): q0, q1 = cirq.LineQubit.range(2) model = ThermalNoiseModel( qubits={q0, q1}, - gate_durations_ns={ - cirq.PhasedXZGate: 25.0, - cirq.CZPowGate: 25.0, - }, + gate_durations_ns={cirq.PhasedXZGate: 25.0, cirq.CZPowGate: 25.0}, heat_rate_GHz={q0: 1e-5, q1: 2e-5}, cool_rate_GHz={q0: 1e-4, q1: 2e-4}, dephase_rate_GHz={q0: 3e-4, q1: 4e-4}, @@ -268,10 +260,7 @@ def test_noisy_moment_two_qubit(): q0, q1 = cirq.LineQubit.range(2) model = ThermalNoiseModel( qubits={q0, q1}, - gate_durations_ns={ - cirq.PhasedXZGate: 25.0, - cirq.CZPowGate: 25.0, - }, + gate_durations_ns={cirq.PhasedXZGate: 25.0, cirq.CZPowGate: 25.0}, heat_rate_GHz={q0: 1e-5, q1: 2e-5}, cool_rate_GHz={q0: 1e-4, q1: 2e-4}, dephase_rate_GHz={q0: 3e-4, q1: 4e-4}, diff --git a/cirq-core/cirq/experiments/__init__.py b/cirq-core/cirq/experiments/__init__.py index 7a12206d15d..5f9183272c4 100644 --- a/cirq-core/cirq/experiments/__init__.py +++ b/cirq-core/cirq/experiments/__init__.py @@ -53,9 +53,7 @@ compute_grid_parallel_two_qubit_xeb_results, ) -from cirq.experiments.purity_estimation import ( - purity_from_probabilities, -) +from cirq.experiments.purity_estimation import purity_from_probabilities from cirq.experiments.random_quantum_circuit_generation import ( GRID_ALIGNED_PATTERN, @@ -82,14 +80,8 @@ SingleQubitReadoutCalibrationResult, ) -from cirq.experiments.t1_decay_experiment import ( - t1_decay, - T1DecayResult, -) +from cirq.experiments.t1_decay_experiment import t1_decay, T1DecayResult -from cirq.experiments.t2_decay_experiment import ( - t2_decay, - T2DecayResult, -) +from cirq.experiments.t2_decay_experiment import t2_decay, T2DecayResult from cirq.experiments.xeb_fitting import XEBPhasedFSimCharacterizationOptions diff --git a/cirq-core/cirq/experiments/cross_entropy_benchmarking.py b/cirq-core/cirq/experiments/cross_entropy_benchmarking.py index 4228ea6530a..2d6855ccc90 100644 --- a/cirq-core/cirq/experiments/cross_entropy_benchmarking.py +++ b/cirq-core/cirq/experiments/cross_entropy_benchmarking.py @@ -255,9 +255,7 @@ class CrossEntropyResultDict(Mapping[Tuple['cirq.Qid', ...], CrossEntropyResult] results: Dict[Tuple['cirq.Qid', ...], CrossEntropyResult] def _json_dict_(self) -> Dict[str, Any]: - return { - 'results': list(self.results.items()), - } + return {'results': list(self.results.items())} @classmethod def _from_json_dict_( diff --git a/cirq-core/cirq/experiments/fidelity_estimation.py b/cirq-core/cirq/experiments/fidelity_estimation.py index b5f66ab2c27..1021796a886 100644 --- a/cirq-core/cirq/experiments/fidelity_estimation.py +++ b/cirq-core/cirq/experiments/fidelity_estimation.py @@ -12,15 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. """Estimation of fidelity associated with experimental circuit executions.""" -from typing import ( - Callable, - List, - Mapping, - Optional, - Sequence, - Tuple, - cast, -) +from typing import Callable, List, Mapping, Optional, Sequence, Tuple, cast import numpy as np @@ -31,8 +23,7 @@ def linear_xeb_fidelity_from_probabilities( - hilbert_space_dimension: int, - probabilities: Sequence[float], + hilbert_space_dimension: int, probabilities: Sequence[float] ) -> float: """Linear XEB fidelity estimator. @@ -73,8 +64,7 @@ def linear_xeb_fidelity_from_probabilities( def log_xeb_fidelity_from_probabilities( - hilbert_space_dimension: int, - probabilities: Sequence[float], + hilbert_space_dimension: int, probabilities: Sequence[float] ) -> float: """Logarithmic XEB fidelity estimator. @@ -107,8 +97,7 @@ def log_xeb_fidelity_from_probabilities( def hog_score_xeb_fidelity_from_probabilities( - hilbert_space_dimension: int, - probabilities: Sequence[float], + hilbert_space_dimension: int, probabilities: Sequence[float] ) -> float: """XEB fidelity estimator based on normalized HOG score. diff --git a/cirq-core/cirq/experiments/grid_parallel_two_qubit_xeb.py b/cirq-core/cirq/experiments/grid_parallel_two_qubit_xeb.py index 0b87dc1ea2d..c39f35bbef1 100644 --- a/cirq-core/cirq/experiments/grid_parallel_two_qubit_xeb.py +++ b/cirq-core/cirq/experiments/grid_parallel_two_qubit_xeb.py @@ -528,9 +528,7 @@ def _get_xeb_result( ) -def _coupled_qubit_pairs( - qubits: List['cirq.GridQubit'], -) -> List[GridQubitPair]: +def _coupled_qubit_pairs(qubits: List['cirq.GridQubit']) -> List[GridQubitPair]: """Get pairs of GridQubits that are neighbors.""" pairs = [] qubit_set = set(qubits) diff --git a/cirq-core/cirq/experiments/n_qubit_tomography.py b/cirq-core/cirq/experiments/n_qubit_tomography.py index be9b444a800..a2c558601cf 100644 --- a/cirq-core/cirq/experiments/n_qubit_tomography.py +++ b/cirq-core/cirq/experiments/n_qubit_tomography.py @@ -82,10 +82,7 @@ def __init__( self.rot_sweep = study.Product(*sweeps) self.mat = self._make_state_tomography_matrix(qubits) - def _make_state_tomography_matrix( - self, - qubits: Sequence['cirq.Qid'], - ) -> np.ndarray: + def _make_state_tomography_matrix(self, qubits: Sequence['cirq.Qid']) -> np.ndarray: """Gets the matrix used for solving the linear system of the tomography. Args: diff --git a/cirq-core/cirq/experiments/purity_estimation.py b/cirq-core/cirq/experiments/purity_estimation.py index 3b581bdf551..59cb3cc4940 100644 --- a/cirq-core/cirq/experiments/purity_estimation.py +++ b/cirq-core/cirq/experiments/purity_estimation.py @@ -18,8 +18,7 @@ def purity_from_probabilities( - hilbert_space_dimension: int, - probabilities: Sequence[float], + hilbert_space_dimension: int, probabilities: Sequence[float] ) -> float: """Purity estimator from speckle purity benchmarking. diff --git a/cirq-core/cirq/experiments/qubit_characterizations.py b/cirq-core/cirq/experiments/qubit_characterizations.py index 785a4c72167..917e4277152 100644 --- a/cirq-core/cirq/experiments/qubit_characterizations.py +++ b/cirq-core/cirq/experiments/qubit_characterizations.py @@ -790,38 +790,16 @@ def _single_qubit_cliffords() -> Cliffords: c1_in_xy.append([Y, X]) c1_in_xz.append([Z, X]) - phi_xy = [ - [-0.5, 0.5, 0.5], - [-0.5, -0.5, 0.5], - [0.5, 0.5, 0.5], - [-0.5, 0.5, -0.5], - ] + phi_xy = [[-0.5, 0.5, 0.5], [-0.5, -0.5, 0.5], [0.5, 0.5, 0.5], [-0.5, 0.5, -0.5]] for y0, x, y1 in phi_xy: c1_in_xy.append([Y**y0, X**x, Y**y1]) - phi_xz = [ - [0.5, 0.5, -0.5], - [0.5, -0.5, -0.5], - [-0.5, -0.5, -0.5], - [-0.5, 0.5, -0.5], - ] + phi_xz = [[0.5, 0.5, -0.5], [0.5, -0.5, -0.5], [-0.5, -0.5, -0.5], [-0.5, 0.5, -0.5]] for z0, x, z1 in phi_xz: 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], - ] - s1_x: List[List['cirq.Gate']] = [ - [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], - ] + s1: List[List['cirq.Gate']] = [[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]] + s1_y: List[List['cirq.Gate']] = [[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-core/cirq/experiments/random_quantum_circuit_generation.py b/cirq-core/cirq/experiments/random_quantum_circuit_generation.py index c759afa97be..17f57d101b3 100644 --- a/cirq-core/cirq/experiments/random_quantum_circuit_generation.py +++ b/cirq-core/cirq/experiments/random_quantum_circuit_generation.py @@ -618,9 +618,7 @@ def random_rotations_between_grid_interaction_layers_circuit( return circuit -def _coupled_qubit_pairs( - qubits: List['cirq.GridQubit'], -) -> List[GridQubitPairT]: +def _coupled_qubit_pairs(qubits: List['cirq.GridQubit']) -> List[GridQubitPairT]: pairs = [] qubit_set = set(qubits) for qubit in qubits: diff --git a/cirq-core/cirq/experiments/random_quantum_circuit_generation_test.py b/cirq-core/cirq/experiments/random_quantum_circuit_generation_test.py index 33527269503..a035ee7c501 100644 --- a/cirq-core/cirq/experiments/random_quantum_circuit_generation_test.py +++ b/cirq-core/cirq/experiments/random_quantum_circuit_generation_test.py @@ -74,10 +74,7 @@ def test_random_rotation_between_two_qubit_circuit(): def test_generate_library_of_2q_circuits(): circuits = generate_library_of_2q_circuits( - n_library_circuits=5, - two_qubit_gate=cirq.CNOT, - max_cycle_depth=13, - random_state=9, + n_library_circuits=5, two_qubit_gate=cirq.CNOT, max_cycle_depth=13, random_state=9 ) assert len(circuits) == 5 for circuit in circuits: @@ -121,10 +118,7 @@ def test_get_random_combinations_for_device(): graph = _gridqubits_to_graph_device(cirq.GridQubit.rect(3, 3)) n_combinations = 4 combinations = get_random_combinations_for_device( - n_library_circuits=3, - n_combinations=n_combinations, - device_graph=graph, - random_state=99, + n_library_circuits=3, n_combinations=n_combinations, device_graph=graph, random_state=99 ) assert len(combinations) == 4 # degree-four graph for i, comb in enumerate(combinations): @@ -143,10 +137,7 @@ def test_get_random_combinations_for_small_device(): graph = _gridqubits_to_graph_device(cirq.GridQubit.rect(3, 1)) n_combinations = 4 combinations = get_random_combinations_for_device( - n_library_circuits=3, - n_combinations=n_combinations, - device_graph=graph, - random_state=99, + n_library_circuits=3, n_combinations=n_combinations, device_graph=graph, random_state=99 ) assert len(combinations) == 2 # 3x1 device only fits two layers diff --git a/cirq-core/cirq/experiments/readout_confusion_matrix.py b/cirq-core/cirq/experiments/readout_confusion_matrix.py index 2a89607c9b6..c7a4526f2b7 100644 --- a/cirq-core/cirq/experiments/readout_confusion_matrix.py +++ b/cirq-core/cirq/experiments/readout_confusion_matrix.py @@ -354,8 +354,7 @@ def measure_confusion_matrix( for qs in qubits: flip_symbols = sympy.symbols(f'flip_0:{len(qs)}') flip_circuit = circuits.Circuit( - [ops.X(q) ** s for q, s in zip(qs, flip_symbols)], - ops.measure(*qs), + [ops.X(q) ** s for q, s in zip(qs, flip_symbols)], ops.measure(*qs) ) sweeps = study.Product(*[study.Points(f'flip_{i}', [0, 1]) for i in range(len(qs))]) results = sampler.run_sweep(flip_circuit, sweeps, repetitions=repetitions) diff --git a/cirq-core/cirq/experiments/single_qubit_readout_calibration_test.py b/cirq-core/cirq/experiments/single_qubit_readout_calibration_test.py index 69424b1028e..3ca5260a676 100644 --- a/cirq-core/cirq/experiments/single_qubit_readout_calibration_test.py +++ b/cirq-core/cirq/experiments/single_qubit_readout_calibration_test.py @@ -44,10 +44,7 @@ def __init__(self, p0: float, p1: float, seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE' self.simulator = cirq.Simulator(seed=self.prng, split_untangled_states=False) def run_sweep( - self, - program: 'cirq.AbstractCircuit', - params: cirq.Sweepable, - repetitions: int = 1, + self, program: 'cirq.AbstractCircuit', params: cirq.Sweepable, repetitions: int = 1 ) -> Sequence[cirq.Result]: results = self.simulator.run_sweep(program, params, repetitions) for result in results: @@ -140,11 +137,7 @@ def test_estimate_parallel_readout_errors_zero_reps(): qubits = cirq.LineQubit.range(10) with pytest.raises(ValueError, match='non-zero repetition'): _ = cirq.estimate_parallel_single_qubit_readout_errors( - cirq.ZerosSampler(), - qubits=qubits, - repetitions=0, - trials=35, - trials_per_batch=10, + cirq.ZerosSampler(), qubits=qubits, repetitions=0, trials=35, trials_per_batch=10 ) @@ -152,11 +145,7 @@ def test_estimate_parallel_readout_errors_zero_trials(): qubits = cirq.LineQubit.range(10) with pytest.raises(ValueError, match='non-zero trials'): _ = cirq.estimate_parallel_single_qubit_readout_errors( - cirq.ZerosSampler(), - qubits=qubits, - repetitions=1000, - trials=0, - trials_per_batch=10, + cirq.ZerosSampler(), qubits=qubits, repetitions=1000, trials=0, trials_per_batch=10 ) @@ -164,11 +153,7 @@ def test_estimate_parallel_readout_errors_zero_batch(): qubits = cirq.LineQubit.range(10) with pytest.raises(ValueError, match='non-zero trials_per_batch'): _ = cirq.estimate_parallel_single_qubit_readout_errors( - cirq.ZerosSampler(), - qubits=qubits, - repetitions=1000, - trials=10, - trials_per_batch=0, + cirq.ZerosSampler(), qubits=qubits, repetitions=1000, trials=10, trials_per_batch=0 ) diff --git a/cirq-core/cirq/experiments/t1_decay_experiment.py b/cirq-core/cirq/experiments/t1_decay_experiment.py index dd13dbd2b9a..9406bb37947 100644 --- a/cirq-core/cirq/experiments/t1_decay_experiment.py +++ b/cirq-core/cirq/experiments/t1_decay_experiment.py @@ -73,16 +73,11 @@ def t1_decay( var = sympy.Symbol('delay_ns') sweep = study.Linspace( - var, - start=min_delay_dur.total_nanos(), - stop=max_delay_dur.total_nanos(), - length=num_points, + var, start=min_delay_dur.total_nanos(), stop=max_delay_dur.total_nanos(), length=num_points ) circuit = circuits.Circuit( - ops.X(qubit), - ops.wait(qubit, nanos=var), - ops.measure(qubit, key='output'), + ops.X(qubit), ops.wait(qubit, nanos=var), ops.measure(qubit, key='output') ) results = sampler.sample(circuit, params=sweep, repetitions=repetitions) diff --git a/cirq-core/cirq/experiments/t1_decay_experiment_test.py b/cirq-core/cirq/experiments/t1_decay_experiment_test.py index 01230735ca0..2c4bc99ba39 100644 --- a/cirq-core/cirq/experiments/t1_decay_experiment_test.py +++ b/cirq-core/cirq/experiments/t1_decay_experiment_test.py @@ -25,10 +25,7 @@ def test_init_result(): data = pd.DataFrame( columns=['delay_ns', 'false_count', 'true_count'], index=range(2), - data=[ - [100.0, 0, 10], - [1000.0, 10, 0], - ], + data=[[100.0, 0, 10], [1000.0, 10, 0]], ) result = cirq.experiments.T1DecayResult(data) assert result.data is data @@ -64,11 +61,7 @@ def test_result_eq(): eq.make_equality_group( lambda: cirq.experiments.T1DecayResult( data=pd.DataFrame( - columns=['delay_ns', 'false_count', 'true_count'], - index=[0], - data=[ - [100.0, 2, 8], - ], + columns=['delay_ns', 'false_count', 'true_count'], index=[0], data=[[100.0, 2, 8]] ) ) ) @@ -77,9 +70,7 @@ def test_result_eq(): data=pd.DataFrame( columns=['delay_ns', 'false_count', 'true_count'], index=[0], - data=[ - [100.0, 2, 50002], - ], + data=[[100.0, 2, 50002]], ) ) ) @@ -112,12 +103,7 @@ def noisy_moment(self, moment, system_qubits): data=pd.DataFrame( columns=['delay_ns', 'false_count', 'true_count'], index=range(4), - data=[ - [100.0, 0, 10], - [400.0, 0, 10], - [700.0, 10, 0], - [1000.0, 10, 0], - ], + data=[[100.0, 0, 10], [400.0, 0, 10], [700.0, 10, 0], [1000.0, 10, 0]], ) ) @@ -135,12 +121,7 @@ def test_all_on_results(): data=pd.DataFrame( columns=['delay_ns', 'false_count', 'true_count'], index=range(4), - data=[ - [100.0, 0, 10], - [400.0, 0, 10], - [700.0, 0, 10], - [1000.0, 0, 10], - ], + data=[[100.0, 0, 10], [400.0, 0, 10], [700.0, 0, 10], [1000.0, 0, 10]], ) ) @@ -158,12 +139,7 @@ def test_all_off_results(): data=pd.DataFrame( columns=['delay_ns', 'false_count', 'true_count'], index=range(4), - data=[ - [100.0, 10, 0], - [400.0, 10, 0], - [700.0, 10, 0], - [1000.0, 10, 0], - ], + data=[[100.0, 10, 0], [400.0, 10, 0], [700.0, 10, 0], [1000.0, 10, 0]], ) ) @@ -174,12 +150,7 @@ def test_curve_fit_plot_works(): data=pd.DataFrame( columns=['delay_ns', 'false_count', 'true_count'], index=range(4), - data=[ - [100.0, 6, 4], - [400.0, 10, 0], - [700.0, 10, 0], - [1000.0, 10, 0], - ], + data=[[100.0, 6, 4], [400.0, 10, 0], [700.0, 10, 0], [1000.0, 10, 0]], ) ) @@ -192,12 +163,7 @@ def test_curve_fit_plot_warning(): data=pd.DataFrame( columns=['delay_ns', 'false_count', 'true_count'], index=range(4), - data=[ - [100.0, 10, 0], - [400.0, 10, 0], - [700.0, 10, 0], - [1000.0, 10, 0], - ], + data=[[100.0, 10, 0], [400.0, 10, 0], [700.0, 10, 0], [1000.0, 10, 0]], ) ) @@ -295,10 +261,7 @@ def test_str(): data=pd.DataFrame( columns=['delay_ns', 'false_count', 'true_count'], index=range(2), - data=[ - [100.0, 0, 10], - [1000.0, 10, 0], - ], + data=[[100.0, 0, 10], [1000.0, 10, 0]], ) ) diff --git a/cirq-core/cirq/experiments/t2_decay_experiment.py b/cirq-core/cirq/experiments/t2_decay_experiment.py index 370515f1e72..746e0e47d94 100644 --- a/cirq-core/cirq/experiments/t2_decay_experiment.py +++ b/cirq-core/cirq/experiments/t2_decay_experiment.py @@ -165,10 +165,7 @@ def t2_decay( # Evolve the state for a given amount of delay time # Then measure the state in both X and Y bases. - circuit = circuits.Circuit( - ops.Y(qubit) ** 0.5, - ops.wait(qubit, nanos=delay_var), - ) + circuit = circuits.Circuit(ops.Y(qubit) ** 0.5, ops.wait(qubit, nanos=delay_var)) else: if experiment_type == ExperimentType.HAHN_ECHO: # Hahn / Spin Echo T2 experiment @@ -196,8 +193,7 @@ def t2_decay( circuit.append(ops.Y(qubit) ** inv_y_var) circuit.append(ops.measure(qubit, key='output')) tomography_sweep = study.Zip( - study.Points('inv_x', [0.0, 0.5]), - study.Points('inv_y', [-0.5, 0.0]), + study.Points('inv_x', [0.0, 0.5]), study.Points('inv_y', [-0.5, 0.0]) ) if num_pulses and max_pulses > 0: diff --git a/cirq-core/cirq/experiments/t2_decay_experiment_test.py b/cirq-core/cirq/experiments/t2_decay_experiment_test.py index ede53b4f610..cd3dff99b61 100644 --- a/cirq-core/cirq/experiments/t2_decay_experiment_test.py +++ b/cirq-core/cirq/experiments/t2_decay_experiment_test.py @@ -23,31 +23,16 @@ def test_init_t2_decay_result(): x_data = pd.DataFrame( - columns=['delay_ns', 0, 1], - index=range(2), - data=[ - [100.0, 0, 10], - [1000.0, 10, 0], - ], + columns=['delay_ns', 0, 1], index=range(2), data=[[100.0, 0, 10], [1000.0, 10, 0]] ) y_data = pd.DataFrame( - columns=['delay_ns', 0, 1], - index=range(2), - data=[ - [100.0, 5, 5], - [1000.0, 5, 5], - ], + columns=['delay_ns', 0, 1], index=range(2), data=[[100.0, 5, 5], [1000.0, 5, 5]] ) result = cirq.experiments.T2DecayResult(x_data, y_data) assert result bad_data = pd.DataFrame( - columns=['delay_ms', 0, 1], - index=range(2), - data=[ - [100.0, 0, 10], - [1000.0, 10, 0], - ], + columns=['delay_ms', 0, 1], index=range(2), data=[[100.0, 0, 10], [1000.0, 10, 0]] ) with pytest.raises(ValueError): cirq.experiments.T2DecayResult(bad_data, y_data) @@ -85,24 +70,12 @@ def test_result_eq(): example_data = pd.DataFrame( columns=['delay_ns', 0, 1], index=range(5), - data=[ - [200.0, 0, 100], - [400.0, 20, 80], - [600.0, 40, 60], - [800.0, 60, 40], - [1000.0, 80, 20], - ], + data=[[200.0, 0, 100], [400.0, 20, 80], [600.0, 40, 60], [800.0, 60, 40], [1000.0, 80, 20]], ) other_data = pd.DataFrame( columns=['delay_ns', 0, 1], index=range(5), - data=[ - [200.0, 0, 100], - [400.0, 19, 81], - [600.0, 39, 61], - [800.0, 59, 41], - [1000.0, 79, 21], - ], + data=[[200.0, 0, 100], [400.0, 19, 81], [600.0, 39, 61], [800.0, 59, 41], [1000.0, 79, 21]], ) eq = cirq.testing.EqualsTester() eq.make_equality_group(lambda: cirq.experiments.T2DecayResult(example_data, example_data)) @@ -216,22 +189,12 @@ def test_all_off_results(experiment_type): x_basis_data=pd.DataFrame( columns=['delay_ns', 0, 1], index=range(4), - data=[ - [100.0, 10, 0], - [400.0, 10, 0], - [700.0, 10, 0], - [1000.0, 10, 0], - ], + data=[[100.0, 10, 0], [400.0, 10, 0], [700.0, 10, 0], [1000.0, 10, 0]], ), y_basis_data=pd.DataFrame( columns=['delay_ns', 0, 1], index=range(4), - data=[ - [100.0, 10, 0], - [400.0, 10, 0], - [700.0, 10, 0], - [1000.0, 10, 0], - ], + data=[[100.0, 10, 0], [400.0, 10, 0], [700.0, 10, 0], [1000.0, 10, 0]], ), ) @@ -257,24 +220,12 @@ def test_custom_delay_sweep(experiment_type): x_basis_data=pd.DataFrame( columns=['delay_ns', 0, 1], index=range(5), - data=[ - [1.0, 10, 0], - [10.0, 10, 0], - [100.0, 10, 0], - [1000.0, 10, 0], - [10000.0, 10, 0], - ], + data=[[1.0, 10, 0], [10.0, 10, 0], [100.0, 10, 0], [1000.0, 10, 0], [10000.0, 10, 0]], ), y_basis_data=pd.DataFrame( columns=['delay_ns', 0, 1], index=range(5), - data=[ - [1.0, 10, 0], - [10.0, 10, 0], - [100.0, 10, 0], - [1000.0, 10, 0], - [10000.0, 10, 0], - ], + data=[[1.0, 10, 0], [10.0, 10, 0], [100.0, 10, 0], [1000.0, 10, 0], [10000.0, 10, 0]], ), ) @@ -315,14 +266,10 @@ def test_multiple_pulses(): ] assert results == cirq.experiments.T2DecayResult( x_basis_data=pd.DataFrame( - columns=['delay_ns', 'num_pulses', 0, 1], - index=range(20), - data=data, + columns=['delay_ns', 'num_pulses', 0, 1], index=range(20), data=data ), y_basis_data=pd.DataFrame( - columns=['delay_ns', 'num_pulses', 0, 1], - index=range(20), - data=data, + columns=['delay_ns', 'num_pulses', 0, 1], index=range(20), data=data ), ) expected = pd.DataFrame( @@ -462,20 +409,10 @@ def test_cpmg_sweep(): def test_str(): x_data = pd.DataFrame( - columns=['delay_ns', 0, 1], - index=range(2), - data=[ - [100.0, 0, 10], - [1000.0, 10, 0], - ], + columns=['delay_ns', 0, 1], index=range(2), data=[[100.0, 0, 10], [1000.0, 10, 0]] ) y_data = pd.DataFrame( - columns=['delay_ns', 0, 1], - index=range(2), - data=[ - [100.0, 5, 5], - [1000.0, 5, 5], - ], + columns=['delay_ns', 0, 1], index=range(2), data=[[100.0, 5, 5], [1000.0, 5, 5]] ) result = cirq.experiments.T2DecayResult(x_data, y_data) diff --git a/cirq-core/cirq/experiments/xeb_fitting.py b/cirq-core/cirq/experiments/xeb_fitting.py index 3adc79488ab..8d311b0c4ba 100644 --- a/cirq-core/cirq/experiments/xeb_fitting.py +++ b/cirq-core/cirq/experiments/xeb_fitting.py @@ -14,15 +14,7 @@ """Estimation of fidelity associated with experimental circuit executions.""" import dataclasses from abc import abstractmethod, ABC -from typing import ( - List, - Optional, - Sequence, - Tuple, - TYPE_CHECKING, - Dict, - Iterable, -) +from typing import List, Optional, Sequence, Tuple, TYPE_CHECKING, Dict, Iterable import numpy as np import pandas as pd @@ -327,8 +319,7 @@ def SqrtISwapXEBOptions(*args, **kwargs): def parameterize_circuit( - circuit: 'cirq.Circuit', - options: XEBCharacterizationOptions, + circuit: 'cirq.Circuit', options: XEBCharacterizationOptions ) -> 'cirq.Circuit': """Parameterize PhasedFSim-like gates in a given circuit according to `phased_fsim_options`. @@ -418,11 +409,7 @@ def _mean_infidelity(angles): optimization_result = optimize.minimize( _mean_infidelity, x0=x0, - options={ - 'initial_simplex': initial_simplex, - 'xatol': xatol, - 'fatol': fatol, - }, + options={'initial_simplex': initial_simplex, 'xatol': xatol, 'fatol': fatol}, method='nelder-mead', ) diff --git a/cirq-core/cirq/experiments/xeb_fitting_test.py b/cirq-core/cirq/experiments/xeb_fitting_test.py index ceabbd48f45..e65dfc38cb7 100644 --- a/cirq-core/cirq/experiments/xeb_fitting_test.py +++ b/cirq-core/cirq/experiments/xeb_fitting_test.py @@ -108,10 +108,7 @@ def test_benchmark_2q_xeb_fidelities_parallel(): cycle_depths = [2, 3, 4] graph = _gridqubits_to_graph_device(cirq.GridQubit.rect(2, 2)) combs = rqcg.get_random_combinations_for_device( - n_library_circuits=len(circuits), - n_combinations=2, - device_graph=graph, - random_state=10, + n_library_circuits=len(circuits), n_combinations=2, device_graph=graph, random_state=10 ) sampled_df = sample_2q_xeb_circuits( @@ -211,11 +208,7 @@ def test_characterize_phased_fsim_parameters_with_xeb(): rs = np.random.RandomState(52) circuits = [ rqcg.random_rotations_between_two_qubit_circuit( - q0, - q1, - depth=20, - two_qubit_op_factory=lambda a, b, _: cirq.SQRT_ISWAP(a, b), - seed=rs, + q0, q1, depth=20, two_qubit_op_factory=lambda a, b, _: cirq.SQRT_ISWAP(a, b), seed=rs ) for _ in range(2) ] @@ -265,10 +258,7 @@ def test_parallel_full_workflow(use_pool): cycle_depths = [2, 3, 4] graph = _gridqubits_to_graph_device(cirq.GridQubit.rect(2, 2)) combs = rqcg.get_random_combinations_for_device( - n_library_circuits=len(circuits), - n_combinations=2, - device_graph=graph, - random_state=10, + n_library_circuits=len(circuits), n_combinations=2, device_graph=graph, random_state=10 ) sampled_df = sample_2q_xeb_circuits( @@ -284,10 +274,7 @@ def test_parallel_full_workflow(use_pool): pool = None fids_df_0 = benchmark_2q_xeb_fidelities( - sampled_df=sampled_df, - circuits=circuits, - cycle_depths=cycle_depths, - pool=pool, + sampled_df=sampled_df, circuits=circuits, cycle_depths=cycle_depths, pool=pool ) options = SqrtISwapXEBOptions( diff --git a/cirq-core/cirq/experiments/xeb_sampling.py b/cirq-core/cirq/experiments/xeb_sampling.py index 3d4349cc73a..97bc0a3b0d1 100644 --- a/cirq-core/cirq/experiments/xeb_sampling.py +++ b/cirq-core/cirq/experiments/xeb_sampling.py @@ -135,9 +135,7 @@ class _NoProgress: def __init__(self, total: int): pass - def __enter__( - self, - ): + def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): @@ -193,9 +191,7 @@ def _get_combinations_by_layer_for_isolated_xeb( ] return [ CircuitLibraryCombination( - layer=None, - combinations=np.arange(len(circuits))[:, np.newaxis], - pairs=[(q0, q1)], + layer=None, combinations=np.arange(len(circuits))[:, np.newaxis], pairs=[(q0, q1)] ) ], circuits diff --git a/cirq-core/cirq/experiments/xeb_sampling_test.py b/cirq-core/cirq/experiments/xeb_sampling_test.py index 1aa731cd43a..939c8868ed4 100644 --- a/cirq-core/cirq/experiments/xeb_sampling_test.py +++ b/cirq-core/cirq/experiments/xeb_sampling_test.py @@ -30,10 +30,7 @@ def test_sample_2q_xeb_circuits(): q1 = cirq.NamedQubit('b') circuits = [ rqcg.random_rotations_between_two_qubit_circuit( - q0, - q1, - depth=20, - two_qubit_op_factory=lambda a, b, _: cirq.SQRT_ISWAP(a, b), + q0, q1, depth=20, two_qubit_op_factory=lambda a, b, _: cirq.SQRT_ISWAP(a, b) ) for _ in range(2) ] @@ -59,9 +56,7 @@ def test_sample_2q_xeb_circuits_error(): cycle_depths = np.arange(3, 50, 9) with pytest.raises(ValueError): # three qubit circuits _ = sample_2q_xeb_circuits( - sampler=cirq.Simulator(), - circuits=circuits, - cycle_depths=cycle_depths, + sampler=cirq.Simulator(), circuits=circuits, cycle_depths=cycle_depths ) @@ -70,10 +65,7 @@ def test_sample_2q_xeb_circuits_no_progress(capsys): circuits = [cirq.testing.random_circuit(qubits, n_moments=7, op_density=0.8, random_state=52)] cycle_depths = np.arange(3, 4) _ = sample_2q_xeb_circuits( - sampler=cirq.Simulator(), - circuits=circuits, - cycle_depths=cycle_depths, - progress_bar=None, + sampler=cirq.Simulator(), circuits=circuits, cycle_depths=cycle_depths, progress_bar=None ) captured = capsys.readouterr() assert captured.out == '' @@ -110,10 +102,7 @@ def test_sample_2q_parallel_xeb_circuits(tmpdir): cycle_depths = [5, 10] graph = _gridqubits_to_graph_device(cirq.GridQubit.rect(3, 2)) combs = rqcg.get_random_combinations_for_device( - n_library_circuits=len(circuits), - n_combinations=5, - device_graph=graph, - random_state=10, + n_library_circuits=len(circuits), n_combinations=5, device_graph=graph, random_state=10 ) df = sample_2q_xeb_circuits( @@ -180,10 +169,7 @@ def test_sample_2q_parallel_xeb_circuits_error_bad_qubits(): cycle_depths = [10] graph = _gridqubits_to_graph_device(cirq.GridQubit.rect(3, 2)) combs = rqcg.get_random_combinations_for_device( - n_library_circuits=len(circuits), - n_combinations=5, - device_graph=graph, - random_state=10, + n_library_circuits=len(circuits), n_combinations=5, device_graph=graph, random_state=10 ) with pytest.raises(ValueError, match=r'.*each operating on LineQubit\(0\) and LineQubit\(1\)'): diff --git a/cirq-core/cirq/experiments/xeb_simulation.py b/cirq-core/cirq/experiments/xeb_simulation.py index f40a38e5d68..72bbf252217 100644 --- a/cirq-core/cirq/experiments/xeb_simulation.py +++ b/cirq-core/cirq/experiments/xeb_simulation.py @@ -13,14 +13,7 @@ # limitations under the License. """Estimation of fidelity associated with experimental circuit executions.""" from dataclasses import dataclass -from typing import ( - List, - Optional, - Sequence, - TYPE_CHECKING, - Dict, - Any, -) +from typing import List, Optional, Sequence, TYPE_CHECKING, Dict, Any import numpy as np import pandas as pd @@ -76,11 +69,7 @@ def __call__(self, task: _Simulate2qXEBTask) -> List[Dict[str, Any]]: pure_probs = value.state_vector_to_probabilities(psi) records += [ - { - 'circuit_i': circuit_i, - 'cycle_depth': cycle_depth, - 'pure_probs': pure_probs, - } + {'circuit_i': circuit_i, 'cycle_depth': cycle_depth, 'pure_probs': pure_probs} ] return records diff --git a/cirq-core/cirq/experiments/xeb_simulation_test.py b/cirq-core/cirq/experiments/xeb_simulation_test.py index 092e7a8891f..8615dd41904 100644 --- a/cirq-core/cirq/experiments/xeb_simulation_test.py +++ b/cirq-core/cirq/experiments/xeb_simulation_test.py @@ -29,19 +29,13 @@ def test_simulate_2q_xeb_circuits(): q0, q1 = cirq.LineQubit.range(2) circuits = [ rqcg.random_rotations_between_two_qubit_circuit( - q0, - q1, - depth=50, - two_qubit_op_factory=lambda a, b, _: cirq.SQRT_ISWAP(a, b), + q0, q1, depth=50, two_qubit_op_factory=lambda a, b, _: cirq.SQRT_ISWAP(a, b) ) for _ in range(2) ] cycle_depths = np.arange(3, 50, 9) - df = simulate_2q_xeb_circuits( - circuits=circuits, - cycle_depths=cycle_depths, - ) + df = simulate_2q_xeb_circuits(circuits=circuits, cycle_depths=cycle_depths) assert len(df) == len(cycle_depths) * len(circuits) for (circuit_i, cycle_depth), row in df.iterrows(): assert 0 <= circuit_i < len(circuits) @@ -68,10 +62,7 @@ def test_simulate_circuit_length_validation(): ] cycle_depths = np.arange(3, 50, 9) with pytest.raises(ValueError, match='.*not long enough.*'): - _ = simulate_2q_xeb_circuits( - circuits=circuits, - cycle_depths=cycle_depths, - ) + _ = simulate_2q_xeb_circuits(circuits=circuits, cycle_depths=cycle_depths) def _ref_simulate_2q_xeb_circuit(task: Dict[str, Any]): @@ -91,11 +82,7 @@ def _ref_simulate_2q_xeb_circuit(task: Dict[str, Any]): psi = psi.final_state_vector pure_probs = cirq.state_vector_to_probabilities(psi) - return { - 'circuit_i': circuit_i, - 'cycle_depth': cycle_depth, - 'pure_probs': pure_probs, - } + return {'circuit_i': circuit_i, 'cycle_depth': cycle_depth, 'pure_probs': pure_probs} def _ref_simulate_2q_xeb_circuits( @@ -137,10 +124,7 @@ def test_incremental_simulate(multiprocess): q0, q1 = cirq.LineQubit.range(2) circuits = [ rqcg.random_rotations_between_two_qubit_circuit( - q0, - q1, - depth=100, - two_qubit_op_factory=lambda a, b, _: cirq.SQRT_ISWAP(a, b), + q0, q1, depth=100, two_qubit_op_factory=lambda a, b, _: cirq.SQRT_ISWAP(a, b) ) for _ in range(20) ] @@ -152,11 +136,7 @@ def test_incremental_simulate(multiprocess): pool = None start = time.perf_counter() - df_ref = _ref_simulate_2q_xeb_circuits( - circuits=circuits, - cycle_depths=cycle_depths, - pool=pool, - ) + df_ref = _ref_simulate_2q_xeb_circuits(circuits=circuits, cycle_depths=cycle_depths, pool=pool) end1 = time.perf_counter() df = simulate_2q_xeb_circuits(circuits=circuits, cycle_depths=cycle_depths, pool=pool) diff --git a/cirq-core/cirq/interop/__init__.py b/cirq-core/cirq/interop/__init__.py index 6048fa5f86c..44978128a99 100644 --- a/cirq-core/cirq/interop/__init__.py +++ b/cirq-core/cirq/interop/__init__.py @@ -13,7 +13,4 @@ # limitations under the License. """Methods for interoperating with other quantum software.""" -from cirq.interop.quirk import ( - quirk_json_to_circuit, - quirk_url_to_circuit, -) +from cirq.interop.quirk import quirk_json_to_circuit, quirk_url_to_circuit diff --git a/cirq-core/cirq/interop/quirk/__init__.py b/cirq-core/cirq/interop/quirk/__init__.py index 6b8fab56626..b2b97b58775 100644 --- a/cirq-core/cirq/interop/quirk/__init__.py +++ b/cirq-core/cirq/interop/quirk/__init__.py @@ -25,7 +25,4 @@ QuirkQubitPermutationGate, ) -from cirq.interop.quirk.url_to_circuit import ( - quirk_json_to_circuit, - quirk_url_to_circuit, -) +from cirq.interop.quirk.url_to_circuit import quirk_json_to_circuit, quirk_url_to_circuit diff --git a/cirq-core/cirq/interop/quirk/cells/__init__.py b/cirq-core/cirq/interop/quirk/cells/__init__.py index bd10f94f820..5f7cf8ccbb9 100644 --- a/cirq-core/cirq/interop/quirk/cells/__init__.py +++ b/cirq-core/cirq/interop/quirk/cells/__init__.py @@ -13,32 +13,17 @@ # limitations under the License. """This module defines building blocks for parsing Quirk circuits.""" -from cirq.interop.quirk.cells.all_cells import ( - generate_all_quirk_cell_makers, -) +from cirq.interop.quirk.cells.all_cells import generate_all_quirk_cell_makers -from cirq.interop.quirk.cells.cell import ( - Cell, - CellMaker, - CellMakerArgs, - ExplicitOperationsCell, -) +from cirq.interop.quirk.cells.cell import Cell, CellMaker, CellMakerArgs, ExplicitOperationsCell -from cirq.interop.quirk.cells.composite_cell import ( - CompositeCell, -) +from cirq.interop.quirk.cells.composite_cell import CompositeCell -from cirq.interop.quirk.cells.qubit_permutation_cells import ( - QuirkQubitPermutationGate, -) +from cirq.interop.quirk.cells.qubit_permutation_cells import QuirkQubitPermutationGate -from cirq.interop.quirk.cells.arithmetic_cells import ( - QuirkArithmeticOperation, -) +from cirq.interop.quirk.cells.arithmetic_cells import QuirkArithmeticOperation -from cirq.interop.quirk.cells.input_rotation_cells import ( - QuirkInputRotationOperation, -) +from cirq.interop.quirk.cells.input_rotation_cells import QuirkInputRotationOperation import cirq.interop.quirk.cells.swap_cell import cirq.interop.quirk.cells.control_cells diff --git a/cirq-core/cirq/interop/quirk/cells/arithmetic_cells.py b/cirq-core/cirq/interop/quirk/cells/arithmetic_cells.py index fd421fb20f2..8f89d6c99b8 100644 --- a/cirq-core/cirq/interop/quirk/cells/arithmetic_cells.py +++ b/cirq-core/cirq/interop/quirk/cells/arithmetic_cells.py @@ -348,8 +348,7 @@ def _arithmetic_family(identifier_prefix: str, func: _IntsToIntCallable) -> Iter def _size_dependent_arithmetic_family( - identifier_prefix: str, - size_to_func: Callable[[int], _IntsToIntCallable], + identifier_prefix: str, size_to_func: Callable[[int], _IntsToIntCallable] ) -> Iterator[CellMaker]: for i in CELL_SIZES: yield _arithmetic_gate(identifier_prefix + str(i), size=i, func=size_to_func(i)) diff --git a/cirq-core/cirq/interop/quirk/cells/arithmetic_cells_test.py b/cirq-core/cirq/interop/quirk/cells/arithmetic_cells_test.py index 12dd482bd20..ff93fef0f3b 100644 --- a/cirq-core/cirq/interop/quirk/cells/arithmetic_cells_test.py +++ b/cirq-core/cirq/interop/quirk/cells/arithmetic_cells_test.py @@ -49,47 +49,27 @@ def test_arithmetic_comparison_gates(): assert_url_to_circuit_returns( '{"cols":[["^A>B","inputA2",1,"inputB2"]]}', - maps={ - 0b_0_11_10: 0b_1_11_10, - 0b_0_10_10: 0b_0_10_10, - 0b_0_01_10: 0b_0_01_10, - }, + maps={0b_0_11_10: 0b_1_11_10, 0b_0_10_10: 0b_0_10_10, 0b_0_01_10: 0b_0_01_10}, ) assert_url_to_circuit_returns( '{"cols":[["^A>=B","inputA2",1,"inputB2"]]}', - maps={ - 0b_0_11_10: 0b_1_11_10, - 0b_0_10_10: 0b_1_10_10, - 0b_0_01_10: 0b_0_01_10, - }, + maps={0b_0_11_10: 0b_1_11_10, 0b_0_10_10: 0b_1_10_10, 0b_0_01_10: 0b_0_01_10}, ) assert_url_to_circuit_returns( '{"cols":[["^A<=B","inputA2",1,"inputB2"]]}', - maps={ - 0b_0_11_10: 0b_0_11_10, - 0b_0_10_10: 0b_1_10_10, - 0b_0_01_10: 0b_1_01_10, - }, + maps={0b_0_11_10: 0b_0_11_10, 0b_0_10_10: 0b_1_10_10, 0b_0_01_10: 0b_1_01_10}, ) assert_url_to_circuit_returns( '{"cols":[["^A=B","inputA2",1,"inputB2"]]}', - maps={ - 0b_0_11_10: 0b_0_11_10, - 0b_0_10_10: 0b_1_10_10, - 0b_0_01_10: 0b_0_01_10, - }, + maps={0b_0_11_10: 0b_0_11_10, 0b_0_10_10: 0b_1_10_10, 0b_0_01_10: 0b_0_01_10}, ) assert_url_to_circuit_returns( '{"cols":[["^A!=B","inputA2",1,"inputB2"]]}', - maps={ - 0b_0_11_10: 0b_1_11_10, - 0b_0_10_10: 0b_0_10_10, - 0b_0_01_10: 0b_1_01_10, - }, + maps={0b_0_11_10: 0b_1_11_10, 0b_0_10_10: 0b_0_10_10, 0b_0_01_10: 0b_1_01_10}, ) @@ -116,36 +96,20 @@ def test_arithmetic_unlisted_misc_gates(): ) assert_url_to_circuit_returns( - '{"cols":[[{"id":"setA","arg":5}],["^=A4"]]}', - maps={ - 0b_0000: 0b_0101, - 0b_1111: 0b_1010, - }, + '{"cols":[[{"id":"setA","arg":5}],["^=A4"]]}', maps={0b_0000: 0b_0101, 0b_1111: 0b_1010} ) assert_url_to_circuit_returns( '{"cols":[[{"id":"setA","arg":11}],["+cntA4"]]}', - maps={ - 0b_0000: 0b_0011, - 0b_0001: 0b_0100, - 0b_1111: 0b_0010, - }, + maps={0b_0000: 0b_0011, 0b_0001: 0b_0100, 0b_1111: 0b_0010}, ) assert_url_to_circuit_returns( '{"cols":[[{"id":"setA","arg":5}],["+cntA4"]]}', - maps={ - 0b_0000: 0b_0010, - 0b_0001: 0b_0011, - 0b_1111: 0b_0001, - }, + maps={0b_0000: 0b_0010, 0b_0001: 0b_0011, 0b_1111: 0b_0001}, ) assert_url_to_circuit_returns( '{"cols":[[{"id":"setA","arg":7}],["-cntA4"]]}', - maps={ - 0b_0000: 0b_1101, - 0b_0001: 0b_1110, - 0b_1111: 0b_1100, - }, + maps={0b_0000: 0b_1101, 0b_0001: 0b_1110, 0b_1111: 0b_1100}, ) assert_url_to_circuit_returns( @@ -187,73 +151,38 @@ def test_arithmetic_addition_gates(): │ 2: ───#3──────────── """, - maps={ - 0: 1, - 3: 4, - 7: 0, - }, - ) - assert_url_to_circuit_returns( - '{"cols":[["dec3"]]}', - maps={ - 0: 7, - 3: 2, - 7: 6, - }, + maps={0: 1, 3: 4, 7: 0}, ) + assert_url_to_circuit_returns('{"cols":[["dec3"]]}', maps={0: 7, 3: 2, 7: 6}) assert_url_to_circuit_returns( '{"cols":[["+=A2",1,"inputA2"]]}', - maps={ - 0b_00_00: 0b_00_00, - 0b_01_10: 0b_11_10, - 0b_10_11: 0b_01_11, - }, + maps={0b_00_00: 0b_00_00, 0b_01_10: 0b_11_10, 0b_10_11: 0b_01_11}, ) assert_url_to_circuit_returns( '{"cols":[["-=A2",1,"inputA2"]]}', - maps={ - 0b_00_00: 0b_00_00, - 0b_01_10: 0b_11_10, - 0b_10_11: 0b_11_11, - }, + maps={0b_00_00: 0b_00_00, 0b_01_10: 0b_11_10, 0b_10_11: 0b_11_11}, ) def test_arithmetic_multiply_accumulate_gates(): assert_url_to_circuit_returns( '{"cols":[["+=AA4",1,1,1,"inputA2"]]}', - maps={ - 0b_0000_00: 0b_0000_00, - 0b_0100_10: 0b_1000_10, - 0b_1000_11: 0b_0001_11, - }, + maps={0b_0000_00: 0b_0000_00, 0b_0100_10: 0b_1000_10, 0b_1000_11: 0b_0001_11}, ) assert_url_to_circuit_returns( '{"cols":[["-=AA4",1,1,1,"inputA2"]]}', - maps={ - 0b_0000_00: 0b_0000_00, - 0b_0100_10: 0b_0000_10, - 0b_1000_11: 0b_1111_11, - }, + maps={0b_0000_00: 0b_0000_00, 0b_0100_10: 0b_0000_10, 0b_1000_11: 0b_1111_11}, ) assert_url_to_circuit_returns( '{"cols":[["+=AB3",1,1,"inputA2",1,"inputB2"]]}', - maps={ - 0b_000_00_00: 0b_000_00_00, - 0b_000_11_10: 0b_110_11_10, - 0b_100_11_11: 0b_101_11_11, - }, + maps={0b_000_00_00: 0b_000_00_00, 0b_000_11_10: 0b_110_11_10, 0b_100_11_11: 0b_101_11_11}, ) assert_url_to_circuit_returns( '{"cols":[["-=AB3",1,1,"inputA2",1,"inputB2"]]}', - maps={ - 0b_000_00_00: 0b_000_00_00, - 0b_000_11_10: 0b_010_11_10, - 0b_100_11_11: 0b_011_11_11, - }, + maps={0b_000_00_00: 0b_000_00_00, 0b_000_11_10: 0b_010_11_10, 0b_100_11_11: 0b_011_11_11}, ) @@ -291,65 +220,25 @@ def test_arithmetic_modular_addition_gates(): │ 3: ───#4───────────────────── """, - maps={ - 0: 1, - 1: 2, - 2: 3, - 3: 4, - 4: 5, - 5: 6, - 15: 0, - }, + maps={0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 15: 0}, ) assert_url_to_circuit_returns( '{"cols":[[{"id":"setR","arg":5}],["incmodR4"]]}', - maps={ - 0: 1, - 1: 2, - 2: 3, - 3: 4, - 4: 0, - 5: 5, - 15: 15, - }, + maps={0: 1, 1: 2, 2: 3, 3: 4, 4: 0, 5: 5, 15: 15}, ) assert_url_to_circuit_returns( '{"cols":[[{"id":"setR","arg":5}],["decmodR4"]]}', - maps={ - 0: 4, - 1: 0, - 2: 1, - 3: 2, - 4: 3, - 5: 5, - 15: 15, - }, + maps={0: 4, 1: 0, 2: 1, 3: 2, 4: 3, 5: 5, 15: 15}, ) assert_url_to_circuit_returns( '{"cols":[[{"id":"setR","arg":5},{"id":"setA","arg":3}],["+AmodR4"]]}', - maps={ - 0: 3, - 1: 4, - 2: 0, - 3: 1, - 4: 2, - 5: 5, - 15: 15, - }, + maps={0: 3, 1: 4, 2: 0, 3: 1, 4: 2, 5: 5, 15: 15}, ) assert_url_to_circuit_returns( '{"cols":[[{"id":"setR","arg":5},{"id":"setA","arg":3}],["-AmodR4"]]}', - maps={ - 0: 2, - 1: 3, - 2: 4, - 3: 0, - 4: 1, - 5: 5, - 15: 15, - }, + maps={0: 2, 1: 3, 2: 4, 3: 0, 4: 1, 5: 5, 15: 15}, ) @@ -357,121 +246,51 @@ def test_arithmetic_modular_multiply_accumulate_gates(): assert_url_to_circuit_returns( '{"cols":[[{"id":"setR","arg":5},{"id":"setA","arg":3},' '{"id":"setB","arg":4}],["+ABmodR4"]]}', - maps={ - 0: 2, - 1: 3, - 2: 4, - 3: 0, - 4: 1, - 5: 5, - 15: 15, - }, + maps={0: 2, 1: 3, 2: 4, 3: 0, 4: 1, 5: 5, 15: 15}, ) assert_url_to_circuit_returns( '{"cols":[[{"id":"setR","arg":27},{"id":"setA","arg":3},' '{"id":"setB","arg":5}],["-ABmodR6"]]}', - maps={ - 0: 27 - 15, - 1: 27 - 14, - 15: 0, - 16: 1, - 26: 26 - 15, - 27: 27, - 63: 63, - }, + maps={0: 27 - 15, 1: 27 - 14, 15: 0, 16: 1, 26: 26 - 15, 27: 27, 63: 63}, ) def test_arithmetic_multiply_gates(): assert_url_to_circuit_returns( - '{"cols":[[{"id":"setA","arg":3}],["*A4"]]}', - maps={ - 0: 0, - 1: 3, - 3: 9, - 9: 11, - 11: 1, - }, + '{"cols":[[{"id":"setA","arg":3}],["*A4"]]}', maps={0: 0, 1: 3, 3: 9, 9: 11, 11: 1} ) assert_url_to_circuit_returns( - '{"cols":[[{"id":"setA","arg":3}],["/A4"]]}', - maps={ - 0: 0, - 1: 11, - 3: 1, - 9: 3, - 11: 9, - }, + '{"cols":[[{"id":"setA","arg":3}],["/A4"]]}', maps={0: 0, 1: 11, 3: 1, 9: 3, 11: 9} ) # Irreversible multipliers have no effect. assert_url_to_circuit_returns( - '{"cols":[[{"id":"setA","arg":4}],["*A4"]]}', - maps={ - 0: 0, - 1: 1, - 3: 3, - }, + '{"cols":[[{"id":"setA","arg":4}],["*A4"]]}', maps={0: 0, 1: 1, 3: 3} ) assert_url_to_circuit_returns( - '{"cols":[[{"id":"setA","arg":4}],["/A4"]]}', - maps={ - 0: 0, - 1: 1, - 3: 3, - }, + '{"cols":[[{"id":"setA","arg":4}],["/A4"]]}', maps={0: 0, 1: 1, 3: 3} ) def test_arithmetic_modular_multiply_gates(): assert_url_to_circuit_returns( '{"cols":[[{"id":"setA","arg":3},{"id":"setR","arg":7}],["*AmodR4"]]}', - maps={ - 0: 0, - 1: 3, - 3: 2, - 2: 6, - 6: 4, - 4: 5, - 5: 1, - 7: 7, - 15: 15, - }, + maps={0: 0, 1: 3, 3: 2, 2: 6, 6: 4, 4: 5, 5: 1, 7: 7, 15: 15}, ) assert_url_to_circuit_returns( '{"cols":[[{"id":"setA","arg":3},{"id":"setR","arg":7}],["/AmodR4"]]}', - maps={ - 0: 0, - 1: 5, - 2: 3, - 3: 1, - 4: 6, - 5: 4, - 6: 2, - 7: 7, - 15: 15, - }, + maps={0: 0, 1: 5, 2: 3, 3: 1, 4: 6, 5: 4, 6: 2, 7: 7, 15: 15}, ) # Irreversible multipliers have no effect. assert_url_to_circuit_returns( '{"cols":[[{"id":"setA","arg":5},{"id":"setR","arg":15}],["*AmodR4"]]}', - maps={ - 0: 0, - 1: 1, - 3: 3, - 15: 15, - }, + maps={0: 0, 1: 1, 3: 3, 15: 15}, ) assert_url_to_circuit_returns( '{"cols":[[{"id":"setA","arg":5},{"id":"setR","arg":15}],["/AmodR4"]]}', - maps={ - 0: 0, - 1: 1, - 3: 3, - 15: 15, - }, + maps={0: 0, 1: 1, 3: 3, 15: 15}, ) @@ -479,43 +298,23 @@ def test_arithmetic_modular_exponentiation_gates(): assert_url_to_circuit_returns( '{"cols":[[{"id":"setA","arg":5},{"id":"setB","arg":3},' '{"id":"setR","arg":7}],["*BToAmodR4"]]}', - maps={ - 0: 0, - 1: 5, - 2: 3, - 15: 15, - }, + maps={0: 0, 1: 5, 2: 3, 15: 15}, ) assert_url_to_circuit_returns( '{"cols":[[{"id":"setA","arg":6},{"id":"setB","arg":3},' '{"id":"setR","arg":7}],["*BToAmodR4"]]}', - maps={ - 0: 0, - 1: 1, - 2: 2, - 15: 15, - }, + maps={0: 0, 1: 1, 2: 2, 15: 15}, ) assert_url_to_circuit_returns( '{"cols":[[{"id":"setA","arg":5},{"id":"setB","arg":3},' '{"id":"setR","arg":7}],["/BToAmodR4"]]}', - maps={ - 0: 0, - 1: 3, - 2: 6, - 15: 15, - }, + maps={0: 0, 1: 3, 2: 6, 15: 15}, ) assert_url_to_circuit_returns( '{"cols":[[{"id":"setA","arg":6},{"id":"setB","arg":3},' '{"id":"setR","arg":7}],["/BToAmodR4"]]}', - maps={ - 0: 0, - 1: 1, - 2: 2, - 15: 15, - }, + maps={0: 0, 1: 1, 2: 2, 15: 15}, ) diff --git a/cirq-core/cirq/interop/quirk/cells/cell.py b/cirq-core/cirq/interop/quirk/cells/cell.py index 64b8d93b317..734b4cf074a 100644 --- a/cirq-core/cirq/interop/quirk/cells/cell.py +++ b/cirq-core/cirq/interop/quirk/cells/cell.py @@ -215,13 +215,7 @@ def controlled_by(self, qubit: 'cirq.Qid') -> 'ExplicitOperationsCell': CELL_SIZES = range(1, 17) CellMakerArgs = NamedTuple( - 'CellMakerArgs', - [ - ('qubits', Sequence['cirq.Qid']), - ('value', Any), - ('row', int), - ('col', int), - ], + 'CellMakerArgs', [('qubits', Sequence['cirq.Qid']), ('value', Any), ('row', int), ('col', int)] ) CellMaker = NamedTuple( diff --git a/cirq-core/cirq/interop/quirk/cells/composite_cell_test.py b/cirq-core/cirq/interop/quirk/cells/composite_cell_test.py index 58b249d1630..db13e29e8b1 100644 --- a/cirq-core/cirq/interop/quirk/cells/composite_cell_test.py +++ b/cirq-core/cirq/interop/quirk/cells/composite_cell_test.py @@ -78,11 +78,7 @@ def test_custom_circuit_gate(): assert_url_to_circuit_returns( '{"cols":[["~d3pq"],["Y"]],' '"gates":[{"id":"~d3pq","circuit":{"cols":[["H"],["•","X"]]}}]}', - cirq.Circuit( - cirq.H(a), - cirq.X(b).controlled_by(a), - cirq.Y(a), - ), + cirq.Circuit(cirq.H(a), cirq.X(b).controlled_by(a), cirq.Y(a)), ) # With name. @@ -90,11 +86,7 @@ def test_custom_circuit_gate(): '{"cols":[["~d3pq"],["Y"]],' '"gates":[{"id":"~d3pq","name":"test",' '"circuit":{"cols":[["H"],["•","X"]]}}]}', - cirq.Circuit( - cirq.H(a), - cirq.X(b).controlled_by(a), - cirq.Y(a), - ), + cirq.Circuit(cirq.H(a), cirq.X(b).controlled_by(a), cirq.Y(a)), ) # With internal input. diff --git a/cirq-core/cirq/interop/quirk/cells/control_cells_test.py b/cirq-core/cirq/interop/quirk/cells/control_cells_test.py index 4a1ba069706..df29041ed60 100644 --- a/cirq-core/cirq/interop/quirk/cells/control_cells_test.py +++ b/cirq-core/cirq/interop/quirk/cells/control_cells_test.py @@ -19,28 +19,14 @@ def test_controls(): a, b = cirq.LineQubit.range(2) + assert_url_to_circuit_returns('{"cols":[["•","X"]]}', cirq.Circuit(cirq.X(b).controlled_by(a))) assert_url_to_circuit_returns( - '{"cols":[["•","X"]]}', - cirq.Circuit( - cirq.X(b).controlled_by(a), - ), - ) - assert_url_to_circuit_returns( - '{"cols":[["◦","X"]]}', - cirq.Circuit( - cirq.X(a), - cirq.X(b).controlled_by(a), - cirq.X(a), - ), + '{"cols":[["◦","X"]]}', cirq.Circuit(cirq.X(a), cirq.X(b).controlled_by(a), cirq.X(a)) ) assert_url_to_circuit_returns( '{"cols":[["⊕","X"]]}', - cirq.Circuit( - cirq.Y(a) ** 0.5, - cirq.X(b).controlled_by(a), - cirq.Y(a) ** -0.5, - ), + cirq.Circuit(cirq.Y(a) ** 0.5, cirq.X(b).controlled_by(a), cirq.Y(a) ** -0.5), output_amplitudes_from_quirk=[ {"r": 0.5, "i": 0}, {"r": -0.5, "i": 0}, @@ -50,11 +36,7 @@ def test_controls(): ) assert_url_to_circuit_returns( '{"cols":[["⊖","X"]]}', - cirq.Circuit( - cirq.Y(a) ** -0.5, - cirq.X(b).controlled_by(a), - cirq.Y(a) ** +0.5, - ), + cirq.Circuit(cirq.Y(a) ** -0.5, cirq.X(b).controlled_by(a), cirq.Y(a) ** +0.5), output_amplitudes_from_quirk=[ {"r": 0.5, "i": 0}, {"r": 0.5, "i": 0}, @@ -65,11 +47,7 @@ def test_controls(): assert_url_to_circuit_returns( '{"cols":[["⊗","X"]]}', - cirq.Circuit( - cirq.X(a) ** -0.5, - cirq.X(b).controlled_by(a), - cirq.X(a) ** +0.5, - ), + cirq.Circuit(cirq.X(a) ** -0.5, cirq.X(b).controlled_by(a), cirq.X(a) ** +0.5), output_amplitudes_from_quirk=[ {"r": 0.5, "i": 0}, {"r": 0, "i": -0.5}, @@ -79,11 +57,7 @@ def test_controls(): ) assert_url_to_circuit_returns( '{"cols":[["(/)","X"]]}', - cirq.Circuit( - cirq.X(a) ** +0.5, - cirq.X(b).controlled_by(a), - cirq.X(a) ** -0.5, - ), + cirq.Circuit(cirq.X(a) ** +0.5, cirq.X(b).controlled_by(a), cirq.X(a) ** -0.5), output_amplitudes_from_quirk=[ {"r": 0.5, "i": 0}, {"r": 0, "i": 0.5}, diff --git a/cirq-core/cirq/interop/quirk/cells/frequency_space_cells.py b/cirq-core/cirq/interop/quirk/cells/frequency_space_cells.py index ecd7c93feb3..4ddc2a589d2 100644 --- a/cirq-core/cirq/interop/quirk/cells/frequency_space_cells.py +++ b/cirq-core/cirq/interop/quirk/cells/frequency_space_cells.py @@ -16,11 +16,7 @@ import sympy import cirq -from cirq.interop.quirk.cells.cell import ( - CellMaker, - CELL_SIZES, - ExplicitOperationsCell, -) +from cirq.interop.quirk.cells.cell import CellMaker, CELL_SIZES, ExplicitOperationsCell def generate_all_frequency_space_cell_makers() -> Iterator[CellMaker]: diff --git a/cirq-core/cirq/interop/quirk/cells/frequency_space_cells_test.py b/cirq-core/cirq/interop/quirk/cells/frequency_space_cells_test.py index 6533849b7da..7599cf06275 100644 --- a/cirq-core/cirq/interop/quirk/cells/frequency_space_cells_test.py +++ b/cirq-core/cirq/interop/quirk/cells/frequency_space_cells_test.py @@ -21,48 +21,30 @@ def test_frequency_space_gates(): a, b, c = cirq.LineQubit.range(3) + assert_url_to_circuit_returns('{"cols":[["QFT3"]]}', cirq.Circuit(cirq.qft(a, b, c))) assert_url_to_circuit_returns( - '{"cols":[["QFT3"]]}', - cirq.Circuit( - cirq.qft(a, b, c), - ), - ) - assert_url_to_circuit_returns( - '{"cols":[["QFT†3"]]}', - cirq.Circuit( - cirq.inverse(cirq.qft(a, b, c)), - ), + '{"cols":[["QFT†3"]]}', cirq.Circuit(cirq.inverse(cirq.qft(a, b, c))) ) assert_url_to_circuit_returns( '{"cols":[["PhaseGradient3"]]}', - cirq.Circuit( - cirq.PhaseGradientGate(num_qubits=3, exponent=0.5)(a, b, c), - ), + cirq.Circuit(cirq.PhaseGradientGate(num_qubits=3, exponent=0.5)(a, b, c)), ) assert_url_to_circuit_returns( '{"cols":[["PhaseUngradient3"]]}', - cirq.Circuit( - cirq.PhaseGradientGate(num_qubits=3, exponent=-0.5)(a, b, c), - ), + cirq.Circuit(cirq.PhaseGradientGate(num_qubits=3, exponent=-0.5)(a, b, c)), ) t = sympy.Symbol('t') assert_url_to_circuit_returns( '{"cols":[["grad^t2"]]}', - cirq.Circuit( - cirq.PhaseGradientGate(num_qubits=2, exponent=2 * t)(a, b), - ), + cirq.Circuit(cirq.PhaseGradientGate(num_qubits=2, exponent=2 * t)(a, b)), ) assert_url_to_circuit_returns( '{"cols":[["grad^t3"]]}', - cirq.Circuit( - cirq.PhaseGradientGate(num_qubits=3, exponent=4 * t)(a, b, c), - ), + cirq.Circuit(cirq.PhaseGradientGate(num_qubits=3, exponent=4 * t)(a, b, c)), ) assert_url_to_circuit_returns( '{"cols":[["grad^-t3"]]}', - cirq.Circuit( - cirq.PhaseGradientGate(num_qubits=3, exponent=-4 * t)(a, b, c), - ), + cirq.Circuit(cirq.PhaseGradientGate(num_qubits=3, exponent=-4 * t)(a, b, c)), ) diff --git a/cirq-core/cirq/interop/quirk/cells/input_cells_test.py b/cirq-core/cirq/interop/quirk/cells/input_cells_test.py index e54703ebbdd..2453d73fd84 100644 --- a/cirq-core/cirq/interop/quirk/cells/input_cells_test.py +++ b/cirq-core/cirq/interop/quirk/cells/input_cells_test.py @@ -26,21 +26,12 @@ def test_missing_input_cell(): def test_input_cell(): assert_url_to_circuit_returns( - '{"cols":[["inputA4",1,1,1,"+=A4"]]}', - maps={ - 0x_0_0: 0x_0_0, - 0x_2_3: 0x_2_5, - }, + '{"cols":[["inputA4",1,1,1,"+=A4"]]}', maps={0x_0_0: 0x_0_0, 0x_2_3: 0x_2_5} ) assert_url_to_circuit_returns( '{"cols":[["inputA3",1,1,"inputB3",1,1,"+=AB3"]]}', - maps={ - 0o_0_0_0: 0o_0_0_0, - 0o_2_3_1: 0o_2_3_7, - 0o_1_1_0: 0o_1_1_1, - 0o_4_4_0: 0o_4_4_0, - }, + maps={0o_0_0_0: 0o_0_0_0, 0o_2_3_1: 0o_2_3_7, 0o_1_1_0: 0o_1_1_1, 0o_4_4_0: 0o_4_4_0}, ) # Overlaps with effect. @@ -53,21 +44,12 @@ def test_input_cell(): def test_reversed_input_cell(): assert_url_to_circuit_returns( '{"cols":[["revinputA4",1,1,1,"+=A4"]]}', - maps={ - 0x_0_0: 0x_0_0, - 0x_2_3: 0x_2_7, - 0x_1_3: 0x_1_B, - }, + maps={0x_0_0: 0x_0_0, 0x_2_3: 0x_2_7, 0x_1_3: 0x_1_B}, ) assert_url_to_circuit_returns( '{"cols":[["revinputA3",1,1,"revinputB3",1,1,"+=AB3"]]}', - maps={ - 0o_0_0_0: 0o_0_0_0, - 0o_2_6_1: 0o_2_6_7, - 0o_1_1_0: 0o_1_1_0, - 0o_4_4_0: 0o_4_4_1, - }, + maps={0o_0_0_0: 0o_0_0_0, 0o_2_6_1: 0o_2_6_7, 0o_1_1_0: 0o_1_1_0, 0o_4_4_0: 0o_4_4_1}, ) # Overlaps with effect. @@ -80,57 +62,33 @@ def test_reversed_input_cell(): def test_set_default_input_cell(): # Later column. assert_url_to_circuit_returns( - '{"cols":[[{"id":"setA","arg":11}],["+=A4"]]}', - maps={ - 0: 11, - 4: 15, - 5: 0, - }, + '{"cols":[[{"id":"setA","arg":11}],["+=A4"]]}', maps={0: 11, 4: 15, 5: 0} ) # Same column. assert_url_to_circuit_returns( - '{"cols":[["+=A4",{"id":"setA","arg":11}]]}', - maps={ - 0: 11, - 4: 15, - 5: 0, - }, + '{"cols":[["+=A4",{"id":"setA","arg":11}]]}', maps={0: 11, 4: 15, 5: 0} ) # Overwrite. assert_url_to_circuit_returns( '{"cols":[[{"id":"setA","arg":0}],["+=A4",{"id":"setA","arg":11}]]}', - maps={ - 0: 11, - 4: 15, - 5: 0, - }, + maps={0: 11, 4: 15, 5: 0}, ) assert_url_to_circuit_returns( '{"cols":[[{"id":"setA","arg":11}],["+=A4",{"id":"setA","arg":0}]]}', - maps={ - 0: 0, - 4: 4, - 5: 5, - }, + maps={0: 0, 4: 4, 5: 5}, ) # Different values over time. assert_url_to_circuit_returns( - '{"cols":[[{"id":"setA","arg":1}],["+=A4"],[{"id":"setA","arg":4}],["+=A4"]]}', - maps={ - 0: 5, - }, + '{"cols":[[{"id":"setA","arg":1}],["+=A4"],[{"id":"setA","arg":4}],["+=A4"]]}', maps={0: 5} ) # Broadcast. assert_url_to_circuit_returns( '{"cols":[[{"id":"setA","arg":1}],["+=A2",1,"+=A2"],["+=A2",1,"+=A2"]]}', - maps={ - 0b_00_00: 0b_10_10, - 0b_10_01: 0b_00_11, - }, + maps={0b_00_00: 0b_10_10, 0b_10_01: 0b_00_11}, ) # Too late. diff --git a/cirq-core/cirq/interop/quirk/cells/input_rotation_cells.py b/cirq-core/cirq/interop/quirk/cells/input_rotation_cells.py index 01ef39079e4..eb71ae8482a 100644 --- a/cirq-core/cirq/interop/quirk/cells/input_rotation_cells.py +++ b/cirq-core/cirq/interop/quirk/cells/input_rotation_cells.py @@ -38,12 +38,7 @@ def __init__( self.exponent_sign = exponent_sign def _value_equality_values_(self) -> Any: - return ( - self.identifier, - self.register, - self.base_operation, - self.exponent_sign, - ) + return (self.identifier, self.register, self.base_operation, self.exponent_sign) def __repr__(self) -> str: return ( @@ -115,12 +110,7 @@ def __init__( self.exponent_sign = exponent_sign def _value_equality_values_(self) -> Any: - return ( - self.identifier, - self.register, - self.base_operation, - self.exponent_sign, - ) + return (self.identifier, self.register, self.base_operation, self.exponent_sign) @property def qubits(self) -> Tuple['cirq.Qid', ...]: diff --git a/cirq-core/cirq/interop/quirk/cells/parse_test.py b/cirq-core/cirq/interop/quirk/cells/parse_test.py index 2d9ad0b8235..bbc82010905 100644 --- a/cirq-core/cirq/interop/quirk/cells/parse_test.py +++ b/cirq-core/cirq/interop/quirk/cells/parse_test.py @@ -16,11 +16,7 @@ import pytest import sympy -from cirq.interop.quirk.cells.parse import ( - parse_matrix, - parse_formula, - parse_complex, -) +from cirq.interop.quirk.cells.parse import parse_matrix, parse_formula, parse_complex def test_parse_matrix(): diff --git a/cirq-core/cirq/interop/quirk/cells/qubit_permutation_cells.py b/cirq-core/cirq/interop/quirk/cells/qubit_permutation_cells.py index a1bb08af5ed..38a6b0353e9 100644 --- a/cirq-core/cirq/interop/quirk/cells/qubit_permutation_cells.py +++ b/cirq-core/cirq/interop/quirk/cells/qubit_permutation_cells.py @@ -15,10 +15,7 @@ from typing import Callable, Iterator, Sequence, Tuple, TYPE_CHECKING from cirq import ops, value -from cirq.interop.quirk.cells.cell import ( - CELL_SIZES, - CellMaker, -) +from cirq.interop.quirk.cells.cell import CELL_SIZES, CellMaker if TYPE_CHECKING: import cirq @@ -75,11 +72,7 @@ def _permutation_family( yield _permutation(identifier_prefix + str(n), name, permutation) -def _permutation( - identifier: str, - name: str, - permutation: Tuple[int, ...], -) -> CellMaker: +def _permutation(identifier: str, name: str, permutation: Tuple[int, ...]) -> CellMaker: return CellMaker( identifier, size=len(permutation), diff --git a/cirq-core/cirq/interop/quirk/cells/qubit_permutation_cells_test.py b/cirq-core/cirq/interop/quirk/cells/qubit_permutation_cells_test.py index 10e86ecb0d9..4954946e346 100644 --- a/cirq-core/cirq/interop/quirk/cells/qubit_permutation_cells_test.py +++ b/cirq-core/cirq/interop/quirk/cells/qubit_permutation_cells_test.py @@ -13,9 +13,7 @@ # limitations under the License. import cirq -from cirq.interop.quirk.cells.qubit_permutation_cells import ( - QuirkQubitPermutationGate, -) +from cirq.interop.quirk.cells.qubit_permutation_cells import QuirkQubitPermutationGate from cirq.interop.quirk.cells.testing import assert_url_to_circuit_returns diff --git a/cirq-core/cirq/interop/quirk/cells/single_qubit_rotation_cells_test.py b/cirq-core/cirq/interop/quirk/cells/single_qubit_rotation_cells_test.py index 108aee0b4a4..e388ac996d4 100644 --- a/cirq-core/cirq/interop/quirk/cells/single_qubit_rotation_cells_test.py +++ b/cirq-core/cirq/interop/quirk/cells/single_qubit_rotation_cells_test.py @@ -82,13 +82,7 @@ def test_fixed_single_qubit_rotations(): cirq.Z(c) ** (1 / 32), cirq.Z(a) ** (1 / 64), cirq.Z(b) ** (1 / 128), - cirq.Moment( - [ - cirq.Z(a) ** (-1 / 2), - cirq.Z(b) ** (-1 / 3), - cirq.Z(c) ** (-1 / 4), - ] - ), + cirq.Moment([cirq.Z(a) ** (-1 / 2), cirq.Z(b) ** (-1 / 3), cirq.Z(c) ** (-1 / 4)]), cirq.Z(a) ** (-1 / 8), cirq.Z(b) ** (-1 / 16), ), @@ -130,43 +124,25 @@ def test_formulaic_gates(): assert_url_to_circuit_returns( '{"cols":[["X^ft",{"id":"X^ft","arg":"t*t"}]]}', - cirq.Circuit( - cirq.X(a) ** sympy.sin(sympy.pi * t), - cirq.X(b) ** (t * t), - ), + cirq.Circuit(cirq.X(a) ** sympy.sin(sympy.pi * t), cirq.X(b) ** (t * t)), ) assert_url_to_circuit_returns( '{"cols":[["Y^ft",{"id":"Y^ft","arg":"t*t"}]]}', - cirq.Circuit( - cirq.Y(a) ** sympy.sin(sympy.pi * t), - cirq.Y(b) ** (t * t), - ), + cirq.Circuit(cirq.Y(a) ** sympy.sin(sympy.pi * t), cirq.Y(b) ** (t * t)), ) assert_url_to_circuit_returns( '{"cols":[["Z^ft",{"id":"Z^ft","arg":"t*t"}]]}', - cirq.Circuit( - cirq.Z(a) ** sympy.sin(sympy.pi * t), - cirq.Z(b) ** (t * t), - ), + cirq.Circuit(cirq.Z(a) ** sympy.sin(sympy.pi * t), cirq.Z(b) ** (t * t)), ) assert_url_to_circuit_returns( '{"cols":[["Rxft",{"id":"Rxft","arg":"t*t"}]]}', - cirq.Circuit( - cirq.rx(sympy.pi * t * t).on(a), - cirq.rx(t * t).on(b), - ), + cirq.Circuit(cirq.rx(sympy.pi * t * t).on(a), cirq.rx(t * t).on(b)), ) assert_url_to_circuit_returns( '{"cols":[["Ryft",{"id":"Ryft","arg":"t*t"}]]}', - cirq.Circuit( - cirq.ry(sympy.pi * t * t).on(a), - cirq.ry(t * t).on(b), - ), + cirq.Circuit(cirq.ry(sympy.pi * t * t).on(a), cirq.ry(t * t).on(b)), ) assert_url_to_circuit_returns( '{"cols":[["Rzft",{"id":"Rzft","arg":"t*t"}]]}', - cirq.Circuit( - cirq.rz(sympy.pi * t * t).on(a), - cirq.rz(t * t).on(b), - ), + cirq.Circuit(cirq.rz(sympy.pi * t * t).on(a), cirq.rz(t * t).on(b)), ) diff --git a/cirq-core/cirq/interop/quirk/cells/testing_test.py b/cirq-core/cirq/interop/quirk/cells/testing_test.py index 840e8be2345..e5c66af5d29 100644 --- a/cirq-core/cirq/interop/quirk/cells/testing_test.py +++ b/cirq-core/cirq/interop/quirk/cells/testing_test.py @@ -83,11 +83,7 @@ def test_assert_url_to_circuit_misc(): assert_url_to_circuit_returns( '{"cols":[["X","X"],["X"]]}', - cirq.Circuit( - cirq.X(a), - cirq.X(b), - cirq.X(a), - ), + cirq.Circuit(cirq.X(a), cirq.X(b), cirq.X(a)), output_amplitudes_from_quirk=[ {"r": 0, "i": 0}, {"r": 0, "i": 0}, @@ -97,22 +93,13 @@ def test_assert_url_to_circuit_misc(): ) assert_url_to_circuit_returns( - '{"cols":[["X","X"],["X"]]}', - cirq.Circuit( - cirq.X(a), - cirq.X(b), - cirq.X(a), - ), + '{"cols":[["X","X"],["X"]]}', cirq.Circuit(cirq.X(a), cirq.X(b), cirq.X(a)) ) with pytest.raises(AssertionError, match='Not equal to tolerance'): assert_url_to_circuit_returns( '{"cols":[["X","X"],["X"]]}', - cirq.Circuit( - cirq.X(a), - cirq.X(b), - cirq.X(a), - ), + cirq.Circuit(cirq.X(a), cirq.X(b), cirq.X(a)), output_amplitudes_from_quirk=[ {"r": 0, "i": 0}, {"r": 0, "i": -1}, @@ -123,10 +110,5 @@ def test_assert_url_to_circuit_misc(): with pytest.raises(AssertionError, match='differs from expected circuit'): assert_url_to_circuit_returns( - '{"cols":[["X","X"],["X"]]}', - cirq.Circuit( - cirq.X(a), - cirq.Y(b), - cirq.X(a), - ), + '{"cols":[["X","X"],["X"]]}', cirq.Circuit(cirq.X(a), cirq.Y(b), cirq.X(a)) ) diff --git a/cirq-core/cirq/interop/quirk/cells/unsupported_cells.py b/cirq-core/cirq/interop/quirk/cells/unsupported_cells.py index 209c58a4495..873458aad0a 100644 --- a/cirq-core/cirq/interop/quirk/cells/unsupported_cells.py +++ b/cirq-core/cirq/interop/quirk/cells/unsupported_cells.py @@ -13,10 +13,7 @@ # limitations under the License. from typing import Iterator -from cirq.interop.quirk.cells.cell import ( - CellMaker, - CELL_SIZES, -) +from cirq.interop.quirk.cells.cell import CellMaker, CELL_SIZES def generate_all_unsupported_cell_makers() -> Iterator[CellMaker]: diff --git a/cirq-core/cirq/interop/quirk/url_to_circuit_test.py b/cirq-core/cirq/interop/quirk/url_to_circuit_test.py index 2205c53870f..fedc28fc6e4 100644 --- a/cirq-core/cirq/interop/quirk/url_to_circuit_test.py +++ b/cirq-core/cirq/interop/quirk/url_to_circuit_test.py @@ -232,31 +232,13 @@ def test_custom_matrix_gate(): # Without name. assert_url_to_circuit_returns( '{"cols":[["~cv0d"]],"gates":[{"id":"~cv0d","matrix":"{{0,1},{1,0}}"}]}', - cirq.Circuit( - cirq.MatrixGate( - np.array( - [ - [0, 1], - [1, 0], - ] - ) - ).on(a), - ), + cirq.Circuit(cirq.MatrixGate(np.array([[0, 1], [1, 0]])).on(a)), ) # With name. assert_url_to_circuit_returns( '{"cols":[["~cv0d"]],"gates":[{"id":"~cv0d","name":"test","matrix":"{{0,i},{1,0}}"}]}', - cirq.Circuit( - cirq.MatrixGate( - np.array( - [ - [0, 1j], - [1, 0], - ] - ) - ).on(a), - ), + cirq.Circuit(cirq.MatrixGate(np.array([[0, 1j], [1, 0]])).on(a)), ) # Multi-qubit. Reversed qubit order to account for endian-ness difference. @@ -264,10 +246,7 @@ def test_custom_matrix_gate(): '{"cols":[["X"],["~2hj0"]],' '"gates":[{"id":"~2hj0",' '"matrix":"{{-1,0,0,0},{0,i,0,0},{0,0,1,0},{0,0,0,-i}}"}]}', - cirq.Circuit( - cirq.X(a), - cirq.MatrixGate(np.diag([-1, 1j, 1, -1j])).on(b, a), - ), + cirq.Circuit(cirq.X(a), cirq.MatrixGate(np.diag([-1, 1j, 1, -1j])).on(b, a)), output_amplitudes_from_quirk=[ {"r": 0, "i": 0}, {"r": 0, "i": 1}, diff --git a/cirq-core/cirq/ion/__init__.py b/cirq-core/cirq/ion/__init__.py index 1a4115e7855..dee7b5281f0 100644 --- a/cirq-core/cirq/ion/__init__.py +++ b/cirq-core/cirq/ion/__init__.py @@ -14,30 +14,16 @@ """Trapped ion devices, gates, and compiling utilties.""" -from cirq.ion.ion_gates import ( - ms, -) +from cirq.ion.ion_gates import ms -from cirq.ion.ion_decomposition import ( - two_qubit_matrix_to_ion_operations, -) +from cirq.ion.ion_decomposition import two_qubit_matrix_to_ion_operations -from cirq.ion.ion_device import ( - IonDevice, -) +from cirq.ion.ion_device import IonDevice -from cirq.ion.convert_to_ion_gates import ( - ConvertToIonGates, -) +from cirq.ion.convert_to_ion_gates import ConvertToIonGates -from cirq.ion.ion_decomposition import ( - two_qubit_matrix_to_ion_operations, -) +from cirq.ion.ion_decomposition import two_qubit_matrix_to_ion_operations -from cirq.ion.ion_device import ( - IonDevice, -) +from cirq.ion.ion_device import IonDevice -from cirq.ion.convert_to_ion_gates import ( - ConvertToIonGates, -) +from cirq.ion.convert_to_ion_gates import ConvertToIonGates diff --git a/cirq-core/cirq/ion/ion_decomposition.py b/cirq-core/cirq/ion/ion_decomposition.py index 691780e1115..49a2fdc23b9 100644 --- a/cirq-core/cirq/ion/ion_decomposition.py +++ b/cirq-core/cirq/ion/ion_decomposition.py @@ -72,11 +72,7 @@ def _kak_decomposition_to_operations( cast( Iterable[ops.Operation], ops.flatten_op_tree( - [ - pre, - _non_local_part(q0, q1, kak.interaction_coefficients, atol), - post, - ] + [pre, _non_local_part(q0, q1, kak.interaction_coefficients, atol), post] ), ) ) diff --git a/cirq-core/cirq/ion/ion_device.py b/cirq-core/cirq/ion/ion_device.py index ea40d1193d2..1103a75b397 100644 --- a/cirq-core/cirq/ion/ion_device.py +++ b/cirq-core/cirq/ion/ion_device.py @@ -79,16 +79,12 @@ def __init__( def metadata(self) -> devices.DeviceMetadata: return self._metadata - @_compat.deprecated( - fix='Use metadata.qubit_set if applicable.', - deadline='v0.15', - ) + @_compat.deprecated(fix='Use metadata.qubit_set if applicable.', deadline='v0.15') def qubit_set(self) -> FrozenSet['cirq.LineQubit']: return self.qubits @_compat.deprecated( - deadline='v0.15', - fix='qubit coupling data can now be found in device.metadata if provided.', + deadline='v0.15', fix='qubit coupling data can now be found in device.metadata if provided.' ) def qid_pairs(self) -> FrozenSet['cirq.SymmetricalQidPair']: """Qubits have all-to-all connectivity, so returns all pairs. @@ -147,10 +143,7 @@ def at(self, position: int) -> Optional[devices.LineQubit]: def neighbors_of(self, qubit: devices.LineQubit) -> Iterable[devices.LineQubit]: """Returns the qubits that the given qubit can interact with.""" - possibles = [ - devices.LineQubit(qubit.x + 1), - devices.LineQubit(qubit.x - 1), - ] + possibles = [devices.LineQubit(qubit.x + 1), devices.LineQubit(qubit.x - 1)] return [e for e in possibles if e in self.qubits] def __repr__(self) -> str: diff --git a/cirq-core/cirq/linalg/__init__.py b/cirq-core/cirq/linalg/__init__.py index c973094da1d..62d21593551 100644 --- a/cirq-core/cirq/linalg/__init__.py +++ b/cirq-core/cirq/linalg/__init__.py @@ -17,13 +17,7 @@ Avoids duplicating functionality present in numpy. """ -from cirq.linalg.combinators import ( - block_diag, - CONTROL_TAG, - dot, - kron, - kron_with_controls, -) +from cirq.linalg.combinators import block_diag, CONTROL_TAG, dot, kron, kron_with_controls from cirq.linalg.decompositions import ( axis_angle, @@ -73,10 +67,7 @@ slice_for_qubits_equal_to, ) -from cirq.linalg.tolerance import ( - all_near_zero, - all_near_zero_mod, -) +from cirq.linalg.tolerance import all_near_zero, all_near_zero_mod from cirq.linalg.transformations import ( apply_matrix_to_slices, diff --git a/cirq-core/cirq/linalg/decompositions.py b/cirq-core/cirq/linalg/decompositions.py index 4a4c78ccdf3..ef5f0b7f646 100644 --- a/cirq-core/cirq/linalg/decompositions.py +++ b/cirq-core/cirq/linalg/decompositions.py @@ -184,9 +184,7 @@ def map_eigenvalues( return total -def kron_factor_4x4_to_2x2s( - matrix: np.ndarray, -) -> Tuple[complex, np.ndarray, np.ndarray]: +def kron_factor_4x4_to_2x2s(matrix: np.ndarray) -> Tuple[complex, np.ndarray, np.ndarray]: """Splits a 4x4 matrix U = kron(A, B) into A, B, and a global factor. Requires the matrix to be the kronecker product of two 2x2 unitaries. diff --git a/cirq-core/cirq/linalg/decompositions_test.py b/cirq-core/cirq/linalg/decompositions_test.py index 8b1f255f085..e34dc8a49a5 100644 --- a/cirq-core/cirq/linalg/decompositions_test.py +++ b/cirq-core/cirq/linalg/decompositions_test.py @@ -259,14 +259,7 @@ def test_kak_plot_empty(): @pytest.mark.parametrize( 'target', - [ - np.eye(4), - SWAP, - SWAP * 1j, - CZ, - CNOT, - SWAP @ CZ, - ] + [np.eye(4), SWAP, SWAP * 1j, CZ, CNOT, SWAP @ CZ] + [cirq.testing.random_unitary(4) for _ in range(10)], ) def test_kak_decomposition(target): diff --git a/cirq-core/cirq/linalg/diagonalize_test.py b/cirq-core/cirq/linalg/diagonalize_test.py index b1cd603505d..3b79da5f2d7 100644 --- a/cirq-core/cirq/linalg/diagonalize_test.py +++ b/cirq-core/cirq/linalg/diagonalize_test.py @@ -272,13 +272,7 @@ def test_bidiagonalize_unitary_with_special_orthogonals(mat): @pytest.mark.parametrize( 'mat', - [ - np.diag([0]), - np.diag([0.5]), - np.diag([1, 0]), - np.diag([0.5, 2]), - np.array([[0, 1], [0, 0]]), - ], + [np.diag([0]), np.diag([0.5]), np.diag([1, 0]), np.diag([0.5, 2]), np.array([[0, 1], [0, 0]])], ) def test_bidiagonalize_unitary_fails(mat): with pytest.raises(ValueError): diff --git a/cirq-core/cirq/linalg/operator_spaces.py b/cirq-core/cirq/linalg/operator_spaces.py index 4e0fcbd5327..28900fb02be 100644 --- a/cirq-core/cirq/linalg/operator_spaces.py +++ b/cirq-core/cirq/linalg/operator_spaces.py @@ -50,8 +50,7 @@ def hilbert_schmidt_inner_product(m1: np.ndarray, m2: np.ndarray) -> complex: def expand_matrix_in_orthogonal_basis( - m: np.ndarray, - basis: Dict[str, np.ndarray], + m: np.ndarray, basis: Dict[str, np.ndarray] ) -> value.LinearDict[str]: """Computes coefficients of expansion of m in basis. diff --git a/cirq-core/cirq/linalg/operator_spaces_test.py b/cirq-core/cirq/linalg/operator_spaces_test.py index 3070c8ec4df..37241a08f28 100644 --- a/cirq-core/cirq/linalg/operator_spaces_test.py +++ b/cirq-core/cirq/linalg/operator_spaces_test.py @@ -135,13 +135,7 @@ def test_kron_bases_repeat_sanity_checks(basis, repeat): @pytest.mark.parametrize( 'm1,m2,expect_real', - ( - (X, X, True), - (X, Y, True), - (X, H, True), - (X, SQRT_X, False), - (I, SQRT_Z, False), - ), + ((X, X, True), (X, Y, True), (X, H, True), (X, SQRT_X, False), (I, SQRT_Z, False)), ) def test_hilbert_schmidt_inner_product_is_conjugate_symmetric(m1, m2, expect_real): v1 = cirq.hilbert_schmidt_inner_product(m1, m2) @@ -153,15 +147,7 @@ def test_hilbert_schmidt_inner_product_is_conjugate_symmetric(m1, m2, expect_rea assert v1 != v2 -@pytest.mark.parametrize( - 'a,m1,b,m2', - ( - (1, X, 1, Z), - (2, X, 3, Y), - (2j, X, 3, I), - (2, X, 3, X), - ), -) +@pytest.mark.parametrize('a,m1,b,m2', ((1, X, 1, Z), (2, X, 3, Y), (2j, X, 3, I), (2, X, 3, X))) def test_hilbert_schmidt_inner_product_is_linear(a, m1, b, m2): v1 = cirq.hilbert_schmidt_inner_product(H, (a * m1 + b * m2)) v2 = a * cirq.hilbert_schmidt_inner_product(H, m1) + b * cirq.hilbert_schmidt_inner_product( @@ -206,10 +192,7 @@ def test_hilbert_schmidt_inner_product_values(m1, m2, expected_value): @pytest.mark.parametrize( 'm,basis', - itertools.product( - (I, X, Y, Z, H, SQRT_X, SQRT_Y, SQRT_Z), - (PAULI_BASIS, STANDARD_BASIS), - ), + itertools.product((I, X, Y, Z, H, SQRT_X, SQRT_Y, SQRT_Z), (PAULI_BASIS, STANDARD_BASIS)), ) def test_expand_matrix_in_orthogonal_basis(m, basis): expansion = cirq.expand_matrix_in_orthogonal_basis(m, basis) diff --git a/cirq-core/cirq/linalg/transformations.py b/cirq-core/cirq/linalg/transformations.py index d407ffe57e2..fc7d7885eaf 100644 --- a/cirq-core/cirq/linalg/transformations.py +++ b/cirq-core/cirq/linalg/transformations.py @@ -510,10 +510,7 @@ def to_special(u: np.ndarray) -> np.ndarray: return u * (np.linalg.det(u) ** (-1 / len(u))) -def state_vector_kronecker_product( - t1: np.ndarray, - t2: np.ndarray, -) -> np.ndarray: +def state_vector_kronecker_product(t1: np.ndarray, t2: np.ndarray) -> np.ndarray: """Merges two state vectors into a single unified state vector. The resulting vector's shape will be `t1.shape + t2.shape`. @@ -527,10 +524,7 @@ def state_vector_kronecker_product( return np.outer(t1, t2).reshape(t1.shape + t2.shape) -def density_matrix_kronecker_product( - t1: np.ndarray, - t2: np.ndarray, -) -> np.ndarray: +def density_matrix_kronecker_product(t1: np.ndarray, t2: np.ndarray) -> np.ndarray: """Merges two density matrices into a single unified density matrix. The resulting matrix's shape will be `(t1.shape/2 + t2.shape/2) * 2`. In @@ -555,11 +549,7 @@ def density_matrix_kronecker_product( def factor_state_vector( - t: np.ndarray, - axes: Sequence[int], - *, - validate=True, - atol=1e-07, + t: np.ndarray, axes: Sequence[int], *, validate=True, atol=1e-07 ) -> Tuple[np.ndarray, np.ndarray]: """Factors a state vector into two independent state vectors. @@ -605,11 +595,7 @@ def factor_state_vector( def factor_density_matrix( - t: np.ndarray, - axes: Sequence[int], - *, - validate=True, - atol=1e-07, + t: np.ndarray, axes: Sequence[int], *, validate=True, atol=1e-07 ) -> Tuple[np.ndarray, np.ndarray]: """Factors a density matrix into two independent density matrices. diff --git a/cirq-core/cirq/linalg/transformations_test.py b/cirq-core/cirq/linalg/transformations_test.py index d9f5175e18c..6e13fb64d62 100644 --- a/cirq-core/cirq/linalg/transformations_test.py +++ b/cirq-core/cirq/linalg/transformations_test.py @@ -160,26 +160,7 @@ def test_targeted_left_multiply_matches_kron_then_dot(): def test_targeted_left_multiply_reorders_matrices(): t = np.eye(4).reshape((2, 2, 2, 2)) - m = np.array( - [ - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 1, - 0, - ] - ).reshape((2, 2, 2, 2)) + m = np.array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0]).reshape((2, 2, 2, 2)) np.testing.assert_allclose( cirq.targeted_left_multiply(left_matrix=m, right_target=t, target_axes=[0, 1]), m, atol=1e-8 @@ -187,26 +168,7 @@ def test_targeted_left_multiply_reorders_matrices(): np.testing.assert_allclose( cirq.targeted_left_multiply(left_matrix=m, right_target=t, target_axes=[1, 0]), - np.array( - [ - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 1, - 0, - 0, - 1, - 0, - 0, - ] - ).reshape((2, 2, 2, 2)), + np.array([1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0]).reshape((2, 2, 2, 2)), atol=1e-8, ) @@ -576,16 +538,13 @@ def test_partial_trace_of_state_vector_as_mixture_pure_result_qudits(): state = np.kron(np.kron(a, b), c).reshape((2, 3, 4)) assert mixtures_equal( - cirq.partial_trace_of_state_vector_as_mixture(state, [0], atol=1e-8), - ((1.0, a),), + cirq.partial_trace_of_state_vector_as_mixture(state, [0], atol=1e-8), ((1.0, a),) ) assert mixtures_equal( - cirq.partial_trace_of_state_vector_as_mixture(state, [1], atol=1e-8), - ((1.0, b),), + cirq.partial_trace_of_state_vector_as_mixture(state, [1], atol=1e-8), ((1.0, b),) ) assert mixtures_equal( - cirq.partial_trace_of_state_vector_as_mixture(state, [2], atol=1e-8), - ((1.0, c),), + cirq.partial_trace_of_state_vector_as_mixture(state, [2], atol=1e-8), ((1.0, c),) ) assert mixtures_equal( cirq.partial_trace_of_state_vector_as_mixture(state, [0, 1], atol=1e-8), @@ -648,14 +607,7 @@ def test_default_tolerance(): a, b = cirq.LineQubit.range(2) final_state_vector = ( cirq.Simulator() - .simulate( - cirq.Circuit( - cirq.H(a), - cirq.H(b), - cirq.CZ(a, b), - cirq.measure(a), - ) - ) + .simulate(cirq.Circuit(cirq.H(a), cirq.H(b), cirq.CZ(a, b), cirq.measure(a))) .final_state_vector.reshape((2, 2)) ) # Here, we do NOT specify the default tolerance. It is merely to check that the default value diff --git a/cirq-core/cirq/neutral_atoms/__init__.py b/cirq-core/cirq/neutral_atoms/__init__.py index ca7741b576d..3d946a766d1 100644 --- a/cirq-core/cirq/neutral_atoms/__init__.py +++ b/cirq-core/cirq/neutral_atoms/__init__.py @@ -14,9 +14,7 @@ """Neutral atom devices and gates.""" -from cirq.neutral_atoms.neutral_atom_devices import ( - NeutralAtomDevice, -) +from cirq.neutral_atoms.neutral_atom_devices import NeutralAtomDevice from cirq.neutral_atoms.convert_to_neutral_atom_gates import ( ConvertToNeutralAtomGates, diff --git a/cirq-core/cirq/neutral_atoms/convert_to_neutral_atom_gates.py b/cirq-core/cirq/neutral_atoms/convert_to_neutral_atom_gates.py index 5e365426e1a..91f91690038 100644 --- a/cirq-core/cirq/neutral_atoms/convert_to_neutral_atom_gates.py +++ b/cirq-core/cirq/neutral_atoms/convert_to_neutral_atom_gates.py @@ -14,10 +14,7 @@ from typing import List, Optional, TYPE_CHECKING from cirq import ops, protocols -from cirq.circuits.optimization_pass import ( - PointOptimizationSummary, - PointOptimizer, -) +from cirq.circuits.optimization_pass import PointOptimizationSummary, PointOptimizer from cirq.neutral_atoms import neutral_atom_devices from cirq import transformers diff --git a/cirq-core/cirq/neutral_atoms/neutral_atom_devices.py b/cirq-core/cirq/neutral_atoms/neutral_atom_devices.py index 166d347803d..c3dda0e4105 100644 --- a/cirq-core/cirq/neutral_atoms/neutral_atom_devices.py +++ b/cirq-core/cirq/neutral_atoms/neutral_atom_devices.py @@ -216,17 +216,8 @@ def validate_moment(self, moment: circuits.Moment): CATEGORIES = { 'Z': (ops.ZPowGate,), - 'XY': ( - ops.XPowGate, - ops.YPowGate, - ops.PhasedXPowGate, - ), - 'controlled': ( - ops.CNotPowGate, - ops.CZPowGate, - ops.CCXPowGate, - ops.CCZPowGate, - ), + 'XY': (ops.XPowGate, ops.YPowGate, ops.PhasedXPowGate), + 'controlled': (ops.CNotPowGate, ops.CZPowGate, ops.CCXPowGate, ops.CCZPowGate), 'measure': (ops.MeasurementGate,), } diff --git a/cirq-core/cirq/ops/__init__.py b/cirq-core/cirq/ops/__init__.py index b882c4be733..f3a649fd4aa 100644 --- a/cirq-core/cirq/ops/__init__.py +++ b/cirq-core/cirq/ops/__init__.py @@ -14,15 +14,9 @@ """Gates (unitary and non-unitary), operations, base types, and gate sets. """ -from cirq.ops.arithmetic_operation import ( - ArithmeticOperation, -) +from cirq.ops.arithmetic_operation import ArithmeticOperation -from cirq.ops.clifford_gate import ( - CliffordGate, - PauliTransform, - SingleQubitCliffordGate, -) +from cirq.ops.clifford_gate import CliffordGate, PauliTransform, SingleQubitCliffordGate from cirq.ops.dense_pauli_string import ( BaseDensePauliString, @@ -30,9 +24,7 @@ MutableDensePauliString, ) -from cirq.ops.boolean_hamiltonian import ( - BooleanHamiltonianGate, -) +from cirq.ops.boolean_hamiltonian import BooleanHamiltonianGate from cirq.ops.common_channels import ( amplitude_damp, @@ -83,59 +75,29 @@ ParallelGateFamily, ) -from cirq.ops.classically_controlled_operation import ( - ClassicallyControlledOperation, -) +from cirq.ops.classically_controlled_operation import ClassicallyControlledOperation -from cirq.ops.controlled_gate import ( - ControlledGate, -) +from cirq.ops.controlled_gate import ControlledGate -from cirq.ops.diagonal_gate import ( - DiagonalGate, -) +from cirq.ops.diagonal_gate import DiagonalGate -from cirq.ops.eigen_gate import ( - EigenGate, -) +from cirq.ops.eigen_gate import EigenGate -from cirq.ops.fourier_transform import ( - PhaseGradientGate, - qft, - QuantumFourierTransformGate, -) +from cirq.ops.fourier_transform import PhaseGradientGate, qft, QuantumFourierTransformGate -from cirq.ops.fsim_gate import ( - FSimGate, - PhasedFSimGate, -) +from cirq.ops.fsim_gate import FSimGate, PhasedFSimGate -from cirq.ops.gate_features import ( - InterchangeableQubitsGate, - SingleQubitGate, -) +from cirq.ops.gate_features import InterchangeableQubitsGate, SingleQubitGate -from cirq.ops.gate_operation import ( - GateOperation, -) +from cirq.ops.gate_operation import GateOperation from cirq.ops.gateset import GateFamily, Gateset -from cirq.ops.identity import ( - I, - identity_each, - IdentityGate, -) +from cirq.ops.identity import I, identity_each, IdentityGate -from cirq.ops.global_phase_op import ( - GlobalPhaseGate, - GlobalPhaseOperation, - global_phase_operation, -) +from cirq.ops.global_phase_op import GlobalPhaseGate, GlobalPhaseOperation, global_phase_operation -from cirq.ops.kraus_channel import ( - KrausChannel, -) +from cirq.ops.kraus_channel import KrausChannel from cirq.ops.linear_combinations import ( LinearCombinationOfGates, @@ -145,39 +107,23 @@ ProjectorSum, ) -from cirq.ops.mixed_unitary_channel import ( - MixedUnitaryChannel, -) +from cirq.ops.mixed_unitary_channel import MixedUnitaryChannel -from cirq.ops.pauli_sum_exponential import ( - PauliSumExponential, -) +from cirq.ops.pauli_sum_exponential import PauliSumExponential -from cirq.ops.pauli_measurement_gate import ( - PauliMeasurementGate, -) +from cirq.ops.pauli_measurement_gate import PauliMeasurementGate from cirq.ops.parallel_gate import ParallelGate, parallel_gate_op -from cirq.ops.projector import ( - ProjectorString, -) +from cirq.ops.projector import ProjectorString -from cirq.ops.controlled_operation import ( - ControlledOperation, -) +from cirq.ops.controlled_operation import ControlledOperation -from cirq.ops.qubit_order import ( - QubitOrder, -) +from cirq.ops.qubit_order import QubitOrder -from cirq.ops.qubit_order_or_list import ( - QubitOrderOrList, -) +from cirq.ops.qubit_order_or_list import QubitOrderOrList -from cirq.ops.matrix_gates import ( - MatrixGate, -) +from cirq.ops.matrix_gates import MatrixGate from cirq.ops.measure_util import ( measure, @@ -186,14 +132,9 @@ measure_single_paulistring, ) -from cirq.ops.measurement_gate import ( - MeasurementGate, -) +from cirq.ops.measurement_gate import MeasurementGate -from cirq.ops.named_qubit import ( - NamedQubit, - NamedQid, -) +from cirq.ops.named_qubit import NamedQubit, NamedQid from cirq.ops.op_tree import ( flatten_op_tree, @@ -204,25 +145,11 @@ transform_op_tree, ) -from cirq.ops.parity_gates import ( - XX, - XXPowGate, - YY, - YYPowGate, - ZZ, - ZZPowGate, -) +from cirq.ops.parity_gates import XX, XXPowGate, YY, YYPowGate, ZZ, ZZPowGate -from cirq.ops.pauli_gates import ( - Pauli, - X, - Y, - Z, -) +from cirq.ops.pauli_gates import Pauli, X, Y, Z -from cirq.ops.pauli_interaction_gate import ( - PauliInteractionGate, -) +from cirq.ops.pauli_interaction_gate import PauliInteractionGate from cirq.ops.pauli_string import ( MutablePauliString, @@ -232,44 +159,23 @@ SingleQubitPauliStringGateOperation, ) -from cirq.ops.pauli_string_phasor import ( - PauliStringPhasor, - PauliStringPhasorGate, -) +from cirq.ops.pauli_string_phasor import PauliStringPhasor, PauliStringPhasorGate -from cirq.ops.pauli_string_raw_types import ( - PauliStringGateOperation, -) +from cirq.ops.pauli_string_raw_types import PauliStringGateOperation -from cirq.ops.permutation_gate import ( - QubitPermutationGate, -) +from cirq.ops.permutation_gate import QubitPermutationGate -from cirq.ops.phased_iswap_gate import ( - givens, - PhasedISwapPowGate, -) +from cirq.ops.phased_iswap_gate import givens, PhasedISwapPowGate -from cirq.ops.phased_x_gate import ( - PhasedXPowGate, -) +from cirq.ops.phased_x_gate import PhasedXPowGate -from cirq.ops.phased_x_z_gate import ( - PhasedXZGate, -) +from cirq.ops.phased_x_z_gate import PhasedXZGate from cirq.ops.qid_util import q -from cirq.ops.random_gate_channel import ( - RandomGateChannel, -) +from cirq.ops.random_gate_channel import RandomGateChannel -from cirq.ops.raw_types import ( - Gate, - Operation, - Qid, - TaggedOperation, -) +from cirq.ops.raw_types import Gate, Operation, Qid, TaggedOperation from cirq.ops.swap_gates import ( ISWAP, @@ -281,9 +187,7 @@ SwapPowGate, ) -from cirq.ops.tags import ( - VirtualTag, -) +from cirq.ops.tags import VirtualTag from cirq.ops.three_qubit_gates import ( CCNOT, @@ -299,13 +203,8 @@ TOFFOLI, ) -from cirq.ops.two_qubit_diagonal_gate import ( - TwoQubitDiagonalGate, -) +from cirq.ops.two_qubit_diagonal_gate import TwoQubitDiagonalGate -from cirq.ops.wait_gate import ( - wait, - WaitGate, -) +from cirq.ops.wait_gate import wait, WaitGate from cirq.ops.state_preparation_channel import StatePreparationChannel diff --git a/cirq-core/cirq/ops/arithmetic_operation_test.py b/cirq-core/cirq/ops/arithmetic_operation_test.py index ad394d13286..4586c9582a7 100644 --- a/cirq-core/cirq/ops/arithmetic_operation_test.py +++ b/cirq-core/cirq/ops/arithmetic_operation_test.py @@ -35,6 +35,7 @@ def adder_matrix(target_width: int, source_width: int) -> np.ndarray: def test_the_tests(): + # fmt: off np.testing.assert_allclose( shift_matrix(4, 1), np.array( @@ -47,6 +48,7 @@ def test_the_tests(): ), atol=1e-8, ) + # fmt: on np.testing.assert_allclose( shift_matrix(8, -1), np.array( diff --git a/cirq-core/cirq/ops/boolean_hamiltonian.py b/cirq-core/cirq/ops/boolean_hamiltonian.py index d892a87485b..43b97b99a41 100644 --- a/cirq-core/cirq/ops/boolean_hamiltonian.py +++ b/cirq-core/cirq/ops/boolean_hamiltonian.py @@ -38,12 +38,7 @@ class BooleanHamiltonianGate(raw_types.Gate): """A gate that represents a Hamiltonian from a set of Boolean functions.""" - def __init__( - self, - parameter_names: Sequence[str], - boolean_strs: Sequence[str], - theta: float, - ): + def __init__(self, parameter_names: Sequence[str], boolean_strs: Sequence[str], theta: float): """Builds a BooleanHamiltonianGate. For each element of a sequence of Boolean expressions, the code first transforms it into a diff --git a/cirq-core/cirq/ops/boolean_hamiltonian_test.py b/cirq-core/cirq/ops/boolean_hamiltonian_test.py index f34cf009f35..c4a3f781720 100644 --- a/cirq-core/cirq/ops/boolean_hamiltonian_test.py +++ b/cirq-core/cirq/ops/boolean_hamiltonian_test.py @@ -89,11 +89,7 @@ def test_circuit(boolean_str): def test_gate_with_custom_names(): q0, q1, q2, q3 = cirq.LineQubit.range(4) - gate = cirq.BooleanHamiltonianGate( - ['a', 'b'], - ['a'], - 0.1, - ) + gate = cirq.BooleanHamiltonianGate(['a', 'b'], ['a'], 0.1) assert cirq.decompose(gate.on(q0, q1)) == [cirq.Rz(rads=-0.05).on(q0)] assert cirq.decompose_once_with_qubits(gate, (q0, q1)) == [cirq.Rz(rads=-0.05).on(q0)] assert cirq.decompose(gate.on(q2, q3)) == [cirq.Rz(rads=-0.05).on(q2)] @@ -106,11 +102,7 @@ def test_gate_with_custom_names(): def test_gate_consistent(): - gate = cirq.BooleanHamiltonianGate( - ['a', 'b'], - ['a'], - 0.1, - ) + gate = cirq.BooleanHamiltonianGate(['a', 'b'], ['a'], 0.1) op = gate.on(*cirq.LineQubit.range(2)) cirq.testing.assert_implements_consistent_protocols(gate) cirq.testing.assert_implements_consistent_protocols(op) @@ -147,13 +139,7 @@ def test_gray_code_sorting(n_bits, expected_hs): @pytest.mark.parametrize( - 'seq_a,seq_b,expected', - [ - ((), (), 0), - ((), (0,), -1), - ((0,), (), 1), - ((0,), (0,), 0), - ], + 'seq_a,seq_b,expected', [((), (), 0), ((), (0,), -1), ((0,), (), 1), ((0,), (0,), 0)] ) def test_gray_code_comparison(seq_a, seq_b, expected): assert bh._gray_code_comparator(seq_a, seq_b) == expected diff --git a/cirq-core/cirq/ops/classically_controlled_operation.py b/cirq-core/cirq/ops/classically_controlled_operation.py index 10fa65977f2..28d9c22a003 100644 --- a/cirq-core/cirq/ops/classically_controlled_operation.py +++ b/cirq-core/cirq/ops/classically_controlled_operation.py @@ -169,10 +169,7 @@ def _circuit_diagram_info_( ) def _json_dict_(self) -> Dict[str, Any]: - return { - 'conditions': self._conditions, - 'sub_operation': self._sub_operation, - } + return {'conditions': self._conditions, 'sub_operation': self._sub_operation} def _act_on_(self, args: 'cirq.OperationTarget') -> bool: if all(c.resolve(args.classical_data) for c in self._conditions): @@ -194,9 +191,7 @@ def _with_key_path_prefix_(self, prefix: Tuple[str, ...]) -> 'ClassicallyControl return sub_operation.with_classical_controls(*conditions) def _with_rescoped_keys_( - self, - path: Tuple[str, ...], - bindable_keys: FrozenSet['cirq.MeasurementKey'], + self, path: Tuple[str, ...], bindable_keys: FrozenSet['cirq.MeasurementKey'] ) -> 'ClassicallyControlledOperation': conds = [protocols.with_rescoped_keys(c, path, bindable_keys) for c in self._conditions] sub_operation = protocols.with_rescoped_keys(self._sub_operation, path, bindable_keys) diff --git a/cirq-core/cirq/ops/classically_controlled_operation_test.py b/cirq-core/cirq/ops/classically_controlled_operation_test.py index 52018b25218..437e5002453 100644 --- a/cirq-core/cirq/ops/classically_controlled_operation_test.py +++ b/cirq-core/cirq/ops/classically_controlled_operation_test.py @@ -19,11 +19,7 @@ import cirq -ALL_SIMULATORS = ( - cirq.Simulator(), - cirq.DensityMatrixSimulator(), - cirq.CliffordSimulator(), -) +ALL_SIMULATORS = (cirq.Simulator(), cirq.DensityMatrixSimulator(), cirq.CliffordSimulator()) def test_diagram(): @@ -86,10 +82,7 @@ def test_diagram_extra_measurements(): def test_diagram_extra_controlled_bits(): q0, q1 = cirq.LineQubit.range(2) - circuit = cirq.Circuit( - cirq.measure(q0, key='a'), - cirq.CX(q0, q1).with_classical_controls('a'), - ) + circuit = cirq.Circuit(cirq.measure(q0, key='a'), cirq.CX(q0, q1).with_classical_controls('a')) cirq.testing.assert_has_diagram( circuit, @@ -157,10 +150,7 @@ def test_diagram_subcircuit(): q0, q1 = cirq.LineQubit.range(2) circuit = cirq.Circuit( cirq.CircuitOperation( - cirq.FrozenCircuit( - cirq.measure(q0, key='a'), - cirq.X(q1).with_classical_controls('a'), - ) + cirq.FrozenCircuit(cirq.measure(q0, key='a'), cirq.X(q1).with_classical_controls('a')) ) ) @@ -184,10 +174,7 @@ def test_diagram_subcircuit_layered(): circuit = cirq.Circuit( cirq.measure(q0, key='a'), cirq.CircuitOperation( - cirq.FrozenCircuit( - cirq.measure(q0, key='a'), - cirq.X(q1).with_classical_controls('a'), - ), + cirq.FrozenCircuit(cirq.measure(q0, key='a'), cirq.X(q1).with_classical_controls('a')) ), cirq.X(q1).with_classical_controls('a'), ) @@ -341,9 +328,7 @@ def test_subcircuit_key_set(sim): def test_key_unset_in_subcircuit_outer_scope(): q0, q1 = cirq.LineQubit.range(2) - circuit = cirq.Circuit( - cirq.measure(q0, key='a'), - ) + circuit = cirq.Circuit(cirq.measure(q0, key='a')) # TODO (daxfohl): This will not need an InsertStrategy after scope PR. circuit.append( cirq.CircuitOperation(cirq.FrozenCircuit(cirq.X(q1).with_classical_controls('a'))), @@ -357,10 +342,7 @@ def test_key_unset_in_subcircuit_outer_scope(): def test_key_set_in_subcircuit_outer_scope(): q0, q1 = cirq.LineQubit.range(2) - circuit = cirq.Circuit( - cirq.X(q0), - cirq.measure(q0, key='a'), - ) + circuit = cirq.Circuit(cirq.X(q0), cirq.measure(q0, key='a')) # TODO (daxfohl): This will not need an InsertStrategy after scope PR. circuit.append( cirq.CircuitOperation(cirq.FrozenCircuit(cirq.X(q1).with_classical_controls('a'))), @@ -442,10 +424,7 @@ def test_str(): def test_scope_local(): q = cirq.LineQubit(0) - inner = cirq.Circuit( - cirq.measure(q, key='a'), - cirq.X(q).with_classical_controls('a'), - ) + inner = cirq.Circuit(cirq.measure(q, key='a'), cirq.X(q).with_classical_controls('a')) middle = cirq.Circuit(cirq.CircuitOperation(inner.freeze(), repetitions=2)) outer_subcircuit = cirq.CircuitOperation(middle.freeze(), repetitions=2) circuit = outer_subcircuit.mapped_circuit(deep=True) @@ -484,10 +463,7 @@ def test_scope_local(): def test_scope_flatten_both(): q = cirq.LineQubit(0) - inner = cirq.Circuit( - cirq.measure(q, key='a'), - cirq.X(q).with_classical_controls('a'), - ) + inner = cirq.Circuit(cirq.measure(q, key='a'), cirq.X(q).with_classical_controls('a')) middle = cirq.Circuit( cirq.CircuitOperation(inner.freeze(), repetitions=2, use_repetition_ids=False) ) @@ -523,10 +499,7 @@ def test_scope_flatten_both(): def test_scope_flatten_inner(): q = cirq.LineQubit(0) - inner = cirq.Circuit( - cirq.measure(q, key='a'), - cirq.X(q).with_classical_controls('a'), - ) + inner = cirq.Circuit(cirq.measure(q, key='a'), cirq.X(q).with_classical_controls('a')) middle = cirq.Circuit( cirq.CircuitOperation(inner.freeze(), repetitions=2, use_repetition_ids=False) ) @@ -562,10 +535,7 @@ def test_scope_flatten_inner(): def test_scope_flatten_outer(): q = cirq.LineQubit(0) - inner = cirq.Circuit( - cirq.measure(q, key='a'), - cirq.X(q).with_classical_controls('a'), - ) + inner = cirq.Circuit(cirq.measure(q, key='a'), cirq.X(q).with_classical_controls('a')) middle = cirq.Circuit(cirq.CircuitOperation(inner.freeze(), repetitions=2)) outer_subcircuit = cirq.CircuitOperation( middle.freeze(), repetitions=2, use_repetition_ids=False @@ -601,10 +571,7 @@ def test_scope_flatten_outer(): def test_scope_extern(): q = cirq.LineQubit(0) - inner = cirq.Circuit( - cirq.measure(q, key='a'), - cirq.X(q).with_classical_controls('b'), - ) + inner = cirq.Circuit(cirq.measure(q, key='a'), cirq.X(q).with_classical_controls('b')) middle = cirq.Circuit( cirq.measure(q, key=cirq.MeasurementKey('b')), cirq.CircuitOperation(inner.freeze(), repetitions=2), @@ -651,8 +618,7 @@ def wrap_frozen(*ops): q = cirq.LineQubit(0) inner = wrap_frozen( - wrap(cirq.measure(q, key='a')), - wrap(cirq.X(q).with_classical_controls('b')), + wrap(cirq.measure(q, key='a')), wrap(cirq.X(q).with_classical_controls('b')) ) middle = wrap_frozen( wrap(cirq.measure(q, key=cirq.MeasurementKey('b'))), @@ -682,10 +648,7 @@ def wrap_frozen(*ops): def test_scope_root(): q = cirq.LineQubit(0) - inner = cirq.Circuit( - cirq.measure(q, key='a'), - cirq.X(q).with_classical_controls('b'), - ) + inner = cirq.Circuit(cirq.measure(q, key='a'), cirq.X(q).with_classical_controls('b')) middle = cirq.Circuit( cirq.measure(q, key=cirq.MeasurementKey('c')), cirq.CircuitOperation(inner.freeze(), repetitions=2), @@ -725,10 +688,7 @@ def test_scope_root(): def test_scope_extern_mismatch(): q = cirq.LineQubit(0) - inner = cirq.Circuit( - cirq.measure(q, key='a'), - cirq.X(q).with_classical_controls('b'), - ) + inner = cirq.Circuit(cirq.measure(q, key='a'), cirq.X(q).with_classical_controls('b')) middle = cirq.Circuit( cirq.measure(q, key=cirq.MeasurementKey('b', ('0',))), cirq.CircuitOperation(inner.freeze(), repetitions=2), @@ -795,12 +755,9 @@ def test_layered_circuit_operations_with_controls_in_between(): q = cirq.LineQubit(0) outer_subcircuit = cirq.CircuitOperation( cirq.Circuit( - cirq.CircuitOperation( - cirq.FrozenCircuit( - cirq.X(q), - cirq.Y(q), - ) - ).with_classical_controls('m') + cirq.CircuitOperation(cirq.FrozenCircuit(cirq.X(q), cirq.Y(q))).with_classical_controls( + 'm' + ) ).freeze() ) circuit = outer_subcircuit.mapped_circuit(deep=True) diff --git a/cirq-core/cirq/ops/clifford_gate.py b/cirq-core/cirq/ops/clifford_gate.py index 3b001154782..5d9af227a0c 100644 --- a/cirq-core/cirq/ops/clifford_gate.py +++ b/cirq-core/cirq/ops/clifford_gate.py @@ -148,11 +148,7 @@ class SingleQubitCliffordGate(gate_features.SingleQubitGate): Y_nsqrt = _pretend_initialized() Z_nsqrt = _pretend_initialized() - def __init__( - self, - *, - _clifford_tableau: qis.CliffordTableau, - ) -> None: + def __init__(self, *, _clifford_tableau: qis.CliffordTableau) -> None: self._clifford_tableau = _clifford_tableau @property @@ -503,12 +499,7 @@ def __repr__(self) -> str: @classmethod def _from_json_dict_(cls, n, rs, xs, zs, **kwargs): - _clifford_tableau = qis.CliffordTableau._from_json_dict_( - n, - rs, - xs, - zs, - ) + _clifford_tableau = qis.CliffordTableau._from_json_dict_(n, rs, xs, zs) return cls(_clifford_tableau=_clifford_tableau) def _json_dict_(self) -> Dict[str, Any]: @@ -727,9 +718,7 @@ def from_op_list( base_tableau = qis.CliffordTableau(len(qubit_order)) args = sim.clifford.ActOnCliffordTableauArgs( - tableau=base_tableau, - qubits=qubit_order, - prng=np.random.RandomState(0), # unused + tableau=base_tableau, qubits=qubit_order, prng=np.random.RandomState(0) # unused ) for op in operations: protocols.act_on(op, args, allow_decompose=True) @@ -738,12 +727,7 @@ def from_op_list( @classmethod def _from_json_dict_(cls, n, rs, xs, zs, **kwargs): - _clifford_tableau = qis.CliffordTableau._from_json_dict_( - n, - rs, - xs, - zs, - ) + _clifford_tableau = qis.CliffordTableau._from_json_dict_(n, rs, xs, zs) return cls(_clifford_tableau=_clifford_tableau) @@ -775,11 +759,7 @@ def _pad_tableau( class CliffordGate(raw_types.Gate, CommonCliffordGates): """Clifford rotation for N-qubit.""" - def __init__( - self, - *, - _clifford_tableau: qis.CliffordTableau, - ) -> None: + def __init__(self, *, _clifford_tableau: qis.CliffordTableau) -> None: # We use the Clifford tableau to represent a Clifford gate. # It is crucial to note that the meaning of tableau here is different # from the one used to represent a Clifford state (Of course, they are related). diff --git a/cirq-core/cirq/ops/clifford_gate_test.py b/cirq-core/cirq/ops/clifford_gate_test.py index 4aa8db2f90d..a72cb3512b1 100644 --- a/cirq-core/cirq/ops/clifford_gate_test.py +++ b/cirq-core/cirq/ops/clifford_gate_test.py @@ -20,10 +20,7 @@ import cirq from cirq.protocols.act_on_protocol_test import DummyActOnArgs -from cirq.testing import ( - EqualsTester, - assert_allclose_up_to_global_phase, -) +from cirq.testing import EqualsTester, assert_allclose_up_to_global_phase _bools = (False, True) _paulis = (cirq.X, cirq.Y, cirq.Z) @@ -49,10 +46,7 @@ def _assert_no_collision(gate) -> None: def _all_rotations(): - for ( - pauli, - flip, - ) in itertools.product(_paulis, _bools): + for (pauli, flip) in itertools.product(_paulis, _bools): yield cirq.PauliTransform(pauli, flip) @@ -369,9 +363,7 @@ def test_y_rotation(gate, trans_y): def test_decompose(gate, gate_equiv): q0 = cirq.NamedQubit('q0') mat = cirq.Circuit(gate(q0)).unitary() - mat_check = cirq.Circuit( - gate_equiv(q0), - ).unitary() + mat_check = cirq.Circuit(gate_equiv(q0)).unitary() assert_allclose_up_to_global_phase(mat, mat_check, rtol=1e-7, atol=1e-7) @@ -428,23 +420,14 @@ def test_commutes_single_qubit_gate(gate, other): q0 = cirq.NamedQubit('q0') gate_op = gate(q0) other_op = other(q0) - mat = cirq.Circuit( - gate_op, - other_op, - ).unitary() - mat_swap = cirq.Circuit( - other_op, - gate_op, - ).unitary() + mat = cirq.Circuit(gate_op, other_op).unitary() + mat_swap = cirq.Circuit(other_op, gate_op).unitary() commutes = cirq.commutes(gate, other) commutes_check = cirq.allclose_up_to_global_phase(mat, mat_swap) assert commutes == commutes_check # Test after switching order - mat_swap = cirq.Circuit( - gate.equivalent_gate_before(other)(q0), - gate_op, - ).unitary() + mat_swap = cirq.Circuit(gate.equivalent_gate_before(other)(q0), gate_op).unitary() assert_allclose_up_to_global_phase(mat, mat_swap, rtol=1e-7, atol=1e-7) @@ -461,14 +444,8 @@ 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 q0 = cirq.NamedQubit('q0') - mat = cirq.Circuit( - gate(q0), - pauli_gate(q0), - ).unitary() - mat_swap = cirq.Circuit( - pauli_gate(q0), - gate(q0), - ).unitary() + mat = cirq.Circuit(gate(q0), pauli_gate(q0)).unitary() + mat_swap = cirq.Circuit(pauli_gate(q0), gate(q0)).unitary() commutes = cirq.commutes(gate, pauli_gate) commutes_check = np.allclose(mat, mat_swap) assert commutes == commutes_check, f"gate: {gate}, pauli {pauli}" @@ -774,6 +751,7 @@ def test_pad_tableau(): padded_tableau = cirq.ops.clifford_gate._pad_tableau( tableau, num_qubits_after_padding=2, axes=[0] ) + # fmt: off np.testing.assert_equal( padded_tableau.matrix().astype(np.int64), np.array( @@ -781,16 +759,18 @@ def test_pad_tableau(): [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0], - [0, 0, 0, 1], + [0, 0, 0, 1] ] ), ) + # fmt: on np.testing.assert_equal(padded_tableau.rs.astype(np.int64), np.zeros(4)) # The tableau of H again but pad for another ax tableau = cirq.CliffordGate.H.clifford_tableau padded_tableau = cirq.ops.clifford_gate._pad_tableau( tableau, num_qubits_after_padding=2, axes=[1] ) + # fmt: off np.testing.assert_equal( padded_tableau.matrix().astype(np.int64), np.array( @@ -798,10 +778,11 @@ def test_pad_tableau(): [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], - [0, 1, 0, 0], + [0, 1, 0, 0] ] ), ) + # fmt: on np.testing.assert_equal(padded_tableau.rs.astype(np.int64), np.zeros(4)) @@ -810,14 +791,10 @@ def test_clifford_gate_act_on_small_case(): qubits = cirq.LineQubit.range(5) args = cirq.ActOnCliffordTableauArgs( - tableau=cirq.CliffordTableau(num_qubits=5), - qubits=qubits, - prng=np.random.RandomState(), + tableau=cirq.CliffordTableau(num_qubits=5), qubits=qubits, prng=np.random.RandomState() ) expected_args = cirq.ActOnCliffordTableauArgs( - tableau=cirq.CliffordTableau(num_qubits=5), - qubits=qubits, - prng=np.random.RandomState(), + tableau=cirq.CliffordTableau(num_qubits=5), qubits=qubits, prng=np.random.RandomState() ) cirq.act_on(cirq.H, expected_args, qubits=[qubits[0]], allow_decompose=False) cirq.act_on(cirq.CliffordGate.H, args, qubits=[qubits[0]], allow_decompose=False) diff --git a/cirq-core/cirq/ops/common_channels_test.py b/cirq-core/cirq/ops/common_channels_test.py index 3808e194163..e3090beb7fb 100644 --- a/cirq-core/cirq/ops/common_channels_test.py +++ b/cirq-core/cirq/ops/common_channels_test.py @@ -138,12 +138,7 @@ def test_depolarizing_channel(): d = cirq.depolarize(0.3) np.testing.assert_almost_equal( cirq.kraus(d), - ( - np.sqrt(0.7) * np.eye(2), - np.sqrt(0.1) * X, - np.sqrt(0.1) * Y, - np.sqrt(0.1) * Z, - ), + (np.sqrt(0.7) * np.eye(2), np.sqrt(0.1) * X, np.sqrt(0.1) * Y, np.sqrt(0.1) * Z), ) assert cirq.has_kraus(d) diff --git a/cirq-core/cirq/ops/common_gates.py b/cirq-core/cirq/ops/common_gates.py index 9844a7b1f50..0721b3d579e 100644 --- a/cirq-core/cirq/ops/common_gates.py +++ b/cirq-core/cirq/ops/common_gates.py @@ -111,10 +111,7 @@ def with_canonical_global_phase(self) -> 'XPowGate': return XPowGate(exponent=self._exponent) def _eigen_components(self) -> List[Tuple[float, np.ndarray]]: - return [ - (0, np.array([[0.5, 0.5], [0.5, 0.5]])), - (1, np.array([[0.5, -0.5], [-0.5, 0.5]])), - ] + return [(0, np.array([[0.5, 0.5], [0.5, 0.5]])), (1, np.array([[0.5, -0.5], [-0.5, 0.5]]))] def _decompose_into_clifford_with_qubits_(self, qubits): from cirq.ops.clifford_gate import SingleQubitCliffordGate @@ -186,12 +183,7 @@ def _pauli_expansion_(self) -> value.LinearDict[str]: return NotImplemented phase = 1j ** (2 * self._exponent * (self._global_shift + 0.5)) angle = np.pi * self._exponent / 2 - return value.LinearDict( - { - 'I': phase * np.cos(angle), - 'X': -1j * phase * np.sin(angle), - } - ) + return value.LinearDict({'I': phase * np.cos(angle), 'X': -1j * phase * np.sin(angle)}) def _circuit_diagram_info_( self, args: 'cirq.CircuitDiagramInfoArgs' @@ -282,9 +274,7 @@ def __repr__(self) -> str: return f'cirq.Rx(rads={proper_repr(self._rads)})' def _json_dict_(self) -> Dict[str, Any]: - return { - 'rads': self._rads, - } + return {'rads': self._rads} @classmethod def _from_json_dict_(cls, rads, **kwargs) -> 'Rx': @@ -364,12 +354,7 @@ def _pauli_expansion_(self) -> value.LinearDict[str]: return NotImplemented phase = 1j ** (2 * self._exponent * (self._global_shift + 0.5)) angle = np.pi * self._exponent / 2 - return value.LinearDict( - { - 'I': phase * np.cos(angle), - 'Y': -1j * phase * np.sin(angle), - } - ) + return value.LinearDict({'I': phase * np.cos(angle), 'Y': -1j * phase * np.sin(angle)}) def _circuit_diagram_info_( self, args: 'cirq.CircuitDiagramInfoArgs' @@ -457,9 +442,7 @@ def __repr__(self) -> str: return f'cirq.Ry(rads={proper_repr(self._rads)})' def _json_dict_(self) -> Dict[str, Any]: - return { - 'rads': self._rads, - } + return {'rads': self._rads} @classmethod def _from_json_dict_(cls, rads, **kwargs) -> 'Ry': @@ -569,10 +552,7 @@ def controlled( return result def _eigen_components(self) -> List[Tuple[float, np.ndarray]]: - return [ - (0, np.diag([1, 0])), - (1, np.diag([0, 1])), - ] + return [(0, np.diag([1, 0])), (1, np.diag([0, 1]))] def _trace_distance_bound_(self) -> Optional[float]: if self._is_parameterized_(): @@ -584,12 +564,7 @@ def _pauli_expansion_(self) -> value.LinearDict[str]: return NotImplemented phase = 1j ** (2 * self._exponent * (self._global_shift + 0.5)) angle = np.pi * self._exponent / 2 - return value.LinearDict( - { - 'I': phase * np.cos(angle), - 'Z': -1j * phase * np.sin(angle), - } - ) + return value.LinearDict({'I': phase * np.cos(angle), 'Z': -1j * phase * np.sin(angle)}) def _phase_by_(self, phase_turns: float, qubit_index: int): return self @@ -706,9 +681,7 @@ def __repr__(self) -> str: return f'cirq.Rz(rads={proper_repr(self._rads)})' def _json_dict_(self) -> Dict[str, Any]: - return { - 'rads': self._rads, - } + return {'rads': self._rads} @classmethod def _from_json_dict_(cls, rads, **kwargs) -> 'Rz': @@ -880,10 +853,7 @@ def _decompose_into_clifford_with_qubits_(self, qubits): return NotImplemented def _eigen_components(self) -> List[Tuple[float, np.ndarray]]: - return [ - (0, np.diag([1, 1, 1, 0])), - (1, np.diag([0, 0, 0, 1])), - ] + return [(0, np.diag([1, 1, 1, 0])), (1, np.diag([0, 0, 0, 1]))] def _trace_distance_bound_(self) -> Optional[float]: if self._is_parameterized_(): diff --git a/cirq-core/cirq/ops/common_gates_test.py b/cirq-core/cirq/ops/common_gates_test.py index efdd2c54f0a..803fa43e17d 100644 --- a/cirq-core/cirq/ops/common_gates_test.py +++ b/cirq-core/cirq/ops/common_gates_test.py @@ -25,25 +25,13 @@ @pytest.mark.parametrize( - 'eigen_gate_type', - [ - cirq.CZPowGate, - cirq.XPowGate, - cirq.YPowGate, - cirq.ZPowGate, - ], + 'eigen_gate_type', [cirq.CZPowGate, cirq.XPowGate, cirq.YPowGate, cirq.ZPowGate] ) def test_phase_insensitive_eigen_gates_consistent_protocols(eigen_gate_type): cirq.testing.assert_eigengate_implements_consistent_protocols(eigen_gate_type) -@pytest.mark.parametrize( - 'eigen_gate_type', - [ - cirq.CNotPowGate, - cirq.HPowGate, - ], -) +@pytest.mark.parametrize('eigen_gate_type', [cirq.CNotPowGate, cirq.HPowGate]) def test_phase_sensitive_eigen_gates_consistent_protocols(eigen_gate_type): cirq.testing.assert_eigengate_implements_consistent_protocols( eigen_gate_type, ignoring_global_phase=True @@ -926,11 +914,7 @@ def test_rz_unitary(): @pytest.mark.parametrize( 'angle_rads, expected_unitary', - [ - (0, np.eye(4)), - (1, np.diag([1, 1, 1, np.exp(1j)])), - (np.pi / 2, np.diag([1, 1, 1, 1j])), - ], + [(0, np.eye(4)), (1, np.diag([1, 1, 1, np.exp(1j)])), (np.pi / 2, np.diag([1, 1, 1, 1j]))], ) def test_cphase_unitary(angle_rads, expected_unitary): np.testing.assert_allclose(cirq.unitary(cirq.cphase(angle_rads)), expected_unitary) @@ -1005,26 +989,14 @@ def test_ixyz_circuit_diagram(): ) cirq.testing.assert_has_diagram( - cirq.Circuit( - iy(q), - iy(q) ** -1, - iy(q) ** 3, - iy(q) ** 4.5, - iy(q) ** 4.500001, - ), + cirq.Circuit(iy(q), iy(q) ** -1, iy(q) ** 3, iy(q) ** 4.5, iy(q) ** 4.500001), """ q: ───Y───Y───Y───Y^0.5───Y^0.5─── """, ) cirq.testing.assert_has_diagram( - cirq.Circuit( - iz(q), - iz(q) ** -1, - iz(q) ** 3, - iz(q) ** 4.5, - iz(q) ** 4.500001, - ), + cirq.Circuit(iz(q), iz(q) ** -1, iz(q) ** 3, iz(q) ** 4.5, iz(q) ** 4.500001), """ q: ───Z───Z───Z───S───S─── """, diff --git a/cirq-core/cirq/ops/controlled_gate.py b/cirq-core/cirq/ops/controlled_gate.py index 1b0902d92d9..cf59ebb0f18 100644 --- a/cirq-core/cirq/ops/controlled_gate.py +++ b/cirq-core/cirq/ops/controlled_gate.py @@ -198,12 +198,7 @@ def on(self, *qubits: 'cirq.Qid') -> cop.ControlledOperation: ) def _value_equality_values_(self): - return ( - self.sub_gate, - self.num_controls(), - self.control_values, - self.control_qid_shape, - ) + return (self.sub_gate, self.num_controls(), self.control_values, self.control_qid_shape) def _apply_unitary_(self, args: 'protocols.ApplyUnitaryArgs') -> np.ndarray: qubits = line_qubit.LineQid.for_gate(self) diff --git a/cirq-core/cirq/ops/controlled_gate_test.py b/cirq-core/cirq/ops/controlled_gate_test.py index f119c207641..d436c6f01a4 100644 --- a/cirq-core/cirq/ops/controlled_gate_test.py +++ b/cirq-core/cirq/ops/controlled_gate_test.py @@ -226,22 +226,20 @@ def test_eq(): cirq.ControlledGate(cirq.H, control_values=(1, [0, 2]), control_qid_shape=(2, 3)), ) eq.add_equality_group( - cirq.ControlledGate(cirq.H, control_values=[(2, 0), 1], control_qid_shape=[3, 2]), + cirq.ControlledGate(cirq.H, control_values=[(2, 0), 1], control_qid_shape=[3, 2]) ) eq.add_equality_group( cirq.ControlledGate(cirq.H, control_values=[1, 0], control_qid_shape=[2, 3]), cirq.ControlledGate(cirq.H, control_values=(1, 0), control_qid_shape=(2, 3)), ) eq.add_equality_group( - cirq.ControlledGate(cirq.H, control_values=[0, 1], control_qid_shape=[3, 2]), + cirq.ControlledGate(cirq.H, control_values=[0, 1], control_qid_shape=[3, 2]) ) eq.add_equality_group( cirq.ControlledGate(cirq.H, control_values=[1, 0]), cirq.ControlledGate(cirq.H, control_values=(1, 0)), ) - eq.add_equality_group( - cirq.ControlledGate(cirq.H, control_values=[0, 1]), - ) + eq.add_equality_group(cirq.ControlledGate(cirq.H, control_values=[0, 1])) for group in eq._groups: if isinstance(group[0], cirq.Gate): for item in group: @@ -281,17 +279,13 @@ def test_control(): g.controlled(control_values=[0, 1]), g.controlled(control_values=[1]).controlled(control_values=[0]), ) - eq.add_equality_group( - g.controlled(control_values=[0]).controlled(control_values=[1]), - ) + eq.add_equality_group(g.controlled(control_values=[0]).controlled(control_values=[1])) eq.add_equality_group( cirq.ControlledGate(g, control_qid_shape=[4, 3]), g.controlled(control_qid_shape=[4, 3]), g.controlled(control_qid_shape=[3]).controlled(control_qid_shape=[4]), ) - eq.add_equality_group( - g.controlled(control_qid_shape=[4]).controlled(control_qid_shape=[3]), - ) + eq.add_equality_group(g.controlled(control_qid_shape=[4]).controlled(control_qid_shape=[3])) def test_unitary(): @@ -301,6 +295,7 @@ def test_unitary(): assert cirq.has_unitary(CY) assert cirq.has_unitary(CCH) + # fmt: off np.testing.assert_allclose( cirq.unitary(CY), np.array( @@ -325,6 +320,7 @@ def test_unitary(): ), atol=1e-8, ) + # fmt: on np.testing.assert_allclose( cirq.unitary(CCH), np.array( @@ -578,22 +574,10 @@ class NoDetails(cirq.Gate): def num_qubits(self) -> int: return 1 - c_no = cirq.ControlledGate( - num_controls=1, - sub_gate=NoDetails(), - ) + c_no = cirq.ControlledGate(num_controls=1, sub_gate=NoDetails()) assert not cirq.has_mixture(c_no) assert cirq.mixture(c_no, None) is None - c_yes = cirq.ControlledGate( - sub_gate=cirq.phase_flip(0.25), - num_controls=1, - ) + c_yes = cirq.ControlledGate(sub_gate=cirq.phase_flip(0.25), num_controls=1) assert cirq.has_mixture(c_yes) - assert cirq.approx_eq( - cirq.mixture(c_yes), - [ - (0.75, np.eye(4)), - (0.25, cirq.unitary(cirq.CZ)), - ], - ) + assert cirq.approx_eq(cirq.mixture(c_yes), [(0.75, np.eye(4)), (0.25, cirq.unitary(cirq.CZ))]) diff --git a/cirq-core/cirq/ops/controlled_operation_test.py b/cirq-core/cirq/ops/controlled_operation_test.py index 5ab0c20437a..ee9eb62adf8 100644 --- a/cirq-core/cirq/ops/controlled_operation_test.py +++ b/cirq-core/cirq/ops/controlled_operation_test.py @@ -436,22 +436,10 @@ def qubits(self): def with_qubits(self, *new_qubits): raise NotImplementedError() - c_no = cirq.ControlledOperation( - controls=[b], - sub_operation=NoDetails(), - ) + c_no = cirq.ControlledOperation(controls=[b], sub_operation=NoDetails()) assert not cirq.has_mixture(c_no) assert cirq.mixture(c_no, None) is None - c_yes = cirq.ControlledOperation( - controls=[b], - sub_operation=cirq.phase_flip(0.25).on(a), - ) + c_yes = cirq.ControlledOperation(controls=[b], sub_operation=cirq.phase_flip(0.25).on(a)) assert cirq.has_mixture(c_yes) - assert cirq.approx_eq( - cirq.mixture(c_yes), - [ - (0.75, np.eye(4)), - (0.25, cirq.unitary(cirq.CZ)), - ], - ) + assert cirq.approx_eq(cirq.mixture(c_yes), [(0.75, np.eye(4)), (0.25, cirq.unitary(cirq.CZ))]) diff --git a/cirq-core/cirq/ops/dense_pauli_string_test.py b/cirq-core/cirq/ops/dense_pauli_string_test.py index b0dc51f8a68..283b1f7fd9c 100644 --- a/cirq-core/cirq/ops/dense_pauli_string_test.py +++ b/cirq-core/cirq/ops/dense_pauli_string_test.py @@ -553,43 +553,17 @@ def table(*rows: str) -> List[cirq.MutableDensePauliString]: f(t) assert t == table('+X') - t = table( - "+.X.X", - "+Z.Z.", - "+X.XX", - "+ZZ.Z", - ) + t = table("+.X.X", "+Z.Z.", "+X.XX", "+ZZ.Z") f(t) - assert t == table( - "+X.XX", - "+Z.Z.", - "+.X.X", - "+.ZZZ", - ) + assert t == table("+X.XX", "+Z.Z.", "+.X.X", "+.ZZZ") - t = table( - "+XXX", - "+YYY", - ) + t = table("+XXX", "+YYY") f(t) - assert t == table( - "+XXX", - "iZZZ", - ) + assert t == table("+XXX", "iZZZ") - t = table( - "+XXXX", - "+X...", - "+..ZZ", - "+.ZZ.", - ) + t = table("+XXXX", "+X...", "+..ZZ", "+.ZZ.") f(t) - assert t == table( - "+X...", - "+.XXX", - "+.Z.Z", - "+..ZZ", - ) + assert t == table("+X...", "+.XXX", "+.Z.Z", "+..ZZ") t = table( '+ZZZ.........', diff --git a/cirq-core/cirq/ops/eigen_gate.py b/cirq-core/cirq/ops/eigen_gate.py index 0e49977c52e..077b5f6a32d 100644 --- a/cirq-core/cirq/ops/eigen_gate.py +++ b/cirq-core/cirq/ops/eigen_gate.py @@ -202,9 +202,7 @@ def _diagram_exponent( return result def _format_exponent_as_angle( - self, - args: 'protocols.CircuitDiagramInfoArgs', - order: int = 2, + self, args: 'protocols.CircuitDiagramInfoArgs', order: int = 2 ) -> str: """Returns string with exponent expressed as angle in radians. diff --git a/cirq-core/cirq/ops/eigen_gate_test.py b/cirq-core/cirq/ops/eigen_gate_test.py index 8e2d64f8614..60a95e3de58 100644 --- a/cirq-core/cirq/ops/eigen_gate_test.py +++ b/cirq-core/cirq/ops/eigen_gate_test.py @@ -56,10 +56,7 @@ def exponent(self): return self._exponent def _eigen_components(self) -> List[Tuple[float, np.ndarray]]: - return [ - (0, np.diag([1, 0])), - (1, np.diag([0, 1])), - ] + return [(0, np.diag([1, 0])), (1, np.diag([0, 1]))] def test_approximate_common_period(): @@ -209,10 +206,7 @@ def _num_qubits_(self): return 1 def _eigen_components(self) -> List[Tuple[float, np.ndarray]]: - return [ - (0, np.array([[1, 0], [0, 0]])), - (12, np.array([[0, 0], [0, 1]])), - ] + return [(0, np.array([[1, 0], [0, 0]])), (12, np.array([[0, 0], [0, 1]]))] for numerator in range(13): assert_has_consistent_trace_distance_bound(E() ** (numerator / 12)) @@ -344,10 +338,7 @@ def _value_equality_values_(self): _value_equality_approximate_values_ = _value_equality_values_ def _eigen_components(self) -> List[Tuple[float, np.ndarray]]: - return [ - (0, np.diag([1, 0])), - (self.weight, np.diag([0, 1])), - ] + return [(0, np.diag([1, 0])), (self.weight, np.diag([0, 1]))] def _with_exponent(self, exponent): return type(self)(self.weight, exponent=exponent, global_shift=self._global_shift) diff --git a/cirq-core/cirq/ops/fourier_transform.py b/cirq-core/cirq/ops/fourier_transform.py index f14389c06a1..b5e01050e66 100644 --- a/cirq-core/cirq/ops/fourier_transform.py +++ b/cirq-core/cirq/ops/fourier_transform.py @@ -41,10 +41,7 @@ def __init__(self, num_qubits: int, *, without_reverse: bool = False): self._without_reverse = without_reverse def _json_dict_(self) -> Dict[str, Any]: - return { - 'num_qubits': self._num_qubits, - 'without_reverse': self._without_reverse, - } + return {'num_qubits': self._num_qubits, 'without_reverse': self._without_reverse} def _value_equality_values_(self): return self._num_qubits, self._without_reverse @@ -100,10 +97,7 @@ def exponent(self) -> Union[float, sympy.Basic]: return self._exponent def _json_dict_(self) -> Dict[str, Any]: - return { - 'num_qubits': self._num_qubits, - 'exponent': self.exponent, - } + return {'num_qubits': self._num_qubits, 'exponent': self.exponent} def _value_equality_values_(self): return self._num_qubits, self.exponent diff --git a/cirq-core/cirq/ops/fourier_transform_test.py b/cirq-core/cirq/ops/fourier_transform_test.py index c1e7cbdde5f..c678faba258 100644 --- a/cirq-core/cirq/ops/fourier_transform_test.py +++ b/cirq-core/cirq/ops/fourier_transform_test.py @@ -66,6 +66,7 @@ def test_pow(): def test_qft(): + # fmt: off np.testing.assert_allclose( cirq.unitary(cirq.qft(*cirq.LineQubit.range(2))), np.array( @@ -93,6 +94,7 @@ def test_qft(): / 2, atol=1e-8, ) + # fmt: on np.testing.assert_allclose( cirq.unitary(cirq.qft(*cirq.LineQubit.range(4))), @@ -102,15 +104,7 @@ def test_qft(): np.testing.assert_allclose( cirq.unitary(cirq.qft(*cirq.LineQubit.range(2)) ** -1), - np.array( - [ - [1, 1, 1, 1], - [1, -1j, -1, 1j], - [1, -1, 1, -1], - [1, 1j, -1, -1j], - ] - ) - / 2, + np.array([[1, 1, 1, 1], [1, -1j, -1, 1j], [1, -1, 1, -1], [1, 1j, -1, -1j]]) / 2, atol=1e-8, ) diff --git a/cirq-core/cirq/ops/fsim_gate.py b/cirq-core/cirq/ops/fsim_gate.py index 238e4904bff..0a33167f834 100644 --- a/cirq-core/cirq/ops/fsim_gate.py +++ b/cirq-core/cirq/ops/fsim_gate.py @@ -122,6 +122,7 @@ def _unitary_(self) -> Optional[np.ndarray]: a = math.cos(self.theta) b = -1j * math.sin(self.theta) c = cmath.exp(-1j * self.phi) + # fmt: off return np.array( [ [1, 0, 0, 0], @@ -130,6 +131,7 @@ def _unitary_(self) -> Optional[np.ndarray]: [0, 0, 0, c], ] ) + # fmt: on def _pauli_expansion_(self) -> value.LinearDict[str]: if protocols.is_parameterized(self): @@ -387,6 +389,7 @@ def _unitary_(self) -> Optional[np.ndarray]: f3 = cmath.exp(-1j * self.gamma - 1j * self.chi) f4 = cmath.exp(-1j * self.gamma + 1j * self.zeta) f5 = cmath.exp(-2j * self.gamma) + # fmt: off return np.array( [ [1, 0, 0, 0], @@ -395,6 +398,7 @@ def _unitary_(self) -> Optional[np.ndarray]: [0, 0, 0, f5 * c], ] ) + # fmt: on def _resolve_parameters_( self, resolver: 'cirq.ParamResolver', recursive: bool diff --git a/cirq-core/cirq/ops/fsim_gate_test.py b/cirq-core/cirq/ops/fsim_gate_test.py index b9e41b1a81b..684f36dffa8 100644 --- a/cirq-core/cirq/ops/fsim_gate_test.py +++ b/cirq-core/cirq/ops/fsim_gate_test.py @@ -68,8 +68,7 @@ def test_fsim_consistent(theta, phi): def test_fsim_circuit(): a, b = cirq.LineQubit.range(2) c = cirq.Circuit( - cirq.FSimGate(np.pi / 2, np.pi).on(a, b), - cirq.FSimGate(-np.pi, np.pi / 2).on(a, b), + cirq.FSimGate(np.pi / 2, np.pi).on(a, b), cirq.FSimGate(-np.pi, np.pi / 2).on(a, b) ) cirq.testing.assert_has_diagram( c, @@ -124,6 +123,7 @@ def test_fsim_resolve(resolve_fn): def test_fsim_unitary(): + # fmt: off np.testing.assert_allclose( cirq.unitary(cirq.FSimGate(theta=0, phi=0)), np.array( @@ -174,6 +174,7 @@ def test_fsim_unitary(): ), atol=1e-8, ) + # fmt: on np.testing.assert_allclose( cirq.unitary(cirq.FSimGate(theta=2 * np.pi, phi=0)), cirq.unitary(cirq.FSimGate(theta=0, phi=0)), @@ -186,6 +187,7 @@ def test_fsim_unitary(): ) # Phi + # fmt: off np.testing.assert_allclose( cirq.unitary(cirq.FSimGate(theta=0, phi=np.pi / 2)), np.array( @@ -222,6 +224,7 @@ def test_fsim_unitary(): ), atol=1e-8, ) + # fmt: on np.testing.assert_allclose( cirq.unitary(cirq.FSimGate(theta=0, phi=0)), cirq.unitary(cirq.FSimGate(theta=0, phi=2 * np.pi)), @@ -277,10 +280,7 @@ def test_fsim_repr(): def test_fsim_json_dict(): - assert cirq.FSimGate(theta=0.123, phi=0.456)._json_dict_() == { - 'theta': 0.123, - 'phi': 0.456, - } + assert cirq.FSimGate(theta=0.123, phi=0.456)._json_dict_() == {'theta': 0.123, 'phi': 0.456} def test_phased_fsim_init(): @@ -563,6 +563,7 @@ def test_phased_fsim_resolve(resolve_fn): def test_phased_fsim_unitary(): + # fmt: off np.testing.assert_allclose( cirq.unitary(cirq.PhasedFSimGate(theta=0, phi=0)), np.array( @@ -613,6 +614,7 @@ def test_phased_fsim_unitary(): ), atol=1e-8, ) + # fmt: on np.testing.assert_allclose( cirq.unitary(cirq.PhasedFSimGate(theta=2 * np.pi, phi=0)), cirq.unitary(cirq.PhasedFSimGate(theta=0, phi=0)), @@ -625,6 +627,7 @@ def test_phased_fsim_unitary(): ) # Phi + # fmt: off np.testing.assert_allclose( cirq.unitary(cirq.PhasedFSimGate(theta=0, phi=np.pi / 2)), np.array( @@ -661,6 +664,7 @@ def test_phased_fsim_unitary(): ), atol=1e-8, ) + # fmt: on np.testing.assert_allclose( cirq.unitary(cirq.PhasedFSimGate(theta=0, phi=0)), cirq.unitary(cirq.PhasedFSimGate(theta=0, phi=2 * np.pi)), @@ -691,14 +695,7 @@ def test_phased_fsim_unitary(): w6 = np.exp(-1j * np.pi / 6) np.testing.assert_allclose( cirq.unitary(cirq.PhasedFSimGate(theta=0, gamma=np.pi / 2, zeta=np.pi / 3)), - np.array( - [ - [1, 0, 0, 0], - [0, -w6.conjugate(), 0, 0], - [0, 0, w6, 0], - [0, 0, 0, -1], - ] - ), + np.array([[1, 0, 0, 0], [0, -w6.conjugate(), 0, 0], [0, 0, w6, 0], [0, 0, 0, -1]]), atol=1e-8, ) np.testing.assert_allclose( @@ -711,6 +708,7 @@ def test_phased_fsim_unitary(): cirq.unitary(cirq.PhasedFSimGate(theta=np.pi, chi=0.2)), atol=1e-8, ) + # fmt: off np.testing.assert_allclose( cirq.unitary(cirq.PhasedFSimGate(theta=-np.pi / 2, gamma=np.pi / 2, chi=np.pi / 3)), np.array( @@ -723,6 +721,7 @@ def test_phased_fsim_unitary(): ), atol=1e-8, ) + # fmt: on np.testing.assert_allclose( cirq.unitary(cirq.PhasedFSimGate(theta=np.pi / 2, phi=0)), cirq.unitary(cirq.PhasedFSimGate(theta=np.pi / 2, zeta=0.2, phi=0)), @@ -797,10 +796,4 @@ def test_phased_fsim_repr(): def test_phased_fsim_json_dict(): assert cirq.PhasedFSimGate( theta=0.12, zeta=0.34, chi=0.56, gamma=0.78, phi=0.9 - )._json_dict_() == { - 'theta': 0.12, - 'zeta': 0.34, - 'chi': 0.56, - 'gamma': 0.78, - 'phi': 0.9, - } + )._json_dict_() == {'theta': 0.12, 'zeta': 0.34, 'chi': 0.56, 'gamma': 0.78, 'phi': 0.9} diff --git a/cirq-core/cirq/ops/gate_operation.py b/cirq-core/cirq/ops/gate_operation.py index 6f80710d42d..0d83f26fe78 100644 --- a/cirq-core/cirq/ops/gate_operation.py +++ b/cirq-core/cirq/ops/gate_operation.py @@ -109,9 +109,7 @@ def _with_key_path_prefix_(self, prefix: Tuple[str, ...]): return new_gate.on(*self.qubits) def _with_rescoped_keys_( - self, - path: Tuple[str, ...], - bindable_keys: FrozenSet['cirq.MeasurementKey'], + self, path: Tuple[str, ...], bindable_keys: FrozenSet['cirq.MeasurementKey'] ): new_gate = protocols.with_rescoped_keys(self.gate, path, bindable_keys) if new_gate is self.gate: diff --git a/cirq-core/cirq/ops/gateset.py b/cirq-core/cirq/ops/gateset.py index 43ef71026ee..c11b2147533 100644 --- a/cirq-core/cirq/ops/gateset.py +++ b/cirq-core/cirq/ops/gateset.py @@ -346,10 +346,7 @@ def __contains__(self, item: Union[raw_types.Gate, raw_types.Operation]) -> bool return any(item in gate_family for gate_family in self._gates) - def validate( - self, - circuit_or_optree: Union['cirq.AbstractCircuit', op_tree.OP_TREE], - ) -> bool: + def validate(self, circuit_or_optree: Union['cirq.AbstractCircuit', op_tree.OP_TREE]) -> bool: """Validates gates forming `circuit_or_optree` should be contained in Gateset. Args: @@ -397,12 +394,7 @@ def _validate_operation(self, op: raw_types.Operation) -> bool: return False def _value_equality_values_(self) -> Any: - return ( - self.gates, - self.name, - self._unroll_circuit_op, - self._accept_global_phase_op, - ) + return (self.gates, self.name, self._unroll_circuit_op, self._accept_global_phase_op) def __repr__(self) -> str: name_str = f'name = "{self.name}", ' if self.name is not None else '' diff --git a/cirq-core/cirq/ops/gateset_test.py b/cirq-core/cirq/ops/gateset_test.py index 5bfc0c786d1..34277ece445 100644 --- a/cirq-core/cirq/ops/gateset_test.py +++ b/cirq-core/cirq/ops/gateset_test.py @@ -23,10 +23,7 @@ class CustomXPowGate(cirq.EigenGate): def _eigen_components(self) -> List[Tuple[float, np.ndarray]]: - return [ - (0, np.array([[0.5, 0.5], [0.5, 0.5]])), - (1, np.array([[0.5, -0.5], [-0.5, 0.5]])), - ] + return [(0, np.array([[0.5, 0.5], [0.5, 0.5]])), (1, np.array([[0.5, -0.5], [-0.5, 0.5]]))] def __str__(self) -> str: if self._global_shift == 0: @@ -149,10 +146,7 @@ def test_gate_family_eq(): ), ( cirq.GateFamily(CustomX, ignore_global_phase=False), - [ - (CustomX, True), - (CustomXPowGate(exponent=1, global_shift=0.15), False), - ], + [(CustomX, True), (CustomXPowGate(exponent=1, global_shift=0.15), False)], ), ], ) @@ -265,18 +259,14 @@ def assert_validate_and_contains_consistent(gateset, op_tree, result): op_tree = [*get_ops(use_circuit_op, use_global_phase)] assert_validate_and_contains_consistent( gateset.with_params( - unroll_circuit_op=use_circuit_op, - accept_global_phase_op=use_global_phase, + unroll_circuit_op=use_circuit_op, accept_global_phase_op=use_global_phase ), op_tree, True, ) if use_circuit_op or use_global_phase: assert_validate_and_contains_consistent( - gateset.with_params( - unroll_circuit_op=False, - accept_global_phase_op=False, - ), + gateset.with_params(unroll_circuit_op=False, accept_global_phase_op=False), op_tree, False, ) diff --git a/cirq-core/cirq/ops/global_phase_op_test.py b/cirq-core/cirq/ops/global_phase_op_test.py index 21153195374..a2e8ccf62c5 100644 --- a/cirq-core/cirq/ops/global_phase_op_test.py +++ b/cirq-core/cirq/ops/global_phase_op_test.py @@ -52,9 +52,7 @@ def test_act_on_tableau(phase): def test_act_on_ch_form(phase): state = cirq.StabilizerStateChForm(0) args = cirq.ActOnStabilizerCHFormArgs( - qubits=[], - prng=np.random.RandomState(), - initial_state=state, + qubits=[], prng=np.random.RandomState(), initial_state=state ) cirq.act_on(cirq.global_phase_operation(phase), args, allow_decompose=False) assert state.state_vector() == [[phase]] @@ -88,15 +86,7 @@ def test_diagram(): cirq.testing.assert_has_diagram( cirq.Circuit( - [ - cirq.Moment( - [ - cirq.CNOT(a, x), - cirq.CNOT(b, y), - cirq.global_phase_operation(-1), - ] - ) - ] + [cirq.Moment([cirq.CNOT(a, x), cirq.CNOT(b, y), cirq.global_phase_operation(-1)])] ), """ ┌──┐ @@ -123,7 +113,7 @@ def test_diagram(): cirq.global_phase_operation(-1), cirq.global_phase_operation(-1), ] - ), + ) ] ), """ @@ -152,16 +142,8 @@ def test_diagram(): cirq.global_phase_operation(-1), ] ), - cirq.Moment( - [ - cirq.global_phase_operation(1j), - ] - ), - cirq.Moment( - [ - cirq.X(a), - ] - ), + cirq.Moment([cirq.global_phase_operation(1j)]), + cirq.Moment([cirq.X(a)]), ] ), """ @@ -180,20 +162,7 @@ def test_diagram(): ) cirq.testing.assert_has_diagram( - cirq.Circuit( - [ - cirq.Moment( - [ - cirq.X(a), - ] - ), - cirq.Moment( - [ - cirq.global_phase_operation(-1j), - ] - ), - ] - ), + cirq.Circuit([cirq.Moment([cirq.X(a)]), cirq.Moment([cirq.global_phase_operation(-1j)])]), """ 0: ─────────────X─────────── @@ -202,16 +171,7 @@ def test_diagram(): ) cirq.testing.assert_has_diagram( - cirq.Circuit( - [ - cirq.Moment( - [ - cirq.X(a), - cirq.global_phase_operation(np.exp(1j)), - ] - ), - ] - ), + cirq.Circuit([cirq.Moment([cirq.X(a), cirq.global_phase_operation(np.exp(1j))])]), """ 0: ─────────────X──────── @@ -220,16 +180,7 @@ def test_diagram(): ) cirq.testing.assert_has_diagram( - cirq.Circuit( - [ - cirq.Moment( - [ - cirq.X(a), - cirq.global_phase_operation(np.exp(1j)), - ] - ), - ] - ), + cirq.Circuit([cirq.Moment([cirq.X(a), cirq.global_phase_operation(np.exp(1j))])]), """ 0: ─────────────X────────── @@ -241,17 +192,8 @@ def test_diagram(): cirq.testing.assert_has_diagram( cirq.Circuit( [ - cirq.Moment( - [ - cirq.X(a), - cirq.global_phase_operation(1j), - ] - ), - cirq.Moment( - [ - cirq.global_phase_operation(-1j), - ] - ), + cirq.Moment([cirq.X(a), cirq.global_phase_operation(1j)]), + cirq.Moment([cirq.global_phase_operation(-1j)]), ] ), """ @@ -263,15 +205,7 @@ def test_diagram(): ) cirq.testing.assert_has_diagram( - cirq.Circuit( - [ - cirq.Moment( - [ - cirq.global_phase_operation(-1j), - ] - ), - ] - ), + cirq.Circuit([cirq.Moment([cirq.global_phase_operation(-1j)])]), """ global phase: -0.5π """, @@ -280,9 +214,7 @@ def test_diagram(): def test_global_phase_op_json_dict(): with cirq.testing.assert_deprecated('Use cirq.global_phase_operation', deadline='v0.16'): - assert cirq.GlobalPhaseOperation(-1j)._json_dict_() == { - 'coefficient': -1j, - } + assert cirq.GlobalPhaseOperation(-1j)._json_dict_() == {'coefficient': -1j} def test_gate_init(): @@ -317,9 +249,7 @@ def test_gate_act_on_tableau(phase): def test_gate_act_on_ch_form(phase): state = cirq.StabilizerStateChForm(0) args = cirq.ActOnStabilizerCHFormArgs( - qubits=[], - prng=np.random.RandomState(), - initial_state=state, + qubits=[], prng=np.random.RandomState(), initial_state=state ) cirq.act_on(cirq.GlobalPhaseGate(phase), args, qubits=(), allow_decompose=False) assert state.state_vector() == [[phase]] @@ -340,6 +270,4 @@ def test_gate_op_repr(): def test_gate_global_phase_op_json_dict(): - assert cirq.GlobalPhaseGate(-1j)._json_dict_() == { - 'coefficient': -1j, - } + assert cirq.GlobalPhaseGate(-1j)._json_dict_() == {'coefficient': -1j} diff --git a/cirq-core/cirq/ops/identity.py b/cirq-core/cirq/ops/identity.py index 89fbf136f99..435bdabc008 100644 --- a/cirq-core/cirq/ops/identity.py +++ b/cirq-core/cirq/ops/identity.py @@ -114,10 +114,7 @@ def _json_dict_(self) -> Dict[str, Any]: other = {} if not all(d == 2 for d in self._qid_shape): other['qid_shape'] = self._qid_shape - return { - 'num_qubits': len(self._qid_shape), - **other, - } + return {'num_qubits': len(self._qid_shape), **other} def _mul_with_qubits(self, qubits: Tuple['cirq.Qid', ...], other): if isinstance(other, raw_types.Operation): diff --git a/cirq-core/cirq/ops/identity_test.py b/cirq-core/cirq/ops/identity_test.py index c1f13a73f88..e9a7892d280 100644 --- a/cirq-core/cirq/ops/identity_test.py +++ b/cirq-core/cirq/ops/identity_test.py @@ -79,7 +79,7 @@ def test_identity_on_each_two_qubits(): cirq.IdentityGate(2)(q2, q3), ] assert cirq.IdentityGate(2, (3, 3)).on_each([(q0_3, q1_3)]) == [ - cirq.IdentityGate(2, (3, 3))(q0_3, q1_3), + cirq.IdentityGate(2, (3, 3))(q0_3, q1_3) ] assert cirq.IdentityGate(2).on_each((q0, q1)) == [cirq.IdentityGate(2)(q0, q1)] with pytest.raises(ValueError, match='Inputs to multi-qubit gates must be Sequence'): @@ -129,9 +129,7 @@ def test_identity_apply_unitary(): def test_identity_eq(): equals_tester = cirq.testing.EqualsTester() equals_tester.make_equality_group( - lambda: cirq.I, - lambda: cirq.IdentityGate(1), - lambda: cirq.IdentityGate(1, (2,)), + lambda: cirq.I, lambda: cirq.IdentityGate(1), lambda: cirq.IdentityGate(1, (2,)) ) equals_tester.add_equality_group(cirq.IdentityGate(2), cirq.IdentityGate(2, (2, 2))) equals_tester.add_equality_group(cirq.IdentityGate(4)) diff --git a/cirq-core/cirq/ops/kraus_channel.py b/cirq-core/cirq/ops/kraus_channel.py index cf3feb3a638..a1159a54083 100644 --- a/cirq-core/cirq/ops/kraus_channel.py +++ b/cirq-core/cirq/ops/kraus_channel.py @@ -100,9 +100,7 @@ def _with_key_path_prefix_(self, prefix: Tuple[str, ...]): ) def _with_rescoped_keys_( - self, - path: Tuple[str, ...], - bindable_keys: FrozenSet['cirq.MeasurementKey'], + self, path: Tuple[str, ...], bindable_keys: FrozenSet['cirq.MeasurementKey'] ): return KrausChannel( kraus_ops=self._kraus_ops, diff --git a/cirq-core/cirq/ops/kraus_channel_test.py b/cirq-core/cirq/ops/kraus_channel_test.py index 0e6164f19b7..ecb94f336f8 100644 --- a/cirq-core/cirq/ops/kraus_channel_test.py +++ b/cirq-core/cirq/ops/kraus_channel_test.py @@ -33,10 +33,7 @@ def test_kraus_channel_equality(): assert kc_a1 != kc_b1 assert kc_a2 != kc_b1 - ops = [ - np.array([[1, 0], [0, 0]]), - np.array([[0, 0], [0, 1]]), - ] + ops = [np.array([[1, 0], [0, 0]]), np.array([[0, 0], [0, 1]])] x_meas = cirq.KrausChannel(ops) ops_inv = list(reversed(ops)) x_meas_inv = cirq.KrausChannel(ops_inv) @@ -65,10 +62,7 @@ def test_kraus_channel_remap_keys(): def test_kraus_channel_from_kraus(): q0 = cirq.LineQubit(0) # This is equivalent to an X-basis measurement. - ops = [ - np.array([[1, 1], [1, 1]]) * 0.5, - np.array([[1, -1], [-1, 1]]) * 0.5, - ] + ops = [np.array([[1, 1], [1, 1]]) * 0.5, np.array([[1, -1], [-1, 1]]) * 0.5] x_meas = cirq.KrausChannel(ops, key='x_meas') assert cirq.measurement_key_name(x_meas) == 'x_meas' @@ -82,10 +76,7 @@ def test_kraus_channel_from_kraus(): def test_kraus_channel_str(): # This is equivalent to an X-basis measurement. - ops = [ - np.array([[1, 1], [1, 1]]) * 0.5, - np.array([[1, -1], [-1, 1]]) * 0.5, - ] + ops = [np.array([[1, 1], [1, 1]]) * 0.5, np.array([[1, -1], [-1, 1]]) * 0.5] x_meas = cirq.KrausChannel(ops) assert ( str(x_meas) @@ -136,10 +127,7 @@ def test_ops_mismatch_fails(): def test_nonqubit_kraus_ops_fails(): - ops = [ - np.array([[1, 0, 0], [0, 0, 0]]), - np.array([[0, 0, 0], [0, 1, 0]]), - ] + ops = [np.array([[1, 0, 0], [0, 0, 0]]), np.array([[0, 0, 0], [0, 1, 0]])] with pytest.raises(ValueError, match='Input Kraus ops'): _ = cirq.KrausChannel(kraus_ops=ops, key='m') @@ -147,9 +135,6 @@ def test_nonqubit_kraus_ops_fails(): def test_validate(): # Not quite CPTP. - ops = [ - np.array([[1, 0], [0, 0]]), - np.array([[0, 0], [0, 0.9]]), - ] + ops = [np.array([[1, 0], [0, 0]]), np.array([[0, 0], [0, 0.9]])] with pytest.raises(ValueError, match='CPTP map'): _ = cirq.KrausChannel(kraus_ops=ops, key='m', validate=True) diff --git a/cirq-core/cirq/ops/linear_combinations.py b/cirq-core/cirq/ops/linear_combinations.py index 3249d8ef512..9e7db8ba287 100644 --- a/cirq-core/cirq/ops/linear_combinations.py +++ b/cirq-core/cirq/ops/linear_combinations.py @@ -134,12 +134,7 @@ def __pow__(self, exponent: int) -> 'LinearCombinationOfGates': return NotImplemented if self.num_qubits() != 1: return NotImplemented - pauli_basis = { - identity.I, - pauli_gates.X, - pauli_gates.Y, - pauli_gates.Z, - } + pauli_basis = {identity.I, pauli_gates.X, pauli_gates.Y, pauli_gates.Z} if not set(self.keys()).issubset(pauli_basis): return NotImplemented @@ -782,9 +777,7 @@ def _json_dict_(self) -> Dict[str, Any]: for projector_dict, scalar in dict(self._linear_dict).items(): key = [[k, v] for k, v in dict(projector_dict).items()] linear_dict.append([key, scalar]) - return { - 'linear_dict': linear_dict, - } + return {'linear_dict': linear_dict} @classmethod def _from_json_dict_(cls, linear_dict, **kwargs): @@ -839,9 +832,7 @@ def matrix(self, projector_qids: Optional[Iterable[raw_types.Qid]] = None) -> cs ) def expectation_from_state_vector( - self, - state_vector: np.ndarray, - qid_map: Mapping[raw_types.Qid, int], + self, state_vector: np.ndarray, qid_map: Mapping[raw_types.Qid, int] ) -> float: """Compute the expectation value of this ProjectorSum given a state vector. @@ -865,9 +856,7 @@ def expectation_from_state_vector( ) def expectation_from_density_matrix( - self, - state: np.ndarray, - qid_map: Mapping[raw_types.Qid, int], + self, state: np.ndarray, qid_map: Mapping[raw_types.Qid, int] ) -> float: """Expectation of the sum of projections from a density matrix. diff --git a/cirq-core/cirq/ops/linear_combinations_test.py b/cirq-core/cirq/ops/linear_combinations_test.py index 74e88bed551..bcf9cbc276d 100644 --- a/cirq-core/cirq/ops/linear_combinations_test.py +++ b/cirq-core/cirq/ops/linear_combinations_test.py @@ -70,17 +70,7 @@ def test_linear_combination_of_gates_rejects_inconsistent_gates(terms): combination[gate] += coefficient -@pytest.mark.parametrize( - 'gate', - ( - cirq.X, - cirq.Y, - cirq.XX, - cirq.CZ, - cirq.CSWAP, - cirq.FREDKIN, - ), -) +@pytest.mark.parametrize('gate', (cirq.X, cirq.Y, cirq.XX, cirq.CZ, cirq.CSWAP, cirq.FREDKIN)) def test_empty_linear_combination_of_gates_accepts_all_gates(gate): combination = cirq.LinearCombinationOfGates({}) combination[gate] = -0.5j @@ -132,10 +122,7 @@ def test_linear_combination_of_gates_has_correct_matrix(terms, expected_matrix): np.array([[0, np.sqrt(-1j)], [np.sqrt(1j), 0]]), ), ( - { - cirq.IdentityGate(2): np.sqrt(0.5), - cirq.YY: -1j * np.sqrt(0.5), - }, + {cirq.IdentityGate(2): np.sqrt(0.5), cirq.YY: -1j * np.sqrt(0.5)}, np.sqrt(0.5) * np.array([[1, 0, 0, 1j], [0, 1, -1j, 0], [0, -1j, 1, 0], [1j, 0, 0, 1]]), ), ), @@ -179,75 +166,17 @@ def test_linear_combination_of_gates_has_correct_pauli_expansion(terms, expected @pytest.mark.parametrize( 'terms, exponent, expected_terms', ( + ({cirq.X: 1}, 2, {cirq.I: 1}), + ({cirq.X: 1}, 3, {cirq.X: 1}), + ({cirq.Y: 0.5}, 10, {cirq.I: 2**-10}), + ({cirq.Y: 0.5}, 11, {cirq.Y: 2**-11}), ( - { - cirq.X: 1, - }, - 2, - { - cirq.I: 1, - }, - ), - ( - { - cirq.X: 1, - }, - 3, - { - cirq.X: 1, - }, - ), - ( - { - cirq.Y: 0.5, - }, - 10, - { - cirq.I: 2**-10, - }, - ), - ( - { - cirq.Y: 0.5, - }, - 11, - { - cirq.Y: 2**-11, - }, - ), - ( - { - cirq.I: 1, - cirq.X: 2, - cirq.Y: 3, - cirq.Z: 4, - }, - 2, - { - cirq.I: 30, - cirq.X: 4, - cirq.Y: 6, - cirq.Z: 8, - }, - ), - ( - { - cirq.X: 1, - cirq.Y: 1j, - }, + {cirq.I: 1, cirq.X: 2, cirq.Y: 3, cirq.Z: 4}, 2, - {}, - ), - ( - { - cirq.X: 0.4, - cirq.Y: 0.4, - }, - 0, - { - cirq.I: 1, - }, + {cirq.I: 30, cirq.X: 4, cirq.Y: 6, cirq.Z: 8}, ), + ({cirq.X: 1, cirq.Y: 1j}, 2, {}), + ({cirq.X: 0.4, cirq.Y: 0.4}, 0, {cirq.I: 1}), ), ) def test_linear_combinations_of_gates_valid_powers(terms, exponent, expected_terms): @@ -262,37 +191,11 @@ def test_linear_combinations_of_gates_valid_powers(terms, exponent, expected_ter 'terms, exponent', ( ({}, 2), - ( - { - cirq.H: 1, - }, - 2, - ), - ( - { - cirq.CNOT: 2, - }, - 2, - ), - ( - { - cirq.X: 1, - cirq.S: -1, - }, - 2, - ), - ( - { - cirq.X: 1, - }, - -1, - ), - ( - { - cirq.Y: 1, - }, - sympy.Symbol('k'), - ), + ({cirq.H: 1}, 2), + ({cirq.CNOT: 2}, 2), + ({cirq.X: 1, cirq.S: -1}, 2), + ({cirq.X: 1}, -1), + ({cirq.Y: 1}, sympy.Symbol('k')), ), ) def test_linear_combinations_of_gates_invalid_powers(terms, exponent): @@ -303,10 +206,7 @@ def test_linear_combinations_of_gates_invalid_powers(terms, exponent): @pytest.mark.parametrize( 'terms, is_parameterized, parameter_names', - [ - ({cirq.H: 1}, False, set()), - ({cirq.X ** sympy.Symbol('t'): 1}, True, {'t'}), - ], + [({cirq.H: 1}, False, set()), ({cirq.X ** sympy.Symbol('t'): 1}, True, {'t'})], ) @pytest.mark.parametrize('resolve_fn', [cirq.resolve_parameters, cirq.resolve_parameters_once]) def test_parameterized_linear_combination_of_gates( @@ -471,15 +371,18 @@ def test_linear_combination_of_operations_has_correct_qubits(terms, expected_qub ({}, np.array([0])), ( {cirq.I(q0): 2, cirq.X(q0): 3, cirq.Y(q0): 4, cirq.Z(q0): 5j}, + # fmt: off np.array( [ [2 + 5j, 3 - 4j], [3 + 4j, 2 - 5j], ] ), + # fmt: on ), ( {cirq.X(q0): 2, cirq.Y(q1): 3}, + # fmt: off np.array( [ [0, -3j, 2, 0], @@ -488,6 +391,7 @@ def test_linear_combination_of_operations_has_correct_qubits(terms, expected_qub [0, 2, 3j, 0], ] ), + # fmt: on ), ({cirq.XX(q0, q1): 0.5, cirq.YY(q0, q1): -0.5}, np.rot90(np.diag([1, 0, 0, 1]))), ({cirq.CCZ(q0, q1, q2): 3j}, np.diag([3j, 3j, 3j, 3j, 3j, 3j, 3j, -3j])), @@ -768,75 +672,17 @@ def test_linear_combination_of_operations_has_correct_pauli_expansion(terms, exp @pytest.mark.parametrize( 'terms, exponent, expected_terms', ( + ({cirq.X(q0): 1}, 2, {cirq.I(q0): 1}), + ({cirq.X(q0): 1}, 3, {cirq.X(q0): 1}), + ({cirq.Y(q0): 0.5}, 10, {cirq.I(q0): 2**-10}), + ({cirq.Y(q0): 0.5}, 11, {cirq.Y(q0): 2**-11}), ( - { - cirq.X(q0): 1, - }, - 2, - { - cirq.I(q0): 1, - }, - ), - ( - { - cirq.X(q0): 1, - }, - 3, - { - cirq.X(q0): 1, - }, - ), - ( - { - cirq.Y(q0): 0.5, - }, - 10, - { - cirq.I(q0): 2**-10, - }, - ), - ( - { - cirq.Y(q0): 0.5, - }, - 11, - { - cirq.Y(q0): 2**-11, - }, - ), - ( - { - cirq.I(q0): 1, - cirq.X(q0): 2, - cirq.Y(q0): 3, - cirq.Z(q0): 4, - }, - 2, - { - cirq.I(q0): 30, - cirq.X(q0): 4, - cirq.Y(q0): 6, - cirq.Z(q0): 8, - }, - ), - ( - { - cirq.X(q0): 1, - cirq.Y(q0): 1j, - }, + {cirq.I(q0): 1, cirq.X(q0): 2, cirq.Y(q0): 3, cirq.Z(q0): 4}, 2, - {}, - ), - ( - { - cirq.Y(q1): 2, - cirq.Z(q1): 3, - }, - 0, - { - cirq.I(q1): 1, - }, + {cirq.I(q0): 30, cirq.X(q0): 4, cirq.Y(q0): 6, cirq.Z(q0): 8}, ), + ({cirq.X(q0): 1, cirq.Y(q0): 1j}, 2, {}), + ({cirq.Y(q1): 2, cirq.Z(q1): 3}, 0, {cirq.I(q1): 1}), ), ) def test_linear_combinations_of_operations_valid_powers(terms, exponent, expected_terms): @@ -851,44 +697,12 @@ def test_linear_combinations_of_operations_valid_powers(terms, exponent, expecte 'terms, exponent', ( ({}, 2), - ( - { - cirq.H(q0): 1, - }, - 2, - ), - ( - { - cirq.CNOT(q0, q1): 2, - }, - 2, - ), - ( - { - cirq.X(q0): 1, - cirq.S(q0): -1, - }, - 2, - ), - ( - { - cirq.X(q0): 1, - cirq.Y(q1): 1, - }, - 2, - ), - ( - { - cirq.Z(q0): 1, - }, - -1, - ), - ( - { - cirq.X(q0): 1, - }, - sympy.Symbol('k'), - ), + ({cirq.H(q0): 1}, 2), + ({cirq.CNOT(q0, q1): 2}, 2), + ({cirq.X(q0): 1, cirq.S(q0): -1}, 2), + ({cirq.X(q0): 1, cirq.Y(q1): 1}, 2), + ({cirq.Z(q0): 1}, -1), + ({cirq.X(q0): 1}, sympy.Symbol('k')), ), ) def test_linear_combinations_of_operations_invalid_powers(terms, exponent): @@ -929,12 +743,7 @@ def test_parameterized_linear_combination_of_ops( cirq.IdentityGate(2).on(q0, q1): 1, cirq.PauliString({q1: cirq.X}): 1, cirq.PauliString({q0: cirq.Z}): 1, - cirq.PauliString( - { - q0: cirq.Z, - q1: cirq.X, - } - ): -1, + cirq.PauliString({q0: cirq.Z, q1: cirq.X}): -1, } ), ), @@ -1168,12 +977,7 @@ def test_add_number_paulistring(): assert ( cirq.X(a) + 2 == 2 + cirq.X(a) - == cirq.PauliSum.from_pauli_strings( - [ - cirq.PauliString() * 2, - cirq.PauliString({a: cirq.X}), - ] - ) + == cirq.PauliSum.from_pauli_strings([cirq.PauliString() * 2, cirq.PauliString({a: cirq.X})]) ) @@ -1628,8 +1432,7 @@ def test_expectation_from_density_matrix_basis_states(): psum.expectation_from_density_matrix(np.array([[1, 0], [0, 0]], dtype=complex), q_map), 3 ) np.testing.assert_allclose( - psum.expectation_from_density_matrix(np.array([[0, 0], [0, 1]], dtype=complex), q_map), - -3, + psum.expectation_from_density_matrix(np.array([[0, 0], [0, 1]], dtype=complex), q_map), -3 ) diff --git a/cirq-core/cirq/ops/matrix_gates.py b/cirq-core/cirq/ops/matrix_gates.py index bb6d53207fe..e4fe85d82dd 100644 --- a/cirq-core/cirq/ops/matrix_gates.py +++ b/cirq-core/cirq/ops/matrix_gates.py @@ -93,10 +93,7 @@ def __init__( raise ValueError(f'Not a unitary matrix: {self._matrix}') def _json_dict_(self) -> Dict[str, Any]: - return { - 'matrix': self._matrix.tolist(), - 'qid_shape': self._qid_shape, - } + return {'matrix': self._matrix.tolist(), 'qid_shape': self._qid_shape} @classmethod def _from_json_dict_(cls, matrix, qid_shape, **kwargs): diff --git a/cirq-core/cirq/ops/measurement_gate.py b/cirq-core/cirq/ops/measurement_gate.py index aa3f8851e7e..66f16080ea5 100644 --- a/cirq-core/cirq/ops/measurement_gate.py +++ b/cirq-core/cirq/ops/measurement_gate.py @@ -105,9 +105,7 @@ def _with_key_path_prefix_(self, prefix: Tuple[str, ...]): return self.with_key(self.mkey._with_key_path_prefix_(prefix)) def _with_rescoped_keys_( - self, - path: Tuple[str, ...], - bindable_keys: FrozenSet['cirq.MeasurementKey'], + self, path: Tuple[str, ...], bindable_keys: FrozenSet['cirq.MeasurementKey'] ): return self.with_key(protocols.with_rescoped_keys(self.mkey, path, bindable_keys)) diff --git a/cirq-core/cirq/ops/measurement_gate_test.py b/cirq-core/cirq/ops/measurement_gate_test.py index 5e8e666f879..ae29c4f792d 100644 --- a/cirq-core/cirq/ops/measurement_gate_test.py +++ b/cirq-core/cirq/ops/measurement_gate_test.py @@ -21,18 +21,11 @@ @pytest.mark.parametrize( 'key', - [ - 'q0_1_0', - cirq.MeasurementKey(name='q0_1_0'), - cirq.MeasurementKey(path=('a', 'b'), name='c'), - ], + ['q0_1_0', cirq.MeasurementKey(name='q0_1_0'), cirq.MeasurementKey(path=('a', 'b'), name='c')], ) def test_eval_repr(key): # Basic safeguard against repr-inequality. - op = cirq.GateOperation( - gate=cirq.MeasurementGate(1, key), - qubits=[cirq.GridQubit(0, 1)], - ) + op = cirq.GateOperation(gate=cirq.MeasurementGate(1, key), qubits=[cirq.GridQubit(0, 1)]) cirq.testing.assert_equivalent_repr(op) @@ -377,26 +370,20 @@ def test_act_on_stabilizer_ch_form(): cirq.testing.assert_all_implemented_act_on_effects_match_unitary(m) args = cirq.ActOnStabilizerCHFormArgs( - qubits=cirq.LineQubit.range(5), - prng=np.random.RandomState(), - initial_state=0, + qubits=cirq.LineQubit.range(5), prng=np.random.RandomState(), initial_state=0 ) cirq.act_on(m, args) assert args.log_of_measurement_results == {'out': [1, 0]} args = cirq.ActOnStabilizerCHFormArgs( - qubits=cirq.LineQubit.range(5), - prng=np.random.RandomState(), - initial_state=8, + qubits=cirq.LineQubit.range(5), prng=np.random.RandomState(), initial_state=8 ) cirq.act_on(m, args) assert args.log_of_measurement_results == {'out': [1, 1]} args = cirq.ActOnStabilizerCHFormArgs( - qubits=cirq.LineQubit.range(5), - prng=np.random.RandomState(), - initial_state=10, + qubits=cirq.LineQubit.range(5), prng=np.random.RandomState(), initial_state=10 ) cirq.act_on(m, args) datastore = cast(cirq.ClassicalDataDictionaryStore, args.classical_data) diff --git a/cirq-core/cirq/ops/mixed_unitary_channel.py b/cirq-core/cirq/ops/mixed_unitary_channel.py index 5f5bdb9b9e2..45ae0d269d6 100644 --- a/cirq-core/cirq/ops/mixed_unitary_channel.py +++ b/cirq-core/cirq/ops/mixed_unitary_channel.py @@ -67,15 +67,9 @@ def __eq__(self, other) -> bool: return NotImplemented if self._key != other._key: return False - if not np.allclose( - [m[0] for m in self._mixture], - [m[0] for m in other._mixture], - ): + if not np.allclose([m[0] for m in self._mixture], [m[0] for m in other._mixture]): return False - return np.allclose( - [m[1] for m in self._mixture], - [m[1] for m in other._mixture], - ) + return np.allclose([m[1] for m in self._mixture], [m[1] for m in other._mixture]) def num_qubits(self) -> int: return self._num_qubits @@ -111,13 +105,10 @@ def _with_key_path_prefix_(self, prefix: Tuple[str, ...]): ) def _with_rescoped_keys_( - self, - path: Tuple[str, ...], - bindable_keys: FrozenSet['cirq.MeasurementKey'], + self, path: Tuple[str, ...], bindable_keys: FrozenSet['cirq.MeasurementKey'] ): return MixedUnitaryChannel( - mixture=self._mixture, - key=protocols.with_rescoped_keys(self._key, path, bindable_keys), + mixture=self._mixture, key=protocols.with_rescoped_keys(self._key, path, bindable_keys) ) def __str__(self): diff --git a/cirq-core/cirq/ops/mixed_unitary_channel_test.py b/cirq-core/cirq/ops/mixed_unitary_channel_test.py index 03b671a3b49..53d862c1e97 100644 --- a/cirq-core/cirq/ops/mixed_unitary_channel_test.py +++ b/cirq-core/cirq/ops/mixed_unitary_channel_test.py @@ -33,10 +33,7 @@ def test_matrix_mixture_equality(): assert mm_a1 != mm_b1 assert mm_a2 != mm_b1 - mix = [ - (0.5, np.array([[1, 0], [0, 1]])), - (0.5, np.array([[0, 1], [1, 0]])), - ] + mix = [(0.5, np.array([[1, 0], [0, 1]])), (0.5, np.array([[0, 1], [1, 0]]))] half_flip = cirq.MixedUnitaryChannel(mix) mix_inv = list(reversed(mix)) half_flip_inv = cirq.MixedUnitaryChannel(mix_inv) @@ -64,10 +61,7 @@ def test_matrix_mixture_remap_keys(): def test_matrix_mixture_from_unitaries(): q0 = cirq.LineQubit(0) - mix = [ - (0.5, np.array([[1, 0], [0, 1]])), - (0.5, np.array([[0, 1], [1, 0]])), - ] + mix = [(0.5, np.array([[1, 0], [0, 1]])), (0.5, np.array([[0, 1], [1, 0]]))] half_flip = cirq.MixedUnitaryChannel(mix, key='flip') assert cirq.measurement_key_name(half_flip) == 'flip' @@ -80,10 +74,7 @@ def test_matrix_mixture_from_unitaries(): def test_matrix_mixture_str(): - mix = [ - (0.5, np.array([[1, 0], [0, 1]])), - (0.5, np.array([[0, 1], [1, 0]])), - ] + mix = [(0.5, np.array([[1, 0], [0, 1]])), (0.5, np.array([[0, 1], [1, 0]]))] half_flip = cirq.MixedUnitaryChannel(mix) assert ( str(half_flip) @@ -131,29 +122,20 @@ def test_mix_bad_prob_fails(): def test_mix_mismatch_fails(): op2 = np.zeros((4, 4)) op2[1][1] = 1 - mix = [ - (0.5, np.array([[1, 0], [0, 0]])), - (0.5, op2), - ] + mix = [(0.5, np.array([[1, 0], [0, 0]])), (0.5, op2)] with pytest.raises(ValueError, match='Inconsistent unitary shapes'): _ = cirq.MixedUnitaryChannel(mixture=mix, key='m') def test_nonqubit_mixture_fails(): - mix = [ - (0.5, np.array([[1, 0, 0], [0, 1, 0]])), - (0.5, np.array([[0, 1, 0], [1, 0, 0]])), - ] + mix = [(0.5, np.array([[1, 0, 0], [0, 1, 0]])), (0.5, np.array([[0, 1, 0], [1, 0, 0]]))] with pytest.raises(ValueError, match='Input mixture'): _ = cirq.MixedUnitaryChannel(mixture=mix, key='m') def test_validate(): - mix = [ - (0.5, np.array([[1, 0], [0, 0]])), - (0.5, np.array([[0, 0], [0, 1]])), - ] + mix = [(0.5, np.array([[1, 0], [0, 0]])), (0.5, np.array([[0, 0], [0, 1]]))] with pytest.raises(ValueError, match='non-unitary'): _ = cirq.MixedUnitaryChannel(mixture=mix, key='m', validate=True) diff --git a/cirq-core/cirq/ops/named_qubit_test.py b/cirq-core/cirq/ops/named_qubit_test.py index 392c3635ee5..12611b16cab 100644 --- a/cirq-core/cirq/ops/named_qubit_test.py +++ b/cirq-core/cirq/ops/named_qubit_test.py @@ -105,11 +105,7 @@ def test_named_qubit_range(): assert qubits == [cirq.NamedQubit('a0'), cirq.NamedQubit('a1')] qubits = cirq.NamedQubit.range(-1, 4, 2, prefix='a') - assert qubits == [ - cirq.NamedQubit('a-1'), - cirq.NamedQubit('a1'), - cirq.NamedQubit('a3'), - ] + assert qubits == [cirq.NamedQubit('a-1'), cirq.NamedQubit('a1'), cirq.NamedQubit('a3')] def test_named_qid_range(): @@ -135,11 +131,6 @@ def test_named_qid_range(): def test_to_json(): - assert cirq.NamedQubit('c')._json_dict_() == { - 'name': 'c', - } - - assert cirq.NamedQid('c', dimension=3)._json_dict_() == { - 'name': 'c', - 'dimension': 3, - } + assert cirq.NamedQubit('c')._json_dict_() == {'name': 'c'} + + assert cirq.NamedQid('c', dimension=3)._json_dict_() == {'name': 'c', 'dimension': 3} diff --git a/cirq-core/cirq/ops/op_tree_test.py b/cirq-core/cirq/ops/op_tree_test.py index 3ebe5cc8732..60609e356c2 100644 --- a/cirq-core/cirq/ops/op_tree_test.py +++ b/cirq-core/cirq/ops/op_tree_test.py @@ -56,11 +56,7 @@ def test_flatten_to_ops_or_moments(): operations = [ cirq.GateOperation(cirq.SingleQubitGate(), [cirq.NamedQubit(str(i))]) for i in range(10) ] - op_tree = [ - operations[0], - cirq.Moment(operations[1:5]), - operations[5:], - ] + op_tree = [operations[0], cirq.Moment(operations[1:5]), operations[5:]] output = [operations[0], cirq.Moment(operations[1:5])] + operations[5:] assert list(cirq.flatten_to_ops_or_moments(op_tree)) == output assert list(cirq.flatten_op_tree(op_tree, preserve_moments=True)) == output diff --git a/cirq-core/cirq/ops/parallel_gate_test.py b/cirq-core/cirq/ops/parallel_gate_test.py index b2d807b90cd..1e8255c78e4 100644 --- a/cirq-core/cirq/ops/parallel_gate_test.py +++ b/cirq-core/cirq/ops/parallel_gate_test.py @@ -48,10 +48,7 @@ def test_invalid_parallel_gate_operation(gate, num_copies, qubits, error_msg): @pytest.mark.parametrize( 'gate, num_copies, qubits', - [ - (cirq.X, 2, cirq.LineQubit.range(2)), - (cirq.H**0.5, 4, cirq.LineQubit.range(4)), - ], + [(cirq.X, 2, cirq.LineQubit.range(2)), (cirq.H**0.5, 4, cirq.LineQubit.range(4))], ) def test_decompose(gate, num_copies, qubits): g = cirq.ParallelGate(gate, num_copies) @@ -112,9 +109,7 @@ def test_unitary(gate, num_copies, qubits): step = gate.num_qubits() qubit_lists = [qubits[i * step : (i + 1) * step] for i in range(num_copies)] np.testing.assert_allclose( - cirq.unitary(g), - cirq.unitary(cirq.Circuit(gate.on_each(qubit_lists))), - atol=1e-8, + cirq.unitary(g), cirq.unitary(cirq.Circuit(gate.on_each(qubit_lists))), atol=1e-8 ) @@ -147,15 +142,7 @@ def test_equivalent_circuit(): cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent(oldc, newc, atol=1e-6) -@pytest.mark.parametrize( - 'gate, num_copies', - [ - (cirq.X, 1), - (cirq.Y, 2), - (cirq.Z, 3), - (cirq.H, 4), - ], -) +@pytest.mark.parametrize('gate, num_copies', [(cirq.X, 1), (cirq.Y, 2), (cirq.Z, 3), (cirq.H, 4)]) def test_parallel_gate_operation_is_consistent(gate, num_copies): cirq.testing.assert_implements_consistent_protocols(cirq.ParallelGate(gate, num_copies)) @@ -172,15 +159,7 @@ def test_trace_distance(): assert cirq.approx_eq(cirq.trace_distance_bound(spg), 1.0) -@pytest.mark.parametrize( - 'gate, num_copies', - [ - (cirq.X, 1), - (cirq.Y, 2), - (cirq.Z, 3), - (cirq.H, 4), - ], -) +@pytest.mark.parametrize('gate, num_copies', [(cirq.X, 1), (cirq.Y, 2), (cirq.Z, 3), (cirq.H, 4)]) def test_parallel_gate_op(gate, num_copies): qubits = cirq.LineQubit.range(num_copies * gate.num_qubits()) assert cirq.parallel_gate_op(gate, *qubits) == cirq.ParallelGate(gate, num_copies).on(*qubits) diff --git a/cirq-core/cirq/ops/parity_gates.py b/cirq-core/cirq/ops/parity_gates.py index e09e60a3434..8b28a74b35f 100644 --- a/cirq-core/cirq/ops/parity_gates.py +++ b/cirq-core/cirq/ops/parity_gates.py @@ -291,10 +291,7 @@ def _decompose_(self, qubits): )(qubits[0], qubits[1]) def _eigen_components(self) -> List[Tuple[float, np.ndarray]]: - return [ - (0, np.diag([1, 0, 0, 1])), - (1, np.diag([0, 1, 1, 0])), - ] + return [(0, np.diag([1, 0, 0, 1])), (1, np.diag([0, 1, 1, 0]))] def _eigen_shifts(self): return [0, 1] diff --git a/cirq-core/cirq/ops/parity_gates_test.py b/cirq-core/cirq/ops/parity_gates_test.py index f04502fa3b9..5f13d1a3d96 100644 --- a/cirq-core/cirq/ops/parity_gates_test.py +++ b/cirq-core/cirq/ops/parity_gates_test.py @@ -21,14 +21,7 @@ import cirq -@pytest.mark.parametrize( - 'eigen_gate_type', - [ - cirq.XXPowGate, - cirq.YYPowGate, - cirq.ZZPowGate, - ], -) +@pytest.mark.parametrize('eigen_gate_type', [cirq.XXPowGate, cirq.YYPowGate, cirq.ZZPowGate]) def test_eigen_gates_consistent_protocols(eigen_gate_type): cirq.testing.assert_eigengate_implements_consistent_protocols(eigen_gate_type) @@ -91,11 +84,7 @@ def test_xx_matrix(): def test_xx_diagrams(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') - circuit = cirq.Circuit( - cirq.XX(a, b), - cirq.XX(a, b) ** 3, - cirq.XX(a, b) ** 0.5, - ) + circuit = cirq.Circuit(cirq.XX(a, b), cirq.XX(a, b) ** 3, cirq.XX(a, b) ** 0.5) cirq.testing.assert_has_diagram( circuit, """ @@ -167,11 +156,7 @@ def test_yy_matrix(): def test_yy_diagrams(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') - circuit = cirq.Circuit( - cirq.YY(a, b), - cirq.YY(a, b) ** 3, - cirq.YY(a, b) ** 0.5, - ) + circuit = cirq.Circuit(cirq.YY(a, b), cirq.YY(a, b) ** 3, cirq.YY(a, b) ** 0.5) cirq.testing.assert_has_diagram( circuit, """ @@ -243,11 +228,7 @@ def test_zz_matrix(): def test_zz_diagrams(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') - circuit = cirq.Circuit( - cirq.ZZ(a, b), - cirq.ZZ(a, b) ** 3, - cirq.ZZ(a, b) ** 0.5, - ) + circuit = cirq.Circuit(cirq.ZZ(a, b), cirq.ZZ(a, b) ** 3, cirq.ZZ(a, b) ** 0.5) cirq.testing.assert_has_diagram( circuit, """ diff --git a/cirq-core/cirq/ops/pauli_gates.py b/cirq-core/cirq/ops/pauli_gates.py index 7fa27f5fae3..12c82e7c8c5 100644 --- a/cirq-core/cirq/ops/pauli_gates.py +++ b/cirq-core/cirq/ops/pauli_gates.py @@ -128,10 +128,7 @@ def _from_json_dict_(cls, exponent, global_shift, **kwargs): def basis(self: '_PauliX') -> Dict[int, '_XEigenState']: from cirq.value.product_state import _XEigenState - return { - +1: _XEigenState(+1), - -1: _XEigenState(-1), - } + return {+1: _XEigenState(+1), -1: _XEigenState(-1)} class _PauliY(Pauli, common_gates.YPowGate): @@ -155,10 +152,7 @@ def _from_json_dict_(cls, exponent, global_shift, **kwargs): def basis(self: '_PauliY') -> Dict[int, '_YEigenState']: from cirq.value.product_state import _YEigenState - return { - +1: _YEigenState(+1), - -1: _YEigenState(-1), - } + return {+1: _YEigenState(+1), -1: _YEigenState(-1)} class _PauliZ(Pauli, common_gates.ZPowGate): @@ -182,10 +176,7 @@ def _from_json_dict_(cls, exponent, global_shift, **kwargs): def basis(self: '_PauliZ') -> Dict[int, '_ZEigenState']: from cirq.value.product_state import _ZEigenState - return { - +1: _ZEigenState(+1), - -1: _ZEigenState(-1), - } + return {+1: _ZEigenState(+1), -1: _ZEigenState(-1)} X = _PauliX() diff --git a/cirq-core/cirq/ops/pauli_measurement_gate.py b/cirq-core/cirq/ops/pauli_measurement_gate.py index ca72c1506d1..02975dd1192 100644 --- a/cirq-core/cirq/ops/pauli_measurement_gate.py +++ b/cirq-core/cirq/ops/pauli_measurement_gate.py @@ -99,9 +99,7 @@ def _with_key_path_prefix_(self, prefix: Tuple[str, ...]) -> 'PauliMeasurementGa return self.with_key(self.mkey._with_key_path_prefix_(prefix)) def _with_rescoped_keys_( - self, - path: Tuple[str, ...], - bindable_keys: FrozenSet['cirq.MeasurementKey'], + self, path: Tuple[str, ...], bindable_keys: FrozenSet['cirq.MeasurementKey'] ) -> 'PauliMeasurementGate': return self.with_key(protocols.with_rescoped_keys(self.mkey, path, bindable_keys)) @@ -180,17 +178,11 @@ def _value_equality_values_(self) -> Any: return self.key, self._observable def _json_dict_(self) -> Dict[str, Any]: - return { - 'observable': self._observable, - 'key': self.key, - } + return {'observable': self._observable, 'key': self.key} @classmethod def _from_json_dict_(cls, observable, key, **kwargs) -> 'PauliMeasurementGate': - return cls( - observable=observable, - key=value.MeasurementKey.parse_serialized(key), - ) + return cls(observable=observable, key=value.MeasurementKey.parse_serialized(key)) def _default_measurement_key(qubits: Iterable[raw_types.Qid]) -> str: diff --git a/cirq-core/cirq/ops/pauli_measurement_gate_test.py b/cirq-core/cirq/ops/pauli_measurement_gate_test.py index b7313c72fe7..a304f18dbee 100644 --- a/cirq-core/cirq/ops/pauli_measurement_gate_test.py +++ b/cirq-core/cirq/ops/pauli_measurement_gate_test.py @@ -19,11 +19,7 @@ @pytest.mark.parametrize( 'key', - [ - 'q0_1_0', - cirq.MeasurementKey(name='q0_1_0'), - cirq.MeasurementKey(path=('a', 'b'), name='c'), - ], + ['q0_1_0', cirq.MeasurementKey(name='q0_1_0'), cirq.MeasurementKey(path=('a', 'b'), name='c')], ) def test_eval_repr(key): # Basic safeguard against repr-inequality. @@ -128,11 +124,7 @@ def test_measurement_gate_diagram(): @pytest.mark.parametrize('observable', [[cirq.X], [cirq.X, cirq.Y, cirq.Z]]) @pytest.mark.parametrize( 'key', - [ - 'q0_1_0', - cirq.MeasurementKey(name='q0_1_0'), - cirq.MeasurementKey(path=('a', 'b'), name='c'), - ], + ['q0_1_0', cirq.MeasurementKey(name='q0_1_0'), cirq.MeasurementKey(path=('a', 'b'), name='c')], ) def test_consistent_protocols(observable, key): gate = cirq.PauliMeasurementGate(observable, key=key) diff --git a/cirq-core/cirq/ops/pauli_string.py b/cirq-core/cirq/ops/pauli_string.py index 8ab23744bbc..c450771834c 100644 --- a/cirq-core/cirq/ops/pauli_string.py +++ b/cirq-core/cirq/ops/pauli_string.py @@ -90,12 +90,7 @@ """, ) -PAULI_GATE_LIKE = Union[ - 'cirq.Pauli', - 'cirq.IdentityGate', - str, - int, -] +PAULI_GATE_LIKE = Union['cirq.Pauli', 'cirq.IdentityGate', str, int,] document( PAULI_GATE_LIKE, # type: ignore """An object that can be interpreted as a Pauli gate. @@ -1112,8 +1107,7 @@ def frozen(self) -> 'cirq.PauliString': def mutable_copy(self) -> 'cirq.MutablePauliString': """Returns a new cirq.MutablePauliString with the same contents.""" return MutablePauliString( - coefficient=self.coefficient, - pauli_int_dict=dict(self.pauli_int_dict), + coefficient=self.coefficient, pauli_int_dict=dict(self.pauli_int_dict) ) def items(self) -> Iterator[Tuple[TKey, Union['cirq.Pauli', 'cirq.IdentityGate']]]: @@ -1354,10 +1348,7 @@ def transform_qubits( """ new_dict = {func(q): p for q, p in self.pauli_int_dict.items()} if not inplace: - return MutablePauliString( - coefficient=self.coefficient, - pauli_int_dict=new_dict, - ) + return MutablePauliString(coefficient=self.coefficient, pauli_int_dict=new_dict) result = cast('cirq.MutablePauliString[TKeyNew]', self) result.pauli_int_dict = new_dict return result @@ -1429,9 +1420,7 @@ def _decompose_into_cliffords(op: 'cirq.Operation') -> List['cirq.Operation']: def _pass_operation_over( - pauli_map: Dict[TKey, pauli_gates.Pauli], - op: 'cirq.Operation', - after_to_before: bool = False, + pauli_map: Dict[TKey, pauli_gates.Pauli], op: 'cirq.Operation', after_to_before: bool = False ) -> bool: if isinstance(op, gate_operation.GateOperation): gate = op.gate diff --git a/cirq-core/cirq/ops/pauli_string_phasor.py b/cirq-core/cirq/ops/pauli_string_phasor.py index 319b7de35eb..d62e087072f 100644 --- a/cirq-core/cirq/ops/pauli_string_phasor.py +++ b/cirq-core/cirq/ops/pauli_string_phasor.py @@ -95,11 +95,7 @@ def exponent_relative(self) -> Union[int, float, sympy.Basic]: return self.gate.exponent_relative def _value_equality_values_(self): - return ( - self.pauli_string, - self.exponent_neg, - self.exponent_pos, - ) + return (self.pauli_string, self.exponent_neg, self.exponent_pos) def equal_up_to_global_phase(self, other): """Checks equality of two PauliStringPhasors, up to global phase.""" @@ -252,11 +248,7 @@ def dense_pauli_string(self): return self._dense_pauli_string def _value_equality_values_(self): - return ( - self.dense_pauli_string, - self.exponent_neg, - self.exponent_pos, - ) + return (self.dense_pauli_string, self.exponent_neg, self.exponent_pos) def equal_up_to_global_phase(self, other): """Checks equality of two PauliStringPhasors, up to global phase.""" diff --git a/cirq-core/cirq/ops/pauli_string_phasor_test.py b/cirq-core/cirq/ops/pauli_string_phasor_test.py index 6e0e97fe79d..6262c5c5bb1 100644 --- a/cirq-core/cirq/ops/pauli_string_phasor_test.py +++ b/cirq-core/cirq/ops/pauli_string_phasor_test.py @@ -80,15 +80,9 @@ def test_equal_up_to_global_phase(): cirq.PauliString({a: cirq.X}), exponent_pos=-0.125, exponent_neg=0.125 ), ], - [ - cirq.PauliStringPhasor(cirq.PauliString({a: cirq.X})), - ], - [ - cirq.PauliStringPhasor(cirq.PauliString({a: cirq.Y}), exponent_neg=0.25), - ], - [ - cirq.PauliStringPhasor(cirq.PauliString({a: cirq.X, b: cirq.Y}), exponent_neg=0.25), - ], + [cirq.PauliStringPhasor(cirq.PauliString({a: cirq.X}))], + [cirq.PauliStringPhasor(cirq.PauliString({a: cirq.Y}), exponent_neg=0.25)], + [cirq.PauliStringPhasor(cirq.PauliString({a: cirq.X, b: cirq.Y}), exponent_neg=0.25)], ] for g1 in groups: for e1 in g1: @@ -259,14 +253,12 @@ def test_manual_default_decompose(): q0, q1, q2 = _make_qubits(3) mat = cirq.Circuit( - cirq.PauliStringPhasor(cirq.PauliString({q0: cirq.Z})) ** 0.25, - cirq.Z(q0) ** -0.25, + cirq.PauliStringPhasor(cirq.PauliString({q0: cirq.Z})) ** 0.25, cirq.Z(q0) ** -0.25 ).unitary() cirq.testing.assert_allclose_up_to_global_phase(mat, np.eye(2), rtol=1e-7, atol=1e-7) mat = cirq.Circuit( - cirq.PauliStringPhasor(cirq.PauliString({q0: cirq.Y})) ** 0.25, - cirq.Y(q0) ** -0.25, + cirq.PauliStringPhasor(cirq.PauliString({q0: cirq.Y})) ** 0.25, cirq.Y(q0) ** -0.25 ).unitary() cirq.testing.assert_allclose_up_to_global_phase(mat, np.eye(2), rtol=1e-7, atol=1e-7) @@ -563,11 +555,7 @@ def test_gate_with_parameters_resolved_by(resolve_fn): def test_gate_repr(): cirq.testing.assert_equivalent_repr( - cirq.PauliStringPhasorGate( - dps_zyx, - exponent_neg=0.5, - exponent_pos=0.25, - ) + cirq.PauliStringPhasorGate(dps_zyx, exponent_neg=0.5, exponent_pos=0.25) ) cirq.testing.assert_equivalent_repr( cirq.PauliStringPhasorGate(-dps_yx, exponent_neg=-0.5, exponent_pos=0.25) diff --git a/cirq-core/cirq/ops/pauli_string_raw_types.py b/cirq-core/cirq/ops/pauli_string_raw_types.py index 3384a04c2aa..f102c834ede 100644 --- a/cirq-core/cirq/ops/pauli_string_raw_types.py +++ b/cirq-core/cirq/ops/pauli_string_raw_types.py @@ -59,9 +59,7 @@ def qubits(self) -> Tuple[raw_types.Qid, ...]: return tuple(self.pauli_string) def _pauli_string_diagram_info( - self, - args: 'protocols.CircuitDiagramInfoArgs', - exponent: Any = 1, + self, args: 'protocols.CircuitDiagramInfoArgs', exponent: Any = 1 ) -> 'cirq.CircuitDiagramInfo': qubits = self.qubits if args.known_qubits is None else args.known_qubits syms = tuple(f'[{self.pauli_string[qubit]}]' for qubit in qubits) diff --git a/cirq-core/cirq/ops/pauli_string_raw_types_test.py b/cirq-core/cirq/ops/pauli_string_raw_types_test.py index ed34fadc789..a925ca6e959 100644 --- a/cirq-core/cirq/ops/pauli_string_raw_types_test.py +++ b/cirq-core/cirq/ops/pauli_string_raw_types_test.py @@ -77,10 +77,7 @@ def _circuit_diagram_info_( q0, q1, q2 = _make_qubits(3) ps = cirq.PauliString({q0: cirq.X, q1: cirq.Y, q2: cirq.Z}) - circuit = cirq.Circuit( - DiagramGate(ps), - DiagramGate(-ps), - ) + circuit = cirq.Circuit(DiagramGate(ps), DiagramGate(-ps)) cirq.testing.assert_has_diagram( circuit, """ diff --git a/cirq-core/cirq/ops/pauli_string_test.py b/cirq-core/cirq/ops/pauli_string_test.py index c164d573b38..659aa45750c 100644 --- a/cirq-core/cirq/ops/pauli_string_test.py +++ b/cirq-core/cirq/ops/pauli_string_test.py @@ -460,14 +460,7 @@ def test_mul_strings(): a, b, c, d = cirq.LineQubit.range(4) p1 = cirq.PauliString({a: cirq.X, b: cirq.Y, c: cirq.Z}) p2 = cirq.PauliString({b: cirq.X, c: cirq.Y, d: cirq.Z}) - assert p1 * p2 == -cirq.PauliString( - { - a: cirq.X, - b: cirq.Z, - c: cirq.X, - d: cirq.Z, - } - ) + assert p1 * p2 == -cirq.PauliString({a: cirq.X, b: cirq.Z, c: cirq.X, d: cirq.Z}) assert cirq.X(a) * cirq.PauliString({a: cirq.X}) == cirq.PauliString() assert cirq.PauliString({a: cirq.X}) * cirq.X(a) == cirq.PauliString() @@ -830,6 +823,7 @@ def test_unitary_matrix(): a, b = cirq.LineQubit.range(2) assert not cirq.has_unitary(2 * cirq.X(a) * cirq.Z(b)) assert cirq.unitary(2 * cirq.X(a) * cirq.Z(b), default=None) is None + # fmt: off np.testing.assert_allclose( cirq.unitary(cirq.X(a) * cirq.Z(b)), np.array( @@ -852,6 +846,7 @@ def test_unitary_matrix(): ] ), ) + # fmt: on def test_decompose(): @@ -1050,10 +1045,7 @@ def test_pauli_string_expectation_from_state_vector_pure_state(): q_map = {q: i for i, q in enumerate(qubits)} circuit = cirq.Circuit( - cirq.X(qubits[1]), - cirq.H(qubits[2]), - cirq.X(qubits[3]), - cirq.H(qubits[3]), + cirq.X(qubits[1]), cirq.H(qubits[2]), cirq.X(qubits[3]), cirq.H(qubits[3]) ) wf = circuit.final_state_vector(qubit_order=qubits) @@ -1079,12 +1071,7 @@ def test_pauli_string_expectation_from_state_vector_pure_state_with_coef(): qs = cirq.LineQubit.range(4) q_map = {q: i for i, q in enumerate(qs)} - circuit = cirq.Circuit( - cirq.X(qs[1]), - cirq.H(qs[2]), - cirq.X(qs[3]), - cirq.H(qs[3]), - ) + circuit = cirq.Circuit(cirq.X(qs[1]), cirq.H(qs[2]), cirq.X(qs[3]), cirq.H(qs[3])) wf = circuit.final_state_vector(qubit_order=qs) z0z1 = cirq.Z(qs[0]) * cirq.Z(qs[1]) * 0.123 @@ -1200,8 +1187,7 @@ def test_expectation_from_density_matrix_basis_states(): x0.expectation_from_density_matrix(np.array([[0, 0], [0, 1]], dtype=complex), q_map), 0 ) np.testing.assert_allclose( - x0.expectation_from_density_matrix(np.array([[1, 1], [1, 1]], dtype=complex) / 2, q_map), - 1, + x0.expectation_from_density_matrix(np.array([[1, 1], [1, 1]], dtype=complex) / 2, q_map), 1 ) np.testing.assert_allclose( x0.expectation_from_density_matrix(np.array([[1, -1], [-1, 1]], dtype=complex) / 2, q_map), @@ -1268,10 +1254,7 @@ def test_pauli_string_expectation_from_density_matrix_pure_state(): q_map = {q: i for i, q in enumerate(qubits)} circuit = cirq.Circuit( - cirq.X(qubits[1]), - cirq.H(qubits[2]), - cirq.X(qubits[3]), - cirq.H(qubits[3]), + cirq.X(qubits[1]), cirq.H(qubits[2]), cirq.X(qubits[3]), cirq.H(qubits[3]) ) state_vector = circuit.final_state_vector(qubit_order=qubits) rho = np.outer(state_vector, np.conj(state_vector)) @@ -1298,12 +1281,7 @@ def test_pauli_string_expectation_from_density_matrix_pure_state_with_coef(): qs = cirq.LineQubit.range(4) q_map = {q: i for i, q in enumerate(qs)} - circuit = cirq.Circuit( - cirq.X(qs[1]), - cirq.H(qs[2]), - cirq.X(qs[3]), - cirq.H(qs[3]), - ) + circuit = cirq.Circuit(cirq.X(qs[1]), cirq.H(qs[2]), cirq.X(qs[3]), cirq.H(qs[3])) state_vector = circuit.final_state_vector(qubit_order=qs) rho = np.outer(state_vector, np.conj(state_vector)) @@ -1444,12 +1422,8 @@ 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(): @@ -1504,11 +1478,7 @@ def _decompose_(self, qubits): cirq.YY**-0.5, cirq.ZZ**-0.5, ] - two_qubit_gates.extend( - [ - OrderSensitiveGate(), - ] - ) + two_qubit_gates.extend([OrderSensitiveGate()]) for p1 in [cirq.I, cirq.X, cirq.Y, cirq.Z]: for p2 in [cirq.I, cirq.X, cirq.Y, cirq.Z]: pd = cirq.DensePauliString([p1, p2]) diff --git a/cirq-core/cirq/ops/permutation_gate_test.py b/cirq-core/cirq/ops/permutation_gate_test.py index 40f16ab94d7..f80451bc007 100644 --- a/cirq-core/cirq/ops/permutation_gate_test.py +++ b/cirq-core/cirq/ops/permutation_gate_test.py @@ -75,9 +75,7 @@ def test_permutation_gate_diagram(): def test_permutation_gate_json_dict(): - assert cirq.QubitPermutationGate([0, 1, 2])._json_dict_() == { - 'permutation': (0, 1, 2), - } + assert cirq.QubitPermutationGate([0, 1, 2])._json_dict_() == {'permutation': (0, 1, 2)} @pytest.mark.parametrize( diff --git a/cirq-core/cirq/ops/phased_iswap_gate.py b/cirq-core/cirq/ops/phased_iswap_gate.py index e0ae692a156..e0d02ced58c 100644 --- a/cirq-core/cirq/ops/phased_iswap_gate.py +++ b/cirq-core/cirq/ops/phased_iswap_gate.py @@ -75,10 +75,7 @@ def _num_qubits_(self) -> int: return 2 def _json_dict_(self) -> Dict[str, Any]: - return { - 'phase_exponent': self._phase_exponent, - 'exponent': self._exponent, - } + return {'phase_exponent': self._phase_exponent, 'exponent': self._exponent} def _value_equality_values_cls_(self): if self.phase_exponent == 0: diff --git a/cirq-core/cirq/ops/phased_iswap_gate_test.py b/cirq-core/cirq/ops/phased_iswap_gate_test.py index 4ee64f09671..d75fc39d6d5 100644 --- a/cirq-core/cirq/ops/phased_iswap_gate_test.py +++ b/cirq-core/cirq/ops/phased_iswap_gate_test.py @@ -175,13 +175,7 @@ def test_givens_rotation_equivalent_circuit(): gate = cirq.givens(angle_rads) q0, q1 = cirq.LineQubit.range(2) equivalent_circuit = cirq.Circuit( - [ - cirq.T(q0), - cirq.T(q1) ** -1, - cirq.ISWAP(q0, q1) ** t, - cirq.T(q0) ** -1, - cirq.T(q1), - ] + [cirq.T(q0), cirq.T(q1) ** -1, cirq.ISWAP(q0, q1) ** t, cirq.T(q0) ** -1, cirq.T(q1)] ) assert np.allclose(cirq.unitary(gate), cirq.unitary(equivalent_circuit)) diff --git a/cirq-core/cirq/ops/phased_x_gate_test.py b/cirq-core/cirq/ops/phased_x_gate_test.py index c3fdfa1bc91..cd237327c50 100644 --- a/cirq-core/cirq/ops/phased_x_gate_test.py +++ b/cirq-core/cirq/ops/phased_x_gate_test.py @@ -22,24 +22,14 @@ @pytest.mark.parametrize( - 'phase_exponent', - [ - -0.5, - 0, - 0.1, - 0.25, - 0.5, - 1, - sympy.Symbol('p'), - sympy.Symbol('p') + 1, - ], + 'phase_exponent', [-0.5, 0, 0.1, 0.25, 0.5, 1, sympy.Symbol('p'), sympy.Symbol('p') + 1] ) def test_phased_x_consistent_protocols(phase_exponent): cirq.testing.assert_implements_consistent_protocols( - cirq.PhasedXPowGate(phase_exponent=phase_exponent, exponent=1.0), + cirq.PhasedXPowGate(phase_exponent=phase_exponent, exponent=1.0) ) cirq.testing.assert_implements_consistent_protocols( - cirq.PhasedXPowGate(phase_exponent=phase_exponent, exponent=1.0, global_shift=0.1), + cirq.PhasedXPowGate(phase_exponent=phase_exponent, exponent=1.0, global_shift=0.1) ) @@ -60,13 +50,7 @@ def test_init(): assert y._global_shift == 0.2 -@pytest.mark.parametrize( - 'sym', - [ - sympy.Symbol('a'), - sympy.Symbol('a') + 1, - ], -) +@pytest.mark.parametrize('sym', [sympy.Symbol('a'), sympy.Symbol('a') + 1]) def test_no_symbolic_qasm_but_fails_gracefully(sym): q = cirq.NamedQubit('q') v = cirq.PhasedXPowGate(phase_exponent=sym).on(q) @@ -252,8 +236,7 @@ def test_phase_by(): @pytest.mark.parametrize( - 'exponent,phase_exponent', - itertools.product(np.arange(-2.5, 2.75, 0.25), repeat=2), + 'exponent,phase_exponent', itertools.product(np.arange(-2.5, 2.75, 0.25), repeat=2) ) def test_exponent_consistency(exponent, phase_exponent): """Verifies that instances of PhasedX gate expose consistent exponents.""" diff --git a/cirq-core/cirq/ops/projector.py b/cirq-core/cirq/ops/projector.py index 290ba2351e5..b1c29237e2c 100644 --- a/cirq-core/cirq/ops/projector.py +++ b/cirq-core/cirq/ops/projector.py @@ -1,14 +1,6 @@ # pylint: disable=wrong-or-nonexistent-copyright-notice import itertools -from typing import ( - Any, - Dict, - Iterable, - List, - Mapping, - Optional, - Union, -) +from typing import Any, Dict, Iterable, List, Mapping, Optional, Union import numpy as np from scipy.sparse import csr_matrix @@ -27,9 +19,7 @@ def _check_qids_dimension(qids): @value.value_equality(approximate=True) class ProjectorString: def __init__( - self, - projector_dict: Dict[raw_types.Qid, int], - coefficient: Union[int, float, complex] = 1, + self, projector_dict: Dict[raw_types.Qid, int], coefficient: Union[int, float, complex] = 1 ): """Contructor for ProjectorString @@ -92,9 +82,7 @@ def _get_idx_to_keep(self, qid_map: Mapping[raw_types.Qid, int]): return tuple(idx_to_keep) def expectation_from_state_vector( - self, - state_vector: np.ndarray, - qid_map: Mapping[raw_types.Qid, int], + self, state_vector: np.ndarray, qid_map: Mapping[raw_types.Qid, int] ) -> complex: """Expectation of the projection from a state vector. @@ -116,9 +104,7 @@ def expectation_from_state_vector( ) def expectation_from_density_matrix( - self, - state: np.ndarray, - qid_map: Mapping[raw_types.Qid, int], + self, state: np.ndarray, qid_map: Mapping[raw_types.Qid, int] ) -> complex: """Expectation of the projection from a density matrix. diff --git a/cirq-core/cirq/ops/qubit_order.py b/cirq-core/cirq/ops/qubit_order.py index d48b8e0aacb..6b951866ee6 100644 --- a/cirq-core/cirq/ops/qubit_order.py +++ b/cirq-core/cirq/ops/qubit_order.py @@ -13,15 +13,7 @@ # limitations under the License. -from typing import ( - Any, - Callable, - Iterable, - Optional, - Tuple, - TypeVar, - TYPE_CHECKING, -) +from typing import Any, Callable, Iterable, Optional, Tuple, TypeVar, TYPE_CHECKING from cirq.ops import raw_types diff --git a/cirq-core/cirq/ops/random_gate_channel.py b/cirq-core/cirq/ops/random_gate_channel.py index eaf8c5e9525..cb38d80cdba 100644 --- a/cirq-core/cirq/ops/random_gate_channel.py +++ b/cirq-core/cirq/ops/random_gate_channel.py @@ -13,16 +13,7 @@ # limitations under the License. import numbers -from typing import ( - AbstractSet, - Tuple, - TYPE_CHECKING, - Dict, - Any, - cast, - SupportsFloat, - Optional, -) +from typing import AbstractSet, Tuple, TYPE_CHECKING, Dict, Any, cast, SupportsFloat, Optional import numpy as np diff --git a/cirq-core/cirq/ops/random_gate_channel_test.py b/cirq-core/cirq/ops/random_gate_channel_test.py index c54e5f91e17..8e46fdcff99 100644 --- a/cirq-core/cirq/ops/random_gate_channel_test.py +++ b/cirq-core/cirq/ops/random_gate_channel_test.py @@ -44,16 +44,11 @@ def test_eq(): # `with_probability(1)` doesn't wrap eq.add_equality_group(cirq.X, cirq.X.with_probability(1)) eq.add_equality_group( - cirq.X.with_probability(1).on(q), - cirq.X.on(q).with_probability(1), - cirq.X(q), + cirq.X.with_probability(1).on(q), cirq.X.on(q).with_probability(1), cirq.X(q) ) # `with_probability` with `on`. - eq.add_equality_group( - cirq.X.with_probability(0.5).on(q), - cirq.X.on(q).with_probability(0.5), - ) + eq.add_equality_group(cirq.X.with_probability(0.5).on(q), cirq.X.on(q).with_probability(0.5)) # Flattening. eq.add_equality_group( @@ -66,15 +61,9 @@ def test_eq(): ) # Supports approximate equality. - assert cirq.approx_eq( - cirq.X.with_probability(0.5), - cirq.X.with_probability(0.50001), - atol=1e-2, - ) + assert cirq.approx_eq(cirq.X.with_probability(0.5), cirq.X.with_probability(0.50001), atol=1e-2) assert not cirq.approx_eq( - cirq.X.with_probability(0.5), - cirq.X.with_probability(0.50001), - atol=1e-8, + cirq.X.with_probability(0.5), cirq.X.with_probability(0.50001), atol=1e-8 ) @@ -181,52 +170,28 @@ def num_qubits(self) -> int: m = cirq.kraus(cirq.X.with_probability(0.25)) assert len(m) == 2 - np.testing.assert_allclose( - m[0], - cirq.unitary(cirq.X) * np.sqrt(0.25), - atol=1e-8, - ) - np.testing.assert_allclose( - m[1], - cirq.unitary(cirq.I) * np.sqrt(0.75), - atol=1e-8, - ) + np.testing.assert_allclose(m[0], cirq.unitary(cirq.X) * np.sqrt(0.25), atol=1e-8) + np.testing.assert_allclose(m[1], cirq.unitary(cirq.I) * np.sqrt(0.75), atol=1e-8) m = cirq.kraus(cirq.bit_flip(0.75).with_probability(0.25)) assert len(m) == 3 np.testing.assert_allclose( - m[0], - cirq.unitary(cirq.I) * np.sqrt(0.25) * np.sqrt(0.25), - atol=1e-8, - ) - np.testing.assert_allclose( - m[1], - cirq.unitary(cirq.X) * np.sqrt(0.25) * np.sqrt(0.75), - atol=1e-8, + m[0], cirq.unitary(cirq.I) * np.sqrt(0.25) * np.sqrt(0.25), atol=1e-8 ) np.testing.assert_allclose( - m[2], - cirq.unitary(cirq.I) * np.sqrt(0.75), - atol=1e-8, + m[1], cirq.unitary(cirq.X) * np.sqrt(0.25) * np.sqrt(0.75), atol=1e-8 ) + np.testing.assert_allclose(m[2], cirq.unitary(cirq.I) * np.sqrt(0.75), atol=1e-8) m = cirq.kraus(cirq.amplitude_damp(0.75).with_probability(0.25)) assert len(m) == 3 np.testing.assert_allclose( - m[0], - np.array([[1, 0], [0, np.sqrt(1 - 0.75)]]) * np.sqrt(0.25), - atol=1e-8, - ) - np.testing.assert_allclose( - m[1], - np.array([[0, np.sqrt(0.75)], [0, 0]]) * np.sqrt(0.25), - atol=1e-8, + m[0], np.array([[1, 0], [0, np.sqrt(1 - 0.75)]]) * np.sqrt(0.25), atol=1e-8 ) np.testing.assert_allclose( - m[2], - cirq.unitary(cirq.I) * np.sqrt(0.75), - atol=1e-8, + m[1], np.array([[0, np.sqrt(0.75)], [0, 0]]) * np.sqrt(0.25), atol=1e-8 ) + np.testing.assert_allclose(m[2], cirq.unitary(cirq.I) * np.sqrt(0.75), atol=1e-8) def test_trace_distance(): diff --git a/cirq-core/cirq/ops/raw_types_test.py b/cirq-core/cirq/ops/raw_types_test.py index 3dfec760ccc..daec1f3c0d8 100644 --- a/cirq-core/cirq/ops/raw_types_test.py +++ b/cirq-core/cirq/ops/raw_types_test.py @@ -621,10 +621,7 @@ def test_tagged_operation_forwards_protocols(): assert 3 * tagged_y == (3 * y) assert cirq.phase_by(y, 0.125, 0) == cirq.phase_by(tagged_y, 0.125, 0) controlled_y = tagged_y.controlled_by(q2) - assert controlled_y.qubits == ( - q2, - q1, - ) + assert controlled_y.qubits == (q2, q1) assert isinstance(controlled_y, cirq.Operation) assert not isinstance(controlled_y, cirq.TaggedOperation) diff --git a/cirq-core/cirq/ops/state_preparation_channel.py b/cirq-core/cirq/ops/state_preparation_channel.py index daf6b0faca7..cdd84dee009 100644 --- a/cirq-core/cirq/ops/state_preparation_channel.py +++ b/cirq-core/cirq/ops/state_preparation_channel.py @@ -59,10 +59,7 @@ def _has_unitary_(self) -> bool: def _json_dict_(self) -> Dict[str, Any]: """Converts the gate object into a serializable dictionary""" - return { - 'target_state': self._state.tolist(), - 'name': self._name, - } + return {'target_state': self._state.tolist(), 'name': self._name} @classmethod def _from_json_dict_( diff --git a/cirq-core/cirq/ops/swap_gates_test.py b/cirq-core/cirq/ops/swap_gates_test.py index 17fd161b17b..4cf7dc7cb61 100644 --- a/cirq-core/cirq/ops/swap_gates_test.py +++ b/cirq-core/cirq/ops/swap_gates_test.py @@ -20,13 +20,7 @@ import cirq -@pytest.mark.parametrize( - 'eigen_gate_type', - [ - cirq.ISwapPowGate, - cirq.SwapPowGate, - ], -) +@pytest.mark.parametrize('eigen_gate_type', [cirq.ISwapPowGate, cirq.SwapPowGate]) def test_phase_sensitive_eigen_gates_consistent_protocols(eigen_gate_type): cirq.testing.assert_eigengate_implements_consistent_protocols(eigen_gate_type) diff --git a/cirq-core/cirq/ops/three_qubit_gates.py b/cirq-core/cirq/ops/three_qubit_gates.py index d32b161547b..2be5ef92acb 100644 --- a/cirq-core/cirq/ops/three_qubit_gates.py +++ b/cirq-core/cirq/ops/three_qubit_gates.py @@ -55,10 +55,7 @@ class CCZPowGate(gate_features.InterchangeableQubitsGate, eigen_gate.EigenGate): """ def _eigen_components(self) -> List[Tuple[float, np.ndarray]]: - return [ - (0, np.diag([1, 1, 1, 1, 1, 1, 1, 0])), - (1, np.diag([0, 0, 0, 0, 0, 0, 0, 1])), - ] + return [(0, np.diag([1, 1, 1, 1, 1, 1, 1, 0])), (1, np.diag([0, 0, 0, 0, 0, 0, 0, 1]))] def _trace_distance_bound_(self) -> Optional[float]: if self._is_parameterized_(): diff --git a/cirq-core/cirq/ops/three_qubit_gates_test.py b/cirq-core/cirq/ops/three_qubit_gates_test.py index 77ecabcbb91..b900a7fb599 100644 --- a/cirq-core/cirq/ops/three_qubit_gates_test.py +++ b/cirq-core/cirq/ops/three_qubit_gates_test.py @@ -20,13 +20,7 @@ import cirq -@pytest.mark.parametrize( - 'eigen_gate_type', - [ - cirq.CCXPowGate, - cirq.CCZPowGate, - ], -) +@pytest.mark.parametrize('eigen_gate_type', [cirq.CCXPowGate, cirq.CCZPowGate]) def test_eigen_gates_consistent_protocols(eigen_gate_type): cirq.testing.assert_eigengate_implements_consistent_protocols( eigen_gate_type, ignoring_global_phase=True @@ -214,12 +208,7 @@ def test_decomposition_cost(op: cirq.Operation, max_two_cost: int): @pytest.mark.parametrize( 'gate', - [ - cirq.CCX, - cirq.CSWAP, - cirq.CCZ, - cirq.ThreeQubitDiagonalGate([2, 3, 5, 7, 11, 13, 17, 19]), - ], + [cirq.CCX, cirq.CSWAP, cirq.CCZ, cirq.ThreeQubitDiagonalGate([2, 3, 5, 7, 11, 13, 17, 19])], ) def test_decomposition_respects_locality(gate): a = cirq.GridQubit(0, 0) diff --git a/cirq-core/cirq/ops/wait_gate.py b/cirq-core/cirq/ops/wait_gate.py index e0a0b45de39..d55de5615cb 100644 --- a/cirq-core/cirq/ops/wait_gate.py +++ b/cirq-core/cirq/ops/wait_gate.py @@ -155,12 +155,6 @@ def wait( millis: Milliseconds to wait (see Duration). """ return WaitGate( - duration=value.Duration( - duration, - picos=picos, - nanos=nanos, - micros=micros, - millis=millis, - ), + duration=value.Duration(duration, picos=picos, nanos=nanos, micros=micros, millis=millis), qid_shape=protocols.qid_shape(target), ).on(*target) diff --git a/cirq-core/cirq/optimizers/__init__.py b/cirq-core/cirq/optimizers/__init__.py index 41809bd0f6f..38c4d544ce0 100644 --- a/cirq-core/cirq/optimizers/__init__.py +++ b/cirq-core/cirq/optimizers/__init__.py @@ -14,45 +14,25 @@ """Classes and methods that optimize quantum circuits.""" -from cirq.optimizers.align_left import ( - AlignLeft, -) +from cirq.optimizers.align_left import AlignLeft -from cirq.optimizers.align_right import ( - AlignRight, -) +from cirq.optimizers.align_right import AlignRight -from cirq.optimizers.drop_empty_moments import ( - DropEmptyMoments, -) +from cirq.optimizers.drop_empty_moments import DropEmptyMoments -from cirq.optimizers.drop_negligible import ( - DropNegligible, -) +from cirq.optimizers.drop_negligible import DropNegligible -from cirq.optimizers.convert_to_cz_and_single_gates import ( - ConvertToCzAndSingleGates, -) +from cirq.optimizers.convert_to_cz_and_single_gates import ConvertToCzAndSingleGates -from cirq.optimizers.eject_phased_paulis import ( - EjectPhasedPaulis, -) +from cirq.optimizers.eject_phased_paulis import EjectPhasedPaulis -from cirq.optimizers.eject_z import ( - EjectZ, -) +from cirq.optimizers.eject_z import EjectZ -from cirq.optimizers.expand_composite import ( - ExpandComposite, -) +from cirq.optimizers.expand_composite import ExpandComposite -from cirq.optimizers.merge_interactions import ( - MergeInteractions, -) +from cirq.optimizers.merge_interactions import MergeInteractions -from cirq.optimizers.merge_interactions_to_sqrt_iswap import ( - MergeInteractionsToSqrtIswap, -) +from cirq.optimizers.merge_interactions_to_sqrt_iswap import MergeInteractionsToSqrtIswap from cirq.optimizers.merge_single_qubit_gates import ( merge_single_qubit_gates_into_phased_x_z, @@ -60,9 +40,7 @@ MergeSingleQubitGates, ) -from cirq.optimizers.synchronize_terminal_measurements import ( - SynchronizeTerminalMeasurements, -) +from cirq.optimizers.synchronize_terminal_measurements import SynchronizeTerminalMeasurements from cirq.transformers.stratify import stratified_circuit diff --git a/cirq-core/cirq/optimizers/convert_to_cz_and_single_gates_test.py b/cirq-core/cirq/optimizers/convert_to_cz_and_single_gates_test.py index cce7fe5f2ec..58d53be2dbd 100644 --- a/cirq-core/cirq/optimizers/convert_to_cz_and_single_gates_test.py +++ b/cirq-core/cirq/optimizers/convert_to_cz_and_single_gates_test.py @@ -74,16 +74,9 @@ def _decompose_(self, qubits): yield CompositeDummy()(qubits[1]) q0, q1 = cirq.LineQubit.range(2) - circuit = cirq.Circuit( - CompositeDummy()(q0), - CompositeDummy2()(q0, q1), - ) + circuit = cirq.Circuit(CompositeDummy()(q0), CompositeDummy2()(q0, q1)) expected = cirq.Circuit( - cirq.X(q0), - cirq.Y(q0) ** 0.5, - cirq.CZ(q0, q1), - cirq.X(q1), - cirq.Y(q1) ** 0.5, + cirq.X(q0), cirq.Y(q0) ** 0.5, cirq.CZ(q0, q1), cirq.X(q1), cirq.Y(q1) ** 0.5 ) c_orig = cirq.Circuit(circuit) with cirq.testing.assert_deprecated("Use cirq.optimize_for_target_gateset", deadline='v1.0'): @@ -100,9 +93,7 @@ class UnsupportedDummy(cirq.testing.TwoQubitGate): pass q0, q1 = cirq.LineQubit.range(2) - circuit = cirq.Circuit( - UnsupportedDummy()(q0, q1), - ) + circuit = cirq.Circuit(UnsupportedDummy()(q0, q1)) c_orig = cirq.Circuit(circuit) with cirq.testing.assert_deprecated("Use cirq.optimize_for_target_gateset", deadline='v1.0'): cirq.ConvertToCzAndSingleGates(ignore_failures=True).optimize_circuit(circuit) @@ -115,9 +106,7 @@ class UnsupportedDummy(cirq.testing.TwoQubitGate): pass q0, q1 = cirq.LineQubit.range(2) - circuit = cirq.Circuit( - UnsupportedDummy()(q0, q1), - ) + circuit = cirq.Circuit(UnsupportedDummy()(q0, q1)) with pytest.raises(TypeError): with cirq.testing.assert_deprecated( "Use cirq.optimize_for_target_gateset", deadline='v1.0' @@ -128,8 +117,7 @@ class UnsupportedDummy(cirq.testing.TwoQubitGate): def test_passes_through_measurements(): q0, q1, q2 = cirq.LineQubit.range(3) circuit = cirq.Circuit( - cirq.measure(q0, key='m0'), - cirq.measure(q1, q2, key='m1', invert_mask=(True, False)), + cirq.measure(q0, key='m0'), cirq.measure(q1, q2, key='m1', invert_mask=(True, False)) ) c_orig = cirq.Circuit(circuit) with cirq.testing.assert_deprecated("Use cirq.optimize_for_target_gateset", deadline='v1.0'): @@ -140,8 +128,7 @@ def test_passes_through_measurements(): def test_allow_partial_czs(): q0, q1 = cirq.LineQubit.range(2) circuit = cirq.Circuit( - cirq.CZ(q0, q1) ** 0.5, - cirq.CZPowGate(exponent=0.5, global_shift=-0.5).on(q0, q1), + cirq.CZ(q0, q1) ** 0.5, cirq.CZPowGate(exponent=0.5, global_shift=-0.5).on(q0, q1) ) c_orig = cirq.Circuit(circuit) with cirq.testing.assert_deprecated("Use cirq.optimize_for_target_gateset", deadline='v1.0'): @@ -167,17 +154,14 @@ def test_allow_partial_czs(): def test_dont_allow_partial_czs(): q0, q1 = cirq.LineQubit.range(2) circuit = cirq.Circuit( - cirq.CZ(q0, q1), - cirq.CZPowGate(exponent=1, global_shift=-0.5).on(q0, q1), + cirq.CZ(q0, q1), cirq.CZPowGate(exponent=1, global_shift=-0.5).on(q0, q1) ) c_orig = cirq.Circuit(circuit) with cirq.testing.assert_deprecated("Use cirq.optimize_for_target_gateset", deadline='v1.0'): cirq.ConvertToCzAndSingleGates().optimize_circuit(circuit) assert circuit == c_orig - circuit = cirq.Circuit( - cirq.CZ(q0, q1) ** 0.5, - ) + circuit = cirq.Circuit(cirq.CZ(q0, q1) ** 0.5) c_orig = cirq.Circuit(circuit) with cirq.testing.assert_deprecated("Use cirq.optimize_for_target_gateset", deadline='v1.0'): cirq.ConvertToCzAndSingleGates(ignore_failures=True).optimize_circuit(circuit) diff --git a/cirq-core/cirq/optimizers/drop_empty_moments_test.py b/cirq-core/cirq/optimizers/drop_empty_moments_test.py index 04d68e3adba..7f08449a68f 100644 --- a/cirq-core/cirq/optimizers/drop_empty_moments_test.py +++ b/cirq-core/cirq/optimizers/drop_empty_moments_test.py @@ -27,16 +27,7 @@ def test_drop(): q2 = cirq.NamedQubit('q2') assert_optimizes( before=cirq.Circuit( - [ - cirq.Moment(), - cirq.Moment(), - cirq.Moment([cirq.CNOT(q1, q2)]), - cirq.Moment(), - ] - ), - after=cirq.Circuit( - [ - cirq.Moment([cirq.CNOT(q1, q2)]), - ] + [cirq.Moment(), cirq.Moment(), cirq.Moment([cirq.CNOT(q1, q2)]), cirq.Moment()] ), + after=cirq.Circuit([cirq.Moment([cirq.CNOT(q1, q2)])]), ) diff --git a/cirq-core/cirq/optimizers/drop_negligible_test.py b/cirq-core/cirq/optimizers/drop_negligible_test.py index 4edc4830531..47f67072c23 100644 --- a/cirq-core/cirq/optimizers/drop_negligible_test.py +++ b/cirq-core/cirq/optimizers/drop_negligible_test.py @@ -43,9 +43,7 @@ def test_clears_known_empties_even_at_zero_tolerance(): cirq.Z(a) ** 0, cirq.Y(a) ** 0.0000001, cirq.X(a) ** -0.0000001, cirq.CZ(a, b) ** 0 ) assert_optimizes( - 0.001, - initial_circuit=circuit, - expected_circuit=cirq.Circuit([cirq.Moment()] * 4), + 0.001, initial_circuit=circuit, expected_circuit=cirq.Circuit([cirq.Moment()] * 4) ) assert_optimizes( 0, diff --git a/cirq-core/cirq/optimizers/eject_phased_paulis_test.py b/cirq-core/cirq/optimizers/eject_phased_paulis_test.py index 04c1c2b1f98..900e328d657 100644 --- a/cirq-core/cirq/optimizers/eject_phased_paulis_test.py +++ b/cirq-core/cirq/optimizers/eject_phased_paulis_test.py @@ -88,91 +88,53 @@ def test_absorbs_z(): # Full Z. assert_optimizes( - before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], - [cirq.Z(q)], - ), - expected=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.625).on(q)], - [], - ), + before=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], [cirq.Z(q)]), + expected=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.625).on(q)], []), ) # Partial Z. assert_optimizes( - before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], - [cirq.S(q)], - ), - expected=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.375).on(q)], - [], - ), + before=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], [cirq.S(q)]), + expected=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.375).on(q)], []), ) # parameterized Z. assert_optimizes( - before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], - [cirq.Z(q) ** x], - ), - expected=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.125 + x / 2).on(q)], - [], - ), + before=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], [cirq.Z(q) ** x]), + expected=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.125 + x / 2).on(q)], []), eject_parameterized=True, ) assert_optimizes( before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], - [cirq.Z(q) ** (x + 1)], - ), - expected=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.625 + x / 2).on(q)], - [], + [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], [cirq.Z(q) ** (x + 1)] ), + expected=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.625 + x / 2).on(q)], []), eject_parameterized=True, ) # Multiple Zs. assert_optimizes( before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], - [cirq.S(q)], - [cirq.T(q) ** -1], - ), - expected=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], - [], - [], + [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], [cirq.S(q)], [cirq.T(q) ** -1] ), + expected=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], [], []), ) # Multiple Parameterized Zs. assert_optimizes( before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], - [cirq.S(q) ** x], - [cirq.T(q) ** -x], + [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], [cirq.S(q) ** x], [cirq.T(q) ** -x] ), expected=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.125 + x * 0.125).on(q)], - [], - [], + [cirq.PhasedXPowGate(phase_exponent=0.125 + x * 0.125).on(q)], [], [] ), eject_parameterized=True, ) # Parameterized Phase and Partial Z assert_optimizes( - before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=x).on(q)], - [cirq.S(q)], - ), - expected=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=x + 0.25).on(q)], - [], - ), + before=quick_circuit([cirq.PhasedXPowGate(phase_exponent=x).on(q)], [cirq.S(q)]), + expected=quick_circuit([cirq.PhasedXPowGate(phase_exponent=x + 0.25).on(q)], []), eject_parameterized=True, ) @@ -186,62 +148,33 @@ def test_crosses_czs(): # Full CZ. assert_optimizes( - before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.25).on(a)], - [cirq.CZ(a, b)], - ), + before=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.25).on(a)], [cirq.CZ(a, b)]), expected=quick_circuit( - [cirq.Z(b)], - [cirq.CZ(a, b)], - [cirq.PhasedXPowGate(phase_exponent=0.25).on(a)], + [cirq.Z(b)], [cirq.CZ(a, b)], [cirq.PhasedXPowGate(phase_exponent=0.25).on(a)] ), ) assert_optimizes( - before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.125).on(a)], - [cirq.CZ(b, a)], - ), + before=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.125).on(a)], [cirq.CZ(b, a)]), expected=quick_circuit( - [cirq.Z(b)], - [cirq.CZ(a, b)], - [cirq.PhasedXPowGate(phase_exponent=0.125).on(a)], + [cirq.Z(b)], [cirq.CZ(a, b)], [cirq.PhasedXPowGate(phase_exponent=0.125).on(a)] ), ) assert_optimizes( - before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=x).on(a)], - [cirq.CZ(b, a)], - ), + before=quick_circuit([cirq.PhasedXPowGate(phase_exponent=x).on(a)], [cirq.CZ(b, a)]), expected=quick_circuit( - [cirq.Z(b)], - [cirq.CZ(a, b)], - [cirq.PhasedXPowGate(phase_exponent=x).on(a)], + [cirq.Z(b)], [cirq.CZ(a, b)], [cirq.PhasedXPowGate(phase_exponent=x).on(a)] ), eject_parameterized=True, ) # Partial CZ. assert_optimizes( - before=quick_circuit( - [cirq.X(a)], - [cirq.CZ(a, b) ** 0.25], - ), - expected=quick_circuit( - [cirq.Z(b) ** 0.25], - [cirq.CZ(a, b) ** -0.25], - [cirq.X(a)], - ), + before=quick_circuit([cirq.X(a)], [cirq.CZ(a, b) ** 0.25]), + expected=quick_circuit([cirq.Z(b) ** 0.25], [cirq.CZ(a, b) ** -0.25], [cirq.X(a)]), ) assert_optimizes( - before=quick_circuit( - [cirq.X(a)], - [cirq.CZ(a, b) ** x], - ), - expected=quick_circuit( - [cirq.Z(b) ** x], - [cirq.CZ(a, b) ** -x], - [cirq.X(a)], - ), + before=quick_circuit([cirq.X(a)], [cirq.CZ(a, b) ** x]), + expected=quick_circuit([cirq.Z(b) ** x], [cirq.CZ(a, b) ** -x], [cirq.X(a)]), eject_parameterized=True, ) @@ -289,33 +222,19 @@ def test_toggles_measurements(): # Single. assert_optimizes( before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.25).on(a)], - [cirq.measure(a, b)], - ), - expected=quick_circuit( - [], - [cirq.measure(a, b, invert_mask=(True,))], + [cirq.PhasedXPowGate(phase_exponent=0.25).on(a)], [cirq.measure(a, b)] ), + expected=quick_circuit([], [cirq.measure(a, b, invert_mask=(True,))]), ) assert_optimizes( before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.25).on(b)], - [cirq.measure(a, b)], - ), - expected=quick_circuit( - [], - [cirq.measure(a, b, invert_mask=(False, True))], + [cirq.PhasedXPowGate(phase_exponent=0.25).on(b)], [cirq.measure(a, b)] ), + expected=quick_circuit([], [cirq.measure(a, b, invert_mask=(False, True))]), ) assert_optimizes( - before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=x).on(b)], - [cirq.measure(a, b)], - ), - expected=quick_circuit( - [], - [cirq.measure(a, b, invert_mask=(False, True))], - ), + before=quick_circuit([cirq.PhasedXPowGate(phase_exponent=x).on(b)], [cirq.measure(a, b)]), + expected=quick_circuit([], [cirq.measure(a, b, invert_mask=(False, True))]), eject_parameterized=True, ) @@ -326,23 +245,15 @@ def test_toggles_measurements(): [cirq.PhasedXPowGate(phase_exponent=0.25).on(b)], [cirq.measure(a, b)], ), - expected=quick_circuit( - [], - [], - [cirq.measure(a, b, invert_mask=(True, True))], - ), + expected=quick_circuit([], [], [cirq.measure(a, b, invert_mask=(True, True))]), ) # Xmon. assert_optimizes( before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.25).on(a)], - [cirq.measure(a, b, key='t')], - ), - expected=quick_circuit( - [], - [cirq.measure(a, b, invert_mask=(True,), key='t')], + [cirq.PhasedXPowGate(phase_exponent=0.25).on(a)], [cirq.measure(a, b, key='t')] ), + expected=quick_circuit([], [cirq.measure(a, b, invert_mask=(True,), key='t')]), ) @@ -356,10 +267,7 @@ def test_cancels_other_full_w(): [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], ), - expected=quick_circuit( - [], - [], - ), + expected=quick_circuit([], []), ) assert_optimizes( @@ -367,10 +275,7 @@ def test_cancels_other_full_w(): [cirq.PhasedXPowGate(phase_exponent=x).on(q)], [cirq.PhasedXPowGate(phase_exponent=x).on(q)], ), - expected=quick_circuit( - [], - [], - ), + expected=quick_circuit([], []), eject_parameterized=True, ) @@ -379,32 +284,17 @@ def test_cancels_other_full_w(): [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], ), - expected=quick_circuit( - [], - [cirq.Z(q) ** -0.25], - ), + expected=quick_circuit([], [cirq.Z(q) ** -0.25]), ) assert_optimizes( - before=quick_circuit( - [cirq.X(q)], - [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], - ), - expected=quick_circuit( - [], - [cirq.Z(q) ** 0.5], - ), + before=quick_circuit([cirq.X(q)], [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)]), + expected=quick_circuit([], [cirq.Z(q) ** 0.5]), ) assert_optimizes( - before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], - [cirq.X(q)], - ), - expected=quick_circuit( - [], - [cirq.Z(q) ** -0.5], - ), + before=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], [cirq.X(q)]), + expected=quick_circuit([], [cirq.Z(q) ** -0.5]), ) assert_optimizes( @@ -412,10 +302,7 @@ def test_cancels_other_full_w(): [cirq.PhasedXPowGate(phase_exponent=x).on(q)], [cirq.PhasedXPowGate(phase_exponent=y).on(q)], ), - expected=quick_circuit( - [], - [cirq.Z(q) ** (2 * (y - x))], - ), + expected=quick_circuit([], [cirq.Z(q) ** (2 * (y - x))]), eject_parameterized=True, ) @@ -428,21 +315,15 @@ def test_phases_partial_ws(): assert_optimizes( before=quick_circuit( - [cirq.X(q)], - [cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(q)], + [cirq.X(q)], [cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(q)] ), expected=quick_circuit( - [], - [cirq.PhasedXPowGate(phase_exponent=-0.25, exponent=0.5).on(q)], - [cirq.X(q)], + [], [cirq.PhasedXPowGate(phase_exponent=-0.25, exponent=0.5).on(q)], [cirq.X(q)] ), ) assert_optimizes( - before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], - [cirq.X(q) ** 0.5], - ), + before=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], [cirq.X(q) ** 0.5]), expected=quick_circuit( [], [cirq.PhasedXPowGate(phase_exponent=0.5, exponent=0.5).on(q)], @@ -456,9 +337,7 @@ def test_phases_partial_ws(): [cirq.PhasedXPowGate(phase_exponent=0.5, exponent=0.75).on(q)], ), expected=quick_circuit( - [], - [cirq.X(q) ** 0.75], - [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], + [], [cirq.X(q) ** 0.75], [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)] ), ) @@ -467,9 +346,7 @@ def test_phases_partial_ws(): [cirq.X(q)], [cirq.PhasedXPowGate(exponent=-0.25, phase_exponent=0.5).on(q)] ), expected=quick_circuit( - [], - [cirq.PhasedXPowGate(exponent=-0.25, phase_exponent=-0.5).on(q)], - [cirq.X(q)], + [], [cirq.PhasedXPowGate(exponent=-0.25, phase_exponent=-0.5).on(q)], [cirq.X(q)] ), ) @@ -487,55 +364,25 @@ def test_phases_partial_ws(): ) -@pytest.mark.parametrize( - 'sym', - [ - sympy.Symbol('x'), - sympy.Symbol('x') + 1, - ], -) +@pytest.mark.parametrize('sym', [sympy.Symbol('x'), sympy.Symbol('x') + 1]) def test_blocked_by_unknown_and_symbols(sym): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') assert_optimizes( - before=quick_circuit( - [cirq.X(a)], - [cirq.SWAP(a, b)], - [cirq.X(a)], - ), - expected=quick_circuit( - [cirq.X(a)], - [cirq.SWAP(a, b)], - [cirq.X(a)], - ), + before=quick_circuit([cirq.X(a)], [cirq.SWAP(a, b)], [cirq.X(a)]), + expected=quick_circuit([cirq.X(a)], [cirq.SWAP(a, b)], [cirq.X(a)]), ) assert_optimizes( - before=quick_circuit( - [cirq.X(a)], - [cirq.Z(a) ** sym], - [cirq.X(a)], - ), - expected=quick_circuit( - [cirq.X(a)], - [cirq.Z(a) ** sym], - [cirq.X(a)], - ), + before=quick_circuit([cirq.X(a)], [cirq.Z(a) ** sym], [cirq.X(a)]), + expected=quick_circuit([cirq.X(a)], [cirq.Z(a) ** sym], [cirq.X(a)]), compare_unitaries=False, ) assert_optimizes( - before=quick_circuit( - [cirq.X(a)], - [cirq.CZ(a, b) ** sym], - [cirq.X(a)], - ), - expected=quick_circuit( - [cirq.X(a)], - [cirq.CZ(a, b) ** sym], - [cirq.X(a)], - ), + before=quick_circuit([cirq.X(a)], [cirq.CZ(a, b) ** sym], [cirq.X(a)]), + expected=quick_circuit([cirq.X(a)], [cirq.CZ(a, b) ** sym], [cirq.X(a)]), compare_unitaries=False, ) @@ -543,11 +390,4 @@ def test_blocked_by_unknown_and_symbols(sym): def test_zero_x_rotation(): a = cirq.NamedQubit('a') - assert_optimizes( - before=quick_circuit( - [cirq.rx(0)(a)], - ), - expected=quick_circuit( - [cirq.rx(0)(a)], - ), - ) + assert_optimizes(before=quick_circuit([cirq.rx(0)(a)]), expected=quick_circuit([cirq.rx(0)(a)])) diff --git a/cirq-core/cirq/optimizers/eject_z_test.py b/cirq-core/cirq/optimizers/eject_z_test.py index 22fbee20bd8..8cd7c84b920 100644 --- a/cirq-core/cirq/optimizers/eject_z_test.py +++ b/cirq-core/cirq/optimizers/eject_z_test.py @@ -69,16 +69,8 @@ def assert_removes_all_z_gates(circuit: cirq.Circuit, eject_parameterized: bool def test_single_z_stays(): q = cirq.NamedQubit('q') assert_optimizes( - before=cirq.Circuit( - [ - cirq.Moment([cirq.Z(q) ** 0.5]), - ] - ), - expected=cirq.Circuit( - [ - cirq.Moment([cirq.Z(q) ** 0.5]), - ] - ), + before=cirq.Circuit([cirq.Moment([cirq.Z(q) ** 0.5])]), + expected=cirq.Circuit([cirq.Moment([cirq.Z(q) ** 0.5])]), ) @@ -116,56 +108,25 @@ def test_ignores_xz_and_cz(): def test_early_z(): q = cirq.NamedQubit('q') assert_optimizes( - before=cirq.Circuit( - [ - cirq.Moment([cirq.Z(q) ** 0.5]), - cirq.Moment(), - cirq.Moment(), - ] - ), - expected=cirq.Circuit( - [ - cirq.Moment([cirq.Z(q) ** 0.5]), - cirq.Moment(), - cirq.Moment(), - ] - ), + before=cirq.Circuit([cirq.Moment([cirq.Z(q) ** 0.5]), cirq.Moment(), cirq.Moment()]), + expected=cirq.Circuit([cirq.Moment([cirq.Z(q) ** 0.5]), cirq.Moment(), cirq.Moment()]), ) def test_multi_z_merges(): q = cirq.NamedQubit('q') assert_optimizes( - before=cirq.Circuit( - [ - cirq.Moment([cirq.Z(q) ** 0.5]), - cirq.Moment([cirq.Z(q) ** 0.25]), - ] - ), - expected=cirq.Circuit( - [ - cirq.Moment(), - cirq.Moment([cirq.Z(q) ** 0.75]), - ] - ), + before=cirq.Circuit([cirq.Moment([cirq.Z(q) ** 0.5]), cirq.Moment([cirq.Z(q) ** 0.25])]), + expected=cirq.Circuit([cirq.Moment(), cirq.Moment([cirq.Z(q) ** 0.75])]), ) def test_z_pushes_past_xy_and_phases_it(): q = cirq.NamedQubit('q') assert_optimizes( - before=cirq.Circuit( - [ - cirq.Moment([cirq.Z(q) ** 0.5]), - cirq.Moment([cirq.Y(q) ** 0.25]), - ] - ), + before=cirq.Circuit([cirq.Moment([cirq.Z(q) ** 0.5]), cirq.Moment([cirq.Y(q) ** 0.25])]), expected=cirq.Circuit( - [ - cirq.Moment(), - cirq.Moment([cirq.X(q) ** 0.25]), - cirq.Moment([cirq.Z(q) ** 0.5]), - ] + [cirq.Moment(), cirq.Moment([cirq.X(q) ** 0.25]), cirq.Moment([cirq.Z(q) ** 0.5])] ), ) @@ -175,17 +136,10 @@ def test_z_pushes_past_cz(): b = cirq.NamedQubit('b') assert_optimizes( before=cirq.Circuit( - [ - cirq.Moment([cirq.Z(a) ** 0.5]), - cirq.Moment([cirq.CZ(a, b) ** 0.25]), - ] + [cirq.Moment([cirq.Z(a) ** 0.5]), cirq.Moment([cirq.CZ(a, b) ** 0.25])] ), expected=cirq.Circuit( - [ - cirq.Moment(), - cirq.Moment([cirq.CZ(a, b) ** 0.25]), - cirq.Moment([cirq.Z(a) ** 0.5]), - ] + [cirq.Moment(), cirq.Moment([cirq.CZ(a, b) ** 0.25]), cirq.Moment([cirq.Z(a) ** 0.5])] ), ) @@ -200,13 +154,7 @@ def test_measurement_consumes_zs(): cirq.Moment([cirq.measure(q)]), ] ), - expected=cirq.Circuit( - [ - cirq.Moment(), - cirq.Moment(), - cirq.Moment([cirq.measure(q)]), - ] - ), + expected=cirq.Circuit([cirq.Moment(), cirq.Moment(), cirq.Moment([cirq.measure(q)])]), ) @@ -245,13 +193,7 @@ class UnknownGate(cirq.SingleQubitGate): ) -@pytest.mark.parametrize( - 'sym', - [ - sympy.Symbol('a'), - sympy.Symbol('a') + 1, - ], -) +@pytest.mark.parametrize('sym', [sympy.Symbol('a'), sympy.Symbol('a') + 1]) def test_symbols_block(sym): q = cirq.NamedQubit('q') assert_optimizes( @@ -263,22 +205,12 @@ def test_symbols_block(sym): ] ), expected=cirq.Circuit( - [ - cirq.Moment(), - cirq.Moment([cirq.Z(q) ** sym]), - cirq.Moment([cirq.Z(q) ** 1.25]), - ] + [cirq.Moment(), cirq.Moment([cirq.Z(q) ** sym]), cirq.Moment([cirq.Z(q) ** 1.25])] ), ) -@pytest.mark.parametrize( - 'sym', - [ - sympy.Symbol('a'), - sympy.Symbol('a') + 1, - ], -) +@pytest.mark.parametrize('sym', [sympy.Symbol('a'), sympy.Symbol('a') + 1]) def test_symbols_eject(sym): q = cirq.NamedQubit('q') assert_optimizes( @@ -290,11 +222,7 @@ def test_symbols_eject(sym): ] ), expected=cirq.Circuit( - [ - cirq.Moment(), - cirq.Moment(), - cirq.Moment([cirq.Z(q) ** (sym + 1.25)]), - ] + [cirq.Moment(), cirq.Moment(), cirq.Moment([cirq.Z(q) ** (sym + 1.25)])] ), eject_parameterized=True, ) @@ -353,18 +281,8 @@ def with_qubits(self, *new_qubits): u = UnknownOp() assert_optimizes( - before=cirq.Circuit( - [ - cirq.Moment([cirq.Z(q)]), - cirq.Moment([u]), - ] - ), - expected=cirq.Circuit( - [ - cirq.Moment([cirq.Z(q)]), - cirq.Moment([u]), - ] - ), + before=cirq.Circuit([cirq.Moment([cirq.Z(q)]), cirq.Moment([u])]), + expected=cirq.Circuit([cirq.Moment([cirq.Z(q)]), cirq.Moment([u])]), ) diff --git a/cirq-core/cirq/optimizers/expand_composite.py b/cirq-core/cirq/optimizers/expand_composite.py index 9f62f927ed1..2f650961f07 100644 --- a/cirq-core/cirq/optimizers/expand_composite.py +++ b/cirq-core/cirq/optimizers/expand_composite.py @@ -17,10 +17,7 @@ from typing import Callable, Optional, TYPE_CHECKING from cirq import ops, protocols -from cirq.circuits.optimization_pass import ( - PointOptimizer, - PointOptimizationSummary, -) +from cirq.circuits.optimization_pass import PointOptimizer, PointOptimizationSummary from cirq._compat import deprecated_class if TYPE_CHECKING: diff --git a/cirq-core/cirq/optimizers/merge_interactions.py b/cirq-core/cirq/optimizers/merge_interactions.py index 53f13b9dbb9..2fcc59caf06 100644 --- a/cirq-core/cirq/optimizers/merge_interactions.py +++ b/cirq-core/cirq/optimizers/merge_interactions.py @@ -99,10 +99,7 @@ def _may_keep_old_op(self, old_op: 'cirq.Operation') -> bool: @abc.abstractmethod def _two_qubit_matrix_to_cz_operations( - self, - q0: 'cirq.Qid', - q1: 'cirq.Qid', - mat: np.ndarray, + self, q0: 'cirq.Qid', q1: 'cirq.Qid', mat: np.ndarray ) -> Sequence['cirq.Operation']: """Decomposes the merged two-qubit gate unitary into the minimum number of two-qubit gates. @@ -248,10 +245,7 @@ def _may_keep_old_op(self, old_op: 'cirq.Operation') -> bool: return old_op in self.gateset def _two_qubit_matrix_to_cz_operations( - self, - q0: 'cirq.Qid', - q1: 'cirq.Qid', - mat: np.ndarray, + self, q0: 'cirq.Qid', q1: 'cirq.Qid', mat: np.ndarray ) -> Sequence['cirq.Operation']: """Decomposes the merged two-qubit gate unitary into the minimum number of CZ gates. diff --git a/cirq-core/cirq/optimizers/merge_interactions_test.py b/cirq-core/cirq/optimizers/merge_interactions_test.py index 8df5bcf561c..9156c948311 100644 --- a/cirq-core/cirq/optimizers/merge_interactions_test.py +++ b/cirq-core/cirq/optimizers/merge_interactions_test.py @@ -60,12 +60,7 @@ def assert_optimization_not_broken(circuit): def test_clears_paired_cnot(): a, b = cirq.LineQubit.range(2) assert_optimizes( - before=cirq.Circuit( - [ - cirq.Moment([cirq.CNOT(a, b)]), - cirq.Moment([cirq.CNOT(a, b)]), - ] - ), + before=cirq.Circuit([cirq.Moment([cirq.CNOT(a, b)]), cirq.Moment([cirq.CNOT(a, b)])]), expected=cirq.Circuit(), ) @@ -114,25 +109,13 @@ def test_ignores_czs_separated_by_outer_cz(): def test_cnots_separated_by_single_gates_correct(): a, b = cirq.LineQubit.range(2) - assert_optimization_not_broken( - cirq.Circuit( - cirq.CNOT(a, b), - cirq.H(b), - cirq.CNOT(a, b), - ) - ) + assert_optimization_not_broken(cirq.Circuit(cirq.CNOT(a, b), cirq.H(b), cirq.CNOT(a, b))) def test_czs_separated_by_single_gates_correct(): a, b = cirq.LineQubit.range(2) assert_optimization_not_broken( - cirq.Circuit( - cirq.CZ(a, b), - cirq.X(b), - cirq.X(b), - cirq.X(b), - cirq.CZ(a, b), - ) + cirq.Circuit(cirq.CZ(a, b), cirq.X(b), cirq.X(b), cirq.X(b), cirq.CZ(a, b)) ) @@ -200,9 +183,7 @@ def test_not_decompose_czs(): @pytest.mark.parametrize( 'circuit', ( - cirq.Circuit( - cirq.CZPowGate(exponent=0.1)(*cirq.LineQubit.range(2)), - ), + cirq.Circuit(cirq.CZPowGate(exponent=0.1)(*cirq.LineQubit.range(2))), cirq.Circuit( cirq.CZPowGate(exponent=0.2)(*cirq.LineQubit.range(2)), cirq.CZPowGate(exponent=0.3, global_shift=-0.5)(*cirq.LineQubit.range(2)), @@ -229,7 +210,7 @@ def test_decompose_partial_czs(circuit): def test_not_decompose_partial_czs(): circuit = cirq.Circuit( - cirq.CZPowGate(exponent=0.1, global_shift=-0.5)(*cirq.LineQubit.range(2)), + cirq.CZPowGate(exponent=0.1, global_shift=-0.5)(*cirq.LineQubit.range(2)) ) with cirq.testing.assert_deprecated( "Use cirq.optimize_for_target_gateset", deadline='v1.0', count=2 @@ -253,13 +234,7 @@ class Marker(cirq.testing.TwoQubitGate): pass a, b = cirq.LineQubit.range(2) - c_orig = cirq.Circuit( - cirq.CZ(a, b), - cirq.CZ(a, b), - cirq.CZ(a, b), - cirq.CZ(a, b), - cirq.CZ(a, b), - ) + c_orig = cirq.Circuit(cirq.CZ(a, b), cirq.CZ(a, b), cirq.CZ(a, b), cirq.CZ(a, b), cirq.CZ(a, b)) circuit = cirq.Circuit(c_orig) def clean_up(operations): diff --git a/cirq-core/cirq/optimizers/merge_interactions_to_sqrt_iswap.py b/cirq-core/cirq/optimizers/merge_interactions_to_sqrt_iswap.py index 0dcb44b9996..eaf4d8f4a43 100644 --- a/cirq-core/cirq/optimizers/merge_interactions_to_sqrt_iswap.py +++ b/cirq-core/cirq/optimizers/merge_interactions_to_sqrt_iswap.py @@ -86,10 +86,7 @@ def _may_keep_old_op(self, old_op: 'cirq.Operation') -> bool: return old_op in self.gateset def _two_qubit_matrix_to_cz_operations( - self, - q0: 'cirq.Qid', - q1: 'cirq.Qid', - mat: np.ndarray, + self, q0: 'cirq.Qid', q1: 'cirq.Qid', mat: np.ndarray ) -> Sequence['cirq.Operation']: """Decomposes the merged two-qubit gate unitary into the minimum number of SQRT_ISWAP gates. diff --git a/cirq-core/cirq/optimizers/merge_interactions_to_sqrt_iswap_test.py b/cirq-core/cirq/optimizers/merge_interactions_to_sqrt_iswap_test.py index 68458590cf3..119a15637d5 100644 --- a/cirq-core/cirq/optimizers/merge_interactions_to_sqrt_iswap_test.py +++ b/cirq-core/cirq/optimizers/merge_interactions_to_sqrt_iswap_test.py @@ -85,12 +85,7 @@ def assert_optimization_not_broken(circuit: cirq.Circuit, **kwargs): def test_clears_paired_cnot(): a, b = cirq.LineQubit.range(2) assert_optimizes( - before=cirq.Circuit( - [ - cirq.Moment([cirq.CNOT(a, b)]), - cirq.Moment([cirq.CNOT(a, b)]), - ] - ), + before=cirq.Circuit([cirq.Moment([cirq.CNOT(a, b)]), cirq.Moment([cirq.CNOT(a, b)])]), expected=cirq.Circuit(), ) @@ -112,11 +107,7 @@ def test_simplifies_sqrt_iswap(): cirq.Moment([cirq.SQRT_ISWAP(a, b)]), ] ), - expected=cirq.Circuit( - [ - cirq.Moment([cirq.SQRT_ISWAP(a, b)]), - ] - ), + expected=cirq.Circuit([cirq.Moment([cirq.SQRT_ISWAP(a, b)])]), ) @@ -138,11 +129,7 @@ def test_simplifies_sqrt_iswap_inv(): cirq.Moment([cirq.SQRT_ISWAP(a, b)]), ] ), - expected=cirq.Circuit( - [ - cirq.Moment([cirq.SQRT_ISWAP_INV(a, b)]), - ] - ), + expected=cirq.Circuit([cirq.Moment([cirq.SQRT_ISWAP_INV(a, b)])]), ) @@ -156,11 +143,7 @@ def test_works_with_tags(): cirq.Moment([cirq.SQRT_ISWAP_INV(a, b).with_tags('mytag3')]), ] ), - expected=cirq.Circuit( - [ - cirq.Moment([cirq.SQRT_ISWAP(a, b)]), - ] - ), + expected=cirq.Circuit([cirq.Moment([cirq.SQRT_ISWAP(a, b)])]), ) @@ -170,7 +153,7 @@ def test_no_touch_single_sqrt_iswap(): [ cirq.Moment( [cirq.ISwapPowGate(exponent=0.5, global_shift=-0.5).on(a, b).with_tags('mytag')] - ), + ) ] ) assert_optimizes(before=circuit, expected=circuit) @@ -182,7 +165,7 @@ def test_no_touch_single_sqrt_iswap_inv(): [ cirq.Moment( [cirq.ISwapPowGate(exponent=-0.5, global_shift=-0.5).on(a, b).with_tags('mytag')] - ), + ) ] ) assert_optimizes(before=circuit, expected=circuit, use_sqrt_iswap_inv=True) @@ -190,25 +173,13 @@ def test_no_touch_single_sqrt_iswap_inv(): def test_cnots_separated_by_single_gates_correct(): a, b = cirq.LineQubit.range(2) - assert_optimization_not_broken( - cirq.Circuit( - cirq.CNOT(a, b), - cirq.H(b), - cirq.CNOT(a, b), - ) - ) + assert_optimization_not_broken(cirq.Circuit(cirq.CNOT(a, b), cirq.H(b), cirq.CNOT(a, b))) def test_czs_separated_by_single_gates_correct(): a, b = cirq.LineQubit.range(2) assert_optimization_not_broken( - cirq.Circuit( - cirq.CZ(a, b), - cirq.X(b), - cirq.X(b), - cirq.X(b), - cirq.CZ(a, b), - ) + cirq.Circuit(cirq.CZ(a, b), cirq.X(b), cirq.X(b), cirq.X(b), cirq.CZ(a, b)) ) diff --git a/cirq-core/cirq/optimizers/merge_single_qubit_gates.py b/cirq-core/cirq/optimizers/merge_single_qubit_gates.py index 8e59cb801c0..f19110fe5dd 100644 --- a/cirq-core/cirq/optimizers/merge_single_qubit_gates.py +++ b/cirq-core/cirq/optimizers/merge_single_qubit_gates.py @@ -122,10 +122,7 @@ def merge_single_qubit_gates_into_phased_x_z(circuit: circuits.Circuit, atol: fl @_compat.deprecated(deadline='v1.0', fix='Use cirq.merge_single_qubit_gates_to_phxz instead.') -def merge_single_qubit_gates_into_phxz( - circuit: circuits.Circuit, - atol: float = 1e-8, -) -> None: +def merge_single_qubit_gates_into_phxz(circuit: circuits.Circuit, atol: float = 1e-8) -> None: """Canonicalizes runs of single-qubit rotations in a circuit. Specifically, any run of non-parameterized single-qubit gates will be diff --git a/cirq-core/cirq/optimizers/merge_single_qubit_gates_test.py b/cirq-core/cirq/optimizers/merge_single_qubit_gates_test.py index 805965c16d3..ce1d8c86bcc 100644 --- a/cirq-core/cirq/optimizers/merge_single_qubit_gates_test.py +++ b/cirq-core/cirq/optimizers/merge_single_qubit_gates_test.py @@ -121,11 +121,7 @@ def test_ignores_2qubit_target(): m = cirq.MergeSingleQubitGates() q = cirq.NamedQubit('q') q2 = cirq.NamedQubit('q2') - c = cirq.Circuit( - [ - cirq.Moment([cirq.CZ(q, q2)]), - ] - ) + c = cirq.Circuit([cirq.Moment([cirq.CZ(q, q2)])]) m.optimization_at(c, 0, c.operation_at(q, 0)) @@ -137,9 +133,7 @@ class UnsupportedDummy(cirq.SingleQubitGate): pass q0 = cirq.LineQubit(0) - circuit = cirq.Circuit( - UnsupportedDummy()(q0), - ) + circuit = cirq.Circuit(UnsupportedDummy()(q0)) c_orig = cirq.Circuit(circuit) with cirq.testing.assert_deprecated("Use cirq.merge_k_qubit_unitaries", deadline='v1.0'): cirq.MergeSingleQubitGates().optimize_circuit(circuit) @@ -150,13 +144,7 @@ class UnsupportedDummy(cirq.SingleQubitGate): def test_rewrite(): q0 = cirq.LineQubit(0) q1 = cirq.LineQubit(1) - circuit = cirq.Circuit( - cirq.X(q0), - cirq.X(q1), - cirq.Y(q0), - cirq.CZ(q0, q1), - cirq.Y(q1), - ) + circuit = cirq.Circuit(cirq.X(q0), cirq.X(q1), cirq.Y(q0), cirq.CZ(q0, q1), cirq.Y(q1)) with cirq.testing.assert_deprecated("Use cirq.merge_k_qubit_unitaries", deadline='v1.0'): cirq.MergeSingleQubitGates(rewriter=lambda ops: cirq.H(ops[0].qubits[0])).optimize_circuit( circuit @@ -164,26 +152,14 @@ def test_rewrite(): circuit = cirq.drop_empty_moments(circuit) cirq.testing.assert_same_circuits( - circuit, - cirq.Circuit( - cirq.H(q0), - cirq.H(q1), - cirq.CZ(q0, q1), - cirq.H(q1), - ), + circuit, cirq.Circuit(cirq.H(q0), cirq.H(q1), cirq.CZ(q0, q1), cirq.H(q1)) ) def test_merge_single_qubit_gates_into_phased_x_z(): a, b = cirq.LineQubit.range(2) assert_optimizes( - before=cirq.Circuit( - cirq.X(a), - cirq.Y(b) ** 0.5, - cirq.CZ(a, b), - cirq.H(a), - cirq.Z(a), - ), + before=cirq.Circuit(cirq.X(a), cirq.Y(b) ** 0.5, cirq.CZ(a, b), cirq.H(a), cirq.Z(a)), expected=cirq.Circuit( cirq.PhasedXPowGate(phase_exponent=1)(a), cirq.Y(b) ** 0.5, @@ -197,26 +173,13 @@ def test_merge_single_qubit_gates_into_phased_x_z(): def test_merge_single_qubit_gates_into_phxz(): def phxz(a, x, z): - return cirq.PhasedXZGate( - axis_phase_exponent=a, - x_exponent=x, - z_exponent=z, - ) + return cirq.PhasedXZGate(axis_phase_exponent=a, x_exponent=x, z_exponent=z) a, b = cirq.LineQubit.range(2) assert_optimizes( - before=cirq.Circuit( - cirq.X(a), - cirq.Y(b) ** 0.5, - cirq.CZ(a, b), - cirq.H(a), - cirq.Z(a), - ), + before=cirq.Circuit(cirq.X(a), cirq.Y(b) ** 0.5, cirq.CZ(a, b), cirq.H(a), cirq.Z(a)), expected=cirq.Circuit( - phxz(-1, 1, 0).on(a), - phxz(0.5, 0.5, 0).on(b), - cirq.CZ(a, b), - phxz(-0.5, 0.5, 0).on(a), + phxz(-1, 1, 0).on(a), phxz(0.5, 0.5, 0).on(b), cirq.CZ(a, b), phxz(-0.5, 0.5, 0).on(a) ), optimizer=cirq.merge_single_qubit_gates_into_phxz, deprecated_msg="Use cirq.merge_single_qubit_gates_to_phxz", diff --git a/cirq-core/cirq/optimizers/synchronize_terminal_measurements_test.py b/cirq-core/cirq/optimizers/synchronize_terminal_measurements_test.py index 1e2331eaf03..6ed8038339c 100644 --- a/cirq-core/cirq/optimizers/synchronize_terminal_measurements_test.py +++ b/cirq-core/cirq/optimizers/synchronize_terminal_measurements_test.py @@ -55,10 +55,7 @@ def test_simple_partial_align(): q1 = cirq.NamedQubit('q1') q2 = cirq.NamedQubit('q2') before = cirq.Circuit( - [ - cirq.Moment([cirq.measure(q1), cirq.Z(q2)]), - cirq.Moment([cirq.Z(q1), cirq.measure(q2)]), - ] + [cirq.Moment([cirq.measure(q1), cirq.Z(q2)]), cirq.Moment([cirq.Z(q1), cirq.measure(q2)])] ) after = cirq.Circuit( [ @@ -74,11 +71,7 @@ def test_slide_forward_one(): q1 = cirq.NamedQubit('q1') q2 = cirq.NamedQubit('q2') q3 = cirq.NamedQubit('q3') - before = cirq.Circuit( - [ - cirq.Moment([cirq.H(q1), cirq.measure(q2), cirq.measure(q3)]), - ] - ) + before = cirq.Circuit([cirq.Moment([cirq.H(q1), cirq.measure(q2), cirq.measure(q3)])]) after = cirq.Circuit( [cirq.Moment([cirq.H(q1)]), cirq.Moment([cirq.measure(q2), cirq.measure(q3)])] ) @@ -89,16 +82,8 @@ def test_no_slide_forward_one(): q1 = cirq.NamedQubit('q1') q2 = cirq.NamedQubit('q2') q3 = cirq.NamedQubit('q3') - before = cirq.Circuit( - [ - cirq.Moment([cirq.H(q1), cirq.measure(q2), cirq.measure(q3)]), - ] - ) - after = cirq.Circuit( - [ - cirq.Moment([cirq.H(q1), cirq.measure(q2), cirq.measure(q3)]), - ] - ) + before = cirq.Circuit([cirq.Moment([cirq.H(q1), cirq.measure(q2), cirq.measure(q3)])]) + after = cirq.Circuit([cirq.Moment([cirq.H(q1), cirq.measure(q2), cirq.measure(q3)])]) assert_optimizes(before=before, after=after, measure_only_moment=False) diff --git a/cirq-core/cirq/protocols/__init__.py b/cirq-core/cirq/protocols/__init__.py index daf3ddae09c..c568aa95682 100644 --- a/cirq-core/cirq/protocols/__init__.py +++ b/cirq-core/cirq/protocols/__init__.py @@ -14,11 +14,7 @@ """Protocols (structural subtyping) supported in Cirq.""" -from cirq.protocols.act_on_protocol import ( - act_on, - SupportsActOn, - SupportsActOnQubits, -) +from cirq.protocols.act_on_protocol import act_on, SupportsActOn, SupportsActOnQubits from cirq.protocols.apply_unitary_protocol import ( apply_unitaries, apply_unitary, @@ -35,20 +31,9 @@ ApplyMixtureArgs, SupportsApplyMixture, ) -from cirq.protocols.approximate_equality_protocol import ( - approx_eq, - SupportsApproximateEquality, -) -from cirq.protocols.kraus_protocol import ( - kraus, - has_kraus, - SupportsKraus, -) -from cirq.protocols.commutes_protocol import ( - commutes, - definitely_commutes, - SupportsCommutes, -) +from cirq.protocols.approximate_equality_protocol import approx_eq, SupportsApproximateEquality +from cirq.protocols.kraus_protocol import kraus, has_kraus, SupportsKraus +from cirq.protocols.commutes_protocol import commutes, definitely_commutes, SupportsCommutes from cirq.protocols.control_key_protocol import ( control_keys, measurement_keys_touched, @@ -72,16 +57,9 @@ equal_up_to_global_phase, SupportsEqualUpToGlobalPhase, ) -from cirq.protocols.has_stabilizer_effect_protocol import ( - has_stabilizer_effect, -) -from cirq.protocols.has_unitary_protocol import ( - has_unitary, - SupportsExplicitHasUnitary, -) -from cirq.protocols.inverse_protocol import ( - inverse, -) +from cirq.protocols.has_stabilizer_effect_protocol import has_stabilizer_effect +from cirq.protocols.has_unitary_protocol import has_unitary, SupportsExplicitHasUnitary +from cirq.protocols.inverse_protocol import inverse from cirq.protocols.json_serialization import ( cirq_type_from_json, DEFAULT_RESOLVERS, @@ -111,24 +89,12 @@ with_rescoped_keys, SupportsMeasurementKey, ) -from cirq.protocols.mixture_protocol import ( - has_mixture, - mixture, - SupportsMixture, - validate_mixture, -) -from cirq.protocols.mul_protocol import ( - mul, -) -from cirq.protocols.pauli_expansion_protocol import ( - pauli_expansion, - SupportsPauliExpansion, -) +from cirq.protocols.mixture_protocol import has_mixture, mixture, SupportsMixture, validate_mixture +from cirq.protocols.mul_protocol import mul +from cirq.protocols.pauli_expansion_protocol import pauli_expansion, SupportsPauliExpansion # pylint: disable=redefined-builtin -from cirq.protocols.pow_protocol import ( - pow, -) +from cirq.protocols.pow_protocol import pow # pylint: enable=redefined-builtin from cirq.protocols.qasm import ( @@ -152,17 +118,11 @@ resolve_parameters_once, SupportsParameterization, ) -from cirq.protocols.phase_protocol import ( - phase_by, - SupportsPhase, -) +from cirq.protocols.phase_protocol import phase_by, SupportsPhase from cirq.protocols.qid_shape_protocol import ( num_qubits, qid_shape, SupportsExplicitQidShape, SupportsExplicitNumQubits, ) -from cirq.protocols.unitary_protocol import ( - SupportsUnitary, - unitary, -) +from cirq.protocols.unitary_protocol import SupportsUnitary, unitary diff --git a/cirq-core/cirq/protocols/act_on_protocol.py b/cirq-core/cirq/protocols/act_on_protocol.py index 5ab7f9372f5..a38515b30ae 100644 --- a/cirq-core/cirq/protocols/act_on_protocol.py +++ b/cirq-core/cirq/protocols/act_on_protocol.py @@ -59,9 +59,7 @@ class SupportsActOnQubits(Protocol): @doc_private def _act_on_( - self, - args: 'cirq.OperationTarget', - qubits: Sequence['cirq.Qid'], + self, args: 'cirq.OperationTarget', qubits: Sequence['cirq.Qid'] ) -> Union[NotImplementedType, bool]: """Applies an action to the given argument, if it is a supported type. diff --git a/cirq-core/cirq/protocols/apply_channel_protocol.py b/cirq-core/cirq/protocols/apply_channel_protocol.py index c67564fe871..e1f9a282b89 100644 --- a/cirq-core/cirq/protocols/apply_channel_protocol.py +++ b/cirq-core/cirq/protocols/apply_channel_protocol.py @@ -20,10 +20,7 @@ from cirq import linalg from cirq._doc import doc_private -from cirq.protocols.apply_unitary_protocol import ( - apply_unitary, - ApplyUnitaryArgs, -) +from cirq.protocols.apply_unitary_protocol import apply_unitary, ApplyUnitaryArgs from cirq.protocols.kraus_protocol import kraus from cirq.protocols import qid_shape_protocol from cirq.type_workarounds import NotImplementedType diff --git a/cirq-core/cirq/protocols/apply_channel_protocol_test.py b/cirq-core/cirq/protocols/apply_channel_protocol_test.py index e27501cf837..e87d7e5fa6b 100644 --- a/cirq-core/cirq/protocols/apply_channel_protocol_test.py +++ b/cirq-core/cirq/protocols/apply_channel_protocol_test.py @@ -257,8 +257,7 @@ def _apply_unitary_(self, args: cirq.ApplyChannelArgs): val, rho, left_axes=[1], right_axes=[3], assert_result_is_out_buf=True ) np.testing.assert_almost_equal( - result, - np.reshape(np.outer([1, 1j, 1, 1j], [1, -1j, 1, -1j]), shape), + result, np.reshape(np.outer([1, 1j, 1, 1j], [1, -1j, 1, -1j]), shape) ) diff --git a/cirq-core/cirq/protocols/apply_mixture_protocol.py b/cirq-core/cirq/protocols/apply_mixture_protocol.py index 2a5972dfba9..46dd83ece1d 100644 --- a/cirq-core/cirq/protocols/apply_mixture_protocol.py +++ b/cirq-core/cirq/protocols/apply_mixture_protocol.py @@ -20,10 +20,7 @@ from cirq import linalg from cirq._doc import doc_private -from cirq.protocols.apply_unitary_protocol import ( - apply_unitary, - ApplyUnitaryArgs, -) +from cirq.protocols.apply_unitary_protocol import apply_unitary, ApplyUnitaryArgs from cirq.protocols.mixture_protocol import mixture from cirq.protocols import qid_shape_protocol diff --git a/cirq-core/cirq/protocols/apply_unitary_protocol.py b/cirq-core/cirq/protocols/apply_unitary_protocol.py index f73c14d2586..58c8e47d527 100644 --- a/cirq-core/cirq/protocols/apply_unitary_protocol.py +++ b/cirq-core/cirq/protocols/apply_unitary_protocol.py @@ -13,17 +13,7 @@ # limitations under the License. """A protocol for implementing high performance unitary left-multiplies.""" -from typing import ( - Any, - cast, - Iterable, - Optional, - Sequence, - Tuple, - TYPE_CHECKING, - TypeVar, - Union, -) +from typing import Any, cast, Iterable, Optional, Sequence, Tuple, TYPE_CHECKING, TypeVar, Union import numpy as np from typing_extensions import Protocol @@ -31,9 +21,7 @@ from cirq import linalg, qis from cirq._doc import doc_private from cirq.protocols import qid_shape_protocol -from cirq.protocols.decompose_protocol import ( - _try_decompose_into_operations_and_qubits, -) +from cirq.protocols.decompose_protocol import _try_decompose_into_operations_and_qubits from cirq.type_workarounds import NotImplementedType if TYPE_CHECKING: diff --git a/cirq-core/cirq/protocols/apply_unitary_protocol_test.py b/cirq-core/cirq/protocols/apply_unitary_protocol_test.py index aac0f7b23ca..f3304cdc4c2 100644 --- a/cirq-core/cirq/protocols/apply_unitary_protocol_test.py +++ b/cirq-core/cirq/protocols/apply_unitary_protocol_test.py @@ -16,9 +16,7 @@ import pytest import cirq -from cirq.protocols.apply_unitary_protocol import ( - _incorporate_result_into_target, -) +from cirq.protocols.apply_unitary_protocol import _incorporate_result_into_target def test_apply_unitary_presence_absence(): @@ -56,10 +54,7 @@ def _apply_unitary_(self, args: cirq.ApplyUnitaryArgs) -> np.ndarray: args.target_tensor[one] *= -1 return args.target_tensor - fails = [ - NoUnitaryEffect(), - HasApplyReturnsNotImplemented(), - ] + fails = [NoUnitaryEffect(), HasApplyReturnsNotImplemented()] passes = [ HasUnitary(), HasApplyReturnsNotImplementedButHasUnitary(), @@ -283,18 +278,7 @@ def test_apply_unitaries(): unitary_values=[cirq.H(a), cirq.CNOT(a, b), cirq.H(c).controlled_by(b)], qubits=[a, b, c] ) np.testing.assert_allclose( - result.reshape(8), - [ - np.sqrt(0.5), - 0, - 0, - 0, - 0, - 0, - 0.5, - 0.5, - ], - atol=1e-8, + result.reshape(8), [np.sqrt(0.5), 0, 0, 0, 0, 0, 0.5, 0.5], atol=1e-8 ) # Different order. @@ -302,18 +286,7 @@ def test_apply_unitaries(): unitary_values=[cirq.H(a), cirq.CNOT(a, b), cirq.H(c).controlled_by(b)], qubits=[a, c, b] ) np.testing.assert_allclose( - result.reshape(8), - [ - np.sqrt(0.5), - 0, - 0, - 0, - 0, - 0.5, - 0, - 0.5, - ], - atol=1e-8, + result.reshape(8), [np.sqrt(0.5), 0, 0, 0, 0, 0.5, 0, 0.5], atol=1e-8 ) # Explicit arguments. @@ -323,18 +296,7 @@ def test_apply_unitaries(): args=cirq.ApplyUnitaryArgs.default(num_qubits=3), ) np.testing.assert_allclose( - result.reshape(8), - [ - np.sqrt(0.5), - 0, - 0, - 0, - 0, - 0, - 0.5, - 0.5, - ], - atol=1e-8, + result.reshape(8), [np.sqrt(0.5), 0, 0, 0, 0, 0, 0.5, 0.5], atol=1e-8 ) # Empty. diff --git a/cirq-core/cirq/protocols/approximate_equality_protocol_test.py b/cirq-core/cirq/protocols/approximate_equality_protocol_test.py index 575219c5380..7d8f8319143 100644 --- a/cirq-core/cirq/protocols/approximate_equality_protocol_test.py +++ b/cirq-core/cirq/protocols/approximate_equality_protocol_test.py @@ -147,13 +147,7 @@ def test_approx_eq_list(): assert not cirq.approx_eq([], [[]], atol=0.0) assert cirq.approx_eq([1, 1], [1, 1], atol=0.0) assert not cirq.approx_eq([1, 1], [1, 1, 1], atol=0.0) - assert not cirq.approx_eq( - [1, 1], - [ - 1, - ], - atol=0.0, - ) + assert not cirq.approx_eq([1, 1], [1], atol=0.0) assert cirq.approx_eq([1.1, 1.2, 1.3], [1, 1, 1], atol=0.4) assert not cirq.approx_eq([1.1, 1.2, 1.3], [1, 1, 1], atol=0.2) diff --git a/cirq-core/cirq/protocols/circuit_diagram_info_protocol.py b/cirq-core/cirq/protocols/circuit_diagram_info_protocol.py index 9718617a6c7..f54f8306005 100644 --- a/cirq-core/cirq/protocols/circuit_diagram_info_protocol.py +++ b/cirq-core/cirq/protocols/circuit_diagram_info_protocol.py @@ -359,8 +359,7 @@ def _op_info_with_fallback( # pylint: disable=function-redefined @overload def circuit_diagram_info( - val: Any, - args: Optional[CircuitDiagramInfoArgs] = None, + val: Any, args: Optional[CircuitDiagramInfoArgs] = None ) -> CircuitDiagramInfo: pass diff --git a/cirq-core/cirq/protocols/circuit_diagram_info_protocol_test.py b/cirq-core/cirq/protocols/circuit_diagram_info_protocol_test.py index 59f803d7abe..78ed0aebe78 100644 --- a/cirq-core/cirq/protocols/circuit_diagram_info_protocol_test.py +++ b/cirq-core/cirq/protocols/circuit_diagram_info_protocol_test.py @@ -50,12 +50,7 @@ def _circuit_diagram_info_(self, args): == single_info ) - double_info = cirq.CircuitDiagramInfo( - ( - 'Single', - 'Double', - ) - ) + double_info = cirq.CircuitDiagramInfo(('Single', 'Double')) class ReturnDoubleInfo: def _circuit_diagram_info_(self, args): diff --git a/cirq-core/cirq/protocols/commutes_protocol.py b/cirq-core/cirq/protocols/commutes_protocol.py index 73ea8d2a40f..d040c8cae28 100644 --- a/cirq-core/cirq/protocols/commutes_protocol.py +++ b/cirq-core/cirq/protocols/commutes_protocol.py @@ -122,10 +122,7 @@ def commutes( """ atol = float(atol) - strats = [ - _strat_commutes_from_commutes, - _strat_commutes_from_matrix, - ] + strats = [_strat_commutes_from_commutes, _strat_commutes_from_matrix] for strat in strats: result = strat(v1, v2, atol=atol) if result is None: @@ -172,10 +169,7 @@ def _strat_commutes_from_commutes( def _strat_commutes_from_matrix( - v1: Any, - v2: Any, - *, - atol: float, + v1: Any, v2: Any, *, atol: float ) -> Union[bool, NotImplementedType, None]: """Attempts to determine commutativity of matrices.""" if not isinstance(v1, np.ndarray) or not isinstance(v2, np.ndarray): diff --git a/cirq-core/cirq/protocols/decompose_protocol.py b/cirq-core/cirq/protocols/decompose_protocol.py index da90f47be40..5df17acfb6e 100644 --- a/cirq-core/cirq/protocols/decompose_protocol.py +++ b/cirq-core/cirq/protocols/decompose_protocol.py @@ -318,9 +318,7 @@ def decompose_once_with_qubits(val: Any, qubits: Iterable['cirq.Qid']) -> List[' @overload def decompose_once_with_qubits( - val: Any, - qubits: Iterable['cirq.Qid'], - default: Optional[TDefault], + val: Any, qubits: Iterable['cirq.Qid'], default: Optional[TDefault] ) -> Union[TDefault, List['cirq.Operation']]: pass diff --git a/cirq-core/cirq/protocols/decompose_protocol_test.py b/cirq-core/cirq/protocols/decompose_protocol_test.py index fcbfb1ae0a8..71f607b407b 100644 --- a/cirq-core/cirq/protocols/decompose_protocol_test.py +++ b/cirq-core/cirq/protocols/decompose_protocol_test.py @@ -267,11 +267,7 @@ def keep_func(op: 'cirq.Operation'): def x_to_hzh(op: 'cirq.Operation'): if isinstance(op.gate, cirq.XPowGate) and op.gate.exponent == 1: - return [ - cirq.H(*op.qubits), - cirq.Z(*op.qubits), - cirq.H(*op.qubits), - ] + return [cirq.H(*op.qubits), cirq.Z(*op.qubits), cirq.H(*op.qubits)] actual = cirq.Circuit( cirq.decompose( @@ -280,16 +276,12 @@ def x_to_hzh(op: 'cirq.Operation'): intercepting_decomposer=x_to_hzh if decompose_mode == 'intercept' else None, fallback_decomposer=x_to_hzh if decompose_mode == 'fallback' else None, preserve_structure=True, - ), + ) ) # This should keep the CircuitOperations but decompose their SWAPs. fc1_decomp = cirq.FrozenCircuit( - cirq.decompose( - fc1, - keep=keep_func, - fallback_decomposer=x_to_hzh, - ) + cirq.decompose(fc1, keep=keep_func, fallback_decomposer=x_to_hzh) ) expected = cirq.Circuit( cirq.CircuitOperation( @@ -310,12 +302,8 @@ def test_decompose_tagged_operation(): op = cirq.TaggedOperation( cirq.CircuitOperation( circuit=cirq.FrozenCircuit( - [ - cirq.Moment( - cirq.SWAP(cirq.LineQubit(0), cirq.LineQubit(1)), - ), - ] - ), + [cirq.Moment(cirq.SWAP(cirq.LineQubit(0), cirq.LineQubit(1)))] + ) ), 'tag', ) diff --git a/cirq-core/cirq/protocols/has_stabilizer_effect_protocol.py b/cirq-core/cirq/protocols/has_stabilizer_effect_protocol.py index 09064d6bf0e..4aa46053cc4 100644 --- a/cirq-core/cirq/protocols/has_stabilizer_effect_protocol.py +++ b/cirq-core/cirq/protocols/has_stabilizer_effect_protocol.py @@ -12,10 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from typing import ( - Any, - Optional, -) +from typing import Any, Optional from cirq.ops.clifford_gate import SingleQubitCliffordGate diff --git a/cirq-core/cirq/protocols/has_unitary_protocol.py b/cirq-core/cirq/protocols/has_unitary_protocol.py index 95af9aad416..2ac33ee3f73 100644 --- a/cirq-core/cirq/protocols/has_unitary_protocol.py +++ b/cirq-core/cirq/protocols/has_unitary_protocol.py @@ -12,11 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from typing import ( - Any, - TypeVar, - Optional, -) +from typing import Any, TypeVar, Optional import numpy as np from typing_extensions import Protocol @@ -25,9 +21,7 @@ from cirq._doc import doc_private from cirq.protocols import qid_shape_protocol from cirq.protocols.apply_unitary_protocol import ApplyUnitaryArgs -from cirq.protocols.decompose_protocol import ( - _try_decompose_into_operations_and_qubits, -) +from cirq.protocols.decompose_protocol import _try_decompose_into_operations_and_qubits TDefault = TypeVar('TDefault') diff --git a/cirq-core/cirq/protocols/has_unitary_protocol_test.py b/cirq-core/cirq/protocols/has_unitary_protocol_test.py index f0222013801..20530cb92b9 100644 --- a/cirq-core/cirq/protocols/has_unitary_protocol_test.py +++ b/cirq-core/cirq/protocols/has_unitary_protocol_test.py @@ -28,11 +28,7 @@ class No: @pytest.mark.parametrize( - 'measurement_gate', - ( - cirq.MeasurementGate(1, 'a'), - cirq.PauliMeasurementGate([cirq.X], 'a'), - ), + 'measurement_gate', (cirq.MeasurementGate(1, 'a'), cirq.PauliMeasurementGate([cirq.X], 'a')) ) def test_fail_fast_measure(measurement_gate): assert not cirq.has_unitary(measurement_gate) diff --git a/cirq-core/cirq/protocols/inverse_protocol_test.py b/cirq-core/cirq/protocols/inverse_protocol_test.py index f1d95096cb2..8fd65f3ea18 100644 --- a/cirq-core/cirq/protocols/inverse_protocol_test.py +++ b/cirq-core/cirq/protocols/inverse_protocol_test.py @@ -48,14 +48,7 @@ def __iter__(self): @pytest.mark.parametrize( - 'val', - ( - NoMethod(), - 'text', - object(), - ReturnsNotImplemented(), - [NoMethod(), 5], - ), + 'val', (NoMethod(), 'text', object(), ReturnsNotImplemented(), [NoMethod(), 5]) ) def test_objects_with_no_inverse(val): with pytest.raises(TypeError, match="isn't invertible"): diff --git a/cirq-core/cirq/protocols/json_serialization.py b/cirq-core/cirq/protocols/json_serialization.py index b82b10576ae..e62f91eb062 100644 --- a/cirq-core/cirq/protocols/json_serialization.py +++ b/cirq-core/cirq/protocols/json_serialization.py @@ -343,11 +343,7 @@ def default(self, o): return {'cirq_type': 'sympy.Float', 'approx': float(o)} if isinstance(o, sympy.Rational): - return { - 'cirq_type': 'sympy.Rational', - 'p': o.p, - 'q': o.q, - } + return {'cirq_type': 'sympy.Rational', 'p': o.p, 'q': o.q} if isinstance(o, sympy.NumberSymbol): # check if `o` is a numeric symbol, @@ -367,11 +363,7 @@ def default(self, o): if isinstance(o, numbers.Real): return float(o) if isinstance(o, numbers.Complex): - return { - 'cirq_type': 'complex', - 'real': o.real, - 'imag': o.imag, - } + return {'cirq_type': 'complex', 'real': o.real, 'imag': o.imag} # Numpy object? if isinstance(o, np.bool_): @@ -381,17 +373,9 @@ def default(self, o): # Pandas object? if isinstance(o, pd.MultiIndex): - return { - 'cirq_type': 'pandas.MultiIndex', - 'tuples': list(o), - 'names': list(o.names), - } + return {'cirq_type': 'pandas.MultiIndex', 'tuples': list(o), 'names': list(o.names)} if isinstance(o, pd.Index): - return { - 'cirq_type': 'pandas.Index', - 'data': list(o), - 'name': o.name, - } + return {'cirq_type': 'pandas.Index', 'data': list(o), 'name': o.name} if isinstance(o, pd.DataFrame): cols = [o[col].tolist() for col in o.columns] rows = list(zip(*cols)) diff --git a/cirq-core/cirq/protocols/json_serialization_test.py b/cirq-core/cirq/protocols/json_serialization_test.py index fa2c862df37..b0edff1176f 100644 --- a/cirq-core/cirq/protocols/json_serialization_test.py +++ b/cirq-core/cirq/protocols/json_serialization_test.py @@ -343,14 +343,7 @@ def test_builtins(): assert_json_roundtrip_works(True) assert_json_roundtrip_works(1) assert_json_roundtrip_works(1 + 2j) - assert_json_roundtrip_works( - { - 'test': [123, 5.5], - 'key2': 'asdf', - '3': None, - '0.0': [], - } - ) + assert_json_roundtrip_works({'test': [123, 5.5], 'key2': 'asdf', '3': None, '0.0': []}) def test_numpy(): @@ -548,10 +541,7 @@ def _list_public_classes_for_tested_modules(): ) -@pytest.mark.parametrize( - 'mod_spec,cirq_obj_name,cls', - _list_public_classes_for_tested_modules(), -) +@pytest.mark.parametrize('mod_spec,cirq_obj_name,cls', _list_public_classes_for_tested_modules()) def test_json_test_data_coverage(mod_spec: ModuleJsonTestSpec, cirq_obj_name: str, cls): if cirq_obj_name in mod_spec.tested_elsewhere: pytest.skip("Tested elsewhere.") @@ -631,19 +621,14 @@ class SerializableTypeObject: test_type: Type def _json_dict_(self): - return { - 'test_type': json_serialization.json_cirq_type(self.test_type), - } + return {'test_type': json_serialization.json_cirq_type(self.test_type)} @classmethod def _from_json_dict_(cls, test_type, **kwargs): return cls(json_serialization.cirq_type_from_json(test_type)) -@pytest.mark.parametrize( - 'mod_spec,cirq_obj_name,cls', - _list_public_classes_for_tested_modules(), -) +@pytest.mark.parametrize('mod_spec,cirq_obj_name,cls', _list_public_classes_for_tested_modules()) def test_type_serialization(mod_spec: ModuleJsonTestSpec, cirq_obj_name: str, cls): if cirq_obj_name in mod_spec.tested_elsewhere: pytest.skip("Tested elsewhere.") @@ -738,11 +723,7 @@ def _eval_repr_data_file(path: pathlib.Path, deprecation_deadline: Optional[str] with contextlib.ExitStack() as stack: for ctx_manager in ctx_managers: stack.enter_context(ctx_manager) - obj = eval( - content, - imports, - {}, - ) + obj = eval(content, imports, {}) return obj diff --git a/cirq-core/cirq/protocols/json_test_data/spec.py b/cirq-core/cirq/protocols/json_test_data/spec.py index 20595dd03bb..8fc2e49f64d 100644 --- a/cirq-core/cirq/protocols/json_test_data/spec.py +++ b/cirq-core/cirq/protocols/json_test_data/spec.py @@ -188,13 +188,10 @@ 'Unique', 'DEFAULT_RESOLVERS', ], - deprecated={ - 'GlobalPhaseOperation': 'v0.16', - 'SymmetricalQidPair': 'v0.15', - }, + deprecated={'GlobalPhaseOperation': 'v0.16', 'SymmetricalQidPair': 'v0.15'}, tested_elsewhere=[ # SerializableByKey does not follow common serialization rules. # It is tested separately in test_context_serialization. - 'SerializableByKey', + 'SerializableByKey' ], ) diff --git a/cirq-core/cirq/protocols/kraus_protocol.py b/cirq-core/cirq/protocols/kraus_protocol.py index b6e3856488c..b5fe94be3a0 100644 --- a/cirq-core/cirq/protocols/kraus_protocol.py +++ b/cirq-core/cirq/protocols/kraus_protocol.py @@ -21,9 +21,7 @@ from typing_extensions import Protocol from cirq._doc import doc_private -from cirq.protocols.decompose_protocol import ( - _try_decompose_into_operations_and_qubits, -) +from cirq.protocols.decompose_protocol import _try_decompose_into_operations_and_qubits from cirq.protocols.mixture_protocol import has_mixture diff --git a/cirq-core/cirq/protocols/measurement_key_protocol.py b/cirq-core/cirq/protocols/measurement_key_protocol.py index 20b6fa29695..ac7fb637a13 100644 --- a/cirq-core/cirq/protocols/measurement_key_protocol.py +++ b/cirq-core/cirq/protocols/measurement_key_protocol.py @@ -311,9 +311,7 @@ def with_key_path_prefix(val: Any, prefix: Tuple[str, ...]): def with_rescoped_keys( - val: Any, - path: Tuple[str, ...], - bindable_keys: FrozenSet['cirq.MeasurementKey'] = None, + val: Any, path: Tuple[str, ...], bindable_keys: FrozenSet['cirq.MeasurementKey'] = None ): """Rescopes any measurement and control keys to the provided path, given the existing keys. diff --git a/cirq-core/cirq/protocols/pauli_expansion_protocol_test.py b/cirq-core/cirq/protocols/pauli_expansion_protocol_test.py index 6e7e98c528c..20b733a1486 100644 --- a/cirq-core/cirq/protocols/pauli_expansion_protocol_test.py +++ b/cirq-core/cirq/protocols/pauli_expansion_protocol_test.py @@ -52,16 +52,7 @@ def _unitary_(self) -> np.ndarray: @pytest.mark.parametrize( - 'val', - ( - NoMethod(), - ReturnsNotImplemented(), - HasQuditUnitary(), - 123, - np.eye(2), - object(), - cirq, - ), + 'val', (NoMethod(), ReturnsNotImplemented(), HasQuditUnitary(), 123, np.eye(2), object(), cirq) ) def test_raises_no_pauli_expansion(val): assert cirq.pauli_expansion(val, default=None) is None diff --git a/cirq-core/cirq/protocols/pow_protocol_test.py b/cirq-core/cirq/protocols/pow_protocol_test.py index 12185ee003b..1cb862ee883 100644 --- a/cirq-core/cirq/protocols/pow_protocol_test.py +++ b/cirq-core/cirq/protocols/pow_protocol_test.py @@ -31,15 +31,7 @@ def __pow__(self, exponent) -> int: return exponent -@pytest.mark.parametrize( - 'val', - ( - NoMethod(), - 'text', - object(), - ReturnsNotImplemented(), - ), -) +@pytest.mark.parametrize('val', (NoMethod(), 'text', object(), ReturnsNotImplemented())) def test_powerless(val): assert cirq.pow(val, 5, None) is None assert cirq.pow(val, 2, NotImplemented) is NotImplemented @@ -55,14 +47,7 @@ def test_pow_error(): _ = cirq.pow(NoMethod(), 3) -@pytest.mark.parametrize( - 'val,exponent,out', - ( - (ReturnsExponent(), 2, 2), - (1, 2, 1), - (2, 3, 8), - ), -) +@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 diff --git a/cirq-core/cirq/protocols/resolve_parameters_test.py b/cirq-core/cirq/protocols/resolve_parameters_test.py index a7fc25a17eb..7f0ac378319 100644 --- a/cirq-core/cirq/protocols/resolve_parameters_test.py +++ b/cirq-core/cirq/protocols/resolve_parameters_test.py @@ -18,13 +18,7 @@ from cirq.study import ParamResolver -@pytest.mark.parametrize( - 'resolve_fn', - [ - cirq.resolve_parameters, - cirq.resolve_parameters_once, - ], -) +@pytest.mark.parametrize('resolve_fn', [cirq.resolve_parameters, cirq.resolve_parameters_once]) def test_resolve_parameters(resolve_fn): class NoMethod: pass @@ -109,13 +103,7 @@ def test_parameter_names(): assert cirq.parameter_names(1j) == set() -@pytest.mark.parametrize( - 'resolve_fn', - [ - cirq.resolve_parameters, - cirq.resolve_parameters_once, - ], -) +@pytest.mark.parametrize('resolve_fn', [cirq.resolve_parameters, cirq.resolve_parameters_once]) def test_skips_empty_resolution(resolve_fn): class Tester: def _resolve_parameters_(self, resolver, recursive): diff --git a/cirq-core/cirq/protocols/unitary_protocol.py b/cirq-core/cirq/protocols/unitary_protocol.py index a94583d6a8d..ecc38214e9f 100644 --- a/cirq-core/cirq/protocols/unitary_protocol.py +++ b/cirq-core/cirq/protocols/unitary_protocol.py @@ -12,12 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from typing import ( - Any, - TypeVar, - Union, - Optional, -) +from typing import Any, TypeVar, Union, Optional import numpy as np from typing_extensions import Protocol @@ -25,13 +20,8 @@ from cirq import qis from cirq._doc import doc_private from cirq.protocols import qid_shape_protocol -from cirq.protocols.apply_unitary_protocol import ( - ApplyUnitaryArgs, - apply_unitaries, -) -from cirq.protocols.decompose_protocol import ( - _try_decompose_into_operations_and_qubits, -) +from cirq.protocols.apply_unitary_protocol import ApplyUnitaryArgs, apply_unitaries +from cirq.protocols.decompose_protocol import _try_decompose_into_operations_and_qubits from cirq.type_workarounds import NotImplementedType # This is a special indicator value used by the unitary method to determine diff --git a/cirq-core/cirq/qis/__init__.py b/cirq-core/cirq/qis/__init__.py index 3faccde034e..9fbed5de10f 100644 --- a/cirq-core/cirq/qis/__init__.py +++ b/cirq-core/cirq/qis/__init__.py @@ -27,11 +27,7 @@ from cirq.qis.clifford_tableau import CliffordTableau, QuantumStateRepresentation, StabilizerState -from cirq.qis.measures import ( - entanglement_fidelity, - fidelity, - von_neumann_entropy, -) +from cirq.qis.measures import entanglement_fidelity, fidelity, von_neumann_entropy from cirq.qis.states import ( bloch_vector_from_state_vector, diff --git a/cirq-core/cirq/qis/channels_test.py b/cirq-core/cirq/qis/channels_test.py index 6856684be9e..9132918ea07 100644 --- a/cirq-core/cirq/qis/channels_test.py +++ b/cirq-core/cirq/qis/channels_test.py @@ -128,6 +128,7 @@ def test_choi_to_kraus_invalid_input(choi, error): ), ( # Amplitude damping channel + # fmt: off np.array( [ [1, 0, 0, 0.8], @@ -136,6 +137,7 @@ def test_choi_to_kraus_invalid_input(choi, error): [0.8, 0, 0, 0.64], ], ), + # fmt: off (np.diag([1, 0.8]), np.array([[0, 0.6], [0, 0]])), ), ( @@ -204,6 +206,7 @@ def test_choi_to_kraus_action_on_operatorial_basis(choi): np.eye(4), np.diag([1, 0, 0, 1]), np.diag([0.2, 0.3, 0.8, 0.7]), + # fmt: off np.array( [ [1, 0, 1, 0], @@ -220,6 +223,7 @@ def test_choi_to_kraus_action_on_operatorial_basis(choi): [0.5, 0, 0, 0.7], ], ), + # fmt: on ), ) def test_choi_to_kraus_inverse_of_kraus_to_choi(choi): @@ -291,6 +295,7 @@ def test_superoperator_to_kraus_fixed_values(superoperator, expected_kraus_opera np.eye(4), np.diag([1, 0, 0, 1]), np.diag([1, -1j, 1j, 1]), + # fmt: off np.array( [ [1, 0, 0, 1], @@ -307,6 +312,7 @@ def test_superoperator_to_kraus_fixed_values(superoperator, expected_kraus_opera [0, 0, 0, 0.64], ], ), + # fmt: on ), ) def test_superoperator_to_kraus_inverse_of_kraus_to_superoperator(superoperator): @@ -347,11 +353,7 @@ def test_choi_to_superoperator_invalid_input(choi, error): @pytest.mark.parametrize( - 'superoperator, error', - ( - (np.array([[1, 2, 3], [4, 5, 6]]), "shape"), - (np.eye(2), "shape"), - ), + 'superoperator, error', ((np.array([[1, 2, 3], [4, 5, 6]]), "shape"), (np.eye(2), "shape")) ) def test_superoperator_to_choi_invalid_input(superoperator, error): with pytest.raises(ValueError, match=error): @@ -383,6 +385,7 @@ def test_superoperator_to_choi_invalid_input(superoperator, error): ), ( # Amplitude damping channel + # fmt: off np.array( [ [1, 0, 0, 0.36], @@ -399,6 +402,7 @@ def test_superoperator_to_choi_invalid_input(superoperator, error): [0.8, 0, 0, 0.64], ], ), + # fmt: on ), ( # Completely depolarizing channel @@ -421,6 +425,7 @@ def test_superoperator_vs_choi_fixed_values(superoperator, choi): np.eye(4), np.diag([1, 0, 0, 1]), np.diag([0.2, 0.3, 0.8, 0.7]), + # fmt: off np.array( [ [1, 0, 1, 0], @@ -437,6 +442,7 @@ def test_superoperator_vs_choi_fixed_values(superoperator, choi): [0.5, 0, 0, 0.7], ], ), + # fmt: on ), ) def test_choi_to_superoperator_inverse_of_superoperator_to_choi(choi): diff --git a/cirq-core/cirq/qis/states.py b/cirq-core/cirq/qis/states.py index 65f13562f20..394d1860d54 100644 --- a/cirq-core/cirq/qis/states.py +++ b/cirq-core/cirq/qis/states.py @@ -13,18 +13,7 @@ # limitations under the License. """Classes and methods for quantum states.""" -from typing import ( - Any, - cast, - Iterable, - List, - Optional, - Sequence, - Set, - TYPE_CHECKING, - Tuple, - Union, -) +from typing import Any, cast, Iterable, List, Optional, Sequence, Set, TYPE_CHECKING, Tuple, Union import itertools import numpy as np @@ -182,10 +171,7 @@ def validate( state_vector = self.state_vector() assert state_vector is not None validate_normalized_state_vector( - state_vector, - qid_shape=self.qid_shape, - dtype=dtype, - atol=atol, + state_vector, qid_shape=self.qid_shape, dtype=dtype, atol=atol ) elif self._is_density_matrix(): validate_density_matrix( diff --git a/cirq-core/cirq/qis/states_test.py b/cirq-core/cirq/qis/states_test.py index f4073b48715..60058383216 100644 --- a/cirq-core/cirq/qis/states_test.py +++ b/cirq-core/cirq/qis/states_test.py @@ -546,8 +546,7 @@ def test_invalid_to_valid_state_vector(): def test_validate_normalized_state(): cirq.validate_normalized_state_vector(cirq.testing.random_superposition(2), qid_shape=(2,)) cirq.validate_normalized_state_vector( - np.array([0.5, 0.5, 0.5, 0.5], dtype=np.complex64), - qid_shape=(2, 2), + np.array([0.5, 0.5, 0.5, 0.5], dtype=np.complex64), qid_shape=(2, 2) ) with pytest.raises(ValueError, match='invalid dtype'): cirq.validate_normalized_state_vector( @@ -708,8 +707,7 @@ def test_to_valid_density_matrix_from_state_vector(): def test_to_valid_density_matrix_from_state_vector_tensor(): np.testing.assert_almost_equal( cirq.to_valid_density_matrix( - density_matrix_rep=np.array(np.full((2, 2), 0.5), dtype=np.complex64), - num_qubits=2, + density_matrix_rep=np.array(np.full((2, 2), 0.5), dtype=np.complex64), num_qubits=2 ), 0.25 * np.ones((4, 4)), ) diff --git a/cirq-core/cirq/sim/__init__.py b/cirq-core/cirq/sim/__init__.py index 69bf0ef8fa4..307047c8d30 100644 --- a/cirq-core/cirq/sim/__init__.py +++ b/cirq-core/cirq/sim/__init__.py @@ -15,26 +15,15 @@ """Classes for circuit simulators and base implementations of these classes.""" from typing import Tuple, Dict -from cirq.sim.act_on_args import ( - ActOnArgs, -) +from cirq.sim.act_on_args import ActOnArgs -from cirq.sim.act_on_args_container import ( - ActOnArgsContainer, -) +from cirq.sim.act_on_args_container import ActOnArgsContainer -from cirq.sim.act_on_density_matrix_args import ( - ActOnDensityMatrixArgs, -) +from cirq.sim.act_on_density_matrix_args import ActOnDensityMatrixArgs -from cirq.sim.act_on_state_vector_args import ( - ActOnStateVectorArgs, -) +from cirq.sim.act_on_state_vector_args import ActOnStateVectorArgs -from cirq.sim.density_matrix_utils import ( - measure_density_matrix, - sample_density_matrix, -) +from cirq.sim.density_matrix_utils import measure_density_matrix, sample_density_matrix from cirq.sim.density_matrix_simulator import ( DensityMatrixSimulator, @@ -63,16 +52,9 @@ StepResult, ) -from cirq.sim.simulator_base import ( - SimulationTrialResultBase, - SimulatorBase, - StepResultBase, -) +from cirq.sim.simulator_base import SimulationTrialResultBase, SimulatorBase, StepResultBase -from cirq.sim.sparse_simulator import ( - Simulator, - SparseSimulatorStep, -) +from cirq.sim.sparse_simulator import Simulator, SparseSimulatorStep from cirq.sim.state_vector_simulator import ( SimulatesIntermediateStateVector, @@ -81,11 +63,7 @@ StateVectorTrialResult, ) -from cirq.sim.state_vector import ( - measure_state_vector, - sample_state_vector, - StateVectorMixin, -) +from cirq.sim.state_vector import measure_state_vector, sample_state_vector, StateVectorMixin from cirq.sim.clifford import ( ActOnCliffordTableauArgs, diff --git a/cirq-core/cirq/sim/act_on_args_container_test.py b/cirq-core/cirq/sim/act_on_args_container_test.py index c0fdcb82a5a..92dde560fdb 100644 --- a/cirq-core/cirq/sim/act_on_args_container_test.py +++ b/cirq-core/cirq/sim/act_on_args_container_test.py @@ -39,17 +39,10 @@ def reindex(self, axes): class EmptyActOnArgs(cirq.ActOnArgs): def __init__(self, qubits, classical_data): - super().__init__( - state=EmptyQuantumState(), - qubits=qubits, - classical_data=classical_data, - ) + super().__init__(state=EmptyQuantumState(), qubits=qubits, classical_data=classical_data) def _act_on_fallback_( - self, - action: Any, - qubits: Sequence['cirq.Qid'], - allow_decompose: bool = True, + self, action: Any, qubits: Sequence['cirq.Qid'], allow_decompose: bool = True ) -> bool: return True @@ -59,8 +52,7 @@ def _act_on_fallback_( def create_container( - qubits: Sequence['cirq.Qid'], - split_untangled_states=True, + qubits: Sequence['cirq.Qid'], split_untangled_states=True ) -> cirq.ActOnArgsContainer[EmptyActOnArgs]: args_map: Dict[Optional['cirq.Qid'], EmptyActOnArgs] = {} log = cirq.ClassicalDataDictionaryStore() diff --git a/cirq-core/cirq/sim/act_on_density_matrix_args_test.py b/cirq-core/cirq/sim/act_on_density_matrix_args_test.py index e82685bd452..559759f5f10 100644 --- a/cirq-core/cirq/sim/act_on_density_matrix_args_test.py +++ b/cirq-core/cirq/sim/act_on_density_matrix_args_test.py @@ -23,10 +23,7 @@ def test_default_parameter(): tensor = cirq.to_valid_density_matrix( 0, len(qid_shape), qid_shape=qid_shape, dtype=np.complex64 ) - args = cirq.ActOnDensityMatrixArgs( - qubits=cirq.LineQubit.range(1), - initial_state=0, - ) + args = cirq.ActOnDensityMatrixArgs(qubits=cirq.LineQubit.range(1), initial_state=0) np.testing.assert_almost_equal(args.target_tensor, tensor) assert len(args.available_buffer) == 3 for buffer in args.available_buffer: @@ -36,10 +33,7 @@ def test_default_parameter(): def test_shallow_copy_buffers(): - args = cirq.ActOnDensityMatrixArgs( - qubits=cirq.LineQubit.range(1), - initial_state=0, - ) + args = cirq.ActOnDensityMatrixArgs(qubits=cirq.LineQubit.range(1), initial_state=0) copy = args.copy(deep_copy_buffers=False) assert copy.available_buffer is args.available_buffer @@ -81,9 +75,7 @@ class NoDetails: def test_with_qubits(): original = cirq.ActOnDensityMatrixArgs( - qubits=cirq.LineQubit.range(1), - initial_state=1, - dtype=np.complex64, + qubits=cirq.LineQubit.range(1), initial_state=1, dtype=np.complex64 ) extened = original.with_qubits(cirq.LineQubit.range(1, 2)) np.testing.assert_almost_equal( diff --git a/cirq-core/cirq/sim/act_on_state_vector_args_test.py b/cirq-core/cirq/sim/act_on_state_vector_args_test.py index ddf51fd7c2b..dd08eeca095 100644 --- a/cirq-core/cirq/sim/act_on_state_vector_args_test.py +++ b/cirq-core/cirq/sim/act_on_state_vector_args_test.py @@ -24,17 +24,10 @@ def test_default_parameter(): dtype = np.complex64 tensor = cirq.one_hot(shape=(2, 2, 2), dtype=np.complex64) qubits = cirq.LineQubit.range(3) - args = cirq.ActOnStateVectorArgs( - qubits=qubits, - initial_state=tensor, - dtype=dtype, - ) + args = cirq.ActOnStateVectorArgs(qubits=qubits, initial_state=tensor, dtype=dtype) qid_shape = cirq.protocols.qid_shape(qubits) tensor = np.reshape(tensor, qid_shape) - np.testing.assert_almost_equal( - args.target_tensor, - tensor, - ) + np.testing.assert_almost_equal(args.target_tensor, tensor) assert args.available_buffer.shape == tensor.shape assert args.available_buffer.dtype == tensor.dtype @@ -51,11 +44,7 @@ def test_infer_target_tensor(): np.array([[1.0 + 0.0j, 0.0 + 0.0j], [0.0 + 0.0j, 0.0 + 0.0j]], dtype=dtype), ) - args = cirq.ActOnStateVectorArgs( - qubits=cirq.LineQubit.range(2), - initial_state=0, - dtype=dtype, - ) + args = cirq.ActOnStateVectorArgs(qubits=cirq.LineQubit.range(2), initial_state=0, dtype=dtype) np.testing.assert_almost_equal( args.target_tensor, np.array([[1.0 + 0.0j, 0.0 + 0.0j], [0.0 + 0.0j, 0.0 + 0.0j]], dtype=dtype), @@ -63,10 +52,7 @@ def test_infer_target_tensor(): def test_shallow_copy_buffers(): - args = cirq.ActOnStateVectorArgs( - qubits=cirq.LineQubit.range(1), - initial_state=0, - ) + args = cirq.ActOnStateVectorArgs(qubits=cirq.LineQubit.range(1), initial_state=0) copy = args.copy(deep_copy_buffers=False) assert copy.available_buffer is args.available_buffer @@ -115,10 +101,7 @@ def num_qubits(self) -> int: return 1 def _kraus_(self): - return [ - cirq.unitary(cirq.S) * np.sqrt(1 / 3), - cirq.unitary(cirq.X) * np.sqrt(2 / 3), - ] + return [cirq.unitary(cirq.S) * np.sqrt(1 / 3), cirq.unitary(cirq.X) * np.sqrt(2 / 3)] initial_state = cirq.testing.random_superposition(dim=16).reshape((2,) * 4) mock_prng = mock.Mock() @@ -211,8 +194,7 @@ def assert_not_affected(state: np.ndarray, sample: float): # Always acts like identity when sample < p=3/4. for _ in range(10): assert_not_affected( - cirq.testing.random_superposition(dim=16).reshape((2,) * 4), - sample=3 / 4 - 1e-8, + cirq.testing.random_superposition(dim=16).reshape((2,) * 4), sample=3 / 4 - 1e-8 ) # Acts like identity on superpositions of first three states. @@ -222,10 +204,7 @@ def assert_not_affected(state: np.ndarray, sample: float): projected_state[cirq.slice_for_qubits_equal_to([1, 3], 3)] = 0 projected_state /= np.linalg.norm(projected_state) assert abs(np.linalg.norm(projected_state) - 1) < 1e-8 - assert_not_affected( - projected_state, - sample=3 / 4 + 1e-8, - ) + assert_not_affected(projected_state, sample=3 / 4 + 1e-8) def test_probability_comes_up_short_results_in_fallback(): @@ -234,10 +213,7 @@ def num_qubits(self) -> int: return 1 def _kraus_(self): - return [ - cirq.unitary(cirq.X) * np.sqrt(0.999), - np.eye(2) * 0, - ] + return [cirq.unitary(cirq.X) * np.sqrt(0.999), np.eye(2) * 0] mock_prng = mock.Mock() mock_prng.random.return_value = 0.9999 @@ -252,20 +228,13 @@ def _kraus_(self): cirq.act_on(Short(), args, cirq.LineQubit.range(1)) - np.testing.assert_allclose( - args.target_tensor, - np.array([0, 1]), - ) + np.testing.assert_allclose(args.target_tensor, np.array([0, 1])) def test_random_channel_has_random_behavior(): q = cirq.LineQubit(0) s = cirq.Simulator().sample( - cirq.Circuit( - cirq.X(q), - cirq.amplitude_damp(0.4).on(q), - cirq.measure(q, key='out'), - ), + cirq.Circuit(cirq.X(q), cirq.amplitude_damp(0.4).on(q), cirq.measure(q, key='out')), repetitions=100, ) v = s['out'].value_counts() @@ -276,11 +245,7 @@ def test_random_channel_has_random_behavior(): def test_measured_channel(): # This behaves like an X-basis measurement. kc = cirq.KrausChannel( - kraus_ops=( - np.array([[1, 1], [1, 1]]) * 0.5, - np.array([[1, -1], [-1, 1]]) * 0.5, - ), - key='m', + kraus_ops=(np.array([[1, 1], [1, 1]]) * 0.5, np.array([[1, -1], [-1, 1]]) * 0.5), key='m' ) q0 = cirq.LineQubit(0) circuit = cirq.Circuit(cirq.H(q0), kc.on(q0)) @@ -292,11 +257,7 @@ def test_measured_channel(): def test_measured_mixture(): # This behaves like an X-basis measurement. mm = cirq.MixedUnitaryChannel( - mixture=( - (0.5, np.array([[1, 0], [0, 1]])), - (0.5, np.array([[0, 1], [1, 0]])), - ), - key='flip', + mixture=((0.5, np.array([[1, 0], [0, 1]])), (0.5, np.array([[0, 1], [1, 0]]))), key='flip' ) q0 = cirq.LineQubit(0) circuit = cirq.Circuit(mm.on(q0), cirq.measure(q0, key='m')) @@ -307,9 +268,7 @@ def test_measured_mixture(): def test_with_qubits(): original = cirq.ActOnStateVectorArgs( - qubits=cirq.LineQubit.range(2), - initial_state=1, - dtype=np.complex64, + qubits=cirq.LineQubit.range(2), initial_state=1, dtype=np.complex64 ) extened = original.with_qubits(cirq.LineQubit.range(2, 4)) np.testing.assert_almost_equal( diff --git a/cirq-core/cirq/sim/clifford/__init__.py b/cirq-core/cirq/sim/clifford/__init__.py index 42ee7bf7ad8..d466ca209b5 100644 --- a/cirq-core/cirq/sim/clifford/__init__.py +++ b/cirq-core/cirq/sim/clifford/__init__.py @@ -1,19 +1,11 @@ # pylint: disable=wrong-or-nonexistent-copyright-notice -from cirq.sim.clifford.act_on_clifford_tableau_args import ( - ActOnCliffordTableauArgs, -) +from cirq.sim.clifford.act_on_clifford_tableau_args import ActOnCliffordTableauArgs -from cirq.sim.clifford.act_on_stabilizer_ch_form_args import ( - ActOnStabilizerCHFormArgs, -) +from cirq.sim.clifford.act_on_stabilizer_ch_form_args import ActOnStabilizerCHFormArgs -from cirq.sim.clifford.act_on_stabilizer_args import ( - ActOnStabilizerArgs, -) +from cirq.sim.clifford.act_on_stabilizer_args import ActOnStabilizerArgs -from cirq.sim.clifford.stabilizer_state_ch_form import ( - StabilizerStateChForm, -) +from cirq.sim.clifford.stabilizer_state_ch_form import StabilizerStateChForm from cirq.sim.clifford.clifford_simulator import ( CliffordSimulator, @@ -22,6 +14,4 @@ CliffordSimulatorStepResult, ) -from cirq.sim.clifford.stabilizer_sampler import ( - StabilizerSampler, -) +from cirq.sim.clifford.stabilizer_sampler import StabilizerSampler diff --git a/cirq-core/cirq/sim/clifford/act_on_stabilizer_ch_form_args_test.py b/cirq-core/cirq/sim/clifford/act_on_stabilizer_ch_form_args_test.py index 7cd10005657..2e655944a2a 100644 --- a/cirq-core/cirq/sim/clifford/act_on_stabilizer_ch_form_args_test.py +++ b/cirq-core/cirq/sim/clifford/act_on_stabilizer_ch_form_args_test.py @@ -19,10 +19,7 @@ def test_init_state(): - args = cirq.ActOnStabilizerCHFormArgs( - qubits=cirq.LineQubit.range(1), - initial_state=1, - ) + args = cirq.ActOnStabilizerCHFormArgs(qubits=cirq.LineQubit.range(1), initial_state=1) np.testing.assert_allclose(args.state.state_vector(), [0, 1]) with pytest.raises(ValueError, match='Must specify qubits'): _ = cirq.ActOnStabilizerCHFormArgs(initial_state=1) @@ -32,10 +29,7 @@ def test_cannot_act(): class NoDetails(cirq.SingleQubitGate): pass - args = cirq.ActOnStabilizerCHFormArgs( - qubits=[], - prng=np.random.RandomState(), - ) + args = cirq.ActOnStabilizerCHFormArgs(qubits=[], prng=np.random.RandomState()) with pytest.raises(TypeError, match="Failed to act"): cirq.act_on(NoDetails(), args, qubits=()) @@ -51,9 +45,7 @@ def _act_on_(self, args, qubits): state = cirq.StabilizerStateChForm(num_qubits=3) args = cirq.ActOnStabilizerCHFormArgs( - qubits=cirq.LineQubit.range(3), - prng=np.random.RandomState(), - initial_state=state, + qubits=cirq.LineQubit.range(3), prng=np.random.RandomState(), initial_state=state ) cirq.act_on(CustomGate(), args, [cirq.LineQubit(1)]) @@ -70,13 +62,11 @@ def _unitary_(self): return np.array([[0, -1j], [1j, 0]]) args = cirq.ActOnStabilizerCHFormArgs( - qubits=cirq.LineQubit.range(3), - prng=np.random.RandomState(), + qubits=cirq.LineQubit.range(3), prng=np.random.RandomState() ) cirq.act_on(UnitaryYGate(), args, [cirq.LineQubit(1)]) expected_args = cirq.ActOnStabilizerCHFormArgs( - qubits=cirq.LineQubit.range(3), - prng=np.random.RandomState(), + qubits=cirq.LineQubit.range(3), prng=np.random.RandomState() ) cirq.act_on(cirq.Y, expected_args, [cirq.LineQubit(1)]) np.testing.assert_allclose(args.state.state_vector(), expected_args.state.state_vector()) @@ -91,13 +81,11 @@ def _unitary_(self): return np.array([[1, 1], [1, -1]]) / (2**0.5) args = cirq.ActOnStabilizerCHFormArgs( - qubits=cirq.LineQubit.range(3), - prng=np.random.RandomState(), + qubits=cirq.LineQubit.range(3), prng=np.random.RandomState() ) cirq.act_on(UnitaryHGate(), args, [cirq.LineQubit(1)]) expected_args = cirq.ActOnStabilizerCHFormArgs( - qubits=cirq.LineQubit.range(3), - prng=np.random.RandomState(), + qubits=cirq.LineQubit.range(3), prng=np.random.RandomState() ) cirq.act_on(cirq.H, expected_args, [cirq.LineQubit(1)]) np.testing.assert_allclose(args.state.state_vector(), expected_args.state.state_vector()) @@ -105,8 +93,7 @@ def _unitary_(self): def test_copy(): args = cirq.ActOnStabilizerCHFormArgs( - qubits=cirq.LineQubit.range(3), - prng=np.random.RandomState(), + qubits=cirq.LineQubit.range(3), prng=np.random.RandomState() ) args1 = args.copy() assert isinstance(args1, cirq.ActOnStabilizerCHFormArgs) diff --git a/cirq-core/cirq/sim/clifford/clifford_simulator.py b/cirq-core/cirq/sim/clifford/clifford_simulator.py index 3f19c253d6f..28799c07435 100644 --- a/cirq-core/cirq/sim/clifford/clifford_simulator.py +++ b/cirq-core/cirq/sim/clifford/clifford_simulator.py @@ -45,14 +45,12 @@ class CliffordSimulator( 'cirq.CliffordTrialResult', 'cirq.CliffordState', 'cirq.ActOnStabilizerCHFormArgs', - ], + ] ): """An efficient simulator for Clifford circuits.""" def __init__( - self, - seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None, - split_untangled_states: bool = False, + self, seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None, split_untangled_states: bool = False ): """Creates instance of `CliffordSimulator`. @@ -62,10 +60,7 @@ def __init__( states independently and merging those states at the end. """ self.init = True - super().__init__( - seed=seed, - split_untangled_states=split_untangled_states, - ) + super().__init__(seed=seed, split_untangled_states=split_untangled_states) @staticmethod def is_supported_operation(op: 'cirq.Operation') -> bool: @@ -105,8 +100,7 @@ def _create_partial_act_on_args( ) def _create_step_result( - self, - sim_state: 'cirq.OperationTarget[clifford.ActOnStabilizerCHFormArgs]', + self, sim_state: 'cirq.OperationTarget[clifford.ActOnStabilizerCHFormArgs]' ): return CliffordSimulatorStepResult(sim_state=sim_state) @@ -156,10 +150,7 @@ class CliffordSimulatorStepResult( ): """A `StepResult` that includes `StateVectorMixin` methods.""" - def __init__( - self, - sim_state: 'cirq.OperationTarget[clifford.ActOnStabilizerCHFormArgs]', - ): + def __init__(self, sim_state: 'cirq.OperationTarget[clifford.ActOnStabilizerCHFormArgs]'): """Results of a step of the simulator. Attributes: sim_state: The qubit:ActOnArgs lookup for this step. @@ -219,10 +210,7 @@ def __init__(self, qubit_map, initial_state: Union[int, 'cirq.StabilizerStateChF ) def _json_dict_(self): - return { - 'qubit_map': [(k, v) for k, v in self.qubit_map.items()], - 'ch_form': self.ch_form, - } + return {'qubit_map': [(k, v) for k, v in self.qubit_map.items()], 'ch_form': self.ch_form} @classmethod def _from_json_dict_(cls, qubit_map, ch_form, **kwargs): @@ -255,9 +243,7 @@ def state_vector(self): def apply_unitary(self, op: 'cirq.Operation'): ch_form_args = clifford.ActOnStabilizerCHFormArgs( - prng=np.random.RandomState(), - qubits=self.qubit_map.keys(), - initial_state=self.ch_form, + prng=np.random.RandomState(), qubits=self.qubit_map.keys(), initial_state=self.ch_form ) try: act_on(op, ch_form_args) diff --git a/cirq-core/cirq/sim/clifford/stabilizer_sampler.py b/cirq-core/cirq/sim/clifford/stabilizer_sampler.py index 38eb707a615..73bab9091f1 100644 --- a/cirq-core/cirq/sim/clifford/stabilizer_sampler.py +++ b/cirq-core/cirq/sim/clifford/stabilizer_sampler.py @@ -36,18 +36,12 @@ def __init__(self, *, seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None): self._prng = value.parse_random_state(seed) def run_sweep( - self, - program: 'cirq.AbstractCircuit', - params: 'cirq.Sweepable', - repetitions: int = 1, + self, program: 'cirq.AbstractCircuit', params: 'cirq.Sweepable', repetitions: int = 1 ) -> Sequence['cirq.Result']: results: List[cirq.Result] = [] for param_resolver in cirq.to_resolvers(params): resolved_circuit = cirq.resolve_parameters(program, param_resolver) - measurements = self._run( - resolved_circuit, - repetitions=repetitions, - ) + measurements = self._run(resolved_circuit, repetitions=repetitions) results.append(cirq.ResultDict(params=param_resolver, measurements=measurements)) return results @@ -60,9 +54,7 @@ def _run(self, circuit: 'cirq.AbstractCircuit', repetitions: int) -> Dict[str, n for _ in range(repetitions): state = ActOnCliffordTableauArgs( - CliffordTableau(num_qubits=len(qubits)), - qubits=list(qubits), - prng=self._prng, + CliffordTableau(num_qubits=len(qubits)), qubits=list(qubits), prng=self._prng ) for op in circuit.all_operations(): protocols.act_on(op, state) diff --git a/cirq-core/cirq/sim/clifford/stabilizer_sampler_test.py b/cirq-core/cirq/sim/clifford/stabilizer_sampler_test.py index 08bedfc2f15..f9c346d6f11 100644 --- a/cirq-core/cirq/sim/clifford/stabilizer_sampler_test.py +++ b/cirq-core/cirq/sim/clifford/stabilizer_sampler_test.py @@ -19,12 +19,7 @@ def test_produces_samples(): a, b = cirq.LineQubit.range(2) - c = cirq.Circuit( - cirq.H(a), - cirq.CNOT(a, b), - cirq.measure(a, key='a'), - cirq.measure(b, key='b'), - ) + c = cirq.Circuit(cirq.H(a), cirq.CNOT(a, b), cirq.measure(a, key='a'), cirq.measure(b, key='b')) result = cirq.StabilizerSampler().sample(c, repetitions=100) assert 5 < sum(result['a']) < 95 diff --git a/cirq-core/cirq/sim/density_matrix_simulator.py b/cirq-core/cirq/sim/density_matrix_simulator.py index 498572f9bc8..813303e947a 100644 --- a/cirq-core/cirq/sim/density_matrix_simulator.py +++ b/cirq-core/cirq/sim/density_matrix_simulator.py @@ -18,11 +18,7 @@ from cirq import ops, protocols, study, value from cirq._compat import deprecated_parameter, proper_repr -from cirq.sim import ( - simulator, - act_on_density_matrix_args, - simulator_base, -) +from cirq.sim import simulator, act_on_density_matrix_args, simulator_base if TYPE_CHECKING: import cirq @@ -145,10 +141,7 @@ def __init__( >>> circuit = cirq.Circuit(cirq.H(q0), cirq.measure(q0)) """ super().__init__( - dtype=dtype, - noise=noise, - seed=seed, - split_untangled_states=split_untangled_states, + dtype=dtype, noise=noise, seed=seed, split_untangled_states=split_untangled_states ) if dtype not in {np.complex64, np.complex128}: raise ValueError(f'dtype must be complex64 or complex128, was {dtype}') @@ -187,14 +180,8 @@ def _create_partial_act_on_args( def _can_be_in_run_prefix(self, val: Any): return not protocols.measurement_keys_touched(val) - def _create_step_result( - self, - sim_state: 'cirq.OperationTarget[cirq.ActOnDensityMatrixArgs]', - ): - return DensityMatrixStepResult( - sim_state=sim_state, - dtype=self._dtype, - ) + def _create_step_result(self, sim_state: 'cirq.OperationTarget[cirq.ActOnDensityMatrixArgs]'): + return DensityMatrixStepResult(sim_state=sim_state, dtype=self._dtype) def _create_simulator_trial_result( self, diff --git a/cirq-core/cirq/sim/mux.py b/cirq-core/cirq/sim/mux.py index 2095abe3113..8de78f285f1 100644 --- a/cirq-core/cirq/sim/mux.py +++ b/cirq-core/cirq/sim/mux.py @@ -279,9 +279,7 @@ def final_density_matrix( else: # noisy case: use DensityMatrixSimulator with dephasing density_result = density_matrix_simulator.DensityMatrixSimulator( - dtype=dtype, - noise=noise, - seed=seed, + dtype=dtype, noise=noise, seed=seed ).simulate( program=measurement_transformers.dephase_measurements(circuit_like) if ignore_measurement_results diff --git a/cirq-core/cirq/sim/mux_test.py b/cirq-core/cirq/sim/mux_test.py index 2b47840cacb..b55a98eb0aa 100644 --- a/cirq-core/cirq/sim/mux_test.py +++ b/cirq-core/cirq/sim/mux_test.py @@ -33,23 +33,13 @@ def test_sample(): assert results.histogram(key=q) == collections.Counter({1: 1}) # Intermediate measurements. - results = cirq.sample( - cirq.Circuit( - cirq.measure(q, key='drop'), - cirq.X(q), - cirq.measure(q), - ) - ) + results = cirq.sample(cirq.Circuit(cirq.measure(q, key='drop'), cirq.X(q), cirq.measure(q))) assert results.histogram(key='drop') == collections.Counter({0: 1}) assert results.histogram(key=q) == collections.Counter({1: 1}) # Overdamped everywhere. results = cirq.sample( - cirq.Circuit( - cirq.measure(q, key='drop'), - cirq.X(q), - cirq.measure(q), - ), + cirq.Circuit(cirq.measure(q, key='drop'), cirq.X(q), cirq.measure(q)), noise=cirq.ConstantQubitNoiseModel(cirq.amplitude_damp(1)), ) assert results.histogram(key='drop') == collections.Counter({0: 1}) @@ -160,12 +150,7 @@ def test_final_state_vector_initial_state(): def test_final_state_vector_dtype_insensitive_to_initial_state(): - assert ( - cirq.final_state_vector( - cirq.X, - ).dtype - == np.complex64 - ) + assert cirq.final_state_vector(cirq.X).dtype == np.complex64 assert cirq.final_state_vector(cirq.X, initial_state=0).dtype == np.complex64 @@ -273,12 +258,7 @@ def test_final_density_matrix_initial_state(): def test_final_density_matrix_dtype_insensitive_to_initial_state(): - assert ( - cirq.final_density_matrix( - cirq.X, - ).dtype - == np.complex64 - ) + assert cirq.final_density_matrix(cirq.X).dtype == np.complex64 assert cirq.final_density_matrix(cirq.X, initial_state=0).dtype == np.complex64 diff --git a/cirq-core/cirq/sim/operation_target.py b/cirq-core/cirq/sim/operation_target.py index 285f0cdaac8..8cb54f95cad 100644 --- a/cirq-core/cirq/sim/operation_target.py +++ b/cirq-core/cirq/sim/operation_target.py @@ -49,10 +49,7 @@ def create_merged_state(self) -> TActOnArgs: @abc.abstractmethod def _act_on_fallback_( - self, - action: Any, - qubits: Sequence['cirq.Qid'], - allow_decompose: bool = True, + self, action: Any, qubits: Sequence['cirq.Qid'], allow_decompose: bool = True ) -> Union[bool, NotImplementedType]: """Handles the act_on protocol fallback implementation. diff --git a/cirq-core/cirq/sim/simulator.py b/cirq-core/cirq/sim/simulator.py index 62c30e6044b..f2c110c8f23 100644 --- a/cirq-core/cirq/sim/simulator.py +++ b/cirq-core/cirq/sim/simulator.py @@ -68,18 +68,12 @@ class SimulatesSamples(work.Sampler, metaclass=abc.ABCMeta): """ def run_sweep( - self, - program: 'cirq.AbstractCircuit', - params: 'cirq.Sweepable', - repetitions: int = 1, + self, program: 'cirq.AbstractCircuit', params: 'cirq.Sweepable', repetitions: int = 1 ) -> Sequence['cirq.Result']: return list(self.run_sweep_iter(program, params, repetitions)) def run_sweep_iter( - self, - program: 'cirq.AbstractCircuit', - params: 'cirq.Sweepable', - repetitions: int = 1, + self, program: 'cirq.AbstractCircuit', params: 'cirq.Sweepable', repetitions: int = 1 ) -> Iterator['cirq.Result']: """Runs the supplied Circuit, mimicking quantum hardware. @@ -406,12 +400,7 @@ def _simulate_expectation_values_sweep_to_iter( "simulate_expectation_values_sweep_iter." ) yield from self.simulate_expectation_values_sweep( - program, - observables, - params, - qubit_order, - initial_state, - permit_terminal_measurements, + program, observables, params, qubit_order, initial_state, permit_terminal_measurements ) @value.alternative( @@ -620,9 +609,7 @@ def simulate_sweep_iter( for k, v in step_result.measurements.items(): measurements[k] = np.array(v, dtype=np.uint8) yield self._create_simulator_trial_result( - params=param_resolver, - measurements=measurements, - final_step_result=step_result, + params=param_resolver, measurements=measurements, final_step_result=step_result ) def simulate_moment_steps( @@ -690,9 +677,7 @@ def _base_iterator( @abc.abstractmethod def _create_act_on_args( - self, - initial_state: Any, - qubits: Sequence['cirq.Qid'], + self, initial_state: Any, qubits: Sequence['cirq.Qid'] ) -> 'cirq.OperationTarget[TActOnArgs]': """Creates the OperationTarget state for a simulator. @@ -1011,8 +996,7 @@ def check_all_resolved(circuit): def split_into_matching_protocol_then_general( - circuit: 'cirq.AbstractCircuit', - predicate: Callable[['cirq.Operation'], bool], + circuit: 'cirq.AbstractCircuit', predicate: Callable[['cirq.Operation'], bool] ) -> Tuple['cirq.AbstractCircuit', 'cirq.AbstractCircuit']: """Splits the circuit into a matching prefix and non-matching suffix. diff --git a/cirq-core/cirq/sim/simulator_base.py b/cirq-core/cirq/sim/simulator_base.py index 7e3ee53a554..58f6fa10577 100644 --- a/cirq-core/cirq/sim/simulator_base.py +++ b/cirq-core/cirq/sim/simulator_base.py @@ -134,10 +134,7 @@ def _create_partial_act_on_args( """ @abc.abstractmethod - def _create_step_result( - self, - sim_state: OperationTarget[TActOnArgs], - ) -> TStepResultBase: + def _create_step_result(self, sim_state: OperationTarget[TActOnArgs]) -> TStepResultBase: """This method should be implemented to create a step result. Args: @@ -235,18 +232,13 @@ def _run( else (resolved_circuit[0:0], resolved_circuit) ) step_result = None - for step_result in self._core_iterator( - circuit=prefix, - sim_state=act_on_args, - ): + for step_result in self._core_iterator(circuit=prefix, sim_state=act_on_args): pass general_ops = list(general_suffix.all_operations()) if all(isinstance(op.gate, ops.MeasurementGate) for op in general_ops): for step_result in self._core_iterator( - circuit=general_suffix, - sim_state=act_on_args, - all_measurements_are_terminal=True, + circuit=general_suffix, sim_state=act_on_args, all_measurements_are_terminal=True ): pass assert step_result is not None @@ -315,18 +307,13 @@ def sweep_prefixable(op: 'cirq.Operation'): else (program[0:0], program) ) step_result = None - for step_result in self._core_iterator( - circuit=prefix, - sim_state=sim_state, - ): + for step_result in self._core_iterator(circuit=prefix, sim_state=sim_state): pass sim_state = step_result._sim_state yield from super().simulate_sweep_iter(suffix, params, qubit_order, sim_state) def _create_act_on_args( - self, - initial_state: Any, - qubits: Sequence['cirq.Qid'], + self, initial_state: Any, qubits: Sequence['cirq.Qid'] ) -> OperationTarget[TActOnArgs]: if isinstance(initial_state, OperationTarget): return initial_state @@ -344,9 +331,7 @@ def _create_act_on_args( initial_state = int(initial_state / q.dimension) else: args = self._create_partial_act_on_args( - initial_state=initial_state, - qubits=qubits, - classical_data=classical_data, + initial_state=initial_state, qubits=qubits, classical_data=classical_data ) for q in qubits: args_map[q] = args @@ -356,19 +341,14 @@ def _create_act_on_args( ) else: return self._create_partial_act_on_args( - initial_state=initial_state, - qubits=qubits, - classical_data=classical_data, + initial_state=initial_state, qubits=qubits, classical_data=classical_data ) class StepResultBase(Generic[TSimulatorState, TActOnArgs], StepResult[TSimulatorState], abc.ABC): """A base class for step results.""" - def __init__( - self, - sim_state: OperationTarget[TActOnArgs], - ): + def __init__(self, sim_state: OperationTarget[TActOnArgs]): """Initializes the step result. Args: diff --git a/cirq-core/cirq/sim/simulator_test.py b/cirq-core/cirq/sim/simulator_test.py index adeb7f15fe1..4623cd1fa68 100644 --- a/cirq-core/cirq/sim/simulator_test.py +++ b/cirq-core/cirq/sim/simulator_test.py @@ -440,8 +440,7 @@ def _kraus_(self): for k in range(4): out = cirq.Simulator().simulate( - cirq.Circuit(Reset11To00().on(*cirq.LineQubit.range(2))), - initial_state=k, + cirq.Circuit(Reset11To00().on(*cirq.LineQubit.range(2))), initial_state=k ) np.testing.assert_allclose( out.state_vector(), cirq.one_hot(index=k % 3, shape=4, dtype=np.complex64), atol=1e-8 @@ -454,9 +453,7 @@ def test_iter_definitions(): ) class FakeNonIterSimulatorImpl( - SimulatesAmplitudes, - SimulatesExpectationValues, - SimulatesFinalState, + SimulatesAmplitudes, SimulatesExpectationValues, SimulatesFinalState ): """A class which defines the non-Iterator simulator API methods. @@ -513,9 +510,7 @@ def simulate_sweep( def test_missing_iter_definitions(): class FakeMissingIterSimulatorImpl( - SimulatesAmplitudes, - SimulatesExpectationValues, - SimulatesFinalState, + SimulatesAmplitudes, SimulatesExpectationValues, SimulatesFinalState ): """A class which fails to define simulator methods.""" diff --git a/cirq-core/cirq/sim/sparse_simulator.py b/cirq-core/cirq/sim/sparse_simulator.py index f18379357db..31331d21f41 100644 --- a/cirq-core/cirq/sim/sparse_simulator.py +++ b/cirq-core/cirq/sim/sparse_simulator.py @@ -14,27 +14,13 @@ """A simulator that uses numpy's einsum for sparse matrix operations.""" -from typing import ( - Any, - Iterator, - List, - Type, - TYPE_CHECKING, - Union, - Sequence, - Optional, -) +from typing import Any, Iterator, List, Type, TYPE_CHECKING, Union, Sequence, Optional import numpy as np from cirq import ops from cirq._compat import deprecated_parameter -from cirq.sim import ( - simulator, - state_vector, - state_vector_simulator, - act_on_state_vector_args, -) +from cirq.sim import simulator, state_vector, state_vector_simulator, act_on_state_vector_args if TYPE_CHECKING: import cirq @@ -164,10 +150,7 @@ def __init__( if np.dtype(dtype).kind != 'c': raise ValueError(f'dtype must be a complex type but was {dtype}') super().__init__( - dtype=dtype, - noise=noise, - seed=seed, - split_untangled_states=split_untangled_states, + dtype=dtype, noise=noise, seed=seed, split_untangled_states=split_untangled_states ) def _create_partial_act_on_args( @@ -201,14 +184,8 @@ def _create_partial_act_on_args( dtype=self._dtype, ) - def _create_step_result( - self, - sim_state: 'cirq.OperationTarget[cirq.ActOnStateVectorArgs]', - ): - return SparseSimulatorStep( - sim_state=sim_state, - dtype=self._dtype, - ) + def _create_step_result(self, sim_state: 'cirq.OperationTarget[cirq.ActOnStateVectorArgs]'): + return SparseSimulatorStep(sim_state=sim_state, dtype=self._dtype) def simulate_expectation_values_sweep_iter( self, @@ -239,8 +216,7 @@ def simulate_expectation_values_sweep_iter( class SparseSimulatorStep( - state_vector.StateVectorMixin, - state_vector_simulator.StateVectorStepResult, + state_vector.StateVectorMixin, state_vector_simulator.StateVectorStepResult ): """A `StepResult` that includes `StateVectorMixin` methods.""" diff --git a/cirq-core/cirq/sim/sparse_simulator_test.py b/cirq-core/cirq/sim/sparse_simulator_test.py index 59a948930b6..0a27e775f30 100644 --- a/cirq-core/cirq/sim/sparse_simulator_test.py +++ b/cirq-core/cirq/sim/sparse_simulator_test.py @@ -386,10 +386,7 @@ def _mixture_(self): def test_simulate_qudits(dtype: Type[np.number], split: bool): q0, q1 = cirq.LineQid.for_qid_shape((3, 4)) simulator = cirq.Simulator(dtype=dtype, split_untangled_states=split) - circuit = cirq.Circuit( - PlusGate(3)(q0), - PlusGate(4, increment=3)(q1), - ) + circuit = cirq.Circuit(PlusGate(3)(q0), PlusGate(4, increment=3)(q1)) result = simulator.simulate(circuit, qubit_order=[q0, q1]) expected = np.zeros(12) expected[4 * 1 + 3] = 1 @@ -760,10 +757,7 @@ def test_simulator_step_state_mixin(): initial_state=np.array([0, 1, 0, 0], dtype=np.complex64).reshape((2, 2)), dtype=np.complex64, ) - result = cirq.SparseSimulatorStep( - sim_state=args, - dtype=np.complex64, - ) + result = cirq.SparseSimulatorStep(sim_state=args, dtype=np.complex64) rho = np.array([[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) np.testing.assert_array_almost_equal(rho, result.density_matrix_of(qubits)) bloch = np.array([0, 0, -1]) @@ -876,11 +870,7 @@ def test_compute_amplitudes_bad_input(): def test_sample_from_amplitudes(): q0, q1 = cirq.LineQubit.range(2) - circuit = cirq.Circuit( - cirq.H(q0), - cirq.CNOT(q0, q1), - cirq.X(q1), - ) + circuit = cirq.Circuit(cirq.H(q0), cirq.CNOT(q0, q1), cirq.X(q1)) sim = cirq.Simulator(seed=1) result = sim.sample_from_amplitudes(circuit, {}, sim._prng, repetitions=100) assert 40 < result[1] < 60 @@ -929,10 +919,7 @@ def test_sample_from_amplitudes_nonunitary_fails(): _ = sim.sample_from_amplitudes(circuit1, {}, sim._prng) circuit2 = cirq.Circuit( - cirq.H(q0), - cirq.CNOT(q0, q1), - cirq.amplitude_damp(0.01)(q0), - cirq.amplitude_damp(0.01)(q1), + cirq.H(q0), cirq.CNOT(q0, q1), cirq.amplitude_damp(0.01)(q0), cirq.amplitude_damp(0.01)(q1) ) with pytest.raises(ValueError, match='does not support non-unitary'): _ = sim.sample_from_amplitudes(circuit2, {}, sim._prng) @@ -1387,10 +1374,7 @@ def test_noise_model(): def test_separated_states_str_does_not_merge(): q0, q1 = cirq.LineQubit.range(2) circuit = cirq.Circuit( - cirq.measure(q0), - cirq.measure(q1), - cirq.H(q0), - cirq.global_phase_operation(0 + 1j), + cirq.measure(q0), cirq.measure(q1), cirq.H(q0), cirq.global_phase_operation(0 + 1j) ) result = cirq.Simulator().simulate(circuit) @@ -1422,10 +1406,7 @@ def test_separable_non_dirac_str(): def test_unseparated_states_str(): q0, q1 = cirq.LineQubit.range(2) circuit = cirq.Circuit( - cirq.measure(q0), - cirq.measure(q1), - cirq.H(q0), - cirq.global_phase_operation(0 + 1j), + cirq.measure(q0), cirq.measure(q1), cirq.H(q0), cirq.global_phase_operation(0 + 1j) ) result = cirq.Simulator(split_untangled_states=False).simulate(circuit) diff --git a/cirq-core/cirq/sim/state_vector_simulator.py b/cirq-core/cirq/sim/state_vector_simulator.py index 3e92bc2a31c..89f36f0bac1 100644 --- a/cirq-core/cirq/sim/state_vector_simulator.py +++ b/cirq-core/cirq/sim/state_vector_simulator.py @@ -65,10 +65,7 @@ def __init__( split_untangled_states: bool = False, ): super().__init__( - dtype=dtype, - noise=noise, - seed=seed, - split_untangled_states=split_untangled_states, + dtype=dtype, noise=noise, seed=seed, split_untangled_states=split_untangled_states ) def _create_simulator_trial_result( diff --git a/cirq-core/cirq/study/__init__.py b/cirq-core/cirq/study/__init__.py index c63df34e5bf..b1cd838a1b5 100644 --- a/cirq-core/cirq/study/__init__.py +++ b/cirq-core/cirq/study/__init__.py @@ -21,18 +21,9 @@ flatten_with_sweep, ) -from cirq.study.resolver import ( - ParamDictType, - ParamResolver, - ParamResolverOrSimilarType, -) +from cirq.study.resolver import ParamDictType, ParamResolver, ParamResolverOrSimilarType -from cirq.study.sweepable import ( - Sweepable, - to_resolvers, - to_sweep, - to_sweeps, -) +from cirq.study.sweepable import Sweepable, to_resolvers, to_sweep, to_sweeps from cirq.study.sweeps import ( Linspace, @@ -46,7 +37,4 @@ dict_to_zip_sweep, ) -from cirq.study.result import ( - ResultDict, - Result, -) +from cirq.study.result import ResultDict, Result diff --git a/cirq-core/cirq/study/flatten_expressions.py b/cirq-core/cirq/study/flatten_expressions.py index 328668c57d9..d2acecb1069 100644 --- a/cirq-core/cirq/study/flatten_expressions.py +++ b/cirq-core/cirq/study/flatten_expressions.py @@ -195,12 +195,7 @@ def __init__( self, param_dict: Optional[resolver.ParamResolverOrSimilarType] = None, *, # Force keyword args - get_param_name: Callable[ - [ - sympy.Basic, - ], - str, - ] = None, + get_param_name: Callable[[sympy.Basic], str,] = None, ): """Initializes a new _ParamFlattener. diff --git a/cirq-core/cirq/study/flatten_expressions_test.py b/cirq-core/cirq/study/flatten_expressions_test.py index 7de97b66ca5..4efbd6a2a31 100644 --- a/cirq-core/cirq/study/flatten_expressions_test.py +++ b/cirq-core/cirq/study/flatten_expressions_test.py @@ -68,32 +68,20 @@ def test_expression_map_repr(): def test_flatten_circuit(): qubit = cirq.LineQubit(0) a = sympy.Symbol('a') - circuit = cirq.Circuit( - cirq.X(qubit) ** a, - cirq.X(qubit) ** (1 + a / 2), - ) + circuit = cirq.Circuit(cirq.X(qubit) ** a, cirq.X(qubit) ** (1 + a / 2)) c_flat, expr_map = cirq.flatten(circuit) - c_expected = cirq.Circuit( - cirq.X(qubit) ** a, - cirq.X(qubit) ** sympy.Symbol(''), - ) + c_expected = cirq.Circuit(cirq.X(qubit) ** a, cirq.X(qubit) ** sympy.Symbol('')) assert c_flat == c_expected assert isinstance(expr_map, cirq.ExpressionMap) - assert expr_map == { - a: a, - 1 + a / 2: sympy.Symbol(''), - } + assert expr_map == {a: a, 1 + a / 2: sympy.Symbol('')} def test_transform_params(): qubit = cirq.LineQubit(0) a = sympy.Symbol('a') - circuit = cirq.Circuit( - cirq.X(qubit) ** (a / 4), - cirq.X(qubit) ** (1 + a / 2), - ) + circuit = cirq.Circuit(cirq.X(qubit) ** (a / 4), cirq.X(qubit) ** (1 + a / 2)) params = {'a': 3} _, new_params = cirq.flatten_with_params(circuit, params) @@ -105,10 +93,7 @@ def test_transform_params(): def test_transform_sweep(): qubit = cirq.LineQubit(0) a = sympy.Symbol('a') - circuit = cirq.Circuit( - cirq.X(qubit) ** (a / 4), - cirq.X(qubit) ** (1 + a / 2), - ) + circuit = cirq.Circuit(cirq.X(qubit) ** (a / 4), cirq.X(qubit) ** (1 + a / 2)) sweep = cirq.Linspace(a, start=0, stop=3, length=4) _, new_sweep = cirq.flatten_with_sweep(circuit, sweep) @@ -116,30 +101,10 @@ def test_transform_sweep(): resolvers = list(new_sweep) expected_resolvers = [ - cirq.ParamResolver( - { - '': 0.0, - '': 1.0, - } - ), - cirq.ParamResolver( - { - '': 0.25, - '': 1.5, - } - ), - cirq.ParamResolver( - { - '': 0.5, - '': 2, - } - ), - cirq.ParamResolver( - { - '': 0.75, - '': 2.5, - } - ), + cirq.ParamResolver({'': 0.0, '': 1.0}), + cirq.ParamResolver({'': 0.25, '': 1.5}), + cirq.ParamResolver({'': 0.5, '': 2}), + cirq.ParamResolver({'': 0.75, '': 2.5}), ] assert resolvers == expected_resolvers diff --git a/cirq-core/cirq/study/resolver.py b/cirq-core/cirq/study/resolver.py index c126688e06e..499d1859337 100644 --- a/cirq-core/cirq/study/resolver.py +++ b/cirq-core/cirq/study/resolver.py @@ -234,7 +234,7 @@ def __repr__(self) -> str: def _json_dict_(self) -> Dict[str, Any]: return { # JSON requires mappings to have keys of basic types. - 'param_dict': list(self.param_dict.items()), + 'param_dict': list(self.param_dict.items()) } @classmethod diff --git a/cirq-core/cirq/study/resolver_test.py b/cirq-core/cirq/study/resolver_test.py index 877023b1030..c612448b7c9 100644 --- a/cirq-core/cirq/study/resolver_test.py +++ b/cirq-core/cirq/study/resolver_test.py @@ -185,15 +185,7 @@ def test_recursive_evaluation(): c = sympy.Symbol('c') d = sympy.Symbol('d') e = sympy.Symbol('e') - r = cirq.ParamResolver( - { - a: a, - b: e + 2, - c: b + d, - d: a + 3, - e: 0, - } - ) + r = cirq.ParamResolver({a: a, b: e + 2, c: b + d, d: a + 3, e: 0}) # sympy.Basic.subs evaluates in alphabetical order. assert c.subs(r.param_dict) == b + a + 3 diff --git a/cirq-core/cirq/study/result.py b/cirq-core/cirq/study/result.py index 578a858aa62..32b0c33d9ca 100644 --- a/cirq-core/cirq/study/result.py +++ b/cirq-core/cirq/study/result.py @@ -433,10 +433,7 @@ def _json_dict_(self): 'dtype': digits.dtype.name, 'shape': digits.shape, } - return { - 'params': self.params, - 'records': packed_records, - } + return {'params': self.params, 'records': packed_records} @classmethod def _from_json_dict_(cls, params, **kwargs): @@ -448,8 +445,7 @@ def _from_json_dict_(cls, params, **kwargs): ) records = kwargs['records'] return cls( - params=params, - records={key: _unpack_digits(**val) for key, val in records.items()}, + params=params, records={key: _unpack_digits(**val) for key, val in records.items()} ) diff --git a/cirq-core/cirq/study/result_test.py b/cirq-core/cirq/study/result_test.py index fd5bd481564..abd91e9a872 100644 --- a/cirq-core/cirq/study/result_test.py +++ b/cirq-core/cirq/study/result_test.py @@ -83,10 +83,7 @@ def test_from_single_parameter_set_deprecation(): def test_construct_from_measurements(): r = cirq.ResultDict( params=None, - measurements={ - 'a': np.array([[0, 0], [1, 1]]), - 'b': np.array([[0, 0, 0], [1, 1, 1]]), - }, + measurements={'a': np.array([[0, 0], [1, 1]]), 'b': np.array([[0, 0, 0], [1, 1, 1]])}, ) assert np.all(r.measurements['a'] == np.array([[0, 0], [1, 1]])) assert np.all(r.measurements['b'] == np.array([[0, 0, 0], [1, 1, 1]])) @@ -110,10 +107,7 @@ def test_construct_from_repeated_measurements(): r2 = cirq.ResultDict( params=None, - records={ - 'a': np.array([[[0, 0]], [[1, 1]]]), - 'b': np.array([[[0, 0, 0]], [[1, 1, 1]]]), - }, + records={'a': np.array([[[0, 0]], [[1, 1]]]), 'b': np.array([[[0, 0, 0]], [[1, 1, 1]]])}, ) assert np.all(r2.measurements['a'] == np.array([[0, 0], [1, 1]])) assert np.all(r2.measurements['b'] == np.array([[0, 0, 0], [1, 1, 1]])) @@ -196,11 +190,7 @@ def test_histogram(): assert result.histogram(key='ab', fold_func=tuple) == collections.Counter( {(False, True): 4, (True, False): 1} ) - assert result.histogram(key='ab', fold_func=lambda e: None) == collections.Counter( - { - None: 5, - } - ) + assert result.histogram(key='ab', fold_func=lambda e: None) == collections.Counter({None: 5}) assert result.histogram(key='c') == collections.Counter({0: 3, 1: 2}) @@ -214,64 +204,27 @@ def test_multi_measurement_histogram(): ) assert result.multi_measurement_histogram(keys=['ab']) == collections.Counter( - { - (1,): 4, - (2,): 1, - } - ) - assert result.multi_measurement_histogram(keys=['c']) == collections.Counter( - { - (0,): 3, - (1,): 2, - } + {(1,): 4, (2,): 1} ) + assert result.multi_measurement_histogram(keys=['c']) == collections.Counter({(0,): 3, (1,): 2}) assert result.multi_measurement_histogram(keys=['ab', 'c']) == collections.Counter( - { - ( - 1, - 0, - ): 2, - ( - 1, - 1, - ): 2, - ( - 2, - 0, - ): 1, - } + {(1, 0): 2, (1, 1): 2, (2, 0): 1} ) assert result.multi_measurement_histogram( keys=[], fold_func=lambda e: None - ) == collections.Counter( - { - None: 5, - } - ) + ) == collections.Counter({None: 5}) assert result.multi_measurement_histogram( keys=['ab'], fold_func=lambda e: None - ) == collections.Counter( - { - None: 5, - } - ) + ) == collections.Counter({None: 5}) assert result.multi_measurement_histogram( keys=['ab', 'c'], fold_func=lambda e: None - ) == collections.Counter( - { - None: 5, - } - ) + ) == collections.Counter({None: 5}) assert result.multi_measurement_histogram( keys=['ab', 'c'], fold_func=lambda e: tuple(tuple(f) for f in e) ) == collections.Counter( - { - ((False, True), (False,)): 2, - ((False, True), (True,)): 2, - ((True, False), (False,)): 1, - } + {((False, True), (False,)): 2, ((False, True), (True,)): 2, ((True, False), (False,)): 1} ) @@ -302,10 +255,7 @@ def test_result_addition_valid(): ) b = cirq.ResultDict( params=cirq.ParamResolver({'ax': 1}), - measurements={ - 'q0': np.array([[0, 1]], dtype=bool), - 'q1': np.array([[0]], dtype=bool), - }, + measurements={'q0': np.array([[0, 1]], dtype=bool), 'q1': np.array([[0]], dtype=bool)}, ) c = a + b @@ -322,10 +272,7 @@ def test_result_addition_valid(): ) b = cirq.ResultDict( params=cirq.ParamResolver({'ax': 1}), - records={ - 'q0': np.array([[[0, 1]]], dtype=bool), - 'q1': np.array([[[1], [1]]], dtype=bool), - }, + records={'q0': np.array([[[0, 1]]], dtype=bool), 'q1': np.array([[[1], [1]]], dtype=bool)}, ) c = a + b @@ -388,11 +335,7 @@ def test_result_addition_invalid(): def test_qubit_keys_for_histogram(): a, b, c = cirq.LineQubit.range(3) - circuit = cirq.Circuit( - cirq.measure(a, b), - cirq.X(c), - cirq.measure(c), - ) + circuit = cirq.Circuit(cirq.measure(a, b), cirq.X(c), cirq.measure(c)) results = cirq.Simulator().run(program=circuit, repetitions=100) with pytest.raises(KeyError): _ = results.histogram(key=a) diff --git a/cirq-core/cirq/study/sweepable.py b/cirq-core/cirq/study/sweepable.py index 0c6ce35dbbd..bfb5553b7f8 100644 --- a/cirq-core/cirq/study/sweepable.py +++ b/cirq-core/cirq/study/sweepable.py @@ -35,10 +35,7 @@ def __iter__(self) -> Iterator[Union[SweepLike, '_Sweepable']]: Sweepable = Union[SweepLike, _Sweepable] -document( - Sweepable, - """An object or collection of objects representing a parameter sweep.""", -) +document(Sweepable, """An object or collection of objects representing a parameter sweep.""") def to_resolvers(sweepable: Sweepable) -> Iterator[ParamResolver]: diff --git a/cirq-core/cirq/study/sweepable_test.py b/cirq-core/cirq/study/sweepable_test.py index 98a35878d1a..c09ef35c7e1 100644 --- a/cirq-core/cirq/study/sweepable_test.py +++ b/cirq-core/cirq/study/sweepable_test.py @@ -70,10 +70,7 @@ def test_to_sweeps_sweep(): def test_to_sweeps_iterable(): resolvers = [cirq.ParamResolver({'a': 2}), cirq.ParamResolver({'a': 1})] - sweeps = [ - cirq.study.Zip(cirq.Points('a', [2])), - cirq.study.Zip(cirq.Points('a', [1])), - ] + sweeps = [cirq.study.Zip(cirq.Points('a', [2])), cirq.study.Zip(cirq.Points('a', [1]))] assert cirq.study.to_sweeps(resolvers) == sweeps assert cirq.study.to_sweeps([{'a': 2}, {'a': 1}]) == sweeps diff --git a/cirq-core/cirq/testing/__init__.py b/cirq-core/cirq/testing/__init__.py index 7124f91173e..5f2a3e20d98 100644 --- a/cirq-core/cirq/testing/__init__.py +++ b/cirq-core/cirq/testing/__init__.py @@ -24,13 +24,9 @@ assert_has_consistent_qid_shape, ) -from cirq.testing.consistent_act_on import ( - assert_all_implemented_act_on_effects_match_unitary, -) +from cirq.testing.consistent_act_on import assert_all_implemented_act_on_effects_match_unitary -from cirq.testing.consistent_controlled_gate_op import ( - assert_controlled_and_controlled_by_identical, -) +from cirq.testing.consistent_controlled_gate_op import assert_controlled_and_controlled_by_identical from cirq.testing.consistent_decomposition import ( assert_decompose_ends_at_default_gateset, @@ -41,9 +37,7 @@ assert_pauli_expansion_is_consistent_with_unitary, ) -from cirq.testing.consistent_phase_by import ( - assert_phase_by_is_consistent_with_unitary, -) +from cirq.testing.consistent_phase_by import assert_phase_by_is_consistent_with_unitary from cirq.testing.consistent_protocols import ( assert_eigengate_implements_consistent_protocols, @@ -52,46 +46,25 @@ assert_commutes_magic_method_consistent_with_unitaries, ) -from cirq.testing.consistent_qasm import ( - assert_qasm_is_consistent_with_unitary, -) +from cirq.testing.consistent_qasm import assert_qasm_is_consistent_with_unitary -from cirq.testing.consistent_resolve_parameters import ( - assert_consistent_resolve_parameters, -) +from cirq.testing.consistent_resolve_parameters import assert_consistent_resolve_parameters -from cirq.testing.consistent_specified_has_unitary import ( - assert_specifies_has_unitary_if_unitary, -) +from cirq.testing.consistent_specified_has_unitary import assert_specifies_has_unitary_if_unitary -from cirq.testing.deprecation import ( - assert_deprecated, -) +from cirq.testing.deprecation import assert_deprecated -from cirq.testing.devices import ( - ValidatingTestDevice, -) +from cirq.testing.devices import ValidatingTestDevice -from cirq.testing.equals_tester import ( - EqualsTester, -) +from cirq.testing.equals_tester import EqualsTester -from cirq.testing.equivalent_basis_map import ( - assert_equivalent_computational_basis_map, -) +from cirq.testing.equivalent_basis_map import assert_equivalent_computational_basis_map -from cirq.testing.equivalent_repr_eval import ( - assert_equivalent_repr, -) +from cirq.testing.equivalent_repr_eval import assert_equivalent_repr -from cirq.testing.gate_features import ( - TwoQubitGate, - ThreeQubitGate, -) +from cirq.testing.gate_features import TwoQubitGate, ThreeQubitGate -from cirq.testing.json import ( - assert_json_roundtrip_works, -) +from cirq.testing.json import assert_json_roundtrip_works from cirq.testing.lin_alg_utils import ( assert_allclose_up_to_global_phase, @@ -103,21 +76,13 @@ random_unitary, ) -from cirq.testing.logs import ( - assert_logs, -) +from cirq.testing.logs import assert_logs -from cirq.testing.no_identifier_qubit import ( - NoIdentifierQubit, -) +from cirq.testing.no_identifier_qubit import NoIdentifierQubit -from cirq.testing.op_tree import ( - assert_equivalent_op_tree, -) +from cirq.testing.op_tree import assert_equivalent_op_tree -from cirq.testing.order_tester import ( - OrderTester, -) +from cirq.testing.order_tester import OrderTester from cirq.testing.random_circuit import ( DEFAULT_GATE_DOMAIN, @@ -125,11 +90,6 @@ random_two_qubit_circuit_with_czs, ) -from cirq.testing.repr_pretty_tester import ( - assert_repr_pretty, - FakePrinter, -) +from cirq.testing.repr_pretty_tester import assert_repr_pretty, FakePrinter -from cirq.testing.sample_circuits import ( - nonoptimal_toffoli_circuit, -) +from cirq.testing.sample_circuits import nonoptimal_toffoli_circuit diff --git a/cirq-core/cirq/testing/_compat_test_data/module_a/__init__.py b/cirq-core/cirq/testing/_compat_test_data/module_a/__init__.py index 5c2c9cd80b9..1d564f403b5 100644 --- a/cirq-core/cirq/testing/_compat_test_data/module_a/__init__.py +++ b/cirq-core/cirq/testing/_compat_test_data/module_a/__init__.py @@ -3,17 +3,11 @@ from logging import info -from cirq.testing._compat_test_data.module_a import ( - module_b, -) +from cirq.testing._compat_test_data.module_a import module_b -from cirq.testing._compat_test_data.module_a.dupe import ( - DUPE_CONSTANT, -) +from cirq.testing._compat_test_data.module_a.dupe import DUPE_CONSTANT -from cirq.testing._compat_test_data.module_a.types import ( - SampleType, -) +from cirq.testing._compat_test_data.module_a.types import SampleType MODULE_A_ATTRIBUTE = "module_a" diff --git a/cirq-core/cirq/testing/circuit_compare.py b/cirq-core/cirq/testing/circuit_compare.py index 4595c21eebb..cc8e512c30f 100644 --- a/cirq-core/cirq/testing/circuit_compare.py +++ b/cirq-core/cirq/testing/circuit_compare.py @@ -183,8 +183,7 @@ def assert_circuits_with_terminal_measurements_are_equivalent( def assert_same_circuits( - actual: circuits.AbstractCircuit, - expected: circuits.AbstractCircuit, + actual: circuits.AbstractCircuit, expected: circuits.AbstractCircuit ) -> None: """Asserts that two circuits are identical, with a descriptive error. diff --git a/cirq-core/cirq/testing/circuit_compare_test.py b/cirq-core/cirq/testing/circuit_compare_test.py index a66eeb99af8..c3391d71e44 100644 --- a/cirq-core/cirq/testing/circuit_compare_test.py +++ b/cirq-core/cirq/testing/circuit_compare_test.py @@ -17,9 +17,7 @@ import numpy as np import cirq -from cirq.testing.circuit_compare import ( - _assert_apply_unitary_works_when_axes_transposed, -) +from cirq.testing.circuit_compare import _assert_apply_unitary_works_when_axes_transposed def test_sensitive_to_phase(): @@ -49,65 +47,35 @@ def test_sensitive_to_measurement_but_not_measured_phase(): cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent( cirq.Circuit([cirq.Moment([cirq.measure(q)])]), - cirq.Circuit( - [ - cirq.Moment([cirq.Z(q)]), - cirq.Moment([cirq.measure(q)]), - ] - ), + cirq.Circuit([cirq.Moment([cirq.Z(q)]), cirq.Moment([cirq.measure(q)])]), ) a, b = cirq.LineQubit.range(2) cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent( cirq.Circuit([cirq.Moment([cirq.measure(a, b)])]), - cirq.Circuit( - [ - cirq.Moment([cirq.Z(a)]), - cirq.Moment([cirq.measure(a, b)]), - ] - ), + cirq.Circuit([cirq.Moment([cirq.Z(a)]), cirq.Moment([cirq.measure(a, b)])]), ) cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent( cirq.Circuit([cirq.Moment([cirq.measure(a)])]), - cirq.Circuit( - [ - cirq.Moment([cirq.Z(a)]), - cirq.Moment([cirq.measure(a)]), - ] - ), + cirq.Circuit([cirq.Moment([cirq.Z(a)]), cirq.Moment([cirq.measure(a)])]), ) cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent( cirq.Circuit([cirq.Moment([cirq.measure(a, b)])]), - cirq.Circuit( - [ - cirq.Moment([cirq.T(a), cirq.S(b)]), - cirq.Moment([cirq.measure(a, b)]), - ] - ), + cirq.Circuit([cirq.Moment([cirq.T(a), cirq.S(b)]), cirq.Moment([cirq.measure(a, b)])]), ) with pytest.raises(AssertionError): cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent( cirq.Circuit([cirq.Moment([cirq.measure(a)])]), - cirq.Circuit( - [ - cirq.Moment([cirq.T(a), cirq.S(b)]), - cirq.Moment([cirq.measure(a)]), - ] - ), + cirq.Circuit([cirq.Moment([cirq.T(a), cirq.S(b)]), cirq.Moment([cirq.measure(a)])]), ) cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent( cirq.Circuit([cirq.Moment([cirq.measure(a, b)])]), - cirq.Circuit( - [ - cirq.Moment([cirq.CZ(a, b)]), - cirq.Moment([cirq.measure(a, b)]), - ] - ), + cirq.Circuit([cirq.Moment([cirq.CZ(a, b)]), cirq.Moment([cirq.measure(a, b)])]), ) @@ -117,31 +85,19 @@ def test_sensitive_to_measurement_toggle(): with pytest.raises(AssertionError): cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent( cirq.Circuit([cirq.Moment([cirq.measure(q)])]), - cirq.Circuit( - [ - cirq.Moment([cirq.X(q)]), - cirq.Moment([cirq.measure(q)]), - ] - ), + cirq.Circuit([cirq.Moment([cirq.X(q)]), cirq.Moment([cirq.measure(q)])]), ) with pytest.raises(AssertionError): cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent( cirq.Circuit([cirq.Moment([cirq.measure(q)])]), - cirq.Circuit( - [ - cirq.Moment([cirq.measure(q, invert_mask=(True,))]), - ] - ), + cirq.Circuit([cirq.Moment([cirq.measure(q, invert_mask=(True,))])]), ) cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent( cirq.Circuit([cirq.Moment([cirq.measure(q)])]), cirq.Circuit( - [ - cirq.Moment([cirq.X(q)]), - cirq.Moment([cirq.measure(q, invert_mask=(True,))]), - ] + [cirq.Moment([cirq.X(q)]), cirq.Moment([cirq.measure(q, invert_mask=(True,))])] ), ) @@ -161,12 +117,7 @@ def test_measuring_qubits(): ) cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent( - cirq.Circuit( - [ - cirq.Moment([cirq.measure(a)]), - cirq.Moment([cirq.measure(b)]), - ] - ), + cirq.Circuit([cirq.Moment([cirq.measure(a)]), cirq.Moment([cirq.measure(b)])]), cirq.Circuit([cirq.Moment([cirq.measure(a, b)])]), ) @@ -220,29 +171,21 @@ def test_known_old_failure(): def test_assert_same_circuits(): a, b = cirq.LineQubit.range(2) - cirq.testing.assert_same_circuits( - cirq.Circuit(cirq.H(a)), - cirq.Circuit(cirq.H(a)), - ) + cirq.testing.assert_same_circuits(cirq.Circuit(cirq.H(a)), cirq.Circuit(cirq.H(a))) with pytest.raises(AssertionError) as exc_info: - cirq.testing.assert_same_circuits( - cirq.Circuit(cirq.H(a)), - cirq.Circuit(), - ) + cirq.testing.assert_same_circuits(cirq.Circuit(cirq.H(a)), cirq.Circuit()) assert 'differing moment:\n0\n' in exc_info.value.args[0] with pytest.raises(AssertionError) as exc_info: cirq.testing.assert_same_circuits( - cirq.Circuit(cirq.H(a), cirq.H(a)), - cirq.Circuit(cirq.H(a), cirq.CZ(a, b)), + cirq.Circuit(cirq.H(a), cirq.H(a)), cirq.Circuit(cirq.H(a), cirq.CZ(a, b)) ) assert 'differing moment:\n1\n' in exc_info.value.args[0] with pytest.raises(AssertionError): cirq.testing.assert_same_circuits( - cirq.Circuit(cirq.CNOT(a, b)), - cirq.Circuit(cirq.ControlledGate(cirq.X).on(a, b)), + cirq.Circuit(cirq.CNOT(a, b)), cirq.Circuit(cirq.ControlledGate(cirq.X).on(a, b)) ) diff --git a/cirq-core/cirq/testing/consistent_act_on.py b/cirq-core/cirq/testing/consistent_act_on.py index f4b617741a3..0bd30f378ec 100644 --- a/cirq-core/cirq/testing/consistent_act_on.py +++ b/cirq-core/cirq/testing/consistent_act_on.py @@ -160,9 +160,7 @@ def _final_clifford_tableau( tableau = clifford_tableau.CliffordTableau(len(qubit_map)) args = act_on_clifford_tableau_args.ActOnCliffordTableauArgs( - tableau=tableau, - qubits=list(qubit_map.keys()), - prng=np.random.RandomState(), + tableau=tableau, qubits=list(qubit_map.keys()), prng=np.random.RandomState() ) for op in circuit.all_operations(): try: diff --git a/cirq-core/cirq/testing/consistent_controlled_gate_op_test.py b/cirq-core/cirq/testing/consistent_controlled_gate_op_test.py index ade2a64c8b7..1e5b2d3c421 100644 --- a/cirq-core/cirq/testing/consistent_controlled_gate_op_test.py +++ b/cirq-core/cirq/testing/consistent_controlled_gate_op_test.py @@ -24,10 +24,7 @@ class GoodGate(cirq.EigenGate, cirq.SingleQubitGate): def _eigen_components(self) -> List[Tuple[float, np.ndarray]]: # coverage: ignore - return [ - (0, np.diag([1, 0])), - (1, np.diag([0, 1])), - ] + return [(0, np.diag([1, 0])), (1, np.diag([0, 1]))] class BadGateOperation(cirq.GateOperation): @@ -42,10 +39,7 @@ def controlled_by( class BadGate(cirq.EigenGate, cirq.SingleQubitGate): def _eigen_components(self) -> List[Tuple[float, np.ndarray]]: # coverage: ignore - return [ - (0, np.diag([1, 0])), - (1, np.diag([0, 1])), - ] + return [(0, np.diag([1, 0])), (1, np.diag([0, 1]))] def on(self, *qubits: 'cirq.Qid') -> 'cirq.Operation': return BadGateOperation(self, list(qubits)) @@ -75,14 +69,5 @@ def test_assert_controlled_and_controlled_by_identical(): with pytest.raises(ValueError, match=r'len\(control_values\[1\]\) != num_controls\[1\]'): cirq.testing.assert_controlled_and_controlled_by_identical( - GoodGate(), - num_controls=[1, 2], - control_values=[ - (1,), - ( - 1, - 1, - 1, - ), - ], + GoodGate(), num_controls=[1, 2], control_values=[(1,), (1, 1, 1)] ) diff --git a/cirq-core/cirq/testing/consistent_phase_by.py b/cirq-core/cirq/testing/consistent_phase_by.py index 3fd33b2fbc2..72a883c0a66 100644 --- a/cirq-core/cirq/testing/consistent_phase_by.py +++ b/cirq-core/cirq/testing/consistent_phase_by.py @@ -50,8 +50,5 @@ def assert_phase_by_is_consistent_with_unitary(val: Any): expected[s] *= np.conj(p) lin_alg_utils.assert_allclose_up_to_global_phase( - actual, - expected, - atol=1e-8, - err_msg=f'Phased unitary was incorrect for index #{i}', + actual, expected, atol=1e-8, err_msg=f'Phased unitary was incorrect for index #{i}' ) diff --git a/cirq-core/cirq/testing/consistent_phase_by_test.py b/cirq-core/cirq/testing/consistent_phase_by_test.py index 03c9f46eff7..97a4d1ae99b 100644 --- a/cirq-core/cirq/testing/consistent_phase_by_test.py +++ b/cirq-core/cirq/testing/consistent_phase_by_test.py @@ -41,13 +41,7 @@ def _qid_shape_(self): return (3,) def _unitary_(self): - return np.array( - [ - [0, 1j**-self.e, 0], - [0, 0, 1j**self.e], - [1, 0, 0], - ] - ) + return np.array([[0, 1j**-self.e, 0], [0, 0, 1j**self.e], [1, 0, 0]]) def _phase_by_(self, phase_turns: float, qubit_index: int): return GoodQuditPhaser(self.e + phase_turns * 4) diff --git a/cirq-core/cirq/testing/consistent_protocols.py b/cirq-core/cirq/testing/consistent_protocols.py index 1c0e5666fbd..bee35c6dd63 100644 --- a/cirq-core/cirq/testing/consistent_protocols.py +++ b/cirq-core/cirq/testing/consistent_protocols.py @@ -28,21 +28,13 @@ assert_decompose_is_consistent_with_unitary, assert_decompose_ends_at_default_gateset, ) -from cirq.testing.consistent_phase_by import ( - assert_phase_by_is_consistent_with_unitary, -) -from cirq.testing.consistent_qasm import ( - assert_qasm_is_consistent_with_unitary, -) +from cirq.testing.consistent_phase_by import assert_phase_by_is_consistent_with_unitary +from cirq.testing.consistent_qasm import assert_qasm_is_consistent_with_unitary from cirq.testing.consistent_pauli_expansion import ( assert_pauli_expansion_is_consistent_with_unitary, ) -from cirq.testing.consistent_resolve_parameters import ( - assert_consistent_resolve_parameters, -) -from cirq.testing.consistent_specified_has_unitary import ( - assert_specifies_has_unitary_if_unitary, -) +from cirq.testing.consistent_resolve_parameters import assert_consistent_resolve_parameters +from cirq.testing.consistent_specified_has_unitary import assert_specifies_has_unitary_if_unitary from cirq.testing.equivalent_repr_eval import assert_equivalent_repr from cirq.testing.consistent_controlled_gate_op import assert_controlled_and_controlled_by_identical diff --git a/cirq-core/cirq/testing/consistent_protocols_test.py b/cirq-core/cirq/testing/consistent_protocols_test.py index 4c9ef31518c..893a79e51bd 100644 --- a/cirq-core/cirq/testing/consistent_protocols_test.py +++ b/cirq-core/cirq/testing/consistent_protocols_test.py @@ -186,10 +186,7 @@ def __repr__(self): class GoodEigenGate(cirq.EigenGate, cirq.SingleQubitGate): def _eigen_components(self) -> List[Tuple[float, np.ndarray]]: - return [ - (0, np.diag([1, 0])), - (1, np.diag([0, 1])), - ] + return [(0, np.diag([1, 0])), (1, np.diag([0, 1]))] def __repr__(self): return 'GoodEigenGate(exponent={}, global_shift={!r})'.format( diff --git a/cirq-core/cirq/testing/deprecation.py b/cirq-core/cirq/testing/deprecation.py index 967c3b9dcac..32a39b35f17 100644 --- a/cirq-core/cirq/testing/deprecation.py +++ b/cirq-core/cirq/testing/deprecation.py @@ -42,11 +42,7 @@ def assert_deprecated(*msgs: str, deadline: str, count: Optional[int] = 1) -> It os.environ[ALLOW_DEPRECATION_IN_TEST] = 'True' try: with assert_logs( - *msgs, - deadline, - min_level=logging.WARNING, - max_level=logging.WARNING, - count=count, + *msgs, deadline, min_level=logging.WARNING, max_level=logging.WARNING, count=count ): yield finally: diff --git a/cirq-core/cirq/testing/equivalent_basis_map_test.py b/cirq-core/cirq/testing/equivalent_basis_map_test.py index 012a7bbc90b..ee84cbe7a3d 100644 --- a/cirq-core/cirq/testing/equivalent_basis_map_test.py +++ b/cirq-core/cirq/testing/equivalent_basis_map_test.py @@ -26,11 +26,7 @@ def test_correct_mappings(): ) cirq.testing.assert_equivalent_computational_basis_map( - maps={ - 0b001: 0b100, - 0b010: 0b010, - 0b100: 0b001, - }, + maps={0b001: 0b100, 0b010: 0b010, 0b100: 0b001}, circuit=circuits.Circuit(cirq.SWAP(a, c), cirq.I(b)), ) @@ -42,10 +38,6 @@ def test_incorrect_mappings(): match=r"0b001 \(1\) was mapped to " r"0b100 \(4\) instead of " r"0b010 \(2\)", ): cirq.testing.assert_equivalent_computational_basis_map( - maps={ - 0b001: 0b010, - 0b010: 0b100, - 0b100: 0b001, - }, + maps={0b001: 0b010, 0b010: 0b100, 0b100: 0b001}, circuit=circuits.Circuit(cirq.SWAP(a, c), cirq.I(b)), ) diff --git a/cirq-core/cirq/testing/random_circuit.py b/cirq-core/cirq/testing/random_circuit.py index e46f36e125f..c9c1b205a18 100644 --- a/cirq-core/cirq/testing/random_circuit.py +++ b/cirq-core/cirq/testing/random_circuit.py @@ -150,11 +150,7 @@ def random_one_qubit_gate(): return ops.PhasedXPowGate(phase_exponent=prng.rand(), exponent=prng.rand()) def one_cz(): - return [ - ops.CZ.on(q0, q1), - random_one_qubit_gate().on(q0), - random_one_qubit_gate().on(q1), - ] + return [ops.CZ.on(q0, q1), random_one_qubit_gate().on(q0), random_one_qubit_gate().on(q1)] return circuits.Circuit( [ diff --git a/cirq-core/cirq/transformers/__init__.py b/cirq-core/cirq/transformers/__init__.py index 33ad13c2e30..cbe0a73b45f 100644 --- a/cirq-core/cirq/transformers/__init__.py +++ b/cirq-core/cirq/transformers/__init__.py @@ -65,10 +65,7 @@ from cirq.transformers.eject_z import eject_z -from cirq.transformers.measurement_transformers import ( - defer_measurements, - dephase_measurements, -) +from cirq.transformers.measurement_transformers import defer_measurements, dephase_measurements from cirq.transformers.merge_k_qubit_gates import merge_k_qubit_unitaries diff --git a/cirq-core/cirq/transformers/analytical_decompositions/clifford_decomposition_test.py b/cirq-core/cirq/transformers/analytical_decompositions/clifford_decomposition_test.py index f339117eee8..e635ff7ae2f 100644 --- a/cirq-core/cirq/transformers/analytical_decompositions/clifford_decomposition_test.py +++ b/cirq-core/cirq/transformers/analytical_decompositions/clifford_decomposition_test.py @@ -40,9 +40,7 @@ def test_clifford_decompose_one_qubit(): """Two random instance for one qubit decomposition.""" qubits = cirq.LineQubit.range(1) args = cirq.ActOnCliffordTableauArgs( - tableau=cirq.CliffordTableau(num_qubits=1), - qubits=qubits, - prng=np.random.RandomState(), + tableau=cirq.CliffordTableau(num_qubits=1), qubits=qubits, prng=np.random.RandomState() ) cirq.act_on(cirq.X, args, qubits=[qubits[0]], allow_decompose=False) cirq.act_on(cirq.H, args, qubits=[qubits[0]], allow_decompose=False) @@ -54,9 +52,7 @@ def test_clifford_decompose_one_qubit(): qubits = cirq.LineQubit.range(1) args = cirq.ActOnCliffordTableauArgs( - tableau=cirq.CliffordTableau(num_qubits=1), - qubits=qubits, - prng=np.random.RandomState(), + tableau=cirq.CliffordTableau(num_qubits=1), qubits=qubits, prng=np.random.RandomState() ) cirq.act_on(cirq.Z, args, qubits=[qubits[0]], allow_decompose=False) cirq.act_on(cirq.H, args, qubits=[qubits[0]], allow_decompose=False) @@ -79,9 +75,7 @@ def test_clifford_decompose_two_qubits(): """Two random instance for two qubits decomposition.""" qubits = cirq.LineQubit.range(2) args = cirq.ActOnCliffordTableauArgs( - tableau=cirq.CliffordTableau(num_qubits=2), - qubits=qubits, - prng=np.random.RandomState(), + tableau=cirq.CliffordTableau(num_qubits=2), qubits=qubits, prng=np.random.RandomState() ) cirq.act_on(cirq.H, args, qubits=[qubits[0]], allow_decompose=False) cirq.act_on(cirq.CNOT, args, qubits=[qubits[0], qubits[1]], allow_decompose=False) @@ -92,9 +86,7 @@ def test_clifford_decompose_two_qubits(): qubits = cirq.LineQubit.range(2) args = cirq.ActOnCliffordTableauArgs( - tableau=cirq.CliffordTableau(num_qubits=2), - qubits=qubits, - prng=np.random.RandomState(), + tableau=cirq.CliffordTableau(num_qubits=2), qubits=qubits, prng=np.random.RandomState() ) cirq.act_on(cirq.H, args, qubits=[qubits[0]], allow_decompose=False) cirq.act_on(cirq.CNOT, args, qubits=[qubits[0], qubits[1]], allow_decompose=False) diff --git a/cirq-core/cirq/transformers/analytical_decompositions/single_qubit_decompositions.py b/cirq-core/cirq/transformers/analytical_decompositions/single_qubit_decompositions.py index e899b62c382..289da0f959a 100644 --- a/cirq-core/cirq/transformers/analytical_decompositions/single_qubit_decompositions.py +++ b/cirq-core/cirq/transformers/analytical_decompositions/single_qubit_decompositions.py @@ -199,10 +199,7 @@ def single_qubit_matrix_to_phased_x_z( return result -def single_qubit_matrix_to_phxz( - mat: np.ndarray, - atol: float = 0, -) -> Optional[ops.PhasedXZGate]: +def single_qubit_matrix_to_phxz(mat: np.ndarray, atol: float = 0) -> Optional[ops.PhasedXZGate]: """Implements a single-qubit operation with a PhasedXZ gate. Under the hood, this uses deconstruct_single_qubit_matrix_into_angles which @@ -224,9 +221,7 @@ def single_qubit_matrix_to_phxz( # Build the intended operation out of non-negligible XY and Z rotations. g = ops.PhasedXZGate( - axis_phase_exponent=2 * xy_phase_turn, - x_exponent=2 * xy_turn, - z_exponent=2 * total_z_turn, + axis_phase_exponent=2 * xy_phase_turn, x_exponent=2 * xy_turn, z_exponent=2 * total_z_turn ) if protocols.trace_distance_bound(g) <= atol: @@ -235,9 +230,7 @@ def single_qubit_matrix_to_phxz( # Special case: XY half-turns can absorb Z rotations. if math.isclose(abs(xy_turn), 0.5, abs_tol=atol): g = ops.PhasedXZGate( - axis_phase_exponent=2 * xy_phase_turn + total_z_turn, - x_exponent=1, - z_exponent=0, + axis_phase_exponent=2 * xy_phase_turn + total_z_turn, x_exponent=1, z_exponent=0 ) return g diff --git a/cirq-core/cirq/transformers/analytical_decompositions/single_qubit_decompositions_test.py b/cirq-core/cirq/transformers/analytical_decompositions/single_qubit_decompositions_test.py index 5b49bee62b0..9f82ae8c410 100644 --- a/cirq-core/cirq/transformers/analytical_decompositions/single_qubit_decompositions_test.py +++ b/cirq-core/cirq/transformers/analytical_decompositions/single_qubit_decompositions_test.py @@ -229,10 +229,7 @@ def test_single_qubit_matrix_to_phased_x_z_known(): @pytest.mark.parametrize( 'intended_effect', - [ - np.array([[0, 1j], [1, 0]]), - ] - + [cirq.testing.random_unitary(2) for _ in range(10)], + [np.array([[0, 1j], [1, 0]])] + [cirq.testing.random_unitary(2) for _ in range(10)], ) def test_single_qubit_matrix_to_phased_x_z_cases(intended_effect): gates = cirq.single_qubit_matrix_to_phased_x_z(intended_effect, atol=1e-6) diff --git a/cirq-core/cirq/transformers/analytical_decompositions/two_qubit_to_cz_test.py b/cirq-core/cirq/transformers/analytical_decompositions/two_qubit_to_cz_test.py index 08e6374c088..e968cb807d5 100644 --- a/cirq-core/cirq/transformers/analytical_decompositions/two_qubit_to_cz_test.py +++ b/cirq-core/cirq/transformers/analytical_decompositions/two_qubit_to_cz_test.py @@ -125,18 +125,7 @@ def assert_ops_implement_unitary(q0, q1, operations, intended_effect, atol=0.01) 'max_partial_cz_depth,max_full_cz_depth,effect', [ (0, 0, np.eye(4)), - ( - 0, - 0, - np.array( - [ - [0, 0, 0, 1], - [0, 0, 1, 0], - [0, 1, 0, 0], - [1, 0, 0, 0j], - ] - ), - ), + (0, 0, np.array([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0j]])), (0, 0, cirq.unitary(cirq.CZ**0.00000001)), (0.5, 2, cirq.unitary(cirq.CZ**0.5)), (1, 1, cirq.unitary(cirq.CZ)), @@ -144,57 +133,23 @@ def assert_ops_implement_unitary(q0, q1, operations, intended_effect, atol=0.01) ( 1, 1, - np.array( - [ - [1, 0, 0, 1j], - [0, 1, 1j, 0], - [0, 1j, 1, 0], - [1j, 0, 0, 1], - ] - ) - * np.sqrt(0.5), + np.array([[1, 0, 0, 1j], [0, 1, 1j, 0], [0, 1j, 1, 0], [1j, 0, 0, 1]]) * np.sqrt(0.5), ), ( 1, 1, - np.array( - [ - [1, 0, 0, -1j], - [0, 1, -1j, 0], - [0, -1j, 1, 0], - [-1j, 0, 0, 1], - ] - ) + np.array([[1, 0, 0, -1j], [0, 1, -1j, 0], [0, -1j, 1, 0], [-1j, 0, 0, 1]]) * np.sqrt(0.5), ), ( 1, 1, - np.array( - [ - [1, 0, 0, 1j], - [0, 1, -1j, 0], - [0, -1j, 1, 0], - [1j, 0, 0, 1], - ] - ) - * np.sqrt(0.5), + np.array([[1, 0, 0, 1j], [0, 1, -1j, 0], [0, -1j, 1, 0], [1j, 0, 0, 1]]) * np.sqrt(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)), - ( - 3, - 3, - np.array( - [ - [0, 0, 0, 1], - [0, 1, 0, 0], - [0, 0, 1, 0], - [1, 0, 0, 0j], - ] - ), - ), + (3, 3, np.array([[0, 0, 0, 1], [0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0j]])), ] + [(1, 2, _random_single_partial_cz_effect()) for _ in range(10)] + [(2, 2, _random_double_full_cz_effect()) for _ in range(10)] diff --git a/cirq-core/cirq/transformers/analytical_decompositions/two_qubit_to_fsim.py b/cirq-core/cirq/transformers/analytical_decompositions/two_qubit_to_fsim.py index f42fa8e294a..ec82098f10a 100644 --- a/cirq-core/cirq/transformers/analytical_decompositions/two_qubit_to_fsim.py +++ b/cirq-core/cirq/transformers/analytical_decompositions/two_qubit_to_fsim.py @@ -14,16 +14,7 @@ """Utility methods for decomposing two-qubit unitaries into FSim gates.""" -from typing import ( - Sequence, - Union, - Any, - List, - Iterator, - TYPE_CHECKING, - Iterable, - Optional, -) +from typing import Sequence, Union, Any, List, Iterator, TYPE_CHECKING, Iterable, Optional import numpy as np @@ -171,10 +162,7 @@ def num_qubits(self) -> int: def _decompose_(self, qubits): a, b = qubits - return [ - ops.XX(a, b) ** -0.5, - ops.YY(a, b) ** -0.25, - ] + return [ops.XX(a, b) ** -0.5, ops.YY(a, b) ** -0.25] _B = _BGate() @@ -231,26 +219,15 @@ def _decompose_interaction_into_two_b_gates_ignoring_single_qubit_ops( r = (np.sin(y) * np.cos(z)) ** 2 r = max(0.0, r) # Clamp out-of-range floating point error. if r > 0.499999999999: - rb = [ - ops.ry(np.pi).on(b), - ] + rb = [ops.ry(np.pi).on(b)] else: b1 = np.cos(y * 2) * np.cos(z * 2) / (1 - 2 * r) b1 = max(0.0, min(1, b1)) # Clamp out-of-range floating point error. b2 = np.arcsin(np.sqrt(b1)) b3 = np.arccos(1 - 4 * r) - rb = [ - ops.rz(-b2).on(b), - ops.ry(-b3).on(b), - ops.rz(-b2).on(b), - ] + rb = [ops.rz(-b2).on(b), ops.ry(-b3).on(b), ops.rz(-b2).on(b)] s = 1 if z < 0 else -1 - return [ - _B(a, b), - ops.ry(s * 2 * x).on(a), - *rb, - _B(a, b), - ] + return [_B(a, b), ops.ry(s * 2 * x).on(a), *rb, _B(a, b)] def _fix_single_qubit_gates_around_kak_interaction( diff --git a/cirq-core/cirq/transformers/analytical_decompositions/two_qubit_to_fsim_test.py b/cirq-core/cirq/transformers/analytical_decompositions/two_qubit_to_fsim_test.py index 73106b28db8..f821a9153b5 100644 --- a/cirq-core/cirq/transformers/analytical_decompositions/two_qubit_to_fsim_test.py +++ b/cirq-core/cirq/transformers/analytical_decompositions/two_qubit_to_fsim_test.py @@ -155,9 +155,7 @@ def test_decompose_two_qubit_interaction_into_four_fsim_gates(): ) assert set(c.all_qubits()) == set(cirq.LineQubit.range(10, 12)) c = cirq.decompose_two_qubit_interaction_into_four_fsim_gates( - cirq.CZ(*cirq.LineQubit.range(20, 22)), - fsim_gate=iswap, - qubits=cirq.LineQubit.range(10, 12), + cirq.CZ(*cirq.LineQubit.range(20, 22)), fsim_gate=iswap, qubits=cirq.LineQubit.range(10, 12) ) assert set(c.all_qubits()) == set(cirq.LineQubit.range(10, 12)) diff --git a/cirq-core/cirq/transformers/analytical_decompositions/two_qubit_to_sqrt_iswap.py b/cirq-core/cirq/transformers/analytical_decompositions/two_qubit_to_sqrt_iswap.py index 4cdb8898dc5..314200be135 100644 --- a/cirq-core/cirq/transformers/analytical_decompositions/two_qubit_to_sqrt_iswap.py +++ b/cirq-core/cirq/transformers/analytical_decompositions/two_qubit_to_sqrt_iswap.py @@ -321,13 +321,7 @@ def _kak_decomposition_to_sqrt_iswap_operations( u0_after=z_unitary, atol=atol, ) - return _decomp_to_operations( - q0, - q1, - ops.SQRT_ISWAP, - single_qubit_operations, - atol=atol, - ) + return _decomp_to_operations(q0, q1, ops.SQRT_ISWAP, single_qubit_operations, atol=atol) def _decomp_to_operations( @@ -436,8 +430,7 @@ def _single_qubit_matrices_with_sqrt_iswap( def _in_0_region( - interaction_coefficients: Tuple[float, float, float], - weyl_tol: float = 1e-8, + interaction_coefficients: Tuple[float, float, float], weyl_tol: float = 1e-8 ) -> bool: """Tests if (x, y, z) ~= (0, 0, 0) assuming x, y, z are canonical.""" x, y, z = interaction_coefficients @@ -445,8 +438,7 @@ def _in_0_region( def _in_1sqrt_iswap_region( - interaction_coefficients: Tuple[float, float, float], - weyl_tol: float = 1e-8, + interaction_coefficients: Tuple[float, float, float], weyl_tol: float = 1e-8 ) -> bool: """Tests if (x, y, z) ~= (π/8, π/8, 0), assuming x, y, z are canonical.""" x, y, z = interaction_coefficients @@ -454,8 +446,7 @@ def _in_1sqrt_iswap_region( def _in_2sqrt_iswap_region( - interaction_coefficients: Tuple[float, float, float], - weyl_tol: float = 1e-8, + interaction_coefficients: Tuple[float, float, float], weyl_tol: float = 1e-8 ) -> bool: """Tests if (x, y, z) is inside or within weyl_tol of the volume x >= y + |z| assuming x, y, z are canonical. @@ -472,8 +463,7 @@ def _in_2sqrt_iswap_region( def _in_3sqrt_iswap_region( - interaction_coefficients: Tuple[float, float, float], - weyl_tol: float = 1e-8, + interaction_coefficients: Tuple[float, float, float], weyl_tol: float = 1e-8 ) -> bool: """Any two-qubit operation is decomposable into three SQRT_ISWAP gates. @@ -486,8 +476,7 @@ def _in_3sqrt_iswap_region( def _decomp_0_matrices( - kak: 'cirq.KakDecomposition', - atol: float = 1e-8, + kak: 'cirq.KakDecomposition', atol: float = 1e-8 ) -> Tuple[Sequence[Tuple[np.ndarray, np.ndarray]], complex]: """Returns the single-qubit matrices for the 0-SQRT_ISWAP decomposition. @@ -505,8 +494,7 @@ def _decomp_0_matrices( def _decomp_1sqrt_iswap_matrices( - kak: 'cirq.KakDecomposition', - atol: float = 1e-8, + kak: 'cirq.KakDecomposition', atol: float = 1e-8 ) -> Tuple[Sequence[Tuple[np.ndarray, np.ndarray]], complex]: """Returns the single-qubit matrices for the 1-SQRT_ISWAP decomposition. @@ -519,8 +507,7 @@ def _decomp_1sqrt_iswap_matrices( def _decomp_2sqrt_iswap_matrices( - kak: 'cirq.KakDecomposition', - atol: float = 1e-8, + kak: 'cirq.KakDecomposition', atol: float = 1e-8 ) -> Tuple[Sequence[Tuple[np.ndarray, np.ndarray]], complex]: """Returns the single-qubit matrices for the 2-SQRT_ISWAP decomposition. @@ -583,8 +570,7 @@ def nonzero_sign(v): def _decomp_3sqrt_iswap_matrices( - kak: 'cirq.KakDecomposition', - atol: float = 1e-8, + kak: 'cirq.KakDecomposition', atol: float = 1e-8 ) -> Tuple[Sequence[Tuple[np.ndarray, np.ndarray]], complex]: """Returns the single-qubit matrices for the 3-SQRT_ISWAP decomposition. diff --git a/cirq-core/cirq/transformers/analytical_decompositions/two_qubit_to_sqrt_iswap_test.py b/cirq-core/cirq/transformers/analytical_decompositions/two_qubit_to_sqrt_iswap_test.py index 8db240fabb0..57e2a50a9a7 100644 --- a/cirq-core/cirq/transformers/analytical_decompositions/two_qubit_to_sqrt_iswap_test.py +++ b/cirq-core/cirq/transformers/analytical_decompositions/two_qubit_to_sqrt_iswap_test.py @@ -73,12 +73,7 @@ def perturbations_gate(gate, amount=1e-10): def perturbations_weyl(x, y, z, amount=1e-10): - return perturbations_gate( - cirq.KakDecomposition( - interaction_coefficients=(x, y, z), - ), - amount, - ) + return perturbations_gate(cirq.KakDecomposition(interaction_coefficients=(x, y, z)), amount) THREE_SQRT_ISWAP_UNITARIES = [ @@ -466,24 +461,12 @@ def test_decomp_sqrt_iswap_inv(u): def test_valid_check_raises(): q0 = cirq.LineQubit(0) with pytest.raises(AssertionError, match='Unitaries are completely different'): - assert_valid_decomp( - np.eye(4), - [cirq.X(q0)], - single_qubit_gate_types=(cirq.XPowGate,), - ) + assert_valid_decomp(np.eye(4), [cirq.X(q0)], single_qubit_gate_types=(cirq.XPowGate,)) with pytest.raises(AssertionError, match='Unitaries do not match closely enough'): - assert_valid_decomp( - np.eye(4), - [cirq.rx(0.01)(q0)], - single_qubit_gate_types=(cirq.Rx,), - ) + assert_valid_decomp(np.eye(4), [cirq.rx(0.01)(q0)], single_qubit_gate_types=(cirq.Rx,)) with pytest.raises( AssertionError, match='Global phase operation was output when it should not' ): assert_valid_decomp(np.eye(4), [cirq.global_phase_operation(np.exp(1j * 0.01))]) with pytest.raises(AssertionError, match='Disallowed operation was output'): - assert_valid_decomp( - np.eye(4), - [cirq.X(q0)], - single_qubit_gate_types=(cirq.IdentityGate,), - ) + assert_valid_decomp(np.eye(4), [cirq.X(q0)], single_qubit_gate_types=(cirq.IdentityGate,)) diff --git a/cirq-core/cirq/transformers/drop_empty_moments_test.py b/cirq-core/cirq/transformers/drop_empty_moments_test.py index 9fb2f58968e..213c75007ec 100644 --- a/cirq-core/cirq/transformers/drop_empty_moments_test.py +++ b/cirq-core/cirq/transformers/drop_empty_moments_test.py @@ -21,10 +21,7 @@ def test_drop(): cirq.testing.assert_same_circuits( cirq.drop_empty_moments( cirq.Circuit( - cirq.Moment(), - cirq.Moment(), - cirq.Moment([cirq.CNOT(q1, q2)]), - cirq.Moment(), + cirq.Moment(), cirq.Moment(), cirq.Moment([cirq.CNOT(q1, q2)]), cirq.Moment() ) ), cirq.Circuit(cirq.Moment([cirq.CNOT(q1, q2)])), @@ -34,10 +31,7 @@ def test_drop(): def test_drop_empty_moments(): q1, q2 = cirq.LineQubit.range(2) c_nested = cirq.FrozenCircuit( - cirq.Moment(), - cirq.Moment(), - cirq.Moment([cirq.CNOT(q1, q2)]), - cirq.Moment(), + cirq.Moment(), cirq.Moment(), cirq.Moment([cirq.CNOT(q1, q2)]), cirq.Moment() ) c_nested_dropped = cirq.FrozenCircuit(cirq.CNOT(q1, q2)) c_orig = cirq.Circuit( diff --git a/cirq-core/cirq/transformers/drop_negligible_operations_test.py b/cirq-core/cirq/transformers/drop_negligible_operations_test.py index 3f454decf95..cf2371f6380 100644 --- a/cirq-core/cirq/transformers/drop_negligible_operations_test.py +++ b/cirq-core/cirq/transformers/drop_negligible_operations_test.py @@ -92,6 +92,5 @@ def test_recursively_runs_inside_circuit_ops_deep(): ) context = cirq.TransformerContext(tags_to_ignore=[NO_COMPILE_TAG], deep=True) cirq.testing.assert_same_circuits( - cirq.drop_negligible_operations(c_orig, context=context, atol=0.001), - c_expected, + cirq.drop_negligible_operations(c_orig, context=context, atol=0.001), c_expected ) diff --git a/cirq-core/cirq/transformers/eject_phased_paulis.py b/cirq-core/cirq/transformers/eject_phased_paulis.py index c58fb6b14ed..369b733ac1d 100644 --- a/cirq-core/cirq/transformers/eject_phased_paulis.py +++ b/cirq-core/cirq/transformers/eject_phased_paulis.py @@ -150,9 +150,7 @@ def _dump_into_measurement( def _potential_cross_whole_w( - op: ops.Operation, - atol: float, - held_w_phases: Dict[ops.Qid, value.TParamVal], + op: ops.Operation, atol: float, held_w_phases: Dict[ops.Qid, value.TParamVal] ) -> 'cirq.OP_TREE': """Grabs or cancels a held W gate against an existing W gate. @@ -185,8 +183,7 @@ def _potential_cross_whole_w( def _potential_cross_partial_w( - op: ops.Operation, - held_w_phases: Dict[ops.Qid, value.TParamVal], + op: ops.Operation, held_w_phases: Dict[ops.Qid, value.TParamVal] ) -> 'cirq.OP_TREE': """Cross the held W over a partial W gate. diff --git a/cirq-core/cirq/transformers/eject_phased_paulis_test.py b/cirq-core/cirq/transformers/eject_phased_paulis_test.py index 9ef93c97777..58a45f03452 100644 --- a/cirq-core/cirq/transformers/eject_phased_paulis_test.py +++ b/cirq-core/cirq/transformers/eject_phased_paulis_test.py @@ -104,13 +104,8 @@ def test_absorbs_z(): # Full Z. assert_optimizes( - before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], - [cirq.Z(q)], - ), - expected=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.625).on(q)], - ), + before=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], [cirq.Z(q)]), + expected=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.625).on(q)]), ) # PhasedXZGate @@ -119,9 +114,7 @@ def test_absorbs_z(): [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], [cirq.PhasedXZGate(x_exponent=0, axis_phase_exponent=0, z_exponent=1).on(q)], ), - expected=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.625).on(q)], - ), + expected=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.625).on(q)]), ) # Partial Z. PhasedXZGate with z_exponent = 0. @@ -130,67 +123,44 @@ def test_absorbs_z(): [cirq.PhasedXZGate(x_exponent=1, axis_phase_exponent=0.125, z_exponent=0).on(q)], [cirq.S(q)], ), - expected=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.375).on(q)], - ), + expected=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.375).on(q)]), ) # parameterized Z. assert_optimizes( - before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], - [cirq.Z(q) ** x], - ), - expected=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.125 + x / 2).on(q)], - ), + before=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], [cirq.Z(q) ** x]), + expected=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.125 + x / 2).on(q)]), eject_parameterized=True, ) assert_optimizes( before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], - [cirq.Z(q) ** (x + 1)], - ), - expected=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.625 + x / 2).on(q)], + [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], [cirq.Z(q) ** (x + 1)] ), + expected=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.625 + x / 2).on(q)]), eject_parameterized=True, ) # Multiple Zs. assert_optimizes( before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], - [cirq.S(q)], - [cirq.T(q) ** -1], - ), - expected=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], + [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], [cirq.S(q)], [cirq.T(q) ** -1] ), + expected=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.25).on(q)]), ) # Multiple Parameterized Zs. assert_optimizes( before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], - [cirq.S(q) ** x], - [cirq.T(q) ** -x], - ), - expected=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.125 + x * 0.125).on(q)], + [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], [cirq.S(q) ** x], [cirq.T(q) ** -x] ), + expected=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.125 + x * 0.125).on(q)]), eject_parameterized=True, ) # Parameterized Phase and Partial Z assert_optimizes( - before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=x).on(q)], - [cirq.S(q)], - ), - expected=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=x + 0.25).on(q)], - ), + before=quick_circuit([cirq.PhasedXPowGate(phase_exponent=x).on(q)], [cirq.S(q)]), + expected=quick_circuit([cirq.PhasedXPowGate(phase_exponent=x + 0.25).on(q)]), eject_parameterized=True, ) @@ -204,62 +174,33 @@ def test_crosses_czs(): # Full CZ. assert_optimizes( - before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.25).on(a)], - [cirq.CZ(a, b)], - ), + before=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.25).on(a)], [cirq.CZ(a, b)]), expected=quick_circuit( - [cirq.Z(b)], - [cirq.CZ(a, b)], - [cirq.PhasedXPowGate(phase_exponent=0.25).on(a)], + [cirq.Z(b)], [cirq.CZ(a, b)], [cirq.PhasedXPowGate(phase_exponent=0.25).on(a)] ), ) assert_optimizes( - before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.125).on(a)], - [cirq.CZ(b, a)], - ), + before=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.125).on(a)], [cirq.CZ(b, a)]), expected=quick_circuit( - [cirq.Z(b)], - [cirq.CZ(a, b)], - [cirq.PhasedXPowGate(phase_exponent=0.125).on(a)], + [cirq.Z(b)], [cirq.CZ(a, b)], [cirq.PhasedXPowGate(phase_exponent=0.125).on(a)] ), ) assert_optimizes( - before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=x).on(a)], - [cirq.CZ(b, a)], - ), + before=quick_circuit([cirq.PhasedXPowGate(phase_exponent=x).on(a)], [cirq.CZ(b, a)]), expected=quick_circuit( - [cirq.Z(b)], - [cirq.CZ(a, b)], - [cirq.PhasedXPowGate(phase_exponent=x).on(a)], + [cirq.Z(b)], [cirq.CZ(a, b)], [cirq.PhasedXPowGate(phase_exponent=x).on(a)] ), eject_parameterized=True, ) # Partial CZ. assert_optimizes( - before=quick_circuit( - [cirq.X(a)], - [cirq.CZ(a, b) ** 0.25], - ), - expected=quick_circuit( - [cirq.Z(b) ** 0.25], - [cirq.CZ(a, b) ** -0.25], - [cirq.X(a)], - ), + before=quick_circuit([cirq.X(a)], [cirq.CZ(a, b) ** 0.25]), + expected=quick_circuit([cirq.Z(b) ** 0.25], [cirq.CZ(a, b) ** -0.25], [cirq.X(a)]), ) assert_optimizes( - before=quick_circuit( - [cirq.X(a)], - [cirq.CZ(a, b) ** x], - ), - expected=quick_circuit( - [cirq.Z(b) ** x], - [cirq.CZ(a, b) ** -x], - [cirq.X(a)], - ), + before=quick_circuit([cirq.X(a)], [cirq.CZ(a, b) ** x]), + expected=quick_circuit([cirq.Z(b) ** x], [cirq.CZ(a, b) ** -x], [cirq.X(a)]), eject_parameterized=True, ) @@ -303,30 +244,19 @@ def test_toggles_measurements(): # Single. assert_optimizes( before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.25).on(a)], - [cirq.measure(a, b)], - ), - expected=quick_circuit( - [cirq.measure(a, b, invert_mask=(True,))], + [cirq.PhasedXPowGate(phase_exponent=0.25).on(a)], [cirq.measure(a, b)] ), + expected=quick_circuit([cirq.measure(a, b, invert_mask=(True,))]), ) assert_optimizes( before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.25).on(b)], - [cirq.measure(a, b)], - ), - expected=quick_circuit( - [cirq.measure(a, b, invert_mask=(False, True))], + [cirq.PhasedXPowGate(phase_exponent=0.25).on(b)], [cirq.measure(a, b)] ), + expected=quick_circuit([cirq.measure(a, b, invert_mask=(False, True))]), ) assert_optimizes( - before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=x).on(b)], - [cirq.measure(a, b)], - ), - expected=quick_circuit( - [cirq.measure(a, b, invert_mask=(False, True))], - ), + before=quick_circuit([cirq.PhasedXPowGate(phase_exponent=x).on(b)], [cirq.measure(a, b)]), + expected=quick_circuit([cirq.measure(a, b, invert_mask=(False, True))]), eject_parameterized=True, ) @@ -337,20 +267,15 @@ def test_toggles_measurements(): [cirq.PhasedXPowGate(phase_exponent=0.25).on(b)], [cirq.measure(a, b)], ), - expected=quick_circuit( - [cirq.measure(a, b, invert_mask=(True, True))], - ), + expected=quick_circuit([cirq.measure(a, b, invert_mask=(True, True))]), ) # Xmon. assert_optimizes( before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.25).on(a)], - [cirq.measure(a, b, key='t')], - ), - expected=quick_circuit( - [cirq.measure(a, b, invert_mask=(True,), key='t')], + [cirq.PhasedXPowGate(phase_exponent=0.25).on(a)], [cirq.measure(a, b, key='t')] ), + expected=quick_circuit([cirq.measure(a, b, invert_mask=(True,), key='t')]), ) # CCOs @@ -411,49 +336,27 @@ def test_cancels_other_full_w(): [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], ), - expected=quick_circuit( - [cirq.Z(q) ** -0.25], - ), + expected=quick_circuit([cirq.Z(q) ** -0.25]), ) assert_optimizes( - before=quick_circuit( - [cirq.X(q)], - [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], - ), - expected=quick_circuit( - [cirq.Z(q) ** 0.5], - ), + before=quick_circuit([cirq.X(q)], [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)]), + expected=quick_circuit([cirq.Z(q) ** 0.5]), ) assert_optimizes( - before=quick_circuit( - [cirq.Y(q)], - [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], - ), - expected=quick_circuit( - [cirq.Z(q) ** -0.5], - ), + before=quick_circuit([cirq.Y(q)], [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)]), + expected=quick_circuit([cirq.Z(q) ** -0.5]), ) assert_optimizes( - before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], - [cirq.X(q)], - ), - expected=quick_circuit( - [cirq.Z(q) ** -0.5], - ), + before=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], [cirq.X(q)]), + expected=quick_circuit([cirq.Z(q) ** -0.5]), ) assert_optimizes( - before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], - [cirq.Y(q)], - ), - expected=quick_circuit( - [cirq.Z(q) ** 0.5], - ), + before=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], [cirq.Y(q)]), + expected=quick_circuit([cirq.Z(q) ** 0.5]), ) assert_optimizes( @@ -461,9 +364,7 @@ def test_cancels_other_full_w(): [cirq.PhasedXPowGate(phase_exponent=x).on(q)], [cirq.PhasedXPowGate(phase_exponent=y).on(q)], ), - expected=quick_circuit( - [cirq.Z(q) ** (2 * (y - x))], - ), + expected=quick_circuit([cirq.Z(q) ** (2 * (y - x))]), eject_parameterized=True, ) @@ -476,20 +377,15 @@ def test_phases_partial_ws(): assert_optimizes( before=quick_circuit( - [cirq.X(q)], - [cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(q)], + [cirq.X(q)], [cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(q)] ), expected=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=-0.25, exponent=0.5).on(q)], - [cirq.X(q)], + [cirq.PhasedXPowGate(phase_exponent=-0.25, exponent=0.5).on(q)], [cirq.X(q)] ), ) assert_optimizes( - before=quick_circuit( - [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], - [cirq.X(q) ** 0.5], - ), + before=quick_circuit([cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], [cirq.X(q) ** 0.5]), expected=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.5, exponent=0.5).on(q)], [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], @@ -502,8 +398,7 @@ def test_phases_partial_ws(): [cirq.PhasedXPowGate(phase_exponent=0.5, exponent=0.75).on(q)], ), expected=quick_circuit( - [cirq.X(q) ** 0.75], - [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], + [cirq.X(q) ** 0.75], [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)] ), ) @@ -512,8 +407,7 @@ def test_phases_partial_ws(): [cirq.X(q)], [cirq.PhasedXPowGate(exponent=-0.25, phase_exponent=0.5).on(q)] ), expected=quick_circuit( - [cirq.PhasedXPowGate(exponent=-0.25, phase_exponent=-0.5).on(q)], - [cirq.X(q)], + [cirq.PhasedXPowGate(exponent=-0.25, phase_exponent=-0.5).on(q)], [cirq.X(q)] ), ) @@ -530,55 +424,25 @@ def test_phases_partial_ws(): ) -@pytest.mark.parametrize( - 'sym', - [ - sympy.Symbol('x'), - sympy.Symbol('x') + 1, - ], -) +@pytest.mark.parametrize('sym', [sympy.Symbol('x'), sympy.Symbol('x') + 1]) def test_blocked_by_unknown_and_symbols(sym): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') assert_optimizes( - before=quick_circuit( - [cirq.X(a)], - [cirq.SWAP(a, b)], - [cirq.X(a)], - ), - expected=quick_circuit( - [cirq.X(a)], - [cirq.SWAP(a, b)], - [cirq.X(a)], - ), + before=quick_circuit([cirq.X(a)], [cirq.SWAP(a, b)], [cirq.X(a)]), + expected=quick_circuit([cirq.X(a)], [cirq.SWAP(a, b)], [cirq.X(a)]), ) assert_optimizes( - before=quick_circuit( - [cirq.X(a)], - [cirq.Z(a) ** sym], - [cirq.X(a)], - ), - expected=quick_circuit( - [cirq.X(a)], - [cirq.Z(a) ** sym], - [cirq.X(a)], - ), + before=quick_circuit([cirq.X(a)], [cirq.Z(a) ** sym], [cirq.X(a)]), + expected=quick_circuit([cirq.X(a)], [cirq.Z(a) ** sym], [cirq.X(a)]), compare_unitaries=False, ) assert_optimizes( - before=quick_circuit( - [cirq.X(a)], - [cirq.CZ(a, b) ** sym], - [cirq.X(a)], - ), - expected=quick_circuit( - [cirq.X(a)], - [cirq.CZ(a, b) ** sym], - [cirq.X(a)], - ), + before=quick_circuit([cirq.X(a)], [cirq.CZ(a, b) ** sym], [cirq.X(a)]), + expected=quick_circuit([cirq.X(a)], [cirq.CZ(a, b) ** sym], [cirq.X(a)]), compare_unitaries=False, ) @@ -588,16 +452,8 @@ def test_blocked_by_nocompile_tag(): b = cirq.NamedQubit('b') assert_optimizes( - before=quick_circuit( - [cirq.X(a)], - [cirq.CZ(a, b).with_tags("nocompile")], - [cirq.X(a)], - ), - expected=quick_circuit( - [cirq.X(a)], - [cirq.CZ(a, b).with_tags("nocompile")], - [cirq.X(a)], - ), + before=quick_circuit([cirq.X(a)], [cirq.CZ(a, b).with_tags("nocompile")], [cirq.X(a)]), + expected=quick_circuit([cirq.X(a)], [cirq.CZ(a, b).with_tags("nocompile")], [cirq.X(a)]), with_context=True, ) @@ -605,11 +461,4 @@ def test_blocked_by_nocompile_tag(): def test_zero_x_rotation(): a = cirq.NamedQubit('a') - assert_optimizes( - before=quick_circuit( - [cirq.rx(0)(a)], - ), - expected=quick_circuit( - [cirq.rx(0)(a)], - ), - ) + assert_optimizes(before=quick_circuit([cirq.rx(0)(a)]), expected=quick_circuit([cirq.rx(0)(a)])) diff --git a/cirq-core/cirq/transformers/eject_z_test.py b/cirq-core/cirq/transformers/eject_z_test.py index 7c0daae894a..45059304b3b 100644 --- a/cirq-core/cirq/transformers/eject_z_test.py +++ b/cirq-core/cirq/transformers/eject_z_test.py @@ -97,16 +97,8 @@ def assert_removes_all_z_gates(circuit: cirq.Circuit, eject_parameterized: bool def test_single_z_stays(): q = cirq.NamedQubit('q') assert_optimizes( - before=cirq.Circuit( - [ - cirq.Moment([cirq.Z(q) ** 0.5]), - ] - ), - expected=cirq.Circuit( - [ - cirq.Moment([cirq.Z(q) ** 0.5]), - ] - ), + before=cirq.Circuit([cirq.Moment([cirq.Z(q) ** 0.5])]), + expected=cirq.Circuit([cirq.Moment([cirq.Z(q) ** 0.5])]), ) @@ -144,56 +136,25 @@ def test_ignores_xz_and_cz(): def test_early_z(): q = cirq.NamedQubit('q') assert_optimizes( - before=cirq.Circuit( - [ - cirq.Moment([cirq.Z(q) ** 0.5]), - cirq.Moment(), - cirq.Moment(), - ] - ), - expected=cirq.Circuit( - [ - cirq.Moment([cirq.Z(q) ** 0.5]), - cirq.Moment(), - cirq.Moment(), - ] - ), + before=cirq.Circuit([cirq.Moment([cirq.Z(q) ** 0.5]), cirq.Moment(), cirq.Moment()]), + expected=cirq.Circuit([cirq.Moment([cirq.Z(q) ** 0.5]), cirq.Moment(), cirq.Moment()]), ) def test_multi_z_merges(): q = cirq.NamedQubit('q') assert_optimizes( - before=cirq.Circuit( - [ - cirq.Moment([cirq.Z(q) ** 0.5]), - cirq.Moment([cirq.Z(q) ** 0.25]), - ] - ), - expected=cirq.Circuit( - [ - cirq.Moment(), - cirq.Moment([cirq.Z(q) ** 0.75]), - ] - ), + before=cirq.Circuit([cirq.Moment([cirq.Z(q) ** 0.5]), cirq.Moment([cirq.Z(q) ** 0.25])]), + expected=cirq.Circuit([cirq.Moment(), cirq.Moment([cirq.Z(q) ** 0.75])]), ) def test_z_pushes_past_xy_and_phases_it(): q = cirq.NamedQubit('q') assert_optimizes( - before=cirq.Circuit( - [ - cirq.Moment([cirq.Z(q) ** 0.5]), - cirq.Moment([cirq.Y(q) ** 0.25]), - ] - ), + before=cirq.Circuit([cirq.Moment([cirq.Z(q) ** 0.5]), cirq.Moment([cirq.Y(q) ** 0.25])]), expected=cirq.Circuit( - [ - cirq.Moment(), - cirq.Moment([cirq.X(q) ** 0.25]), - cirq.Moment([cirq.Z(q) ** 0.5]), - ] + [cirq.Moment(), cirq.Moment([cirq.X(q) ** 0.25]), cirq.Moment([cirq.Z(q) ** 0.5])] ), ) @@ -203,17 +164,10 @@ def test_z_pushes_past_cz(): b = cirq.NamedQubit('b') assert_optimizes( before=cirq.Circuit( - [ - cirq.Moment([cirq.Z(a) ** 0.5]), - cirq.Moment([cirq.CZ(a, b) ** 0.25]), - ] + [cirq.Moment([cirq.Z(a) ** 0.5]), cirq.Moment([cirq.CZ(a, b) ** 0.25])] ), expected=cirq.Circuit( - [ - cirq.Moment(), - cirq.Moment([cirq.CZ(a, b) ** 0.25]), - cirq.Moment([cirq.Z(a) ** 0.5]), - ] + [cirq.Moment(), cirq.Moment([cirq.CZ(a, b) ** 0.25]), cirq.Moment([cirq.Z(a) ** 0.5])] ), ) @@ -228,13 +182,7 @@ def test_measurement_consumes_zs(): cirq.Moment([cirq.measure(q)]), ] ), - expected=cirq.Circuit( - [ - cirq.Moment(), - cirq.Moment(), - cirq.Moment([cirq.measure(q)]), - ] - ), + expected=cirq.Circuit([cirq.Moment(), cirq.Moment(), cirq.Moment([cirq.measure(q)])]), ) @@ -273,13 +221,7 @@ class UnknownGate(cirq.SingleQubitGate): ) -@pytest.mark.parametrize( - 'sym', - [ - sympy.Symbol('a'), - sympy.Symbol('a') + 1, - ], -) +@pytest.mark.parametrize('sym', [sympy.Symbol('a'), sympy.Symbol('a') + 1]) def test_symbols_block(sym): q = cirq.NamedQubit('q') assert_optimizes( @@ -291,22 +233,12 @@ def test_symbols_block(sym): ] ), expected=cirq.Circuit( - [ - cirq.Moment(), - cirq.Moment([cirq.Z(q) ** sym]), - cirq.Moment([cirq.Z(q) ** 1.25]), - ] + [cirq.Moment(), cirq.Moment([cirq.Z(q) ** sym]), cirq.Moment([cirq.Z(q) ** 1.25])] ), ) -@pytest.mark.parametrize( - 'sym', - [ - sympy.Symbol('a'), - sympy.Symbol('a') + 1, - ], -) +@pytest.mark.parametrize('sym', [sympy.Symbol('a'), sympy.Symbol('a') + 1]) def test_symbols_eject(sym): q = cirq.NamedQubit('q') assert_optimizes( @@ -318,11 +250,7 @@ def test_symbols_eject(sym): ] ), expected=cirq.Circuit( - [ - cirq.Moment(), - cirq.Moment(), - cirq.Moment([cirq.Z(q) ** (sym + 1.25)]), - ] + [cirq.Moment(), cirq.Moment(), cirq.Moment([cirq.Z(q) ** (sym + 1.25)])] ), eject_parameterized=True, ) @@ -381,18 +309,8 @@ def with_qubits(self, *new_qubits): u = UnknownOp() assert_optimizes( - before=cirq.Circuit( - [ - cirq.Moment([cirq.Z(q)]), - cirq.Moment([u]), - ] - ), - expected=cirq.Circuit( - [ - cirq.Moment([cirq.Z(q)]), - cirq.Moment([u]), - ] - ), + before=cirq.Circuit([cirq.Moment([cirq.Z(q)]), cirq.Moment([u])]), + expected=cirq.Circuit([cirq.Moment([cirq.Z(q)]), cirq.Moment([u])]), ) @@ -400,18 +318,8 @@ def test_tagged_nocompile_operation_blocks(): q = cirq.NamedQubit('q') u = cirq.Z(q).with_tags("nocompile") assert_optimizes( - before=cirq.Circuit( - [ - cirq.Moment([cirq.Z(q)]), - cirq.Moment([u]), - ] - ), - expected=cirq.Circuit( - [ - cirq.Moment([cirq.Z(q)]), - cirq.Moment([u]), - ] - ), + before=cirq.Circuit([cirq.Moment([cirq.Z(q)]), cirq.Moment([u])]), + expected=cirq.Circuit([cirq.Moment([cirq.Z(q)]), cirq.Moment([u])]), with_context=True, ) diff --git a/cirq-core/cirq/transformers/expand_composite.py b/cirq-core/cirq/transformers/expand_composite.py index db1f97fe54c..ef15d06537c 100644 --- a/cirq-core/cirq/transformers/expand_composite.py +++ b/cirq-core/cirq/transformers/expand_composite.py @@ -51,11 +51,7 @@ def expand_composite( def map_func(op: 'cirq.Operation', _) -> 'cirq.OP_TREE': if context and context.deep and isinstance(op.untagged, circuits.CircuitOperation): return op - return protocols.decompose( - op, - keep=no_decomp, - on_stuck_raise=None, - ) + return protocols.decompose(op, keep=no_decomp, on_stuck_raise=None) return transformer_primitives.map_operations_and_unroll( circuit, diff --git a/cirq-core/cirq/transformers/measurement_transformers.py b/cirq-core/cirq/transformers/measurement_transformers.py index 1c1323e0242..711d6cc56ea 100644 --- a/cirq-core/cirq/transformers/measurement_transformers.py +++ b/cirq-core/cirq/transformers/measurement_transformers.py @@ -15,10 +15,7 @@ from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union from cirq import ops, protocols, value -from cirq.transformers import ( - transformer_api, - transformer_primitives, -) +from cirq.transformers import transformer_api, transformer_primitives from cirq.transformers.synchronize_terminal_measurements import find_terminal_measurements if TYPE_CHECKING: diff --git a/cirq-core/cirq/transformers/measurement_transformers_test.py b/cirq-core/cirq/transformers/measurement_transformers_test.py index 462665278ab..c8defced4c9 100644 --- a/cirq-core/cirq/transformers/measurement_transformers_test.py +++ b/cirq-core/cirq/transformers/measurement_transformers_test.py @@ -272,10 +272,7 @@ def test_repr(qid: _MeasurementQid): def test_multi_qubit_control(): q0, q1 = cirq.LineQubit.range(2) - circuit = cirq.Circuit( - cirq.measure(q0, q1, key='a'), - cirq.X(q1).with_classical_controls('a'), - ) + circuit = cirq.Circuit(cirq.measure(q0, q1, key='a'), cirq.X(q1).with_classical_controls('a')) with pytest.raises(ValueError, match='Only single qubit conditions are allowed'): _ = cirq.defer_measurements(circuit) @@ -283,8 +280,7 @@ def test_multi_qubit_control(): def test_sympy_control(): q0, q1 = cirq.LineQubit.range(2) circuit = cirq.Circuit( - cirq.measure(q0, q1, key='a'), - cirq.X(q1).with_classical_controls(sympy.Symbol('a')), + cirq.measure(q0, q1, key='a'), cirq.X(q1).with_classical_controls(sympy.Symbol('a')) ) with pytest.raises(ValueError, match='Only KeyConditions are allowed'): _ = cirq.defer_measurements(circuit) diff --git a/cirq-core/cirq/transformers/merge_k_qubit_gates_test.py b/cirq-core/cirq/transformers/merge_k_qubit_gates_test.py index 1135ce3a1d4..9f475326060 100644 --- a/cirq-core/cirq/transformers/merge_k_qubit_gates_test.py +++ b/cirq-core/cirq/transformers/merge_k_qubit_gates_test.py @@ -228,10 +228,7 @@ def rewriter_merge_to_circuit_op(op: 'cirq.CircuitOperation') -> 'cirq.OP_TREE': context = cirq.TransformerContext(tags_to_ignore=("ignore",), deep=True) c_new = cirq.merge_k_qubit_unitaries( - c_orig, - k=2, - context=context, - rewriter=rewriter_merge_to_circuit_op, + c_orig, k=2, context=context, rewriter=rewriter_merge_to_circuit_op ) cirq.testing.assert_same_circuits(c_new, c_expected) diff --git a/cirq-core/cirq/transformers/optimize_for_target_gateset_test.py b/cirq-core/cirq/transformers/optimize_for_target_gateset_test.py index 0efb950fa7a..cb2e971c2bd 100644 --- a/cirq-core/cirq/transformers/optimize_for_target_gateset_test.py +++ b/cirq-core/cirq/transformers/optimize_for_target_gateset_test.py @@ -127,10 +127,7 @@ def decompose_to_target_gateset(self, op: 'cirq.Operation', _) -> DecomposeResul def test_optimize_for_target_gateset_default(): q = cirq.LineQubit.range(2) c_orig = cirq.Circuit( - cirq.T(q[0]), - cirq.SWAP(*q), - cirq.T(q[0]), - cirq.SWAP(*q).with_tags("ignore"), + cirq.T(q[0]), cirq.SWAP(*q), cirq.T(q[0]), cirq.SWAP(*q).with_tags("ignore") ) context = cirq.TransformerContext(tags_to_ignore=("ignore",)) c_new = cirq.optimize_for_target_gateset(c_orig, context=context) diff --git a/cirq-core/cirq/transformers/stratify.py b/cirq-core/cirq/transformers/stratify.py index cccce4163ae..61cbdd412a4 100644 --- a/cirq-core/cirq/transformers/stratify.py +++ b/cirq-core/cirq/transformers/stratify.py @@ -15,17 +15,7 @@ """Transformer pass to repack circuits avoiding simultaneous operations with different classes.""" import itertools -from typing import ( - TYPE_CHECKING, - Type, - Callable, - Optional, - Union, - Iterable, - Sequence, - List, - Tuple, -) +from typing import TYPE_CHECKING, Type, Callable, Optional, Union, Iterable, Sequence, List, Tuple from cirq import ops, circuits, _import from cirq.transformers import transformer_api, transformer_primitives diff --git a/cirq-core/cirq/transformers/stratify_test.py b/cirq-core/cirq/transformers/stratify_test.py index f3f002711c8..fa8b5c3d62d 100644 --- a/cirq-core/cirq/transformers/stratify_test.py +++ b/cirq-core/cirq/transformers/stratify_test.py @@ -24,130 +24,43 @@ def test_deprecated_submodule(): def test_stratified_circuit_classifier_types(): a, b, c, d = cirq.LineQubit.range(4) - circuit = cirq.Circuit( - cirq.Moment( - [ - cirq.X(a), - cirq.Y(b), - cirq.X(c) ** 0.5, - cirq.X(d), - ] - ), - ) + circuit = cirq.Circuit(cirq.Moment([cirq.X(a), cirq.Y(b), cirq.X(c) ** 0.5, cirq.X(d)])) - gate_result = cirq.stratified_circuit( - circuit, - categories=[ - cirq.X, - ], - ) + gate_result = cirq.stratified_circuit(circuit, categories=[cirq.X]) cirq.testing.assert_same_circuits( gate_result, cirq.Circuit( - cirq.Moment( - [ - cirq.X(a), - cirq.X(d), - ] - ), - cirq.Moment( - [ - cirq.Y(b), - cirq.X(c) ** 0.5, - ] - ), + cirq.Moment([cirq.X(a), cirq.X(d)]), cirq.Moment([cirq.Y(b), cirq.X(c) ** 0.5]) ), ) - gate_type_result = cirq.stratified_circuit( - circuit, - categories=[ - cirq.XPowGate, - ], - ) + gate_type_result = cirq.stratified_circuit(circuit, categories=[cirq.XPowGate]) cirq.testing.assert_same_circuits( gate_type_result, cirq.Circuit( - cirq.Moment( - [ - cirq.X(a), - cirq.X(c) ** 0.5, - cirq.X(d), - ] - ), - cirq.Moment( - [ - cirq.Y(b), - ] - ), + cirq.Moment([cirq.X(a), cirq.X(c) ** 0.5, cirq.X(d)]), cirq.Moment([cirq.Y(b)]) ), ) - operation_result = cirq.stratified_circuit( - circuit, - categories=[ - cirq.X(a), - ], - ) + operation_result = cirq.stratified_circuit(circuit, categories=[cirq.X(a)]) cirq.testing.assert_same_circuits( operation_result, cirq.Circuit( - cirq.Moment( - [ - cirq.X(a), - ] - ), - cirq.Moment( - [ - cirq.Y(b), - cirq.X(c) ** 0.5, - cirq.X(d), - ] - ), + cirq.Moment([cirq.X(a)]), cirq.Moment([cirq.Y(b), cirq.X(c) ** 0.5, cirq.X(d)]) ), ) - operation_type_result = cirq.stratified_circuit( - circuit, - categories=[ - cirq.GateOperation, - ], - ) + operation_type_result = cirq.stratified_circuit(circuit, categories=[cirq.GateOperation]) cirq.testing.assert_same_circuits( operation_type_result, - cirq.Circuit( - cirq.Moment( - [ - cirq.X(a), - cirq.Y(b), - cirq.X(c) ** 0.5, - cirq.X(d), - ] - ) - ), + cirq.Circuit(cirq.Moment([cirq.X(a), cirq.Y(b), cirq.X(c) ** 0.5, cirq.X(d)])), ) - predicate_result = cirq.stratified_circuit( - circuit, - categories=[ - lambda op: op.qubits == (b,), - ], - ) + predicate_result = cirq.stratified_circuit(circuit, categories=[lambda op: op.qubits == (b,)]) cirq.testing.assert_same_circuits( predicate_result, cirq.Circuit( - cirq.Moment( - [ - cirq.Y(b), - ] - ), - cirq.Moment( - [ - cirq.X(a), - cirq.X(d), - cirq.X(c) ** 0.5, - ] - ), + cirq.Moment([cirq.Y(b)]), cirq.Moment([cirq.X(a), cirq.X(d), cirq.X(c) ** 0.5]) ), ) @@ -160,30 +73,10 @@ def test_overlapping_categories(): result = cirq.stratified_circuit( cirq.Circuit( - cirq.Moment( - [ - cirq.X(a), - cirq.Y(b), - cirq.Z(c), - ] - ), - cirq.Moment( - [ - cirq.CNOT(a, b), - ] - ), - cirq.Moment( - [ - cirq.CNOT(c, d), - ] - ), - cirq.Moment( - [ - cirq.X(a), - cirq.Y(b), - cirq.Z(c), - ] - ), + cirq.Moment([cirq.X(a), cirq.Y(b), cirq.Z(c)]), + cirq.Moment([cirq.CNOT(a, b)]), + cirq.Moment([cirq.CNOT(c, d)]), + cirq.Moment([cirq.X(a), cirq.Y(b), cirq.Z(c)]), ), categories=[ lambda op: len(op.qubits) == 1 and not isinstance(op.gate, cirq.XPowGate), @@ -194,34 +87,11 @@ def test_overlapping_categories(): cirq.testing.assert_same_circuits( result, cirq.Circuit( - cirq.Moment( - [ - cirq.Y(b), - cirq.Z(c), - ] - ), - cirq.Moment( - [ - cirq.X(a), - ] - ), - cirq.Moment( - [ - cirq.CNOT(a, b), - cirq.CNOT(c, d), - ] - ), - cirq.Moment( - [ - cirq.Y(b), - cirq.Z(c), - ] - ), - cirq.Moment( - [ - cirq.X(a), - ] - ), + cirq.Moment([cirq.Y(b), cirq.Z(c)]), + cirq.Moment([cirq.X(a)]), + cirq.Moment([cirq.CNOT(a, b), cirq.CNOT(c, d)]), + cirq.Moment([cirq.Y(b), cirq.Z(c)]), + cirq.Moment([cirq.X(a)]), ), ) @@ -363,19 +233,13 @@ def test_stratify_respects_no_compile_operations(): cirq.TaggedOperation(cirq.X(cirq.LineQubit(0)), 'nocompile'), cirq.TaggedOperation(cirq.ISWAP(cirq.LineQubit(1), cirq.LineQubit(2)), 'nocompile'), ), - cirq.Moment( - cirq.X(cirq.LineQubit(0)), - ), - cirq.Moment( - cirq.Z(cirq.LineQubit(4)), - ), + cirq.Moment(cirq.X(cirq.LineQubit(0))), + cirq.Moment(cirq.Z(cirq.LineQubit(4))), cirq.Moment( cirq.ISWAP(cirq.LineQubit(3), cirq.LineQubit(4)), cirq.ISWAP(cirq.LineQubit(0), cirq.LineQubit(1)), ), - cirq.Moment( - cirq.X(cirq.LineQubit(3)), - ), + cirq.Moment(cirq.X(cirq.LineQubit(3))), ] ) cirq.testing.assert_has_diagram( @@ -465,20 +329,9 @@ def test_heterogeneous_circuit(): expected = cirq.Circuit( cirq.Moment([cirq.ISWAP(q3, q4), cirq.ISWAP(q5, q6)]), cirq.Moment([cirq.X(q1), cirq.X(q2), cirq.X(q5), cirq.X(q6)]), - cirq.Moment( - [ - cirq.ISWAP(q1, q2), - cirq.ISWAP(q3, q4), - ] - ), + cirq.Moment([cirq.ISWAP(q1, q2), cirq.ISWAP(q3, q4)]), cirq.Moment([cirq.Z(q2), cirq.Z(q4), cirq.Z(q6)]), - cirq.Moment( - [ - cirq.X(q1), - cirq.X(q3), - cirq.X(q5), - ] - ), + cirq.Moment([cirq.X(q1), cirq.X(q3), cirq.X(q5)]), ) cirq.testing.assert_same_circuits( diff --git a/cirq-core/cirq/transformers/synchronize_terminal_measurements_test.py b/cirq-core/cirq/transformers/synchronize_terminal_measurements_test.py index 76a7795c512..f80547e2fe9 100644 --- a/cirq-core/cirq/transformers/synchronize_terminal_measurements_test.py +++ b/cirq-core/cirq/transformers/synchronize_terminal_measurements_test.py @@ -101,9 +101,7 @@ def test_slide_forward_one(): q2 = cirq.NamedQubit('q2') q3 = cirq.NamedQubit('q3') before = cirq.Circuit( - [ - cirq.Moment([cirq.H(q1), cirq.measure(q2).with_tags(NO_COMPILE_TAG), cirq.measure(q3)]), - ] + [cirq.Moment([cirq.H(q1), cirq.measure(q2).with_tags(NO_COMPILE_TAG), cirq.measure(q3)])] ) after = cirq.Circuit( [ @@ -125,16 +123,8 @@ def test_no_slide_forward_one(): q1 = cirq.NamedQubit('q1') q2 = cirq.NamedQubit('q2') q3 = cirq.NamedQubit('q3') - before = cirq.Circuit( - [ - cirq.Moment([cirq.H(q1), cirq.measure(q2), cirq.measure(q3)]), - ] - ) - after = cirq.Circuit( - [ - cirq.Moment([cirq.H(q1), cirq.measure(q2), cirq.measure(q3)]), - ] - ) + before = cirq.Circuit([cirq.Moment([cirq.H(q1), cirq.measure(q2), cirq.measure(q3)])]) + after = cirq.Circuit([cirq.Moment([cirq.H(q1), cirq.measure(q2), cirq.measure(q3)])]) assert_optimizes(before=before, after=after, measure_only_moment=False) diff --git a/cirq-core/cirq/transformers/target_gatesets/compilation_target_gateset.py b/cirq-core/cirq/transformers/target_gatesets/compilation_target_gateset.py index fd1516aec17..d63e7d09ac4 100644 --- a/cirq-core/cirq/transformers/target_gatesets/compilation_target_gateset.py +++ b/cirq-core/cirq/transformers/target_gatesets/compilation_target_gateset.py @@ -19,10 +19,7 @@ from cirq import circuits, ops, protocols, _import from cirq.protocols.decompose_protocol import DecomposeResult -from cirq.transformers import ( - merge_k_qubit_gates, - merge_single_qubit_gates, -) +from cirq.transformers import merge_k_qubit_gates, merge_single_qubit_gates drop_empty_moments = _import.LazyLoader('drop_empty_moments', globals(), 'cirq.transformers') drop_negligible = _import.LazyLoader('drop_negligible_operations', globals(), 'cirq.transformers') diff --git a/cirq-core/cirq/transformers/target_gatesets/cz_gateset.py b/cirq-core/cirq/transformers/target_gatesets/cz_gateset.py index 5fd2d358fd4..02d89544a44 100644 --- a/cirq-core/cirq/transformers/target_gatesets/cz_gateset.py +++ b/cirq-core/cirq/transformers/target_gatesets/cz_gateset.py @@ -62,10 +62,7 @@ def _value_equality_values_(self) -> Any: return self.atol, self.allow_partial_czs def _json_dict_(self) -> Dict[str, Any]: - return { - 'atol': self.atol, - 'allow_partial_czs': self.allow_partial_czs, - } + return {'atol': self.atol, 'allow_partial_czs': self.allow_partial_czs} @classmethod def _from_json_dict_(cls, atol, allow_partial_czs, **kwargs): diff --git a/cirq-core/cirq/transformers/target_gatesets/cz_gateset_test.py b/cirq-core/cirq/transformers/target_gatesets/cz_gateset_test.py index 14b89cab966..3f3964d9385 100644 --- a/cirq-core/cirq/transformers/target_gatesets/cz_gateset_test.py +++ b/cirq-core/cirq/transformers/target_gatesets/cz_gateset_test.py @@ -87,10 +87,7 @@ def test_convert_to_cz_preserving_moment_structure(): def test_clears_paired_cnot(): a, b = cirq.LineQubit.range(2) assert_optimizes( - before=cirq.Circuit( - cirq.Moment(cirq.CNOT(a, b)), - cirq.Moment(cirq.CNOT(a, b)), - ), + before=cirq.Circuit(cirq.Moment(cirq.CNOT(a, b)), cirq.Moment(cirq.CNOT(a, b))), expected=cirq.Circuit(), ) @@ -117,25 +114,13 @@ def test_ignores_czs_separated_by_parameterized(): def test_cnots_separated_by_single_gates_correct(): a, b = cirq.LineQubit.range(2) - assert_optimization_not_broken( - cirq.Circuit( - cirq.CNOT(a, b), - cirq.H(b), - cirq.CNOT(a, b), - ) - ) + assert_optimization_not_broken(cirq.Circuit(cirq.CNOT(a, b), cirq.H(b), cirq.CNOT(a, b))) def test_czs_separated_by_single_gates_correct(): a, b = cirq.LineQubit.range(2) assert_optimization_not_broken( - cirq.Circuit( - cirq.CZ(a, b), - cirq.X(b), - cirq.X(b), - cirq.X(b), - cirq.CZ(a, b), - ) + cirq.Circuit(cirq.CZ(a, b), cirq.X(b), cirq.X(b), cirq.X(b), cirq.CZ(a, b)) ) @@ -192,9 +177,7 @@ def test_not_decompose_czs(): @pytest.mark.parametrize( 'circuit', ( - cirq.Circuit( - cirq.CZPowGate(exponent=0.1)(*cirq.LineQubit.range(2)), - ), + cirq.Circuit(cirq.CZPowGate(exponent=0.1)(*cirq.LineQubit.range(2))), cirq.Circuit( cirq.CZPowGate(exponent=0.2)(*cirq.LineQubit.range(2)), cirq.CZPowGate(exponent=0.3, global_shift=-0.5)(*cirq.LineQubit.range(2)), @@ -216,7 +199,7 @@ def test_decompose_partial_czs(circuit): def test_not_decompose_partial_czs(): circuit = cirq.Circuit( - cirq.CZPowGate(exponent=0.1, global_shift=-0.5)(*cirq.LineQubit.range(2)), + cirq.CZPowGate(exponent=0.1, global_shift=-0.5)(*cirq.LineQubit.range(2)) ) cirq.optimize_for_target_gateset(circuit, gateset=cirq.CZTargetGateset()) cz_gates = [ @@ -273,16 +256,9 @@ def _decompose_(self, qubits): yield CompositeDummy()(qubits[1]) q0, q1 = cirq.LineQubit.range(2) - circuit = cirq.Circuit( - CompositeDummy()(q0), - CompositeDummy2()(q0, q1), - ) + circuit = cirq.Circuit(CompositeDummy()(q0), CompositeDummy2()(q0, q1)) expected = cirq.Circuit( - cirq.X(q0), - cirq.Y(q0) ** 0.5, - cirq.CZ(q0, q1), - cirq.X(q1), - cirq.Y(q1) ** 0.5, + cirq.X(q0), cirq.Y(q0) ** 0.5, cirq.CZ(q0, q1), cirq.X(q1), cirq.Y(q1) ** 0.5 ) c_new = cirq.optimize_for_target_gateset(circuit, gateset=cirq.CZTargetGateset()) diff --git a/cirq-core/cirq/transformers/target_gatesets/sqrt_iswap_gateset.py b/cirq-core/cirq/transformers/target_gatesets/sqrt_iswap_gateset.py index 1cfdb556505..256df95b4ac 100644 --- a/cirq-core/cirq/transformers/target_gatesets/sqrt_iswap_gateset.py +++ b/cirq-core/cirq/transformers/target_gatesets/sqrt_iswap_gateset.py @@ -89,11 +89,7 @@ def __repr__(self) -> str: ) def _value_equality_values_(self) -> Any: - return ( - self.atol, - self.required_sqrt_iswap_count, - self.use_sqrt_iswap_inv, - ) + return (self.atol, self.required_sqrt_iswap_count, self.use_sqrt_iswap_inv) def _json_dict_(self) -> Dict[str, Any]: return { diff --git a/cirq-core/cirq/transformers/target_gatesets/sqrt_iswap_gateset_test.py b/cirq-core/cirq/transformers/target_gatesets/sqrt_iswap_gateset_test.py index 81f2553420c..9f2af0fd3ba 100644 --- a/cirq-core/cirq/transformers/target_gatesets/sqrt_iswap_gateset_test.py +++ b/cirq-core/cirq/transformers/target_gatesets/sqrt_iswap_gateset_test.py @@ -177,11 +177,7 @@ def test_simplifies_sqrt_iswap(): cirq.Moment([cirq.SQRT_ISWAP(a, b)]), ] ), - expected=cirq.Circuit( - [ - cirq.Moment([cirq.SQRT_ISWAP(a, b)]), - ] - ), + expected=cirq.Circuit([cirq.Moment([cirq.SQRT_ISWAP(a, b)])]), ) @@ -203,11 +199,7 @@ def test_simplifies_sqrt_iswap_inv(): cirq.Moment([cirq.SQRT_ISWAP(a, b)]), ] ), - expected=cirq.Circuit( - [ - cirq.Moment([cirq.SQRT_ISWAP_INV(a, b)]), - ] - ), + expected=cirq.Circuit([cirq.Moment([cirq.SQRT_ISWAP_INV(a, b)])]), ) @@ -221,11 +213,7 @@ def test_works_with_tags(): cirq.Moment([cirq.SQRT_ISWAP_INV(a, b).with_tags('mytag3')]), ] ), - expected=cirq.Circuit( - [ - cirq.Moment([cirq.SQRT_ISWAP(a, b)]), - ] - ), + expected=cirq.Circuit([cirq.Moment([cirq.SQRT_ISWAP(a, b)])]), ) @@ -235,7 +223,7 @@ def test_no_touch_single_sqrt_iswap(): [ cirq.Moment( [cirq.ISwapPowGate(exponent=0.5, global_shift=-0.5).on(a, b).with_tags('mytag')] - ), + ) ] ) assert_optimizes(before=circuit, expected=circuit) @@ -247,7 +235,7 @@ def test_no_touch_single_sqrt_iswap_inv(): [ cirq.Moment( [cirq.ISwapPowGate(exponent=-0.5, global_shift=-0.5).on(a, b).with_tags('mytag')] - ), + ) ] ) assert_optimizes(before=circuit, expected=circuit, use_sqrt_iswap_inv=True) @@ -255,25 +243,13 @@ def test_no_touch_single_sqrt_iswap_inv(): def test_cnots_separated_by_single_gates_correct(): a, b = cirq.LineQubit.range(2) - assert_optimization_not_broken( - cirq.Circuit( - cirq.CNOT(a, b), - cirq.H(b), - cirq.CNOT(a, b), - ) - ) + assert_optimization_not_broken(cirq.Circuit(cirq.CNOT(a, b), cirq.H(b), cirq.CNOT(a, b))) def test_czs_separated_by_single_gates_correct(): a, b = cirq.LineQubit.range(2) assert_optimization_not_broken( - cirq.Circuit( - cirq.CZ(a, b), - cirq.X(b), - cirq.X(b), - cirq.X(b), - cirq.CZ(a, b), - ) + cirq.Circuit(cirq.CZ(a, b), cirq.X(b), cirq.X(b), cirq.X(b), cirq.CZ(a, b)) ) diff --git a/cirq-core/cirq/transformers/transformer_api.py b/cirq-core/cirq/transformers/transformer_api.py index 66e275c484d..3111ff00278 100644 --- a/cirq-core/cirq/transformers/transformer_api.py +++ b/cirq-core/cirq/transformers/transformer_api.py @@ -347,8 +347,7 @@ def transformer(cls_or_func: Any = None, *, add_deep_support: bool = False) -> A # without a `cls` argument, then passes `cls` into the result. if cls_or_func is None: return lambda deferred_cls_or_func: transformer( - deferred_cls_or_func, - add_deep_support=add_deep_support, + deferred_cls_or_func, add_deep_support=add_deep_support ) if isinstance(cls_or_func, type): diff --git a/cirq-core/cirq/transformers/transformer_api_test.py b/cirq-core/cirq/transformers/transformer_api_test.py index 9ec7d506661..938fd407a61 100644 --- a/cirq-core/cirq/transformers/transformer_api_test.py +++ b/cirq-core/cirq/transformers/transformer_api_test.py @@ -103,10 +103,7 @@ def mock_tranformer_func( cirq.TransformerContext(logger=mock.Mock(), tags_to_ignore=('tag',)), ], ) -@pytest.mark.parametrize( - 'transformer', - [MockTransformerClass(), make_transformer_func()], -) +@pytest.mark.parametrize('transformer', [MockTransformerClass(), make_transformer_func()]) def test_transformer_decorator(context, transformer): circuit = cirq.Circuit(cirq.X(cirq.NamedQubit("a"))) transformer(circuit, context=context) @@ -120,11 +117,7 @@ def test_transformer_decorator(context, transformer): @pytest.mark.parametrize( - 'transformer', - [ - MockTransformerClassWithDefaults(), - make_transformer_func_with_defaults(), - ], + 'transformer', [MockTransformerClassWithDefaults(), make_transformer_func_with_defaults()] ) def test_transformer_decorator_with_defaults(transformer): circuit = cirq.Circuit(cirq.X(cirq.NamedQubit("a"))) diff --git a/cirq-core/cirq/transformers/transformer_primitives.py b/cirq-core/cirq/transformers/transformer_primitives.py index 38ec7bbde7f..934ae13fb50 100644 --- a/cirq-core/cirq/transformers/transformer_primitives.py +++ b/cirq-core/cirq/transformers/transformer_primitives.py @@ -15,17 +15,7 @@ """Defines primitives for common transformer patterns.""" from collections import defaultdict -from typing import ( - cast, - Callable, - Dict, - Hashable, - List, - Optional, - Sequence, - Union, - TYPE_CHECKING, -) +from typing import cast, Callable, Dict, Hashable, List, Optional, Sequence, Union, TYPE_CHECKING from cirq import circuits, ops, protocols from cirq.circuits.circuit import CIRCUIT_TYPE diff --git a/cirq-core/cirq/transformers/transformer_primitives_test.py b/cirq-core/cirq/transformers/transformer_primitives_test.py index 51f947c645a..7f824eae3e1 100644 --- a/cirq-core/cirq/transformers/transformer_primitives_test.py +++ b/cirq-core/cirq/transformers/transformer_primitives_test.py @@ -62,11 +62,7 @@ def test_map_operations_can_write_new_gates_inline(): def test_map_operations_does_not_insert_too_many_moments(): q = cirq.LineQubit.range(5) - c_orig = cirq.Circuit( - cirq.CX(q[0], q[1]), - cirq.CX(q[3], q[2]), - cirq.CX(q[3], q[4]), - ) + c_orig = cirq.Circuit(cirq.CX(q[0], q[1]), cirq.CX(q[3], q[2]), cirq.CX(q[3], q[4])) def map_func(op: cirq.Operation, _: int) -> cirq.OP_TREE: yield cirq.Z.on_each(*op.qubits) @@ -120,11 +116,7 @@ def map_func(op: cirq.Operation, _: int) -> cirq.OP_TREE: # pylint: disable=line-too-long def test_map_operations_deep_subcircuits(): q = cirq.LineQubit.range(5) - c_orig = cirq.Circuit( - cirq.CX(q[0], q[1]), - cirq.CX(q[3], q[2]), - cirq.CX(q[3], q[4]), - ) + c_orig = cirq.Circuit(cirq.CX(q[0], q[1]), cirq.CX(q[3], q[2]), cirq.CX(q[3], q[4])) c_orig_with_circuit_ops = cirq.Circuit( cirq.CircuitOperation( cirq.FrozenCircuit( @@ -402,10 +394,7 @@ def test_unroll_circuit_op_no_tags(): unroller(c, tags_to_check=("custom tag",)), cirq.Circuit([op1, op_list, op3]) ) cirq.testing.assert_same_circuits( - unroller( - c, - tags_to_check=("custom tag", MAPPED_CIRCUIT_OP_TAG), - ), + unroller(c, tags_to_check=("custom tag", MAPPED_CIRCUIT_OP_TAG)), cirq.Circuit([op1, op_list, op_list]), ) diff --git a/cirq-core/cirq/value/__init__.py b/cirq-core/cirq/value/__init__.py index bd34876530c..728c564404e 100644 --- a/cirq-core/cirq/value/__init__.py +++ b/cirq-core/cirq/value/__init__.py @@ -13,11 +13,7 @@ # limitations under the License. """Value conversion utilities and classes for time and quantum states.""" -from cirq.value.abc_alt import ( - ABCMetaImplementAnyOneOf, - alternative, - GenericMetaImplementAnyOneOf, -) +from cirq.value.abc_alt import ABCMetaImplementAnyOneOf, alternative, GenericMetaImplementAnyOneOf from cirq.value.angle import ( canonicalize_half_turns, @@ -32,11 +28,7 @@ MeasurementType, ) -from cirq.value.condition import ( - Condition, - KeyCondition, - SympyCondition, -) +from cirq.value.condition import Condition, KeyCondition, SympyCondition from cirq.value.digits import ( big_endian_bits_to_int, @@ -45,20 +37,11 @@ big_endian_int_to_digits, ) -from cirq.value.duration import ( - Duration, - DURATION_LIKE, -) +from cirq.value.duration import Duration, DURATION_LIKE -from cirq.value.linear_dict import ( - LinearDict, - Scalar, -) +from cirq.value.linear_dict import LinearDict, Scalar -from cirq.value.measurement_key import ( - MEASUREMENT_KEY_SEPARATOR, - MeasurementKey, -) +from cirq.value.measurement_key import MEASUREMENT_KEY_SEPARATOR, MeasurementKey from cirq.value.probability import state_vector_to_probabilities, validate_probability @@ -73,24 +56,12 @@ PAULI_STATES, ) -from cirq.value.periodic_value import ( - PeriodicValue, -) +from cirq.value.periodic_value import PeriodicValue -from cirq.value.random_state import ( - parse_random_state, - RANDOM_STATE_OR_SEED_LIKE, -) +from cirq.value.random_state import parse_random_state, RANDOM_STATE_OR_SEED_LIKE -from cirq.value.timestamp import ( - Timestamp, -) +from cirq.value.timestamp import Timestamp -from cirq.value.type_alias import ( - TParamKey, - TParamVal, -) +from cirq.value.type_alias import TParamKey, TParamVal -from cirq.value.value_equality_attr import ( - value_equality, -) +from cirq.value.value_equality_attr import value_equality diff --git a/cirq-core/cirq/value/condition.py b/cirq-core/cirq/value/condition.py index 081c2d04e71..98cbf76566f 100644 --- a/cirq-core/cirq/value/condition.py +++ b/cirq-core/cirq/value/condition.py @@ -39,10 +39,7 @@ def replace_key(self, current: 'cirq.MeasurementKey', replacement: 'cirq.Measure """Replaces the control keys.""" @abc.abstractmethod - def resolve( - self, - classical_data: 'cirq.ClassicalDataStoreReader', - ) -> bool: + def resolve(self, classical_data: 'cirq.ClassicalDataStoreReader') -> bool: """Resolves the condition based on the measurements.""" @property @@ -63,9 +60,7 @@ def _with_key_path_prefix_(self, path: Tuple[str, ...]) -> 'cirq.Condition': return condition def _with_rescoped_keys_( - self, - path: Tuple[str, ...], - bindable_keys: FrozenSet['cirq.MeasurementKey'], + self, path: Tuple[str, ...], bindable_keys: FrozenSet['cirq.MeasurementKey'] ) -> 'cirq.Condition': condition = self for key in self.keys: @@ -104,10 +99,7 @@ def __repr__(self): return f'cirq.KeyCondition({self.key!r}, {self.index})' return f'cirq.KeyCondition({self.key!r})' - def resolve( - self, - classical_data: 'cirq.ClassicalDataStoreReader', - ) -> bool: + def resolve(self, classical_data: 'cirq.ClassicalDataStoreReader') -> bool: if self.key not in classical_data.keys(): raise ValueError(f'Measurement key {self.key} missing when testing classical control') return classical_data.get_int(self.key, self.index) != 0 @@ -153,10 +145,7 @@ def __str__(self): def __repr__(self): return f'cirq.SympyCondition({proper_repr(self.expr)})' - def resolve( - self, - classical_data: 'cirq.ClassicalDataStoreReader', - ) -> bool: + def resolve(self, classical_data: 'cirq.ClassicalDataStoreReader') -> bool: missing = [str(k) for k in self.keys if k not in classical_data.keys()] if missing: raise ValueError(f'Measurement keys {missing} missing when testing classical control') diff --git a/cirq-core/cirq/value/linear_dict_test.py b/cirq-core/cirq/value/linear_dict_test.py index 0d1ff5575e3..d2cafd6d4a2 100644 --- a/cirq-core/cirq/value/linear_dict_test.py +++ b/cirq-core/cirq/value/linear_dict_test.py @@ -42,10 +42,7 @@ def test_fromkeys(keys, coefficient, terms_expected): @pytest.mark.parametrize( 'terms, valid_vectors, invalid_vectors', - ( - ({'X': 2}, ('X'), ('A', 'B')), - ({'X': 2, 'Y': -2}, ('X', 'Y', 'Z'), ('A', 'B')), - ), + (({'X': 2}, ('X'), ('A', 'B')), ({'X': 2, 'Y': -2}, ('X', 'Y', 'Z'), ('A', 'B'))), ) def test_invalid_vectors_are_rejected(terms, valid_vectors, invalid_vectors): linear_dict = cirq.LinearDict(terms, validator=lambda v: v in valid_vectors) @@ -65,11 +62,7 @@ def test_invalid_vectors_are_rejected(terms, valid_vectors, invalid_vectors): @pytest.mark.parametrize( - 'terms, valid_vectors', - ( - ({'X': 2}, ('X')), - ({'X': 2, 'Y': -2}, ('X', 'Y', 'Z')), - ), + 'terms, valid_vectors', (({'X': 2}, ('X')), ({'X': 2, 'Y': -2}, ('X', 'Y', 'Z'))) ) def test_valid_vectors_are_accepted(terms, valid_vectors): linear_dict = cirq.LinearDict(terms, validator=lambda v: v in valid_vectors) @@ -105,14 +98,7 @@ def test_clean(terms, atol, terms_expected): assert expected == linear_dict -@pytest.mark.parametrize( - 'terms', - ( - {'X': 1j / 2}, - {'X': 1, 'Y': 2, 'Z': 3}, - {}, - ), -) +@pytest.mark.parametrize('terms', ({'X': 1j / 2}, {'X': 1, 'Y': 2, 'Z': 3}, {})) def test_copy(terms): original = cirq.LinearDict(terms) copy = original.copy() @@ -128,12 +114,7 @@ def test_copy(terms): @pytest.mark.parametrize( 'terms, expected_keys', - ( - ({}, ()), - ({'X': 0}, ()), - ({'X': 0.1}, ('X',)), - ({'X': -1, 'Y': 0, 'Z': 1}, ('X', 'Z')), - ), + (({}, ()), ({'X': 0}, ()), ({'X': 0.1}, ('X',)), ({'X': -1, 'Y': 0, 'Z': 1}, ('X', 'Z'))), ) def test_keys(terms, expected_keys): linear_dict = cirq.LinearDict(terms) @@ -142,12 +123,7 @@ def test_keys(terms, expected_keys): @pytest.mark.parametrize( 'terms, expected_values', - ( - ({}, ()), - ({'X': 0}, ()), - ({'X': 0.1}, (0.1,)), - ({'X': -1, 'Y': 0, 'Z': 1}, (-1, 1)), - ), + (({}, ()), ({'X': 0}, ()), ({'X': 0.1}, (0.1,)), ({'X': -1, 'Y': 0, 'Z': 1}, (-1, 1))), ) def test_values(terms, expected_values): linear_dict = cirq.LinearDict(terms) @@ -189,13 +165,7 @@ def test_update(terms_1, terms_2, terms_expected): @pytest.mark.parametrize( 'terms, vector, expected_coefficient', - ( - ({}, '', 0), - ({}, 'X', 0), - ({'X': 0}, 'X', 0), - ({'X': -1j}, 'X', -1j), - ({'X': 1j}, 'Y', 0), - ), + (({}, '', 0), ({}, 'X', 0), ({'X': 0}, 'X', 0), ({'X': -1j}, 'X', -1j), ({'X': 1j}, 'Y', 0)), ) def test_get(terms, vector, expected_coefficient): linear_dict = cirq.LinearDict(terms) @@ -343,11 +313,7 @@ def test_vector_subtraction(terms_1, terms_2, terms_expected): @pytest.mark.parametrize( 'terms, terms_expected', - ( - ({}, {}), - ({'key': 1}, {'key': -1}), - ({'1': 10, '2': -20}, {'1': -10, '2': 20}), - ), + (({}, {}), ({'key': 1}, {'key': -1}), ({'1': 10, '2': -20}, {'1': -10, '2': 20})), ) def test_vector_negation(terms, terms_expected): linear_dict = cirq.LinearDict(terms) @@ -412,13 +378,7 @@ def test_expressions(expression, expected): @pytest.mark.parametrize( - 'terms, bool_value', - ( - ({}, False), - ({'X': 0}, False), - ({'Z': 1e-12}, True), - ({'Y': 1}, True), - ), + 'terms, bool_value', (({}, False), ({'X': 0}, False), ({'Z': 1e-12}, True), ({'Y': 1}, True)) ) def test_bool(terms, bool_value): linear_dict = cirq.LinearDict(terms) @@ -427,12 +387,7 @@ def test_bool(terms, bool_value): @pytest.mark.parametrize( 'terms_1, terms_2', - ( - ({}, {}), - ({}, {'X': 0}), - ({'X': 0.0}, {'Y': 0.0}), - ({'a': 1}, {'a': 1, 'b': 0}), - ), + (({}, {}), ({}, {'X': 0}), ({'X': 0.0}, {'Y': 0.0}), ({'a': 1}, {'a': 1, 'b': 0})), ) def test_equal(terms_1, terms_2): linear_dict_1 = cirq.LinearDict(terms_1) diff --git a/cirq-core/cirq/value/measurement_key.py b/cirq-core/cirq/value/measurement_key.py index e888325db81..a3792fe2a59 100644 --- a/cirq-core/cirq/value/measurement_key.py +++ b/cirq-core/cirq/value/measurement_key.py @@ -88,18 +88,10 @@ def __le__(self, other): return self == other or self < other def _json_dict_(self): - return { - 'name': self.name, - 'path': self.path, - } + return {'name': self.name, 'path': self.path} @classmethod - def _from_json_dict_( - cls, - name, - path, - **kwargs, - ): + def _from_json_dict_(cls, name, path, **kwargs): return cls(name=name, path=tuple(path)) @classmethod @@ -126,9 +118,7 @@ def with_key_path_prefix(self, *path_component: str): return self.replace(path=path_component + self.path) def _with_rescoped_keys_( - self, - path: Tuple[str, ...], - bindable_keys: FrozenSet['MeasurementKey'], + self, path: Tuple[str, ...], bindable_keys: FrozenSet['MeasurementKey'] ): return self.replace(path=path + self.path) diff --git a/cirq-core/cirq/value/periodic_value_test.py b/cirq-core/cirq/value/periodic_value_test.py index 4af9187a962..5d6087cb046 100644 --- a/cirq-core/cirq/value/periodic_value_test.py +++ b/cirq-core/cirq/value/periodic_value_test.py @@ -28,10 +28,7 @@ def test_periodic_value_equality(): cirq.PeriodicValue(5, 2), cirq.PeriodicValue(-1, 2), ) - eq.add_equality_group( - cirq.PeriodicValue(1.5, 2.0), - cirq.PeriodicValue(1.5, 2.0), - ) + eq.add_equality_group(cirq.PeriodicValue(1.5, 2.0), cirq.PeriodicValue(1.5, 2.0)) eq.add_equality_group(cirq.PeriodicValue(0, 2)) eq.add_equality_group(cirq.PeriodicValue(1, 3)) eq.add_equality_group(cirq.PeriodicValue(2, 4)) diff --git a/cirq-core/cirq/value/product_state.py b/cirq-core/cirq/value/product_state.py index ba54265cddf..7050f68778b 100644 --- a/cirq-core/cirq/value/product_state.py +++ b/cirq-core/cirq/value/product_state.py @@ -113,9 +113,7 @@ def __hash__(self): return hash(tuple(self.states.items())) def _json_dict_(self): - return { - 'states': list(self.states.items()), - } + return {'states': list(self.states.items())} @classmethod def _from_json_dict_(cls, states, **kwargs): @@ -323,12 +321,5 @@ def stabilized_by(self) -> Tuple[int, 'cirq.Pauli']: """, ) -PAULI_STATES = [ - KET_PLUS, - KET_MINUS, - KET_IMAG, - KET_MINUS_IMAG, - KET_ZERO, - KET_ONE, -] +PAULI_STATES = [KET_PLUS, KET_MINUS, KET_IMAG, KET_MINUS_IMAG, KET_ZERO, KET_ONE] document(PAULI_STATES, """All one-qubit states stabalized by the pauli operators.""") diff --git a/cirq-core/cirq/value/product_state_test.py b/cirq-core/cirq/value/product_state_test.py index ebc77e3f0e2..b3b042d2e7f 100644 --- a/cirq-core/cirq/value/product_state_test.py +++ b/cirq-core/cirq/value/product_state_test.py @@ -7,14 +7,7 @@ def test_name(): names = [str(state) for state in cirq.PAULI_STATES] - assert names == [ - '+X', - '-X', - '+Y', - '-Y', - '+Z', - '-Z', - ] + assert names == ['+X', '-X', '+Y', '-Y', '+Z', '-Z'] def test_repr(): @@ -120,11 +113,7 @@ def test_product_iter(): q0, q1, q2 = cirq.LineQubit.range(3) ps = cirq.KET_PLUS(q0) * cirq.KET_PLUS(q1) * cirq.KET_ZERO(q2) - should_be = [ - (q0, cirq.KET_PLUS), - (q1, cirq.KET_PLUS), - (q2, cirq.KET_ZERO), - ] + should_be = [(q0, cirq.KET_PLUS), (q1, cirq.KET_PLUS), (q2, cirq.KET_ZERO)] assert list(ps) == should_be assert len(ps) == 3 @@ -180,13 +169,7 @@ def test_tp_projector(): np.testing.assert_allclose(rho, p01) ppp = (cirq.KET_PLUS(q0) * cirq.KET_PLUS(q1)).projector() - rho = cirq.final_density_matrix( - cirq.Circuit( - [ - cirq.H.on_each(q0, q1), - ] - ) - ) + rho = cirq.final_density_matrix(cirq.Circuit([cirq.H.on_each(q0, q1)])) np.testing.assert_allclose(rho, ppp, atol=1e-7) ppm = (cirq.KET_PLUS(q0) * cirq.KET_MINUS(q1)).projector() diff --git a/cirq-core/cirq/vis/__init__.py b/cirq-core/cirq/vis/__init__.py index 3b5f560682e..b0cc92ec754 100644 --- a/cirq-core/cirq/vis/__init__.py +++ b/cirq-core/cirq/vis/__init__.py @@ -20,10 +20,7 @@ from cirq.vis.histogram import integrated_histogram -from cirq.vis.state_histogram import ( - get_state_histogram, - plot_state_histogram, -) +from cirq.vis.state_histogram import get_state_histogram, plot_state_histogram from cirq.vis.density_matrix import plot_density_matrix diff --git a/cirq-core/cirq/vis/heatmap.py b/cirq-core/cirq/vis/heatmap.py index b703dfc1727..eeec9379fe3 100644 --- a/cirq-core/cirq/vis/heatmap.py +++ b/cirq-core/cirq/vis/heatmap.py @@ -150,11 +150,7 @@ def _validate_kwargs(self, kwargs) -> None: "colorbar_pad", "colorbar_options", ] - valid_collection_kwargs = [ - "collection_options", - "vmin", - "vmax", - ] + valid_collection_kwargs = ["collection_options", "vmin", "vmax"] valid_heatmap_kwargs = [ "title", "annotation_map", @@ -181,12 +177,7 @@ def _qubits_to_polygon(self, qubits: QubitTuple) -> Tuple[Polygon, Point]: qubit = qubits[0] x, y = float(qubit.row), float(qubit.col) return ( - [ - (y - 0.5, x - 0.5), - (y - 0.5, x + 0.5), - (y + 0.5, x + 0.5), - (y + 0.5, x - 0.5), - ], + [(y - 0.5, x - 0.5), (y - 0.5, x + 0.5), (y + 0.5, x + 0.5), (y + 0.5, x - 0.5)], Point(y, x), ) @@ -255,8 +246,7 @@ def _plot_on_axis(self, ax: plt.Axes) -> mpl_collections.Collection: # Step-1: Convert value_map to a list of polygons to plot. polygon_list = self._get_polygon_units() collection: mpl_collections.Collection = mpl_collections.PolyCollection( - [c.polygon for c in polygon_list], - **self._config.get('collection_options', {}), + [c.polygon for c in polygon_list], **self._config.get('collection_options', {}) ) collection.set_clim(self._config.get('vmin'), self._config.get('vmax')) collection.set_array(np.array([c.value for c in polygon_list])) @@ -330,10 +320,7 @@ def __init__(self, value_map: Mapping[QubitTuple, SupportsFloat], **kwargs): coupler_margin: float, default = 0.03 coupler_width: float, default = 0.6 """ - self._config: Dict[str, Any] = { - "coupler_margin": 0.03, - "coupler_width": 0.6, - } + self._config: Dict[str, Any] = {"coupler_margin": 0.03, "coupler_width": 0.6} super().__init__(value_map, **kwargs) def _extra_valid_kwargs(self) -> List[str]: diff --git a/cirq-core/cirq/vis/histogram.py b/cirq-core/cirq/vis/histogram.py index 4a4621415ee..2173de7dbea 100644 --- a/cirq-core/cirq/vis/histogram.py +++ b/cirq-core/cirq/vis/histogram.py @@ -95,13 +95,7 @@ def integrated_histogram( else: bin_values = np.linspace(0, 1, n) parameter_values = sorted(data) - plot_options = { - "where": 'post', - "color": 'b', - "linestyle": '-', - "lw": 1.0, - "ms": 0.0, - } + plot_options = {"where": 'post', "color": 'b', "linestyle": '-', "lw": 1.0, "ms": 0.0} plot_options.update(kwargs) if cdf_on_x: diff --git a/cirq-core/cirq/vis/state_histogram_test.py b/cirq-core/cirq/vis/state_histogram_test.py index 27c6cb55af8..703555057e7 100644 --- a/cirq-core/cirq/vis/state_histogram_test.py +++ b/cirq-core/cirq/vis/state_histogram_test.py @@ -43,8 +43,7 @@ def test_get_state_histogram(): def test_get_state_histogram_multi_1(): qubits = cirq.LineQubit.range(4) c = cirq.Circuit( - cirq.X.on_each(*qubits[1:]), - cirq.measure(*qubits), # One multi-qubit measurement + cirq.X.on_each(*qubits[1:]), cirq.measure(*qubits) # One multi-qubit measurement ) r = cirq.sample(c, repetitions=5) values_to_plot = state_histogram.get_state_histogram(r) @@ -69,8 +68,7 @@ def test_get_state_histogram_multi_2(): def test_plot_state_histogram_result(): qubits = cirq.LineQubit.range(4) c = cirq.Circuit( - cirq.X.on_each(*qubits[1:]), - cirq.measure(*qubits), # One multi-qubit measurement + cirq.X.on_each(*qubits[1:]), cirq.measure(*qubits) # One multi-qubit measurement ) r = cirq.sample(c, repetitions=5) expected_values = [0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0] @@ -86,8 +84,7 @@ def test_plot_state_histogram_result(): def test_plot_state_histogram_collection(): qubits = cirq.LineQubit.range(4) c = cirq.Circuit( - cirq.X.on_each(*qubits[1:]), - cirq.measure(*qubits), # One multi-qubit measurement + cirq.X.on_each(*qubits[1:]), cirq.measure(*qubits) # One multi-qubit measurement ) r = cirq.sample(c, repetitions=5) _, (ax1, ax2) = plt.subplots(1, 2) diff --git a/cirq-core/cirq/work/__init__.py b/cirq-core/cirq/work/__init__.py index 1cf21dfe1c3..16297299aef 100644 --- a/cirq-core/cirq/work/__init__.py +++ b/cirq-core/cirq/work/__init__.py @@ -14,21 +14,10 @@ """Workflow utilities for sampling and measurement collection.""" -from cirq.work.collector import ( - CircuitSampleJob, - Collector, -) -from cirq.work.pauli_sum_collector import ( - PauliSumCollector, -) -from cirq.work.observable_settings import ( - InitObsSetting, - _MeasurementSpec, - observables_to_settings, -) -from cirq.work.observable_grouping import ( - group_settings_greedy, -) +from cirq.work.collector import CircuitSampleJob, Collector +from cirq.work.pauli_sum_collector import PauliSumCollector +from cirq.work.observable_settings import InitObsSetting, _MeasurementSpec, observables_to_settings +from cirq.work.observable_grouping import group_settings_greedy from cirq.work.observable_measurement_data import ( ObservableMeasuredResult, BitstringAccumulator, @@ -39,12 +28,6 @@ RepetitionsStoppingCriteria, measure_grouped_settings, ) -from cirq.work.observable_readout_calibration import ( - calibrate_readout_error, -) -from cirq.work.sampler import ( - Sampler, -) -from cirq.work.zeros_sampler import ( - ZerosSampler, -) +from cirq.work.observable_readout_calibration import calibrate_readout_error +from cirq.work.sampler import Sampler +from cirq.work.zeros_sampler import ZerosSampler diff --git a/cirq-core/cirq/work/observable_grouping_test.py b/cirq-core/cirq/work/observable_grouping_test.py index 394687480e2..dee1fa578d7 100644 --- a/cirq-core/cirq/work/observable_grouping_test.py +++ b/cirq-core/cirq/work/observable_grouping_test.py @@ -18,17 +18,12 @@ def test_group_settings_greedy_one_group(): qubits = cirq.LineQubit.range(2) q0, q1 = qubits - terms = [ - cirq.X(q0), - cirq.Y(q1), - ] + terms = [cirq.X(q0), cirq.Y(q1)] settings = list(cirq.work.observables_to_settings(terms, qubits)) grouped_settings = cirq.work.group_settings_greedy(settings) assert len(grouped_settings) == 1 - group_max_obs_should_be = [ - cirq.X(q0) * cirq.Y(q1), - ] + group_max_obs_should_be = [cirq.X(q0) * cirq.Y(q1)] group_max_settings_should_be = list( cirq.work.observables_to_settings(group_max_obs_should_be, qubits) ) @@ -41,10 +36,7 @@ def test_group_settings_greedy_one_group(): def test_group_settings_greedy_two_groups(): qubits = cirq.LineQubit.range(2) q0, q1 = qubits - terms = [ - cirq.X(q0) * cirq.X(q1), - cirq.Y(q0) * cirq.Y(q1), - ] + terms = [cirq.X(q0) * cirq.X(q1), cirq.Y(q0) * cirq.Y(q1)] settings = list(cirq.work.observables_to_settings(terms, qubits)) grouped_settings = cirq.work.group_settings_greedy(settings) assert len(grouped_settings) == 2 diff --git a/cirq-core/cirq/work/observable_measurement.py b/cirq-core/cirq/work/observable_measurement.py index bce4aedaad4..6fcb442d7af 100644 --- a/cirq-core/cirq/work/observable_measurement.py +++ b/cirq-core/cirq/work/observable_measurement.py @@ -18,18 +18,7 @@ import os import tempfile import warnings -from typing import ( - Optional, - Union, - Iterable, - Dict, - List, - Tuple, - TYPE_CHECKING, - Set, - Sequence, - Any, -) +from typing import Optional, Union, Iterable, Dict, List, Tuple, TYPE_CHECKING, Set, Sequence, Any import numpy as np import pandas as pd @@ -42,11 +31,7 @@ ObservableMeasuredResult, flatten_grouped_results, ) -from cirq.work.observable_settings import ( - InitObsSetting, - observables_to_settings, - _MeasurementSpec, -) +from cirq.work.observable_settings import InitObsSetting, observables_to_settings, _MeasurementSpec if TYPE_CHECKING: import cirq @@ -64,9 +49,7 @@ def _with_parameterized_layers( - circuit: 'cirq.AbstractCircuit', - qubits: Sequence['cirq.Qid'], - needs_init_layer: bool, + circuit: 'cirq.AbstractCircuit', qubits: Sequence['cirq.Qid'], needs_init_layer: bool ) -> 'cirq.Circuit': """Return a copy of the input circuit with parameterized single-qubit rotations. @@ -348,22 +331,12 @@ def _subdivide_meas_specs( flippy_mspecs = [] for meas_spec in meas_specs: all_normal = np.zeros(n_qubits, dtype=bool) - flippy_mspecs.append( - _FlippyMeasSpec( - meas_spec=meas_spec, - flips=all_normal, - qubits=qubits, - ) - ) + flippy_mspecs.append(_FlippyMeasSpec(meas_spec=meas_spec, flips=all_normal, qubits=qubits)) if readout_symmetrization: all_flipped = np.ones(n_qubits, dtype=bool) flippy_mspecs.append( - _FlippyMeasSpec( - meas_spec=meas_spec, - flips=all_flipped, - qubits=qubits, - ) + _FlippyMeasSpec(meas_spec=meas_spec, flips=all_flipped, qubits=qubits) ) if readout_symmetrization: @@ -608,9 +581,7 @@ def measure_grouped_settings( return list(accumulators.values()) -_GROUPING_FUNCS: Dict[str, GROUPER_T] = { - 'greedy': group_settings_greedy, -} +_GROUPING_FUNCS: Dict[str, GROUPER_T] = {'greedy': group_settings_greedy} def _parse_grouper(grouper: Union[str, GROUPER_T] = group_settings_greedy) -> GROUPER_T: @@ -625,8 +596,7 @@ def _parse_grouper(grouper: Union[str, GROUPER_T] = group_settings_greedy) -> GR def _get_all_qubits( - circuit: 'cirq.AbstractCircuit', - observables: Iterable['cirq.PauliString'], + circuit: 'cirq.AbstractCircuit', observables: Iterable['cirq.PauliString'] ) -> List['cirq.Qid']: """Helper function for `measure_observables` to get all qubits from a circuit and a collection of observables.""" diff --git a/cirq-core/cirq/work/observable_measurement_data_test.py b/cirq-core/cirq/work/observable_measurement_data_test.py index 3054640bfc6..3c41d25893d 100644 --- a/cirq-core/cirq/work/observable_measurement_data_test.py +++ b/cirq-core/cirq/work/observable_measurement_data_test.py @@ -37,14 +37,7 @@ def test_get_real_coef(): def test_obs_vals_from_measurements(): - bitstrings = np.array( - [ - [0, 0], - [0, 1], - [1, 0], - [1, 1], - ] - ) + bitstrings = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') qubit_to_index = {a: 0, b: 1} @@ -55,14 +48,7 @@ def test_obs_vals_from_measurements(): def test_stats_from_measurements(): - bitstrings = np.array( - [ - [0, 0], - [0, 1], - [1, 0], - [1, 1], - ] - ) + bitstrings = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') qubit_to_index = {a: 0, b: 1} @@ -85,8 +71,7 @@ def test_observable_measured_result(): b = cirq.NamedQubit('b') omr = cw.ObservableMeasuredResult( setting=cw.InitObsSetting( - init_state=cirq.Z(a) * cirq.Z(b), - observable=cirq.Y(a) * cirq.Y(b), + init_state=cirq.Z(a) * cirq.Z(b), observable=cirq.Y(a) * cirq.Y(b) ), mean=0, variance=5**2, @@ -135,11 +120,7 @@ def example_bsa() -> 'cw.BitstringAccumulator': init_state=cirq.KET_ZERO(q0) * cirq.KET_ZERO(q1), observable=cirq.X(q0) * cirq.Y(q1) ) meas_spec = _MeasurementSpec( - max_setting=setting, - circuit_params={ - 'beta': 0.123, - 'gamma': 0.456, - }, + max_setting=setting, circuit_params={'beta': 0.123, 'gamma': 0.456} ) bsa = cw.BitstringAccumulator( meas_spec=meas_spec, @@ -160,15 +141,7 @@ def test_bitstring_accumulator(example_bsa): assert example_bsa.timestamps.shape == (0,) # test consume_results - bitstrings = np.array( - [ - [0, 0], - [0, 1], - [1, 0], - [1, 1], - ], - dtype=np.uint8, - ) + bitstrings = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=np.uint8) example_bsa.consume_results(bitstrings) assert example_bsa.bitstrings.shape == (4, 2) assert example_bsa.chunksizes.shape == (1,) @@ -192,25 +165,12 @@ def test_bitstring_accumulator(example_bsa): def test_bitstring_accumulator_strings(example_bsa): - bitstrings = np.array( - [ - [0, 0], - [0, 1], - [1, 0], - [1, 1], - ], - dtype=np.uint8, - ) + bitstrings = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=np.uint8) example_bsa.consume_results(bitstrings) q0, q1 = cirq.LineQubit.range(2) settings = cw.observables_to_settings( - [ - cirq.X(q0), - cirq.Y(q1), - cirq.X(q0) * cirq.Y(q1), - ], - qubits=[q0, q1], + [cirq.X(q0), cirq.Y(q1), cirq.X(q0) * cirq.Y(q1)], qubits=[q0, q1] ) strings_should_be = [ @@ -232,15 +192,7 @@ def test_bitstring_accumulator_strings(example_bsa): def test_bitstring_accumulator_equality(): et = cirq.testing.EqualsTester() - bitstrings = np.array( - [ - [0, 0], - [0, 1], - [1, 0], - [1, 1], - ], - dtype=np.uint8, - ) + bitstrings = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=np.uint8) chunksizes = np.asarray([4]) timestamps = np.asarray([datetime.datetime.now()]) a = cirq.NamedQubit('a') @@ -331,15 +283,7 @@ def test_bitstring_accumulator_equality(): def _get_ZZ_Z_Z_bsa_constructor_args(): - bitstrings = np.array( - [ - [0, 0], - [0, 1], - [1, 0], - [1, 1], - ], - dtype=np.uint8, - ) + bitstrings = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=np.uint8) chunksizes = np.asarray([4]) timestamps = np.asarray([datetime.datetime.now()]) a = cirq.NamedQubit('a') @@ -379,13 +323,7 @@ def test_bitstring_accumulator_stats(): # value is +-1, so (x-xbar)(y-bar) is +-1 (neglecting observable coefficients) # For off-diagonal elements, there are two +1 and two -1 terms for each entry # 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], - ] - ) + should_be = np.array([[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()) @@ -402,15 +340,7 @@ def test_bitstring_accumulator_stats(): def test_bitstring_accumulator_stats_2(): - bitstrings = np.array( - [ - [0, 0], - [0, 0], - [1, 1], - [1, 1], - ], - np.uint8, - ) + bitstrings = np.array([[0, 0], [0, 0], [1, 1], [1, 1]], np.uint8) chunksizes = np.asarray([4]) timestamps = np.asarray([datetime.datetime.now()]) a = cirq.NamedQubit('a') @@ -437,12 +367,7 @@ def test_bitstring_accumulator_stats_2(): # where xbar and ybar are 0, per above. Each individual observed # value is +-1, so (x-xbar)(y-bar) is +-1 (neglecting observable coefficients) # In this case, the measurements are perfectly correlated. - should_be = 4 * np.array( - [ - [5 * 5, 5 * 3], - [3 * 5, 3 * 3], - ] - ) + should_be = 4 * np.array([[5 * 5, 5 * 3], [3 * 5, 3 * 3]]) 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()) @@ -456,13 +381,7 @@ def test_bitstring_accumulator_stats_2(): def test_bitstring_accumulator_errors(): q0, q1 = cirq.LineQubit.range(2) settings = cw.observables_to_settings( - [ - cirq.X(q0), - cirq.Y(q0), - cirq.Z(q0), - cirq.Z(q0) * cirq.Z(q1), - ], - qubits=[q0, q1], + [cirq.X(q0), cirq.Y(q0), cirq.Z(q0), cirq.Z(q0) * cirq.Z(q1)], qubits=[q0, q1] ) grouped_settings = cw.group_settings_greedy(settings) max_setting = list(grouped_settings.keys())[0] @@ -505,13 +424,7 @@ def test_bitstring_accumulator_errors(): def test_flatten_grouped_results(): q0, q1 = cirq.LineQubit.range(2) settings = cw.observables_to_settings( - [ - cirq.X(q0), - cirq.Y(q0), - cirq.Z(q0), - cirq.Z(q0) * cirq.Z(q1), - ], - qubits=[q0, q1], + [cirq.X(q0), cirq.Y(q0), cirq.Z(q0), cirq.Z(q0) * cirq.Z(q1)], qubits=[q0, q1] ) grouped_settings = cw.group_settings_greedy(settings) bsas = [] @@ -521,16 +434,7 @@ def test_flatten_grouped_results(): simul_settings=simul_settings, qubit_to_index={q0: 0, q1: 1}, ) - bsa.consume_results( - np.array( - [ - [0, 0], - [0, 0], - [0, 0], - ], - dtype=np.uint8, - ) - ) + bsa.consume_results(np.array([[0, 0], [0, 0], [0, 0]], dtype=np.uint8)) bsas.append(bsa) results = cw.flatten_grouped_results(bsas) @@ -585,17 +489,7 @@ def test_readout_correction(): assert np.isclose(ro_bsa.mean(ro_meas_spec_setting), 0.8 * 0.82, atol=0.05) bitstrings = np.array( - [ - [0, 0], - [0, 0], - [0, 0], - [0, 0], - [0, 0], - [0, 0], - [0, 1], - [1, 1], - ], - dtype=np.uint8, + [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 1], [1, 1]], dtype=np.uint8 ) chunksizes = np.asarray([len(bitstrings)]) timestamps = np.asarray([datetime.datetime.now()]) diff --git a/cirq-core/cirq/work/observable_measurement_test.py b/cirq-core/cirq/work/observable_measurement_test.py index 02a801db5c3..7b96e72d749 100644 --- a/cirq-core/cirq/work/observable_measurement_test.py +++ b/cirq-core/cirq/work/observable_measurement_test.py @@ -39,13 +39,7 @@ def test_with_parameterized_layers(): qs = cirq.LineQubit.range(3) - circuit = cirq.Circuit( - [ - cirq.H.on_each(*qs), - cirq.CZ(qs[0], qs[1]), - cirq.CZ(qs[1], qs[2]), - ] - ) + circuit = cirq.Circuit([cirq.H.on_each(*qs), cirq.CZ(qs[0], qs[1]), cirq.CZ(qs[1], qs[2])]) circuit2 = _with_parameterized_layers(circuit, qubits=qs, needs_init_layer=False) assert circuit != circuit2 assert len(circuit2) == 3 + 3 # 3 original, then X, Y, measure layer @@ -88,16 +82,10 @@ def test_get_params_for_setting(): needs_init_layer = True with pytest.raises(ValueError): _get_params_for_setting( - padded_setting, - flips=[0, 0], - qubits=qubits, - needs_init_layer=needs_init_layer, + padded_setting, flips=[0, 0], qubits=qubits, needs_init_layer=needs_init_layer ) params = _get_params_for_setting( - padded_setting, - flips=[0, 0, 1], - qubits=qubits, - needs_init_layer=needs_init_layer, + padded_setting, flips=[0, 0, 1], qubits=qubits, needs_init_layer=needs_init_layer ) assert all( x in params @@ -118,11 +106,7 @@ def test_get_params_for_setting(): ) circuit = cirq.Circuit(cirq.I.on_each(*qubits)) - circuit = _with_parameterized_layers( - circuit, - qubits=qubits, - needs_init_layer=needs_init_layer, - ) + circuit = _with_parameterized_layers(circuit, qubits=qubits, needs_init_layer=needs_init_layer) circuit = circuit[:-1] # remove measurement so we can compute psi = cirq.Simulator().simulate(circuit, param_resolver=params) ma = cirq.Z(a).expectation_from_state_vector(psi.final_state_vector, qubit_map=psi.qubit_map) @@ -146,10 +130,7 @@ def test_params_and_settings(): ] for init, obs, coef in tests: - setting = cw.InitObsSetting( - init_state=init(q), - observable=obs(q), - ) + setting = cw.InitObsSetting(init_state=init(q), observable=obs(q)) circuit = cirq.Circuit(cirq.I.on_each(*qubits)) circuit = _with_parameterized_layers(circuit, qubits=qubits, needs_init_layer=True) params = _get_params_for_setting( @@ -169,11 +150,7 @@ def test_subdivide_meas_specs(): init_state=cirq.KET_ZERO(q0) * cirq.KET_ZERO(q1), observable=cirq.X(q0) * cirq.Y(q1) ) meas_spec = cw._MeasurementSpec( - max_setting=setting, - circuit_params={ - 'beta': 0.123, - 'gamma': 0.456, - }, + max_setting=setting, circuit_params={'beta': 0.123, 'gamma': 0.456} ) flippy_mspecs, repetitions = _subdivide_meas_specs( @@ -283,11 +260,7 @@ def _set_up_meas_specs_for_testing(): init_state=cirq.KET_ZERO(q0) * cirq.KET_ZERO(q1), observable=cirq.X(q0) * cirq.Y(q1) ) meas_spec = _MeasurementSpec( - max_setting=setting, - circuit_params={ - 'beta': 0.123, - 'gamma': 0.456, - }, + max_setting=setting, circuit_params={'beta': 0.123, 'gamma': 0.456} ) bsa = cw.BitstringAccumulator( meas_spec, [], {q: i for i, q in enumerate(cirq.LineQubit.range(3))} @@ -301,9 +274,7 @@ def test_meas_specs_still_todo(): # 1. before taking any data still_todo, reps = _check_meas_specs_still_todo( - meas_specs=[meas_spec], - accumulators={meas_spec: bsa}, - stopping_criteria=stop, + meas_specs=[meas_spec], accumulators={meas_spec: bsa}, stopping_criteria=stop ) assert still_todo == [meas_spec] assert reps == 1_000 @@ -311,9 +282,7 @@ def test_meas_specs_still_todo(): # 2. After taking a mocked-out 997 shots. bsa.consume_results(np.zeros((997, 3), dtype=np.uint8)) still_todo, reps = _check_meas_specs_still_todo( - meas_specs=[meas_spec], - accumulators={meas_spec: bsa}, - stopping_criteria=stop, + meas_specs=[meas_spec], accumulators={meas_spec: bsa}, stopping_criteria=stop ) assert still_todo == [meas_spec] assert reps == 3 @@ -321,9 +290,7 @@ def test_meas_specs_still_todo(): # 3. After taking the final 3 shots bsa.consume_results(np.zeros((reps, 3), dtype=np.uint8)) still_todo, reps = _check_meas_specs_still_todo( - meas_specs=[meas_spec], - accumulators={meas_spec: bsa}, - stopping_criteria=stop, + meas_specs=[meas_spec], accumulators={meas_spec: bsa}, stopping_criteria=stop ) assert still_todo == [] assert reps == 0 @@ -339,9 +306,7 @@ def more_repetitions(self, accumulator: BitstringAccumulator) -> int: bad_stop = BadStopping() with pytest.raises(ValueError, match='positive'): _, _ = _check_meas_specs_still_todo( - meas_specs=[meas_spec], - accumulators={meas_spec: bsa}, - stopping_criteria=bad_stop, + meas_specs=[meas_spec], accumulators={meas_spec: bsa}, stopping_criteria=bad_stop ) @@ -352,9 +317,7 @@ def test_meas_spec_still_todo_too_many_params(monkeypatch): stop = cw.RepetitionsStoppingCriteria(10_000) with pytest.raises(ValueError, match='too many parameter settings'): _, _ = _check_meas_specs_still_todo( - meas_specs=lots_of_meas_spec, - accumulators={meas_spec: bsa}, - stopping_criteria=stop, + meas_specs=lots_of_meas_spec, accumulators={meas_spec: bsa}, stopping_criteria=stop ) @@ -365,9 +328,7 @@ def test_meas_spec_still_todo_lots_of_params(monkeypatch): stop = cw.RepetitionsStoppingCriteria(10_000) with pytest.warns(UserWarning, match='will be throttled from 10000 to 7500'): _, _ = _check_meas_specs_still_todo( - meas_specs=lots_of_meas_spec, - accumulators={meas_spec: bsa}, - stopping_criteria=stop, + meas_specs=lots_of_meas_spec, accumulators={meas_spec: bsa}, stopping_criteria=stop ) @@ -442,10 +403,7 @@ def test_measure_grouped_settings(with_circuit_sweep, checkpoint, tmpdir): checkpoint_fn = None for init, obs, coef in tests: - setting = cw.InitObsSetting( - init_state=init(q), - observable=obs(q), - ) + setting = cw.InitObsSetting(init_state=init(q), observable=obs(q)) grouped_settings = {setting: [setting]} circuit = cirq.Circuit(cirq.I.on_each(*qubits)) results = cw.measure_grouped_settings( @@ -467,10 +425,7 @@ def test_measure_grouped_settings(with_circuit_sweep, checkpoint, tmpdir): def _get_some_grouped_settings(): qubits = cirq.LineQubit.range(2) q0, q1 = qubits - terms = [ - cirq.X(q0), - cirq.Y(q1), - ] + terms = [cirq.X(q0), cirq.Y(q1)] settings = list(cirq.work.observables_to_settings(terms, qubits)) grouped_settings = cirq.work.group_settings_greedy(settings) return grouped_settings, qubits @@ -497,10 +452,7 @@ def test_measure_grouped_settings_read_checkpoint(tmpdir): qubits = cirq.LineQubit.range(1) (q,) = qubits - setting = cw.InitObsSetting( - init_state=cirq.KET_ZERO(q), - observable=cirq.Z(q), - ) + setting = cw.InitObsSetting(init_state=cirq.KET_ZERO(q), observable=cirq.Z(q)) grouped_settings = {setting: [setting]} circuit = cirq.Circuit(cirq.I.on_each(*qubits)) with pytest.raises(ValueError, match=r'same filename.*'): @@ -567,10 +519,7 @@ def _each_in_its_own_group_grouper( ) def test_measure_observable_grouper(grouper): circuit = cirq.Circuit(cirq.X(Q) ** 0.2) - observables = [ - cirq.Z(Q), - cirq.Z(cirq.NamedQubit('q2')), - ] + observables = [cirq.Z(Q), cirq.Z(cirq.NamedQubit('q2'))] results = measure_observables( circuit, observables, @@ -585,10 +534,7 @@ def test_measure_observable_grouper(grouper): def test_measure_observable_bad_grouper(): circuit = cirq.Circuit(cirq.X(Q) ** 0.2) - observables = [ - cirq.Z(Q), - cirq.Z(cirq.NamedQubit('q2')), - ] + observables = [cirq.Z(Q), cirq.Z(cirq.NamedQubit('q2'))] with pytest.raises(ValueError, match=r'Unknown grouping function'): _ = measure_observables( circuit, diff --git a/cirq-core/cirq/work/observable_readout_calibration.py b/cirq-core/cirq/work/observable_readout_calibration.py index 96d5832bcb8..0ecd7051a3b 100644 --- a/cirq-core/cirq/work/observable_readout_calibration.py +++ b/cirq-core/cirq/work/observable_readout_calibration.py @@ -4,10 +4,7 @@ from cirq import circuits, study, ops from cirq.work.observable_measurement import measure_grouped_settings, StoppingCriteria -from cirq.work.observable_settings import ( - InitObsSetting, - zeros_state, -) +from cirq.work.observable_settings import InitObsSetting, zeros_state if TYPE_CHECKING: import cirq diff --git a/cirq-core/cirq/work/observable_readout_calibration_test.py b/cirq-core/cirq/work/observable_readout_calibration_test.py index 877e488742a..4e1a00e8aa7 100644 --- a/cirq-core/cirq/work/observable_readout_calibration_test.py +++ b/cirq-core/cirq/work/observable_readout_calibration_test.py @@ -32,9 +32,7 @@ def noisy_moment(self, moment: 'cirq.Moment', system_qubits: Sequence['cirq.Qid' def test_calibrate_readout_error(): sampler = cirq.DensityMatrixSimulator( noise=DepolarizingWithDampedReadoutNoiseModel( - depol_prob=1e-3, - bitflip_prob=0.03, - decay_prob=0.03, + depol_prob=1e-3, bitflip_prob=0.03, decay_prob=0.03 ), seed=10, ) diff --git a/cirq-core/cirq/work/observable_settings_test.py b/cirq-core/cirq/work/observable_settings_test.py index 5602e871a33..bb6a4900129 100644 --- a/cirq-core/cirq/work/observable_settings_test.py +++ b/cirq-core/cirq/work/observable_settings_test.py @@ -42,10 +42,7 @@ def test_max_weight_observable(): def test_max_weight_state(): q0, q1 = cirq.LineQubit.range(2) - states = [ - cirq.KET_PLUS(q0), - cirq.KET_PLUS(q1), - ] + states = [cirq.KET_PLUS(q0), cirq.KET_PLUS(q1)] assert _max_weight_state(states) == cirq.KET_PLUS(q0) * cirq.KET_PLUS(q1) states = [cirq.KET_PLUS(q0), cirq.KET_PLUS(q1), cirq.KET_MINUS(q1)] @@ -54,10 +51,7 @@ def test_max_weight_state(): def test_observable_to_setting(): q0, q1, q2 = cirq.LineQubit.range(3) - observables = [ - cirq.X(q0) * cirq.Y(q1), - cirq.Z(q2) * 1, - ] + observables = [cirq.X(q0) * cirq.Y(q1), cirq.Z(q2) * 1] zero_state = cirq.KET_ZERO(q0) * cirq.KET_ZERO(q1) * cirq.KET_ZERO(q2) settings_should_be = [ @@ -68,18 +62,9 @@ def test_observable_to_setting(): def test_param_hash(): - params1 = [ - ('beta', 1.23), - ('gamma', 4.56), - ] - params2 = [ - ('beta', 1.23), - ('gamma', 4.56), - ] - params3 = [ - ('beta', 1.24), - ('gamma', 4.57), - ] + params1 = [('beta', 1.23), ('gamma', 4.56)] + params2 = [('beta', 1.23), ('gamma', 4.56)] + params3 = [('beta', 1.24), ('gamma', 4.57)] assert _hashable_param(params1) == _hashable_param(params1) assert hash(_hashable_param(params1)) == hash(_hashable_param(params1)) assert _hashable_param(params1) == _hashable_param(params2) @@ -94,18 +79,10 @@ def test_measurement_spec(): init_state=cirq.KET_ZERO(q0) * cirq.KET_ZERO(q1), observable=cirq.X(q0) * cirq.Y(q1) ) meas_spec = _MeasurementSpec( - max_setting=setting, - circuit_params={ - 'beta': 0.123, - 'gamma': 0.456, - }, + max_setting=setting, circuit_params={'beta': 0.123, 'gamma': 0.456} ) meas_spec2 = _MeasurementSpec( - max_setting=setting, - circuit_params={ - 'beta': 0.123, - 'gamma': 0.456, - }, + max_setting=setting, circuit_params={'beta': 0.123, 'gamma': 0.456} ) assert hash(meas_spec) == hash(meas_spec2) cirq.testing.assert_equivalent_repr(meas_spec) diff --git a/cirq-core/cirq/work/sampler.py b/cirq-core/cirq/work/sampler.py index 103f62cb0d2..ac03d43a76a 100644 --- a/cirq-core/cirq/work/sampler.py +++ b/cirq-core/cirq/work/sampler.py @@ -161,10 +161,7 @@ def sample( @abc.abstractmethod def run_sweep( - self, - program: 'cirq.AbstractCircuit', - params: 'cirq.Sweepable', - repetitions: int = 1, + self, program: 'cirq.AbstractCircuit', params: 'cirq.Sweepable', repetitions: int = 1 ) -> Sequence['cirq.Result']: """Samples from the given Circuit. @@ -181,10 +178,7 @@ def run_sweep( """ async def run_sweep_async( - self, - program: 'cirq.AbstractCircuit', - params: 'cirq.Sweepable', - repetitions: int = 1, + self, program: 'cirq.AbstractCircuit', params: 'cirq.Sweepable', repetitions: int = 1 ) -> Sequence['cirq.Result']: """Asynchronously samples from the given Circuit. diff --git a/cirq-core/cirq/work/sampler_test.py b/cirq-core/cirq/work/sampler_test.py index a26be57030c..070af023fd3 100644 --- a/cirq-core/cirq/work/sampler_test.py +++ b/cirq-core/cirq/work/sampler_test.py @@ -68,12 +68,7 @@ def test_sampler_sample_multiple_params(): results = sampler.sample( circuit, repetitions=3, - params=[ - {'s': 0, 't': 0}, - {'s': 0, 't': 1}, - {'s': 1, 't': 0}, - {'s': 1, 't': 1}, - ], + params=[{'s': 0, 't': 0}, {'s': 0, 't': 1}, {'s': 1, 't': 0}, {'s': 1, 't': 1}], ) pd.testing.assert_frame_equal( results, @@ -130,16 +125,7 @@ def test_sampler_sample_no_params(): circuit = cirq.Circuit(cirq.X(a), cirq.measure(a, b, key='out')) results = sampler.sample(circuit, repetitions=3) pd.testing.assert_frame_equal( - results, - pd.DataFrame( - columns=['out'], - index=[0, 1, 2], - data=[ - [2], - [2], - [2], - ], - ), + results, pd.DataFrame(columns=['out'], index=[0, 1, 2], data=[[2], [2], [2]]) ) @@ -148,13 +134,7 @@ def test_sampler_sample_inconsistent_keys(): sampler = cirq.Simulator() circuit = cirq.Circuit(cirq.measure(q, key='out')) with pytest.raises(ValueError, match='Inconsistent sweep parameters'): - _ = sampler.sample( - circuit, - params=[ - {'a': 1}, - {'a': 1, 'b': 2}, - ], - ) + _ = sampler.sample(circuit, params=[{'a': 1}, {'a': 1, 'b': 2}]) @duet.sync @@ -243,10 +223,7 @@ class DeterministicImbalancedStateSampler(cirq.Sampler): """ def run_sweep( - self, - program: 'cirq.AbstractCircuit', - params: 'cirq.Sweepable', - repetitions: int = 1, + self, program: 'cirq.AbstractCircuit', params: 'cirq.Sweepable', repetitions: int = 1 ) -> Sequence['cirq.Result']: results = np.zeros((repetitions, 1), dtype=bool) for idx in range(repetitions // 4): @@ -297,21 +274,12 @@ def test_sampler_sample_expectation_values_composite(): t = [sympy.Symbol(f't{x}') for x in range(3)] sampler = cirq.Simulator(seed=1) - circuit = cirq.Circuit( - cirq.X(q[0]) ** t[0], - cirq.X(q[1]) ** t[1], - cirq.X(q[2]) ** t[2], - ) + circuit = cirq.Circuit(cirq.X(q[0]) ** t[0], cirq.X(q[1]) ** t[1], cirq.X(q[2]) ** t[2]) obs = [cirq.Z(q[x]) for x in range(3)] # t0 is in the inner loop to make bit-ordering easier below. params = ([{'t0': t0, 't1': t1, 't2': t2} for t2 in [0, 1] for t1 in [0, 1] for t0 in [0, 1]],) - results = sampler.sample_expectation_values( - circuit, - obs, - num_samples=5, - params=params, - ) + results = sampler.sample_expectation_values(circuit, obs, num_samples=5, params=params) assert len(results) == 8 assert np.allclose( diff --git a/cirq-core/cirq/work/zeros_sampler.py b/cirq-core/cirq/work/zeros_sampler.py index 1f8dc7555c9..dc2ba074233 100644 --- a/cirq-core/cirq/work/zeros_sampler.py +++ b/cirq-core/cirq/work/zeros_sampler.py @@ -36,10 +36,7 @@ def __init__(self, device: devices.Device = None): self.device = device def run_sweep( - self, - program: 'cirq.AbstractCircuit', - params: study.Sweepable, - repetitions: int = 1, + self, program: 'cirq.AbstractCircuit', params: study.Sweepable, repetitions: int = 1 ) -> List[study.Result]: """Samples circuit as if every measurement resulted in zero. diff --git a/cirq-core/cirq/work/zeros_sampler_test.py b/cirq-core/cirq/work/zeros_sampler_test.py index 0d9f0e80993..0e74f200e02 100644 --- a/cirq-core/cirq/work/zeros_sampler_test.py +++ b/cirq-core/cirq/work/zeros_sampler_test.py @@ -66,10 +66,7 @@ def test_repeated_keys(): assert result.records['a'].shape == (10, 2, 1) assert result.records['b'].shape == (10, 3, 2) - c2 = cirq.Circuit( - cirq.measure(q0, key='a'), - cirq.measure(q1, q2, key='a'), - ) + c2 = cirq.Circuit(cirq.measure(q0, key='a'), cirq.measure(q1, q2, key='a')) with pytest.raises(ValueError, match="Different qid shapes for repeated measurement"): cirq.ZerosSampler().run(c2, repetitions=10) diff --git a/cirq-core/setup.py b/cirq-core/setup.py index 66bcaba9700..9cf0c26f1da 100644 --- a/cirq-core/setup.py +++ b/cirq-core/setup.py @@ -65,15 +65,10 @@ author_email='cirq-dev@googlegroups.com', python_requires=('>=3.6.0'), install_requires=requirements, - extras_require={ - 'contrib': contrib_requirements, - }, + extras_require={'contrib': contrib_requirements}, license='Apache 2', description=description, long_description=long_description, packages=cirq_packages, - package_data={ - 'cirq': ['py.typed'], - 'cirq.protocols.json_test_data': ['*'], - }, + package_data={'cirq': ['py.typed'], 'cirq.protocols.json_test_data': ['*']}, ) diff --git a/cirq-google/cirq_google/api/v1/__init__.py b/cirq-google/cirq_google/api/v1/__init__.py index 4bd1fde55d6..454cc3bcd7f 100644 --- a/cirq-google/cirq_google/api/v1/__init__.py +++ b/cirq-google/cirq_google/api/v1/__init__.py @@ -13,11 +13,7 @@ # limitations under the License. """Data format v1 for google api.""" -from cirq_google.api.v1 import ( - operations_pb2, - params_pb2, - program_pb2, -) +from cirq_google.api.v1 import operations_pb2, params_pb2, program_pb2 from cirq_google.api.v1.params import sweep_from_proto, sweep_to_proto diff --git a/cirq-google/cirq_google/api/v1/params.py b/cirq-google/cirq_google/api/v1/params.py index b65fa2d4628..83a35e0b17f 100644 --- a/cirq-google/cirq_google/api/v1/params.py +++ b/cirq-google/cirq_google/api/v1/params.py @@ -81,9 +81,7 @@ def _sweep_from_param_sweep_zip_proto(param_sweep_zip: params_pb2.ZipSweep) -> c return cirq.UnitSweep -def _sweep_from_single_param_sweep_proto( - single_param_sweep: params_pb2.SingleSweep, -) -> cirq.Sweep: +def _sweep_from_single_param_sweep_proto(single_param_sweep: params_pb2.SingleSweep) -> cirq.Sweep: key = single_param_sweep.parameter_key if single_param_sweep.HasField('points'): points = single_param_sweep.points diff --git a/cirq-google/cirq_google/api/v1/programs.py b/cirq-google/cirq_google/api/v1/programs.py index cb975b0d159..256d5b86789 100644 --- a/cirq-google/cirq_google/api/v1/programs.py +++ b/cirq-google/cirq_google/api/v1/programs.py @@ -302,8 +302,7 @@ def xmon_op_from_proto(proto: operations_pb2.Operation) -> cirq.Operation: if proto.HasField('exp_w'): exp_w = proto.exp_w return cirq.PhasedXPowGate( - exponent=param(exp_w.half_turns), - phase_exponent=param(exp_w.axis_half_turns), + exponent=param(exp_w.half_turns), phase_exponent=param(exp_w.axis_half_turns) ).on(qubit(exp_w.target)) if proto.HasField('exp_z'): exp_z = proto.exp_z diff --git a/cirq-google/cirq_google/api/v1/programs_test.py b/cirq-google/cirq_google/api/v1/programs_test.py index 7dab8d890c7..e02834387ee 100644 --- a/cirq-google/cirq_google/api/v1/programs_test.py +++ b/cirq-google/cirq_google/api/v1/programs_test.py @@ -73,32 +73,9 @@ def test_pack_results(): measurements = [ ( 'a', - np.array( - [ - [0, 0, 0], - [0, 0, 1], - [0, 1, 0], - [0, 1, 1], - [1, 0, 0], - [1, 0, 1], - [1, 1, 0], - ] - ), - ), - ( - 'b', - np.array( - [ - [0, 0], - [0, 1], - [1, 0], - [1, 1], - [0, 0], - [0, 1], - [1, 0], - ] - ), + np.array([[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0]]), ), + ('b', np.array([[0, 0], [0, 1], [1, 0], [1, 1], [0, 0], [0, 1], [1, 0]])), ] data = programs.pack_results(measurements) expected = make_bytes( @@ -150,32 +127,14 @@ def test_unpack_results(): assert results['a'].shape == (7, 3) assert results['a'].dtype == bool np.testing.assert_array_equal( - results['a'], - [ - [0, 0, 0], - [0, 0, 1], - [0, 1, 0], - [0, 1, 1], - [1, 0, 0], - [1, 0, 1], - [1, 1, 0], - ], + results['a'], [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0]] ) assert 'b' in results assert results['b'].shape == (7, 2) assert results['b'].dtype == bool np.testing.assert_array_equal( - results['b'], - [ - [0, 0], - [0, 1], - [1, 0], - [1, 1], - [0, 0], - [0, 1], - [1, 0], - ], + results['b'], [[0, 0], [0, 1], [1, 0], [1, 1], [0, 0], [0, 1], [1, 0]] ) diff --git a/cirq-google/cirq_google/api/v2/results.py b/cirq-google/cirq_google/api/v2/results.py index f6fc16e5878..8c99fec6f2e 100644 --- a/cirq-google/cirq_google/api/v2/results.py +++ b/cirq-google/cirq_google/api/v2/results.py @@ -11,17 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -from typing import ( - cast, - Dict, - Hashable, - Iterable, - Iterator, - List, - Optional, - Sequence, - Set, -) +from typing import cast, Dict, Hashable, Iterable, Iterator, List, Optional, Sequence, Set from collections import OrderedDict import dataclasses import numpy as np @@ -161,8 +151,7 @@ def results_to_proto( def results_from_proto( - msg: result_pb2.Result, - measurements: List[MeasureInfo] = None, + msg: result_pb2.Result, measurements: List[MeasureInfo] = None ) -> Sequence[Sequence[cirq.Result]]: """Converts a v2 result proto into List of list of trial results. @@ -184,8 +173,7 @@ def results_from_proto( def _trial_sweep_from_proto( - msg: result_pb2.SweepResult, - measure_map: Dict[str, MeasureInfo] = None, + msg: result_pb2.SweepResult, measure_map: Dict[str, MeasureInfo] = None ) -> Sequence[cirq.Result]: """Converts a SweepResult proto into List of list of trial results. @@ -220,8 +208,7 @@ def _trial_sweep_from_proto( m_data[mr.key] = np.array(ordered_results).transpose() trial_sweep.append( cirq.ResultDict( - params=cirq.ParamResolver(dict(pr.params.assignments)), - measurements=m_data, + params=cirq.ParamResolver(dict(pr.params.assignments)), measurements=m_data ) ) return trial_sweep diff --git a/cirq-google/cirq_google/api/v2/results_test.py b/cirq-google/cirq_google/api/v2/results_test.py index b6146106886..2cdd95272e1 100644 --- a/cirq-google/cirq_google/api/v2/results_test.py +++ b/cirq-google/cirq_google/api/v2/results_test.py @@ -142,29 +142,21 @@ def test_results_to_proto(): [ cirq.ResultDict( params=cirq.ParamResolver({'i': 0}), - measurements={ - 'foo': np.array([[0], [1], [0], [1]], dtype=bool), - }, + measurements={'foo': np.array([[0], [1], [0], [1]], dtype=bool)}, ), cirq.ResultDict( params=cirq.ParamResolver({'i': 1}), - measurements={ - 'foo': np.array([[0], [1], [1], [0]], dtype=bool), - }, + measurements={'foo': np.array([[0], [1], [1], [0]], dtype=bool)}, ), ], [ cirq.ResultDict( params=cirq.ParamResolver({'i': 0}), - measurements={ - 'foo': np.array([[0], [1], [0], [1]], dtype=bool), - }, + measurements={'foo': np.array([[0], [1], [0], [1]], dtype=bool)}, ), cirq.ResultDict( params=cirq.ParamResolver({'i': 1}), - measurements={ - 'foo': np.array([[0], [1], [1], [0]], dtype=bool), - }, + measurements={'foo': np.array([[0], [1], [1], [0]], dtype=bool)}, ), ], ] @@ -189,15 +181,11 @@ def test_results_to_proto_sweep_repetitions(): [ cirq.ResultDict( params=cirq.ParamResolver({'i': 0}), - measurements={ - 'foo': np.array([[0]], dtype=bool), - }, + measurements={'foo': np.array([[0]], dtype=bool)}, ), cirq.ResultDict( params=cirq.ParamResolver({'i': 1}), - measurements={ - 'foo': np.array([[0], [1]], dtype=bool), - }, + measurements={'foo': np.array([[0], [1]], dtype=bool)}, ), ] ] @@ -218,11 +206,7 @@ def test_results_from_proto_qubit_ordering(): pr.params.assignments.update({'i': 1}) mr = pr.measurement_results.add() mr.key = 'foo' - for qubit, results in [ - (q(0, 1), 0b1100_1100), - (q(1, 1), 0b1010_1010), - (q(0, 0), 0b1111_0000), - ]: + for qubit, results in [(q(0, 1), 0b1100_1100), (q(1, 1), 0b1010_1010), (q(0, 0), 0b1111_0000)]: qmr = mr.qubit_measurement_results.add() qmr.qubit.id = v2.qubit_to_proto_id(qubit) qmr.results = bytes([results]) @@ -262,11 +246,7 @@ def test_results_from_proto_duplicate_qubit(): pr.params.assignments.update({'i': 0}) mr = pr.measurement_results.add() mr.key = 'foo' - for qubit, results in [ - (q(0, 0), 0b1100_1100), - (q(0, 1), 0b1010_1010), - (q(0, 1), 0b1111_0000), - ]: + for qubit, results in [(q(0, 0), 0b1100_1100), (q(0, 1), 0b1010_1010), (q(0, 1), 0b1111_0000)]: qmr = mr.qubit_measurement_results.add() qmr.qubit.id = v2.qubit_to_proto_id(qubit) qmr.results = bytes([results]) @@ -282,11 +262,7 @@ def test_results_from_proto_default_ordering(): pr.params.assignments.update({'i': 1}) mr = pr.measurement_results.add() mr.key = 'foo' - for qubit, results in [ - (q(0, 1), 0b1100_1100), - (q(1, 1), 0b1010_1010), - (q(0, 0), 0b1111_0000), - ]: + for qubit, results in [(q(0, 1), 0b1100_1100), (q(1, 1), 0b1010_1010), (q(0, 0), 0b1111_0000)]: qmr = mr.qubit_measurement_results.add() qmr.qubit.id = v2.qubit_to_proto_id(qubit) qmr.results = bytes([results]) diff --git a/cirq-google/cirq_google/api/v2/sweeps.py b/cirq-google/cirq_google/api/v2/sweeps.py index 9cbfdc4391b..bdee60b2d9c 100644 --- a/cirq-google/cirq_google/api/v2/sweeps.py +++ b/cirq-google/cirq_google/api/v2/sweeps.py @@ -20,9 +20,7 @@ def sweep_to_proto( - sweep: cirq.Sweep, - *, - out: Optional[run_context_pb2.Sweep] = None, + sweep: cirq.Sweep, *, out: Optional[run_context_pb2.Sweep] = None ) -> run_context_pb2.Sweep: """Converts a Sweep to v2 protobuf message. diff --git a/cirq-google/cirq_google/ops/sycamore_gate_test.py b/cirq-google/cirq_google/ops/sycamore_gate_test.py index 5fce1df30c9..d6185be3330 100644 --- a/cirq-google/cirq_google/ops/sycamore_gate_test.py +++ b/cirq-google/cirq_google/ops/sycamore_gate_test.py @@ -59,6 +59,7 @@ def test_syc_is_specific_fsim(): def test_syc_unitary(): cirq.testing.assert_allclose_up_to_global_phase( cirq.unitary(cg.SYC), + # fmt: off np.array( [ [1.0, 0.0, 0.0, 0.0], @@ -67,5 +68,6 @@ def test_syc_unitary(): [0.0, 0.0, 0.0, np.exp(-1j * np.pi / 6)], ] ), + # fmt: on atol=1e-6, ) diff --git a/cirq-google/cirq_google/serialization/common_serializers_test.py b/cirq-google/cirq_google/serialization/common_serializers_test.py index 93c92aa425d..49377cf7f0b 100644 --- a/cirq-google/cirq_google/serialization/common_serializers_test.py +++ b/cirq-google/cirq_google/serialization/common_serializers_test.py @@ -183,15 +183,7 @@ def test_half_pi_does_not_serialize_arbitrary_xy(): @pytest.mark.parametrize( ('x_exponent', 'z_exponent', 'axis_phase_exponent'), - [ - (0, 0, 0), - (1, 0, 0), - (0, 1, 0), - (0.5, 0, 0.5), - (0.5, 0.5, 0.5), - (0.1, 0.2, 0.3), - (0.25, 0.375, 0.125), - ], + [(0, 0, 0), (1, 0, 0), (0, 1, 0), (0.5, 0, 0.5), (0.5, 0.5, 0.5), (0.25, 0.375, 0.125)], ) def test_serialize_deserialize_arbitrary_xyz(x_exponent, z_exponent, axis_phase_exponent): gate = cirq.PhasedXZGate( diff --git a/cirq-ionq/cirq_ionq/__init__.py b/cirq-ionq/cirq_ionq/__init__.py index a4d41a638e4..28d7179dc18 100644 --- a/cirq-ionq/cirq_ionq/__init__.py +++ b/cirq-ionq/cirq_ionq/__init__.py @@ -12,18 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -from cirq_ionq._version import ( - __version__, -) +from cirq_ionq._version import __version__ -from cirq_ionq.calibration import ( - Calibration, -) +from cirq_ionq.calibration import Calibration -from cirq_ionq.ionq_devices import ( - IonQAPIDevice, - decompose_to_device, -) +from cirq_ionq.ionq_devices import IonQAPIDevice, decompose_to_device from cirq_ionq.ionq_exceptions import ( IonQException, @@ -31,24 +24,12 @@ IonQUnsuccessfulJobException, ) -from cirq_ionq.job import ( - Job, -) +from cirq_ionq.job import Job -from cirq_ionq.results import ( - QPUResult, - SimulatorResult, -) +from cirq_ionq.results import QPUResult, SimulatorResult -from cirq_ionq.sampler import ( - Sampler, -) +from cirq_ionq.sampler import Sampler -from cirq_ionq.serializer import ( - Serializer, - SerializedProgram, -) +from cirq_ionq.serializer import Serializer, SerializedProgram -from cirq_ionq.service import ( - Service, -) +from cirq_ionq.service import Service diff --git a/cirq-ionq/cirq_ionq/calibration_test.py b/cirq-ionq/cirq_ionq/calibration_test.py index f873bcd4ea2..fd650b3fd0c 100644 --- a/cirq-ionq/cirq_ionq/calibration_test.py +++ b/cirq-ionq/cirq_ionq/calibration_test.py @@ -20,20 +20,11 @@ def test_calibration_fields(): calibration_dict = { - 'connectivity': [ - [0, 1], - [0, 2], - [1, 2], - ], + 'connectivity': [[0, 1], [0, 2], [1, 2]], 'target': 'ionq.qpu', 'qubits': 3, 'fidelity': {'1q': {'mean': 0.999}, '2q': {'mean': 0.999}}, - 'timing': { - '1q': 1.1e-05, - '2q': 0.00021, - 'readout': 0.000175, - 'reset': 3.5e-05, - }, + 'timing': {'1q': 1.1e-05, '2q': 0.00021, 'readout': 0.000175, 'reset': 3.5e-05}, 'date': '2020-08-07T12:47:22.337Z', } cal = ionq.Calibration(calibration_dict=calibration_dict) diff --git a/cirq-ionq/cirq_ionq/ionq_client.py b/cirq-ionq/cirq_ionq/ionq_client.py index a4de746a33a..ebaf00e6e08 100644 --- a/cirq-ionq/cirq_ionq/ionq_client.py +++ b/cirq-ionq/cirq_ionq/ionq_client.py @@ -24,10 +24,7 @@ import cirq_ionq from cirq_ionq import ionq_exceptions -RETRIABLE_STATUS_CODES = { - requests.codes.internal_server_error, - requests.codes.service_unavailable, -} +RETRIABLE_STATUS_CODES = {requests.codes.internal_server_error, requests.codes.service_unavailable} def _is_retriable(code): @@ -43,9 +40,7 @@ class _IonQClient: """ SUPPORTED_TARGETS = {'qpu', 'simulator'} - SUPPORTED_VERSIONS = { - 'v0.1', - } + SUPPORTED_VERSIONS = {'v0.1'} def __init__( self, diff --git a/cirq-ionq/cirq_ionq/ionq_devices.py b/cirq-ionq/cirq_ionq/ionq_devices.py index 5f42cbe8f43..d48bdb2bba2 100644 --- a/cirq-ionq/cirq_ionq/ionq_devices.py +++ b/cirq-ionq/cirq_ionq/ionq_devices.py @@ -67,18 +67,14 @@ def __init__(self, qubits: Union[Sequence[cirq.LineQubit], int], atol=1e-8): self.qubits = frozenset(qubits) self.atol = atol self._metadata = cirq.DeviceMetadata( - self.qubits, - [(a, b) for a in self.qubits for b in self.qubits if a != b], + self.qubits, [(a, b) for a in self.qubits for b in self.qubits if a != b] ) @property def metadata(self) -> cirq.DeviceMetadata: return self._metadata - @_compat.deprecated( - fix='Use metadata.qubit_set if applicable.', - deadline='v0.15', - ) + @_compat.deprecated(fix='Use metadata.qubit_set if applicable.', deadline='v0.15') def qubit_set(self) -> AbstractSet['cirq.Qid']: return self.qubits @@ -96,8 +92,7 @@ def is_api_gate(self, operation: cirq.Operation) -> bool: return operation in _VALID_GATES @_compat.deprecated( - fix='Use cirq_ionq.decompose_to_device operation instead.', - deadline='v0.15', + fix='Use cirq_ionq.decompose_to_device operation instead.', deadline='v0.15' ) def decompose_operation(self, operation: cirq.Operation) -> cirq.OP_TREE: return decompose_to_device(operation) @@ -158,6 +153,5 @@ def _decompose_two_qubit(operation: cirq.Operation) -> cirq.OP_TREE: temp = cirq.merge_single_qubit_gates_to_phased_x_and_z(temp) # A final pass breaks up PhasedXPow into Rz, Rx. yield cirq.map_operations_and_unroll( - temp, - lambda op, _: cirq.decompose_once(op) if type(op.gate) == cirq.PhasedXPowGate else op, + temp, lambda op, _: cirq.decompose_once(op) if type(op.gate) == cirq.PhasedXPowGate else op ).all_operations() diff --git a/cirq-ionq/cirq_ionq/ionq_devices_test.py b/cirq-ionq/cirq_ionq/ionq_devices_test.py index 23b36252fe2..a829f7911ad 100644 --- a/cirq-ionq/cirq_ionq/ionq_devices_test.py +++ b/cirq-ionq/cirq_ionq/ionq_devices_test.py @@ -22,9 +22,9 @@ 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.rx(0.1), cirq.ry(0.1), cirq.rz(0.1), @@ -37,9 +37,9 @@ 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, cirq.SWAP, cirq.SwapPowGate(exponent=1, global_shift=-0.5), cirq.MeasurementGate(num_qubits=1, key='a'), @@ -56,13 +56,7 @@ def test_validate_operation_valid(gate): device.validate_operation(operation) -INVALID_GATES = ( - cirq.CNOT ** 0.5, - cirq.SWAP ** 0.5, - cirq.CCX, - cirq.CCZ, - cirq.CZ, -) +INVALID_GATES = (cirq.CNOT**0.5, cirq.SWAP**0.5, cirq.CCX, cirq.CCZ, cirq.CZ) @pytest.mark.parametrize('gate', INVALID_GATES) diff --git a/cirq-ionq/cirq_ionq/job_test.py b/cirq-ionq/cirq_ionq/job_test.py index 3c0fc60bf9f..b0177b6be7e 100644 --- a/cirq-ionq/cirq_ionq/job_test.py +++ b/cirq-ionq/cirq_ionq/job_test.py @@ -65,9 +65,7 @@ def test_job_results_qpu(): 'target': 'qpu', 'metadata': {'shots': 1000, 'measurement0': f'a{chr(31)}0,1'}, 'data': {'histogram': {'0': '0.6', '2': '0.4'}}, - 'warning': { - 'messages': ['foo', 'bar'], - }, + 'warning': {'messages': ['foo', 'bar']}, } job = ionq.Job(None, job_dict) with warnings.catch_warnings(record=True) as w: @@ -125,10 +123,7 @@ def test_job_results_qpu_target_endianness(): @mock.patch('time.sleep', return_value=None) def test_job_results_poll(mock_sleep): - ready_job = { - 'id': 'my_id', - 'status': 'ready', - } + ready_job = {'id': 'my_id', 'status': 'ready'} completed_job = { 'id': 'my_id', 'status': 'completed', @@ -147,10 +142,7 @@ def test_job_results_poll(mock_sleep): @mock.patch('time.sleep', return_value=None) def test_job_results_poll_timeout(mock_sleep): - ready_job = { - 'id': 'my_id', - 'status': 'ready', - } + ready_job = {'id': 'my_id', 'status': 'ready'} mock_client = mock.MagicMock() mock_client.get_job.return_value = ready_job job = ionq.Job(mock_client, ready_job) @@ -199,10 +191,7 @@ def test_job_results_simulator_endianness(): def test_job_cancel(): - ready_job = { - 'id': 'my_id', - 'status': 'ready', - } + ready_job = {'id': 'my_id', 'status': 'ready'} canceled_job = {'id': 'my_id', 'status': 'canceled'} mock_client = mock.MagicMock() mock_client.cancel_job.return_value = canceled_job @@ -213,10 +202,7 @@ def test_job_cancel(): def test_job_delete(): - ready_job = { - 'id': 'my_id', - 'status': 'ready', - } + ready_job = {'id': 'my_id', 'status': 'ready'} deleted_job = {'id': 'my_id', 'status': 'deleted'} mock_client = mock.MagicMock() mock_client.delete_job.return_value = deleted_job diff --git a/cirq-ionq/cirq_ionq/json_test_data/spec.py b/cirq-ionq/cirq_ionq/json_test_data/spec.py index ab0a1a1ea71..522bcc5ab37 100644 --- a/cirq-ionq/cirq_ionq/json_test_data/spec.py +++ b/cirq-ionq/cirq_ionq/json_test_data/spec.py @@ -34,11 +34,7 @@ "Job", "SimulatorResult", ], - should_not_be_serialized=[ - "Sampler", - "Service", - "Serializer", - ], + should_not_be_serialized=["Sampler", "Service", "Serializer"], resolver_cache=_class_resolver_dictionary(), deprecated={}, ) diff --git a/cirq-ionq/cirq_ionq/results.py b/cirq-ionq/cirq_ionq/results.py index c5024f1d6e0..6d5bbc09520 100644 --- a/cirq-ionq/cirq_ionq/results.py +++ b/cirq-ionq/cirq_ionq/results.py @@ -107,10 +107,7 @@ def measurement_dict(self) -> Dict[str, Sequence[int]]: """Returns a map from measurement keys to target qubit indices for this measurement.""" return self._measurement_dict - def to_cirq_result( - self, - params: Optional[cirq.ParamResolver] = None, - ) -> cirq.Result: + def to_cirq_result(self, params: Optional[cirq.ParamResolver] = None) -> cirq.Result: """Returns a `cirq.Result` for these results. `cirq.Result` contains a less dense representation of results than that returned by diff --git a/cirq-ionq/cirq_ionq/results_test.py b/cirq-ionq/cirq_ionq/results_test.py index 71a961a88cf..1c8f60bd60a 100644 --- a/cirq-ionq/cirq_ionq/results_test.py +++ b/cirq-ionq/cirq_ionq/results_test.py @@ -159,10 +159,7 @@ def test_ordered_results_invalid_key(): def test_simulator_result_fields(): result = ionq.SimulatorResult( - {0: 0.4, 1: 0.6}, - num_qubits=1, - measurement_dict={'a': [0]}, - repetitions=100, + {0: 0.4, 1: 0.6}, num_qubits=1, measurement_dict={'a': [0]}, repetitions=100 ) assert result.probabilities() == {0: 0.4, 1: 0.6} assert result.num_qubits() == 1 diff --git a/cirq-ionq/cirq_ionq/sampler.py b/cirq-ionq/cirq_ionq/sampler.py index 5522fceeeac..02c07d17a6e 100644 --- a/cirq-ionq/cirq_ionq/sampler.py +++ b/cirq-ionq/cirq_ionq/sampler.py @@ -66,10 +66,7 @@ def __init__( self._timeout_seconds = timeout_seconds def run_sweep( - self, - program: cirq.AbstractCircuit, - params: cirq.Sweepable, - repetitions: int = 1, + self, program: cirq.AbstractCircuit, params: cirq.Sweepable, repetitions: int = 1 ) -> Sequence[cirq.Result]: """Runs a sweep for the given Circuit. diff --git a/cirq-ionq/cirq_ionq/serializer.py b/cirq-ionq/cirq_ionq/serializer.py index 9d3bfc10925..4845dfb858c 100644 --- a/cirq-ionq/cirq_ionq/serializer.py +++ b/cirq-ionq/cirq_ionq/serializer.py @@ -13,16 +13,7 @@ # limitations under the License. """Support for serializing gates supported by IonQ's API.""" import dataclasses -from typing import ( - Callable, - cast, - Collection, - Dict, - Iterator, - Optional, - Sequence, - Type, -) +from typing import Callable, cast, Collection, Dict, Iterator, Optional, Sequence, Type import numpy as np @@ -149,32 +140,20 @@ def _serialize_x_pow_gate(self, gate: cirq.XPowGate, targets: Sequence[int]) -> def _serialize_y_pow_gate(self, gate: cirq.YPowGate, targets: Sequence[int]) -> dict: if self._near_mod_n(gate.exponent, 1, 2): - return { - 'gate': 'y', - 'targets': targets, - } + return {'gate': 'y', 'targets': targets} return {'gate': 'ry', 'targets': targets, 'rotation': gate.exponent * np.pi} def _serialize_z_pow_gate(self, gate: cirq.ZPowGate, targets: Sequence[int]) -> dict: if self._near_mod_n(gate.exponent, 1, 2): - return { - 'gate': 'z', - 'targets': targets, - } + return {'gate': 'z', 'targets': targets} elif self._near_mod_n(gate.exponent, 0.5, 2): return {'gate': 's', 'targets': targets} elif self._near_mod_n(gate.exponent, -0.5, 2): return {'gate': 'si', 'targets': targets} elif self._near_mod_n(gate.exponent, 0.25, 2): - return { - 'gate': 't', - 'targets': targets, - } + return {'gate': 't', 'targets': targets} elif self._near_mod_n(gate.exponent, -0.25, 2): - return { - 'gate': 'ti', - 'targets': targets, - } + return {'gate': 'ti', 'targets': targets} return {'gate': 'rz', 'targets': targets, 'rotation': gate.exponent * np.pi} def _serialize_xx_pow_gate(self, gate: cirq.XXPowGate, targets: Sequence[int]) -> dict: @@ -195,18 +174,12 @@ def _serialize_swap_gate( self, gate: cirq.SwapPowGate, targets: Sequence[int] ) -> Optional[dict]: if self._near_mod_n(gate.exponent, 1, 2): - return { - 'gate': 'swap', - 'targets': targets, - } + return {'gate': 'swap', 'targets': targets} return None def _serialize_h_pow_gate(self, gate: cirq.HPowGate, targets: Sequence[int]) -> Optional[dict]: if self._near_mod_n(gate.exponent, 1, 2): - return { - 'gate': 'h', - 'targets': targets, - } + return {'gate': 'h', 'targets': targets} return None def _serialize_cnot_pow_gate( diff --git a/cirq-ionq/cirq_ionq/serializer_test.py b/cirq-ionq/cirq_ionq/serializer_test.py index 42706bf9bee..9b2c615fbd2 100644 --- a/cirq-ionq/cirq_ionq/serializer_test.py +++ b/cirq-ionq/cirq_ionq/serializer_test.py @@ -80,7 +80,7 @@ def test_serialize_pow_gates(): serializer = ionq.Serializer() for name, gate in (('rx', cirq.X), ('ry', cirq.Y), ('rz', cirq.Z)): for exponent in (1.1, 0.6): - circuit = cirq.Circuit((gate ** exponent)(q0)) + circuit = cirq.Circuit((gate**exponent)(q0)) result = serializer.serialize(circuit) assert result == ionq.SerializedProgram( body={ @@ -221,8 +221,7 @@ def test_serialize_measurement_gate_target_order(): serializer = ionq.Serializer() result = serializer.serialize(circuit) assert result == ionq.SerializedProgram( - body={'qubits': 3, 'circuit': []}, - metadata={'measurement0': f'tomyheart{chr(31)}2,0'}, + body={'qubits': 3, 'circuit': []}, metadata={'measurement0': f'tomyheart{chr(31)}2,0'} ) diff --git a/cirq-ionq/cirq_ionq/service_test.py b/cirq-ionq/cirq_ionq/service_test.py index e31f1de2b2d..3d4d62a4691 100644 --- a/cirq-ionq/cirq_ionq/service_test.py +++ b/cirq-ionq/cirq_ionq/service_test.py @@ -32,10 +32,7 @@ def test_service_run(target, expected_results): service = ionq.Service(remote_host='http://example.com', api_key='key') mock_client = mock.MagicMock() - mock_client.create_job.return_value = { - 'id': 'job_id', - 'status': 'ready', - } + mock_client.create_job.return_value = {'id': 'job_id', 'status': 'ready'} mock_client.get_job.return_value = { 'id': 'job_id', 'status': 'completed', @@ -49,15 +46,10 @@ def test_service_run(target, expected_results): a = sympy.Symbol('a') q = cirq.LineQubit(0) - circuit = cirq.Circuit((cirq.X ** a)(q), cirq.measure(q, key='a')) + circuit = cirq.Circuit((cirq.X**a)(q), cirq.measure(q, key='a')) params = cirq.ParamResolver({'a': 0.5}) result = service.run( - circuit=circuit, - repetitions=4, - target=target, - name='bacon', - param_resolver=params, - seed=2, + circuit=circuit, repetitions=4, target=target, name='bacon', param_resolver=params, seed=2 ) assert result == cirq.ResultDict(params=params, measurements={'a': np.array(expected_results)}) diff --git a/cirq-ionq/setup.py b/cirq-ionq/setup.py index d8fb11a41cd..ad7190dc9d2 100644 --- a/cirq-ionq/setup.py +++ b/cirq-ionq/setup.py @@ -65,8 +65,5 @@ description=description, long_description=long_description, packages=cirq_packages, - package_data={ - 'cirq_ionq': ['py.typed'], - 'cirq_ionq.json_test_data': ['*'], - }, + package_data={'cirq_ionq': ['py.typed'], 'cirq_ionq.json_test_data': ['*']}, ) diff --git a/cirq-pasqal/cirq_pasqal/__init__.py b/cirq-pasqal/cirq_pasqal/__init__.py index 30c26968a71..e55b1229cc6 100644 --- a/cirq-pasqal/cirq_pasqal/__init__.py +++ b/cirq-pasqal/cirq_pasqal/__init__.py @@ -14,28 +14,15 @@ """Devices, qubits, and sampler for Pasqal's neutral atom device.""" -from cirq_pasqal._version import ( - __version__, -) - -from cirq_pasqal.pasqal_qubits import ( - ThreeDQubit, - TwoDQubit, -) - -from cirq_pasqal.pasqal_device import ( - PasqalDevice, - PasqalVirtualDevice, - PasqalConverter, -) - -from cirq_pasqal.pasqal_noise_model import ( - PasqalNoiseModel, -) - -from cirq_pasqal.pasqal_sampler import ( - PasqalSampler, -) +from cirq_pasqal._version import __version__ + +from cirq_pasqal.pasqal_qubits import ThreeDQubit, TwoDQubit + +from cirq_pasqal.pasqal_device import PasqalDevice, PasqalVirtualDevice, PasqalConverter + +from cirq_pasqal.pasqal_noise_model import PasqalNoiseModel + +from cirq_pasqal.pasqal_sampler import PasqalSampler # Register cirq_pasqal's public classes for JSON serialization. diff --git a/cirq-pasqal/cirq_pasqal/json_test_data/spec.py b/cirq-pasqal/cirq_pasqal/json_test_data/spec.py index d3eae9a50b5..18b2d3280ea 100644 --- a/cirq-pasqal/cirq_pasqal/json_test_data/spec.py +++ b/cirq-pasqal/cirq_pasqal/json_test_data/spec.py @@ -30,11 +30,7 @@ packages=[cirq_pasqal], test_data_path=pathlib.Path(__file__).parent, not_yet_serializable=[], - should_not_be_serialized=[ - "PasqalConverter", - "PasqalNoiseModel", - "PasqalSampler", - ], + should_not_be_serialized=["PasqalConverter", "PasqalNoiseModel", "PasqalSampler"], resolver_cache=_class_resolver_dictionary(), deprecated={}, ) diff --git a/cirq-pasqal/cirq_pasqal/pasqal_device.py b/cirq-pasqal/cirq_pasqal/pasqal_device.py index b97c951cd94..dd9cd00b137 100644 --- a/cirq-pasqal/cirq_pasqal/pasqal_device.py +++ b/cirq-pasqal/cirq_pasqal/pasqal_device.py @@ -96,10 +96,7 @@ def maximum_qubit_number(self): def metadata(self): return self._metadata - @_compat.deprecated( - fix='Use metadata.qubit_set() if applicable.', - deadline='v0.15', - ) + @_compat.deprecated(fix='Use metadata.qubit_set() if applicable.', deadline='v0.15') def qubit_set(self) -> FrozenSet[cirq.Qid]: return frozenset(self.qubits) @@ -265,18 +262,12 @@ def __init__( cirq.AnyIntegerPowerGateFamily(cirq.CCZPowGate), ) self.controlled_gateset = cirq.Gateset( - *self.exclude_gateset.gates, - cirq.AnyIntegerPowerGateFamily(cirq.CZPowGate), + *self.exclude_gateset.gates, cirq.AnyIntegerPowerGateFamily(cirq.CZPowGate) ) @property def supported_qubit_type(self): - return ( - ThreeDQubit, - TwoDQubit, - GridQubit, - LineQubit, - ) + return (ThreeDQubit, TwoDQubit, GridQubit, LineQubit) def is_pasqal_device_op(self, op: cirq.Operation) -> bool: return super().is_pasqal_device_op(op) and op not in self.exclude_gateset @@ -367,8 +358,7 @@ def _json_dict_(self) -> Dict[str, Any]: return cirq.protocols.obj_to_dict_helper(self, ['control_radius', 'qubits']) @_compat.deprecated( - deadline='v0.15', - fix='qubit coupling data can now be found in device.metadata if provided.', + deadline='v0.15', fix='qubit coupling data can now be found in device.metadata if provided.' ) def qid_pairs(self) -> FrozenSet['cirq.SymmetricalQidPair']: """Returns a list of qubit edges on the device. diff --git a/cirq-pasqal/cirq_pasqal/pasqal_device_test.py b/cirq-pasqal/cirq_pasqal/pasqal_device_test.py index 902cbc937c9..d4ca327eadb 100644 --- a/cirq-pasqal/cirq_pasqal/pasqal_device_test.py +++ b/cirq-pasqal/cirq_pasqal/pasqal_device_test.py @@ -45,12 +45,7 @@ def test_init(): assert d.metadata.qubit_set == {TwoDQubit(0, 0)} assert d.qubit_list() == [TwoDQubit(0, 0)] assert d.control_radius == 1.0 - assert d.supported_qubit_type == ( - ThreeDQubit, - TwoDQubit, - cirq.GridQubit, - cirq.LineQubit, - ) + assert d.supported_qubit_type == (ThreeDQubit, TwoDQubit, cirq.GridQubit, cirq.LineQubit) def test_init_errors(): @@ -170,11 +165,7 @@ def test_qubit_set_deprecated(): def test_metadata(): d = generic_device(3) assert d.metadata.qubit_set == frozenset( - [ - cirq.NamedQubit('q0'), - cirq.NamedQubit('q1'), - cirq.NamedQubit('q2'), - ] + [cirq.NamedQubit('q0'), cirq.NamedQubit('q1'), cirq.NamedQubit('q2')] ) assert len(d.metadata.nx_graph.edges()) == 3 @@ -266,10 +257,7 @@ def test_to_json(): assert d == {"qubits": [cirq.NamedQubit('q4')]} vdev = PasqalVirtualDevice(control_radius=2, qubits=[TwoDQubit(0, 0)]) d = vdev._json_dict_() - assert d == { - "control_radius": 2, - "qubits": [cirq_pasqal.TwoDQubit(0, 0)], - } + assert d == {"control_radius": 2, "qubits": [cirq_pasqal.TwoDQubit(0, 0)]} def test_qid_pairs_deprecated(): @@ -286,12 +274,6 @@ def test_qid_pairs_deprecated(): with cirq.testing.assert_deprecated('device.metadata', deadline='v0.15', count=2): assert len(dev.qid_pairs()) == 5 dev1 = PasqalVirtualDevice( - 5, - qubits=[ - TwoDQubit(0, 0), - TwoDQubit(3, 2), - TwoDQubit(3, 4), - TwoDQubit(3, 6), - ], + 5, qubits=[TwoDQubit(0, 0), TwoDQubit(3, 2), TwoDQubit(3, 4), TwoDQubit(3, 6)] ) assert len(dev1.qid_pairs()) == 5 diff --git a/cirq-pasqal/cirq_pasqal/pasqal_qubits_test.py b/cirq-pasqal/cirq_pasqal/pasqal_qubits_test.py index 60256919211..b0b158f43d5 100644 --- a/cirq-pasqal/cirq_pasqal/pasqal_qubits_test.py +++ b/cirq-pasqal/cirq_pasqal/pasqal_qubits_test.py @@ -55,7 +55,7 @@ def test_distance_3d(): for y in np.arange(-2, 3): for z in np.arange(-2, 3): assert ThreeDQubit(0, 0, 0).distance(ThreeDQubit(x, y, z)) == np.sqrt( - x ** 2 + y ** 2 + z ** 2 + x**2 + y**2 + z**2 ) @@ -164,14 +164,7 @@ def test_str(): def test_to_json(): q = ThreeDQubit(1.3, 1, 1) d = q._json_dict_() - assert d == { - 'x': 1.3, - 'y': 1, - 'z': 1, - } + assert d == {'x': 1.3, 'y': 1, 'z': 1} q = TwoDQubit(1.3, 1) d = q._json_dict_() - assert d == { - 'x': 1.3, - 'y': 1, - } + assert d == {'x': 1.3, 'y': 1} diff --git a/cirq-pasqal/cirq_pasqal/pasqal_sampler.py b/cirq-pasqal/cirq_pasqal/pasqal_sampler.py index 4d0a331e785..9ed49ec6fc1 100644 --- a/cirq-pasqal/cirq_pasqal/pasqal_sampler.py +++ b/cirq-pasqal/cirq_pasqal/pasqal_sampler.py @@ -63,11 +63,7 @@ def _retrieve_serialized_result(self, task_id: str) -> str: url = f'{self.remote_host}/get-result/{task_id}' while True: - response = requests.get( - url, - headers=self._authorization_header, - verify=False, - ) + response = requests.get(url, headers=self._authorization_header, verify=False) response.raise_for_status() result = response.text @@ -90,10 +86,7 @@ def _send_serialized_circuit( submit_response = requests.post( simulate_url, verify=False, - headers={ - "Repetitions": str(repetitions), - **self._authorization_header, - }, + headers={"Repetitions": str(repetitions), **self._authorization_header}, data=serialization_str, ) submit_response.raise_for_status() diff --git a/cirq-pasqal/setup.py b/cirq-pasqal/setup.py index dc9ff2a6fc5..8771de9ef2c 100644 --- a/cirq-pasqal/setup.py +++ b/cirq-pasqal/setup.py @@ -64,8 +64,5 @@ description=description, long_description=long_description, packages=cirq_packages, - package_data={ - 'cirq_pasqal': ['py.typed'], - 'cirq_pasqal.json_test_data': ['*'], - }, + package_data={'cirq_pasqal': ['py.typed'], 'cirq_pasqal.json_test_data': ['*']}, ) diff --git a/cirq-rigetti/cirq_rigetti/__init__.py b/cirq-rigetti/cirq_rigetti/__init__.py index 8fe8bcd49a1..4e4a9f4361e 100644 --- a/cirq-rigetti/cirq_rigetti/__init__.py +++ b/cirq-rigetti/cirq_rigetti/__init__.py @@ -12,17 +12,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -from cirq_rigetti._version import ( - __version__, -) -from cirq_rigetti.sampler import ( - RigettiQCSSampler, - get_rigetti_qcs_sampler, -) -from cirq_rigetti.service import ( - RigettiQCSService, - get_rigetti_qcs_service, -) +from cirq_rigetti._version import __version__ +from cirq_rigetti.sampler import RigettiQCSSampler, get_rigetti_qcs_sampler +from cirq_rigetti.service import RigettiQCSService, get_rigetti_qcs_service from cirq_rigetti import circuit_sweep_executors from cirq_rigetti import circuit_transformers from cirq_rigetti.aspen_device import ( diff --git a/cirq-rigetti/cirq_rigetti/aspen_device.py b/cirq-rigetti/cirq_rigetti/aspen_device.py index 20823229e37..f02e608ff0d 100644 --- a/cirq-rigetti/cirq_rigetti/aspen_device.py +++ b/cirq-rigetti/cirq_rigetti/aspen_device.py @@ -20,9 +20,7 @@ import cirq from pyquil.quantum_processor import QCSQuantumProcessor from qcs_api_client.models import InstructionSetArchitecture -from qcs_api_client.operations.sync import ( - get_instruction_set_architecture, -) +from qcs_api_client.operations.sync import get_instruction_set_architecture from cirq_rigetti._qcs_api_client_decorator import _provide_default_client @@ -70,7 +68,7 @@ def __init__(self, isa: Union[InstructionSetArchitecture, Dict[str, Any]]) -> No if self.isa.architecture.family.lower() != 'aspen': raise UnsupportedRigettiQCSQuantumProcessor( 'this integration currently only supports Aspen devices, ' - f'but client provided a {self.isa.architecture.family} device', + f'but client provided a {self.isa.architecture.family} device' ) self.quantum_processor = QCSQuantumProcessor( quantum_processor_id=self.isa.name, isa=self.isa @@ -218,7 +216,7 @@ def validate_operation(self, operation: 'cirq.Operation') -> None: j = self._aspen_qubit_index(qubits[1]) if j not in self.qubit_topology[i]: raise UnsupportedRigettiQCSOperation( - f'qubits {qubits[0]} and {qubits[1]} do not share an edge', + f'qubits {qubits[0]} and {qubits[1]} do not share an edge' ) def _value_equality_values_(self): @@ -228,21 +226,16 @@ def __repr__(self): return f'cirq_rigetti.RigettiQCSAspenDevice(isa={self.isa!r})' def _json_dict_(self): - return { - 'isa': self.isa.to_dict(), - } + return {'isa': self.isa.to_dict()} @classmethod def _from_json_dict_(cls, isa, **kwargs): - return cls( - isa=InstructionSetArchitecture.from_dict(isa), - ) + return cls(isa=InstructionSetArchitecture.from_dict(isa)) @_provide_default_client def get_rigetti_qcs_aspen_device( - quantum_processor_id: str, - client: Optional[httpx.Client], + quantum_processor_id: str, client: Optional[httpx.Client] ) -> RigettiQCSAspenDevice: """Retrieves a `qcs_api_client.models.InstructionSetArchitecture` from the Rigetti QCS API and uses it to initialize a RigettiQCSAspenDevice. @@ -382,9 +375,7 @@ def __repr__(self): return f'cirq_rigetti.OctagonalQubit(octagon_position={self.octagon_position})' def _json_dict_(self): - return { - 'octagon_position': self.octagon_position, - } + return {'octagon_position': self.octagon_position} class AspenQubit(OctagonalQubit): @@ -521,7 +512,4 @@ def __str__(self): return f'({self.octagon}, {self.octagon_position})' def _json_dict_(self): - return { - 'octagon': self.octagon, - 'octagon_position': self.octagon_position, - } + return {'octagon': self.octagon, 'octagon_position': self.octagon_position} diff --git a/cirq-rigetti/cirq_rigetti/aspen_device_test.py b/cirq-rigetti/cirq_rigetti/aspen_device_test.py index 98866434865..da4ef58e9cb 100644 --- a/cirq-rigetti/cirq_rigetti/aspen_device_test.py +++ b/cirq-rigetti/cirq_rigetti/aspen_device_test.py @@ -236,12 +236,7 @@ def test_rigetti_qcs_aspen_device_invalid_operation( device.validate_operation(operation) -@pytest.mark.parametrize( - 'operation', - [ - cirq.CNOT(AspenQubit(0, 1), AspenQubit(0, 2)), - ], -) +@pytest.mark.parametrize('operation', [cirq.CNOT(AspenQubit(0, 1), AspenQubit(0, 2))]) def test_rigetti_qcs_aspen_device_valid_operation( operation: cirq.Operation, qcs_aspen8_isa: InstructionSetArchitecture ): diff --git a/cirq-rigetti/cirq_rigetti/circuit_sweep_executors.py b/cirq-rigetti/cirq_rigetti/circuit_sweep_executors.py index 27741ed1de5..d388fc48c15 100644 --- a/cirq-rigetti/cirq_rigetti/circuit_sweep_executors.py +++ b/cirq-rigetti/cirq_rigetti/circuit_sweep_executors.py @@ -275,11 +275,7 @@ def with_quilc_parametric_compilation( memory_map = _get_param_dict(resolver) logger.debug(f"running pre-compiled parametric circuit with parameters {memory_map}") result = _execute_and_read_result( - quantum_computer, - executable.copy(), - measurement_id_map, - resolver, - memory_map=memory_map, + quantum_computer, executable.copy(), measurement_id_map, resolver, memory_map=memory_map ) cirq_results.append(result) diff --git a/cirq-rigetti/cirq_rigetti/circuit_sweep_executors_test.py b/cirq-rigetti/cirq_rigetti/circuit_sweep_executors_test.py index 3ce98b1ba4b..f3b8e246708 100644 --- a/cirq-rigetti/cirq_rigetti/circuit_sweep_executors_test.py +++ b/cirq-rigetti/cirq_rigetti/circuit_sweep_executors_test.py @@ -8,8 +8,7 @@ def test_with_quilc_compilation_and_cirq_parameter_resolution( - mock_qpu_implementer: Any, - parametric_circuit_with_params: Tuple[cirq.Circuit, cirq.Sweepable], + mock_qpu_implementer: Any, parametric_circuit_with_params: Tuple[cirq.Circuit, cirq.Sweepable] ) -> None: """test that execution with quilc compilation and cirq parameter resolution calls ``quil_to_native_quil`` and ``native_quil_to_executable`` for each parameter @@ -41,8 +40,7 @@ def test_with_quilc_compilation_and_cirq_parameter_resolution( result = results[i] assert param_resolvers[i] == result.params assert np.allclose( - result.measurements["m"], - expected_results[i], + result.measurements["m"], expected_results[i] ), "should return an ordered list of results with correct set of measurements" @@ -85,14 +83,12 @@ def test_with_quilc_parametric_compilation( result = results[i] assert param_resolvers[i] == result.params assert np.allclose( - result.measurements["m"], - expected_results[i], + result.measurements["m"], expected_results[i] ), "should return an ordered list of results with correct set of measurements" def test_without_quilc_compilation( - mock_qpu_implementer: Any, - parametric_circuit_with_params: Tuple[cirq.Circuit, cirq.Sweepable], + mock_qpu_implementer: Any, parametric_circuit_with_params: Tuple[cirq.Circuit, cirq.Sweepable] ) -> None: """test execution without quilc compilation treats the transformed cirq Circuit as native quil and does not pass it through quilc. @@ -124,14 +120,12 @@ def test_without_quilc_compilation( result = results[i] assert param_resolvers[i] == result.params assert np.allclose( - result.measurements["m"], - expected_results[i], + result.measurements["m"], expected_results[i] ), "should return an ordered list of results with correct set of measurements" def test_invalid_pyquil_region_measurement( - mock_qpu_implementer: Any, - parametric_circuit_with_params: Tuple[cirq.Circuit, cirq.Sweepable], + mock_qpu_implementer: Any, parametric_circuit_with_params: Tuple[cirq.Circuit, cirq.Sweepable] ) -> None: """test that executors raise `ValueError` if the measurement_id_map does not exist. @@ -155,7 +149,7 @@ def broken_hook( return program, {cirq_key: f'{cirq_key}-doesnt-exist' for cirq_key in measurement_id_map} transformer = circuit_transformers.build( - post_transformation_hooks=[broken_hook], # type: ignore + post_transformation_hooks=[broken_hook] # type: ignore ) with pytest.raises(ValueError): diff --git a/cirq-rigetti/cirq_rigetti/circuit_transformers.py b/cirq-rigetti/cirq_rigetti/circuit_transformers.py index 2c3e0145f6f..8921454c550 100644 --- a/cirq-rigetti/cirq_rigetti/circuit_transformers.py +++ b/cirq-rigetti/cirq_rigetti/circuit_transformers.py @@ -60,11 +60,7 @@ def _transform_cirq_circuit_to_pyquil_program( class CircuitTransformer(Protocol): """A type definition for `cirq.Circuit` to `pyquil.Program` transformer functions.""" - def __call__( - self, - *, - circuit: cirq.Circuit, - ) -> Tuple[Program, Dict[str, str]]: + def __call__(self, *, circuit: cirq.Circuit) -> Tuple[Program, Dict[str, str]]: """Transforms a `cirq.Circuit` to a pyquil.Program`. Args: diff --git a/cirq-rigetti/cirq_rigetti/circuit_transformers_test.py b/cirq-rigetti/cirq_rigetti/circuit_transformers_test.py index c19085b5569..e214ef58da7 100644 --- a/cirq-rigetti/cirq_rigetti/circuit_transformers_test.py +++ b/cirq-rigetti/cirq_rigetti/circuit_transformers_test.py @@ -9,7 +9,7 @@ def test_transform_cirq_circuit_to_pyquil_program( - parametric_circuit_with_params: Tuple[cirq.Circuit, cirq.Linspace], + parametric_circuit_with_params: Tuple[cirq.Circuit, cirq.Linspace] ) -> None: """test that a user can transform a `cirq.Circuit` to a `pyquil.Program` functionally. @@ -17,9 +17,7 @@ def test_transform_cirq_circuit_to_pyquil_program( parametric_circuit, param_resolvers = parametric_circuit_with_params circuit = cirq.protocols.resolve_parameters(parametric_circuit, param_resolvers[1]) - program, _ = transformers.default( - circuit=circuit, - ) + program, _ = transformers.default(circuit=circuit) assert ( RX(np.pi / 2, 0) in program.instructions @@ -31,7 +29,7 @@ def test_transform_cirq_circuit_to_pyquil_program( def test_transform_cirq_circuit_to_pyquil_program_with_qubit_id_map( - bell_circuit_with_qids: Tuple[cirq.Circuit, List[cirq.Qid]], + bell_circuit_with_qids: Tuple[cirq.Circuit, List[cirq.Qid]] ) -> None: """test that a user can transform a `cirq.Circuit` to a `pyquil.Program` functionally with explicit physical qubit address mapping. @@ -39,10 +37,7 @@ def test_transform_cirq_circuit_to_pyquil_program_with_qubit_id_map( bell_circuit, qubits = bell_circuit_with_qids - qubit_id_map = { - qubits[1]: "11", - qubits[0]: "13", - } + qubit_id_map = {qubits[1]: "11", qubits[0]: "13"} transformer = transformers.build(qubit_id_map=qubit_id_map) program, _ = transformer(circuit=bell_circuit) @@ -60,7 +55,7 @@ def test_transform_cirq_circuit_to_pyquil_program_with_qubit_id_map( def test_transform_with_post_transformation_hooks( - bell_circuit_with_qids: Tuple[cirq.Circuit, List[cirq.Qid]], + bell_circuit_with_qids: Tuple[cirq.Circuit, List[cirq.Qid]] ) -> None: """test that a user can transform a `cirq.Circuit` to a `pyquil.Program` functionally with explicit physical qubit address mapping. @@ -71,10 +66,7 @@ def reset_hook(program, measurement_id_map): program._instructions.insert(0, Reset()) return program, measurement_id_map - reset_hook_spec = create_autospec( - reset_hook, - side_effect=reset_hook, - ) + reset_hook_spec = create_autospec(reset_hook, side_effect=reset_hook) pragma = Pragma('INTIAL_REWIRING', freeform_string='GREEDY') @@ -82,13 +74,9 @@ def rewire_hook(program, measurement_id_map): program._instructions.insert(0, pragma) return program, measurement_id_map - rewire_hook_spec = create_autospec( - rewire_hook, - side_effect=rewire_hook, - ) + rewire_hook_spec = create_autospec(rewire_hook, side_effect=rewire_hook) transformer = transformers.build( - qubits=tuple(qubits), - post_transformation_hooks=[reset_hook_spec, rewire_hook_spec], + qubits=tuple(qubits), post_transformation_hooks=[reset_hook_spec, rewire_hook_spec] ) program, _ = transformer(circuit=bell_circuit) @@ -112,16 +100,14 @@ def rewire_hook(program, measurement_id_map): def test_transform_cirq_circuit_with_explicit_decompose( - parametric_circuit_with_params: Tuple[cirq.Circuit, cirq.Linspace], + parametric_circuit_with_params: Tuple[cirq.Circuit, cirq.Linspace] ) -> None: """test that a user add a custom circuit decomposition function""" parametric_circuit, param_resolvers = parametric_circuit_with_params parametric_circuit.append(cirq.I(cirq.GridQubit(0, 0))) parametric_circuit.append(cirq.I(cirq.GridQubit(0, 1))) - parametric_circuit.append( - cirq.measure(cirq.GridQubit(0, 0), cirq.GridQubit(0, 1), key='m'), - ) + parametric_circuit.append(cirq.measure(cirq.GridQubit(0, 0), cirq.GridQubit(0, 1), key='m')) circuit = cirq.protocols.resolve_parameters(parametric_circuit, param_resolvers[1]) def decompose_operation(operation: cirq.Operation) -> List[cirq.Operation]: @@ -130,9 +116,7 @@ def decompose_operation(operation: cirq.Operation) -> List[cirq.Operation]: operations.append(cirq.I(operation.qubits[0])) return operations - program, _ = transformers.build( - decompose_operation=decompose_operation, - )(circuit=circuit) + program, _ = transformers.build(decompose_operation=decompose_operation)(circuit=circuit) assert ( RX(np.pi / 2, 2) in program.instructions diff --git a/cirq-rigetti/cirq_rigetti/conftest.py b/cirq-rigetti/cirq_rigetti/conftest.py index 37dcef40747..dbd84a686fe 100644 --- a/cirq-rigetti/cirq_rigetti/conftest.py +++ b/cirq-rigetti/cirq_rigetti/conftest.py @@ -54,8 +54,7 @@ def pytest_collection_modifyitems(config, items): def pytest_configure(config): config.addinivalue_line( - "markers", - "rigetti_integration: tests that connect to Quil compiler or QVM.", + "markers", "rigetti_integration: tests that connect to Quil compiler or QVM." ) @@ -66,11 +65,7 @@ class MockQAM(QAM, Generic[T]): _run_count: int _mock_results: Dict[str, np.ndarray] - def __init__( - self, - *args, - **kwargs, - ) -> None: + def __init__(self, *args, **kwargs) -> None: self._run_count = 0 self._mock_results: Dict[str, np.ndarray] = {} @@ -107,11 +102,7 @@ def quantum_processor() -> AbstractQuantumProcessor: def qcs_client_configuration() -> QCSClientConfiguration: settings = QCSClientConfigurationSettings() secrets = QCSClientConfigurationSecrets() - return QCSClientConfiguration( - profile_name="default", - settings=settings, - secrets=secrets, - ) + return QCSClientConfiguration(profile_name="default", settings=settings, secrets=secrets) @pytest.fixture @@ -125,11 +116,7 @@ def compiler(quantum_processor, qcs_client_configuration) -> AbstractCompiler: @pytest.fixture def quantum_computer(qam: QAM, compiler: AbstractCompiler) -> QuantumComputer: - return QuantumComputer( - name='mocked', - qam=qam, - compiler=compiler, - ) + return QuantumComputer(name='mocked', qam=qam, compiler=compiler) @pytest.fixture @@ -169,8 +156,7 @@ def __init__(self, quantum_computer: QuantumComputer): self.quantum_computer = quantum_computer def implement_passive_quantum_computer_with_results( - self, - results: List[np.ndarray], + self, results: List[np.ndarray] ) -> QuantumComputer: """Mocks compilation methods on the `quantum_computer.compiler`, passively passing the `Program` through. Sequentially adds results to the @@ -188,8 +174,7 @@ def quil_to_native_quil(program: Program, *, protoquil: Optional[bool] = None) - return program quantum_computer.compiler.quil_to_native_quil = create_autospec( # type: ignore - quantum_computer.compiler.quil_to_native_quil, - side_effect=quil_to_native_quil, + quantum_computer.compiler.quil_to_native_quil, side_effect=quil_to_native_quil ) def native_quil_to_executable(nq_program: Program) -> QuantumExecutable: @@ -208,13 +193,11 @@ def run(program: Union[Program, EncryptedProgram]) -> QAMExecutionResult: quantum_computer.qam._run_count += 1 # type: ignore return QAMExecutionResult( - executable=program, - readout_data=qam._mock_results, # type: ignore + executable=program, readout_data=qam._mock_results # type: ignore ) quantum_computer.qam.run = Mock( # type: ignore - quantum_computer.qam.run, # type: ignore - side_effect=run, + quantum_computer.qam.run, side_effect=run # type: ignore ) return quantum_computer diff --git a/cirq-rigetti/cirq_rigetti/qcs_sampler_and_service_test.py b/cirq-rigetti/cirq_rigetti/qcs_sampler_and_service_test.py index 2f4cf21214d..eac95ddadb8 100644 --- a/cirq-rigetti/cirq_rigetti/qcs_sampler_and_service_test.py +++ b/cirq-rigetti/cirq_rigetti/qcs_sampler_and_service_test.py @@ -59,16 +59,10 @@ def _build_service_results( expected_results ) service = RigettiQCSService( - quantum_computer=quantum_computer, - executor=executor, - transformer=transformer, + quantum_computer=quantum_computer, executor=executor, transformer=transformer ) - result = service.run( - circuit=circuit, - param_resolver=param_resolver, - repetitions=repetitions, - ) + result = service.run(circuit=circuit, param_resolver=param_resolver, repetitions=repetitions) return [result], quantum_computer, expected_results, [param_resolver] @@ -96,18 +90,12 @@ def _build_sampler_results( expected_results ) service = RigettiQCSService( - quantum_computer=quantum_computer, - executor=executor, - transformer=transformer, + quantum_computer=quantum_computer, executor=executor, transformer=transformer ) sampler = service.sampler() - results = sampler.run_sweep( - program=circuit, - params=param_resolvers, - repetitions=repetitions, - ) + results = sampler.run_sweep(program=circuit, params=param_resolvers, repetitions=repetitions) return results, quantum_computer, expected_results, param_resolvers @@ -135,8 +123,7 @@ def test_parametric_circuit( result = results[i] assert param_resolver == result.params assert np.allclose( - result.measurements["m"], - expected_results[i], + result.measurements["m"], expected_results[i] ), "should return an ordered list of results with correct set of measurements" def test_executable(i: int, program: Program) -> None: @@ -178,9 +165,7 @@ def test_executable(i: int, program: Program) -> None: @pytest.mark.parametrize("result_builder", [_build_service_results, _build_sampler_results]) def test_bell_circuit( - mock_qpu_implementer: Any, - bell_circuit: cirq.Circuit, - result_builder: _ResultBuilder, + mock_qpu_implementer: Any, bell_circuit: cirq.Circuit, result_builder: _ResultBuilder ) -> None: """test that RigettiQCSService and RigettiQCSSampler can run a basic Bell circuit with two read out bits and return expected cirq.Results. @@ -199,8 +184,7 @@ def test_bell_circuit( result = results[i] assert param_resolver == result.params assert np.allclose( - result.measurements["m"], - expected_results[i], + result.measurements["m"], expected_results[i] ), "should return an ordered list of results with correct set of measurements" def test_executable(program: Program) -> None: @@ -248,18 +232,13 @@ def test_explicit_qubit_id_map( """ bell_circuit, qubits = bell_circuit_with_qids - qubit_id_map = { - qubits[1]: "11", - qubits[0]: "13", - } + qubit_id_map = {qubits[1]: "11", qubits[0]: "13"} param_resolvers = [cirq.ParamResolver({})] results, quantum_computer, expected_results, param_resolvers = result_builder( mock_qpu_implementer, bell_circuit, param_resolvers, - transformer=transformers.build( - qubit_id_map=qubit_id_map, # type: ignore - ), + transformer=transformers.build(qubit_id_map=qubit_id_map), # type: ignore ) assert len(param_resolvers) == len( @@ -270,8 +249,7 @@ def test_explicit_qubit_id_map( result = results[i] assert param_resolver == result.params assert np.allclose( - result.measurements["m"], - expected_results[i], + result.measurements["m"], expected_results[i] ), "should return an ordered list of results with correct set of measurements" def test_executable(program: Program) -> None: @@ -310,9 +288,7 @@ def test_executable(program: Program) -> None: @pytest.mark.parametrize("result_builder", [_build_service_results, _build_sampler_results]) def test_run_without_quilc_compilation( - mock_qpu_implementer: Any, - bell_circuit: cirq.Circuit, - result_builder: _ResultBuilder, + mock_qpu_implementer: Any, bell_circuit: cirq.Circuit, result_builder: _ResultBuilder ) -> None: """test that RigettiQCSService and RigettiQCSSampler allow users to execute without using quilc to compile to native Quil. @@ -333,8 +309,7 @@ def test_run_without_quilc_compilation( result = results[i] assert param_resolver == result.params assert np.allclose( - result.measurements["m"], - expected_results[i], + result.measurements["m"], expected_results[i] ), "should return an ordered list of results with correct set of measurements" def test_executable(program: Program) -> None: diff --git a/cirq-rigetti/cirq_rigetti/sampler.py b/cirq-rigetti/cirq_rigetti/sampler.py index bbde6eb0517..c34af6315c5 100644 --- a/cirq-rigetti/cirq_rigetti/sampler.py +++ b/cirq-rigetti/cirq_rigetti/sampler.py @@ -52,10 +52,7 @@ def __init__( self.transformer = transformer def run_sweep( - self, - program: cirq.AbstractCircuit, - params: cirq.Sweepable, - repetitions: int = 1, + self, program: cirq.AbstractCircuit, params: cirq.Sweepable, repetitions: int = 1 ) -> Sequence[cirq.Result]: """This will evaluate results on the circuit for every set of parameters in `params`. @@ -115,13 +112,5 @@ def get_rigetti_qcs_sampler( A `RigettiQCSSampler` with the specified quantum processor, executor, and transformer. """ - qc = get_qc( - quantum_processor_id, - as_qvm=as_qvm, - noisy=noisy, - ) - return RigettiQCSSampler( - quantum_computer=qc, - executor=executor, - transformer=transformer, - ) + qc = get_qc(quantum_processor_id, as_qvm=as_qvm, noisy=noisy) + return RigettiQCSSampler(quantum_computer=qc, executor=executor, transformer=transformer) diff --git a/cirq-rigetti/cirq_rigetti/sampler_parametric_circuit_test.py b/cirq-rigetti/cirq_rigetti/sampler_parametric_circuit_test.py index 028d198e685..4173784810d 100644 --- a/cirq-rigetti/cirq_rigetti/sampler_parametric_circuit_test.py +++ b/cirq-rigetti/cirq_rigetti/sampler_parametric_circuit_test.py @@ -27,13 +27,7 @@ def test_parametric_circuit_through_sampler( results = sampler.run_sweep(program=circuit, params=sweepable, repetitions=repetitions) assert len(sweepable) == len(results) - expected_results = [ - (10, 0), - (4, 6), - (0, 10), - (4, 6), - (10, 0), - ] + expected_results = [(10, 0), (4, 6), (0, 10), (4, 6), (10, 0)] for i, result in enumerate(results): assert isinstance(result, cirq.study.Result) assert sweepable[i] == result.params @@ -57,8 +51,7 @@ def test_parametric_circuit_through_sampler_with_parametric_compilation( qc = get_qc('9q-square', as_qvm=True) sampler = RigettiQCSSampler( - quantum_computer=qc, - executor=circuit_sweep_executors.with_quilc_parametric_compilation, + quantum_computer=qc, executor=circuit_sweep_executors.with_quilc_parametric_compilation ) # set the seed so we get a deterministic set of results. @@ -69,13 +62,7 @@ def test_parametric_circuit_through_sampler_with_parametric_compilation( results = sampler.run_sweep(program=circuit, params=sweepable, repetitions=repetitions) assert len(sweepable) == len(results) - expected_results = [ - (10, 0), - (8, 2), - (0, 10), - (8, 2), - (10, 0), - ] + expected_results = [(10, 0), (8, 2), (0, 10), (8, 2), (10, 0)] for i, result in enumerate(results): assert isinstance(result, cirq.study.Result) assert sweepable[i] == result.params diff --git a/cirq-rigetti/cirq_rigetti/sampler_readout_reassigned_qubits_test.py b/cirq-rigetti/cirq_rigetti/sampler_readout_reassigned_qubits_test.py index 94b1984a126..762f2d6ce11 100644 --- a/cirq-rigetti/cirq_rigetti/sampler_readout_reassigned_qubits_test.py +++ b/cirq-rigetti/cirq_rigetti/sampler_readout_reassigned_qubits_test.py @@ -32,12 +32,7 @@ def test_readout_on_reassigned_qubits( qc = get_qc('9q-square', as_qvm=True) circuit, qubits, sweepable = circuit_data - transformer = circuit_transformers.build( - qubit_id_map={ - qubits[0]: '100', - qubits[1]: '101', - } - ) + transformer = circuit_transformers.build(qubit_id_map={qubits[0]: '100', qubits[1]: '101'}) sampler = RigettiQCSSampler(quantum_computer=qc, transformer=transformer) # set the seed so we get a deterministic set of results. diff --git a/cirq-rigetti/cirq_rigetti/service.py b/cirq-rigetti/cirq_rigetti/service.py index d2db540cd3f..b84fe94529a 100644 --- a/cirq-rigetti/cirq_rigetti/service.py +++ b/cirq-rigetti/cirq_rigetti/service.py @@ -120,16 +120,12 @@ def list_quantum_processors( A qcs_api_client.models.ListQuantumProcessorsResponse containing the identifiers of the available quantum processors.. """ - return cast( - ListQuantumProcessorsResponse, - list_quantum_processors(client=client).parsed, - ) + return cast(ListQuantumProcessorsResponse, list_quantum_processors(client=client).parsed) @staticmethod @_provide_default_client def get_quilt_calibrations( - quantum_processor_id: str, - client: Optional[httpx.Client], + quantum_processor_id: str, client: Optional[httpx.Client] ) -> GetQuiltCalibrationsResponse: """Retrieve the calibration data used for client-side Quil-T generation. @@ -153,8 +149,7 @@ def get_quilt_calibrations( @staticmethod @_provide_default_client def get_instruction_set_architecture( - quantum_processor_id: str, - client: Optional[httpx.Client], + quantum_processor_id: str, client: Optional[httpx.Client] ) -> InstructionSetArchitecture: # coverage: ignore """Retrieve the Instruction Set Architecture of a QuantumProcessor by ID. This includes site specific operations and native gate capabilities. @@ -213,13 +208,5 @@ def get_rigetti_qcs_service( A `RigettiQCSService` with the specified quantum processor, executor, and transformer. """ - qc = get_qc( - quantum_processor_id, - as_qvm=as_qvm, - noisy=noisy, - ) - return RigettiQCSService( - quantum_computer=qc, - executor=executor, - transformer=transformer, - ) + qc = get_qc(quantum_processor_id, as_qvm=as_qvm, noisy=noisy) + return RigettiQCSService(quantum_computer=qc, executor=executor, transformer=transformer) diff --git a/cirq-rigetti/cirq_rigetti/service_bell_circuit_test.py b/cirq-rigetti/cirq_rigetti/service_bell_circuit_test.py index de7a8545fef..5a01991f496 100644 --- a/cirq-rigetti/cirq_rigetti/service_bell_circuit_test.py +++ b/cirq-rigetti/cirq_rigetti/service_bell_circuit_test.py @@ -13,9 +13,7 @@ def test_bell_circuit_through_service(bell_circuit: cirq.Circuit) -> None: ``cirq.study.Result``. """ qc = get_qc('9q-square', as_qvm=True) - service = RigettiQCSService( - quantum_computer=qc, - ) + service = RigettiQCSService(quantum_computer=qc) # set the seed so we get a deterministic set of results. qvm = cast(QVM, qc.qam) diff --git a/cirq-rigetti/cirq_rigetti/service_parametric_circuit_test.py b/cirq-rigetti/cirq_rigetti/service_parametric_circuit_test.py index 11c05885c2b..6320db66460 100644 --- a/cirq-rigetti/cirq_rigetti/service_parametric_circuit_test.py +++ b/cirq-rigetti/cirq_rigetti/service_parametric_circuit_test.py @@ -17,9 +17,7 @@ def test_parametric_circuit_through_service( circuit, sweepable = parametric_circuit_with_params qc = get_qc('9q-square', as_qvm=True) - service = RigettiQCSService( - quantum_computer=qc, - ) + service = RigettiQCSService(quantum_computer=qc) # set the seed so we get a deterministic set of results. qvm = cast(QVM, qc.qam) @@ -28,9 +26,7 @@ def test_parametric_circuit_through_service( repetitions = 10 param_resolvers = [r for r in cirq.study.to_resolvers(sweepable)] result = service.run( - circuit=circuit, - repetitions=repetitions, - param_resolver=param_resolvers[1], + circuit=circuit, repetitions=repetitions, param_resolver=param_resolvers[1] ) assert isinstance(result, cirq.study.Result) assert sweepable[1] == result.params diff --git a/cirq-rigetti/cirq_rigetti/service_test.py b/cirq-rigetti/cirq_rigetti/service_test.py index c88f8e48200..3b566b14514 100644 --- a/cirq-rigetti/cirq_rigetti/service_test.py +++ b/cirq-rigetti/cirq_rigetti/service_test.py @@ -35,10 +35,7 @@ def request( ): return 200, [('Content-Type', 'application/json')], Response(), {} - client = httpx.Client( - base_url="https://mock.api.qcs.rigetti.com", - transport=Transport(), - ) + client = httpx.Client(base_url="https://mock.api.qcs.rigetti.com", transport=Transport()) response = RigettiQCSService.list_quantum_processors(client=client) assert 1 == len(response.quantum_processors) diff --git a/cirq-rigetti/setup.py b/cirq-rigetti/setup.py index ea0e34bf2c2..9bd5f139ef9 100644 --- a/cirq-rigetti/setup.py +++ b/cirq-rigetti/setup.py @@ -66,8 +66,5 @@ description=description, long_description=long_description, packages=cirq_packages, - package_data={ - 'cirq_rigetti': ['py.typed'], - 'cirq_rigetti.json_test_data': ['*'], - }, + package_data={'cirq_rigetti': ['py.typed'], 'cirq_rigetti.json_test_data': ['*']}, ) diff --git a/cirq-web/cirq_web/__init__.py b/cirq-web/cirq_web/__init__.py index 69fb6af9bae..27f44d52449 100644 --- a/cirq-web/cirq_web/__init__.py +++ b/cirq-web/cirq_web/__init__.py @@ -12,16 +12,10 @@ # See the License for the specific language governing permissions and # limitations under the License. -from cirq_web._version import ( - __version__, -) +from cirq_web._version import __version__ from cirq_web.widget import Widget -from cirq_web.bloch_sphere import ( - BlochSphere, -) +from cirq_web.bloch_sphere import BlochSphere -from cirq_web.circuits import ( - Circuit3D, -) +from cirq_web.circuits import Circuit3D diff --git a/cirq-web/cirq_web/bloch_sphere/bloch_sphere.py b/cirq-web/cirq_web/bloch_sphere/bloch_sphere.py index 3d95cb5e01e..ba434fcde2d 100644 --- a/cirq-web/cirq_web/bloch_sphere/bloch_sphere.py +++ b/cirq-web/cirq_web/bloch_sphere/bloch_sphere.py @@ -19,11 +19,7 @@ class BlochSphere(widget.Widget): - def __init__( - self, - sphere_radius: int = 5, - state_vector: STATE_VECTOR_LIKE = None, - ): + def __init__(self, sphere_radius: int = 5, state_vector: STATE_VECTOR_LIKE = None): """Initializes a BlochSphere. Also initializes it's parent class Widget with the bundle file provided. diff --git a/cirq-web/cirq_web/circuits/__init__.py b/cirq-web/cirq_web/circuits/__init__.py index e9f8c5b00db..017f3a79191 100644 --- a/cirq-web/cirq_web/circuits/__init__.py +++ b/cirq-web/cirq_web/circuits/__init__.py @@ -13,6 +13,4 @@ # limitations under the License. from cirq_web.circuits.circuit import Circuit3D -from cirq_web.circuits.symbols import ( - Operation3DSymbol, -) +from cirq_web.circuits.symbols import Operation3DSymbol diff --git a/cirq-web/cirq_web/circuits/symbols_test.py b/cirq-web/cirq_web/circuits/symbols_test.py index d246a405996..72829f60bbf 100644 --- a/cirq-web/cirq_web/circuits/symbols_test.py +++ b/cirq-web/cirq_web/circuits/symbols_test.py @@ -77,13 +77,7 @@ def test_resolve_operation_x_pow(): assert symbol_info.colors == expected_colors -@pytest.mark.parametrize( - 'custom_gate', - [ - MockGateNoDiagramInfo, - MockGateUnimplementedDiagramInfo, - ], -) +@pytest.mark.parametrize('custom_gate', [MockGateNoDiagramInfo, MockGateUnimplementedDiagramInfo]) def test_resolve_operation_invalid_diagram_info(custom_gate): mock_qubit = cirq.NamedQubit('mock') gate = custom_gate() diff --git a/dev_tools/modules_test.py b/dev_tools/modules_test.py index 1775a61752c..86802cb5be3 100644 --- a/dev_tools/modules_test.py +++ b/dev_tools/modules_test.py @@ -68,20 +68,14 @@ def test_modules(): assert parent.top_level_packages == [] assert modules.list_modules( search_dir=Path("dev_tools/modules_test_data"), include_parent=True - ) == [ - mod1, - mod2, - parent, - ] + ) == [mod1, mod2, parent] def test_cli(): env = os.environ.copy() env["PYTHONPATH"] = "../.." output = subprocess.check_output( - [sys.executable, "../modules.py", "list"], - cwd="dev_tools/modules_test_data", - env=env, + [sys.executable, "../modules.py", "list"], cwd="dev_tools/modules_test_data", env=env ) assert output.decode("utf-8") == "mod1 mod2 " diff --git a/dev_tools/notebooks/__init__.py b/dev_tools/notebooks/__init__.py index feaf5d1c557..413ad428929 100644 --- a/dev_tools/notebooks/__init__.py +++ b/dev_tools/notebooks/__init__.py @@ -12,8 +12,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -from dev_tools.notebooks.utils import ( - filter_notebooks, - list_all_notebooks, - rewrite_notebook, -) +from dev_tools.notebooks.utils import filter_notebooks, list_all_notebooks, rewrite_notebook diff --git a/dev_tools/pr_monitor.py b/dev_tools/pr_monitor.py index 37e73fc5594..703e1f06dc9 100644 --- a/dev_tools/pr_monitor.py +++ b/dev_tools/pr_monitor.py @@ -462,10 +462,7 @@ def classify_pr_synced_state(pr: PullRequestDetails) -> Optional[bool]: True if the classification is clean, False if it is behind, and None otherwise. """ state = pr.payload['mergeable_state'].lower() - classification = { - 'behind': False, - 'clean': True, - } + classification = {'behind': False, 'clean': True} return classification.get(state, None) @@ -682,9 +679,7 @@ def update_branch(pr: PullRequestDetails) -> Union[bool, CannotAutomergeError]: f"https://api.github.com/repos/{pr.repo.organization}/{pr.repo.name}" f"/pulls/{pr.pull_id}/update-branch" ) - data = { - 'expected_head_sha': pr.branch_sha, - } + data = {'expected_head_sha': pr.branch_sha} response = pr.repo.put( url, json=data, @@ -694,12 +689,11 @@ def update_branch(pr: PullRequestDetails) -> Union[bool, CannotAutomergeError]: if response.status_code == 422: return CannotAutomergeError( - "Failed to update branch (incorrect expected_head_sha).", - may_be_temporary=True, + "Failed to update branch (incorrect expected_head_sha).", may_be_temporary=True ) if response.status_code != 202: return CannotAutomergeError( - f"Unrecognized update-branch status code ({response.status_code}).", + f"Unrecognized update-branch status code ({response.status_code})." ) return True @@ -938,9 +932,7 @@ def list_open_pull_requests( f"https://api.github.com/repos/{repo.organization}/{repo.name}/pulls" f"?per_page={per_page}" ) - data = { - 'state': 'open', - } + data = {'state': 'open'} if base_branch is not None: data['base'] = base_branch response = repo.get(url, json=data) diff --git a/dev_tools/prepared_env.py b/dev_tools/prepared_env.py index cc2aae9f765..aea65b34438 100644 --- a/dev_tools/prepared_env.py +++ b/dev_tools/prepared_env.py @@ -94,11 +94,7 @@ def report_status_to_github( print(repr(('report_status', context, state, description, target_url)), file=sys.stderr) - payload = { - 'state': state, - 'description': description, - 'context': context, - } + payload = {'state': state, 'description': description, 'context': context} if target_url is not None: payload['target_url'] = target_url diff --git a/dev_tools/profiling/benchmark_serializers_test.py b/dev_tools/profiling/benchmark_serializers_test.py index b7a47f99e69..2da5b2c7e39 100644 --- a/dev_tools/profiling/benchmark_serializers_test.py +++ b/dev_tools/profiling/benchmark_serializers_test.py @@ -46,8 +46,4 @@ def test_main_loop(): def test_parse_args(): args = ('--num_gates 5 --nesting_depth 8 --num_repetitions 2').split() kwargs = benchmark_serializers.parse_arguments(args) - assert kwargs == { - 'num_gates': 5, - 'nesting_depth': 8, - 'num_repetitions': 2, - } + assert kwargs == {'num_gates': 5, 'nesting_depth': 8, 'num_repetitions': 2} diff --git a/dev_tools/pylint_copyright_checker_test.py b/dev_tools/pylint_copyright_checker_test.py index d626d004e0e..dd896b2dcee 100644 --- a/dev_tools/pylint_copyright_checker_test.py +++ b/dev_tools/pylint_copyright_checker_test.py @@ -27,11 +27,7 @@ def test_missing_copyright(self) -> None: r"""Report message when no copyright notice at the beginning of a file.""" node = parse("import os") with self.assertAddsMessages( - MessageTest( - msg_id='wrong-or-nonexistent-copyright-notice', - line=1, - col_offset=0, - ), + MessageTest(msg_id='wrong-or-nonexistent-copyright-notice', line=1, col_offset=0) ): self.checker.process_module(node) @@ -44,7 +40,7 @@ def test_wrong_copyright(self) -> None: msg_id='wrong-or-nonexistent-copyright-notice', line=1, col_offset=comment.index("Someone"), - ), + ) ): self.checker.process_module(node) @@ -54,10 +50,8 @@ def test_shorter_copyright(self) -> None: node = parse(comment) with self.assertAddsMessages( MessageTest( - msg_id='wrong-or-nonexistent-copyright-notice', - line=1, - col_offset=len(comment), - ), + msg_id='wrong-or-nonexistent-copyright-notice', line=1, col_offset=len(comment) + ) ): self.checker.process_module(node) @@ -70,7 +64,7 @@ def test_longer_copyright(self) -> None: msg_id='wrong-or-nonexistent-copyright-notice', line=1, col_offset=comment.index(" and extra"), - ), + ) ): self.checker.process_module(node) diff --git a/dev_tools/shell_tools.py b/dev_tools/shell_tools.py index 3c4600e4b0a..96ea50b0eff 100644 --- a/dev_tools/shell_tools.py +++ b/dev_tools/shell_tools.py @@ -15,26 +15,12 @@ import asyncio import subprocess import sys -from typing import ( - List, - Optional, - Tuple, - Union, - IO, - Any, - cast, - NamedTuple, -) +from typing import List, Optional, Tuple, Union, IO, Any, cast, NamedTuple from collections.abc import AsyncIterable CommandOutput = NamedTuple( - "CommandOutput", - [ - ('out', Optional[str]), - ('err', Optional[str]), - ('exit_code', int), - ], + "CommandOutput", [('out', Optional[str]), ('err', Optional[str]), ('exit_code', int)] ) @@ -56,11 +42,7 @@ def highlight(text: str, color_code: int, bold: bool = False) -> str: Returns: The highlighted string. """ - return '{}\033[{}m{}\033[0m'.format( - '\033[1m' if bold else '', - color_code, - text, - ) + return '{}\033[{}m{}\033[0m'.format('\033[1m' if bold else '', color_code, text) class TeeCapture: diff --git a/dev_tools/shell_tools_test.py b/dev_tools/shell_tools_test.py index 8b9d6b2fb7c..1dace4eae79 100644 --- a/dev_tools/shell_tools_test.py +++ b/dev_tools/shell_tools_test.py @@ -64,17 +64,14 @@ def test_run_shell_capture(): @only_on_posix def test_run_shell_does_not_deadlock_on_large_outputs(): - assert ( - run_shell( - r"""python3 -c "import sys;""" - r"""print((('o' * 99) + '\n') * 10000);""" - r"""print((('e' * 99) + '\n') * 10000, file=sys.stderr)""" - '"', - out=None, - err=None, - ) - == (None, None, 0) - ) + assert run_shell( + r"""python3 -c "import sys;""" + r"""print((('o' * 99) + '\n') * 10000);""" + r"""print((('e' * 99) + '\n') * 10000, file=sys.stderr)""" + '"', + out=None, + err=None, + ) == (None, None, 0) @only_on_posix diff --git a/examples/advanced/quantum_volume_test.py b/examples/advanced/quantum_volume_test.py index 00257d33010..c5ae7ad9b86 100644 --- a/examples/advanced/quantum_volume_test.py +++ b/examples/advanced/quantum_volume_test.py @@ -17,10 +17,4 @@ def test_parse_args(): """Test that an argument string is parsed correctly.""" args = ('--num_qubits 5 --depth 5 --num_circuits 200 --seed 1234').split() kwargs = quantum_volume.parse_arguments(args) - assert kwargs == { - 'num_qubits': 5, - 'depth': 5, - 'num_circuits': 200, - 'seed': 1234, - 'routes': 30, - } + assert kwargs == {'num_qubits': 5, 'depth': 5, 'num_circuits': 200, 'seed': 1234, 'routes': 30} diff --git a/examples/bcs_mean_field.py b/examples/bcs_mean_field.py index d3e4f429dff..227dfbe1e7e 100644 --- a/examples/bcs_mean_field.py +++ b/examples/bcs_mean_field.py @@ -324,13 +324,13 @@ def _bcs_gap(x): s = 0.0 for i in range(n_site): - s += 1.0 / np.sqrt(hop_erg[i] ** 2 + x ** 2) + s += 1.0 / np.sqrt(hop_erg[i] ** 2 + x**2) return 1 + s * u / (2 * n_site) # Superconducting gap delta = scipy.optimize.bisect(_bcs_gap, 0.01, 10000.0 * abs(u)) # The amplitude of the double excitation state - bcs_v = np.sqrt(0.5 * (1 - hop_erg / np.sqrt(hop_erg ** 2 + delta ** 2))) + bcs_v = np.sqrt(0.5 * (1 - hop_erg / np.sqrt(hop_erg**2 + delta**2))) # The rotational angle in the Bogoliubov transformation. bog_theta = np.arcsin(bcs_v) diff --git a/examples/bell_inequality.py b/examples/bell_inequality.py index 4807d4829bd..de9bee88fbf 100644 --- a/examples/bell_inequality.py +++ b/examples/bell_inequality.py @@ -105,20 +105,10 @@ def make_bell_test_circuit(): circuit = cirq.Circuit() # Prepare shared entangled state. - circuit.append( - [ - cirq.H(alice), - cirq.CNOT(alice, bob), - ] - ) + circuit.append([cirq.H(alice), cirq.CNOT(alice, bob)]) # Referees flip coins. - circuit.append( - [ - cirq.H(alice_referee), - cirq.H(bob_referee), - ] - ) + circuit.append([cirq.H(alice_referee), cirq.H(bob_referee)]) # Players do a sqrt(X) based on their referee's coin. circuit.append( diff --git a/examples/bernstein_vazirani.py b/examples/bernstein_vazirani.py index ec29e194afa..2990b1df73c 100644 --- a/examples/bernstein_vazirani.py +++ b/examples/bernstein_vazirani.py @@ -98,13 +98,7 @@ def make_bernstein_vazirani_circuit(input_qubits, output_qubit, oracle): c = cirq.Circuit() # Initialize qubits. - c.append( - [ - cirq.X(output_qubit), - cirq.H(output_qubit), - cirq.H.on_each(*input_qubits), - ] - ) + c.append([cirq.X(output_qubit), cirq.H(output_qubit), cirq.H.on_each(*input_qubits)]) # Query oracle. c.append(oracle) diff --git a/examples/direct_fidelity_estimation.py b/examples/direct_fidelity_estimation.py index 518481e515c..20085320be0 100644 --- a/examples/direct_fidelity_estimation.py +++ b/examples/direct_fidelity_estimation.py @@ -52,12 +52,10 @@ def build_circuit() -> Tuple[cirq.Circuit, List[cirq.Qid]]: def compute_characteristic_function( - pauli_string: cirq.PauliString, - qubits: List[cirq.Qid], - density_matrix: np.ndarray, + pauli_string: cirq.PauliString, qubits: List[cirq.Qid], density_matrix: np.ndarray ): n_qubits = len(qubits) - d = 2 ** n_qubits + d = 2**n_qubits qubit_map = dict(zip(qubits, range(n_qubits))) # rho_i or sigma_i in https://arxiv.org/abs/1104.3835 @@ -194,7 +192,7 @@ def _estimate_pauli_traces_clifford( # Pauli states more efficiently as described on page 4 of: # https://arxiv.org/abs/1104.4695 - d = 2 ** n_qubits + d = 2**n_qubits if n_measured_operators is not None: dense_pauli_strings = _randomly_sample_from_stabilizer_bases( @@ -203,7 +201,7 @@ def _estimate_pauli_traces_clifford( assert len(dense_pauli_strings) == n_measured_operators else: dense_pauli_strings = _enumerate_all_from_stabilizer_bases(stabilizer_basis, n_qubits) - assert len(dense_pauli_strings) == 2 ** n_qubits + assert len(dense_pauli_strings) == 2**n_qubits pauli_traces: List[PauliTrace] = [] for dense_pauli_string in dense_pauli_strings: diff --git a/examples/direct_fidelity_estimation_test.py b/examples/direct_fidelity_estimation_test.py index ebd97cbec92..a597ef5b724 100644 --- a/examples/direct_fidelity_estimation_test.py +++ b/examples/direct_fidelity_estimation_test.py @@ -91,14 +91,9 @@ def test_same_pauli_traces_clifford(): n_qubits = 4 qubits = cirq.LineQubit.range(n_qubits) - circuit_clifford = cirq.Circuit( - cirq.X(qubits[3]), - ) + circuit_clifford = cirq.Circuit(cirq.X(qubits[3])) - circuit_general = cirq.Circuit( - cirq.CCX(qubits[0], qubits[1], qubits[2]), - circuit_clifford, - ) + circuit_general = cirq.Circuit(cirq.CCX(qubits[0], qubits[1], qubits[2]), circuit_clifford) def _run_dfe(circuit): class NoiseOnLastQubitOnly(cirq.NoiseModel): @@ -132,7 +127,7 @@ def noisy_moment(self, moment, system_qubits): assert clifford_is_clifford assert not general_is_clifford - assert len(pauli_traces_clifford) == 2 ** n_qubits + assert len(pauli_traces_clifford) == 2**n_qubits for pauli_trace_clifford in pauli_traces_clifford: pauli_trace_general = [x for x in pauli_traces_general if x.P_i == pauli_trace_clifford.P_i] assert len(pauli_trace_general) == 1 diff --git a/examples/examples_test.py b/examples/examples_test.py index f466c504735..641c383ee51 100644 --- a/examples/examples_test.py +++ b/examples/examples_test.py @@ -267,7 +267,7 @@ def test_example_shor_find_factor_with_prime_n(n, order_finder): assert d is None -@pytest.mark.parametrize('n', (2, 3, 15, 17, 2 ** 89 - 1)) +@pytest.mark.parametrize('n', (2, 3, 15, 17, 2**89 - 1)) def test_example_runs_shor_valid(n): examples.shor.main(n=n) diff --git a/examples/grover.py b/examples/grover.py index 99f2bf5dce2..d2ab5128d85 100644 --- a/examples/grover.py +++ b/examples/grover.py @@ -55,13 +55,7 @@ def make_grover_circuit(input_qubits, output_qubit, oracle): c = cirq.Circuit() # Initialize qubits. - c.append( - [ - cirq.X(output_qubit), - cirq.H(output_qubit), - cirq.H.on_each(*input_qubits), - ] - ) + c.append([cirq.X(output_qubit), cirq.H(output_qubit), cirq.H.on_each(*input_qubits)]) # Query oracle. c.append(oracle) diff --git a/examples/hidden_shift_algorithm.py b/examples/hidden_shift_algorithm.py index 35ab35316d5..74d9cc2c4a8 100644 --- a/examples/hidden_shift_algorithm.py +++ b/examples/hidden_shift_algorithm.py @@ -97,11 +97,7 @@ def make_hs_circuit(qubits, oracle_f, shift): c = cirq.Circuit() # Initialize qubits. - c.append( - [ - cirq.H.on_each(*qubits), - ] - ) + c.append([cirq.H.on_each(*qubits)]) # Query oracle g: It is equivalent to that of f, shifted before and after: # Apply Shift: @@ -114,21 +110,13 @@ def make_hs_circuit(qubits, oracle_f, shift): c.append([cirq.X.on_each([qubits[k] for k in range(len(shift)) if shift[k]])]) # Second Application of Hadamards. - c.append( - [ - cirq.H.on_each(*qubits), - ] - ) + c.append([cirq.H.on_each(*qubits)]) # Query oracle f (this simplifies the phase). c.append(oracle_f) # Inverse Fourier Transform with Hadamards to go back to the shift state: - c.append( - [ - cirq.H.on_each(*qubits), - ] - ) + c.append([cirq.H.on_each(*qubits)]) # Measure the result. c.append(cirq.measure(*qubits, key='result')) diff --git a/examples/noisy_simulation_example.py b/examples/noisy_simulation_example.py index c92f3cfa1e7..1fdc5250077 100644 --- a/examples/noisy_simulation_example.py +++ b/examples/noisy_simulation_example.py @@ -7,9 +7,7 @@ def noisy_circuit_demo(amplitude_damp): """Demonstrates a noisy circuit simulation.""" q = cirq.NamedQubit('q') circuit = cirq.Circuit( - cirq.measure(q, key='initial_state'), - cirq.X(q), - cirq.measure(q, key='after_not_gate'), + cirq.measure(q, key='initial_state'), cirq.X(q), cirq.measure(q, key='after_not_gate') ) results = cirq.sample( program=circuit, diff --git a/examples/phase_estimator.py b/examples/phase_estimator.py index 7d4a4ee16e8..0076c57fdb6 100644 --- a/examples/phase_estimator.py +++ b/examples/phase_estimator.py @@ -44,7 +44,7 @@ def run_estimate(unknown_gate, qnum, repetitions): qubits = cirq.LineQubit.range(qnum) oracle_raised_to_power = [ - unknown_gate.on(ancilla).controlled_by(qubits[i]) ** (2 ** i) for i in range(qnum) + unknown_gate.on(ancilla).controlled_by(qubits[i]) ** (2**i) for i in range(qnum) ] circuit = cirq.Circuit( cirq.H.on_each(*qubits), @@ -74,7 +74,7 @@ def example_gate(phi): for target in np.arange(0, 1, 0.1): result = run_estimate(example_gate(target), qnum, repetitions) mode = result.data['phase'].mode()[0] - guess = mode / 2 ** qnum + guess = mode / 2**qnum print(f'target={target:0.4f}, estimate={guess:0.4f}={mode}/{2**qnum}') errors.append((target - guess) ** 2) rms = np.sqrt(sum(errors) / len(errors)) diff --git a/examples/shor.py b/examples/shor.py index e0624242425..50283ff1c4d 100644 --- a/examples/shor.py +++ b/examples/shor.py @@ -147,10 +147,7 @@ def __init__( def registers(self) -> Sequence[Union[int, Sequence[cirq.Qid]]]: return self.target, self.exponent, self.base, self.modulus - def with_registers( - self, - *new_registers: Union[int, Sequence['cirq.Qid']], - ) -> 'ModularExp': + def with_registers(self, *new_registers: Union[int, Sequence['cirq.Qid']]) -> 'ModularExp': if len(new_registers) != 4: raise ValueError( f'Expected 4 registers (target, exponent, base, ' @@ -170,12 +167,9 @@ def apply(self, *register_values: int) -> int: target, exponent, base, modulus = register_values if target >= modulus: return target - return (target * base ** exponent) % modulus + return (target * base**exponent) % modulus - def _circuit_diagram_info_( - self, - args: cirq.CircuitDiagramInfoArgs, - ) -> cirq.CircuitDiagramInfo: + def _circuit_diagram_info_(self, args: cirq.CircuitDiagramInfoArgs) -> cirq.CircuitDiagramInfo: assert args.known_qubits is not None wire_symbols: List[str] = [] t, e = 0, 0 @@ -256,7 +250,7 @@ def read_eigenphase(result: cirq.Result) -> float: """ exponent_as_integer = result.data['exponent'][0] exponent_num_bits = result.measurements['exponent'].shape[1] - return float(exponent_as_integer / 2 ** exponent_num_bits) + return float(exponent_as_integer / 2**exponent_num_bits) def quantum_order_finder(x: int, n: int) -> Optional[int]: @@ -287,7 +281,7 @@ def quantum_order_finder(x: int, n: int) -> Optional[int]: if f.numerator == 0: return None # coverage: ignore r = f.denominator - if x ** r % n != 1: + if x**r % n != 1: return None # coverage: ignore return r @@ -297,10 +291,10 @@ def find_factor_of_prime_power(n: int) -> Optional[int]: for k in range(2, math.floor(math.log2(n)) + 1): c = math.pow(n, 1 / k) c1 = math.floor(c) - if c1 ** k == n: + if c1**k == n: return c1 c2 = math.ceil(c) - if c2 ** k == n: + if c2**k == n: return c2 return None @@ -346,10 +340,7 @@ def find_factor( return None # coverage: ignore -def main( - n: int, - order_finder: Callable[[int, int], Optional[int]] = naive_order_finder, -): +def main(n: int, order_finder: Callable[[int, int], Optional[int]] = naive_order_finder): if n < 2: raise ValueError(f'Invalid input {n}, expected positive integer greater than one.') @@ -366,9 +357,6 @@ def main( if __name__ == '__main__': # coverage: ignore - ORDER_FINDERS = { - 'naive': naive_order_finder, - 'quantum': quantum_order_finder, - } + ORDER_FINDERS = {'naive': naive_order_finder, 'quantum': quantum_order_finder} args = parser.parse_args() main(n=args.n, order_finder=ORDER_FINDERS[args.order_finder]) diff --git a/examples/simon_algorithm.py b/examples/simon_algorithm.py index 718cae4c067..aadcbffcb17 100644 --- a/examples/simon_algorithm.py +++ b/examples/simon_algorithm.py @@ -129,11 +129,7 @@ def make_simon_circuit(input_qubits, output_qubits, oracle): c = cirq.Circuit() # Initialize qubits. - c.append( - [ - cirq.H.on_each(*input_qubits), - ] - ) + c.append([cirq.H.on_each(*input_qubits)]) # Query oracle. c.append(oracle) diff --git a/examples/stabilizer_code_test.py b/examples/stabilizer_code_test.py index c6d1f92bb8c..ddd28e2b71a 100644 --- a/examples/stabilizer_code_test.py +++ b/examples/stabilizer_code_test.py @@ -17,13 +17,9 @@ def encode_corrupt_correct( ): circuit = cirq.Circuit() additional_qubits: List[cirq.Qid] = cast( - List[cirq.Qid], - [cirq.NamedQubit(str(i)) for i in range(code.n - code.k)], - ) - unencoded_qubits: List[cirq.Qid] = cast( - List[cirq.Qid], - [cirq.NamedQubit('c')], + List[cirq.Qid], [cirq.NamedQubit(str(i)) for i in range(code.n - code.k)] ) + unencoded_qubits: List[cirq.Qid] = cast(List[cirq.Qid], [cirq.NamedQubit('c')]) qubits = additional_qubits + unencoded_qubits ancillas: List[cirq.Qid] = cast( List[cirq.Qid], [cirq.NamedQubit(f"d{i}") for i in range(code.n - code.k)] diff --git a/examples/swap_networks.py b/examples/swap_networks.py index 1391f348135..71c1c7cf90b 100644 --- a/examples/swap_networks.py +++ b/examples/swap_networks.py @@ -120,7 +120,7 @@ def get_max_cut_qaoa_circuit( n_vertices = len(vertices) # G_{i,j} ∝ exp(i gamma (|01><01| + |10><10|)) - phase_sep_gates: LogicalMapping = {edge: cirq.ZZ ** gamma for edge in edges} + phase_sep_gates: LogicalMapping = {edge: cirq.ZZ**gamma for edge in edges} # Physical qubits qubits = cirq.LineQubit.range(n_vertices) diff --git a/rtd_docs/conf.py b/rtd_docs/conf.py index ecdb6981c56..e2445235700 100644 --- a/rtd_docs/conf.py +++ b/rtd_docs/conf.py @@ -38,10 +38,7 @@ # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. -extensions = [ - 'myst_parser', - 'notfound.extension', -] +extensions = ['myst_parser', 'notfound.extension'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] @@ -51,10 +48,7 @@ # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # -source_suffix = { - '.rst': 'restructuredtext', - '.md': 'markdown', -} +source_suffix = {'.rst': 'restructuredtext', '.md': 'markdown'} # The master toctree document. master_doc = 'index' @@ -69,10 +63,7 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path . -exclude_patterns = [ - 'Thumbs.db', - '.DS_Store', -] +exclude_patterns = ['Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' diff --git a/setup.py b/setup.py index 00898f147bd..05907cad8c9 100644 --- a/setup.py +++ b/setup.py @@ -66,9 +66,7 @@ author_email='cirq-dev@googlegroups.com', python_requires='>=3.6.0', install_requires=requirements, - extras_require={ - 'dev_env': dev_requirements, - }, + extras_require={'dev_env': dev_requirements}, license='Apache 2', description=description, long_description=long_description,