diff --git a/cirq-google/cirq_google/__init__.py b/cirq-google/cirq_google/__init__.py index c253ac20c1c..04c0f23119f 100644 --- a/cirq-google/cirq_google/__init__.py +++ b/cirq-google/cirq_google/__init__.py @@ -18,9 +18,7 @@ from cirq import _compat from cirq_google import api -from cirq_google._version import ( - __version__, -) +from cirq_google._version import __version__ from cirq_google.calibration import ( ALL_ANGLES_FLOQUET_PHASED_FSIM_CHARACTERIZATION, @@ -89,13 +87,7 @@ LinePlacementStrategy, ) -from cirq_google.ops import ( - CalibrationTag, - FSimGateFamily, - PhysicalZTag, - SycamoreGate, - SYC, -) +from cirq_google.ops import CalibrationTag, FSimGateFamily, PhysicalZTag, SycamoreGate, SYC from cirq_google.optimizers import ( ConvertToXmonGates, diff --git a/cirq-google/cirq_google/calibration/__init__.py b/cirq-google/cirq_google/calibration/__init__.py index 60c7b39e93f..92b4ff40976 100644 --- a/cirq-google/cirq_google/calibration/__init__.py +++ b/cirq-google/cirq_google/calibration/__init__.py @@ -12,9 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from cirq_google.calibration.engine_simulator import ( - PhasedFSimEngineSimulator, -) +from cirq_google.calibration.engine_simulator import PhasedFSimEngineSimulator from cirq_google.calibration.phased_fsim import ( ALL_ANGLES_FLOQUET_PHASED_FSIM_CHARACTERIZATION, diff --git a/cirq-google/cirq_google/calibration/engine_simulator.py b/cirq-google/cirq_google/calibration/engine_simulator.py index 72b41e4fc7c..bc6708df676 100644 --- a/cirq-google/cirq_google/calibration/engine_simulator.py +++ b/cirq-google/cirq_google/calibration/engine_simulator.py @@ -1,16 +1,5 @@ # pylint: disable=wrong-or-nonexistent-copyright-notice -from typing import ( - Any, - Callable, - Dict, - Iterable, - Iterator, - List, - Optional, - Sequence, - Tuple, - Union, -) +from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, Sequence, Tuple, Union import numpy as np @@ -75,9 +64,7 @@ def __init__( @classmethod def create_with_ideal_sqrt_iswap( - cls, - *, - simulator: Optional[cirq.Simulator] = None, + cls, *, simulator: Optional[cirq.Simulator] = None ) -> 'PhasedFSimEngineSimulator': """Creates a PhasedFSimEngineSimulator that simulates ideal FSimGate(theta=π/4, phi=0). @@ -452,10 +439,7 @@ def create_gate_with_drift( return gate_calibration.as_characterized_phased_fsim_gate(parameters) 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]: converted = _convert_to_circuit_with_drift(self, program) yield from self._simulator.run_sweep_iter(converted, params, repetitions) @@ -479,10 +463,7 @@ def _create_partial_act_on_args( # Needs an implementation since it's abstract but will never actually be called. raise NotImplementedError() - def _create_step_result( - self, - sim_state: cirq.OperationTarget, - ) -> cirq.SparseSimulatorStep: + def _create_step_result(self, sim_state: cirq.OperationTarget) -> cirq.SparseSimulatorStep: # Needs an implementation since it's abstract but will never actually be called. raise NotImplementedError() diff --git a/cirq-google/cirq_google/calibration/engine_simulator_test.py b/cirq-google/cirq_google/calibration/engine_simulator_test.py index fb61e756d15..2058bc26dc7 100644 --- a/cirq-google/cirq_google/calibration/engine_simulator_test.py +++ b/cirq-google/cirq_google/calibration/engine_simulator_test.py @@ -346,7 +346,7 @@ def test_from_dictionary_sqrt_iswap_ideal_when_missing_parameter_fails(): circuit = cirq.Circuit(cirq.FSimGate(np.pi / 4, 0.0).on(a, b)) engine_simulator = PhasedFSimEngineSimulator.create_from_dictionary_sqrt_iswap( - parameters={(a, b): parameters_ab}, + parameters={(a, b): parameters_ab} ) with pytest.raises(ValueError): diff --git a/cirq-google/cirq_google/calibration/phased_fsim.py b/cirq-google/cirq_google/calibration/phased_fsim.py index f62393adbcb..fee33b727db 100644 --- a/cirq-google/cirq_google/calibration/phased_fsim.py +++ b/cirq-google/cirq_google/calibration/phased_fsim.py @@ -37,9 +37,7 @@ import pandas as pd import cirq -from cirq.experiments.xeb_fitting import ( - XEBPhasedFSimCharacterizationOptions, -) +from cirq.experiments.xeb_fitting import XEBPhasedFSimCharacterizationOptions from cirq_google.api import v2 from cirq_google.engine import Calibration, CalibrationLayer, CalibrationResult, Engine, EngineJob from cirq_google.ops import FSimGateFamily @@ -211,9 +209,7 @@ class PhasedFSimCalibrationOptions(abc.ABC, Generic[RequestT]): @abc.abstractmethod def create_phased_fsim_request( - self, - pairs: Tuple[Tuple[cirq.Qid, cirq.Qid], ...], - gate: cirq.Gate, + self, pairs: Tuple[Tuple[cirq.Qid, cirq.Qid], ...], gate: cirq.Gate ) -> RequestT: """Create a PhasedFSimCalibrationRequest of the correct type for these options. @@ -304,8 +300,7 @@ def engine_calibration(self) -> Optional[Calibration]: @classmethod def _create_parameters_dict( - cls, - parameters: List[Tuple[cirq.Qid, cirq.Qid, PhasedFSimCharacterization]], + cls, parameters: List[Tuple[cirq.Qid, cirq.Qid, PhasedFSimCharacterization]] ) -> Dict[Tuple[cirq.Qid, cirq.Qid], PhasedFSimCharacterization]: """Utility function to create parameters from JSON. @@ -314,10 +309,7 @@ def _create_parameters_dict( return {(q_a, q_b): params for q_a, q_b, params in parameters} @classmethod - def _from_json_dict_( - cls, - **kwargs, - ) -> 'PhasedFSimCalibrationResult': + def _from_json_dict_(cls, **kwargs) -> 'PhasedFSimCalibrationResult': """Magic method for the JSON serialization protocol. Converts serialized dictionary into a dict suitable for @@ -482,9 +474,7 @@ def to_args(self) -> Dict[str, Any]: return args def create_phased_fsim_request( - self, - pairs: Tuple[Tuple[cirq.Qid, cirq.Qid], ...], - gate: cirq.Gate, + self, pairs: Tuple[Tuple[cirq.Qid, cirq.Qid], ...], gate: cirq.Gate ) -> 'XEBPhasedFSimCalibrationRequest': return XEBPhasedFSimCalibrationRequest(pairs=pairs, gate=gate, options=self) @@ -537,9 +527,7 @@ class LocalXEBPhasedFSimCalibrationOptions(XEBPhasedFSimCalibrationOptions): n_processes: Optional[int] = None def create_phased_fsim_request( - self, - pairs: Tuple[Tuple[cirq.Qid, cirq.Qid], ...], - gate: cirq.Gate, + self, pairs: Tuple[Tuple[cirq.Qid, cirq.Qid], ...], gate: cirq.Gate ): return LocalXEBPhasedFSimCalibrationRequest(pairs=pairs, gate=gate, options=self) @@ -588,9 +576,7 @@ def zeta_chi_gamma_correction_override(self) -> PhasedFSimCharacterization: ) def create_phased_fsim_request( - self, - pairs: Tuple[Tuple[cirq.Qid, cirq.Qid], ...], - gate: cirq.Gate, + self, pairs: Tuple[Tuple[cirq.Qid, cirq.Qid], ...], gate: cirq.Gate ) -> 'FloquetPhasedFSimCalibrationRequest': return FloquetPhasedFSimCalibrationRequest(pairs=pairs, gate=gate, options=self) @@ -693,9 +679,7 @@ def to_calibration_layer(self) -> CalibrationLayer: self.options.readout_error_tolerance ) return CalibrationLayer( - calibration_type=_FLOQUET_PHASED_FSIM_HANDLER_NAME, - program=circuit, - args=args, + calibration_type=_FLOQUET_PHASED_FSIM_HANDLER_NAME, program=circuit, args=args ) def parse_result( @@ -803,8 +787,7 @@ def _parse_xeb_fidelities_df(metrics: 'cirq_google.Calibration', super_name: str def _parse_characterized_angles( - metrics: 'cirq_google.Calibration', - super_name: str, + metrics: 'cirq_google.Calibration', super_name: str ) -> Dict[Tuple[cirq.Qid, cirq.Qid], Dict[str, float]]: """Parses characterized angles from Metric protos. @@ -1088,9 +1071,7 @@ def try_convert_gate_to_fsim(gate: cirq.Gate) -> Optional[PhaseCalibratedFSimGat return PhaseCalibratedFSimGate(cirq.FSimGate(theta=theta, phi=phi), phase_exponent) -def try_convert_syc_or_sqrt_iswap_to_fsim( - gate: cirq.Gate, -) -> Optional[PhaseCalibratedFSimGate]: +def try_convert_syc_or_sqrt_iswap_to_fsim(gate: cirq.Gate) -> Optional[PhaseCalibratedFSimGate]: """Converts a gate to equivalent PhaseCalibratedFSimGate if possible. Args: diff --git a/cirq-google/cirq_google/calibration/phased_fsim_test.py b/cirq-google/cirq_google/calibration/phased_fsim_test.py index 49848ace1e7..c893877c35d 100644 --- a/cirq-google/cirq_google/calibration/phased_fsim_test.py +++ b/cirq-google/cirq_google/calibration/phased_fsim_test.py @@ -206,9 +206,7 @@ def test_floquet_to_calibration_layer_with_measure_qubits(): assert request.to_calibration_layer() == cirq_google.CalibrationLayer( calibration_type='floquet_phased_fsim_characterization', - program=cirq.Circuit( - [gate.on(q_00, q_01), gate.on(q_02, q_03), cirq.measure(*qubits)], - ), + program=cirq.Circuit([gate.on(q_00, q_01), gate.on(q_02, q_03), cirq.measure(*qubits)]), args={ 'est_theta': True, 'est_zeta': True, @@ -459,7 +457,7 @@ def test_xeb_parse_bad_fidelities(): metrics = cirq_google.Calibration( metrics={ 'initial_fidelities_depth_5': { - ('layer_0', 'pair_0', cirq.GridQubit(0, 0), cirq.GridQubit(1, 1)): [1.0], + ('layer_0', 'pair_0', cirq.GridQubit(0, 0), cirq.GridQubit(1, 1)): [1.0] } } ) @@ -478,21 +476,13 @@ def test_xeb_parse_bad_fidelities(): ) metrics = cirq_google.Calibration( - metrics={ - 'initial_fidelities_depth_5x': { - ('layer_0', 'pair_0', '0_0', '1_1'): [1.0], - } - } + metrics={'initial_fidelities_depth_5x': {('layer_0', 'pair_0', '0_0', '1_1'): [1.0]}} ) df = _parse_xeb_fidelities_df(metrics, 'initial_fidelities') assert len(df) == 0, 'bad metric name ignored' metrics = cirq_google.Calibration( - metrics={ - 'initial_fidelities_depth_5': { - ('bad_name_0', 'pair_0', '0_0', '1_1'): [1.0], - } - } + metrics={'initial_fidelities_depth_5': {('bad_name_0', 'pair_0', '0_0', '1_1'): [1.0]}} ) with pytest.raises(ValueError, match=r'Could not parse layer value for bad_name_0'): _parse_xeb_fidelities_df(metrics, 'initial_fidelities') @@ -589,12 +579,8 @@ def test_floquet_parse_result_bad_metric(): metrics=[ cirq_google.api.v2.metrics_pb2.Metric( name='angles', - targets=[ - '1000gerbils', - ], - values=[ - cirq_google.api.v2.metrics_pb2.Value(str_val='100_10'), - ], + targets=['1000gerbils'], + values=[cirq_google.api.v2.metrics_pb2.Value(str_val='100_10')], ) ] ) @@ -642,33 +628,19 @@ def test_merge_matching_results(): gate = cirq.FSimGate(theta=np.pi / 4, phi=0.0) options = WITHOUT_CHI_FLOQUET_PHASED_FSIM_CHARACTERIZATION parameters_1 = { - (q_00, q_01): PhasedFSimCharacterization( - theta=0.1, zeta=0.2, chi=None, gamma=None, phi=0.3 - ), + (q_00, q_01): PhasedFSimCharacterization(theta=0.1, zeta=0.2, chi=None, gamma=None, phi=0.3) } parameters_2 = { - (q_02, q_03): PhasedFSimCharacterization( - theta=0.4, zeta=0.5, chi=None, gamma=None, phi=0.6 - ), + (q_02, q_03): PhasedFSimCharacterization(theta=0.4, zeta=0.5, chi=None, gamma=None, phi=0.6) } results = [ - PhasedFSimCalibrationResult( - parameters=parameters_1, - gate=gate, - options=options, - ), - PhasedFSimCalibrationResult( - parameters=parameters_2, - gate=gate, - options=options, - ), + PhasedFSimCalibrationResult(parameters=parameters_1, gate=gate, options=options), + PhasedFSimCalibrationResult(parameters=parameters_2, gate=gate, options=options), ] assert merge_matching_results(results) == PhasedFSimCalibrationResult( - parameters={**parameters_1, **parameters_2}, - gate=gate, - options=options, + parameters={**parameters_1, **parameters_2}, gate=gate, options=options ) @@ -681,53 +653,29 @@ def test_merge_matching_results_when_incompatible_fails(): gate = cirq.FSimGate(theta=np.pi / 4, phi=0.0) options = WITHOUT_CHI_FLOQUET_PHASED_FSIM_CHARACTERIZATION parameters_1 = { - (q_00, q_01): PhasedFSimCharacterization( - theta=0.1, zeta=0.2, chi=None, gamma=None, phi=0.3 - ), + (q_00, q_01): PhasedFSimCharacterization(theta=0.1, zeta=0.2, chi=None, gamma=None, phi=0.3) } parameters_2 = { - (q_02, q_03): PhasedFSimCharacterization( - theta=0.4, zeta=0.5, chi=None, gamma=None, phi=0.6 - ), + (q_02, q_03): PhasedFSimCharacterization(theta=0.4, zeta=0.5, chi=None, gamma=None, phi=0.6) } with pytest.raises(ValueError): results = [ - PhasedFSimCalibrationResult( - parameters=parameters_1, - gate=gate, - options=options, - ), - PhasedFSimCalibrationResult( - parameters=parameters_1, - gate=gate, - options=options, - ), + PhasedFSimCalibrationResult(parameters=parameters_1, gate=gate, options=options), + PhasedFSimCalibrationResult(parameters=parameters_1, gate=gate, options=options), ] assert merge_matching_results(results) with pytest.raises(ValueError): results = [ - PhasedFSimCalibrationResult( - parameters=parameters_1, - gate=gate, - options=options, - ), - PhasedFSimCalibrationResult( - parameters=parameters_2, - gate=cirq.CZ, - options=options, - ), + PhasedFSimCalibrationResult(parameters=parameters_1, gate=gate, options=options), + PhasedFSimCalibrationResult(parameters=parameters_2, gate=cirq.CZ, options=options), ] assert merge_matching_results(results) with pytest.raises(ValueError): results = [ - PhasedFSimCalibrationResult( - parameters=parameters_1, - gate=gate, - options=options, - ), + PhasedFSimCalibrationResult(parameters=parameters_1, gate=gate, options=options), PhasedFSimCalibrationResult( parameters=parameters_2, gate=gate, diff --git a/cirq-google/cirq_google/calibration/workflow.py b/cirq-google/cirq_google/calibration/workflow.py index 5ba99f102c8..fb793fa5f9a 100644 --- a/cirq-google/cirq_google/calibration/workflow.py +++ b/cirq-google/cirq_google/calibration/workflow.py @@ -13,18 +13,7 @@ # limitations under the License. import dataclasses import itertools -from typing import ( - Callable, - Dict, - Iterable, - List, - Optional, - Sequence, - Set, - Tuple, - Union, - cast, -) +from typing import Callable, Dict, Iterable, List, Optional, Sequence, Set, Tuple, Union, cast import cirq from cirq.experiments import HALF_GRID_STAGGERED_PATTERN @@ -729,8 +718,7 @@ def _merge_into_calibrations( ) ): calibrations[index] = options.create_phased_fsim_request( - gate=calibration.gate, - pairs=tuple(sorted(new_pairs.union(existing_pairs))), + gate=calibration.gate, pairs=tuple(sorted(new_pairs.union(existing_pairs))) ) return index @@ -774,8 +762,7 @@ def _run_calibrations_via_engine( def _run_local_calibrations_via_sampler( - calibration_requests: Sequence[PhasedFSimCalibrationRequest], - sampler: cirq.Sampler, + calibration_requests: Sequence[PhasedFSimCalibrationRequest], sampler: cirq.Sampler ): """Helper function used by `run_calibrations` to run Local calibrations with a Sampler.""" return [ @@ -854,11 +841,7 @@ def run_calibrations( return _run_local_calibrations_via_sampler(calibrations, engine_sampler) return _run_calibrations_via_engine( - calibrations, - engine, - processor_id, - max_layers_per_request, - progress_func, + calibrations, engine, processor_id, max_layers_per_request, progress_func ) if calibration_request_type == LocalXEBPhasedFSimCalibrationRequest: @@ -1122,10 +1105,7 @@ def _find_moment_zeta_chi_gamma_corrections( pair_parameters = pair_parameters.merge_with(default_phases) corrections = FSimPhaseCorrections.from_characterization( - (a, b), - translated, - pair_parameters, - characterization_index, + (a, b), translated, pair_parameters, characterization_index ) if decompositions_moment_to_calibration is None: diff --git a/cirq-google/cirq_google/calibration/workflow_test.py b/cirq-google/cirq_google/calibration/workflow_test.py index 6c0ffe14e1e..a0163b08432 100644 --- a/cirq-google/cirq_google/calibration/workflow_test.py +++ b/cirq-google/cirq_google/calibration/workflow_test.py @@ -135,9 +135,7 @@ def test_prepare_characterization_for_moment_fails_for_unsupported_gate(options) moment = cirq.Moment(cirq.CZ(a, b)) with pytest.raises(workflow.IncompatibleMomentError): workflow.prepare_characterization_for_moment( - moment, - options, - gates_translator=_fsim_identity_converter, + moment, options, gates_translator=_fsim_identity_converter ) @@ -505,8 +503,7 @@ def test_prepare_floquet_characterization_for_moments_does_not_merge_sub_sets_wh ] ) circuit += cirq.Circuit( - [SQRT_ISWAP_INV_GATE.on(b, c), SQRT_ISWAP_INV_GATE.on(d, e)], - [SQRT_ISWAP_INV_GATE.on(b, c)], + [SQRT_ISWAP_INV_GATE.on(b, c), SQRT_ISWAP_INV_GATE.on(d, e)], [SQRT_ISWAP_INV_GATE.on(b, c)] ) options = WITHOUT_CHI_FLOQUET_PHASED_FSIM_CHARACTERIZATION @@ -554,8 +551,7 @@ def test_prepare_characterization_for_moments_does_not_merge_sub_sets_when_disab ] ) circuit += cirq.Circuit( - [SQRT_ISWAP_INV_GATE.on(b, c), SQRT_ISWAP_INV_GATE.on(d, e)], - [SQRT_ISWAP_INV_GATE.on(b, c)], + [SQRT_ISWAP_INV_GATE.on(b, c), SQRT_ISWAP_INV_GATE.on(d, e)], [SQRT_ISWAP_INV_GATE.on(b, c)] ) circuit_with_calibration, requests = workflow.prepare_characterization_for_moments( @@ -858,13 +854,11 @@ def test_make_zeta_chi_gamma_compensation_for_operations(): ] calibrated_circuit = workflow.make_zeta_chi_gamma_compensation_for_operations( - circuit, - characterizations, + circuit, characterizations ) assert cirq.allclose_up_to_global_phase( - engine_simulator.final_state_vector(calibrated_circuit), - cirq.final_state_vector(circuit), + engine_simulator.final_state_vector(calibrated_circuit), cirq.final_state_vector(circuit) ) @@ -900,10 +894,7 @@ def test_make_zeta_chi_gamma_compensation_for_operations_with_permit_mixed_momen ] with pytest.raises(workflow.IncompatibleMomentError): - workflow.make_zeta_chi_gamma_compensation_for_operations( - circuit, - characterizations, - ) + workflow.make_zeta_chi_gamma_compensation_for_operations(circuit, characterizations) def test_make_zeta_chi_gamma_compensation_for_operations_with_permit_mixed_moments(): @@ -945,14 +936,11 @@ def test_make_zeta_chi_gamma_compensation_for_operations_with_permit_mixed_momen ] calibrated_circuit = workflow.make_zeta_chi_gamma_compensation_for_operations( - circuit, - characterizations, - permit_mixed_moments=True, + circuit, characterizations, permit_mixed_moments=True ) assert cirq.allclose_up_to_global_phase( - engine_simulator.final_state_vector(calibrated_circuit), - cirq.final_state_vector(circuit), + engine_simulator.final_state_vector(calibrated_circuit), cirq.final_state_vector(circuit) ) assert calibrated_circuit[5] == cirq.Moment( [cirq.X(a), SQRT_ISWAP_INV_GATE.on(b, c), cirq.Y(d)] @@ -1166,9 +1154,7 @@ def test_run_calibrations_fails_when_invalid_arguments(): ) request = FloquetPhasedFSimCalibrationRequest( - gate=SQRT_ISWAP_INV_GATE, - pairs=(), - options=WITHOUT_CHI_FLOQUET_PHASED_FSIM_CHARACTERIZATION, + gate=SQRT_ISWAP_INV_GATE, pairs=(), options=WITHOUT_CHI_FLOQUET_PHASED_FSIM_CHARACTERIZATION ) engine = mock.MagicMock(spec=cirq_google.Engine) @@ -1582,8 +1568,7 @@ def test_make_zeta_chi_gamma_compensation_for_moments_imperfect_gates(): ] circuit_with_calibration = workflow.make_zeta_chi_gamma_compensation_for_moments( - circuit, - characterizations, + circuit, characterizations ) assert cirq.allclose_up_to_global_phase( @@ -1623,10 +1608,7 @@ def test_run_zeta_chi_gamma_calibration_for_moments() -> None: ) calibrated_circuit, calibrations = workflow.run_zeta_chi_gamma_compensation_for_moments( - circuit, - engine_simulator, - processor_id=None, - options=options, + circuit, engine_simulator, processor_id=None, options=options ) assert cirq.allclose_up_to_global_phase( @@ -1684,10 +1666,7 @@ def test_run_zeta_chi_gamma_calibration_for_moments_no_chi() -> None: def test_run_local(sampler_engine, monkeypatch): called_times = 0 - def myfunc( - calibration: LocalXEBPhasedFSimCalibrationRequest, - sampler: cirq.Sampler, - ): + def myfunc(calibration: LocalXEBPhasedFSimCalibrationRequest, sampler: cirq.Sampler): nonlocal called_times assert isinstance(calibration, LocalXEBPhasedFSimCalibrationRequest) assert sampler is not None @@ -1697,12 +1676,7 @@ def myfunc( # Note: you must patch specifically the function imported into `workflow`. monkeypatch.setattr('cirq_google.calibration.workflow.run_local_xeb_calibration', myfunc) - qubit_indices = [ - (0, 5), - (0, 6), - (1, 6), - (2, 6), - ] + qubit_indices = [(0, 5), (0, 6), (1, 6), (2, 6)] qubits = [cirq.GridQubit(*idx) for idx in qubit_indices] circuits = [ diff --git a/cirq-google/cirq_google/calibration/xeb_wrapper.py b/cirq-google/cirq_google/calibration/xeb_wrapper.py index 2e13fcddf88..9aa90b118a2 100644 --- a/cirq-google/cirq_google/calibration/xeb_wrapper.py +++ b/cirq-google/cirq_google/calibration/xeb_wrapper.py @@ -43,8 +43,7 @@ def _maybe_multiprocessing_pool( def run_local_xeb_calibration( - calibration: LocalXEBPhasedFSimCalibrationRequest, - sampler: cirq.Sampler, + calibration: LocalXEBPhasedFSimCalibrationRequest, sampler: cirq.Sampler ) -> PhasedFSimCalibrationResult: """Run a calibration request using `cirq.experiments` XEB utilities and a sampler rather than `Engine.run_calibrations`. diff --git a/cirq-google/cirq_google/calibration/xeb_wrapper_test.py b/cirq-google/cirq_google/calibration/xeb_wrapper_test.py index a8674d5f6b0..4a6fe6669ec 100644 --- a/cirq-google/cirq_google/calibration/xeb_wrapper_test.py +++ b/cirq-google/cirq_google/calibration/xeb_wrapper_test.py @@ -107,12 +107,7 @@ def _minimize_patch_2(*args, **kwargs): monkeypatch.setattr( 'cirq_google.calibration.xeb_wrapper.xebf.benchmark_2q_xeb_fidelities', _benchmark_patch ) - qubit_indices = [ - (0, 5), - (0, 6), - (1, 6), - (2, 6), - ] + qubit_indices = [(0, 5), (0, 6), (1, 6), (2, 6)] qubits = [cirq.GridQubit(*idx) for idx in qubit_indices] sampler = cirq.ZerosSampler() @@ -127,10 +122,7 @@ def _minimize_patch_2(*args, **kwargs): for depth in [5, 10] ] - options = LocalXEBPhasedFSimCalibrationOptions( - fsim_options=fsim_options, - n_processes=1, - ) + options = LocalXEBPhasedFSimCalibrationOptions(fsim_options=fsim_options, n_processes=1) characterization_requests = [] for circuit in circuits: diff --git a/cirq-google/cirq_google/devices/__init__.py b/cirq-google/cirq_google/devices/__init__.py index 9746693735a..ac295331171 100644 --- a/cirq-google/cirq_google/devices/__init__.py +++ b/cirq-google/cirq_google/devices/__init__.py @@ -12,17 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -from cirq_google.devices.known_devices import ( - Bristlecone, - Foxtail, - Sycamore, - Sycamore23, -) +from cirq_google.devices.known_devices import Bristlecone, Foxtail, Sycamore, Sycamore23 -from cirq_google.devices.serializable_device import ( - SerializableDevice, -) +from cirq_google.devices.serializable_device import SerializableDevice -from cirq_google.devices.xmon_device import ( - XmonDevice, -) +from cirq_google.devices.xmon_device import XmonDevice diff --git a/cirq-google/cirq_google/devices/google_noise_properties_test.py b/cirq-google/cirq_google/devices/google_noise_properties_test.py index aa627b6ddc6..1f521c13dea 100644 --- a/cirq-google/cirq_google/devices/google_noise_properties_test.py +++ b/cirq-google/cirq_google/devices/google_noise_properties_test.py @@ -22,10 +22,7 @@ SYMMETRIC_TWO_QUBIT_GATES, SINGLE_QUBIT_GATES, ) -from cirq.devices.noise_utils import ( - OpIdentifier, - PHYSICAL_GATE_TAG, -) +from cirq.devices.noise_utils import OpIdentifier, PHYSICAL_GATE_TAG from cirq_google.devices.google_noise_properties import ( GoogleNoiseProperties, diff --git a/cirq-google/cirq_google/devices/known_devices.py b/cirq-google/cirq_google/devices/known_devices.py index 7cae1a4aaf0..f333bd133cc 100644 --- a/cirq-google/cirq_google/devices/known_devices.py +++ b/cirq-google/cirq_google/devices/known_devices.py @@ -210,9 +210,7 @@ def _from_json_dict_(cls, constant: str, **kwargs): raise ValueError(f'Unrecognized xmon device name: {constant!r}') def _json_dict_(self) -> Dict[str, Any]: - return { - 'constant': self._repr, - } + return {'constant': self._repr} Foxtail = _NamedConstantXmonDevice( @@ -308,9 +306,7 @@ def _json_dict_(self) -> Dict[str, Any]: } SYCAMORE_PROTO = create_device_proto_from_diagram( - _SYCAMORE_GRID, - [gate_sets.SQRT_ISWAP_GATESET, gate_sets.SYC_GATESET], - _SYCAMORE_DURATIONS_PICOS, + _SYCAMORE_GRID, [gate_sets.SQRT_ISWAP_GATESET, gate_sets.SYC_GATESET], _SYCAMORE_DURATIONS_PICOS ) Sycamore = SerializableDevice.from_proto( diff --git a/cirq-google/cirq_google/devices/known_devices_test.py b/cirq-google/cirq_google/devices/known_devices_test.py index 9c932c46ea2..f3f79873000 100644 --- a/cirq-google/cirq_google/devices/known_devices_test.py +++ b/cirq-google/cirq_google/devices/known_devices_test.py @@ -467,13 +467,9 @@ def test_multiple_gate_sets(): def test_json_dict_deprecated(): with cirq.testing.assert_deprecated('Foxtail', deadline='v0.15', count=1): - assert cirq_google.Foxtail._json_dict_() == { - 'constant': 'cirq_google.Foxtail', - } + assert cirq_google.Foxtail._json_dict_() == {'constant': 'cirq_google.Foxtail'} with cirq.testing.assert_deprecated('Bristlecone', deadline='v0.15', count=1): - assert cirq_google.Bristlecone._json_dict_() == { - 'constant': 'cirq_google.Bristlecone', - } + assert cirq_google.Bristlecone._json_dict_() == {'constant': 'cirq_google.Bristlecone'} with cirq.testing.assert_deprecated('Constant', deadline='v0.15', count=1): with pytest.raises(ValueError, match='xmon device name'): known_devices._NamedConstantXmonDevice._from_json_dict_('the_unknown_fiddler') @@ -513,19 +509,12 @@ def test_sycamore_circuitop_device(): serializers=[cgc.CIRCUIT_OP_SERIALIZER], deserializers=[cgc.CIRCUIT_OP_DESERIALIZER], ) - gateset_list = [ - cirq_google.SQRT_ISWAP_GATESET, - cirq_google.SYC_GATESET, - circuitop_gateset, - ] + gateset_list = [cirq_google.SQRT_ISWAP_GATESET, cirq_google.SYC_GATESET, circuitop_gateset] circuitop_proto = cirq_google.devices.known_devices.create_device_proto_from_diagram( - known_devices._SYCAMORE23_GRID, - gateset_list, - known_devices._SYCAMORE_DURATIONS_PICOS, + known_devices._SYCAMORE23_GRID, gateset_list, known_devices._SYCAMORE_DURATIONS_PICOS ) device = cirq_google.SerializableDevice.from_proto( - proto=circuitop_proto, - gate_sets=gateset_list, + proto=circuitop_proto, gate_sets=gateset_list ) q0 = cirq.GridQubit(5, 3) q1 = cirq.GridQubit(5, 4) @@ -563,8 +552,7 @@ def test_proto_with_circuitop(): deserializers=[cgc.CIRCUIT_OP_DESERIALIZER], ) circuitop_proto = cirq_google.devices.known_devices.create_device_proto_from_diagram( - "aa\naa", - [circuitop_gateset], + "aa\naa", [circuitop_gateset] ) assert ( @@ -615,8 +603,7 @@ def test_proto_with_waitgate(): deserializers=[cgc.WAIT_GATE_DESERIALIZER], ) wait_proto = cirq_google.devices.known_devices.create_device_proto_from_diagram( - "aa\naa", - [wait_gateset], + "aa\naa", [wait_gateset] ) wait_device = cirq_google.SerializableDevice.from_proto( proto=wait_proto, gate_sets=[wait_gateset] @@ -682,8 +669,7 @@ def test_adding_gates_multiple_times(): ], ) wait_proto = cirq_google.devices.known_devices.create_device_proto_from_diagram( - "aa", - [waiting_for_godot], + "aa", [waiting_for_godot] ) wait_device = cirq_google.SerializableDevice.from_proto( proto=wait_proto, gate_sets=[waiting_for_godot] diff --git a/cirq-google/cirq_google/devices/serializable_device.py b/cirq-google/cirq_google/devices/serializable_device.py index 03e77714c68..8d409fa28bd 100644 --- a/cirq-google/cirq_google/devices/serializable_device.py +++ b/cirq-google/cirq_google/devices/serializable_device.py @@ -13,19 +13,7 @@ # limitations under the License. """Device object for converting from device specification protos""" -from typing import ( - Any, - Callable, - cast, - Dict, - Iterable, - Optional, - List, - Set, - Tuple, - Type, - FrozenSet, -) +from typing import Any, Callable, cast, Dict, Iterable, Optional, List, Set, Tuple, Type, FrozenSet import cirq from cirq import _compat from cirq_google.serialization import serializable_gate_set @@ -92,9 +80,7 @@ class SerializableDevice(cirq.Device): """ def __init__( - self, - qubits: List[cirq.Qid], - gate_definitions: Dict[Type[cirq.Gate], List[_GateDefinition]], + self, qubits: List[cirq.Qid], gate_definitions: Dict[Type[cirq.Gate], List[_GateDefinition]] ): """Constructor for SerializableDevice using python objects. @@ -128,10 +114,7 @@ def metadata(self) -> cirq.GridDeviceMetadata: """Get metadata information for device.""" return self._metadata - @_compat.deprecated( - fix='Please use metadata.qubit_set if applicable.', - deadline='v0.15', - ) + @_compat.deprecated(fix='Please use metadata.qubit_set if applicable.', deadline='v0.15') def qubit_set(self) -> FrozenSet[cirq.Qid]: return frozenset(self.qubits) @@ -209,8 +192,7 @@ def from_proto( gates_by_type[internal_type].append(gate_def) return SerializableDevice( - qubits=[_qid_from_str(q) for q in proto.valid_qubits], - gate_definitions=gates_by_type, + qubits=[_qid_from_str(q) for q in proto.valid_qubits], gate_definitions=gates_by_type ) @classmethod @@ -264,8 +246,7 @@ def __str__(self) -> str: return super().__str__() @_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, defined by the gate diff --git a/cirq-google/cirq_google/devices/serializable_device_test.py b/cirq-google/cirq_google/devices/serializable_device_test.py index c19526e239c..f372f24fd53 100644 --- a/cirq-google/cirq_google/devices/serializable_device_test.py +++ b/cirq-google/cirq_google/devices/serializable_device_test.py @@ -86,9 +86,7 @@ def test_metadata_correct(): (qubits[4], qubits[5]), ] device_proto = cgdk.create_device_proto_for_qubits( - qubits=qubits, - pairs=pairs, - gate_sets=[cg.FSIM_GATESET], + qubits=qubits, pairs=pairs, gate_sets=[cg.FSIM_GATESET] ) device = cgdk.SerializableDevice.from_proto(device_proto, gate_sets=[cg.FSIM_GATESET]) assert device.metadata.qubit_pairs == frozenset(pairs) @@ -385,17 +383,10 @@ def test_half_pi_takes_half_duration(): """ half_pi_gs = cirq_google.SerializableGateSet( gate_set_name='half_pi', - serializers=[ - *cgc.SINGLE_QUBIT_HALF_PI_SERIALIZERS, - ], - deserializers=[ - *cgc.SINGLE_QUBIT_HALF_PI_DESERIALIZERS, - ], + serializers=[*cgc.SINGLE_QUBIT_HALF_PI_SERIALIZERS], + deserializers=[*cgc.SINGLE_QUBIT_HALF_PI_DESERIALIZERS], ) - durations_dict = { - 'xy_pi': 20_000, - 'xy_half_pi': 10_000, - } + durations_dict = {'xy_pi': 20_000, 'xy_half_pi': 10_000} spec = cirq_google.devices.known_devices.create_device_proto_from_diagram( "aa\naa", [half_pi_gs], durations_dict ) @@ -416,17 +407,10 @@ def test_multiple_fsim_gatesets(): """ half_pi_gs = cirq_google.SerializableGateSet( gate_set_name='half_pi', - serializers=[ - *cgc.SINGLE_QUBIT_HALF_PI_SERIALIZERS, - ], - deserializers=[ - *cgc.SINGLE_QUBIT_HALF_PI_DESERIALIZERS, - ], + serializers=[*cgc.SINGLE_QUBIT_HALF_PI_SERIALIZERS], + deserializers=[*cgc.SINGLE_QUBIT_HALF_PI_DESERIALIZERS], ) - durations_dict = { - 'xy_pi': 20_000, - 'xy_half_pi': 10_000, - } + durations_dict = {'xy_pi': 20_000, 'xy_half_pi': 10_000} spec = cirq_google.devices.known_devices.create_device_proto_from_diagram( "aa\naa", [half_pi_gs], durations_dict ) diff --git a/cirq-google/cirq_google/devices/xmon_device.py b/cirq-google/cirq_google/devices/xmon_device.py index 87187789fe9..f4b6f0734a0 100644 --- a/cirq-google/cirq_google/devices/xmon_device.py +++ b/cirq-google/cirq_google/devices/xmon_device.py @@ -63,10 +63,7 @@ def metadata(self) -> cirq.GridDeviceMetadata: """Return the metadata for this device""" 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.GridQubit]: return self.qubits diff --git a/cirq-google/cirq_google/engine/__init__.py b/cirq-google/cirq_google/engine/__init__.py index 1037e97a15c..52d094f6635 100644 --- a/cirq-google/cirq_google/engine/__init__.py +++ b/cirq-google/cirq_google/engine/__init__.py @@ -15,63 +15,33 @@ """Client for running on Google's Quantum Engine. """ -from cirq_google.engine.abstract_engine import ( - AbstractEngine, -) +from cirq_google.engine.abstract_engine import AbstractEngine -from cirq_google.engine.abstract_job import ( - AbstractJob, -) +from cirq_google.engine.abstract_job import AbstractJob -from cirq_google.engine.abstract_processor import ( - AbstractProcessor, -) +from cirq_google.engine.abstract_processor import AbstractProcessor -from cirq_google.engine.abstract_program import ( - AbstractProgram, -) +from cirq_google.engine.abstract_program import AbstractProgram -from cirq_google.engine.abstract_local_engine import ( - AbstractLocalEngine, -) +from cirq_google.engine.abstract_local_engine import AbstractLocalEngine -from cirq_google.engine.abstract_local_job import ( - AbstractLocalJob, -) +from cirq_google.engine.abstract_local_job import AbstractLocalJob -from cirq_google.engine.abstract_local_processor import ( - AbstractLocalProcessor, -) +from cirq_google.engine.abstract_local_processor import AbstractLocalProcessor -from cirq_google.engine.abstract_local_program import ( - AbstractLocalProgram, -) +from cirq_google.engine.abstract_local_program import AbstractLocalProgram -from cirq_google.engine.simulated_local_engine import ( - SimulatedLocalEngine, -) +from cirq_google.engine.simulated_local_engine import SimulatedLocalEngine -from cirq_google.engine.simulated_local_job import ( - SimulatedLocalJob, -) +from cirq_google.engine.simulated_local_job import SimulatedLocalJob -from cirq_google.engine.simulated_local_processor import ( - SimulatedLocalProcessor, -) +from cirq_google.engine.simulated_local_processor import SimulatedLocalProcessor -from cirq_google.engine.simulated_local_program import ( - SimulatedLocalProgram, -) -from cirq_google.engine.calibration import ( - Calibration, -) +from cirq_google.engine.simulated_local_program import SimulatedLocalProgram +from cirq_google.engine.calibration import Calibration -from cirq_google.engine.calibration_layer import ( - CalibrationLayer, -) -from cirq_google.engine.calibration_result import ( - CalibrationResult, -) +from cirq_google.engine.calibration_layer import CalibrationLayer +from cirq_google.engine.calibration_result import CalibrationResult from cirq_google.engine.engine import ( Engine, get_engine, @@ -80,21 +50,13 @@ ProtoVersion, ) -from cirq_google.engine.engine_client import ( - EngineException, -) +from cirq_google.engine.engine_client import EngineException -from cirq_google.engine.engine_job import ( - EngineJob, -) +from cirq_google.engine.engine_job import EngineJob -from cirq_google.engine.engine_processor import ( - EngineProcessor, -) +from cirq_google.engine.engine_processor import EngineProcessor -from cirq_google.engine.engine_program import ( - EngineProgram, -) +from cirq_google.engine.engine_program import EngineProgram from cirq_google.engine.runtime_estimator import ( estimate_run_time, @@ -102,14 +64,9 @@ estimate_run_sweep_time, ) -from cirq_google.engine.engine_sampler import ( - get_engine_sampler, - QuantumEngineSampler, -) +from cirq_google.engine.engine_sampler import get_engine_sampler, QuantumEngineSampler -from cirq_google.engine.validating_sampler import ( - ValidatingSampler, -) +from cirq_google.engine.validating_sampler import ValidatingSampler from cirq_google.engine.virtual_engine_factory import ( create_noiseless_virtual_engine_from_device, diff --git a/cirq-google/cirq_google/engine/calibration_to_noise_properties.py b/cirq-google/cirq_google/engine/calibration_to_noise_properties.py index e95d951647f..b369a2ea7c7 100644 --- a/cirq-google/cirq_google/engine/calibration_to_noise_properties.py +++ b/cirq-google/cirq_google/engine/calibration_to_noise_properties.py @@ -157,12 +157,10 @@ def noise_properties_from_calibration( fsim_errors = {} for gate, prefix in gate_prefix_pairs.items(): theta_errors = _unpack_2q_from_calibration( - prefix + '_xeb_entangler_theta_error_per_cycle', - calibration, + prefix + '_xeb_entangler_theta_error_per_cycle', calibration ) phi_errors = _unpack_2q_from_calibration( - prefix + '_xeb_entangler_phi_error_per_cycle', - calibration, + prefix + '_xeb_entangler_phi_error_per_cycle', calibration ) angle_keys = set(theta_errors.keys()) | set(phi_errors.keys()) for qubits in angle_keys: diff --git a/cirq-google/cirq_google/engine/engine_processor_test.py b/cirq-google/cirq_google/engine/engine_processor_test.py index 315703c7f80..c937ff55a6a 100644 --- a/cirq-google/cirq_google/engine/engine_processor_test.py +++ b/cirq-google/cirq_google/engine/engine_processor_test.py @@ -840,8 +840,7 @@ def test_run_sweep_params(client): processor = cg.EngineProcessor('a', 'p', EngineContext()) job = processor.run_sweep( - program=_CIRCUIT, - params=[cirq.ParamResolver({'a': 1}), cirq.ParamResolver({'a': 2})], + program=_CIRCUIT, params=[cirq.ParamResolver({'a': 1}), cirq.ParamResolver({'a': 2})] ) results = job.results() assert len(results) == 2 diff --git a/cirq-google/cirq_google/engine/engine_sampler_test.py b/cirq-google/cirq_google/engine/engine_sampler_test.py index fe5c26b4f61..bb194e94dd0 100644 --- a/cirq-google/cirq_google/engine/engine_sampler_test.py +++ b/cirq-google/cirq_google/engine/engine_sampler_test.py @@ -54,10 +54,7 @@ def test_run_batch(): params_list = [params1, params2] sampler.run_batch(circuits, params_list, 5) engine.run_batch.assert_called_with( - params_list=params_list, - processor_ids=['tmp'], - programs=circuits, - repetitions=5, + params_list=params_list, processor_ids=['tmp'], programs=circuits, repetitions=5 ) @@ -73,10 +70,7 @@ def test_run_batch_identical_repetitions(): params_list = [params1, params2] sampler.run_batch(circuits, params_list, [5, 5]) engine.run_batch.assert_called_with( - params_list=params_list, - processor_ids=['tmp'], - programs=circuits, - repetitions=5, + params_list=params_list, processor_ids=['tmp'], programs=circuits, repetitions=5 ) diff --git a/cirq-google/cirq_google/engine/engine_validator.py b/cirq-google/cirq_google/engine/engine_validator.py index 84f5b16e13b..9421d68c34b 100644 --- a/cirq-google/cirq_google/engine/engine_validator.py +++ b/cirq-google/cirq_google/engine/engine_validator.py @@ -24,14 +24,12 @@ MAX_TOTAL_REPETITIONS = 5_000_000 GATE_SET_VALIDATOR_TYPE = Callable[ - [Sequence[cirq.AbstractCircuit], Sequence[cirq.Sweepable], int, 'Serializer'], - None, + [Sequence[cirq.AbstractCircuit], Sequence[cirq.Sweepable], int, 'Serializer'], None, ] def _validate_depth( - circuits: Sequence[cirq.AbstractCircuit], - max_moments: int = MAX_MOMENTS, + circuits: Sequence[cirq.AbstractCircuit], max_moments: int = MAX_MOMENTS ) -> None: """Validate that the depth of the circuit is not too long (too many moments).""" for circuit in circuits: diff --git a/cirq-google/cirq_google/engine/engine_validator_test.py b/cirq-google/cirq_google/engine/engine_validator_test.py index e59ac1a02b1..ed94b6e85e1 100644 --- a/cirq-google/cirq_google/engine/engine_validator_test.py +++ b/cirq-google/cirq_google/engine/engine_validator_test.py @@ -17,14 +17,7 @@ import cirq_google as cg import cirq_google.engine.engine_validator as engine_validator -SERIALIZABLE_GATE_DOMAIN = { - cirq.X: 1, - cirq.Y: 1, - cirq.Z: 1, - cirq.S: 1, - cirq.T: 1, - cirq.CZ: 2, -} +SERIALIZABLE_GATE_DOMAIN = {cirq.X: 1, cirq.Y: 1, cirq.Z: 1, cirq.S: 1, cirq.T: 1, cirq.CZ: 2} def _big_circuit(num_cycles: int) -> cirq.Circuit: diff --git a/cirq-google/cirq_google/engine/simulated_local_processor.py b/cirq-google/cirq_google/engine/simulated_local_processor.py index bf637b2d754..e8fa7ccbc43 100644 --- a/cirq-google/cirq_google/engine/simulated_local_processor.py +++ b/cirq-google/cirq_google/engine/simulated_local_processor.py @@ -36,8 +36,7 @@ ] GATE_SET_VALIDATOR_TYPE = Callable[ - [Sequence[cirq.AbstractCircuit], Sequence[cirq.Sweepable], int, 'Serializer'], - None, + [Sequence[cirq.AbstractCircuit], Sequence[cirq.Sweepable], int, 'Serializer'], None, ] diff --git a/cirq-google/cirq_google/engine/validating_sampler.py b/cirq-google/cirq_google/engine/validating_sampler.py index 3e7dfcebc4e..48ced6e82d7 100644 --- a/cirq-google/cirq_google/engine/validating_sampler.py +++ b/cirq-google/cirq_google/engine/validating_sampler.py @@ -59,10 +59,7 @@ def _validate_circuit( self._validator(circuits, sweeps, repetitions) 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]: self._validate_circuit([program], [params], repetitions) return self._sampler.run_sweep(program, params, repetitions) diff --git a/cirq-google/cirq_google/engine/validating_sampler_test.py b/cirq-google/cirq_google/engine/validating_sampler_test.py index 673fca6abc0..80ce2edbb25 100644 --- a/cirq-google/cirq_google/engine/validating_sampler_test.py +++ b/cirq-google/cirq_google/engine/validating_sampler_test.py @@ -83,9 +83,7 @@ def _too_many_reps(circuits: List[cirq.Circuit], sweeps: List[cirq.Sweepable], r def test_sweeps_validation(): sampler = cg.ValidatingSampler( - device=cirq.UNCONSTRAINED_DEVICE, - validator=_too_many_reps, - sampler=cirq.Simulator(), + device=cirq.UNCONSTRAINED_DEVICE, validator=_too_many_reps, sampler=cirq.Simulator() ) q = cirq.GridQubit(2, 2) circuit = cirq.Circuit(cirq.X(q) ** sympy.Symbol('t'), cirq.measure(q, key='m')) diff --git a/cirq-google/cirq_google/engine/virtual_engine_factory.py b/cirq-google/cirq_google/engine/virtual_engine_factory.py index d1128e0cbba..4dd7cff1170 100644 --- a/cirq-google/cirq_google/engine/virtual_engine_factory.py +++ b/cirq-google/cirq_google/engine/virtual_engine_factory.py @@ -20,11 +20,7 @@ import google.protobuf.text_format as text_format import cirq from cirq_google.api import v2 -from cirq_google.engine import ( - calibration, - engine_validator, - simulated_local_processor, -) +from cirq_google.engine import calibration, engine_validator, simulated_local_processor from cirq_google.devices import serializable_device from cirq_google.serialization.gate_sets import FSIM_GATESET from cirq_google.serialization import serializable_gate_set @@ -199,9 +195,7 @@ def create_noiseless_virtual_engine_from_proto( ) -def _create_device_spec_from_template( - template_name: str, -) -> v2.device_pb2.DeviceSpecification: +def _create_device_spec_from_template(template_name: str) -> v2.device_pb2.DeviceSpecification: """Load a template proto into a `v2.device_pb2.DeviceSpecification`.""" path = pathlib.Path(__file__).parent.parent.resolve() diff --git a/cirq-google/cirq_google/experimental/__init__.py b/cirq-google/cirq_google/experimental/__init__.py index 50eae1e3308..7ede4123e87 100644 --- a/cirq-google/cirq_google/experimental/__init__.py +++ b/cirq-google/cirq_google/experimental/__init__.py @@ -19,6 +19,4 @@ simple_noise_from_calibration_metrics, ) -from cirq_google.experimental.ops import ( - CouplerPulse, -) +from cirq_google.experimental.ops import CouplerPulse diff --git a/cirq-google/cirq_google/experimental/noise_models/noise_models_test.py b/cirq-google/cirq_google/experimental/noise_models/noise_models_test.py index 418ca2bf0db..2bf82d4a81c 100644 --- a/cirq-google/cirq_google/experimental/noise_models/noise_models_test.py +++ b/cirq-google/cirq_google/experimental/noise_models/noise_models_test.py @@ -21,9 +21,7 @@ from cirq.testing import assert_equivalent_op_tree import cirq_google from cirq_google.api import v2 -from cirq_google.experimental.noise_models import ( - simple_noise_from_calibration_metrics, -) +from cirq_google.experimental.noise_models import simple_noise_from_calibration_metrics # Fake calibration data object. _CALIBRATION_DATA = Merge( diff --git a/cirq-google/cirq_google/experimental/ops/__init__.py b/cirq-google/cirq_google/experimental/ops/__init__.py index 0f4bb80d186..d8c33714bff 100644 --- a/cirq-google/cirq_google/experimental/ops/__init__.py +++ b/cirq-google/cirq_google/experimental/ops/__init__.py @@ -12,6 +12,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -from cirq_google.experimental.ops.coupler_pulse import ( - CouplerPulse, -) +from cirq_google.experimental.ops.coupler_pulse import CouplerPulse diff --git a/cirq-google/cirq_google/experimental/ops/coupler_pulse_test.py b/cirq-google/cirq_google/experimental/ops/coupler_pulse_test.py index 8878c6ae90e..5f7aeade68d 100644 --- a/cirq-google/cirq_google/experimental/ops/coupler_pulse_test.py +++ b/cirq-google/cirq_google/experimental/ops/coupler_pulse_test.py @@ -83,9 +83,7 @@ def test_equality(): def test_coupler_pulse_validation(): with pytest.raises(ValueError, match='Total time of coupler pulse'): _ = coupler_pulse.CouplerPulse( - hold_time=cirq.Duration(nanos=210), - coupling_mhz=25.0, - rise_time=cirq.Duration(nanos=10), + hold_time=cirq.Duration(nanos=210), coupling_mhz=25.0, rise_time=cirq.Duration(nanos=10) ) with pytest.raises(ValueError, match='hold_time must be greater'): _ = coupler_pulse.CouplerPulse( @@ -107,15 +105,11 @@ def test_coupler_pulse_validation(): ) with pytest.raises(ValueError, match='rise_time must be greater'): _ = coupler_pulse.CouplerPulse( - hold_time=cirq.Duration(nanos=10), - coupling_mhz=25.0, - rise_time=cirq.Duration(nanos=-1), + hold_time=cirq.Duration(nanos=10), coupling_mhz=25.0, rise_time=cirq.Duration(nanos=-1) ) with pytest.raises(ValueError, match='Total time of coupler pulse'): _ = coupler_pulse.CouplerPulse( - hold_time=cirq.Duration(nanos=10), - coupling_mhz=25.0, - rise_time=cirq.Duration(nanos=302), + hold_time=cirq.Duration(nanos=10), coupling_mhz=25.0, rise_time=cirq.Duration(nanos=302) ) diff --git a/cirq-google/cirq_google/line/placement/__init__.py b/cirq-google/cirq_google/line/placement/__init__.py index a3a34ea4fc0..a8b6ef14e70 100644 --- a/cirq-google/cirq_google/line/placement/__init__.py +++ b/cirq-google/cirq_google/line/placement/__init__.py @@ -12,26 +12,14 @@ # See the License for the specific language governing permissions and # limitations under the License. -from cirq_google.line.placement.anneal import ( - AnnealSequenceSearchStrategy, -) +from cirq_google.line.placement.anneal import AnnealSequenceSearchStrategy -from cirq_google.line.placement.greedy import ( - GreedySequenceSearchStrategy, -) +from cirq_google.line.placement.greedy import GreedySequenceSearchStrategy -from cirq_google.line.placement.place_strategy import ( - LinePlacementStrategy, -) +from cirq_google.line.placement.place_strategy import LinePlacementStrategy -from cirq_google.line.placement.sequence import ( - GridQubitLineTuple, -) +from cirq_google.line.placement.sequence import GridQubitLineTuple -from cirq_google.line.placement.line import ( - line_on_device, -) +from cirq_google.line.placement.line import line_on_device -from cirq_google.line.placement.optimization import ( - anneal_minimize, -) +from cirq_google.line.placement.optimization import anneal_minimize diff --git a/cirq-google/cirq_google/line/placement/anneal.py b/cirq-google/cirq_google/line/placement/anneal.py index d2cf63213d8..3e72785a158 100644 --- a/cirq-google/cirq_google/line/placement/anneal.py +++ b/cirq-google/cirq_google/line/placement/anneal.py @@ -18,12 +18,7 @@ import cirq from cirq_google.line.placement import place_strategy, optimization -from cirq_google.line.placement.chip import ( - above, - right_of, - chip_as_adjacency_list, - EDGE, -) +from cirq_google.line.placement.chip import above, right_of, chip_as_adjacency_list, EDGE from cirq_google.line.placement.sequence import GridQubitLineTuple, LineSequence if TYPE_CHECKING: diff --git a/cirq-google/cirq_google/line/placement/greedy.py b/cirq-google/cirq_google/line/placement/greedy.py index 57edd2d3b14..a841a8f4fcd 100644 --- a/cirq-google/cirq_google/line/placement/greedy.py +++ b/cirq-google/cirq_google/line/placement/greedy.py @@ -307,16 +307,9 @@ def place_line(self, device: 'cirq_google.XmonDevice', length: int) -> GridQubit start: GridQubit = min(device.qubits) sequences: List[LineSequence] = [] greedy_search: Dict[str, List[GreedySequenceSearch]] = { - 'minimal_connectivity': [ - _PickFewestNeighbors(device, start), - ], - 'largest_area': [ - _PickLargestArea(device, start), - ], - 'best': [ - _PickFewestNeighbors(device, start), - _PickLargestArea(device, start), - ], + 'minimal_connectivity': [_PickFewestNeighbors(device, start)], + 'largest_area': [_PickLargestArea(device, start)], + 'best': [_PickFewestNeighbors(device, start), _PickLargestArea(device, start)], } algos = greedy_search.get(self.algorithm) diff --git a/cirq-google/cirq_google/line/placement/greedy_test.py b/cirq-google/cirq_google/line/placement/greedy_test.py index 67911be46b2..1d9ac8d4106 100644 --- a/cirq-google/cirq_google/line/placement/greedy_test.py +++ b/cirq-google/cirq_google/line/placement/greedy_test.py @@ -18,10 +18,7 @@ import cirq from cirq_google.line.placement import greedy -from cirq_google.line.placement.sequence import ( - GridQubitLineTuple, - NotFoundError, -) +from cirq_google.line.placement.sequence import GridQubitLineTuple, NotFoundError class FakeDevice(cirq.Device): diff --git a/cirq-google/cirq_google/ops/__init__.py b/cirq-google/cirq_google/ops/__init__.py index 946bda07b78..5283f00b821 100644 --- a/cirq-google/cirq_google/ops/__init__.py +++ b/cirq-google/cirq_google/ops/__init__.py @@ -12,19 +12,10 @@ # See the License for the specific language governing permissions and # limitations under the License. -from cirq_google.ops.calibration_tag import ( - CalibrationTag, -) +from cirq_google.ops.calibration_tag import CalibrationTag -from cirq_google.ops.fsim_gate_family import ( - FSimGateFamily, -) +from cirq_google.ops.fsim_gate_family import FSimGateFamily -from cirq_google.ops.physical_z_tag import ( - PhysicalZTag, -) +from cirq_google.ops.physical_z_tag import PhysicalZTag -from cirq_google.ops.sycamore_gate import ( - SycamoreGate, - SYC, -) +from cirq_google.ops.sycamore_gate import SycamoreGate, SYC diff --git a/cirq-google/cirq_google/ops/fsim_gate_family_test.py b/cirq-google/cirq_google/ops/fsim_gate_family_test.py index 212149d6bb6..95528bc8e85 100644 --- a/cirq-google/cirq_google/ops/fsim_gate_family_test.py +++ b/cirq-google/cirq_google/ops/fsim_gate_family_test.py @@ -45,19 +45,13 @@ (cirq.FSimGate(theta=2 * np.pi, phi=PHI), {PHI: -0.4}), ( cirq.PhasedFSimGate.from_fsim_rz( - theta=THETA, - phi=10, - rz_angles_before=(THETA, THETA), - rz_angles_after=(PHI, PHI), + theta=THETA, phi=10, rz_angles_before=(THETA, THETA), rz_angles_after=(PHI, PHI) ), {THETA: 0, PHI: 2 * np.pi}, ), ( cirq.PhasedFSimGate.from_fsim_rz( - theta=THETA, - phi=PHI, - rz_angles_before=(2 * np.pi, 2 * np.pi), - rz_angles_after=(0, 0), + theta=THETA, phi=PHI, rz_angles_before=(2 * np.pi, 2 * np.pi), rz_angles_after=(0, 0) ), {THETA: 2 * np.pi, PHI: -0.01}, ), @@ -72,19 +66,13 @@ (cirq.FSimGate(theta=-0.4, phi=PHI), {PHI: 2 * np.pi}), ( cirq.PhasedFSimGate.from_fsim_rz( - theta=10, - phi=PHI, - rz_angles_before=(PHI, PHI), - rz_angles_after=(THETA, THETA), + theta=10, phi=PHI, rz_angles_before=(PHI, PHI), rz_angles_after=(THETA, THETA) ), {THETA: 2 * np.pi, PHI: 0}, ), ( cirq.PhasedFSimGate.from_fsim_rz( - theta=THETA, - phi=PHI, - rz_angles_before=(PHI, PHI), - rz_angles_after=(0, 0), + theta=THETA, phi=PHI, rz_angles_before=(PHI, PHI), rz_angles_after=(0, 0) ), {THETA: -0.01, PHI: 2 * np.pi}, ), diff --git a/cirq-google/cirq_google/ops/sycamore_gate_test.py b/cirq-google/cirq_google/ops/sycamore_gate_test.py index e4fe53e51bc..5fce1df30c9 100644 --- a/cirq-google/cirq_google/ops/sycamore_gate_test.py +++ b/cirq-google/cirq_google/ops/sycamore_gate_test.py @@ -61,10 +61,10 @@ def test_syc_unitary(): cirq.unitary(cg.SYC), np.array( [ - [1, 0, 0, 0], - [0, 0, -1j, 0], - [0, -1j, 0, 0], - [0, 0, 0, np.exp(-1j * np.pi / 6)], + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, -1.0j, 0.0], + [0.0, -1.0j, 0.0, 0.0], + [0.0, 0.0, 0.0, np.exp(-1j * np.pi / 6)], ] ), atol=1e-6, diff --git a/cirq-google/cirq_google/optimizers/__init__.py b/cirq-google/cirq_google/optimizers/__init__.py index 1fa1603f7c7..00b5f736c2f 100644 --- a/cirq-google/cirq_google/optimizers/__init__.py +++ b/cirq-google/cirq_google/optimizers/__init__.py @@ -12,27 +12,14 @@ # See the License for the specific language governing permissions and # limitations under the License. """Package for optimizers and gate compilers related to Google-specific devices.""" -from cirq_google.optimizers.two_qubit_gates import ( - gate_product_tabulation, - GateTabulation, -) +from cirq_google.optimizers.two_qubit_gates import gate_product_tabulation, GateTabulation -from cirq_google.optimizers.convert_to_sycamore_gates import ( - ConvertToSycamoreGates, -) +from cirq_google.optimizers.convert_to_sycamore_gates import ConvertToSycamoreGates -from cirq_google.optimizers.convert_to_sqrt_iswap import ( - ConvertToSqrtIswapGates, -) +from cirq_google.optimizers.convert_to_sqrt_iswap import ConvertToSqrtIswapGates -from cirq_google.optimizers.convert_to_xmon_gates import ( - ConvertToXmonGates, -) +from cirq_google.optimizers.convert_to_xmon_gates import ConvertToXmonGates -from cirq_google.optimizers.optimize_for_sycamore import ( - optimized_for_sycamore, -) +from cirq_google.optimizers.optimize_for_sycamore import optimized_for_sycamore -from cirq_google.optimizers.optimize_for_xmon import ( - optimized_for_xmon, -) +from cirq_google.optimizers.optimize_for_xmon import optimized_for_xmon diff --git a/cirq-google/cirq_google/optimizers/convert_to_sycamore_gates_test.py b/cirq-google/cirq_google/optimizers/convert_to_sycamore_gates_test.py index f8458b0f99c..ddde36b9056 100644 --- a/cirq-google/cirq_google/optimizers/convert_to_sycamore_gates_test.py +++ b/cirq-google/cirq_google/optimizers/convert_to_sycamore_gates_test.py @@ -234,7 +234,7 @@ def test_zztheta_zzpow_unsorted_qubits(): qubits = cirq.LineQubit(1), cirq.LineQubit(0) exponent = 0.06366197723675814 expected_circuit = cirq.Circuit( - cirq.ZZPowGate(exponent=exponent, global_shift=-0.5).on(qubits[0], qubits[1]), + cirq.ZZPowGate(exponent=exponent, global_shift=-0.5).on(qubits[0], qubits[1]) ) actual_circuit = expected_circuit.copy() with cirq.testing.assert_deprecated("Use cirq.optimize_for_target_gateset", deadline='v1.0'): diff --git a/cirq-google/cirq_google/optimizers/convert_to_xmon_gates.py b/cirq-google/cirq_google/optimizers/convert_to_xmon_gates.py index 53d7113ef00..bf1eaa696a0 100644 --- a/cirq-google/cirq_google/optimizers/convert_to_xmon_gates.py +++ b/cirq-google/cirq_google/optimizers/convert_to_xmon_gates.py @@ -17,8 +17,7 @@ @cirq._compat.deprecated_class( - deadline='v1.0', - fix='Use cirq.optimize_for_target_gateset and cirq.CZTargetGateset instead.', + deadline='v1.0', fix='Use cirq.optimize_for_target_gateset and cirq.CZTargetGateset instead.' ) class ConvertToXmonGates(cirq.PointOptimizer): """Attempts to convert strange gates into XmonGates. diff --git a/cirq-google/cirq_google/optimizers/optimize_for_xmon_test.py b/cirq-google/cirq_google/optimizers/optimize_for_xmon_test.py index eed11197768..246bee47770 100644 --- a/cirq-google/cirq_google/optimizers/optimize_for_xmon_test.py +++ b/cirq-google/cirq_google/optimizers/optimize_for_xmon_test.py @@ -16,21 +16,10 @@ import cirq import cirq_google as cg -from cirq.testing import ( - assert_circuits_with_terminal_measurements_are_equivalent, -) - - -@pytest.mark.parametrize( - 'n,d', - [ - (3, 2), - (4, 3), - (4, 4), - (5, 4), - (7, 4), - ], -) +from cirq.testing import assert_circuits_with_terminal_measurements_are_equivalent + + +@pytest.mark.parametrize('n,d', [(3, 2), (4, 3), (4, 4), (5, 4), (7, 4)]) def test_swap_field(n: int, d: int): before = cirq.Circuit( cirq.ISWAP(cirq.LineQubit(j), cirq.LineQubit(j + 1)) diff --git a/cirq-google/cirq_google/optimizers/two_qubit_gates/gate_compilation_test.py b/cirq-google/cirq_google/optimizers/two_qubit_gates/gate_compilation_test.py index f94aacd243e..e9efa2f5af9 100644 --- a/cirq-google/cirq_google/optimizers/two_qubit_gates/gate_compilation_test.py +++ b/cirq-google/cirq_google/optimizers/two_qubit_gates/gate_compilation_test.py @@ -11,18 +11,12 @@ def test_deprecated_gate_product_tabulation(): - with cirq.testing.assert_deprecated( - deadline='v0.16', - count=None, - ): + with cirq.testing.assert_deprecated(deadline='v0.16', count=None): _ = gate_product_tabulation(np.eye(4), 0.25) def test_deprecated_gate_tabulation_repr(): - with cirq.testing.assert_deprecated( - deadline='v0.16', - count=None, - ): + with cirq.testing.assert_deprecated(deadline='v0.16', count=None): GateTabulation( np.array([[(1 + 0j), 0j, 0j, 0j]], dtype=np.complex128), np.array([[(1 + 0j), 0j, 0j, 0j]], dtype=np.complex128), diff --git a/cirq-google/cirq_google/serialization/__init__.py b/cirq-google/cirq_google/serialization/__init__.py index 2e90ded3330..ed65e0ed76f 100644 --- a/cirq-google/cirq_google/serialization/__init__.py +++ b/cirq-google/cirq_google/serialization/__init__.py @@ -14,15 +14,10 @@ """Classes for serializing circuits into protocol buffers.""" -from cirq_google.serialization.arg_func_langs import ( - arg_from_proto, -) +from cirq_google.serialization.arg_func_langs import arg_from_proto -from cirq_google.serialization.circuit_serializer import ( - CircuitSerializer, - CIRCUIT_SERIALIZER, -) +from cirq_google.serialization.circuit_serializer import CircuitSerializer, CIRCUIT_SERIALIZER from cirq_google.serialization.gate_sets import ( XMON, @@ -44,10 +39,6 @@ SerializingArg, ) -from cirq_google.serialization.serializer import ( - Serializer, -) +from cirq_google.serialization.serializer import Serializer -from cirq_google.serialization.serializable_gate_set import ( - SerializableGateSet, -) +from cirq_google.serialization.serializable_gate_set import SerializableGateSet diff --git a/cirq-google/cirq_google/serialization/arg_func_langs.py b/cirq-google/cirq_google/serialization/arg_func_langs.py index 66e1879166b..2da90e559ce 100644 --- a/cirq-google/cirq_google/serialization/arg_func_langs.py +++ b/cirq-google/cirq_google/serialization/arg_func_langs.py @@ -12,15 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. import math -from typing import ( - List, - Union, - Optional, - Iterator, - Iterable, - Dict, - FrozenSet, -) +from typing import List, Union, Optional, Iterator, Iterable, Dict, FrozenSet import numpy as np import sympy @@ -48,11 +40,7 @@ # Supported function languages in order from least to most flexible. # Clients should use the least flexible language they can, to make it easier # to gradually roll out new capabilities to clients and servers. -LANGUAGE_ORDER = [ - '', - 'linear', - 'exp', -] +LANGUAGE_ORDER = ['', 'linear', 'exp'] def _max_lang(langs: Iterable[str]) -> str: diff --git a/cirq-google/cirq_google/serialization/circuit_serializer.py b/cirq-google/cirq_google/serialization/circuit_serializer.py index a2b6fa449b3..4b6812c005e 100644 --- a/cirq-google/cirq_google/serialization/circuit_serializer.py +++ b/cirq-google/cirq_google/serialization/circuit_serializer.py @@ -37,10 +37,7 @@ class CircuitSerializer(serializer.Serializer): at the cost of some extendability. """ - def __init__( - self, - gate_set_name: str, - ): + def __init__(self, gate_set_name: str): """Construct the circuit serializer object. Args: @@ -207,20 +204,14 @@ def _serialize_gate_op( ) elif isinstance(gate, cirq.FSimGate): arg_func_langs.float_arg_to_proto( - gate.theta, - out=msg.fsimgate.theta, - arg_function_language=arg_function_language, + gate.theta, out=msg.fsimgate.theta, arg_function_language=arg_function_language ) arg_func_langs.float_arg_to_proto( - gate.phi, - out=msg.fsimgate.phi, - arg_function_language=arg_function_language, + gate.phi, out=msg.fsimgate.phi, arg_function_language=arg_function_language ) elif isinstance(gate, cirq.MeasurementGate): arg_func_langs.arg_to_proto( - gate.key, - out=msg.measurementgate.key, - arg_function_language=arg_function_language, + gate.key, out=msg.measurementgate.key, arg_function_language=arg_function_language ) arg_func_langs.arg_to_proto( gate.invert_mask, diff --git a/cirq-google/cirq_google/serialization/circuit_serializer_test.py b/cirq-google/cirq_google/serialization/circuit_serializer_test.py index f1a994f8b9f..fa75b043756 100644 --- a/cirq-google/cirq_google/serialization/circuit_serializer_test.py +++ b/cirq-google/cirq_google/serialization/circuit_serializer_test.py @@ -49,51 +49,26 @@ def circuit_proto(json: Dict, qubits: List[str]): Q1 = cirq.GridQubit(2, 5) -X_PROTO = op_proto( - { - 'xpowgate': {'exponent': {'float_value': 1.0}}, - 'qubit_constant_index': [0], - } -) +X_PROTO = op_proto({'xpowgate': {'exponent': {'float_value': 1.0}}, 'qubit_constant_index': [0]}) OPERATIONS = [ (cirq.X(Q0), X_PROTO), ( cirq.Y(Q0), - op_proto( - { - 'ypowgate': {'exponent': {'float_value': 1.0}}, - 'qubit_constant_index': [0], - } - ), + op_proto({'ypowgate': {'exponent': {'float_value': 1.0}}, 'qubit_constant_index': [0]}), ), ( cirq.Z(Q0), - op_proto( - { - 'zpowgate': {'exponent': {'float_value': 1.0}}, - 'qubit_constant_index': [0], - } - ), + op_proto({'zpowgate': {'exponent': {'float_value': 1.0}}, 'qubit_constant_index': [0]}), ), ( cirq.XPowGate(exponent=0.125)(Q1), - op_proto( - { - 'xpowgate': {'exponent': {'float_value': 0.125}}, - 'qubit_constant_index': [0], - } - ), + op_proto({'xpowgate': {'exponent': {'float_value': 0.125}}, 'qubit_constant_index': [0]}), ), ( cirq.XPowGate(exponent=sympy.Symbol('a'))(Q1), - op_proto( - { - 'xpowgate': {'exponent': {'symbol': 'a'}}, - 'qubit_constant_index': [0], - } - ), + op_proto({'xpowgate': {'exponent': {'symbol': 'a'}}, 'qubit_constant_index': [0]}), ), ( cirq.XPowGate(exponent=0.25 + sympy.Symbol('t'))(Q1), @@ -145,21 +120,11 @@ def circuit_proto(json: Dict, qubits: List[str]): ), ( cirq.YPowGate(exponent=0.25)(Q0), - op_proto( - { - 'ypowgate': {'exponent': {'float_value': 0.25}}, - 'qubit_constant_index': [0], - } - ), + op_proto({'ypowgate': {'exponent': {'float_value': 0.25}}, 'qubit_constant_index': [0]}), ), ( cirq.ZPowGate(exponent=0.5)(Q0), - op_proto( - { - 'zpowgate': {'exponent': {'float_value': 0.5}}, - 'qubit_constant_index': [0], - } - ), + op_proto({'zpowgate': {'exponent': {'float_value': 0.5}}, 'qubit_constant_index': [0]}), ), ( cirq.ZPowGate(exponent=0.5)(Q0).with_tags(cg.PhysicalZTag()), @@ -197,29 +162,16 @@ def circuit_proto(json: Dict, qubits: List[str]): ), ( cirq.CZ(Q0, Q1), - op_proto( - { - 'czpowgate': {'exponent': {'float_value': 1.0}}, - 'qubit_constant_index': [0, 1], - } - ), + op_proto({'czpowgate': {'exponent': {'float_value': 1.0}}, 'qubit_constant_index': [0, 1]}), ), ( cirq.CZPowGate(exponent=0.5)(Q0, Q1), - op_proto( - { - 'czpowgate': {'exponent': {'float_value': 0.5}}, - 'qubit_constant_index': [0, 1], - } - ), + op_proto({'czpowgate': {'exponent': {'float_value': 0.5}}, 'qubit_constant_index': [0, 1]}), ), ( cirq.ISwapPowGate(exponent=0.5)(Q0, Q1), op_proto( - { - 'iswappowgate': {'exponent': {'float_value': 0.5}}, - 'qubit_constant_index': [0, 1], - } + {'iswappowgate': {'exponent': {'float_value': 0.5}}, 'qubit_constant_index': [0, 1]} ), ), ( @@ -269,10 +221,7 @@ def circuit_proto(json: Dict, qubits: List[str]): ( cirq.WaitGate(duration=cirq.Duration(nanos=15))(Q0), op_proto( - { - 'waitgate': {'duration_nanos': {'float_value': 15}}, - 'qubit_constant_index': [0], - } + {'waitgate': {'duration_nanos': {'float_value': 15}}, 'qubit_constant_index': [0]} ), ), ( @@ -337,7 +286,7 @@ def test_serialize_deserialize_circuit(): ), qubit_constant_index=[1], ), - ], + ] ), v2.program_pb2.Moment( operations=[ @@ -346,8 +295,8 @@ def test_serialize_deserialize_circuit(): exponent=v2.program_pb2.FloatArg(float_value=1.0) ), qubit_constant_index=[0], - ), - ], + ) + ] ), ], ), @@ -392,15 +341,9 @@ def test_serialize_deserialize_circuit_with_tokens(): circuit=v2.program_pb2.Circuit( scheduling_strategy=v2.program_pb2.Circuit.MOMENT_BY_MOMENT, moments=[ - v2.program_pb2.Moment( - operations=[op_q0_tag1, op_q1_tag2], - ), - v2.program_pb2.Moment( - operations=[op_q0_tag2], - ), - v2.program_pb2.Moment( - operations=[X_PROTO], - ), + v2.program_pb2.Moment(operations=[op_q0_tag1, op_q1_tag2]), + v2.program_pb2.Moment(operations=[op_q0_tag2]), + v2.program_pb2.Moment(operations=[X_PROTO]), ], ), constants=[ @@ -430,14 +373,12 @@ def test_deserialize_circuit_with_token_strings(): ), token_value='abc123', qubit_constant_index=[0], - ), - ], - ), + ) + ] + ) ], ), - constants=[ - v2.program_pb2.Constant(qubit=v2.program_pb2.Qubit(id='2_4')), - ], + constants=[v2.program_pb2.Constant(qubit=v2.program_pb2.Qubit(id='2_4'))], ) tag = cg.CalibrationTag('abc123') circuit = cirq.Circuit(cirq.X(Q0).with_tags(tag)) @@ -486,14 +427,8 @@ def test_serialize_deserialize_circuit_with_subcircuit(): circuit=v2.program_pb2.Circuit( scheduling_strategy=v2.program_pb2.Circuit.MOMENT_BY_MOMENT, moments=[ - v2.program_pb2.Moment( - operations=[op_tag], - circuit_operations=[c_op1], - ), - v2.program_pb2.Moment( - operations=[op_x], - circuit_operations=[c_op2], - ), + v2.program_pb2.Moment(operations=[op_tag], circuit_operations=[c_op1]), + v2.program_pb2.Moment(operations=[op_x], circuit_operations=[c_op2]), ], ), constants=[ @@ -503,11 +438,7 @@ def test_serialize_deserialize_circuit_with_subcircuit(): v2.program_pb2.Constant( circuit_value=v2.program_pb2.Circuit( scheduling_strategy=v2.program_pb2.Circuit.MOMENT_BY_MOMENT, - moments=[ - v2.program_pb2.Moment( - operations=[op_symbol], - ) - ], + moments=[v2.program_pb2.Moment(operations=[op_symbol])], ) ), ], @@ -538,9 +469,7 @@ def test_deserialize_empty_moment(): language=v2.program_pb2.Language(arg_function_language='', gate_set='my_gate_set'), circuit=v2.program_pb2.Circuit( scheduling_strategy=v2.program_pb2.Circuit.MOMENT_BY_MOMENT, - moments=[ - v2.program_pb2.Moment(), - ], + moments=[v2.program_pb2.Moment()], ), ) assert serializer.deserialize(proto) == circuit @@ -568,11 +497,7 @@ def default_circuit_proto(): return v2.program_pb2.Circuit( scheduling_strategy=v2.program_pb2.Circuit.MOMENT_BY_MOMENT, - moments=[ - v2.program_pb2.Moment( - operations=[op1], - ), - ], + moments=[v2.program_pb2.Moment(operations=[op1])], ) @@ -604,9 +529,7 @@ def test_deserialize_unsupported_gate_type(): operation_proto = op_proto( { 'gate': {'id': 'no_pow'}, - 'args': { - 'half_turns': {'arg_value': {'float_value': 0.125}}, - }, + 'args': {'half_turns': {'arg_value': {'float_value': 0.125}}}, 'qubits': [{'id': '1_1'}], } ) @@ -614,9 +537,7 @@ def test_deserialize_unsupported_gate_type(): language=v2.program_pb2.Language(arg_function_language='', gate_set='my_gate_set'), circuit=v2.program_pb2.Circuit( scheduling_strategy=v2.program_pb2.Circuit.MOMENT_BY_MOMENT, - moments=[ - v2.program_pb2.Moment(operations=[operation_proto]), - ], + moments=[v2.program_pb2.Moment(operations=[operation_proto])], ), ) with pytest.raises(ValueError, match='no_pow'): @@ -686,12 +607,7 @@ def test_deserialize_schedule_not_supported(): def test_deserialize_fsim_missing_parameters(): serializer = cg.CircuitSerializer('my_gate_set') proto = circuit_proto( - { - 'fsimgate': { - 'theta': {'float_value': 3.0}, - }, - 'qubit_constant_index': [0, 1], - }, + {'fsimgate': {'theta': {'float_value': 3.0}}, 'qubit_constant_index': [0, 1]}, ['1_1', '1_2'], ) with pytest.raises(ValueError, match='theta and phi must be specified'): diff --git a/cirq-google/cirq_google/serialization/common_serializers.py b/cirq-google/cirq_google/serialization/common_serializers.py index afdaa95a7f5..adf6d6c66cd 100644 --- a/cirq-google/cirq_google/serialization/common_serializers.py +++ b/cirq-google/cirq_google/serialization/common_serializers.py @@ -80,14 +80,10 @@ def _convert_physical_z(op: cirq.Operation, proto: v2.program_pb2.Operation): serialized_gate_id='xy', args=[ op_serializer.SerializingArg( - serialized_name='axis_half_turns', - serialized_type=float, - op_getter='phase_exponent', + serialized_name='axis_half_turns', serialized_type=float, op_getter='phase_exponent' ), op_serializer.SerializingArg( - serialized_name='half_turns', - serialized_type=float, - op_getter='exponent', + serialized_name='half_turns', serialized_type=float, op_getter='exponent' ), ], ), @@ -96,14 +92,10 @@ def _convert_physical_z(op: cirq.Operation, proto: v2.program_pb2.Operation): serialized_gate_id='xy', args=[ op_serializer.SerializingArg( - serialized_name='axis_half_turns', - serialized_type=float, - op_getter=lambda op: 0.0, + serialized_name='axis_half_turns', serialized_type=float, op_getter=lambda op: 0.0 ), op_serializer.SerializingArg( - serialized_name='half_turns', - serialized_type=float, - op_getter='exponent', + serialized_name='half_turns', serialized_type=float, op_getter='exponent' ), ], ), @@ -112,14 +104,10 @@ def _convert_physical_z(op: cirq.Operation, proto: v2.program_pb2.Operation): serialized_gate_id='xy', args=[ op_serializer.SerializingArg( - serialized_name='axis_half_turns', - serialized_type=float, - op_getter=lambda op: 0.5, + serialized_name='axis_half_turns', serialized_type=float, op_getter=lambda op: 0.5 ), op_serializer.SerializingArg( - serialized_name='half_turns', - serialized_type=float, - op_getter='exponent', + serialized_name='half_turns', serialized_type=float, op_getter='exponent' ), ], ), @@ -128,9 +116,7 @@ def _convert_physical_z(op: cirq.Operation, proto: v2.program_pb2.Operation): serialized_gate_id='z', args=[ op_serializer.SerializingArg( - serialized_name='half_turns', - serialized_type=float, - op_getter='exponent', + serialized_name='half_turns', serialized_type=float, op_getter='exponent' ), op_serializer.SerializingArg( serialized_name='type', @@ -144,14 +130,10 @@ def _convert_physical_z(op: cirq.Operation, proto: v2.program_pb2.Operation): serialized_gate_id='xyz', args=[ op_serializer.SerializingArg( - serialized_name='x_exponent', - serialized_type=float, - op_getter='x_exponent', + serialized_name='x_exponent', serialized_type=float, op_getter='x_exponent' ), op_serializer.SerializingArg( - serialized_name='z_exponent', - serialized_type=float, - op_getter='z_exponent', + serialized_name='z_exponent', serialized_type=float, op_getter='z_exponent' ), op_serializer.SerializingArg( serialized_name='axis_phase_exponent', @@ -176,9 +158,7 @@ def _convert_physical_z(op: cirq.Operation, proto: v2.program_pb2.Operation): default=0.0, ), op_deserializer.DeserializingArg( - serialized_name='half_turns', - constructor_arg_name='exponent', - default=1.0, + serialized_name='half_turns', constructor_arg_name='exponent', default=1.0 ), ], ), @@ -187,10 +167,8 @@ def _convert_physical_z(op: cirq.Operation, proto: v2.program_pb2.Operation): gate_constructor=cirq.ZPowGate, args=[ op_deserializer.DeserializingArg( - serialized_name='half_turns', - constructor_arg_name='exponent', - default=1.0, - ), + serialized_name='half_turns', constructor_arg_name='exponent', default=1.0 + ) ], op_wrapper=lambda op, proto: _convert_physical_z(op, proto), ), @@ -199,14 +177,10 @@ def _convert_physical_z(op: cirq.Operation, proto: v2.program_pb2.Operation): gate_constructor=cirq.PhasedXZGate, args=[ op_deserializer.DeserializingArg( - serialized_name='x_exponent', - constructor_arg_name='x_exponent', - default=0.0, + serialized_name='x_exponent', constructor_arg_name='x_exponent', default=0.0 ), op_deserializer.DeserializingArg( - serialized_name='z_exponent', - constructor_arg_name='z_exponent', - default=0.0, + serialized_name='z_exponent', constructor_arg_name='z_exponent', default=0.0 ), op_deserializer.DeserializingArg( serialized_name='axis_phase_exponent', @@ -258,7 +232,7 @@ def _convert_physical_z(op: cirq.Operation, proto: v2.program_pb2.Operation): args=[ op_serializer.SerializingArg( serialized_name='axis_half_turns', serialized_type=float, op_getter='phase_exponent' - ), + ) ], can_serialize_predicate=lambda op: _near_mod_2( cast(cirq.PhasedXPowGate, op.gate).exponent, 1 @@ -318,7 +292,7 @@ def _convert_physical_z(op: cirq.Operation, proto: v2.program_pb2.Operation): args=[ op_serializer.SerializingArg( serialized_name='axis_half_turns', serialized_type=float, op_getter='phase_exponent' - ), + ) ], can_serialize_predicate=lambda op: _near_mod_2( cast(cirq.PhasedXPowGate, op.gate).exponent, 0.5 @@ -335,8 +309,7 @@ def _convert_physical_z(op: cirq.Operation, proto: v2.program_pb2.Operation): gate_constructor=cirq.PhasedXPowGate, args=[ op_deserializer.DeserializingArg( - serialized_name='axis_half_turns', - constructor_arg_name='phase_exponent', + serialized_name='axis_half_turns', constructor_arg_name='phase_exponent' ), op_deserializer.DeserializingArg( serialized_name='axis_half_turns', @@ -416,10 +389,8 @@ def _add_phase_match(op: cirq.Operation, proto: v2.program_pb2.Operation): gate_constructor=cirq.CZPowGate, args=[ op_deserializer.DeserializingArg( - serialized_name='half_turns', - constructor_arg_name='exponent', - default=1.0, - ), + serialized_name='half_turns', constructor_arg_name='exponent', default=1.0 + ) ], op_wrapper=lambda op, proto: _add_phase_match(op, proto), ) @@ -578,14 +549,10 @@ def _add_phase_match(op: cirq.Operation, proto: v2.program_pb2.Operation): gate_constructor=cirq.FSimGate, args=[ op_deserializer.DeserializingArg( - serialized_name='theta', - constructor_arg_name='theta', - default=0.0, + serialized_name='theta', constructor_arg_name='theta', default=0.0 ), op_deserializer.DeserializingArg( - serialized_name='phi', - constructor_arg_name='phi', - default=0.0, + serialized_name='phi', constructor_arg_name='phi', default=0.0 ), ], op_wrapper=lambda op, proto: _add_phase_match(op, proto), @@ -630,8 +597,7 @@ def _add_phase_match(op: cirq.Operation, proto: v2.program_pb2.Operation): gate_constructor=CouplerPulse, args=[ op_deserializer.DeserializingArg( - serialized_name='coupling_mhz', - constructor_arg_name='coupling_mhz', + serialized_name='coupling_mhz', constructor_arg_name='coupling_mhz' ), op_deserializer.DeserializingArg( serialized_name='hold_time_ns', @@ -668,7 +634,7 @@ def _add_phase_match(op: cirq.Operation, proto: v2.program_pb2.Operation): serialized_name='nanos', serialized_type=float, op_getter=lambda op: cast(cirq.WaitGate, op.gate).duration.total_nanos(), - ), + ) ], ) WAIT_GATE_DESERIALIZER = op_deserializer.GateOpDeserializer( diff --git a/cirq-google/cirq_google/serialization/common_serializers_test.py b/cirq-google/cirq_google/serialization/common_serializers_test.py index 5cc8542a164..93c92aa425d 100644 --- a/cirq-google/cirq_google/serialization/common_serializers_test.py +++ b/cirq-google/cirq_google/serialization/common_serializers_test.py @@ -166,9 +166,7 @@ def test_serialize_deserialize_arbitrary_xy(gate, axis_half_turns, half_turns): assert SINGLE_QUBIT_GATE_SET.serialize_op(op) == expected deserialized_op = SINGLE_QUBIT_GATE_SET.deserialize_op(expected) cirq.testing.assert_allclose_up_to_global_phase( - cirq.unitary(deserialized_op), - cirq.unitary(op), - atol=1e-7, + cirq.unitary(deserialized_op), cirq.unitary(op), atol=1e-7 ) @@ -191,18 +189,13 @@ def test_half_pi_does_not_serialize_arbitrary_xy(): (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), ], ) -def test_serialize_deserialize_arbitrary_xyz( - x_exponent, - z_exponent, - axis_phase_exponent, -): +def test_serialize_deserialize_arbitrary_xyz(x_exponent, z_exponent, axis_phase_exponent): gate = cirq.PhasedXZGate( - x_exponent=x_exponent, - z_exponent=z_exponent, - axis_phase_exponent=axis_phase_exponent, + x_exponent=x_exponent, z_exponent=z_exponent, axis_phase_exponent=axis_phase_exponent ) op = gate.on(cirq.GridQubit(1, 2)) expected = op_proto( @@ -219,9 +212,7 @@ def test_serialize_deserialize_arbitrary_xyz( assert SINGLE_QUBIT_GATE_SET.serialize_op(op) == expected deserialized_op = SINGLE_QUBIT_GATE_SET.deserialize_op(expected) cirq.testing.assert_allclose_up_to_global_phase( - cirq.unitary(deserialized_op), - cirq.unitary(op), - atol=1e-7, + cirq.unitary(deserialized_op), cirq.unitary(op), atol=1e-7 ) @@ -322,11 +313,7 @@ def test_serialize_xy_parameterized_axis_half_turns(): @pytest.mark.parametrize( ('gate', 'half_turns'), - [ - (cirq.Z, 1.0), - (cirq.Z**0.125, 0.125), - (cirq.rz(0.125 * np.pi), 0.125), - ], + [(cirq.Z, 1.0), (cirq.Z**0.125, 0.125), (cirq.rz(0.125 * np.pi), 0.125)], ) def test_serialize_z(gate, half_turns): q = cirq.GridQubit(1, 2) @@ -353,14 +340,7 @@ def test_serialize_z(gate, half_turns): ) -@pytest.mark.parametrize( - ('axis_half_turns', 'half_turns'), - [ - (0.25, 0.25), - (0, 0.25), - (0.5, 0.25), - ], -) +@pytest.mark.parametrize(('axis_half_turns', 'half_turns'), [(0.25, 0.25), (0, 0.25), (0.5, 0.25)]) def test_deserialize_xy(axis_half_turns, half_turns): serialized_op = op_proto( { @@ -440,12 +420,7 @@ def assert_phys_z_tag(phys_z, op): @pytest.mark.parametrize( - ('gate', 'exponent'), - [ - (cirq.CZ, 1.0), - (cirq.CZ**3.0, 3.0), - (cirq.CZ**-1.0, -1.0), - ], + ('gate', 'exponent'), [(cirq.CZ, 1.0), (cirq.CZ**3.0, 3.0), (cirq.CZ**-1.0, -1.0)] ) @pytest.mark.parametrize('phys_z', [False, True]) def test_serialize_deserialize_cz_gate(gate, exponent, phys_z): @@ -469,9 +444,7 @@ def test_serialize_deserialize_cz_gate(gate, exponent, phys_z): deserialized_op = gate_set.deserialize_op(proto) expected_gate = cirq.CZPowGate(exponent=exponent) cirq.testing.assert_allclose_up_to_global_phase( - cirq.unitary(deserialized_op), - cirq.unitary(expected_gate), - atol=1e-7, + cirq.unitary(deserialized_op), cirq.unitary(expected_gate), atol=1e-7 ) assert_phys_z_tag(phys_z, deserialized_op) @@ -598,9 +571,7 @@ def test_serialize_deserialize_fsim_gate(gate, theta, phi, phys_z): assert gate_set.serialize_op(op) == proto deserialized_op = gate_set.deserialize_op(proto) cirq.testing.assert_allclose_up_to_global_phase( - cirq.unitary(deserialized_op), - cirq.unitary(expected_gate), - atol=1e-7, + cirq.unitary(deserialized_op), cirq.unitary(expected_gate), atol=1e-7 ) assert_phys_z_tag(phys_z, deserialized_op) diff --git a/cirq-google/cirq_google/serialization/gate_sets.py b/cirq-google/cirq_google/serialization/gate_sets.py index a6026464706..ca15f0ff710 100644 --- a/cirq-google/cirq_google/serialization/gate_sets.py +++ b/cirq-google/cirq_google/serialization/gate_sets.py @@ -141,19 +141,10 @@ ) document(XMON, """Gate set for XMON devices.""") -NAMED_GATESETS = { - 'sqrt_iswap': SQRT_ISWAP_GATESET, - 'sycamore': SYC_GATESET, - 'fsim': FSIM_GATESET, -} +NAMED_GATESETS = {'sqrt_iswap': SQRT_ISWAP_GATESET, 'sycamore': SYC_GATESET, 'fsim': FSIM_GATESET} document(NAMED_GATESETS, """A convenience mapping from gateset names to gatesets""") -GOOGLE_GATESETS = [ - SYC_GATESET, - SQRT_ISWAP_GATESET, - FSIM_GATESET, - XMON, -] +GOOGLE_GATESETS = [SYC_GATESET, SQRT_ISWAP_GATESET, FSIM_GATESET, XMON] document(GOOGLE_GATESETS, """All Google gatesets""") diff --git a/cirq-google/cirq_google/serialization/gate_sets_test.py b/cirq-google/cirq_google/serialization/gate_sets_test.py index 8173751faf9..354b2150a85 100644 --- a/cirq-google/cirq_google/serialization/gate_sets_test.py +++ b/cirq-google/cirq_google/serialization/gate_sets_test.py @@ -100,11 +100,7 @@ def test_serialize_exp_w_parameterized_axis_half_turns(): @pytest.mark.parametrize( ('gate', 'half_turns'), - [ - (cirq.Z, 1.0), - (cirq.Z**0.125, 0.125), - (cirq.rz(0.125 * np.pi), 0.125), - ], + [(cirq.Z, 1.0), (cirq.Z**0.125, 0.125), (cirq.rz(0.125 * np.pi), 0.125)], ) def test_serialize_exp_z(gate, half_turns): q = cirq.GridQubit(1, 2) @@ -135,22 +131,14 @@ def test_serialize_exp_z_parameterized(): ) -@pytest.mark.parametrize( - ('gate', 'half_turns'), - [ - (cirq.CZ, 1.0), - (cirq.CZ**0.125, 0.125), - ], -) +@pytest.mark.parametrize(('gate', 'half_turns'), [(cirq.CZ, 1.0), (cirq.CZ**0.125, 0.125)]) def test_serialize_exp_11(gate, half_turns): c = cirq.GridQubit(1, 2) t = cirq.GridQubit(1, 3) assert cg.XMON.serialize_op(gate.on(c, t)) == op_proto( { 'gate': {'id': 'cz'}, - 'args': { - 'half_turns': {'arg_value': {'float_value': half_turns}}, - }, + 'args': {'half_turns': {'arg_value': {'float_value': half_turns}}}, 'qubits': [{'id': '1_2'}, {'id': '1_3'}], } ) @@ -212,14 +200,7 @@ def test_serialize_circuit(): assert cg.XMON.serialize(circuit) == expected -@pytest.mark.parametrize( - ('axis_half_turns', 'half_turns'), - [ - (0.25, 0.25), - (0, 0.25), - (0.5, 0.25), - ], -) +@pytest.mark.parametrize(('axis_half_turns', 'half_turns'), [(0.25, 0.25), (0, 0.25), (0.5, 0.25)]) def test_deserialize_exp_w(axis_half_turns, half_turns): serialized_op = op_proto( { @@ -470,16 +451,12 @@ def test_serialize_deserialize_arbitrary_xy(gate, axis_half_turns, half_turns): assert cg.SYC_GATESET.serialize_op(op) == expected deserialized_op = cg.SYC_GATESET.deserialize_op(expected) cirq.testing.assert_allclose_up_to_global_phase( - cirq.unitary(deserialized_op), - cirq.unitary(op), - atol=1e-7, + cirq.unitary(deserialized_op), cirq.unitary(op), atol=1e-7 ) assert cg.SQRT_ISWAP_GATESET.serialize_op(op) == expected deserialized_op = cg.SQRT_ISWAP_GATESET.deserialize_op(expected) cirq.testing.assert_allclose_up_to_global_phase( - cirq.unitary(deserialized_op), - cirq.unitary(op), - atol=1e-7, + cirq.unitary(deserialized_op), cirq.unitary(op), atol=1e-7 ) @@ -515,9 +492,7 @@ def test_serialize_deserialize_wait_gate(): { 'gate': {'id': 'wait'}, 'qubits': [{'id': '1_2'}], - 'args': { - 'nanos': {'arg_value': {'float_value': 50.0}}, - }, + 'args': {'nanos': {'arg_value': {'float_value': 50.0}}}, } ) assert cg.SYC_GATESET.serialize_op(op) == proto @@ -534,11 +509,7 @@ def default_circuit_proto(): return v2.program_pb2.Circuit( scheduling_strategy=v2.program_pb2.Circuit.MOMENT_BY_MOMENT, - moments=[ - v2.program_pb2.Moment( - operations=[op1], - ), - ], + moments=[v2.program_pb2.Moment(operations=[op1])], ) diff --git a/cirq-google/cirq_google/serialization/op_deserializer.py b/cirq-google/cirq_google/serialization/op_deserializer.py index e9690a5fbef..d1771c4222c 100644 --- a/cirq-google/cirq_google/serialization/op_deserializer.py +++ b/cirq-google/cirq_google/serialization/op_deserializer.py @@ -12,14 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from typing import ( - Any, - Callable, - Dict, - List, - Optional, - Sequence, -) +from typing import Any, Callable, Dict, List, Optional, Sequence from dataclasses import dataclass import abc @@ -317,10 +310,5 @@ def from_proto( ) return cirq.CircuitOperation( - circuit, - repetitions, - qubit_map, - measurement_key_map, - arg_map, # type: ignore - rep_ids, + circuit, repetitions, qubit_map, measurement_key_map, arg_map, rep_ids # type: ignore ) diff --git a/cirq-google/cirq_google/serialization/op_deserializer_test.py b/cirq-google/cirq_google/serialization/op_deserializer_test.py index c1a73811329..c8f54040db1 100644 --- a/cirq-google/cirq_google/serialization/op_deserializer_test.py +++ b/cirq-google/cirq_google/serialization/op_deserializer_test.py @@ -46,12 +46,7 @@ def base_deserializer(): return cg.GateOpDeserializer( serialized_gate_id='my_gate', gate_constructor=GateWithAttribute, - args=[ - cg.DeserializingArg( - serialized_name='my_val', - constructor_arg_name='val', - ) - ], + args=[cg.DeserializingArg(serialized_name='my_val', constructor_arg_name='val')], ) @@ -115,10 +110,7 @@ def test_from_proto_unknown_function(): 'my_val': { 'func': { 'type': 'UNKNOWN_OPERATION', - 'args': [ - {'symbol': 'x'}, - {'arg_value': {'float_value': -1.0}}, - ], + 'args': [{'symbol': 'x'}, {'arg_value': {'float_value': -1.0}}], } } }, @@ -134,11 +126,7 @@ def test_from_proto_value_type_not_recognized(): serialized = op_proto( { 'gate': {'id': 'my_gate'}, - 'args': { - 'my_val': { - 'arg_value': {}, - } - }, + 'args': {'my_val': {'arg_value': {}}}, 'qubits': [{'id': '1_2'}], } ) @@ -151,17 +139,7 @@ def test_from_proto_function_argument_not_set(): serialized = op_proto( { 'gate': {'id': 'my_gate'}, - 'args': { - 'my_val': { - 'func': { - 'type': 'mul', - 'args': [ - {'symbol': 'x'}, - {}, - ], - } - } - }, + 'args': {'my_val': {'func': {'type': 'mul', 'args': [{'symbol': 'x'}, {}]}}}, 'qubits': [{'id': '1_2'}], } ) @@ -196,10 +174,7 @@ def test_from_proto_not_required_ok(): serialized_gate_id='my_gate', gate_constructor=GateWithAttribute, args=[ - cg.DeserializingArg( - serialized_name='my_val', - constructor_arg_name='val', - ), + cg.DeserializingArg(serialized_name='my_val', constructor_arg_name='val'), cg.DeserializingArg( serialized_name='not_req', constructor_arg_name='not_req', required=False ), @@ -222,10 +197,7 @@ def test_from_proto_missing_required_arg(): serialized_gate_id='my_gate', gate_constructor=GateWithAttribute, args=[ - cg.DeserializingArg( - serialized_name='my_val', - constructor_arg_name='val', - ), + cg.DeserializingArg(serialized_name='my_val', constructor_arg_name='val'), cg.DeserializingArg( serialized_name='not_req', constructor_arg_name='not_req', required=False ), @@ -247,10 +219,7 @@ def test_from_proto_required_arg_not_assigned(): serialized_gate_id='my_gate', gate_constructor=GateWithAttribute, args=[ - cg.DeserializingArg( - serialized_name='my_val', - constructor_arg_name='val', - ), + cg.DeserializingArg(serialized_name='my_val', constructor_arg_name='val'), cg.DeserializingArg( serialized_name='not_req', constructor_arg_name='not_req', required=False ), @@ -337,11 +306,7 @@ def default_circuit_proto(): return v2.program_pb2.Circuit( scheduling_strategy=v2.program_pb2.Circuit.MOMENT_BY_MOMENT, - moments=[ - v2.program_pb2.Moment( - operations=[op1, op2], - ), - ], + moments=[v2.program_pb2.Moment(operations=[op1, op2])], ) diff --git a/cirq-google/cirq_google/serialization/op_serializer_test.py b/cirq-google/cirq_google/serialization/op_serializer_test.py index f72bd05b364..2b32a1b76af 100644 --- a/cirq-google/cirq_google/serialization/op_serializer_test.py +++ b/cirq-google/cirq_google/serialization/op_serializer_test.py @@ -367,11 +367,7 @@ def test_token_serialization(): @pytest.mark.parametrize( ('constants', 'expected_index', 'expected_constants'), - ( - ([], 0, ONE_CONSTANT), - (ONE_CONSTANT, 0, ONE_CONSTANT), - (TWO_CONSTANTS, 1, TWO_CONSTANTS), - ), + (([], 0, ONE_CONSTANT), (ONE_CONSTANT, 0, ONE_CONSTANT), (TWO_CONSTANTS, 1, TWO_CONSTANTS)), ) def test_token_serialization_with_constant_reference(constants, expected_index, expected_constants): serializer = cg.GateOpSerializer( @@ -411,11 +407,7 @@ def default_circuit_proto(): return v2.program_pb2.Circuit( scheduling_strategy=v2.program_pb2.Circuit.MOMENT_BY_MOMENT, - moments=[ - v2.program_pb2.Moment( - operations=[op1, op2], - ), - ], + moments=[v2.program_pb2.Moment(operations=[op1, op2])], ) @@ -447,10 +439,7 @@ def test_circuit_op_to_proto_errors(): v2.program_pb2.Constant(string_value=DEFAULT_TOKEN), v2.program_pb2.Constant(circuit_value=default_circuit_proto()), ] - raw_constants = { - DEFAULT_TOKEN: 0, - default_circuit(): 1, - } + raw_constants = {DEFAULT_TOKEN: 0, default_circuit(): 1} with pytest.raises(ValueError, match='CircuitOp serialization requires a constants list'): serializer.to_proto(to_serialize) @@ -497,10 +486,7 @@ def test_circuit_op_to_proto(repetitions): v2.program_pb2.Constant(string_value=DEFAULT_TOKEN), v2.program_pb2.Constant(circuit_value=default_circuit_proto()), ] - raw_constants = { - DEFAULT_TOKEN: 0, - default_circuit(): 1, - } + raw_constants = {DEFAULT_TOKEN: 0, default_circuit(): 1} repetition_spec = v2.program_pb2.RepetitionSpecification() if repetition_ids is None: diff --git a/cirq-google/cirq_google/serialization/serializable_gate_set.py b/cirq-google/cirq_google/serialization/serializable_gate_set.py index a7edacc4760..0c4e92506c1 100644 --- a/cirq-google/cirq_google/serialization/serializable_gate_set.py +++ b/cirq-google/cirq_google/serialization/serializable_gate_set.py @@ -14,16 +14,7 @@ """Support for serializing and deserializing cirq_google.api.v2 protos.""" from itertools import chain -from typing import ( - Any, - Dict, - Iterable, - List, - Optional, - Tuple, - Type, - Union, -) +from typing import Any, Dict, Iterable, List, Optional, Tuple, Type, Union import cirq from cirq_google.api import v2 @@ -326,10 +317,7 @@ def deserialize(self, proto: v2.program_pb2.Program) -> cirq.Circuit: def deserialize_op( self, - operation_proto: Union[ - v2.program_pb2.Operation, - v2.program_pb2.CircuitOperation, - ], + operation_proto: Union[v2.program_pb2.Operation, v2.program_pb2.CircuitOperation,], **kwargs, ) -> cirq.Operation: """Disambiguation for operation deserialization.""" @@ -487,10 +475,7 @@ def _deserialize_circuit( return cirq.Circuit(moments) def _deserialize_schedule( - self, - schedule_proto: v2.program_pb2.Schedule, - *, - arg_function_language: str, + self, schedule_proto: v2.program_pb2.Schedule, *, arg_function_language: str ) -> cirq.Circuit: result = [] for scheduled_op_proto in schedule_proto.scheduled_operations: diff --git a/cirq-google/cirq_google/serialization/serializable_gate_set_test.py b/cirq-google/cirq_google/serialization/serializable_gate_set_test.py index d5e8b896b6e..abd3038539f 100644 --- a/cirq-google/cirq_google/serialization/serializable_gate_set_test.py +++ b/cirq-google/cirq_google/serialization/serializable_gate_set_test.py @@ -25,46 +25,28 @@ gate_type=cirq.XPowGate, serialized_gate_id='x_pow', args=[ - cg.SerializingArg( - serialized_name='half_turns', - serialized_type=float, - op_getter='exponent', - ) + cg.SerializingArg(serialized_name='half_turns', serialized_type=float, op_getter='exponent') ], ) X_DESERIALIZER = cg.GateOpDeserializer( serialized_gate_id='x_pow', gate_constructor=cirq.XPowGate, - args=[ - cg.DeserializingArg( - serialized_name='half_turns', - constructor_arg_name='exponent', - ) - ], + args=[cg.DeserializingArg(serialized_name='half_turns', constructor_arg_name='exponent')], ) Y_SERIALIZER = cg.GateOpSerializer( gate_type=cirq.YPowGate, serialized_gate_id='y_pow', args=[ - cg.SerializingArg( - serialized_name='half_turns', - serialized_type=float, - op_getter='exponent', - ) + cg.SerializingArg(serialized_name='half_turns', serialized_type=float, op_getter='exponent') ], ) Y_DESERIALIZER = cg.GateOpDeserializer( serialized_gate_id='y_pow', gate_constructor=cirq.YPowGate, - args=[ - cg.DeserializingArg( - serialized_name='half_turns', - constructor_arg_name='exponent', - ) - ], + args=[cg.DeserializingArg(serialized_name='half_turns', constructor_arg_name='exponent')], ) CIRCUIT_OP_SERIALIZER = cg.CircuitOpSerializer() @@ -137,9 +119,7 @@ def test_is_supported_operation_can_serialize_predicate(): serialized_gate_id='x_pow', args=[ cg.SerializingArg( - serialized_name='half_turns', - serialized_type=float, - op_getter='exponent', + serialized_name='half_turns', serialized_type=float, op_getter='exponent' ) ], can_serialize_predicate=lambda x: x.gate.exponent == 1.0, @@ -165,11 +145,9 @@ def test_serialize_deserialize_circuit(): operations=[ X_SERIALIZER.to_proto(cirq.X(q0)), X_SERIALIZER.to_proto(cirq.X(q1)), - ], - ), - v2.program_pb2.Moment( - operations=[X_SERIALIZER.to_proto(cirq.X(q0))], + ] ), + v2.program_pb2.Moment(operations=[X_SERIALIZER.to_proto(cirq.X(q0))]), ], ), ) @@ -202,12 +180,8 @@ def test_serialize_deserialize_circuit_with_tokens(): circuit=v2.program_pb2.Circuit( scheduling_strategy=v2.program_pb2.Circuit.MOMENT_BY_MOMENT, moments=[ - v2.program_pb2.Moment( - operations=[op1, op2], - ), - v2.program_pb2.Moment( - operations=[X_SERIALIZER.to_proto(cirq.X(q0))], - ), + v2.program_pb2.Moment(operations=[op1, op2]), + v2.program_pb2.Moment(operations=[X_SERIALIZER.to_proto(cirq.X(q0))]), ], ), constants=[ @@ -255,13 +229,9 @@ def test_serialize_deserialize_circuit_with_subcircuit(): circuit=v2.program_pb2.Circuit( scheduling_strategy=v2.program_pb2.Circuit.MOMENT_BY_MOMENT, moments=[ + v2.program_pb2.Moment(operations=[op1], circuit_operations=[c_op1]), v2.program_pb2.Moment( - operations=[op1], - circuit_operations=[c_op1], - ), - v2.program_pb2.Moment( - operations=[X_SERIALIZER.to_proto(cirq.X(q0))], - circuit_operations=[c_op2], + operations=[X_SERIALIZER.to_proto(cirq.X(q0))], circuit_operations=[c_op2] ), ], ), @@ -270,11 +240,7 @@ def test_serialize_deserialize_circuit_with_subcircuit(): v2.program_pb2.Constant( circuit_value=v2.program_pb2.Circuit( scheduling_strategy=v2.program_pb2.Circuit.MOMENT_BY_MOMENT, - moments=[ - v2.program_pb2.Moment( - operations=[X_SERIALIZER.to_proto(cirq.X(q0))], - ) - ], + moments=[v2.program_pb2.Moment(operations=[X_SERIALIZER.to_proto(cirq.X(q0))])], ) ), ], @@ -302,23 +268,15 @@ def test_deserialize_infinite_recursion_fails(): language=v2.program_pb2.Language(arg_function_language='', gate_set='my_gate_set'), circuit=v2.program_pb2.Circuit( scheduling_strategy=v2.program_pb2.Circuit.MOMENT_BY_MOMENT, - moments=[ - v2.program_pb2.Moment( - circuit_operations=[c_op1], - ), - ], + moments=[v2.program_pb2.Moment(circuit_operations=[c_op1])], ), constants=[ v2.program_pb2.Constant( circuit_value=v2.program_pb2.Circuit( scheduling_strategy=v2.program_pb2.Circuit.MOMENT_BY_MOMENT, - moments=[ - v2.program_pb2.Moment( - circuit_operations=[c_op1], - ), - ], + moments=[v2.program_pb2.Moment(circuit_operations=[c_op1])], ) - ), + ) ], ) with pytest.raises(ValueError, match="Failed to deserialize circuit"): @@ -374,9 +332,7 @@ def test_deserialize_empty_moment(): language=v2.program_pb2.Language(arg_function_language='', gate_set='my_gate_set'), circuit=v2.program_pb2.Circuit( scheduling_strategy=v2.program_pb2.Circuit.MOMENT_BY_MOMENT, - moments=[ - v2.program_pb2.Moment(), - ], + moments=[v2.program_pb2.Moment()], ), ) assert MY_GATE_SET.deserialize(proto) == circuit @@ -392,9 +348,7 @@ def test_serialize_deserialize_op(): proto = op_proto( { 'gate': {'id': 'x_pow'}, - 'args': { - 'half_turns': {'arg_value': {'float_value': 0.125}}, - }, + 'args': {'half_turns': {'arg_value': {'float_value': 0.125}}}, 'qubits': [{'id': '1_1'}], } ) @@ -407,9 +361,7 @@ def test_serialize_deserialize_op_with_token(): proto = op_proto( { 'gate': {'id': 'x_pow'}, - 'args': { - 'half_turns': {'arg_value': {'float_value': 0.125}}, - }, + 'args': {'half_turns': {'arg_value': {'float_value': 0.125}}}, 'qubits': [{'id': '1_1'}], 'token_value': 'abc123', } @@ -424,9 +376,7 @@ def test_serialize_deserialize_op_with_constants(): proto = op_proto( { 'gate': {'id': 'x_pow'}, - 'args': { - 'half_turns': {'arg_value': {'float_value': 0.125}}, - }, + 'args': {'half_turns': {'arg_value': {'float_value': 0.125}}}, 'qubits': [{'id': '1_1'}], 'token_constant_index': 0, } @@ -443,9 +393,7 @@ def test_serialize_deserialize_op_subclass(): proto = op_proto( { 'gate': {'id': 'x_pow'}, - 'args': { - 'half_turns': {'arg_value': {'float_value': 1.0}}, - }, + 'args': {'half_turns': {'arg_value': {'float_value': 1.0}}}, 'qubits': [{'id': '1_1'}], } ) @@ -462,11 +410,7 @@ def default_circuit_proto(): return v2.program_pb2.Circuit( scheduling_strategy=v2.program_pb2.Circuit.MOMENT_BY_MOMENT, - moments=[ - v2.program_pb2.Moment( - operations=[op1], - ), - ], + moments=[v2.program_pb2.Moment(operations=[op1])], ) @@ -519,9 +463,7 @@ def test_deserialize_circuit_op_errors(): ) BAD_CIRCUIT_DESERIALIZER = cg.GateOpDeserializer( - serialized_gate_id='circuit', - gate_constructor=cirq.ZPowGate, - args=[], + serialized_gate_id='circuit', gate_constructor=cirq.ZPowGate, args=[] ) BAD_CIRCUIT_DESERIALIZER_GATE_SET = cg.SerializableGateSet( gate_set_name='bad_circuit_gateset', @@ -585,14 +527,10 @@ def test_multiple_serializers(): def test_gateset_with_added_types(): q = cirq.GridQubit(1, 1) x_gateset = cg.SerializableGateSet( - gate_set_name='x', - serializers=[X_SERIALIZER], - deserializers=[X_DESERIALIZER], + gate_set_name='x', serializers=[X_SERIALIZER], deserializers=[X_DESERIALIZER] ) xy_gateset = x_gateset.with_added_types( - gate_set_name='xy', - serializers=[Y_SERIALIZER], - deserializers=[Y_DESERIALIZER], + gate_set_name='xy', serializers=[Y_SERIALIZER], deserializers=[Y_DESERIALIZER] ) assert x_gateset.name == 'x' assert x_gateset.is_supported_operation(cirq.X(q)) @@ -605,9 +543,7 @@ def test_gateset_with_added_types(): proto = op_proto( { 'gate': {'id': 'y_pow'}, - 'args': { - 'half_turns': {'arg_value': {'float_value': 0.125}}, - }, + 'args': {'half_turns': {'arg_value': {'float_value': 0.125}}}, 'qubits': [{'id': '1_1'}], } ) @@ -621,14 +557,10 @@ def test_gateset_with_added_types_again(): """Verify that adding a serializer twice doesn't mess anything up.""" q = cirq.GridQubit(2, 2) x_gateset = cg.SerializableGateSet( - gate_set_name='x', - serializers=[X_SERIALIZER], - deserializers=[X_DESERIALIZER], + gate_set_name='x', serializers=[X_SERIALIZER], deserializers=[X_DESERIALIZER] ) xx_gateset = x_gateset.with_added_types( - gate_set_name='xx', - serializers=[X_SERIALIZER], - deserializers=[X_DESERIALIZER], + gate_set_name='xx', serializers=[X_SERIALIZER], deserializers=[X_DESERIALIZER] ) assert xx_gateset.name == 'xx' @@ -639,9 +571,7 @@ def test_gateset_with_added_types_again(): proto = op_proto( { 'gate': {'id': 'x_pow'}, - 'args': { - 'half_turns': {'arg_value': {'float_value': 0.125}}, - }, + 'args': {'half_turns': {'arg_value': {'float_value': 0.125}}}, 'qubits': [{'id': '1_1'}], } ) @@ -655,9 +585,7 @@ def test_deserialize_op_invalid_gate(): proto = op_proto( { 'gate': {}, - 'args': { - 'half_turns': {'arg_value': {'float_value': 0.125}}, - }, + 'args': {'half_turns': {'arg_value': {'float_value': 0.125}}}, 'qubits': [{'id': '1_1'}], } ) @@ -665,12 +593,7 @@ def test_deserialize_op_invalid_gate(): MY_GATE_SET.deserialize_op(proto) proto = op_proto( - { - 'args': { - 'half_turns': {'arg_value': {'float_value': 0.125}}, - }, - 'qubits': [{'id': '1_1'}], - } + {'args': {'half_turns': {'arg_value': {'float_value': 0.125}}}, 'qubits': [{'id': '1_1'}]} ) with pytest.raises(ValueError, match='does not have a gate'): MY_GATE_SET.deserialize_op(proto) @@ -686,9 +609,7 @@ def test_deserialize_unsupported_gate_type(): proto = op_proto( { 'gate': {'id': 'no_pow'}, - 'args': { - 'half_turns': {'arg_value': {'float_value': 0.125}}, - }, + 'args': {'half_turns': {'arg_value': {'float_value': 0.125}}}, 'qubits': [{'id': '1_1'}], } ) diff --git a/cirq-google/cirq_google/transformers/target_gatesets/sycamore_gateset.py b/cirq-google/cirq_google/transformers/target_gatesets/sycamore_gateset.py index eb262b702ea..3f4212f1587 100644 --- a/cirq-google/cirq_google/transformers/target_gatesets/sycamore_gateset.py +++ b/cirq-google/cirq_google/transformers/target_gatesets/sycamore_gateset.py @@ -137,8 +137,7 @@ def __init__( def preprocess_transformers(self) -> List[cirq.TRANSFORMER]: return [ _create_transformer_with_kwargs( - cirq.expand_composite, - no_decomp=lambda op: cirq.num_qubits(op) <= self.num_qubits, + cirq.expand_composite, no_decomp=lambda op: cirq.num_qubits(op) <= self.num_qubits ), _create_transformer_with_kwargs( merge_swap_rzz_and_2q_unitaries, diff --git a/cirq-google/cirq_google/transformers/target_gatesets/sycamore_gateset_test.py b/cirq-google/cirq_google/transformers/target_gatesets/sycamore_gateset_test.py index c9d65d5e289..49da82e75a8 100644 --- a/cirq-google/cirq_google/transformers/target_gatesets/sycamore_gateset_test.py +++ b/cirq-google/cirq_google/transformers/target_gatesets/sycamore_gateset_test.py @@ -36,11 +36,7 @@ def test_merge_swap_rzz_and_2q_unitaries(): cirq.Moment(cirq.H.on_each(*q)), cirq.CNOT(q[0], q[2]), cirq.CircuitOperation( - cirq.FrozenCircuit( - cirq.CNOT(*q[0:2]), - cirq.H(q[0]), - cirq.CZ(*q[:2]), - ) + cirq.FrozenCircuit(cirq.CNOT(*q[0:2]), cirq.H(q[0]), cirq.CZ(*q[:2])) ), cirq.CNOT(*q[1:3]), cirq.X(q[0]), @@ -282,7 +278,7 @@ def test_zztheta_zzpow_unsorted_qubits(): qubits = cirq.LineQubit(1), cirq.LineQubit(0) exponent = 0.06366197723675814 circuit = cirq.Circuit( - cirq.ZZPowGate(exponent=exponent, global_shift=-0.5).on(qubits[0], qubits[1]), + cirq.ZZPowGate(exponent=exponent, global_shift=-0.5).on(qubits[0], qubits[1]) ) converted_circuit = cirq.optimize_for_target_gateset( circuit, gateset=cirq_google.SycamoreTargetGateset() diff --git a/cirq-google/cirq_google/workflow/__init__.py b/cirq-google/cirq_google/workflow/__init__.py index a0c959e3c2e..661f09b2ce5 100644 --- a/cirq-google/cirq_google/workflow/__init__.py +++ b/cirq-google/cirq_google/workflow/__init__.py @@ -16,9 +16,7 @@ execute, ) -from cirq_google.workflow.io import ( - ExecutableGroupResultFilesystemRecord, -) +from cirq_google.workflow.io import ExecutableGroupResultFilesystemRecord from cirq_google.workflow.qubit_placement import ( QubitPlacer, diff --git a/cirq-google/cirq_google/workflow/io_test.py b/cirq-google/cirq_google/workflow/io_test.py index e09d8069296..206b743adb0 100644 --- a/cirq-google/cirq_google/workflow/io_test.py +++ b/cirq-google/cirq_google/workflow/io_test.py @@ -23,22 +23,14 @@ def cg_assert_equivalent_repr(value): """cirq.testing.assert_equivalent_repr with cirq_google.workflow imported.""" - return cirq.testing.assert_equivalent_repr( - value, - global_vals={ - 'cirq_google': cg, - }, - ) + return cirq.testing.assert_equivalent_repr(value, global_vals={'cirq_google': cg}) def test_egr_filesystem_record_repr(): egr_fs_record = cg.ExecutableGroupResultFilesystemRecord( runtime_configuration_path='RuntimeConfiguration.json.gz', shared_runtime_info_path='SharedRuntimeInfo.jzon.gz', - executable_result_paths=[ - 'ExecutableResult.1.json.gz', - 'ExecutableResult.2.json.gz', - ], + executable_result_paths=['ExecutableResult.1.json.gz', 'ExecutableResult.2.json.gz'], run_id='my-run-id', ) cg_assert_equivalent_repr(egr_fs_record) @@ -49,10 +41,7 @@ def test_egr_filesystem_record_from_json(tmpdir): egr_fs_record = cg.ExecutableGroupResultFilesystemRecord( runtime_configuration_path='RuntimeConfiguration.json.gz', shared_runtime_info_path='SharedRuntimeInfo.jzon.gz', - executable_result_paths=[ - 'ExecutableResult.1.json.gz', - 'ExecutableResult.2.json.gz', - ], + executable_result_paths=['ExecutableResult.1.json.gz', 'ExecutableResult.2.json.gz'], run_id=run_id, ) diff --git a/cirq-google/cirq_google/workflow/processor_record.py b/cirq-google/cirq_google/workflow/processor_record.py index 72c3e538c23..197f5edd036 100644 --- a/cirq-google/cirq_google/workflow/processor_record.py +++ b/cirq-google/cirq_google/workflow/processor_record.py @@ -115,9 +115,7 @@ def _get_input_device(self) -> 'cirq.Device': """ return cg.get_engine_device(self.processor_id) - def _get_input_sampler( - self, - ) -> 'cirq.Sampler': + def _get_input_sampler(self) -> 'cirq.Sampler': """Return a local `cirq.Sampler` based on the `noise_strength` attribute. If `self.noise_strength` is `0` return a noiseless state-vector simulator. diff --git a/cirq-google/cirq_google/workflow/quantum_executable.py b/cirq-google/cirq_google/workflow/quantum_executable.py index 99c1e350853..3b256aac305 100644 --- a/cirq-google/cirq_google/workflow/quantum_executable.py +++ b/cirq-google/cirq_google/workflow/quantum_executable.py @@ -67,8 +67,7 @@ def _json_dict_(self) -> Dict[str, Any]: @classmethod def from_dict(cls, d: Dict[str, Any], *, executable_family: str) -> 'KeyValueExecutableSpec': return cls( - executable_family=executable_family, - key_value_pairs=tuple((k, v) for k, v in d.items()), + executable_family=executable_family, key_value_pairs=tuple((k, v) for k, v in d.items()) ) @classmethod @@ -234,10 +233,7 @@ class QuantumExecutableGroup: executables: Tuple[QuantumExecutable, ...] - def __init__( - self, - executables: Sequence[QuantumExecutable], - ): + def __init__(self, executables: Sequence[QuantumExecutable]): """Initialize and normalize the quantum executable group. Args: diff --git a/cirq-google/cirq_google/workflow/quantum_executable_test.py b/cirq-google/cirq_google/workflow/quantum_executable_test.py index a75b0df50f3..fe9f36e24fc 100644 --- a/cirq-google/cirq_google/workflow/quantum_executable_test.py +++ b/cirq-google/cirq_google/workflow/quantum_executable_test.py @@ -199,20 +199,8 @@ def test_quantum_executable_group_serialization(tmpdir): def test_equality(): - k1 = KeyValueExecutableSpec( - executable_family='test', - key_value_pairs=( - ('a', 1), - ('b', 2), - ), - ) - k2 = KeyValueExecutableSpec( - executable_family='test', - key_value_pairs=( - ('b', 2), - ('a', 1), - ), - ) + k1 = KeyValueExecutableSpec(executable_family='test', key_value_pairs=(('a', 1), ('b', 2))) + k2 = KeyValueExecutableSpec(executable_family='test', key_value_pairs=(('b', 2), ('a', 1))) assert k1 == k2 diff --git a/cirq-google/cirq_google/workflow/quantum_runtime.py b/cirq-google/cirq_google/workflow/quantum_runtime.py index 72294af4bc1..d0882276820 100644 --- a/cirq-google/cirq_google/workflow/quantum_runtime.py +++ b/cirq-google/cirq_google/workflow/quantum_runtime.py @@ -261,10 +261,7 @@ def execute( sampler = rt_config.processor_record.get_sampler() device = rt_config.processor_record.get_device() - shared_rt_info = SharedRuntimeInfo( - run_id=run_id, - device=device, - ) + shared_rt_info = SharedRuntimeInfo(run_id=run_id, device=device) executable_results = [] saver = _FilesystemSaver(base_data_dir=base_data_dir, run_id=run_id) @@ -298,9 +295,7 @@ def execute( sampler_run_result = sampler.run(circuit, repetitions=exe.measurement.n_repetitions) exe_result = ExecutableResult( - spec=exe.spec, - runtime_info=runtime_info, - raw_data=sampler_run_result, + spec=exe.spec, runtime_info=runtime_info, raw_data=sampler_run_result ) # Do bookkeeping for finished ExecutableResult executable_results.append(exe_result) diff --git a/cirq-google/cirq_google/workflow/quantum_runtime_test.py b/cirq-google/cirq_google/workflow/quantum_runtime_test.py index 3fcb30ac430..73b715c81da 100644 --- a/cirq-google/cirq_google/workflow/quantum_runtime_test.py +++ b/cirq-google/cirq_google/workflow/quantum_runtime_test.py @@ -28,12 +28,7 @@ def cg_assert_equivalent_repr(value): """cirq.testing.assert_equivalent_repr with cirq_google.workflow imported.""" - return cirq.testing.assert_equivalent_repr( - value, - global_vals={ - 'cirq_google': cg, - }, - ) + return cirq.testing.assert_equivalent_repr(value, global_vals={'cirq_google': cg}) def test_shared_runtime_info(): @@ -68,8 +63,7 @@ def _assert_json_roundtrip(o, tmpdir): def test_quantum_runtime_configuration(): rt_config = cg.QuantumRuntimeConfiguration( - processor_record=cg.SimulatedProcessorWithLocalDeviceRecord('rainbow'), - run_id='unit-test', + processor_record=cg.SimulatedProcessorWithLocalDeviceRecord('rainbow'), run_id='unit-test' ) sampler = rt_config.processor_record.get_sampler() @@ -81,8 +75,7 @@ def test_quantum_runtime_configuration(): def test_quantum_runtime_configuration_serialization(tmpdir): rt_config = cg.QuantumRuntimeConfiguration( - processor_record=cg.SimulatedProcessorWithLocalDeviceRecord('rainbow'), - run_id='unit-test', + processor_record=cg.SimulatedProcessorWithLocalDeviceRecord('rainbow'), run_id='unit-test' ) cg_assert_equivalent_repr(rt_config) _assert_json_roundtrip(rt_config, tmpdir) diff --git a/cirq-google/cirq_google/workflow/qubit_placement.py b/cirq-google/cirq_google/workflow/qubit_placement.py index f2e77570335..cb1e1921831 100644 --- a/cirq-google/cirq_google/workflow/qubit_placement.py +++ b/cirq-google/cirq_google/workflow/qubit_placement.py @@ -138,8 +138,7 @@ def _get_random_placement( class RandomDevicePlacer(QubitPlacer): def __init__( - self, - topo_node_to_qubit_func: Callable[[Any], cirq.Qid] = default_topo_node_to_qubit, + self, topo_node_to_qubit_func: Callable[[Any], cirq.Qid] = default_topo_node_to_qubit ): """A placement strategy that randomly places circuits onto devices.